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        if entry.is_symlink() {
149            return Err(ValidationError::Symlink(entry.name().to_string()));
150        }
151
152        // `enclosed_name()` normalizes absolute POSIX paths (`/foo`) and
153        // Windows drive-letter prefixes (`C:\foo`) by stripping them
154        // into innocent-looking relative paths, which masks adversarial
155        // intent. Catch those shapes on the raw name first so the
156        // rejection carries the original, truthful path.
157        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        // `.md` files inside the meta dir are NOT entities — without
207        // this guard a `.memstead/notes.md` would slip past the
208        // whitelist as markdown.
209        let is_markdown =
210            path_string.ends_with(".md") && !path_string.starts_with(&meta_dir_prefix);
211        // Forward-compat: a *top-level* member under the engine-owned
212        // `.memstead/` meta dir that none of the recognised kinds claim is
213        // an additive payload a newer writer added (the next
214        // `provenance.json`-shaped file). Tolerate-and-ignore it (still
215        // size-cap-enforced below, then discarded) so a future-meta-bearing
216        // archive installs without error on an engine that does not
217        // recognise the member. Inert: never loaded or served.
218        //
219        // Deliberately narrow — the existing strict boundaries stay:
220        // a `.md` file inside the meta dir is still rejected (it must not
221        // slip past as a non-entity), and the `.memstead/schema/` subtree
222        // stays strict (an ill-formed schema member is rejected, not
223        // silently ignored, so archives can't smuggle payloads under the
224        // schema prefix). Future additive payloads live as new top-level
225        // meta files, not under the schema subtree. Members OUTSIDE the
226        // meta dir are still rejected.
227        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        // An unrecognised meta member has now passed the size caps; drop
285        // it (forward-compat tolerate-and-ignore) without surfacing it.
286        if is_ignored_meta {
287            continue;
288        }
289
290        if is_config {
291            config_bytes = Some(buf);
292        } else if is_provenance {
293            // Raw bytes surfaced for the caller to parse into
294            // `ArchiveProvenance`; the validator does not interpret the
295            // payload (a malformed payload is the install path's call to
296            // downgrade to "provenance absent", not an archive-shape error).
297            provenance_bytes = Some(buf);
298        } else if is_anchors {
299            // Strict, unlike provenance: a recognised anchors member that
300            // does not parse as an `AnchorSidecar` is corruption, not
301            // forward-compat — silently dropping it is exactly the
302            // publish-strip failure the anchors member exists to close. Validate the
303            // structure here; thread the verbatim bytes through the
304            // canonical re-pack on success.
305            let sidecar = crate::anchor::AnchorSidecar::from_bytes(&buf).map_err(|e| {
306                ValidationError::InvalidAnchorsMember {
307                    reason: e.to_string(),
308                }
309            })?;
310            // An empty artifact reference is corruption the mutation
311            // surface never admits — including a botched publish-time
312            // redaction that blanked to nothing instead of the pinned
313            // sentinel. Caught here rather than shipped.
314            sidecar
315                .validate_artifact_references()
316                .map_err(|reason| ValidationError::InvalidAnchorsMember { reason })?;
317            anchors_bytes = Some(buf);
318        } else if is_checks {
319            // Strict like the anchors member: the shape and the vocabulary
320            // are checked here; the entity roster is checked once every
321            // entity path is known, below. Silently dropping a malformed
322            // member would read as "never checked", the one false answer
323            // the member exists to make impossible.
324            // The shape refuses here; the vocabulary and the entity
325            // roster are checked after the walk, once every entity path
326            // is known (zip order is not entity-first).
327            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            // Strict like the checks member: a record that does not parse
335            // would otherwise read as "no proposal was ever rejected", the
336            // one false answer the record exists to make impossible.
337            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            // Normalize CRLF → LF so every downstream pass (strict
354            // checker, parse_markdown, generate_markdown, canonical
355            // re-pack) sees the same bytes regardless of the
356            // publisher's editor. Without this, two semantically
357            // identical archives produce different canonical_bytes.
358            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    // The sealed check records: version, kind and verdict vocabulary,
379    // and the entity roster. A record naming an entity the archive does
380    // not carry is corruption, not a record that could be "stale".
381    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
403/// Recognize the archive-side layout of an embedded schema package:
404/// the manifest (`.memstead/schema/schema.yaml`) and per-type files
405/// (`.memstead/schema/types/<stem>.yaml`). Matching the loader's
406/// on-disk layout keeps embed + extract symmetric — anything outside
407/// this shape is rejected as an unknown file so archives can't smuggle
408/// arbitrary payloads past the whitelist under a schema prefix.
409fn 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    // The sealed format marker rides with the package so a published
417    // archive keeps its metadata-polarity generation.
418    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    /// Minimal archive builder for tests. Writes a DEFLATE-compressed
438    /// zip with the given entries to a Vec<u8>.
439    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        // A provenance-free archive surfaces no provenance — absent, not
469        // an error.
470        assert!(entries.provenance_bytes.is_none());
471    }
472
473    /// The engine-owned anchors sidecar (`.memstead/anchors.json`) is a
474    /// recognised member surfaced verbatim — not stripped as an unknown
475    /// meta member, not mistaken for an entity.
476    #[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    /// A recognised-but-structurally-invalid anchors member is a typed
494    /// failure — silent drop is exactly the publish-strip failure this
495    /// closes. (Unknown OTHER meta members keep tolerate-and-ignore.)
496    #[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    /// An anchors member with an EMPTY artifact reference refuses — the
511    /// mutation surface never admits one, so it is corruption: notably a
512    /// botched publish-time redaction that blanked to nothing instead of
513    /// the pinned sentinel. The sentinel form itself validates.
514    #[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    /// Plan-proposal 03 (AC3): the proposal record (`.memstead/proposals.json`)
540    /// is a recognised strict meta member: surfaced verbatim, never an
541    /// entity, refused naming the member when it does not parse, and
542    /// carried through the canonical re-pack. An engine older than the
543    /// member sees an unrecognised `.memstead/` file, which it tolerates
544    /// and ignores (the rule `unknown_meta_member_is_tolerated` pins).
545    #[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        // The canonical re-pack carries the member verbatim.
577        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    /// AC2: the sealed check-records member (`.memstead/checks.json`) is a
607    /// recognised strict meta member: surfaced verbatim, not an entity.
608    #[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        // Every kind spelling the vocabulary admits, foreign included.
625        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    /// AC2 complement: a malformed member refuses with the typed code
638    /// naming the member and the first offending record: not the
639    /// declared shape, an unknown kind spelling, an unknown verdict, a
640    /// record naming an entity the archive does not carry, a version
641    /// this engine does not read. (Unknown OTHER meta members keep
642    /// tolerate-and-ignore; a `checks.json` outside the meta dir is an
643    /// unknown root member as before.)
644    #[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        // Outside the meta dir: an unknown root member, as before.
680        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    /// The optional `.memstead/provenance.json` payload is recognised and
693    /// surfaced verbatim on `ArchiveEntries` — not rejected as an unknown
694    /// file, not mistaken for a markdown entity (it lives under the meta
695    /// dir).
696    #[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    /// Forward-compat: an unrecognised member under the engine-owned
718    /// `.memstead/` meta dir (a payload a newer writer added) is tolerated
719    /// and ignored — the archive still extracts cleanly, so a future-meta-
720    /// bearing archive installs without error on an engine that does not
721    /// know the member. This is the additive contract the provenance
722    /// payload relies on. An unknown member OUTSIDE the meta dir is still
723    /// rejected.
724    #[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    /// A meta member under a foreign (non-`.memstead/`) dir alongside a
752    /// current `.memstead/` config is rejected — it falls outside the
753    /// whitelist. Guards that only `.memstead/` is the tolerated layout.
754    #[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    /// `.md` files inside the meta dir are engine-internal, not
771    /// entities — they must not pass the whitelist as markdown.
772    #[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        // The whitelist must admit the two shapes `export_mem` embeds:
831        // the manifest at `.memstead/schema/schema.yaml` and per-type YAMLs
832        // under `.memstead/schema/types/`. Anything else under
833        // `.memstead/schema/` is still an unknown file (asserted separately).
834        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    /// The sealed format marker rides the archive: it is admitted by
857    /// the whitelist and lands in `schema_files` so the loaders can
858    /// honor the package's metadata-polarity generation.
859    #[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        // Anything under `.memstead/schema/` that isn't the manifest or a
883        // type file must still be rejected — otherwise archives could
884        // smuggle arbitrary payloads behind the whitelist.
885        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    /// An unknown root-level file (not part of the whitelist) is
907    /// rejected as an unknown file — no special-casing survives.
908    #[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    // Raw zip-bytes helpers below exercise rejection paths that the
945    // cooperative `ZipWriter` API normalizes away or refuses to emit:
946    // duplicate filenames, absolute paths, drive letters, symlinks.
947
948    /// Minimal CRC32/ISO-HDLC — zip expects this exact polynomial in
949    /// both the local file header and the central directory entry.
950    /// Inlined to avoid a dev-dependency just for the raw-zip helper.
951    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    /// Hand-crafts a stored-only (uncompressed) zip with arbitrary
964    /// entry names — including shapes that `ZipWriter` rejects or
965    /// rewrites. Produces a structurally valid archive the `zip` crate
966    /// can open; validator-level checks are the ones doing the rejecting.
967    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            // Local file header (PK\3\4)
979            out.extend_from_slice(&[0x50, 0x4b, 0x03, 0x04]);
980            out.extend_from_slice(&10u16.to_le_bytes()); // version needed
981            out.extend_from_slice(&0u16.to_le_bytes()); // flags
982            out.extend_from_slice(&0u16.to_le_bytes()); // stored
983            out.extend_from_slice(&0u16.to_le_bytes()); // mtime
984            out.extend_from_slice(&0u16.to_le_bytes()); // mdate
985            out.extend_from_slice(&crc.to_le_bytes());
986            out.extend_from_slice(&size.to_le_bytes()); // compressed
987            out.extend_from_slice(&size.to_le_bytes()); // uncompressed
988            out.extend_from_slice(&(name_bytes.len() as u16).to_le_bytes());
989            out.extend_from_slice(&0u16.to_le_bytes()); // extra length
990            out.extend_from_slice(name_bytes);
991            out.extend_from_slice(content);
992
993            // Central directory file header (PK\1\2)
994            central.extend_from_slice(&[0x50, 0x4b, 0x01, 0x02]);
995            central.extend_from_slice(&20u16.to_le_bytes()); // version made by
996            central.extend_from_slice(&10u16.to_le_bytes()); // version needed
997            central.extend_from_slice(&0u16.to_le_bytes()); // flags
998            central.extend_from_slice(&0u16.to_le_bytes()); // stored
999            central.extend_from_slice(&0u16.to_le_bytes()); // mtime
1000            central.extend_from_slice(&0u16.to_le_bytes()); // mdate
1001            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()); // extra
1006            central.extend_from_slice(&0u16.to_le_bytes()); // comment
1007            central.extend_from_slice(&0u16.to_le_bytes()); // disk number
1008            central.extend_from_slice(&0u16.to_le_bytes()); // internal attrs
1009            central.extend_from_slice(&0u32.to_le_bytes()); // external attrs
1010            central.extend_from_slice(&offset.to_le_bytes()); // LFH offset
1011            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(&central);
1019
1020        // End of central directory (PK\5\6)
1021        out.extend_from_slice(&[0x50, 0x4b, 0x05, 0x06]);
1022        out.extend_from_slice(&0u16.to_le_bytes()); // disk number
1023        out.extend_from_slice(&0u16.to_le_bytes()); // disk with CD start
1024        out.extend_from_slice(&count.to_le_bytes()); // entries this disk
1025        out.extend_from_slice(&count.to_le_bytes()); // entries total
1026        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()); // comment length
1029
1030        out
1031    }
1032
1033    // Duplicate-entry path: verified empirically with `raw_zip` that
1034    // the zip 8 reader itself collapses duplicates during central-
1035    // directory parse (only the last entry survives, `archive.len()`
1036    // returns 1). The `seen_paths` guard in `extract_entries` is
1037    // therefore only reachable if a future zip-crate release preserves
1038    // duplicates — kept as defense-in-depth, cannot be exercised in a
1039    // unit test against current zip 8.x.
1040
1041    #[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        // `enclosed_name()` refuses absolute paths → validator maps to
1049        // `Zip` with the unsafe-entry reason.
1050        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        // Backslashes are allowed inside zip member names on Windows-
1064        // produced archives; `enclosed_name()` normalizes separators
1065        // and then refuses drive-prefixed absolute paths.
1066        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        // The cooperative writer exposes `add_symlink`, which is the
1077        // only path that sets the external-attributes bit the reader
1078        // interprets as `is_symlink() == true`. Defense-in-depth test
1079        // for R5: even if an adversary smuggles a symlink past the
1080        // whitelist, the structural check fires.
1081        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}