1use std::sync::Arc;
7
8use crate::mac_pep::NamespaceAction;
9#[cfg(not(target_arch = "wasm32"))]
10use crate::mac_pep::NamespacePep;
11use crate::mount::{DirEntry, Fid, Mount, MountError, Stat, OWRITE};
12use hyprstream_rpc::Subject;
13
14#[derive(Debug)]
20pub enum NamespaceError {
21 Mount(MountError),
22 ReservedPath(String),
23 Denied(NamespaceAction, String),
30}
31
32impl std::fmt::Display for NamespaceError {
33 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34 match self {
35 Self::Mount(e) => write!(f, "{e}"),
36 Self::ReservedPath(p) => write!(f, "reserved path: {p}"),
37 Self::Denied(action, detail) => {
38 write!(f, "MAC denied {action:?}: {detail}")
39 }
40 }
41 }
42}
43
44impl std::error::Error for NamespaceError {}
45
46impl From<MountError> for NamespaceError {
47 fn from(e: MountError) -> Self {
48 Self::Mount(e)
49 }
50}
51
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum BindFlag {
55 Replace,
57 Before,
59 After,
61 Upper,
67}
68
69pub type MountTarget = Arc<dyn Mount>;
71
72#[derive(Clone)]
75pub struct ReadMountTarget(MountTarget);
76
77impl ReadMountTarget {
78 pub async fn walk(&self, components: &[&str], caller: &Subject) -> Result<Fid, MountError> {
79 self.0.walk(components, caller).await
80 }
81
82 pub async fn open(&self, fid: &mut Fid, mode: u8, caller: &Subject) -> Result<(), MountError> {
83 if mode != 0 {
84 return Err(MountError::PermissionDenied(
85 "read-only namespace target".into(),
86 ));
87 }
88 self.0.open(fid, mode, caller).await
89 }
90
91 pub async fn read(
92 &self,
93 fid: &Fid,
94 offset: u64,
95 count: u32,
96 caller: &Subject,
97 ) -> Result<Vec<u8>, MountError> {
98 self.0.read(fid, offset, count, caller).await
99 }
100
101 pub async fn readdir(&self, fid: &Fid, caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
102 self.0.readdir(fid, caller).await
103 }
104
105 pub async fn stat(&self, fid: &Fid, caller: &Subject) -> Result<Stat, MountError> {
106 self.0.stat(fid, caller).await
107 }
108
109 pub async fn clunk(&self, fid: Fid, caller: &Subject) {
110 self.0.clunk(fid, caller).await;
111 }
112}
113
114struct MountEntry {
115 prefix: String,
116 targets: Vec<MountTarget>,
117 upper: Option<MountTarget>,
122}
123
124const MAX_READ_SIZE: usize = 16 * 1024 * 1024;
130
131pub struct Namespace {
147 mounts: Vec<MountEntry>,
148 #[cfg(not(target_arch = "wasm32"))]
151 pep: Option<Arc<NamespacePep>>,
152}
153
154impl Namespace {
155 pub fn new() -> Self {
161 Self {
162 mounts: Vec::new(),
163 #[cfg(not(target_arch = "wasm32"))]
164 pep: None,
165 }
166 }
167
168 #[cfg(not(target_arch = "wasm32"))]
178 pub fn set_pep(&mut self, pep: Arc<NamespacePep>) -> Option<Arc<NamespacePep>> {
179 self.pep.replace(pep)
180 }
181
182 #[cfg(not(target_arch = "wasm32"))]
184 pub fn pep_armed(&self) -> bool {
185 self.pep.is_some()
186 }
187
188 #[cfg(target_arch = "wasm32")]
190 pub const fn pep_armed(&self) -> bool {
191 false
192 }
193
194 #[cfg(not(target_arch = "wasm32"))]
199 async fn enforce(
200 &self,
201 subject: &Subject,
202 path: &str,
203 action: NamespaceAction,
204 ) -> Result<(), NamespaceError> {
205 let Some(pep) = &self.pep else {
206 return Ok(());
207 };
208 let normalized = normalize_path(path);
213 pep.authorize(subject, &normalized, action).await
214 }
215
216 #[cfg(target_arch = "wasm32")]
217 async fn enforce(
218 &self,
219 _subject: &Subject,
220 _path: &str,
221 _action: NamespaceAction,
222 ) -> Result<(), NamespaceError> {
223 Ok(())
226 }
227
228 pub fn mount(&mut self, prefix: &str, target: MountTarget) -> Result<(), NamespaceError> {
235 self.bind_mount(prefix, target, BindFlag::Replace)
236 }
237
238 pub async fn mount_as(
240 &mut self,
241 prefix: &str,
242 target: MountTarget,
243 subject: &Subject,
244 ) -> Result<(), NamespaceError> {
245 self.enforce(subject, prefix, NamespaceAction::Mount)
246 .await?;
247 self.bind_mount_inner(prefix, target, BindFlag::Replace)
248 }
249
250 pub fn bind_mount(
262 &mut self,
263 prefix: &str,
264 target: MountTarget,
265 flag: BindFlag,
266 ) -> Result<(), NamespaceError> {
267 #[cfg(not(target_arch = "wasm32"))]
268 if let Some(pep) = &self.pep {
269 let normalized = normalize_path(prefix);
274 return Err(pep.deny_uncredentialed(&normalized, NamespaceAction::BindMount));
275 }
276 self.bind_mount_inner(prefix, target, flag)
277 }
278
279 pub async fn bind_mount_as(
281 &mut self,
282 prefix: &str,
283 target: MountTarget,
284 flag: BindFlag,
285 subject: &Subject,
286 ) -> Result<(), NamespaceError> {
287 self.enforce(subject, prefix, NamespaceAction::BindMount)
288 .await?;
289 self.bind_mount_inner(prefix, target, flag)
290 }
291
292 fn bind_mount_inner(
296 &mut self,
297 prefix: &str,
298 target: MountTarget,
299 flag: BindFlag,
300 ) -> Result<(), NamespaceError> {
301 let prefix = normalize_prefix(prefix);
302
303 match flag {
304 BindFlag::Replace => {
305 self.mounts.retain(|m| m.prefix != prefix);
306 self.mounts.push(MountEntry {
307 prefix,
308 targets: vec![target],
309 upper: None,
310 });
311 }
312 BindFlag::Before => {
313 if let Some(entry) = self.mounts.iter_mut().find(|m| m.prefix == prefix) {
314 entry.targets.insert(0, target);
315 } else {
316 self.mounts.push(MountEntry {
317 prefix,
318 targets: vec![target],
319 upper: None,
320 });
321 }
322 }
323 BindFlag::After => {
324 if let Some(entry) = self.mounts.iter_mut().find(|m| m.prefix == prefix) {
325 entry.targets.push(target);
326 } else {
327 self.mounts.push(MountEntry {
328 prefix,
329 targets: vec![target],
330 upper: None,
331 });
332 }
333 }
334 BindFlag::Upper => {
335 if let Some(entry) = self.mounts.iter_mut().find(|m| m.prefix == prefix) {
342 entry.targets.insert(0, Arc::clone(&target));
343 entry.upper = Some(target);
344 } else {
345 self.mounts.push(MountEntry {
346 prefix,
347 targets: vec![Arc::clone(&target)],
348 upper: Some(target),
349 });
350 }
351 }
352 }
353 self.mounts
355 .sort_by_key(|b| std::cmp::Reverse(b.prefix.len()));
356 Ok(())
357 }
358
359 pub fn unmount(&mut self, prefix: &str) -> Result<(), NamespaceError> {
364 #[cfg(not(target_arch = "wasm32"))]
365 if let Some(pep) = &self.pep {
366 let normalized = normalize_path(prefix);
367 return Err(pep.deny_uncredentialed(&normalized, NamespaceAction::Unmount));
368 }
369 let prefix = normalize_prefix(prefix);
370 self.mounts.retain(|m| m.prefix != prefix);
371 Ok(())
372 }
373
374 pub async fn unmount_as(
376 &mut self,
377 prefix: &str,
378 subject: &Subject,
379 ) -> Result<(), NamespaceError> {
380 self.enforce(subject, prefix, NamespaceAction::Unmount)
381 .await?;
382 let prefix = normalize_prefix(prefix);
383 self.mounts.retain(|m| m.prefix != prefix);
384 Ok(())
385 }
386
387 pub fn fork(&self) -> Namespace {
394 Namespace {
395 #[cfg(not(target_arch = "wasm32"))]
396 pep: self.pep.clone(),
397 mounts: self
398 .mounts
399 .iter()
400 .map(|m| MountEntry {
401 prefix: m.prefix.clone(),
402 targets: m.targets.iter().map(Arc::clone).collect(),
403 upper: m.upper.as_ref().map(Arc::clone),
404 })
405 .collect(),
406 }
407 }
408
409 pub fn mount_prefixes(&self) -> Vec<&str> {
411 self.mounts.iter().map(|m| m.prefix.as_str()).collect()
412 }
413
414 pub fn has_designated_upper(&self, prefix: &str) -> bool {
423 let prefix = normalize_prefix(prefix);
424 self.mounts
425 .iter()
426 .find(|m| m.prefix == prefix)
427 .is_some_and(|m| m.upper.is_some())
428 }
429
430 pub async fn cat(&self, path: &str, caller: &Subject) -> Result<Vec<u8>, NamespaceError> {
437 self.enforce(caller, path, NamespaceAction::Read).await?;
438 let (targets, remainder) = self.resolve(path)?;
439 let components: Vec<&str> = split_path(&remainder);
440 let mut last_err = None;
441 for mount in targets {
442 let result: Result<Vec<u8>, MountError> = async {
443 let mut fid = mount.walk(&components, caller).await?;
444 if let Err(e) = mount.open(&mut fid, 0, caller).await {
445 mount.clunk(fid, caller).await;
446 return Err(e);
447 }
448 let mut data = Vec::new();
449 loop {
450 match mount.read(&fid, data.len() as u64, 64 * 1024, caller).await {
451 Ok(chunk) if chunk.is_empty() => break,
452 Ok(chunk) => {
453 data.extend_from_slice(&chunk);
454 if data.len() >= MAX_READ_SIZE {
455 break;
456 }
457 }
458 Err(e) => {
459 mount.clunk(fid, caller).await;
460 return Err(e);
461 }
462 }
463 }
464 mount.clunk(fid, caller).await;
465 Ok(data)
466 }
467 .await;
468 match result {
469 Ok(data) => return Ok(data),
470 Err(e) => {
471 last_err = Some(e);
472 }
473 }
474 }
475 Err(NamespaceError::Mount(
476 last_err.unwrap_or_else(|| MountError::NotFound(path.to_owned())),
477 ))
478 }
479
480 pub async fn read_one(&self, path: &str, caller: &Subject) -> Result<Vec<u8>, NamespaceError> {
485 self.enforce(caller, path, NamespaceAction::Read).await?;
486 let (targets, remainder) = self.resolve(path)?;
487 let components: Vec<&str> = split_path(&remainder);
488 let mut last_err = None;
489 for mount in targets {
490 let result: Result<Vec<u8>, MountError> = async {
491 let mut fid = mount.walk(&components, caller).await?;
492 if let Err(e) = mount.open(&mut fid, 0, caller).await {
493 mount.clunk(fid, caller).await;
494 return Err(e);
495 }
496 let chunk = mount.read(&fid, 0, 64 * 1024, caller).await;
497 mount.clunk(fid, caller).await;
498 chunk
499 }
500 .await;
501 match result {
502 Ok(data) => return Ok(data),
503 Err(e) => {
504 last_err = Some(e);
505 }
506 }
507 }
508 Err(NamespaceError::Mount(
509 last_err.unwrap_or_else(|| MountError::NotFound(path.to_owned())),
510 ))
511 }
512
513 pub async fn echo(
530 &self,
531 path: &str,
532 data: &[u8],
533 caller: &Subject,
534 ) -> Result<(), NamespaceError> {
535 self.enforce(caller, path, NamespaceAction::Write).await?;
536 let (entry, remainder) = self.resolve_entry(path)?;
537 let targets = &entry.targets[..];
538 let components: Vec<&str> = split_path(&remainder);
539 let mut last_err = None;
540
541 for mount in targets {
543 let result: Result<(), MountError> = async {
544 let mut fid = mount.walk(&components, caller).await?;
545 if let Err(e) = mount.open(&mut fid, OWRITE, caller).await {
546 mount.clunk(fid, caller).await;
547 return Err(e);
548 }
549 mount.write(&fid, 0, data, caller).await?;
550 mount.clunk(fid, caller).await;
551 Ok(())
552 }
553 .await;
554 match result {
555 Ok(()) => return Ok(()),
556 Err(MountError::NotSupported(_)) => {
557 last_err = Some(MountError::NotSupported(path.to_owned()));
561 }
562 Err(e) => {
563 last_err = Some(e);
564 }
565 }
566 }
567
568 if let Some(copied) = self
572 .copy_up(targets, entry.upper.as_ref(), &components, data, caller)
573 .await?
574 {
575 return Ok(copied);
576 }
577
578 Err(NamespaceError::Mount(
579 last_err.unwrap_or_else(|| MountError::NotFound(path.to_owned())),
580 ))
581 }
582
583 pub async fn create(
594 &self,
595 path: &str,
596 perm: u32,
597 caller: &Subject,
598 ) -> Result<Stat, NamespaceError> {
599 self.enforce(caller, path, NamespaceAction::Create).await?;
600 let (targets, remainder) = self.resolve(path)?;
601 let components: Vec<&str> = split_path(&remainder);
602 if components.is_empty() {
603 return Err(NamespaceError::Mount(MountError::InvalidArgument(
604 "create requires a non-empty path".into(),
605 )));
606 }
607 let (name, parent) = components.split_last().expect("non-empty");
608
609 let mut last_err: Option<MountError> = None;
610 for mount in targets {
611 let result: Result<Stat, MountError> = async {
612 let mut dir_fid = mount.walk(parent, caller).await?;
613 if let Err(e) = mount.open(&mut dir_fid, 0, caller).await {
616 mount.clunk(dir_fid, caller).await;
617 return Err(e);
618 }
619 let stat = mount
620 .create(&mut dir_fid, name, perm, OWRITE, caller)
621 .await?;
622 mount.clunk(dir_fid, caller).await;
623 Ok(stat)
624 }
625 .await;
626 match result {
627 Ok(stat) => return Ok(stat),
628 Err(MountError::NotSupported(_)) => {
629 last_err = Some(MountError::NotSupported(path.to_owned()));
630 }
631 Err(e) => {
632 last_err = Some(e);
633 }
634 }
635 }
636 Err(NamespaceError::Mount(
637 last_err.unwrap_or_else(|| MountError::NotFound(path.to_owned())),
638 ))
639 }
640
641 async fn copy_up(
670 &self,
671 targets: &[MountTarget],
672 upper: Option<&MountTarget>,
673 components: &[&str],
674 new_data: &[u8],
675 caller: &Subject,
676 ) -> Result<Option<()>, NamespaceError> {
677 let (name, parent) = match components.split_last() {
678 Some(split) => split,
679 None => return Ok(None),
680 };
681
682 let mut lower_bytes: Option<Vec<u8>> = None;
684 for mount in targets {
685 let result: Result<Vec<u8>, MountError> = async {
686 let mut fid = mount.walk(components, caller).await?;
687 if let Err(e) = mount.open(&mut fid, 0, caller).await {
688 mount.clunk(fid, caller).await;
689 return Err(e);
690 }
691 let mut data = Vec::new();
692 loop {
693 match mount.read(&fid, data.len() as u64, 64 * 1024, caller).await {
694 Ok(chunk) if chunk.is_empty() => break,
695 Ok(chunk) => {
696 data.extend_from_slice(&chunk);
697 if data.len() >= MAX_READ_SIZE {
698 break;
699 }
700 }
701 Err(e) => {
702 mount.clunk(fid, caller).await;
703 return Err(e);
704 }
705 }
706 }
707 mount.clunk(fid, caller).await;
708 Ok(data)
709 }
710 .await;
711 if let Ok(data) = result {
712 lower_bytes = Some(data);
713 break;
714 }
715 }
716 let Some(_lower) = lower_bytes else {
717 return Ok(None);
718 };
719
720 let create_into = |mount: &MountTarget| {
735 let mount = Arc::clone(mount);
736 let new_data = new_data.to_vec();
737 let name = name.to_string();
738 let parent: Vec<String> = parent.iter().map(|s| s.to_string()).collect();
739 async move {
740 let parent_refs: Vec<&str> = parent.iter().map(String::as_str).collect();
741 let mut dir_fid = mount.walk(&parent_refs, caller).await?;
742 if let Err(e) = mount.open(&mut dir_fid, 0, caller).await {
745 mount.clunk(dir_fid, caller).await;
746 return Err(e);
747 }
748 let _stat = mount
749 .create(&mut dir_fid, &name, 0o644, OWRITE, caller)
750 .await?;
751 mount.write(&dir_fid, 0, &new_data, caller).await?;
754 mount.clunk(dir_fid, caller).await;
755 Ok::<(), MountError>(())
756 }
757 };
758
759 if let Some(up) = upper {
760 return match create_into(up).await {
765 Ok(()) => Ok(Some(())),
766 Err(MountError::NotSupported(_)) => Ok(None),
767 Err(e) => Err(NamespaceError::Mount(e)),
768 };
769 }
770
771 for mount in targets {
772 match create_into(mount).await {
773 Ok(()) => return Ok(Some(())),
774 Err(MountError::NotSupported(_)) => continue,
775 Err(e) => return Err(NamespaceError::Mount(e)),
776 }
777 }
778 Ok(None)
780 }
781
782 pub async fn ctl(
789 &self,
790 path: &str,
791 data: &[u8],
792 caller: &Subject,
793 ) -> Result<Vec<u8>, NamespaceError> {
794 self.enforce(caller, path, NamespaceAction::Write).await?;
795 let (targets, remainder) = self.resolve(path)?;
796 let components: Vec<&str> = split_path(&remainder);
797 let mut last_err = None;
798 for mount in targets {
799 let result: Result<Vec<u8>, MountError> = async {
800 let mut fid = mount.walk(&components, caller).await?;
801 if let Err(e) = mount.open(&mut fid, 2, caller).await {
802 mount.clunk(fid, caller).await;
803 return Err(e);
804 }
805 if let Err(e) = mount.write(&fid, 0, data, caller).await {
806 mount.clunk(fid, caller).await;
807 return Err(e);
808 }
809 let mut resp = Vec::new();
810 loop {
811 match mount.read(&fid, resp.len() as u64, 64 * 1024, caller).await {
812 Ok(chunk) if chunk.is_empty() => break,
813 Ok(chunk) => {
814 resp.extend_from_slice(&chunk);
815 if resp.len() >= MAX_READ_SIZE {
816 break;
817 }
818 }
819 Err(e) => {
820 mount.clunk(fid, caller).await;
821 return Err(e);
822 }
823 }
824 }
825 mount.clunk(fid, caller).await;
826 Ok(resp)
827 }
828 .await;
829 match result {
830 Ok(resp) => return Ok(resp),
831 Err(e) => {
832 last_err = Some(e);
833 }
834 }
835 }
836 Err(NamespaceError::Mount(
837 last_err.unwrap_or_else(|| MountError::NotFound(path.to_owned())),
838 ))
839 }
840
841 pub async fn ls(&self, path: &str, caller: &Subject) -> Result<Vec<DirEntry>, NamespaceError> {
846 self.enforce(caller, path, NamespaceAction::Read).await?;
847 if path == "/" || path.is_empty() {
849 return Ok(self.root_dir_entries());
850 }
851
852 match self.resolve(path) {
853 Ok((targets, remainder)) => {
854 let components: Vec<&str> = split_path(&remainder);
855 let mut seen = std::collections::HashSet::new();
856 let mut merged = Vec::new();
857 let mut any_ok = false;
858 for mount in targets {
859 if let Ok(mut fid) = mount.walk(&components, caller).await {
860 if mount.open(&mut fid, 0, caller).await.is_ok() {
861 if let Ok(entries) = mount.readdir(&fid, caller).await {
862 any_ok = true;
863 for entry in entries {
864 if seen.insert(entry.name.clone()) {
865 merged.push(entry);
866 }
867 }
868 }
869 }
870 mount.clunk(fid, caller).await;
871 }
872 }
873 if any_ok {
874 Ok(merged)
875 } else {
876 Err(NamespaceError::Mount(MountError::NotFound(path.to_owned())))
877 }
878 }
879 Err(_) => {
880 let normalized = normalize_path(path);
884 let prefix_with_slash = format!("{}/", normalized);
885 let mut seen = std::collections::HashSet::new();
886 let mut entries = Vec::new();
887 for m in &self.mounts {
888 if let Some(rest) = m.prefix.strip_prefix(&prefix_with_slash[..]) {
889 let next = rest.split('/').next().unwrap_or("");
890 if !next.is_empty() && seen.insert(next.to_owned()) {
891 entries.push(DirEntry {
892 name: next.to_owned(),
893 is_dir: true,
894 size: 0,
895 stat: None,
896 });
897 }
898 }
899 }
900 if entries.is_empty() {
901 Err(NamespaceError::Mount(MountError::NotFound(path.to_owned())))
902 } else {
903 Ok(entries)
904 }
905 }
906 }
907 }
908
909 pub async fn resolve_targets(
934 &self,
935 path: &str,
936 caller: &Subject,
937 ) -> Result<(Vec<MountTarget>, Vec<String>), NamespaceError> {
938 self.enforce(caller, path, NamespaceAction::ResolveHandle)
939 .await?;
940 self.route_targets(path)
941 }
942
943 pub async fn resolve_read_targets(
946 &self,
947 path: &str,
948 caller: &Subject,
949 ) -> Result<(Vec<ReadMountTarget>, Vec<String>), NamespaceError> {
950 self.enforce(caller, path, NamespaceAction::Read).await?;
951 let (targets, relative) = self.route_targets(path)?;
952 Ok((targets.into_iter().map(ReadMountTarget).collect(), relative))
953 }
954
955 pub async fn authorize_read_path(
957 &self,
958 path: &str,
959 caller: &Subject,
960 ) -> Result<(), NamespaceError> {
961 self.enforce(caller, path, NamespaceAction::Read).await
962 }
963
964 pub fn resolve_targets_dormant(
972 &self,
973 path: &str,
974 caller: &Subject,
975 ) -> Result<(Vec<MountTarget>, Vec<String>), NamespaceError> {
976 if self.pep_armed() {
977 return Err(NamespaceError::Denied(
978 NamespaceAction::ResolveHandle,
979 format!(
980 "'{}': sync plane cannot revalidate subject authority",
981 caller.name().unwrap_or("<anonymous>")
982 ),
983 ));
984 }
985 self.route_targets(path)
986 }
987
988 fn route_targets(&self, path: &str) -> Result<(Vec<MountTarget>, Vec<String>), NamespaceError> {
991 let (targets, remainder) = self.resolve(path)?;
992 let components = split_path(&remainder)
993 .into_iter()
994 .map(str::to_owned)
995 .collect();
996 Ok((targets.to_vec(), components))
997 }
998
999 pub fn intermediate_children(&self, path: &str) -> Option<Vec<String>> {
1007 let normalized = normalize_path(path);
1008 if self.mounts.iter().any(|m| m.prefix == normalized) {
1010 return None;
1011 }
1012 let prefix_with_slash = if normalized == "/" {
1013 "/".to_owned()
1014 } else {
1015 format!("{normalized}/")
1016 };
1017 let mut seen = std::collections::HashSet::new();
1018 let mut names = Vec::new();
1019 for m in &self.mounts {
1020 if let Some(rest) = m.prefix.strip_prefix(&prefix_with_slash[..]) {
1021 let next = rest.split('/').next().unwrap_or("");
1022 if !next.is_empty() && seen.insert(next.to_owned()) {
1023 names.push(next.to_owned());
1024 }
1025 }
1026 }
1027 if names.is_empty() {
1028 None
1029 } else {
1030 Some(names)
1031 }
1032 }
1033
1034 fn resolve(&self, path: &str) -> Result<(&[MountTarget], String), NamespaceError> {
1040 self.resolve_entry(path)
1041 .map(|(entry, remainder)| (&entry.targets[..], remainder))
1042 }
1043
1044 fn resolve_entry(&self, path: &str) -> Result<(&MountEntry, String), NamespaceError> {
1047 let path = normalize_path(path);
1048
1049 for entry in &self.mounts {
1050 if entry.prefix == "/" {
1055 return Ok((entry, path));
1056 }
1057 if path == entry.prefix || path.starts_with(&format!("{}/", entry.prefix)) {
1058 let remainder = path[entry.prefix.len()..].to_owned();
1059 return Ok((entry, remainder));
1060 }
1061 }
1062
1063 Err(NamespaceError::Mount(MountError::NotFound(path)))
1064 }
1065
1066 fn root_dir_entries(&self) -> Vec<DirEntry> {
1068 let mut seen = std::collections::HashSet::new();
1069 let mut entries = Vec::new();
1070 for m in &self.mounts {
1071 let first = m
1073 .prefix
1074 .trim_start_matches('/')
1075 .split('/')
1076 .next()
1077 .unwrap_or("");
1078 if !first.is_empty() && seen.insert(first.to_owned()) {
1079 entries.push(DirEntry {
1080 name: first.to_owned(),
1081 is_dir: true,
1082 size: 0,
1083 stat: None,
1084 });
1085 }
1086 }
1087 entries
1088 }
1089}
1090
1091impl Default for Namespace {
1092 fn default() -> Self {
1093 Self::new()
1094 }
1095}
1096
1097fn normalize_prefix(prefix: &str) -> String {
1102 let p = if prefix.starts_with('/') {
1103 prefix.to_owned()
1104 } else {
1105 format!("/{prefix}")
1106 };
1107 if p.len() > 1 && p.ends_with('/') {
1109 p[..p.len() - 1].to_owned()
1110 } else {
1111 p
1112 }
1113}
1114
1115fn normalize_path(path: &str) -> String {
1117 let path = if path.starts_with('/') {
1118 path.to_owned()
1119 } else {
1120 format!("/{path}")
1121 };
1122 let mut parts: Vec<&str> = Vec::new();
1123 for seg in path.split('/') {
1124 match seg {
1125 "" | "." => {}
1126 ".." => {
1127 parts.pop();
1128 }
1129 s => parts.push(s),
1130 }
1131 }
1132 if parts.is_empty() {
1133 "/".to_owned()
1134 } else {
1135 format!("/{}", parts.join("/"))
1136 }
1137}
1138
1139fn split_path(path: &str) -> Vec<&str> {
1140 path.split('/')
1141 .filter(|s| !s.is_empty() && *s != "." && *s != "..")
1142 .collect()
1143}
1144
1145#[cfg(all(test, not(target_arch = "wasm32")))]
1150#[allow(clippy::unwrap_used, clippy::disallowed_types)]
1151mod tests {
1152 use super::*;
1153 use crate::mount::{Fid, MountError, Stat};
1154 use async_trait::async_trait;
1155 use std::collections::HashMap;
1156
1157 struct MemMount {
1159 files: HashMap<String, Vec<u8>>,
1160 }
1161
1162 impl MemMount {
1163 fn new(files: Vec<(&str, &[u8])>) -> Self {
1164 Self {
1165 files: files
1166 .into_iter()
1167 .map(|(k, v)| (k.to_owned(), v.to_vec()))
1168 .collect(),
1169 }
1170 }
1171 }
1172
1173 struct MemFid {
1174 path: String,
1175 is_open: bool,
1176 }
1177
1178 #[async_trait]
1179 impl Mount for MemMount {
1180 async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
1181 let path = components.join("/");
1182 Ok(Fid::new(MemFid {
1183 path,
1184 is_open: false,
1185 }))
1186 }
1187
1188 async fn open(
1189 &self,
1190 fid: &mut Fid,
1191 _mode: u8,
1192 _caller: &Subject,
1193 ) -> Result<(), MountError> {
1194 let inner = fid
1195 .downcast_mut::<MemFid>()
1196 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1197 inner.is_open = true;
1198 Ok(())
1199 }
1200
1201 async fn read(
1202 &self,
1203 fid: &Fid,
1204 offset: u64,
1205 _count: u32,
1206 _caller: &Subject,
1207 ) -> Result<Vec<u8>, MountError> {
1208 let inner = fid
1209 .downcast_ref::<MemFid>()
1210 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1211 match self.files.get(&inner.path) {
1212 Some(data) => {
1213 let start = offset as usize;
1214 if start >= data.len() {
1215 Ok(vec![])
1216 } else {
1217 Ok(data[start..].to_vec())
1218 }
1219 }
1220 None => Err(MountError::NotFound(inner.path.clone())),
1221 }
1222 }
1223
1224 async fn write(
1225 &self,
1226 _fid: &Fid,
1227 _offset: u64,
1228 data: &[u8],
1229 _caller: &Subject,
1230 ) -> Result<u32, MountError> {
1231 Ok(data.len() as u32)
1232 }
1233
1234 async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
1235 let inner = fid
1236 .downcast_ref::<MemFid>()
1237 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1238 let prefix = if inner.path.is_empty() {
1239 String::new()
1240 } else {
1241 format!("{}/", inner.path)
1242 };
1243 let mut entries = Vec::new();
1244 for key in self.files.keys() {
1245 if let Some(rest) = key.strip_prefix(&prefix) {
1246 if !rest.contains('/') {
1247 entries.push(DirEntry {
1248 name: rest.to_owned(),
1249 is_dir: false,
1250 size: 0,
1251 stat: None,
1252 });
1253 }
1254 }
1255 }
1256 Ok(entries)
1257 }
1258
1259 async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
1260 let inner = fid
1261 .downcast_ref::<MemFid>()
1262 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1263 Ok(Stat::unknown_qid(0, 0, inner.path.clone(), 0))
1264 }
1265
1266 async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
1267 }
1268
1269 fn test_subject() -> Subject {
1270 Subject::new("test")
1271 }
1272
1273 #[tokio::test]
1274 async fn mount_and_cat() {
1275 let mut ns = Namespace::new();
1276 let mount: MountTarget = Arc::new(MemMount::new(vec![("temperature", b"0.7\n")]));
1277 ns.mount("/config", mount).unwrap();
1278
1279 let data = ns
1280 .cat("/config/temperature", &test_subject())
1281 .await
1282 .unwrap();
1283 assert_eq!(data, b"0.7\n");
1284 }
1285
1286 #[tokio::test]
1287 async fn mount_and_ls_root() {
1288 let mut ns = Namespace::new();
1289 ns.mount("/srv/model", Arc::new(MemMount::new(vec![])) as MountTarget)
1290 .unwrap();
1291 ns.mount("/srv/mcp", Arc::new(MemMount::new(vec![])) as MountTarget)
1292 .unwrap();
1293 ns.mount("/config", Arc::new(MemMount::new(vec![])) as MountTarget)
1294 .unwrap();
1295
1296 let entries = ns.ls("/", &test_subject()).await.unwrap();
1297 let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
1298 assert!(names.contains(&"srv"));
1299 assert!(names.contains(&"config"));
1300 }
1301
1302 #[tokio::test]
1303 async fn longest_prefix_match() {
1304 let mut ns = Namespace::new();
1305 let srv: MountTarget = Arc::new(MemMount::new(vec![("status", b"ok")]));
1306 let nested: MountTarget = Arc::new(MemMount::new(vec![("status", b"loaded")]));
1307 ns.mount("/srv", srv).unwrap();
1308 ns.mount("/srv/model", nested).unwrap();
1309
1310 let data = ns.cat("/srv/model/status", &test_subject()).await.unwrap();
1311 assert_eq!(data, b"loaded");
1312 }
1313
1314 #[test]
1315 fn reserved_path_allows_mount() {
1316 let mut ns = Namespace::new();
1317 let mount: MountTarget = Arc::new(MemMount::new(vec![]));
1318 assert!(ns.mount("/config", mount).is_ok());
1319 }
1320
1321 #[tokio::test]
1322 async fn fork_and_unmount() {
1323 let mut ns = Namespace::new();
1324 ns.mount(
1325 "/srv/model",
1326 Arc::new(MemMount::new(vec![("status", b"loaded")])) as MountTarget,
1327 )
1328 .unwrap();
1329 ns.mount(
1330 "/srv/worker",
1331 Arc::new(MemMount::new(vec![])) as MountTarget,
1332 )
1333 .unwrap();
1334
1335 let mut child = ns.fork();
1336 let _ = child.unmount("/srv/worker");
1337
1338 assert_eq!(ns.mount_prefixes().len(), 2);
1339 assert_eq!(child.mount_prefixes().len(), 1);
1340 assert_eq!(child.mount_prefixes()[0], "/srv/model");
1341
1342 let data = child
1343 .cat("/srv/model/status", &test_subject())
1344 .await
1345 .unwrap();
1346 assert_eq!(data, b"loaded");
1347 }
1348
1349 #[tokio::test]
1352 async fn root_mount_is_catch_all() {
1353 let mut ns = Namespace::new();
1354 let rootfs: MountTarget = Arc::new(MemMount::new(vec![("etc/hostname", b"host\n")]));
1355 ns.mount("/", rootfs).unwrap();
1356 let stream: MountTarget = Arc::new(MemMount::new(vec![("job/data", b"chunk")]));
1357 ns.mount("/stream", stream).unwrap();
1358
1359 assert_eq!(
1361 ns.cat("/etc/hostname", &test_subject()).await.unwrap(),
1362 b"host\n"
1363 );
1364 assert_eq!(
1366 ns.cat("/stream/job/data", &test_subject()).await.unwrap(),
1367 b"chunk"
1368 );
1369 assert!(ns.resolve_targets("/", &test_subject()).await.is_ok());
1371 }
1372
1373 #[tokio::test]
1374 async fn not_found() {
1375 let ns = Namespace::new();
1376 assert!(matches!(
1377 ns.cat("/nonexistent/file", &test_subject()).await,
1378 Err(NamespaceError::Mount(MountError::NotFound(_)))
1379 ));
1380 }
1381
1382 #[tokio::test]
1383 async fn echo_writes() {
1384 let mut ns = Namespace::new();
1385 let mount: MountTarget = Arc::new(MemMount::new(vec![("ctl", b"")]));
1386 ns.mount("/cmd", mount).unwrap();
1387
1388 assert!(ns
1389 .echo("/cmd/ctl", b"load qwen3:main", &test_subject())
1390 .await
1391 .is_ok());
1392 }
1393
1394 #[tokio::test]
1398 async fn read_loop_large_file() {
1399 let big_data = vec![0x42u8; 100 * 1024]; let mut ns = Namespace::new();
1402
1403 struct ChunkedMount {
1404 data: Vec<u8>,
1405 }
1406 struct ChunkedFid {
1407 _offset_limit: bool,
1408 }
1409
1410 #[async_trait]
1411 impl Mount for ChunkedMount {
1412 async fn walk(&self, _c: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
1413 Ok(Fid::new(ChunkedFid {
1414 _offset_limit: false,
1415 }))
1416 }
1417 async fn open(
1418 &self,
1419 _fid: &mut Fid,
1420 _mode: u8,
1421 _caller: &Subject,
1422 ) -> Result<(), MountError> {
1423 Ok(())
1424 }
1425 async fn read(
1426 &self,
1427 _fid: &Fid,
1428 offset: u64,
1429 count: u32,
1430 _caller: &Subject,
1431 ) -> Result<Vec<u8>, MountError> {
1432 let start = offset as usize;
1433 if start >= self.data.len() {
1434 return Ok(vec![]);
1435 }
1436 let end = std::cmp::min(start + count as usize, self.data.len());
1437 Ok(self.data[start..end].to_vec())
1438 }
1439 async fn write(
1440 &self,
1441 _fid: &Fid,
1442 _o: u64,
1443 d: &[u8],
1444 _c: &Subject,
1445 ) -> Result<u32, MountError> {
1446 Ok(d.len() as u32)
1447 }
1448 async fn readdir(&self, _fid: &Fid, _c: &Subject) -> Result<Vec<DirEntry>, MountError> {
1449 Ok(vec![])
1450 }
1451 async fn stat(
1452 &self,
1453 _fid: &Fid,
1454 _c: &Subject,
1455 ) -> Result<crate::mount::Stat, MountError> {
1456 Ok(crate::mount::Stat::unknown_qid(0, 0, String::new(), 0))
1457 }
1458 async fn clunk(&self, _fid: Fid, _c: &Subject) {}
1459 }
1460
1461 ns.mount(
1462 "/big",
1463 Arc::new(ChunkedMount {
1464 data: big_data.clone(),
1465 }) as MountTarget,
1466 )
1467 .unwrap();
1468 let result = ns.cat("/big/file", &test_subject()).await.unwrap();
1469 assert_eq!(result.len(), 100 * 1024);
1470 assert_eq!(result, big_data);
1471 }
1472
1473 #[test]
1475 fn otrunc_mode_passthrough() {
1476 use crate::mount::{OTRUNC, OWRITE};
1477 let mode = OWRITE | OTRUNC;
1479 assert_eq!(mode & 0x03, OWRITE);
1480 assert_ne!(mode & OTRUNC, 0);
1481 }
1482
1483 #[test]
1485 fn path_normalization_with_dotdot() {
1486 assert_eq!(normalize_path("/config/../srv/model"), "/srv/model");
1487 assert_eq!(normalize_path("/config/./status"), "/config/status");
1488 assert_eq!(normalize_path("//config///status"), "/config/status");
1489 assert_eq!(normalize_path("/a/b/c/../../d"), "/a/d");
1490 assert_eq!(normalize_path("/.."), "/");
1491 }
1492
1493 #[tokio::test]
1495 async fn resolve_with_dotdot_path() {
1496 let mut ns = Namespace::new();
1497 ns.mount(
1498 "/srv/model",
1499 Arc::new(MemMount::new(vec![("status", b"ok")])) as MountTarget,
1500 )
1501 .unwrap();
1502
1503 let data = ns
1505 .cat("/config/../srv/model/status", &test_subject())
1506 .await
1507 .unwrap();
1508 assert_eq!(data, b"ok");
1509 }
1510
1511 #[tokio::test]
1514 async fn bind_before_walk_tries_new_mount_first() {
1515 let mut ns = Namespace::new();
1516 let orig: MountTarget = Arc::new(MemMount::new(vec![("status", b"original")]));
1518 ns.mount("/bin", orig).unwrap();
1519
1520 let overlay: MountTarget = Arc::new(MemMount::new(vec![("status", b"override")]));
1522 ns.bind_mount("/bin", overlay, BindFlag::Before).unwrap();
1523
1524 let data = ns.cat("/bin/status", &test_subject()).await.unwrap();
1525 assert_eq!(data, b"override");
1526 }
1527
1528 #[tokio::test]
1529 async fn bind_after_walk_tries_existing_first() {
1530 let mut ns = Namespace::new();
1531 let orig: MountTarget = Arc::new(MemMount::new(vec![("status", b"original")]));
1532 ns.mount("/bin", orig).unwrap();
1533
1534 let extra: MountTarget = Arc::new(MemMount::new(vec![("status", b"extra")]));
1536 ns.bind_mount("/bin", extra, BindFlag::After).unwrap();
1537
1538 let data = ns.cat("/bin/status", &test_subject()).await.unwrap();
1539 assert_eq!(data, b"original");
1540 }
1541
1542 #[tokio::test]
1543 async fn bind_after_fallback_to_new_mount() {
1544 let mut ns = Namespace::new();
1545 let orig: MountTarget = Arc::new(MemMount::new(vec![("cat", b"cat-impl")]));
1547 ns.mount("/bin", orig).unwrap();
1548
1549 let extra: MountTarget = Arc::new(MemMount::new(vec![("mytool", b"mytool-impl")]));
1551 ns.bind_mount("/bin", extra, BindFlag::After).unwrap();
1552
1553 let data = ns.cat("/bin/cat", &test_subject()).await.unwrap();
1555 assert_eq!(data, b"cat-impl");
1556
1557 let data = ns.cat("/bin/mytool", &test_subject()).await.unwrap();
1559 assert_eq!(data, b"mytool-impl");
1560 }
1561
1562 #[tokio::test]
1563 async fn bind_before_fallback_to_existing() {
1564 let mut ns = Namespace::new();
1565 let orig: MountTarget = Arc::new(MemMount::new(vec![("cat", b"cat-impl")]));
1566 ns.mount("/bin", orig).unwrap();
1567
1568 let overlay: MountTarget = Arc::new(MemMount::new(vec![("newtool", b"newtool-impl")]));
1570 ns.bind_mount("/bin", overlay, BindFlag::Before).unwrap();
1571
1572 let data = ns.cat("/bin/cat", &test_subject()).await.unwrap();
1574 assert_eq!(data, b"cat-impl");
1575
1576 let data = ns.cat("/bin/newtool", &test_subject()).await.unwrap();
1578 assert_eq!(data, b"newtool-impl");
1579 }
1580
1581 #[tokio::test]
1582 async fn union_readdir_merges_entries() {
1583 let mut ns = Namespace::new();
1584 let mount_a: MountTarget = Arc::new(MemMount::new(vec![("cat", b""), ("ls", b"")]));
1585 ns.mount("/bin", mount_a).unwrap();
1586
1587 let mount_b: MountTarget = Arc::new(MemMount::new(vec![("mytool", b""), ("cat", b"")]));
1588 ns.bind_mount("/bin", mount_b, BindFlag::After).unwrap();
1589
1590 let entries = ns.ls("/bin", &test_subject()).await.unwrap();
1591 let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
1592
1593 assert!(names.contains(&"cat"));
1595 assert!(names.contains(&"ls"));
1596 assert!(names.contains(&"mytool"));
1597 assert_eq!(names.iter().filter(|&&n| n == "cat").count(), 1);
1598 }
1599
1600 #[tokio::test]
1601 async fn bind_replace_still_works() {
1602 let mut ns = Namespace::new();
1603 let orig: MountTarget = Arc::new(MemMount::new(vec![("status", b"original")]));
1604 ns.mount("/bin", orig).unwrap();
1605
1606 let extra: MountTarget = Arc::new(MemMount::new(vec![("extra", b"x")]));
1608 ns.bind_mount("/bin", extra, BindFlag::After).unwrap();
1609
1610 let replacement: MountTarget = Arc::new(MemMount::new(vec![("status", b"replaced")]));
1612 ns.mount("/bin", replacement).unwrap();
1613
1614 let data = ns.cat("/bin/status", &test_subject()).await.unwrap();
1615 assert_eq!(data, b"replaced");
1616
1617 assert!(ns.cat("/bin/extra", &test_subject()).await.is_err());
1619 }
1620
1621 #[tokio::test]
1629 async fn ls_intermediate_directory() {
1630 let mut ns = Namespace::new();
1631 let mount = Arc::new(MemMount::new(vec![("status", b"ok")]));
1632 ns.mount("/srv/model", mount).unwrap();
1633 let lang_mount = Arc::new(MemMount::new(vec![("interp", b"tcl")]));
1634 ns.mount("/lang/tcl", lang_mount).unwrap();
1635
1636 let entries = ns.ls("/srv", &test_subject()).await.unwrap();
1638 assert_eq!(entries.len(), 1);
1639 assert_eq!(entries[0].name, "model");
1640 assert!(entries[0].is_dir);
1641
1642 let entries = ns.ls("/lang", &test_subject()).await.unwrap();
1644 assert_eq!(entries.len(), 1);
1645 assert_eq!(entries[0].name, "tcl");
1646 assert!(entries[0].is_dir);
1647
1648 assert!(ns.ls("/nonexistent", &test_subject()).await.is_err());
1650 }
1651
1652 #[tokio::test]
1654 async fn ls_intermediate_multiple_children() {
1655 let mut ns = Namespace::new();
1656 ns.mount("/a/b", Arc::new(MemMount::new(vec![("x", b"")])))
1657 .unwrap();
1658 ns.mount("/a/c", Arc::new(MemMount::new(vec![("y", b"")])))
1659 .unwrap();
1660 ns.mount("/a/d/e", Arc::new(MemMount::new(vec![("z", b"")])))
1661 .unwrap();
1662
1663 let entries = ns.ls("/a", &test_subject()).await.unwrap();
1664 let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
1665 assert!(names.contains(&"b"));
1666 assert!(names.contains(&"c"));
1667 assert!(names.contains(&"d"));
1668 assert_eq!(entries.len(), 3);
1669
1670 let entries = ns.ls("/a/d", &test_subject()).await.unwrap();
1672 assert_eq!(entries.len(), 1);
1673 assert_eq!(entries[0].name, "e");
1674 }
1675
1676 struct ReadOnlyMemMount {
1681 files: HashMap<String, Vec<u8>>,
1682 }
1683
1684 impl ReadOnlyMemMount {
1685 fn new(files: Vec<(&str, &[u8])>) -> Self {
1686 Self {
1687 files: files
1688 .into_iter()
1689 .map(|(k, v)| (k.to_owned(), v.to_vec()))
1690 .collect(),
1691 }
1692 }
1693 }
1694
1695 struct RoFid {
1696 path: String,
1697 }
1698
1699 #[async_trait]
1700 impl Mount for ReadOnlyMemMount {
1701 async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
1702 let path = components.join("/");
1703 Ok(Fid::new(RoFid { path }))
1704 }
1705 async fn open(&self, fid: &mut Fid, mode: u8, _caller: &Subject) -> Result<(), MountError> {
1706 let base_mode = mode & 0x03;
1707 if base_mode == OWRITE {
1708 return Err(MountError::PermissionDenied("read-only floor".into()));
1709 }
1710 let _ = fid
1711 .downcast_ref::<RoFid>()
1712 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1713 Ok(())
1714 }
1715 async fn read(
1716 &self,
1717 fid: &Fid,
1718 offset: u64,
1719 _count: u32,
1720 _caller: &Subject,
1721 ) -> Result<Vec<u8>, MountError> {
1722 let inner = fid
1723 .downcast_ref::<RoFid>()
1724 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1725 match self.files.get(&inner.path) {
1726 Some(data) => {
1727 let start = offset as usize;
1728 if start >= data.len() {
1729 Ok(vec![])
1730 } else {
1731 Ok(data[start..].to_vec())
1732 }
1733 }
1734 None => Err(MountError::NotFound(inner.path.clone())),
1735 }
1736 }
1737 async fn write(
1738 &self,
1739 _fid: &Fid,
1740 _o: u64,
1741 _d: &[u8],
1742 _c: &Subject,
1743 ) -> Result<u32, MountError> {
1744 Err(MountError::PermissionDenied("read-only floor".into()))
1745 }
1746 async fn readdir(&self, _fid: &Fid, _c: &Subject) -> Result<Vec<DirEntry>, MountError> {
1747 Ok(vec![])
1748 }
1749 async fn stat(&self, fid: &Fid, _c: &Subject) -> Result<Stat, MountError> {
1750 let inner = fid
1751 .downcast_ref::<RoFid>()
1752 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1753 Ok(Stat::unknown_qid(0, 0, inner.path.clone(), 0))
1754 }
1755 async fn clunk(&self, _fid: Fid, _c: &Subject) {}
1756 }
1757
1758 struct WritableMemMount {
1763 files: std::sync::Mutex<HashMap<String, Vec<u8>>>,
1764 }
1765
1766 impl WritableMemMount {
1767 fn empty() -> Self {
1768 Self {
1769 files: std::sync::Mutex::new(HashMap::new()),
1770 }
1771 }
1772
1773 fn snapshot(&self) -> HashMap<String, Vec<u8>> {
1774 self.files.lock().unwrap().clone()
1775 }
1776 }
1777
1778 struct WritableFid {
1779 path: String,
1780 is_open: bool,
1781 mode: u8,
1782 }
1783
1784 #[async_trait]
1785 impl Mount for WritableMemMount {
1786 async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
1787 let path = components.join("/");
1788 Ok(Fid::new(WritableFid {
1789 path,
1790 is_open: false,
1791 mode: 0,
1792 }))
1793 }
1794
1795 async fn open(&self, fid: &mut Fid, mode: u8, _caller: &Subject) -> Result<(), MountError> {
1796 let inner = fid
1797 .downcast_mut::<WritableFid>()
1798 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1799 let base_mode = mode & 0x03;
1800 if inner.path.is_empty() {
1802 inner.is_open = true;
1803 inner.mode = mode;
1804 return Ok(());
1805 }
1806 let files = self.files.lock().unwrap();
1807 if !files.contains_key(&inner.path) {
1808 return Err(MountError::NotFound(inner.path.clone()));
1809 }
1810 let _ = base_mode;
1812 inner.is_open = true;
1813 inner.mode = mode;
1814 Ok(())
1815 }
1816
1817 async fn read(
1818 &self,
1819 fid: &Fid,
1820 offset: u64,
1821 _count: u32,
1822 _caller: &Subject,
1823 ) -> Result<Vec<u8>, MountError> {
1824 let inner = fid
1825 .downcast_ref::<WritableFid>()
1826 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1827 let files = self.files.lock().unwrap();
1828 match files.get(&inner.path) {
1829 Some(data) => {
1830 let start = offset as usize;
1831 if start >= data.len() {
1832 Ok(vec![])
1833 } else {
1834 Ok(data[start..].to_vec())
1835 }
1836 }
1837 None => Err(MountError::NotFound(inner.path.clone())),
1838 }
1839 }
1840
1841 async fn write(
1842 &self,
1843 fid: &Fid,
1844 offset: u64,
1845 data: &[u8],
1846 _caller: &Subject,
1847 ) -> Result<u32, MountError> {
1848 let inner = fid
1849 .downcast_ref::<WritableFid>()
1850 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1851 let mut files = self.files.lock().unwrap();
1852 let entry = files.entry(inner.path.clone()).or_default();
1853 let start = offset as usize;
1854 if start > entry.len() {
1855 entry.resize(start, 0);
1856 }
1857 let end = start + data.len();
1858 if end > entry.len() {
1859 entry.resize(end, 0);
1860 }
1861 entry[start..end].copy_from_slice(data);
1862 Ok(data.len() as u32)
1863 }
1864
1865 async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
1866 let inner = fid
1867 .downcast_ref::<WritableFid>()
1868 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1869 let prefix = if inner.path.is_empty() {
1870 String::new()
1871 } else {
1872 format!("{}/", inner.path)
1873 };
1874 let files = self.files.lock().unwrap();
1875 let mut entries = Vec::new();
1876 for key in files.keys() {
1877 if let Some(rest) = key.strip_prefix(&prefix) {
1878 if !rest.contains('/') {
1879 entries.push(DirEntry {
1880 name: rest.to_owned(),
1881 is_dir: false,
1882 size: 0,
1883 stat: None,
1884 });
1885 }
1886 }
1887 }
1888 Ok(entries)
1889 }
1890
1891 async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
1892 let inner = fid
1893 .downcast_ref::<WritableFid>()
1894 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1895 Ok(Stat::unknown_qid(0, 0, inner.path.clone(), 0))
1896 }
1897
1898 async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
1899
1900 async fn create(
1902 &self,
1903 fid: &mut Fid,
1904 name: &str,
1905 _perm: u32,
1906 mode: u8,
1907 _caller: &Subject,
1908 ) -> Result<Stat, MountError> {
1909 let inner = fid
1910 .downcast_mut::<WritableFid>()
1911 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
1912 let child_path = if inner.path.is_empty() {
1913 name.to_owned()
1914 } else {
1915 format!("{}/{}", inner.path, name)
1916 };
1917 self.files
1919 .lock()
1920 .unwrap()
1921 .insert(child_path.clone(), Vec::new());
1922 inner.path = child_path;
1924 inner.is_open = true;
1925 inner.mode = mode;
1926 Ok(Stat::unknown_qid(0, 0, name.to_owned(), 0))
1927 }
1928 }
1929
1930 #[tokio::test]
1932 async fn namespace_create_lands_in_writable_target() {
1933 let mut ns = Namespace::new();
1934 let writable: MountTarget = Arc::new(WritableMemMount::empty());
1935 ns.mount("/wt", writable).unwrap();
1936
1937 let caller = test_subject();
1938 let stat = ns.create("/wt/newfile.txt", 0o644, &caller).await.unwrap();
1939 assert_eq!(stat.name, "newfile.txt");
1940
1941 let data = ns.cat("/wt/newfile.txt", &caller).await.unwrap();
1943 assert_eq!(data, b"");
1944 }
1945
1946 #[tokio::test]
1949 async fn copy_up_writes_to_upper_when_lower_is_readonly() {
1950 let mut ns = Namespace::new();
1951
1952 let floor: MountTarget = Arc::new(ReadOnlyMemMount::new(vec![("config", b"floor-bytes")]));
1954 let upper = Arc::new(WritableMemMount::empty());
1957
1958 ns.bind_mount("/union", floor, BindFlag::Replace).unwrap();
1961 ns.bind_mount("/union", Arc::clone(&upper) as MountTarget, BindFlag::After)
1962 .unwrap();
1963
1964 let caller = test_subject();
1965
1966 let before = ns.cat("/union/config", &caller).await.unwrap();
1968 assert_eq!(before, b"floor-bytes");
1969
1970 ns.echo("/union/config", b"new-bytes", &caller)
1974 .await
1975 .unwrap();
1976
1977 let upper_files = upper.snapshot();
1978 assert!(upper_files.contains_key("config"));
1979 assert_eq!(upper_files.get("config").unwrap(), b"new-bytes");
1980 }
1981
1982 #[tokio::test]
1984 async fn copy_up_does_not_mutate_floor() {
1985 let mut ns = Namespace::new();
1986 let floor: MountTarget = Arc::new(ReadOnlyMemMount::new(vec![("data", b"immutable")]));
1988 let upper = Arc::new(WritableMemMount::empty());
1989
1990 ns.bind_mount("/u", floor, BindFlag::Replace).unwrap();
1991 ns.bind_mount("/u", Arc::clone(&upper) as MountTarget, BindFlag::After)
1992 .unwrap();
1993
1994 let caller = test_subject();
1995 ns.echo("/u/data", b"mutated", &caller).await.unwrap();
1996
1997 let upper_files = upper.snapshot();
1999 assert_eq!(upper_files.get("data").unwrap(), b"mutated");
2000
2001 let floor_read = ns.cat("/u/data", &caller).await.unwrap();
2007 assert_eq!(floor_read, b"immutable");
2008 }
2009
2010 #[tokio::test]
2013 async fn default_create_returns_not_supported() {
2014 let mut ns = Namespace::new();
2015 let mount: MountTarget = Arc::new(MemMount::new(vec![]));
2016 ns.mount("/ro", mount).unwrap();
2017
2018 let caller = test_subject();
2019 let err = ns.create("/ro/anything", 0o644, &caller).await.unwrap_err();
2020 match err {
2021 NamespaceError::Mount(MountError::NotSupported(_)) => {}
2022 other => panic!("expected NotSupported, got {other:?}"),
2023 }
2024 }
2025
2026 struct SubjectGatedMount {
2032 allow: String,
2033 files: std::sync::Mutex<HashMap<String, Vec<u8>>>,
2034 }
2035
2036 impl SubjectGatedMount {
2037 fn new(allow: &str) -> Self {
2038 Self {
2039 allow: allow.to_owned(),
2040 files: std::sync::Mutex::new(HashMap::new()),
2041 }
2042 }
2043 fn snapshot(&self) -> HashMap<String, Vec<u8>> {
2044 self.files.lock().unwrap().clone()
2045 }
2046 fn check(&self, caller: &Subject) -> Result<(), MountError> {
2047 if caller.name() == Some(self.allow.as_str()) {
2048 Ok(())
2049 } else {
2050 Err(MountError::PermissionDenied("subject not permitted".into()))
2051 }
2052 }
2053 }
2054
2055 #[async_trait]
2056 impl Mount for SubjectGatedMount {
2057 async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
2058 Ok(Fid::new(WritableFid {
2059 path: components.join("/"),
2060 is_open: false,
2061 mode: 0,
2062 }))
2063 }
2064 async fn open(&self, fid: &mut Fid, mode: u8, caller: &Subject) -> Result<(), MountError> {
2065 let inner = fid
2066 .downcast_mut::<WritableFid>()
2067 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2068 if inner.path.is_empty() {
2069 inner.is_open = true;
2070 inner.mode = mode;
2071 return Ok(());
2072 }
2073 if mode & 0x03 == OWRITE {
2076 self.check(caller)?;
2077 }
2078 if !self.files.lock().unwrap().contains_key(&inner.path) {
2079 return Err(MountError::NotFound(inner.path.clone()));
2080 }
2081 inner.is_open = true;
2082 inner.mode = mode;
2083 Ok(())
2084 }
2085 async fn read(
2086 &self,
2087 fid: &Fid,
2088 offset: u64,
2089 _count: u32,
2090 _caller: &Subject,
2091 ) -> Result<Vec<u8>, MountError> {
2092 let inner = fid
2093 .downcast_ref::<WritableFid>()
2094 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2095 match self.files.lock().unwrap().get(&inner.path) {
2096 Some(data) => {
2097 let start = offset as usize;
2098 if start >= data.len() {
2099 Ok(vec![])
2100 } else {
2101 Ok(data[start..].to_vec())
2102 }
2103 }
2104 None => Err(MountError::NotFound(inner.path.clone())),
2105 }
2106 }
2107 async fn write(
2108 &self,
2109 fid: &Fid,
2110 offset: u64,
2111 data: &[u8],
2112 caller: &Subject,
2113 ) -> Result<u32, MountError> {
2114 self.check(caller)?;
2115 let inner = fid
2116 .downcast_ref::<WritableFid>()
2117 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2118 let mut files = self.files.lock().unwrap();
2119 let entry = files.entry(inner.path.clone()).or_default();
2120 let start = offset as usize;
2121 let end = start + data.len();
2122 if end > entry.len() {
2123 entry.resize(end, 0);
2124 }
2125 entry[start..end].copy_from_slice(data);
2126 Ok(data.len() as u32)
2127 }
2128 async fn readdir(
2129 &self,
2130 _fid: &Fid,
2131 _caller: &Subject,
2132 ) -> Result<Vec<DirEntry>, MountError> {
2133 Ok(vec![])
2134 }
2135 async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
2136 let inner = fid
2137 .downcast_ref::<WritableFid>()
2138 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2139 Ok(Stat::unknown_qid(0, 0, inner.path.clone(), 0))
2140 }
2141 async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
2142 async fn create(
2143 &self,
2144 fid: &mut Fid,
2145 name: &str,
2146 _perm: u32,
2147 mode: u8,
2148 caller: &Subject,
2149 ) -> Result<Stat, MountError> {
2150 self.check(caller)?;
2151 let inner = fid
2152 .downcast_mut::<WritableFid>()
2153 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2154 let child = if inner.path.is_empty() {
2155 name.to_owned()
2156 } else {
2157 format!("{}/{}", inner.path, name)
2158 };
2159 self.files.lock().unwrap().insert(child.clone(), Vec::new());
2160 inner.path = child;
2161 inner.is_open = true;
2162 inner.mode = mode;
2163 Ok(Stat::unknown_qid(0, 0, name.to_owned(), 0))
2164 }
2165 }
2166
2167 struct ReadOnlyReaddirMount {
2171 files: HashMap<String, Vec<u8>>,
2172 }
2173
2174 impl ReadOnlyReaddirMount {
2175 fn new(files: Vec<(&str, &[u8])>) -> Self {
2176 Self {
2177 files: files
2178 .into_iter()
2179 .map(|(k, v)| (k.to_owned(), v.to_vec()))
2180 .collect(),
2181 }
2182 }
2183 }
2184
2185 #[async_trait]
2186 impl Mount for ReadOnlyReaddirMount {
2187 async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
2188 Ok(Fid::new(RoFid {
2189 path: components.join("/"),
2190 }))
2191 }
2192 async fn open(&self, fid: &mut Fid, mode: u8, _caller: &Subject) -> Result<(), MountError> {
2193 if mode & 0x03 == OWRITE {
2194 return Err(MountError::PermissionDenied("read-only".into()));
2195 }
2196 let _ = fid
2197 .downcast_ref::<RoFid>()
2198 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2199 Ok(())
2200 }
2201 async fn read(
2202 &self,
2203 fid: &Fid,
2204 offset: u64,
2205 _count: u32,
2206 _caller: &Subject,
2207 ) -> Result<Vec<u8>, MountError> {
2208 let inner = fid
2209 .downcast_ref::<RoFid>()
2210 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2211 match self.files.get(&inner.path) {
2212 Some(data) => {
2213 let start = offset as usize;
2214 if start >= data.len() {
2215 Ok(vec![])
2216 } else {
2217 Ok(data[start..].to_vec())
2218 }
2219 }
2220 None if inner.path.is_empty() => Ok(vec![]),
2222 None => Err(MountError::NotFound(inner.path.clone())),
2223 }
2224 }
2225 async fn write(
2226 &self,
2227 _fid: &Fid,
2228 _o: u64,
2229 _d: &[u8],
2230 _c: &Subject,
2231 ) -> Result<u32, MountError> {
2232 Err(MountError::PermissionDenied("read-only".into()))
2233 }
2234 async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
2235 let inner = fid
2236 .downcast_ref::<RoFid>()
2237 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2238 let prefix = if inner.path.is_empty() {
2239 String::new()
2240 } else {
2241 format!("{}/", inner.path)
2242 };
2243 let mut entries = Vec::new();
2244 for key in self.files.keys() {
2245 if let Some(rest) = key.strip_prefix(&prefix) {
2246 if !rest.contains('/') {
2247 entries.push(DirEntry {
2248 name: rest.to_owned(),
2249 is_dir: false,
2250 size: 0,
2251 stat: None,
2252 });
2253 }
2254 }
2255 }
2256 Ok(entries)
2257 }
2258 async fn stat(&self, fid: &Fid, _c: &Subject) -> Result<Stat, MountError> {
2259 let inner = fid
2260 .downcast_ref::<RoFid>()
2261 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
2262 Ok(Stat::unknown_qid(0, 0, inner.path.clone(), 0))
2263 }
2264 async fn clunk(&self, _fid: Fid, _c: &Subject) {}
2265 }
2266
2267 #[tokio::test]
2271 async fn copy_up_targets_designated_upper_not_bind_order() {
2272 let mut ns = Namespace::new();
2273 let floor: MountTarget = Arc::new(ReadOnlyMemMount::new(vec![("weights", b"shared-ro")]));
2274 let first = Arc::new(WritableMemMount::empty());
2277 let chosen = Arc::new(WritableMemMount::empty());
2278
2279 ns.bind_mount("/m", floor, BindFlag::Replace).unwrap();
2280 ns.bind_mount("/m", Arc::clone(&first) as MountTarget, BindFlag::After)
2281 .unwrap();
2282 ns.bind_mount("/m", Arc::clone(&chosen) as MountTarget, BindFlag::Upper)
2283 .unwrap();
2284
2285 assert!(ns.has_designated_upper("/m"));
2286
2287 let caller = test_subject();
2288 ns.echo("/m/weights", b"tenant-edit", &caller)
2289 .await
2290 .unwrap();
2291
2292 assert_eq!(chosen.snapshot().get("weights").unwrap(), b"tenant-edit");
2294 assert!(
2295 !first.snapshot().contains_key("weights"),
2296 "first writable must NOT receive the copy-up"
2297 );
2298 }
2299
2300 #[tokio::test]
2303 async fn write_to_existing_upper_file_skips_copy_up() {
2304 let mut ns = Namespace::new();
2305 let floor: MountTarget = Arc::new(ReadOnlyMemMount::new(vec![("f", b"floor")]));
2306 let upper = Arc::new(WritableMemMount::empty());
2307 upper
2311 .files
2312 .lock()
2313 .unwrap()
2314 .insert("f".to_owned(), b"upperorig".to_vec());
2315
2316 ns.bind_mount("/x", floor, BindFlag::Replace).unwrap();
2317 ns.bind_mount("/x", Arc::clone(&upper) as MountTarget, BindFlag::Upper)
2318 .unwrap();
2319
2320 let caller = test_subject();
2321 ns.echo("/x/f", b"upper-new", &caller).await.unwrap();
2322
2323 assert_eq!(upper.snapshot().get("f").unwrap(), b"upper-new");
2324 }
2325
2326 #[tokio::test]
2329 async fn write_new_path_creates_in_designated_upper() {
2330 let mut ns = Namespace::new();
2331 let floor: MountTarget = Arc::new(ReadOnlyMemMount::new(vec![("existing", b"ro")]));
2332 let upper = Arc::new(WritableMemMount::empty());
2333
2334 ns.bind_mount("/n", floor, BindFlag::Replace).unwrap();
2335 ns.bind_mount("/n", Arc::clone(&upper) as MountTarget, BindFlag::Upper)
2336 .unwrap();
2337
2338 let caller = test_subject();
2339 ns.create("/n/fresh", 0o644, &caller).await.unwrap();
2342 ns.echo("/n/fresh", b"brand-new", &caller).await.unwrap();
2343
2344 assert_eq!(upper.snapshot().get("fresh").unwrap(), b"brand-new");
2345 }
2346
2347 #[tokio::test]
2350 async fn readdir_after_copy_up_shows_file_once() {
2351 let mut ns = Namespace::new();
2352 let floor: MountTarget =
2354 Arc::new(ReadOnlyReaddirMount::new(vec![("shared", b"floor-bytes")]));
2355 let upper = Arc::new(WritableMemMount::empty());
2356
2357 ns.bind_mount("/r", floor, BindFlag::Replace).unwrap();
2358 ns.bind_mount("/r", Arc::clone(&upper) as MountTarget, BindFlag::Upper)
2359 .unwrap();
2360
2361 let caller = test_subject();
2362 ns.echo("/r/shared", b"edited", &caller).await.unwrap();
2363
2364 let entries = ns.ls("/r", &caller).await.unwrap();
2365 let shared_count = entries.iter().filter(|e| e.name == "shared").count();
2366 assert_eq!(
2367 shared_count, 1,
2368 "copied-up file must appear once, not once per layer"
2369 );
2370 }
2371
2372 #[tokio::test]
2376 async fn copy_up_fails_closed_for_denied_subject() {
2377 let mut ns = Namespace::new();
2378 let floor: MountTarget = Arc::new(ReadOnlyMemMount::new(vec![("secret", b"floor")]));
2379 let upper = Arc::new(SubjectGatedMount::new("alice"));
2381
2382 ns.bind_mount("/g", floor, BindFlag::Replace).unwrap();
2383 ns.bind_mount("/g", Arc::clone(&upper) as MountTarget, BindFlag::Upper)
2384 .unwrap();
2385
2386 let mallory = Subject::new("mallory");
2388 let err = ns.echo("/g/secret", b"evil", &mallory).await.unwrap_err();
2389 match err {
2390 NamespaceError::Mount(MountError::PermissionDenied(_)) => {}
2391 other => panic!("expected PermissionDenied (fail closed), got {other:?}"),
2392 }
2393 assert!(
2394 upper.snapshot().is_empty(),
2395 "denied copy-up must not write the upper"
2396 );
2397
2398 let alice = Subject::new("alice");
2401 ns.echo("/g/secret", b"ok", &alice).await.unwrap();
2402 assert_eq!(upper.snapshot().get("secret").unwrap(), b"ok");
2403 }
2404
2405 #[tokio::test]
2417 async fn copy_up_through_root_catch_all() {
2418 let mut ns = Namespace::new();
2419 let image: MountTarget = Arc::new(ReadOnlyMemMount::new(vec![("hostname", b"worker\n")]));
2420 let upper = Arc::new(WritableMemMount::empty());
2421
2422 ns.bind_mount("/", image, BindFlag::Replace).unwrap();
2423 ns.bind_mount("/", Arc::clone(&upper) as MountTarget, BindFlag::Upper)
2424 .unwrap();
2425 assert!(ns.has_designated_upper("/"));
2426
2427 let caller = test_subject();
2428
2429 assert_eq!(ns.cat("/hostname", &caller).await.unwrap(), b"worker\n");
2431
2432 ns.echo("/hostname", b"tenant\n", &caller).await.unwrap();
2435 assert_eq!(upper.snapshot().get("hostname").unwrap(), b"tenant\n");
2436
2437 assert_eq!(ns.cat("/hostname", &caller).await.unwrap(), b"tenant\n");
2439
2440 let stream: MountTarget = Arc::new(MemMount::new(vec![("job", b"chunk")]));
2443 ns.mount("/stream", stream).unwrap();
2444 assert_eq!(ns.cat("/stream/job", &caller).await.unwrap(), b"chunk");
2445 }
2446
2447 use crate::mac_pep::{
2450 DenyAllNamespace, DenyAllSubjects, NamespaceAccessDecider, NamespaceAction, NamespacePep,
2451 SubjectContextResolver,
2452 };
2453 use hyprstream_rpc::auth::mac::{
2454 Assurance, CompartmentSet, Level, MacDecision, MacDenyReason, RpcObjectLabelResolver,
2455 SecurityContext, SecurityLabel, VerifiedKeyMaterial,
2456 };
2457
2458 fn sec_label(level: Level) -> SecurityLabel {
2459 SecurityLabel::new(level, Assurance::Classical, CompartmentSet::EMPTY)
2460 }
2461 fn sec_ctx(level: Level) -> SecurityContext {
2462 SecurityContext::from_clearance(sec_label(level), VerifiedKeyMaterial::Classical)
2463 }
2464
2465 struct OneSubject {
2467 name: &'static str,
2468 ctx: SecurityContext,
2469 }
2470 #[async_trait::async_trait]
2471 impl SubjectContextResolver for OneSubject {
2472 async fn resolve(&self, s: &Subject) -> Option<SecurityContext> {
2473 (s.name() == Some(self.name)).then(|| self.ctx.clone())
2474 }
2475 }
2476
2477 struct PublicOnlyResolver;
2479 impl RpcObjectLabelResolver for PublicOnlyResolver {
2480 fn resolve(&self, service_domain: &str, _method: Option<&[u16]>) -> Option<SecurityLabel> {
2481 service_domain
2482 .strip_prefix("/public")
2483 .filter(|suffix| suffix.is_empty() || suffix.starts_with('/'))
2484 .map(|_| sec_label(Level::Public))
2485 }
2486 }
2487
2488 struct ReadFloorDecider;
2491 impl NamespaceAccessDecider for ReadFloorDecider {
2492 fn check(
2493 &self,
2494 ctx: Option<&SecurityContext>,
2495 object_label: Option<SecurityLabel>,
2496 action: NamespaceAction,
2497 ) -> MacDecision {
2498 let Some(ctx) = ctx else {
2499 return MacDecision::Deny(MacDenyReason::NoClearance);
2500 };
2501 let Some(object_label) = object_label else {
2502 return MacDecision::Deny(MacDenyReason::UnlabeledObject);
2503 };
2504 if action != NamespaceAction::Read {
2505 return MacDecision::Deny(MacDenyReason::FloorDeny);
2506 }
2507 if ctx.clearance().can_access(&object_label) {
2508 MacDecision::Permit
2509 } else {
2510 MacDecision::Deny(MacDenyReason::FloorDeny)
2511 }
2512 }
2513 }
2514
2515 fn deny_all_pep() -> Arc<NamespacePep> {
2516 Arc::new(NamespacePep::new(
2517 Arc::new(DenyAllSubjects),
2518 Arc::new(crate::mac_pep::DenyUnlabeledResolver),
2519 Arc::new(DenyAllNamespace),
2520 ))
2521 }
2522
2523 #[tokio::test]
2526 async fn un_unarmed_namespace_is_unenforced() {
2527 let mut ns = Namespace::new();
2528 ns.mount(
2529 "/public",
2530 Arc::new(MemMount::new(vec![("f", b"data")])) as MountTarget,
2531 )
2532 .unwrap();
2533 assert!(!ns.pep_armed());
2534 assert_eq!(
2535 ns.cat("/public/f", &Subject::new("anyone")).await.unwrap(),
2536 b"data"
2537 );
2538 }
2539
2540 #[tokio::test]
2543 async fn armed_deny_all_pep_denies_reads() {
2544 let mut ns = Namespace::new();
2545 ns.mount(
2546 "/public",
2547 Arc::new(MemMount::new(vec![("f", b"data")])) as MountTarget,
2548 )
2549 .unwrap();
2550 ns.set_pep(deny_all_pep());
2551 assert!(ns.pep_armed());
2552 let err = ns
2553 .cat("/public/f", &Subject::new("anyone"))
2554 .await
2555 .unwrap_err();
2556 assert!(matches!(
2557 err,
2558 NamespaceError::Denied(NamespaceAction::Read, _)
2559 ));
2560 }
2561
2562 #[tokio::test]
2566 async fn resolve_targets_denies_without_clearance() {
2567 let mut ns = Namespace::new();
2568 ns.mount(
2569 "/public",
2570 Arc::new(MemMount::new(vec![("f", b"data")])) as MountTarget,
2571 )
2572 .unwrap();
2573 ns.set_pep(deny_all_pep());
2574
2575 assert!(matches!(
2576 ns.resolve_targets("/public/f", &Subject::new("unverified"))
2577 .await,
2578 Err(NamespaceError::Denied(NamespaceAction::ResolveHandle, _))
2579 ));
2580 }
2581
2582 #[tokio::test]
2585 async fn armed_pep_permits_cleared_read_denies_uncleared() {
2586 let mut ns = Namespace::new();
2587 ns.mount(
2588 "/public",
2589 Arc::new(MemMount::new(vec![("f", b"data")])) as MountTarget,
2590 )
2591 .unwrap();
2592 let pep = Arc::new(NamespacePep::new(
2593 Arc::new(OneSubject {
2594 name: "alice",
2595 ctx: sec_ctx(Level::Public),
2596 }),
2597 Arc::new(PublicOnlyResolver),
2598 Arc::new(ReadFloorDecider),
2599 ));
2600 ns.set_pep(pep);
2601
2602 assert_eq!(
2604 ns.cat("/public/f", &Subject::new("alice")).await.unwrap(),
2605 b"data"
2606 );
2607 let err = ns
2609 .cat("/public/f", &Subject::new("mallory"))
2610 .await
2611 .unwrap_err();
2612 assert!(matches!(
2613 err,
2614 NamespaceError::Denied(NamespaceAction::Read, _)
2615 ));
2616 }
2617
2618 #[tokio::test]
2621 async fn armed_pep_denies_writes_under_read_floor_decider() {
2622 let mut ns = Namespace::new();
2623 ns.mount(
2624 "/public",
2625 Arc::new(MemMount::new(vec![("ctl", b"")])) as MountTarget,
2626 )
2627 .unwrap();
2628 let pep = Arc::new(NamespacePep::new(
2629 Arc::new(OneSubject {
2630 name: "alice",
2631 ctx: sec_ctx(Level::Secret),
2632 }),
2633 Arc::new(PublicOnlyResolver),
2634 Arc::new(ReadFloorDecider),
2635 ));
2636 ns.set_pep(pep);
2637
2638 let err = ns
2639 .echo("/public/ctl", b"x", &Subject::new("alice"))
2640 .await
2641 .unwrap_err();
2642 assert!(matches!(
2643 err,
2644 NamespaceError::Denied(NamespaceAction::Write, _)
2645 ));
2646 }
2647
2648 #[tokio::test]
2651 async fn armed_pep_denies_unlabeled_object() {
2652 let mut ns = Namespace::new();
2653 ns.mount(
2655 "/secret",
2656 Arc::new(MemMount::new(vec![("f", b"x")])) as MountTarget,
2657 )
2658 .unwrap();
2659 let pep = Arc::new(NamespacePep::new(
2660 Arc::new(OneSubject {
2661 name: "alice",
2662 ctx: sec_ctx(Level::Secret),
2663 }),
2664 Arc::new(PublicOnlyResolver),
2665 Arc::new(ReadFloorDecider),
2666 ));
2667 ns.set_pep(pep);
2668
2669 let err = ns
2670 .cat("/secret/f", &Subject::new("alice"))
2671 .await
2672 .unwrap_err();
2673 assert!(matches!(
2674 err,
2675 NamespaceError::Denied(NamespaceAction::Read, _)
2676 ));
2677 }
2678
2679 #[tokio::test]
2683 async fn armed_pep_blocks_subjectless_mutation() {
2684 let mut ns = Namespace::new();
2685 ns.set_pep(deny_all_pep());
2686
2687 let err = ns
2689 .mount("/x", Arc::new(MemMount::new(vec![])) as MountTarget)
2690 .unwrap_err();
2691 assert!(matches!(
2692 err,
2693 NamespaceError::Denied(NamespaceAction::BindMount, _)
2694 ));
2695
2696 let err = ns.unmount("/x").unwrap_err();
2697 assert!(matches!(
2698 err,
2699 NamespaceError::Denied(NamespaceAction::Unmount, _)
2700 ));
2701
2702 let err = ns
2704 .mount_as(
2705 "/x",
2706 Arc::new(MemMount::new(vec![])) as MountTarget,
2707 &Subject::new("a"),
2708 )
2709 .await
2710 .unwrap_err();
2711 assert!(matches!(
2712 err,
2713 NamespaceError::Denied(NamespaceAction::Mount, _)
2714 ));
2715 }
2716
2717 #[tokio::test]
2720 async fn fork_inherits_pep() {
2721 let mut ns = Namespace::new();
2722 ns.mount(
2723 "/public",
2724 Arc::new(MemMount::new(vec![("f", b"data")])) as MountTarget,
2725 )
2726 .unwrap();
2727 ns.set_pep(deny_all_pep());
2728
2729 let child = ns.fork();
2730 assert!(child.pep_armed());
2731 let err = child
2732 .cat("/public/f", &Subject::new("anyone"))
2733 .await
2734 .unwrap_err();
2735 assert!(matches!(
2736 err,
2737 NamespaceError::Denied(NamespaceAction::Read, _)
2738 ));
2739 }
2740
2741 #[tokio::test]
2742 async fn read_target_never_opens_writable_even_if_backing_mount_accepts_it() {
2743 let mut ns = Namespace::new();
2744 ns.mount(
2745 "/srv/registry",
2746 Arc::new(MemMount::new(vec![("repo/main/file", b"proof")])) as MountTarget,
2747 )
2748 .unwrap();
2749 let caller = test_subject();
2750 let (mut targets, relative) = ns
2751 .resolve_read_targets("/srv/registry/repo/main/file", &caller)
2752 .await
2753 .unwrap();
2754 assert_eq!(relative, ["repo", "main", "file"]);
2755 let target = targets.remove(0);
2756 let mut fid = target
2757 .walk(&["repo", "main", "file"], &caller)
2758 .await
2759 .unwrap();
2760 assert!(matches!(
2761 target.open(&mut fid, 1, &caller).await,
2762 Err(MountError::PermissionDenied(_))
2763 ));
2764 target.open(&mut fid, 0, &caller).await.unwrap();
2765 assert_eq!(target.read(&fid, 0, 16, &caller).await.unwrap(), b"proof");
2766 target.clunk(fid, &caller).await;
2767 }
2768}