interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-crumb / src / lib.rs

752 lines · 26544 bytes Raw Blame History
1//! Versioned, bounded reader for Directory Crumb (`.crumb`) context over Synapse virtual trees (ADR 0004).
2//!
3//! * Each known on-disk dialect parses into its own typed variant of [`DirectoryCrumb`];
4//! nothing is coerced between dialects and anything else is refused with an [`InvalidReason`].
5//! * [`CrumbContext`] is the root-to-directory chain of `.crumb` entries for one snapshot,
6//! with missing and invalid entries reported, matching `crumb.c` `sniff`, `validate`, and
7//! `explain` (pinned at aien-architecture `29780e5`) except for the divergences listed in ADR 0004.
8//! * [`CrumbContextDigest`] is a domain-separated SHA-256 over the whole chain.
9//!
10//! The crate performs no I/O of its own: the caller supplies the bytes for each `.crumb`
11//! path (see `SynapseService::crumb_context` in `synapse-api`).
12
13pub mod json;
14pub mod yaml;
15
16use json::{JsonError, JsonValue};
17use sha2::{Digest, Sha256};
18use std::fmt;
19use synapse_core::{
20 validate_repo_relative_path, BlobDigest, RefusalCode, SynapseError, SynapseResult,
21};
22use yaml::{YamlCrumbV1, YamlError};
23
24/// File name of a Directory Crumb.
25pub const CRUMB_FILE_NAME: &str = ".crumb";
26
27/// Largest `.crumb` document accepted, in bytes. `crumb.c` has no cap; this is a deliberate divergence.
28pub const MAX_CRUMB_BYTES: u64 = 64 * 1024;
29
30/// Largest number of directories in one chain (root included).
31pub const MAX_CHAIN_LEN: usize = 256;
32
33/// `schema_version` required by RFC-0001 (D1).
34pub const RFC0001_SCHEMA_VERSION: &str = "1.0.0";
35
36/// Domain separation tag for [`CrumbContextDigest`].
37pub const DOMAIN_CRUMB_CONTEXT_V1: &[u8] = b"SYNAPSE_CRUMB_CONTEXT_V1\0";
38
39/// Repository-relative name of the repository root directory.
40pub const ROOT_DIR: &str = ".";
41
42/// A recognised Directory Crumb dialect (ADR 0004 section 1.2).
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
44pub enum Dialect {
45 /// D1: RFC-0001 JSON, `schema_version` `"1.0.0"`.
46 Rfc0001Json,
47 /// D2: pre-RFC Atlas / `spark-crumbs` `DirCrumb` JSON (`version`, no `schema_version`).
48 AtlasJson,
49 /// D3: YAML-like `schema: "crumb/v1"`.
50 YamlV1,
51}
52
53impl Dialect {
54 /// Stable byte used in [`CrumbContextDigest`]; 0 is reserved for "no dialect".
55 pub fn tag_byte(self) -> u8 {
56 match self {
57 Self::Rfc0001Json => 1,
58 Self::AtlasJson => 2,
59 Self::YamlV1 => 3,
60 }
61 }
62}
63
64/// D1 document: the fields Synapse surfaces. The full bytes are pinned by the entry's `BlobDigest`.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct Rfc0001Crumb {
67 pub name: String,
68 pub purpose: String,
69 pub layer: Option<String>,
70 /// Textual guidance; enforced by nothing until made a deterministic check.
71 pub invariants: Vec<String>,
72}
73
74/// D2 document, following `spark-crumbs` `DirCrumb` (aien-sovereign-core `d01201b`).
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct AtlasCrumb {
77 pub version: u32,
78 pub dir_path: String,
79 pub dir_name: String,
80 pub description: String,
81 /// `purpose.statement` when a `purpose` object is present.
82 pub purpose_statement: Option<String>,
83}
84
85/// A successfully parsed Directory Crumb, one variant per dialect.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub enum DirectoryCrumb {
88 Rfc0001(Rfc0001Crumb),
89 Atlas(AtlasCrumb),
90 YamlV1(YamlCrumbV1),
91}
92
93impl DirectoryCrumb {
94 pub fn dialect(&self) -> Dialect {
95 match self {
96 Self::Rfc0001(_) => Dialect::Rfc0001Json,
97 Self::Atlas(_) => Dialect::AtlasJson,
98 Self::YamlV1(_) => Dialect::YamlV1,
99 }
100 }
101
102 /// RFC-0001 invariants; other dialects define none.
103 pub fn invariants(&self) -> &[String] {
104 match self {
105 Self::Rfc0001(c) => &c.invariants,
106 _ => &[],
107 }
108 }
109}
110
111/// Why a `.crumb` file was refused. Every variant has a stable [`InvalidReason::code`].
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum InvalidReason {
114 /// Larger than [`MAX_CRUMB_BYTES`]; not read.
115 TooLarge {
116 size: u64,
117 },
118 /// The tree entry is a symlink, not a regular file.
119 NotRegularFile,
120 NotUtf8,
121 /// Neither JSON (`{` or `[` first) nor a D3 `schema:` document.
122 UnrecognizedFormat,
123 Json(JsonError),
124 /// Valid JSON whose top level is not an object.
125 NotJsonObject,
126 /// A JSON object with neither `schema_version` nor `version`.
127 UnknownJsonDialect,
128 /// D1 `schema_version` is not the string `"1.0.0"`.
129 UnsupportedSchemaVersion,
130 MissingField {
131 dialect: Dialect,
132 field: &'static str,
133 },
134 WrongFieldType {
135 dialect: Dialect,
136 field: &'static str,
137 },
138 Yaml(YamlError),
139}
140
141impl InvalidReason {
142 /// Stable code bound into [`CrumbContextDigest`].
143 pub fn code(&self) -> u16 {
144 match self {
145 Self::TooLarge { .. } => 1,
146 Self::NotRegularFile => 2,
147 Self::NotUtf8 => 3,
148 Self::UnrecognizedFormat => 4,
149 Self::Json(JsonError::Syntax { .. }) => 5,
150 Self::Json(JsonError::TooDeep) => 6,
151 Self::Json(JsonError::DuplicateKey { .. }) => 7,
152 Self::NotJsonObject => 8,
153 Self::UnknownJsonDialect => 9,
154 Self::UnsupportedSchemaVersion => 10,
155 Self::MissingField { .. } => 11,
156 Self::WrongFieldType { .. } => 12,
157 Self::Yaml(YamlError::Syntax { .. }) => 13,
158 Self::Yaml(YamlError::DuplicateKey { .. }) => 14,
159 Self::Yaml(YamlError::ComponentIncomplete { .. }) => 15,
160 Self::Yaml(YamlError::UnsupportedSchema) => 16,
161 }
162 }
163
164 /// The dialect the file claimed, when it got far enough to claim one.
165 pub fn claimed_dialect(&self) -> Option<Dialect> {
166 match self {
167 Self::UnsupportedSchemaVersion => Some(Dialect::Rfc0001Json),
168 Self::MissingField { dialect, .. } | Self::WrongFieldType { dialect, .. } => {
169 Some(*dialect)
170 }
171 Self::Yaml(_) => Some(Dialect::YamlV1),
172 _ => None,
173 }
174 }
175}
176
177/// Parse one `.crumb` document into its typed dialect, or say why not.
178pub fn parse_crumb(bytes: &[u8]) -> Result<DirectoryCrumb, InvalidReason> {
179 if bytes.len() as u64 > MAX_CRUMB_BYTES {
180 return Err(InvalidReason::TooLarge {
181 size: bytes.len() as u64,
182 });
183 }
184 let text = std::str::from_utf8(bytes).map_err(|_| InvalidReason::NotUtf8)?;
185 let first = text
186 .trim_start_matches([' ', '\t', '\n', '\r'])
187 .bytes()
188 .next();
189 if matches!(first, Some(b'{' | b'[')) {
190 let v = json::parse(text).map_err(InvalidReason::Json)?;
191 if !matches!(v, JsonValue::Object(_)) {
192 return Err(InvalidReason::NotJsonObject);
193 }
194 if v.get("schema_version").is_some() {
195 return parse_rfc0001(&v).map(DirectoryCrumb::Rfc0001);
196 }
197 if v.get("version").is_some() {
198 return parse_atlas(&v).map(DirectoryCrumb::Atlas);
199 }
200 return Err(InvalidReason::UnknownJsonDialect);
201 }
202 if yaml::looks_like_yaml_v1(text) {
203 return yaml::parse(text)
204 .map(DirectoryCrumb::YamlV1)
205 .map_err(InvalidReason::Yaml);
206 }
207 Err(InvalidReason::UnrecognizedFormat)
208}
209
210fn req_str(v: &JsonValue, d: Dialect, field: &'static str) -> Result<String, InvalidReason> {
211 match v.get(field) {
212 None => Err(InvalidReason::MissingField { dialect: d, field }),
213 Some(JsonValue::String(s)) => Ok(s.clone()),
214 Some(_) => Err(InvalidReason::WrongFieldType { dialect: d, field }),
215 }
216}
217
218fn opt_str(
219 v: &JsonValue,
220 d: Dialect,
221 field: &'static str,
222) -> Result<Option<String>, InvalidReason> {
223 match v.get(field) {
224 None => Ok(None),
225 Some(_) => req_str(v, d, field).map(Some),
226 }
227}
228
229fn parse_rfc0001(v: &JsonValue) -> Result<Rfc0001Crumb, InvalidReason> {
230 const D: Dialect = Dialect::Rfc0001Json;
231 if v.get("schema_version").and_then(JsonValue::as_str) != Some(RFC0001_SCHEMA_VERSION) {
232 return Err(InvalidReason::UnsupportedSchemaVersion);
233 }
234 let name = req_str(v, D, "name")?;
235 let purpose = req_str(v, D, "purpose")?;
236 let layer = opt_str(v, D, "layer")?;
237 let invariants = match v.get("invariants") {
238 None => Vec::new(),
239 Some(JsonValue::Array(items)) => items
240 .iter()
241 .map(|i| i.as_str().map(str::to_string))
242 .collect::<Option<Vec<_>>>()
243 .ok_or(InvalidReason::WrongFieldType {
244 dialect: D,
245 field: "invariants",
246 })?,
247 Some(_) => {
248 return Err(InvalidReason::WrongFieldType {
249 dialect: D,
250 field: "invariants",
251 })
252 }
253 };
254 Ok(Rfc0001Crumb {
255 name,
256 purpose,
257 layer,
258 invariants,
259 })
260}
261
262/// D2 checks mirror the serde shape of `spark-crumbs` `DirCrumb`: required `version` (u32),
263/// `dir_path`, `dir_name`, `description`; `purpose` absent, null, or an object with a string
264/// `statement`; `above` absent, null, a string, or an object of strings `path`, `canonical`,
265/// `name`, `role`; required arrays `below` (objects with strings `name`, `item_type`, `role`),
266/// `history`, and `whispers` (objects; their inner fields are not checked).
267fn parse_atlas(v: &JsonValue) -> Result<AtlasCrumb, InvalidReason> {
268 const D: Dialect = Dialect::AtlasJson;
269 let wrong = |field| InvalidReason::WrongFieldType { dialect: D, field };
270 let version = match v.get("version") {
271 Some(JsonValue::Number(n)) => n.parse::<u32>().map_err(|_| wrong("version"))?,
272 _ => return Err(wrong("version")),
273 };
274 let dir_path = req_str(v, D, "dir_path")?;
275 let dir_name = req_str(v, D, "dir_name")?;
276 let description = req_str(v, D, "description")?;
277 let purpose_statement = match v.get("purpose") {
278 None | Some(JsonValue::Null) => None,
279 Some(p @ JsonValue::Object(_)) => {
280 Some(req_str(p, D, "statement").map_err(|e| match e {
281 InvalidReason::MissingField { .. } => InvalidReason::MissingField {
282 dialect: D,
283 field: "purpose.statement",
284 },
285 _ => wrong("purpose.statement"),
286 })?)
287 }
288 Some(_) => return Err(wrong("purpose")),
289 };
290 match v.get("above") {
291 None | Some(JsonValue::Null) | Some(JsonValue::String(_)) => {}
292 Some(a @ JsonValue::Object(_)) => {
293 for f in ["path", "canonical", "name", "role"] {
294 if a.get(f).and_then(JsonValue::as_str).is_none() {
295 return Err(wrong("above"));
296 }
297 }
298 }
299 Some(_) => return Err(wrong("above")),
300 }
301 for field in ["below", "history", "whispers"] {
302 match v.get(field) {
303 None => return Err(InvalidReason::MissingField { dialect: D, field }),
304 Some(JsonValue::Array(items)) => {
305 for item in items {
306 if !matches!(item, JsonValue::Object(_)) {
307 return Err(wrong(field));
308 }
309 if field == "below"
310 && ["name", "item_type", "role"]
311 .iter()
312 .any(|f| item.get(f).and_then(JsonValue::as_str).is_none())
313 {
314 return Err(wrong(field));
315 }
316 }
317 }
318 Some(_) => return Err(wrong(field)),
319 }
320 }
321 Ok(AtlasCrumb {
322 version,
323 dir_path,
324 dir_name,
325 description,
326 purpose_statement,
327 })
328}
329
330/// What a snapshot holds at one `.crumb` path, as supplied by the caller.
331#[derive(Debug, Clone, PartialEq, Eq)]
332pub enum CrumbFile {
333 /// No file at this path.
334 Missing,
335 /// A symlink entry; its target is not followed.
336 NotRegularFile { blob_digest: BlobDigest },
337 /// A file larger than [`MAX_CRUMB_BYTES`]; its bytes were not read.
338 Oversized { blob_digest: BlobDigest, size: u64 },
339 /// The file's bytes.
340 Bytes(Vec<u8>),
341}
342
343/// Status of one directory's `.crumb` in a [`CrumbContext`].
344#[derive(Debug, Clone, PartialEq, Eq)]
345pub enum EntryStatus {
346 Present(DirectoryCrumb),
347 Missing,
348 Invalid(InvalidReason),
349}
350
351impl EntryStatus {
352 fn tag_byte(&self) -> u8 {
353 match self {
354 Self::Missing => 0,
355 Self::Present(_) => 1,
356 Self::Invalid(_) => 2,
357 }
358 }
359}
360
361/// One directory of a [`CrumbContext`] chain.
362#[derive(Debug, Clone, PartialEq, Eq)]
363pub struct CrumbContextEntry {
364 /// Repository-relative directory, [`ROOT_DIR`] for the root.
365 pub dir: String,
366 pub status: EntryStatus,
367 /// Digest of the `.crumb` bytes when a file exists (also for invalid files).
368 pub blob_digest: Option<BlobDigest>,
369}
370
371impl CrumbContextEntry {
372 /// Parsed dialect, or the dialect an invalid file claimed.
373 pub fn dialect(&self) -> Option<Dialect> {
374 match &self.status {
375 EntryStatus::Present(c) => Some(c.dialect()),
376 EntryStatus::Invalid(r) => r.claimed_dialect(),
377 EntryStatus::Missing => None,
378 }
379 }
380
381 pub fn crumb(&self) -> Option<&DirectoryCrumb> {
382 match &self.status {
383 EntryStatus::Present(c) => Some(c),
384 _ => None,
385 }
386 }
387}
388
389/// Repository-relative path of the `.crumb` file in `dir`.
390pub fn crumb_path(dir: &str) -> String {
391 if dir == ROOT_DIR {
392 CRUMB_FILE_NAME.to_string()
393 } else {
394 format!("{dir}/{CRUMB_FILE_NAME}")
395 }
396}
397
398/// The Directory Crumb context of one directory in one snapshot.
399#[derive(Debug, Clone, PartialEq, Eq)]
400pub struct CrumbContext {
401 target_dir: String,
402 /// Root first, `target_dir` last.
403 entries: Vec<CrumbContextEntry>,
404}
405
406impl CrumbContext {
407 /// Build the chain for `target_dir` (`"."` or a clean repository-relative directory),
408 /// asking `fetch` for each `.crumb` path from the root down.
409 pub fn resolve(
410 target_dir: &str,
411 mut fetch: impl FnMut(&str) -> SynapseResult<CrumbFile>,
412 ) -> SynapseResult<Self> {
413 let mut dirs = vec![ROOT_DIR.to_string()];
414 if target_dir != ROOT_DIR {
415 validate_repo_relative_path(target_dir)?;
416 let mut acc = String::new();
417 for seg in target_dir.split('/') {
418 if !acc.is_empty() {
419 acc.push('/');
420 }
421 acc.push_str(seg);
422 dirs.push(acc.clone());
423 }
424 }
425 if dirs.len() > MAX_CHAIN_LEN {
426 return Err(SynapseError::new(
427 RefusalCode::PathInvalid,
428 format!("directory chain longer than {MAX_CHAIN_LEN}: {target_dir}"),
429 ));
430 }
431 let mut entries = Vec::with_capacity(dirs.len());
432 for dir in dirs {
433 let (status, blob_digest) = match fetch(&crumb_path(&dir))? {
434 CrumbFile::Missing => (EntryStatus::Missing, None),
435 CrumbFile::NotRegularFile { blob_digest } => (
436 EntryStatus::Invalid(InvalidReason::NotRegularFile),
437 Some(blob_digest),
438 ),
439 CrumbFile::Oversized { blob_digest, size } => (
440 EntryStatus::Invalid(InvalidReason::TooLarge { size }),
441 Some(blob_digest),
442 ),
443 CrumbFile::Bytes(bytes) => {
444 let status = match parse_crumb(&bytes) {
445 Ok(c) => EntryStatus::Present(c),
446 Err(r) => EntryStatus::Invalid(r),
447 };
448 (status, Some(BlobDigest::compute(&bytes)))
449 }
450 };
451 entries.push(CrumbContextEntry {
452 dir,
453 status,
454 blob_digest,
455 });
456 }
457 Ok(Self {
458 target_dir: target_dir.to_string(),
459 entries,
460 })
461 }
462
463 pub fn target_dir(&self) -> &str {
464 &self.target_dir
465 }
466
467 /// Root first, target directory last.
468 pub fn entries(&self) -> &[CrumbContextEntry] {
469 &self.entries
470 }
471
472 /// The target directory's own entry (what `crumb sniff` and `crumb validate` report).
473 pub fn leaf(&self) -> &CrumbContextEntry {
474 // `resolve` always pushes the root, so the chain is never empty.
475 &self.entries[self.entries.len() - 1]
476 }
477
478 /// Nearest present crumb at or above the target (`crumb explain` "NEAREST CRUMB").
479 pub fn nearest(&self) -> Option<&CrumbContextEntry> {
480 self.entries
481 .iter()
482 .rev()
483 .find(|e| matches!(e.status, EntryStatus::Present(_)))
484 }
485
486 /// Invariants of present crumbs strictly above [`Self::nearest`], closest ancestor first,
487 /// each with its directory (`crumb explain` "INHERITED INVARIANTS").
488 pub fn inherited_invariants(&self) -> Vec<(&str, &str)> {
489 let Some(pos) = self
490 .entries
491 .iter()
492 .rposition(|e| matches!(e.status, EntryStatus::Present(_)))
493 else {
494 return Vec::new();
495 };
496 self.entries[..pos]
497 .iter()
498 .rev()
499 .filter_map(|e| e.crumb().map(|c| (e.dir.as_str(), c)))
500 .flat_map(|(d, c)| c.invariants().iter().map(move |i| (d, i.as_str())))
501 .collect()
502 }
503
504 /// Domain-separated digest of the whole chain, missing and invalid entries included.
505 pub fn digest(&self) -> CrumbContextDigest {
506 fn put(h: &mut Sha256, bytes: &[u8]) {
507 h.update((bytes.len() as u64).to_le_bytes());
508 h.update(bytes);
509 }
510 let mut h = Sha256::new();
511 h.update(DOMAIN_CRUMB_CONTEXT_V1);
512 put(&mut h, self.target_dir.as_bytes());
513 h.update((self.entries.len() as u64).to_le_bytes());
514 for e in &self.entries {
515 put(&mut h, e.dir.as_bytes());
516 h.update([
517 e.dialect().map_or(0, Dialect::tag_byte),
518 e.status.tag_byte(),
519 ]);
520 let reason = match &e.status {
521 EntryStatus::Invalid(r) => r.code(),
522 _ => 0,
523 };
524 h.update(reason.to_le_bytes());
525 match e.blob_digest {
526 Some(d) => {
527 h.update([1]);
528 h.update(d.0);
529 }
530 None => h.update([0]),
531 }
532 }
533 CrumbContextDigest(h.finalize().into())
534 }
535}
536
537/// 32-byte domain-separated SHA-256 digest (`"SYNAPSE_CRUMB_CONTEXT_V1\0"`) of a [`CrumbContext`].
538#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
539pub struct CrumbContextDigest(pub [u8; 32]);
540
541impl CrumbContextDigest {
542 pub fn to_hex(self) -> String {
543 hex::encode(self.0)
544 }
545}
546
547impl fmt::Debug for CrumbContextDigest {
548 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
549 write!(f, "CrumbContextDigest({})", self.to_hex())
550 }
551}
552
553impl fmt::Display for CrumbContextDigest {
554 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
555 f.write_str(&self.to_hex())
556 }
557}
558
559#[cfg(test)]
560mod tests {
561 use super::*;
562 use std::collections::BTreeMap;
563
564 const D1: &str =
565 r#"{"schema_version":"1.0.0","name":"n","purpose":"p","invariants":["i1","i2"]}"#;
566
567 fn ctx(files: &[(&str, &str)], dir: &str) -> CrumbContext {
568 let map: BTreeMap<String, Vec<u8>> = files
569 .iter()
570 .map(|(k, v)| (k.to_string(), v.as_bytes().to_vec()))
571 .collect();
572 CrumbContext::resolve(dir, |p| {
573 Ok(map
574 .get(p)
575 .map_or(CrumbFile::Missing, |b| CrumbFile::Bytes(b.clone())))
576 })
577 .unwrap()
578 }
579
580 #[test]
581 fn classifies_each_dialect_without_coercion() {
582 assert!(matches!(
583 parse_crumb(D1.as_bytes()),
584 Ok(DirectoryCrumb::Rfc0001(_))
585 ));
586 let d2 = r#"{"version":1,"dir_path":"/x","dir_name":"x","description":"d","purpose":{"statement":"s"},"above":null,"below":[],"history":[],"whispers":[]}"#;
587 match parse_crumb(d2.as_bytes()) {
588 Ok(DirectoryCrumb::Atlas(a)) => assert_eq!(a.purpose_statement.as_deref(), Some("s")),
589 other => panic!("{other:?}"),
590 }
591 assert!(matches!(
592 parse_crumb(b"schema: \"crumb/v1\"\n"),
593 Ok(DirectoryCrumb::YamlV1(_))
594 ));
595 }
596
597 #[test]
598 fn refuses_with_typed_reasons() {
599 let cases: Vec<(&[u8], InvalidReason)> = vec![
600 (b"[1]", InvalidReason::NotJsonObject),
601 (b"{\"name\":\"x\"}", InvalidReason::UnknownJsonDialect),
602 (
603 b"{\"schema_version\":\"2.0.0\",\"name\":\"n\",\"purpose\":\"p\"}",
604 InvalidReason::UnsupportedSchemaVersion,
605 ),
606 (
607 b"{\"schema_version\":\"1.0.0\",\"name\":\"n\"}",
608 InvalidReason::MissingField {
609 dialect: Dialect::Rfc0001Json,
610 field: "purpose",
611 },
612 ),
613 (
614 b"{\"schema_version\":\"1.0.0\",\"name\":\"n\",\"purpose\":\"p\",\"invariants\":\"x\"}",
615 InvalidReason::WrongFieldType {
616 dialect: Dialect::Rfc0001Json,
617 field: "invariants",
618 },
619 ),
620 (
621 b"{\"version\":\"1\",\"dir_path\":\"a\"}",
622 InvalidReason::WrongFieldType {
623 dialect: Dialect::AtlasJson,
624 field: "version",
625 },
626 ),
627 (
628 b"{\"version\":1,\"dir_path\":\"a\",\"dir_name\":\"a\",\"description\":\"d\",\"below\":[]}",
629 InvalidReason::MissingField {
630 dialect: Dialect::AtlasJson,
631 field: "history",
632 },
633 ),
634 (b"\xff\xfe", InvalidReason::NotUtf8),
635 (b"name: x\n", InvalidReason::UnrecognizedFormat),
636 (b"", InvalidReason::UnrecognizedFormat),
637 (
638 b"{\"a\":1,\"a\":2}",
639 InvalidReason::Json(JsonError::DuplicateKey { offset: 7 }),
640 ),
641 ];
642 for (doc, want) in cases {
643 assert_eq!(
644 parse_crumb(doc),
645 Err(want),
646 "{:?}",
647 String::from_utf8_lossy(doc)
648 );
649 }
650 }
651
652 /// Deliberate divergence from crumb.c (which reads any size): a document one byte over
653 /// the cap is refused before parsing, even when it is otherwise a valid D1 crumb.
654 #[test]
655 fn size_cap_is_enforced_where_crumb_c_has_none() {
656 let pad = MAX_CRUMB_BYTES as usize - D1.len();
657 let at_cap = format!("{}{}", D1, " ".repeat(pad));
658 assert_eq!(at_cap.len() as u64, MAX_CRUMB_BYTES);
659 assert!(parse_crumb(at_cap.as_bytes()).is_ok());
660 let over = format!("{at_cap} ");
661 assert_eq!(
662 parse_crumb(over.as_bytes()),
663 Err(InvalidReason::TooLarge {
664 size: MAX_CRUMB_BYTES + 1
665 })
666 );
667 }
668
669 #[test]
670 fn chain_nearest_and_inherited_follow_explain() {
671 let root = r#"{"schema_version":"1.0.0","name":"r","purpose":"p","invariants":["root-a"]}"#;
672 let c = ctx(&[(".crumb", root), ("a/.crumb", D1)], "a/b/c");
673 let dirs: Vec<&str> = c.entries().iter().map(|e| e.dir.as_str()).collect();
674 assert_eq!(dirs, [".", "a", "a/b", "a/b/c"]);
675 assert_eq!(c.leaf().status, EntryStatus::Missing);
676 assert_eq!(c.nearest().unwrap().dir, "a");
677 assert_eq!(c.inherited_invariants(), vec![(".", "root-a")]);
678
679 let root_only = ctx(&[(".crumb", root)], ".");
680 assert_eq!(root_only.entries().len(), 1);
681 assert!(root_only.inherited_invariants().is_empty());
682
683 let none = ctx(&[], "x");
684 assert!(none.nearest().is_none());
685 }
686
687 #[test]
688 fn invalid_entries_are_reported_and_skipped_for_nearest() {
689 let c = ctx(&[(".crumb", D1), ("a/.crumb", "{not json")], "a");
690 assert!(matches!(
691 c.leaf().status,
692 EntryStatus::Invalid(InvalidReason::Json(_))
693 ));
694 assert!(c.leaf().blob_digest.is_some());
695 assert_eq!(c.nearest().unwrap().dir, ".");
696 }
697
698 #[test]
699 fn digest_covers_missing_invalid_and_bytes() {
700 let base = ctx(&[(".crumb", D1)], "a").digest();
701 assert_eq!(base, ctx(&[(".crumb", D1)], "a").digest());
702 // A different target directory changes the digest even with identical crumbs.
703 assert_ne!(base, ctx(&[(".crumb", D1)], ".").digest());
704 // Missing vs invalid at the same directory.
705 assert_ne!(
706 base,
707 ctx(&[(".crumb", D1), ("a/.crumb", "{")], "a").digest()
708 );
709 // Different invalid bytes with the same reason code.
710 assert_ne!(
711 ctx(&[("a/.crumb", "{")], "a").digest(),
712 ctx(&[("a/.crumb", "{x")], "a").digest()
713 );
714 // Not a BlobDigest of anything obvious: the domain tag separates it.
715 assert_ne!(base.0, BlobDigest::compute(D1.as_bytes()).0);
716 }
717
718 #[test]
719 fn oversized_and_symlink_entries_are_invalid_with_digest() {
720 let d = BlobDigest::compute(b"x");
721 let c = CrumbContext::resolve(".", |_| {
722 Ok(CrumbFile::Oversized {
723 blob_digest: d,
724 size: MAX_CRUMB_BYTES + 1,
725 })
726 })
727 .unwrap();
728 assert_eq!(
729 c.leaf().status,
730 EntryStatus::Invalid(InvalidReason::TooLarge {
731 size: MAX_CRUMB_BYTES + 1
732 })
733 );
734 assert_eq!(c.leaf().blob_digest, Some(d));
735 let s = CrumbContext::resolve(".", |_| Ok(CrumbFile::NotRegularFile { blob_digest: d }))
736 .unwrap();
737 assert_eq!(
738 s.leaf().status,
739 EntryStatus::Invalid(InvalidReason::NotRegularFile)
740 );
741 }
742
743 #[test]
744 fn refuses_bad_target_paths() {
745 for bad in ["", "/a", "a/", "a/../b", "a/.git"] {
746 let r = CrumbContext::resolve(bad, |_| Ok(CrumbFile::Missing));
747 assert_eq!(r.unwrap_err().code, RefusalCode::PathInvalid, "{bad:?}");
748 }
749 let deep = vec!["d"; MAX_CHAIN_LEN].join("/");
750 assert!(CrumbContext::resolve(&deep, |_| Ok(CrumbFile::Missing)).is_err());
751 }
752}