Skip to main content

hyprstream_core/services/oauth/
identity_registration.rs

1//! Identity registration, federation-intake, and public resolution HTTP face.
2//!
3//! Registration has two distinct routes with the same handle-only body:
4//! browser-session self service and bearer-authenticated operator manual
5//! registration. The route, never a client field, selects the authority path.
6//!
7//! Federation intake is deliberately exposed only beside the authenticated
8//! self-service route. Its `did:web` arm checks an exact, deployment-owned
9//! HTTPS-origin allowlist before [`FederationIntake::intake`] can perform any
10//! resolver network I/O.
11
12use std::collections::BTreeSet;
13use std::fs::{File, OpenOptions};
14use std::io::{Read as _, Write as _};
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17use std::time::Duration;
18
19use anyhow::{ensure, Context as _, Result};
20use async_trait::async_trait;
21use axum::extract::{Extension, Query, Request, State};
22use axum::http::StatusCode;
23use axum::middleware::Next;
24use axum::response::{IntoResponse, Response};
25use axum::Json;
26use hyprstream_discovery::{
27    ConnectTimeDiscovery, InMemoryPlcDirectoryStore, LivePlcDiscovery, PlcDirectory,
28};
29use hyprstream_pds::{
30    sign_genesis, AccountRecord, AllocatedAccountName, DidOpSignature, DirectoryHostedAccountStore,
31    GenesisDidOp, GenesisRepoHead, GenesisRotationKeys, HostKeyEnrollment, HybridRotationKey,
32    RecoveryKeyEnrollment, SealedHostedDidDocument, UnsignedGenesisDidOp, UserRotationKey,
33};
34use hyprstream_pds_service::federation_intake::{
35    FederatedDidDocumentResolver, FederatedDidResolver, FederationIntake,
36    InMemoryIdentityInventory, InventoryEntry,
37};
38use hyprstream_pds_service::hosted_account_mint::{
39    AuthorityHostedAccountBinding, HostedAccountAuthority, HostedAccountGenesisSigner,
40    HostedAccountRegistrationRequest, HostedAccountRegistrationResult, HostedPdsAccountMinter,
41    HostedPdsAccountPublication, HostedPdsAccountPublisher, HostedPdsDiscovery,
42    LiveHostedPdsDiscovery,
43};
44use hyprstream_rpc::identity::UNAUTHENTICATED_DID_SENTINEL;
45use serde::{Deserialize, Serialize};
46use tracing::warn;
47use url::Url;
48use zeroize::Zeroize as _;
49
50use super::auth::AuthenticatedUser;
51use super::session;
52use super::state::OAuthState;
53use crate::account::{AccountZone, AccountZoneConfig};
54use crate::config::{OAuthConfig, QuicConfig};
55use crate::server::middleware::RateLimiter;
56
57const REGISTRATION_RATE_LIMIT_REQUESTS: u32 = 10;
58const REGISTRATION_RATE_LIMIT_WINDOW_SECS: i64 = 60;
59const PUBLIC_RESOLVE_RATE_LIMIT_BUCKET: &str = "identity-resolve-unauthenticated-floor";
60const COLD_SIGNUP_GLOBAL_RATE_LIMIT_BUCKET: &str = "oauth-authorize-signup-global-floor";
61const MAX_AUTHORITY_ARTIFACT_BYTES: u64 = 64 * 1024;
62const ACCOUNT_GENESIS_ED25519_PURPOSE: &str = "hyprstream-hosted-account-genesis-ed25519-v1";
63const ACCOUNT_GENESIS_MLDSA65_PURPOSE: &str = "hyprstream-hosted-account-genesis-mldsa65-v1";
64const SIGNUP_TRANSACTION_FILE: &str = "signup-transaction.json";
65/// Journal directory (under the PDS root) for durable enrollment intents
66/// (#698 Phase 2).
67pub(crate) const ENROLLMENT_JOURNAL_DIR: &str = "enrollment-intents";
68
69#[derive(Debug, Deserialize, Serialize)]
70struct HostedAccountReservation {
71    version: u8,
72    did: String,
73    #[serde(skip_serializing_if = "Option::is_none")]
74    transaction_id: Option<String>,
75}
76
77/// Assemble the production registration face installed by the OAuth factory.
78///
79/// The account zone may be unconfigured: the API remains installed so
80/// federation intake still works, while minting fails closed at the authority
81/// boundary with the account-zone configuration error.
82pub(crate) fn production_identity_registration_api(
83    oauth: &OAuthConfig,
84    account: &AccountZoneConfig,
85    quic: &QuicConfig,
86    oauth_signing_key: ed25519_dalek::SigningKey,
87    pds_root: PathBuf,
88) -> Result<Arc<IdentityRegistrationApi>> {
89    let ttl = Duration::from_secs(oauth.atproto_did_cache_ttl_secs);
90    let plc_config = hyprstream_rpc::did_plc::PlcResolverConfig::new(
91        Url::parse(&oauth.atproto_plc_directory_url)
92            .context("identity intake PLC directory URL is invalid")?,
93        ttl,
94    )
95    .context("identity intake PLC resolver configuration is invalid")?;
96    let plc = Arc::new(
97        hyprstream_rpc::did_plc::DidPlcResolver::new(plc_config)
98            .context("identity intake PLC resolver construction failed")?,
99    );
100    let web = Arc::new(hyprstream_rpc::did_web::DidWebResolver::new(
101        hyprstream_rpc::did_web::HttpDidDocFetcher::new(ttl)
102            .context("identity intake did:web HTTPS client construction failed")?,
103    ));
104    let resolver: Arc<dyn FederatedDidDocumentResolver> =
105        Arc::new(FederatedDidResolver::new(plc, web));
106    let live_discovery = Arc::new(ConfiguredHostedPdsDiscovery {
107        pds_endpoint: oauth.issuer_url(),
108        quic: quic.clone(),
109    });
110    let directory = PlcDirectory::new(
111        Arc::new(InMemoryPlcDirectoryStore::default()),
112        live_discovery.clone(),
113        hyprstream_discovery::deployment_registry_verifier()
114            .context("identity PLC directory authority is not installed")?,
115    );
116    let identity_resolver = Arc::new(AuthorityConnectTimeResolver {
117        plc: directory,
118        hosted: account
119            .resolve_zone()
120            .ok()
121            .map(|zone| HostedConnectTimeResolver {
122                pds_root: pds_root.clone(),
123                zone,
124                live_discovery,
125            }),
126    });
127    compose_identity_registration_api(
128        oauth,
129        account,
130        quic,
131        oauth_signing_key,
132        pds_root,
133        resolver,
134        identity_resolver,
135    )
136}
137
138pub(super) fn compose_identity_registration_api(
139    oauth: &OAuthConfig,
140    account: &AccountZoneConfig,
141    quic: &QuicConfig,
142    oauth_signing_key: ed25519_dalek::SigningKey,
143    pds_root: PathBuf,
144    resolver: Arc<dyn FederatedDidDocumentResolver>,
145    identity_resolver: Arc<dyn IdentityConnectTimeResolver>,
146) -> Result<Arc<IdentityRegistrationApi>> {
147    let authority = Arc::new(ProductionHostedAccountAuthority {
148        account: account.clone(),
149        pds_root: pds_root.clone(),
150        signing_root: oauth_signing_key.clone(),
151    });
152    let discovery = Arc::new(ConfiguredHostedPdsDiscovery {
153        pds_endpoint: oauth.issuer_url(),
154        quic: quic.clone(),
155    });
156    let publisher = Arc::new(ProductionHostedAccountPublisher { pds_root });
157    let minter = Arc::new(HostedPdsAccountMinter::new(authority, discovery, publisher));
158    let signer = Arc::new(ProductionRegistrationGenesisSigner {
159        signing_root: oauth_signing_key,
160    });
161    let intake = Arc::new(FederationIntake::new(
162        resolver,
163        Arc::new(InMemoryIdentityInventory::default()),
164        vec![oauth.issuer_url()],
165    ));
166    let allowlist = DidWebOriginAllowlist::new(&oauth.identity_registration_did_web_origins)
167        .context("identity registration did:web origin allowlist is invalid")?;
168    Ok(Arc::new(IdentityRegistrationApi::new(
169        minter,
170        signer,
171        intake,
172        identity_resolver,
173        allowlist,
174        Arc::new(RateLimiter::new(
175            REGISTRATION_RATE_LIMIT_REQUESTS,
176            REGISTRATION_RATE_LIMIT_WINDOW_SECS,
177        )),
178    )))
179}
180
181struct ProductionHostedAccountAuthority {
182    account: AccountZoneConfig,
183    pds_root: PathBuf,
184    signing_root: ed25519_dalek::SigningKey,
185}
186
187impl ProductionHostedAccountAuthority {
188    fn allocate_inner(
189        &self,
190        requested_handle: &str,
191        transaction_id: Option<&str>,
192    ) -> Result<AuthorityHostedAccountBinding> {
193        let zone = self
194            .account
195            .resolve_zone()
196            .context("hosted-account minting is not configured")?;
197        let host = zone.host_for_label(requested_handle)?;
198        let name = AllocatedAccountName::new(requested_handle, format!("did:web:{host}"))?;
199        let tenant = zone.apex().to_owned();
200
201        // Allocation is a permanent, authority-owned reservation. OAuth
202        // signup binds it to the already-committed AS credential transaction,
203        // allowing only that exact verified pair to resume.
204        let reservation_dir = self.pds_root.join(&tenant).join(".allocated");
205        create_private_dir_all(&reservation_dir)?;
206        let reservation = reservation_dir.join(requested_handle);
207        let reservation_value = HostedAccountReservation {
208            version: 1,
209            did: name.did().to_owned(),
210            transaction_id: transaction_id.map(str::to_owned),
211        };
212        let mut staged_reservation = tempfile::Builder::new()
213            .prefix(".allocation-")
214            .tempfile_in(&reservation_dir)?;
215        #[cfg(unix)]
216        {
217            use std::os::unix::fs::PermissionsExt as _;
218            std::fs::set_permissions(
219                staged_reservation.path(),
220                std::fs::Permissions::from_mode(0o600),
221            )?;
222        }
223        serde_json::to_writer(staged_reservation.as_file_mut(), &reservation_value)?;
224        staged_reservation.as_file_mut().write_all(b"\n")?;
225        staged_reservation.as_file_mut().sync_all()?;
226        #[cfg(all(target_os = "linux", target_env = "gnu"))]
227        match nix::fcntl::renameat2(
228            None,
229            staged_reservation.path(),
230            None,
231            &reservation,
232            nix::fcntl::RenameFlags::RENAME_NOREPLACE,
233        ) {
234            Ok(()) => {
235                sync_directory(&reservation_dir)?;
236                sync_directory(
237                    reservation_dir
238                        .parent()
239                        .context("hosted-account reservation directory has no tenant parent")?,
240                )?;
241            }
242            Err(nix::errno::Errno::EEXIST) => {
243                let existing: HostedAccountReservation = serde_json::from_slice(
244                    &read_authority_artifact(&reservation)
245                        .context("reading hosted-account reservation")?,
246                )
247                .context("verifying hosted-account reservation")?;
248                ensure!(
249                    existing.version == 1
250                        && existing.did == name.did()
251                        && transaction_id.is_some()
252                        && existing.transaction_id.as_deref() == transaction_id,
253                    std::io::Error::new(
254                        std::io::ErrorKind::AlreadyExists,
255                        format!("hosted-account label {requested_handle:?} is unavailable"),
256                    )
257                );
258                sync_directory(&reservation_dir)?;
259                sync_directory(
260                    reservation_dir
261                        .parent()
262                        .context("hosted-account reservation directory has no tenant parent")?,
263                )?;
264            }
265            Err(error) => return Err(error.into()),
266        }
267        #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
268        anyhow::bail!("atomic hosted-account allocation requires Linux renameat2");
269
270        AuthorityHostedAccountBinding::new(
271            tenant,
272            name,
273            account_genesis_rotation_keys(&self.signing_root, requested_handle)?,
274        )
275    }
276}
277
278impl HostedAccountAuthority for ProductionHostedAccountAuthority {
279    fn allocate(&self, requested_handle: &str) -> Result<AuthorityHostedAccountBinding> {
280        self.allocate_inner(requested_handle, None)
281    }
282
283    fn allocate_for_transaction(
284        &self,
285        requested_handle: &str,
286        transaction_id: &str,
287    ) -> Result<AuthorityHostedAccountBinding> {
288        ensure!(
289            !transaction_id.is_empty(),
290            "hosted-account reservation transaction id is empty"
291        );
292        self.allocate_inner(requested_handle, Some(transaction_id))
293    }
294}
295
296struct ProductionRegistrationGenesisSigner {
297    signing_root: ed25519_dalek::SigningKey,
298}
299
300impl RegistrationGenesisSigner for ProductionRegistrationGenesisSigner {
301    fn sign_genesis(
302        &self,
303        caller: &str,
304        operator_manual: bool,
305        unsigned: &UnsignedGenesisDidOp,
306    ) -> Result<DidOpSignature> {
307        ensure!(
308            !caller.is_empty() && caller != UNAUTHENTICATED_DID_SENTINEL,
309            "genesis signing requires an authenticated caller"
310        );
311        ensure!(
312            !operator_manual || caller.starts_with("service:"),
313            "manual genesis signing requires a service authority"
314        );
315        let label = hosted_account_label(unsigned.did())?;
316        let (ed, pq) = account_genesis_signing_keys(&self.signing_root, label);
317        sign_genesis(unsigned, &ed, &pq)
318    }
319}
320
321fn account_genesis_signing_keys(
322    root: &ed25519_dalek::SigningKey,
323    label: &str,
324) -> (
325    ed25519_dalek::SigningKey,
326    hyprstream_crypto::pq::MlDsaSigningKey,
327) {
328    let ed = hyprstream_rpc::node_identity::derive_purpose_key(
329        root,
330        &format!("{ACCOUNT_GENESIS_ED25519_PURPOSE}/{label}"),
331    );
332    let pq_seed_key = hyprstream_rpc::node_identity::derive_purpose_key(
333        root,
334        &format!("{ACCOUNT_GENESIS_MLDSA65_PURPOSE}/{label}"),
335    );
336    let mut pq_seed = pq_seed_key.to_bytes();
337    let pq = hyprstream_crypto::pq::ml_dsa_sk_from_seed(&pq_seed);
338    pq_seed.zeroize();
339    (ed, pq)
340}
341
342fn account_genesis_rotation_keys(
343    root: &ed25519_dalek::SigningKey,
344    label: &str,
345) -> Result<GenesisRotationKeys> {
346    let (ed, pq) = account_genesis_signing_keys(root, label);
347    let hybrid = HybridRotationKey::new(
348        ed.verifying_key().to_bytes(),
349        hyprstream_crypto::pq::ml_dsa_sk_to_vk_bytes(&pq),
350    )?;
351    GenesisRotationKeys::new(
352        UserRotationKey::new(hybrid),
353        RecoveryKeyEnrollment::Declined,
354        HostKeyEnrollment::Absent,
355    )
356}
357
358fn hosted_account_label(did: &str) -> Result<&str> {
359    let host = did
360        .strip_prefix("did:web:")
361        .context("hosted-account genesis DID must use did:web")?;
362    let label = host
363        .split('.')
364        .next()
365        .context("hosted-account genesis DID has no account label")?;
366    ensure!(
367        !label.is_empty() && !label.contains([':', '/', '%']),
368        "hosted-account genesis DID has an invalid account label"
369    );
370    Ok(label)
371}
372
373struct ConfiguredHostedPdsDiscovery {
374    pds_endpoint: String,
375    quic: QuicConfig,
376}
377
378impl HostedPdsDiscovery for ConfiguredHostedPdsDiscovery {
379    fn current(&self) -> Result<LiveHostedPdsDiscovery> {
380        ensure!(
381            self.quic.enabled,
382            "hosted-account minting requires live QUIC"
383        );
384        let endpoint = Url::parse(&self.pds_endpoint).context("hosted PDS endpoint is invalid")?;
385        ensure!(
386            endpoint.scheme() == "https",
387            "hosted PDS endpoint must use HTTPS"
388        );
389        let pds_endpoint = endpoint.origin().ascii_serialization();
390        let host = endpoint
391            .host_str()
392            .context("hosted PDS endpoint has no host")?;
393        let port = self.quic.socket_addr()?.port();
394        let quic_url = format!("https://{host}:{port}");
395        let (cert_chain, _) = self.quic.load_tls_materials()?;
396        let leaf = cert_chain
397            .first()
398            .context("hosted PDS QUIC certificate chain is empty")?;
399        let digest = ring::digest::digest(&ring::digest::SHA256, leaf);
400        let mut cert_hash = [0_u8; 32];
401        cert_hash.copy_from_slice(digest.as_ref());
402        let auth = hyprstream_rpc::transport::QuicServerAuth::pinned(vec![cert_hash])?;
403        let entry = serde_json::json!({
404            "id": format!("{pds_endpoint}#quic"),
405            "type": "QuicTransport",
406            "serviceEndpoint": hyprstream_rpc::service_entry::encode_quic(
407                &quic_url,
408                &auth,
409                &["hyprstream-rpc/1"],
410            ),
411        });
412        Ok(LiveHostedPdsDiscovery {
413            pds_endpoint,
414            browser_quic_reach: hyprstream_rpc::service_entry::decode_browser_quic_reach(&entry)?,
415        })
416    }
417}
418
419impl LivePlcDiscovery for ConfiguredHostedPdsDiscovery {
420    fn current(
421        &self,
422        _did: &str,
423        pds_endpoint: &str,
424    ) -> Result<hyprstream_rpc::service_entry::BrowserQuicReach> {
425        let current = <Self as HostedPdsDiscovery>::current(self)?;
426        let bound_endpoint = Url::parse(pds_endpoint)
427            .context("PLC directory PDS endpoint is invalid")?
428            .origin()
429            .ascii_serialization();
430        ensure!(
431            current.pds_endpoint == bound_endpoint,
432            "PLC directory identity is not bound to this hosted PDS"
433        );
434        Ok(current.browser_quic_reach)
435    }
436}
437
438struct HostedConnectTimeResolver {
439    pds_root: PathBuf,
440    zone: AccountZone,
441    live_discovery: Arc<ConfiguredHostedPdsDiscovery>,
442}
443
444impl HostedConnectTimeResolver {
445    fn local_label<'a>(&self, did: &'a str) -> Option<&'a str> {
446        let host = did.strip_prefix("did:web:")?;
447        let suffix = format!(".{}", self.zone.apex());
448        let label = host.strip_suffix(&suffix)?;
449        let name = AllocatedAccountName::new(label, did).ok()?;
450        (self.zone.host_for_label(name.label()).ok()?.as_str() == host).then_some(label)
451    }
452
453    fn resolve(&self, did: &str) -> Result<ConnectTimeDiscovery> {
454        let label = self
455            .local_label(did)
456            .context("DID is not a local hosted account")?;
457        let account_dir = self
458            .pds_root
459            .join(self.zone.apex())
460            .join("accounts")
461            .join(label);
462        let record = AccountRecord::from_dag_cbor(
463            &read_authority_artifact(&account_dir.join("account-record.cbor"))
464                .context("reading hosted account record")?,
465        )
466        .context("verifying hosted account record")?;
467        let genesis = GenesisDidOp::from_dag_cbor(
468            &read_authority_artifact(&account_dir.join("genesis.didop.cbor"))
469                .context("reading hosted account genesis")?,
470        )
471        .context("verifying hosted account genesis")?;
472        let document = SealedHostedDidDocument::from_canonical_json(
473            &read_authority_artifact(&account_dir.join("did-document.json"))
474                .context("reading hosted account DID document")?,
475        )
476        .context("verifying hosted account DID document")?;
477        ensure!(
478            record.name().label() == label
479                && record.name().did() == did
480                && document.did() == did
481                && record.genesis_op() == genesis.cid()?
482                && record.current_op() == record.genesis_op()
483                && record.doc_cid() == genesis.unsigned().doc_cid()
484                && record.doc_cid() == document.cid()
485                && record.atproto_verifying_key()?.to_encoded_point(true)
486                    == document.atproto_verifying_key()?.to_encoded_point(true),
487            "hosted account authority artifacts are inconsistent"
488        );
489        let reach = <ConfiguredHostedPdsDiscovery as LivePlcDiscovery>::current(
490            self.live_discovery.as_ref(),
491            did,
492            document.pds_endpoint(),
493        )?;
494        serde_json::from_value(serde_json::json!({
495            "quicUrl": reach.quic_url,
496            "certHash": reach.cert_hash,
497        }))
498        .context("encoding hosted connect-time discovery")
499    }
500}
501
502impl IdentityConnectTimeResolver for HostedConnectTimeResolver {
503    fn recognizes(&self, did: &str) -> bool {
504        self.local_label(did).is_some()
505    }
506
507    fn resolve(&self, did: &str) -> Result<ConnectTimeDiscovery> {
508        HostedConnectTimeResolver::resolve(self, did)
509    }
510
511    fn hosted_tenant(&self, did: &str) -> Result<Option<String>> {
512        // Verify the authority artifacts before returning the deployment-owned
513        // tenant. Classification by DID suffix alone is not sufficient.
514        HostedConnectTimeResolver::resolve(self, did)?;
515        Ok(Some(self.zone.apex().to_owned()))
516    }
517}
518
519fn read_authority_artifact(path: &Path) -> Result<Vec<u8>> {
520    let mut limited = File::open(path)?.take(MAX_AUTHORITY_ARTIFACT_BYTES + 1);
521    let mut bytes = Vec::new();
522    limited.read_to_end(&mut bytes)?;
523    ensure!(
524        bytes.len() <= MAX_AUTHORITY_ARTIFACT_BYTES as usize,
525        "authority artifact exceeds the {MAX_AUTHORITY_ARTIFACT_BYTES}-byte read limit"
526    );
527    Ok(bytes)
528}
529
530struct AuthorityConnectTimeResolver {
531    plc: PlcDirectory,
532    hosted: Option<HostedConnectTimeResolver>,
533}
534
535impl IdentityConnectTimeResolver for AuthorityConnectTimeResolver {
536    fn recognizes(&self, did: &str) -> bool {
537        hyprstream_rpc::did_plc::is_did_plc(did)
538            || self
539                .hosted
540                .as_ref()
541                .and_then(|resolver| resolver.local_label(did))
542                .is_some()
543    }
544
545    fn resolve(&self, did: &str) -> Result<ConnectTimeDiscovery> {
546        if hyprstream_rpc::did_plc::is_did_plc(did) {
547            return self.plc.resolve(did);
548        }
549        self.hosted
550            .as_ref()
551            .context("hosted account resolution is not configured")?
552            .resolve(did)
553    }
554
555    fn hosted_tenant(&self, did: &str) -> Result<Option<String>> {
556        if hyprstream_rpc::did_plc::is_did_plc(did) {
557            return Ok(None);
558        }
559        match &self.hosted {
560            Some(hosted) => hosted.hosted_tenant(did),
561            None => Ok(None),
562        }
563    }
564}
565
566struct ProductionHostedAccountPublisher {
567    pds_root: PathBuf,
568}
569
570impl HostedPdsAccountPublisher for ProductionHostedAccountPublisher {
571    fn publish(&self, publication: HostedPdsAccountPublication<'_>) -> Result<()> {
572        let tenant_root = self.pds_root.join(publication.tenant());
573        let accounts_root = tenant_root.join("accounts");
574        create_private_dir_all(&accounts_root)?;
575        sync_directory(&tenant_root)?;
576        let staging = tempfile::Builder::new()
577            .prefix(".account-mint-")
578            .tempdir_in(&tenant_root)?;
579        let staging_store = DirectoryHostedAccountStore::new(staging.path());
580        publication.account().write_to(&staging_store)?;
581        let staged_account = staging.path().join(publication.label());
582        write_repo_genesis(&staged_account, publication.repo())?;
583        if let Some(transaction_id) = publication.transaction_id() {
584            let transaction = serde_json::to_vec(&serde_json::json!({
585                "version": 1,
586                "transaction_id": transaction_id,
587            }))?;
588            write_private_file(&staged_account.join(SIGNUP_TRANSACTION_FILE), &transaction)?;
589            sync_directory(&staged_account)?;
590        }
591
592        let final_account = accounts_root.join(publication.label());
593        #[cfg(all(target_os = "linux", target_env = "gnu"))]
594        match nix::fcntl::renameat2(
595            None,
596            &staged_account,
597            None,
598            &final_account,
599            nix::fcntl::RenameFlags::RENAME_NOREPLACE,
600        ) {
601            Ok(()) => {}
602            Err(nix::errno::Errno::EEXIST) if publication.transaction_id().is_some() => {
603                verify_resumable_signup_publication(&final_account, &publication)?;
604                sync_directory(&accounts_root)?;
605                self.append_enrollment_intent(&publication)?;
606                return Ok(());
607            }
608            Err(error) => {
609                return Err(error).with_context(|| {
610                    format!(
611                        "failed to atomically publish hosted account {:?}",
612                        publication.label()
613                    )
614                });
615            }
616        }
617        #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
618        anyhow::bail!("atomic hosted-account publication requires Linux renameat2");
619        sync_directory(&accounts_root)?;
620        self.append_enrollment_intent(&publication)
621    }
622}
623
624impl ProductionHostedAccountPublisher {
625    /// #698 Phase 2: once the account is durable (atomic rename + directory
626    /// fsync above), append the enrollment intents to the journal. A journal
627    /// failure fails the mint but never rolls the account back: signup mints
628    /// are transaction-idempotent, so a retry resumes the exact verified
629    /// publication and re-appends (replay is a no-op once committed).
630    /// Both the hosted DID and the local username are journaled: the atproto
631    /// token profile carries `sub=<did>` while native Bearer-only clients
632    /// carry `sub=<username>`, and the clearance table matches by exact
633    /// subject. Keyless operator mints get a journal-internal sequence; a
634    /// keyless retry of an already-journaled subject fails closed as a
635    /// conflict.
636    fn append_enrollment_intent(
637        &self,
638        publication: &HostedPdsAccountPublication<'_>,
639    ) -> Result<()> {
640        use crate::mac::enrollment_journal as journal;
641        let did = publication.account().record().name().did();
642        // The hosted DID is `did:web:{label}.{zone}` and the credential
643        // store stages the account under the label as its local username,
644        // so the label is the exact `sub` non-atproto tokens carry.
645        let username = publication.label();
646        let provision_epoch = std::time::SystemTime::now()
647            .duration_since(std::time::UNIX_EPOCH)
648            .map(|d| d.as_secs())
649            .unwrap_or(0);
650        let intents = journal::hosted_signup_intents(
651            did,
652            username,
653            publication.transaction_id(),
654            provision_epoch,
655        );
656        // Prefer the process-global dir when startup wiring installed one so
657        // hosted and JIT intents share a single journal (review F4);
658        // otherwise fall back to the pinned default under the PDS root.
659        let dir = journal::global_journal_dir()
660            .map(Path::to_path_buf)
661            .unwrap_or_else(|| self.pds_root.join(ENROLLMENT_JOURNAL_DIR));
662        for intent in intents {
663            let outcome = journal::record_intent(&dir, intent)
664                .context("recording durable enrollment intent for published hosted account")?;
665            if let journal::AppendOutcome::Conflict { seq } = outcome {
666                tracing::error!(
667                    did,
668                    seq,
669                    "enrollment-intent journal recorded a conflict — operator reconciliation required"
670                );
671            }
672        }
673        Ok(())
674    }
675}
676
677fn verify_resumable_signup_publication(
678    account_dir: &Path,
679    expected: &HostedPdsAccountPublication<'_>,
680) -> Result<()> {
681    let transaction: serde_json::Value = serde_json::from_slice(
682        &read_authority_artifact(&account_dir.join(SIGNUP_TRANSACTION_FILE))
683            .context("reading hosted signup transaction marker")?,
684    )
685    .context("verifying hosted signup transaction marker")?;
686    ensure!(
687        transaction
688            .get("version")
689            .and_then(serde_json::Value::as_u64)
690            == Some(1)
691            && transaction
692                .get("transaction_id")
693                .and_then(serde_json::Value::as_str)
694                == expected.transaction_id(),
695        "published hosted account belongs to a different signup transaction"
696    );
697
698    let record_bytes = read_authority_artifact(&account_dir.join("account-record.cbor"))
699        .context("reading published hosted account record")?;
700    let record =
701        AccountRecord::from_dag_cbor(&record_bytes).context("verifying hosted account record")?;
702    let genesis = GenesisDidOp::from_dag_cbor(
703        &read_authority_artifact(&account_dir.join("genesis.didop.cbor"))
704            .context("reading published hosted account genesis")?,
705    )
706    .context("verifying hosted account genesis")?;
707    let document = SealedHostedDidDocument::from_canonical_json(
708        &read_authority_artifact(&account_dir.join("did-document.json"))
709            .context("reading published hosted account DID document")?,
710    )
711    .context("verifying hosted account DID document")?;
712    let expected_name = expected.account().record().name();
713    ensure!(
714        record.name() == expected_name
715            && document.did() == expected_name.did()
716            && document.handle() == expected.account().did_document().handle()
717            && document.pds_endpoint() == expected.account().did_document().pds_endpoint()
718            && record.genesis_op() == genesis.cid()?
719            && record.current_op() == record.genesis_op()
720            && record.doc_cid() == genesis.unsigned().doc_cid()
721            && record.doc_cid() == document.cid()
722            && record.atproto_verifying_key()?.to_encoded_point(true)
723                == document.atproto_verifying_key()?.to_encoded_point(true),
724        "published hosted signup authority artifacts are inconsistent"
725    );
726
727    let commit_bytes = read_authority_artifact(&account_dir.join("repo/commit.cbor"))
728        .context("reading published hosted repo commit")?;
729    let commit = hyprstream_pds::commit::Commit::from_dag_cbor(&commit_bytes)
730        .context("verifying published hosted repo commit")?;
731    commit
732        .verify(&record.atproto_verifying_key()?)
733        .context("published hosted repo signature is invalid")?;
734    let commit_cid = commit.cid();
735    ensure!(
736        commit.did == expected_name.did()
737            && commit.prev.is_none()
738            && genesis.unsigned().head_at_op() == GenesisRepoHead::Existing(commit_cid)
739            && read_authority_artifact(
740                &account_dir.join(format!("repo/blocks/{}.cbor", commit.data))
741            )
742            .is_ok_and(|bytes| hyprstream_pds::Cid::from_dag_cbor(&bytes) == commit.data)
743            && std::fs::read_to_string(account_dir.join("repo/head"))
744                .is_ok_and(|head| head == commit_cid.to_string()),
745        "published hosted signup repo genesis is incomplete or inconsistent"
746    );
747    // Native-only publications predate the public sidecar. Resume the exact
748    // already-verified transaction and identity; XRPC derives its public form
749    // later through the original account custody. Never sign with the fresh
750    // retry candidate's key, or treat a present invalid artifact as absent.
751    let public_path = account_dir.join("repo/public-commit.cbor");
752    match std::fs::symlink_metadata(&public_path) {
753        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
754        Err(error) => return Err(error).context("checking published hosted public repo genesis"),
755        Ok(metadata) => ensure!(
756            metadata.file_type().is_file(),
757            "public repo genesis is not a regular file"
758        ),
759    }
760    let public_commit_bytes = read_authority_artifact(&public_path)
761        .context("reading published hosted public repo genesis")?;
762    let public_commit = hyprstream_pds::commit::Commit::from_atproto_dag_cbor(&public_commit_bytes)
763        .context("verifying published hosted public repo genesis")?;
764    public_commit
765        .verify_atproto(&record.atproto_verifying_key()?)
766        .context("published hosted public repo signature is invalid")?;
767    ensure!(
768        public_commit.did == expected_name.did()
769            && public_commit.data == commit.data
770            && public_commit.rev == commit.rev
771            && public_commit.prev.is_none(),
772        "published hosted public repo genesis does not match native genesis state"
773    );
774    Ok(())
775}
776
777fn write_repo_genesis(account_dir: &Path, repo: &hyprstream_pds::HostedRepoGenesis) -> Result<()> {
778    let repo_dir = account_dir.join("repo");
779    let blocks_dir = repo_dir.join("blocks");
780    create_private_dir_all(&blocks_dir)?;
781    for (cid, bytes) in repo.mst_blocks() {
782        write_private_file(&blocks_dir.join(format!("{cid}.cbor")), bytes)?;
783    }
784    write_private_file(&repo_dir.join("commit.cbor"), repo.commit_bytes())?;
785    write_private_file(
786        &repo_dir.join("public-commit.cbor"),
787        repo.public_commit_bytes(),
788    )?;
789    write_private_file(
790        &repo_dir.join("head"),
791        repo.commit_cid().to_string().as_bytes(),
792    )?;
793    sync_directory(&blocks_dir)?;
794    sync_directory(&repo_dir)?;
795    sync_directory(account_dir)
796}
797
798fn create_private_dir_all(path: &Path) -> Result<()> {
799    std::fs::create_dir_all(path)?;
800    #[cfg(unix)]
801    {
802        use std::os::unix::fs::PermissionsExt as _;
803        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))?;
804    }
805    Ok(())
806}
807
808fn private_create_new(path: &Path) -> std::io::Result<File> {
809    let mut options = OpenOptions::new();
810    options.write(true).create_new(true);
811    #[cfg(unix)]
812    {
813        use std::os::unix::fs::OpenOptionsExt as _;
814        options.mode(0o600);
815    }
816    options.open(path)
817}
818
819fn write_private_file(path: &Path, bytes: &[u8]) -> Result<()> {
820    let mut file = private_create_new(path)?;
821    file.write_all(bytes)?;
822    file.sync_all()?;
823    Ok(())
824}
825
826fn sync_directory(path: &Path) -> Result<()> {
827    File::open(path)?.sync_all()?;
828    Ok(())
829}
830
831/// Handle-only registration payload.
832///
833/// `deny_unknown_fields` makes `tenant`, `did`, mode, and transport metadata
834/// invalid at the JSON boundary instead of silently ignoring them.
835#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
836#[serde(deny_unknown_fields)]
837pub struct RegisterHostedAccountRequest {
838    pub handle: String,
839}
840
841/// Browser registration result.
842#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
843#[serde(rename_all = "camelCase")]
844pub struct RegisterHostedAccountResponse {
845    pub handle: String,
846    pub did: String,
847    pub pds_endpoint: String,
848    pub quic_url: String,
849    pub cert_hash: String,
850}
851
852impl From<HostedAccountRegistrationResult> for RegisterHostedAccountResponse {
853    fn from(result: HostedAccountRegistrationResult) -> Self {
854        Self {
855            handle: result.handle,
856            did: result.did,
857            pds_endpoint: result.pds_endpoint,
858            quic_url: result.quic_url,
859            cert_hash: result.cert_hash,
860        }
861    }
862}
863
864/// Federation-add payload.
865#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
866#[serde(rename_all = "camelCase", deny_unknown_fields)]
867pub struct FederationIntakeRequest {
868    pub did: String,
869}
870
871/// Public connect-time resolution query.
872#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
873#[serde(deny_unknown_fields)]
874pub struct ResolveIdentityQuery {
875    pub did: String,
876}
877
878#[derive(Clone, Copy, Debug, PartialEq, Eq)]
879enum RegistrationPath {
880    SelfService,
881    OperatorManual,
882}
883
884/// An identity created only after the corresponding HTTP authenticator passes.
885#[derive(Clone, Debug)]
886pub(crate) struct AuthenticatedIdentityCaller {
887    subject: String,
888}
889
890impl AuthenticatedIdentityCaller {
891    fn new(subject: impl Into<String>) -> Result<Self, IdentityApiError> {
892        let subject = subject.into();
893        if subject.is_empty() || subject == UNAUTHENTICATED_DID_SENTINEL {
894            return Err(IdentityApiError::Unauthenticated);
895        }
896        Ok(Self { subject })
897    }
898
899    fn subject(&self) -> &str {
900        &self.subject
901    }
902}
903
904/// Select and use the hybrid genesis signer for one authenticated request.
905///
906/// Implementations may map self-service callers to user-held key material and
907/// operator-manual callers to the deployment-authority workflow. The client
908/// cannot select this path in its JSON body.
909pub trait RegistrationGenesisSigner: Send + Sync {
910    fn sign_genesis(
911        &self,
912        caller: &str,
913        operator_manual: bool,
914        unsigned: &UnsignedGenesisDidOp,
915    ) -> Result<DidOpSignature>;
916}
917
918/// Injectable mint boundary used by the HTTP adapter and causal tests.
919pub trait HostedRegistrationMint: Send + Sync {
920    fn mint(
921        &self,
922        request: &HostedAccountRegistrationRequest,
923        signer: &dyn HostedAccountGenesisSigner,
924    ) -> Result<HostedAccountRegistrationResult>;
925
926    fn mint_for_transaction(
927        &self,
928        request: &HostedAccountRegistrationRequest,
929        signer: &dyn HostedAccountGenesisSigner,
930        _transaction_id: &str,
931    ) -> Result<HostedAccountRegistrationResult> {
932        self.mint(request, signer)
933    }
934}
935
936impl HostedRegistrationMint for HostedPdsAccountMinter {
937    fn mint(
938        &self,
939        request: &HostedAccountRegistrationRequest,
940        signer: &dyn HostedAccountGenesisSigner,
941    ) -> Result<HostedAccountRegistrationResult> {
942        HostedPdsAccountMinter::mint(self, request, signer)
943    }
944
945    fn mint_for_transaction(
946        &self,
947        request: &HostedAccountRegistrationRequest,
948        signer: &dyn HostedAccountGenesisSigner,
949        transaction_id: &str,
950    ) -> Result<HostedAccountRegistrationResult> {
951        HostedPdsAccountMinter::mint_for_transaction(self, request, signer, transaction_id)
952    }
953}
954
955/// Injectable federation-intake boundary.
956#[async_trait]
957pub trait FederatedIdentityIntake: Send + Sync {
958    async fn intake(&self, did: &str) -> Result<InventoryEntry>;
959}
960
961#[async_trait]
962impl FederatedIdentityIntake for FederationIntake {
963    async fn intake(&self, did: &str) -> Result<InventoryEntry> {
964        FederationIntake::intake(self, did).await
965    }
966}
967
968/// Injectable connect-time boundary over authority-known local identities.
969pub trait IdentityConnectTimeResolver: Send + Sync {
970    /// Pure classification that must not perform resolver or network I/O.
971    fn recognizes(&self, did: &str) -> bool;
972
973    fn resolve(&self, did: &str) -> Result<ConnectTimeDiscovery>;
974
975    /// Return the deployment-authority tenant for a verified local hosted DID.
976    ///
977    /// Federation resolvers and test fakes default to no local binding.
978    fn hosted_tenant(&self, _did: &str) -> Result<Option<String>> {
979        Ok(None)
980    }
981}
982
983/// Exact HTTPS origins that may be resolved through the `did:web` intake arm.
984///
985/// Wildcards and suffix matching are intentionally unsupported. An empty set
986/// means `did:web` intake is disabled, while fixed-directory `did:plc` intake
987/// remains available.
988#[derive(Clone, Debug)]
989pub struct DidWebOriginAllowlist {
990    origins: BTreeSet<String>,
991}
992
993impl DidWebOriginAllowlist {
994    pub fn new<I, S>(origins: I) -> Result<Self>
995    where
996        I: IntoIterator<Item = S>,
997        S: AsRef<str>,
998    {
999        let mut normalized = BTreeSet::new();
1000        for origin in origins {
1001            let origin = origin.as_ref();
1002            let parsed = Url::parse(origin)?;
1003            ensure!(
1004                parsed.scheme() == "https"
1005                    && parsed.host_str().is_some_and(|host| !host.contains('*'))
1006                    && parsed.username().is_empty()
1007                    && parsed.password().is_none()
1008                    && parsed.path() == "/"
1009                    && parsed.query().is_none()
1010                    && parsed.fragment().is_none(),
1011                "did:web allowlist entries must be exact HTTPS origins"
1012            );
1013            normalized.insert(parsed.origin().ascii_serialization());
1014        }
1015        Ok(Self {
1016            origins: normalized,
1017        })
1018    }
1019
1020    fn require_allowed(&self, did: &str) -> Result<(), IdentityApiError> {
1021        let document_url = hyprstream_rpc::did_web::did_web_to_url(did)
1022            .map_err(|_| IdentityApiError::InvalidRequest)?;
1023        let parsed = Url::parse(&document_url).map_err(|_| IdentityApiError::InvalidRequest)?;
1024        let origin = parsed.origin().ascii_serialization();
1025        if !self.origins.contains(&origin) {
1026            return Err(IdentityApiError::ResolvableHostDenied);
1027        }
1028        Ok(())
1029    }
1030}
1031
1032/// Rate-limited wire adapter over hosted mint, intake, and public local resolution.
1033pub struct IdentityRegistrationApi {
1034    minter: Arc<dyn HostedRegistrationMint>,
1035    signer: Arc<dyn RegistrationGenesisSigner>,
1036    intake: Arc<dyn FederatedIdentityIntake>,
1037    identity_resolver: Arc<dyn IdentityConnectTimeResolver>,
1038    did_web_origins: DidWebOriginAllowlist,
1039    rate_limiter: Arc<RateLimiter>,
1040}
1041
1042impl IdentityRegistrationApi {
1043    #[must_use]
1044    pub fn new(
1045        minter: Arc<dyn HostedRegistrationMint>,
1046        signer: Arc<dyn RegistrationGenesisSigner>,
1047        intake: Arc<dyn FederatedIdentityIntake>,
1048        identity_resolver: Arc<dyn IdentityConnectTimeResolver>,
1049        did_web_origins: DidWebOriginAllowlist,
1050        rate_limiter: Arc<RateLimiter>,
1051    ) -> Self {
1052        Self {
1053            minter,
1054            signer,
1055            intake,
1056            identity_resolver,
1057            did_web_origins,
1058            rate_limiter,
1059        }
1060    }
1061
1062    fn register(
1063        &self,
1064        caller: &AuthenticatedIdentityCaller,
1065        path: RegistrationPath,
1066        request: RegisterHostedAccountRequest,
1067    ) -> Result<RegisterHostedAccountResponse, IdentityApiError> {
1068        if path == RegistrationPath::OperatorManual && !caller.subject().starts_with("service:") {
1069            return Err(IdentityApiError::Forbidden);
1070        }
1071        self.check_rate(caller)?;
1072        if request.handle.is_empty() || request.handle == UNAUTHENTICATED_DID_SENTINEL {
1073            return Err(IdentityApiError::InvalidRequest);
1074        }
1075
1076        let mint_request =
1077            HostedAccountRegistrationRequest::from_client_fields(request.handle, None)
1078                .map_err(|_| IdentityApiError::InvalidRequest)?;
1079        let signer = CallerGenesisSigner {
1080            provider: self.signer.as_ref(),
1081            caller: caller.subject(),
1082            operator_manual: path == RegistrationPath::OperatorManual,
1083        };
1084        let result = self
1085            .minter
1086            .mint(&mint_request, &signer)
1087            .map_err(IdentityApiError::Backend)?;
1088        if result.did == UNAUTHENTICATED_DID_SENTINEL {
1089            return Err(IdentityApiError::Backend(anyhow::anyhow!(
1090                "hosted-account mint returned the reserved unauthenticated DID"
1091            )));
1092        }
1093        Ok(RegisterHostedAccountResponse::from(result))
1094    }
1095
1096    /// Mint a hosted account from a cryptographically authenticated OAuth
1097    /// authorize transaction.
1098    ///
1099    /// This is deliberately an internal call, not an HTTP registration route.
1100    /// `dpop_jkt` comes from the verified PAR snapshot and `fingerprint` from
1101    /// the verified vault proof. Both are used only as rate-limit identities;
1102    /// the deployment authority still allocates the DID and tenant.
1103    pub(super) fn mint_for_oauth_signup(
1104        &self,
1105        handle: &str,
1106        dpop_jkt: &str,
1107        fingerprint: &str,
1108    ) -> Result<RegisterHostedAccountResponse, IdentityApiError> {
1109        if handle.is_empty()
1110            || handle == UNAUTHENTICATED_DID_SENTINEL
1111            || dpop_jkt.is_empty()
1112            || fingerprint.is_empty()
1113        {
1114            return Err(IdentityApiError::InvalidRequest);
1115        }
1116        if self
1117            .rate_limiter
1118            .check_and_increment(&format!("oauth-authorize-signup-key:{fingerprint}"))
1119        {
1120            return Err(IdentityApiError::RateLimited);
1121        }
1122
1123        let mint_request =
1124            HostedAccountRegistrationRequest::from_client_fields(handle.to_owned(), None)
1125                .map_err(|_| IdentityApiError::InvalidRequest)?;
1126        let caller = format!("oauth-signup:{fingerprint}");
1127        let signer = CallerGenesisSigner {
1128            provider: self.signer.as_ref(),
1129            caller: &caller,
1130            operator_manual: false,
1131        };
1132        let result = self
1133            .minter
1134            .mint_for_transaction(&mint_request, &signer, fingerprint)
1135            .map_err(|error| {
1136                if error.chain().any(|cause| {
1137                    cause
1138                        .downcast_ref::<std::io::Error>()
1139                        .is_some_and(|io| io.kind() == std::io::ErrorKind::AlreadyExists)
1140                }) {
1141                    IdentityApiError::HandleUnavailable
1142                } else {
1143                    IdentityApiError::Backend(error)
1144                }
1145            })?;
1146        if result.did == UNAUTHENTICATED_DID_SENTINEL {
1147            return Err(IdentityApiError::Backend(anyhow::anyhow!(
1148                "hosted-account mint returned the reserved unauthenticated DID"
1149            )));
1150        }
1151        Ok(result.into())
1152    }
1153
1154    /// Charge the public/global and verified PAR-DPoP signup buckets before
1155    /// performing even an Ed25519 proof verification. A single-use authorize
1156    /// nonce limits replay; these bounded buckets limit fresh-PAR abuse.
1157    pub(super) fn check_oauth_signup_rate(&self, dpop_jkt: &str) -> Result<(), IdentityApiError> {
1158        if dpop_jkt.is_empty() {
1159            return Err(IdentityApiError::InvalidRequest);
1160        }
1161        for bucket in [
1162            COLD_SIGNUP_GLOBAL_RATE_LIMIT_BUCKET.to_owned(),
1163            format!("oauth-authorize-signup-dpop:{dpop_jkt}"),
1164        ] {
1165            if self.rate_limiter.check_and_increment(&bucket) {
1166                return Err(IdentityApiError::RateLimited);
1167            }
1168        }
1169        Ok(())
1170    }
1171
1172    async fn intake(
1173        &self,
1174        caller: &AuthenticatedIdentityCaller,
1175        request: FederationIntakeRequest,
1176    ) -> Result<InventoryEntry, IdentityApiError> {
1177        self.check_rate(caller)?;
1178        if request.did == UNAUTHENTICATED_DID_SENTINEL {
1179            return Err(IdentityApiError::InvalidRequest);
1180        }
1181        if request.did.starts_with("did:web:") {
1182            self.did_web_origins.require_allowed(&request.did)?;
1183        } else if !hyprstream_rpc::did_plc::is_did_plc(&request.did) {
1184            return Err(IdentityApiError::InvalidRequest);
1185        }
1186        self.intake
1187            .intake(&request.did)
1188            .await
1189            .map_err(IdentityApiError::Backend)
1190    }
1191
1192    fn resolve(&self, did: &str) -> Result<ConnectTimeDiscovery, IdentityApiError> {
1193        if self
1194            .rate_limiter
1195            .check_and_increment(PUBLIC_RESOLVE_RATE_LIMIT_BUCKET)
1196        {
1197            return Err(IdentityApiError::ResolveRateLimited);
1198        }
1199        if did == UNAUTHENTICATED_DID_SENTINEL || !self.identity_resolver.recognizes(did) {
1200            return Err(IdentityApiError::NotFound(anyhow::anyhow!(
1201                "identity is outside the local authority directory"
1202            )));
1203        }
1204        self.identity_resolver
1205            .resolve(did)
1206            .map_err(IdentityApiError::NotFound)
1207    }
1208
1209    pub(super) fn hosted_tenant(&self, did: &str) -> Result<Option<String>> {
1210        self.identity_resolver.hosted_tenant(did)
1211    }
1212
1213    fn check_rate(&self, caller: &AuthenticatedIdentityCaller) -> Result<(), IdentityApiError> {
1214        if self.rate_limiter.check_and_increment(caller.subject()) {
1215            return Err(IdentityApiError::RateLimited);
1216        }
1217        Ok(())
1218    }
1219}
1220
1221struct CallerGenesisSigner<'a> {
1222    provider: &'a dyn RegistrationGenesisSigner,
1223    caller: &'a str,
1224    operator_manual: bool,
1225}
1226
1227impl HostedAccountGenesisSigner for CallerGenesisSigner<'_> {
1228    fn sign(&self, unsigned: &UnsignedGenesisDidOp) -> Result<DidOpSignature> {
1229        self.provider
1230            .sign_genesis(self.caller, self.operator_manual, unsigned)
1231    }
1232}
1233
1234#[derive(Debug)]
1235pub(super) enum IdentityApiError {
1236    Unauthenticated,
1237    LocalAuthorityRequired,
1238    Forbidden,
1239    RateLimited,
1240    ResolveRateLimited,
1241    ResolvableHostDenied,
1242    InvalidRequest,
1243    HandleUnavailable,
1244    NotFound(anyhow::Error),
1245    Backend(anyhow::Error),
1246}
1247
1248impl IntoResponse for IdentityApiError {
1249    fn into_response(self) -> Response {
1250        let (status, code, description) = match &self {
1251            Self::Unauthenticated => (
1252                StatusCode::UNAUTHORIZED,
1253                "authentication_required",
1254                "Authenticated caller required",
1255            ),
1256            Self::LocalAuthorityRequired => (
1257                StatusCode::FORBIDDEN,
1258                "local_authority_required",
1259                "A server-verified local account is required",
1260            ),
1261            Self::Forbidden => (
1262                StatusCode::FORBIDDEN,
1263                "insufficient_scope",
1264                "Operator authority required",
1265            ),
1266            Self::RateLimited => (
1267                StatusCode::TOO_MANY_REQUESTS,
1268                "rate_limited",
1269                "Identity mutation rate limit exceeded",
1270            ),
1271            Self::ResolveRateLimited => (
1272                StatusCode::TOO_MANY_REQUESTS,
1273                "rate_limited",
1274                "Identity resolution rate limit exceeded",
1275            ),
1276            Self::ResolvableHostDenied => (
1277                StatusCode::FORBIDDEN,
1278                "origin_not_allowed",
1279                "DID web origin is not permitted",
1280            ),
1281            Self::InvalidRequest => (
1282                StatusCode::BAD_REQUEST,
1283                "invalid_request",
1284                "Registration or intake request is invalid",
1285            ),
1286            Self::HandleUnavailable => (
1287                StatusCode::CONFLICT,
1288                "handle_unavailable",
1289                "Requested hosted-account handle is unavailable",
1290            ),
1291            Self::NotFound(_) => (
1292                StatusCode::NOT_FOUND,
1293                "not_found",
1294                "Identity resolution not found",
1295            ),
1296            Self::Backend(_) => (
1297                StatusCode::INTERNAL_SERVER_ERROR,
1298                "server_error",
1299                "Identity operation failed",
1300            ),
1301        };
1302        if let Self::Backend(error) = &self {
1303            warn!(%error, "identity registration/intake backend failed");
1304        }
1305        if let Self::NotFound(error) = &self {
1306            warn!(%error, "identity resolution failed closed");
1307        }
1308        (
1309            status,
1310            Json(serde_json::json!({
1311                "error": code,
1312                "error_description": description,
1313            })),
1314        )
1315            .into_response()
1316    }
1317}
1318
1319fn unavailable_response() -> Response {
1320    (
1321        StatusCode::SERVICE_UNAVAILABLE,
1322        Json(serde_json::json!({
1323            "error": "temporarily_unavailable",
1324            "error_description": "Identity registration is not configured",
1325        })),
1326    )
1327        .into_response()
1328}
1329
1330pub(super) async fn require_registration_session(
1331    State(state): State<Arc<OAuthState>>,
1332    mut request: Request,
1333    next: Next,
1334) -> Response {
1335    let session = match session::extract_session_id(request.headers()) {
1336        Some(session_id) => state.sessions.get(&session_id).await,
1337        None => None,
1338    };
1339    let Some(session) = session else {
1340        return IdentityApiError::Unauthenticated.into_response();
1341    };
1342    let caller = match AuthenticatedIdentityCaller::new(session.username) {
1343        Ok(caller) => caller,
1344        Err(error) => return error.into_response(),
1345    };
1346    request.extensions_mut().insert(caller);
1347    next.run(request).await
1348}
1349
1350/// Require the local authority that the ATProto session-exchange admission
1351/// derived from the authority-owned hosted-account binding. Registration keeps
1352/// its separate onboarding policy: intake is the existing protected action
1353/// that must never be authorized merely by a federated browser session.
1354pub(super) async fn require_local_intake_session(
1355    State(state): State<Arc<OAuthState>>,
1356    mut request: Request,
1357    next: Next,
1358) -> Response {
1359    let session = match session::extract_session_id(request.headers()) {
1360        Some(session_id) => state.sessions.get(&session_id).await,
1361        None => None,
1362    };
1363    let Some(session) = session else {
1364        return IdentityApiError::Unauthenticated.into_response();
1365    };
1366    let local_atproto_session = session.auth_method == "atproto"
1367        && session.atproto_did.as_deref() == Some(session.username.as_str())
1368        && session
1369            .verified_tenant
1370            .as_deref()
1371            .is_some_and(|tenant| !tenant.is_empty());
1372    if !local_atproto_session {
1373        return IdentityApiError::LocalAuthorityRequired.into_response();
1374    }
1375    let caller = match AuthenticatedIdentityCaller::new(session.username) {
1376        Ok(caller) => caller,
1377        Err(error) => return error.into_response(),
1378    };
1379    request.extensions_mut().insert(caller);
1380    next.run(request).await
1381}
1382
1383pub(super) async fn register_self_service(
1384    State(state): State<Arc<OAuthState>>,
1385    Extension(caller): Extension<AuthenticatedIdentityCaller>,
1386    Json(request): Json<RegisterHostedAccountRequest>,
1387) -> Response {
1388    match state.identity_registration_api.as_deref() {
1389        Some(api) => api
1390            .register(&caller, RegistrationPath::SelfService, request)
1391            .map(Json)
1392            .into_response(),
1393        None => unavailable_response(),
1394    }
1395}
1396
1397pub(super) async fn register_operator_manual(
1398    State(state): State<Arc<OAuthState>>,
1399    Extension(user): Extension<AuthenticatedUser>,
1400    Json(request): Json<RegisterHostedAccountRequest>,
1401) -> Response {
1402    let caller = match AuthenticatedIdentityCaller::new(user.user) {
1403        Ok(caller) => caller,
1404        Err(error) => return error.into_response(),
1405    };
1406    match state.identity_registration_api.as_deref() {
1407        Some(api) => api
1408            .register(&caller, RegistrationPath::OperatorManual, request)
1409            .map(Json)
1410            .into_response(),
1411        None => unavailable_response(),
1412    }
1413}
1414
1415pub(super) async fn intake_federated_identity(
1416    State(state): State<Arc<OAuthState>>,
1417    Extension(caller): Extension<AuthenticatedIdentityCaller>,
1418    Json(request): Json<FederationIntakeRequest>,
1419) -> Response {
1420    match state.identity_registration_api.as_deref() {
1421        Some(api) => api.intake(&caller, request).await.map(Json).into_response(),
1422        None => unavailable_response(),
1423    }
1424}
1425
1426pub(super) async fn resolve_identity(
1427    State(state): State<Arc<OAuthState>>,
1428    Query(query): Query<ResolveIdentityQuery>,
1429) -> Response {
1430    match state.identity_registration_api.as_deref() {
1431        Some(api) => api.resolve(&query.did).map(Json).into_response(),
1432        None => unavailable_response(),
1433    }
1434}
1435
1436#[cfg(test)]
1437mod tests {
1438    #![allow(clippy::expect_used, clippy::unwrap_used)]
1439
1440    use std::sync::atomic::{AtomicUsize, Ordering};
1441
1442    use anyhow::bail;
1443
1444    use super::*;
1445
1446    const PUBLIC_PLC_DID: &str = "did:plc:ewvi7nxzyoun6zhxrhs64oiz";
1447    const LOCAL_HOSTED_DID: &str = "did:web:alice.accounts.example.com";
1448
1449    struct FakeMint {
1450        calls: AtomicUsize,
1451    }
1452
1453    impl HostedRegistrationMint for FakeMint {
1454        fn mint(
1455            &self,
1456            request: &HostedAccountRegistrationRequest,
1457            _signer: &dyn HostedAccountGenesisSigner,
1458        ) -> Result<HostedAccountRegistrationResult> {
1459            self.calls.fetch_add(1, Ordering::SeqCst);
1460            let did = if request.handle() == "reserved-result" {
1461                UNAUTHENTICATED_DID_SENTINEL.to_owned()
1462            } else {
1463                format!("did:web:{}.accounts.example", request.handle())
1464            };
1465            Ok(HostedAccountRegistrationResult {
1466                handle: format!("at://{}.accounts.example", request.handle()),
1467                did,
1468                pds_endpoint: "https://pds.example".to_owned(),
1469                quic_url: "https://pds.example:4433/wt".to_owned(),
1470                cert_hash: "zQmPin".to_owned(),
1471            })
1472        }
1473    }
1474
1475    struct FakeSigner;
1476
1477    impl RegistrationGenesisSigner for FakeSigner {
1478        fn sign_genesis(
1479            &self,
1480            _caller: &str,
1481            _operator_manual: bool,
1482            _unsigned: &UnsignedGenesisDidOp,
1483        ) -> Result<DidOpSignature> {
1484            bail!("fake mint must not invoke the signer")
1485        }
1486    }
1487
1488    struct CountingIntake {
1489        calls: AtomicUsize,
1490    }
1491
1492    #[async_trait]
1493    impl FederatedIdentityIntake for CountingIntake {
1494        async fn intake(&self, _did: &str) -> Result<InventoryEntry> {
1495            self.calls.fetch_add(1, Ordering::SeqCst);
1496            bail!("counting intake reached")
1497        }
1498    }
1499
1500    struct CountingIdentityResolver {
1501        calls: AtomicUsize,
1502    }
1503
1504    impl IdentityConnectTimeResolver for CountingIdentityResolver {
1505        fn recognizes(&self, did: &str) -> bool {
1506            matches!(did, PUBLIC_PLC_DID | LOCAL_HOSTED_DID)
1507                || did == "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa"
1508        }
1509
1510        fn resolve(&self, did: &str) -> Result<ConnectTimeDiscovery> {
1511            self.calls.fetch_add(1, Ordering::SeqCst);
1512            if !matches!(did, PUBLIC_PLC_DID | LOCAL_HOSTED_DID) {
1513                bail!("identity not found");
1514            }
1515            Ok(serde_json::from_value(serde_json::json!({
1516                "quicUrl": "https://pds.example:4433",
1517                "certHash": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=",
1518            }))?)
1519        }
1520    }
1521
1522    fn fixture(
1523        max_requests: u32,
1524    ) -> (
1525        Arc<FakeMint>,
1526        Arc<CountingIntake>,
1527        Arc<CountingIdentityResolver>,
1528        IdentityRegistrationApi,
1529    ) {
1530        let mint = Arc::new(FakeMint {
1531            calls: AtomicUsize::new(0),
1532        });
1533        let intake = Arc::new(CountingIntake {
1534            calls: AtomicUsize::new(0),
1535        });
1536        let identity_resolver = Arc::new(CountingIdentityResolver {
1537            calls: AtomicUsize::new(0),
1538        });
1539        let api = IdentityRegistrationApi::new(
1540            mint.clone(),
1541            Arc::new(FakeSigner),
1542            intake.clone(),
1543            identity_resolver.clone(),
1544            DidWebOriginAllowlist::new(["https://federated.example"]).unwrap(),
1545            Arc::new(RateLimiter::new(max_requests, 60)),
1546        );
1547        (mint, intake, identity_resolver, api)
1548    }
1549
1550    #[test]
1551    fn handle_only_contract_rejects_client_authority_fields() {
1552        let error = serde_json::from_value::<RegisterHostedAccountRequest>(
1553            serde_json::json!({"handle": "alice", "tenant": "attacker"}),
1554        )
1555        .unwrap_err();
1556        assert!(error.to_string().contains("unknown field"));
1557
1558        let error = serde_json::from_value::<RegisterHostedAccountRequest>(
1559            serde_json::json!({"handle": "alice", "mode": "operator"}),
1560        )
1561        .unwrap_err();
1562        assert!(error.to_string().contains("unknown field"));
1563    }
1564
1565    #[test]
1566    fn self_service_and_manual_paths_return_exact_registration_contract() {
1567        let (mint, _intake, _plc_resolver, api) = fixture(10);
1568        let self_caller = AuthenticatedIdentityCaller::new("did:web:alice.example").unwrap();
1569        let response = api
1570            .register(
1571                &self_caller,
1572                RegistrationPath::SelfService,
1573                RegisterHostedAccountRequest {
1574                    handle: "alice".to_owned(),
1575                },
1576            )
1577            .unwrap();
1578        assert_eq!(response.handle, "at://alice.accounts.example");
1579        assert_eq!(response.did, "did:web:alice.accounts.example");
1580        assert_eq!(response.pds_endpoint, "https://pds.example");
1581        assert_eq!(response.quic_url, "https://pds.example:4433/wt");
1582        assert_eq!(response.cert_hash, "zQmPin");
1583        assert_eq!(
1584            serde_json::to_value(&response).unwrap(),
1585            serde_json::json!({
1586                "handle": "at://alice.accounts.example",
1587                "did": "did:web:alice.accounts.example",
1588                "pdsEndpoint": "https://pds.example",
1589                "quicUrl": "https://pds.example:4433/wt",
1590                "certHash": "zQmPin",
1591            })
1592        );
1593
1594        let operator = AuthenticatedIdentityCaller::new("service:identity-operator").unwrap();
1595        api.register(
1596            &operator,
1597            RegistrationPath::OperatorManual,
1598            RegisterHostedAccountRequest {
1599                handle: "bob".to_owned(),
1600            },
1601        )
1602        .unwrap();
1603        assert_eq!(mint.calls.load(Ordering::SeqCst), 2);
1604    }
1605
1606    #[test]
1607    fn manual_path_rejects_non_service_and_unknown_before_mint() {
1608        let (mint, _intake, _plc_resolver, api) = fixture(10);
1609        let user = AuthenticatedIdentityCaller::new("did:web:alice.example").unwrap();
1610        assert!(matches!(
1611            api.register(
1612                &user,
1613                RegistrationPath::OperatorManual,
1614                RegisterHostedAccountRequest {
1615                    handle: "alice".to_owned(),
1616                },
1617            ),
1618            Err(IdentityApiError::Forbidden)
1619        ));
1620        assert!(matches!(
1621            api.register(
1622                &user,
1623                RegistrationPath::SelfService,
1624                RegisterHostedAccountRequest {
1625                    handle: UNAUTHENTICATED_DID_SENTINEL.to_owned(),
1626                },
1627            ),
1628            Err(IdentityApiError::InvalidRequest)
1629        ));
1630        assert_eq!(mint.calls.load(Ordering::SeqCst), 0);
1631    }
1632
1633    #[test]
1634    fn reserved_did_is_rejected_again_at_the_api_output_boundary() {
1635        let (mint, _intake, _plc_resolver, api) = fixture(10);
1636        let caller = AuthenticatedIdentityCaller::new("did:web:alice.example").unwrap();
1637        assert!(matches!(
1638            api.register(
1639                &caller,
1640                RegistrationPath::SelfService,
1641                RegisterHostedAccountRequest {
1642                    handle: "reserved-result".to_owned(),
1643                },
1644            ),
1645            Err(IdentityApiError::Backend(_))
1646        ));
1647        assert_eq!(mint.calls.load(Ordering::SeqCst), 1);
1648    }
1649
1650    #[test]
1651    fn rate_limit_runs_before_mint() {
1652        let (mint, _intake, _plc_resolver, api) = fixture(1);
1653        let caller = AuthenticatedIdentityCaller::new("did:web:alice.example").unwrap();
1654        let request = || RegisterHostedAccountRequest {
1655            handle: "alice".to_owned(),
1656        };
1657        api.register(&caller, RegistrationPath::SelfService, request())
1658            .unwrap();
1659        assert!(matches!(
1660            api.register(&caller, RegistrationPath::SelfService, request()),
1661            Err(IdentityApiError::RateLimited)
1662        ));
1663        assert_eq!(mint.calls.load(Ordering::SeqCst), 1);
1664    }
1665
1666    #[tokio::test]
1667    async fn intake_constrains_did_web_before_resolver_io() {
1668        let (_mint, intake, _plc_resolver, api) = fixture(10);
1669        let caller = AuthenticatedIdentityCaller::new("did:web:alice.example").unwrap();
1670
1671        assert!(matches!(
1672            api.intake(
1673                &caller,
1674                FederationIntakeRequest {
1675                    did: "did:web:127.0.0.1%3A8443".to_owned(),
1676                },
1677            )
1678            .await,
1679            Err(IdentityApiError::ResolvableHostDenied)
1680        ));
1681        assert!(matches!(
1682            api.intake(
1683                &caller,
1684                FederationIntakeRequest {
1685                    did: UNAUTHENTICATED_DID_SENTINEL.to_owned(),
1686                },
1687            )
1688            .await,
1689            Err(IdentityApiError::InvalidRequest)
1690        ));
1691        assert_eq!(intake.calls.load(Ordering::SeqCst), 0);
1692
1693        let error = api
1694            .intake(
1695                &caller,
1696                FederationIntakeRequest {
1697                    did: "did:web:federated.example".to_owned(),
1698                },
1699            )
1700            .await
1701            .unwrap_err();
1702        assert!(matches!(error, IdentityApiError::Backend(_)));
1703        assert_eq!(intake.calls.load(Ordering::SeqCst), 1);
1704    }
1705
1706    #[test]
1707    fn public_resolution_returns_exact_connect_time_contract() {
1708        let (_mint, _intake, identity_resolver, api) = fixture(10);
1709
1710        let response = api.resolve(PUBLIC_PLC_DID).unwrap();
1711
1712        assert_eq!(response.quic_url(), "https://pds.example:4433");
1713        assert_eq!(
1714            serde_json::to_value(response).unwrap(),
1715            serde_json::json!({
1716                "quicUrl": "https://pds.example:4433",
1717                "certHash": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=",
1718            })
1719        );
1720        assert_eq!(identity_resolver.calls.load(Ordering::SeqCst), 1);
1721    }
1722
1723    #[test]
1724    fn public_resolution_covers_local_hosted_inventory_entries() {
1725        let (_mint, _intake, identity_resolver, api) = fixture(10);
1726
1727        let response = api.resolve(LOCAL_HOSTED_DID).unwrap();
1728
1729        assert_eq!(response.quic_url(), "https://pds.example:4433");
1730        assert_eq!(identity_resolver.calls.load(Ordering::SeqCst), 1);
1731    }
1732
1733    #[test]
1734    fn public_resolution_rejects_sentinel_and_external_dids_before_resolver_io() {
1735        let (_mint, _intake, identity_resolver, api) = fixture(10);
1736
1737        for did in [
1738            UNAUTHENTICATED_DID_SENTINEL,
1739            "did:web:foreign.example",
1740            "did:key:zAttacker",
1741        ] {
1742            assert!(matches!(
1743                api.resolve(did),
1744                Err(IdentityApiError::NotFound(_))
1745            ));
1746        }
1747        assert_eq!(identity_resolver.calls.load(Ordering::SeqCst), 0);
1748
1749        assert!(matches!(
1750            api.resolve("did:plc:aaaaaaaaaaaaaaaaaaaaaaaa"),
1751            Err(IdentityApiError::NotFound(_))
1752        ));
1753        assert_eq!(identity_resolver.calls.load(Ordering::SeqCst), 1);
1754    }
1755
1756    #[test]
1757    fn public_resolution_rate_limit_runs_before_resolver_io() {
1758        let (_mint, _intake, identity_resolver, api) = fixture(1);
1759
1760        api.resolve(PUBLIC_PLC_DID).unwrap();
1761        assert!(matches!(
1762            api.resolve(PUBLIC_PLC_DID),
1763            Err(IdentityApiError::ResolveRateLimited)
1764        ));
1765        assert_eq!(identity_resolver.calls.load(Ordering::SeqCst), 1);
1766    }
1767
1768    #[test]
1769    fn allowlist_accepts_only_exact_https_origins() {
1770        assert!(DidWebOriginAllowlist::new(["http://example.com"]).is_err());
1771        assert!(DidWebOriginAllowlist::new(["https://example.com/path"]).is_err());
1772        assert!(DidWebOriginAllowlist::new(["https://*.example.com"]).is_err());
1773
1774        let allowlist =
1775            DidWebOriginAllowlist::new(["https://example.com", "https://example.com:8443"])
1776                .unwrap();
1777        assert!(allowlist.require_allowed("did:web:example.com").is_ok());
1778        assert!(allowlist
1779            .require_allowed("did:web:example.com%3A8443")
1780            .is_ok());
1781        assert!(matches!(
1782            allowlist.require_allowed("did:web:sub.example.com"),
1783            Err(IdentityApiError::ResolvableHostDenied)
1784        ));
1785    }
1786
1787    fn oauth_state() -> (Arc<OAuthState>, crate::config::CorsConfig) {
1788        use hyprstream_rpc::crypto::CryptoPolicy;
1789        use hyprstream_rpc::rpc_client::RpcClientImpl;
1790        use hyprstream_rpc::signer::LocalSigner;
1791        use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
1792
1793        let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x51; 32]);
1794        let remote_key = ed25519_dalek::SigningKey::from_bytes(&[0x52; 32]).verifying_key();
1795        let make_client = || {
1796            Arc::new(
1797                RpcClientImpl::new(
1798                    LocalSigner::new(signing_key.clone()),
1799                    LazyUdsTransport::new("/dev/null/identity-registration-test.sock".into()),
1800                    Some(remote_key),
1801                )
1802                .with_response_verify_policy(CryptoPolicy::Classical),
1803            )
1804        };
1805        let mut config = crate::config::OAuthConfig::default();
1806        config.external_url = Some("https://pds.example.test".to_owned());
1807        let cors = config.cors.clone();
1808        (
1809            Arc::new(OAuthState::new(
1810                &config,
1811                hyprstream_rpc_std::policy_client::PolicyClient::new(make_client()),
1812                hyprstream_rpc_std::discovery_client::DiscoveryClient::new(make_client()),
1813                signing_key.verifying_key().to_bytes(),
1814            )),
1815            cors,
1816        )
1817    }
1818
1819    struct FixtureFederatedResolver;
1820
1821    #[async_trait]
1822    impl FederatedDidDocumentResolver for FixtureFederatedResolver {
1823        async fn resolve_federated_document(&self, did: &str) -> Result<serde_json::Value> {
1824            Ok(serde_json::json!({
1825                "id": did,
1826                "alsoKnownAs": ["at://foreign.example"],
1827                "service": [{
1828                    "id": format!("{did}#atproto_pds"),
1829                    "type": "AtprotoPersonalDataServer",
1830                    "serviceEndpoint": "https://foreign.example",
1831                }],
1832            }))
1833        }
1834    }
1835
1836    struct ProductionRouterFixture {
1837        state: Arc<OAuthState>,
1838        cors: crate::config::CorsConfig,
1839        quic: QuicConfig,
1840        signing_key: ed25519_dalek::SigningKey,
1841        storage: tempfile::TempDir,
1842    }
1843
1844    fn production_router_fixture() -> ProductionRouterFixture {
1845        use hyprstream_rpc::crypto::CryptoPolicy;
1846        use hyprstream_rpc::rpc_client::RpcClientImpl;
1847        use hyprstream_rpc::signer::LocalSigner;
1848        use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
1849
1850        let storage = tempfile::TempDir::new().unwrap();
1851        // Bearer-token verification fails closed without the process-global
1852        // revocation store (one canonical store; no per-service plumbing).
1853        // Install an in-memory authority when no other test in this binary
1854        // got there first.
1855        if hyprstream_rpc::auth::global_credential_revocation_store().is_none() {
1856            let _ = hyprstream_rpc::auth::set_global_credential_revocation_store(Arc::new(
1857                hyprstream_rpc::auth::InMemoryCredentialRevocationStore::new(),
1858            ));
1859        }
1860        let certified =
1861            rcgen::generate_simple_self_signed(vec!["pds.example.test".to_owned()]).unwrap();
1862        let cert_path = storage.path().join("quic-cert.pem");
1863        let key_path = storage.path().join("quic-key.pem");
1864        std::fs::write(&cert_path, certified.cert.pem()).unwrap();
1865        std::fs::write(&key_path, certified.key_pair.serialize_pem()).unwrap();
1866
1867        let mut oauth = crate::config::OAuthConfig::default();
1868        oauth.external_url = Some("https://pds.example.test".to_owned());
1869        oauth.identity_registration_did_web_origins = vec!["https://foreign.example".to_owned()];
1870        let account = AccountZoneConfig {
1871            zone: Some("accounts.example.com".to_owned()),
1872            ..AccountZoneConfig::default()
1873        };
1874        let quic = QuicConfig {
1875            event_publishers: Default::default(),
1876            stream_publishers: Default::default(),
1877            enabled: true,
1878            bind_addr: "127.0.0.1:4433".to_owned(),
1879            server_name: "pds.example.test".to_owned(),
1880            cert_path: cert_path.to_string_lossy().into_owned(),
1881            key_path: key_path.to_string_lossy().into_owned(),
1882            iroh: false,
1883            native_network_profile: crate::config::NativeNetworkProfile::Compatibility,
1884            relay: String::new(),
1885        };
1886        let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x53; 32]);
1887        let api = compose_identity_registration_api(
1888            &oauth,
1889            &account,
1890            &quic,
1891            signing_key.clone(),
1892            storage.path().join("pds"),
1893            Arc::new(FixtureFederatedResolver),
1894            Arc::new(CountingIdentityResolver {
1895                calls: AtomicUsize::new(0),
1896            }),
1897        )
1898        .unwrap();
1899
1900        let remote_key = ed25519_dalek::SigningKey::from_bytes(&[0x54; 32]).verifying_key();
1901        let make_client = || {
1902            Arc::new(
1903                RpcClientImpl::new(
1904                    LocalSigner::new(signing_key.clone()),
1905                    LazyUdsTransport::new(
1906                        "/dev/null/identity-registration-production-test.sock".into(),
1907                    ),
1908                    Some(remote_key),
1909                )
1910                .with_response_verify_policy(CryptoPolicy::Classical),
1911            )
1912        };
1913        let cors = oauth.cors.clone();
1914        let state = Arc::new(
1915            OAuthState::new(
1916                &oauth,
1917                hyprstream_rpc_std::policy_client::PolicyClient::new(make_client()),
1918                hyprstream_rpc_std::discovery_client::DiscoveryClient::new(make_client()),
1919                signing_key.verifying_key().to_bytes(),
1920            )
1921            .with_identity_registration_api(api),
1922        );
1923        ProductionRouterFixture {
1924            state,
1925            cors,
1926            quic,
1927            signing_key,
1928            storage,
1929        }
1930    }
1931
1932    fn post(
1933        path: &str,
1934        body: &'static str,
1935        cookie: Option<String>,
1936        bearer: Option<&str>,
1937    ) -> axum::http::Request<axum::body::Body> {
1938        let mut request = axum::http::Request::post(path)
1939            .header(axum::http::header::CONTENT_TYPE, "application/json")
1940            .body(axum::body::Body::from(body))
1941            .unwrap();
1942        if let Some(cookie) = cookie {
1943            request
1944                .headers_mut()
1945                .insert(axum::http::header::COOKIE, cookie.parse().unwrap());
1946        }
1947        if let Some(bearer) = bearer {
1948            request.headers_mut().insert(
1949                axum::http::header::AUTHORIZATION,
1950                format!("Bearer {bearer}").parse().unwrap(),
1951            );
1952        }
1953        request
1954    }
1955
1956    fn get(path: &str) -> axum::http::Request<axum::body::Body> {
1957        axum::http::Request::get(path)
1958            .body(axum::body::Body::empty())
1959            .unwrap()
1960    }
1961
1962    #[tokio::test]
1963    async fn live_routes_never_expose_unauthenticated_registration_or_intake() {
1964        use tower::ServiceExt;
1965
1966        let (state, cors) = oauth_state();
1967        let app = super::super::create_app(Arc::clone(&state), &cors);
1968
1969        for path in [
1970            "/api/identity/register",
1971            "/api/identity/intake",
1972            "/api/identity/register/manual",
1973        ] {
1974            let response = app
1975                .clone()
1976                .oneshot(post(path, r#"{"handle":"alice"}"#, None, None))
1977                .await
1978                .unwrap();
1979            assert_eq!(
1980                response.status(),
1981                StatusCode::UNAUTHORIZED,
1982                "{path} must authenticate before its handler"
1983            );
1984        }
1985
1986        let session_id = state
1987            .sessions
1988            .create("did:web:alice.example".to_owned(), "local".to_owned())
1989            .await;
1990        let response = app
1991            .oneshot(post(
1992                "/api/identity/register",
1993                r#"{"handle":"alice"}"#,
1994                Some(format!("{}={session_id}", session::SESSION_COOKIE_NAME)),
1995                None,
1996            ))
1997            .await
1998            .unwrap();
1999        assert_eq!(
2000            response.status(),
2001            StatusCode::SERVICE_UNAVAILABLE,
2002            "an authenticated route with no injected minter must fail closed"
2003        );
2004    }
2005
2006    #[tokio::test]
2007    async fn public_resolve_route_is_floor_readable_for_plc_and_hosted_local_dids() {
2008        use tower::ServiceExt;
2009
2010        for did in [PUBLIC_PLC_DID, LOCAL_HOSTED_DID] {
2011            let fixture = production_router_fixture();
2012            let response = super::super::create_app(Arc::clone(&fixture.state), &fixture.cors)
2013                .oneshot(get(&format!("/api/identity/resolve?did={did}")))
2014                .await
2015                .unwrap();
2016            assert_eq!(
2017                response.status(),
2018                StatusCode::OK,
2019                "{did} must resolve without authentication"
2020            );
2021            let body = axum::body::to_bytes(response.into_body(), usize::MAX)
2022                .await
2023                .unwrap();
2024            let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
2025            assert_eq!(
2026                value,
2027                serde_json::json!({
2028                    "quicUrl": "https://pds.example:4433",
2029                    "certHash": "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=",
2030                })
2031            );
2032            assert_eq!(value.as_object().unwrap().len(), 2);
2033        }
2034    }
2035
2036    #[tokio::test]
2037    async fn public_resolve_route_collapses_sentinel_external_and_missing_to_not_found() {
2038        use tower::ServiceExt;
2039
2040        for did in [
2041            UNAUTHENTICATED_DID_SENTINEL,
2042            "did:web:foreign.example",
2043            "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa",
2044        ] {
2045            let fixture = production_router_fixture();
2046            let response = super::super::create_app(Arc::clone(&fixture.state), &fixture.cors)
2047                .oneshot(get(&format!("/api/identity/resolve?did={did}")))
2048                .await
2049                .unwrap();
2050            assert_eq!(response.status(), StatusCode::NOT_FOUND);
2051            let body = axum::body::to_bytes(response.into_body(), usize::MAX)
2052                .await
2053                .unwrap();
2054            assert_eq!(
2055                serde_json::from_slice::<serde_json::Value>(&body).unwrap(),
2056                serde_json::json!({
2057                    "error": "not_found",
2058                    "error_description": "Identity resolution not found",
2059                })
2060            );
2061        }
2062    }
2063
2064    #[tokio::test]
2065    async fn production_composition_live_session_register_mints_and_publishes() {
2066        use tower::ServiceExt;
2067
2068        let fixture = production_router_fixture();
2069        let session_id = fixture
2070            .state
2071            .sessions
2072            .create("did:web:member.example".to_owned(), "local".to_owned())
2073            .await;
2074        let response = super::super::create_app(Arc::clone(&fixture.state), &fixture.cors)
2075            .oneshot(post(
2076                "/api/identity/register",
2077                r#"{"handle":"alice"}"#,
2078                Some(format!("{}={session_id}", session::SESSION_COOKIE_NAME)),
2079                None,
2080            ))
2081            .await
2082            .unwrap();
2083        assert_eq!(response.status(), StatusCode::OK);
2084        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
2085            .await
2086            .unwrap();
2087        let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
2088        assert_eq!(value.as_object().unwrap().len(), 5);
2089        assert_eq!(value["handle"], "at://alice.accounts.example.com");
2090        assert_eq!(value["did"], "did:web:alice.accounts.example.com");
2091        assert_eq!(value["pdsEndpoint"], "https://pds.example.test");
2092        assert_eq!(value["quicUrl"], "https://pds.example.test:4433");
2093        assert!(value["certHash"]
2094            .as_str()
2095            .is_some_and(|hash| !hash.is_empty()));
2096        let published = fixture
2097            .storage
2098            .path()
2099            .join("pds/accounts.example.com/accounts/alice");
2100        assert!(published.join("account-record.cbor").is_file());
2101        assert!(published.join("genesis.didop.cbor").is_file());
2102        assert!(published.join("did-document.json").is_file());
2103        assert!(published.join("repo/commit.cbor").is_file());
2104        assert!(published.join("repo/public-commit.cbor").is_file());
2105    }
2106
2107    #[test]
2108    fn production_cold_signup_mint_resumes_published_genesis_for_exact_transaction() {
2109        let fixture = production_router_fixture();
2110        let api = fixture.state.identity_registration_api.as_ref().unwrap();
2111
2112        let first = api
2113            .mint_for_oauth_signup("alice", "verified-dpop-jkt", "SHA256:vault-key")
2114            .unwrap();
2115        let second = api
2116            .mint_for_oauth_signup("alice", "verified-dpop-jkt", "SHA256:vault-key")
2117            .unwrap();
2118
2119        assert_eq!(second, first);
2120        assert!(matches!(
2121            api.mint_for_oauth_signup("alice", "verified-dpop-jkt", "SHA256:different-key"),
2122            Err(IdentityApiError::HandleUnavailable)
2123        ));
2124        let account = fixture
2125            .storage
2126            .path()
2127            .join("pds/accounts.example.com/accounts/alice");
2128        assert!(account.join("account-record.cbor").is_file());
2129        assert!(account.join("repo/commit.cbor").is_file());
2130        assert!(account.join("repo/public-commit.cbor").is_file());
2131        let transaction: serde_json::Value =
2132            serde_json::from_slice(&std::fs::read(account.join(SIGNUP_TRANSACTION_FILE)).unwrap())
2133                .unwrap();
2134        assert_eq!(transaction["transaction_id"], "SHA256:vault-key");
2135    }
2136
2137    #[test]
2138    fn production_legacy_signup_resume_preserves_original_identity_and_transaction() {
2139        let fixture = production_router_fixture();
2140        let api = fixture.state.identity_registration_api.as_ref().unwrap();
2141        let first = api
2142            .mint_for_oauth_signup("alice", "verified-dpop-jkt", "SHA256:vault-key")
2143            .unwrap();
2144        let account = fixture
2145            .storage
2146            .path()
2147            .join("pds/accounts.example.com/accounts/alice");
2148        let files = [
2149            "account-record.cbor",
2150            "genesis.didop.cbor",
2151            "did-document.json",
2152            hyprstream_pds::ATPROTO_SIGNING_KEY_FILE,
2153            "repo/commit.cbor",
2154            "repo/head",
2155            SIGNUP_TRANSACTION_FILE,
2156        ];
2157        let original: Vec<_> = files
2158            .iter()
2159            .map(|file| std::fs::read(account.join(file)).unwrap())
2160            .collect();
2161        std::fs::remove_file(account.join("repo/public-commit.cbor")).unwrap();
2162        let resumed = api
2163            .mint_for_oauth_signup("alice", "verified-dpop-jkt", "SHA256:vault-key")
2164            .unwrap();
2165        assert_eq!(resumed, first);
2166        assert!(!account.join("repo/public-commit.cbor").exists());
2167        for (file, bytes) in files.iter().zip(&original) {
2168            assert_eq!(&std::fs::read(account.join(file)).unwrap(), bytes, "{file}");
2169        }
2170        assert!(matches!(
2171            api.mint_for_oauth_signup("alice", "verified-dpop-jkt", "SHA256:different-key"),
2172            Err(IdentityApiError::HandleUnavailable)
2173        ));
2174        // Present invalid bytes must not take the legacy absence path.
2175        std::fs::write(
2176            account.join("repo/public-commit.cbor"),
2177            b"corrupt public genesis",
2178        )
2179        .unwrap();
2180        assert!(api
2181            .mint_for_oauth_signup("alice", "verified-dpop-jkt", "SHA256:vault-key")
2182            .is_err());
2183        #[cfg(unix)]
2184        {
2185            std::fs::remove_file(account.join("repo/public-commit.cbor")).unwrap();
2186            std::os::unix::fs::symlink("missing-target", account.join("repo/public-commit.cbor"))
2187                .unwrap();
2188            assert!(api
2189                .mint_for_oauth_signup("alice", "verified-dpop-jkt", "SHA256:vault-key")
2190                .is_err());
2191        }
2192    }
2193
2194    #[test]
2195    fn production_legacy_signup_resume_still_requires_native_authority_closure() {
2196        for artifact in [
2197            "account-record.cbor",
2198            "genesis.didop.cbor",
2199            "did-document.json",
2200            "repo/commit.cbor",
2201            "repo/head",
2202            "root-block",
2203            SIGNUP_TRANSACTION_FILE,
2204            "missing-native",
2205        ] {
2206            let fixture = production_router_fixture();
2207            let api = fixture.state.identity_registration_api.as_ref().unwrap();
2208            api.mint_for_oauth_signup("alice", "verified-dpop-jkt", "SHA256:vault-key")
2209                .unwrap();
2210            let account = fixture
2211                .storage
2212                .path()
2213                .join("pds/accounts.example.com/accounts/alice");
2214            std::fs::remove_file(account.join("repo/public-commit.cbor")).unwrap();
2215            let path = if artifact == "root-block" {
2216                let native = hyprstream_pds::commit::Commit::from_dag_cbor(
2217                    &std::fs::read(account.join("repo/commit.cbor")).unwrap(),
2218                )
2219                .unwrap();
2220                account.join(format!("repo/blocks/{}.cbor", native.data))
2221            } else {
2222                account.join(artifact)
2223            };
2224            if artifact == "missing-native" {
2225                std::fs::remove_file(account.join("repo/commit.cbor")).unwrap();
2226            } else {
2227                std::fs::write(path, b"corrupt native authority").unwrap();
2228            }
2229            assert!(
2230                api.mint_for_oauth_signup("alice", "verified-dpop-jkt", "SHA256:vault-key")
2231                    .is_err(),
2232                "{artifact}"
2233            );
2234        }
2235    }
2236
2237    #[cfg(feature = "rocksdb")]
2238    #[tokio::test]
2239    async fn production_mac_published_genesis_supports_hosted_reads_and_writes() {
2240        use crate::mac::audit::{AuditError, AuditRecord, AuditSink, DecisionReason};
2241        use crate::services::public_repo::{
2242            hosted_tests, HostedAccountPublicRepoWriter, HostedAccountSelfAuthorizer,
2243            PublicRepoStore,
2244        };
2245        use tower::ServiceExt;
2246        #[derive(Default)]
2247        struct CaptureAudit(parking_lot::Mutex<Vec<AuditRecord>>);
2248        impl AuditSink for CaptureAudit {
2249            fn record(&self, record: &AuditRecord) -> Result<(), AuditError> {
2250                self.0.lock().push(record.clone());
2251                Ok(())
2252            }
2253        }
2254        for legacy in [false, true] {
2255            let mut fixture = production_router_fixture();
2256            fixture
2257                .state
2258                .identity_registration_api
2259                .as_ref()
2260                .unwrap()
2261                .mint_for_oauth_signup("alice", "verified-dpop-jkt", "SHA256:vault-key")
2262                .unwrap();
2263            let root = fixture.storage.path().join("pds");
2264            if legacy {
2265                std::fs::remove_file(
2266                    root.join("accounts.example.com/accounts/alice/repo/public-commit.cbor"),
2267                )
2268                .unwrap();
2269            }
2270            let audit = Arc::new(CaptureAudit::default());
2271            // Real descriptor-bound directory mount, Enrollment clearance,
2272            // structural labels and mandatory audited PEP; no permit substitute.
2273            let accounts = crate::mac::production_pds_account_record_store(
2274                Arc::new(crate::mac::PdsDirectoryMount::open(&root).unwrap()),
2275                audit.clone(),
2276            );
2277            let authority = hyprstream_rpc::Subject::new(
2278                hyprstream_pds_service::OAUTH_ACCOUNT_RESOLVER_SUBJECT,
2279            );
2280            accounts.refresh_hosted_did_index(&authority).await.unwrap();
2281            let store = Arc::new(
2282                PublicRepoStore::open(&fixture.storage.path().join("public-repos")).unwrap(),
2283            );
2284            let writer = Arc::new(HostedAccountPublicRepoWriter::new(
2285                store.clone(),
2286                accounts,
2287                authority,
2288                Arc::new(HostedAccountSelfAuthorizer),
2289            ));
2290            let state = Arc::get_mut(&mut fixture.state).unwrap();
2291            state.hosted_account_zone = Some(AccountZone::new("accounts.example.com").unwrap());
2292            state.hosted_public_repo_writer = Some(writer.clone());
2293            let app = super::super::xrpc::xrpc_routes().with_state(fixture.state.clone());
2294            let description = app
2295                .clone()
2296                .oneshot(get(&format!(
2297                    "/xrpc/com.atproto.repo.describeRepo?repo={}",
2298                    hosted_tests::DID
2299                )))
2300                .await
2301                .unwrap();
2302            assert_eq!(description.status(), StatusCode::OK, "legacy={legacy}");
2303            let body = axum::body::to_bytes(description.into_body(), 65536)
2304                .await
2305                .unwrap();
2306            let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
2307            assert_eq!(body["did"], hosted_tests::DID);
2308            assert_eq!(body["collections"], serde_json::json!([]));
2309            let genesis = store.snapshot(hosted_tests::DID).unwrap().unwrap().commit;
2310            let exported = app
2311                .clone()
2312                .oneshot(get(&format!(
2313                    "/xrpc/com.atproto.sync.getRepo?did={}",
2314                    hosted_tests::DID
2315                )))
2316                .await
2317                .unwrap();
2318            assert_eq!(exported.status(), StatusCode::OK);
2319            assert!(!axum::body::to_bytes(exported.into_body(), 2 * 1024 * 1024)
2320                .await
2321                .unwrap()
2322                .is_empty());
2323            let record = writer
2324                .create_record(
2325                    hosted_tests::request(1),
2326                    Some(&genesis.cid_atproto().unwrap().to_string()),
2327                )
2328                .await
2329                .unwrap();
2330            let snapshot = store.snapshot(hosted_tests::DID).unwrap().unwrap();
2331            assert_eq!(snapshot.commit.prev, Some(genesis.cid_atproto().unwrap()));
2332            assert_eq!(snapshot.commit.cid_atproto().unwrap(), record.commit_cid);
2333            let get_record = app.oneshot(get(&format!("/xrpc/com.atproto.repo.getRecord?repo={}&collection=app.bsky.feed.post&rkey=post-1", hosted_tests::DID))).await.unwrap();
2334            assert_eq!(get_record.status(), StatusCode::OK);
2335            let records = audit.0.lock();
2336            let artifacts: &[&str] = if legacy {
2337                &["repo/commit.cbor", hyprstream_pds::ATPROTO_SIGNING_KEY_FILE]
2338            } else {
2339                &[
2340                    "repo/commit.cbor",
2341                    "repo/public-commit.cbor",
2342                    hyprstream_pds::ATPROTO_SIGNING_KEY_FILE,
2343                ]
2344            };
2345            for artifact in artifacts {
2346                let path = format!("/pds/accounts.example.com/accounts/alice/{artifact}");
2347                assert!(
2348                    records
2349                        .iter()
2350                        .any(|record| record.object_id.as_deref() == Some(path.as_str())
2351                            && record.subject_id.as_deref()
2352                                == Some(hyprstream_pds_service::OAUTH_ACCOUNT_RESOLVER_SUBJECT)
2353                            && record.reason == DecisionReason::Permit),
2354                    "missing actual audited permit: {path}"
2355                );
2356            }
2357            assert!(records
2358                .iter()
2359                .all(|record| record.reason == DecisionReason::Permit));
2360        }
2361    }
2362
2363    #[tokio::test]
2364    async fn minted_hosted_account_is_browser_resolvable_from_authority_storage() {
2365        use tower::ServiceExt;
2366
2367        let mut fixture = production_router_fixture();
2368        let session_id = fixture
2369            .state
2370            .sessions
2371            .create("did:web:member.example".to_owned(), "local".to_owned())
2372            .await;
2373        let response = super::super::create_app(Arc::clone(&fixture.state), &fixture.cors)
2374            .oneshot(post(
2375                "/api/identity/register",
2376                r#"{"handle":"alice"}"#,
2377                Some(format!("{}={session_id}", session::SESSION_COOKIE_NAME)),
2378                None,
2379            ))
2380            .await
2381            .unwrap();
2382        assert_eq!(response.status(), StatusCode::OK);
2383
2384        let identity_resolver = Arc::new(HostedConnectTimeResolver {
2385            pds_root: fixture.storage.path().join("pds"),
2386            zone: AccountZone::new("accounts.example.com").unwrap(),
2387            live_discovery: Arc::new(ConfiguredHostedPdsDiscovery {
2388                pds_endpoint: "https://pds.example.test".to_owned(),
2389                quic: fixture.quic.clone(),
2390            }),
2391        });
2392        assert!(!identity_resolver.recognizes("did:web:foreign.example"));
2393        let api = IdentityRegistrationApi::new(
2394            Arc::new(FakeMint {
2395                calls: AtomicUsize::new(0),
2396            }),
2397            Arc::new(FakeSigner),
2398            Arc::new(CountingIntake {
2399                calls: AtomicUsize::new(0),
2400            }),
2401            identity_resolver,
2402            DidWebOriginAllowlist::new(["https://foreign.example"]).unwrap(),
2403            Arc::new(RateLimiter::new(10, 60)),
2404        );
2405        Arc::get_mut(&mut fixture.state)
2406            .unwrap()
2407            .identity_registration_api = Some(Arc::new(api));
2408
2409        let response = super::super::create_app(Arc::clone(&fixture.state), &fixture.cors)
2410            .oneshot(get(
2411                "/api/identity/resolve?did=did:web:alice.accounts.example.com",
2412            ))
2413            .await
2414            .unwrap();
2415        assert_eq!(response.status(), StatusCode::OK);
2416        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
2417            .await
2418            .unwrap();
2419        let resolved: ConnectTimeDiscovery = serde_json::from_slice(&body).unwrap();
2420        assert_eq!(resolved.quic_url(), "https://pds.example.test:4433");
2421        assert!(!resolved.cert_hash().is_empty());
2422    }
2423
2424    #[tokio::test]
2425    async fn production_composition_live_global_manual_register_mints() {
2426        use tower::ServiceExt;
2427
2428        let fixture = production_router_fixture();
2429        let now = chrono::Utc::now().timestamp();
2430        let claims = hyprstream_rpc::auth::Claims::new(
2431            "service:identity-operator".to_owned(),
2432            now,
2433            now + 60,
2434        )
2435        .with_issuer("https://pds.example.test".to_owned())
2436        .with_audience(Some("https://pds.example.test".to_owned()))
2437        .with_client_id("hyprstream-oauth-client-1");
2438        let token = hyprstream_rpc::auth::jwt::encode(&claims, &fixture.signing_key);
2439        let response = super::super::create_app(Arc::clone(&fixture.state), &fixture.cors)
2440            .oneshot(post(
2441                "/api/identity/register/manual",
2442                r#"{"handle":"operator"}"#,
2443                None,
2444                Some(&token),
2445            ))
2446            .await
2447            .unwrap();
2448        assert_eq!(response.status(), StatusCode::OK);
2449        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
2450            .await
2451            .unwrap();
2452        let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
2453        assert_eq!(value["did"], "did:web:operator.accounts.example.com");
2454        assert!(fixture
2455            .storage
2456            .path()
2457            .join("pds/accounts.example.com/accounts/operator/account-record.cbor")
2458            .is_file());
2459    }
2460
2461    #[tokio::test]
2462    async fn production_composition_live_allowlisted_intake_indexes_identity() {
2463        use tower::ServiceExt;
2464
2465        let fixture = production_router_fixture();
2466        let session_id = fixture
2467            .state
2468            .sessions
2469            .create_atproto(
2470                "did:web:member.example".to_owned(),
2471                Some("accounts.example.com".to_owned()),
2472            )
2473            .await;
2474        let response = super::super::create_app(Arc::clone(&fixture.state), &fixture.cors)
2475            .oneshot(post(
2476                "/api/identity/intake",
2477                r#"{"did":"did:web:foreign.example"}"#,
2478                Some(format!("{}={session_id}", session::SESSION_COOKIE_NAME)),
2479                None,
2480            ))
2481            .await
2482            .unwrap();
2483        assert_eq!(response.status(), StatusCode::OK);
2484        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
2485            .await
2486            .unwrap();
2487        let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
2488        assert_eq!(value["did"], "did:web:foreign.example");
2489        assert_eq!(value["handle"], "foreign.example");
2490        assert_eq!(value["kind"], "federated");
2491        assert!(value["tenant"].is_null());
2492        assert_eq!(value["pdsEndpoint"], "https://foreign.example");
2493    }
2494}