1use std::path::{Path, PathBuf};
10
11use super::loader::LoadError;
12use crate::validator::{BoundedZipRead, ValidatorLimits, read_zip_entry_bounded};
13
14pub enum EntitySource {
16 Directory { root: PathBuf },
19 ZipArchive(PathBuf),
23}
24
25#[derive(Debug, Clone)]
27pub struct SourceEntry {
28 pub relative_path: String,
32 pub source_path: PathBuf,
37 pub content: String,
39}
40
41#[derive(Debug)]
45pub struct SourceReadError {
46 pub source_path: PathBuf,
47 pub error: std::io::Error,
48}
49
50impl EntitySource {
51 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 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 let raw_name = entry
138 .name()
139 .map_err(|e| LoadError::InvalidArchive(format!("entry {i}: undecodable name: {e}")))?
140 .into_owned();
141
142 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 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 continue;
176 }
177
178 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 entries.sort_by(|a, b| a.relative_path.cmp(&b.relative_path));
214
215 Ok((entries, errors))
216}
217
218fn 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 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 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 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 use std::io::Write;
333 use zip::CompressionMethod;
334 use zip::write::SimpleFileOptions;
335
336 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 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 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 }