1use crate::scope::{ScopeError, ScopedPath};
4use base64::{engine::general_purpose::STANDARD, Engine};
5use serde::{Deserialize, Serialize};
6use std::fmt;
7use std::fs;
8use std::io::Read;
9use std::path::Path;
10
11#[derive(Debug)]
13pub enum FilesError {
14 Scope(ScopeError),
16 Io(std::io::Error),
18 NotAFile,
20}
21
22impl FilesError {
23 pub fn code(&self) -> &'static str {
25 match self {
26 FilesError::Scope(e) => e.code(),
27 FilesError::Io(_) => "files_io",
28 FilesError::NotAFile => "files_not_a_file",
29 }
30 }
31}
32
33impl fmt::Display for FilesError {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 f.write_str(match self {
36 FilesError::Scope(_) => "the scope refused the file",
37 FilesError::Io(_) => "the folder or file could not be read",
38 FilesError::NotAFile => "not a file",
39 })
40 }
41}
42
43impl std::error::Error for FilesError {
44 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
45 match self {
46 FilesError::Scope(e) => Some(e),
47 FilesError::Io(e) => Some(e),
48 FilesError::NotAFile => None,
49 }
50 }
51}
52
53impl From<ScopeError> for FilesError {
54 fn from(error: ScopeError) -> Self {
55 FilesError::Scope(error)
56 }
57}
58
59impl From<std::io::Error> for FilesError {
60 fn from(error: std::io::Error) -> Self {
61 FilesError::Io(error)
62 }
63}
64
65const MIB: u64 = 1024 * 1024;
67
68#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize)]
79#[serde(rename_all = "camelCase", deny_unknown_fields)]
80pub struct Limits {
81 pub max_entries: Option<usize>,
82 pub max_text_preview: Option<usize>,
83 pub max_image_preview: Option<u64>,
84 pub max_pdf_preview: Option<u64>,
85 pub max_send: Option<u64>,
86}
87
88pub const DEFAULT_MAX_ENTRIES: usize = 2000;
92pub const CEILING_MAX_ENTRIES: usize = 20_000;
93pub const DEFAULT_MAX_TEXT_PREVIEW: usize = 64 * 1024;
94pub const CEILING_MAX_TEXT_PREVIEW: usize = 1024 * 1024;
95pub const DEFAULT_MAX_IMAGE_PREVIEW: u64 = 5 * MIB;
96pub const CEILING_MAX_IMAGE_PREVIEW: u64 = 25 * MIB;
97pub const DEFAULT_MAX_PDF_PREVIEW: u64 = 12 * MIB;
98pub const CEILING_MAX_PDF_PREVIEW: u64 = 50 * MIB;
99pub const DEFAULT_MAX_SEND: u64 = 50 * MIB;
100pub const CEILING_MAX_SEND: u64 = 200 * MIB;
101
102impl Limits {
103 pub fn entries(&self) -> usize {
105 self.max_entries
106 .unwrap_or(DEFAULT_MAX_ENTRIES)
107 .clamp(1, CEILING_MAX_ENTRIES)
108 }
109
110 pub fn text_preview(&self) -> usize {
112 self.max_text_preview
113 .unwrap_or(DEFAULT_MAX_TEXT_PREVIEW)
114 .clamp(1, CEILING_MAX_TEXT_PREVIEW)
115 }
116
117 pub fn image_preview(&self) -> u64 {
119 self.max_image_preview
120 .unwrap_or(DEFAULT_MAX_IMAGE_PREVIEW)
121 .clamp(1, CEILING_MAX_IMAGE_PREVIEW)
122 }
123
124 pub fn pdf_preview(&self) -> u64 {
126 self.max_pdf_preview
127 .unwrap_or(DEFAULT_MAX_PDF_PREVIEW)
128 .clamp(1, CEILING_MAX_PDF_PREVIEW)
129 }
130
131 pub fn send(&self) -> u64 {
133 self.max_send
134 .unwrap_or(DEFAULT_MAX_SEND)
135 .clamp(1, CEILING_MAX_SEND)
136 }
137}
138
139#[derive(Debug, Serialize, Clone, Copy, PartialEq, Eq)]
141#[serde(rename_all = "lowercase")]
142pub enum Kind {
143 Folder,
144 Pdf,
145 Image,
146 Video,
147 Audio,
148 Text,
149 Document,
150 Sheet,
151 File,
152}
153
154const UNKNOWN_MIME: &str = "application/octet-stream";
156
157const TYPES: &[(&str, Kind, &str)] = &[
159 ("pdf", Kind::Pdf, "application/pdf"),
160 ("png", Kind::Image, "image/png"),
161 ("jpg", Kind::Image, "image/jpeg"),
162 ("jpeg", Kind::Image, "image/jpeg"),
163 ("gif", Kind::Image, "image/gif"),
164 ("webp", Kind::Image, "image/webp"),
165 ("heic", Kind::Image, "image/heic"),
166 ("svg", Kind::Image, "image/svg+xml"),
167 ("mp4", Kind::Video, "video/mp4"),
168 ("m4v", Kind::Video, "video/mp4"),
169 ("mov", Kind::Video, "video/quicktime"),
170 ("webm", Kind::Video, "video/webm"),
171 ("mp3", Kind::Audio, "audio/mpeg"),
172 ("wav", Kind::Audio, "audio/wav"),
173 ("m4a", Kind::Audio, "audio/mp4"),
174 ("flac", Kind::Audio, "audio/flac"),
175 ("txt", Kind::Text, "text/plain"),
176 ("log", Kind::Text, "text/plain"),
177 ("md", Kind::Text, "text/markdown"),
178 ("csv", Kind::Text, "text/csv"),
179 ("tsv", Kind::Text, "text/tab-separated-values"),
180 ("json", Kind::Text, "application/json"),
181 ("yaml", Kind::Text, "application/yaml"),
182 ("yml", Kind::Text, "application/yaml"),
183 ("xml", Kind::Text, "application/xml"),
184 ("html", Kind::Text, "text/html"),
185 ("doc", Kind::Document, "application/msword"),
186 (
187 "docx",
188 Kind::Document,
189 "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
190 ),
191 (
192 "odt",
193 Kind::Document,
194 "application/vnd.oasis.opendocument.text",
195 ),
196 ("rtf", Kind::Document, "application/rtf"),
197 ("pages", Kind::Document, "application/vnd.apple.pages"),
198 ("xls", Kind::Sheet, "application/vnd.ms-excel"),
199 (
200 "xlsx",
201 Kind::Sheet,
202 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
203 ),
204 (
205 "ods",
206 Kind::Sheet,
207 "application/vnd.oasis.opendocument.spreadsheet",
208 ),
209 ("numbers", Kind::Sheet, "application/vnd.apple.numbers"),
210];
211
212fn type_of(name: &str) -> Option<&'static (&'static str, Kind, &'static str)> {
213 let ext = extension(name);
214 TYPES.iter().find(|(e, _, _)| *e == ext)
215}
216
217#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
218#[serde(rename_all = "camelCase")]
219pub struct Entry {
220 pub name: String,
221 pub path: String,
222 pub is_dir: bool,
223 pub size: u64,
224 pub modified: u64,
225 pub kind: Kind,
226}
227
228#[derive(Debug, Serialize, PartialEq, Eq)]
229#[serde(rename_all = "camelCase")]
230pub struct Listing {
231 pub entries: Vec<Entry>,
232 pub truncated: bool,
233}
234
235#[derive(Debug, Serialize, PartialEq, Eq)]
236#[serde(rename_all = "camelCase")]
237pub struct Preview {
238 pub name: String,
239 pub size: u64,
240 pub mime: String,
241 pub kind: Kind,
242 pub text: Option<String>,
243 pub data: Option<String>,
245}
246
247pub fn kind_of(name: &str) -> Kind {
248 type_of(name).map_or(Kind::File, |(_, kind, _)| *kind)
249}
250
251pub fn mime_of(name: &str) -> &'static str {
252 type_of(name).map_or(UNKNOWN_MIME, |(_, _, mime)| mime)
253}
254
255fn extension(name: &str) -> String {
256 Path::new(name)
257 .extension()
258 .map(|e| e.to_string_lossy().to_lowercase())
259 .unwrap_or_default()
260}
261
262pub fn is_noise(name: &str) -> bool {
264 name.starts_with('.')
265 || name.starts_with("~$")
266 || name.ends_with('~')
267 || name.ends_with(".crdownload")
268 || name.ends_with(".part")
269 || name.ends_with(".tmp")
270 || name.ends_with(".download")
271}
272
273pub fn list_dir(dir: &ScopedPath, limits: &Limits) -> Result<Listing, FilesError> {
282 let mut entries: Vec<Entry> = Vec::new();
283 let rd = fs::read_dir(dir.as_path())?;
284 for item in rd.flatten() {
285 let name = item.file_name().to_string_lossy().to_string();
286 if is_noise(&name) {
287 continue;
288 }
289 let Ok(meta) = item.path().symlink_metadata() else {
291 continue;
292 };
293 if meta.file_type().is_symlink() {
294 continue;
295 }
296 let modified = meta
297 .modified()
298 .ok()
299 .and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok())
300 .map(|d| d.as_secs())
301 .unwrap_or(0);
302 entries.push(Entry {
303 kind: if meta.is_dir() {
304 Kind::Folder
305 } else {
306 kind_of(&name)
307 },
308 path: item.path().display().to_string(),
309 is_dir: meta.is_dir(),
310 size: if meta.is_dir() { 0 } else { meta.len() },
311 modified,
312 name,
313 });
314 }
315 entries.sort_by_cached_key(|e| (!e.is_dir, e.name.to_lowercase()));
318 let max = limits.entries();
319 let truncated = entries.len() > max;
320 entries.truncate(max);
321 Ok(Listing { entries, truncated })
322}
323
324pub fn preview(file: &ScopedPath, limits: &Limits) -> Result<Preview, FilesError> {
332 let opened = file.open()?;
334 let meta = opened.metadata()?;
335 if !meta.is_file() {
336 return Err(FilesError::NotAFile);
337 }
338 let name = file
339 .as_path()
340 .file_name()
341 .map(|n| n.to_string_lossy().to_string())
342 .unwrap_or_default();
343 let kind = kind_of(&name);
344 let mut p = Preview {
345 mime: mime_of(&name).into(),
346 kind,
347 size: meta.len(),
348 name,
349 text: None,
350 data: None,
351 };
352 match kind {
353 Kind::Text => {
354 let buf = read_at_most(opened, limits.text_preview() as u64)?;
355 p.text = Some(String::from_utf8_lossy(&buf).to_string());
356 }
357 Kind::Image if meta.len() <= limits.image_preview() => {
358 p.data = Some(STANDARD.encode(read_at_most(opened, limits.image_preview())?));
359 }
360 Kind::Pdf if meta.len() <= limits.pdf_preview() => {
361 p.data = Some(STANDARD.encode(read_at_most(opened, limits.pdf_preview())?));
362 }
363 _ => {}
364 }
365 Ok(p)
366}
367
368fn read_at_most(file: fs::File, limit: u64) -> Result<Vec<u8>, FilesError> {
370 let mut buf = Vec::new();
371 file.take(limit).read_to_end(&mut buf)?;
372 Ok(buf)
373}
374
375#[cfg(test)]
376mod tests {
377 use super::*;
378 use crate::scope::ScopeStore;
379 use std::path::PathBuf;
380 use tempfile::{tempdir, TempDir};
381
382 type TestResult = Result<(), Box<dyn std::error::Error>>;
383
384 struct Granted {
386 home: TempDir,
387 outside: TempDir,
388 scope: ScopeStore,
389 }
390
391 impl Granted {
392 fn new() -> Result<Granted, Box<dyn std::error::Error>> {
393 let home = tempdir()?;
394 let outside = tempdir()?;
395 fs::create_dir(home.path().join("docs"))?;
396 let mut scope = ScopeStore::default();
397 let canon = home.path().canonicalize()?;
398 scope.grant_with_home(&canon.join("docs"), Some(&canon))?;
399 Ok(Granted {
400 home,
401 outside,
402 scope,
403 })
404 }
405
406 fn docs(&self) -> PathBuf {
407 self.home.path().join("docs")
408 }
409
410 fn resolve(&self, path: &Path) -> Result<ScopedPath, Box<dyn std::error::Error>> {
411 let home = self.home.path().canonicalize()?;
412 Ok(self.scope.resolve_with_home(path, Some(&home))?)
413 }
414 }
415
416 #[test]
417 fn lists_folders_first_hides_noise_and_skips_symlinks() -> TestResult {
418 let granted = Granted::new()?;
419 let d = granted.docs();
420 fs::create_dir(d.join("b-folder"))?;
421 fs::write(d.join("a.pdf"), "%PDF")?;
422 fs::write(d.join(".DS_Store"), "x")?;
423 fs::write(d.join("~$draft.docx"), "x")?;
424 fs::write(d.join("big.crdownload"), "x")?;
425 #[cfg(unix)]
426 std::os::unix::fs::symlink("/etc/hosts", d.join("link.txt"))?;
427 let l = list_dir(&granted.resolve(&d)?, &Limits::default())?;
428 let names: Vec<_> = l.entries.iter().map(|e| e.name.as_str()).collect();
429 assert_eq!(names, ["b-folder", "a.pdf"]);
430 assert_eq!(l.entries[0].kind, Kind::Folder);
431 assert_eq!(l.entries[1].kind, Kind::Pdf);
432 Ok(())
433 }
434
435 #[test]
436 fn previews_text_is_capped_and_pdf_is_base64() -> TestResult {
437 let granted = Granted::new()?;
438 let d = granted.docs();
439 fs::write(d.join("n.md"), "x".repeat(DEFAULT_MAX_TEXT_PREVIEW + 100))?;
440 fs::write(d.join("a.pdf"), "%PDF-1.4")?;
441 fs::write(d.join("x.bin"), [0u8, 1, 2])?;
442 let t = preview(&granted.resolve(&d.join("n.md"))?, &Limits::default())?;
443 assert_eq!(t.size, (DEFAULT_MAX_TEXT_PREVIEW + 100) as u64);
444 assert_eq!(
445 t.text.map(|text| text.len()),
446 Some(DEFAULT_MAX_TEXT_PREVIEW)
447 );
448 let p = preview(&granted.resolve(&d.join("a.pdf"))?, &Limits::default())?;
449 assert_eq!(p.mime, "application/pdf");
450 assert_eq!(
451 p.data.map(|data| STANDARD.decode(data)).transpose()?,
452 Some(b"%PDF-1.4".to_vec())
453 );
454 let b = preview(&granted.resolve(&d.join("x.bin"))?, &Limits::default())?;
455 assert!(b.text.is_none() && b.data.is_none());
456 assert!(preview(&granted.resolve(&d)?, &Limits::default()).is_err());
457 Ok(())
458 }
459
460 #[cfg(unix)]
461 #[test]
462 fn a_file_swapped_for_a_link_out_after_resolve_is_not_read() -> TestResult {
463 let granted = Granted::new()?;
464 let target = granted.docs().join("a.txt");
465 fs::write(&target, "public")?;
466 fs::write(granted.outside.path().join("a.txt"), "secret")?;
467 let resolved = granted.resolve(&target)?;
468 fs::remove_file(&target)?;
469 std::os::unix::fs::symlink(granted.outside.path().join("a.txt"), &target)?;
470 let read = preview(&resolved, &Limits::default());
471 assert!(read.is_err(), "read through a swapped link: {read:?}");
472 Ok(())
473 }
474
475 #[cfg(unix)]
476 #[test]
477 fn a_parent_swapped_for_a_link_out_after_resolve_is_not_read() -> TestResult {
478 let granted = Granted::new()?;
479 let sub = granted.docs().join("sub");
480 fs::create_dir(&sub)?;
481 fs::write(sub.join("a.txt"), "public")?;
482 fs::write(granted.outside.path().join("a.txt"), "secret")?;
483 let resolved = granted.resolve(&sub.join("a.txt"))?;
484 fs::rename(&sub, granted.docs().join("old"))?;
485 std::os::unix::fs::symlink(granted.outside.path(), &sub)?;
486 let read = preview(&resolved, &Limits::default());
487 assert!(read.is_err(), "read through a swapped parent: {read:?}");
488 Ok(())
489 }
490
491 #[cfg(unix)]
492 #[test]
493 fn a_file_swapped_for_a_pipe_after_resolve_is_refused_without_blocking() -> TestResult {
494 let granted = Granted::new()?;
495 let target = granted.docs().join("a.txt");
496 fs::write(&target, "public")?;
497 let resolved = granted.resolve(&target)?;
498 fs::remove_file(&target)?;
499 let made = std::process::Command::new("mkfifo").arg(&target).status()?;
500 assert!(made.success());
501 assert!(preview(&resolved, &Limits::default()).is_err());
502 Ok(())
503 }
504
505 #[cfg(target_os = "macos")]
506 #[test]
507 fn a_path_typed_in_another_case_is_previewed() -> TestResult {
508 let granted = Granted::new()?;
509 fs::write(granted.docs().join("Note.txt"), "hello")?;
510 let typed = granted.docs().join("NOTE.TXT");
511 if !typed.exists() {
512 return Ok(()); }
514 let resolved = granted.resolve(&typed)?;
515 assert_eq!(
516 preview(&resolved, &Limits::default())?.text.as_deref(),
517 Some("hello")
518 );
519 Ok(())
520 }
521
522 #[test]
523 fn noise_names() {
524 for n in [".hidden", "~$a.docx", "a.part", "a.crdownload", "a.tmp"] {
525 assert!(is_noise(n), "{n}");
526 }
527 assert!(!is_noise("contract.pdf"));
528 }
529
530 #[test]
531 fn the_listing_is_sorted_before_it_is_cut() -> TestResult {
532 let granted = Granted::new()?;
533 let d = granted.docs();
534 for name in ["e", "d", "c", "b", "a"] {
536 fs::write(d.join(format!("{name}.txt")), "x")?;
537 }
538 fs::create_dir(d.join("zz-folder"))?;
539 let limits = Limits {
540 max_entries: Some(3),
541 ..Limits::default()
542 };
543 let l = list_dir(&granted.resolve(&d)?, &limits)?;
544 let names: Vec<_> = l.entries.iter().map(|e| e.name.as_str()).collect();
545 assert_eq!(names, ["zz-folder", "a.txt", "b.txt"]);
546 assert!(l.truncated);
547 let all = list_dir(&granted.resolve(&d)?, &Limits::default())?;
548 assert!(!all.truncated && all.entries.len() == 6);
549 Ok(())
550 }
551
552 #[test]
553 fn a_limit_defaults_and_is_held_by_its_ceiling() {
554 let none = Limits::default();
555 assert_eq!(none.entries(), DEFAULT_MAX_ENTRIES);
556 assert_eq!(none.send(), DEFAULT_MAX_SEND);
557 let huge = Limits {
558 max_entries: Some(usize::MAX),
559 max_text_preview: Some(usize::MAX),
560 max_image_preview: Some(u64::MAX),
561 max_pdf_preview: Some(u64::MAX),
562 max_send: Some(u64::MAX),
563 };
564 assert_eq!(huge.entries(), CEILING_MAX_ENTRIES);
565 assert_eq!(huge.text_preview(), CEILING_MAX_TEXT_PREVIEW);
566 assert_eq!(huge.image_preview(), CEILING_MAX_IMAGE_PREVIEW);
567 assert_eq!(huge.pdf_preview(), CEILING_MAX_PDF_PREVIEW);
568 assert_eq!(huge.send(), CEILING_MAX_SEND);
569 let zero = Limits {
570 max_entries: Some(0),
571 max_send: Some(0),
572 ..Limits::default()
573 };
574 assert_eq!((zero.entries(), zero.send()), (1, 1));
575 }
576
577 #[test]
578 fn limits_come_from_the_page_and_refuse_unknown_names() -> Result<(), serde_json::Error> {
579 let l: Limits = serde_json::from_str(r#"{"maxEntries": 10, "maxSend": 99}"#)?;
580 assert_eq!((l.entries(), l.send()), (10, 99));
581 assert!(serde_json::from_str::<Limits>(r#"{"maxEntry": 10}"#).is_err());
582 Ok(())
583 }
584
585 #[test]
586 fn a_preview_follows_the_limits_of_its_call() -> TestResult {
587 let granted = Granted::new()?;
588 let d = granted.docs();
589 fs::write(d.join("n.txt"), "abcdefgh")?;
590 fs::write(d.join("p.png"), [7u8; 100])?;
591 let tight = Limits {
592 max_text_preview: Some(3),
593 max_image_preview: Some(50),
594 ..Limits::default()
595 };
596 let t = preview(&granted.resolve(&d.join("n.txt"))?, &tight)?;
597 assert_eq!(t.text.as_deref(), Some("abc"));
598 let image = granted.resolve(&d.join("p.png"))?;
599 assert!(preview(&image, &tight)?.data.is_none());
600 assert!(preview(&image, &Limits::default())?.data.is_some());
601 Ok(())
602 }
603
604 #[test]
605 fn one_table_gives_kind_and_mime_and_the_wire_values_hold() -> Result<(), serde_json::Error> {
606 assert_eq!(kind_of("IMG.HEIC"), Kind::Image);
607 assert_eq!(mime_of("IMG.HEIC"), "image/heic");
608 assert_eq!(kind_of("a.webm"), Kind::Video);
609 assert_eq!(mime_of("a.webm"), "video/webm");
610 assert_eq!(kind_of("a.unknown"), Kind::File);
611 assert_eq!(mime_of("a.unknown"), "application/octet-stream");
612 assert_eq!(kind_of("noext"), Kind::File);
613 for (ext, kind, mime) in TYPES {
614 let name = format!("f.{ext}");
615 assert_eq!((kind_of(&name), mime_of(&name)), (*kind, *mime), "{ext}");
616 assert_ne!(*kind, Kind::File);
617 }
618 let wire: Vec<String> = [
619 Kind::Folder,
620 Kind::Pdf,
621 Kind::Image,
622 Kind::Video,
623 Kind::Audio,
624 Kind::Text,
625 Kind::Document,
626 Kind::Sheet,
627 Kind::File,
628 ]
629 .iter()
630 .map(serde_json::to_string)
631 .collect::<Result<_, _>>()?;
632 assert_eq!(
633 wire,
634 [
635 "\"folder\"",
636 "\"pdf\"",
637 "\"image\"",
638 "\"video\"",
639 "\"audio\"",
640 "\"text\"",
641 "\"document\"",
642 "\"sheet\"",
643 "\"file\""
644 ]
645 );
646 Ok(())
647 }
648}