Skip to main content

memstead_base/validator/
archive.rs

1//! Archive-level checks over raw zip bytes.
2//!
3//! Single pass: walks every entry once, enforces safety + caps + the
4//! file-type whitelist, yields entries to downstream modules. Returns
5//! the config-file bytes separately from the markdown entries because
6//! downstream dispatch differs — config goes to `validator::config`,
7//! markdown goes to `validator::strict` + `parse_markdown`.
8
9use 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/// One markdown file extracted from the archive. `content` is the raw
19/// UTF-8 body; BOM stripping is deferred to the strict checker so the
20/// raw bytes for offset reporting stay truthful.
21#[derive(Debug)]
22pub struct MarkdownEntry {
23    pub path: String,
24    pub content: String,
25}
26
27/// One schema-source file extracted from the archive's
28/// `.memstead/schema/` tree.
29///
30/// `archive_path` is relative to the archive root — e.g.
31/// `".memstead/schema/schema.yaml"` or `".memstead/schema/types/spec.yaml"`.
32/// Carried as `String` so the canonical re-pack and the install-time
33/// staging side effect can write identical bytes back out (CRLF → LF
34/// normalization is applied at extract time so re-validation over
35/// `canonical_bytes` is a fixpoint).
36#[derive(Debug)]
37pub struct SchemaFile {
38    pub archive_path: String,
39    pub content: String,
40}
41
42/// Re-key an archive's schema tree to the package-relative shape every
43/// sealed schema surface speaks (`schema.yaml`, `types/<t>.yaml`,
44/// `schema-format.json`) — the form
45/// [`memstead_schema::load_sealed_package`] reads and the form the
46/// local schema source is written in. Files outside the
47/// `.memstead/schema/` tree cannot appear here (the extractor filters
48/// them), so the strip is total in practice; anything unprefixed is
49/// passed through unchanged rather than silently dropped.
50pub 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    /// Raw bytes of the optional authoring-provenance payload
69    /// (`.memstead/provenance.json`), or `None` when the archive carries
70    /// none. Additive: a provenance-free archive yields `None`, and an
71    /// unrecognised future meta member is tolerated-and-ignored (never
72    /// surfaced here, never an error).
73    pub provenance_bytes: Option<Vec<u8>>,
74    /// Raw bytes of the optional engine-owned anchors sidecar
75    /// (`.memstead/anchors.json`), or `None` when the archive carries
76    /// none. Recognised as a first-class member so the canonical re-pack
77    /// threads it through verbatim rather than dropping it; a
78    /// recognised-but-structurally-invalid payload is a typed validation
79    /// failure (unlike unknown future meta members, which stay
80    /// tolerate-and-ignore).
81    pub anchors_bytes: Option<Vec<u8>>,
82    /// Raw bytes of the optional sealed check-records member
83    /// (`.memstead/checks.json`), or `None` when the archive carries
84    /// none (an archive sealed with no check record, or by an engine
85    /// before the member existed). Strict like the anchors member: a
86    /// recognised member that is not the declared shape, names a kind
87    /// outside the vocabulary or an entity the archive does not carry
88    /// is a typed validation failure; threaded verbatim through the
89    /// canonical re-pack on success.
90    pub checks_bytes: Option<Vec<u8>>,
91    /// Raw bytes of the optional proposal record
92    /// (`.memstead/proposals.json`), or `None` when the archive carries
93    /// none (a mem no proposal was merged into, or an archive sealed by
94    /// an engine before the member existed). Strict like the checks
95    /// member: a recognised member that does not parse as a record is
96    /// a typed validation failure naming the member; threaded verbatim
97    /// through the canonical re-pack on success. An engine older than
98    /// the member tolerates it as an unrecognised meta member.
99    pub proposals_bytes: Option<Vec<u8>>,
100}
101
102/// Walk the archive, enforce archive-level rules, return entries in
103/// sorted path order. Fails with a typed `ValidationError` on any
104/// violation. Performs no I/O; reads from the provided byte slice.
105pub 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        // zip 9 decodes the entry name fallibly: a name the crate cannot
149        // read is refused with the entry index, never validated under a
150        // guessed spelling.
151        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        // `enclosed_name()` normalizes absolute POSIX paths (`/foo`) and
161        // Windows drive-letter prefixes (`C:\foo`) by stripping them
162        // into innocent-looking relative paths, which masks adversarial
163        // intent. Catch those shapes on the raw name first so the
164        // rejection carries the original, truthful path.
165        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        // `.md` files inside the meta dir are NOT entities — without
214        // this guard a `.memstead/notes.md` would slip past the
215        // whitelist as markdown.
216        let is_markdown =
217            path_string.ends_with(".md") && !path_string.starts_with(&meta_dir_prefix);
218        // Forward-compat: a *top-level* member under the engine-owned
219        // `.memstead/` meta dir that none of the recognised kinds claim is
220        // an additive payload a newer writer added (the next
221        // `provenance.json`-shaped file). Tolerate-and-ignore it (still
222        // size-cap-enforced below, then discarded) so a future-meta-bearing
223        // archive installs without error on an engine that does not
224        // recognise the member. Inert: never loaded or served.
225        //
226        // Deliberately narrow — the existing strict boundaries stay:
227        // a `.md` file inside the meta dir is still rejected (it must not
228        // slip past as a non-entity), and the `.memstead/schema/` subtree
229        // stays strict (an ill-formed schema member is rejected, not
230        // silently ignored, so archives can't smuggle payloads under the
231        // schema prefix). Future additive payloads live as new top-level
232        // meta files, not under the schema subtree. Members OUTSIDE the
233        // meta dir are still rejected.
234        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        // An unrecognised meta member has now passed the size caps; drop
292        // it (forward-compat tolerate-and-ignore) without surfacing it.
293        if is_ignored_meta {
294            continue;
295        }
296
297        if is_config {
298            config_bytes = Some(buf);
299        } else if is_provenance {
300            // Raw bytes surfaced for the caller to parse into
301            // `ArchiveProvenance`; the validator does not interpret the
302            // payload (a malformed payload is the install path's call to
303            // downgrade to "provenance absent", not an archive-shape error).
304            provenance_bytes = Some(buf);
305        } else if is_anchors {
306            // Strict, unlike provenance: a recognised anchors member that
307            // does not parse as an `AnchorSidecar` is corruption, not
308            // forward-compat — silently dropping it is exactly the
309            // publish-strip failure the anchors member exists to close. Validate the
310            // structure here; thread the verbatim bytes through the
311            // canonical re-pack on success.
312            let sidecar = crate::anchor::AnchorSidecar::from_bytes(&buf).map_err(|e| {
313                ValidationError::InvalidAnchorsMember {
314                    reason: e.to_string(),
315                }
316            })?;
317            // An empty artifact reference is corruption the mutation
318            // surface never admits — including a botched publish-time
319            // redaction that blanked to nothing instead of the pinned
320            // sentinel. Caught here rather than shipped.
321            sidecar
322                .validate_artifact_references()
323                .map_err(|reason| ValidationError::InvalidAnchorsMember { reason })?;
324            anchors_bytes = Some(buf);
325        } else if is_checks {
326            // Strict like the anchors member: the shape and the vocabulary
327            // are checked here; the entity roster is checked once every
328            // entity path is known, below. Silently dropping a malformed
329            // member would read as "never checked", the one false answer
330            // the member exists to make impossible.
331            // The shape refuses here; the vocabulary and the entity
332            // roster are checked after the walk, once every entity path
333            // is known (zip order is not entity-first).
334            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            // Strict like the checks member: a record that does not parse
342            // would otherwise read as "no proposal was ever rejected", the
343            // one false answer the record exists to make impossible.
344            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            // Normalize CRLF → LF so every downstream pass (strict
361            // checker, parse_markdown, generate_markdown, canonical
362            // re-pack) sees the same bytes regardless of the
363            // publisher's editor. Without this, two semantically
364            // identical archives produce different canonical_bytes.
365            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    // The sealed check records: version, kind and verdict vocabulary,
386    // and the entity roster. A record naming an entity the archive does
387    // not carry is corruption, not a record that could be "stale".
388    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
410/// Recognize the archive-side layout of an embedded schema package:
411/// the manifest (`.memstead/schema/schema.yaml`) and per-type files
412/// (`.memstead/schema/types/<stem>.yaml`). Matching the loader's
413/// on-disk layout keeps embed + extract symmetric — anything outside
414/// this shape is rejected as an unknown file so archives can't smuggle
415/// arbitrary payloads past the whitelist under a schema prefix.
416fn 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    // The sealed format marker rides with the package so a published
424    // archive keeps its metadata-polarity generation.
425    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    /// Minimal archive builder for tests. Writes a DEFLATE-compressed
445    /// zip with the given entries to a Vec<u8>.
446    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        // A provenance-free archive surfaces no provenance — absent, not
476        // an error.
477        assert!(entries.provenance_bytes.is_none());
478    }
479
480    /// The engine-owned anchors sidecar (`.memstead/anchors.json`) is a
481    /// recognised member surfaced verbatim — not stripped as an unknown
482    /// meta member, not mistaken for an entity.
483    #[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    /// A recognised-but-structurally-invalid anchors member is a typed
501    /// failure — silent drop is exactly the publish-strip failure this
502    /// closes. (Unknown OTHER meta members keep tolerate-and-ignore.)
503    #[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    /// An anchors member with an EMPTY artifact reference refuses — the
518    /// mutation surface never admits one, so it is corruption: notably a
519    /// botched publish-time redaction that blanked to nothing instead of
520    /// the pinned sentinel. The sentinel form itself validates.
521    #[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    /// The proposal record (`.memstead/proposals.json`)
547    /// is a recognised strict meta member: surfaced verbatim, never an
548    /// entity, refused naming the member when it does not parse, and
549    /// carried through the canonical re-pack. An engine older than the
550    /// member sees an unrecognised `.memstead/` file, which it tolerates
551    /// and ignores (the rule `unknown_meta_member_is_tolerated` pins).
552    #[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        // The canonical re-pack carries the member verbatim.
584        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    /// The sealed check-records member (`.memstead/checks.json`) is a
614    /// recognised strict meta member: surfaced verbatim, not an entity.
615    #[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        // Every kind spelling the vocabulary admits, foreign included.
632        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    /// Complement: a malformed member refuses with the typed code
645    /// naming the member and the first offending record: not the
646    /// declared shape, an unknown kind spelling, an unknown verdict, a
647    /// record naming an entity the archive does not carry, a version
648    /// this engine does not read. (Unknown OTHER meta members keep
649    /// tolerate-and-ignore; a `checks.json` outside the meta dir is an
650    /// unknown root member as before.)
651    #[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        // Outside the meta dir: an unknown root member, as before.
687        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    /// The optional `.memstead/provenance.json` payload is recognised and
700    /// surfaced verbatim on `ArchiveEntries` — not rejected as an unknown
701    /// file, not mistaken for a markdown entity (it lives under the meta
702    /// dir).
703    #[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    /// Forward-compat: an unrecognised member under the engine-owned
725    /// `.memstead/` meta dir (a payload a newer writer added) is tolerated
726    /// and ignored — the archive still extracts cleanly, so a future-meta-
727    /// bearing archive installs without error on an engine that does not
728    /// know the member. This is the additive contract the provenance
729    /// payload relies on. An unknown member OUTSIDE the meta dir is still
730    /// rejected.
731    #[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    /// A meta member under a foreign (non-`.memstead/`) dir alongside a
759    /// current `.memstead/` config is rejected — it falls outside the
760    /// whitelist. Guards that only `.memstead/` is the tolerated layout.
761    #[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    /// `.md` files inside the meta dir are engine-internal, not
778    /// entities — they must not pass the whitelist as markdown.
779    #[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        // The whitelist must admit the two shapes `export_mem` embeds:
838        // the manifest at `.memstead/schema/schema.yaml` and per-type YAMLs
839        // under `.memstead/schema/types/`. Anything else under
840        // `.memstead/schema/` is still an unknown file (asserted separately).
841        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    /// The sealed format marker rides the archive: it is admitted by
864    /// the whitelist and lands in `schema_files` so the loaders can
865    /// honor the package's metadata-polarity generation.
866    #[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        // Anything under `.memstead/schema/` that isn't the manifest or a
890        // type file must still be rejected — otherwise archives could
891        // smuggle arbitrary payloads behind the whitelist.
892        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    /// An unknown root-level file (not part of the whitelist) is
914    /// rejected as an unknown file — no special-casing survives.
915    #[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    // Raw zip-bytes helpers below exercise rejection paths that the
952    // cooperative `ZipWriter` API normalizes away or refuses to emit:
953    // duplicate filenames, absolute paths, drive letters, symlinks.
954
955    /// Minimal CRC32/ISO-HDLC — zip expects this exact polynomial in
956    /// both the local file header and the central directory entry.
957    /// Inlined to avoid a dev-dependency just for the raw-zip helper.
958    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    /// Hand-crafts a stored-only (uncompressed) zip with arbitrary
971    /// entry names — including shapes that `ZipWriter` rejects or
972    /// rewrites. Produces a structurally valid archive the `zip` crate
973    /// can open; validator-level checks are the ones doing the rejecting.
974    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            // Local file header (PK\3\4)
986            out.extend_from_slice(&[0x50, 0x4b, 0x03, 0x04]);
987            out.extend_from_slice(&10u16.to_le_bytes()); // version needed
988            out.extend_from_slice(&0u16.to_le_bytes()); // flags
989            out.extend_from_slice(&0u16.to_le_bytes()); // stored
990            out.extend_from_slice(&0u16.to_le_bytes()); // mtime
991            out.extend_from_slice(&0u16.to_le_bytes()); // mdate
992            out.extend_from_slice(&crc.to_le_bytes());
993            out.extend_from_slice(&size.to_le_bytes()); // compressed
994            out.extend_from_slice(&size.to_le_bytes()); // uncompressed
995            out.extend_from_slice(&(name_bytes.len() as u16).to_le_bytes());
996            out.extend_from_slice(&0u16.to_le_bytes()); // extra length
997            out.extend_from_slice(name_bytes);
998            out.extend_from_slice(content);
999
1000            // Central directory file header (PK\1\2)
1001            central.extend_from_slice(&[0x50, 0x4b, 0x01, 0x02]);
1002            central.extend_from_slice(&20u16.to_le_bytes()); // version made by
1003            central.extend_from_slice(&10u16.to_le_bytes()); // version needed
1004            central.extend_from_slice(&0u16.to_le_bytes()); // flags
1005            central.extend_from_slice(&0u16.to_le_bytes()); // stored
1006            central.extend_from_slice(&0u16.to_le_bytes()); // mtime
1007            central.extend_from_slice(&0u16.to_le_bytes()); // mdate
1008            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()); // extra
1013            central.extend_from_slice(&0u16.to_le_bytes()); // comment
1014            central.extend_from_slice(&0u16.to_le_bytes()); // disk number
1015            central.extend_from_slice(&0u16.to_le_bytes()); // internal attrs
1016            central.extend_from_slice(&0u32.to_le_bytes()); // external attrs
1017            central.extend_from_slice(&offset.to_le_bytes()); // LFH offset
1018            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(&central);
1026
1027        // End of central directory (PK\5\6)
1028        out.extend_from_slice(&[0x50, 0x4b, 0x05, 0x06]);
1029        out.extend_from_slice(&0u16.to_le_bytes()); // disk number
1030        out.extend_from_slice(&0u16.to_le_bytes()); // disk with CD start
1031        out.extend_from_slice(&count.to_le_bytes()); // entries this disk
1032        out.extend_from_slice(&count.to_le_bytes()); // entries total
1033        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()); // comment length
1036
1037        out
1038    }
1039
1040    // Duplicate-entry path: verified empirically with `raw_zip` that
1041    // the zip 8 reader itself collapses duplicates during central-
1042    // directory parse (only the last entry survives, `archive.len()`
1043    // returns 1). The `seen_paths` guard in `extract_entries` is
1044    // therefore only reachable if a future zip-crate release preserves
1045    // duplicates — kept as defense-in-depth, cannot be exercised in a
1046    // unit test against current zip 8.x.
1047
1048    #[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        // `enclosed_name()` refuses absolute paths → validator maps to
1056        // `Zip` with the unsafe-entry reason.
1057        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        // Backslashes are allowed inside zip member names on Windows-
1071        // produced archives; `enclosed_name()` normalizes separators
1072        // and then refuses drive-prefixed absolute paths.
1073        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        // The cooperative writer exposes `add_symlink`, which is the
1084        // only path that sets the external-attributes bit the reader
1085        // interprets as `is_symlink() == true`. Defense-in-depth test
1086        // for the symlink rule: even if an adversary smuggles a symlink past the
1087        // whitelist, the structural check fires.
1088        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}