Skip to main content

hyprstream_pds_service/
account_http.rs

1//! Credential-free HTTP face for hosted-account identity artifacts (#1165).
2//!
3//! The router in this module is intentionally a complete, small Axum router
4//! with no session, cookie, bearer, or authorization middleware. It serves
5//! immutable bytes loaded from sealed publication artifacts on a separately
6//! bound listener. The listener and TLS termination are deployment concerns;
7//! this module owns the routing and credential-free security contract.
8
9use std::{collections::BTreeMap, sync::Arc};
10
11use anyhow::{ensure, Result};
12use async_trait::async_trait;
13use axum::{
14    extract::{Request, State},
15    http::{header, uri::Authority, HeaderMap, HeaderValue, StatusCode},
16    response::{IntoResponse, Response},
17    routing::get,
18    Router,
19};
20use hyprstream_pds::{
21    AccountLabel, AccountRecord, GenesisDidOp, SealedHostedAccount, SealedHostedDidDocument,
22};
23
24use crate::{
25    AccountRecordStore, OAUTH_ACCOUNT_RESOLVER_SUBJECT, PDS_ACCOUNT_DID_DOCUMENT_FILE,
26    PDS_ACCOUNT_DID_LOG_FILE, PDS_ACCOUNT_RECORD_FILE,
27};
28
29/// Canonical hosted account zone used by the default deployment.
30pub const DEFAULT_ACCOUNT_ZONE: &str = "tormentnexus.social";
31
32/// A byte-stable set of artifacts for one hosted account.
33///
34/// Values are copied into this object once, at publication/index-load time.
35/// Request handlers only clone the `Arc`-backed bytes; they never regenerate
36/// or reserialize a DID document or operation log.
37#[derive(Clone, Debug, Eq, PartialEq)]
38pub struct HostedAccountHttpArtifacts {
39    label: String,
40    did: String,
41    did_document: Arc<[u8]>,
42    atproto_did: Arc<[u8]>,
43    did_log: Arc<[u8]>,
44}
45
46impl HostedAccountHttpArtifacts {
47    /// Construct an artifact bundle after the publisher has validated the
48    /// sealed bytes. The constructor checks identity binding and rejects empty
49    /// artifacts; it does not parse or rewrite any bytes.
50    pub fn new(
51        label: impl Into<String>,
52        did: impl Into<String>,
53        did_document: impl Into<Vec<u8>>,
54        atproto_did: impl Into<Vec<u8>>,
55        did_log: impl Into<Vec<u8>>,
56    ) -> Result<Self> {
57        let label = label.into();
58        AccountLabel::parse(&label).map_err(|error| anyhow::anyhow!(error))?;
59        let did = did.into();
60        let host = did
61            .strip_prefix("did:web:")
62            .ok_or_else(|| anyhow::anyhow!("hosted account HTTP artifact DID is not did:web"))?;
63        ensure!(
64            !host.is_empty()
65                && !host.contains([':', '/'])
66                && host.split('.').count() >= 2
67                && host.split('.').next() == Some(label.as_str()),
68            "hosted account HTTP artifact DID does not match its label"
69        );
70        for component in host.split('.') {
71            ensure!(
72                !component.is_empty()
73                    && component.len() <= 63
74                    && component.bytes().all(|byte| {
75                        byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-'
76                    })
77                    && !component.starts_with('-')
78                    && !component.ends_with('-'),
79                "hosted account HTTP artifact DID contains an invalid DNS label"
80            );
81        }
82        let did_document: Arc<[u8]> = did_document.into().into();
83        let atproto_did: Arc<[u8]> = atproto_did.into().into();
84        let did_log: Arc<[u8]> = did_log.into().into();
85        ensure!(!did_document.is_empty(), "sealed DID document is empty");
86        ensure!(
87            !atproto_did.is_empty(),
88            "sealed atproto DID artifact is empty"
89        );
90        ensure!(!did_log.is_empty(), "sealed DID operation log is empty");
91        ensure!(
92            atproto_did.as_ref() == did.as_bytes(),
93            "atproto DID artifact does not match its sealed DID"
94        );
95        Ok(Self {
96            label,
97            did,
98            did_document,
99            atproto_did,
100            did_log,
101        })
102    }
103
104    /// Build the HTTP bundle from a sealed account publication.
105    ///
106    /// `SealedHostedAccount` has already bound the DID document and operation
107    /// log into the signed genesis. This method only copies those exact bytes
108    /// and creates the plaintext atproto-did artifact once.
109    pub fn from_sealed(account: &SealedHostedAccount) -> Result<Self> {
110        let label = account.record().name().label().to_owned();
111        let did = account.record().name().did().to_owned();
112        let document = account.did_document().as_bytes();
113        let parsed = hyprstream_pds::SealedHostedDidDocument::from_canonical_json(document)?;
114        ensure!(
115            parsed.did() == did,
116            "sealed DID document does not match account record"
117        );
118        Self::new(
119            label,
120            did.clone(),
121            document.to_vec(),
122            did.into_bytes(),
123            account.genesis_bytes().to_vec(),
124        )
125    }
126
127    #[must_use]
128    pub fn label(&self) -> &str {
129        &self.label
130    }
131
132    #[must_use]
133    pub fn did(&self) -> &str {
134        &self.did
135    }
136
137    #[must_use]
138    pub fn did_document(&self) -> &[u8] {
139        &self.did_document
140    }
141
142    #[must_use]
143    pub fn atproto_did(&self) -> &[u8] {
144        &self.atproto_did
145    }
146
147    #[must_use]
148    pub fn did_log(&self) -> &[u8] {
149        &self.did_log
150    }
151}
152
153/// Read-only account artifact index used by the credential-free router.
154#[async_trait]
155pub trait HostedAccountHttpDirectory: Send + Sync {
156    /// Return the immutable artifact bundle for one canonical host label.
157    async fn lookup(&self, label: &str) -> Result<Option<Arc<HostedAccountHttpArtifacts>>>;
158}
159
160/// Immutable in-memory index suitable for a startup-loaded sealed artifact
161/// snapshot and for deterministic tests.
162#[derive(Clone, Default)]
163pub struct StaticHostedAccountHttpDirectory {
164    entries: Arc<BTreeMap<String, Arc<HostedAccountHttpArtifacts>>>,
165}
166
167impl StaticHostedAccountHttpDirectory {
168    pub fn new(artifacts: impl IntoIterator<Item = HostedAccountHttpArtifacts>) -> Result<Self> {
169        let mut entries = BTreeMap::new();
170        for artifact in artifacts {
171            let label = artifact.label().to_owned();
172            ensure!(
173                entries.insert(label.clone(), Arc::new(artifact)).is_none(),
174                "duplicate hosted account HTTP label {label:?}"
175            );
176        }
177        Ok(Self {
178            entries: Arc::new(entries),
179        })
180    }
181}
182
183#[async_trait]
184impl HostedAccountHttpDirectory for StaticHostedAccountHttpDirectory {
185    async fn lookup(&self, label: &str) -> Result<Option<Arc<HostedAccountHttpArtifacts>>> {
186        Ok(self.entries.get(label).cloned())
187    }
188}
189
190/// Live adapter that loads the immutable artifact bundle from the authorized
191/// PDS mount. The OAuth service identity is fixed at construction; callers
192/// cannot substitute a tenant or subject through an HTTP request.
193#[derive(Clone)]
194pub struct MountedHostedAccountHttpDirectory {
195    store: Arc<AccountRecordStore>,
196    authority: hyprstream_rpc::Subject,
197    zone: String,
198}
199
200impl MountedHostedAccountHttpDirectory {
201    pub fn new(
202        store: Arc<AccountRecordStore>,
203        authority: hyprstream_rpc::Subject,
204        zone: impl Into<String>,
205    ) -> Result<Self> {
206        Self::new_inner(store, authority, zone, true)
207    }
208
209    /// Construct a directory without scheduling a refresh on the caller's
210    /// runtime. Production OAuth uses this after performing the bounded warm-up
211    /// on its owned runtime, avoiding detached blocking work during shutdown.
212    pub fn new_without_refresh(
213        store: Arc<AccountRecordStore>,
214        authority: hyprstream_rpc::Subject,
215        zone: impl Into<String>,
216    ) -> Result<Self> {
217        Self::new_inner(store, authority, zone, false)
218    }
219
220    fn new_inner(
221        store: Arc<AccountRecordStore>,
222        authority: hyprstream_rpc::Subject,
223        zone: impl Into<String>,
224        schedule_refresh: bool,
225    ) -> Result<Self> {
226        ensure!(
227            authority.name() == Some(OAUTH_ACCOUNT_RESOLVER_SUBJECT),
228            "hosted HTTP directory requires the fixed OAuth resolver subject"
229        );
230        let directory = Self {
231            store,
232            authority,
233            zone: canonical_zone(&zone.into())?,
234        };
235        if schedule_refresh {
236            directory
237                .store
238                .schedule_hosted_did_index_refresh(directory.authority.clone());
239        }
240        Ok(directory)
241    }
242}
243
244#[async_trait]
245impl HostedAccountHttpDirectory for MountedHostedAccountHttpDirectory {
246    async fn lookup(&self, label: &str) -> Result<Option<Arc<HostedAccountHttpArtifacts>>> {
247        AccountLabel::parse(label).map_err(|error| anyhow::anyhow!(error))?;
248        let did = format!("did:web:{label}.{}", self.zone);
249        // The store keeps a refreshed immutable label/DID index, so each
250        // request performs one bounded map lookup. Index refresh is serialized
251        // independently and never holds the request lookup lock.
252        let tenant = self
253            .store
254            .resolve_tenant_for_hosted_did(&self.authority, &did)
255            .await?;
256        let Some(tenant) = tenant else {
257            return Ok(None);
258        };
259        let record_bytes = self
260            .store
261            .read_hosted_http_artifact(
262                &self.authority,
263                &tenant,
264                label,
265                PDS_ACCOUNT_RECORD_FILE,
266                16 * 1024,
267            )
268            .await?;
269        let record = AccountRecord::from_dag_cbor(&record_bytes)?;
270        ensure!(
271            record.name().label() == label && record.name().did() == did,
272            "hosted account record does not match host"
273        );
274        let document = self
275            .store
276            .read_hosted_http_artifact(
277                &self.authority,
278                &tenant,
279                label,
280                PDS_ACCOUNT_DID_DOCUMENT_FILE,
281                16 * 1024,
282            )
283            .await?;
284        let parsed = SealedHostedDidDocument::from_canonical_json(&document)?;
285        ensure!(
286            parsed.did() == did && parsed.cid() == record.doc_cid(),
287            "served DID document does not match host or account record"
288        );
289        ensure!(
290            parsed.atproto_verifying_key()?.to_encoded_point(true)
291                == record.atproto_verifying_key()?.to_encoded_point(true),
292            "served DID document #atproto key does not match account record"
293        );
294        let log = self
295            .store
296            .read_hosted_http_artifact(
297                &self.authority,
298                &tenant,
299                label,
300                PDS_ACCOUNT_DID_LOG_FILE,
301                64 * 1024,
302            )
303            .await?;
304        let genesis = GenesisDidOp::from_dag_cbor(&log)?;
305        ensure!(
306            genesis.cid()? == record.genesis_op(),
307            "served genesis operation does not match account record"
308        );
309        ensure!(
310            genesis.unsigned().did() == did,
311            "served genesis operation does not match hosted DID"
312        );
313        ensure!(
314            genesis.unsigned().doc_cid() == record.doc_cid(),
315            "served genesis operation does not match account document"
316        );
317        // This immutable layout contains only the sealed genesis envelope,
318        // not a validated update chain. Match the sealed-bundle and hosted
319        // connect-time validators instead of presenting genesis as current.
320        ensure!(
321            record.current_op() == record.genesis_op(),
322            "immutable hosted account record current operation is not genesis"
323        );
324        Ok(Some(Arc::new(HostedAccountHttpArtifacts::new(
325            label,
326            did.clone(),
327            document,
328            did.into_bytes(),
329            log,
330        )?)))
331    }
332}
333
334#[derive(Clone)]
335struct AccountHttpState {
336    zone: String,
337    directory: Arc<dyn HostedAccountHttpDirectory>,
338}
339
340/// Build the separate credential-free account-artifact router.
341///
342/// The returned router has only three GET routes and no layers. Bind it to a
343/// distinct listener from authenticated OAuth/XRPC routes. The caller remains
344/// responsible for binding the wildcard certificate and for refusing to mount
345/// this router into an authenticated listener.
346pub fn router(
347    zone: impl Into<String>,
348    directory: Arc<dyn HostedAccountHttpDirectory>,
349) -> Result<Router> {
350    let zone = canonical_zone(&zone.into())?;
351    let state = AccountHttpState { zone, directory };
352    Ok(Router::new()
353        .route("/.well-known/did.json", get(serve_did_document))
354        .route("/.well-known/atproto-did", get(serve_atproto_did))
355        .route("/.well-known/did-log.json", get(serve_did_log))
356        .with_state(Arc::new(state)))
357}
358
359async fn serve_did_document(
360    State(state): State<Arc<AccountHttpState>>,
361    request: Request,
362) -> Response {
363    serve_artifact(&state, request, ArtifactKind::DidDocument).await
364}
365
366async fn serve_atproto_did(
367    State(state): State<Arc<AccountHttpState>>,
368    request: Request,
369) -> Response {
370    serve_artifact(&state, request, ArtifactKind::AtprotoDid).await
371}
372
373async fn serve_did_log(State(state): State<Arc<AccountHttpState>>, request: Request) -> Response {
374    serve_artifact(&state, request, ArtifactKind::DidLog).await
375}
376
377#[derive(Clone, Copy)]
378enum ArtifactKind {
379    DidDocument,
380    AtprotoDid,
381    DidLog,
382}
383
384async fn serve_artifact(
385    state: &AccountHttpState,
386    request: Request,
387    kind: ArtifactKind,
388) -> Response {
389    // A credential-bearing request must never reach an artifact lookup. This
390    // explicit rejection is the testable security boundary for the separate
391    // origin; there is no cookie/session/bearer middleware to accidentally
392    // inherit from the authenticated service.
393    let label = {
394        let headers: &HeaderMap = request.headers();
395        if headers.contains_key(header::AUTHORIZATION) || headers.contains_key(header::COOKIE) {
396            return (StatusCode::BAD_REQUEST, "credentials are not accepted").into_response();
397        }
398        // HTTP/1.1 supplies Host, while HTTP/2 carries the origin in the
399        // :authority pseudo-header, which `http` exposes as the URI authority.
400        // When both are present, they must be byte-identical: accepting a
401        // mismatched Host would let a proxy route one public account while the
402        // request authority names another. Only an absent URI authority may
403        // use Host as its target.
404        let uri_authority = request.uri().authority().map(Authority::as_str);
405        let host_header = headers
406            .get(header::HOST)
407            .map(|value| value.to_str().unwrap_or_default());
408        if headers.contains_key(header::HOST) && host_header == Some("") {
409            return StatusCode::BAD_REQUEST.into_response();
410        }
411        let host = match (uri_authority, host_header) {
412            (Some(authority), Some(host))
413                if !equivalent_authorities(authority, host, &state.zone) =>
414            {
415                return StatusCode::BAD_REQUEST.into_response();
416            }
417            (Some(authority), _) => authority,
418            (None, Some(host)) => host,
419            (None, None) => return StatusCode::BAD_REQUEST.into_response(),
420        };
421        if host.is_empty() {
422            return negative_response(StatusCode::BAD_REQUEST);
423        }
424        let Some(label) = host_label(host, &state.zone) else {
425            return negative_response(StatusCode::NOT_FOUND);
426        };
427        label
428    };
429    drop(request);
430    let artifact = match state.directory.lookup(&label).await {
431        Ok(Some(artifact)) => artifact,
432        Ok(None) => return negative_response(StatusCode::NOT_FOUND),
433        Err(_) => return StatusCode::SERVICE_UNAVAILABLE.into_response(),
434    };
435    if artifact.did() != format!("did:web:{label}.{}", state.zone) {
436        return StatusCode::NOT_FOUND.into_response();
437    }
438    let (body, content_type): (&[u8], &'static str) = match kind {
439        ArtifactKind::DidDocument => (artifact.did_document(), "application/did+json"),
440        ArtifactKind::AtprotoDid => (artifact.atproto_did(), "text/plain; charset=utf-8"),
441        // The current sealed operation-log artifact is a signed CBOR genesis
442        // envelope even though the stable URL retains its historical .json
443        // suffix. Never transcode it at the HTTP boundary.
444        ArtifactKind::DidLog => (artifact.did_log(), "application/cbor"),
445    };
446    let mut response = body.to_vec().into_response();
447    response
448        .headers_mut()
449        .insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
450    response.headers_mut().insert(
451        header::CACHE_CONTROL,
452        HeaderValue::from_static("public, max-age=300, immutable"),
453    );
454    response
455}
456
457fn negative_response(status: StatusCode) -> Response {
458    let mut response = status.into_response();
459    response
460        .headers_mut()
461        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
462    response
463}
464
465fn canonical_zone(zone: &str) -> Result<String> {
466    ensure!(
467        !zone.is_empty() && zone.is_ascii(),
468        "account zone must be ASCII"
469    );
470    let zone = zone.trim_end_matches('.');
471    let labels: Vec<&str> = zone.split('.').collect();
472    ensure!(labels.len() >= 2, "account zone must contain two labels");
473    for label in labels {
474        ensure!(
475            !label.is_empty()
476                && label.len() <= 63
477                && label
478                    .bytes()
479                    .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
480                && !label.starts_with('-')
481                && !label.ends_with('-'),
482            "account zone contains an invalid DNS label"
483        );
484    }
485    Ok(zone.to_owned())
486}
487
488fn host_label(host: &str, zone: &str) -> Option<String> {
489    if host.contains('@') {
490        return None;
491    }
492    let authority: Authority = host.parse().ok()?;
493    if host.contains(':') {
494        let port = authority.port()?;
495        if !port.as_str().bytes().all(|byte| byte.is_ascii_digit()) {
496            return None;
497        }
498    }
499    let hostname = authority.host().trim_end_matches('.').to_ascii_lowercase();
500    let suffix = format!(".{zone}");
501    let label = hostname.strip_suffix(&suffix)?;
502    if label.contains('.') {
503        return None;
504    }
505    AccountLabel::parse(label).ok().map(|_| label.to_owned())
506}
507
508fn equivalent_authorities(left: &str, right: &str, zone: &str) -> bool {
509    let Some(left_label) = host_label(left, zone) else {
510        return false;
511    };
512    let Some(right_label) = host_label(right, zone) else {
513        return false;
514    };
515    if left_label != right_label {
516        return false;
517    }
518    let Ok(left_authority) = left.parse::<Authority>() else {
519        return false;
520    };
521    let Ok(right_authority) = right.parse::<Authority>() else {
522        return false;
523    };
524    let effective_port = |authority: &Authority| {
525        authority
526            .port()
527            .map_or(Some(443), |port| port.as_str().parse::<u16>().ok())
528    };
529    effective_port(&left_authority) == effective_port(&right_authority)
530}
531
532#[cfg(test)]
533mod tests {
534    #![allow(clippy::expect_used, clippy::unwrap_used)]
535
536    use super::*;
537    use axum::{body::to_bytes, http::Request};
538    use ed25519_dalek::SigningKey;
539    use hyprstream_crypto::pq::{ml_dsa_generate_keypair, ml_dsa_vk_bytes};
540    use hyprstream_pds::dag_cbor::DagCbor;
541    use hyprstream_pds::did_op::{
542        sign_genesis, GenesisRepoHead, GenesisRotationKeys, HostKeyEnrollment, HybridRotationKey,
543        RecoveryKeyEnrollment, UserRotationKey,
544    };
545    use hyprstream_pds::{
546        AllocatedAccountName, Cid, HostedAccountMint, DID_DOCUMENT_FILE, GENESIS_DID_OP_FILE,
547    };
548    use hyprstream_rpc::auth::mac::{MacDecision, SecurityContext};
549    use hyprstream_rpc::Subject;
550    use hyprstream_vfs::{SyntheticMount, SyntheticNode};
551    use rand::rngs::OsRng;
552    use tower::ServiceExt;
553
554    use crate::{PDS_ACCOUNTS_DIRECTORY, PDS_ACCOUNT_RECORD_FILE};
555
556    struct PermitReads;
557
558    impl crate::AccountRecordReadAuthorizer for PermitReads {
559        fn check_read(
560            &self,
561            _subject: &Subject,
562            _verified_tenant: Option<&str>,
563            _security_context: Option<&SecurityContext>,
564            _object_id: &str,
565        ) -> MacDecision {
566            MacDecision::Permit
567        }
568    }
569
570    fn directory() -> Arc<StaticHostedAccountHttpDirectory> {
571        Arc::new(
572            StaticHostedAccountHttpDirectory::new([HostedAccountHttpArtifacts::new(
573                "alice",
574                "did:web:alice.tormentnexus.social",
575                b"sealed-did-document".to_vec(),
576                b"did:web:alice.tormentnexus.social".to_vec(),
577                b"sealed-did-log".to_vec(),
578            )
579            .unwrap()])
580            .unwrap(),
581        )
582    }
583
584    fn mounted_directory() -> (
585        Arc<MountedHostedAccountHttpDirectory>,
586        Vec<u8>,
587        Vec<u8>,
588        Vec<u8>,
589    ) {
590        mounted_directory_with_files(None, None, None)
591    }
592
593    fn mounted_directory_with_files(
594        record_override: Option<Vec<u8>>,
595        document_override: Option<Vec<u8>>,
596        log_override: Option<Vec<u8>>,
597    ) -> (
598        Arc<MountedHostedAccountHttpDirectory>,
599        Vec<u8>,
600        Vec<u8>,
601        Vec<u8>,
602    ) {
603        let ed = SigningKey::generate(&mut OsRng);
604        let (pq, pq_vk) = ml_dsa_generate_keypair();
605        let hybrid =
606            HybridRotationKey::new(ed.verifying_key().to_bytes(), ml_dsa_vk_bytes(&pq_vk)).unwrap();
607        let rotations = GenesisRotationKeys::new(
608            UserRotationKey::new(hybrid),
609            RecoveryKeyEnrollment::Declined,
610            HostKeyEnrollment::Absent,
611        )
612        .unwrap();
613        let name =
614            AllocatedAccountName::new("alice", "did:web:alice.tormentnexus.social".to_owned())
615                .unwrap();
616        let mint = HostedAccountMint::begin(name, rotations).unwrap();
617        let document = mint.seal_did_document("https://pds.example.com").unwrap();
618        let pending = mint
619            .prepare_genesis(document, GenesisRepoHead::EmptyRepo)
620            .unwrap();
621        let signature = sign_genesis(pending.unsigned_genesis(), &ed, &pq).unwrap();
622        let account = pending.seal(signature).unwrap();
623        let record_bytes = account.record_bytes().to_vec();
624        let document_bytes = account.did_document().as_bytes().to_vec();
625        let log_bytes = account.genesis_bytes().to_vec();
626        let record_file = record_override.unwrap_or_else(|| record_bytes.clone());
627        let document_file = document_override.unwrap_or_else(|| document_bytes.clone());
628        let log_file = log_override.unwrap_or_else(|| log_bytes.clone());
629        let root = SyntheticNode::dir().with_child(
630            "tenant",
631            SyntheticNode::dir().with_child(
632                PDS_ACCOUNTS_DIRECTORY,
633                SyntheticNode::dir().with_child(
634                    "alice",
635                    SyntheticNode::dir()
636                        .with_child(PDS_ACCOUNT_RECORD_FILE, SyntheticNode::file(record_file))
637                        .with_child(DID_DOCUMENT_FILE, SyntheticNode::file(document_file))
638                        .with_child(GENESIS_DID_OP_FILE, SyntheticNode::file(log_file)),
639                ),
640            ),
641        );
642        let store = Arc::new(crate::AccountRecordStore::new(
643            Arc::new(SyntheticMount::new(root)),
644            Arc::new(PermitReads),
645        ));
646        let directory = Arc::new(
647            MountedHostedAccountHttpDirectory::new(
648                store,
649                Subject::new(crate::OAUTH_ACCOUNT_RESOLVER_SUBJECT),
650                DEFAULT_ACCOUNT_ZONE,
651            )
652            .unwrap(),
653        );
654        (directory, document_bytes, log_bytes, record_bytes)
655    }
656
657    fn alternate_genesis_same_did() -> Vec<u8> {
658        let ed = SigningKey::generate(&mut OsRng);
659        let (pq, pq_vk) = ml_dsa_generate_keypair();
660        let hybrid =
661            HybridRotationKey::new(ed.verifying_key().to_bytes(), ml_dsa_vk_bytes(&pq_vk)).unwrap();
662        let rotations = GenesisRotationKeys::new(
663            UserRotationKey::new(hybrid),
664            RecoveryKeyEnrollment::Declined,
665            HostKeyEnrollment::Absent,
666        )
667        .unwrap();
668        let name =
669            AllocatedAccountName::new("alice", "did:web:alice.tormentnexus.social".to_owned())
670                .unwrap();
671        let mint = HostedAccountMint::begin(name, rotations).unwrap();
672        let document = mint
673            .seal_did_document("https://alternate.example.com")
674            .unwrap();
675        let pending = mint
676            .prepare_genesis(document, GenesisRepoHead::EmptyRepo)
677            .unwrap();
678        let signature = sign_genesis(pending.unsigned_genesis(), &ed, &pq).unwrap();
679        pending.seal(signature).unwrap().genesis_bytes().to_vec()
680    }
681
682    #[tokio::test]
683    async fn serves_exact_sealed_bytes_by_host_label() {
684        let app = router("tormentnexus.social", directory()).unwrap();
685        let response = app
686            .oneshot(
687                Request::builder()
688                    .uri("/.well-known/did.json")
689                    .header(header::HOST, "alice.tormentnexus.social")
690                    .body(axum::body::Body::empty())
691                    .unwrap(),
692            )
693            .await
694            .unwrap();
695        assert_eq!(response.status(), StatusCode::OK);
696        assert_eq!(
697            response.headers()[header::CONTENT_TYPE],
698            "application/did+json"
699        );
700        assert_eq!(
701            to_bytes(response.into_body(), 1024).await.unwrap().as_ref(),
702            b"sealed-did-document"
703        );
704    }
705
706    #[tokio::test]
707    async fn authority_only_requests_use_http2_uri_authority() {
708        let app = router("tormentnexus.social", directory()).unwrap();
709        let response = app
710            .oneshot(
711                Request::builder()
712                    .uri("https://alice.tormentnexus.social/.well-known/did.json")
713                    .body(axum::body::Body::empty())
714                    .unwrap(),
715            )
716            .await
717            .unwrap();
718        assert_eq!(response.status(), StatusCode::OK);
719        assert_eq!(
720            to_bytes(response.into_body(), 1024).await.unwrap().as_ref(),
721            b"sealed-did-document"
722        );
723    }
724
725    #[tokio::test]
726    async fn mismatched_http2_authority_and_host_fail_closed() {
727        let app = router("tormentnexus.social", directory()).unwrap();
728        let response = app
729            .oneshot(
730                Request::builder()
731                    .uri("https://bob.tormentnexus.social/.well-known/did.json")
732                    .header(header::HOST, "alice.tormentnexus.social")
733                    .body(axum::body::Body::empty())
734                    .unwrap(),
735            )
736            .await
737            .unwrap();
738        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
739    }
740
741    #[tokio::test]
742    async fn equivalent_http2_authority_and_host_ignore_dns_case() {
743        let app = router("tormentnexus.social", directory()).unwrap();
744        let response = app
745            .oneshot(
746                Request::builder()
747                    .uri("https://alice.tormentnexus.social/.well-known/did.json")
748                    .header(header::HOST, "ALICE.TORMENTNEXUS.SOCIAL")
749                    .body(axum::body::Body::empty())
750                    .unwrap(),
751            )
752            .await
753            .unwrap();
754        assert_eq!(response.status(), StatusCode::OK);
755    }
756
757    #[test]
758    fn equivalent_authorities_accept_implicit_https_port() {
759        assert!(equivalent_authorities(
760            "alice.tormentnexus.social",
761            "alice.tormentnexus.social:443",
762            "tormentnexus.social",
763        ));
764        assert!(!equivalent_authorities(
765            "alice.tormentnexus.social",
766            "alice.tormentnexus.social:8443",
767            "tormentnexus.social",
768        ));
769    }
770
771    #[tokio::test]
772    async fn authority_only_requests_still_reject_credentials() {
773        let app = router("tormentnexus.social", directory()).unwrap();
774        for name in [header::AUTHORIZATION, header::COOKIE] {
775            let response = app
776                .clone()
777                .oneshot(
778                    Request::builder()
779                        .uri("https://alice.tormentnexus.social/.well-known/did.json")
780                        .header(name, "present")
781                        .body(axum::body::Body::empty())
782                        .unwrap(),
783                )
784                .await
785                .unwrap();
786            assert_eq!(response.status(), StatusCode::BAD_REQUEST);
787        }
788    }
789
790    #[tokio::test]
791    async fn hostname_matching_is_case_insensitive() {
792        let app = router("tormentnexus.social", directory()).unwrap();
793        let response = app
794            .oneshot(
795                Request::builder()
796                    .uri("/.well-known/did.json")
797                    .header(header::HOST, "ALICE.TORMENTNEXUS.SOCIAL")
798                    .body(axum::body::Body::empty())
799                    .unwrap(),
800            )
801            .await
802            .unwrap();
803        assert_eq!(response.status(), StatusCode::OK);
804    }
805
806    #[tokio::test]
807    async fn unallocated_label_404_is_not_cached() {
808        let app = router("tormentnexus.social", directory()).unwrap();
809        let response = app
810            .oneshot(
811                Request::builder()
812                    .uri("/.well-known/did.json")
813                    .header(header::HOST, "bob.tormentnexus.social")
814                    .body(axum::body::Body::empty())
815                    .unwrap(),
816            )
817            .await
818            .unwrap();
819        assert_eq!(response.status(), StatusCode::NOT_FOUND);
820        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
821    }
822
823    #[tokio::test]
824    async fn serves_atproto_did_and_did_log_without_transcoding() {
825        let app = router("tormentnexus.social", directory()).unwrap();
826        for (path, expected, content_type) in [
827            (
828                "/.well-known/atproto-did",
829                &b"did:web:alice.tormentnexus.social"[..],
830                "text/plain; charset=utf-8",
831            ),
832            (
833                "/.well-known/did-log.json",
834                &b"sealed-did-log"[..],
835                "application/cbor",
836            ),
837        ] {
838            let response = app
839                .clone()
840                .oneshot(
841                    Request::builder()
842                        .uri(path)
843                        .header(header::HOST, "alice.tormentnexus.social:443")
844                        .body(axum::body::Body::empty())
845                        .unwrap(),
846                )
847                .await
848                .unwrap();
849            assert_eq!(response.status(), StatusCode::OK);
850            assert_eq!(response.headers()[header::CONTENT_TYPE], content_type);
851            assert_eq!(
852                to_bytes(response.into_body(), 1024).await.unwrap(),
853                expected
854            );
855        }
856    }
857
858    #[tokio::test]
859    async fn unknown_or_malformed_hosts_are_not_synthesized() {
860        let app = router("tormentnexus.social", directory()).unwrap();
861        for host in [
862            "bob.tormentnexus.social",
863            "alice.other.example",
864            "nested.alice.tormentnexus.social",
865            "-alice.tormentnexus.social",
866            "attacker@alice.tormentnexus.social",
867            "alice.tormentnexus.social:bad",
868        ] {
869            let response = app
870                .clone()
871                .oneshot(
872                    Request::builder()
873                        .uri("/.well-known/did.json")
874                        .header(header::HOST, host)
875                        .body(axum::body::Body::empty())
876                        .unwrap(),
877                )
878                .await
879                .unwrap();
880            assert_eq!(response.status(), StatusCode::NOT_FOUND, "host={host}");
881        }
882        let response = app
883            .oneshot(
884                Request::builder()
885                    .uri("/.well-known/did.json")
886                    .body(axum::body::Body::empty())
887                    .unwrap(),
888            )
889            .await
890            .unwrap();
891        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
892    }
893
894    #[tokio::test]
895    async fn credentials_are_rejected_before_lookup() {
896        let app = router("tormentnexus.social", directory()).unwrap();
897        for name in [header::AUTHORIZATION, header::COOKIE] {
898            let response = app
899                .clone()
900                .oneshot(
901                    Request::builder()
902                        .uri("/.well-known/did.json")
903                        .header(header::HOST, "alice.tormentnexus.social")
904                        .header(name, "present")
905                        .body(axum::body::Body::empty())
906                        .unwrap(),
907                )
908                .await
909                .unwrap();
910            assert_eq!(response.status(), StatusCode::BAD_REQUEST);
911        }
912    }
913
914    #[tokio::test]
915    async fn mounted_directory_reads_only_authorized_sealed_files() {
916        let (directory, document, log, _record) = mounted_directory();
917        directory
918            .store
919            .refresh_hosted_did_index(&directory.authority)
920            .await
921            .unwrap();
922        let app = router(DEFAULT_ACCOUNT_ZONE, directory).unwrap();
923        let did_response = app
924            .clone()
925            .oneshot(
926                Request::builder()
927                    .uri("/.well-known/did.json")
928                    .header(header::HOST, "alice.tormentnexus.social")
929                    .body(axum::body::Body::empty())
930                    .unwrap(),
931            )
932            .await
933            .unwrap();
934        assert_eq!(did_response.status(), StatusCode::OK);
935        assert_eq!(
936            to_bytes(did_response.into_body(), 16 * 1024)
937                .await
938                .unwrap()
939                .as_ref(),
940            document
941        );
942        let log_response = app
943            .oneshot(
944                Request::builder()
945                    .uri("/.well-known/did-log.json")
946                    .header(header::HOST, "alice.tormentnexus.social")
947                    .body(axum::body::Body::empty())
948                    .unwrap(),
949            )
950            .await
951            .unwrap();
952        assert_eq!(log_response.status(), StatusCode::OK);
953        assert_eq!(
954            to_bytes(log_response.into_body(), 64 * 1024)
955                .await
956                .unwrap()
957                .as_ref(),
958            log
959        );
960    }
961
962    #[tokio::test]
963    async fn mounted_directory_unallocated_404_is_not_cached() {
964        let (directory, _document, _log, _record) = mounted_directory();
965        directory
966            .store
967            .refresh_hosted_did_index(&directory.authority)
968            .await
969            .unwrap();
970        let response = router(DEFAULT_ACCOUNT_ZONE, directory)
971            .unwrap()
972            .oneshot(
973                Request::builder()
974                    .uri("/.well-known/did.json")
975                    .header(header::HOST, "bob.tormentnexus.social")
976                    .body(axum::body::Body::empty())
977                    .unwrap(),
978            )
979            .await
980            .unwrap();
981        assert_eq!(response.status(), StatusCode::NOT_FOUND);
982        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
983    }
984
985    #[tokio::test]
986    async fn mounted_directory_rejects_artifacts_rebound_from_account_record() {
987        let (_directory, document, log, _record) = mounted_directory();
988
989        let mut altered_document = String::from_utf8(document).unwrap();
990        assert!(altered_document.contains("https://pds.example.com"));
991        altered_document =
992            altered_document.replace("https://pds.example.com", "https://other.example.com");
993        let document_directory = mounted_directory_with_files(
994            None,
995            Some(altered_document.into_bytes()),
996            Some(log.clone()),
997        )
998        .0;
999        document_directory
1000            .store
1001            .refresh_hosted_did_index(&document_directory.authority)
1002            .await
1003            .unwrap();
1004        assert!(document_directory.lookup("alice").await.is_err());
1005
1006        let mut altered_log = log;
1007        let last = altered_log.len() - 1;
1008        altered_log[last] ^= 1;
1009        let log_directory = mounted_directory_with_files(None, None, Some(altered_log)).0;
1010        log_directory
1011            .store
1012            .refresh_hosted_did_index(&log_directory.authority)
1013            .await
1014            .unwrap();
1015        assert!(log_directory.lookup("alice").await.is_err());
1016    }
1017
1018    #[tokio::test]
1019    async fn mounted_directory_rejects_document_key_rebound_from_account_record() {
1020        let (_original, document, log, record) = mounted_directory();
1021        let replacement = p256::ecdsa::SigningKey::random(&mut OsRng)
1022            .verifying_key()
1023            .to_encoded_point(true)
1024            .as_bytes()
1025            .to_vec();
1026        let mut record_value = DagCbor::decode(&record).unwrap();
1027        let fields = match &mut record_value {
1028            DagCbor::Map(fields) => fields,
1029            other => panic!("account record must be a map, got {other:?}"),
1030        };
1031        let mut replaced = false;
1032        for (key, value) in fields {
1033            if matches!(key, DagCbor::Text(name) if name == "atproto_key") {
1034                *value = DagCbor::Bytes(replacement.clone());
1035                replaced = true;
1036            }
1037        }
1038        assert!(replaced, "account record must contain atproto_key");
1039        let rebound =
1040            mounted_directory_with_files(Some(record_value.encode()), Some(document), Some(log)).0;
1041        rebound
1042            .store
1043            .refresh_hosted_did_index(&rebound.authority)
1044            .await
1045            .unwrap();
1046        let error = rebound
1047            .lookup("alice")
1048            .await
1049            .expect_err("document key rebound must be rejected");
1050        assert!(error.to_string().contains("#atproto key"));
1051    }
1052
1053    #[tokio::test]
1054    async fn mounted_directory_rejects_non_genesis_current_operation_on_every_route() {
1055        let (original, document, log, record) = mounted_directory();
1056        original
1057            .store
1058            .refresh_hosted_did_index(&original.authority)
1059            .await
1060            .unwrap();
1061        assert!(original.lookup("alice").await.unwrap().is_some());
1062
1063        // Change only current_op: host, document, key, and sealed genesis
1064        // remain valid and mutually consistent, so no other guard can mask
1065        // the unsupported current-operation pointer.
1066        let mut record_value = DagCbor::decode(&record).unwrap();
1067        let fields = match &mut record_value {
1068            DagCbor::Map(fields) => fields,
1069            other => panic!("account record must be a map, got {other:?}"),
1070        };
1071        let mut replaced = false;
1072        for (key, value) in fields {
1073            if matches!(key, DagCbor::Text(name) if name == "current_op") {
1074                *value = DagCbor::Link(Cid::from_dag_cbor(b"unvalidated-current-operation"));
1075                replaced = true;
1076            }
1077        }
1078        assert!(replaced, "account record must contain current_op");
1079        let invalid =
1080            mounted_directory_with_files(Some(record_value.encode()), Some(document), Some(log)).0;
1081        invalid
1082            .store
1083            .refresh_hosted_did_index(&invalid.authority)
1084            .await
1085            .unwrap();
1086        let error = invalid
1087            .lookup("alice")
1088            .await
1089            .expect_err("current op must be sealed genesis");
1090        assert!(error
1091            .to_string()
1092            .contains("current operation is not genesis"));
1093        let app = router(DEFAULT_ACCOUNT_ZONE, invalid).unwrap();
1094        for path in [
1095            "/.well-known/did.json",
1096            "/.well-known/atproto-did",
1097            "/.well-known/did-log.json",
1098        ] {
1099            let response = app
1100                .clone()
1101                .oneshot(
1102                    Request::builder()
1103                        .uri(path)
1104                        .header(header::HOST, "alice.tormentnexus.social")
1105                        .body(axum::body::Body::empty())
1106                        .unwrap(),
1107                )
1108                .await
1109                .unwrap();
1110            assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
1111            assert!(to_bytes(response.into_body(), 1024)
1112                .await
1113                .unwrap()
1114                .is_empty());
1115        }
1116    }
1117
1118    #[tokio::test]
1119    async fn mounted_directory_rejects_genesis_rebound_from_document() {
1120        let (_original, document, _log, record) = mounted_directory();
1121        let alternate_log = alternate_genesis_same_did();
1122        let alternate_cid = Cid::from_dag_cbor(&alternate_log);
1123        let mut record_value = DagCbor::decode(&record).unwrap();
1124        let fields = match &mut record_value {
1125            DagCbor::Map(fields) => fields,
1126            other => panic!("account record must be a map, got {other:?}"),
1127        };
1128        let mut replaced = false;
1129        for (key, value) in fields {
1130            if matches!(key, DagCbor::Text(name) if name == "genesis_op") {
1131                *value = DagCbor::Link(alternate_cid);
1132                replaced = true;
1133            }
1134        }
1135        assert!(replaced, "account record must contain genesis_op");
1136        let rebound_record = record_value.encode();
1137        let rebound =
1138            mounted_directory_with_files(Some(rebound_record), Some(document), Some(alternate_log))
1139                .0;
1140        rebound
1141            .store
1142            .refresh_hosted_did_index(&rebound.authority)
1143            .await
1144            .unwrap();
1145        let error = rebound
1146            .lookup("alice")
1147            .await
1148            .expect_err("genesis for another document must be rejected");
1149        assert!(error.to_string().contains("account document"));
1150    }
1151
1152    #[test]
1153    fn duplicate_labels_are_rejected() {
1154        let first = HostedAccountHttpArtifacts::new(
1155            "alice",
1156            "did:web:alice.tormentnexus.social",
1157            vec![1],
1158            b"did:web:alice.tormentnexus.social".to_vec(),
1159            vec![2],
1160        )
1161        .unwrap();
1162        let second = HostedAccountHttpArtifacts::new(
1163            "alice",
1164            "did:web:alice.tormentnexus.social",
1165            vec![3],
1166            b"did:web:alice.tormentnexus.social".to_vec(),
1167            vec![4],
1168        )
1169        .unwrap();
1170        assert!(StaticHostedAccountHttpDirectory::new([first, second]).is_err());
1171    }
1172}