1use std::{
29 io::Read,
30 path::{Component, Path, PathBuf},
31 sync::{
32 atomic::{AtomicU64, Ordering},
33 Arc,
34 },
35 time::UNIX_EPOCH,
36};
37
38use murmur_artifact::{ContainmentClass, ExportMode, FileExport, PeerFilesExport};
39use serde::Serialize;
40
41use crate::{errors::RuntimeError, trace::ResourceTraceAppender};
42
43pub const RESOURCE_PATH_PREFIX: &str = "/resources/";
45
46const FILES_ROUTE: &str = "files";
48
49#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct DeclaredExport {
60 pub declared_root: String,
63 pub root: PathBuf,
65 pub mode: ExportMode,
66 pub max_bytes: u64,
69}
70
71impl DeclaredExport {
72 pub fn resolve(accessible_workdir: &Path, export: &FileExport) -> Self {
77 Self {
78 declared_root: export.root.clone(),
79 root: accessible_workdir.join(&export.root),
80 mode: export.mode,
81 max_bytes: export.max_bytes,
82 }
83 }
84
85 pub fn for_peer_files(accessible_workdir: &Path, export: &PeerFilesExport) -> Self {
93 Self {
94 declared_root: export.root.clone(),
95 root: accessible_workdir.join(&export.root),
96 mode: ExportMode::ReadOnly,
97 max_bytes: export.max_bytes,
98 }
99 }
100}
101
102pub fn check_peer_files_root(
105 accessible_workdir: &Path,
106 export: &PeerFilesExport,
107) -> Result<(), RuntimeError> {
108 check_root_within_workdir(accessible_workdir, "exports.peer_files.root", &export.root)
109}
110
111pub fn check_export_root(
119 accessible_workdir: &Path,
120 export: &FileExport,
121) -> Result<(), RuntimeError> {
122 check_root_within_workdir(accessible_workdir, "exports.files.root", &export.root)
123}
124
125fn check_root_within_workdir(
126 accessible_workdir: &Path,
127 field: &str,
128 root: &str,
129) -> Result<(), RuntimeError> {
130 let Ok(workdir_canon) = std::fs::canonicalize(accessible_workdir) else {
131 return Ok(());
134 };
135 let Ok(resolved) = std::fs::canonicalize(workdir_canon.join(root)) else {
136 return Ok(());
137 };
138 if !resolved.starts_with(&workdir_canon) {
139 return Err(RuntimeError::ExportRootOutsideWorkdir {
140 field: field.to_string(),
141 declared: root.to_string(),
142 resolved: resolved.display().to_string(),
143 workdir: workdir_canon.display().to_string(),
144 });
145 }
146 Ok(())
147}
148
149pub struct ResourcePlane {
157 export: Option<DeclaredExport>,
160 containment_achieved: ContainmentClass,
163 generation: Arc<AtomicU64>,
166 trace: Option<Arc<ResourceTraceAppender>>,
169}
170
171impl ResourcePlane {
172 pub fn new(
178 accessible_workdir: &Path,
179 export: Option<&FileExport>,
180 containment_achieved: ContainmentClass,
181 generation: Arc<AtomicU64>,
182 trace: Option<Arc<ResourceTraceAppender>>,
183 ) -> Self {
184 Self::with_export(
185 export.map(|export| DeclaredExport::resolve(accessible_workdir, export)),
186 containment_achieved,
187 generation,
188 trace,
189 )
190 }
191
192 pub fn with_export(
194 export: Option<DeclaredExport>,
195 containment_achieved: ContainmentClass,
196 generation: Arc<AtomicU64>,
197 trace: Option<Arc<ResourceTraceAppender>>,
198 ) -> Self {
199 Self {
200 export,
201 containment_achieved,
202 generation,
203 trace,
204 }
205 }
206
207 pub fn generation(&self) -> u64 {
215 self.generation.load(Ordering::SeqCst)
216 }
217
218 pub fn containment_achieved(&self) -> ContainmentClass {
219 self.containment_achieved
220 }
221}
222
223#[derive(Debug, Clone, PartialEq, Eq)]
230pub struct ResourceResponse {
231 pub status: u16,
232 pub headers: Vec<(String, String)>,
233 pub body: Vec<u8>,
234}
235
236impl ResourceResponse {
237 pub(crate) fn framed(status: u16, mut headers: Vec<(String, String)>, body: Vec<u8>) -> Self {
244 headers.push(("content-length".to_string(), body.len().to_string()));
245 Self {
246 status,
247 headers,
248 body,
249 }
250 }
251}
252
253#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
254pub struct ListResponse {
255 pub root: String,
256 pub mode: ExportMode,
257 pub max_bytes: u64,
258 pub generation: u64,
259 pub containment_achieved: ContainmentClass,
260 pub entries: Vec<ListEntry>,
261}
262
263#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
266pub struct ListEntry {
267 pub path: String,
269 pub size_bytes: u64,
270 pub mtime_ms: u64,
271 pub sha256: String,
272}
273
274#[derive(Debug, Clone, PartialEq, Eq)]
279pub struct ReadResponse {
280 pub bytes: Vec<u8>,
281 pub sha256: String,
282 pub mtime_ms: u64,
283}
284
285#[derive(Debug, Clone, PartialEq, Eq)]
288pub enum ResourceError {
289 NoResourcePlane,
291 NotFound,
292 OutsideRoot,
293 SymlinkRefused,
295 NotARegularFile,
296 TooLarge {
297 max_bytes: u64,
298 },
299 MethodNotAllowed,
300 IoError(String),
301}
302
303impl ResourceError {
304 pub fn code(&self) -> &'static str {
307 match self {
308 ResourceError::NoResourcePlane => "no_resource_plane",
309 ResourceError::NotFound => "not_found",
310 ResourceError::OutsideRoot => "outside_root",
311 ResourceError::SymlinkRefused => "symlink_refused",
312 ResourceError::NotARegularFile => "not_a_regular_file",
313 ResourceError::TooLarge { .. } => "too_large",
314 ResourceError::MethodNotAllowed => "method_not_allowed",
315 ResourceError::IoError(_) => "io_error",
316 }
317 }
318
319 pub fn status(&self) -> u16 {
320 match self {
321 ResourceError::NoResourcePlane | ResourceError::NotFound => 404,
322 ResourceError::OutsideRoot
323 | ResourceError::SymlinkRefused
324 | ResourceError::NotARegularFile => 403,
325 ResourceError::TooLarge { .. } => 413,
326 ResourceError::MethodNotAllowed => 405,
327 ResourceError::IoError(_) => 500,
328 }
329 }
330
331 pub fn message(&self) -> String {
332 match self {
333 ResourceError::NoResourcePlane => {
334 "this capsule declares no exports.files block, so it has no resource plane"
335 .to_string()
336 }
337 ResourceError::NotFound => "no such file under the export root".to_string(),
338 ResourceError::OutsideRoot => {
339 "the requested path resolves outside the export root".to_string()
340 }
341 ResourceError::SymlinkRefused => {
342 "a symlink was encountered and the achieved containment class is scoped".to_string()
343 }
344 ResourceError::NotARegularFile => {
345 "the requested path is not a regular file".to_string()
346 }
347 ResourceError::TooLarge { max_bytes } => {
348 format!("file exceeds the declared exports.files.max_bytes of {max_bytes} bytes")
349 }
350 ResourceError::MethodNotAllowed => {
351 "the resource plane serves GET only; it has no write path".to_string()
352 }
353 ResourceError::IoError(detail) => format!("read failed: {detail}"),
354 }
355 }
356}
357
358fn io_to_resource_error(error: &std::io::Error) -> ResourceError {
359 match error.kind() {
360 std::io::ErrorKind::NotFound => ResourceError::NotFound,
361 std::io::ErrorKind::NotADirectory => ResourceError::NotFound,
364 std::io::ErrorKind::PermissionDenied => ResourceError::IoError(error.to_string()),
365 _ if error.raw_os_error() == Some(libc::ELOOP) => ResourceError::SymlinkRefused,
366 _ => ResourceError::IoError(error.to_string()),
367 }
368}
369
370#[derive(Debug, Clone, Copy, PartialEq, Eq)]
373pub enum SymlinkPolicy {
374 Refuse,
377 FollowWithinRoot,
380}
381
382pub fn symlink_policy(class: ContainmentClass) -> SymlinkPolicy {
395 match class {
396 ContainmentClass::Scoped => SymlinkPolicy::Refuse,
397 ContainmentClass::Sealed | ContainmentClass::Advisory => SymlinkPolicy::FollowWithinRoot,
398 }
399}
400
401fn percent_decode(raw: &str) -> Vec<u8> {
410 let bytes = raw.as_bytes();
411 let mut out = Vec::with_capacity(bytes.len());
412 let mut index = 0;
413 while index < bytes.len() {
414 if bytes[index] == b'%' && index + 2 < bytes.len() {
415 let hex = std::str::from_utf8(&bytes[index + 1..index + 3])
416 .ok()
417 .and_then(|pair| u8::from_str_radix(pair, 16).ok());
418 if let Some(byte) = hex {
419 out.push(byte);
420 index += 3;
421 continue;
422 }
423 }
424 out.push(bytes[index]);
425 index += 1;
426 }
427 out
428}
429
430pub(crate) fn export_relpath_components(raw: &str) -> Result<Vec<String>, ResourceError> {
438 let decoded = percent_decode(raw);
439 if decoded.is_empty() || decoded.contains(&0) {
440 return Err(ResourceError::OutsideRoot);
441 }
442 let decoded = String::from_utf8(decoded).map_err(|_| ResourceError::OutsideRoot)?;
443 if decoded.starts_with('/') || Path::new(&decoded).is_absolute() {
444 return Err(ResourceError::OutsideRoot);
445 }
446 let mut components = Vec::new();
449 for part in decoded.strip_suffix('/').unwrap_or(&decoded).split('/') {
450 if part.is_empty() || part == "." || part == ".." {
451 return Err(ResourceError::OutsideRoot);
452 }
453 components.push(part.to_string());
454 }
455 if components.is_empty() {
456 return Err(ResourceError::OutsideRoot);
457 }
458 for component in &components {
461 if Path::new(component)
462 .components()
463 .any(|c| !matches!(c, Component::Normal(_)))
464 {
465 return Err(ResourceError::OutsideRoot);
466 }
467 }
468 Ok(components)
469}
470
471fn resolve_beneath(
477 root_canon: &Path,
478 components: &[String],
479 policy: SymlinkPolicy,
480) -> Result<PathBuf, ResourceError> {
481 let mut target = root_canon.to_path_buf();
482 if policy == SymlinkPolicy::Refuse {
483 for component in components {
487 target.push(component);
488 let metadata =
489 std::fs::symlink_metadata(&target).map_err(|e| io_to_resource_error(&e))?;
490 if metadata.file_type().is_symlink() {
491 return Err(ResourceError::SymlinkRefused);
492 }
493 }
494 } else {
495 for component in components {
496 target.push(component);
497 }
498 }
499 let canonical = std::fs::canonicalize(&target).map_err(|e| io_to_resource_error(&e))?;
500 if !canonical.starts_with(root_canon) {
501 return Err(ResourceError::OutsideRoot);
502 }
503 Ok(canonical)
504}
505
506fn open_regular_file(path: &Path) -> Result<(std::fs::File, std::fs::Metadata), ResourceError> {
513 use std::os::unix::fs::OpenOptionsExt;
514
515 let file = std::fs::OpenOptions::new()
516 .read(true)
517 .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
518 .open(path)
519 .map_err(|e| io_to_resource_error(&e))?;
520 let metadata = file.metadata().map_err(|e| io_to_resource_error(&e))?;
521 if !metadata.is_file() {
522 return Err(ResourceError::NotARegularFile);
523 }
524 Ok((file, metadata))
525}
526
527fn mtime_ms(metadata: &std::fs::Metadata) -> u64 {
528 metadata
529 .modified()
530 .ok()
531 .and_then(|time| time.duration_since(UNIX_EPOCH).ok())
532 .map(|d| d.as_millis() as u64)
533 .unwrap_or(0)
534}
535
536pub(crate) fn resolve_relpath_beneath_root(
546 export: &DeclaredExport,
547 relpath: &str,
548 policy: SymlinkPolicy,
549) -> Result<(PathBuf, String), ResourceError> {
550 let components = export_relpath_components(relpath)?;
551 let root_canon = std::fs::canonicalize(&export.root).map_err(|e| io_to_resource_error(&e))?;
552 let target = resolve_beneath(&root_canon, &components, policy)?;
553 let relative = target
554 .strip_prefix(&root_canon)
555 .map_err(|_| ResourceError::OutsideRoot)?
556 .components()
557 .map(|component| component.as_os_str().to_string_lossy().into_owned())
558 .collect::<Vec<_>>()
559 .join("/");
560 if relative.is_empty() {
561 return Err(ResourceError::OutsideRoot);
562 }
563 Ok((target, relative))
564}
565
566pub(crate) fn read_export_file_with_policy(
576 export: &DeclaredExport,
577 relpath: &str,
578 policy: SymlinkPolicy,
579) -> Result<ReadResponse, ResourceError> {
580 let (target, _) = resolve_relpath_beneath_root(export, relpath, policy)?;
581
582 let (file, metadata) = open_regular_file(&target)?;
583 if metadata.len() > export.max_bytes {
584 return Err(ResourceError::TooLarge {
585 max_bytes: export.max_bytes,
586 });
587 }
588 let mtime = mtime_ms(&metadata);
589
590 let mut bytes = Vec::with_capacity(metadata.len() as usize);
593 let mut limited = file.take(export.max_bytes.saturating_add(1));
594 limited
595 .read_to_end(&mut bytes)
596 .map_err(|e| io_to_resource_error(&e))?;
597 if bytes.len() as u64 > export.max_bytes {
598 return Err(ResourceError::TooLarge {
599 max_bytes: export.max_bytes,
600 });
601 }
602
603 let sha256 = murmur_artifact::sha256_hex(&bytes);
604 Ok(ReadResponse {
605 bytes,
606 sha256,
607 mtime_ms: mtime,
608 })
609}
610
611pub(crate) fn read_file_beneath_root(
623 root: &Path,
624 relpath: &str,
625 max_bytes: u64,
626 policy: SymlinkPolicy,
627) -> Result<ReadResponse, ResourceError> {
628 let export = DeclaredExport {
629 declared_root: ".".to_string(),
630 root: root.to_path_buf(),
631 mode: ExportMode::ReadOnly,
632 max_bytes,
633 };
634 read_export_file_with_policy(&export, relpath, policy)
635}
636
637fn list_export_files(
645 export: &DeclaredExport,
646 policy: SymlinkPolicy,
647) -> Result<Vec<ListEntry>, ResourceError> {
648 let root_canon = match std::fs::canonicalize(&export.root) {
649 Ok(path) => path,
650 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
651 Err(error) => return Err(io_to_resource_error(&error)),
652 };
653 if !root_canon.is_dir() {
654 return Ok(Vec::new());
655 }
656
657 let mut entries = Vec::new();
658 let mut pending = vec![(root_canon.clone(), String::new())];
659 while let Some((dir, prefix)) = pending.pop() {
660 let reader = match std::fs::read_dir(&dir) {
661 Ok(reader) => reader,
662 Err(_) => continue,
665 };
666 for entry in reader.flatten() {
667 let name = entry.file_name().to_string_lossy().to_string();
668 let relative = if prefix.is_empty() {
669 name.clone()
670 } else {
671 format!("{prefix}/{name}")
672 };
673 let Ok(file_type) = entry.file_type() else {
674 continue;
675 };
676 let path = entry.path();
677
678 if file_type.is_symlink() {
679 if policy == SymlinkPolicy::Refuse {
680 continue;
681 }
682 let Ok(canonical) = std::fs::canonicalize(&path) else {
686 continue;
687 };
688 if !canonical.starts_with(&root_canon) {
689 continue;
690 }
691 if let Some(entry) = describe_entry(&canonical, relative) {
692 entries.push(entry);
693 }
694 continue;
695 }
696
697 if file_type.is_dir() {
698 pending.push((path, relative));
699 } else if file_type.is_file() {
700 if let Some(entry) = describe_entry(&path, relative) {
701 entries.push(entry);
702 }
703 }
704 }
705 }
706 entries.sort_by(|a, b| a.path.cmp(&b.path));
707 Ok(entries)
708}
709
710fn describe_entry(path: &Path, relative: String) -> Option<ListEntry> {
714 let (mut file, metadata) = open_regular_file(path).ok()?;
715 let mtime = mtime_ms(&metadata);
716 let (size_bytes, sha256) = murmur_artifact::sha256_hex_of_reader(&mut file).ok()?;
719 Some(ListEntry {
720 path: relative,
721 size_bytes,
722 mtime_ms: mtime,
723 sha256,
724 })
725}
726
727pub async fn handle_resource_request(
737 plane: &ResourcePlane,
738 method: &str,
739 raw_path: &str,
740) -> ResourceResponse {
741 let path = raw_path.split('?').next().unwrap_or("");
742 let Some(rest) = path.strip_prefix(RESOURCE_PATH_PREFIX) else {
743 return error_response(&ResourceError::NotFound, None);
744 };
745
746 if rest == FILES_ROUTE || rest == "files/" {
747 return handle_list(plane, method).await;
748 }
749 if let Some(relpath) = rest.strip_prefix("files/") {
750 return handle_read(plane, method, relpath).await;
751 }
752 if method != "GET" {
756 return error_response(&ResourceError::MethodNotAllowed, None);
757 }
758 error_response(&ResourceError::NotFound, None)
759}
760
761fn servable_export<'a>(
766 plane: &'a ResourcePlane,
767 method: &str,
768) -> Result<&'a DeclaredExport, ResourceError> {
769 if method != "GET" {
770 return Err(ResourceError::MethodNotAllowed);
771 }
772 plane.export.as_ref().ok_or(ResourceError::NoResourcePlane)
773}
774
775async fn handle_list(plane: &ResourcePlane, method: &str) -> ResourceResponse {
776 let generation = plane.generation();
777 let class = plane.containment_achieved;
778
779 let export = match servable_export(plane, method) {
780 Ok(export) => export.clone(),
781 Err(error) => return refuse_list(plane, "", &error, generation, class).await,
784 };
785
786 let listed = {
787 let export = export.clone();
788 let policy = symlink_policy(class);
789 tokio::task::spawn_blocking(move || list_export_files(&export, policy))
790 .await
791 .unwrap_or_else(|join| Err(ResourceError::IoError(join.to_string())))
792 };
793
794 let entries = match listed {
795 Ok(entries) => entries,
796 Err(error) => {
797 return refuse_list(plane, &export.declared_root, &error, generation, class).await
798 }
799 };
800
801 if let Some(trace) = &plane.trace {
802 trace
803 .write_resource_list(
804 &export.declared_root,
805 entries.len(),
806 entries.iter().map(|entry| entry.size_bytes).sum(),
807 generation,
808 class,
809 "ok",
810 None,
811 )
812 .await;
813 }
814
815 let body = ListResponse {
816 root: export.declared_root.clone(),
817 mode: export.mode,
818 max_bytes: export.max_bytes,
819 generation,
820 containment_achieved: class,
821 entries,
822 };
823 ResourceResponse::framed(
824 200,
825 vec![
826 ("content-type".to_string(), "application/json".to_string()),
827 ("x-murmur-generation".to_string(), generation.to_string()),
828 ("x-murmur-containment".to_string(), class.to_string()),
829 ("x-murmur-export-root".to_string(), export.declared_root),
830 ],
831 serde_json::to_vec(&body).unwrap_or_default(),
832 )
833}
834
835async fn handle_read(plane: &ResourcePlane, method: &str, relpath: &str) -> ResourceResponse {
836 let generation = plane.generation();
837 let class = plane.containment_achieved;
838 let traced_path = decoded_request_path(relpath);
842
843 let export = match servable_export(plane, method) {
844 Ok(export) => export.clone(),
845 Err(error) => return refuse_read(plane, &traced_path, &error, generation, class).await,
846 };
847
848 let read = {
849 let export = export.clone();
850 let policy = symlink_policy(class);
851 let relpath = relpath.to_string();
852 tokio::task::spawn_blocking(move || read_export_file_with_policy(&export, &relpath, policy))
853 .await
854 .unwrap_or_else(|join| Err(ResourceError::IoError(join.to_string())))
855 };
856
857 let response = match read {
858 Ok(response) => response,
859 Err(error) => return refuse_read(plane, &traced_path, &error, generation, class).await,
860 };
861
862 if let Some(trace) = &plane.trace {
863 trace
864 .write_resource_read(
865 &traced_path,
866 "ok",
867 Some(response.bytes.len() as u64),
868 Some(response.sha256.clone()),
869 generation,
870 class,
871 None,
872 )
873 .await;
874 }
875
876 ResourceResponse::framed(
877 200,
878 vec![
879 (
880 "content-type".to_string(),
881 "application/octet-stream".to_string(),
882 ),
883 (
884 "etag".to_string(),
885 format!("\"sha256:{}\"", response.sha256),
886 ),
887 (
888 "x-murmur-mtime-ms".to_string(),
889 response.mtime_ms.to_string(),
890 ),
891 ("x-murmur-generation".to_string(), generation.to_string()),
892 ("x-murmur-containment".to_string(), class.to_string()),
893 ("x-murmur-export-root".to_string(), export.declared_root),
894 ],
895 response.bytes,
896 )
897}
898
899async fn refuse_list(
900 plane: &ResourcePlane,
901 root: &str,
902 error: &ResourceError,
903 generation: u64,
904 class: ContainmentClass,
905) -> ResourceResponse {
906 if let Some(trace) = &plane.trace {
907 trace
908 .write_resource_list(
909 root,
910 0,
911 0,
912 generation,
913 class,
914 error.code(),
915 Some(error.message()),
916 )
917 .await;
918 }
919 error_response(error, Some(generation))
920}
921
922async fn refuse_read(
923 plane: &ResourcePlane,
924 path: &str,
925 error: &ResourceError,
926 generation: u64,
927 class: ContainmentClass,
928) -> ResourceResponse {
929 if let Some(trace) = &plane.trace {
930 trace
931 .write_resource_read(
932 path,
933 error.code(),
934 None,
935 None,
936 generation,
937 class,
938 Some(error.message()),
939 )
940 .await;
941 }
942 error_response(error, Some(generation))
943}
944
945fn decoded_request_path(raw: &str) -> String {
948 String::from_utf8_lossy(&percent_decode(raw)).into_owned()
949}
950
951fn error_response(error: &ResourceError, generation: Option<u64>) -> ResourceResponse {
952 let body = serde_json::json!({"error": error.code(), "message": error.message()});
953 let mut headers = vec![("content-type".to_string(), "application/json".to_string())];
954 if let Some(generation) = generation {
955 headers.push(("x-murmur-generation".to_string(), generation.to_string()));
956 }
957 if matches!(error, ResourceError::MethodNotAllowed) {
958 headers.push(("allow".to_string(), "GET".to_string()));
959 }
960 ResourceResponse::framed(
961 error.status(),
962 headers,
963 serde_json::to_vec(&body).unwrap_or_default(),
964 )
965}
966
967pub fn reason_phrase(status: u16) -> &'static str {
970 match status {
971 200 => "OK",
972 400 => "Bad Request",
973 403 => "Forbidden",
974 404 => "Not Found",
975 405 => "Method Not Allowed",
976 410 => "Gone",
977 413 => "Payload Too Large",
978 _ => "Internal Server Error",
979 }
980}
981
982#[cfg(test)]
983mod tests {
984 use super::*;
985 use std::io::Write;
986
987 fn export_for(root: &Path, max_bytes: u64) -> DeclaredExport {
988 DeclaredExport {
989 declared_root: "out/".to_string(),
990 root: root.to_path_buf(),
991 mode: ExportMode::ReadOnly,
992 max_bytes,
993 }
994 }
995
996 #[test]
999 fn percent_decoding_happens_before_validation() {
1000 assert_eq!(
1003 export_relpath_components("%2e%2e%2fsecret.txt"),
1004 Err(ResourceError::OutsideRoot)
1005 );
1006 assert_eq!(
1007 export_relpath_components("%2E%2E/secret.txt"),
1008 Err(ResourceError::OutsideRoot)
1009 );
1010 }
1011
1012 #[test]
1013 fn percent_decoding_accepts_ordinary_escapes() {
1014 assert_eq!(
1015 export_relpath_components("sub%20dir/report.md").unwrap(),
1016 vec!["sub dir".to_string(), "report.md".to_string()]
1017 );
1018 }
1019
1020 #[test]
1021 fn a_lone_percent_is_left_as_written() {
1022 assert_eq!(percent_decode("100%"), b"100%".to_vec());
1023 assert_eq!(percent_decode("%zz"), b"%zz".to_vec());
1024 }
1025
1026 #[test]
1027 fn every_escaping_shape_is_refused() {
1028 for path in [
1029 "",
1030 "..",
1031 "../secret.txt",
1032 "out/../../secret.txt",
1033 "/etc/passwd",
1034 "/",
1035 "./report.md",
1036 "a//b",
1037 "a/./b",
1038 "a/../b",
1039 "report.md%00.txt",
1040 "%00",
1041 ] {
1042 assert_eq!(
1043 export_relpath_components(path),
1044 Err(ResourceError::OutsideRoot),
1045 "path {path:?} must be refused"
1046 );
1047 }
1048 }
1049
1050 #[test]
1051 fn a_trailing_slash_names_the_same_file() {
1052 assert_eq!(
1053 export_relpath_components("dir/report.md/").unwrap(),
1054 vec!["dir".to_string(), "report.md".to_string()]
1055 );
1056 }
1057
1058 #[test]
1059 fn ordinary_relative_paths_survive() {
1060 assert_eq!(
1061 export_relpath_components("a/b/c.txt").unwrap(),
1062 vec!["a".to_string(), "b".to_string(), "c.txt".to_string()]
1063 );
1064 }
1065
1066 #[test]
1069 fn symlink_policy_covers_every_containment_class() {
1070 assert_eq!(
1071 symlink_policy(ContainmentClass::Scoped),
1072 SymlinkPolicy::Refuse
1073 );
1074 assert_eq!(
1075 symlink_policy(ContainmentClass::Sealed),
1076 SymlinkPolicy::FollowWithinRoot
1077 );
1078 assert_eq!(
1079 symlink_policy(ContainmentClass::Advisory),
1080 SymlinkPolicy::FollowWithinRoot
1081 );
1082 }
1083
1084 #[test]
1085 fn an_escaping_symlink_is_refused_at_every_class() {
1086 let dir = tempfile::tempdir().unwrap();
1087 let secret = dir.path().join("secret.txt");
1088 std::fs::write(&secret, b"top secret").unwrap();
1089 let root = dir.path().join("out");
1090 std::fs::create_dir(&root).unwrap();
1091 std::os::unix::fs::symlink(&secret, root.join("escape.txt")).unwrap();
1092 let export = export_for(&root, 1024);
1093
1094 for class in [
1095 ContainmentClass::Advisory,
1096 ContainmentClass::Scoped,
1097 ContainmentClass::Sealed,
1098 ] {
1099 let error = read_export_file_with_policy(&export, "escape.txt", symlink_policy(class))
1100 .expect_err("an escaping symlink must never be served");
1101 let expected = match class {
1102 ContainmentClass::Scoped => ResourceError::SymlinkRefused,
1103 _ => ResourceError::OutsideRoot,
1104 };
1105 assert_eq!(error, expected, "class {class}");
1106
1107 let entries = list_export_files(&export, symlink_policy(class)).unwrap();
1108 assert!(
1109 entries.is_empty(),
1110 "class {class}: an escaping symlink must not be listed; got {entries:?}"
1111 );
1112 }
1113 }
1114
1115 #[test]
1116 fn an_in_root_symlink_is_refused_under_scoped_and_followed_otherwise() {
1117 let dir = tempfile::tempdir().unwrap();
1118 let root = dir.path().join("out");
1119 std::fs::create_dir(&root).unwrap();
1120 std::fs::write(root.join("real.txt"), b"real bytes").unwrap();
1121 std::os::unix::fs::symlink("real.txt", root.join("alias.txt")).unwrap();
1122 let export = export_for(&root, 1024);
1123
1124 assert_eq!(
1125 read_export_file_with_policy(&export, "alias.txt", SymlinkPolicy::Refuse),
1126 Err(ResourceError::SymlinkRefused)
1127 );
1128 assert_eq!(
1129 list_export_files(&export, SymlinkPolicy::Refuse)
1130 .unwrap()
1131 .iter()
1132 .map(|entry| entry.path.clone())
1133 .collect::<Vec<_>>(),
1134 vec!["real.txt".to_string()]
1135 );
1136
1137 let followed =
1138 read_export_file_with_policy(&export, "alias.txt", SymlinkPolicy::FollowWithinRoot)
1139 .unwrap();
1140 assert_eq!(followed.bytes, b"real bytes");
1141 assert_eq!(
1142 list_export_files(&export, SymlinkPolicy::FollowWithinRoot)
1143 .unwrap()
1144 .len(),
1145 2
1146 );
1147 }
1148
1149 #[test]
1150 fn a_symlinked_directory_on_the_path_is_refused_under_scoped() {
1151 let dir = tempfile::tempdir().unwrap();
1152 let root = dir.path().join("out");
1153 std::fs::create_dir_all(root.join("real")).unwrap();
1154 std::fs::write(root.join("real/report.md"), b"hello").unwrap();
1155 std::os::unix::fs::symlink("real", root.join("alias")).unwrap();
1156 let export = export_for(&root, 1024);
1157
1158 assert_eq!(
1159 read_export_file_with_policy(&export, "alias/report.md", SymlinkPolicy::Refuse),
1160 Err(ResourceError::SymlinkRefused)
1161 );
1162 }
1163
1164 #[test]
1167 fn a_read_hashes_the_bytes_it_serves() {
1168 let dir = tempfile::tempdir().unwrap();
1169 let root = dir.path().join("out");
1170 std::fs::create_dir(&root).unwrap();
1171 std::fs::write(root.join("report.md"), b"# report\n").unwrap();
1172 let response = read_export_file_with_policy(
1173 &export_for(&root, 1024),
1174 "report.md",
1175 SymlinkPolicy::FollowWithinRoot,
1176 )
1177 .unwrap();
1178 assert_eq!(response.bytes, b"# report\n");
1179 assert_eq!(response.sha256, murmur_artifact::sha256_hex(b"# report\n"));
1180 assert!(response.mtime_ms > 0);
1181 }
1182
1183 #[test]
1184 fn max_bytes_refuses_the_read_but_not_the_listing() {
1185 let dir = tempfile::tempdir().unwrap();
1186 let root = dir.path().join("out");
1187 std::fs::create_dir(&root).unwrap();
1188 std::fs::write(root.join("small.txt"), vec![b'a'; 100]).unwrap();
1189 std::fs::write(root.join("big.bin"), vec![b'b'; 4096]).unwrap();
1190 let export = export_for(&root, 1024);
1191
1192 assert_eq!(
1193 read_export_file_with_policy(&export, "big.bin", SymlinkPolicy::FollowWithinRoot),
1194 Err(ResourceError::TooLarge { max_bytes: 1024 })
1195 );
1196 assert_eq!(
1197 read_export_file_with_policy(&export, "small.txt", SymlinkPolicy::FollowWithinRoot)
1198 .unwrap()
1199 .bytes
1200 .len(),
1201 100
1202 );
1203
1204 let entries = list_export_files(&export, SymlinkPolicy::FollowWithinRoot).unwrap();
1205 let big = entries.iter().find(|e| e.path == "big.bin").unwrap();
1206 assert_eq!(
1207 big.size_bytes, 4096,
1208 "discovery must not hide an oversized file"
1209 );
1210 }
1211
1212 #[test]
1213 fn a_directory_is_not_a_regular_file() {
1214 let dir = tempfile::tempdir().unwrap();
1215 let root = dir.path().join("out");
1216 std::fs::create_dir_all(root.join("nested")).unwrap();
1217 assert_eq!(
1218 read_export_file_with_policy(
1219 &export_for(&root, 1024),
1220 "nested",
1221 SymlinkPolicy::FollowWithinRoot
1222 ),
1223 Err(ResourceError::NotARegularFile)
1224 );
1225 }
1226
1227 #[test]
1228 fn a_missing_root_lists_empty_and_reads_not_found() {
1229 let dir = tempfile::tempdir().unwrap();
1230 let root = dir.path().join("out");
1231 let export = export_for(&root, 1024);
1232 assert_eq!(
1233 list_export_files(&export, SymlinkPolicy::FollowWithinRoot).unwrap(),
1234 Vec::new()
1235 );
1236 assert_eq!(
1237 read_export_file_with_policy(&export, "report.md", SymlinkPolicy::FollowWithinRoot),
1238 Err(ResourceError::NotFound)
1239 );
1240 }
1241
1242 #[test]
1243 fn a_listing_is_recursive_and_sorted() {
1244 let dir = tempfile::tempdir().unwrap();
1245 let root = dir.path().join("out");
1246 std::fs::create_dir_all(root.join("b/c")).unwrap();
1247 std::fs::write(root.join("z.txt"), b"z").unwrap();
1248 std::fs::write(root.join("b/y.txt"), b"y").unwrap();
1249 std::fs::write(root.join("b/c/x.txt"), b"x").unwrap();
1250 let entries = list_export_files(&export_for(&root, 1024), SymlinkPolicy::Refuse).unwrap();
1251 assert_eq!(
1252 entries
1253 .iter()
1254 .map(|entry| entry.path.clone())
1255 .collect::<Vec<_>>(),
1256 vec![
1257 "b/c/x.txt".to_string(),
1258 "b/y.txt".to_string(),
1259 "z.txt".to_string()
1260 ]
1261 );
1262 assert_eq!(entries[2].sha256, murmur_artifact::sha256_hex(b"z"));
1263 }
1264
1265 #[test]
1266 fn a_fifo_is_refused_without_blocking() {
1267 let dir = tempfile::tempdir().unwrap();
1268 let root = dir.path().join("out");
1269 std::fs::create_dir(&root).unwrap();
1270 let fifo = root.join("pipe");
1271 let status = std::process::Command::new("mkfifo")
1272 .arg(&fifo)
1273 .status()
1274 .expect("mkfifo should be runnable");
1275 if !status.success() {
1276 return;
1277 }
1278 assert_eq!(
1279 read_export_file_with_policy(
1280 &export_for(&root, 1024),
1281 "pipe",
1282 SymlinkPolicy::FollowWithinRoot
1283 ),
1284 Err(ResourceError::NotARegularFile)
1285 );
1286 assert!(
1287 list_export_files(&export_for(&root, 1024), SymlinkPolicy::Refuse)
1288 .unwrap()
1289 .is_empty()
1290 );
1291 }
1292
1293 #[test]
1296 fn every_error_maps_to_its_documented_status() {
1297 for (error, code, status) in [
1298 (ResourceError::NoResourcePlane, "no_resource_plane", 404),
1299 (ResourceError::NotFound, "not_found", 404),
1300 (ResourceError::OutsideRoot, "outside_root", 403),
1301 (ResourceError::SymlinkRefused, "symlink_refused", 403),
1302 (ResourceError::NotARegularFile, "not_a_regular_file", 403),
1303 (ResourceError::TooLarge { max_bytes: 1 }, "too_large", 413),
1304 (ResourceError::MethodNotAllowed, "method_not_allowed", 405),
1305 (ResourceError::IoError("x".into()), "io_error", 500),
1306 ] {
1307 assert_eq!(error.code(), code);
1308 assert_eq!(error.status(), status);
1309 }
1310 }
1311
1312 fn file_export(root: &str) -> FileExport {
1315 FileExport {
1316 root: root.to_string(),
1317 mode: ExportMode::ReadOnly,
1318 max_bytes: 1024,
1319 }
1320 }
1321
1322 #[test]
1325 fn a_root_that_already_escapes_the_workdir_refuses_the_launch() {
1326 let workdir = tempfile::tempdir().unwrap();
1327 let outside = tempfile::tempdir().unwrap();
1328 std::os::unix::fs::symlink(outside.path(), workdir.path().join("out")).unwrap();
1329
1330 let error = check_export_root(workdir.path(), &file_export("out/")).unwrap_err();
1331 let RuntimeError::ExportRootOutsideWorkdir {
1332 declared, resolved, ..
1333 } = &error
1334 else {
1335 panic!("expected ExportRootOutsideWorkdir, got {error:?}");
1336 };
1337 assert_eq!(declared, "out/");
1340 assert_eq!(
1341 Path::new(resolved),
1342 std::fs::canonicalize(outside.path()).unwrap()
1343 );
1344 }
1345
1346 #[test]
1349 fn a_root_that_does_not_exist_yet_is_accepted() {
1350 let workdir = tempfile::tempdir().unwrap();
1351 assert!(check_export_root(workdir.path(), &file_export("out/")).is_ok());
1352
1353 std::fs::create_dir(workdir.path().join("out")).unwrap();
1354 assert!(check_export_root(workdir.path(), &file_export("out/")).is_ok());
1355 }
1356
1357 #[test]
1360 fn a_workdir_that_does_not_exist_yet_is_accepted() {
1361 let parent = tempfile::tempdir().unwrap();
1362 let missing = parent.path().join("not-created-yet");
1363 assert!(check_export_root(&missing, &file_export("out/")).is_ok());
1364 }
1365
1366 #[test]
1369 fn a_root_symlinked_within_the_workdir_is_accepted() {
1370 let workdir = tempfile::tempdir().unwrap();
1371 std::fs::create_dir(workdir.path().join("real")).unwrap();
1372 std::os::unix::fs::symlink(workdir.path().join("real"), workdir.path().join("out"))
1373 .unwrap();
1374
1375 assert!(check_export_root(workdir.path(), &file_export("out/")).is_ok());
1376 }
1377
1378 fn plane_for(export: Option<DeclaredExport>, class: ContainmentClass) -> ResourcePlane {
1381 ResourcePlane::with_export(export, class, Arc::new(AtomicU64::new(0)), None)
1382 }
1383
1384 #[tokio::test]
1385 async fn an_undeclared_plane_denies_both_verbs() {
1386 let plane = plane_for(None, ContainmentClass::Advisory);
1387 for path in ["/resources/files", "/resources/files/report.md"] {
1388 let response = handle_resource_request(&plane, "GET", path).await;
1389 assert_eq!(response.status, 404);
1390 let body: serde_json::Value = serde_json::from_slice(&response.body).unwrap();
1391 assert_eq!(body["error"], "no_resource_plane");
1392 }
1393 }
1394
1395 #[tokio::test]
1396 async fn every_write_verb_is_refused_with_an_allow_header() {
1397 let dir = tempfile::tempdir().unwrap();
1398 let root = dir.path().join("out");
1399 std::fs::create_dir(&root).unwrap();
1400 std::fs::write(root.join("report.md"), b"hello").unwrap();
1401 let plane = plane_for(Some(export_for(&root, 1024)), ContainmentClass::Advisory);
1402
1403 for method in ["POST", "PUT", "PATCH", "DELETE"] {
1404 let response =
1405 handle_resource_request(&plane, method, "/resources/files/report.md").await;
1406 assert_eq!(response.status, 405, "{method}");
1407 assert!(response
1408 .headers
1409 .iter()
1410 .any(|(name, value)| name == "allow" && value == "GET"));
1411 }
1412 assert_eq!(
1413 std::fs::read(root.join("report.md")).unwrap(),
1414 b"hello".to_vec()
1415 );
1416 assert!(!root.join("new.txt").exists());
1417 }
1418
1419 #[tokio::test]
1420 async fn a_read_carries_its_validator_and_provenance() {
1421 let dir = tempfile::tempdir().unwrap();
1422 let root = dir.path().join("out");
1423 std::fs::create_dir(&root).unwrap();
1424 let mut file = std::fs::File::create(root.join("report.md")).unwrap();
1425 file.write_all(b"# report\n").unwrap();
1426 drop(file);
1427
1428 let generation = Arc::new(AtomicU64::new(7));
1429 let plane = ResourcePlane::with_export(
1430 Some(export_for(&root, 1024)),
1431 ContainmentClass::Scoped,
1432 Arc::clone(&generation),
1433 None,
1434 );
1435 let response = handle_resource_request(&plane, "GET", "/resources/files/report.md").await;
1436 assert_eq!(response.status, 200);
1437 assert_eq!(response.body, b"# report\n");
1438 let header = |name: &str| {
1439 response
1440 .headers
1441 .iter()
1442 .find(|(key, _)| key == name)
1443 .map(|(_, value)| value.clone())
1444 .unwrap_or_default()
1445 };
1446 assert_eq!(
1447 header("etag"),
1448 format!("\"sha256:{}\"", murmur_artifact::sha256_hex(b"# report\n"))
1449 );
1450 assert_eq!(header("x-murmur-generation"), "7");
1451 assert_eq!(header("x-murmur-containment"), "scoped");
1452 assert_eq!(header("x-murmur-export-root"), "out/");
1453 }
1454
1455 #[tokio::test]
1456 async fn a_query_string_does_not_select_a_generation() {
1457 let dir = tempfile::tempdir().unwrap();
1458 let root = dir.path().join("out");
1459 std::fs::create_dir(&root).unwrap();
1460 std::fs::write(root.join("report.md"), b"now").unwrap();
1461 let plane = ResourcePlane::with_export(
1462 Some(export_for(&root, 1024)),
1463 ContainmentClass::Advisory,
1464 Arc::new(AtomicU64::new(3)),
1465 None,
1466 );
1467 let response =
1468 handle_resource_request(&plane, "GET", "/resources/files/report.md?generation=1").await;
1469 assert_eq!(response.status, 200);
1470 assert_eq!(response.body, b"now");
1471 }
1472
1473 #[tokio::test]
1474 async fn a_list_reports_the_declared_block_verbatim() {
1475 let dir = tempfile::tempdir().unwrap();
1476 let root = dir.path().join("out");
1477 std::fs::create_dir(&root).unwrap();
1478 std::fs::write(root.join("report.md"), b"hello").unwrap();
1479 let plane = plane_for(Some(export_for(&root, 4096)), ContainmentClass::Advisory);
1480 let response = handle_resource_request(&plane, "GET", "/resources/files").await;
1481 assert_eq!(response.status, 200);
1482 let body: serde_json::Value = serde_json::from_slice(&response.body).unwrap();
1483 assert_eq!(body["root"], "out/");
1484 assert_eq!(body["mode"], "read-only");
1485 assert_eq!(body["max_bytes"], 4096);
1486 assert_eq!(body["generation"], 0);
1487 assert_eq!(body["containment_achieved"], "advisory");
1488 assert_eq!(body["entries"][0]["path"], "report.md");
1489 assert_eq!(body["entries"][0]["size_bytes"], 5);
1490 }
1491
1492 #[tokio::test]
1493 async fn an_unknown_route_under_the_prefix_is_not_found() {
1494 let plane = plane_for(None, ContainmentClass::Advisory);
1495 let response = handle_resource_request(&plane, "GET", "/resources/secrets").await;
1496 assert_eq!(response.status, 404);
1497 let body: serde_json::Value = serde_json::from_slice(&response.body).unwrap();
1498 assert_eq!(body["error"], "not_found");
1499 }
1500
1501 #[tokio::test]
1503 async fn an_unknown_route_still_answers_the_method_first() {
1504 let plane = plane_for(None, ContainmentClass::Advisory);
1505 let response = handle_resource_request(&plane, "PUT", "/resources/secrets").await;
1506 assert_eq!(response.status, 405);
1507 assert!(response
1508 .headers
1509 .iter()
1510 .any(|(name, value)| name == "allow" && value == "GET"));
1511 }
1512
1513 #[tokio::test]
1516 async fn every_response_carries_its_own_content_length() {
1517 let dir = tempfile::tempdir().unwrap();
1518 let root = dir.path().join("out");
1519 std::fs::create_dir(&root).unwrap();
1520 std::fs::write(root.join("report.md"), b"hello").unwrap();
1521 let plane = plane_for(Some(export_for(&root, 1024)), ContainmentClass::Advisory);
1522
1523 for (method, path) in [
1524 ("GET", "/resources/files"),
1525 ("GET", "/resources/files/report.md"),
1526 ("GET", "/resources/files/../secret.txt"),
1527 ("PUT", "/resources/files/report.md"),
1528 ] {
1529 let response = handle_resource_request(&plane, method, path).await;
1530 let declared = response
1531 .headers
1532 .iter()
1533 .find(|(name, _)| name == "content-length")
1534 .map(|(_, value)| value.clone())
1535 .unwrap_or_else(|| panic!("{method} {path} must declare a content-length"));
1536 assert_eq!(
1537 declared,
1538 response.body.len().to_string(),
1539 "{method} {path}: content-length must match the body served"
1540 );
1541 }
1542 }
1543}