1use std::sync::Arc;
9use std::time::{SystemTime, UNIX_EPOCH};
10
11#[cfg(not(target_arch = "wasm32"))]
12use async_trait::async_trait;
13use hyprstream_pds::ATPROTO_SIGNING_KEY_FILE;
14use hyprstream_pds_service::{
15 AccountRecordReadAuthorizer, OAUTH_ACCOUNT_RESOLVER_SUBJECT, PDS_ACCOUNTS_DIRECTORY,
16 PDS_ACCOUNT_DID_DOCUMENT_FILE, PDS_ACCOUNT_DID_LOG_FILE, PDS_ACCOUNT_RECORD_FILE,
17};
18use hyprstream_rpc::auth::mac::{
19 Assurance, CompartmentSet, Level, MacDecision, MacDenyReason, ObjectLabelResolver, ObjectRef,
20 SecurityContext, SecurityLabel, VerifiedKeyMaterial,
21};
22use hyprstream_rpc::Subject;
23#[cfg(not(target_arch = "wasm32"))]
24use hyprstream_vfs::{DirEntry, Fid, Mount, MountError, Stat};
25#[cfg(not(target_arch = "wasm32"))]
26use parking_lot::Mutex;
27#[cfg(not(target_arch = "wasm32"))]
28use std::fs::File;
29#[cfg(not(target_arch = "wasm32"))]
30use std::io::{Read, Seek, SeekFrom};
31#[cfg(not(target_arch = "wasm32"))]
32use std::path::{Path, PathBuf};
33
34use crate::mac::audit::{AuditRecord, AuditSink, DecisionReason};
35use crate::mac::te::{Action, Decision, ObjectType, ScopeAction, SubjectType};
36
37const PDS_SUBJECT_TYPE: SubjectType = SubjectType(u32::MAX - 4);
39const PDS_OBJECT_TYPE: ObjectType = ObjectType(u32::MAX - 4);
40
41fn pds_account_label() -> SecurityLabel {
42 SecurityLabel::new(
43 Level::Confidential,
44 Assurance::Classical,
45 CompartmentSet::EMPTY,
46 )
47}
48
49#[derive(Debug, Default, Clone, Copy)]
59pub struct PdsAccountObjectLabelResolver;
60
61impl ObjectLabelResolver for PdsAccountObjectLabelResolver {
62 fn resolve(&self, object: ObjectRef<'_>) -> Option<SecurityLabel> {
63 let ObjectRef::Path(components) = object else {
64 return None;
65 };
66 match components {
67 ["pds"] => Some(pds_account_label()),
68 ["pds", tenant] if crate::auth::valid_tenant_component(tenant) => {
69 Some(pds_account_label())
70 }
71 ["pds", tenant, accounts]
72 if crate::auth::valid_tenant_component(tenant)
73 && *accounts == PDS_ACCOUNTS_DIRECTORY =>
74 {
75 Some(pds_account_label())
76 }
77 ["pds", tenant, accounts, account]
78 if crate::auth::valid_tenant_component(tenant)
79 && *accounts == PDS_ACCOUNTS_DIRECTORY
80 && valid_account_component(account) =>
81 {
82 Some(pds_account_label())
83 }
84 ["pds", tenant, accounts, account, file]
85 if crate::auth::valid_tenant_component(tenant)
86 && *accounts == PDS_ACCOUNTS_DIRECTORY
87 && valid_account_component(account)
88 && matches!(
89 *file,
90 PDS_ACCOUNT_RECORD_FILE
91 | ATPROTO_SIGNING_KEY_FILE
92 | PDS_ACCOUNT_DID_DOCUMENT_FILE
93 | PDS_ACCOUNT_DID_LOG_FILE
94 ) =>
95 {
96 Some(pds_account_label())
97 }
98 ["pds", tenant, accounts, account, "repo", file]
99 if crate::auth::valid_tenant_component(tenant)
100 && *accounts == PDS_ACCOUNTS_DIRECTORY
101 && valid_account_component(account)
102 && matches!(*file, "commit.cbor" | "public-commit.cbor") =>
103 {
104 Some(pds_account_label())
105 }
106 _ => None,
107 }
108 }
109}
110
111fn valid_account_component(value: &str) -> bool {
112 !value.is_empty()
113 && value.len() <= 63
114 && value
115 .bytes()
116 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
117 && !value.starts_with('-')
118 && !value.ends_with('-')
119}
120
121#[cfg(not(target_arch = "wasm32"))]
129pub struct PdsDirectoryMount {
130 root: PathBuf,
131 root_directory: File,
132}
133
134#[cfg(not(target_arch = "wasm32"))]
135impl PdsDirectoryMount {
136 pub fn open(root: impl AsRef<Path>) -> std::io::Result<Self> {
137 #[cfg(not(target_os = "linux"))]
138 return Err(std::io::Error::new(
139 std::io::ErrorKind::Unsupported,
140 "descriptor-bound PDS directory mount requires Linux /proc",
141 ));
142
143 #[cfg(target_os = "linux")]
144 {
145 std::fs::create_dir_all(root.as_ref())?;
146 #[cfg(unix)]
147 {
148 use std::os::unix::fs::PermissionsExt as _;
149 std::fs::set_permissions(root.as_ref(), std::fs::Permissions::from_mode(0o700))?;
150 }
151 let root = std::fs::canonicalize(root)?;
152 let root_directory = File::open(&root)?;
153 Ok(Self {
154 root,
155 root_directory,
156 })
157 }
158 }
159
160 fn relative_path(&self, components: &[&str]) -> Result<String, MountError> {
161 if components
162 .iter()
163 .any(|component| !valid_walk_component(component))
164 {
165 return Err(MountError::InvalidArgument(
166 "PDS path contains an invalid component".to_owned(),
167 ));
168 }
169 Ok(if components.is_empty() {
170 ".".to_owned()
171 } else {
172 components.join("/")
173 })
174 }
175}
176
177#[cfg(not(target_arch = "wasm32"))]
178struct PdsDirectoryFid {
179 handle: File,
180 opened_file: Mutex<Option<File>>,
181 components: Vec<String>,
182 is_dir: bool,
183}
184
185#[cfg(not(target_arch = "wasm32"))]
186fn valid_walk_component(component: &str) -> bool {
187 !component.is_empty()
188 && component != "."
189 && component != ".."
190 && !component.contains(['/', '\\', '\0'])
191}
192
193#[cfg(not(target_arch = "wasm32"))]
194fn mount_io_error(action: &str, path: &Path, error: std::io::Error) -> MountError {
195 let detail = format!("{action} {path:?}: {error}");
196 if matches!(
197 error.raw_os_error(),
198 Some(libc::ELOOP | libc::EXDEV | libc::ENOTDIR)
199 ) {
200 return MountError::PermissionDenied(detail);
201 }
202 match error.kind() {
203 std::io::ErrorKind::NotFound => MountError::NotFound(detail),
204 std::io::ErrorKind::PermissionDenied => MountError::PermissionDenied(detail),
205 _ => MountError::Io(detail),
206 }
207}
208
209#[cfg(target_os = "linux")]
210fn open_beneath_without_symlinks(root: &File, relative: &str) -> std::io::Result<File> {
211 use std::ffi::CString;
212 use std::os::fd::{AsRawFd as _, FromRawFd as _};
213
214 #[repr(C)]
215 struct OpenHow {
216 flags: u64,
217 mode: u64,
218 resolve: u64,
219 }
220
221 const RESOLVE_NO_MAGICLINKS: u64 = 0x02;
222 const RESOLVE_NO_SYMLINKS: u64 = 0x04;
223 const RESOLVE_BENEATH: u64 = 0x08;
224
225 let relative = CString::new(relative)
226 .map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput))?;
227 let how = OpenHow {
228 flags: (libc::O_PATH | libc::O_CLOEXEC) as u64,
229 mode: 0,
230 resolve: RESOLVE_BENEATH | RESOLVE_NO_MAGICLINKS | RESOLVE_NO_SYMLINKS,
231 };
232 let descriptor = unsafe {
236 libc::syscall(
237 libc::SYS_openat2,
238 root.as_raw_fd(),
239 relative.as_ptr(),
240 &raw const how,
241 std::mem::size_of::<OpenHow>(),
242 )
243 };
244 if descriptor < 0 {
245 return Err(std::io::Error::last_os_error());
246 }
247 Ok(unsafe { File::from_raw_fd(descriptor as libc::c_int) })
249}
250
251#[cfg(target_os = "linux")]
252fn reopen_bound_handle(handle: &File, is_dir: bool) -> std::io::Result<File> {
253 use std::os::fd::AsRawFd as _;
254 use std::os::unix::fs::OpenOptionsExt as _;
255
256 let mut options = std::fs::OpenOptions::new();
257 options.read(true).custom_flags(
258 libc::O_CLOEXEC | libc::O_NONBLOCK | if is_dir { libc::O_DIRECTORY } else { 0 },
259 );
260 options.open(format!("/proc/self/fd/{}", handle.as_raw_fd()))
261}
262
263#[cfg(not(target_arch = "wasm32"))]
264fn fid_state(fid: &Fid) -> Result<&PdsDirectoryFid, MountError> {
265 fid.downcast_ref::<PdsDirectoryFid>()
266 .ok_or_else(|| MountError::InvalidArgument("PDS mount received a foreign fid".to_owned()))
267}
268
269#[cfg(not(target_arch = "wasm32"))]
270fn fid_state_mut(fid: &mut Fid) -> Result<&mut PdsDirectoryFid, MountError> {
271 fid.downcast_mut::<PdsDirectoryFid>()
272 .ok_or_else(|| MountError::InvalidArgument("PDS mount received a foreign fid".to_owned()))
273}
274
275#[cfg(not(target_arch = "wasm32"))]
276#[async_trait]
277impl Mount for PdsDirectoryMount {
278 async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
279 let relative = self.relative_path(components)?;
280 let display_path = self.root.join(&relative);
281 #[cfg(not(target_os = "linux"))]
282 return Err(MountError::NotSupported(
283 "descriptor-bound PDS walk requires Linux openat2".to_owned(),
284 ));
285 #[cfg(target_os = "linux")]
286 {
287 let handle = open_beneath_without_symlinks(&self.root_directory, &relative)
288 .map_err(|error| mount_io_error("resolve during walk", &display_path, error))?;
289 let metadata = handle
290 .metadata()
291 .map_err(|error| mount_io_error("stat walked descriptor", &display_path, error))?;
292 if !metadata.is_dir() && !metadata.is_file() {
293 return Err(MountError::PermissionDenied(format!(
294 "PDS walk accepts only ordinary files and directories: {display_path:?}"
295 )));
296 }
297 Ok(Fid::new(PdsDirectoryFid {
298 handle,
299 opened_file: Mutex::new(None),
300 components: components
301 .iter()
302 .map(|component| (*component).to_owned())
303 .collect(),
304 is_dir: metadata.is_dir(),
305 }))
306 }
307 }
308
309 async fn open(&self, fid: &mut Fid, mode: u8, _caller: &Subject) -> Result<(), MountError> {
310 if mode & 0x03 != 0 {
311 return Err(MountError::PermissionDenied(
312 "PDS account mount is read-only".to_owned(),
313 ));
314 }
315 let state = fid_state_mut(fid)?;
316 #[cfg(not(target_os = "linux"))]
317 return Err(MountError::NotSupported(
318 "descriptor-bound PDS open requires Linux /proc".to_owned(),
319 ));
320 #[cfg(target_os = "linux")]
321 {
322 let file = reopen_bound_handle(&state.handle, state.is_dir).map_err(|error| {
323 MountError::Io(format!("open walked PDS descriptor for reading: {error}"))
324 })?;
325 *state.opened_file.lock() = Some(file);
326 }
327 Ok(())
328 }
329
330 async fn read(
331 &self,
332 fid: &Fid,
333 offset: u64,
334 count: u32,
335 _caller: &Subject,
336 ) -> Result<Vec<u8>, MountError> {
337 let state = fid_state(fid)?;
338 if state.is_dir {
339 return Err(MountError::IsDirectory(state.components.join("/")));
340 }
341 let mut opened_file = state.opened_file.lock();
342 let file = opened_file
343 .as_mut()
344 .ok_or_else(|| MountError::InvalidArgument("PDS fid is not open".to_owned()))?;
345 file.seek(SeekFrom::Start(offset))
346 .map_err(|error| MountError::Io(format!("seek PDS record: {error}")))?;
347 let mut bytes = vec![0; count as usize];
348 let read = file
349 .read(&mut bytes)
350 .map_err(|error| MountError::Io(format!("read PDS record: {error}")))?;
351 bytes.truncate(read);
352 Ok(bytes)
353 }
354
355 async fn write(
356 &self,
357 _fid: &Fid,
358 _offset: u64,
359 _data: &[u8],
360 _caller: &Subject,
361 ) -> Result<u32, MountError> {
362 Err(MountError::PermissionDenied(
363 "PDS account mount is read-only".to_owned(),
364 ))
365 }
366
367 async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
368 let state = fid_state(fid)?;
369 if !state.is_dir {
370 return Err(MountError::NotDirectory(state.components.join("/")));
371 }
372
373 #[cfg(not(target_os = "linux"))]
374 return Err(MountError::NotSupported(
375 "descriptor-bound PDS readdir requires Linux /proc".to_owned(),
376 ));
377
378 #[cfg(target_os = "linux")]
379 {
380 use std::os::fd::AsRawFd as _;
381 let opened_file = state.opened_file.lock();
382 let file = opened_file
383 .as_ref()
384 .ok_or_else(|| MountError::InvalidArgument("PDS fid is not open".to_owned()))?;
385 let descriptor = PathBuf::from(format!("/proc/self/fd/{}", file.as_raw_fd()));
386 let entries = std::fs::read_dir(&descriptor)
387 .map_err(|error| mount_io_error("read PDS directory", &descriptor, error))?;
388 let mut result = Vec::new();
389 for entry in entries {
390 let entry = entry.map_err(|error| {
391 mount_io_error("read PDS directory entry", &descriptor, error)
392 })?;
393 let name = entry.file_name().into_string().map_err(|_| {
394 MountError::InvalidArgument(
395 "PDS directory contains a non-UTF-8 name".to_owned(),
396 )
397 })?;
398 let file_type = entry.file_type().map_err(|error| {
399 mount_io_error("type PDS directory entry", &entry.path(), error)
400 })?;
401 let metadata = std::fs::symlink_metadata(entry.path()).map_err(|error| {
402 mount_io_error("stat PDS directory entry", &entry.path(), error)
403 })?;
404 result.push(DirEntry {
405 name,
406 is_dir: file_type.is_dir(),
407 size: metadata.len(),
408 stat: None,
409 });
410 }
411 result.sort_by(|left, right| left.name.cmp(&right.name));
412 Ok(result)
413 }
414 }
415
416 async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
417 let state = fid_state(fid)?;
418 let opened_file = state.opened_file.lock();
419 let metadata = opened_file
420 .as_ref()
421 .ok_or_else(|| MountError::InvalidArgument("PDS fid is not open".to_owned()))?
422 .metadata()
423 .map_err(|error| MountError::Io(format!("stat PDS descriptor: {error}")))?;
424 Ok(Stat::unknown_qid(
425 if metadata.is_dir() { 0x80 } else { 0 },
426 metadata.len(),
427 state.components.last().cloned().unwrap_or_default(),
428 0,
429 ))
430 }
431
432 async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
433}
434
435pub trait PdsClearanceSource: Send + Sync {
443 fn clearance_for(
444 &self,
445 subject: &Subject,
446 verified_tenant: Option<&str>,
447 request_context: Option<&SecurityContext>,
448 ) -> Option<SecurityContext>;
449}
450
451#[derive(Debug, Default, Clone, Copy)]
458pub struct EnrollmentPdsClearanceSource;
459
460impl PdsClearanceSource for EnrollmentPdsClearanceSource {
461 fn clearance_for(
462 &self,
463 subject: &Subject,
464 verified_tenant: Option<&str>,
465 request_context: Option<&SecurityContext>,
466 ) -> Option<SecurityContext> {
467 let subject_id = subject.name()?;
468 if subject_id == OAUTH_ACCOUNT_RESOLVER_SUBJECT {
469 return Some(SecurityContext::from_clearance(
470 pds_account_label(),
471 VerifiedKeyMaterial::Classical,
472 ));
473 }
474 verified_tenant?;
475 request_context.cloned()
476 }
477}
478
479pub struct PdsAccountReadPep {
481 clearance: Arc<dyn PdsClearanceSource>,
482 labels: Arc<dyn ObjectLabelResolver + Send + Sync>,
483 sink: Arc<dyn AuditSink>,
484}
485
486impl PdsAccountReadPep {
487 pub fn new(
488 clearance: Arc<dyn PdsClearanceSource>,
489 labels: Arc<dyn ObjectLabelResolver + Send + Sync>,
490 sink: Arc<dyn AuditSink>,
491 ) -> Self {
492 Self {
493 clearance,
494 labels,
495 sink,
496 }
497 }
498
499 fn check(
500 &self,
501 subject: &Subject,
502 verified_tenant: Option<&str>,
503 request_context: Option<&SecurityContext>,
504 object_id: &str,
505 ) -> MacDecision {
506 let components: Vec<&str> = object_id
507 .split('/')
508 .filter(|component| !component.is_empty())
509 .collect();
510 let label = self.labels.resolve(ObjectRef::Path(&components));
511 let Some(ctx) = self
512 .clearance
513 .clearance_for(subject, verified_tenant, request_context)
514 else {
515 return self.audit(
516 subject,
517 object_id,
518 None,
519 label,
520 MacDecision::Deny(MacDenyReason::NoClearance),
521 );
522 };
523 let Some(label) = label else {
524 return self.audit(
525 subject,
526 object_id,
527 Some(&ctx),
528 None,
529 MacDecision::Deny(MacDenyReason::UnlabeledObject),
530 );
531 };
532
533 let decision = if ctx.can_access(&label) {
534 MacDecision::Permit
535 } else {
536 MacDecision::Deny(MacDenyReason::FloorDeny)
537 };
538 self.audit(subject, object_id, Some(&ctx), Some(label), decision)
539 }
540
541 fn audit(
542 &self,
543 subject: &Subject,
544 object_id: &str,
545 ctx: Option<&SecurityContext>,
546 label: Option<SecurityLabel>,
547 decision: MacDecision,
548 ) -> MacDecision {
549 let (audit_decision, reason) = match decision {
550 MacDecision::Permit => (Decision::Permit, DecisionReason::Permit),
551 MacDecision::Deny(MacDenyReason::NoClearance) => {
552 (Decision::Deny, DecisionReason::NoClearance)
553 }
554 MacDecision::Deny(MacDenyReason::UnlabeledObject) => {
555 (Decision::Deny, DecisionReason::UnlabeledObject)
556 }
557 MacDecision::Deny(
558 MacDenyReason::FloorDeny
559 | MacDenyReason::NoPepInstalled
560 | MacDenyReason::StaleAuthority,
561 ) => (Decision::Deny, DecisionReason::FloorDeny),
562 };
563 let policy = crate::mac::compiled_policy();
564 let record = AuditRecord {
565 seq: 0,
566 prev_hash: [0; 32],
567 ts_unix_nanos: SystemTime::now()
568 .duration_since(UNIX_EPOCH)
569 .map_or(0, |duration| duration.as_nanos()),
570 decision: audit_decision,
571 generation: policy.as_ref().map_or(0, |policy| policy.generation),
572 policy_hash: policy.as_ref().and_then(|policy| policy.policy_hash().ok()),
573 subject_type: PDS_SUBJECT_TYPE,
574 subject_clearance: ctx
575 .map(|context| *context.clearance())
576 .unwrap_or_else(SecurityLabel::bottom),
577 on_behalf_of: None,
578 object_type: PDS_OBJECT_TYPE,
579 object_label: label.unwrap_or_else(SecurityLabel::bottom),
580 action: Action::from_scope_action(ScopeAction::Query),
581 reason,
582 subject_id: Some(subject.to_string()),
583 object_id: Some(object_id.to_owned()),
584 };
585
586 match self.sink.record(&record) {
587 Ok(()) => decision,
588 Err(error) => {
589 let deny_record = AuditRecord {
590 decision: Decision::Deny,
591 reason: DecisionReason::AuditFailClosed,
592 ..record
593 };
594 let _ = self.sink.record(&deny_record);
595 tracing::error!(
596 target: "hyprstream.mac.pds_pep",
597 %error,
598 "PDS account-read decision could not be durably audited; enforcing deny"
599 );
600 MacDecision::Deny(MacDenyReason::FloorDeny)
601 }
602 }
603 }
604}
605
606impl AccountRecordReadAuthorizer for PdsAccountReadPep {
607 fn check_read(
608 &self,
609 subject: &Subject,
610 verified_tenant: Option<&str>,
611 security_context: Option<&SecurityContext>,
612 object_id: &str,
613 ) -> MacDecision {
614 self.check(subject, verified_tenant, security_context, object_id)
615 }
616}
617
618pub fn production_pds_account_read_authorizer(
621 sink: Arc<dyn AuditSink>,
622) -> Arc<dyn AccountRecordReadAuthorizer> {
623 Arc::new(PdsAccountReadPep::new(
624 Arc::new(EnrollmentPdsClearanceSource),
625 Arc::new(PdsAccountObjectLabelResolver),
626 sink,
627 ))
628}
629
630#[cfg(not(target_arch = "wasm32"))]
638pub fn production_pds_account_record_store(
639 mount: Arc<PdsDirectoryMount>,
640 sink: Arc<dyn AuditSink>,
641) -> Arc<hyprstream_pds_service::AccountRecordStore> {
642 Arc::new(hyprstream_pds_service::AccountRecordStore::new(
643 mount,
644 production_pds_account_read_authorizer(sink),
645 ))
646}
647
648#[cfg(test)]
649#[allow(clippy::unwrap_used)]
650mod tests {
651 use std::sync::atomic::{AtomicUsize, Ordering};
652
653 use async_trait::async_trait;
654 use ed25519_dalek::SigningKey;
655 use parking_lot::Mutex;
656 use rand::rngs::OsRng;
657
658 use hyprstream_pds_service::{AccountReadError, AccountRecordStore};
659 use hyprstream_rpc::auth::mac::{Assurance, CompartmentSet, Level};
660 use hyprstream_rpc::EnvelopeContext;
661 use hyprstream_vfs::{DirEntry, Fid, Mount, MountError, Stat};
662
663 use super::*;
664 use crate::mac::audit::{AuditError, AuditRecord};
665
666 #[derive(Default)]
667 struct SpySink {
668 records: Mutex<Vec<AuditRecord>>,
669 }
670
671 impl AuditSink for SpySink {
672 fn record(&self, record: &AuditRecord) -> Result<(), AuditError> {
673 self.records.lock().push(record.clone());
674 Ok(())
675 }
676 }
677
678 struct PublicReaders;
679
680 impl PdsClearanceSource for PublicReaders {
681 fn clearance_for(
682 &self,
683 subject: &Subject,
684 verified_tenant: Option<&str>,
685 _request_context: Option<&SecurityContext>,
686 ) -> Option<SecurityContext> {
687 ((subject.name() == Some("alice") && verified_tenant == Some("acme"))
688 || (subject.name() == Some(OAUTH_ACCOUNT_RESOLVER_SUBJECT)
689 && verified_tenant.is_none()))
690 .then(|| {
691 SecurityContext::from_clearance(
692 label(Level::Public),
693 VerifiedKeyMaterial::Classical,
694 )
695 })
696 }
697 }
698
699 struct ConfidentialReaders;
700
701 impl PdsClearanceSource for ConfidentialReaders {
702 fn clearance_for(
703 &self,
704 subject: &Subject,
705 verified_tenant: Option<&str>,
706 _request_context: Option<&SecurityContext>,
707 ) -> Option<SecurityContext> {
708 (subject.name() == Some("alice") && verified_tenant == Some("acme")).then(|| {
709 SecurityContext::from_clearance(
710 label(Level::Confidential),
711 VerifiedKeyMaterial::Classical,
712 )
713 })
714 }
715 }
716
717 struct NoClearance;
718
719 impl PdsClearanceSource for NoClearance {
720 fn clearance_for(
721 &self,
722 _subject: &Subject,
723 _verified_tenant: Option<&str>,
724 _request_context: Option<&SecurityContext>,
725 ) -> Option<SecurityContext> {
726 None
727 }
728 }
729
730 struct NoLabels;
731
732 impl ObjectLabelResolver for NoLabels {
733 fn resolve(&self, _object: ObjectRef<'_>) -> Option<SecurityLabel> {
734 None
735 }
736 }
737
738 #[derive(Default)]
739 struct FailingSink {
740 attempts: AtomicUsize,
741 records: Mutex<Vec<AuditRecord>>,
742 }
743
744 impl AuditSink for FailingSink {
745 fn record(&self, record: &AuditRecord) -> Result<(), AuditError> {
746 self.attempts.fetch_add(1, Ordering::SeqCst);
747 self.records.lock().push(record.clone());
748 Err(AuditError::Io("injected PDS audit failure".to_owned()))
749 }
750 }
751
752 struct AccountLabels;
753
754 impl ObjectLabelResolver for AccountLabels {
755 fn resolve(&self, object: ObjectRef<'_>) -> Option<SecurityLabel> {
756 match object {
757 ObjectRef::Path(["pds", "acme", "accounts", "alice", "account-record.cbor"]) => {
758 Some(label(Level::Secret))
759 }
760 _ => None,
761 }
762 }
763 }
764
765 #[derive(Default)]
766 struct ReadTrapMount {
767 walks: AtomicUsize,
768 opens: AtomicUsize,
769 stats: AtomicUsize,
770 reads: AtomicUsize,
771 readdirs: AtomicUsize,
772 }
773
774 #[async_trait]
775 impl Mount for ReadTrapMount {
776 async fn walk(&self, _components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
777 self.walks.fetch_add(1, Ordering::SeqCst);
778 Ok(Fid::new(()))
779 }
780
781 async fn open(
782 &self,
783 _fid: &mut Fid,
784 _mode: u8,
785 _caller: &Subject,
786 ) -> Result<(), MountError> {
787 self.opens.fetch_add(1, Ordering::SeqCst);
788 Ok(())
789 }
790
791 async fn read(
792 &self,
793 _fid: &Fid,
794 _offset: u64,
795 _count: u32,
796 _caller: &Subject,
797 ) -> Result<Vec<u8>, MountError> {
798 self.reads.fetch_add(1, Ordering::SeqCst);
799 Ok(b"record bytes must remain unreachable".to_vec())
800 }
801
802 async fn write(
803 &self,
804 _fid: &Fid,
805 _offset: u64,
806 _data: &[u8],
807 _caller: &Subject,
808 ) -> Result<u32, MountError> {
809 Err(MountError::NotSupported("read-only test mount".to_owned()))
810 }
811
812 async fn readdir(
813 &self,
814 _fid: &Fid,
815 _caller: &Subject,
816 ) -> Result<Vec<DirEntry>, MountError> {
817 self.readdirs.fetch_add(1, Ordering::SeqCst);
818 Ok(vec![DirEntry {
819 name: "tenant-bytes-must-remain-unreachable".to_owned(),
820 is_dir: true,
821 size: 0,
822 stat: None,
823 }])
824 }
825
826 async fn stat(&self, _fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
827 self.stats.fetch_add(1, Ordering::SeqCst);
828 Ok(Stat::unknown_qid(
829 0,
830 38,
831 "account-record.cbor".to_owned(),
832 0,
833 ))
834 }
835
836 async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
837 }
838
839 fn label(level: Level) -> SecurityLabel {
840 SecurityLabel::new(level, Assurance::Classical, CompartmentSet::EMPTY)
841 }
842
843 #[tokio::test]
844 async fn account_store_denies_before_record_bytes_and_audits_identity() {
845 let mount = Arc::new(ReadTrapMount::default());
846 let sink = Arc::new(SpySink::default());
847 let authorizer = Arc::new(PdsAccountReadPep::new(
848 Arc::new(PublicReaders),
849 Arc::new(AccountLabels),
850 sink.clone(),
851 ));
852 let store = AccountRecordStore::new(mount.clone(), authorizer);
853 let signer = SigningKey::generate(&mut OsRng);
854 let context = EnvelopeContext::for_test_authenticated_subject_in_tenant(
855 Subject::new("alice"),
856 "acme",
857 signer.verifying_key(),
858 );
859
860 let error = store
861 .scope(&context)
862 .unwrap()
863 .get("alice")
864 .await
865 .unwrap_err();
866 assert!(matches!(
867 error,
868 AccountReadError::MacDenied {
869 reason: MacDenyReason::FloorDeny,
870 ..
871 }
872 ));
873
874 assert_eq!(mount.walks.load(Ordering::SeqCst), 1);
875 assert_eq!(mount.opens.load(Ordering::SeqCst), 0);
876 assert_eq!(mount.stats.load(Ordering::SeqCst), 0);
877 assert_eq!(mount.reads.load(Ordering::SeqCst), 0);
878 assert_eq!(mount.readdirs.load(Ordering::SeqCst), 0);
879
880 let records = sink.records.lock();
881 assert_eq!(records.len(), 1);
882 assert_eq!(records[0].decision, Decision::Deny);
883 assert_eq!(records[0].reason, DecisionReason::FloorDeny);
884 assert_eq!(records[0].subject_id.as_deref(), Some("alice"));
885 assert_eq!(
886 records[0].object_id.as_deref(),
887 Some("/pds/acme/accounts/alice/account-record.cbor")
888 );
889 assert_eq!(records[0].subject_clearance, label(Level::Public));
890 assert_eq!(records[0].object_label, label(Level::Secret));
891 }
892
893 #[tokio::test]
894 async fn hosted_directory_deny_precedes_open_and_readdir_and_is_audited() {
895 let mount = Arc::new(ReadTrapMount::default());
896 let sink = Arc::new(SpySink::default());
897 let authorizer = Arc::new(PdsAccountReadPep::new(
898 Arc::new(PublicReaders),
899 Arc::new(PdsAccountObjectLabelResolver),
900 sink.clone(),
901 ));
902 let store = AccountRecordStore::new(mount.clone(), authorizer);
903 let error = store
904 .refresh_hosted_did_index(&Subject::new(OAUTH_ACCOUNT_RESOLVER_SUBJECT))
905 .await
906 .unwrap_err();
907 assert!(matches!(
908 error,
909 AccountReadError::MacDenied {
910 reason: MacDenyReason::FloorDeny,
911 ..
912 }
913 ));
914 assert_eq!(mount.walks.load(Ordering::SeqCst), 1);
915 assert_eq!(mount.opens.load(Ordering::SeqCst), 0);
916 assert_eq!(mount.readdirs.load(Ordering::SeqCst), 0);
917 assert_eq!(mount.stats.load(Ordering::SeqCst), 0);
918 assert_eq!(mount.reads.load(Ordering::SeqCst), 0);
919
920 let records = sink.records.lock();
921 assert_eq!(records.len(), 1);
922 assert_eq!(records[0].decision, Decision::Deny);
923 assert_eq!(records[0].reason, DecisionReason::FloorDeny);
924 assert_eq!(
925 records[0].subject_id.as_deref(),
926 Some(OAUTH_ACCOUNT_RESOLVER_SUBJECT)
927 );
928 assert_eq!(records[0].object_id.as_deref(), Some("/pds"));
929 }
930
931 #[tokio::test]
932 async fn audit_failure_downgrades_permit_before_record_open() {
933 let mount = Arc::new(ReadTrapMount::default());
934 let sink = Arc::new(FailingSink::default());
935 let authorizer = Arc::new(PdsAccountReadPep::new(
936 Arc::new(ConfidentialReaders),
937 Arc::new(PdsAccountObjectLabelResolver),
938 sink.clone(),
939 ));
940 let store = AccountRecordStore::new(mount.clone(), authorizer);
941 let signer = SigningKey::generate(&mut OsRng);
942 let context = EnvelopeContext::for_test_authenticated_subject_in_tenant(
943 Subject::new("alice"),
944 "acme",
945 signer.verifying_key(),
946 );
947
948 let error = store
949 .scope(&context)
950 .unwrap()
951 .get("alice")
952 .await
953 .unwrap_err();
954 assert!(matches!(
955 error,
956 AccountReadError::MacDenied {
957 reason: MacDenyReason::FloorDeny,
958 ..
959 }
960 ));
961 assert_eq!(mount.walks.load(Ordering::SeqCst), 1);
962 assert_eq!(mount.opens.load(Ordering::SeqCst), 0);
963 assert_eq!(mount.stats.load(Ordering::SeqCst), 0);
964 assert_eq!(mount.reads.load(Ordering::SeqCst), 0);
965 assert_eq!(sink.attempts.load(Ordering::SeqCst), 2);
966 let records = sink.records.lock();
967 assert_eq!(records[0].decision, Decision::Permit);
968 assert_eq!(records[1].decision, Decision::Deny);
969 assert_eq!(records[1].reason, DecisionReason::AuditFailClosed);
970 assert_eq!(records[1].subject_id.as_deref(), Some("alice"));
971 assert_eq!(
972 records[1].object_id.as_deref(),
973 Some("/pds/acme/accounts/alice/account-record.cbor")
974 );
975 }
976
977 #[test]
978 fn missing_clearance_and_label_denials_are_audited_with_identities() {
979 let sink = Arc::new(SpySink::default());
980 let no_clearance = PdsAccountReadPep::new(
981 Arc::new(NoClearance),
982 Arc::new(PdsAccountObjectLabelResolver),
983 sink.clone(),
984 );
985 let object = "/pds/acme/accounts/alice/account-record.cbor";
986 assert_eq!(
987 no_clearance.check_read(&Subject::new("alice"), Some("acme"), None, object),
988 MacDecision::Deny(MacDenyReason::NoClearance)
989 );
990
991 let no_label = PdsAccountReadPep::new(
992 Arc::new(ConfidentialReaders),
993 Arc::new(NoLabels),
994 sink.clone(),
995 );
996 assert_eq!(
997 no_label.check_read(&Subject::new("alice"), Some("acme"), None, object),
998 MacDecision::Deny(MacDenyReason::UnlabeledObject)
999 );
1000
1001 let records = sink.records.lock();
1002 assert_eq!(records.len(), 2);
1003 assert_eq!(records[0].reason, DecisionReason::NoClearance);
1004 assert_eq!(records[1].reason, DecisionReason::UnlabeledObject);
1005 for record in records.iter() {
1006 assert_eq!(record.decision, Decision::Deny);
1007 assert_eq!(record.subject_id.as_deref(), Some("alice"));
1008 assert_eq!(record.object_id.as_deref(), Some(object));
1009 }
1010 }
1011
1012 #[test]
1013 fn production_sources_label_only_account_artifacts_and_recognize_oauth() {
1014 let resolver = PdsAccountObjectLabelResolver;
1015 assert_eq!(
1016 resolver.resolve(ObjectRef::Path(&["pds"])),
1017 Some(pds_account_label())
1018 );
1019 assert_eq!(
1020 resolver.resolve(ObjectRef::Path(&["pds", "acme"])),
1021 Some(pds_account_label())
1022 );
1023 assert_eq!(
1024 resolver.resolve(ObjectRef::Path(&["pds", "acme", PDS_ACCOUNTS_DIRECTORY,])),
1025 Some(pds_account_label())
1026 );
1027 assert_eq!(
1028 resolver.resolve(ObjectRef::Path(&[
1029 "pds",
1030 "acme",
1031 PDS_ACCOUNTS_DIRECTORY,
1032 "alice",
1033 ])),
1034 Some(pds_account_label())
1035 );
1036 assert_eq!(
1037 resolver.resolve(ObjectRef::Path(&[
1038 "pds",
1039 "acme",
1040 PDS_ACCOUNTS_DIRECTORY,
1041 "alice",
1042 PDS_ACCOUNT_RECORD_FILE,
1043 ])),
1044 Some(pds_account_label())
1045 );
1046 assert_eq!(
1047 resolver.resolve(ObjectRef::Path(&[
1048 "pds",
1049 "acme",
1050 PDS_ACCOUNTS_DIRECTORY,
1051 "alice",
1052 PDS_ACCOUNT_DID_DOCUMENT_FILE,
1053 ])),
1054 Some(pds_account_label())
1055 );
1056 assert_eq!(
1057 resolver.resolve(ObjectRef::Path(&[
1058 "pds",
1059 "acme",
1060 PDS_ACCOUNTS_DIRECTORY,
1061 "alice",
1062 PDS_ACCOUNT_DID_LOG_FILE,
1063 ])),
1064 Some(pds_account_label())
1065 );
1066 assert_eq!(
1067 resolver.resolve(ObjectRef::Path(&[
1068 "pds",
1069 "acme",
1070 PDS_ACCOUNTS_DIRECTORY,
1071 "alice",
1072 ATPROTO_SIGNING_KEY_FILE,
1073 ])),
1074 Some(pds_account_label())
1075 );
1076 assert_eq!(
1077 resolver.resolve(ObjectRef::Path(&["pds", "acme", "private-key"])),
1078 None
1079 );
1080
1081 let source = EnrollmentPdsClearanceSource;
1082 let oauth = source
1083 .clearance_for(&Subject::new(OAUTH_ACCOUNT_RESOLVER_SUBJECT), None, None)
1084 .unwrap();
1085 assert!(oauth.can_access(&pds_account_label()));
1086 assert!(source
1087 .clearance_for(&Subject::new("alice"), None, None)
1088 .is_none());
1089
1090 let attenuated =
1091 SecurityContext::from_clearance(label(Level::Public), VerifiedKeyMaterial::Classical);
1092 assert_eq!(
1093 source
1094 .clearance_for(&Subject::new("alice"), Some("acme"), Some(&attenuated))
1095 .unwrap(),
1096 attenuated
1097 );
1098 }
1099
1100 #[test]
1101 fn production_genesis_pep_permits_exact_artifacts_and_audits_denials() {
1102 let sink = Arc::new(SpySink::default());
1103 let pep = production_pds_account_read_authorizer(sink.clone());
1104 let oauth = Subject::new(OAUTH_ACCOUNT_RESOLVER_SUBJECT);
1105 for file in ["commit.cbor", "public-commit.cbor"] {
1106 let object = format!("/pds/acme/accounts/alice/repo/{file}");
1107 assert_eq!(
1108 pep.check_read(&oauth, Some("acme"), None, &object),
1109 MacDecision::Permit
1110 );
1111 let records = sink.records.lock();
1112 let record = records.last().unwrap();
1113 assert_eq!(record.object_id.as_deref(), Some(object.as_str()));
1114 assert_eq!(
1115 record.subject_id.as_deref(),
1116 Some(OAUTH_ACCOUNT_RESOLVER_SUBJECT)
1117 );
1118 assert_eq!(record.object_label, pds_account_label());
1119 assert_eq!(record.reason, DecisionReason::Permit);
1120 }
1121 for object in [
1122 "/pds/acme/accounts/alice/repo",
1123 "/pds/acme/accounts/alice/repo/head",
1124 "/pds/acme/accounts/alice/repo/blocks/block.cbor",
1125 "/pds/acme/accounts/alice/repo/private-key",
1126 "/pds/acme/accounts/alice/repo/commit.cbor/child",
1127 "/pds/acme/accounts/alice/repo/../commit.cbor",
1128 "/pds/../accounts/alice/repo/commit.cbor",
1129 "/pds/*/accounts/alice/repo/commit.cbor",
1130 "/pds/acme/accounts/ALICE/repo/commit.cbor",
1131 "/pds/acme/accounts/-alice/repo/commit.cbor",
1132 ] {
1133 assert_eq!(
1134 pep.check_read(&oauth, Some("acme"), None, object),
1135 MacDecision::Deny(MacDenyReason::UnlabeledObject),
1136 "{object}"
1137 );
1138 let records = sink.records.lock();
1139 let record = records.last().unwrap();
1140 assert_eq!(record.object_id.as_deref(), Some(object));
1141 assert_eq!(record.decision, Decision::Deny);
1142 assert_eq!(record.reason, DecisionReason::UnlabeledObject);
1143 }
1144 let object = "/pds/acme/accounts/alice/repo/commit.cbor";
1145 assert_eq!(
1146 pep.check_read(&Subject::new("alice"), Some("acme"), None, object),
1147 MacDecision::Deny(MacDenyReason::NoClearance)
1148 );
1149 let attenuated =
1150 SecurityContext::from_clearance(label(Level::Public), VerifiedKeyMaterial::Classical);
1151 assert_eq!(
1152 pep.check_read(
1153 &Subject::new("alice"),
1154 Some("acme"),
1155 Some(&attenuated),
1156 object
1157 ),
1158 MacDecision::Deny(MacDenyReason::FloorDeny)
1159 );
1160 let failing = Arc::new(FailingSink::default());
1161 let pep = production_pds_account_read_authorizer(failing.clone());
1162 assert_eq!(
1163 pep.check_read(&oauth, Some("acme"), None, object),
1164 MacDecision::Deny(MacDenyReason::FloorDeny)
1165 );
1166 let records = failing.records.lock();
1167 assert_eq!(records[0].decision, Decision::Permit);
1168 assert_eq!(records[1].reason, DecisionReason::AuditFailClosed);
1169 }
1170
1171 #[tokio::test]
1172 async fn production_directory_mount_keeps_the_walked_record_descriptor_bound() {
1173 let temporary = tempfile::tempdir().unwrap();
1174 let root = temporary.path().join("pds");
1175 let record_dir = root.join("acme/accounts/alice");
1176 std::fs::create_dir_all(&record_dir).unwrap();
1177 let record = record_dir.join(PDS_ACCOUNT_RECORD_FILE);
1178 std::fs::write(&record, b"original").unwrap();
1179 let mount = PdsDirectoryMount::open(&root).unwrap();
1180 let subject = Subject::new("alice");
1181 let components = [
1182 "acme",
1183 PDS_ACCOUNTS_DIRECTORY,
1184 "alice",
1185 PDS_ACCOUNT_RECORD_FILE,
1186 ];
1187 let mut fid = mount.walk(&components, &subject).await.unwrap();
1188
1189 let replaced = record_dir.join("replaced.cbor");
1190 std::fs::rename(&record, &replaced).unwrap();
1191 std::fs::write(&record, b"substitute").unwrap();
1192
1193 mount
1194 .open(&mut fid, hyprstream_vfs::OREAD, &subject)
1195 .await
1196 .unwrap();
1197 assert_eq!(
1198 mount.read(&fid, 0, 64, &subject).await.unwrap(),
1199 b"original"
1200 );
1201 mount.clunk(fid, &subject).await;
1202 }
1203
1204 #[tokio::test]
1205 async fn production_directory_mount_rejects_final_and_intermediate_symlinks() {
1206 use std::os::unix::fs::symlink;
1207
1208 let temporary = tempfile::tempdir().unwrap();
1209 let root = temporary.path().join("pds");
1210 let acme = root.join("acme/accounts/alice");
1211 let beta = root.join("beta/accounts/alice");
1212 std::fs::create_dir_all(&acme).unwrap();
1213 std::fs::create_dir_all(&beta).unwrap();
1214 let beta_record = beta.join(PDS_ACCOUNT_RECORD_FILE);
1215 std::fs::write(&beta_record, b"beta").unwrap();
1216
1217 let final_link = acme.join(PDS_ACCOUNT_RECORD_FILE);
1218 symlink(&beta_record, &final_link).unwrap();
1219 let mount = PdsDirectoryMount::open(&root).unwrap();
1220 let subject = Subject::new("alice");
1221 let final_components = [
1222 "acme",
1223 PDS_ACCOUNTS_DIRECTORY,
1224 "alice",
1225 PDS_ACCOUNT_RECORD_FILE,
1226 ];
1227 assert!(matches!(
1228 mount.walk(&final_components, &subject).await,
1229 Err(MountError::PermissionDenied(_))
1230 ));
1231
1232 std::fs::remove_file(&final_link).unwrap();
1233 std::fs::remove_dir_all(root.join("acme/accounts")).unwrap();
1234 symlink(root.join("beta/accounts"), root.join("acme/accounts")).unwrap();
1235 assert!(matches!(
1236 mount.walk(&final_components, &subject).await,
1237 Err(MountError::PermissionDenied(_))
1238 ));
1239 }
1240
1241 #[tokio::test]
1242 async fn production_directory_mount_enumerates_only_real_root_directories() {
1243 use std::os::unix::fs::symlink;
1244
1245 let temporary = tempfile::tempdir().unwrap();
1246 let root = temporary.path().join("pds");
1247 std::fs::create_dir_all(root.join("acme")).unwrap();
1248 symlink(root.join("acme"), root.join("alias")).unwrap();
1249 let mount = PdsDirectoryMount::open(&root).unwrap();
1250 let subject = Subject::new(OAUTH_ACCOUNT_RESOLVER_SUBJECT);
1251 let mut fid = mount.walk(&[], &subject).await.unwrap();
1252 mount
1253 .open(&mut fid, hyprstream_vfs::OREAD, &subject)
1254 .await
1255 .unwrap();
1256 let entries = mount.readdir(&fid, &subject).await.unwrap();
1257 assert_eq!(entries.len(), 2);
1258 assert!(entries
1259 .iter()
1260 .any(|entry| entry.name == "acme" && entry.is_dir));
1261 assert!(entries
1262 .iter()
1263 .any(|entry| entry.name == "alias" && !entry.is_dir));
1264 mount.clunk(fid, &subject).await;
1265 }
1266}