Skip to main content

memstead_base/entity/
source.rs

1//! Entity source abstraction — where markdown comes from.
2//!
3//! Two backend-agnostic shapes live here: a directory on disk (for
4//! live, writable workspaces) and a sealed `.mem` zip archive (for read-only
5//! attached mems). The git-tree shape lives in
6//! `memstead-git-branch::entity::git_tree_source`. All shapes feed the
7//! same parse pipeline via the helper [`crate::entity::loader::parse_entries`].
8
9use std::path::{Path, PathBuf};
10
11use super::loader::LoadError;
12use crate::validator::{BoundedZipRead, ValidatorLimits, read_zip_entry_bounded};
13
14/// A backend-agnostic source of markdown entities.
15pub enum EntitySource {
16    /// A directory on disk. Walked recursively; engine-internal
17    /// directories (`.git/`, `.memstead/`) are always skipped.
18    Directory { root: PathBuf },
19    /// A sealed `.mem` mem archive: a zip containing the same markdown
20    /// tree a `Directory` would. Read-only; loaded as a dep alongside
21    /// the primary mem. Zip-slip protected via `enclosed_name`.
22    ZipArchive(PathBuf),
23}
24
25/// One successfully-read markdown entry produced by an `EntitySource`.
26#[derive(Debug, Clone)]
27pub struct SourceEntry {
28    /// Path relative to the source root. Used as `Entity.file_path`.
29    /// Uses the platform's native separator for `Directory`; will use
30    /// POSIX separators for `ZipArchive` when that variant lands.
31    pub relative_path: String,
32    /// Source-specific path for error reporting — absolute on disk,
33    /// archive-relative for zips. Opaque to the parser; kept so callers
34    /// can surface a human-useful location in error messages without
35    /// re-joining paths.
36    pub source_path: PathBuf,
37    /// Raw file contents.
38    pub content: String,
39}
40
41/// A per-file read failure. Non-fatal: the walker continues past these
42/// and hands them back to the caller alongside the successful entries,
43/// preserving the loader's "collect errors, don't stop" behavior.
44#[derive(Debug)]
45pub struct SourceReadError {
46    pub source_path: PathBuf,
47    pub error: std::io::Error,
48}
49
50impl EntitySource {
51    /// Read every `.md` entry from this source. Returns the successful
52    /// entries and any per-file read errors.
53    ///
54    /// Source-level failures (missing directory, unreadable directory
55    /// listing) surface as `Err(LoadError::…)`. Individual file read
56    /// failures go into the `SourceReadError` bucket.
57    pub fn read_all(&self) -> Result<(Vec<SourceEntry>, Vec<SourceReadError>), LoadError> {
58        match self {
59            EntitySource::Directory { root } => read_directory(root),
60            EntitySource::ZipArchive(archive) => read_zip_archive(archive),
61        }
62    }
63}
64
65fn read_directory(root: &Path) -> Result<(Vec<SourceEntry>, Vec<SourceReadError>), LoadError> {
66    if !root.exists() {
67        return Err(LoadError::DirNotFound(root.display().to_string()));
68    }
69    // A folder mem whose last commit was cut off is not read, here as
70    // on the backend's own reads: this walk goes to the directory
71    // directly (a publish, a conflict scan) and would otherwise serve
72    // part of that commit. An engine load completes it.
73    crate::storage::filesystem::refuse_cut_off_commit(root)
74        .map_err(|e| LoadError::Io(std::io::Error::other(e.to_string())))?;
75
76    let mut files = Vec::new();
77    find_markdown_files(root, &mut files)?;
78    files.sort();
79
80    let mut entries = Vec::with_capacity(files.len());
81    let mut errors = Vec::new();
82
83    for file in &files {
84        match std::fs::read_to_string(file) {
85            Ok(content) => {
86                let relative_path = file
87                    .strip_prefix(root)
88                    .unwrap_or(file)
89                    .to_string_lossy()
90                    .to_string();
91                entries.push(SourceEntry {
92                    relative_path,
93                    source_path: file.clone(),
94                    content,
95                });
96            }
97            Err(error) => errors.push(SourceReadError {
98                source_path: file.clone(),
99                error,
100            }),
101        }
102    }
103
104    Ok((entries, errors))
105}
106
107fn read_zip_archive(
108    archive_path: &Path,
109) -> Result<(Vec<SourceEntry>, Vec<SourceReadError>), LoadError> {
110    if !archive_path.is_file() {
111        return Err(LoadError::ArchiveNotFound(
112            archive_path.display().to_string(),
113        ));
114    }
115
116    let file = std::fs::File::open(archive_path)?;
117    let mut archive = zip::ZipArchive::new(file)?;
118
119    let limits = ValidatorLimits::DEFAULT;
120    if archive.len() as u32 > limits.max_file_count {
121        return Err(LoadError::InvalidArchive(format!(
122            "archive contains {} entries, exceeding the {}-entry cap",
123            archive.len(),
124            limits.max_file_count
125        )));
126    }
127
128    let mut entries = Vec::new();
129    let mut errors = Vec::new();
130    let mut uncompressed_total: u64 = 0;
131
132    for i in 0..archive.len() {
133        let mut entry = archive.by_index(i)?;
134        // zip 9 decodes the entry name fallibly; a name the crate
135        // cannot read is refused with the entry index, as the other
136        // shape refusals are, never served under a guessed spelling.
137        let raw_name = entry
138            .name()
139            .map_err(|e| LoadError::InvalidArchive(format!("entry {i}: undecodable name: {e}")))?
140            .into_owned();
141
142        // Symlinks are rejected outright — a malicious archive could
143        // point one at /etc/passwd or any other absolute path. We never
144        // extract, but we also never want to surface their content.
145        if entry.is_symlink() {
146            return Err(LoadError::InvalidArchive(format!(
147                "entry '{raw_name}': symlinks are not allowed in sealed mem archives"
148            )));
149        }
150
151        // `enclosed_name` is the zip crate's blessed zip-slip guard:
152        // returns `Some(path)` only if the entry name is safe (relative,
153        // no `..` escape, no absolute prefix, no drive letters). `None`
154        // means the archive is trying to write outside its own root.
155        let safe_path = match entry.enclosed_name() {
156            Some(p) => p,
157            None => {
158                return Err(LoadError::InvalidArchive(format!(
159                    "entry '{raw_name}': path escapes archive root \
160                     (absolute, '..'-components, or otherwise unsafe)"
161                )));
162            }
163        };
164
165        if entry.is_dir() {
166            continue;
167        }
168
169        let relative_path = safe_path.to_string_lossy().to_string();
170        if !relative_path.ends_with(".md") {
171            // Non-markdown entries (including the meta-dir config) are
172            // silently skipped here. The entity source only yields
173            // entity content; mem metadata is read by
174            // `mem_cache::read_published_config` on a separate pass.
175            continue;
176        }
177
178        // Bounded read: decompression is never sized by the entry's
179        // declared header, and a bomb refuses with a typed error —
180        // the same caps the ingress validator enforces.
181        let bytes = match read_zip_entry_bounded(&mut entry, limits.max_uncompressed_entry)? {
182            BoundedZipRead::Within(bytes) => bytes,
183            BoundedZipRead::ExceedsCap => {
184                return Err(LoadError::InvalidArchive(format!(
185                    "entry '{relative_path}' exceeds the {}-byte uncompressed cap",
186                    limits.max_uncompressed_entry
187                )));
188            }
189        };
190        uncompressed_total = uncompressed_total.saturating_add(bytes.len() as u64);
191        if uncompressed_total > limits.max_uncompressed_archive {
192            return Err(LoadError::InvalidArchive(format!(
193                "archive exceeds the {}-byte total uncompressed cap",
194                limits.max_uncompressed_archive
195            )));
196        }
197        match String::from_utf8(bytes) {
198            Ok(content) => entries.push(SourceEntry {
199                relative_path: relative_path.clone(),
200                source_path: PathBuf::from(&relative_path),
201                content,
202            }),
203            Err(error) => errors.push(SourceReadError {
204                source_path: PathBuf::from(&relative_path),
205                error: std::io::Error::new(std::io::ErrorKind::InvalidData, error),
206            }),
207        }
208    }
209
210    // Sort for deterministic ordering — the zip crate yields entries in
211    // archive order, which our deterministic-export contract already
212    // sorts by path, but external archives may not.
213    entries.sort_by(|a, b| a.relative_path.cmp(&b.relative_path));
214
215    Ok((entries, errors))
216}
217
218/// Recursively find all .md files under a directory.
219///
220/// Skip rules:
221/// - `.git/` — external git metadata, never entity territory.
222/// - `.memstead/` — engine-internal (config, schemas cache). Always
223///   hidden at every depth.
224/// - `README.md` — repository documentation, never an entity. A
225///   folder mem living visibly in a repo tree carries a human-facing
226///   README beside its entity files (quickstart already tolerates
227///   README-grade files at init; the load side matches). Entities are
228///   slug-named after their titles, so no legitimate entity file
229///   carries this name.
230///
231/// All other directories (including unrelated dot-prefixed dirs like
232/// `.obsidian/`, `.idea/`) are walked.
233fn find_markdown_files(dir: &Path, files: &mut Vec<PathBuf>) -> Result<(), LoadError> {
234    let entries = std::fs::read_dir(dir)?;
235
236    for entry in entries {
237        let entry = entry?;
238        let path = entry.path();
239        let file_name = entry.file_name();
240        let name = file_name.to_string_lossy();
241
242        if path.is_dir() {
243            if name.as_ref() == ".git" || name.as_ref() == crate::mem::MEM_META_DIR {
244                continue;
245            }
246            // A subdirectory with its own mem config is another mem: its
247            // entities are its own, never this mem's under a second id.
248            if crate::mem::is_nested_mem_root(&path) {
249                continue;
250            }
251            find_markdown_files(&path, files)?;
252        } else if name.ends_with(".md") && name.as_ref() != "README.md" {
253            files.push(path);
254        }
255    }
256
257    Ok(())
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use std::fs;
264    use tempfile::TempDir;
265
266    #[test]
267    fn directory_reads_markdown_in_sorted_order() {
268        let dir = TempDir::new().unwrap();
269        fs::write(dir.path().join("b.md"), "b").unwrap();
270        fs::write(dir.path().join("a.md"), "a").unwrap();
271
272        let (entries, errors) = EntitySource::Directory {
273            root: dir.path().to_path_buf(),
274        }
275        .read_all()
276        .unwrap();
277        assert!(errors.is_empty());
278        let paths: Vec<_> = entries.iter().map(|e| e.relative_path.as_str()).collect();
279        assert_eq!(paths, vec!["a.md", "b.md"]);
280    }
281
282    #[test]
283    fn directory_skips_engine_internal_dirs_and_non_md() {
284        // `.git/` and `.memstead/` are always skipped (engine-internal).
285        // Other dot-prefixed dirs (e.g. `.obsidian/`) walk normally.
286        let dir = TempDir::new().unwrap();
287        fs::write(dir.path().join("keep.md"), "k").unwrap();
288        fs::write(dir.path().join("ignore.txt"), "i").unwrap();
289        // README.md is repo documentation beside the entity files —
290        // never loaded as an entity.
291        fs::write(dir.path().join("README.md"), "docs").unwrap();
292        fs::create_dir_all(dir.path().join(".git")).unwrap();
293        fs::write(dir.path().join(".git/secret.md"), "s").unwrap();
294        fs::create_dir_all(dir.path().join(".memstead")).unwrap();
295        fs::write(dir.path().join(".memstead/note.md"), "n").unwrap();
296        fs::create_dir_all(dir.path().join(".obsidian")).unwrap();
297        fs::write(dir.path().join(".obsidian/vis.md"), "v").unwrap();
298
299        let (entries, _) = EntitySource::Directory {
300            root: dir.path().to_path_buf(),
301        }
302        .read_all()
303        .unwrap();
304        let paths: Vec<_> = entries.iter().map(|e| e.relative_path.as_str()).collect();
305        assert!(paths.contains(&"keep.md"), "keep.md must load: {paths:?}");
306        assert!(
307            paths.iter().any(|p| p.ends_with("vis.md")),
308            ".obsidian/vis.md must load: {paths:?}"
309        );
310        assert!(
311            !paths.iter().any(|p| p.contains(".git")),
312            ".git/* must be skipped: {paths:?}"
313        );
314        assert!(
315            !paths.iter().any(|p| p.contains(".memstead")),
316            ".memstead/* must be skipped: {paths:?}"
317        );
318    }
319
320    #[test]
321    fn directory_missing_root_returns_error() {
322        let err = EntitySource::Directory {
323            root: PathBuf::from("/nonexistent/path/xyz"),
324        }
325        .read_all()
326        .unwrap_err();
327        assert!(matches!(err, LoadError::DirNotFound(_)));
328    }
329
330    // --- zip archive ---
331
332    use std::io::Write;
333    use zip::CompressionMethod;
334    use zip::write::SimpleFileOptions;
335
336    /// Build a minimal zip with the given `(name, content)` entries.
337    /// Caller controls entry names exactly — used to test zip-slip.
338    fn write_zip(path: &Path, entries: &[(&str, &str)]) {
339        let file = fs::File::create(path).unwrap();
340        let mut zip = zip::ZipWriter::new(file);
341        let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Stored);
342        for (name, content) in entries {
343            zip.start_file(*name, opts).unwrap();
344            zip.write_all(content.as_bytes()).unwrap();
345        }
346        zip.finish().unwrap();
347    }
348
349    #[test]
350    fn zip_archive_reads_markdown_in_sorted_order() {
351        let dir = TempDir::new().unwrap();
352        let archive = dir.path().join("pkg.mem");
353        write_zip(
354            &archive,
355            &[
356                ("b.md", "b"),
357                ("a.md", "a"),
358                ("meta.json", "{\"name\":\"pkg\"}"),
359                (".memstead/config.json", "{}"),
360                ("readme.txt", "ignored"),
361                ("nested/c.md", "c"),
362            ],
363        );
364
365        let (entries, errors) = EntitySource::ZipArchive(archive).read_all().unwrap();
366        assert!(errors.is_empty());
367        let paths: Vec<_> = entries.iter().map(|e| e.relative_path.as_str()).collect();
368        assert_eq!(paths, vec!["a.md", "b.md", "nested/c.md"]);
369        let contents: Vec<_> = entries.iter().map(|e| e.content.as_str()).collect();
370        assert_eq!(contents, vec!["a", "b", "c"]);
371    }
372
373    #[test]
374    fn zip_archive_missing_file_returns_error() {
375        let err = EntitySource::ZipArchive(PathBuf::from("/nonexistent/pkg.mem"))
376            .read_all()
377            .unwrap_err();
378        assert!(matches!(err, LoadError::ArchiveNotFound(_)));
379    }
380
381    #[test]
382    fn zip_archive_corrupt_file_returns_zip_error() {
383        let dir = TempDir::new().unwrap();
384        let archive = dir.path().join("bad.mem");
385        fs::write(&archive, b"not a zip file at all, just bytes").unwrap();
386
387        let err = EntitySource::ZipArchive(archive).read_all().unwrap_err();
388        assert!(
389            matches!(err, LoadError::Zip(_)),
390            "corrupt archive should surface as LoadError::Zip, got {err:?}"
391        );
392    }
393
394    #[test]
395    fn zip_archive_rejects_parent_dir_escape() {
396        let dir = TempDir::new().unwrap();
397        let archive = dir.path().join("evil.mem");
398        write_zip(&archive, &[("../escape.md", "bad")]);
399
400        let err = EntitySource::ZipArchive(archive).read_all().unwrap_err();
401        let msg = format!("{err}");
402        assert!(matches!(err, LoadError::InvalidArchive(_)));
403        assert!(
404            msg.contains("escape") || msg.contains("..") || msg.contains("unsafe"),
405            "zip-slip error should explain the rejection: {msg}"
406        );
407    }
408
409    #[test]
410    fn zip_archive_rejects_nested_parent_dir_escape() {
411        // `subdir/../../outside.md` has `..`-components that normalize to
412        // "one level above the archive root". `enclosed_name` must reject
413        // this — a single `..` check that only looks at the first path
414        // segment would miss it.
415        let dir = TempDir::new().unwrap();
416        let archive = dir.path().join("evil.mem");
417        write_zip(&archive, &[("subdir/../../outside.md", "bad")]);
418
419        let err = EntitySource::ZipArchive(archive).read_all().unwrap_err();
420        assert!(matches!(err, LoadError::InvalidArchive(_)));
421    }
422
423    #[test]
424    fn zip_archive_rejects_oversized_entry() {
425        // A deflate bomb: highly compressible content one byte past the
426        // per-entry uncompressed cap. Must refuse with a typed error —
427        // and the read must stop at the cap, not decompress it all.
428        let dir = TempDir::new().unwrap();
429        let archive = dir.path().join("bomb.mem");
430        let big = "a".repeat((ValidatorLimits::DEFAULT.max_uncompressed_entry + 1) as usize);
431        let file = fs::File::create(&archive).unwrap();
432        let mut zip = zip::ZipWriter::new(file);
433        let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
434        zip.start_file("bomb.md", opts).unwrap();
435        zip.write_all(big.as_bytes()).unwrap();
436        zip.finish().unwrap();
437
438        let err = EntitySource::ZipArchive(archive).read_all().unwrap_err();
439        let msg = format!("{err}");
440        assert!(matches!(err, LoadError::InvalidArchive(_)), "got {err:?}");
441        assert!(msg.contains("cap"), "error should name the cap: {msg}");
442    }
443
444    // Note on absolute entry paths: the standard `zip::ZipWriter::start_file`
445    // normalizes leading separators away, so crafting a `/etc/evil.md` entry
446    // via the writer API is impossible — the writer stores it as
447    // `etc/evil.md` (relative). `enclosed_name` covers the hand-crafted
448    // malicious-archive case by rejecting anything that doesn't resolve to
449    // a relative path, including Windows drive letters. The two `..`-based
450    // tests above verify the guard is actually wired up; we trust
451    // `enclosed_name` for the rest.
452
453    // Git-tree adapter parity tests live alongside the GitTreeSource
454    // implementation in `memstead-git-branch::entity::git_tree_source`.
455}