Skip to main content

hyprstream_pds_service/
lib.rs

1//! Durable PDS service seams over Hyprstream's subject-carrying 9P plane.
2//!
3//! This crate owns the service boundary between the pure `hyprstream-pds`
4//! record library and deployment storage. It deliberately has no host-path or
5//! database API: callers provide the mount rooted at `/pds`, allowing CAS (and
6//! its storage-layer sealing policy) to remain below the service.
7//!
8//! The first demo slice is the account-record read path. A read scope can only
9//! be created from [`EnvelopeContext::domain`], which derives its value from
10//! `verified_tenant`. The tenant is never inferred from the subject, accepted
11//! from a request payload, or supplied as a free-form method argument.
12
13pub mod account_http;
14pub mod federation_intake;
15
16use std::{
17    collections::BTreeMap,
18    sync::{
19        atomic::{AtomicBool, Ordering},
20        Arc,
21    },
22    time::{Duration, Instant},
23};
24
25use hyprstream_pds::{
26    AccountLabel, AccountRecord, ATPROTO_SIGNING_KEY_FILE, DID_DOCUMENT_FILE, GENESIS_DID_OP_FILE,
27};
28use hyprstream_rpc::auth::mac::{MacDecision, MacDenyReason, SecurityContext};
29use hyprstream_rpc::{EnvelopeContext, Subject};
30use hyprstream_vfs::{Mount, MountError, OREAD};
31use thiserror::Error;
32
33/// Namespace location at which an [`AccountRecordStore`] backing mount is bound.
34pub const PDS_NAMESPACE: &str = "/pds";
35
36/// Directory component containing hosted account records within a tenant.
37pub const PDS_ACCOUNTS_DIRECTORY: &str = "accounts";
38/// Public account-record publication marker.
39pub const PDS_ACCOUNT_RECORD_FILE: &str = "account-record.cbor";
40/// Sealed account DID-document bytes published beside the account record.
41pub const PDS_ACCOUNT_DID_DOCUMENT_FILE: &str = DID_DOCUMENT_FILE;
42/// Sealed account operation-log bytes published beside the account record.
43pub const PDS_ACCOUNT_DID_LOG_FILE: &str = GENESIS_DID_OP_FILE;
44
45pub mod hosted_account_mint;
46
47/// Fixed internal principal allowed to resolve a hosted DID to its tenant.
48pub const OAUTH_ACCOUNT_RESOLVER_SUBJECT: &str = "service:oauth";
49const DEFAULT_MAX_RECORD_BYTES: usize = 64 * 1024;
50const READ_CHUNK_BYTES: usize = 8 * 1024;
51const ATPROTO_SIGNING_KEY_BYTES: usize = 32;
52
53/// Failure from the mandatory tenant boundary or the PDS record read.
54#[derive(Debug, Error)]
55pub enum AccountReadError {
56    #[error("PDS account access denied: caller is unauthenticated")]
57    UnauthenticatedCaller,
58    #[error("PDS account access denied: no valid verified tenant")]
59    MissingVerifiedTenant,
60    #[error("PDS account access denied: invalid verified tenant {0:?}")]
61    InvalidVerifiedTenant(String),
62    #[error("invalid hosted account label {0:?}")]
63    InvalidAccountLabel(String),
64    #[error("invalid hosted repository artifact name {0:?}")]
65    InvalidRepositoryArtifact(String),
66    #[error("PDS hosted-account tenant resolution denied for {0:?}")]
67    UnauthorizedTenantResolver(String),
68    #[error("PDS account read denied for {subject:?} on {object:?}: {reason:?}")]
69    MacDenied {
70        subject: String,
71        object: String,
72        reason: MacDenyReason,
73    },
74    #[error("invalid hosted account DID {0:?}")]
75    InvalidHostedAccountDid(String),
76    #[error("hosted account DID {0:?} is bound to more than one tenant")]
77    AmbiguousHostedAccountDid(String),
78    #[error("hosted account DID index is still warming")]
79    HostedDidIndexNotReady,
80    #[error("PDS account record exceeds the {limit}-byte read limit")]
81    RecordTooLarge { limit: usize },
82    #[error("PDS account record for {requested:?} contains label {stored:?}")]
83    RecordLabelMismatch { requested: String, stored: String },
84    #[error("PDS account record for {requested:?} contains DID {stored:?}")]
85    RecordDidMismatch { requested: String, stored: String },
86    #[error("hosted account #atproto signing key for {0:?} is unavailable")]
87    SigningKeyUnavailable(String),
88    #[error("hosted account #atproto signing key for {0:?} is invalid")]
89    InvalidSigningKey(String),
90    #[error("hosted account #atproto signing key for {0:?} does not match its account record")]
91    SigningKeyMismatch(String),
92    #[error("invalid PDS account record: {0}")]
93    InvalidRecord(#[source] anyhow::Error),
94    #[error("PDS mount operation failed: {0}")]
95    Mount(#[source] MountError),
96}
97
98impl From<MountError> for AccountReadError {
99    fn from(error: MountError) -> Self {
100        Self::Mount(error)
101    }
102}
103
104/// Mandatory MAC capability for account-record reads.
105///
106/// Implementations resolve the subject clearance and the trusted label of the
107/// exact canonical `object_id`, apply the lattice floor, and audit every MAC
108/// decision. Input-validation and mount-resolution errors are not policy
109/// decisions; they fail before an object read is attempted. The account store
110/// has no constructor without this capability.
111pub trait AccountRecordReadAuthorizer: Send + Sync {
112    /// Check a read before the store opens or reads the fid bound to
113    /// `object_id`.
114    ///
115    /// `security_context` is derived from the verified request envelope and
116    /// retains its assurance and delegated attenuation. It is `None` only when
117    /// the request had no MAC clearance, or for the fixed OAuth service's
118    /// tenant-index lookup before a hosted-account binding has been resolved.
119    fn check_read(
120        &self,
121        subject: &Subject,
122        verified_tenant: Option<&str>,
123        security_context: Option<&SecurityContext>,
124        object_id: &str,
125    ) -> MacDecision;
126}
127
128/// Read-only account record service over a mount rooted at [`PDS_NAMESPACE`].
129///
130/// Every construction requires an [`AccountRecordReadAuthorizer`]. The store
131/// binds the requested canonical name to one fid, MAC-authorizes that exact
132/// name, and only then opens and reads from the same fid.
133#[derive(Clone)]
134pub struct AccountRecordStore {
135    pds_mount: Arc<dyn Mount>,
136    read_authorizer: Arc<dyn AccountRecordReadAuthorizer>,
137    max_record_bytes: usize,
138    hosted_did_index: Arc<tokio::sync::RwLock<Option<HostedDidIndex>>>,
139    hosted_did_index_refresh: Arc<tokio::sync::Mutex<()>>,
140    hosted_did_index_refreshing: Arc<AtomicBool>,
141    hosted_did_index_refreshed: Arc<tokio::sync::Notify>,
142    hosted_did_index_last_attempt: Arc<parking_lot::Mutex<Option<Instant>>>,
143}
144
145struct HostedDidIndex {
146    entries: BTreeMap<(String, String), Option<String>>,
147    built_at: Instant,
148}
149
150const HOSTED_DID_INDEX_TTL: Duration = Duration::from_secs(5);
151const HOSTED_DID_MAX_STALE: Duration = Duration::from_secs(30);
152const HOSTED_DID_REFRESH_RETRY_COOLDOWN: Duration = Duration::from_secs(1);
153const HOSTED_DID_REFRESH_WAIT: Duration = Duration::from_secs(1);
154const HOSTED_DID_NEGATIVE_TTL: Duration = HOSTED_DID_INDEX_TTL;
155
156impl AccountRecordStore {
157    /// Construct a store over the mount bound at `/pds` and a mandatory MAC
158    /// read capability.
159    pub fn new(
160        pds_mount: Arc<dyn Mount>,
161        read_authorizer: Arc<dyn AccountRecordReadAuthorizer>,
162    ) -> Self {
163        Self {
164            pds_mount,
165            read_authorizer,
166            max_record_bytes: DEFAULT_MAX_RECORD_BYTES,
167            hosted_did_index: Arc::new(tokio::sync::RwLock::new(None)),
168            hosted_did_index_refresh: Arc::new(tokio::sync::Mutex::new(())),
169            hosted_did_index_refreshing: Arc::new(AtomicBool::new(false)),
170            hosted_did_index_refreshed: Arc::new(tokio::sync::Notify::new()),
171            hosted_did_index_last_attempt: Arc::new(parking_lot::Mutex::new(None)),
172        }
173    }
174
175    /// Capture a tenant-scoped account reader from a verified RPC context.
176    ///
177    /// `EnvelopeContext::domain()` is the only tenant input. It fails closed
178    /// when `verified_tenant` is missing, empty, or wildcard. This method then
179    /// applies path-component validation before the tenant can reach 9P.
180    pub fn scope(&self, context: &EnvelopeContext) -> Result<AccountReadScope, AccountReadError> {
181        let subject = context.subject();
182        if subject.is_anonymous() {
183            return Err(AccountReadError::UnauthenticatedCaller);
184        }
185
186        let tenant = context
187            .domain()
188            .map_err(|_| AccountReadError::MissingVerifiedTenant)?;
189        validate_tenant_component(&tenant)?;
190
191        Ok(AccountReadScope {
192            pds_mount: Arc::clone(&self.pds_mount),
193            read_authorizer: Arc::clone(&self.read_authorizer),
194            max_record_bytes: self.max_record_bytes,
195            tenant,
196            subject,
197            security_context: context.security_context(),
198        })
199    }
200
201    /// Resolve a hosted account DID to its authority-owned tenant binding.
202    ///
203    /// Unlike [`Self::scope`], this lookup starts without a tenant because the
204    /// ATProto assertion proves only the DID. It therefore accepts no tenant
205    /// argument: the OAuth service identity scans the account-record index and
206    /// returns the tenant containing the one canonical record whose DID
207    /// matches. Missing records return `Ok(None)` (federated-only identity);
208    /// corrupt, denied, or ambiguous records fail closed.
209    pub async fn resolve_tenant_for_hosted_did(
210        &self,
211        authority: &Subject,
212        did: &str,
213    ) -> Result<Option<String>, AccountReadError> {
214        if authority.name() != Some(OAUTH_ACCOUNT_RESOLVER_SUBJECT) {
215            return Err(AccountReadError::UnauthorizedTenantResolver(
216                authority.to_string(),
217            ));
218        }
219        let Some(label) = hosted_account_label(did)? else {
220            return Ok(None);
221        };
222
223        let mut index = self.hosted_did_index.read().await;
224        if index.as_ref().is_some_and(|snapshot| {
225            snapshot.built_at.elapsed() >= HOSTED_DID_INDEX_TTL + HOSTED_DID_MAX_STALE
226        }) {
227            // The first request after an idle period may wait for the shared
228            // isolated refresher, but must never scan tenants itself or serve
229            // an expired binding. Subscribe before releasing the read lock so
230            // a concurrent refresh cannot publish unnoticed.
231            let refreshed = self.hosted_did_index_refreshed.notified();
232            tokio::pin!(refreshed);
233            refreshed.as_mut().enable();
234            drop(index);
235            self.schedule_hosted_did_index_refresh(authority.clone());
236            let _ = tokio::time::timeout(HOSTED_DID_REFRESH_WAIT, refreshed).await;
237            index = self.hosted_did_index.read().await;
238        }
239        let Some(snapshot) = index.as_ref() else {
240            // A request must never become the tenant enumerator. Startup
241            // refresh runs independently; callers retry after the index is
242            // ready instead of amplifying a full mount scan per miss.
243            self.schedule_hosted_did_index_refresh(authority.clone());
244            return Err(AccountReadError::HostedDidIndexNotReady);
245        };
246        let age = snapshot.built_at.elapsed();
247        if age >= HOSTED_DID_INDEX_TTL {
248            self.schedule_hosted_did_index_refresh(authority.clone());
249        }
250        if age >= HOSTED_DID_INDEX_TTL + HOSTED_DID_MAX_STALE {
251            return Err(AccountReadError::HostedDidIndexNotReady);
252        }
253        let key = (label.to_owned(), did.to_owned());
254        match snapshot.entries.get(&key) {
255            Some(Some(tenant)) => Ok(Some(tenant.clone())),
256            Some(None) => Err(AccountReadError::AmbiguousHostedAccountDid(did.to_owned())),
257            None if age < HOSTED_DID_NEGATIVE_TTL => Ok(None),
258            None => {
259                // A negative entry is eligible for refresh at the normal
260                // snapshot interval, but remains a stable 404 while refresh
261                // runs. This avoids turning ordinary missing-account traffic
262                // into repeated transient OAuth/HTTP failures.
263                self.schedule_hosted_did_index_refresh(authority.clone());
264                Ok(None)
265            }
266        }
267    }
268
269    /// Uncached authority read for disabled Federate admission integration.
270    /// The caller must impose an aggregate deadline and capacity bound. This
271    /// never publishes or consumes the shared hosted-DID cache. The admitted
272    /// mount remains responsible for signed-record authority and freshness.
273    pub async fn resolve_current_tenant_for_hosted_did(
274        &self,
275        authority: &Subject,
276        did: &str,
277    ) -> Result<Option<String>, AccountReadError> {
278        if authority.name() != Some(OAUTH_ACCOUNT_RESOLVER_SUBJECT) {
279            return Err(AccountReadError::UnauthorizedTenantResolver(
280                authority.to_string(),
281            ));
282        }
283        let Some(label) = hosted_account_label(did)? else {
284            return Ok(None);
285        };
286        let tenants = read_directory(
287            self.pds_mount.as_ref(),
288            self.read_authorizer.as_ref(),
289            &[],
290            authority,
291            None,
292            None,
293        )
294        .await?;
295        // Only exact account-record paths are read; never enumerate accounts.
296        // Refuse unexpectedly large deployments rather than expanding a login
297        // into unbounded tenant probing. No fallback to the shared index.
298        if tenants.len() > 256 {
299            return Err(AccountReadError::HostedDidIndexNotReady);
300        }
301        let mut found = None;
302        for entry in tenants.into_iter().filter(|entry| entry.is_dir) {
303            validate_tenant_component(&entry.name)?;
304            let components = [
305                entry.name.as_str(),
306                PDS_ACCOUNTS_DIRECTORY,
307                label,
308                PDS_ACCOUNT_RECORD_FILE,
309            ];
310            let bytes = match read_file(
311                self.pds_mount.as_ref(),
312                self.read_authorizer.as_ref(),
313                &components,
314                authority,
315                Some(entry.name.as_str()),
316                None,
317                self.max_record_bytes,
318            )
319            .await
320            {
321                Ok(bytes) => bytes,
322                Err(AccountReadError::Mount(MountError::NotFound(_))) => continue,
323                Err(error) => return Err(error),
324            };
325            let record =
326                AccountRecord::from_dag_cbor(&bytes).map_err(AccountReadError::InvalidRecord)?;
327            if record.name().label() != label {
328                return Err(AccountReadError::RecordLabelMismatch {
329                    requested: label.to_owned(),
330                    stored: record.name().label().to_owned(),
331                });
332            }
333            if record.name().did() == did {
334                if found.is_some() {
335                    return Err(AccountReadError::AmbiguousHostedAccountDid(did.to_owned()));
336                }
337                found = Some(entry.name);
338            }
339        }
340        Ok(found)
341    }
342
343    /// Start a single-flight refresh without making the caller perform tenant
344    /// enumeration. A stale snapshot remains available for O(1) lookups while
345    /// one background task refreshes it; the refresh lock prevents duplicate
346    /// scans. Before the first snapshot, lookups return
347    /// [`AccountReadError::HostedDidIndexNotReady`] while this task warms it.
348    pub fn schedule_hosted_did_index_refresh(&self, authority: Subject) {
349        if self
350            .hosted_did_index_refreshing
351            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
352            .is_err()
353        {
354            return;
355        }
356        {
357            let mut last_attempt = self.hosted_did_index_last_attempt.lock();
358            if last_attempt
359                .is_some_and(|attempt| attempt.elapsed() < HOSTED_DID_REFRESH_RETRY_COOLDOWN)
360            {
361                self.hosted_did_index_refreshing
362                    .store(false, Ordering::Release);
363                return;
364            }
365            *last_attempt = Some(Instant::now());
366        }
367        let store = self.clone();
368        if std::thread::Builder::new()
369            .name("hyprstream-pds-index-refresh".to_owned())
370            .spawn(move || {
371                let runtime = match tokio::runtime::Builder::new_current_thread()
372                    .enable_all()
373                    .build()
374                {
375                    Ok(runtime) => runtime,
376                    Err(_) => {
377                        store
378                            .hosted_did_index_refreshing
379                            .store(false, Ordering::Release);
380                        store.hosted_did_index_refreshed.notify_waiters();
381                        return;
382                    }
383                };
384                let refresh_store = store.clone();
385                runtime.block_on(async {
386                    let _ = refresh_store.refresh_hosted_did_index(&authority).await;
387                });
388                store
389                    .hosted_did_index_refreshing
390                    .store(false, Ordering::Release);
391                store.hosted_did_index_refreshed.notify_waiters();
392            })
393            .is_err()
394        {
395            self.hosted_did_index_refreshing
396                .store(false, Ordering::Release);
397            self.hosted_did_index_refreshed.notify_waiters();
398        }
399    }
400
401    /// Check an already-published snapshot without starting filesystem work.
402    /// In-process consumers must warm their injected store before startup.
403    pub async fn hosted_did_index_ready(&self) -> bool {
404        self.hosted_did_index
405            .read()
406            .await
407            .as_ref()
408            .is_some_and(|snapshot| {
409                snapshot.built_at.elapsed() < HOSTED_DID_INDEX_TTL + HOSTED_DID_MAX_STALE
410            })
411    }
412
413    pub async fn refresh_hosted_did_index(
414        &self,
415        authority: &Subject,
416    ) -> Result<(), AccountReadError> {
417        let _refresh = self.hosted_did_index_refresh.lock().await;
418        let stale = self
419            .hosted_did_index
420            .read()
421            .await
422            .as_ref()
423            .map(|snapshot| snapshot.built_at.elapsed() >= HOSTED_DID_INDEX_TTL)
424            .unwrap_or(true);
425        if stale {
426            let entries = self.build_hosted_did_index(authority).await?;
427            self.hosted_did_index.write().await.replace(HostedDidIndex {
428                entries,
429                built_at: Instant::now(),
430            });
431        }
432        Ok(())
433    }
434
435    /// Force a new hosted-DID snapshot after an authority-owned account
436    /// publication. Unlike the periodic/startup refresh above, this does not
437    /// honor the negative-entry TTL: callers use it only after the durable
438    /// account-record publication has completed and before issuing credentials
439    /// that depend on the new binding.
440    pub async fn refresh_hosted_did_index_after_publish(
441        &self,
442        authority: &Subject,
443    ) -> Result<(), AccountReadError> {
444        let _refresh = self.hosted_did_index_refresh.lock().await;
445        let entries = self.build_hosted_did_index(authority).await?;
446        self.hosted_did_index.write().await.replace(HostedDidIndex {
447            entries,
448            built_at: Instant::now(),
449        });
450        Ok(())
451    }
452
453    async fn build_hosted_did_index(
454        &self,
455        authority: &Subject,
456    ) -> Result<BTreeMap<(String, String), Option<String>>, AccountReadError> {
457        let tenants = read_directory(
458            self.pds_mount.as_ref(),
459            self.read_authorizer.as_ref(),
460            &[],
461            authority,
462            None,
463            None,
464        )
465        .await?;
466        let mut index = BTreeMap::new();
467        for entry in tenants.into_iter().filter(|entry| entry.is_dir) {
468            validate_tenant_component(&entry.name)?;
469            let accounts_components = [entry.name.as_str(), PDS_ACCOUNTS_DIRECTORY];
470            let accounts = match read_directory(
471                self.pds_mount.as_ref(),
472                self.read_authorizer.as_ref(),
473                &accounts_components,
474                authority,
475                Some(entry.name.as_str()),
476                None,
477            )
478            .await
479            {
480                Ok(bytes) => bytes,
481                Err(AccountReadError::Mount(MountError::NotFound(_))) => continue,
482                Err(error) => return Err(error),
483            };
484            for account in accounts.into_iter().filter(|account| account.is_dir) {
485                let label = account.name;
486                if hyprstream_pds::is_hosted_account_staging_directory(&label) {
487                    continue;
488                }
489                AccountLabel::parse(&label)
490                    .map_err(|_| AccountReadError::InvalidAccountLabel(label.clone()))?;
491                let components = [
492                    entry.name.as_str(),
493                    PDS_ACCOUNTS_DIRECTORY,
494                    label.as_str(),
495                    PDS_ACCOUNT_RECORD_FILE,
496                ];
497                let bytes = match read_file(
498                    self.pds_mount.as_ref(),
499                    self.read_authorizer.as_ref(),
500                    &components,
501                    authority,
502                    Some(entry.name.as_str()),
503                    None,
504                    self.max_record_bytes,
505                )
506                .await
507                {
508                    Ok(bytes) => bytes,
509                    Err(AccountReadError::Mount(MountError::NotFound(_))) => continue,
510                    Err(error) => return Err(error),
511                };
512                let record = AccountRecord::from_dag_cbor(&bytes)
513                    .map_err(AccountReadError::InvalidRecord)?;
514                if record.name().label() != label {
515                    return Err(AccountReadError::RecordLabelMismatch {
516                        requested: label,
517                        stored: record.name().label().to_owned(),
518                    });
519                }
520                let key = (label, record.name().did().to_owned());
521                match index.entry(key) {
522                    std::collections::btree_map::Entry::Vacant(slot) => {
523                        slot.insert(Some(entry.name.clone()));
524                    }
525                    std::collections::btree_map::Entry::Occupied(mut slot) => {
526                        slot.insert(None);
527                    }
528                }
529            }
530        }
531        Ok(index)
532    }
533
534    /// Sign bytes with the account-specific `#atproto` key for one hosted DID.
535    ///
536    /// This is deliberately an authority-only operation: the caller supplies
537    /// neither a tenant nor a label. The store resolves the tenant from the
538    /// immutable account index, reloads the exact public account record, and
539    /// verifies the secret key against that record before signing. Missing,
540    /// corrupt, substituted, or ambiguous state fails closed and the secret
541    /// key never leaves this service boundary.
542    pub async fn sign_for_hosted_did(
543        &self,
544        authority: &Subject,
545        did: &str,
546        signing_input: &[u8],
547    ) -> Result<Option<Vec<u8>>, AccountReadError> {
548        use p256::ecdsa::signature::Signer as _;
549
550        // Signing runs on authenticated request paths; never turn a cold or
551        // hard-stale lookup into a synchronous tenant enumeration. Startup
552        // warms the index before OAuth readiness, while this resolver remains
553        // fail-closed until a snapshot is available.
554        let resolved = self.resolve_tenant_for_hosted_did(authority, did).await?;
555        let Some(tenant) = resolved else {
556            return Ok(None);
557        };
558        let Some(label) = hosted_account_label(did)? else {
559            return Ok(None);
560        };
561
562        let record_components = [
563            tenant.as_str(),
564            PDS_ACCOUNTS_DIRECTORY,
565            label,
566            PDS_ACCOUNT_RECORD_FILE,
567        ];
568        let record_bytes = read_file(
569            self.pds_mount.as_ref(),
570            self.read_authorizer.as_ref(),
571            &record_components,
572            authority,
573            Some(tenant.as_str()),
574            None,
575            self.max_record_bytes,
576        )
577        .await?;
578        let record =
579            AccountRecord::from_dag_cbor(&record_bytes).map_err(AccountReadError::InvalidRecord)?;
580        if record.name().label() != label {
581            return Err(AccountReadError::RecordLabelMismatch {
582                requested: label.to_owned(),
583                stored: record.name().label().to_owned(),
584            });
585        }
586        if record.name().did() != did {
587            return Err(AccountReadError::RecordDidMismatch {
588                requested: did.to_owned(),
589                stored: record.name().did().to_owned(),
590            });
591        }
592
593        let key_components = [
594            tenant.as_str(),
595            PDS_ACCOUNTS_DIRECTORY,
596            label,
597            ATPROTO_SIGNING_KEY_FILE,
598        ];
599        let key_bytes = match read_file(
600            self.pds_mount.as_ref(),
601            self.read_authorizer.as_ref(),
602            &key_components,
603            authority,
604            Some(tenant.as_str()),
605            None,
606            ATPROTO_SIGNING_KEY_BYTES,
607        )
608        .await
609        {
610            Ok(bytes) => bytes,
611            Err(AccountReadError::Mount(MountError::NotFound(_))) => {
612                return Err(AccountReadError::SigningKeyUnavailable(did.to_owned()));
613            }
614            Err(AccountReadError::RecordTooLarge { .. }) => {
615                return Err(AccountReadError::InvalidSigningKey(did.to_owned()));
616            }
617            Err(error) => return Err(error),
618        };
619        if key_bytes.len() != ATPROTO_SIGNING_KEY_BYTES {
620            return Err(AccountReadError::InvalidSigningKey(did.to_owned()));
621        }
622        let signing_key = p256::ecdsa::SigningKey::from_slice(&key_bytes)
623            .map_err(|_| AccountReadError::InvalidSigningKey(did.to_owned()))?;
624        if signing_key.verifying_key().to_encoded_point(true)
625            != record
626                .atproto_verifying_key()
627                .map_err(AccountReadError::InvalidRecord)?
628                .to_encoded_point(true)
629        {
630            return Err(AccountReadError::SigningKeyMismatch(did.to_owned()));
631        }
632
633        let signature: p256::ecdsa::Signature = signing_key.sign(signing_input);
634        Ok(Some(signature.to_bytes().to_vec()))
635    }
636
637    /// Read the public `#atproto` verification key for one authority-owned
638    /// hosted DID without exposing its private signing material. The same
639    /// bounded index, exact account-record checks, and fixed OAuth authority
640    /// used by [`Self::sign_for_hosted_did`] are applied.
641    pub async fn verifying_key_for_hosted_did(
642        &self,
643        authority: &Subject,
644        did: &str,
645    ) -> Result<Option<p256::ecdsa::VerifyingKey>, AccountReadError> {
646        let resolved = self.resolve_tenant_for_hosted_did(authority, did).await?;
647        let Some(tenant) = resolved else {
648            return Ok(None);
649        };
650        let Some(label) = hosted_account_label(did)? else {
651            return Ok(None);
652        };
653        let record_components = [
654            tenant.as_str(),
655            PDS_ACCOUNTS_DIRECTORY,
656            label,
657            PDS_ACCOUNT_RECORD_FILE,
658        ];
659        let record_bytes = read_file(
660            self.pds_mount.as_ref(),
661            self.read_authorizer.as_ref(),
662            &record_components,
663            authority,
664            Some(tenant.as_str()),
665            None,
666            self.max_record_bytes,
667        )
668        .await?;
669        let record =
670            AccountRecord::from_dag_cbor(&record_bytes).map_err(AccountReadError::InvalidRecord)?;
671        if record.name().label() != label {
672            return Err(AccountReadError::RecordLabelMismatch {
673                requested: label.to_owned(),
674                stored: record.name().label().to_owned(),
675            });
676        }
677        if record.name().did() != did {
678            return Err(AccountReadError::RecordDidMismatch {
679                requested: did.to_owned(),
680                stored: record.name().did().to_owned(),
681            });
682        }
683        record
684            .atproto_verifying_key()
685            .map(Some)
686            .map_err(AccountReadError::InvalidRecord)
687    }
688
689    /// Resolve an owned account's public genesis, including legacy conversion.
690    pub async fn hosted_repo_genesis_for_hosted_did(
691        &self,
692        authority: &Subject,
693        did: &str,
694    ) -> Result<Option<(Vec<u8>, Vec<u8>)>, AccountReadError> {
695        self.hosted_repo_genesis_with_cached_public(authority, did, None)
696            .await
697    }
698
699    /// Read the verified native/public empty genesis pair for an owned DID.
700    /// Older accounts may have only the native artifact. In that case reuse a
701    /// caller's durable public genesis after verification, or convert through
702    /// account signing custody. Neither a corrupt artifact nor a progressed
703    /// native commit is eligible for conversion. Private keys never escape.
704    pub async fn hosted_repo_genesis_with_cached_public(
705        &self,
706        authority: &Subject,
707        did: &str,
708        cached_public: Option<&[u8]>,
709    ) -> Result<Option<(Vec<u8>, Vec<u8>)>, AccountReadError> {
710        use hyprstream_pds::{commit::Commit, mst::Node};
711        let resolved = self.resolve_tenant_for_hosted_did(authority, did).await?;
712        let Some(tenant) = resolved else {
713            return Ok(None);
714        };
715        let Some(label) = hosted_account_label(did)? else {
716            return Ok(None);
717        };
718        let native_bytes = match self
719            .read_hosted_repo_artifact(authority, &tenant, label, "commit.cbor", 64 * 1024)
720            .await
721        {
722            Ok(bytes) => bytes,
723            Err(AccountReadError::Mount(MountError::NotFound(_))) => return Ok(None),
724            Err(error) => return Err(error),
725        };
726        let Some(key) = self.verifying_key_for_hosted_did(authority, did).await? else {
727            return Ok(None);
728        };
729        let native = (|| -> anyhow::Result<Commit> {
730            let native = Commit::from_dag_cbor(&native_bytes)?;
731            native.verify(&key)?;
732            let (empty, _) = Node::empty().to_node_data_with_blocks_atproto()?;
733            anyhow::ensure!(
734                native.did == did && native.prev.is_none() && native.data == empty.cid_atproto()?,
735                "invalid native empty genesis"
736            );
737            Ok(native)
738        })()
739        .map_err(AccountReadError::InvalidRecord)?;
740        let public_bytes = match self
741            .read_hosted_repo_artifact(authority, &tenant, label, "public-commit.cbor", 64 * 1024)
742            .await
743        {
744            Ok(bytes) => bytes,
745            Err(AccountReadError::Mount(MountError::NotFound(_))) => {
746                if let Some(bytes) = cached_public {
747                    // Treat cache bytes as untrusted until the common checks below.
748                    if bytes.len() > DEFAULT_MAX_RECORD_BYTES {
749                        return Err(AccountReadError::RecordTooLarge {
750                            limit: DEFAULT_MAX_RECORD_BYTES,
751                        });
752                    }
753                    bytes.to_vec()
754                } else {
755                    let unsigned = native.unsigned();
756                    let input = unsigned
757                        .to_atproto_dag_cbor()
758                        .map_err(AccountReadError::InvalidRecord)?;
759                    let signature = self
760                        .sign_for_hosted_did(authority, did, &input)
761                        .await?
762                        .ok_or_else(|| AccountReadError::SigningKeyUnavailable(did.to_owned()))?;
763                    Commit::from_atproto_signature(&unsigned, signature, &key)
764                        .and_then(|commit| commit.to_atproto_dag_cbor())
765                        .map_err(AccountReadError::InvalidRecord)?
766                }
767            }
768            Err(error) => return Err(error),
769        };
770        (|| -> anyhow::Result<()> {
771            let public = Commit::from_atproto_dag_cbor(&public_bytes)?;
772            public.verify_atproto(&key)?;
773            anyhow::ensure!(
774                public.unsigned() == native.unsigned(),
775                "public genesis differs from native genesis"
776            );
777            if let Some(cached) = cached_public {
778                anyhow::ensure!(
779                    cached == public_bytes,
780                    "public genesis differs from durable genesis"
781                );
782            }
783            Ok(())
784        })()
785        .map_err(AccountReadError::InvalidRecord)?;
786        Ok(Some((native_bytes, public_bytes)))
787    }
788
789    #[cfg(test)]
790    fn with_max_record_bytes(mut self, max_record_bytes: usize) -> Self {
791        self.max_record_bytes = max_record_bytes;
792        self
793    }
794
795    /// Read one immutable public identity artifact after the hosted DID has
796    /// already resolved to its authority-owned tenant.
797    pub(crate) async fn read_hosted_http_artifact(
798        &self,
799        authority: &Subject,
800        tenant: &str,
801        label: &str,
802        file: &str,
803        limit: usize,
804    ) -> Result<Vec<u8>, AccountReadError> {
805        validate_tenant_component(tenant)?;
806        validate_account_label(label)?;
807        let components = [tenant, PDS_ACCOUNTS_DIRECTORY, label, file];
808        read_file(
809            self.pds_mount.as_ref(),
810            self.read_authorizer.as_ref(),
811            &components,
812            authority,
813            Some(tenant),
814            None,
815            limit,
816        )
817        .await
818    }
819
820    pub(crate) async fn read_hosted_repo_artifact(
821        &self,
822        authority: &Subject,
823        tenant: &str,
824        label: &str,
825        file: &str,
826        limit: usize,
827    ) -> Result<Vec<u8>, AccountReadError> {
828        validate_tenant_component(tenant)?;
829        validate_account_label(label)?;
830        ensure_repo_artifact_name(file)?;
831        let components = [tenant, PDS_ACCOUNTS_DIRECTORY, label, "repo", file];
832        read_file(
833            self.pds_mount.as_ref(),
834            self.read_authorizer.as_ref(),
835            &components,
836            authority,
837            Some(tenant),
838            None,
839            limit,
840        )
841        .await
842    }
843}
844
845/// A read capability bound to one authority-verified tenant and subject.
846///
847/// There is intentionally no method that changes the tenant after creation.
848pub struct AccountReadScope {
849    pds_mount: Arc<dyn Mount>,
850    read_authorizer: Arc<dyn AccountRecordReadAuthorizer>,
851    max_record_bytes: usize,
852    tenant: String,
853    subject: Subject,
854    security_context: Option<SecurityContext>,
855}
856
857impl AccountReadScope {
858    /// The verified tenant captured for this scope.
859    #[must_use]
860    pub fn tenant(&self) -> &str {
861        &self.tenant
862    }
863
864    /// Read and validate a hosted account record by allocated label.
865    ///
866    /// Records live at
867    /// `/pds/{verified_tenant}/accounts/{label}/account-record.cbor`.
868    /// A missing record returns `Ok(None)`; malformed, oversized, mislabeled,
869    /// or denied records fail closed.
870    pub async fn get(&self, label: &str) -> Result<Option<AccountRecord>, AccountReadError> {
871        validate_account_label(label)?;
872        let components = [
873            self.tenant.as_str(),
874            PDS_ACCOUNTS_DIRECTORY,
875            label,
876            PDS_ACCOUNT_RECORD_FILE,
877        ];
878        let bytes = match read_file(
879            self.pds_mount.as_ref(),
880            self.read_authorizer.as_ref(),
881            &components,
882            &self.subject,
883            Some(self.tenant.as_str()),
884            self.security_context.as_ref(),
885            self.max_record_bytes,
886        )
887        .await
888        {
889            Ok(bytes) => bytes,
890            Err(AccountReadError::Mount(MountError::NotFound(_))) => return Ok(None),
891            Err(error) => return Err(error),
892        };
893
894        let record =
895            AccountRecord::from_dag_cbor(&bytes).map_err(AccountReadError::InvalidRecord)?;
896        if record.name().label() != label {
897            return Err(AccountReadError::RecordLabelMismatch {
898                requested: label.to_owned(),
899                stored: record.name().label().to_owned(),
900            });
901        }
902        Ok(Some(record))
903    }
904}
905
906fn validate_tenant_component(tenant: &str) -> Result<(), AccountReadError> {
907    let valid = !tenant.is_empty()
908        && tenant.len() <= 253
909        && tenant != "."
910        && tenant != ".."
911        && tenant != "*"
912        && tenant
913            .bytes()
914            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'));
915    if valid {
916        Ok(())
917    } else {
918        Err(AccountReadError::InvalidVerifiedTenant(tenant.to_owned()))
919    }
920}
921
922fn validate_account_label(label: &str) -> Result<(), AccountReadError> {
923    let valid = !label.is_empty()
924        && label.len() <= 63
925        && label
926            .bytes()
927            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
928        && !label.starts_with('-')
929        && !label.ends_with('-');
930    if valid {
931        Ok(())
932    } else {
933        Err(AccountReadError::InvalidAccountLabel(label.to_owned()))
934    }
935}
936
937fn ensure_repo_artifact_name(file: &str) -> Result<(), AccountReadError> {
938    if matches!(file, "commit.cbor" | "public-commit.cbor") {
939        Ok(())
940    } else {
941        Err(AccountReadError::InvalidRepositoryArtifact(file.to_owned()))
942    }
943}
944
945fn hosted_account_label(did: &str) -> Result<Option<&str>, AccountReadError> {
946    let Some(host) = did.strip_prefix("did:web:") else {
947        return Ok(None);
948    };
949    if host.contains([':', '/']) {
950        return Err(AccountReadError::InvalidHostedAccountDid(did.to_owned()));
951    }
952    let label = host
953        .split('.')
954        .next()
955        .ok_or_else(|| AccountReadError::InvalidHostedAccountDid(did.to_owned()))?;
956    validate_account_label(label)
957        .map_err(|_| AccountReadError::InvalidHostedAccountDid(did.to_owned()))?;
958    Ok(Some(label))
959}
960
961async fn read_file(
962    mount: &dyn Mount,
963    authorizer: &dyn AccountRecordReadAuthorizer,
964    components: &[&str],
965    subject: &Subject,
966    verified_tenant: Option<&str>,
967    security_context: Option<&SecurityContext>,
968    limit: usize,
969) -> Result<Vec<u8>, AccountReadError> {
970    let mut fid = mount.walk(components, subject).await?;
971    let object_id = canonical_object_id(components);
972    if let MacDecision::Deny(reason) =
973        authorizer.check_read(subject, verified_tenant, security_context, &object_id)
974    {
975        mount.clunk(fid, subject).await;
976        return Err(AccountReadError::MacDenied {
977            subject: subject.to_string(),
978            object: object_id,
979            reason,
980        });
981    }
982
983    // The walk above binds the canonical name to this fid. Authorization is
984    // complete before open/stat/read, and the same fid is consumed below:
985    // there is no partial resolution or post-check re-walk/handle substitution.
986    if let Err(error) = mount.open(&mut fid, OREAD, subject).await {
987        mount.clunk(fid, subject).await;
988        return Err(error.into());
989    }
990
991    let result = read_open_fid(mount, &fid, subject, limit).await;
992    mount.clunk(fid, subject).await;
993    result
994}
995
996async fn read_directory(
997    mount: &dyn Mount,
998    authorizer: &dyn AccountRecordReadAuthorizer,
999    components: &[&str],
1000    subject: &Subject,
1001    verified_tenant: Option<&str>,
1002    security_context: Option<&SecurityContext>,
1003) -> Result<Vec<hyprstream_vfs::DirEntry>, AccountReadError> {
1004    let mut fid = mount.walk(components, subject).await?;
1005    let object_id = canonical_object_id(components);
1006    if let MacDecision::Deny(reason) =
1007        authorizer.check_read(subject, verified_tenant, security_context, &object_id)
1008    {
1009        mount.clunk(fid, subject).await;
1010        return Err(AccountReadError::MacDenied {
1011            subject: subject.to_string(),
1012            object: object_id,
1013            reason,
1014        });
1015    }
1016    if let Err(error) = mount.open(&mut fid, OREAD, subject).await {
1017        mount.clunk(fid, subject).await;
1018        return Err(error.into());
1019    }
1020    let result = mount.readdir(&fid, subject).await.map_err(Into::into);
1021    mount.clunk(fid, subject).await;
1022    result
1023}
1024
1025fn canonical_object_id(components: &[&str]) -> String {
1026    if components.is_empty() {
1027        return PDS_NAMESPACE.to_owned();
1028    }
1029    format!("{PDS_NAMESPACE}/{}", components.join("/"))
1030}
1031
1032async fn read_open_fid(
1033    mount: &dyn Mount,
1034    fid: &hyprstream_vfs::Fid,
1035    subject: &Subject,
1036    limit: usize,
1037) -> Result<Vec<u8>, AccountReadError> {
1038    let stat = mount.stat(fid, subject).await?;
1039    if stat.size > limit as u64 {
1040        return Err(AccountReadError::RecordTooLarge { limit });
1041    }
1042
1043    let mut bytes = Vec::with_capacity((stat.size as usize).min(limit));
1044    loop {
1045        let remaining_with_sentinel = limit.saturating_sub(bytes.len()).saturating_add(1);
1046        let count = READ_CHUNK_BYTES.min(remaining_with_sentinel) as u32;
1047        let chunk = mount.read(fid, bytes.len() as u64, count, subject).await?;
1048        if chunk.len() > count as usize {
1049            return Err(AccountReadError::RecordTooLarge { limit });
1050        }
1051        if chunk.is_empty() {
1052            break;
1053        }
1054        bytes.extend_from_slice(&chunk);
1055        if bytes.len() > limit {
1056            return Err(AccountReadError::RecordTooLarge { limit });
1057        }
1058    }
1059    Ok(bytes)
1060}
1061
1062#[cfg(all(test, not(target_arch = "wasm32")))]
1063mod tests {
1064    #![allow(clippy::expect_used, clippy::unwrap_used)]
1065
1066    use super::*;
1067    use ed25519_dalek::SigningKey;
1068    use hyprstream_crypto::pq::{ml_dsa_generate_keypair, ml_dsa_vk_bytes};
1069    use hyprstream_pds::did_op::{
1070        sign_genesis, GenesisRepoHead, GenesisRotationKeys, HostKeyEnrollment, HybridRotationKey,
1071        RecoveryKeyEnrollment, UserRotationKey,
1072    };
1073    use hyprstream_pds::{AllocatedAccountName, HostedAccountMint};
1074    use hyprstream_rpc::Subject;
1075    use hyprstream_vfs::{SyntheticMount, SyntheticNode};
1076    use rand::rngs::OsRng;
1077
1078    struct PermitAccountReads;
1079
1080    impl AccountRecordReadAuthorizer for PermitAccountReads {
1081        fn check_read(
1082            &self,
1083            _subject: &Subject,
1084            _verified_tenant: Option<&str>,
1085            _security_context: Option<&SecurityContext>,
1086            _object_id: &str,
1087        ) -> MacDecision {
1088            MacDecision::Permit
1089        }
1090    }
1091
1092    struct SlowPermitAccountReads;
1093
1094    impl AccountRecordReadAuthorizer for SlowPermitAccountReads {
1095        fn check_read(
1096            &self,
1097            _subject: &Subject,
1098            _verified_tenant: Option<&str>,
1099            _security_context: Option<&SecurityContext>,
1100            _object_id: &str,
1101        ) -> MacDecision {
1102            // This models the synchronous filesystem/audit work performed by
1103            // the production authorizer and mount. A current-thread OAuth
1104            // runtime must remain able to make progress while it runs.
1105            std::thread::sleep(Duration::from_millis(200));
1106            MacDecision::Permit
1107        }
1108    }
1109
1110    fn permit_account_reads() -> Arc<dyn AccountRecordReadAuthorizer> {
1111        Arc::new(PermitAccountReads)
1112    }
1113
1114    fn account_artifacts(label: &str, zone: &str) -> (Vec<u8>, Vec<u8>) {
1115        let ed = SigningKey::generate(&mut OsRng);
1116        let (pq, pq_vk) = ml_dsa_generate_keypair();
1117        let hybrid =
1118            HybridRotationKey::new(ed.verifying_key().to_bytes(), ml_dsa_vk_bytes(&pq_vk)).unwrap();
1119        let rotations = GenesisRotationKeys::new(
1120            UserRotationKey::new(hybrid),
1121            RecoveryKeyEnrollment::Declined,
1122            HostKeyEnrollment::Absent,
1123        )
1124        .unwrap();
1125        let name = AllocatedAccountName::new(label, format!("did:web:{label}.{zone}")).unwrap();
1126        let mint = HostedAccountMint::begin(name, rotations).unwrap();
1127        let document = mint.seal_did_document("https://pds.example.com").unwrap();
1128        let pending = mint
1129            .prepare_genesis(document, GenesisRepoHead::EmptyRepo)
1130            .unwrap();
1131        let signature = sign_genesis(pending.unsigned_genesis(), &ed, &pq).unwrap();
1132        let account = pending.seal(signature).unwrap();
1133        (
1134            account.record_bytes().to_vec(),
1135            account.atproto_signing_key().to_bytes().to_vec(),
1136        )
1137    }
1138
1139    fn account_bytes(label: &str, zone: &str) -> Vec<u8> {
1140        account_artifacts(label, zone).0
1141    }
1142
1143    fn tenant_node(label: &str, record: Vec<u8>) -> SyntheticNode {
1144        SyntheticNode::dir().with_child(
1145            PDS_ACCOUNTS_DIRECTORY,
1146            SyntheticNode::dir().with_child(
1147                label,
1148                SyntheticNode::dir()
1149                    .with_child(PDS_ACCOUNT_RECORD_FILE, SyntheticNode::file(record)),
1150            ),
1151        )
1152    }
1153
1154    fn tenant_node_with_key(label: &str, record: Vec<u8>, key: Vec<u8>) -> SyntheticNode {
1155        SyntheticNode::dir().with_child(
1156            PDS_ACCOUNTS_DIRECTORY,
1157            SyntheticNode::dir().with_child(
1158                label,
1159                SyntheticNode::dir()
1160                    .with_child(PDS_ACCOUNT_RECORD_FILE, SyntheticNode::file(record))
1161                    .with_child(ATPROTO_SIGNING_KEY_FILE, SyntheticNode::file(key)),
1162            ),
1163        )
1164    }
1165
1166    fn store() -> AccountRecordStore {
1167        let root = SyntheticNode::dir()
1168            .with_child(
1169                "acme",
1170                tenant_node("alice", account_bytes("alice", "acme.example")),
1171            )
1172            .with_child(
1173                "beta",
1174                tenant_node("alice", account_bytes("alice", "beta.example")),
1175            );
1176        AccountRecordStore::new(Arc::new(SyntheticMount::new(root)), permit_account_reads())
1177    }
1178
1179    fn context(tenant: &str) -> EnvelopeContext {
1180        let signer = SigningKey::generate(&mut OsRng);
1181        EnvelopeContext::for_test_authenticated_subject_in_tenant(
1182            Subject::new("alice"),
1183            tenant,
1184            signer.verifying_key(),
1185        )
1186    }
1187
1188    fn oauth_authority() -> Subject {
1189        Subject::new(OAUTH_ACCOUNT_RESOLVER_SUBJECT)
1190    }
1191
1192    #[tokio::test]
1193    async fn h2_current_tenant_ignores_cached_positive_and_negative_bindings() {
1194        let store = store();
1195        store
1196            .hosted_did_index
1197            .write()
1198            .await
1199            .replace(HostedDidIndex {
1200                entries: BTreeMap::from([
1201                    (
1202                        ("alice".into(), "did:web:alice.acme.example".into()),
1203                        Some("wrong-tenant".into()),
1204                    ),
1205                    (
1206                        ("missing".into(), "did:web:missing.acme.example".into()),
1207                        Some("acme".into()),
1208                    ),
1209                ]),
1210                built_at: Instant::now(),
1211            });
1212        assert_eq!(
1213            store
1214                .resolve_current_tenant_for_hosted_did(
1215                    &oauth_authority(),
1216                    "did:web:alice.acme.example"
1217                )
1218                .await
1219                .unwrap(),
1220            Some("acme".into())
1221        );
1222        assert_eq!(
1223            store
1224                .resolve_current_tenant_for_hosted_did(
1225                    &oauth_authority(),
1226                    "did:web:missing.acme.example"
1227                )
1228                .await
1229                .unwrap(),
1230            None
1231        );
1232        assert!(store
1233            .resolve_current_tenant_for_hosted_did(
1234                &Subject::new("alice"),
1235                "did:web:alice.acme.example"
1236            )
1237            .await
1238            .is_err());
1239    }
1240
1241    #[tokio::test]
1242    async fn h2_current_tenant_rejects_ambiguous_records() {
1243        let bytes = account_bytes("alice", "acme.example");
1244        let root = SyntheticNode::dir()
1245            .with_child("a", tenant_node("alice", bytes.clone()))
1246            .with_child("b", tenant_node("alice", bytes));
1247        let store =
1248            AccountRecordStore::new(Arc::new(SyntheticMount::new(root)), permit_account_reads());
1249        assert!(matches!(
1250            store
1251                .resolve_current_tenant_for_hosted_did(
1252                    &oauth_authority(),
1253                    "did:web:alice.acme.example"
1254                )
1255                .await,
1256            Err(AccountReadError::AmbiguousHostedAccountDid(_))
1257        ));
1258    }
1259
1260    #[tokio::test]
1261    async fn verified_tenant_selects_the_only_visible_account_tree() {
1262        let store = store();
1263        let acme = store.scope(&context("acme")).unwrap();
1264        let beta = store.scope(&context("beta")).unwrap();
1265
1266        let acme_record = acme.get("alice").await.unwrap().unwrap();
1267        let beta_record = beta.get("alice").await.unwrap().unwrap();
1268
1269        assert_eq!(acme.tenant(), "acme");
1270        assert_eq!(beta.tenant(), "beta");
1271        assert_eq!(acme_record.name().did(), "did:web:alice.acme.example");
1272        assert_eq!(beta_record.name().did(), "did:web:alice.beta.example");
1273    }
1274
1275    #[tokio::test]
1276    async fn oauth_authority_resolves_tenant_from_matching_account_record() {
1277        let store = store();
1278        store
1279            .refresh_hosted_did_index(&oauth_authority())
1280            .await
1281            .unwrap();
1282
1283        assert_eq!(
1284            store
1285                .resolve_tenant_for_hosted_did(&oauth_authority(), "did:web:alice.acme.example",)
1286                .await
1287                .unwrap()
1288                .as_deref(),
1289            Some("acme"),
1290        );
1291        assert_eq!(
1292            store
1293                .resolve_tenant_for_hosted_did(&oauth_authority(), "did:web:missing.acme.example",)
1294                .await
1295                .unwrap(),
1296            None,
1297        );
1298        assert_eq!(
1299            store
1300                .resolve_tenant_for_hosted_did(&oauth_authority(), "did:plc:federated-only",)
1301                .await
1302                .unwrap(),
1303            None,
1304        );
1305        assert_eq!(
1306            store
1307                .resolve_tenant_for_hosted_did(
1308                    &oauth_authority(),
1309                    hyprstream_rpc::identity::UNAUTHENTICATED_DID_SENTINEL,
1310                )
1311                .await
1312                .unwrap(),
1313            None,
1314        );
1315    }
1316
1317    #[tokio::test]
1318    async fn hosted_did_index_ignores_mint_staging_directories() {
1319        let record = account_bytes("alice", "acme.example");
1320        let accounts = SyntheticNode::dir()
1321            .with_child(
1322                "alice",
1323                SyntheticNode::dir()
1324                    .with_child(PDS_ACCOUNT_RECORD_FILE, SyntheticNode::file(record)),
1325            )
1326            .with_child(".alice.mint-123-0", SyntheticNode::dir());
1327        let root = SyntheticNode::dir().with_child(
1328            "acme",
1329            SyntheticNode::dir().with_child(PDS_ACCOUNTS_DIRECTORY, accounts),
1330        );
1331        let store =
1332            AccountRecordStore::new(Arc::new(SyntheticMount::new(root)), permit_account_reads());
1333
1334        store
1335            .refresh_hosted_did_index(&oauth_authority())
1336            .await
1337            .expect("staging residue must not abort index refresh");
1338        assert_eq!(
1339            store
1340                .resolve_tenant_for_hosted_did(&oauth_authority(), "did:web:alice.acme.example",)
1341                .await
1342                .unwrap()
1343                .as_deref(),
1344            Some("acme")
1345        );
1346    }
1347
1348    #[tokio::test]
1349    async fn hosted_did_index_rejects_malformed_permanent_account_labels() {
1350        for label in [".alice.mint-*", ".garbage", "Alice", "alice_"] {
1351            let accounts = SyntheticNode::dir().with_child(label, SyntheticNode::dir());
1352            let root = SyntheticNode::dir().with_child(
1353                "acme",
1354                SyntheticNode::dir().with_child(PDS_ACCOUNTS_DIRECTORY, accounts),
1355            );
1356            let store = AccountRecordStore::new(
1357                Arc::new(SyntheticMount::new(root)),
1358                permit_account_reads(),
1359            );
1360
1361            let error = store
1362                .refresh_hosted_did_index(&oauth_authority())
1363                .await
1364                .expect_err("malformed permanent labels must fail closed");
1365            assert!(
1366                matches!(error, AccountReadError::InvalidAccountLabel(ref actual) if actual == label),
1367                "unexpected error for {label:?}: {error:?}"
1368            );
1369        }
1370    }
1371
1372    #[tokio::test]
1373    async fn hosted_did_resolution_requires_oauth_authority_and_is_unambiguous() {
1374        let denied = store()
1375            .resolve_tenant_for_hosted_did(&Subject::new("alice"), "did:web:alice.acme.example")
1376            .await
1377            .unwrap_err();
1378        assert!(matches!(
1379            denied,
1380            AccountReadError::UnauthorizedTenantResolver(_)
1381        ));
1382
1383        let duplicated = account_bytes("alice", "acme.example");
1384        let root = SyntheticNode::dir()
1385            .with_child("acme", tenant_node("alice", duplicated.clone()))
1386            .with_child("beta", tenant_node("alice", duplicated));
1387        let ambiguous_store =
1388            AccountRecordStore::new(Arc::new(SyntheticMount::new(root)), permit_account_reads());
1389        ambiguous_store
1390            .refresh_hosted_did_index(&oauth_authority())
1391            .await
1392            .unwrap();
1393        let ambiguous = ambiguous_store
1394            .resolve_tenant_for_hosted_did(&oauth_authority(), "did:web:alice.acme.example")
1395            .await
1396            .unwrap_err();
1397        assert!(matches!(
1398            ambiguous,
1399            AccountReadError::AmbiguousHostedAccountDid(_)
1400        ));
1401    }
1402
1403    #[tokio::test]
1404    async fn cold_hosted_did_lookup_never_enumerates_on_request_path() {
1405        let store = store();
1406        let error = store
1407            .resolve_tenant_for_hosted_did(&oauth_authority(), "did:web:alice.acme.example")
1408            .await
1409            .unwrap_err();
1410        assert!(matches!(error, AccountReadError::HostedDidIndexNotReady));
1411    }
1412
1413    #[tokio::test]
1414    async fn cold_hosted_did_signing_never_refreshes_on_request_path() {
1415        let store = store();
1416        let error = store
1417            .sign_for_hosted_did(
1418                &oauth_authority(),
1419                "did:web:alice.acme.example",
1420                b"header.payload",
1421            )
1422            .await
1423            .unwrap_err();
1424        assert!(matches!(error, AccountReadError::HostedDidIndexNotReady));
1425    }
1426
1427    #[tokio::test(flavor = "current_thread")]
1428    async fn scheduled_hosted_did_refresh_does_not_block_current_thread_runtime() {
1429        let root = SyntheticNode::dir().with_child(
1430            "acme",
1431            tenant_node("alice", account_bytes("alice", "acme.example")),
1432        );
1433        let store = AccountRecordStore::new(
1434            Arc::new(SyntheticMount::new(root)),
1435            Arc::new(SlowPermitAccountReads),
1436        );
1437
1438        store.schedule_hosted_did_index_refresh(oauth_authority());
1439        tokio::time::timeout(
1440            Duration::from_millis(100),
1441            tokio::time::sleep(Duration::from_millis(10)),
1442        )
1443        .await
1444        .expect("index refresh must not block the HTTP runtime");
1445    }
1446
1447    #[tokio::test]
1448    async fn hosted_did_negative_lookup_expires() {
1449        let store = store();
1450        store
1451            .hosted_did_index
1452            .write()
1453            .await
1454            .replace(HostedDidIndex {
1455                entries: BTreeMap::new(),
1456                built_at: Instant::now() - HOSTED_DID_NEGATIVE_TTL - Duration::from_millis(1),
1457            });
1458        let result = store
1459            .resolve_tenant_for_hosted_did(&oauth_authority(), "did:web:new.acme.example")
1460            .await;
1461        assert_eq!(result.unwrap(), None);
1462    }
1463
1464    #[tokio::test]
1465    async fn hosted_did_idle_lookup_waits_for_fresh_binding() {
1466        let store = store();
1467        seed_expired_hosted_did_binding(&store).await;
1468        let tenant = store
1469            .resolve_tenant_for_hosted_did(&oauth_authority(), "did:web:alice.acme.example")
1470            .await
1471            .expect("first lookup after idle must recover within its refresh budget");
1472        assert_eq!(tenant.as_deref(), Some("acme"));
1473        assert!(store.hosted_did_index_ready().await);
1474    }
1475
1476    async fn seed_expired_hosted_did_binding(store: &AccountRecordStore) {
1477        store
1478            .hosted_did_index
1479            .write()
1480            .await
1481            .replace(HostedDidIndex {
1482                entries: BTreeMap::from([(
1483                    ("alice".to_owned(), "did:web:alice.acme.example".to_owned()),
1484                    Some("obsolete-tenant".to_owned()),
1485                )]),
1486                built_at: Instant::now() - HOSTED_DID_INDEX_TTL - HOSTED_DID_MAX_STALE,
1487            });
1488    }
1489
1490    #[tokio::test]
1491    async fn hosted_did_positive_binding_has_a_hard_stale_deadline() {
1492        let root = SyntheticNode::dir().with_child(
1493            "acme",
1494            tenant_node("alice", b"corrupt account record".to_vec()),
1495        );
1496        let store =
1497            AccountRecordStore::new(Arc::new(SyntheticMount::new(root)), permit_account_reads());
1498        seed_expired_hosted_did_binding(&store).await;
1499        let error = store
1500            .resolve_tenant_for_hosted_did(&oauth_authority(), "did:web:alice.acme.example")
1501            .await
1502            .unwrap_err();
1503        assert!(matches!(error, AccountReadError::HostedDidIndexNotReady));
1504        assert!(!store.hosted_did_index_ready().await);
1505        assert!(!store.hosted_did_index_refreshing.load(Ordering::Acquire));
1506    }
1507
1508    #[tokio::test(flavor = "current_thread")]
1509    async fn hosted_did_idle_wait_is_bounded_coalesced_and_off_request_executor() {
1510        struct BlockRootRead {
1511            release: parking_lot::Mutex<std::sync::mpsc::Receiver<()>>,
1512            scans: std::sync::atomic::AtomicUsize,
1513            request_thread: std::thread::ThreadId,
1514        }
1515        impl AccountRecordReadAuthorizer for BlockRootRead {
1516            fn check_read(
1517                &self,
1518                _subject: &Subject,
1519                _verified_tenant: Option<&str>,
1520                _security_context: Option<&SecurityContext>,
1521                object_id: &str,
1522            ) -> MacDecision {
1523                if object_id == PDS_NAMESPACE {
1524                    assert_ne!(std::thread::current().id(), self.request_thread);
1525                    self.scans.fetch_add(1, Ordering::AcqRel);
1526                    self.release
1527                        .lock()
1528                        .recv_timeout(Duration::from_secs(5))
1529                        .unwrap();
1530                }
1531                MacDecision::Permit
1532            }
1533        }
1534        let (release, blocked) = std::sync::mpsc::channel();
1535        let authorizer = Arc::new(BlockRootRead {
1536            release: parking_lot::Mutex::new(blocked),
1537            scans: std::sync::atomic::AtomicUsize::new(0),
1538            request_thread: std::thread::current().id(),
1539        });
1540        let mut store = store();
1541        store.read_authorizer = authorizer.clone();
1542        seed_expired_hosted_did_binding(&store).await;
1543        let authority = oauth_authority();
1544        let started = Instant::now();
1545        let (first, second, heartbeat) = tokio::join!(
1546            store.resolve_tenant_for_hosted_did(&authority, "did:web:alice.acme.example"),
1547            store.resolve_tenant_for_hosted_did(&authority, "did:web:alice.acme.example"),
1548            async {
1549                tokio::time::sleep(Duration::from_millis(10)).await;
1550                started.elapsed()
1551            },
1552        );
1553        let elapsed = started.elapsed();
1554        // Another timed-out caller must share the existing worker as well.
1555        let third = store
1556            .resolve_tenant_for_hosted_did(&authority, "did:web:alice.acme.example")
1557            .await;
1558        let refreshed = store.hosted_did_index_refreshed.notified();
1559        tokio::pin!(refreshed);
1560        refreshed.as_mut().enable();
1561        release.send(()).unwrap();
1562        tokio::time::timeout(Duration::from_secs(2), refreshed)
1563            .await
1564            .expect("released refresh must finish");
1565
1566        for result in [first, second, third] {
1567            assert!(matches!(
1568                result,
1569                Err(AccountReadError::HostedDidIndexNotReady)
1570            ));
1571        }
1572        assert!(elapsed >= HOSTED_DID_REFRESH_WAIT);
1573        assert!(elapsed < HOSTED_DID_REFRESH_WAIT + Duration::from_millis(500));
1574        assert!(heartbeat < Duration::from_millis(500));
1575        assert_eq!(authorizer.scans.load(Ordering::Acquire), 1);
1576        assert_eq!(
1577            store
1578                .resolve_tenant_for_hosted_did(&authority, "did:web:alice.acme.example")
1579                .await
1580                .unwrap()
1581                .as_deref(),
1582            Some("acme")
1583        );
1584    }
1585
1586    #[tokio::test]
1587    async fn hosted_service_auth_signing_is_authority_bound_and_record_bound() {
1588        use p256::ecdsa::signature::Verifier as _;
1589
1590        let did = "did:web:alice.acme.example";
1591        let (record, key) = account_artifacts("alice", "acme.example");
1592        let verifying_key = p256::ecdsa::SigningKey::from_slice(&key)
1593            .unwrap()
1594            .verifying_key()
1595            .to_owned();
1596        let root = SyntheticNode::dir().with_child(
1597            "acme",
1598            tenant_node_with_key("alice", record.clone(), key.clone()),
1599        );
1600        let store =
1601            AccountRecordStore::new(Arc::new(SyntheticMount::new(root)), permit_account_reads());
1602        store
1603            .refresh_hosted_did_index(&oauth_authority())
1604            .await
1605            .expect("startup warm-up must complete before signing");
1606        let input = b"header.payload";
1607        let signature = store
1608            .sign_for_hosted_did(&oauth_authority(), did, input)
1609            .await
1610            .unwrap()
1611            .expect("hosted account key");
1612        let signature = p256::ecdsa::Signature::from_slice(&signature).unwrap();
1613        verifying_key.verify(input, &signature).unwrap();
1614
1615        let denied = store
1616            .sign_for_hosted_did(&Subject::new("alice"), did, input)
1617            .await
1618            .unwrap_err();
1619        assert!(matches!(
1620            denied,
1621            AccountReadError::UnauthorizedTenantResolver(_)
1622        ));
1623
1624        let missing_root =
1625            SyntheticNode::dir().with_child("acme", tenant_node("alice", record.clone()));
1626        let missing = AccountRecordStore::new(
1627            Arc::new(SyntheticMount::new(missing_root)),
1628            permit_account_reads(),
1629        );
1630        missing
1631            .refresh_hosted_did_index(&oauth_authority())
1632            .await
1633            .expect("startup warm-up must complete before signing");
1634        let missing = missing
1635            .sign_for_hosted_did(&oauth_authority(), did, input)
1636            .await
1637            .unwrap_err();
1638        assert!(matches!(
1639            missing,
1640            AccountReadError::SigningKeyUnavailable(_)
1641        ));
1642
1643        let (_, other_key) = account_artifacts("other", "acme.example");
1644        let mismatch_root = SyntheticNode::dir()
1645            .with_child("acme", tenant_node_with_key("alice", record, other_key));
1646        let mismatch = AccountRecordStore::new(
1647            Arc::new(SyntheticMount::new(mismatch_root)),
1648            permit_account_reads(),
1649        );
1650        mismatch
1651            .refresh_hosted_did_index(&oauth_authority())
1652            .await
1653            .expect("startup warm-up must complete before signing");
1654        let mismatch = mismatch
1655            .sign_for_hosted_did(&oauth_authority(), did, input)
1656            .await
1657            .unwrap_err();
1658        assert!(matches!(mismatch, AccountReadError::SigningKeyMismatch(_)));
1659    }
1660
1661    #[test]
1662    fn missing_verified_tenant_fails_closed() {
1663        let signer = SigningKey::generate(&mut OsRng);
1664        let context = EnvelopeContext::for_test_authenticated_subject(
1665            Subject::new("alice"),
1666            signer.verifying_key(),
1667        );
1668        let error = store().scope(&context).err().expect("scope must be denied");
1669        assert!(matches!(error, AccountReadError::MissingVerifiedTenant));
1670    }
1671
1672    #[tokio::test]
1673    async fn unauthenticated_and_path_injection_fail_before_mount_access() {
1674        let store = store();
1675        let signer = SigningKey::generate(&mut OsRng);
1676        let unauthenticated = EnvelopeContext::for_test_authenticated_subject_in_tenant(
1677            Subject::anonymous(),
1678            "acme",
1679            signer.verifying_key(),
1680        );
1681        let error = store
1682            .scope(&unauthenticated)
1683            .err()
1684            .expect("unauthenticated caller must be denied");
1685        assert!(matches!(error, AccountReadError::UnauthenticatedCaller));
1686
1687        let error = store
1688            .scope(&context("../acme"))
1689            .err()
1690            .expect("invalid tenant must be denied");
1691        assert!(matches!(error, AccountReadError::InvalidVerifiedTenant(_)));
1692
1693        let scope = store.scope(&context("acme")).unwrap();
1694        let error = scope
1695            .get("../beta")
1696            .await
1697            .expect_err("invalid label must be denied");
1698        assert!(matches!(error, AccountReadError::InvalidAccountLabel(_)));
1699    }
1700
1701    #[tokio::test]
1702    async fn oversized_and_mislabeled_records_fail_closed() {
1703        let oversized = SyntheticNode::dir().with_child("acme", tenant_node("alice", vec![0; 32]));
1704        let store = AccountRecordStore::new(
1705            Arc::new(SyntheticMount::new(oversized)),
1706            permit_account_reads(),
1707        )
1708        .with_max_record_bytes(8);
1709        let error = store
1710            .scope(&context("acme"))
1711            .unwrap()
1712            .get("alice")
1713            .await
1714            .expect_err("oversized record must fail");
1715        assert!(matches!(error, AccountReadError::RecordTooLarge { .. }));
1716
1717        let mislabeled = SyntheticNode::dir().with_child(
1718            "acme",
1719            tenant_node("bob", account_bytes("alice", "acme.example")),
1720        );
1721        let error = AccountRecordStore::new(
1722            Arc::new(SyntheticMount::new(mislabeled)),
1723            permit_account_reads(),
1724        )
1725        .scope(&context("acme"))
1726        .unwrap()
1727        .get("bob")
1728        .await
1729        .expect_err("mislabeled record must fail");
1730        assert!(matches!(
1731            error,
1732            AccountReadError::RecordLabelMismatch { .. }
1733        ));
1734    }
1735}