-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcodec.rs
More file actions
397 lines (370 loc) · 13 KB
/
Copy pathcodec.rs
File metadata and controls
397 lines (370 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
// SPDX-License-Identifier: Apache-2.0
//! Versioned bounded JSON codecs for cache blobs.
use std::io::{self, Write};
use code2graph::{
CODE_GRAPH_SCHEMA_VERSION, CodeGraph, FILE_FACTS_SCHEMA_VERSION, FILE_SUBGRAPH_SCHEMA_VERSION,
FileFacts, FileFactsValidationContext, FileSubgraph, IncrementalGraph, validate_file_facts,
validate_file_facts_with_context,
};
use serde::{Deserialize, Serialize};
/// Maximum accepted encoded cache blob size.
pub const CACHE_BLOB_MAX_BYTES: usize = 16 * 1024 * 1024;
const CACHE_COLLECTION_MAX: usize = 1_000_000;
const CACHE_STRING_MAX: usize = 1_048_576;
const CACHE_OWNER_MAX_BYTES: usize = 4096;
/// Typed cache failures; callers may map these to their public CLI error.
#[derive(Debug, thiserror::Error)]
pub enum CacheError {
#[error("cache blob exceeds the size limit")]
Oversize,
#[error("cache blob is malformed")]
Malformed,
#[error("cache blob has an unsupported format or schema")]
Incompatible,
#[error("cache blob violates structural limits")]
Limits,
#[error("cache facts failed validation")]
InvalidFacts,
#[error("cache subgraph could not be restored")]
InvalidSubgraph,
#[error("cache database is missing")]
Missing,
#[error("cache database uses an unsupported schema version")]
UnsupportedSchema,
#[error("cache database is corrupt")]
Corrupt,
#[error("cache database belongs to a different project")]
RootMismatch,
#[error("cache database is read-only")]
ReadOnly,
#[error("cache database is locked by another writer")]
LockContention,
#[error("cache database operation timed out")]
Timeout,
#[error("cache database could not be accessed")]
Access,
#[error("cache candidate is invalid or internally inconsistent")]
InvalidCandidate,
#[error("cache candidate conflicts with an existing candidate id")]
CandidateConflict,
#[error("requested cache snapshot is missing")]
SnapshotMissing,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Envelope<T> {
format: String,
schema: u32,
payload: T,
}
pub fn encode_file_facts(facts: &FileFacts) -> Result<Vec<u8>, CacheError> {
encode("file-facts", FILE_FACTS_SCHEMA_VERSION, facts)
}
/// Crate-private cache decode failure that preserves bounded validation detail
/// without changing the public `CacheError` shape.
#[derive(Debug)]
pub(crate) enum DetailedFileFactsDecodeError {
Cache(CacheError),
InvalidFacts { detail: String },
}
impl From<DetailedFileFactsDecodeError> for CacheError {
fn from(error: DetailedFileFactsDecodeError) -> Self {
match error {
DetailedFileFactsDecodeError::Cache(error) => error,
DetailedFileFactsDecodeError::InvalidFacts { .. } => CacheError::InvalidFacts,
}
}
}
pub fn decode_file_facts(
blob: &[u8],
context: Option<FileFactsValidationContext<'_>>,
) -> Result<FileFacts, CacheError> {
decode_file_facts_detailed(blob, context).map_err(Into::into)
}
pub(crate) fn decode_file_facts_detailed(
blob: &[u8],
context: Option<FileFactsValidationContext<'_>>,
) -> Result<FileFacts, DetailedFileFactsDecodeError> {
let facts = decode("file-facts", FILE_FACTS_SCHEMA_VERSION, blob)
.map_err(DetailedFileFactsDecodeError::Cache)?;
match context {
Some(context) => validate_file_facts_with_context(&facts, context),
None => validate_file_facts(std::slice::from_ref(&facts)),
}
.map_err(|error| DetailedFileFactsDecodeError::InvalidFacts {
detail: bounded_validation_detail(&error.to_string()),
})?;
Ok(facts)
}
fn bounded_validation_detail(detail: &str) -> String {
const MAX_DETAIL_BYTES: usize = 512;
let mut value = detail.to_owned();
if value.len() > MAX_DETAIL_BYTES {
value.truncate(MAX_DETAIL_BYTES);
while !value.is_char_boundary(value.len()) {
value.pop();
}
}
value
}
pub fn encode_subgraph(subgraph: &FileSubgraph) -> Result<Vec<u8>, CacheError> {
encode("file-subgraph", FILE_SUBGRAPH_SCHEMA_VERSION, subgraph)
}
/// Decode only through the incremental store's checked restore boundary.
pub fn restore_subgraph(
blob: &[u8],
owner: String,
graph: &mut IncrementalGraph,
) -> Result<(), CacheError> {
if owner.len() > CACHE_OWNER_MAX_BYTES {
return Err(CacheError::Limits);
}
let subgraph = decode("file-subgraph", FILE_SUBGRAPH_SCHEMA_VERSION, blob)?;
graph
.try_upsert_subgraph(owner, subgraph)
.map_err(|_| CacheError::InvalidSubgraph)
}
pub fn encode_graph(graph: &CodeGraph) -> Result<Vec<u8>, CacheError> {
encode("code-graph", CODE_GRAPH_SCHEMA_VERSION, graph)
}
pub fn decode_graph(blob: &[u8]) -> Result<CodeGraph, CacheError> {
let graph: CodeGraph = decode("code-graph", CODE_GRAPH_SCHEMA_VERSION, blob)?;
if graph.symbols.len() > CACHE_COLLECTION_MAX || graph.edges.len() > CACHE_COLLECTION_MAX {
return Err(CacheError::Limits);
}
Ok(graph)
}
fn encode<T: Serialize>(format: &str, schema: u32, payload: &T) -> Result<Vec<u8>, CacheError> {
let mut writer = BoundedWriter::new(CACHE_BLOB_MAX_BYTES);
let result = serde_json::to_writer(
&mut writer,
&Envelope {
format: format.to_owned(),
schema,
payload,
},
);
match result {
Ok(()) => Ok(writer.bytes),
Err(_) if writer.overflowed => Err(CacheError::Oversize),
Err(_) => Err(CacheError::Malformed),
}
}
struct BoundedWriter {
bytes: Vec<u8>,
limit: usize,
overflowed: bool,
}
impl BoundedWriter {
fn new(limit: usize) -> Self {
Self {
bytes: Vec::new(),
limit,
overflowed: false,
}
}
}
impl Write for BoundedWriter {
fn write(&mut self, input: &[u8]) -> io::Result<usize> {
let remaining = self.limit.saturating_sub(self.bytes.len());
if input.len() > remaining {
self.bytes.extend_from_slice(&input[..remaining]);
self.overflowed = true;
return Err(io::Error::other("cache blob limit"));
}
self.bytes.extend_from_slice(input);
Ok(input.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
fn decode<T: for<'de> Deserialize<'de>>(
format: &str,
schema: u32,
blob: &[u8],
) -> Result<T, CacheError> {
if blob.len() > CACHE_BLOB_MAX_BYTES {
return Err(CacheError::Oversize);
}
let value: serde_json::Value =
serde_json::from_slice(blob).map_err(|_| CacheError::Malformed)?;
validate_json_limits(&value)?;
let envelope: Envelope<T> = serde_json::from_value(value).map_err(|_| CacheError::Malformed)?;
if envelope.format != format || envelope.schema != schema {
return Err(CacheError::Incompatible);
}
Ok(envelope.payload)
}
fn validate_json_limits(value: &serde_json::Value) -> Result<(), CacheError> {
match value {
serde_json::Value::String(text) if text.len() > CACHE_STRING_MAX => Err(CacheError::Limits),
serde_json::Value::Array(values) => {
if values.len() > CACHE_COLLECTION_MAX {
return Err(CacheError::Limits);
}
for value in values {
validate_json_limits(value)?;
}
Ok(())
}
serde_json::Value::Object(values) => {
if values.len() > CACHE_COLLECTION_MAX {
return Err(CacheError::Limits);
}
for (key, value) in values {
if key.len() > CACHE_STRING_MAX {
return Err(CacheError::Limits);
}
validate_json_limits(value)?;
}
Ok(())
}
_ => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn facts() -> FileFacts {
FileFacts {
file: "src/a.rs".into(),
lang: "rust".into(),
symbols: Vec::new(),
references: Vec::new(),
scopes: Vec::new(),
bindings: Vec::new(),
ffi_exports: Vec::new(),
}
}
#[test]
fn facts_and_graph_round_trip_with_deterministic_bytes() {
use code2graph::{ByteSpan, Descriptor, Symbol, SymbolId, SymbolKind, Visibility};
let facts = facts();
let first = encode_file_facts(&facts).expect("encode");
let second = encode_file_facts(&facts).expect("encode");
assert_eq!(first, second);
assert!(!String::from_utf8_lossy(&first).contains("\"source\""));
let restored = decode_file_facts(&first, None).expect("decode");
assert_eq!(encode_file_facts(&restored).expect("encode"), first);
let ids = [
SymbolId::global("rust", vec![Descriptor::Term("run".into())]),
SymbolId::local("src/a.rs", "scope:0:x"),
];
let graph = CodeGraph {
symbols: ids
.iter()
.enumerate()
.map(|(index, id)| Symbol {
id: id.clone(),
name: format!("symbol-{index}"),
kind: SymbolKind::Function,
visibility: Visibility::Public,
entry_points: Vec::new(),
file: "src/a.rs".into(),
line: 7,
span: ByteSpan { start: 2, end: 9 },
signature: "fn run()".into(),
})
.collect(),
edges: Vec::new(),
};
let encoded = encode_graph(&graph).expect("encode graph");
let restored = decode_graph(&encoded).expect("decode graph");
assert_eq!(
restored
.symbols
.iter()
.map(|symbol| symbol.id.clone())
.collect::<Vec<_>>(),
ids
);
assert_eq!(encode_graph(&restored).expect("re-encode graph"), encoded);
}
#[test]
fn invalid_facts_preserves_legacy_unit_error_and_private_detail() {
let blob = encode_file_facts(&facts()).expect("encode");
let context = FileFactsValidationContext {
expected_file: "src/other.rs",
expected_language: code2graph::Language::Rust,
source_len: 0,
};
assert!(matches!(
decode_file_facts(&blob, Some(context)),
Err(CacheError::InvalidFacts)
));
let detail = decode_file_facts_detailed(&blob, Some(context)).unwrap_err();
assert!(matches!(
detail,
DetailedFileFactsDecodeError::InvalidFacts { ref detail }
if detail.contains("file") && detail.len() <= 512
));
let _: CacheError = CacheError::InvalidFacts;
}
#[test]
fn rejects_oversize_malformed_and_wrong_subgraph_owner() {
assert!(matches!(
decode_graph(&vec![b'x'; CACHE_BLOB_MAX_BYTES + 1]),
Err(CacheError::Oversize)
));
assert!(matches!(
decode_graph(b"not-json"),
Err(CacheError::Malformed)
));
let mut oversized = facts();
oversized.file = "x".repeat(CACHE_BLOB_MAX_BYTES);
assert!(matches!(
encode_file_facts(&oversized),
Err(CacheError::Oversize)
));
let facts = facts();
let mut source = IncrementalGraph::new();
source.upsert(&facts);
let blob = encode_subgraph(source.subgraph("src/a.rs").expect("subgraph")).expect("encode");
let mut destination = IncrementalGraph::new();
assert!(matches!(
restore_subgraph(&blob, "src/b.rs".into(), &mut destination),
Err(CacheError::InvalidSubgraph)
));
assert!(destination.is_empty());
assert!(matches!(
restore_subgraph(
&blob,
"x".repeat(CACHE_OWNER_MAX_BYTES + 1),
&mut destination
),
Err(CacheError::Limits)
));
}
#[test]
fn rejects_schema_string_and_collection_limit_attacks() {
let wrong_schema =
br#"{"format":"code-graph","schema":4294967295,"payload":{"symbols":[],"edges":[]}}"#;
assert!(matches!(
decode_graph(wrong_schema),
Err(CacheError::Incompatible)
));
let long_string = "x".repeat(CACHE_STRING_MAX + 1);
let blob = serde_json::to_vec(&serde_json::json!({
"format": "code-graph",
"schema": CODE_GRAPH_SCHEMA_VERSION,
"payload": { "symbols": [], "edges": [], "extra": long_string }
}))
.expect("JSON");
assert!(matches!(decode_graph(&blob), Err(CacheError::Limits)));
let mut many = String::from("{\"format\":\"code-graph\",\"schema\":1,\"payload\":{");
many.push_str("\"symbols\":[");
for index in 0..=CACHE_COLLECTION_MAX {
if index != 0 {
many.push(',');
}
many.push_str("null");
}
many.push_str("],\"edges\":[]}}");
assert!(many.len() < CACHE_BLOB_MAX_BYTES);
assert!(matches!(
decode_graph(many.as_bytes()),
Err(CacheError::Limits)
));
}
}