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 let raw_name: String = entry
152 .name()
153 .map_err(|e| ValidationError::Zip(format!("entry {i}: undecodable name: {e}")))?
154 .into_owned();
155
156 if entry.is_symlink() {
157 return Err(ValidationError::Symlink(raw_name));
158 }
159
160 if raw_name.starts_with('/') || raw_name.starts_with('\\') {
166 return Err(ValidationError::Zip(format!(
167 "unsafe entry path: {raw_name}"
168 )));
169 }
170 let raw_bytes = raw_name.as_bytes();
171 if raw_bytes.len() >= 2 && raw_bytes[1] == b':' && raw_bytes[0].is_ascii_alphabetic() {
172 return Err(ValidationError::Zip(format!(
173 "unsafe entry path: {raw_name}"
174 )));
175 }
176
177 let enclosed = entry
178 .enclosed_name()
179 .ok_or_else(|| ValidationError::Zip(format!("unsafe entry path: {raw_name}")))?;
180 let path_string = enclosed
181 .to_str()
182 .ok_or_else(|| ValidationError::Zip(format!("non-UTF-8 entry path: {raw_name}")))?
183 .replace('\\', "/");
184
185 if path_string.len() > limits.max_path_length {
186 return Err(ValidationError::PathTooLong {
187 path: path_string.clone(),
188 len: path_string.len(),
189 limit: limits.max_path_length,
190 });
191 }
192
193 let depth = path_string.split('/').count();
194 if depth > limits.max_path_depth {
195 return Err(ValidationError::PathTooDeep {
196 path: path_string.clone(),
197 depth,
198 limit: limits.max_path_depth,
199 });
200 }
201
202 if seen_paths.iter().any(|p| p == &path_string) {
203 return Err(ValidationError::DuplicateEntry(path_string));
204 }
205
206 let meta_dir_prefix = format!("{ARCHIVE_META_DIR}/");
207 let is_config = path_string == ARCHIVE_CONFIG_PATH;
208 let is_schema = is_schema_path(&path_string);
209 let is_provenance = path_string == ARCHIVE_PROVENANCE_PATH;
210 let is_anchors = path_string == ARCHIVE_ANCHORS_PATH;
211 let is_checks = path_string == ARCHIVE_CHECKS_PATH;
212 let is_proposals = path_string == crate::ops::proposal::PROPOSAL_RECORD_PATH;
213 let is_markdown =
217 path_string.ends_with(".md") && !path_string.starts_with(&meta_dir_prefix);
218 let is_ignored_meta = path_string.starts_with(&meta_dir_prefix)
235 && !is_config
236 && !is_schema
237 && !is_provenance
238 && !is_anchors
239 && !is_checks
240 && !is_proposals
241 && !path_string.ends_with(".md")
242 && !path_string.starts_with(ARCHIVE_SCHEMA_PREFIX);
243 if !is_config
244 && !is_markdown
245 && !is_schema
246 && !is_provenance
247 && !is_anchors
248 && !is_checks
249 && !is_proposals
250 && !is_ignored_meta
251 {
252 return Err(ValidationError::UnknownFile(path_string));
253 }
254
255 let per_entry_cap = if is_config {
256 limits.max_config_file
257 } else {
258 limits.max_uncompressed_entry
259 };
260
261 let mut buf = Vec::new();
262 let mut reader = (&mut entry).take(per_entry_cap + 1);
263 reader
264 .read_to_end(&mut buf)
265 .map_err(|e| ValidationError::Zip(e.to_string()))?;
266
267 if buf.len() as u64 > per_entry_cap {
268 let kind = if is_config {
269 SizeCapKind::ConfigFile
270 } else {
271 SizeCapKind::UncompressedEntry
272 };
273 return Err(ValidationError::SizeCapExceeded {
274 kind,
275 got: buf.len() as u64,
276 limit: per_entry_cap,
277 });
278 }
279
280 uncompressed_total = uncompressed_total.saturating_add(buf.len() as u64);
281 if uncompressed_total > limits.max_uncompressed_archive {
282 return Err(ValidationError::SizeCapExceeded {
283 kind: SizeCapKind::UncompressedArchive,
284 got: uncompressed_total,
285 limit: limits.max_uncompressed_archive,
286 });
287 }
288
289 seen_paths.push(path_string.clone());
290
291 if is_ignored_meta {
294 continue;
295 }
296
297 if is_config {
298 config_bytes = Some(buf);
299 } else if is_provenance {
300 provenance_bytes = Some(buf);
305 } else if is_anchors {
306 let sidecar = crate::anchor::AnchorSidecar::from_bytes(&buf).map_err(|e| {
313 ValidationError::InvalidAnchorsMember {
314 reason: e.to_string(),
315 }
316 })?;
317 sidecar
322 .validate_artifact_references()
323 .map_err(|reason| ValidationError::InvalidAnchorsMember { reason })?;
324 anchors_bytes = Some(buf);
325 } else if is_checks {
326 crate::check::SealedChecks::from_archive_bytes(&buf).map_err(|e| {
335 ValidationError::InvalidChecksMember {
336 reason: e.to_string(),
337 }
338 })?;
339 checks_bytes = Some(buf);
340 } else if is_proposals {
341 crate::ops::proposal::ProposalRecord::from_bytes(&buf).map_err(|e| {
345 ValidationError::InvalidProposalsMember {
346 reason: e.to_string(),
347 }
348 })?;
349 proposals_bytes = Some(buf);
350 } else {
351 let content = match std::str::from_utf8(&buf) {
352 Ok(s) => s.to_string(),
353 Err(e) => {
354 return Err(ValidationError::Utf8 {
355 path: path_string,
356 offset: e.valid_up_to(),
357 });
358 }
359 };
360 let content = content.replace("\r\n", "\n");
366 if is_schema {
367 schema_files.push(SchemaFile {
368 archive_path: path_string,
369 content,
370 });
371 } else {
372 markdown_files.push(MarkdownEntry {
373 path: path_string,
374 content,
375 });
376 }
377 }
378 }
379
380 let config_bytes = config_bytes.ok_or(ValidationError::MissingConfig)?;
381
382 markdown_files.sort_by(|a, b| a.path.cmp(&b.path));
383 schema_files.sort_by(|a, b| a.archive_path.cmp(&b.archive_path));
384
385 if let Some(bytes) = &checks_bytes {
389 let carried: std::collections::BTreeSet<String> = markdown_files
390 .iter()
391 .map(|m| m.path.strip_suffix(".md").unwrap_or(&m.path).to_string())
392 .collect();
393 crate::check::SealedChecks::from_archive_bytes(bytes)
394 .map_err(|e| e.to_string())
395 .and_then(|sealed| sealed.validate(&carried))
396 .map_err(|reason| ValidationError::InvalidChecksMember { reason })?;
397 }
398
399 Ok(ArchiveEntries {
400 config_bytes,
401 markdown_files,
402 schema_files,
403 provenance_bytes,
404 anchors_bytes,
405 checks_bytes,
406 proposals_bytes,
407 })
408}
409
410fn is_schema_path(path: &str) -> bool {
417 let Some(rest) = path.strip_prefix(ARCHIVE_SCHEMA_PREFIX) else {
418 return false;
419 };
420 if rest == "schema.yaml" {
421 return true;
422 }
423 if rest == memstead_schema::loader::SCHEMA_FORMAT_MARKER_FILE {
426 return true;
427 }
428 let Some(rest) = rest.strip_prefix("types/") else {
429 return false;
430 };
431 if !rest.ends_with(".yaml") {
432 return false;
433 }
434 let stem = &rest[..rest.len() - ".yaml".len()];
435 !stem.is_empty() && !stem.contains('/')
436}
437
438#[cfg(test)]
439mod tests {
440 use super::*;
441 use std::io::Write;
442 use zip::write::SimpleFileOptions;
443
444 fn build_archive(entries: &[(&str, &[u8])]) -> Vec<u8> {
447 let mut buf = Vec::new();
448 {
449 let cursor = Cursor::new(&mut buf);
450 let mut w = zip::ZipWriter::new(cursor);
451 let options =
452 SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
453 for (name, content) in entries {
454 w.start_file(*name, options).unwrap();
455 w.write_all(content).unwrap();
456 }
457 w.finish().unwrap();
458 }
459 buf
460 }
461
462 fn ok_config() -> &'static [u8] {
463 br#"{"format":3,"name":"v","version":"0.1.0","schema":"default@1.0.0"}"#
464 }
465
466 #[test]
467 fn accepts_minimal_valid_archive() {
468 let zip = build_archive(&[
469 (".memstead/config.json", ok_config()),
470 ("foo.md", b"# Foo\n"),
471 ]);
472 let entries = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap();
473 assert_eq!(entries.markdown_files.len(), 1);
474 assert_eq!(entries.markdown_files[0].path, "foo.md");
475 assert!(entries.provenance_bytes.is_none());
478 }
479
480 #[test]
484 fn recognises_valid_anchors_member() {
485 let anchors = br#"{"version":1,"entities":{"v--foo":[{"artifact":"src/lib.rs","grain":"file","class":"anchored","hash_stability":"stable","hash":"h1"}]}}"#;
486 let zip = build_archive(&[
487 (".memstead/config.json", ok_config()),
488 (".memstead/anchors.json", anchors),
489 ("foo.md", b"# Foo\n"),
490 ]);
491 let entries = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap();
492 assert_eq!(
493 entries.anchors_bytes.as_deref(),
494 Some(&anchors[..]),
495 "anchors bytes surface verbatim"
496 );
497 assert_eq!(entries.markdown_files.len(), 1, "anchors is not an entity");
498 }
499
500 #[test]
504 fn rejects_malformed_anchors_member() {
505 let zip = build_archive(&[
506 (".memstead/config.json", ok_config()),
507 (".memstead/anchors.json", b"{ this is not valid json"),
508 ("foo.md", b"# Foo\n"),
509 ]);
510 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
511 assert!(
512 matches!(err, ValidationError::InvalidAnchorsMember { .. }),
513 "expected InvalidAnchorsMember, got {err:?}"
514 );
515 }
516
517 #[test]
522 fn rejects_empty_artifact_reference_in_anchors_member() {
523 let empty_ref = br#"{"version":1,"entities":{"v--foo":[{"artifact":"","grain":"file","class":"anchored","hash_stability":"stable"}]}}"#;
524 let zip = build_archive(&[
525 (".memstead/config.json", ok_config()),
526 (".memstead/anchors.json", empty_ref),
527 ("foo.md", b"# Foo\n"),
528 ]);
529 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
530 assert!(
531 matches!(err, ValidationError::InvalidAnchorsMember { .. }),
532 "expected InvalidAnchorsMember, got {err:?}"
533 );
534
535 let redacted = br#"{"version":1,"entities":{"v--foo":[{"artifact":"[redacted]","grain":"file","class":"anchored","hash_stability":"stable","hash":"h1"}]}}"#;
536 let zip = build_archive(&[
537 (".memstead/config.json", ok_config()),
538 (".memstead/anchors.json", redacted),
539 ("foo.md", b"# Foo\n"),
540 ]);
541 let entries = extract_entries(&zip, &ValidatorLimits::DEFAULT)
542 .expect("the pinned sentinel form is a valid member");
543 assert!(entries.anchors_bytes.is_some());
544 }
545
546 #[test]
553 fn recognises_and_repacks_the_proposals_member_and_refuses_a_malformed_one() {
554 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"}}}]}"#;
555 let archive = build_archive(&[
556 (".memstead/config.json", ok_config()),
557 (".memstead/proposals.json", record),
558 ("foo.md", b"# Foo\n"),
559 ]);
560 let entries = extract_entries(&archive, &ValidatorLimits::DEFAULT).unwrap();
561 assert_eq!(entries.proposals_bytes.as_deref(), Some(&record[..]));
562 assert_eq!(
563 entries.markdown_files.len(),
564 1,
565 "the member is not an entity"
566 );
567
568 let broken = build_archive(&[
569 (".memstead/config.json", ok_config()),
570 (".memstead/proposals.json", b"not a record"),
571 ("foo.md", b"# Foo\n"),
572 ]);
573 let err = extract_entries(&broken, &ValidatorLimits::DEFAULT).unwrap_err();
574 match &err {
575 ValidationError::InvalidProposalsMember { .. } => {}
576 other => panic!("expected InvalidProposalsMember, got {other:?}"),
577 }
578 assert!(
579 err.to_string().contains(".memstead/proposals.json"),
580 "{err}"
581 );
582
583 let config: memstead_schema::PublishedMemConfig =
585 serde_json::from_slice(ok_config()).unwrap();
586 let repacked = crate::validator::canonical::canonical_bytes(
587 &config,
588 &[],
589 &[],
590 None,
591 None,
592 None,
593 None,
594 Some(record),
595 )
596 .unwrap();
597 let mut zip = zip::ZipArchive::new(Cursor::new(repacked)).unwrap();
598 let mut member = zip
599 .by_name(".memstead/proposals.json")
600 .expect("member carried");
601 let mut bytes = Vec::new();
602 member.read_to_end(&mut bytes).unwrap();
603 assert_eq!(bytes, record);
604 }
605
606 fn checks_member(entity: &str, kind: &str, verdict: &str) -> Vec<u8> {
607 format!(
608 r#"{{"version":1,"entities":{{"{entity}":{{"{kind}":{{"ts":1,"verdict":"{verdict}","entity_hash":"h1","actor":"cli","role":"checker","identity":"checker-s1"}}}}}}}}"#
609 )
610 .into_bytes()
611 }
612
613 #[test]
616 fn recognises_valid_checks_member() {
617 let checks = checks_member("foo", "verification", "ok");
618 let archive = build_archive(&[
619 (".memstead/config.json", ok_config()),
620 (".memstead/checks.json", &checks),
621 ("foo.md", b"# Foo\n"),
622 ]);
623 let entries = extract_entries(&archive, &ValidatorLimits::DEFAULT).unwrap();
624 assert_eq!(
625 entries.checks_bytes.as_deref(),
626 Some(&checks[..]),
627 "checks bytes surface verbatim"
628 );
629 assert_eq!(entries.markdown_files.len(), 1, "checks is not an entity");
630
631 for kind in ["conformance", "x-audit"] {
633 let checks = checks_member("foo", kind, "failed");
634 let archive = build_archive(&[
635 (".memstead/config.json", ok_config()),
636 (".memstead/checks.json", &checks),
637 ("foo.md", b"# Foo\n"),
638 ]);
639 extract_entries(&archive, &ValidatorLimits::DEFAULT)
640 .unwrap_or_else(|e| panic!("kind {kind} is in the vocabulary: {e}"));
641 }
642 }
643
644 #[test]
652 fn rejects_malformed_checks_member() {
653 let refuse = |member: &[u8], expect: &str| {
654 let archive = build_archive(&[
655 (".memstead/config.json", ok_config()),
656 (".memstead/checks.json", member),
657 ("foo.md", b"# Foo\n"),
658 ]);
659 let err = extract_entries(&archive, &ValidatorLimits::DEFAULT).unwrap_err();
660 match &err {
661 ValidationError::InvalidChecksMember { reason } => {
662 assert!(reason.contains(expect), "expected `{expect}` in: {reason}");
663 }
664 other => panic!("expected InvalidChecksMember, got {other:?}"),
665 }
666 assert!(
667 err.to_string().contains(".memstead/checks.json"),
668 "the refusal names the member: {err}"
669 );
670 };
671 refuse(b"{ this is not valid json", "key must be a string");
672 refuse(&checks_member("foo", "audit", "ok"), "kind `audit`");
673 refuse(
674 &checks_member("foo", "verification", "maybe"),
675 "verdict `maybe`",
676 );
677 refuse(
678 &checks_member("bar", "verification", "ok"),
679 "entity `bar` names no entity the archive carries",
680 );
681 refuse(
682 br#"{"version":2,"entities":{}}"#,
683 "version 2 is not the version this engine reads",
684 );
685
686 let archive = build_archive(&[
688 (".memstead/config.json", ok_config()),
689 ("checks.json", &checks_member("foo", "verification", "ok")),
690 ("foo.md", b"# Foo\n"),
691 ]);
692 let err = extract_entries(&archive, &ValidatorLimits::DEFAULT).unwrap_err();
693 assert!(
694 matches!(err, ValidationError::UnknownFile(ref p) if p == "checks.json"),
695 "got {err:?}"
696 );
697 }
698
699 #[test]
704 fn recognises_provenance_member() {
705 let prov = br#"{"format":1,"history":"summarised","entities":{}}"#;
706 let zip = build_archive(&[
707 (".memstead/config.json", ok_config()),
708 (".memstead/provenance.json", prov),
709 ("foo.md", b"# Foo\n"),
710 ]);
711 let entries = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap();
712 assert_eq!(
713 entries.provenance_bytes.as_deref(),
714 Some(&prov[..]),
715 "provenance bytes surface verbatim"
716 );
717 assert_eq!(
718 entries.markdown_files.len(),
719 1,
720 "provenance is not an entity"
721 );
722 }
723
724 #[test]
732 fn tolerates_unknown_meta_member_but_rejects_unknown_root_member() {
733 let tolerated = build_archive(&[
734 (".memstead/config.json", ok_config()),
735 (".memstead/future-payload.json", br#"{"x":1}"#),
736 ("foo.md", b"# Foo\n"),
737 ]);
738 let entries = extract_entries(&tolerated, &ValidatorLimits::DEFAULT)
739 .expect("unknown meta member must be tolerated");
740 assert_eq!(entries.markdown_files.len(), 1);
741 assert!(
742 entries.provenance_bytes.is_none(),
743 "an unrecognised meta member is ignored, not surfaced as provenance"
744 );
745
746 let rejected = build_archive(&[
747 (".memstead/config.json", ok_config()),
748 ("stray.txt", b"not allowed at root"),
749 ("foo.md", b"# Foo\n"),
750 ]);
751 let err = extract_entries(&rejected, &ValidatorLimits::DEFAULT).unwrap_err();
752 assert!(
753 matches!(err, ValidationError::UnknownFile(ref p) if p == "stray.txt"),
754 "unknown non-meta member must still be rejected, got {err:?}"
755 );
756 }
757
758 #[test]
762 fn rejects_mixed_meta_dir_layout() {
763 let zip = build_archive(&[
764 (".memstead/config.json", ok_config()),
765 (".other/schema/schema.yaml", b"name: default\n"),
766 ("foo.md", b"# Foo\n"),
767 ]);
768 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
769 match err {
770 ValidationError::UnknownFile(path) => {
771 assert!(path.starts_with(".other/"), "path={path}");
772 }
773 other => panic!("expected UnknownFile for the foreign meta member, got {other:?}"),
774 }
775 }
776
777 #[test]
780 fn rejects_markdown_inside_meta_dir() {
781 let zip = build_archive(&[
782 (".memstead/config.json", ok_config()),
783 (".memstead/notes.md", b"# not an entity\n"),
784 ]);
785 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
786 assert!(
787 matches!(err, ValidationError::UnknownFile(_)),
788 "got {err:?}"
789 );
790 }
791
792 #[test]
793 fn markdown_files_are_sorted() {
794 let zip = build_archive(&[
795 (".memstead/config.json", ok_config()),
796 ("z.md", b"# Z\n"),
797 ("a.md", b"# A\n"),
798 ("m.md", b"# M\n"),
799 ]);
800 let entries = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap();
801 let paths: Vec<_> = entries
802 .markdown_files
803 .iter()
804 .map(|e| e.path.as_str())
805 .collect();
806 assert_eq!(paths, vec!["a.md", "m.md", "z.md"]);
807 }
808
809 #[test]
810 fn rejects_corrupt_zip() {
811 let err = extract_entries(b"not a zip at all", &ValidatorLimits::DEFAULT).unwrap_err();
812 assert!(matches!(err, ValidationError::Zip(_)));
813 }
814
815 #[test]
816 fn rejects_missing_config() {
817 let zip = build_archive(&[("foo.md", b"# Foo\n")]);
818 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
819 assert!(matches!(err, ValidationError::MissingConfig));
820 }
821
822 #[test]
823 fn rejects_non_markdown_non_config_file() {
824 let zip = build_archive(&[
825 (".memstead/config.json", ok_config()),
826 ("binary.exe", b"\x7fELF"),
827 ]);
828 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
829 match err {
830 ValidationError::UnknownFile(p) => assert_eq!(p, "binary.exe"),
831 other => panic!("expected UnknownFile, got {other:?}"),
832 }
833 }
834
835 #[test]
836 fn accepts_schema_package_entries() {
837 let zip = build_archive(&[
842 (".memstead/config.json", ok_config()),
843 ("foo.md", b"# Foo\n"),
844 (".memstead/schema/schema.yaml", b"name: default\n"),
845 (".memstead/schema/types/spec.yaml", b"name: spec\n"),
846 ]);
847 let entries = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap();
848 assert_eq!(entries.schema_files.len(), 2);
849 let paths: Vec<&str> = entries
850 .schema_files
851 .iter()
852 .map(|s| s.archive_path.as_str())
853 .collect();
854 assert_eq!(
855 paths,
856 vec![
857 ".memstead/schema/schema.yaml",
858 ".memstead/schema/types/spec.yaml"
859 ]
860 );
861 }
862
863 #[test]
867 fn accepts_schema_format_marker() {
868 let zip = build_archive(&[
869 (".memstead/config.json", ok_config()),
870 ("foo.md", b"# Foo\n"),
871 (".memstead/schema/schema.yaml", b"name: default\n"),
872 (
873 ".memstead/schema/schema-format.json",
874 b"{\"metadata_polarity\":\"required-opt-in\"}\n",
875 ),
876 ]);
877 let entries = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap();
878 assert!(
879 entries
880 .schema_files
881 .iter()
882 .any(|s| s.archive_path == ".memstead/schema/schema-format.json"),
883 "marker must ride in schema_files"
884 );
885 }
886
887 #[test]
888 fn rejects_unknown_schema_subpath() {
889 let zip = build_archive(&[
893 (".memstead/config.json", ok_config()),
894 (".memstead/schema/unexpected.json", b"{}"),
895 ]);
896 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
897 assert!(matches!(err, ValidationError::UnknownFile(_)));
898 }
899
900 #[test]
901 fn rejects_nested_schema_type_file() {
902 let zip = build_archive(&[
903 (".memstead/config.json", ok_config()),
904 (
905 ".memstead/schema/types/nested/subtype.yaml",
906 b"name: subtype\n",
907 ),
908 ]);
909 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
910 assert!(matches!(err, ValidationError::UnknownFile(_)));
911 }
912
913 #[test]
916 fn rejects_unknown_root_file() {
917 let zip = build_archive(&[
918 (".memstead/config.json", ok_config()),
919 (
920 "some-root.json",
921 br#"{"format":3,"name":"v","version":"0.1.0"}"#,
922 ),
923 ]);
924 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
925 assert!(
926 matches!(err, ValidationError::UnknownFile(ref p) if p == "some-root.json"),
927 "unknown root file must be rejected as UnknownFile, got {err:?}"
928 );
929 }
930
931 #[test]
932 fn rejects_zip_slip() {
933 let zip = build_archive(&[
934 (".memstead/config.json", ok_config()),
935 ("../escape.md", b"# Escape\n"),
936 ]);
937 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
938 assert!(matches!(err, ValidationError::Zip(_)));
939 }
940
941 #[test]
942 fn rejects_nested_zip_slip() {
943 let zip = build_archive(&[
944 (".memstead/config.json", ok_config()),
945 ("subdir/../../escape.md", b"# Escape\n"),
946 ]);
947 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
948 assert!(matches!(err, ValidationError::Zip(_)));
949 }
950
951 fn crc32(data: &[u8]) -> u32 {
959 let mut crc = !0u32;
960 for &b in data {
961 crc ^= b as u32;
962 for _ in 0..8 {
963 let mask = (crc & 1).wrapping_neg();
964 crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
965 }
966 }
967 !crc
968 }
969
970 fn raw_zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
975 let mut out: Vec<u8> = Vec::new();
976 let mut central: Vec<u8> = Vec::new();
977 let mut count: u16 = 0;
978
979 for (name, content) in entries {
980 let name_bytes = name.as_bytes();
981 let crc = crc32(content);
982 let size = content.len() as u32;
983 let offset = out.len() as u32;
984
985 out.extend_from_slice(&[0x50, 0x4b, 0x03, 0x04]);
987 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());
993 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());
996 out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(name_bytes);
998 out.extend_from_slice(content);
999
1000 central.extend_from_slice(&[0x50, 0x4b, 0x01, 0x02]);
1002 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());
1009 central.extend_from_slice(&size.to_le_bytes());
1010 central.extend_from_slice(&size.to_le_bytes());
1011 central.extend_from_slice(&(name_bytes.len() as u16).to_le_bytes());
1012 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);
1019
1020 count += 1;
1021 }
1022
1023 let cd_offset = out.len() as u32;
1024 let cd_size = central.len() as u32;
1025 out.extend_from_slice(¢ral);
1026
1027 out.extend_from_slice(&[0x50, 0x4b, 0x05, 0x06]);
1029 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());
1034 out.extend_from_slice(&cd_offset.to_le_bytes());
1035 out.extend_from_slice(&0u16.to_le_bytes()); out
1038 }
1039
1040 #[test]
1049 fn rejects_absolute_path_entry() {
1050 let zip = raw_zip(&[
1051 (".memstead/config.json", ok_config()),
1052 ("/etc/passwd.md", b"# Escape\n"),
1053 ]);
1054 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
1055 match err {
1058 ValidationError::Zip(reason) => {
1059 assert!(
1060 reason.contains("unsafe entry path"),
1061 "unexpected reason: {reason}"
1062 );
1063 }
1064 other => panic!("expected Zip(unsafe entry), got {other:?}"),
1065 }
1066 }
1067
1068 #[test]
1069 fn rejects_windows_drive_letter_entry() {
1070 let zip = raw_zip(&[
1074 (".memstead/config.json", ok_config()),
1075 ("C:\\evil.md", b"# Escape\n"),
1076 ]);
1077 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
1078 assert!(matches!(err, ValidationError::Zip(_)));
1079 }
1080
1081 #[test]
1082 fn rejects_symlink_entry() {
1083 let mut buf: Vec<u8> = Vec::new();
1089 {
1090 let cursor = Cursor::new(&mut buf);
1091 let mut w = zip::ZipWriter::new(cursor);
1092 w.start_file(".memstead/config.json", SimpleFileOptions::default())
1093 .unwrap();
1094 w.write_all(ok_config()).unwrap();
1095 w.add_symlink("link.md", "target.md", SimpleFileOptions::default())
1096 .unwrap();
1097 w.finish().unwrap();
1098 }
1099 let err = extract_entries(&buf, &ValidatorLimits::DEFAULT).unwrap_err();
1100 match err {
1101 ValidationError::Symlink(name) => assert_eq!(name, "link.md"),
1102 other => panic!("expected Symlink, got {other:?}"),
1103 }
1104 }
1105
1106 #[test]
1107 fn rejects_compressed_archive_too_large() {
1108 let mut limits = ValidatorLimits::DEFAULT;
1109 limits.max_compressed_archive = 64;
1110 let zip = build_archive(&[
1111 (".memstead/config.json", ok_config()),
1112 ("foo.md", b"# Foo\n"),
1113 ]);
1114 let err = extract_entries(&zip, &limits).unwrap_err();
1115 assert!(matches!(
1116 err,
1117 ValidationError::SizeCapExceeded {
1118 kind: SizeCapKind::CompressedArchive,
1119 ..
1120 }
1121 ));
1122 }
1123
1124 #[test]
1125 fn rejects_single_entry_too_large() {
1126 let mut limits = ValidatorLimits::DEFAULT;
1127 limits.max_uncompressed_entry = 10;
1128 let zip = build_archive(&[
1129 (".memstead/config.json", ok_config()),
1130 ("big.md", &[b'x'; 100]),
1131 ]);
1132 let err = extract_entries(&zip, &limits).unwrap_err();
1133 assert!(matches!(
1134 err,
1135 ValidationError::SizeCapExceeded {
1136 kind: SizeCapKind::UncompressedEntry,
1137 ..
1138 }
1139 ));
1140 }
1141
1142 #[test]
1143 fn rejects_config_file_too_large() {
1144 let mut limits = ValidatorLimits::DEFAULT;
1145 limits.max_config_file = 10;
1146 let zip = build_archive(&[
1147 (".memstead/config.json", &[b'x'; 50]),
1148 ("foo.md", b"# Foo\n"),
1149 ]);
1150 let err = extract_entries(&zip, &limits).unwrap_err();
1151 assert!(matches!(
1152 err,
1153 ValidationError::SizeCapExceeded {
1154 kind: SizeCapKind::ConfigFile,
1155 ..
1156 }
1157 ));
1158 }
1159
1160 #[test]
1161 fn rejects_uncompressed_sum_too_large() {
1162 let mut limits = ValidatorLimits::DEFAULT;
1163 limits.max_uncompressed_archive = 30;
1164 let zip = build_archive(&[
1165 (".memstead/config.json", ok_config()),
1166 ("a.md", &[b'x'; 20]),
1167 ("b.md", &[b'x'; 20]),
1168 ]);
1169 let err = extract_entries(&zip, &limits).unwrap_err();
1170 assert!(matches!(
1171 err,
1172 ValidationError::SizeCapExceeded {
1173 kind: SizeCapKind::UncompressedArchive,
1174 ..
1175 }
1176 ));
1177 }
1178
1179 #[test]
1180 fn rejects_entry_count_too_large() {
1181 let mut limits = ValidatorLimits::DEFAULT;
1182 limits.max_file_count = 2;
1183 let zip = build_archive(&[
1184 (".memstead/config.json", ok_config()),
1185 ("a.md", b"# A\n"),
1186 ("b.md", b"# B\n"),
1187 ]);
1188 let err = extract_entries(&zip, &limits).unwrap_err();
1189 assert!(matches!(
1190 err,
1191 ValidationError::SizeCapExceeded {
1192 kind: SizeCapKind::EntryCount,
1193 ..
1194 }
1195 ));
1196 }
1197
1198 #[test]
1199 fn rejects_path_too_long() {
1200 let mut limits = ValidatorLimits::DEFAULT;
1201 limits.max_path_length = 10;
1202 let long_name = format!("{}.md", "a".repeat(20));
1203 let zip = build_archive(&[
1204 (".memstead/config.json", ok_config()),
1205 (long_name.as_str(), b"# x\n"),
1206 ]);
1207 let err = extract_entries(&zip, &limits).unwrap_err();
1208 assert!(matches!(err, ValidationError::PathTooLong { .. }));
1209 }
1210
1211 #[test]
1212 fn rejects_path_too_deep() {
1213 let mut limits = ValidatorLimits::DEFAULT;
1214 limits.max_path_depth = 2;
1215 let zip = build_archive(&[
1216 (".memstead/config.json", ok_config()),
1217 ("a/b/c/d.md", b"# x\n"),
1218 ]);
1219 let err = extract_entries(&zip, &limits).unwrap_err();
1220 assert!(matches!(err, ValidationError::PathTooDeep { .. }));
1221 }
1222
1223 #[test]
1224 fn rejects_non_utf8_markdown_content() {
1225 let zip = build_archive(&[
1226 (".memstead/config.json", ok_config()),
1227 ("bad.md", &[0xff, 0xfe, 0xff]),
1228 ]);
1229 let err = extract_entries(&zip, &ValidatorLimits::DEFAULT).unwrap_err();
1230 assert!(matches!(err, ValidationError::Utf8 { .. }));
1231 }
1232}