1use std::io::{Cursor, Read};
10
11use memstead_schema::{
12 ARCHIVE_ANCHORS_PATH, ARCHIVE_CHECKS_PATH, ARCHIVE_CONFIG_PATH, ARCHIVE_META_DIR,
13 ARCHIVE_PROVENANCE_PATH, ARCHIVE_SCHEMA_PREFIX,
14};
15
16use super::{SizeCapKind, ValidationError, ValidatorLimits};
17
18#[derive(Debug)]
22pub struct MarkdownEntry {
23 pub path: String,
24 pub content: String,
25}
26
27#[derive(Debug)]
37pub struct SchemaFile {
38 pub archive_path: String,
39 pub content: String,
40}
41
42pub fn to_package_files(schema_files: &[SchemaFile]) -> Vec<(String, Vec<u8>)> {
51 schema_files
52 .iter()
53 .map(|sf| {
54 let rel = sf
55 .archive_path
56 .strip_prefix(memstead_schema::ARCHIVE_SCHEMA_PREFIX)
57 .unwrap_or(sf.archive_path.as_str());
58 (rel.to_string(), sf.content.as_bytes().to_vec())
59 })
60 .collect()
61}
62
63#[derive(Debug)]
64pub struct ArchiveEntries {
65 pub config_bytes: Vec<u8>,
66 pub markdown_files: Vec<MarkdownEntry>,
67 pub schema_files: Vec<SchemaFile>,
68 pub provenance_bytes: Option<Vec<u8>>,
74 pub anchors_bytes: Option<Vec<u8>>,
82 pub checks_bytes: Option<Vec<u8>>,
91 pub proposals_bytes: Option<Vec<u8>>,
100}
101
102pub fn extract_entries(
106 bytes: &[u8],
107 limits: &ValidatorLimits,
108) -> Result<ArchiveEntries, ValidationError> {
109 if bytes.len() as u64 > limits.max_compressed_archive {
110 return Err(ValidationError::SizeCapExceeded {
111 kind: SizeCapKind::CompressedArchive,
112 got: bytes.len() as u64,
113 limit: limits.max_compressed_archive,
114 });
115 }
116
117 let cursor = Cursor::new(bytes);
118 let mut archive =
119 zip::ZipArchive::new(cursor).map_err(|e| ValidationError::Zip(e.to_string()))?;
120
121 if archive.len() as u32 > limits.max_file_count {
122 return Err(ValidationError::SizeCapExceeded {
123 kind: SizeCapKind::EntryCount,
124 got: archive.len() as u64,
125 limit: limits.max_file_count as u64,
126 });
127 }
128
129 let mut config_bytes: Option<Vec<u8>> = None;
130 let mut markdown_files: Vec<MarkdownEntry> = Vec::new();
131 let mut schema_files: Vec<SchemaFile> = Vec::new();
132 let mut provenance_bytes: Option<Vec<u8>> = None;
133 let mut anchors_bytes: Option<Vec<u8>> = None;
134 let mut checks_bytes: Option<Vec<u8>> = None;
135 let mut proposals_bytes: Option<Vec<u8>> = None;
136 let mut seen_paths: Vec<String> = Vec::new();
137 let mut uncompressed_total: u64 = 0;
138
139 for i in 0..archive.len() {
140 let mut entry = archive
141 .by_index(i)
142 .map_err(|e| ValidationError::Zip(e.to_string()))?;
143
144 if entry.is_dir() {
145 continue;
146 }
147
148 if entry.is_symlink() {
149 return Err(ValidationError::Symlink(entry.name().to_string()));
150 }
151
152 let raw_name = entry.name();
158 if raw_name.starts_with('/') || raw_name.starts_with('\\') {
159 return Err(ValidationError::Zip(format!(
160 "unsafe entry path: {raw_name}"
161 )));
162 }
163 let raw_bytes = raw_name.as_bytes();
164 if raw_bytes.len() >= 2 && raw_bytes[1] == b':' && raw_bytes[0].is_ascii_alphabetic() {
165 return Err(ValidationError::Zip(format!(
166 "unsafe entry path: {raw_name}"
167 )));
168 }
169
170 let enclosed = entry
171 .enclosed_name()
172 .ok_or_else(|| ValidationError::Zip(format!("unsafe entry path: {}", entry.name())))?;
173 let path_string = enclosed
174 .to_str()
175 .ok_or_else(|| ValidationError::Zip(format!("non-UTF-8 entry path: {}", entry.name())))?
176 .replace('\\', "/");
177
178 if path_string.len() > limits.max_path_length {
179 return Err(ValidationError::PathTooLong {
180 path: path_string.clone(),
181 len: path_string.len(),
182 limit: limits.max_path_length,
183 });
184 }
185
186 let depth = path_string.split('/').count();
187 if depth > limits.max_path_depth {
188 return Err(ValidationError::PathTooDeep {
189 path: path_string.clone(),
190 depth,
191 limit: limits.max_path_depth,
192 });
193 }
194
195 if seen_paths.iter().any(|p| p == &path_string) {
196 return Err(ValidationError::DuplicateEntry(path_string));
197 }
198
199 let meta_dir_prefix = format!("{ARCHIVE_META_DIR}/");
200 let is_config = path_string == ARCHIVE_CONFIG_PATH;
201 let is_schema = is_schema_path(&path_string);
202 let is_provenance = path_string == ARCHIVE_PROVENANCE_PATH;
203 let is_anchors = path_string == ARCHIVE_ANCHORS_PATH;
204 let is_checks = path_string == ARCHIVE_CHECKS_PATH;
205 let is_proposals = path_string == crate::ops::proposal::PROPOSAL_RECORD_PATH;
206 let is_markdown =
210 path_string.ends_with(".md") && !path_string.starts_with(&meta_dir_prefix);
211 let is_ignored_meta = path_string.starts_with(&meta_dir_prefix)
228 && !is_config
229 && !is_schema
230 && !is_provenance
231 && !is_anchors
232 && !is_checks
233 && !is_proposals
234 && !path_string.ends_with(".md")
235 && !path_string.starts_with(ARCHIVE_SCHEMA_PREFIX);
236 if !is_config
237 && !is_markdown
238 && !is_schema
239 && !is_provenance
240 && !is_anchors
241 && !is_checks
242 && !is_proposals
243 && !is_ignored_meta
244 {
245 return Err(ValidationError::UnknownFile(path_string));
246 }
247
248 let per_entry_cap = if is_config {
249 limits.max_config_file
250 } else {
251 limits.max_uncompressed_entry
252 };
253
254 let mut buf = Vec::new();
255 let mut reader = (&mut entry).take(per_entry_cap + 1);
256 reader
257 .read_to_end(&mut buf)
258 .map_err(|e| ValidationError::Zip(e.to_string()))?;
259
260 if buf.len() as u64 > per_entry_cap {
261 let kind = if is_config {
262 SizeCapKind::ConfigFile
263 } else {
264 SizeCapKind::UncompressedEntry
265 };
266 return Err(ValidationError::SizeCapExceeded {
267 kind,
268 got: buf.len() as u64,
269 limit: per_entry_cap,
270 });
271 }
272
273 uncompressed_total = uncompressed_total.saturating_add(buf.len() as u64);
274 if uncompressed_total > limits.max_uncompressed_archive {
275 return Err(ValidationError::SizeCapExceeded {
276 kind: SizeCapKind::UncompressedArchive,
277 got: uncompressed_total,
278 limit: limits.max_uncompressed_archive,
279 });
280 }
281
282 seen_paths.push(path_string.clone());
283
284 if is_ignored_meta {
287 continue;
288 }
289
290 if is_config {
291 config_bytes = Some(buf);
292 } else if is_provenance {
293 provenance_bytes = Some(buf);
298 } else if is_anchors {
299 let sidecar = crate::anchor::AnchorSidecar::from_bytes(&buf).map_err(|e| {
306 ValidationError::InvalidAnchorsMember {
307 reason: e.to_string(),
308 }
309 })?;
310 sidecar
315 .validate_artifact_references()
316 .map_err(|reason| ValidationError::InvalidAnchorsMember { reason })?;
317 anchors_bytes = Some(buf);
318 } else if is_checks {
319 crate::check::SealedChecks::from_archive_bytes(&buf).map_err(|e| {
328 ValidationError::InvalidChecksMember {
329 reason: e.to_string(),
330 }
331 })?;
332 checks_bytes = Some(buf);
333 } else if is_proposals {
334 crate::ops::proposal::ProposalRecord::from_bytes(&buf).map_err(|e| {
338 ValidationError::InvalidProposalsMember {
339 reason: e.to_string(),
340 }
341 })?;
342 proposals_bytes = Some(buf);
343 } else {
344 let content = match std::str::from_utf8(&buf) {
345 Ok(s) => s.to_string(),
346 Err(e) => {
347 return Err(ValidationError::Utf8 {
348 path: path_string,
349 offset: e.valid_up_to(),
350 });
351 }
352 };
353 let content = content.replace("\r\n", "\n");
359 if is_schema {
360 schema_files.push(SchemaFile {
361 archive_path: path_string,
362 content,
363 });
364 } else {
365 markdown_files.push(MarkdownEntry {
366 path: path_string,
367 content,
368 });
369 }
370 }
371 }
372
373 let config_bytes = config_bytes.ok_or(ValidationError::MissingConfig)?;
374
375 markdown_files.sort_by(|a, b| a.path.cmp(&b.path));
376 schema_files.sort_by(|a, b| a.archive_path.cmp(&b.archive_path));
377
378 if let Some(bytes) = &checks_bytes {
382 let carried: std::collections::BTreeSet<String> = markdown_files
383 .iter()
384 .map(|m| m.path.strip_suffix(".md").unwrap_or(&m.path).to_string())
385 .collect();
386 crate::check::SealedChecks::from_archive_bytes(bytes)
387 .map_err(|e| e.to_string())
388 .and_then(|sealed| sealed.validate(&carried))
389 .map_err(|reason| ValidationError::InvalidChecksMember { reason })?;
390 }
391
392 Ok(ArchiveEntries {
393 config_bytes,
394 markdown_files,
395 schema_files,
396 provenance_bytes,
397 anchors_bytes,
398 checks_bytes,
399 proposals_bytes,
400 })
401}
402
403fn is_schema_path(path: &str) -> bool {
410 let Some(rest) = path.strip_prefix(ARCHIVE_SCHEMA_PREFIX) else {
411 return false;
412 };
413 if rest == "schema.yaml" {
414 return true;
415 }
416 if rest == memstead_schema::loader::SCHEMA_FORMAT_MARKER_FILE {
419 return true;
420 }
421 let Some(rest) = rest.strip_prefix("types/") else {
422 return false;
423 };
424 if !rest.ends_with(".yaml") {
425 return false;
426 }
427 let stem = &rest[..rest.len() - ".yaml".len()];
428 !stem.is_empty() && !stem.contains('/')
429}
430
431#[cfg(test)]
432mod tests {
433 use super::*;
434 use std::io::Write;
435 use zip::write::SimpleFileOptions;
436
437 fn build_archive(entries: &[(&str, &[u8])]) -> Vec<u8> {
440 let mut buf = Vec::new();
441 {
442 let cursor = Cursor::new(&mut buf);
443 let mut w = zip::ZipWriter::new(cursor);
444 let options =
445 SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
446 for (name, content) in entries {
447 w.start_file(*name, options).unwrap();
448 w.write_all(content).unwrap();
449 }
450 w.finish().unwrap();
451 }
452 buf
453 }
454
455 fn ok_config() -> &'static [u8] {
456 br#"{"format":3,"name":"v","version":"0.1.0","schema":"default@1.0.0"}"#
457 }
458
459 #[test]
460 fn accepts_minimal_valid_archive() {
461 let zip = build_archive(&[
462 (".memstead/config.json", ok_config()),
463 ("foo.md", b"# Foo\n"),
464 ]);
465 let entries = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap();
466 assert_eq!(entries.markdown_files.len(), 1);
467 assert_eq!(entries.markdown_files[0].path, "foo.md");
468 assert!(entries.provenance_bytes.is_none());
471 }
472
473 #[test]
477 fn recognises_valid_anchors_member() {
478 let anchors = br#"{"version":1,"entities":{"v--foo":[{"artifact":"src/lib.rs","grain":"file","class":"anchored","hash_stability":"stable","hash":"h1"}]}}"#;
479 let zip = build_archive(&[
480 (".memstead/config.json", ok_config()),
481 (".memstead/anchors.json", anchors),
482 ("foo.md", b"# Foo\n"),
483 ]);
484 let entries = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap();
485 assert_eq!(
486 entries.anchors_bytes.as_deref(),
487 Some(&anchors[..]),
488 "anchors bytes surface verbatim"
489 );
490 assert_eq!(entries.markdown_files.len(), 1, "anchors is not an entity");
491 }
492
493 #[test]
497 fn rejects_malformed_anchors_member() {
498 let zip = build_archive(&[
499 (".memstead/config.json", ok_config()),
500 (".memstead/anchors.json", b"{ this is not valid json"),
501 ("foo.md", b"# Foo\n"),
502 ]);
503 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
504 assert!(
505 matches!(err, ValidationError::InvalidAnchorsMember { .. }),
506 "expected InvalidAnchorsMember, got {err:?}"
507 );
508 }
509
510 #[test]
515 fn rejects_empty_artifact_reference_in_anchors_member() {
516 let empty_ref = br#"{"version":1,"entities":{"v--foo":[{"artifact":"","grain":"file","class":"anchored","hash_stability":"stable"}]}}"#;
517 let zip = build_archive(&[
518 (".memstead/config.json", ok_config()),
519 (".memstead/anchors.json", empty_ref),
520 ("foo.md", b"# Foo\n"),
521 ]);
522 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
523 assert!(
524 matches!(err, ValidationError::InvalidAnchorsMember { .. }),
525 "expected InvalidAnchorsMember, got {err:?}"
526 );
527
528 let redacted = br#"{"version":1,"entities":{"v--foo":[{"artifact":"[redacted]","grain":"file","class":"anchored","hash_stability":"stable","hash":"h1"}]}}"#;
529 let zip = build_archive(&[
530 (".memstead/config.json", ok_config()),
531 (".memstead/anchors.json", redacted),
532 ("foo.md", b"# Foo\n"),
533 ]);
534 let entries = extract_entries(&zip, &ValidatorLimits::DEFAULT)
535 .expect("the pinned sentinel form is a valid member");
536 assert!(entries.anchors_bytes.is_some());
537 }
538
539 #[test]
546 fn recognises_and_repacks_the_proposals_member_and_refuses_a_malformed_one() {
547 let record = br#"{"version":1,"proposals":[{"id":"f@b","proposer":"p","ancestor":"a","base":"b","target_tip":"t","merged_by":"m","at":"2026-09-20T00:00:00Z","entities":{"foo":{"disposition":"reject","reason":"weak","content_hash":"h1"}}}]}"#;
548 let archive = build_archive(&[
549 (".memstead/config.json", ok_config()),
550 (".memstead/proposals.json", record),
551 ("foo.md", b"# Foo\n"),
552 ]);
553 let entries = extract_entries(&archive, &ValidatorLimits::DEFAULT).unwrap();
554 assert_eq!(entries.proposals_bytes.as_deref(), Some(&record[..]));
555 assert_eq!(
556 entries.markdown_files.len(),
557 1,
558 "the member is not an entity"
559 );
560
561 let broken = build_archive(&[
562 (".memstead/config.json", ok_config()),
563 (".memstead/proposals.json", b"not a record"),
564 ("foo.md", b"# Foo\n"),
565 ]);
566 let err = extract_entries(&broken, &ValidatorLimits::DEFAULT).unwrap_err();
567 match &err {
568 ValidationError::InvalidProposalsMember { .. } => {}
569 other => panic!("expected InvalidProposalsMember, got {other:?}"),
570 }
571 assert!(
572 err.to_string().contains(".memstead/proposals.json"),
573 "{err}"
574 );
575
576 let config: memstead_schema::PublishedMemConfig =
578 serde_json::from_slice(ok_config()).unwrap();
579 let repacked = crate::validator::canonical::canonical_bytes(
580 &config,
581 &[],
582 &[],
583 None,
584 None,
585 None,
586 None,
587 Some(record),
588 )
589 .unwrap();
590 let mut zip = zip::ZipArchive::new(Cursor::new(repacked)).unwrap();
591 let mut member = zip
592 .by_name(".memstead/proposals.json")
593 .expect("member carried");
594 let mut bytes = Vec::new();
595 member.read_to_end(&mut bytes).unwrap();
596 assert_eq!(bytes, record);
597 }
598
599 fn checks_member(entity: &str, kind: &str, verdict: &str) -> Vec<u8> {
600 format!(
601 r#"{{"version":1,"entities":{{"{entity}":{{"{kind}":{{"ts":1,"verdict":"{verdict}","entity_hash":"h1","actor":"cli","role":"checker","identity":"checker-s1"}}}}}}}}"#
602 )
603 .into_bytes()
604 }
605
606 #[test]
609 fn recognises_valid_checks_member() {
610 let checks = checks_member("foo", "verification", "ok");
611 let archive = build_archive(&[
612 (".memstead/config.json", ok_config()),
613 (".memstead/checks.json", &checks),
614 ("foo.md", b"# Foo\n"),
615 ]);
616 let entries = extract_entries(&archive, &ValidatorLimits::DEFAULT).unwrap();
617 assert_eq!(
618 entries.checks_bytes.as_deref(),
619 Some(&checks[..]),
620 "checks bytes surface verbatim"
621 );
622 assert_eq!(entries.markdown_files.len(), 1, "checks is not an entity");
623
624 for kind in ["conformance", "x-audit"] {
626 let checks = checks_member("foo", kind, "failed");
627 let archive = build_archive(&[
628 (".memstead/config.json", ok_config()),
629 (".memstead/checks.json", &checks),
630 ("foo.md", b"# Foo\n"),
631 ]);
632 extract_entries(&archive, &ValidatorLimits::DEFAULT)
633 .unwrap_or_else(|e| panic!("kind {kind} is in the vocabulary: {e}"));
634 }
635 }
636
637 #[test]
645 fn rejects_malformed_checks_member() {
646 let refuse = |member: &[u8], expect: &str| {
647 let archive = build_archive(&[
648 (".memstead/config.json", ok_config()),
649 (".memstead/checks.json", member),
650 ("foo.md", b"# Foo\n"),
651 ]);
652 let err = extract_entries(&archive, &ValidatorLimits::DEFAULT).unwrap_err();
653 match &err {
654 ValidationError::InvalidChecksMember { reason } => {
655 assert!(reason.contains(expect), "expected `{expect}` in: {reason}");
656 }
657 other => panic!("expected InvalidChecksMember, got {other:?}"),
658 }
659 assert!(
660 err.to_string().contains(".memstead/checks.json"),
661 "the refusal names the member: {err}"
662 );
663 };
664 refuse(b"{ this is not valid json", "key must be a string");
665 refuse(&checks_member("foo", "audit", "ok"), "kind `audit`");
666 refuse(
667 &checks_member("foo", "verification", "maybe"),
668 "verdict `maybe`",
669 );
670 refuse(
671 &checks_member("bar", "verification", "ok"),
672 "entity `bar` names no entity the archive carries",
673 );
674 refuse(
675 br#"{"version":2,"entities":{}}"#,
676 "version 2 is not the version this engine reads",
677 );
678
679 let archive = build_archive(&[
681 (".memstead/config.json", ok_config()),
682 ("checks.json", &checks_member("foo", "verification", "ok")),
683 ("foo.md", b"# Foo\n"),
684 ]);
685 let err = extract_entries(&archive, &ValidatorLimits::DEFAULT).unwrap_err();
686 assert!(
687 matches!(err, ValidationError::UnknownFile(ref p) if p == "checks.json"),
688 "got {err:?}"
689 );
690 }
691
692 #[test]
697 fn recognises_provenance_member() {
698 let prov = br#"{"format":1,"history":"summarised","entities":{}}"#;
699 let zip = build_archive(&[
700 (".memstead/config.json", ok_config()),
701 (".memstead/provenance.json", prov),
702 ("foo.md", b"# Foo\n"),
703 ]);
704 let entries = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap();
705 assert_eq!(
706 entries.provenance_bytes.as_deref(),
707 Some(&prov[..]),
708 "provenance bytes surface verbatim"
709 );
710 assert_eq!(
711 entries.markdown_files.len(),
712 1,
713 "provenance is not an entity"
714 );
715 }
716
717 #[test]
725 fn tolerates_unknown_meta_member_but_rejects_unknown_root_member() {
726 let tolerated = build_archive(&[
727 (".memstead/config.json", ok_config()),
728 (".memstead/future-payload.json", br#"{"x":1}"#),
729 ("foo.md", b"# Foo\n"),
730 ]);
731 let entries = extract_entries(&tolerated, &ValidatorLimits::DEFAULT)
732 .expect("unknown meta member must be tolerated");
733 assert_eq!(entries.markdown_files.len(), 1);
734 assert!(
735 entries.provenance_bytes.is_none(),
736 "an unrecognised meta member is ignored, not surfaced as provenance"
737 );
738
739 let rejected = build_archive(&[
740 (".memstead/config.json", ok_config()),
741 ("stray.txt", b"not allowed at root"),
742 ("foo.md", b"# Foo\n"),
743 ]);
744 let err = extract_entries(&rejected, &ValidatorLimits::DEFAULT).unwrap_err();
745 assert!(
746 matches!(err, ValidationError::UnknownFile(ref p) if p == "stray.txt"),
747 "unknown non-meta member must still be rejected, got {err:?}"
748 );
749 }
750
751 #[test]
755 fn rejects_mixed_meta_dir_layout() {
756 let zip = build_archive(&[
757 (".memstead/config.json", ok_config()),
758 (".other/schema/schema.yaml", b"name: default\n"),
759 ("foo.md", b"# Foo\n"),
760 ]);
761 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
762 match err {
763 ValidationError::UnknownFile(path) => {
764 assert!(path.starts_with(".other/"), "path={path}");
765 }
766 other => panic!("expected UnknownFile for the foreign meta member, got {other:?}"),
767 }
768 }
769
770 #[test]
773 fn rejects_markdown_inside_meta_dir() {
774 let zip = build_archive(&[
775 (".memstead/config.json", ok_config()),
776 (".memstead/notes.md", b"# not an entity\n"),
777 ]);
778 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
779 assert!(
780 matches!(err, ValidationError::UnknownFile(_)),
781 "got {err:?}"
782 );
783 }
784
785 #[test]
786 fn markdown_files_are_sorted() {
787 let zip = build_archive(&[
788 (".memstead/config.json", ok_config()),
789 ("z.md", b"# Z\n"),
790 ("a.md", b"# A\n"),
791 ("m.md", b"# M\n"),
792 ]);
793 let entries = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap();
794 let paths: Vec<_> = entries
795 .markdown_files
796 .iter()
797 .map(|e| e.path.as_str())
798 .collect();
799 assert_eq!(paths, vec!["a.md", "m.md", "z.md"]);
800 }
801
802 #[test]
803 fn rejects_corrupt_zip() {
804 let err = extract_entries(b"not a zip at all", &ValidatorLimits::DEFAULT).unwrap_err();
805 assert!(matches!(err, ValidationError::Zip(_)));
806 }
807
808 #[test]
809 fn rejects_missing_config() {
810 let zip = build_archive(&[("foo.md", b"# Foo\n")]);
811 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
812 assert!(matches!(err, ValidationError::MissingConfig));
813 }
814
815 #[test]
816 fn rejects_non_markdown_non_config_file() {
817 let zip = build_archive(&[
818 (".memstead/config.json", ok_config()),
819 ("binary.exe", b"\x7fELF"),
820 ]);
821 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
822 match err {
823 ValidationError::UnknownFile(p) => assert_eq!(p, "binary.exe"),
824 other => panic!("expected UnknownFile, got {other:?}"),
825 }
826 }
827
828 #[test]
829 fn accepts_schema_package_entries() {
830 let zip = build_archive(&[
835 (".memstead/config.json", ok_config()),
836 ("foo.md", b"# Foo\n"),
837 (".memstead/schema/schema.yaml", b"name: default\n"),
838 (".memstead/schema/types/spec.yaml", b"name: spec\n"),
839 ]);
840 let entries = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap();
841 assert_eq!(entries.schema_files.len(), 2);
842 let paths: Vec<&str> = entries
843 .schema_files
844 .iter()
845 .map(|s| s.archive_path.as_str())
846 .collect();
847 assert_eq!(
848 paths,
849 vec![
850 ".memstead/schema/schema.yaml",
851 ".memstead/schema/types/spec.yaml"
852 ]
853 );
854 }
855
856 #[test]
860 fn accepts_schema_format_marker() {
861 let zip = build_archive(&[
862 (".memstead/config.json", ok_config()),
863 ("foo.md", b"# Foo\n"),
864 (".memstead/schema/schema.yaml", b"name: default\n"),
865 (
866 ".memstead/schema/schema-format.json",
867 b"{\"metadata_polarity\":\"required-opt-in\"}\n",
868 ),
869 ]);
870 let entries = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap();
871 assert!(
872 entries
873 .schema_files
874 .iter()
875 .any(|s| s.archive_path == ".memstead/schema/schema-format.json"),
876 "marker must ride in schema_files"
877 );
878 }
879
880 #[test]
881 fn rejects_unknown_schema_subpath() {
882 let zip = build_archive(&[
886 (".memstead/config.json", ok_config()),
887 (".memstead/schema/unexpected.json", b"{}"),
888 ]);
889 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
890 assert!(matches!(err, ValidationError::UnknownFile(_)));
891 }
892
893 #[test]
894 fn rejects_nested_schema_type_file() {
895 let zip = build_archive(&[
896 (".memstead/config.json", ok_config()),
897 (
898 ".memstead/schema/types/nested/subtype.yaml",
899 b"name: subtype\n",
900 ),
901 ]);
902 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
903 assert!(matches!(err, ValidationError::UnknownFile(_)));
904 }
905
906 #[test]
909 fn rejects_unknown_root_file() {
910 let zip = build_archive(&[
911 (".memstead/config.json", ok_config()),
912 (
913 "some-root.json",
914 br#"{"format":3,"name":"v","version":"0.1.0"}"#,
915 ),
916 ]);
917 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
918 assert!(
919 matches!(err, ValidationError::UnknownFile(ref p) if p == "some-root.json"),
920 "unknown root file must be rejected as UnknownFile, got {err:?}"
921 );
922 }
923
924 #[test]
925 fn rejects_zip_slip() {
926 let zip = build_archive(&[
927 (".memstead/config.json", ok_config()),
928 ("../escape.md", b"# Escape\n"),
929 ]);
930 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
931 assert!(matches!(err, ValidationError::Zip(_)));
932 }
933
934 #[test]
935 fn rejects_nested_zip_slip() {
936 let zip = build_archive(&[
937 (".memstead/config.json", ok_config()),
938 ("subdir/../../escape.md", b"# Escape\n"),
939 ]);
940 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
941 assert!(matches!(err, ValidationError::Zip(_)));
942 }
943
944 fn crc32(data: &[u8]) -> u32 {
952 let mut crc = !0u32;
953 for &b in data {
954 crc ^= b as u32;
955 for _ in 0..8 {
956 let mask = (crc & 1).wrapping_neg();
957 crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
958 }
959 }
960 !crc
961 }
962
963 fn raw_zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
968 let mut out: Vec<u8> = Vec::new();
969 let mut central: Vec<u8> = Vec::new();
970 let mut count: u16 = 0;
971
972 for (name, content) in entries {
973 let name_bytes = name.as_bytes();
974 let crc = crc32(content);
975 let size = content.len() as u32;
976 let offset = out.len() as u32;
977
978 out.extend_from_slice(&[0x50, 0x4b, 0x03, 0x04]);
980 out.extend_from_slice(&10u16.to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(&crc.to_le_bytes());
986 out.extend_from_slice(&size.to_le_bytes()); out.extend_from_slice(&size.to_le_bytes()); out.extend_from_slice(&(name_bytes.len() as u16).to_le_bytes());
989 out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(name_bytes);
991 out.extend_from_slice(content);
992
993 central.extend_from_slice(&[0x50, 0x4b, 0x01, 0x02]);
995 central.extend_from_slice(&20u16.to_le_bytes()); central.extend_from_slice(&10u16.to_le_bytes()); central.extend_from_slice(&0u16.to_le_bytes()); central.extend_from_slice(&0u16.to_le_bytes()); central.extend_from_slice(&0u16.to_le_bytes()); central.extend_from_slice(&0u16.to_le_bytes()); central.extend_from_slice(&crc.to_le_bytes());
1002 central.extend_from_slice(&size.to_le_bytes());
1003 central.extend_from_slice(&size.to_le_bytes());
1004 central.extend_from_slice(&(name_bytes.len() as u16).to_le_bytes());
1005 central.extend_from_slice(&0u16.to_le_bytes()); central.extend_from_slice(&0u16.to_le_bytes()); central.extend_from_slice(&0u16.to_le_bytes()); central.extend_from_slice(&0u16.to_le_bytes()); central.extend_from_slice(&0u32.to_le_bytes()); central.extend_from_slice(&offset.to_le_bytes()); central.extend_from_slice(name_bytes);
1012
1013 count += 1;
1014 }
1015
1016 let cd_offset = out.len() as u32;
1017 let cd_size = central.len() as u32;
1018 out.extend_from_slice(¢ral);
1019
1020 out.extend_from_slice(&[0x50, 0x4b, 0x05, 0x06]);
1022 out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(&count.to_le_bytes()); out.extend_from_slice(&count.to_le_bytes()); out.extend_from_slice(&cd_size.to_le_bytes());
1027 out.extend_from_slice(&cd_offset.to_le_bytes());
1028 out.extend_from_slice(&0u16.to_le_bytes()); out
1031 }
1032
1033 #[test]
1042 fn rejects_absolute_path_entry() {
1043 let zip = raw_zip(&[
1044 (".memstead/config.json", ok_config()),
1045 ("/etc/passwd.md", b"# Escape\n"),
1046 ]);
1047 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
1048 match err {
1051 ValidationError::Zip(reason) => {
1052 assert!(
1053 reason.contains("unsafe entry path"),
1054 "unexpected reason: {reason}"
1055 );
1056 }
1057 other => panic!("expected Zip(unsafe entry), got {other:?}"),
1058 }
1059 }
1060
1061 #[test]
1062 fn rejects_windows_drive_letter_entry() {
1063 let zip = raw_zip(&[
1067 (".memstead/config.json", ok_config()),
1068 ("C:\\evil.md", b"# Escape\n"),
1069 ]);
1070 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
1071 assert!(matches!(err, ValidationError::Zip(_)));
1072 }
1073
1074 #[test]
1075 fn rejects_symlink_entry() {
1076 let mut buf: Vec<u8> = Vec::new();
1082 {
1083 let cursor = Cursor::new(&mut buf);
1084 let mut w = zip::ZipWriter::new(cursor);
1085 w.start_file(".memstead/config.json", SimpleFileOptions::default())
1086 .unwrap();
1087 w.write_all(ok_config()).unwrap();
1088 w.add_symlink("link.md", "target.md", SimpleFileOptions::default())
1089 .unwrap();
1090 w.finish().unwrap();
1091 }
1092 let err = extract_entries(&buf, &ValidatorLimits::DEFAULT).unwrap_err();
1093 match err {
1094 ValidationError::Symlink(name) => assert_eq!(name, "link.md"),
1095 other => panic!("expected Symlink, got {other:?}"),
1096 }
1097 }
1098
1099 #[test]
1100 fn rejects_compressed_archive_too_large() {
1101 let mut limits = ValidatorLimits::DEFAULT;
1102 limits.max_compressed_archive = 64;
1103 let zip = build_archive(&[
1104 (".memstead/config.json", ok_config()),
1105 ("foo.md", b"# Foo\n"),
1106 ]);
1107 let err = extract_entries(&zip, &limits).unwrap_err();
1108 assert!(matches!(
1109 err,
1110 ValidationError::SizeCapExceeded {
1111 kind: SizeCapKind::CompressedArchive,
1112 ..
1113 }
1114 ));
1115 }
1116
1117 #[test]
1118 fn rejects_single_entry_too_large() {
1119 let mut limits = ValidatorLimits::DEFAULT;
1120 limits.max_uncompressed_entry = 10;
1121 let zip = build_archive(&[
1122 (".memstead/config.json", ok_config()),
1123 ("big.md", &[b'x'; 100]),
1124 ]);
1125 let err = extract_entries(&zip, &limits).unwrap_err();
1126 assert!(matches!(
1127 err,
1128 ValidationError::SizeCapExceeded {
1129 kind: SizeCapKind::UncompressedEntry,
1130 ..
1131 }
1132 ));
1133 }
1134
1135 #[test]
1136 fn rejects_config_file_too_large() {
1137 let mut limits = ValidatorLimits::DEFAULT;
1138 limits.max_config_file = 10;
1139 let zip = build_archive(&[
1140 (".memstead/config.json", &[b'x'; 50]),
1141 ("foo.md", b"# Foo\n"),
1142 ]);
1143 let err = extract_entries(&zip, &limits).unwrap_err();
1144 assert!(matches!(
1145 err,
1146 ValidationError::SizeCapExceeded {
1147 kind: SizeCapKind::ConfigFile,
1148 ..
1149 }
1150 ));
1151 }
1152
1153 #[test]
1154 fn rejects_uncompressed_sum_too_large() {
1155 let mut limits = ValidatorLimits::DEFAULT;
1156 limits.max_uncompressed_archive = 30;
1157 let zip = build_archive(&[
1158 (".memstead/config.json", ok_config()),
1159 ("a.md", &[b'x'; 20]),
1160 ("b.md", &[b'x'; 20]),
1161 ]);
1162 let err = extract_entries(&zip, &limits).unwrap_err();
1163 assert!(matches!(
1164 err,
1165 ValidationError::SizeCapExceeded {
1166 kind: SizeCapKind::UncompressedArchive,
1167 ..
1168 }
1169 ));
1170 }
1171
1172 #[test]
1173 fn rejects_entry_count_too_large() {
1174 let mut limits = ValidatorLimits::DEFAULT;
1175 limits.max_file_count = 2;
1176 let zip = build_archive(&[
1177 (".memstead/config.json", ok_config()),
1178 ("a.md", b"# A\n"),
1179 ("b.md", b"# B\n"),
1180 ]);
1181 let err = extract_entries(&zip, &limits).unwrap_err();
1182 assert!(matches!(
1183 err,
1184 ValidationError::SizeCapExceeded {
1185 kind: SizeCapKind::EntryCount,
1186 ..
1187 }
1188 ));
1189 }
1190
1191 #[test]
1192 fn rejects_path_too_long() {
1193 let mut limits = ValidatorLimits::DEFAULT;
1194 limits.max_path_length = 10;
1195 let long_name = format!("{}.md", "a".repeat(20));
1196 let zip = build_archive(&[
1197 (".memstead/config.json", ok_config()),
1198 (long_name.as_str(), b"# x\n"),
1199 ]);
1200 let err = extract_entries(&zip, &limits).unwrap_err();
1201 assert!(matches!(err, ValidationError::PathTooLong { .. }));
1202 }
1203
1204 #[test]
1205 fn rejects_path_too_deep() {
1206 let mut limits = ValidatorLimits::DEFAULT;
1207 limits.max_path_depth = 2;
1208 let zip = build_archive(&[
1209 (".memstead/config.json", ok_config()),
1210 ("a/b/c/d.md", b"# x\n"),
1211 ]);
1212 let err = extract_entries(&zip, &limits).unwrap_err();
1213 assert!(matches!(err, ValidationError::PathTooDeep { .. }));
1214 }
1215
1216 #[test]
1217 fn rejects_non_utf8_markdown_content() {
1218 let zip = build_archive(&[
1219 (".memstead/config.json", ok_config()),
1220 ("bad.md", &[0xff, 0xfe, 0xff]),
1221 ]);
1222 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
1223 assert!(matches!(err, ValidationError::Utf8 { .. }));
1224 }
1225}