Skip to main content

hyprstream_core/services/oauth/
mod.rs

1//! OAuth 2.1 Authorization Server for hyprstream.
2//!
3//! Provides OAuth 2.1 (draft-ietf-oauth-v2-1-13) authorization serving both
4//! MCP (:6790) and OAI (:6789) as protected resources.
5//!
6//! # Standards
7//!
8//! - OAuth 2.1 (draft-ietf-oauth-v2-1-13)
9//! - RFC 8414 (Authorization Server Metadata)
10//! - RFC 7591 (Dynamic Client Registration)
11//! - RFC 8707 (Resource Indicators)
12//! - RFC 8628 (Device Authorization Grant)
13//! - RFC 9728 (Protected Resource Metadata)
14//! - Client ID Metadata Documents (draft-ietf-oauth-client-id-metadata-document-00)
15//!
16//! # Architecture
17//!
18//! ```text
19//! OAuth Server (:6791)
20//!   /.well-known/oauth-authorization-server  → metadata
21//!   /oauth/register                          → dynamic registration
22//!   /oauth/authorize                         → consent + auth code
23//!   /oauth/token                             → PKCE + PolicyClient delegation
24//!   /oauth/jwks                              → JSON Web Key Set (RFC 7517)
25//!   /oauth/device                            → device authorization (RFC 8628)
26//!   /oauth/device/verify                     → user verification page
27//! ```
28
29mod account_tls;
30mod account_worker;
31
32pub(crate) mod atproto_session;
33pub mod auth;
34pub mod authorize;
35pub mod browser_session;
36pub mod challenge;
37pub mod cimd_cache;
38pub mod client_auth;
39pub mod deployment_well_known;
40pub mod device;
41pub mod device_enrollment;
42pub mod did_document;
43pub mod dpop;
44pub mod federation_entity;
45// Exact Federate routes deny until the authenticated Policy runtime is installed.
46#[allow(dead_code)]
47pub(crate) mod federate_exchange;
48pub(crate) mod federate_host;
49#[cfg(feature = "postgres")]
50pub(crate) mod federate_policy;
51#[allow(dead_code)]
52pub(crate) mod federate_source;
53// H3b.1 proof primitive only: no constructor installs its authority provider.
54#[cfg(feature = "postgres")]
55#[allow(dead_code)]
56pub(crate) mod federate_proof;
57pub mod identity_registration;
58pub mod introspection;
59pub mod jwks;
60pub mod jwt_bearer;
61pub mod login_page;
62pub mod metadata;
63pub mod mount_ticket;
64pub mod oauth2_userinfo;
65pub mod oidc_callback;
66pub mod oidc_discovery;
67pub mod par;
68mod public_git;
69pub mod registration;
70pub mod replay_key;
71pub mod replay_metrics;
72pub mod revocation;
73pub mod rpc_handler;
74pub mod scim;
75pub mod scim_types;
76pub mod session;
77pub mod spiffe;
78pub mod state;
79pub mod token;
80pub mod token_exchange;
81pub mod token_store;
82pub mod user_mapping;
83pub mod user_service;
84pub mod userinfo;
85pub mod wit_bootstrap;
86pub mod xrpc;
87
88use std::{net::SocketAddr, path::PathBuf, sync::Arc};
89
90use anyhow::Result;
91use axum::{
92    extract::State,
93    response::IntoResponse,
94    routing::{get, post},
95    Router,
96};
97use hyprstream_rpc::registry::SocketKind;
98use hyprstream_rpc::transport::iroh_rpc::LocalServiceBridge;
99use hyprstream_rpc::transport::TransportConfig;
100use hyprstream_service::Spawnable;
101use tokio::sync::Notify;
102use tracing::info;
103
104use crate::config::{CredentialsBackend, OAuthConfig};
105use hyprstream_rpc_std::policy_client::PolicyClient;
106use state::OAuthState;
107
108/// Service name for registry and logging
109pub const SERVICE_NAME: &str = "oauth";
110
111/// Use only this OAuth instance's enrolled credential. Native clients retain
112/// their existing renewing provider; the initial token enables that provider.
113pub(crate) fn runtime_policy_client(
114    transport: &TransportConfig,
115    signing_key: hyprstream_rpc::crypto::SigningKey,
116    policy_vk: hyprstream_rpc::crypto::VerifyingKey,
117) -> Result<PolicyClient> {
118    let token = crate::services::factories::service_token(&signing_key)
119        .ok_or_else(|| anyhow::anyhow!("OAuth has no enrolled service credential"))?;
120    if hyprstream_discovery::native_network_required() {
121        PolicyClient::from_provider(
122            &hyprstream_discovery::ProductionRpcClientProvider,
123            signing_key,
124            Some(token),
125        )
126    } else {
127        anyhow::ensure!(
128            matches!(
129                &transport.endpoint,
130                hyprstream_rpc::transport::EndpointType::Inproc { .. }
131                    | hyprstream_rpc::transport::EndpointType::Ipc { .. }
132                    | hyprstream_rpc::transport::EndpointType::SystemdFd { .. }
133            ),
134            "local bootstrap refuses network transport; use the identity-bound provider",
135        );
136        let key = signing_key.verifying_key();
137        let provider = Arc::new(move || {
138            hyprstream_service::global_trust_store()
139                .get(&key)
140                .and_then(|attestation| attestation.jwt)
141        });
142        let rpc = hyprstream_rpc::dial::dial_with_token_provider(
143            transport,
144            hyprstream_rpc::signer::LocalSigner::new(signing_key),
145            Some(policy_vk),
146            Some(provider),
147        )?;
148        Ok(PolicyClient::new(rpc))
149    }
150}
151
152/// Discovery calls use this OAuth instance's enrolled credential. Native
153/// resolution refreshes it from the trust store for each dial; the local
154/// transport uses the same signer-bound renewal source for each request.
155pub(crate) fn runtime_discovery_client(
156    transport: &TransportConfig,
157    signing_key: hyprstream_rpc::crypto::SigningKey,
158    discovery_vk: hyprstream_rpc::crypto::VerifyingKey,
159) -> Result<hyprstream_rpc_std::discovery_client::DiscoveryClient> {
160    let token = crate::services::factories::service_token(&signing_key)
161        .ok_or_else(|| anyhow::anyhow!("OAuth has no enrolled service credential"))?;
162    if hyprstream_discovery::native_network_required() {
163        hyprstream_rpc_std::discovery_client::DiscoveryClient::from_provider(
164            &hyprstream_discovery::ProductionRpcClientProvider,
165            signing_key,
166            Some(token),
167        )
168    } else {
169        anyhow::ensure!(
170            matches!(
171                &transport.endpoint,
172                hyprstream_rpc::transport::EndpointType::Inproc { .. }
173                    | hyprstream_rpc::transport::EndpointType::Ipc { .. }
174                    | hyprstream_rpc::transport::EndpointType::SystemdFd { .. }
175            ),
176            "local bootstrap refuses network transport; use the identity-bound provider",
177        );
178        let key = signing_key.verifying_key();
179        let provider = Arc::new(move || {
180            hyprstream_service::global_trust_store()
181                .get(&key)
182                .and_then(|attestation| attestation.jwt)
183        });
184        let rpc = hyprstream_rpc::dial::dial_with_token_provider(
185            transport,
186            hyprstream_rpc::signer::LocalSigner::new(signing_key),
187            Some(discovery_vk),
188            Some(provider),
189        )?;
190        Ok(hyprstream_rpc_std::discovery_client::DiscoveryClient::new(
191            rpc,
192        ))
193    }
194}
195
196/// Create the OAuth Axum router.
197///
198/// CORS is outermost (applied last) so OPTIONS preflights are handled before
199/// any inner middleware (like logging) runs. This fixes the previous ordering
200/// where logging was outermost and CORS was inner.
201pub fn create_app(state: Arc<OAuthState>, cors_config: &crate::config::CorsConfig) -> Router {
202    // The public TLS hostname terminates on OAuth. Keep this one bootstrap
203    // route independently rate-limited before accepted-state resolution.
204    let browser_provisioning_router = Router::new()
205        .route(
206            "/.well-known/hyprstream/browser-provisioning/:service",
207            get(crate::server::routes::browser_provisioning::oauth_browser_provisioning),
208        )
209        .layer(axum::middleware::from_fn_with_state(
210            Arc::clone(&state.browser_provisioning_rate_limiter),
211            crate::server::middleware::browser_provisioning_rate_limit_middleware,
212        ));
213    // ── Public routes ──────────────────────────────────────────────────────────
214    // No Bearer token required. Includes all OAuth flow endpoints (clients are
215    // unauthenticated when they arrive) and SCIM discovery (RFC 7644 §4).
216    let public_router = Router::new()
217        .route(
218            "/.well-known/oauth-authorization-server",
219            get(metadata::authorization_server_metadata),
220        )
221        .route(
222            "/.well-known/oauth-protected-resource",
223            get(oauth_self_protected_resource_metadata),
224        )
225        .route(
226            "/.well-known/openid-configuration",
227            get(metadata::openid_configuration),
228        )
229        .route("/.well-known/spiffe/bundle", get(spiffe::spiffe_bundle))
230        .route(
231            "/.well-known/openid-federation",
232            get(federation_entity::entity_configuration),
233        )
234        .route("/oauth/register", post(registration::register_client))
235        .route(
236            "/xrpc/ai.hyprstream.identity.exchangeUcan",
237            post(token_exchange::exchange_atproto_ucan),
238        )
239        .route(
240            "/api/identity/resolve",
241            get(identity_registration::resolve_identity),
242        )
243        .route(
244            "/oauth/authorize",
245            get(authorize::authorize_get).post(authorize::authorize_post),
246        )
247        .route("/oauth/par", post(par::push_authorization_request))
248        .route("/oauth/federate/challenge", post(federate_host::challenge))
249        .route("/oauth/token", post(token::exchange_token))
250        .route("/oauth/spiffe/wit", post(spiffe::exchange_workload_wit))
251        .route("/oauth/jwks", get(jwks::jwks))
252        .route("/oauth/device", post(device::device_authorize))
253        .route(
254            "/oauth/device/verify",
255            get(device::verify_get).post(device::verify_post),
256        )
257        .route("/oauth/device/nonce", get(device::device_nonce))
258        .route(
259            "/api/device/challenge",
260            post(device_enrollment::device_challenge_handler),
261        )
262        .route(
263            "/api/device/enroll",
264            post(device_enrollment::device_enroll_handler),
265        )
266        .route("/oauth/revoke", post(revocation::revoke_token))
267        .route("/oauth/logout", post(handle_logout))
268        .route(
269            browser_session::SESSION_EXCHANGE_PATH,
270            post(browser_session::exchange),
271        )
272        .route(browser_session::WHOAMI_PATH, get(browser_session::whoami))
273        .route(
274            "/oauth/external/authorize/:provider",
275            post(oidc_callback::external_authorize),
276        )
277        .route(
278            "/oauth/callback/:provider",
279            get(oidc_callback::external_callback),
280        )
281        // SCIM discovery endpoints — RFC 7644 §4 requires these to be unauthenticated
282        .route("/scim/v2/Schemas", get(scim::schemas))
283        .route("/scim/v2/ResourceTypes", get(scim::resource_types))
284        .route(
285            "/scim/v2/ServiceProviderConfig",
286            get(scim::service_provider_config),
287        );
288
289    // ── com.atproto XRPC read slice (#1112) ────────────────────────────────
290    // Four public read endpoints, conditionally mounted when the operator
291    // opts in via `OAuthConfig::xrpc_read_slice`. Session endpoints
292    // (createSession/getSession) are NOT here — they arrive with #1113/#948.
293    // Route table lives in `xrpc::xrpc_routes()` — single source of truth.
294    let public_router = if state.xrpc_read_slice {
295        public_router.merge(xrpc::xrpc_routes())
296    } else if state.public_git_canary_record.is_some() {
297        // Keep the wider hosted-account XRPC slice disabled. This route can
298        // answer only the exact configured Registry model record.
299        public_router.merge(xrpc::public_canary_routes())
300    } else {
301        public_router
302    };
303    // The narrow canary route is independent from ATProto XRPC reads. It is
304    // absent unless an operator configures the loopback Git backend port.
305    let public_router = match state
306        .public_git_canary_backend_port
307        .filter(|port| *port != 0)
308    {
309        Some(port) => public_router.merge(public_git::routes(port)),
310        None => public_router,
311    };
312
313    // ── Protected routes ───────────────────────────────────────────────────────
314    // All require a valid Bearer/DPoP token (validated by require_bearer_token).
315    // Inserts AuthenticatedUser into request extensions for downstream handlers.
316    let authority_router = Router::new()
317        .route(
318            "/api/identity/register/manual",
319            post(identity_registration::register_operator_manual),
320        )
321        .route(
322            "/oauth/spiffe/service-svid",
323            post(spiffe::issue_service_svid),
324        )
325        // SCIM 2.0 user management (RFC 7644)
326        .route(
327            "/scim/v2/Users",
328            get(scim::list_users).post(scim::create_user),
329        )
330        .route(
331            "/scim/v2/Users/:id",
332            get(scim::get_user)
333                .put(scim::replace_user)
334                .delete(scim::delete_user),
335        )
336        .route(
337            "/scim/v2/Users/:id/keys",
338            get(scim::list_user_keys).post(scim::add_user_key),
339        )
340        .route(
341            "/scim/v2/Users/:id/keys/:fingerprint",
342            axum::routing::delete(scim::remove_user_key),
343        )
344        .layer(axum::middleware::from_fn(
345            auth::require_global_service_authority,
346        ));
347
348    let protected_routes = Router::new()
349        .route(xrpc::GET_SERVICE_AUTH_PATH, get(xrpc::get_service_auth))
350        .route("/oauth/introspect", post(introspection::introspect_token))
351        .route("/oauth/wit", post(wit_bootstrap::issue_browser_wit))
352        .route(
353            "/oauth/mount-ticket",
354            post(mount_ticket::issue_mount_ticket),
355        )
356        .route(
357            "/oauth/userinfo",
358            get(userinfo::userinfo).post(userinfo::userinfo),
359        )
360        .merge(authority_router)
361        .merge(
362            if state.public_repo_writer.is_some() || state.hosted_public_repo_writer.is_some() {
363                xrpc::xrpc_write_routes()
364            } else {
365                Router::new()
366            },
367        )
368        .merge(if state.atproto_session_resolver.is_some() {
369            xrpc::xrpc_session_routes()
370        } else {
371            Router::new()
372        });
373
374    let protected_router = protected_routes.layer(axum::middleware::from_fn_with_state(
375        Arc::clone(&state),
376        auth::require_bearer_token,
377    ));
378
379    // Browser identity mutations authenticate with the server-side login
380    // session. This is separate from the tenant-requiring bearer middleware:
381    // registration is the onboarding step that creates the authority-owned
382    // hosted-account tenant binding.
383    let self_service_identity_router = Router::new()
384        .route(
385            "/api/identity/register",
386            post(identity_registration::register_self_service),
387        )
388        .route(
389            "/api/identity/federate/link",
390            post(oidc_callback::begin_federate_owner_link),
391        )
392        .layer(axum::Extension(cors_config.allowed_origins.clone()))
393        .layer(axum::middleware::from_fn_with_state(
394            Arc::clone(&state),
395            identity_registration::require_registration_session,
396        ))
397        .merge(
398            Router::new()
399                .route(
400                    "/api/identity/intake",
401                    post(identity_registration::intake_federated_identity),
402                )
403                .layer(axum::middleware::from_fn_with_state(
404                    Arc::clone(&state),
405                    identity_registration::require_local_intake_session,
406                )),
407        );
408
409    // ── DID-document routes ──────────────────────────────────────────────────────
410    // Public, secret-free GET endpoints (did:web + atproto handle resolution).
411    // Per W3C DID Core a DID document is an open identity anchor that must be
412    // fetchable cross-origin with arbitrary request headers, so these get their own
413    // permissive-header CORS layer (CorsConfig::did_document) — kept separate from
414    // the broad public router so the relaxation never reaches secret-bearing
415    // endpoints like /oauth/token (closes #472).
416    let mut did_router = Router::new();
417    if state.deployment_well_known_dir.is_some() {
418        // #1137 serving half — deployment mode: this host terminates the
419        // deployment's did:web. The static router owns `/.well-known/did.json`
420        // plus the at9p capsule, authority log, and registry credential
421        // endpoints (each 404s when its file is absent — never a silent
422        // fall-through).
423        did_router = did_router.merge(deployment_well_known::router(
424            state.deployment_well_known_dir.clone(),
425        ));
426    } else {
427        did_router = did_router
428            .route(
429                "/.well-known/did.json",
430                get(did_document::root_did_document),
431            )
432            .route(
433                "/.well-known/at9p/:cid.cbor",
434                get(did_document::at9p_capsule),
435            );
436    }
437    let mut did_router = did_router
438        // atproto handle→DID HTTP resolution (#500) — plaintext bare DID
439        .route("/.well-known/atproto-did", get(did_document::atproto_did))
440        .route(
441            "/users/:username/did.json",
442            get(did_document::user_did_document),
443        )
444        .route(
445            "/clients/:client_id/did.json",
446            get(did_document::client_did_document),
447        );
448
449    let mut api_router = public_router
450        .merge(browser_provisioning_router)
451        .merge(protected_router)
452        .merge(self_service_identity_router);
453
454    // CORS innermost per route-group, before the shared logging layer.
455    // The broad router keeps the restrictive header allowlist; only the DID routes
456    // opt into permissive headers, and only their paths carry that CORS layer.
457    if cors_config.enabled {
458        api_router = api_router.layer(crate::server::middleware::cors_layer(cors_config));
459        did_router = did_router.layer(crate::server::middleware::cors_layer(
460            &crate::config::CorsConfig::did_document(),
461        ));
462    }
463
464    let router = api_router
465        .merge(did_router)
466        .layer(axum::middleware::from_fn(
467            |req: axum::extract::Request, next: axum::middleware::Next| async move {
468                let method = req.method().clone();
469                let uri = req.uri().clone();
470                tracing::info!(%method, %uri, "OAuth request");
471                next.run(req).await
472            },
473        ));
474
475    router.with_state(state)
476}
477
478/// POST /oauth/logout — clear session and redirect.
479async fn handle_logout(
480    State(state): State<Arc<OAuthState>>,
481    headers: axum::http::HeaderMap,
482) -> axum::response::Response {
483    if let Some(session_id) = session::extract_session_id(&headers) {
484        state.sessions.remove(&session_id).await;
485    }
486    (
487        axum::http::StatusCode::OK,
488        [(
489            axum::http::header::SET_COOKIE,
490            session::clear_session_cookie(),
491        )],
492        "Logged out",
493    )
494        .into_response()
495}
496
497/// RFC 9728 Protected Resource Metadata for the OAuth server itself.
498///
499/// Returns the DiscoveryService QUIC endpoint as the `resource` URL so that
500/// browsers can bootstrap a WebTransport connection via DiscoveryService,
501/// then resolve all other service endpoints from there.
502async fn oauth_self_protected_resource_metadata(
503    State(state): State<Arc<OAuthState>>,
504) -> axum::Json<ProtectedResourceMetadata> {
505    // #1113 r4 F5: use the CANONICAL issuer from OAuthState (same
506    // normalization as token claims/redirect), NOT raw config.issuer_url().
507    // A configured trailing-slash/path must be consistent everywhere.
508    let issuer_url = state.atproto_issuer_url();
509
510    // Use issuer URL as the resource (PDS = its own AS).
511    let resource = issuer_url.clone();
512
513    let mut meta = protected_resource_metadata(&resource, &issuer_url);
514    meta.resource_name = Some("HyprStream OAuth 2.1 Authorization Server".to_owned());
515    meta.scopes_supported = Some(self_resource_scopes());
516
517    // Include the QUIC TLS cert hash so browsers can pin the self-signed certificate.
518    let config = crate::config::HyprConfig::load().unwrap_or_default();
519    if let Ok((cert_chain, _)) = config.quic.load_tls_materials() {
520        meta.x_cert_hash = Some(hyprstream_rpc::transport::zmtp_quic::cert_hash(
521            &cert_chain[0],
522        ));
523    }
524
525    axum::Json(meta)
526}
527
528/// Scopes advertised by the OAuth service's own RFC 9728 protected-resource
529/// document. Includes the atproto transition scopes (#1113) so stock atproto
530/// clients can discover them at the resource (PDS = its own AS).
531fn self_resource_scopes() -> Vec<String> {
532    vec![
533        "openid".into(),
534        "read:*:*".into(),
535        "write:*:*".into(),
536        "infer:model:*".into(),
537        "pds:attach".into(),
538        "atproto".into(),
539        "transition:generic".into(),
540    ]
541}
542
543/// OAuth 2.1 Authorization Server service.
544///
545/// Runs an Axum HTTP server with OAuth endpoints. Token issuance is delegated
546/// to PolicyService via ZMQ.
547///
548/// **Important**: The PolicyClient is created lazily inside `run()` rather than
549/// in the factory. This is because OAuthService runs in its own tokio runtime
550/// (separate thread), and ZMQ async I/O (TMQ) registers socket file descriptors
551/// with the current runtime's epoll. A PolicyClient created in the main runtime
552/// would hang when polled from the OAuth runtime.
553/// Build the OAuth service's reach-only iroh endpoint.
554///
555/// Both inbound ALPNs are refused until #1027/#726 supplies independently
556/// verified application/session proof. In particular, the local user-CRUD
557/// handler is never installed behind `AnySigner`, and anonymous MoQ peers never
558/// receive the process-global origin. The endpoint remains usable as the shared
559/// outbound dialer. Native-only.
560#[cfg(test)]
561#[cfg(test)]
562async fn build_oauth_iroh_substrate(
563    transport_secret: [u8; 32],
564) -> anyhow::Result<hyprstream_rpc::transport::iroh_substrate::IrohSubstrate> {
565    use hyprstream_rpc::transport::iroh_substrate::{IrohSubstrate, RefuseHandler};
566
567    // `presets::N0` discovery (pkarr publisher + n0 DNS) is enabled by
568    // `IrohSubstrate::new`; that reach state grants no inbound authority.
569    IrohSubstrate::new(
570        transport_secret,
571        RefuseHandler::new("OAuth MoQ disabled pending verified session proof (#1027/#726)"),
572        RefuseHandler::new("OAuth RPC disabled pending verified application proof (#1027)"),
573    )
574    .await
575}
576
577async fn warm_hosted_did_index(
578    store: Arc<hyprstream_pds_service::AccountRecordStore>,
579    authority: hyprstream_rpc::Subject,
580    timeout: std::time::Duration,
581) -> Result<(), hyprstream_rpc::error::RpcError> {
582    let mut worker =
583        account_worker::ContainedWorker::spawn("hyprstream-oauth-index-warmup", move || {
584            let runtime = tokio::runtime::Builder::new_current_thread()
585                .enable_all()
586                .build()
587                .map_err(|error| format!("warm-up runtime: {error}"))?;
588            runtime
589                .block_on(store.refresh_hosted_did_index(&authority))
590                .map_err(|error| format!("index refresh: {error}"))
591        })?;
592    worker.finish(timeout).await?.map_err(|error| {
593        hyprstream_rpc::error::RpcError::SpawnFailed(format!(
594            "hosted account index warm-up failed: {error}"
595        ))
596    })
597}
598
599pub(super) async fn refresh_hosted_did_index_after_publish(
600    store: Arc<hyprstream_pds_service::AccountRecordStore>,
601    authority: hyprstream_rpc::Subject,
602    timeout: std::time::Duration,
603) -> Result<(), hyprstream_rpc::error::RpcError> {
604    let mut worker = account_worker::ContainedWorker::spawn(
605        "hyprstream-oauth-index-publish-refresh",
606        move || {
607            let runtime = tokio::runtime::Builder::new_current_thread()
608                .enable_all()
609                .build()
610                .map_err(|error| format!("post-publish runtime: {error}"))?;
611            runtime
612                .block_on(store.refresh_hosted_did_index_after_publish(&authority))
613                .map_err(|error| format!("post-publish index refresh: {error}"))
614        },
615    )?;
616    worker.finish(timeout).await?.map_err(|error| {
617        hyprstream_rpc::error::RpcError::SpawnFailed(format!(
618            "hosted account index refresh after publish failed: {error}"
619        ))
620    })
621}
622
623/// Profile-aware bind of OAuth's inbound reach-only substrate, using the
624/// production substrate builder. See [`bind_oauth_substrate_profile`] — the
625/// builder is a parameter only so causal tests can inject a bind failure at
626/// this exact production boundary.
627#[cfg(test)]
628#[cfg(test)]
629async fn build_oauth_substrate_profile(
630    signing_key: &ed25519_dalek::SigningKey,
631    iroh_required: bool,
632) -> Result<
633    Option<hyprstream_rpc::transport::iroh_substrate::IrohSubstrate>,
634    hyprstream_rpc::error::RpcError,
635> {
636    let signing_key = signing_key.clone();
637    bind_oauth_substrate_profile(iroh_required, move || async move {
638        let transport_key = hyprstream_rpc::node_identity::derive_purpose_key(
639            &signing_key,
640            "hyprstream-iroh-transport-v1",
641        );
642        build_oauth_iroh_substrate(transport_key.to_bytes()).await
643    })
644    .await
645}
646
647/// Bind POLICY for OAuth's inbound reach-only substrate: Required treats a
648/// bind failure as fatal before READY (the child exits nonzero and the
649/// supervised launcher rolls the spawn back); Compatibility warns and
650/// continues without Iroh (documented degraded mode). Bind policy lives here,
651/// separate from the install disposition ([`classify_oauth_endpoint_install`])
652/// so "mandatory local bind" cannot regress into "must replace the global
653/// dialer".
654#[cfg(test)]
655#[cfg(test)]
656async fn bind_oauth_substrate_profile<F, Fut>(
657    iroh_required: bool,
658    build: F,
659) -> Result<
660    Option<hyprstream_rpc::transport::iroh_substrate::IrohSubstrate>,
661    hyprstream_rpc::error::RpcError,
662>
663where
664    F: FnOnce() -> Fut,
665    Fut: std::future::Future<
666        Output = anyhow::Result<hyprstream_rpc::transport::iroh_substrate::IrohSubstrate>,
667    >,
668{
669    match build().await {
670        Ok(substrate) => Ok(Some(substrate)),
671        Err(e) if iroh_required => Err(hyprstream_rpc::error::RpcError::SpawnFailed(format!(
672            "network-iroh-required OAuth iroh substrate bind failed: {e:#}"
673        ))),
674        Err(e) => {
675            tracing::warn!(
676                "OAuth iroh substrate bind failed; continuing without iroh (Compatibility): {e:#}"
677            );
678            Ok(None)
679        }
680    }
681}
682
683/// Disposition of the process-global client-endpoint install for OAuth's
684/// bound substrate. `install_iroh_client_endpoint` is first-write-wins, so an
685/// occupied slot means a DIFFERENT valid endpoint — in real Required startup,
686/// the authenticated OS-owned bootstrap outbound carrier
687/// (`PROCESS_BOOTSTRAP_CARRIER`) — already owns outbound dials. Both outcomes
688/// are valid and expected; neither is ever a startup error. The two carriers'
689/// endpoint IDs are deliberately different (distinct transport purpose keys)
690/// and are never compared; the OAuth substrate is retained in both cases and
691/// the existing global endpoint is never reset or replaced.
692enum OAuthEndpointInstall {
693    /// The empty process-global slot was won by this substrate's endpoint.
694    InstalledHere,
695    /// A previously-installed global endpoint remains the outbound dialer;
696    /// the returned capability clone is dropped and OAuth's substrate stays
697    /// the independent inbound owner.
698    ExistingGlobalRetained,
699}
700
701fn classify_oauth_endpoint_install(
702    substrate: &hyprstream_rpc::transport::iroh_substrate::IrohSubstrate,
703) -> OAuthEndpointInstall {
704    match hyprstream_rpc::transport::lazy_iroh::install_iroh_client_endpoint(
705        substrate.owned_client_endpoint(),
706    ) {
707        Ok(()) => OAuthEndpointInstall::InstalledHere,
708        Err(returned) => {
709            drop(returned);
710            OAuthEndpointInstall::ExistingGlobalRetained
711        }
712    }
713}
714
715pub struct OAuthService {
716    config: OAuthConfig,
717    /// Global TLS configuration (passed from factory, avoids re-loading config)
718    tls_config: crate::config::TlsConfig,
719    /// Account-zone configuration (epic #1158, A3) — used for DNS-01 wildcard
720    /// TLS provisioning.
721    account_config: crate::account::AccountZoneConfig,
722    /// Global QUIC configuration for cert-hash publication in DID doc (#185).
723    quic_config: Option<crate::config::QuicConfig>,
724    /// Signing key for creating RPC clients inside `run()`.
725    signing_key: hyprstream_rpc::prelude::SigningKey,
726    control_transport: TransportConfig,
727    /// Policy transport resolved by the factory. This is an IPC socket when
728    /// OAuth runs in its own rootless Quadlet process.
729    policy_transport: TransportConfig,
730    /// Discovery transport resolved by the factory. This is an IPC socket when
731    /// OAuth runs in its own rootless Quadlet process.
732    discovery_transport: TransportConfig,
733    #[allow(dead_code)]
734    verifying_key: ed25519_dalek::VerifyingKey,
735    /// JWT verifying key (CA key) for JWKS endpoint. This is the key that verifies
736    /// JWTs signed by PolicyService, derived from the root signing key.
737    jwt_verifying_key: [u8; 32],
738    /// Shared JTI blocklist (same Arc as PolicyService) for cross-plane revocation.
739    /// Authority-owned hosted-account records for ATProto DID → tenant
740    /// resolution. Attached by the PDS service composition layer.
741    hosted_account_store: Option<Arc<hyprstream_pds_service::AccountRecordStore>>,
742    /// Authenticated hosted-account registration and federation-intake face.
743    identity_registration_api: Option<Arc<identity_registration::IdentityRegistrationApi>>,
744    /// Authoritative publication root for the hosted-account tree. Set by the
745    /// production factory so OAuth and the public account listener share one
746    /// descriptor-bound store.
747    pds_root: Option<PathBuf>,
748    dedicated_process: bool,
749    /// Operator-selected canonical 9P read export; forwarded to OAuthState so
750    /// hosted-account signup can seed the HolderGate baseline rows.
751    ninep_canonical_read: Option<crate::config::NinepCanonicalReadConfig>,
752}
753
754impl OAuthService {
755    pub fn new(
756        config: OAuthConfig,
757        tls_config: crate::config::TlsConfig,
758        account_config: crate::account::AccountZoneConfig,
759        signing_key: hyprstream_rpc::prelude::SigningKey,
760        control_transport: TransportConfig,
761        policy_transport: TransportConfig,
762        discovery_transport: TransportConfig,
763        verifying_key: ed25519_dalek::VerifyingKey,
764        jwt_verifying_key: ed25519_dalek::VerifyingKey,
765    ) -> Self {
766        Self {
767            config,
768            tls_config,
769            account_config,
770            quic_config: None,
771            signing_key,
772            control_transport,
773            policy_transport,
774            discovery_transport,
775            verifying_key,
776            jwt_verifying_key: jwt_verifying_key.to_bytes(),
777            hosted_account_store: None,
778            identity_registration_api: None,
779            pds_root: None,
780            dedicated_process: false,
781            ninep_canonical_read: None,
782        }
783    }
784
785    /// Attach the global QUIC configuration for DID-doc cert-hash publication (#185).
786    pub fn with_quic_config(mut self, quic: crate::config::QuicConfig) -> Self {
787        self.quic_config = Some(quic);
788        self
789    }
790
791    /// Attach the PDS hosted-account read service.
792    pub fn with_hosted_account_store(
793        mut self,
794        store: Arc<hyprstream_pds_service::AccountRecordStore>,
795    ) -> Self {
796        self.hosted_account_store = Some(store);
797        self
798    }
799
800    /// Attach the hosted-account registration/intake wire adapter.
801    pub fn with_identity_registration_api(
802        mut self,
803        api: Arc<identity_registration::IdentityRegistrationApi>,
804    ) -> Self {
805        self.identity_registration_api = Some(api);
806        self
807    }
808
809    /// Set only from the launcher's explicit single-service process context.
810    pub(crate) fn with_dedicated_process(mut self, dedicated: bool) -> Self {
811        self.dedicated_process = dedicated;
812        self
813    }
814
815    /// Attach the authoritative published-account root used by production
816    /// OAuth/account HTTP composition.
817    pub fn with_pds_root(mut self, root: PathBuf) -> Self {
818        self.pds_root = Some(root);
819        self
820    }
821
822    /// Attach the operator-selected canonical 9P read export for signup-time
823    /// HolderGate baseline seeding.
824    pub fn with_ninep_canonical_read(
825        mut self,
826        export: Option<crate::config::NinepCanonicalReadConfig>,
827    ) -> Self {
828        self.ninep_canonical_read = export;
829        self
830    }
831}
832
833fn account_http_socket_addr(config: &crate::account::AccountHttpConfig) -> Result<SocketAddr> {
834    // Preserve bracketed IPv6 configurations while accepting bare IP literals.
835    let host = config
836        .host
837        .strip_prefix('[')
838        .and_then(|host| host.strip_suffix(']'))
839        .unwrap_or(&config.host);
840    let ip = host
841        .parse::<std::net::IpAddr>()
842        .map_err(|error| anyhow::anyhow!("invalid account HTTP bind IP: {error}"))?;
843    Ok(SocketAddr::new(ip, config.port))
844}
845
846fn hosted_account_store_requested(config: &crate::account::AccountZoneConfig) -> bool {
847    config.local_store || config.http.is_some()
848}
849
850fn validate_local_store_zone(
851    config: &crate::account::AccountZoneConfig,
852) -> Result<(), hyprstream_rpc::error::RpcError> {
853    if config.local_store {
854        config.resolve_zone().map_err(|error| {
855            hyprstream_rpc::error::RpcError::SpawnFailed(format!(
856                "local hosted account store requires a valid account zone: {error}"
857            ))
858        })?;
859    }
860    Ok(())
861}
862
863fn open_hosted_account_store(
864    account_config: &crate::account::AccountZoneConfig,
865    injected: Option<&Arc<hyprstream_pds_service::AccountRecordStore>>,
866    pds_root: Option<&std::path::Path>,
867    audit_sink: Option<&Arc<dyn crate::mac::audit::AuditSink>>,
868) -> Result<Option<Arc<hyprstream_pds_service::AccountRecordStore>>, hyprstream_rpc::error::RpcError>
869{
870    if let Some(store) = injected {
871        return Ok(Some(Arc::clone(store)));
872    }
873    if !hosted_account_store_requested(account_config) {
874        return Ok(None);
875    }
876    let root = pds_root.ok_or_else(|| {
877        hyprstream_rpc::error::RpcError::SpawnFailed(
878            "hosted account store enabled without a PDS publication root".to_owned(),
879        )
880    })?;
881    let sink = audit_sink.cloned().ok_or_else(|| {
882        hyprstream_rpc::error::RpcError::SpawnFailed(
883            "hosted account store requires a usable MAC audit sink".to_owned(),
884        )
885    })?;
886    let mount = crate::mac::PdsDirectoryMount::open(root).map_err(|error| {
887        hyprstream_rpc::error::RpcError::SpawnFailed(format!(
888            "open published PDS account root {}: {error}",
889            root.display()
890        ))
891    })?;
892    Ok(Some(crate::mac::production_pds_account_record_store(
893        Arc::new(mount),
894        sink,
895    )))
896}
897
898/// Resolve explicitly provisioned TLS material for the public account
899/// listener. Account hosts must never fall back to the node/self-signed
900/// certificate, so enabling the listener requires both PEM paths and a valid
901/// rustls keypair.
902async fn resolve_account_http_tls(
903    config: &crate::account::AccountHttpConfig,
904    zone: &crate::account::AccountZone,
905) -> anyhow::Result<axum_server::tls_rustls::RustlsConfig> {
906    anyhow::ensure!(
907        config.port != 0,
908        "account HTTP listener port must be non-zero"
909    );
910    anyhow::ensure!(
911        config.tls_cert.is_file(),
912        "account TLS certificate is unavailable: {}",
913        config.tls_cert.display()
914    );
915    anyhow::ensure!(
916        config.tls_key.is_file(),
917        "account TLS private key is unavailable: {}",
918        config.tls_key.display()
919    );
920    let cert_pem = tokio::fs::read(&config.tls_cert).await?;
921    let key_pem = tokio::fs::read(&config.tls_key).await?;
922    let cert_der = rustls_pemfile::certs(&mut &cert_pem[..])
923        .next()
924        .ok_or_else(|| anyhow::anyhow!("account TLS certificate contains no certificate"))??;
925    let (_, certificate) = x509_parser::parse_x509_certificate(cert_der.as_ref())
926        .map_err(|error| anyhow::anyhow!("invalid account TLS certificate: {error}"))?;
927    let wildcard = zone.wildcard_domain();
928    let covers_zone = certificate.extensions().iter().any(|extension| {
929        matches!(
930            extension.parsed_extension(),
931            x509_parser::extensions::ParsedExtension::SubjectAlternativeName(names)
932                if names.general_names.iter().any(|name| matches!(
933                    name,
934                    x509_parser::extensions::GeneralName::DNSName(dns)
935                        if dns.eq_ignore_ascii_case(wildcard)
936                ))
937        )
938    });
939    anyhow::ensure!(
940        covers_zone,
941        "account TLS certificate does not cover account zone wildcard {wildcard}"
942    );
943    // Validate and install the same bytes, including during rotation. Reopening
944    // the paths here could install a different certificate than the SAN check.
945    axum_server::tls_rustls::RustlsConfig::from_pem(cert_pem, key_pem)
946        .await
947        .map_err(|error| {
948            anyhow::anyhow!(
949                "failed to load account-zone TLS for {}: {error}",
950                zone.wildcard_domain()
951            )
952        })
953}
954
955#[cfg(test)]
956fn runtime_clients(
957    signing_key: &ed25519_dalek::SigningKey,
958) -> anyhow::Result<(
959    PolicyClient,
960    hyprstream_rpc_std::discovery_client::DiscoveryClient,
961)> {
962    let trust = hyprstream_service::global_trust_store();
963    let policy_key = trust
964        .resolve_one("policy")
965        .ok_or_else(|| anyhow::anyhow!("trust store has no authenticated policy key"))?;
966    let discovery_key = trust
967        .resolve_one("discovery")
968        .ok_or_else(|| anyhow::anyhow!("trust store has no authenticated discovery key"))?;
969    Ok((
970        crate::services::policy_client_for_process(signing_key.clone(), policy_key, None)?,
971        crate::services::discovery_client_for_process(signing_key.clone(), discovery_key, None)?,
972    ))
973}
974
975/// Wait until the required native carrier closes. Normal service shutdown is
976/// handled by the outer `tokio::select!`; keeping this watcher independent of
977/// that signal avoids consuming the single shutdown notification before the
978/// HTTP server observes it.
979async fn wait_for_required_iroh_carrier(
980    substrate: &hyprstream_rpc::transport::iroh_substrate::IrohSubstrate,
981) -> bool {
982    loop {
983        if substrate.router().is_shutdown() || substrate.endpoint().is_closed() {
984            return true;
985        }
986        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
987    }
988}
989
990#[cfg(test)]
991mod required_consumer_tests;
992
993#[cfg(test)]
994mod readiness_tests;
995
996impl Spawnable for OAuthService {
997    fn name(&self) -> &str {
998        SERVICE_NAME
999    }
1000
1001    fn registrations(&self) -> Vec<(SocketKind, TransportConfig)> {
1002        vec![(SocketKind::Rep, self.control_transport.clone())]
1003    }
1004
1005    fn run(
1006        self: Box<Self>,
1007        shutdown: Arc<Notify>,
1008        on_ready: Option<tokio::sync::oneshot::Sender<()>>,
1009    ) -> Result<(), hyprstream_rpc::error::RpcError> {
1010        validate_local_store_zone(&self.account_config)?;
1011        let contains_account_workers = hosted_account_store_requested(&self.account_config);
1012        if contains_account_workers && !self.dedicated_process {
1013            return Err(hyprstream_rpc::error::RpcError::SpawnFailed(
1014                "hosted account workers require a dedicated foreground OAuth process".to_owned(),
1015            ));
1016        }
1017        // Timed-out synchronous I/O cannot be cancelled safely. This service
1018        // owns the whole process when account workers are enabled; terminal
1019        // startup/shutdown therefore ends that process and all its workers.
1020        // Use single-threaded runtime + LocalSet because HTTP handlers make ZMQ RPC
1021        // calls (e.g., policy_client.issue_token()), and ZMQ clients use spawn_local.
1022        let rt = tokio::runtime::Builder::new_current_thread()
1023            .enable_all()
1024            .build()
1025            .map_err(|e| hyprstream_rpc::error::RpcError::SpawnFailed(format!("runtime: {e}")))?;
1026
1027        let local = tokio::task::LocalSet::new();
1028        let result = local.block_on(&rt, async move {
1029            let addr_str = format!("{}:{}", self.config.host, self.config.port);
1030            let addr: std::net::SocketAddr = addr_str.parse().map_err(|e| {
1031                hyprstream_rpc::error::RpcError::SpawnFailed(format!("Invalid address: {e}"))
1032            })?;
1033
1034            // Resolve TLS configuration (tls_config passed from factory, not re-loaded)
1035            let rustls_config = crate::server::tls::resolve_rustls_config(
1036                &self.tls_config,
1037                &self.account_config,
1038                self.config.tls_cert.as_ref(),
1039                self.config.tls_key.as_ref(),
1040            )
1041            .await
1042            .map_err(|e| hyprstream_rpc::error::RpcError::SpawnFailed(format!("TLS config: {e}")))?;
1043
1044            let scheme = if rustls_config.is_some() { "https" } else { "http" };
1045
1046            // Create RPC clients HERE, inside the OAuth runtime, so that ZMQ
1047            // async I/O (TMQ) registers socket FDs with THIS runtime's epoll.
1048            // Creating them in the factory (main runtime) would cause hangs.
1049
1050            // Bootstrap: get service verifying keys from the trust store,
1051            // populated during startup by depends_on services. Required profile
1052            // resolves through the checkpoint-backed discovery resolver;
1053            // compatibility dials the deterministic per-process IPC transports
1054            // the factory resolved (available to a separate Quadlet process).
1055            let policy_vk = match hyprstream_service::global_trust_store().resolve_one("policy") {
1056                Some(vk) => vk,
1057                None => {
1058                    return Err(hyprstream_rpc::error::RpcError::SpawnFailed(
1059                        "trust store has no policy key — startup must populate it".to_owned(),
1060                    ));
1061                }
1062            };
1063            let policy_client = runtime_policy_client(
1064                &self.policy_transport,
1065                self.signing_key.clone(),
1066                policy_vk,
1067            ).map_err(|e| hyprstream_rpc::error::RpcError::SpawnFailed(
1068                format!("failed to create PolicyClient: {e}"),
1069            ))?;
1070
1071            let discovery_vk = match hyprstream_service::global_trust_store().resolve_one("discovery") {
1072                Some(vk) => vk,
1073                None => {
1074                    return Err(hyprstream_rpc::error::RpcError::SpawnFailed(
1075                        "trust store has no discovery key — ensure discovery is in depends_on".to_owned(),
1076                    ));
1077                }
1078            };
1079            let discovery_client = runtime_discovery_client(
1080                &self.discovery_transport,
1081                self.signing_key.clone(),
1082                discovery_vk,
1083            )
1084            .map_err(|e| hyprstream_rpc::error::RpcError::SpawnFailed(
1085                format!("failed to create DiscoveryClient: {e}"),
1086            ))?;
1087
1088            let credentials_dir = crate::auth::identity_store::credentials_dir().map_err(|e| {
1089                hyprstream_rpc::error::RpcError::SpawnFailed(
1090                    format!("failed to resolve credentials directory: {e}"),
1091                )
1092            })?;
1093
1094            // Load account and device storage through the single production
1095            // credential-store boundary. Account-store construction failure
1096            // fails closed; no caller can inject a raw backend here.
1097            let credentials_config = crate::config::HyprConfig::load()
1098                .map_err(|error| {
1099                    hyprstream_rpc::error::RpcError::SpawnFailed(format!(
1100                        "failed to load production credential configuration: {error}"
1101                    ))
1102                })?
1103                .credentials;
1104            let (user_store, device_store_opt) =
1105                crate::auth::ProductionUserStore::open_with_device_store(
1106                    &credentials_dir,
1107                    &credentials_config,
1108                )
1109                .await
1110                .map_err(|error| {
1111                    hyprstream_rpc::error::RpcError::SpawnFailed(format!(
1112                        "failed to initialize production credential store: {error:#}"
1113                    ))
1114                })?;
1115            info!("Production credential store admitted at {:?}", credentials_dir);
1116
1117            // Load the CA JWT signing key for browser WIT issuance (POST /oauth/wit).
1118            // Also seed the signing key store from the same root key.
1119            let secrets_dir = credentials_dir.clone();
1120            let oauth_config_arc = Arc::new(self.config.clone());
1121
1122            // Load or initialize ES256 + ML-DSA rotation stores (independent of CA key).
1123            // Uses global singletons — shared with PolicyService and ServiceContext.
1124            let es256_store = crate::auth::key_rotation::global_es256_key_store(
1125                &secrets_dir,
1126                &self.config,
1127            );
1128            info!("ES256 (P-256) signing key rotation store loaded");
1129
1130            let ml_dsa_store = crate::auth::key_rotation::global_ml_dsa_key_store(
1131                &secrets_dir,
1132                &self.config,
1133            );
1134            info!("ML-DSA-65 signing key rotation store loaded");
1135            crate::auth::key_rotation::refresh_ml_dsa_verifying_keys(&ml_dsa_store).await;
1136            let crypto_policy = hyprstream_rpc::envelope::mandatory_envelope_policy();
1137
1138            // MAC #547 / B2 (#674): construct the S6 grant-path audit sink. A
1139            // startup-time snapshot of the active ML-DSA-65 key (rotation
1140            // during the process lifetime is a follow-up — S7's audit key
1141            // provisioning is otherwise the same "load once at boot" shape as
1142            // the rest of this factory). The node's enforced crypto policy
1143            // decides whether the PQ layer is REQUIRED (fail-closed if the key
1144            // snapshot comes back empty) or ignored (Classical).
1145            let audit_sink: Option<Arc<dyn crate::mac::audit::AuditSink>> = {
1146                let audit_pq_key = ml_dsa_store.active_key().await;
1147                let signer = crate::mac::audit::cose::OwnedCoseAuditSigner::new(
1148                    Arc::new(self.signing_key.clone()),
1149                    audit_pq_key,
1150                    crypto_policy,
1151                );
1152                // Fail-closed the SAME way as "store failed to open": a signer
1153                // that can't sign under the enforced policy is not a usable
1154                // audit sink. Do NOT install it — installing it anyway would
1155                // let every real request silently fail two audit-write
1156                // attempts deep (mint's Permit downgrade, then the best-effort
1157                // fallback deny record, both via this same broken signer) with
1158                // only this one startup log line as any indication, instead of
1159                // the immediate, obvious "audit trail is not configured" error
1160                // the grant path already gives when `audit_sink` is `None`.
1161                if !signer.can_sign() {
1162                    tracing::error!(
1163                        "MAC audit signer cannot sign under the enforced Hybrid crypto \
1164                         policy (no ML-DSA-65 key provisioned) — the S6 grant path will \
1165                         fail closed (deny) on every request until a key is provisioned"
1166                    );
1167                    None
1168                } else {
1169                    match crate::mac::audit::WalAuditStore::open(
1170                        credentials_dir.join("mac-audit"),
1171                        signer,
1172                    ) {
1173                        Ok(store) => {
1174                            info!("MAC grant-path audit store opened (WAL, hash-chained, checkpointed)");
1175                            Some(Arc::new(store) as Arc<dyn crate::mac::audit::AuditSink>)
1176                        }
1177                        Err(e) => {
1178                            // Fail-closed by omission: `audit_sink` stays `None`, and
1179                            // the grant path denies every request rather than mint
1180                            // unaudited tokens (see `exchange_ucan_grant`).
1181                            tracing::error!(
1182                                "MAC grant-path audit store failed to open — the S6 grant \
1183                                 path will fail closed (deny) on every request: {e:?}"
1184                            );
1185                            None
1186                        }
1187                    }
1188                }
1189            };
1190
1191            // The local hosted-account store and optional public account face
1192            // share one descriptor-bound store over the authoritative
1193            // publication root. Either explicit local-store opt-in or the
1194            // listener requires the root and mandatory audit sink; the local
1195            // store alone does not start a public account HTTP listener.
1196            let hosted_account_store = open_hosted_account_store(
1197                &self.account_config,
1198                self.hosted_account_store.as_ref(),
1199                self.pds_root.as_deref(),
1200                audit_sink.as_ref(),
1201            )?;
1202
1203            let (ca_jwt_key, signing_key_store) = match crate::auth::identity_store::load_ca_signing_key(&credentials_dir) {
1204                Ok(root_key) => {
1205                    let key = hyprstream_rpc::node_identity::derive_purpose_key(&root_key, "hyprstream-jwt-v1");
1206                    info!("CA JWT signing key loaded — POST /oauth/wit available");
1207
1208                    // Load or initialize the multi-slot Ed25519 rotation store.
1209                    let store_arc = crate::auth::key_rotation::global_ed25519_key_store(
1210                        &secrets_dir,
1211                        &self.config,
1212                    );
1213
1214                    // Publish the current Ed25519 rotation-slot verifying keys to the
1215                    // process-shared handle so the OAI/HTTP validator (`verify_token_claims`)
1216                    // accepts tokens signed by any active/lead/drain slot from startup —
1217                    // before the first rotation tick. Mirrors the /oauth/jwks key set.
1218                    crate::auth::key_rotation::refresh_ed25519_verifying_keys(&store_arc).await;
1219                    crate::auth::key_rotation::initialize_composite_key_set(
1220                        &secrets_dir,
1221                        &store_arc,
1222                        &ml_dsa_store,
1223                        Arc::new(key.clone()),
1224                        self.config.drain_secs(),
1225                    ).await.map_err(|error| {
1226                        hyprstream_rpc::error::RpcError::SpawnFailed(format!(
1227                            "composite key-set initialization failed: {error:#}"
1228                        ))
1229                    })?;
1230
1231                    // Spawn the background rotation task (rotates all algorithm stores).
1232                    crate::auth::key_rotation::spawn_rotation_task(
1233                        Arc::clone(&oauth_config_arc),
1234                        secrets_dir.clone(),
1235                        Arc::clone(&store_arc),
1236                        crate::auth::key_rotation::RotationStores {
1237                            es256: Some(Arc::clone(&es256_store)),
1238                            ml_dsa: Some(Arc::clone(&ml_dsa_store)),
1239                            composite_ca_key: Arc::new(key.clone()),
1240                        },
1241                    );
1242                    // C4 (#1170): publish the head verifying key and write the
1243                    // initial sealed op-log head so the registry's
1244                    // `PdsPublisher` (this process under inproc, or a separate
1245                    // process under `--ipc`) can resolve the active `#atproto`
1246                    // generation before the first rotation tick. Dedicated head
1247                    // key + shared state dir; async because the ES256 store is a
1248                    // tokio RwLock (F1). The rotation task re-seals after every
1249                    // promotion. C2 (#1168) seam — see `auth::op_log`.
1250                    if let Err(e) =
1251                        crate::auth::op_log::advance_sealed_head(&secrets_dir, &es256_store)
1252                            .await
1253                    {
1254                        tracing::error!("failed to seal initial op-log head: {e}");
1255                    }
1256                    info!("JWT signing key rotation task started (active_days={}, lead_days={}, drain_days={})",
1257                        self.config.jwt_key_active_days,
1258                        self.config.jwt_key_lead_days,
1259                        self.config.jwt_key_drain_days,
1260                    );
1261
1262                    (Some(key), Some(store_arc))
1263                }
1264                Err(e) => {
1265                    tracing::warn!("Cannot load CA signing key — POST /oauth/wit unavailable and key rotation disabled: {e}");
1266                    (None, None)
1267                }
1268            };
1269
1270            // Root DID identity rotation is independent of JWT rotation. Seed
1271            // the first active generation from the already-published service
1272            // identity key so upgrading does not change `#key-1` bytes, then
1273            // persist lead/active/drain beneath a dedicated directory.
1274            let root_identity_dir = secrets_dir.join("root-did");
1275            let root_identity_store = Arc::new(
1276                crate::auth::key_rotation::load_or_init_root_identity_key_store(
1277                    &root_identity_dir,
1278                    &self.config,
1279                    self.signing_key.clone(),
1280                ),
1281            );
1282            crate::auth::key_rotation::spawn_root_identity_rotation_task(
1283                Arc::clone(&oauth_config_arc),
1284                root_identity_dir,
1285                Arc::clone(&root_identity_store),
1286            );
1287
1288            // Create shared state — JWKS serves the CA JWT verifying key (from PolicyService)
1289            let jwt_verifying_key = self.jwt_verifying_key;
1290            let mut oauth_state = OAuthState::new(
1291                &self.config,
1292                policy_client,
1293                discovery_client.clone(),
1294                jwt_verifying_key,
1295            )
1296            .with_browser_provisioning_signer(self.signing_key.clone());
1297            if let Some(export) = self.ninep_canonical_read.clone() {
1298                oauth_state = oauth_state.with_ninep_canonical_read(export);
1299            }
1300            match (
1301                self.config.public_git_canary_registry_repo_id.as_deref(),
1302                self.config.public_git_canary_publisher_did.as_deref(),
1303            ) {
1304                (None, None) => {}
1305                (Some(repo_id), Some(publisher_did)) => {
1306                #[cfg(feature = "rocksdb")]
1307                {
1308                    let parsed = uuid::Uuid::parse_str(repo_id).map_err(|_| {
1309                        hyprstream_rpc::error::RpcError::SpawnFailed(
1310                            "public Git canary Registry ID is not a UUID".to_owned(),
1311                        )
1312                    })?;
1313                    if parsed.to_string() != repo_id {
1314                        return Err(hyprstream_rpc::error::RpcError::SpawnFailed(
1315                            "public Git canary Registry ID must be canonical lower-case".to_owned(),
1316                        ));
1317                    }
1318                    let publisher_key = hyprstream_rpc::did_key::did_key_to_ed25519(publisher_did)
1319                        .map_err(|_| hyprstream_rpc::error::RpcError::SpawnFailed(
1320                            "public Git canary publisher DID is not an Ed25519 did:key".to_owned(),
1321                        ))?;
1322                    if hyprstream_rpc::did_key::ed25519_to_did_key(&publisher_key) != publisher_did {
1323                        return Err(hyprstream_rpc::error::RpcError::SpawnFailed(
1324                            "public Git canary publisher DID must be canonical".to_owned(),
1325                        ));
1326                    }
1327                    oauth_state = oauth_state.with_public_git_canary_record(
1328                        state::PublicGitCanaryRecord {
1329                            did: publisher_did.to_owned(),
1330                            rkey: crate::services::discovery::PdsRecordStore::tid_for_repo(repo_id)
1331                                .encode(),
1332                        },
1333                    );
1334                }
1335                #[cfg(not(feature = "rocksdb"))]
1336                {
1337                    let _ = (repo_id, publisher_did);
1338                    return Err(hyprstream_rpc::error::RpcError::SpawnFailed(
1339                        "public Git canary record requires the PDS record store".to_owned(),
1340                    ));
1341                }
1342                }
1343                _ => return Err(hyprstream_rpc::error::RpcError::SpawnFailed(
1344                    "public Git canary Registry ID and publisher DID must be configured together".to_owned(),
1345                )),
1346            }
1347            if let Some(store) = &hosted_account_store {
1348                oauth_state = oauth_state.with_hosted_account_store(Arc::clone(store));
1349            }
1350            if let Some(api) = &self.identity_registration_api {
1351                oauth_state = oauth_state.with_identity_registration_api(Arc::clone(api));
1352            }
1353            if self.config.xrpc_read_slice {
1354                if let (Some(store), Some(root)) = (&hosted_account_store, &self.pds_root) {
1355                    let public_root = root.join("public-repositories");
1356                    let public_store = crate::services::public_repo::PublicRepoStore::open(&public_root)
1357                        .map_err(|error| hyprstream_rpc::error::RpcError::SpawnFailed(format!("open public repository store {}: {error}", public_root.display())))?;
1358                    oauth_state = oauth_state.with_hosted_public_repo_writer(Arc::new(
1359                        crate::services::public_repo::HostedAccountPublicRepoWriter::new(
1360                            Arc::new(public_store),
1361                            Arc::clone(store),
1362                            hyprstream_rpc::Subject::new(hyprstream_pds_service::OAUTH_ACCOUNT_RESOLVER_SUBJECT),
1363                            Arc::new(crate::services::public_repo::HostedAccountSelfAuthorizer),
1364                        ),
1365                    ));
1366                }
1367            }
1368            let account_zone = match self.account_config.resolve_zone() {
1369                Ok(zone) => {
1370                    oauth_state = oauth_state.with_hosted_account_zone(zone.clone());
1371                    Some(zone)
1372                }
1373                Err(error) => {
1374                    tracing::warn!(
1375                        %error,
1376                        "OAuth user-token minting disabled: no deployment account zone"
1377                    );
1378                    None
1379                }
1380            };
1381            if let (Some(store), Some(zone)) = (&hosted_account_store, &account_zone) {
1382                let resolver = Arc::new(
1383                    crate::services::oauth::atproto_session::NativeAtprotoSessionResolver::new(
1384                        user_store.clone_inner(),
1385                        Arc::clone(store),
1386                        zone.clone(),
1387                    ),
1388                );
1389                oauth_state = oauth_state.with_atproto_session_resolver(resolver);
1390            }
1391            oauth_state = oauth_state.with_user_store(user_store);
1392            if let Some(ds) = device_store_opt {
1393                oauth_state = oauth_state.with_device_store(ds);
1394            }
1395            oauth_state = oauth_state
1396                .with_signing_key(self.signing_key.clone(), crypto_policy)
1397                .map_err(|e| hyprstream_rpc::error::RpcError::SpawnFailed(format!("{e:#}")))?;
1398            if let Some(key) = ca_jwt_key {
1399                oauth_state = oauth_state.with_ca_jwt_key(key);
1400            }
1401            // Install the FederateIssuer for the Federate login path (#1718).
1402            // Uses the PolicyClient for prepare/commit and the active OAuth
1403            // access-token key (including key-store rotation) for the session JWT.
1404            if let Some(store) = signing_key_store {
1405                oauth_state = oauth_state.with_signing_key_store(store);
1406            }
1407            #[cfg(feature = "postgres")]
1408            if federate_source::FederateHost::new(&oauth_state.issuer_url).is_ok() {
1409                let admission = std::sync::Arc::new(
1410                    crate::services::oauth::federate_policy::PolicyFederateAdmission::new(
1411                        oauth_state.policy_client.clone(),
1412                    ),
1413                );
1414                let signer = oauth_state
1415                    .federate_signer()
1416                    .await
1417                    .map_err(|e| hyprstream_rpc::error::RpcError::SpawnFailed(
1418                        format!("FederateSigner construction failed: {e:#}"),
1419                    ))?;
1420                // W1.3: the optional second (TUI) client class from the
1421                // trusted-issuer config joins the issuer's accepted classes.
1422                // A configured-but-invalid class disables it (fail closed)
1423                // rather than widening the staging pin.
1424                let federate_tui_client = self
1425                    .config
1426                    .trusted_issuers
1427                    .get(federate_source::ISSUER)
1428                    .and_then(|issuer| issuer.federate_tui_client.as_ref())
1429                    .and_then(|class| {
1430                        match federate_source::ClientClass::new(
1431                            &class.client_id,
1432                            &class.aud,
1433                            class.connector_id.as_deref(),
1434                        ) {
1435                            Ok(class) => Some(class),
1436                            Err(error) => {
1437                                tracing::warn!(
1438                                    %error,
1439                                    "Federate TUI client class disabled: invalid trusted-issuer configuration"
1440                                );
1441                                None
1442                            }
1443                        }
1444                    });
1445                oauth_state
1446                    .install_federate_issuer(admission, signer, federate_tui_client)
1447                    .map_err(|e| hyprstream_rpc::error::RpcError::SpawnFailed(
1448                        format!("FederateIssuer installation failed: {e:#}"),
1449                    ))?;
1450            } else {
1451                tracing::warn!("Federate exchange disabled: OAuth issuer must be an exact canonical HTTPS origin");
1452            }
1453            oauth_state = oauth_state.with_root_identity_key_store(root_identity_store);
1454            oauth_state = oauth_state.with_es256_key_store(Arc::clone(&es256_store));
1455            {
1456                oauth_state = oauth_state.with_ml_dsa_key_store(Arc::clone(&ml_dsa_store));
1457            }
1458            if let Some(sink) = audit_sink {
1459                oauth_state = oauth_state.with_audit_sink(sink);
1460            }
1461
1462            // Warm the authority-owned hosted-DID index before exposing OAuth
1463            // readiness. Request paths remain O(1) lookups and never perform
1464            // tenant enumeration; a bounded startup failure keeps OAuth
1465            // fail-closed instead of serving valid hosted users intermittently
1466            // while the first snapshot is still absent.
1467            if let Some(store) = &hosted_account_store {
1468                let authority = hyprstream_rpc::Subject::new(
1469                    hyprstream_pds_service::OAUTH_ACCOUNT_RESOLVER_SUBJECT,
1470                );
1471                if contains_account_workers {
1472                    warm_hosted_did_index(
1473                        Arc::clone(store),
1474                        authority,
1475                        std::time::Duration::from_secs(30),
1476                    )
1477                    .await?;
1478                } else if !store.hosted_did_index_ready().await {
1479                    return Err(hyprstream_rpc::error::RpcError::SpawnFailed(
1480                        "in-process hosted-account store must be warmed before injection".to_owned(),
1481                    ));
1482                }
1483            }
1484            // Populate legacy JWKS nbf/exp from signing-key file mtime (used when store absent).
1485            let key_nbf = crate::auth::identity_store::node_signing_key_mtime(&credentials_dir);
1486            oauth_state = oauth_state.with_jwt_key_timestamps(key_nbf, key_nbf + 14 * 86400);
1487
1488            // Open persistent refresh token store (non-fatal — tokens simply don't survive restart).
1489            // The token store is decoupled from the account backend: neither
1490            // PGlite nor RDS Postgres UserStore implements a token store.
1491            // Refresh tokens always go to RocksDB or Valkey.
1492            #[cfg(feature = "rocksdb")]
1493            let token_db_path = credentials_dir.join("oauth-tokens");
1494            let token_store: Option<Arc<dyn crate::services::oauth::token_store::TokenStore>> = match credentials_config.backend {
1495                // Relational account stores deliberately fall through to
1496                // RocksDB for durable OAuth refresh tokens.
1497                CredentialsBackend::Pglite
1498                | CredentialsBackend::Postgres
1499                | CredentialsBackend::Rocksdb => {
1500                    #[cfg(feature = "rocksdb")]
1501                    {
1502                        match crate::services::oauth::token_store::RocksDbTokenStore::open(&token_db_path) {
1503                            Ok(s) => {
1504                                info!("Refresh token store (RocksDB) opened at {:?}", token_db_path);
1505                                Some(Arc::new(s))
1506                            }
1507                            Err(e) => {
1508                                tracing::warn!("Could not open refresh token store (tokens will not survive restart): {}", e);
1509                                None
1510                            }
1511                        }
1512                    }
1513                    // Same tolerance as the valkey arm: without the `rocksdb`
1514                    // feature there is no persistent token store, and startup
1515                    // proceeds with refresh tokens non-durable.
1516                    #[cfg(not(feature = "rocksdb"))]
1517                    {
1518                        tracing::warn!("No refresh token store available (tokens will not survive restart): this binary lacks the rocksdb feature");
1519                        None
1520                    }
1521                }
1522                CredentialsBackend::Valkey => {
1523                    #[cfg(feature = "valkey")]
1524                    {
1525                        let url = &credentials_config.valkey.url;
1526                        match crate::services::oauth::token_store::ValkeyTokenStore::connect(url).await {
1527                            Ok(s) => {
1528                                info!("Refresh token store (Valkey) connected at {url}");
1529                                Some(Arc::new(s))
1530                            }
1531                            Err(e) => {
1532                                tracing::warn!("Could not connect refresh token store (Valkey): {e}");
1533                                None
1534                            }
1535                        }
1536                    }
1537                    #[cfg(not(feature = "valkey"))]
1538                    {
1539                        None
1540                    }
1541                }
1542            };
1543            if let Some(store) = token_store {
1544                oauth_state.with_token_store_impl(store);
1545            }
1546
1547            // Resolve discovery URL at startup with LocalSet (RPC calls need LocalSet context).
1548            // Cache it so HTTP handlers don't need to make RPC calls.
1549            #[allow(clippy::expect_used)]
1550            let cached_discovery_url = {
1551                let dc = discovery_client;
1552                std::thread::spawn(move || {
1553                    let rt = tokio::runtime::Builder::new_current_thread()
1554                        .enable_all()
1555                        .build()
1556                        .expect("failed to create discovery resolve runtime");
1557                    let local = tokio::task::LocalSet::new();
1558                    local.block_on(&rt, async {
1559                        match dc.get_endpoints("discovery").await {
1560                            Ok(service_endpoints) => service_endpoints
1561                                .endpoints
1562                                .iter()
1563                                .find(|ep| ep.socket_kind == "quic")
1564                                .and_then(|ep| {
1565                                    let stripped = ep.endpoint.strip_prefix("quic://")?;
1566                                    let parts: Vec<&str> = stripped.splitn(3, ':').collect();
1567                                    if parts.len() >= 3 {
1568                                        Some(format!("https://{}:{}", parts[0], parts[2]))
1569                                    } else {
1570                                        None
1571                                    }
1572                                }),
1573                            Err(_) => None,
1574                        }
1575                    })
1576                })
1577                .join()
1578                .ok()
1579                .flatten()
1580            };
1581            if let Some(_url) = cached_discovery_url {
1582                // Discovery URL caching removed - use issuer URL directly
1583            }
1584
1585            // Publish QUIC cert hash in DID doc (#185): close the two-trust-roots / TOFU gap.
1586            // The leaf cert hash (SHA-256 of cert DER) is stored in OAuthState and
1587            // included in the `#quic` service entry at `GET /.well-known/did.json`.
1588            if let Some(ref quic_cfg) = self.quic_config {
1589                if quic_cfg.enabled {
1590                    if let Ok((cert_chain, _)) = quic_cfg.load_tls_materials() {
1591                        if let Some(leaf) = cert_chain.first() {
1592                            let mut hash = [0u8; 32];
1593                            let digest = ring::digest::digest(&ring::digest::SHA256, leaf);
1594                            hash.copy_from_slice(digest.as_ref());
1595                            // Derive the public QUIC URI: same host as issuer, port from QUIC bind addr.
1596                            let quic_port = quic_cfg.socket_addr().map(|a| a.port()).unwrap_or(4433);
1597                            let issuer_host = url::Url::parse(&oauth_state.issuer_url)
1598                                .ok()
1599                                .and_then(|u| u.host_str().map(str::to_owned))
1600                                .unwrap_or_else(|| "localhost".to_owned());
1601                            let quic_uri = format!("https://{issuer_host}:{quic_port}");
1602                            oauth_state = oauth_state.with_quic_transport(quic_uri, vec![hash]);
1603                        }
1604                    }
1605
1606                    // The Iroh transport entry is populated before state is
1607                    // shared; its RPC plane is bound after bridge readiness.
1608                }
1609            }
1610
1611            if self
1612                .quic_config
1613                .as_ref()
1614                .is_some_and(|q| q.enabled && q.iroh)
1615            {
1616                let transport_key = hyprstream_rpc::node_identity::derive_purpose_key(
1617                    &self.signing_key,
1618                    "hyprstream-iroh-transport-v1",
1619                );
1620                oauth_state.iroh_node_id = Some(transport_key.verifying_key().to_bytes());
1621            }
1622            let state = Arc::new(oauth_state);
1623            state.spawn_code_sweeper();
1624
1625            // Startup transaction (#1585 YuI7): the HTTP(S) listener is
1626            // PREBOUND before any readiness signal and before the irreversible
1627            // process-global Iroh endpoint install — an occupied port fails
1628            // here, while the supervised launcher still owns the launch.
1629            let bound = crate::server::tls::bind_listener(addr, rustls_config, "OAuthService")?;
1630
1631            // Optional public hosted-account face. It has its own listener,
1632            // certificate, and shutdown signal; it is never mounted into the
1633            // authenticated OAuth router.
1634            let account_endpoint = if let Some(http_config) = self.account_config.http.as_ref() {
1635                let zone = self.account_config.resolve_zone().map_err(|error| {
1636                    hyprstream_rpc::error::RpcError::SpawnFailed(format!(
1637                        "account HTTP listener requires a valid account zone: {error}"
1638                    ))
1639                })?;
1640                let store = hosted_account_store.clone().ok_or_else(|| {
1641                    hyprstream_rpc::error::RpcError::SpawnFailed(
1642                        "account HTTP listener has no hosted-account store".to_owned(),
1643                    )
1644                })?;
1645                let directory = Arc::new(
1646                    hyprstream_pds_service::account_http::MountedHostedAccountHttpDirectory::new_without_refresh(
1647                        store,
1648                        hyprstream_rpc::Subject::new(
1649                            hyprstream_pds_service::OAUTH_ACCOUNT_RESOLVER_SUBJECT,
1650                        ),
1651                        zone.apex(),
1652                    )
1653                    .map_err(|error| {
1654                        hyprstream_rpc::error::RpcError::SpawnFailed(format!(
1655                            "compose account HTTP directory: {error}"
1656                        ))
1657                    })?,
1658                );
1659                let account_app =
1660                    hyprstream_pds_service::account_http::router(zone.apex(), directory)
1661                        .map_err(|error| {
1662                            hyprstream_rpc::error::RpcError::SpawnFailed(format!(
1663                                "compose account HTTP router: {error}"
1664                            ))
1665                        })?;
1666                let account_addr = account_http_socket_addr(http_config)
1667                    .map_err(|error| {
1668                        hyprstream_rpc::error::RpcError::SpawnFailed(format!(
1669                            "invalid account HTTP bind host '{}': {error}",
1670                            http_config.host
1671                        ))
1672                    })?;
1673                let account_tls = resolve_account_http_tls(http_config, &zone)
1674                    .await
1675                    .map_err(|error| {
1676                        hyprstream_rpc::error::RpcError::SpawnFailed(format!(
1677                            "account HTTP TLS: {error:#}"
1678                        ))
1679                    })?;
1680                let account_bound = crate::server::tls::bind_listener(
1681                    account_addr,
1682                    Some(crate::server::tls::ResolvedTlsConfig::ordinary(account_tls)),
1683                    "AccountHttpService",
1684                )?;
1685                Some((account_bound, account_app, http_config.clone(), zone))
1686            } else {
1687                None
1688            };
1689
1690            let iroh_required = self
1691                .quic_config
1692                .as_ref()
1693                .is_some_and(crate::config::QuicConfig::iroh_required);
1694            let iroh_enabled = self
1695                .quic_config
1696                .as_ref()
1697                .is_some_and(|q| q.enabled && q.iroh);
1698            if iroh_required && !iroh_enabled {
1699                return Err(hyprstream_rpc::error::RpcError::SpawnFailed(
1700                    "network-iroh-required OAuth service requires [quic] enabled with iroh"
1701                        .to_owned(),
1702                ));
1703            }
1704            let mut substrate_owned: Option<hyprstream_rpc::transport::iroh_substrate::IrohSubstrate> = None;
1705
1706            // Federation publisher: a DIALING task — spawned only after the
1707            // final endpoint decision so its discovery dials use the installed
1708            // endpoint. Startup-owned: aborted/joined on every terminal path.
1709            let publish_state = state.clone();
1710            let publisher_handle = tokio::task::spawn_local(async move {
1711                let mut tick =
1712                    tokio::time::interval(std::time::Duration::from_secs(6 * 3600));
1713                tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
1714                loop {
1715                    tick.tick().await;
1716                    federation_entity::publish_entity_statement_to_discovery(
1717                        publish_state.clone(),
1718                    )
1719                    .await;
1720                }
1721            });
1722
1723            // Create router with configurable CORS
1724            let app = create_app(state.clone(), &self.config.cors);
1725
1726            info!(
1727                "Authorization server metadata at {scheme}://{addr}/.well-known/oauth-authorization-server",
1728            );
1729
1730            // User-CRUD RPC serve, alongside the HTTP server. #136: bridged
1731            // dispatch over the registered transport (inproc/ipc). The bridge
1732            // RUNTIME + handler construction happen on the bridge thread via
1733            // `spawn_with`, whose readiness receiver resolves only after that
1734            // construction succeeds — `spawn` alone proves only that the
1735            // thread started.
1736            let nonce_cache = Arc::new(hyprstream_rpc::envelope::InMemoryNonceCache::new());
1737            let rpc_state_build = state.clone();
1738            let control_transport_build = self.control_transport.clone();
1739            let rpc_signing_key_build = self.signing_key.clone();
1740            let serve_shutdown = Arc::new(Notify::new());
1741            let serve_shutdown_task = Arc::clone(&serve_shutdown);
1742
1743            // Bridge init phase: thread + runtime + handler construction,
1744            // bounded by the readiness receiver. The typed bridge is retained
1745            // OUTSIDE the spawned RPC future — the outer owner drives the
1746            // bounded shutdown on every terminal path. Init failures are
1747            // recorded (not returned) so the single common teardown below
1748            // always runs: a bare `?` past the publisher spawn would strand
1749            // that task and the bound substrate.
1750            let mut bridge_owner: Option<Arc<LocalServiceBridge>> = None;
1751            // (join handle, whether the select branch already consumed it).
1752            let mut rpc_owner: Option<(tokio::task::JoinHandle<anyhow::Result<()>>, bool)> =
1753                None;
1754            let account_shutdown = Arc::new(Notify::new());
1755            let mut account_owner: Option<account_worker::ContainedWorker<
1756                Result<(), hyprstream_rpc::error::RpcError>,
1757            >> = None;
1758            let bridge_init: Result<Arc<LocalServiceBridge>, hyprstream_rpc::error::RpcError> =
1759                async {
1760                    let (bridge, bridge_ready_rx) =
1761                        match LocalServiceBridge::spawn_with(
1762                            "oauth-user-crud",
1763                            move || async move {
1764                                Ok(rpc_handler::OAuthRpcHandler::new(
1765                                    rpc_state_build,
1766                                    control_transport_build,
1767                                    rpc_signing_key_build,
1768                                ))
1769                            },
1770                            nonce_cache,
1771                            0,
1772                        ) {
1773                            Ok(spawned) => spawned,
1774                            Err(e) => {
1775                                return Err(hyprstream_rpc::error::RpcError::SpawnFailed(
1776                                    format!("OAuth bridge thread spawn failed: {e}"),
1777                                ));
1778                            }
1779                        };
1780                    let bridge = Arc::new(bridge);
1781                    bridge_owner = Some(bridge.clone());
1782                    // Bridge runtime/handler readiness must resolve BEFORE
1783                    // serve_bridged (and therefore the external READY signal)
1784                    // is allowed to start — this await, not a comment, imposes
1785                    // the ordering. Bounded so a stuck bridge cannot hang the
1786                    // process.
1787                    match tokio::time::timeout(
1788                        std::time::Duration::from_secs(30),
1789                        bridge_ready_rx,
1790                    )
1791                    .await
1792                    {
1793                        Ok(Ok(Ok(()))) => Ok(bridge),
1794                        Ok(Ok(Err(closed))) => {
1795                            Err(hyprstream_rpc::error::RpcError::SpawnFailed(format!(
1796                                "OAuth bridge runtime initialization failed: {closed:#}"
1797                            )))
1798                        }
1799                        // The bridge task ended without ever sending a
1800                        // readiness result — a fatal init failure, not
1801                        // readiness.
1802                        Ok(Err(_)) => Err(hyprstream_rpc::error::RpcError::SpawnFailed(
1803                            "OAuth bridge runtime initialization receiver closed \
1804                             without a readiness result"
1805                                .to_owned(),
1806                        )),
1807                        Err(_) => Err(hyprstream_rpc::error::RpcError::SpawnFailed(
1808                            "OAuth bridge runtime initialization timed out".to_owned(),
1809                        )),
1810                    }
1811                }
1812                .await;
1813
1814            // Serve phase: register/bind the control transport — serve_bridged's
1815            // existing boundary emits the ONLY external readiness signals
1816            // (on_ready + kernel READY), now gated on bridge runtime readiness,
1817            // substrate bind, and the prebound HTTP(S) listener — then serve
1818            // the prebound listener concurrently with the RPC loop. Whichever
1819            // side finishes first decides the primary outcome; the actual
1820            // serve result propagates (no log-and-swallow).
1821            let mut primary: anyhow::Result<()> = match bridge_init {
1822                Err(e) => Err(anyhow::anyhow!("OAuthService startup failed: {e}")),
1823                Ok(bridge) => async {
1824                    if iroh_enabled {
1825                        let transport_key = hyprstream_rpc::node_identity::derive_purpose_key(
1826                            &self.signing_key,
1827                            "hyprstream-iroh-transport-v1",
1828                        );
1829                        let processor: Arc<dyn hyprstream_rpc::transport::rpc_session::IrohRequestProcessor> = bridge.clone();
1830                        let rpc_handler = hyprstream_rpc::transport::iroh_rpc::IrohRpcProtocolHandler::with_stream_limit(
1831                            processor,
1832                            self.signing_key.clone(),
1833                            hyprstream_rpc::transport::rpc_session::DEFAULT_STREAM_LIMIT,
1834                        );
1835                        let substrate_result = hyprstream_rpc::transport::iroh_substrate::IrohSubstrate::new(
1836                            transport_key.to_bytes(),
1837                            hyprstream_rpc::transport::iroh_substrate::RefuseHandler::new(
1838                                "OAuth MoQ disabled pending verified session proof (#1027/#726)",
1839                            ),
1840                            rpc_handler,
1841                        )
1842                        .await
1843                        .map_err(|e| anyhow::anyhow!("OAuth iroh substrate bind failed: {e}"));
1844                        match substrate_result {
1845                            Ok(substrate) => {
1846                                match classify_oauth_endpoint_install(&substrate) {
1847                                    OAuthEndpointInstall::InstalledHere => {
1848                                        info!("OAuth iroh endpoint installed as the process-global outbound dialer");
1849                                    }
1850                                    OAuthEndpointInstall::ExistingGlobalRetained => {
1851                                        info!("OAuth iroh substrate retained; existing global outbound endpoint is untouched");
1852                                    }
1853                                }
1854                                substrate_owned = Some(substrate);
1855                            }
1856                            Err(error) => {
1857                                // An enabled OAuth Iroh endpoint is advertised in the DID
1858                                // document before the HTTP server becomes reachable. A bind
1859                                // failure must therefore abort every profile; continuing would
1860                                // publish a node id with no live endpoint behind it.
1861                                return Err(error);
1862                            }
1863                        }
1864                    }
1865                    // Finish all fallible account-worker creation before the RPC
1866                    // task can signal readiness. Keep the actual thread owner.
1867                    if let Some((account_bound, account_app, account_config, account_zone)) = account_endpoint {
1868                        let account_shutdown_task = Arc::clone(&account_shutdown);
1869                        let runtime = tokio::runtime::Builder::new_current_thread()
1870                            .enable_all()
1871                            .build()
1872                            .map_err(|error| hyprstream_rpc::error::RpcError::SpawnFailed(
1873                                format!("account HTTP runtime: {error}"),
1874                            ))?;
1875                        account_owner = Some(account_worker::ContainedWorker::spawn(
1876                            "hyprstream-account-http",
1877                            move || {
1878                                runtime.block_on(account_tls::serve_with_reload(
1879                                    account_bound,
1880                                    account_app,
1881                                    account_shutdown_task,
1882                                    account_config,
1883                                    account_zone,
1884                                    std::time::Duration::from_secs(30),
1885                                ))
1886                            },
1887                        )?);
1888                    }
1889                    let control_transport = self.control_transport.clone();
1890                    let rpc_signing_key = self.signing_key.clone();
1891                    let processor: Arc<
1892                        dyn hyprstream_rpc::transport::rpc_session::IrohRequestProcessor,
1893                    > = bridge.clone();
1894                    let mut rpc_loop = tokio::task::spawn_local(async move {
1895                        hyprstream_rpc::service::serve::serve_bridged(
1896                            &control_transport,
1897                            processor,
1898                            rpc_signing_key,
1899                            serve_shutdown_task,
1900                            on_ready,
1901                        )
1902                        .await
1903                    });
1904                    let mut rpc_consumed = false;
1905                    let outcome = tokio::select! {
1906                        http = crate::server::tls::serve_bound(
1907                            bound,
1908                            app,
1909                            shutdown.clone(),
1910                            "OAuthService",
1911                        ) => http.map_err(|e| anyhow::anyhow!("OAuthService HTTP serve error: {e}")),
1912                        account = async {
1913                            match account_owner.as_mut() {
1914                                Some(worker) => worker.result().await,
1915                                None => std::future::pending().await,
1916                            }
1917                        } => {
1918                            match account {
1919                                Ok(Ok(())) => Err(anyhow::anyhow!(
1920                                    "AccountHttpService stopped unexpectedly"
1921                                )),
1922                                Ok(Err(e)) => Err(anyhow::anyhow!(
1923                                    "AccountHttpService error: {e}"
1924                                )),
1925                                Err(join) => Err(anyhow::anyhow!(
1926                                    "AccountHttpService task join error: {join}"
1927                                )),
1928                            }
1929                        },
1930                        rpc = &mut rpc_loop => {
1931                            // This select branch consumed the completed
1932                            // JoinHandle — the teardown below must not poll it
1933                            // again (poll-after-completion panics).
1934                            rpc_consumed = true;
1935                            match rpc {
1936                                Ok(Ok(())) => Ok(()),
1937                                Ok(Err(e)) => Err(anyhow::anyhow!(
1938                                    "OAuthService RPC serve error: {e}"
1939                                )),
1940                                Err(join) => Err(anyhow::anyhow!(
1941                                    "OAuthService RPC task join error: {join}"
1942                                )),
1943                            }
1944                        }
1945                        _carrier_lost = async {
1946                            match substrate_owned.as_ref() {
1947                                Some(substrate) => wait_for_required_iroh_carrier(substrate).await,
1948                                None => std::future::pending::<bool>().await,
1949                            }
1950                        }, if iroh_required => {
1951                            Err(anyhow::anyhow!(
1952                                "OAuth required Iroh carrier terminated unexpectedly"
1953                            ))
1954                        }
1955                    };
1956                    rpc_owner = Some((rpc_loop, rpc_consumed));
1957                    outcome
1958                }.await
1959            };
1960
1961            // ── Single common bounded teardown (the one startup owner): runs
1962            // on EVERY terminal path past the publisher spawn — bridge spawn /
1963            // readiness failure, HTTP or RPC error, or clean shutdown. The
1964            // primary error is preserved; cleanup failures are logged as
1965            // context, never masked. ──
1966            // There is exactly one account listener. `notify_one` preserves a
1967            // permit when teardown races worker startup; `notify_waiters` can
1968            // lose the signal before the isolated runtime begins awaiting.
1969            account_shutdown.notify_one();
1970            serve_shutdown.notify_one();
1971            if let Some(mut worker) = account_owner.take() {
1972                if !worker.is_joined() {
1973                    let completion = worker.finish(std::time::Duration::from_secs(45)).await;
1974                    if let Err(error) = completion.and_then(|result| result) {
1975                        tracing::warn!(%error, "account HTTP worker failed during shutdown");
1976                        if primary.is_ok() {
1977                            primary = Err(anyhow::anyhow!(error));
1978                        }
1979                    }
1980                }
1981            }
1982            if let Some(bridge) = &bridge_owner {
1983                bridge.begin_shutdown(
1984                    tokio::time::Instant::now() + std::time::Duration::from_secs(5),
1985                );
1986            }
1987            if let Some((mut rpc_loop, rpc_consumed)) = rpc_owner.take() {
1988                if !rpc_consumed {
1989                    match tokio::time::timeout(
1990                        std::time::Duration::from_secs(45),
1991                        &mut rpc_loop,
1992                    )
1993                    .await
1994                    {
1995                        Ok(Ok(Ok(()))) => {}
1996                        Ok(Ok(Err(e))) => {
1997                            tracing::warn!("OAuth RPC serve task error during shutdown: {e}");
1998                        }
1999                        Ok(Err(join)) => {
2000                            tracing::warn!(
2001                                "OAuth RPC serve task join error during shutdown: {join}"
2002                            );
2003                        }
2004                        Err(_) => {
2005                            rpc_loop.abort();
2006                            tracing::warn!(
2007                                "OAuth RPC serve task did not stop within the shutdown budget; aborted"
2008                            );
2009                        }
2010                    }
2011                }
2012            }
2013            publisher_handle.abort();
2014            // Abort alone is not teardown: await the cancelled task so its
2015            // future (and its state clones) are actually dropped.
2016            let _ = publisher_handle.await;
2017            // Release the enrollment-intent journal's cached writer (and its
2018            // exclusive flock) so the offline `trust reconcile-mac-boot-enrollment`
2019            // operator step can run right after shutdown without waiting on a
2020            // stale lock (#698 Phase 2 handoff).
2021            {
2022                let journal_dir =
2023                    crate::mac::enrollment_journal::global_journal_dir()
2024                        .map(std::path::Path::to_path_buf)
2025                        .or_else(|| {
2026                            self.pds_root
2027                                .as_ref()
2028                                .map(|root| root.join(identity_registration::ENROLLMENT_JOURNAL_DIR))
2029                        });
2030                if let Some(dir) = journal_dir {
2031                    crate::mac::enrollment_journal::close_cached_writer(&dir);
2032                }
2033            }
2034            if let Some(substrate) = substrate_owned.take() {
2035                if let Err(e) = substrate.shutdown().await {
2036                    tracing::warn!("OAuth iroh substrate shutdown error: {e}");
2037                }
2038            }
2039
2040            primary.map_err(|e| {
2041                hyprstream_rpc::error::RpcError::SpawnFailed(format!("{e:#}"))
2042            })?;
2043            Ok(())
2044        });
2045        if contains_account_workers {
2046            if let Err(error) = &result {
2047                tracing::error!(%error, "dedicated OAuth process failed");
2048            }
2049            std::process::exit(if result.is_ok() {
2050                0
2051            } else {
2052                account_worker::WORKER_FAILURE_EXIT
2053            });
2054        }
2055        result
2056    }
2057}
2058
2059/// RFC 9728 Protected Resource Metadata.
2060///
2061/// Typed representation of the JSON served at `/.well-known/oauth-protected-resource`.
2062/// Used by MCP, OAI, Flight, and QUIC services to advertise their OAuth authorization server.
2063#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
2064pub struct ProtectedResourceMetadata {
2065    pub resource: String,
2066    pub authorization_servers: Vec<String>,
2067    #[serde(skip_serializing_if = "Option::is_none")]
2068    pub bearer_methods_supported: Option<Vec<String>>,
2069    #[serde(skip_serializing_if = "Option::is_none")]
2070    pub scopes_supported: Option<Vec<String>>,
2071    #[serde(skip_serializing_if = "Option::is_none")]
2072    pub resource_name: Option<String>,
2073    #[serde(skip_serializing_if = "Option::is_none")]
2074    pub resource_documentation: Option<String>,
2075    /// Base64 SHA-256 hash of the TLS certificate for WebTransport cert pinning.
2076    #[serde(skip_serializing_if = "Option::is_none")]
2077    pub x_cert_hash: Option<String>,
2078}
2079
2080/// Create a Protected Resource Metadata response (RFC 9728).
2081///
2082/// Used by MCP and OAI servers to advertise their OAuth authorization server.
2083pub fn protected_resource_metadata(
2084    resource_url: &str,
2085    oauth_issuer_url: &str,
2086) -> ProtectedResourceMetadata {
2087    ProtectedResourceMetadata {
2088        resource: resource_url.to_owned(),
2089        authorization_servers: vec![oauth_issuer_url.to_owned()],
2090        bearer_methods_supported: Some(vec!["header".to_owned()]),
2091        scopes_supported: None,
2092        resource_name: None,
2093        resource_documentation: None,
2094        x_cert_hash: None,
2095    }
2096}
2097
2098#[cfg(test)]
2099#[allow(clippy::unwrap_used, clippy::expect_used, clippy::get_unwrap)]
2100mod tests {
2101    use super::registration::validate_redirect_uri;
2102    use super::*;
2103
2104    /// OAuth owns a separate runtime, so its peer clients are made in `run`.
2105    /// The production path must retain the factory-resolved IPC transports;
2106    /// process-local bootstrap cannot see Policy or Discovery across rootless
2107    /// Quadlet process boundaries.
2108    #[test]
2109    fn oauth_run_uses_factory_resolved_peer_transports() {
2110        let source = include_str!("mod.rs");
2111        let production = source
2112            .split("// Tests")
2113            .next()
2114            .expect("tests banner must bound production source");
2115        let run_start = production
2116            .find("impl Spawnable for OAuthService")
2117            .expect("OAuthService must implement Spawnable");
2118        let run = &production[run_start..];
2119
2120        // Merged required/compat shape: required resolves through the
2121        // checkpoint-backed discovery resolver; compat dials the
2122        // factory-resolved IPC transports (20-space continuation inside the
2123        // profile branch).
2124        assert!(run.contains("runtime_policy_client(\n                &self.policy_transport,"));
2125        let policy_constructor = production
2126            .split("pub(crate) fn runtime_policy_client(")
2127            .nth(1)
2128            .and_then(|tail| tail.split("/// Create the OAuth Axum router.").next())
2129            .expect("production Policy constructor must exist");
2130        assert!(policy_constructor.contains("factories::service_token(&signing_key)"));
2131        assert!(policy_constructor.contains("dial::dial_with_token_provider("));
2132        assert!(policy_constructor.contains("local bootstrap refuses network transport"));
2133        assert!(policy_constructor.contains("Some(token)"));
2134        assert!(
2135            run.contains("runtime_discovery_client(\n                &self.discovery_transport,")
2136        );
2137        let discovery_constructor = production
2138            .split("pub(crate) fn runtime_discovery_client(")
2139            .nth(1)
2140            .and_then(|tail| tail.split("/// Create the OAuth Axum router.").next())
2141            .expect("production Discovery constructor must exist");
2142        assert!(
2143            policy_constructor.contains("if hyprstream_discovery::native_network_required() {\n        PolicyClient::from_provider("),
2144            "Required profile must resolve Policy through the checkpoint resolver"
2145        );
2146        assert!(
2147            discovery_constructor.contains("if hyprstream_discovery::native_network_required() {\n        hyprstream_rpc_std::discovery_client::DiscoveryClient::from_provider("),
2148            "Required profile must resolve Discovery through the checkpoint resolver"
2149        );
2150        assert!(
2151            !run.contains("PolicyClient::for_local_bootstrap("),
2152            "OAuth must not use the process-local Policy registry"
2153        );
2154        assert!(
2155            !run.contains("DiscoveryClient::for_local_bootstrap("),
2156            "OAuth must not use the process-local Discovery registry"
2157        );
2158    }
2159
2160    #[test]
2161    fn discovery_client_requires_own_enrolled_credential() {
2162        let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0xa7; 32]);
2163        let discovery_key = ed25519_dalek::SigningKey::from_bytes(&[0xa8; 32]).verifying_key();
2164        let result = runtime_discovery_client(
2165            &TransportConfig::inproc("oauth-discovery-unenrolled"),
2166            signing_key,
2167            discovery_key,
2168        );
2169        assert!(result.err().is_some_and(|error| error
2170            .to_string()
2171            .contains("OAuth has no enrolled service credential")));
2172    }
2173
2174    #[test]
2175    fn account_http_socket_address_preserves_ipv4_and_ipv6_literals() {
2176        let mut config = crate::account::AccountHttpConfig {
2177            host: String::new(),
2178            port: 8443,
2179            tls_cert: "unused.pem".into(),
2180            tls_key: "unused.key".into(),
2181        };
2182        for (host, expected) in [
2183            ("127.0.0.1", "127.0.0.1:8443"),
2184            ("0.0.0.0", "0.0.0.0:8443"),
2185            ("::1", "[::1]:8443"),
2186            ("::", "[::]:8443"),
2187            ("[::1]", "[::1]:8443"),
2188        ] {
2189            config.host = host.to_owned();
2190            assert_eq!(
2191                account_http_socket_addr(&config).unwrap().to_string(),
2192                expected
2193            );
2194        }
2195        for invalid in ["localhost", "[::1", "::1]", "127.0.0.1:8443"] {
2196            config.host = invalid.to_owned();
2197            assert!(account_http_socket_addr(&config).is_err());
2198        }
2199    }
2200
2201    #[test]
2202    fn hosted_account_store_selection_is_explicit_and_listener_implies_store() {
2203        assert!(!hosted_account_store_requested(
2204            &crate::account::AccountZoneConfig::default()
2205        ));
2206        assert!(hosted_account_store_requested(
2207            &crate::account::AccountZoneConfig {
2208                local_store: true,
2209                ..Default::default()
2210            }
2211        ));
2212        assert!(hosted_account_store_requested(
2213            &crate::account::AccountZoneConfig {
2214                http: Some(crate::account::AccountHttpConfig {
2215                    host: "127.0.0.1".to_owned(),
2216                    port: 443,
2217                    tls_cert: PathBuf::from("unused.pem"),
2218                    tls_key: PathBuf::from("unused.key"),
2219                }),
2220                ..Default::default()
2221            }
2222        ));
2223    }
2224
2225    #[test]
2226    fn account_worker_requires_launcher_process_containment() {
2227        let sk = ed25519_dalek::SigningKey::from_bytes(&[3; 32]);
2228        let account = crate::account::AccountZoneConfig {
2229            http: Some(crate::account::AccountHttpConfig {
2230                host: "127.0.0.1".to_owned(),
2231                port: 443,
2232                tls_cert: PathBuf::from("unused.pem"),
2233                tls_key: PathBuf::from("unused.key"),
2234            }),
2235            ..Default::default()
2236        };
2237        let transport = TransportConfig::inproc("test-containment-unused");
2238        let service = OAuthService::new(
2239            Default::default(),
2240            Default::default(),
2241            account,
2242            sk.clone(),
2243            transport.clone(),
2244            transport.clone(),
2245            transport,
2246            sk.verifying_key(),
2247            sk.verifying_key(),
2248        );
2249        let result = Box::new(service).run(Arc::new(Notify::new()), None);
2250        assert!(matches!(result,
2251            Err(hyprstream_rpc::error::RpcError::SpawnFailed(message))
2252                if message.contains("dedicated foreground OAuth process")
2253        ));
2254    }
2255
2256    #[test]
2257    fn local_hosted_store_requires_launcher_process_containment_without_http() {
2258        let sk = ed25519_dalek::SigningKey::from_bytes(&[4; 32]);
2259        let account = crate::account::AccountZoneConfig {
2260            zone: Some("acct.example.com".to_owned()),
2261            local_store: true,
2262            http: None,
2263            ..Default::default()
2264        };
2265        let transport = TransportConfig::inproc("test-local-store-containment-unused");
2266        let service = OAuthService::new(
2267            Default::default(),
2268            Default::default(),
2269            account,
2270            sk.clone(),
2271            transport.clone(),
2272            transport.clone(),
2273            transport,
2274            sk.verifying_key(),
2275            sk.verifying_key(),
2276        );
2277        let result = Box::new(service).run(Arc::new(Notify::new()), None);
2278        assert!(matches!(result,
2279            Err(hyprstream_rpc::error::RpcError::SpawnFailed(message))
2280                if message.contains("dedicated foreground OAuth process")
2281        ));
2282    }
2283
2284    #[test]
2285    fn local_store_rejects_missing_or_invalid_zone_before_startup() {
2286        let missing = crate::account::AccountZoneConfig {
2287            local_store: true,
2288            ..Default::default()
2289        };
2290        assert!(matches!(
2291            validate_local_store_zone(&missing),
2292            Err(hyprstream_rpc::error::RpcError::SpawnFailed(message))
2293                if message.contains("requires a valid account zone")
2294        ));
2295
2296        let invalid = crate::account::AccountZoneConfig {
2297            local_store: true,
2298            zone: Some("bad..example".to_owned()),
2299            ..Default::default()
2300        };
2301        assert!(matches!(
2302            validate_local_store_zone(&invalid),
2303            Err(hyprstream_rpc::error::RpcError::SpawnFailed(message))
2304                if message.contains("requires a valid account zone")
2305        ));
2306
2307        let listener_only = crate::account::AccountZoneConfig {
2308            http: Some(crate::account::AccountHttpConfig {
2309                host: "127.0.0.1".to_owned(),
2310                port: 443,
2311                tls_cert: PathBuf::from("unused.pem"),
2312                tls_key: PathBuf::from("unused.key"),
2313            }),
2314            ..Default::default()
2315        };
2316        assert!(validate_local_store_zone(&listener_only).is_ok());
2317    }
2318
2319    #[test]
2320    fn oauth_warms_hosted_did_index_before_readiness() {
2321        let source = include_str!("mod.rs");
2322        let production = source
2323            .get(
2324                ..source
2325                    .find("\n#[cfg(test)]\n#[allow(clippy::unwrap_used")
2326                    .expect("test module must remain explicit"),
2327            )
2328            .expect("production source must precede tests");
2329        let run_start = production
2330            .find("impl Spawnable for OAuthService")
2331            .expect("OAuthService must implement Spawnable");
2332        let run = &production[run_start..];
2333        let warmup = run
2334            .find("warm_hosted_did_index(")
2335            .expect("OAuth startup must warm the hosted-DID index");
2336        let ready = run
2337            .find("serve_bridged(")
2338            .expect("OAuth readiness boundary must remain explicit");
2339        assert!(
2340            warmup < ready,
2341            "OAuth must not signal readiness before index warm-up"
2342        );
2343        let warmup_block = &run[warmup..ready];
2344        assert!(
2345            warmup_block.contains("warm_hosted_did_index(")
2346                && warmup_block.contains("Duration::from_secs(30)"),
2347            "hosted-DID warm-up must have a bounded timeout"
2348        );
2349        let helper_start = production
2350            .find("async fn warm_hosted_did_index(")
2351            .expect("warm-up helper must remain explicit");
2352        let helper_end = production
2353            .find("/// Profile-aware bind of OAuth's inbound reach-only substrate")
2354            .expect("warm-up helper must be bounded by the next helper");
2355        let helper = &production[helper_start..helper_end];
2356        assert!(
2357            !helper.contains("spawn_blocking"),
2358            "hosted-DID warm-up timeout must not leave an uncancellable blocking task"
2359        );
2360    }
2361
2362    #[tokio::test(flavor = "current_thread")]
2363    async fn hosted_did_warmup_timeout_does_not_wait_for_blocking_scan() {
2364        const TEST: &str =
2365            "services::oauth::tests::hosted_did_warmup_timeout_does_not_wait_for_blocking_scan";
2366        if !account_worker::tests::is_child(TEST) {
2367            account_worker::tests::expect_contained_exit(TEST, &[]);
2368            return;
2369        }
2370        struct SlowReads;
2371        impl hyprstream_pds_service::AccountRecordReadAuthorizer for SlowReads {
2372            fn check_read(
2373                &self,
2374                _subject: &hyprstream_rpc::Subject,
2375                _verified_tenant: Option<&str>,
2376                _security_context: Option<&hyprstream_rpc::auth::mac::SecurityContext>,
2377                _object_id: &str,
2378            ) -> hyprstream_rpc::auth::mac::MacDecision {
2379                std::thread::sleep(std::time::Duration::from_millis(200));
2380                hyprstream_rpc::auth::mac::MacDecision::Permit
2381            }
2382        }
2383
2384        let store = Arc::new(hyprstream_pds_service::AccountRecordStore::new(
2385            Arc::new(hyprstream_vfs::SyntheticMount::new(
2386                hyprstream_vfs::SyntheticNode::dir(),
2387            )),
2388            Arc::new(SlowReads),
2389        ));
2390        let _ = warm_hosted_did_index(
2391            store,
2392            hyprstream_rpc::Subject::new(hyprstream_pds_service::OAUTH_ACCOUNT_RESOLVER_SUBJECT),
2393            std::time::Duration::from_millis(20),
2394        )
2395        .await;
2396        panic!("timed-out warm-up must terminate its dedicated process");
2397    }
2398
2399    fn encode_form(fields: &[(&str, &str)]) -> String {
2400        let mut serializer = url::form_urlencoded::Serializer::new(String::new());
2401        serializer.extend_pairs(fields.iter().copied());
2402        serializer.finish()
2403    }
2404
2405    async fn post_form(
2406        app: &Router,
2407        uri: &str,
2408        fields: &[(&str, &str)],
2409        dpop: Option<&str>,
2410        accept_json: bool,
2411    ) -> axum::response::Response {
2412        use tower::ServiceExt as _;
2413
2414        let mut builder = axum::http::Request::post(uri).header(
2415            axum::http::header::CONTENT_TYPE,
2416            "application/x-www-form-urlencoded",
2417        );
2418        if let Some(proof) = dpop {
2419            builder = builder.header("DPoP", proof);
2420        }
2421        if accept_json {
2422            builder = builder.header(axum::http::header::ACCEPT, "application/json");
2423        }
2424        app.clone()
2425            .oneshot(
2426                builder
2427                    .body(axum::body::Body::from(encode_form(fields)))
2428                    .unwrap(),
2429            )
2430            .await
2431            .unwrap()
2432    }
2433
2434    async fn post_form_bearer(
2435        app: &Router,
2436        uri: &str,
2437        fields: &[(&str, &str)],
2438        bearer: &str,
2439    ) -> axum::response::Response {
2440        use tower::ServiceExt as _;
2441
2442        app.clone()
2443            .oneshot(
2444                axum::http::Request::post(uri)
2445                    .header(
2446                        axum::http::header::CONTENT_TYPE,
2447                        "application/x-www-form-urlencoded",
2448                    )
2449                    .header(
2450                        axum::http::header::AUTHORIZATION,
2451                        format!("Bearer {bearer}"),
2452                    )
2453                    .body(axum::body::Body::from(encode_form(fields)))
2454                    .unwrap(),
2455            )
2456            .await
2457            .unwrap()
2458    }
2459
2460    async fn get(app: &Router, uri: &str) -> axum::response::Response {
2461        use tower::ServiceExt as _;
2462
2463        app.clone()
2464            .oneshot(
2465                axum::http::Request::get(uri)
2466                    .body(axum::body::Body::empty())
2467                    .unwrap(),
2468            )
2469            .await
2470            .unwrap()
2471    }
2472
2473    async fn response_json(response: axum::response::Response) -> serde_json::Value {
2474        let bytes = axum::body::to_bytes(response.into_body(), 1024 * 1024)
2475            .await
2476            .unwrap();
2477        serde_json::from_slice(&bytes).unwrap()
2478    }
2479
2480    async fn response_text(response: axum::response::Response) -> String {
2481        let bytes = axum::body::to_bytes(response.into_body(), 1024 * 1024)
2482            .await
2483            .unwrap();
2484        String::from_utf8(bytes.to_vec()).unwrap()
2485    }
2486
2487    fn html_hidden_value<'a>(html: &'a str, name: &str) -> &'a str {
2488        let prefix = format!(r#"name="{name}" value=""#);
2489        let rest = html.split_once(&prefix).unwrap().1;
2490        rest.split_once('"').unwrap().0
2491    }
2492
2493    fn dpop_proof(
2494        signing_key: &p256::ecdsa::SigningKey,
2495        htu: &str,
2496        jti: &str,
2497        nonce: Option<&str>,
2498    ) -> String {
2499        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
2500        use p256::ecdsa::signature::Signer as _;
2501
2502        let point = signing_key.verifying_key().to_encoded_point(false);
2503        let header = serde_json::json!({
2504            "typ": "dpop+jwt",
2505            "alg": "ES256",
2506            "jwk": {
2507                "kty": "EC",
2508                "crv": "P-256",
2509                "x": URL_SAFE_NO_PAD.encode(point.x().unwrap()),
2510                "y": URL_SAFE_NO_PAD.encode(point.y().unwrap()),
2511            }
2512        });
2513        let mut payload = serde_json::json!({
2514            "jti": jti,
2515            "htm": "POST",
2516            "htu": htu,
2517            "iat": chrono::Utc::now().timestamp(),
2518        });
2519        if let Some(value) = nonce {
2520            payload["nonce"] = serde_json::Value::String(value.to_owned());
2521        }
2522        let header = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap());
2523        let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).unwrap());
2524        let signing_input = format!("{header}.{payload}");
2525        let signature: p256::ecdsa::Signature = signing_key.sign(signing_input.as_bytes());
2526        format!(
2527            "{signing_input}.{}",
2528            URL_SAFE_NO_PAD.encode(signature.to_bytes())
2529        )
2530    }
2531
2532    fn dpop_resource_proof(
2533        signing_key: &p256::ecdsa::SigningKey,
2534        method: &str,
2535        htu: &str,
2536        access_token: &str,
2537        jti: &str,
2538        nonce: Option<&str>,
2539    ) -> String {
2540        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
2541        use p256::ecdsa::signature::Signer as _;
2542        use sha2::{Digest as _, Sha256};
2543
2544        let point = signing_key.verifying_key().to_encoded_point(false);
2545        let header = serde_json::json!({
2546            "typ": "dpop+jwt",
2547            "alg": "ES256",
2548            "jwk": {
2549                "kty": "EC",
2550                "crv": "P-256",
2551                "x": URL_SAFE_NO_PAD.encode(point.x().unwrap()),
2552                "y": URL_SAFE_NO_PAD.encode(point.y().unwrap()),
2553            }
2554        });
2555        let mut payload = serde_json::json!({
2556            "jti": jti,
2557            "htm": method,
2558            "htu": htu,
2559            "iat": chrono::Utc::now().timestamp(),
2560            "ath": URL_SAFE_NO_PAD.encode(Sha256::digest(access_token.as_bytes())),
2561        });
2562        if let Some(value) = nonce {
2563            payload["nonce"] = serde_json::Value::String(value.to_owned());
2564        }
2565        let header = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap());
2566        let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).unwrap());
2567        let signing_input = format!("{header}.{payload}");
2568        let signature: p256::ecdsa::Signature = signing_key.sign(signing_input.as_bytes());
2569        format!(
2570            "{signing_input}.{}",
2571            URL_SAFE_NO_PAD.encode(signature.to_bytes())
2572        )
2573    }
2574
2575    fn private_key_jwt_assertion(
2576        signing_key: &p256::ecdsa::SigningKey,
2577        kid: &str,
2578        client_id: &str,
2579        audience: &str,
2580        jti: &str,
2581    ) -> String {
2582        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
2583        use p256::ecdsa::signature::Signer as _;
2584
2585        let header = serde_json::json!({"alg": "ES256", "typ": "JWT", "kid": kid});
2586        let claims = serde_json::json!({
2587            "iss": client_id,
2588            "sub": client_id,
2589            "aud": audience,
2590            "iat": chrono::Utc::now().timestamp(),
2591            "exp": chrono::Utc::now().timestamp() + 60,
2592            "jti": jti,
2593        });
2594        let header = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap());
2595        let claims = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap());
2596        let signing_input = format!("{header}.{claims}");
2597        let signature: p256::ecdsa::Signature = signing_key.sign(signing_input.as_bytes());
2598        format!(
2599            "{signing_input}.{}",
2600            URL_SAFE_NO_PAD.encode(signature.to_bytes())
2601        )
2602    }
2603
2604    fn jwt_claims(token: &str) -> serde_json::Value {
2605        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
2606
2607        let payload = token.split('.').nth(1).expect("JWT payload");
2608        serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload).expect("JWT payload base64"))
2609            .expect("JWT payload JSON")
2610    }
2611
2612    // Rust mirror of @atproto/oauth-types 0.7.5
2613    // atprotoOAuthTokenResponseSchema. The upstream schema extends the base
2614    // OAuth response with literal DPoP, required atproto DID sub, required
2615    // atproto-containing scope, and an absent id_token.
2616    #[derive(serde::Deserialize)]
2617    struct AtprotoOAuthTokenResponse075 {
2618        access_token: String,
2619        token_type: String,
2620        scope: String,
2621        refresh_token: Option<String>,
2622        expires_in: Option<f64>,
2623        sub: String,
2624    }
2625
2626    fn parse_atproto_token_response_075(
2627        value: serde_json::Value,
2628    ) -> anyhow::Result<AtprotoOAuthTokenResponse075> {
2629        anyhow::ensure!(
2630            value.get("id_token").is_none(),
2631            "atproto OAuth token response must not contain id_token"
2632        );
2633        let parsed: AtprotoOAuthTokenResponse075 = serde_json::from_value(value)?;
2634        anyhow::ensure!(parsed.token_type == "DPoP", "token_type must be DPoP");
2635        anyhow::ensure!(
2636            parsed.scope.bytes().all(|byte| {
2637                byte == b' '
2638                    || byte == b'!'
2639                    || (b'#'..=b'[').contains(&byte)
2640                    || (b']'..=b'~').contains(&byte)
2641            }),
2642            "scope is not an OAuth scope value"
2643        );
2644        anyhow::ensure!(
2645            parsed.scope.split(' ').any(|scope| scope == "atproto"),
2646            "scope must contain atproto"
2647        );
2648        super::state::subject_did_for("https://schema.invalid", &parsed.sub)?;
2649        Ok(parsed)
2650    }
2651
2652    // Publish a disk-backed composite Policy signing pair so this test uses
2653    // the real PolicyService JWT issuance path. The tiny authority directory
2654    // remains because the process-global mint barrier checks disk each time.
2655    fn configure_test_policy_signing_authority() -> anyhow::Result<()> {
2656        use hyprstream_rpc::auth::{CompositeKeyPair, CompositePairRole, CompositePairState};
2657
2658        let authority_dir = tempfile::TempDir::new()?.keep();
2659        let ledger = authority_dir.join("ledger.json");
2660        let committed = authority_dir.join("committed");
2661        let prefix = authority_dir.join("committed-ledger");
2662        let lock = authority_dir.join("ledger.lock");
2663        let key_set = hyprstream_rpc::auth::global_composite_key_set();
2664        let version = key_set.snapshot().version() + 1;
2665        let digest = format!("oauth-handler-r5-{version}");
2666        let generation = serde_json::to_vec(&serde_json::json!({
2667            "version": version,
2668            "component_digest": digest,
2669        }))?;
2670        std::fs::write(&ledger, &generation)?;
2671        std::fs::write(&committed, &generation)?;
2672        std::fs::write(
2673            authority_dir.join(format!("committed-ledger-{version}-{digest}.json")),
2674            &generation,
2675        )?;
2676
2677        let (ml_signing, ml_verifying) = hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair();
2678        let ed_signing = Arc::new(ed25519_dalek::SigningKey::from_bytes(&[0x61; 32]));
2679        let kid = hyprstream_rpc::auth::composite_kid(&ml_verifying, &ed_signing.verifying_key());
2680        let now = chrono::Utc::now().timestamp();
2681        let pair = CompositeKeyPair::signing(
2682            kid,
2683            Arc::new(ml_signing),
2684            ed_signing,
2685            CompositePairRole::Policy,
2686            CompositePairState::Active,
2687            now - 60,
2688            now + 86_400,
2689        );
2690        key_set.configure_authority(ledger, committed, prefix, lock);
2691        key_set.publish(version, digest, vec![pair])?;
2692        Ok(())
2693    }
2694
2695    /// #1113 r5 handler-level conformance suite. Every HTTP exchange goes
2696    /// through the production create_app router and token issuance traverses
2697    /// a real in-process PolicyService.
2698    // The in-process harness opens a PGlite user store and a RocksDB refresh-token store.
2699    #[cfg(all(feature = "rocksdb", feature = "pglite"))]
2700    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2701    async fn oauth_handler_atproto_and_legacy_conformance() -> anyhow::Result<()> {
2702        crate::mac::install_explicit_test_dispatch_pep();
2703        // Interactive OAuth issuance (v16 §3.3) registers a fresh session with
2704        // the canonical registry, and the in-process policy authority validates
2705        // it before minting; both live in THIS process, so publish one isolated
2706        // in-memory session registry (plus a revocation store) — mirroring
2707        // production `init_process_authority_stores`, which this bespoke
2708        // in-process test bypasses. Guarded so a sibling that published first
2709        // keeps its handle; the registrations use distinct keys.
2710        if hyprstream_rpc::auth::global_session_registry().is_none() {
2711            let _ = hyprstream_rpc::auth::set_global_session_registry(std::sync::Arc::new(
2712                hyprstream_rpc::auth::InMemorySessionRegistry::new(),
2713            ));
2714        }
2715        if hyprstream_rpc::auth::global_credential_revocation_store().is_none() {
2716            let _ = hyprstream_rpc::auth::set_global_credential_revocation_store(
2717                std::sync::Arc::new(hyprstream_rpc::auth::InMemoryCredentialRevocationStore::new()),
2718            );
2719        }
2720        use base64::{
2721            engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},
2722            Engine as _,
2723        };
2724        use ed25519_dalek::Signer as _;
2725        use hyprstream_rpc::crypto::CryptoPolicy;
2726        use hyprstream_rpc::rpc_client::RpcClientImpl;
2727        use hyprstream_rpc::signer::LocalSigner;
2728        use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
2729        use hyprstream_rpc::transport::TransportConfig;
2730        use hyprstream_service::{InprocManager, ServiceManager as _};
2731        use sha2::{Digest as _, Sha256};
2732
2733        use super::state::RegisteredClient;
2734        use super::token_store::RocksDbTokenStore;
2735        use crate::auth::pglite_store::PgliteUserStore;
2736        use crate::auth::{AccountKeyCustody, PolicyManager, UserStore};
2737        use crate::services::PolicyService;
2738        use hyprstream_rpc_std::discovery_client::DiscoveryClient;
2739        use hyprstream_rpc_std::policy_client::PolicyClient;
2740        use hyprstream_rpc_std::policy_client::{IssueToken, IssueTokenProfile};
2741
2742        const ISSUER: &str = "https://pds.example.test:8443";
2743        const GENERIC_ISSUER: &str = "https://pds.example.test:8443/configured/path";
2744        const CLIENT_ID: &str = "handler-client";
2745        const PRIVATE_CLIENT_ID: &str = "handler-private-client";
2746        const REDIRECT_URI: &str = "https://client.example.test/callback";
2747        const MAPPED_DID: &str = "did:web:alice.acct.example.test";
2748        const HOSTED_TENANT: &str = "tenant-demo";
2749
2750        const PKCE_VERIFIER: &str = "r5-handler-pkce-verifier-abcdefghijklmnopqrstuvwxyz012345";
2751        const GENERIC_PKCE_VERIFIER: &str =
2752            "r7-generic-pkce-verifier-abcdefghijklmnopqrstuvwxyz012345";
2753
2754        let _ = hyprstream_rpc::envelope::install_verify_config(
2755            hyprstream_rpc::envelope::EnvelopeVerifyConfig {
2756                policy: CryptoPolicy::Classical,
2757                pq_store: None,
2758            },
2759        );
2760        let _ = hyprstream_rpc::envelope::install_response_verify_config(
2761            hyprstream_rpc::envelope::ResponseVerifyConfig {
2762                policy: CryptoPolicy::Classical,
2763                pq_store: None,
2764            },
2765        );
2766        // Resource-token verification fails closed on jti-bearing bearers
2767        // without the process-global revocation store. Install an in-memory
2768        // authority when no other test in this binary got there first — this
2769        // test must not depend on another test's fixture happening to run
2770        // earlier.
2771        if hyprstream_rpc::auth::global_credential_revocation_store().is_none() {
2772            let _ = hyprstream_rpc::auth::set_global_credential_revocation_store(Arc::new(
2773                hyprstream_rpc::auth::InMemoryCredentialRevocationStore::new(),
2774            ));
2775        }
2776        configure_test_policy_signing_authority()?;
2777
2778        let service_key = ed25519_dalek::SigningKey::from_bytes(&[0x62; 32]);
2779        let policy_tag = format!("oauth-handler-r5-{}", uuid::Uuid::new_v4());
2780        let git_dir = tempfile::TempDir::new()?;
2781        let git2db = Arc::new(tokio::sync::RwLock::new(
2782            git2db::Git2DB::open(git_dir.path()).await?,
2783        ));
2784        let policy_service = PolicyService::new(
2785            Arc::new(PolicyManager::permissive().await?),
2786            Arc::new(service_key.clone()),
2787            crate::config::TokenConfig::default(),
2788            git2db,
2789            TransportConfig::inproc(&policy_tag),
2790        )
2791        .with_default_audience(GENERIC_ISSUER.to_owned())
2792        // Production-equivalent key source: token signing resolves the composite
2793        // authority through the configured JwtKeySource (a `ClusterKeySource`
2794        // defaults its ledger to the process-global authority configured above).
2795        .with_jwt_key_source(Arc::new(hyprstream_rpc::auth::ClusterKeySource::new(
2796            service_key.verifying_key(),
2797            GENERIC_ISSUER.to_owned(),
2798        )))
2799        // Production does not install a PrimaryEnrollmentResolver. Standard
2800        // non-DPoP OAuth must work as a non-dispatch Bearer credential.
2801        .with_token_clearance_resolver(Arc::new(|subject| {
2802            use hyprstream_rpc::auth::mac::{Assurance, CompartmentSet, Level, SecurityLabel};
2803            (subject == MAPPED_DID).then(|| {
2804                SecurityLabel::new(
2805                    Level::Secret,
2806                    Assurance::PqHybrid,
2807                    CompartmentSet::single(0),
2808                )
2809            })
2810        }));
2811        let manager = InprocManager::new();
2812        let mut policy_handle = manager.spawn(Box::new(policy_service)).await?;
2813        let policy_client = PolicyClient::for_local_endpoint_bootstrap(
2814            &format!("inproc://{policy_tag}"),
2815            service_key.clone(),
2816            service_key.verifying_key(),
2817            None,
2818        )?;
2819
2820        let user_dir = tempfile::TempDir::new()?;
2821        let user_store = Arc::new(PgliteUserStore::open_for_test(user_dir.path()).await?);
2822        let user_key = ed25519_dalek::SigningKey::from_bytes(&[0x63; 32]);
2823        let hosted_binding = user_store
2824            .provision_hosted_account(
2825                "alice",
2826                MAPPED_DID,
2827                user_key.verifying_key(),
2828                AccountKeyCustody::SelfCustody,
2829            )
2830            .await?;
2831        let fingerprint = hosted_binding.fingerprint;
2832        user_store
2833            .activate_hosted_account(
2834                "alice",
2835                MAPPED_DID,
2836                &fingerprint,
2837                AccountKeyCustody::SelfCustody,
2838            )
2839            .await?;
2840        user_store
2841            .bind_existing_external_idp_to_hosted_account(
2842                "fixture-idp",
2843                "alice",
2844                "alice",
2845                MAPPED_DID,
2846            )
2847            .await?;
2848        assert_eq!(
2849            user_store
2850                .get_profile("alice")
2851                .await?
2852                .and_then(|profile| profile.atproto_did),
2853            Some(MAPPED_DID.to_owned())
2854        );
2855
2856        let dummy_key = ed25519_dalek::SigningKey::from_bytes(&[0x64; 32]);
2857        let dummy_remote = ed25519_dalek::SigningKey::from_bytes(&[0x65; 32]).verifying_key();
2858        let dummy_rpc = Arc::new(
2859            RpcClientImpl::new(
2860                LocalSigner::new(dummy_key),
2861                LazyUdsTransport::new("/dev/null/oauth-handler-discovery.sock".into()),
2862                Some(dummy_remote),
2863            )
2864            .with_response_verify_policy(CryptoPolicy::Classical),
2865        );
2866        let mut config = crate::config::OAuthConfig::default();
2867        // Generic OAuth preserves this path; atproto emissions use its origin.
2868        config.external_url = Some(GENERIC_ISSUER.to_owned());
2869
2870        struct FixtureAtprotoDidResolver(serde_json::Value);
2871        #[async_trait::async_trait]
2872        impl super::state::AtprotoDidDocumentResolver for FixtureAtprotoDidResolver {
2873            async fn resolve_document(&self, did: &str) -> anyhow::Result<serde_json::Value> {
2874                anyhow::ensure!(
2875                    self.0.get("id").and_then(serde_json::Value::as_str) == Some(did),
2876                    "fixture DID mismatch"
2877                );
2878                Ok(self.0.clone())
2879            }
2880        }
2881        // #1314: the hosted account record is the authority binding between
2882        // this DID and HOSTED_TENANT. Its generated #atproto key signs the
2883        // service assertion below, so the fixture exercises the real record
2884        // shape rather than an independent tenant map.
2885        let account_ed = ed25519_dalek::SigningKey::generate(&mut rand::rngs::OsRng);
2886        let (account_pq, account_pq_vk) = hyprstream_crypto::pq::ml_dsa_generate_keypair();
2887        let account_hybrid = hyprstream_pds::did_op::HybridRotationKey::new(
2888            account_ed.verifying_key().to_bytes(),
2889            hyprstream_crypto::pq::ml_dsa_vk_bytes(&account_pq_vk),
2890        )?;
2891        let account_rotations = hyprstream_pds::did_op::GenesisRotationKeys::new(
2892            hyprstream_pds::did_op::UserRotationKey::new(account_hybrid),
2893            hyprstream_pds::did_op::RecoveryKeyEnrollment::Declined,
2894            hyprstream_pds::did_op::HostKeyEnrollment::Absent,
2895        )?;
2896        let account_mint = hyprstream_pds::HostedAccountMint::begin(
2897            hyprstream_pds::AllocatedAccountName::new("alice", MAPPED_DID)?,
2898            account_rotations,
2899        )?;
2900        let account_document = account_mint.seal_did_document(ISSUER)?;
2901        let pending_account = account_mint.prepare_genesis(
2902            account_document,
2903            hyprstream_pds::did_op::GenesisRepoHead::EmptyRepo,
2904        )?;
2905        let account_signature = hyprstream_pds::did_op::sign_genesis(
2906            pending_account.unsigned_genesis(),
2907            &account_ed,
2908            &account_pq,
2909        )?;
2910        let sealed_account = pending_account.seal(account_signature)?;
2911        let atproto_signing_key = sealed_account.atproto_signing_key().clone();
2912        let atproto_document = serde_json::from_slice(sealed_account.did_document().as_bytes())?;
2913        // Exercise the same local_store selection and production PEP/mount
2914        // constructor used by OAuth startup, against a real descriptor-bound
2915        // directory tree. This deliberately does not configure account.http.
2916        let pds_root = tempfile::TempDir::new()?;
2917        let audit_sink: Arc<dyn crate::mac::audit::AuditSink> =
2918            Arc::new(crate::mac::audit::NullAuditSink);
2919        let local_account_config = crate::account::AccountZoneConfig {
2920            zone: Some("acct.example.test".to_owned()),
2921            local_store: true,
2922            http: None,
2923            ..Default::default()
2924        };
2925        let hosted_account_store = open_hosted_account_store(
2926            &local_account_config,
2927            None,
2928            Some(pds_root.path()),
2929            Some(&audit_sink),
2930        )?
2931        .expect("local_store opens production hosted-account store");
2932        let resolver_authority =
2933            hyprstream_rpc::Subject::new(hyprstream_pds_service::OAUTH_ACCOUNT_RESOLVER_SUBJECT);
2934        hosted_account_store
2935            .refresh_hosted_did_index(&resolver_authority)
2936            .await?;
2937        assert_eq!(
2938            hosted_account_store
2939                .resolve_tenant_for_hosted_did(&resolver_authority, MAPPED_DID)
2940                .await?,
2941            None,
2942            "startup has indexed an empty PDS root"
2943        );
2944        let account_dir = pds_root
2945            .path()
2946            .join(HOSTED_TENANT)
2947            .join(hyprstream_pds_service::PDS_ACCOUNTS_DIRECTORY)
2948            .join("alice");
2949        std::fs::create_dir_all(&account_dir)?;
2950        std::fs::write(
2951            account_dir.join(hyprstream_pds_service::PDS_ACCOUNT_RECORD_FILE),
2952            sealed_account.record_bytes(),
2953        )?;
2954        std::fs::write(
2955            account_dir.join(hyprstream_pds::ATPROTO_SIGNING_KEY_FILE),
2956            atproto_signing_key.to_bytes(),
2957        )?;
2958        let mut oauth_state = OAuthState::new(
2959            &config,
2960            policy_client,
2961            DiscoveryClient::new(dummy_rpc),
2962            service_key.verifying_key().to_bytes(),
2963        )
2964        .with_user_store(crate::auth::ProductionUserStore::for_test(
2965            user_store.clone(),
2966        ))
2967        .with_hosted_account_store(hosted_account_store)
2968        .with_atproto_did_resolver(Arc::new(FixtureAtprotoDidResolver(atproto_document)))
2969        .with_hosted_account_zone(crate::account::AccountZone::new("acct.example.test")?);
2970        // This is the post-activation refresh hook called by the OAuth signup
2971        // callback. It must replace the warmed empty snapshot immediately,
2972        // without waiting for the negative-entry TTL.
2973        oauth_state
2974            .refresh_hosted_account_index_after_signup()
2975            .await
2976            .map_err(anyhow::Error::msg)?;
2977        assert_eq!(
2978            oauth_state
2979                .hosted_account_tenant(MAPPED_DID)
2980                .await
2981                .map_err(anyhow::Error::msg)?,
2982            Some(HOSTED_TENANT.to_owned())
2983        );
2984        let token_dir = tempfile::TempDir::new()?;
2985        oauth_state.with_token_store_impl(Arc::new(RocksDbTokenStore::open(
2986            token_dir.path().join("refresh.db"),
2987        )?));
2988        let upstream = Router::new()
2989            .route(
2990                "/token",
2991                post(|| async { axum::Json(serde_json::json!({"access_token": "fixture-token"})) }),
2992            )
2993            .route(
2994                "/userinfo",
2995                axum::routing::get(|| async { axum::Json(serde_json::json!({"sub": "alice"})) }),
2996            );
2997        let upstream_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
2998        let upstream_base = format!("http://{}", upstream_listener.local_addr()?);
2999        let upstream_server =
3000            tokio::spawn(async move { axum::serve(upstream_listener, upstream).await });
3001        // A local OIDC issuer serves discovery, JWKS, and signed ID tokens.
3002        // The callback uses the production signature, issuer, audience, and
3003        // nonce checks before entering the same hosted-account token path.
3004        let oidc_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
3005        let oidc_base = format!("http://{}", oidc_listener.local_addr()?);
3006        let oidc_key = ed25519_dalek::SigningKey::from_bytes(&[0x81; 32]);
3007        let sign_oidc = |issuer: &str, audience: &str, nonce: &str| -> String {
3008            let header = serde_json::json!({"alg": "EdDSA", "typ": "JWT", "kid": "fixture-key"});
3009            let claims = serde_json::json!({
3010                "iss": issuer,
3011                "aud": audience,
3012                "sub": "alice",
3013                "nonce": nonce,
3014                "exp": chrono::Utc::now().timestamp() + 300,
3015            });
3016            let signed = format!(
3017                "{}.{}",
3018                URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).expect("header")),
3019                URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).expect("claims")),
3020            );
3021            format!(
3022                "{}.{}",
3023                signed,
3024                URL_SAFE_NO_PAD.encode(oidc_key.sign(signed.as_bytes()).to_bytes())
3025            )
3026        };
3027        let sign_federate = |owner_did: &str| -> String {
3028            let header = serde_json::json!({"alg": "EdDSA", "typ": "JWT", "kid": "fixture-key"});
3029            let claims = serde_json::json!({
3030                "iss": super::federate_source::ISSUER,
3031                "aud": "fixture-oidc-client",
3032                "sub": "federate-owner-subject",
3033                "nonce": "federate-nonce",
3034                "exp": chrono::Utc::now().timestamp() + 300,
3035                "federated_claims": {
3036                    "connector_id": "atproto",
3037                    "user_id": owner_did
3038                }
3039            });
3040            let signed = format!(
3041                "{}.{}",
3042                URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).expect("header")),
3043                URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).expect("claims")),
3044            );
3045            format!(
3046                "{}.{}",
3047                signed,
3048                URL_SAFE_NO_PAD.encode(oidc_key.sign(signed.as_bytes()).to_bytes())
3049            )
3050        };
3051        let oidc_tokens = Arc::new(std::collections::HashMap::from([
3052            (
3053                "oidc-good".to_owned(),
3054                sign_oidc(&oidc_base, "fixture-oidc-client", "fixture-nonce"),
3055            ),
3056            (
3057                "oidc-wrong-issuer".to_owned(),
3058                sign_oidc(
3059                    "http://wrong-idp.example",
3060                    "fixture-oidc-client",
3061                    "fixture-nonce",
3062                ),
3063            ),
3064            (
3065                "oidc-wrong-audience".to_owned(),
3066                sign_oidc(&oidc_base, "another-client", "fixture-nonce"),
3067            ),
3068            (
3069                "oidc-wrong-nonce".to_owned(),
3070                sign_oidc(&oidc_base, "fixture-oidc-client", "another-nonce"),
3071            ),
3072            (
3073                "federate-owner-good".to_owned(),
3074                sign_federate("did:plc:abcdefghijklmnqrstuvwx2p"),
3075            ),
3076            (
3077                "federate-wrong-owner".to_owned(),
3078                sign_federate("did:plc:bcdefghijklmnqrstuvwx2pa"),
3079            ),
3080        ]));
3081        let oidc_discovery = serde_json::json!({
3082            "issuer": oidc_base,
3083            "authorization_endpoint": format!("{oidc_base}/authorize?realm=fixture"),
3084            "token_endpoint": format!("{oidc_base}/token"),
3085            "jwks_uri": format!("{oidc_base}/jwks"),
3086        });
3087        let oidc_jwks = serde_json::json!({"keys": [{
3088            "kty": "OKP", "crv": "Ed25519", "alg": "EdDSA", "kid": "fixture-key",
3089            "x": URL_SAFE_NO_PAD.encode(oidc_key.verifying_key().as_bytes()),
3090        }]});
3091        let oidc_upstream = Router::new()
3092            .route("/.well-known/openid-configuration", axum::routing::get(move || {
3093                let document = oidc_discovery.clone();
3094                async move { axum::Json(document) }
3095            }))
3096            .route("/jwks", axum::routing::get(move || {
3097                let keys = oidc_jwks.clone();
3098                async move { axum::Json(keys) }
3099            }))
3100            .route("/token", post(move |axum::Form(form): axum::Form<std::collections::HashMap<String, String>>| {
3101                let tokens = oidc_tokens.clone();
3102                async move {
3103                    axum::Json(serde_json::json!({
3104                        "id_token": tokens.get(form.get("code").map(String::as_str).unwrap_or("missing")).cloned().unwrap_or_default(),
3105                    }))
3106                }
3107            }));
3108        let oidc_server =
3109            tokio::spawn(async move { axum::serve(oidc_listener, oidc_upstream).await });
3110        user_store
3111            .bind_existing_external_idp_to_hosted_account(&oidc_base, "alice", "alice", MAPPED_DID)
3112            .await?;
3113        let mut fixture_provider: crate::config::OidcProviderConfig =
3114            serde_json::from_value(serde_json::json!({
3115                "kind": "oauth2",
3116                "client_id": "fixture-upstream-client",
3117                "authorization_endpoint": format!("{upstream_base}/authorize"),
3118                "token_endpoint_url": format!("{upstream_base}/token"),
3119                "userinfo_endpoint": format!("{upstream_base}/userinfo")
3120            }))?;
3121        fixture_provider.user_mapping = crate::config::UserMappingStrategy::Claim {
3122            name: "sub".to_owned(),
3123        };
3124        oauth_state
3125            .external_providers
3126            .insert("fixture-idp".to_owned(), fixture_provider);
3127        let mut oidc_provider: crate::config::OidcProviderConfig = serde_json::from_value(
3128            serde_json::json!({
3129                "kind": "oidc", "client_id": "fixture-oidc-client", "issuer_url": oidc_base, "allow_http": true,
3130            }),
3131        )?;
3132        oidc_provider.user_mapping = crate::config::UserMappingStrategy::Claim {
3133            name: "sub".to_owned(),
3134        };
3135        oauth_state
3136            .external_providers
3137            .insert("fixture-oidc".to_owned(), oidc_provider);
3138        let federate_provider: crate::config::OidcProviderConfig =
3139            serde_json::from_value(serde_json::json!({
3140                "kind": "oidc",
3141                "client_id": "fixture-oidc-client",
3142                "issuer_url": super::federate_source::ISSUER,
3143                "scopes": ["openid", "profile", "federated:id"],
3144                "federate_atproto_owner": {
3145                    "owner_did": "did:plc:abcdefghijklmnqrstuvwx2p"
3146                }
3147            }))?;
3148        oauth_state
3149            .external_providers
3150            .insert("federate".to_owned(), federate_provider);
3151        oauth_state.http_client = reqwest::Client::builder().no_proxy().build()?;
3152        let state = Arc::new(oauth_state);
3153        state
3154            .oidc_discovery
3155            .seed_for_test(
3156                crate::services::oauth::oidc_discovery::OidcProviderMetadata {
3157                    issuer: super::federate_source::ISSUER.to_owned(),
3158                    authorization_endpoint: format!("{oidc_base}/authorize"),
3159                    token_endpoint: format!("{oidc_base}/token"),
3160                    userinfo_endpoint: None,
3161                    jwks_uri: format!("{oidc_base}/jwks"),
3162                    scopes_supported: Vec::new(),
3163                    id_token_signing_alg_values_supported: vec!["EdDSA".to_owned()],
3164                },
3165            )
3166            .await;
3167        state.clients.write().await.insert(
3168            CLIENT_ID.to_owned(),
3169            RegisteredClient {
3170                client_id: CLIENT_ID.to_owned(),
3171                redirect_uris: vec![REDIRECT_URI.to_owned()],
3172                client_name: Some("Handler Conformance Client".to_owned()),
3173                client_uri: None,
3174                logo_uri: None,
3175                grant_types: vec![
3176                    "authorization_code".to_owned(),
3177                    "refresh_token".to_owned(),
3178                    "urn:ietf:params:oauth:grant-type:device_code".to_owned(),
3179                    "urn:ietf:params:oauth:grant-type:token-exchange".to_owned(),
3180                ],
3181                response_types: vec!["code".to_owned()],
3182                token_endpoint_auth_method: Some("none".to_owned()),
3183                jwks: None,
3184                jwks_uri: None,
3185                hyprstream_node_did: None,
3186                scope: Some("atproto read:*:*".to_owned()),
3187                dpop_bound_access_tokens: None,
3188                is_cimd: false,
3189                registered_at: std::time::Instant::now(),
3190            },
3191        );
3192        let private_client_key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
3193        let private_client_point = private_client_key.verifying_key().to_encoded_point(false);
3194        // A second registered key for the same client: proves refresh cannot
3195        // switch assertion keys mid-session (#1146 T3.3).
3196        let private_client_key_2 = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
3197        let private_client_point_2 = private_client_key_2.verifying_key().to_encoded_point(false);
3198        state.clients.write().await.insert(
3199            PRIVATE_CLIENT_ID.to_owned(),
3200            RegisteredClient {
3201                client_id: PRIVATE_CLIENT_ID.to_owned(),
3202                redirect_uris: vec![REDIRECT_URI.to_owned()],
3203                client_name: Some("Handler Private Client".to_owned()),
3204                client_uri: None,
3205                logo_uri: None,
3206                grant_types: vec!["authorization_code".to_owned()],
3207                response_types: vec!["code".to_owned()],
3208                token_endpoint_auth_method: Some("private_key_jwt".to_owned()),
3209                jwks: Some(serde_json::json!({"keys": [{
3210                    "kty": "EC",
3211                    "crv": "P-256",
3212                    "x": URL_SAFE_NO_PAD.encode(private_client_point.x().unwrap()),
3213                    "y": URL_SAFE_NO_PAD.encode(private_client_point.y().unwrap()),
3214                    "kid": "private-k1",
3215                }, {
3216                    "kty": "EC",
3217                    "crv": "P-256",
3218                    "x": URL_SAFE_NO_PAD.encode(private_client_point_2.x().unwrap()),
3219                    "y": URL_SAFE_NO_PAD.encode(private_client_point_2.y().unwrap()),
3220                    "kid": "private-k2",
3221                }]})),
3222                jwks_uri: None,
3223                hyprstream_node_did: None,
3224                scope: Some("atproto".to_owned()),
3225                dpop_bound_access_tokens: Some(true),
3226                is_cimd: false,
3227                registered_at: std::time::Instant::now(),
3228            },
3229        );
3230        let cors = crate::config::server::CorsConfig {
3231            enabled: false,
3232            ..Default::default()
3233        };
3234        let app = create_app(Arc::clone(&state), &cors);
3235
3236        // The external callback shares the generic code/token path. A mock
3237        // OAuth2 IdP supplies claims; the local account, hosted account record,
3238        // policy authority, and token endpoint are the real in-process fixture.
3239        let external_challenge =
3240            URL_SAFE_NO_PAD.encode(Sha256::digest(GENERIC_PKCE_VERIFIER.as_bytes()));
3241        let make_external_pending = |external_state: &str| state::PendingExternalAuth {
3242            provider_slug: "fixture-idp".to_owned(),
3243            external_state: external_state.to_owned(),
3244            external_nonce: String::new(),
3245            provider_kind: crate::config::ProviderKind::OAuth2,
3246            pkce_supported: true,
3247            pkce_verifier: "upstream-pkce-verifier".to_owned(),
3248            client_secret: None,
3249            token_endpoint: format!("{upstream_base}/token"),
3250            original_request: Some(authorize::AuthorizeParams {
3251                client_id: CLIENT_ID.to_owned(),
3252                redirect_uri: REDIRECT_URI.to_owned(),
3253                code_challenge: external_challenge.clone(),
3254                code_challenge_method: "S256".to_owned(),
3255                response_type: "code".to_owned(),
3256                state: Some("external-state&value".to_owned()),
3257                scope: Some("read:*:*".to_owned()),
3258                resource: None,
3259                nonce: None,
3260                dpop_jkt: None,
3261                client_assertion_jkt: None,
3262            }),
3263            federate_owner_link: None,
3264            created_at: std::time::Instant::now(),
3265            expires_at: std::time::Instant::now() + std::time::Duration::from_secs(60),
3266        };
3267        for (external_state, verifier, expected_success) in [
3268            ("external-good", GENERIC_PKCE_VERIFIER, true),
3269            ("external-wrong-pkce", "wrong-verifier", false),
3270        ] {
3271            state.pending_external_auths.write().await.insert(
3272                external_state.to_owned(),
3273                make_external_pending(external_state),
3274            );
3275            let callback = oidc_callback::external_callback(
3276                axum::extract::State(Arc::clone(&state)),
3277                axum::extract::Path("fixture-idp".to_owned()),
3278                axum::http::HeaderMap::new(),
3279                axum::extract::Query(oidc_callback::CallbackParams {
3280                    code: "upstream-code".to_owned(),
3281                    state: external_state.to_owned(),
3282                }),
3283            )
3284            .await;
3285            assert!(
3286                callback.status().is_redirection(),
3287                "external callback: {}",
3288                callback.status()
3289            );
3290            let location = callback
3291                .headers()
3292                .get(axum::http::header::LOCATION)
3293                .and_then(|value| value.to_str().ok())
3294                .expect("external code redirect");
3295            let redirect = url::Url::parse(location)?;
3296            assert_eq!(
3297                redirect
3298                    .query_pairs()
3299                    .find(|(key, _)| key == "state")
3300                    .map(|(_, value)| value.to_string())
3301                    .as_deref(),
3302                Some("external-state&value")
3303            );
3304            assert_eq!(
3305                redirect
3306                    .query_pairs()
3307                    .find(|(key, _)| key == "iss")
3308                    .map(|(_, value)| value.to_string())
3309                    .as_deref(),
3310                Some(GENERIC_ISSUER)
3311            );
3312            let code = redirect
3313                .query_pairs()
3314                .find(|(key, _)| key == "code")
3315                .map(|(_, value)| value.to_string())
3316                .expect("external authorization code");
3317            let token = post_form(
3318                &app,
3319                "/oauth/token",
3320                &[
3321                    ("grant_type", "authorization_code"),
3322                    ("client_id", CLIENT_ID),
3323                    ("redirect_uri", REDIRECT_URI),
3324                    ("code", &code),
3325                    ("code_verifier", verifier),
3326                ],
3327                None,
3328                false,
3329            )
3330            .await;
3331            if expected_success {
3332                assert_eq!(token.status(), axum::http::StatusCode::OK);
3333                let claims = jwt_claims(
3334                    response_json(token).await["access_token"]
3335                        .as_str()
3336                        .expect("access token"),
3337                );
3338                assert_eq!(claims["sub"], "alice");
3339                assert_eq!(claims["tenant"], HOSTED_TENANT);
3340            } else {
3341                assert_eq!(token.status(), axum::http::StatusCode::BAD_REQUEST);
3342                assert_eq!(response_json(token).await["error"], "invalid_grant");
3343            }
3344        }
3345        for (upstream_code, expected_status) in [
3346            ("oidc-good", axum::http::StatusCode::TEMPORARY_REDIRECT),
3347            ("oidc-wrong-issuer", axum::http::StatusCode::BAD_GATEWAY),
3348            ("oidc-wrong-audience", axum::http::StatusCode::BAD_GATEWAY),
3349            ("oidc-wrong-nonce", axum::http::StatusCode::BAD_REQUEST),
3350        ] {
3351            let mut pending = make_external_pending(upstream_code);
3352            pending.provider_slug = "fixture-oidc".to_owned();
3353            pending.provider_kind = crate::config::ProviderKind::Oidc;
3354            pending.external_nonce = "fixture-nonce".to_owned();
3355            pending.token_endpoint = format!("{oidc_base}/token");
3356            state
3357                .pending_external_auths
3358                .write()
3359                .await
3360                .insert(upstream_code.to_owned(), pending);
3361            let callback = oidc_callback::external_callback(
3362                axum::extract::State(Arc::clone(&state)),
3363                axum::extract::Path("fixture-oidc".to_owned()),
3364                axum::http::HeaderMap::new(),
3365                axum::extract::Query(oidc_callback::CallbackParams {
3366                    code: upstream_code.to_owned(),
3367                    state: upstream_code.to_owned(),
3368                }),
3369            )
3370            .await;
3371            assert_eq!(
3372                callback.status(),
3373                expected_status,
3374                "OIDC case {upstream_code}"
3375            );
3376            if upstream_code == "oidc-good" {
3377                let location = callback
3378                    .headers()
3379                    .get(axum::http::header::LOCATION)
3380                    .and_then(|header| header.to_str().ok())
3381                    .expect("OIDC redirect");
3382                let code = url::Url::parse(location)?
3383                    .query_pairs()
3384                    .find(|(name, _)| name == "code")
3385                    .map(|(_, value)| value.to_string())
3386                    .expect("OIDC authorization code");
3387                let token = post_form(
3388                    &app,
3389                    "/oauth/token",
3390                    &[
3391                        ("grant_type", "authorization_code"),
3392                        ("client_id", CLIENT_ID),
3393                        ("redirect_uri", REDIRECT_URI),
3394                        ("code", &code),
3395                        ("code_verifier", GENERIC_PKCE_VERIFIER),
3396                    ],
3397                    None,
3398                    false,
3399                )
3400                .await;
3401                assert_eq!(token.status(), axum::http::StatusCode::OK);
3402                let body = response_json(token).await;
3403                let claims = jwt_claims(body["access_token"].as_str().expect("access token"));
3404                assert_eq!(claims["sub"], "alice");
3405                assert_eq!(claims["tenant"], HOSTED_TENANT);
3406            }
3407        }
3408        // Federate's nested owner claim is checked at the signed callback
3409        // boundary before the exact issuer/subject link is created. A bad
3410        // owner claim cannot leave a binding or authorization code behind.
3411        let make_federate_pending = |external_state: &str| {
3412            let mut pending = make_external_pending(external_state);
3413            pending.provider_slug = "federate".to_owned();
3414            pending.provider_kind = crate::config::ProviderKind::Oidc;
3415            pending.external_nonce = "federate-nonce".to_owned();
3416            pending.token_endpoint = format!("{oidc_base}/token");
3417            pending
3418        };
3419        let wrong_state = "federate-wrong-owner-state";
3420        let pending_codes_before_wrong_owner = state.pending_codes.read().await.len();
3421        state
3422            .pending_external_auths
3423            .write()
3424            .await
3425            .insert(wrong_state.to_owned(), make_federate_pending(wrong_state));
3426        let wrong_owner = oidc_callback::external_callback(
3427            axum::extract::State(Arc::clone(&state)),
3428            axum::extract::Path("federate".to_owned()),
3429            axum::http::HeaderMap::new(),
3430            axum::extract::Query(oidc_callback::CallbackParams {
3431                code: "federate-wrong-owner".to_owned(),
3432                state: wrong_state.to_owned(),
3433            }),
3434        )
3435        .await;
3436        assert_eq!(wrong_owner.status(), axum::http::StatusCode::FORBIDDEN);
3437        assert_eq!(
3438            state.pending_codes.read().await.len(),
3439            pending_codes_before_wrong_owner
3440        );
3441        assert_eq!(
3442            user_store
3443                .get_external_identity_user(
3444                    super::federate_source::ISSUER,
3445                    "federate-owner-subject",
3446                )
3447                .await?,
3448            None
3449        );
3450
3451        // A fresh hosted account links through an explicit local-session flow.
3452        // The provider config pins only the launcher's external owner DID; the
3453        // account target comes from the authenticated session and unique DID
3454        // mapping, never from a request field.
3455        let session_id = state
3456            .sessions
3457            .create_atproto(MAPPED_DID.to_owned(), Some(HOSTED_TENANT.to_owned()))
3458            .await;
3459        let mut link_headers = axum::http::HeaderMap::new();
3460        link_headers.insert(
3461            axum::http::header::ORIGIN,
3462            "https://ui.example.test".parse().unwrap(),
3463        );
3464        link_headers.insert(
3465            axum::http::header::COOKIE,
3466            format!("{}={session_id}", session::SESSION_COOKIE_NAME)
3467                .parse()
3468                .unwrap(),
3469        );
3470        let start_owner_link = || {
3471            oidc_callback::begin_federate_owner_link(
3472                axum::extract::State(Arc::clone(&state)),
3473                axum::Extension(vec!["https://ui.example.test".to_owned()]),
3474                link_headers.clone(),
3475            )
3476        };
3477        let mut missing_origin_headers = link_headers.clone();
3478        missing_origin_headers.remove(axum::http::header::ORIGIN);
3479        let pending_before_missing_origin = state.pending_external_auths.read().await.len();
3480        let missing_origin = oidc_callback::begin_federate_owner_link(
3481            axum::extract::State(Arc::clone(&state)),
3482            axum::Extension(vec!["https://ui.example.test".to_owned()]),
3483            missing_origin_headers,
3484        )
3485        .await;
3486        assert_eq!(missing_origin.status(), axum::http::StatusCode::FORBIDDEN);
3487        assert_eq!(
3488            state.pending_external_auths.read().await.len(),
3489            pending_before_missing_origin,
3490            "missing Origin must not create an OIDC transaction"
3491        );
3492        let wrong_tenant_session = state
3493            .sessions
3494            .create_atproto(MAPPED_DID.to_owned(), Some("wrong.example.test".to_owned()))
3495            .await;
3496        let mut wrong_tenant_headers = link_headers.clone();
3497        wrong_tenant_headers.insert(
3498            axum::http::header::COOKIE,
3499            format!("{}={wrong_tenant_session}", session::SESSION_COOKIE_NAME)
3500                .parse()
3501                .unwrap(),
3502        );
3503        let pending_before_wrong_tenant = state.pending_external_auths.read().await.len();
3504        let wrong_tenant_start = oidc_callback::begin_federate_owner_link(
3505            axum::extract::State(Arc::clone(&state)),
3506            axum::Extension(vec!["https://ui.example.test".to_owned()]),
3507            wrong_tenant_headers,
3508        )
3509        .await;
3510        assert_eq!(
3511            wrong_tenant_start.status(),
3512            axum::http::StatusCode::FORBIDDEN,
3513            "a hosted DID session with a different verified tenant cannot begin owner linking"
3514        );
3515        assert_eq!(
3516            state.pending_external_auths.read().await.len(),
3517            pending_before_wrong_tenant,
3518            "tenant mismatch must not create an OIDC transaction"
3519        );
3520        let start = start_owner_link().await;
3521        assert_eq!(start.status(), axum::http::StatusCode::OK);
3522        let start_body = axum::body::to_bytes(start.into_body(), usize::MAX).await?;
3523        let start_json: serde_json::Value = serde_json::from_slice(&start_body)?;
3524        let start_url = url::Url::parse(start_json["authorization_url"].as_str().unwrap())?;
3525        let link_state = start_url
3526            .query_pairs()
3527            .find(|(name, _)| name == "state")
3528            .map(|(_, value)| value.to_string())
3529            .expect("one-use Federate state");
3530        state
3531            .pending_external_auths
3532            .write()
3533            .await
3534            .get_mut(&link_state)
3535            .unwrap()
3536            .external_nonce = "federate-nonce".to_owned();
3537        let wrong_owner_link = oidc_callback::external_callback(
3538            axum::extract::State(Arc::clone(&state)),
3539            axum::extract::Path("federate".to_owned()),
3540            link_headers.clone(),
3541            axum::extract::Query(oidc_callback::CallbackParams {
3542                code: "federate-wrong-owner".to_owned(),
3543                state: link_state,
3544            }),
3545        )
3546        .await;
3547        assert_eq!(wrong_owner_link.status(), axum::http::StatusCode::FORBIDDEN);
3548        assert_eq!(
3549            user_store
3550                .get_external_identity_user(
3551                    super::federate_source::ISSUER,
3552                    "federate-owner-subject",
3553                )
3554                .await?,
3555            None
3556        );
3557
3558        let start = start_owner_link().await;
3559        assert_eq!(start.status(), axum::http::StatusCode::OK);
3560        let start_body = axum::body::to_bytes(start.into_body(), usize::MAX).await?;
3561        let start_json: serde_json::Value = serde_json::from_slice(&start_body)?;
3562        let link_state = url::Url::parse(start_json["authorization_url"].as_str().unwrap())?
3563            .query_pairs()
3564            .find(|(name, _)| name == "state")
3565            .map(|(_, value)| value.to_string())
3566            .expect("one-use Federate state");
3567        state
3568            .pending_external_auths
3569            .write()
3570            .await
3571            .get_mut(&link_state)
3572            .unwrap()
3573            .external_nonce = "federate-nonce".to_owned();
3574        let wrong_session_id = state
3575            .sessions
3576            .create_atproto(MAPPED_DID.to_owned(), Some(HOSTED_TENANT.to_owned()))
3577            .await;
3578        let mut wrong_session_headers = link_headers.clone();
3579        wrong_session_headers.insert(
3580            axum::http::header::COOKIE,
3581            format!("{}={wrong_session_id}", session::SESSION_COOKIE_NAME)
3582                .parse()
3583                .unwrap(),
3584        );
3585        let wrong_session = oidc_callback::external_callback(
3586            axum::extract::State(Arc::clone(&state)),
3587            axum::extract::Path("federate".to_owned()),
3588            wrong_session_headers,
3589            axum::extract::Query(oidc_callback::CallbackParams {
3590                code: "federate-owner-good".to_owned(),
3591                state: link_state,
3592            }),
3593        )
3594        .await;
3595        assert_eq!(
3596            wrong_session.status(),
3597            axum::http::StatusCode::FORBIDDEN,
3598            "a different signed-in session cannot consume the owner's link intent"
3599        );
3600        assert_eq!(
3601            user_store
3602                .get_external_identity_user(
3603                    super::federate_source::ISSUER,
3604                    "federate-owner-subject",
3605                )
3606                .await?,
3607            None
3608        );
3609
3610        let start = start_owner_link().await;
3611        assert_eq!(start.status(), axum::http::StatusCode::OK);
3612        let start_body = axum::body::to_bytes(start.into_body(), usize::MAX).await?;
3613        let start_json: serde_json::Value = serde_json::from_slice(&start_body)?;
3614        let link_state = url::Url::parse(start_json["authorization_url"].as_str().unwrap())?
3615            .query_pairs()
3616            .find(|(name, _)| name == "state")
3617            .map(|(_, value)| value.to_string())
3618            .expect("one-use Federate state");
3619        state
3620            .pending_external_auths
3621            .write()
3622            .await
3623            .get_mut(&link_state)
3624            .unwrap()
3625            .external_nonce = "federate-nonce".to_owned();
3626        let linked_owner = oidc_callback::external_callback(
3627            axum::extract::State(Arc::clone(&state)),
3628            axum::extract::Path("federate".to_owned()),
3629            link_headers.clone(),
3630            axum::extract::Query(oidc_callback::CallbackParams {
3631                code: "federate-owner-good".to_owned(),
3632                state: link_state.clone(),
3633            }),
3634        )
3635        .await;
3636        assert_eq!(
3637            linked_owner.status(),
3638            axum::http::StatusCode::TEMPORARY_REDIRECT
3639        );
3640        let link_return = linked_owner
3641            .headers()
3642            .get(axum::http::header::LOCATION)
3643            .and_then(|header| header.to_str().ok())
3644            .expect("Federate owner link return");
3645        assert_eq!(link_return, "https://ui.example.test/hosts");
3646        assert!(state.pending_codes.read().await.is_empty());
3647        assert_eq!(
3648            user_store
3649                .get_external_identity_user(
3650                    super::federate_source::ISSUER,
3651                    "federate-owner-subject",
3652                )
3653                .await?
3654                .as_deref(),
3655            Some("alice")
3656        );
3657        let replay = oidc_callback::external_callback(
3658            axum::extract::State(Arc::clone(&state)),
3659            axum::extract::Path("federate".to_owned()),
3660            link_headers.clone(),
3661            axum::extract::Query(oidc_callback::CallbackParams {
3662                code: "federate-owner-good".to_owned(),
3663                state: link_state,
3664            }),
3665        )
3666        .await;
3667        assert_eq!(
3668            replay.status(),
3669            axum::http::StatusCode::BAD_REQUEST,
3670            "a consumed owner-link state cannot be replayed"
3671        );
3672        assert_eq!(
3673            user_store
3674                .get_external_identity_user(
3675                    super::federate_source::ISSUER,
3676                    "federate-owner-subject",
3677                )
3678                .await?
3679                .as_deref(),
3680            Some("alice")
3681        );
3682
3683        let good_state = "federate-good-state";
3684        state
3685            .pending_external_auths
3686            .write()
3687            .await
3688            .insert(good_state.to_owned(), make_federate_pending(good_state));
3689        let good_owner = oidc_callback::external_callback(
3690            axum::extract::State(Arc::clone(&state)),
3691            axum::extract::Path("federate".to_owned()),
3692            axum::http::HeaderMap::new(),
3693            axum::extract::Query(oidc_callback::CallbackParams {
3694                code: "federate-owner-good".to_owned(),
3695                state: good_state.to_owned(),
3696            }),
3697        )
3698        .await;
3699        assert_eq!(
3700            good_owner.status(),
3701            axum::http::StatusCode::TEMPORARY_REDIRECT
3702        );
3703        assert_eq!(
3704            user_store
3705                .get_external_identity_user(
3706                    super::federate_source::ISSUER,
3707                    "federate-owner-subject",
3708                )
3709                .await?
3710                .as_deref(),
3711            Some("alice")
3712        );
3713        let good_code = url::Url::parse(
3714            good_owner
3715                .headers()
3716                .get(axum::http::header::LOCATION)
3717                .and_then(|header| header.to_str().ok())
3718                .expect("Federate owner redirect"),
3719        )?
3720        .query_pairs()
3721        .find(|(name, _)| name == "code")
3722        .map(|(_, value)| value.to_string())
3723        .expect("Federate authorization code");
3724        let good_token = post_form(
3725            &app,
3726            "/oauth/token",
3727            &[
3728                ("grant_type", "authorization_code"),
3729                ("client_id", CLIENT_ID),
3730                ("redirect_uri", REDIRECT_URI),
3731                ("code", &good_code),
3732                ("code_verifier", GENERIC_PKCE_VERIFIER),
3733            ],
3734            None,
3735            false,
3736        )
3737        .await;
3738        assert_eq!(good_token.status(), axum::http::StatusCode::OK);
3739        let federate_claims = jwt_claims(
3740            response_json(good_token).await["access_token"]
3741                .as_str()
3742                .expect("Federate access token"),
3743        );
3744        assert_eq!(federate_claims["sub"], "alice");
3745        assert_eq!(federate_claims["tenant"], HOSTED_TENANT);
3746
3747        // A code created while the account is active is rejected if an
3748        // administrator deactivates the account before token issuance.
3749        let inactive_state = "federate-inactive-state";
3750        state.pending_external_auths.write().await.insert(
3751            inactive_state.to_owned(),
3752            make_federate_pending(inactive_state),
3753        );
3754        let inactive_owner = oidc_callback::external_callback(
3755            axum::extract::State(Arc::clone(&state)),
3756            axum::extract::Path("federate".to_owned()),
3757            axum::http::HeaderMap::new(),
3758            axum::extract::Query(oidc_callback::CallbackParams {
3759                code: "federate-owner-good".to_owned(),
3760                state: inactive_state.to_owned(),
3761            }),
3762        )
3763        .await;
3764        assert_eq!(
3765            inactive_owner.status(),
3766            axum::http::StatusCode::TEMPORARY_REDIRECT
3767        );
3768        let inactive_code = url::Url::parse(
3769            inactive_owner
3770                .headers()
3771                .get(axum::http::header::LOCATION)
3772                .and_then(|header| header.to_str().ok())
3773                .expect("Federate inactive test redirect"),
3774        )?
3775        .query_pairs()
3776        .find(|(name, _)| name == "code")
3777        .map(|(_, value)| value.to_string())
3778        .expect("Federate inactive test code");
3779        user_store
3780            .set_profile(
3781                "alice",
3782                crate::auth::UserProfilePatch {
3783                    active: Some(Some(false)),
3784                    ..Default::default()
3785                },
3786            )
3787            .await?;
3788        let inactive_token = post_form(
3789            &app,
3790            "/oauth/token",
3791            &[
3792                ("grant_type", "authorization_code"),
3793                ("client_id", CLIENT_ID),
3794                ("redirect_uri", REDIRECT_URI),
3795                ("code", &inactive_code),
3796                ("code_verifier", GENERIC_PKCE_VERIFIER),
3797            ],
3798            None,
3799            false,
3800        )
3801        .await;
3802        assert_eq!(inactive_token.status(), axum::http::StatusCode::BAD_REQUEST);
3803        assert_eq!(
3804            response_json(inactive_token).await["error"],
3805            "invalid_request"
3806        );
3807        user_store
3808            .set_profile(
3809                "alice",
3810                crate::auth::UserProfilePatch {
3811                    active: Some(Some(true)),
3812                    ..Default::default()
3813                },
3814            )
3815            .await?;
3816
3817        upstream_server.abort();
3818        oidc_server.abort();
3819
3820        // #1119 service assertions prove the external DID and requested
3821        // operation. They do not bind that DID to a local tenant.
3822        let now = chrono::Utc::now().timestamp();
3823        let service_header = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&serde_json::json!({
3824            "alg": "ES256", "typ": "JWT", "kid": "#atproto"
3825        }))?);
3826        let make_service_jwt_with_times =
3827            |audience: &str, lxm: &str, jti: &str, iat: i64, exp: i64| -> anyhow::Result<String> {
3828                let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&serde_json::json!({
3829                    "iss": MAPPED_DID,
3830                    "aud": audience,
3831                    "iat": iat,
3832                    "exp": exp,
3833                    "lxm": lxm,
3834                    "jti": jti
3835                }))?);
3836                let signing_input = format!("{service_header}.{payload}");
3837                let signature: p256::ecdsa::Signature =
3838                    atproto_signing_key.sign(signing_input.as_bytes());
3839                Ok(format!(
3840                    "{signing_input}.{}",
3841                    URL_SAFE_NO_PAD.encode(signature.to_bytes())
3842                ))
3843            };
3844        let make_service_jwt = |audience: &str, lxm: &str, jti: &str| {
3845            make_service_jwt_with_times(audience, lxm, jti, now, now + 60)
3846        };
3847        let service_jwt = make_service_jwt(
3848            "did:web:pds.example.test%3A8443",
3849            token_exchange::ATPROTO_EXCHANGE_NSID,
3850            "demo-1119-jti",
3851        )?;
3852        let exchange_dpop_key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
3853        let exchange_dpop = dpop_proof(
3854            &exchange_dpop_key,
3855            &format!("{ISSUER}/xrpc/ai.hyprstream.identity.exchangeUcan"),
3856            "demo-1119-exchange-dpop",
3857            None,
3858        );
3859        use tower::ServiceExt as _;
3860        let exchange_request = |jwt: &str, tenant: &str| {
3861            axum::http::Request::post("/xrpc/ai.hyprstream.identity.exchangeUcan")
3862                .header(axum::http::header::CONTENT_TYPE, "application/json")
3863                .header(axum::http::header::AUTHORIZATION, format!("Bearer {jwt}"))
3864                .header("DPoP", &exchange_dpop)
3865                .body(axum::body::Body::from(
3866                    serde_json::json!({
3867                        "tenant": tenant,
3868                        "scope": "transition:generic",
3869                        "audience": ISSUER
3870                    })
3871                    .to_string(),
3872                ))
3873                .unwrap()
3874        };
3875        let wrong_audience = make_service_jwt(
3876            "did:web:other.example",
3877            token_exchange::ATPROTO_EXCHANGE_NSID,
3878            "demo-1119-wrong-aud",
3879        )?;
3880        let rejected_audience = app
3881            .clone()
3882            .oneshot(exchange_request(&wrong_audience, HOSTED_TENANT))
3883            .await?;
3884        assert_eq!(
3885            rejected_audience.status(),
3886            axum::http::StatusCode::UNAUTHORIZED
3887        );
3888        let wrong_lxm = make_service_jwt(
3889            "did:web:pds.example.test%3A8443",
3890            "com.atproto.repo.uploadBlob",
3891            "demo-1119-wrong-lxm",
3892        )?;
3893        let rejected_lxm = app
3894            .clone()
3895            .oneshot(exchange_request(&wrong_lxm, HOSTED_TENANT))
3896            .await?;
3897        assert_eq!(rejected_lxm.status(), axum::http::StatusCode::UNAUTHORIZED);
3898
3899        // The verifier must reject an unrepresentable signed interval before
3900        // DID resolution, replay admission, or a token exchange can occur.
3901        let extreme_interval = make_service_jwt_with_times(
3902            "did:web:pds.example.test%3A8443",
3903            token_exchange::ATPROTO_EXCHANGE_NSID,
3904            "demo-1119-extreme-interval",
3905            i64::MIN,
3906            i64::MAX,
3907        )?;
3908        let rejected_extreme_interval = app
3909            .clone()
3910            .oneshot(exchange_request(&extreme_interval, HOSTED_TENANT))
3911            .await?;
3912        assert_eq!(
3913            rejected_extreme_interval.status(),
3914            axum::http::StatusCode::UNAUTHORIZED
3915        );
3916
3917        // #1314: the authority-owned account record supplies the binding. A
3918        // matching request succeeds and the minted credential carries exactly
3919        // that record's tenant.
3920        let exchanged = app
3921            .clone()
3922            .oneshot(exchange_request(&service_jwt, HOSTED_TENANT))
3923            .await?;
3924        assert_eq!(exchanged.status(), axum::http::StatusCode::OK);
3925        let exchanged_json = response_json(exchanged).await;
3926        let exchanged_token = exchanged_json["access_token"]
3927            .as_str()
3928            .expect("hosted ATProto identity receives a credential");
3929        let exchanged_claims = jwt_claims(exchanged_token);
3930        assert_eq!(exchanged_claims["sub"], MAPPED_DID);
3931        assert_eq!(exchanged_claims["tenant"], HOSTED_TENANT);
3932        assert_eq!(exchanged_claims["scope"], "transition:generic");
3933
3934        // The same XRPC proof cannot authorize a second service assertion.
3935        // Its rejection must not consume that assertion for a fresh proof.
3936        let second_service_jwt = make_service_jwt(
3937            "did:web:pds.example.test%3A8443",
3938            token_exchange::ATPROTO_EXCHANGE_NSID,
3939            "demo-1119-second-service-jti",
3940        )?;
3941        let xrpc_replay = app
3942            .clone()
3943            .oneshot(exchange_request(&second_service_jwt, HOSTED_TENANT))
3944            .await?;
3945        assert_eq!(xrpc_replay.status(), axum::http::StatusCode::BAD_REQUEST);
3946        let fresh_xrpc_proof = dpop_proof(
3947            &exchange_dpop_key,
3948            &format!("{ISSUER}/xrpc/ai.hyprstream.identity.exchangeUcan"),
3949            "demo-1119-fresh-exchange-dpop",
3950            None,
3951        );
3952        let fresh_xrpc_request =
3953            axum::http::Request::post("/xrpc/ai.hyprstream.identity.exchangeUcan")
3954                .header(axum::http::header::CONTENT_TYPE, "application/json")
3955                .header(
3956                    axum::http::header::AUTHORIZATION,
3957                    format!("Bearer {second_service_jwt}"),
3958                )
3959                .header("DPoP", fresh_xrpc_proof)
3960                .body(axum::body::Body::from(
3961                    serde_json::json!({
3962                        "tenant": HOSTED_TENANT, "scope": "transition:generic", "audience": ISSUER
3963                    })
3964                    .to_string(),
3965                ))?;
3966        let xrpc_fresh = app.clone().oneshot(fresh_xrpc_request).await?;
3967        assert_eq!(xrpc_fresh.status(), axum::http::StatusCode::OK);
3968
3969        let wrong_tenant_jwt = make_service_jwt(
3970            "did:web:pds.example.test%3A8443",
3971            token_exchange::ATPROTO_EXCHANGE_NSID,
3972            "demo-1119-wrong-tenant",
3973        )?;
3974        let rejected_tenant = app
3975            .clone()
3976            .oneshot(exchange_request(&wrong_tenant_jwt, "tenant-foreign"))
3977            .await?;
3978        assert_eq!(
3979            rejected_tenant.status(),
3980            axum::http::StatusCode::BAD_REQUEST
3981        );
3982        let rejected_tenant_json = response_json(rejected_tenant).await;
3983        assert_eq!(rejected_tenant_json["error"], "InvalidRequest");
3984        assert_eq!(
3985            rejected_tenant_json["message"],
3986            "requested tenant differs from the verified source-token tenant"
3987        );
3988        assert!(
3989            rejected_tenant_json.get("access_token").is_none(),
3990            "a hosted DID must not receive a credential for a tenant other than its account binding"
3991        );
3992
3993        // Device authorization rejects unknown clients at the real endpoint.
3994        let unknown_device = post_form(
3995            &app,
3996            "/oauth/device",
3997            &[("client_id", "unknown-client"), ("scope", "read:*:*")],
3998            None,
3999            false,
4000        )
4001        .await;
4002        assert_eq!(unknown_device.status(), axum::http::StatusCode::BAD_REQUEST);
4003        assert_eq!(
4004            response_json(unknown_device).await["error"],
4005            "invalid_client"
4006        );
4007
4008        // #1146 T1.3: the atproto profile has no device authorization grant —
4009        // `scope=atproto` is rejected at the device endpoint (it previously
4010        // minted malformed DPoP tokens cnf-bound to the user's login key).
4011        let atproto_device = post_form(
4012            &app,
4013            "/oauth/device",
4014            &[("client_id", CLIENT_ID), ("scope", "atproto")],
4015            None,
4016            false,
4017        )
4018        .await;
4019        assert_eq!(atproto_device.status(), axum::http::StatusCode::BAD_REQUEST);
4020        assert_eq!(
4021            response_json(atproto_device).await["error"],
4022            "invalid_scope"
4023        );
4024
4025        // #1146 T1.1: a fetched CIMD client's declared scope ceiling is
4026        // enforced at PAR. This client declares only `atproto`; requesting
4027        // `transition:generic` must be rejected (the fetched-metadata path
4028        // previously dropped the ceiling entirely).
4029        const CIMD_CLIENT_ID: &str = "https://client.example.test/cimd.json";
4030        state
4031            .cimd_cache
4032            .insert(
4033                RegisteredClient {
4034                    client_id: CIMD_CLIENT_ID.to_owned(),
4035                    redirect_uris: vec![REDIRECT_URI.to_owned()],
4036                    client_name: Some("Handler CIMD Client".to_owned()),
4037                    client_uri: None,
4038                    logo_uri: None,
4039                    grant_types: vec!["authorization_code".to_owned()],
4040                    response_types: vec!["code".to_owned()],
4041                    token_endpoint_auth_method: Some("none".to_owned()),
4042                    jwks: None,
4043                    jwks_uri: None,
4044                    hyprstream_node_did: None,
4045                    scope: Some("atproto".to_owned()),
4046                    dpop_bound_access_tokens: Some(true),
4047                    is_cimd: true,
4048                    registered_at: std::time::Instant::now(),
4049                },
4050                std::time::Duration::from_secs(300),
4051            )
4052            .await;
4053        let cimd_par_challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(
4054            b"cimd-ceiling-pkce-verifier-abcdefghijklmnopqrstuvwxyz",
4055        ));
4056        let cimd_over_scope_par = post_form(
4057            &app,
4058            "/oauth/par",
4059            &[
4060                ("client_id", CIMD_CLIENT_ID),
4061                ("redirect_uri", REDIRECT_URI),
4062                ("code_challenge", &cimd_par_challenge),
4063                ("code_challenge_method", "S256"),
4064                ("response_type", "code"),
4065                ("scope", "atproto transition:generic"),
4066                ("resource", ISSUER),
4067            ],
4068            None,
4069            false,
4070        )
4071        .await;
4072        assert_eq!(
4073            cimd_over_scope_par.status(),
4074            axum::http::StatusCode::BAD_REQUEST,
4075            "CIMD client must not exceed its declared scope ceiling"
4076        );
4077        assert_eq!(
4078            response_json(cimd_over_scope_par).await["error"],
4079            "invalid_scope"
4080        );
4081        // Positive control: the declared scope itself is still granted.
4082        let cimd_dpop_key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
4083        let cimd_par_proof = dpop_proof(
4084            &cimd_dpop_key,
4085            &format!("{ISSUER}/oauth/par"),
4086            "cimd-ceiling-par-jti",
4087            None,
4088        );
4089        let cimd_in_scope_par = post_form(
4090            &app,
4091            "/oauth/par",
4092            &[
4093                ("client_id", CIMD_CLIENT_ID),
4094                ("redirect_uri", REDIRECT_URI),
4095                ("code_challenge", &cimd_par_challenge),
4096                ("code_challenge_method", "S256"),
4097                ("response_type", "code"),
4098                ("scope", "atproto"),
4099                ("resource", ISSUER),
4100            ],
4101            Some(&cimd_par_proof),
4102            false,
4103        )
4104        .await;
4105        assert_eq!(
4106            cimd_in_scope_par.status(),
4107            axum::http::StatusCode::CREATED,
4108            "declared scope must remain grantable"
4109        );
4110
4111        // PAR binds the atproto request to a real ES256 DPoP key.
4112        let dpop_key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
4113        let code_challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(PKCE_VERIFIER.as_bytes()));
4114        let par_proof = dpop_proof(
4115            &dpop_key,
4116            &format!("{ISSUER}/oauth/par"),
4117            "handler-par-jti",
4118            None,
4119        );
4120        let par = post_form(
4121            &app,
4122            "/oauth/par",
4123            &[
4124                ("client_id", CLIENT_ID),
4125                ("redirect_uri", REDIRECT_URI),
4126                ("code_challenge", &code_challenge),
4127                ("code_challenge_method", "S256"),
4128                ("response_type", "code"),
4129                ("state", "client-state"),
4130                ("scope", "atproto"),
4131                ("resource", ISSUER),
4132            ],
4133            Some(&par_proof),
4134            false,
4135        )
4136        .await;
4137        assert_eq!(par.status(), axum::http::StatusCode::CREATED);
4138        let par_nonce = par
4139            .headers()
4140            .get("DPoP-Nonce")
4141            .and_then(|value| value.to_str().ok())
4142            .unwrap()
4143            .to_owned();
4144        let par_json = response_json(par).await;
4145        let request_uri = par_json["request_uri"].as_str().unwrap();
4146
4147        // GET authorize consumes the PAR and renders the real consent callback.
4148        let authorize_uri = format!(
4149            "/oauth/authorize?{}",
4150            encode_form(&[("request_uri", request_uri), ("client_id", CLIENT_ID)])
4151        );
4152        let authorize = get(&app, &authorize_uri).await;
4153        assert_eq!(authorize.status(), axum::http::StatusCode::OK);
4154        let authorize_html = response_text(authorize).await;
4155        let authorize_nonce = html_hidden_value(&authorize_html, "nonce").to_owned();
4156        let challenge = format!("{fingerprint}:{authorize_nonce}:{code_challenge}");
4157        let signature = STANDARD.encode(user_key.sign(challenge.as_bytes()).to_bytes());
4158        let callback = post_form(
4159            &app,
4160            "/oauth/authorize",
4161            &[
4162                ("client_id", CLIENT_ID),
4163                ("redirect_uri", REDIRECT_URI),
4164                ("code_challenge", &code_challenge),
4165                ("scope", "atproto"),
4166                ("state", "client-state"),
4167                ("resource", ISSUER),
4168                ("nonce", &authorize_nonce),
4169                ("fingerprint", &fingerprint),
4170                ("signature", &signature),
4171            ],
4172            None,
4173            false,
4174        )
4175        .await;
4176        assert_eq!(callback.status(), axum::http::StatusCode::SEE_OTHER);
4177        let location = callback
4178            .headers()
4179            .get(axum::http::header::LOCATION)
4180            .and_then(|value| value.to_str().ok())
4181            .unwrap();
4182        let location = url::Url::parse(location)?;
4183        let callback_params: std::collections::HashMap<_, _> =
4184            location.query_pairs().into_owned().collect();
4185        assert_eq!(callback_params.get("iss").map(String::as_str), Some(ISSUER));
4186        assert_eq!(
4187            callback_params.get("state").map(String::as_str),
4188            Some("client-state")
4189        );
4190        let code = callback_params.get("code").unwrap();
4191
4192        // Exchange the code and parse the emitted response against the exact
4193        // @atproto/oauth-types 0.7.5 token-response constraints.
4194        let token_proof = dpop_proof(
4195            &dpop_key,
4196            &format!("{ISSUER}/oauth/token"),
4197            "handler-token-jti",
4198            Some(&par_nonce),
4199        );
4200        let token = post_form(
4201            &app,
4202            "/oauth/token",
4203            &[
4204                ("grant_type", "authorization_code"),
4205                ("client_id", CLIENT_ID),
4206                ("code", code),
4207                ("redirect_uri", REDIRECT_URI),
4208                ("code_verifier", PKCE_VERIFIER),
4209            ],
4210            Some(&token_proof),
4211            false,
4212        )
4213        .await;
4214        assert_eq!(token.status(), axum::http::StatusCode::OK);
4215        let token_nonce = token
4216            .headers()
4217            .get("DPoP-Nonce")
4218            .and_then(|value| value.to_str().ok())
4219            .unwrap()
4220            .to_owned();
4221        let token_response = parse_atproto_token_response_075(response_json(token).await)?;
4222        assert_eq!(token_response.sub, MAPPED_DID);
4223        assert!(token_response.expires_in.is_some());
4224        let refresh_token = token_response.refresh_token.unwrap();
4225        let claims = jwt_claims(&token_response.access_token);
4226        assert_eq!(claims["iss"], ISSUER);
4227        assert_eq!(claims["sub"], MAPPED_DID);
4228        assert_eq!(claims["tenant"], HOSTED_TENANT);
4229        assert_eq!(claims["aud"], ISSUER);
4230        assert_eq!(claims["scope"], "atproto");
4231        assert!(claims["cnf"]["jkt"].as_str().is_some());
4232
4233        // The protected hosted-PDS route consumes the standard DPoP-bound
4234        // OAuth access token and signs the exact #1354 method/audience with
4235        // the account's persisted #atproto key.
4236        let service_auth_htu = format!("{ISSUER}{}", xrpc::GET_SERVICE_AUTH_PATH);
4237        let service_auth_uri = format!(
4238            "{}?aud={}&lxm={}",
4239            xrpc::GET_SERVICE_AUTH_PATH,
4240            urlencoding::encode(&state.atproto_service_did().unwrap()),
4241            urlencoding::encode(token_exchange::ATPROTO_SESSION_EXCHANGE_NSID),
4242        );
4243        let service_auth_proof = dpop_resource_proof(
4244            &dpop_key,
4245            "GET",
4246            &service_auth_htu,
4247            &token_response.access_token,
4248            "handler-service-auth-jti",
4249            Some(&token_nonce),
4250        );
4251        let service_auth = app
4252            .clone()
4253            .oneshot(
4254                axum::http::Request::get(service_auth_uri)
4255                    .header(
4256                        axum::http::header::AUTHORIZATION,
4257                        format!("DPoP {}", token_response.access_token),
4258                    )
4259                    .header("DPoP", service_auth_proof)
4260                    .body(axum::body::Body::empty())?,
4261            )
4262            .await?;
4263        let service_auth_status = service_auth.status();
4264        let service_auth_cache_control = service_auth
4265            .headers()
4266            .get(axum::http::header::CACHE_CONTROL)
4267            .cloned();
4268        let service_auth_json = response_json(service_auth).await;
4269        assert_eq!(
4270            service_auth_status,
4271            axum::http::StatusCode::OK,
4272            "{service_auth_json}"
4273        );
4274        assert_eq!(service_auth_cache_control.as_ref().unwrap(), "no-store");
4275        let service_jwt = service_auth_json["token"]
4276            .as_str()
4277            .ok_or_else(|| anyhow::anyhow!("service-auth response token"))?
4278            .to_owned();
4279        let verified = token_exchange::verify_atproto_service_jwt(
4280            &state,
4281            &service_jwt,
4282            token_exchange::ATPROTO_SESSION_EXCHANGE_NSID,
4283        )
4284        .await
4285        .map_err(anyhow::Error::msg)?;
4286        assert_eq!(verified.sub, MAPPED_DID);
4287        assert_eq!(verified.verified_tenant.as_deref(), Some(HOSTED_TENANT));
4288
4289        // The first hyprstream_session is still issued by the existing #1354
4290        // exchange route; getServiceAuth does not create a parallel session.
4291        let session_proof = dpop_proof(
4292            &dpop_key,
4293            &format!("{ISSUER}{}", browser_session::SESSION_EXCHANGE_PATH),
4294            "handler-session-exchange-jti",
4295            None,
4296        );
4297        let session = app
4298            .clone()
4299            .oneshot(
4300                axum::http::Request::post(browser_session::SESSION_EXCHANGE_PATH)
4301                    .header(
4302                        axum::http::header::AUTHORIZATION,
4303                        format!("Bearer {service_jwt}"),
4304                    )
4305                    .header("DPoP", session_proof)
4306                    .body(axum::body::Body::empty())?,
4307            )
4308            .await?;
4309        assert_eq!(session.status(), axum::http::StatusCode::OK);
4310        assert!(session.headers()[axum::http::header::SET_COOKIE]
4311            .to_str()?
4312            .starts_with("hyprstream_session="));
4313
4314        // A confidential atproto client signs private_key_jwt with the AS
4315        // issuer as the assertion audience (atproto mandate, #1146 T1.2),
4316        // even though the configured generic issuer carries a path.
4317        let advertised_metadata =
4318            response_json(get(&app, "/.well-known/oauth-authorization-server").await).await;
4319        let advertised_token_endpoint = advertised_metadata["token_endpoint"]
4320            .as_str()
4321            .unwrap()
4322            .to_owned();
4323        assert_eq!(advertised_token_endpoint, format!("{ISSUER}/oauth/token"));
4324
4325        let assertion_type = super::client_auth::JWT_BEARER_ASSERTION_TYPE;
4326        let private_dpop_key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
4327        let private_verifier = "private-client-pkce-verifier-abcdefghijklmnopqrstuvwxyz012345";
4328        let private_challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(private_verifier.as_bytes()));
4329
4330        // #1146 T3.3: confidential clients MUST authenticate at PAR — a
4331        // pushed request without a client_assertion is rejected.
4332        let no_auth_par_proof = dpop_proof(
4333            &private_dpop_key,
4334            &format!("{ISSUER}/oauth/par"),
4335            "private-client-par-jti-noauth",
4336            None,
4337        );
4338        let no_auth_par = post_form(
4339            &app,
4340            "/oauth/par",
4341            &[
4342                ("client_id", PRIVATE_CLIENT_ID),
4343                ("redirect_uri", REDIRECT_URI),
4344                ("code_challenge", &private_challenge),
4345                ("code_challenge_method", "S256"),
4346                ("response_type", "code"),
4347                ("state", "private-client-state"),
4348                ("scope", "atproto"),
4349                ("resource", ISSUER),
4350            ],
4351            Some(&no_auth_par_proof),
4352            false,
4353        )
4354        .await;
4355        assert_eq!(no_auth_par.status(), axum::http::StatusCode::UNAUTHORIZED);
4356        assert_eq!(response_json(no_auth_par).await["error"], "invalid_client");
4357
4358        // #1146 T1.2: at PAR the assertion audience MUST be the AS issuer —
4359        // the RFC 7523 token-endpoint form accepted at /oauth/token is not
4360        // sufficient here.
4361        let par_endpoint_aud_assertion = private_key_jwt_assertion(
4362            &private_client_key,
4363            "private-k1",
4364            PRIVATE_CLIENT_ID,
4365            &format!("{ISSUER}/oauth/token"),
4366            "private-par-endpoint-aud-jti",
4367        );
4368        let wrong_aud_par_proof = dpop_proof(
4369            &private_dpop_key,
4370            &format!("{ISSUER}/oauth/par"),
4371            "private-client-par-jti-wrongaod",
4372            None,
4373        );
4374        let wrong_aud_par = post_form(
4375            &app,
4376            "/oauth/par",
4377            &[
4378                ("client_id", PRIVATE_CLIENT_ID),
4379                ("redirect_uri", REDIRECT_URI),
4380                ("code_challenge", &private_challenge),
4381                ("code_challenge_method", "S256"),
4382                ("response_type", "code"),
4383                ("state", "private-client-state"),
4384                ("scope", "atproto"),
4385                ("resource", ISSUER),
4386                ("client_assertion_type", assertion_type),
4387                ("client_assertion", &par_endpoint_aud_assertion),
4388            ],
4389            Some(&wrong_aud_par_proof),
4390            false,
4391        )
4392        .await;
4393        assert_eq!(wrong_aud_par.status(), axum::http::StatusCode::UNAUTHORIZED);
4394        assert_eq!(
4395            response_json(wrong_aud_par).await["error"],
4396            "invalid_client"
4397        );
4398
4399        let private_par_proof = dpop_proof(
4400            &private_dpop_key,
4401            &format!("{ISSUER}/oauth/par"),
4402            "private-client-par-jti",
4403            None,
4404        );
4405        let private_par_assertion = private_key_jwt_assertion(
4406            &private_client_key,
4407            "private-k1",
4408            PRIVATE_CLIENT_ID,
4409            ISSUER,
4410            "private-par-assertion-jti",
4411        );
4412        let private_par = post_form(
4413            &app,
4414            "/oauth/par",
4415            &[
4416                ("client_id", PRIVATE_CLIENT_ID),
4417                ("redirect_uri", REDIRECT_URI),
4418                ("code_challenge", &private_challenge),
4419                ("code_challenge_method", "S256"),
4420                ("response_type", "code"),
4421                ("state", "private-client-state"),
4422                ("scope", "atproto"),
4423                ("resource", ISSUER),
4424                ("client_assertion_type", assertion_type),
4425                ("client_assertion", &private_par_assertion),
4426            ],
4427            Some(&private_par_proof),
4428            false,
4429        )
4430        .await;
4431        assert_eq!(private_par.status(), axum::http::StatusCode::CREATED);
4432        let private_dpop_nonce = private_par
4433            .headers()
4434            .get("DPoP-Nonce")
4435            .and_then(|value| value.to_str().ok())
4436            .unwrap()
4437            .to_owned();
4438        let private_par_json = response_json(private_par).await;
4439        let private_request_uri = private_par_json["request_uri"].as_str().unwrap();
4440        let private_authorize_uri = format!(
4441            "/oauth/authorize?{}",
4442            encode_form(&[
4443                ("request_uri", private_request_uri),
4444                ("client_id", PRIVATE_CLIENT_ID),
4445            ])
4446        );
4447        let private_authorize = get(&app, &private_authorize_uri).await;
4448        assert_eq!(private_authorize.status(), axum::http::StatusCode::OK);
4449        let private_authorize_html = response_text(private_authorize).await;
4450        let private_nonce = html_hidden_value(&private_authorize_html, "nonce").to_owned();
4451        let private_signed = format!("{fingerprint}:{private_nonce}:{private_challenge}");
4452        let private_signature =
4453            STANDARD.encode(user_key.sign(private_signed.as_bytes()).to_bytes());
4454        let private_callback = post_form(
4455            &app,
4456            "/oauth/authorize",
4457            &[
4458                ("client_id", PRIVATE_CLIENT_ID),
4459                ("redirect_uri", REDIRECT_URI),
4460                ("code_challenge", &private_challenge),
4461                ("scope", "atproto"),
4462                ("state", "private-client-state"),
4463                ("resource", ISSUER),
4464                ("nonce", &private_nonce),
4465                ("fingerprint", &fingerprint),
4466                ("signature", &private_signature),
4467            ],
4468            None,
4469            false,
4470        )
4471        .await;
4472        assert_eq!(private_callback.status(), axum::http::StatusCode::SEE_OTHER);
4473        let private_location = private_callback
4474            .headers()
4475            .get(axum::http::header::LOCATION)
4476            .and_then(|value| value.to_str().ok())
4477            .unwrap();
4478        let private_location = url::Url::parse(private_location)?;
4479        let private_callback_params: std::collections::HashMap<_, _> =
4480            private_location.query_pairs().into_owned().collect();
4481        let private_code = private_callback_params["code"].clone();
4482
4483        // #1146 T3.3: a client_assertion is single-use — re-presenting the
4484        // exact assertion accepted at PAR above (same jti) is replay and
4485        // must be rejected, even at a different endpoint.
4486        let replay_assertion_proof = dpop_proof(
4487            &private_dpop_key,
4488            &advertised_token_endpoint,
4489            "private-client-token-jti-replay",
4490            Some(&private_dpop_nonce),
4491        );
4492        let replayed_assertion = post_form(
4493            &app,
4494            "/oauth/token",
4495            &[
4496                ("grant_type", "authorization_code"),
4497                ("client_id", PRIVATE_CLIENT_ID),
4498                ("code", &private_code),
4499                ("redirect_uri", REDIRECT_URI),
4500                ("code_verifier", private_verifier),
4501                ("client_assertion_type", assertion_type),
4502                ("client_assertion", &private_par_assertion),
4503            ],
4504            Some(&replay_assertion_proof),
4505            false,
4506        )
4507        .await;
4508        assert_eq!(
4509            replayed_assertion.status(),
4510            axum::http::StatusCode::UNAUTHORIZED,
4511            "a replayed client_assertion jti must be rejected"
4512        );
4513        assert_eq!(
4514            response_json(replayed_assertion).await["error"],
4515            "invalid_client"
4516        );
4517
4518        let private_token_proof = dpop_proof(
4519            &private_dpop_key,
4520            &advertised_token_endpoint,
4521            "private-client-token-jti",
4522            Some(&private_dpop_nonce),
4523        );
4524        let wrong_assertion = private_key_jwt_assertion(
4525            &private_client_key,
4526            "private-k1",
4527            PRIVATE_CLIENT_ID,
4528            "https://attacker.example/oauth/token",
4529            "private-client-wrong-aud",
4530        );
4531        let wrong_audience = post_form(
4532            &app,
4533            "/oauth/token",
4534            &[
4535                ("grant_type", "authorization_code"),
4536                ("client_id", PRIVATE_CLIENT_ID),
4537                ("code", &private_code),
4538                ("redirect_uri", REDIRECT_URI),
4539                ("code_verifier", private_verifier),
4540                ("client_assertion_type", assertion_type),
4541                ("client_assertion", &wrong_assertion),
4542            ],
4543            Some(&private_token_proof),
4544            false,
4545        )
4546        .await;
4547        assert_eq!(
4548            wrong_audience.status(),
4549            axum::http::StatusCode::UNAUTHORIZED
4550        );
4551        assert_eq!(
4552            response_json(wrong_audience).await["error"],
4553            "invalid_client"
4554        );
4555
4556        // #1146 T1.2 (rev): the RFC 7523 token-endpoint audience form is NOT
4557        // accepted at the token endpoint either — atproto mandates the AS
4558        // issuer alone at every endpoint. This pins the narrowing: accepting
4559        // both forms was the review-flagged deviation.
4560        let endpoint_aud_assertion = private_key_jwt_assertion(
4561            &private_client_key,
4562            "private-k1",
4563            PRIVATE_CLIENT_ID,
4564            &advertised_token_endpoint,
4565            "private-client-endpoint-aud",
4566        );
4567        let endpoint_audience = post_form(
4568            &app,
4569            "/oauth/token",
4570            &[
4571                ("grant_type", "authorization_code"),
4572                ("client_id", PRIVATE_CLIENT_ID),
4573                ("code", &private_code),
4574                ("redirect_uri", REDIRECT_URI),
4575                ("code_verifier", private_verifier),
4576                ("client_assertion_type", assertion_type),
4577                ("client_assertion", &endpoint_aud_assertion),
4578            ],
4579            Some(&private_token_proof),
4580            false,
4581        )
4582        .await;
4583        assert_eq!(
4584            endpoint_audience.status(),
4585            axum::http::StatusCode::UNAUTHORIZED,
4586            "the token-endpoint audience form must be rejected (issuer-only)"
4587        );
4588        assert_eq!(
4589            response_json(endpoint_audience).await["error"],
4590            "invalid_client"
4591        );
4592
4593        // #1146 T1.2: the reference confidential client sends the AS ISSUER
4594        // as the assertion audience — previously rejected, now the ONLY
4595        // accepted form (issuer-only at PAR and token).
4596        let canonical_assertion = private_key_jwt_assertion(
4597            &private_client_key,
4598            "private-k1",
4599            PRIVATE_CLIENT_ID,
4600            ISSUER,
4601            "private-client-canonical-aud",
4602        );
4603        let private_token = post_form(
4604            &app,
4605            "/oauth/token",
4606            &[
4607                ("grant_type", "authorization_code"),
4608                ("client_id", PRIVATE_CLIENT_ID),
4609                ("code", &private_code),
4610                ("redirect_uri", REDIRECT_URI),
4611                ("code_verifier", private_verifier),
4612                ("client_assertion_type", assertion_type),
4613                ("client_assertion", &canonical_assertion),
4614            ],
4615            Some(&private_token_proof),
4616            false,
4617        )
4618        .await;
4619        assert_eq!(private_token.status(), axum::http::StatusCode::OK);
4620        let private_token_nonce = private_token
4621            .headers()
4622            .get("DPoP-Nonce")
4623            .and_then(|value| value.to_str().ok())
4624            .unwrap()
4625            .to_owned();
4626        let private_token_json = response_json(private_token).await;
4627        assert_eq!(private_token_json["token_type"], "DPoP");
4628        assert_eq!(
4629            jwt_claims(private_token_json["access_token"].as_str().unwrap())["iss"],
4630            ISSUER
4631        );
4632        let private_refresh_token = private_token_json["refresh_token"]
4633            .as_str()
4634            .unwrap()
4635            .to_owned();
4636
4637        // #1146 T3.3: the session is bound to the assertion key verified at
4638        // PAR/issuance. Refresh presenting an assertion from ANOTHER
4639        // currently-registered key (private-k2) must be rejected — and must
4640        // not consume the single-use refresh token.
4641        let switch_assertion = private_key_jwt_assertion(
4642            &private_client_key_2,
4643            "private-k2",
4644            PRIVATE_CLIENT_ID,
4645            ISSUER,
4646            "private-refresh-switch-jti",
4647        );
4648        let switch_proof = dpop_proof(
4649            &private_dpop_key,
4650            &advertised_token_endpoint,
4651            "private-refresh-switch-dpop-jti",
4652            Some(&private_token_nonce),
4653        );
4654        let switch_refresh = post_form(
4655            &app,
4656            "/oauth/token",
4657            &[
4658                ("grant_type", "refresh_token"),
4659                ("client_id", PRIVATE_CLIENT_ID),
4660                ("refresh_token", &private_refresh_token),
4661                ("client_assertion_type", assertion_type),
4662                ("client_assertion", &switch_assertion),
4663            ],
4664            Some(&switch_proof),
4665            false,
4666        )
4667        .await;
4668        assert_eq!(
4669            switch_refresh.status(),
4670            axum::http::StatusCode::UNAUTHORIZED,
4671            "refresh must not switch to another registered assertion key"
4672        );
4673        assert_eq!(
4674            response_json(switch_refresh).await["error"],
4675            "invalid_client"
4676        );
4677        assert!(
4678            state
4679                .get_refresh_token(&private_refresh_token)
4680                .await?
4681                .is_some(),
4682            "a rejected client authentication must not consume the refresh token"
4683        );
4684
4685        // Refresh with the BOUND key succeeds and rotates.
4686        let bound_assertion = private_key_jwt_assertion(
4687            &private_client_key,
4688            "private-k1",
4689            PRIVATE_CLIENT_ID,
4690            ISSUER,
4691            "private-refresh-bound-jti",
4692        );
4693        let bound_proof = dpop_proof(
4694            &private_dpop_key,
4695            &advertised_token_endpoint,
4696            "private-refresh-bound-dpop-jti",
4697            Some(&private_token_nonce),
4698        );
4699        let bound_refresh = post_form(
4700            &app,
4701            "/oauth/token",
4702            &[
4703                ("grant_type", "refresh_token"),
4704                ("client_id", PRIVATE_CLIENT_ID),
4705                ("refresh_token", &private_refresh_token),
4706                ("client_assertion_type", assertion_type),
4707                ("client_assertion", &bound_assertion),
4708            ],
4709            Some(&bound_proof),
4710            false,
4711        )
4712        .await;
4713        assert_eq!(bound_refresh.status(), axum::http::StatusCode::OK);
4714        let bound_refresh_nonce = bound_refresh
4715            .headers()
4716            .get("DPoP-Nonce")
4717            .and_then(|value| value.to_str().ok())
4718            .unwrap()
4719            .to_owned();
4720        let bound_refresh_json = response_json(bound_refresh).await;
4721        let rotated_refresh_token = bound_refresh_json["refresh_token"]
4722            .as_str()
4723            .unwrap()
4724            .to_owned();
4725        assert_ne!(rotated_refresh_token, private_refresh_token);
4726
4727        // #1146 T3.3: removing the bound key from the client's JWKS revokes
4728        // the session — the rotated refresh can no longer authenticate.
4729        {
4730            let mut clients = state.clients.write().await;
4731            let entry = clients.get_mut(PRIVATE_CLIENT_ID).unwrap();
4732            let keys = entry.jwks.as_ref().unwrap()["keys"].as_array().unwrap();
4733            let remaining: Vec<serde_json::Value> = keys
4734                .iter()
4735                .filter(|k| k["kid"].as_str() != Some("private-k1"))
4736                .cloned()
4737                .collect();
4738            entry.jwks = Some(serde_json::json!({"keys": remaining}));
4739        }
4740        let removed_key_assertion = private_key_jwt_assertion(
4741            &private_client_key,
4742            "private-k1",
4743            PRIVATE_CLIENT_ID,
4744            ISSUER,
4745            "private-refresh-removed-jti",
4746        );
4747        let removed_key_proof = dpop_proof(
4748            &private_dpop_key,
4749            &advertised_token_endpoint,
4750            "private-refresh-removed-dpop-jti",
4751            Some(&bound_refresh_nonce),
4752        );
4753        let removed_key_refresh = post_form(
4754            &app,
4755            "/oauth/token",
4756            &[
4757                ("grant_type", "refresh_token"),
4758                ("client_id", PRIVATE_CLIENT_ID),
4759                ("refresh_token", &rotated_refresh_token),
4760                ("client_assertion_type", assertion_type),
4761                ("client_assertion", &removed_key_assertion),
4762            ],
4763            Some(&removed_key_proof),
4764            false,
4765        )
4766        .await;
4767        assert_eq!(
4768            removed_key_refresh.status(),
4769            axum::http::StatusCode::UNAUTHORIZED,
4770            "key removal from the client JWKS must revoke the session"
4771        );
4772        assert_eq!(
4773            response_json(removed_key_refresh).await["error"],
4774            "invalid_client"
4775        );
4776        assert!(
4777            state
4778                .get_refresh_token(&rotated_refresh_token)
4779                .await?
4780                .is_some(),
4781            "a rejected client authentication must not consume the refresh token"
4782        );
4783
4784        // A missing refresh proof is rejected before consumption. Retrying
4785        // the same refresh token with the bound key and nonce must succeed.
4786        let stranded_attempt = post_form(
4787            &app,
4788            "/oauth/token",
4789            &[
4790                ("grant_type", "refresh_token"),
4791                ("client_id", CLIENT_ID),
4792                ("refresh_token", &refresh_token),
4793            ],
4794            None,
4795            false,
4796        )
4797        .await;
4798        assert_eq!(
4799            stranded_attempt.status(),
4800            axum::http::StatusCode::BAD_REQUEST
4801        );
4802        assert_eq!(
4803            response_json(stranded_attempt).await["error"],
4804            "invalid_dpop_proof"
4805        );
4806        assert!(state.get_refresh_token(&refresh_token).await?.is_some());
4807        let refresh_proof = dpop_proof(
4808            &dpop_key,
4809            &format!("{ISSUER}/oauth/token"),
4810            "handler-refresh-jti",
4811            Some(&token_nonce),
4812        );
4813        let refreshed = post_form(
4814            &app,
4815            "/oauth/token",
4816            &[
4817                ("grant_type", "refresh_token"),
4818                ("client_id", CLIENT_ID),
4819                ("refresh_token", &refresh_token),
4820            ],
4821            Some(&refresh_proof),
4822            false,
4823        )
4824        .await;
4825        assert_eq!(refreshed.status(), axum::http::StatusCode::OK);
4826        let refreshed_json = response_json(refreshed).await;
4827        assert_eq!(refreshed_json["token_type"], "DPoP");
4828        assert_eq!(refreshed_json["sub"], MAPPED_DID);
4829        assert_ne!(refreshed_json["refresh_token"], refresh_token);
4830        assert!(state.get_refresh_token(&refresh_token).await?.is_none());
4831        let refreshed_claims = jwt_claims(refreshed_json["access_token"].as_str().unwrap());
4832        assert_eq!(refreshed_claims["sub"], MAPPED_DID);
4833        assert_eq!(refreshed_claims["tenant"], HOSTED_TENANT);
4834        assert_eq!(refreshed_claims["scope"], "atproto");
4835        assert_eq!(refreshed_claims["cnf"]["jkt"], claims["cnf"]["jkt"]);
4836
4837        // A non-atproto PAR consent cannot be upgraded to the atproto profile
4838        // by mutating hidden fields on the callback POST.
4839        let downgrade_challenge =
4840            URL_SAFE_NO_PAD.encode(Sha256::digest(GENERIC_PKCE_VERIFIER.as_bytes()));
4841        let downgrade_par = post_form(
4842            &app,
4843            "/oauth/par",
4844            &[
4845                ("client_id", CLIENT_ID),
4846                ("redirect_uri", REDIRECT_URI),
4847                ("code_challenge", &downgrade_challenge),
4848                ("code_challenge_method", "S256"),
4849                ("response_type", "code"),
4850                ("state", "scope-binding-state"),
4851                ("scope", "read:*:*"),
4852                ("resource", ISSUER),
4853            ],
4854            None,
4855            false,
4856        )
4857        .await;
4858        assert_eq!(downgrade_par.status(), axum::http::StatusCode::CREATED);
4859        let downgrade_par_json = response_json(downgrade_par).await;
4860        let downgrade_request_uri = downgrade_par_json["request_uri"].as_str().unwrap();
4861        let downgrade_authorize_uri = format!(
4862            "/oauth/authorize?{}",
4863            encode_form(&[
4864                ("request_uri", downgrade_request_uri),
4865                ("client_id", CLIENT_ID)
4866            ])
4867        );
4868        let downgrade_authorize = get(&app, &downgrade_authorize_uri).await;
4869        assert_eq!(downgrade_authorize.status(), axum::http::StatusCode::OK);
4870        let downgrade_html = response_text(downgrade_authorize).await;
4871        let downgrade_nonce = html_hidden_value(&downgrade_html, "nonce").to_owned();
4872        let downgrade_signed = format!("{fingerprint}:{downgrade_nonce}:{downgrade_challenge}");
4873        let downgrade_signature =
4874            STANDARD.encode(user_key.sign(downgrade_signed.as_bytes()).to_bytes());
4875        let upgraded_callback = post_form(
4876            &app,
4877            "/oauth/authorize",
4878            &[
4879                ("client_id", CLIENT_ID),
4880                ("redirect_uri", REDIRECT_URI),
4881                ("code_challenge", &downgrade_challenge),
4882                ("scope", "atproto"),
4883                ("state", "scope-binding-state"),
4884                ("resource", ISSUER),
4885                ("nonce", &downgrade_nonce),
4886                ("fingerprint", &fingerprint),
4887                ("signature", &downgrade_signature),
4888            ],
4889            None,
4890            false,
4891        )
4892        .await;
4893        assert_eq!(
4894            upgraded_callback.status(),
4895            axum::http::StatusCode::BAD_REQUEST
4896        );
4897        assert_eq!(
4898            response_json(upgraded_callback).await["error"],
4899            "invalid_request"
4900        );
4901
4902        // A real no-resource authorization-code flow retains the local
4903        // username and emits a Bearer token for Policy's default audience.
4904        let generic_code_challenge =
4905            URL_SAFE_NO_PAD.encode(Sha256::digest(GENERIC_PKCE_VERIFIER.as_bytes()));
4906        let generic_authorize_uri = format!(
4907            "/oauth/authorize?{}",
4908            encode_form(&[
4909                ("client_id", CLIENT_ID),
4910                ("redirect_uri", REDIRECT_URI),
4911                ("code_challenge", &generic_code_challenge),
4912                ("code_challenge_method", "S256"),
4913                ("response_type", "code"),
4914                ("state", "generic-client-state"),
4915                ("scope", "read:*:*"),
4916            ])
4917        );
4918        let generic_authorize = get(&app, &generic_authorize_uri).await;
4919        assert_eq!(generic_authorize.status(), axum::http::StatusCode::OK);
4920        let generic_authorize_html = response_text(generic_authorize).await;
4921        let generic_authorize_nonce =
4922            html_hidden_value(&generic_authorize_html, "nonce").to_owned();
4923        let generic_challenge =
4924            format!("{fingerprint}:{generic_authorize_nonce}:{generic_code_challenge}");
4925        let generic_signature =
4926            STANDARD.encode(user_key.sign(generic_challenge.as_bytes()).to_bytes());
4927        let generic_callback = post_form(
4928            &app,
4929            "/oauth/authorize",
4930            &[
4931                ("client_id", CLIENT_ID),
4932                ("redirect_uri", REDIRECT_URI),
4933                ("code_challenge", &generic_code_challenge),
4934                ("scope", "read:*:*"),
4935                ("state", "generic-client-state"),
4936                ("nonce", &generic_authorize_nonce),
4937                ("fingerprint", &fingerprint),
4938                ("signature", &generic_signature),
4939            ],
4940            None,
4941            false,
4942        )
4943        .await;
4944        assert_eq!(generic_callback.status(), axum::http::StatusCode::SEE_OTHER);
4945        let generic_location = generic_callback
4946            .headers()
4947            .get(axum::http::header::LOCATION)
4948            .and_then(|value| value.to_str().ok())
4949            .unwrap();
4950        let generic_location = url::Url::parse(generic_location)?;
4951        let generic_callback_params: std::collections::HashMap<_, _> =
4952            generic_location.query_pairs().into_owned().collect();
4953        assert_eq!(
4954            generic_callback_params.get("state").map(String::as_str),
4955            Some("generic-client-state")
4956        );
4957        assert_eq!(
4958            generic_callback_params.get("iss").map(String::as_str),
4959            Some(GENERIC_ISSUER)
4960        );
4961        let generic_code = generic_callback_params.get("code").unwrap();
4962        let generic_token = post_form(
4963            &app,
4964            "/oauth/token",
4965            &[
4966                ("grant_type", "authorization_code"),
4967                ("client_id", CLIENT_ID),
4968                ("code", generic_code),
4969                ("redirect_uri", REDIRECT_URI),
4970                ("code_verifier", GENERIC_PKCE_VERIFIER),
4971            ],
4972            None,
4973            false,
4974        )
4975        .await;
4976        assert_eq!(generic_token.status(), axum::http::StatusCode::OK);
4977        let generic_token_json = response_json(generic_token).await;
4978        assert_eq!(generic_token_json["token_type"], "Bearer");
4979        assert!(generic_token_json.get("sub").is_none());
4980        let generic_access_token = generic_token_json["access_token"]
4981            .as_str()
4982            .unwrap()
4983            .to_owned();
4984        let generic_refresh_token = generic_token_json["refresh_token"]
4985            .as_str()
4986            .unwrap()
4987            .to_owned();
4988        let generic_claims = jwt_claims(&generic_access_token);
4989        assert_eq!(generic_claims["sub"], "alice");
4990        assert!(generic_claims.get("cnf").is_none());
4991        assert_eq!(generic_claims["iss"], GENERIC_ISSUER);
4992        assert_eq!(generic_claims["aud"], GENERIC_ISSUER);
4993        assert_eq!(generic_claims["scope"], "read:*:*");
4994
4995        // Real authorization-code + S256 flows for each HTTP resource keep
4996        // their exact RFC 8707 audience and never borrow the login key as cnf.
4997        for resource in [
4998            "https://mcp.example.test/mcp",
4999            "https://oai.example.test/v1",
5000        ] {
5001            let authorize_uri = format!(
5002                "/oauth/authorize?{}",
5003                encode_form(&[
5004                    ("client_id", CLIENT_ID),
5005                    ("redirect_uri", REDIRECT_URI),
5006                    ("code_challenge", &generic_code_challenge),
5007                    ("code_challenge_method", "S256"),
5008                    ("response_type", "code"),
5009                    ("scope", "read:*:*"),
5010                    ("resource", resource),
5011                ])
5012            );
5013            let authorize = get(&app, &authorize_uri).await;
5014            assert_eq!(authorize.status(), axum::http::StatusCode::OK);
5015            let nonce = html_hidden_value(&response_text(authorize).await, "nonce").to_owned();
5016            let signature = STANDARD.encode(
5017                user_key
5018                    .sign(format!("{fingerprint}:{nonce}:{generic_code_challenge}").as_bytes())
5019                    .to_bytes(),
5020            );
5021            let callback = post_form(
5022                &app,
5023                "/oauth/authorize",
5024                &[
5025                    ("client_id", CLIENT_ID),
5026                    ("redirect_uri", REDIRECT_URI),
5027                    ("code_challenge", &generic_code_challenge),
5028                    ("scope", "read:*:*"),
5029                    ("resource", resource),
5030                    ("nonce", &nonce),
5031                    ("fingerprint", &fingerprint),
5032                    ("signature", &signature),
5033                ],
5034                None,
5035                false,
5036            )
5037            .await;
5038            assert_eq!(callback.status(), axum::http::StatusCode::SEE_OTHER);
5039            let location = url::Url::parse(
5040                callback
5041                    .headers()
5042                    .get(axum::http::header::LOCATION)
5043                    .unwrap()
5044                    .to_str()?,
5045            )?;
5046            let code = location
5047                .query_pairs()
5048                .find(|(key, _)| key == "code")
5049                .map(|(_, value)| value.into_owned())
5050                .unwrap();
5051            let token = post_form(
5052                &app,
5053                "/oauth/token",
5054                &[
5055                    ("grant_type", "authorization_code"),
5056                    ("client_id", CLIENT_ID),
5057                    ("code", &code),
5058                    ("redirect_uri", REDIRECT_URI),
5059                    ("code_verifier", GENERIC_PKCE_VERIFIER),
5060                ],
5061                None,
5062                false,
5063            )
5064            .await;
5065            assert_eq!(token.status(), axum::http::StatusCode::OK);
5066            let body = response_json(token).await;
5067            assert_eq!(body["token_type"], "Bearer");
5068            let access = body["access_token"].as_str().unwrap();
5069            let claims = jwt_claims(access);
5070            assert_eq!(claims["sub"], "alice");
5071            assert_eq!(claims["aud"], resource);
5072            assert!(claims.get("cnf").is_none());
5073            let wrong_audience = post_form_bearer(
5074                &app,
5075                "/oauth/introspect",
5076                &[("token", &generic_access_token)],
5077                access,
5078            )
5079            .await;
5080            assert_eq!(
5081                wrong_audience.status(),
5082                axum::http::StatusCode::UNAUTHORIZED
5083            );
5084        }
5085
5086        // A token minted without an explicit resource uses PolicyService's
5087        // configured path-bearing default audience. The AS must accept that
5088        // exact local alias on its own protected routes.
5089        let default_audience_token = state
5090            .policy_client
5091            .issue_token(&IssueToken {
5092                requested_scopes: Some(vec!["read:*:*".to_owned()]),
5093                ttl: Some(300),
5094                audience: None,
5095                subject: Some("default-audience-user".to_owned()),
5096                user_pub_key: None,
5097                dpop_jkt: None,
5098                issuer: None,
5099                tenant: Some(HOSTED_TENANT.to_owned()),
5100                require_clearance: false,
5101                session_id: None,
5102                issuance_profile: IssueTokenProfile::Rfc8693,
5103                client_id: Some("hyprstream-oauth-client-1".to_owned()),
5104            })
5105            .await?
5106            .token;
5107        assert_eq!(jwt_claims(&default_audience_token)["aud"], GENERIC_ISSUER);
5108        let default_audience_auth = post_form_bearer(
5109            &app,
5110            "/oauth/introspect",
5111            &[("token", &generic_access_token)],
5112            &default_audience_token,
5113        )
5114        .await;
5115        assert_eq!(
5116            default_audience_auth.status(),
5117            axum::http::StatusCode::OK,
5118            "the AS must accept its path-bearing default audience alias"
5119        );
5120        assert_eq!(response_json(default_audience_auth).await["active"], true);
5121
5122        let cross_tenant_token = state
5123            .policy_client
5124            .issue_token(&IssueToken {
5125                requested_scopes: Some(vec!["read:*:*".to_owned()]),
5126                ttl: Some(300),
5127                audience: Some(ISSUER.to_owned()),
5128                subject: Some("cross-tenant-introspector".to_owned()),
5129                user_pub_key: None,
5130                dpop_jkt: None,
5131                issuer: None,
5132                tenant: Some("other.example.test".to_owned()),
5133                require_clearance: false,
5134                session_id: None,
5135                issuance_profile: IssueTokenProfile::Rfc8693,
5136                client_id: Some("hyprstream-oauth-client-1".to_owned()),
5137            })
5138            .await?
5139            .token;
5140        let cross_tenant_introspection = post_form_bearer(
5141            &app,
5142            "/oauth/introspect",
5143            &[("token", &generic_access_token)],
5144            &cross_tenant_token,
5145        )
5146        .await;
5147        assert_eq!(
5148            response_json(cross_tenant_introspection).await["active"],
5149            false
5150        );
5151
5152        // Token exchange may only attenuate the verified subject token's signed
5153        // grant. A caller holding read:*:* cannot write transition:generic into
5154        // a newly signed scope claim.
5155        let inflation_subject = state
5156            .policy_client
5157            .issue_token(&IssueToken {
5158                requested_scopes: Some(vec!["read:*:*".to_owned()]),
5159                ttl: Some(300),
5160                audience: Some(ISSUER.to_owned()),
5161                subject: Some("scope-inflation-user".to_owned()),
5162                user_pub_key: None,
5163                dpop_jkt: None,
5164                issuer: None,
5165                tenant: Some("example.test".to_owned()),
5166                require_clearance: false,
5167                session_id: None,
5168                issuance_profile: IssueTokenProfile::Rfc8693,
5169                client_id: Some("hyprstream-oauth-client-1".to_owned()),
5170            })
5171            .await?
5172            .token;
5173        let inflated_exchange = post_form(
5174            &app,
5175            "/oauth/token",
5176            &[
5177                (
5178                    "grant_type",
5179                    "urn:ietf:params:oauth:grant-type:token-exchange",
5180                ),
5181                ("client_id", CLIENT_ID),
5182                ("subject_token", &inflation_subject),
5183                (
5184                    "subject_token_type",
5185                    "urn:ietf:params:oauth:token-type:access_token",
5186                ),
5187                ("scope", "transition:generic"),
5188                ("audience", ISSUER),
5189            ],
5190            None,
5191            false,
5192        )
5193        .await;
5194        assert_eq!(
5195            inflated_exchange.status(),
5196            axum::http::StatusCode::BAD_REQUEST
5197        );
5198        assert_eq!(
5199            response_json(inflated_exchange).await["error"],
5200            "invalid_scope"
5201        );
5202
5203        // The same endpoint accepts a production composite access token and
5204        // preserves a requested subset of its signed grant. This exercises the
5205        // shared algorithm/audience/issuer validator on the subject-token path.
5206        let valid_exchange_subject = state
5207            .policy_client
5208            .issue_token(&IssueToken {
5209                requested_scopes: Some(vec![
5210                    "read:*:*".to_owned(),
5211                    "transition:generic".to_owned(),
5212                ]),
5213                ttl: Some(300),
5214                audience: Some(ISSUER.to_owned()),
5215                subject: Some("scope-valid-user".to_owned()),
5216                user_pub_key: None,
5217                dpop_jkt: None,
5218                issuer: None,
5219                tenant: Some("example.test".to_owned()),
5220                require_clearance: false,
5221                session_id: None,
5222                issuance_profile: IssueTokenProfile::Rfc8693,
5223                client_id: Some("hyprstream-oauth-client-1".to_owned()),
5224            })
5225            .await?
5226            .token;
5227        let valid_exchange = post_form(
5228            &app,
5229            "/oauth/token",
5230            &[
5231                (
5232                    "grant_type",
5233                    "urn:ietf:params:oauth:grant-type:token-exchange",
5234                ),
5235                ("client_id", CLIENT_ID),
5236                ("subject_token", &valid_exchange_subject),
5237                (
5238                    "subject_token_type",
5239                    "urn:ietf:params:oauth:token-type:access_token",
5240                ),
5241                ("scope", "read:*:*"),
5242                ("audience", ISSUER),
5243            ],
5244            None,
5245            false,
5246        )
5247        .await;
5248        assert_eq!(valid_exchange.status(), axum::http::StatusCode::OK);
5249        let valid_exchange_json = response_json(valid_exchange).await;
5250        let valid_exchange_claims =
5251            jwt_claims(valid_exchange_json["access_token"].as_str().unwrap());
5252        assert_eq!(valid_exchange_claims["sub"], "scope-valid-user");
5253        assert_eq!(valid_exchange_claims["scope"], "read:*:*");
5254
5255        // A generic RFC 8693 exchange with a DPoP proof must return a
5256        // DPoP token type and bind the issued access token to that key.
5257        let bound_exchange_subject = state
5258            .policy_client
5259            .issue_token(&IssueToken {
5260                requested_scopes: Some(vec!["read:*:*".to_owned()]),
5261                ttl: Some(300),
5262                audience: Some(ISSUER.to_owned()),
5263                subject: Some("bound-exchange-user".to_owned()),
5264                user_pub_key: None,
5265                dpop_jkt: None,
5266                issuer: None,
5267                tenant: Some("example.test".to_owned()),
5268                require_clearance: false,
5269                session_id: None,
5270                issuance_profile: IssueTokenProfile::Rfc8693,
5271                client_id: Some("hyprstream-oauth-client-1".to_owned()),
5272            })
5273            .await?
5274            .token;
5275        let bound_key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
5276        let bound_point = bound_key.verifying_key().to_encoded_point(false);
5277        let bound_x: [u8; 32] = bound_point.x().unwrap().as_slice().try_into().unwrap();
5278        let bound_y: [u8; 32] = bound_point.y().unwrap().as_slice().try_into().unwrap();
5279        let expected_jkt = jwk_thumbprint(&JwkThumbprintInput::Es256 {
5280            x: &bound_x,
5281            y: &bound_y,
5282        });
5283        let proof = dpop_proof(
5284            &bound_key,
5285            &format!("{}/oauth/token", state.issuer_url.trim_end_matches('/')),
5286            "generic-exchange-proof",
5287            None,
5288        );
5289        let bound_exchange = post_form(
5290            &app,
5291            "/oauth/token",
5292            &[
5293                (
5294                    "grant_type",
5295                    "urn:ietf:params:oauth:grant-type:token-exchange",
5296                ),
5297                ("client_id", CLIENT_ID),
5298                ("subject_token", &bound_exchange_subject),
5299                (
5300                    "subject_token_type",
5301                    "urn:ietf:params:oauth:token-type:access_token",
5302                ),
5303                ("scope", "read:*:*"),
5304                ("audience", ISSUER),
5305            ],
5306            Some(&proof),
5307            false,
5308        )
5309        .await;
5310        assert_eq!(bound_exchange.status(), axum::http::StatusCode::OK);
5311        let bound_json = response_json(bound_exchange).await;
5312        assert_eq!(bound_json["token_type"], "DPoP");
5313        assert_eq!(
5314            jwt_claims(bound_json["access_token"].as_str().unwrap())["cnf"]["jkt"],
5315            expected_jkt
5316        );
5317
5318        // A stolen sender-constrained subject must not be downgraded to a
5319        // bearer or rebound to another key. Rejections must not burn the
5320        // legitimate subject token's single-use exchange.
5321        let sender_bound_subject = state
5322            .policy_client
5323            .issue_token(&IssueToken {
5324                requested_scopes: Some(vec!["read:*:*".to_owned()]),
5325                ttl: Some(300),
5326                audience: Some(ISSUER.to_owned()),
5327                subject: Some("sender-bound-exchange-user".to_owned()),
5328                user_pub_key: None,
5329                dpop_jkt: Some(expected_jkt.clone()),
5330                issuer: None,
5331                tenant: Some("example.test".to_owned()),
5332                require_clearance: false,
5333                session_id: None,
5334                issuance_profile: IssueTokenProfile::Rfc8693,
5335                client_id: Some("hyprstream-oauth-client-1".to_owned()),
5336            })
5337            .await?
5338            .token;
5339        let sender_fields = [
5340            (
5341                "grant_type",
5342                "urn:ietf:params:oauth:grant-type:token-exchange",
5343            ),
5344            ("client_id", CLIENT_ID),
5345            ("subject_token", sender_bound_subject.as_str()),
5346            (
5347                "subject_token_type",
5348                "urn:ietf:params:oauth:token-type:access_token",
5349            ),
5350            ("scope", "read:*:*"),
5351            ("audience", ISSUER),
5352        ];
5353        let wrong_key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
5354        let token_htu = format!("{}/oauth/token", state.issuer_url.trim_end_matches('/'));
5355        let wrong_proof = dpop_proof(&wrong_key, &token_htu, "wrong-sender-key", None);
5356        for presented in [None, Some(wrong_proof.as_str())] {
5357            let rejected = post_form(&app, "/oauth/token", &sender_fields, presented, false).await;
5358            assert_eq!(rejected.status(), axum::http::StatusCode::BAD_REQUEST);
5359            assert_eq!(response_json(rejected).await["error"], "invalid_dpop_proof");
5360        }
5361        let right_proof = dpop_proof(&bound_key, &token_htu, "right-sender-key", None);
5362        let accepted = post_form(
5363            &app,
5364            "/oauth/token",
5365            &sender_fields,
5366            Some(&right_proof),
5367            false,
5368        )
5369        .await;
5370        assert_eq!(accepted.status(), axum::http::StatusCode::OK);
5371        let accepted_json = response_json(accepted).await;
5372        assert_eq!(accepted_json["token_type"], "DPoP");
5373        assert_eq!(
5374            jwt_claims(accepted_json["access_token"].as_str().unwrap())["cnf"]["jkt"],
5375            expected_jkt
5376        );
5377
5378        // A proof JTI is single-use even across different subject tokens.
5379        // A fresh proof must still be able to exchange the second subject.
5380        let mut subjects = Vec::new();
5381        for subject in ["jti-subject-one", "jti-subject-two"] {
5382            subjects.push(
5383                state
5384                    .policy_client
5385                    .issue_token(&IssueToken {
5386                        requested_scopes: Some(vec!["read:*:*".to_owned()]),
5387                        ttl: Some(300),
5388                        audience: Some(ISSUER.to_owned()),
5389                        subject: Some(subject.to_owned()),
5390                        user_pub_key: None,
5391                        dpop_jkt: None,
5392                        issuer: None,
5393                        tenant: Some("example.test".to_owned()),
5394                        require_clearance: false,
5395                        session_id: None,
5396                        issuance_profile: IssueTokenProfile::Rfc8693,
5397                        client_id: Some("hyprstream-oauth-client-1".to_owned()),
5398                    })
5399                    .await?
5400                    .token,
5401            );
5402        }
5403        let mut exchange_fields = [
5404            (
5405                "grant_type",
5406                "urn:ietf:params:oauth:grant-type:token-exchange",
5407            ),
5408            ("client_id", CLIENT_ID),
5409            ("subject_token", subjects[0].as_str()),
5410            (
5411                "subject_token_type",
5412                "urn:ietf:params:oauth:token-type:access_token",
5413            ),
5414            ("scope", "read:*:*"),
5415            ("audience", ISSUER),
5416        ];
5417        let replay_proof = dpop_proof(&bound_key, &token_htu, "reused-proof-jti", None);
5418        let first = post_form(
5419            &app,
5420            "/oauth/token",
5421            &exchange_fields,
5422            Some(&replay_proof),
5423            false,
5424        )
5425        .await;
5426        assert_eq!(first.status(), axum::http::StatusCode::OK);
5427        exchange_fields[2].1 = subjects[1].as_str();
5428        let replay = post_form(
5429            &app,
5430            "/oauth/token",
5431            &exchange_fields,
5432            Some(&replay_proof),
5433            false,
5434        )
5435        .await;
5436        assert_eq!(replay.status(), axum::http::StatusCode::BAD_REQUEST);
5437        assert_eq!(response_json(replay).await["error"], "invalid_dpop_proof");
5438        let fresh_proof = dpop_proof(&bound_key, &token_htu, "fresh-proof-jti", None);
5439        let fresh = post_form(
5440            &app,
5441            "/oauth/token",
5442            &exchange_fields,
5443            Some(&fresh_proof),
5444            false,
5445        )
5446        .await;
5447        assert_eq!(fresh.status(), axum::http::StatusCode::OK);
5448
5449        // ── #1425: browser RFC 8693 sender-bound exchange contract ────────────
5450        //
5451        // Wire-level coverage of the DPoP+cnf.jkt browser exchange: positive
5452        // (client_id + DPoP → DPoP-bound token), and negatives (missing proof,
5453        // audience substitution, replayed jti). The request body is the exact
5454        // form the WASM client sends — built via `exchange_form_body`
5455        // (grant_type, subject_token, subject_token_type, client_id, resource)
5456        // — so the contract is tested against the frontend's generated
5457        // request, not a Rust-local fixture.
5458        use hyprstream_rpc::auth::{jwk_thumbprint, JwkThumbprintInput};
5459        use hyprstream_rpc::wasm_token_exchange::BROWSER_PUBLIC_CLIENT_ID;
5460        use rand::Rng as _;
5461        let browser_subject = state
5462            .policy_client
5463            .issue_token(&IssueToken {
5464                requested_scopes: Some(vec!["read:*:*".to_owned()]),
5465                ttl: Some(300),
5466                audience: Some(ISSUER.to_owned()),
5467                subject: Some("browser-user".to_owned()),
5468                user_pub_key: None,
5469                dpop_jkt: None,
5470                issuer: None,
5471                tenant: Some("example.test".to_owned()),
5472                require_clearance: false,
5473                session_id: None,
5474                issuance_profile: IssueTokenProfile::Rfc8693,
5475                client_id: Some("hyprstream-oauth-client-1".to_owned()),
5476            })
5477            .await?
5478            .token;
5479        let browser_dpop_key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
5480        let browser_point = browser_dpop_key.verifying_key().to_encoded_point(false);
5481        let browser_x: [u8; 32] = browser_point.x().unwrap().as_slice().try_into().unwrap();
5482        let browser_y: [u8; 32] = browser_point.y().unwrap().as_slice().try_into().unwrap();
5483        let expected_browser_jkt = jwk_thumbprint(&JwkThumbprintInput::Es256 {
5484            x: &browser_x,
5485            y: &browser_y,
5486        });
5487        let token_endpoint_url = format!("{ISSUER}/oauth/token");
5488        // Each exchange needs a fresh DPoP jti (the jti is single-use); the
5489        // proof KEY is constant, so cnf.jkt is stable across all of them.
5490        let fresh_browser_proof = || -> String {
5491            let jti = format!(
5492                "browser-{}",
5493                URL_SAFE_NO_PAD.encode(rand::rngs::OsRng.gen::<[u8; 8]>())
5494            );
5495            dpop_proof(&browser_dpop_key, &token_endpoint_url, &jti, None)
5496        };
5497
5498        // Build the exact WASM request body (`exchange_form_body`) + an
5499        // optional `audience` override, as owned pairs `post_form` accepts.
5500        //
5501        // #1425 r2 P2: `exchange_form_body` now always sends `resource` — the
5502        // real `fetch_exchange_token` computes it from the exact origin it is
5503        // calling (`exchange_endpoint`), which in this test harness is
5504        // `ISSUER`. This is the same value the real browser client would send
5505        // for a correctly configured deployment (the AS's own origin), so
5506        // every test built from this helper now exercises the client
5507        // actually sending the modeled resource, not a native-only fixture.
5508        let browser_fields = |subject: &str, audience: Option<&str>| -> Vec<(String, String)> {
5509            let body = hyprstream_rpc::wasm_token_exchange::exchange_form_body(
5510                subject,
5511                "urn:ietf:params:oauth:token-type:access_token",
5512                BROWSER_PUBLIC_CLIENT_ID,
5513                ISSUER,
5514            );
5515            let mut pairs: Vec<(String, String)> = url::form_urlencoded::parse(body.as_bytes())
5516                .into_owned()
5517                .collect();
5518            if let Some(aud) = audience {
5519                pairs.push(("audience".to_owned(), aud.to_owned()));
5520            }
5521            pairs
5522        };
5523        let str_slice = strs_of;
5524        fn strs_of(pairs: &[(String, String)]) -> Vec<(&str, &str)> {
5525            pairs
5526                .iter()
5527                .map(|(k, v)| (k.as_str(), v.as_str()))
5528                .collect()
5529        }
5530
5531        // Negative: no DPoP proof → sender binding is mandatory.
5532        let np = browser_fields(&browser_subject, Some(ISSUER));
5533        let np_refs = str_slice(&np);
5534        let no_proof = post_form(&app, "/oauth/token", &np_refs, None, false).await;
5535        assert_eq!(no_proof.status(), axum::http::StatusCode::BAD_REQUEST);
5536        assert_eq!(response_json(no_proof).await["error"], "invalid_request");
5537
5538        // Negative: audience substitution → invalid_target. The browser token
5539        // is restricted to the Hyprstream RPC service resource (the AS origin).
5540        let ef = browser_fields(&browser_subject, Some("https://evil.example"));
5541        let ef_refs = str_slice(&ef);
5542        let evil_proof = fresh_browser_proof();
5543        let evil = post_form(&app, "/oauth/token", &ef_refs, Some(&evil_proof), false).await;
5544        assert_eq!(evil.status(), axum::http::StatusCode::BAD_REQUEST);
5545        assert_eq!(response_json(evil).await["error"], "invalid_target");
5546
5547        // Positive: client_id + valid DPoP proof → DPoP-bound access token.
5548        let pf = browser_fields(&browser_subject, Some(ISSUER));
5549        let pf_refs = str_slice(&pf);
5550        let ok_proof = fresh_browser_proof();
5551        let browser_ok = post_form(&app, "/oauth/token", &pf_refs, Some(&ok_proof), false).await;
5552        assert_eq!(
5553            browser_ok.status(),
5554            axum::http::StatusCode::OK,
5555            "browser exchange positive path must succeed"
5556        );
5557        // #1425 acceptance 5: no token leakage. The response is no-store and
5558        // never echoes the token in a redirect/Location header.
5559        assert_eq!(
5560            browser_ok
5561                .headers()
5562                .get(axum::http::header::CACHE_CONTROL)
5563                .and_then(|v| v.to_str().ok()),
5564            Some("no-store")
5565        );
5566        assert!(browser_ok
5567            .headers()
5568            .get(axum::http::header::LOCATION)
5569            .is_none());
5570        let browser_json = response_json(browser_ok).await;
5571        assert_eq!(browser_json["token_type"].as_str(), Some("DPoP"));
5572        assert_eq!(
5573            browser_json["issued_token_type"].as_str(),
5574            Some("urn:ietf:params:oauth:token-type:access_token")
5575        );
5576        // Access-token only: no refresh token (rotation is a separately
5577        // reviewed, metadata-advertised policy).
5578        assert!(
5579            browser_json.get("refresh_token").is_none(),
5580            "browser exchange must not issue a refresh token"
5581        );
5582        let browser_access = browser_json["access_token"].as_str().unwrap();
5583        // The token never appears anywhere except the access_token field.
5584        assert_eq!(
5585            browser_json
5586                .as_object()
5587                .unwrap()
5588                .iter()
5589                .filter(|(_, v)| v.as_str().is_some_and(|s| s.contains(browser_access)))
5590                .count(),
5591            1,
5592            "access_token must not be echoed in any other response field"
5593        );
5594        let browser_claims = jwt_claims(browser_access);
5595        assert_eq!(browser_claims["sub"], "browser-user");
5596        assert_eq!(
5597            browser_claims["cnf"]["jkt"].as_str(),
5598            Some(expected_browser_jkt.as_str()),
5599            "minted token must be bound to the DPoP proof key (cnf.jkt)"
5600        );
5601        assert_eq!(
5602            browser_claims["aud"].as_str(),
5603            Some(ISSUER),
5604            "issued token audience must be restricted to the RPC service resource"
5605        );
5606        // The "use" half of acceptance 3 (a DPoP-bound token cannot be used as
5607        // a plain Bearer; a resource request needs a matching proof + ath) is
5608        // enforced by the existing resource middleware in `auth.rs` the moment
5609        // the exchange mints `cnf.jkt` — the binding just verified above. That
5610        // enforcement has its own coverage in `auth.rs`; the #1425 deliverable
5611        // is the exchange producing the binding.
5612
5613        // Negative: replayed DPoP proof (same jti) → invalid_dpop_proof.
5614        // A fresh subject token avoids the subject-replay check.
5615        let replay_subject = state
5616            .policy_client
5617            .issue_token(&IssueToken {
5618                requested_scopes: Some(vec!["read:*:*".to_owned()]),
5619                ttl: Some(300),
5620                audience: Some(ISSUER.to_owned()),
5621                subject: Some("browser-replay".to_owned()),
5622                user_pub_key: None,
5623                dpop_jkt: None,
5624                issuer: None,
5625                tenant: Some("example.test".to_owned()),
5626                require_clearance: false,
5627                session_id: None,
5628                issuance_profile: IssueTokenProfile::Rfc8693,
5629                client_id: Some("hyprstream-oauth-client-1".to_owned()),
5630            })
5631            .await?
5632            .token;
5633        let rf = browser_fields(&replay_subject, Some(ISSUER));
5634        let rf_refs = str_slice(&rf);
5635        // Reuse the positive proof's jti → single-use replay rejection.
5636        let replay = post_form(&app, "/oauth/token", &rf_refs, Some(&ok_proof), false).await;
5637        assert_eq!(replay.status(), axum::http::StatusCode::BAD_REQUEST);
5638        assert_eq!(response_json(replay).await["error"], "invalid_dpop_proof");
5639
5640        // ── #1425 r1 P1#3: DPoP resource-use wire tests (cnf.jkt token on a
5641        //    protected route) ────────────────────────────────────────────────
5642        // The exchanged `browser_access` token carries cnf.jkt = the DPoP key's
5643        // thumbprint. The resource layer (`require_bearer_token` middleware on
5644        // `/oauth/userinfo`) enforces: cnf.jkt tokens rejected as Bearer, DPoP
5645        // proof verified (htm/htu/ath/jti/nonce), cnf.jkt matched to the proof
5646        // key. These tests exercise that enforcement with the ACTUAL token the
5647        // exchange minted, not a fixture.
5648        use axum::body::Body as Body_;
5649        let userinfo_htu = format!("{ISSUER}/oauth/userinfo");
5650
5651        // Bearer downgrade rejection (RFC 9449 §7): cnf.jkt token as Bearer.
5652        let bearer_downgrade = app
5653            .clone()
5654            .oneshot(
5655                axum::http::Request::get("/oauth/userinfo")
5656                    .header(
5657                        axum::http::header::AUTHORIZATION,
5658                        format!("Bearer {browser_access}"),
5659                    )
5660                    .body(Body_::empty())
5661                    .unwrap(),
5662            )
5663            .await
5664            .unwrap();
5665        assert_eq!(
5666            bearer_downgrade.status(),
5667            axum::http::StatusCode::UNAUTHORIZED,
5668            "cnf.jkt-bound token presented as Bearer MUST be rejected"
5669        );
5670
5671        // DPoP proof without nonce → 401 use_dpop_nonce (the exchange marked
5672        // this key as nonced). Extract the fresh nonce for the retry.
5673        let no_nonce_jti = format!(
5674            "res-no-nonce-{}",
5675            URL_SAFE_NO_PAD.encode(rand::rngs::OsRng.gen::<[u8; 8]>())
5676        );
5677        let no_nonce_proof = dpop_resource_proof(
5678            &browser_dpop_key,
5679            "GET",
5680            &userinfo_htu,
5681            browser_access,
5682            &no_nonce_jti,
5683            None,
5684        );
5685        let no_nonce_resp = app
5686            .clone()
5687            .oneshot(
5688                axum::http::Request::get("/oauth/userinfo")
5689                    .header(
5690                        axum::http::header::AUTHORIZATION,
5691                        format!("DPoP {browser_access}"),
5692                    )
5693                    .header("DPoP", &no_nonce_proof)
5694                    .body(Body_::empty())
5695                    .unwrap(),
5696            )
5697            .await
5698            .unwrap();
5699        assert_eq!(no_nonce_resp.status(), axum::http::StatusCode::UNAUTHORIZED);
5700        let resource_nonce = no_nonce_resp
5701            .headers()
5702            .get("DPoP-Nonce")
5703            .and_then(|v| v.to_str().ok())
5704            .map(str::to_owned);
5705        assert!(
5706            resource_nonce.is_some(),
5707            "use_dpop_nonce response MUST carry a DPoP-Nonce header"
5708        );
5709
5710        // Resource success WITH the nonce: matching proof key + ath + nonce.
5711        let success_jti = format!(
5712            "res-ok-{}",
5713            URL_SAFE_NO_PAD.encode(rand::rngs::OsRng.gen::<[u8; 8]>())
5714        );
5715        let success_proof = dpop_resource_proof(
5716            &browser_dpop_key,
5717            "GET",
5718            &userinfo_htu,
5719            browser_access,
5720            &success_jti,
5721            resource_nonce.as_deref(),
5722        );
5723        let resource_ok = app
5724            .clone()
5725            .oneshot(
5726                axum::http::Request::get("/oauth/userinfo")
5727                    .header(
5728                        axum::http::header::AUTHORIZATION,
5729                        format!("DPoP {browser_access}"),
5730                    )
5731                    .header("DPoP", &success_proof)
5732                    .body(Body_::empty())
5733                    .unwrap(),
5734            )
5735            .await
5736            .unwrap();
5737        assert_ne!(
5738            resource_ok.status(),
5739            axum::http::StatusCode::UNAUTHORIZED,
5740            "DPoP token with matching proof + nonce + cnf.jkt + ath MUST be accepted at the resource"
5741        );
5742
5743        // Key mismatch rejection: attacker proof key ≠ the token's cnf.jkt.
5744        let attacker_key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
5745        let mismatch_jti = format!(
5746            "res-mismatch-{}",
5747            URL_SAFE_NO_PAD.encode(rand::rngs::OsRng.gen::<[u8; 8]>())
5748        );
5749        let mismatch_proof = dpop_resource_proof(
5750            &attacker_key,
5751            "GET",
5752            &userinfo_htu,
5753            browser_access,
5754            &mismatch_jti,
5755            resource_nonce.as_deref(),
5756        );
5757        let mismatch_resp = app
5758            .clone()
5759            .oneshot(
5760                axum::http::Request::get("/oauth/userinfo")
5761                    .header(
5762                        axum::http::header::AUTHORIZATION,
5763                        format!("DPoP {browser_access}"),
5764                    )
5765                    .header("DPoP", &mismatch_proof)
5766                    .body(Body_::empty())
5767                    .unwrap(),
5768            )
5769            .await
5770            .unwrap();
5771        assert_eq!(
5772            mismatch_resp.status(),
5773            axum::http::StatusCode::UNAUTHORIZED,
5774            "DPoP proof from a different key MUST be rejected (cnf.jkt mismatch)"
5775        );
5776
5777        // ── #1425 r1 P1#2: Subject-token cnf.jkt same-key binding ───────────
5778        // A DPoP-bound subject access token MUST be exchanged under a proof
5779        // from the SAME key. An attacker who steals the token string cannot
5780        // re-bind it to their own key.
5781        let subject_key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
5782        let subject_point = subject_key.verifying_key().to_encoded_point(false);
5783        let subject_x: [u8; 32] = subject_point.x().unwrap().as_slice().try_into().unwrap();
5784        let subject_y: [u8; 32] = subject_point.y().unwrap().as_slice().try_into().unwrap();
5785        let subject_jkt = jwk_thumbprint(&JwkThumbprintInput::Es256 {
5786            x: &subject_x,
5787            y: &subject_y,
5788        });
5789
5790        // Mint a DPoP-bound subject token (carries cnf.jkt = subject_key's jkt).
5791        let cnf_bound_subject = state
5792            .policy_client
5793            .issue_token(&IssueToken {
5794                requested_scopes: Some(vec!["read:*:*".to_owned()]),
5795                ttl: Some(300),
5796                audience: Some(ISSUER.to_owned()),
5797                subject: Some("cnf-bound-user".to_owned()),
5798                user_pub_key: None,
5799                dpop_jkt: Some(subject_jkt.clone()),
5800                issuer: None,
5801                tenant: Some("example.test".to_owned()),
5802                require_clearance: false,
5803                session_id: None,
5804                issuance_profile: IssueTokenProfile::Rfc8693,
5805                client_id: Some("hyprstream-oauth-client-1".to_owned()),
5806            })
5807            .await?
5808            .token;
5809
5810        // Same-key positive: exchange the bound subject under a proof from the
5811        // SAME key. Bootstrap (no nonce) is fine — this is the first exchange
5812        // for this DPoP key.
5813        let same_key_jti = format!(
5814            "same-key-{}",
5815            URL_SAFE_NO_PAD.encode(rand::rngs::OsRng.gen::<[u8; 8]>())
5816        );
5817        let same_key_proof = dpop_proof(&subject_key, &token_endpoint_url, &same_key_jti, None);
5818        let same_key_fields = browser_fields(&cnf_bound_subject, Some(ISSUER));
5819        let same_key_refs = str_slice(&same_key_fields);
5820        let same_key_resp = post_form(
5821            &app,
5822            "/oauth/token",
5823            &same_key_refs,
5824            Some(&same_key_proof),
5825            false,
5826        )
5827        .await;
5828        assert_eq!(
5829            same_key_resp.status(),
5830            axum::http::StatusCode::OK,
5831            "same-key exchange (subject cnf.jkt == proof key) must succeed"
5832        );
5833        let same_key_json = response_json(same_key_resp).await;
5834        assert_eq!(same_key_json["token_type"].as_str(), Some("DPoP"));
5835        let same_key_access = same_key_json["access_token"].as_str().unwrap();
5836        let same_key_claims = jwt_claims(same_key_access);
5837        assert_eq!(
5838            same_key_claims["cnf"]["jkt"].as_str(),
5839            Some(subject_jkt.as_str()),
5840            "minted token must carry the SAME cnf.jkt as the subject token"
5841        );
5842
5843        // Cross-key negative (A-token / B-proof): exchange a fresh DPoP-bound
5844        // subject token under a proof from a DIFFERENT key. The same-key check
5845        // must reject the substitution before consuming the subject token.
5846        let attacker_subject_key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
5847        let cnf_bound_subject_2 = state
5848            .policy_client
5849            .issue_token(&IssueToken {
5850                requested_scopes: Some(vec!["read:*:*".to_owned()]),
5851                ttl: Some(300),
5852                audience: Some(ISSUER.to_owned()),
5853                subject: Some("cnf-bound-user-2".to_owned()),
5854                user_pub_key: None,
5855                dpop_jkt: Some(subject_jkt.clone()),
5856                issuer: None,
5857                tenant: Some("example.test".to_owned()),
5858                require_clearance: false,
5859                session_id: None,
5860                issuance_profile: IssueTokenProfile::Rfc8693,
5861                client_id: Some("hyprstream-oauth-client-1".to_owned()),
5862            })
5863            .await?
5864            .token;
5865        let cross_key_jti = format!(
5866            "cross-key-{}",
5867            URL_SAFE_NO_PAD.encode(rand::rngs::OsRng.gen::<[u8; 8]>())
5868        );
5869        let cross_key_proof = dpop_proof(
5870            &attacker_subject_key,
5871            &token_endpoint_url,
5872            &cross_key_jti,
5873            None,
5874        );
5875        let cross_key_fields = browser_fields(&cnf_bound_subject_2, Some(ISSUER));
5876        let cross_key_refs = str_slice(&cross_key_fields);
5877        let cross_key_resp = post_form(
5878            &app,
5879            "/oauth/token",
5880            &cross_key_refs,
5881            Some(&cross_key_proof),
5882            false,
5883        )
5884        .await;
5885        assert_eq!(
5886            cross_key_resp.status(),
5887            axum::http::StatusCode::BAD_REQUEST,
5888            "cross-key exchange (subject cnf.jkt ≠ proof key) MUST be rejected"
5889        );
5890        assert_eq!(
5891            response_json(cross_key_resp).await["error"],
5892            "invalid_dpop_proof",
5893            "key substitution must surface as invalid_dpop_proof"
5894        );
5895
5896        // ── #1425 r1/r2 P2: RFC 8693 fields the browser contract does not accept ──
5897        // All are rejected before DPoP verification/subject-token
5898        // consumption, so the (already-used) `browser_subject` string is safe
5899        // to reuse — none of these requests reach subject-token verification.
5900        let mut actor_fields = browser_fields(&browser_subject, Some(ISSUER));
5901        actor_fields.push(("actor_token".to_owned(), "some-actor-jwt".to_owned()));
5902        let actor_resp =
5903            post_form(&app, "/oauth/token", &str_slice(&actor_fields), None, false).await;
5904        assert_eq!(actor_resp.status(), axum::http::StatusCode::BAD_REQUEST);
5905        assert_eq!(response_json(actor_resp).await["error"], "invalid_request");
5906
5907        // ── #1425 r2 P2: `actor_token_type` alone (no `actor_token`) must not
5908        //    be treated as if the request carried no actor field at all — the
5909        //    prior revision only modeled/rejected `actor_token`, so an
5910        //    `actor_token_type`-only request was silently dropped by the form
5911        //    extractor and reached subject-token verification unrejected.
5912        //    No DPoP proof is supplied here either, proving (via the returned
5913        //    `invalid_request`, not "requires a DPoP proof") that this is
5914        //    rejected before DPoP admission and before subject-token
5915        //    consumption — `browser_subject` remains safe to reuse below.
5916        let mut actor_type_standalone_fields = browser_fields(&browser_subject, Some(ISSUER));
5917        actor_type_standalone_fields.push((
5918            "actor_token_type".to_owned(),
5919            "urn:ietf:params:oauth:token-type:jwt".to_owned(),
5920        ));
5921        let actor_type_standalone_resp = post_form(
5922            &app,
5923            "/oauth/token",
5924            &str_slice(&actor_type_standalone_fields),
5925            None,
5926            false,
5927        )
5928        .await;
5929        assert_eq!(
5930            actor_type_standalone_resp.status(),
5931            axum::http::StatusCode::BAD_REQUEST,
5932            "actor_token_type alone must be rejected, not silently ignored"
5933        );
5934        assert_eq!(
5935            response_json(actor_type_standalone_resp).await["error"],
5936            "invalid_request"
5937        );
5938
5939        // Duplicate `actor_token_type` fields: proves the rejection is real
5940        // field modeling (caught by the same axum::Form duplicate-key
5941        // detection already proven for `resource`), not a single manually
5942        // inserted value that a second, differently-encoded copy could evade.
5943        let mut actor_type_dup_fields = browser_fields(&browser_subject, Some(ISSUER));
5944        actor_type_dup_fields.push((
5945            "actor_token_type".to_owned(),
5946            "urn:ietf:params:oauth:token-type:jwt".to_owned(),
5947        ));
5948        actor_type_dup_fields.push((
5949            "actor_token_type".to_owned(),
5950            "urn:ietf:params:oauth:token-type:access_token".to_owned(),
5951        ));
5952        let actor_type_dup_resp = post_form(
5953            &app,
5954            "/oauth/token",
5955            &str_slice(&actor_type_dup_fields),
5956            None,
5957            false,
5958        )
5959        .await;
5960        assert!(
5961            actor_type_dup_resp.status().is_client_error(),
5962            "duplicate actor_token_type fields must be rejected, not silently take the last \
5963             value (got {})",
5964            actor_type_dup_resp.status()
5965        );
5966
5967        let mut rtt_fields = browser_fields(&browser_subject, Some(ISSUER));
5968        rtt_fields.push((
5969            "requested_token_type".to_owned(),
5970            "urn:ietf:params:oauth:token-type:refresh_token".to_owned(),
5971        ));
5972        let rtt_resp = post_form(&app, "/oauth/token", &str_slice(&rtt_fields), None, false).await;
5973        assert_eq!(rtt_resp.status(), axum::http::StatusCode::BAD_REQUEST);
5974        assert_eq!(response_json(rtt_resp).await["error"], "invalid_target");
5975
5976        let mut tenant_fields = browser_fields(&browser_subject, Some(ISSUER));
5977        tenant_fields.push(("tenant".to_owned(), "some-other-tenant".to_owned()));
5978        let tenant_resp = post_form(
5979            &app,
5980            "/oauth/token",
5981            &str_slice(&tenant_fields),
5982            None,
5983            false,
5984        )
5985        .await;
5986        assert_eq!(tenant_resp.status(), axum::http::StatusCode::BAD_REQUEST);
5987        assert_eq!(response_json(tenant_resp).await["error"], "invalid_request");
5988
5989        // `resource` mismatch → invalid_target, mirroring the `audience` negative above.
5990        // `browser_fields` now sends the correct `resource` by default (the
5991        // real client always does); strip it before substituting the bad value.
5992        let mut resource_bad_fields = browser_fields(&browser_subject, None);
5993        resource_bad_fields.retain(|(k, _)| k != "resource");
5994        resource_bad_fields.push(("resource".to_owned(), "https://evil.example".to_owned()));
5995        let resource_bad_resp = post_form(
5996            &app,
5997            "/oauth/token",
5998            &str_slice(&resource_bad_fields),
5999            None,
6000            false,
6001        )
6002        .await;
6003        assert_eq!(
6004            resource_bad_resp.status(),
6005            axum::http::StatusCode::BAD_REQUEST
6006        );
6007        assert_eq!(
6008            response_json(resource_bad_resp).await["error"],
6009            "invalid_target"
6010        );
6011
6012        // Duplicate `resource` fields: `axum::Form<TokenRequest>` deserializes
6013        // via serde's generated struct visitor, which errors on a field set
6014        // twice — a duplicate cannot silently smuggle a second, later-wins
6015        // value past the single-value check above.
6016        let mut dup_resource_fields = browser_fields(&browser_subject, None);
6017        dup_resource_fields.retain(|(k, _)| k != "resource");
6018        dup_resource_fields.push(("resource".to_owned(), ISSUER.to_owned()));
6019        dup_resource_fields.push(("resource".to_owned(), "https://evil.example".to_owned()));
6020        let dup_resource_resp = post_form(
6021            &app,
6022            "/oauth/token",
6023            &str_slice(&dup_resource_fields),
6024            None,
6025            false,
6026        )
6027        .await;
6028        assert!(
6029            dup_resource_resp.status().is_client_error(),
6030            "duplicate resource fields must be rejected, not silently take the last value \
6031             (got {})",
6032            dup_resource_resp.status()
6033        );
6034
6035        // `resource` matching the canonical RPC resource is accepted (a fresh
6036        // subject token, since this request runs the full exchange to success).
6037        // #1425 r2 P2: `browser_fields` already sends the correct `resource`
6038        // by default via the real `exchange_form_body` — this positive case
6039        // needs no manual field push, which is exactly the point: the browser
6040        // caller's own request, unmodified, must succeed.
6041        let resource_ok_subject = state
6042            .policy_client
6043            .issue_token(&IssueToken {
6044                requested_scopes: Some(vec!["read:*:*".to_owned()]),
6045                ttl: Some(300),
6046                audience: Some(ISSUER.to_owned()),
6047                subject: Some("resource-field-user".to_owned()),
6048                user_pub_key: None,
6049                dpop_jkt: None,
6050                issuer: None,
6051                tenant: Some("example.test".to_owned()),
6052                require_clearance: false,
6053                session_id: None,
6054                issuance_profile: IssueTokenProfile::Rfc8693,
6055                client_id: Some("hyprstream-oauth-client-1".to_owned()),
6056            })
6057            .await?
6058            .token;
6059        let resource_ok_fields = browser_fields(&resource_ok_subject, None);
6060        // A brand-new DPoP key: `browser_dpop_key` was already marked "nonced"
6061        // by the earlier positive exchange above, so its bootstrap window has
6062        // closed — reusing it here would spuriously hit `use_dpop_nonce`.
6063        let resource_ok_key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
6064        let resource_ok_jti = format!(
6065            "resource-ok-{}",
6066            URL_SAFE_NO_PAD.encode(rand::rngs::OsRng.gen::<[u8; 8]>())
6067        );
6068        let resource_ok_proof = dpop_proof(
6069            &resource_ok_key,
6070            &token_endpoint_url,
6071            &resource_ok_jti,
6072            None,
6073        );
6074        let resource_ok_resp = post_form(
6075            &app,
6076            "/oauth/token",
6077            &str_slice(&resource_ok_fields),
6078            Some(&resource_ok_proof),
6079            false,
6080        )
6081        .await;
6082        assert_eq!(
6083            resource_ok_resp.status(),
6084            axum::http::StatusCode::OK,
6085            "resource matching the canonical RPC resource must be accepted"
6086        );
6087
6088        // ── #1425 r1 P2: id_token is not a supported browser subject type ──────
6089        let mut idt_fields = browser_fields(&browser_subject, Some(ISSUER));
6090        for pair in idt_fields.iter_mut() {
6091            if pair.0 == "subject_token_type" {
6092                pair.1 = "urn:ietf:params:oauth:token-type:id_token".to_owned();
6093            }
6094        }
6095        // A brand-new DPoP key (bootstrap, no nonce needed): `browser_dpop_key`
6096        // is already nonced by the earlier positive exchange.
6097        let idt_key = p256::ecdsa::SigningKey::random(&mut rand::rngs::OsRng);
6098        let idt_jti = format!(
6099            "idt-{}",
6100            URL_SAFE_NO_PAD.encode(rand::rngs::OsRng.gen::<[u8; 8]>())
6101        );
6102        let idt_proof = dpop_proof(&idt_key, &token_endpoint_url, &idt_jti, None);
6103        let idt_resp = post_form(
6104            &app,
6105            "/oauth/token",
6106            &str_slice(&idt_fields),
6107            Some(&idt_proof),
6108            false,
6109        )
6110        .await;
6111        assert_eq!(idt_resp.status(), axum::http::StatusCode::UNAUTHORIZED);
6112        assert_eq!(response_json(idt_resp).await["error"], "invalid_grant");
6113
6114        // ── #1425 r1 P1#3/#4: the actual WASM-shared functions, end to end ─────
6115        // Builds the DPoP proof with the SAME pure functions
6116        // `wasm_token_exchange::fetch_exchange_token` calls from the browser
6117        // (`ed25519_dpop_signing_input` + `assemble_dpop_proof`), signed by a
6118        // real `ed25519_dalek` key — not a Rust-local reconstruction of the
6119        // wire shape, the literal shared code. Exercises bootstrap, the
6120        // `use_dpop_nonce` retry, and confirms the minted `cnf.jkt` is exactly
6121        // `ed25519_dpop_jkt(pubkey)` — the same equality `VfsShell::connect`
6122        // relies on to make the token usable on the RPC path (proven against
6123        // the real RPC verifier in `service/svc.rs`'s
6124        // `browser_cnf_jkt_token_succeeds_over_matching_envelope_signer`).
6125        use hyprstream_rpc::wasm_token_exchange::{
6126            assemble_dpop_proof, ed25519_dpop_jkt, ed25519_dpop_signing_input,
6127        };
6128        let wasm_key = ed25519_dalek::SigningKey::from_bytes(&[0x91; 32]);
6129        let wasm_pubkey: [u8; 32] = wasm_key.verifying_key().to_bytes();
6130        let build_wasm_proof = |jti: &str, nonce: Option<&str>| -> String {
6131            use ed25519_dalek::Signer as _;
6132            let iat = chrono::Utc::now().timestamp();
6133            let (signing_input, _) = ed25519_dpop_signing_input(
6134                &wasm_pubkey,
6135                "POST",
6136                &token_endpoint_url,
6137                iat,
6138                jti,
6139                None,
6140                nonce,
6141            )
6142            .unwrap();
6143            let signature = wasm_key.sign(signing_input.as_bytes());
6144            assemble_dpop_proof(&signing_input, &signature.to_bytes())
6145        };
6146        let wasm_subject = state
6147            .policy_client
6148            .issue_token(&IssueToken {
6149                requested_scopes: Some(vec!["read:*:*".to_owned()]),
6150                ttl: Some(300),
6151                audience: Some(ISSUER.to_owned()),
6152                subject: Some("wasm-shared-fn-user".to_owned()),
6153                user_pub_key: None,
6154                dpop_jkt: None,
6155                issuer: None,
6156                tenant: Some("example.test".to_owned()),
6157                require_clearance: false,
6158                session_id: None,
6159                issuance_profile: IssueTokenProfile::Rfc8693,
6160                client_id: Some("hyprstream-oauth-client-1".to_owned()),
6161            })
6162            .await?
6163            .token;
6164        // Bootstrap: no nonce yet for this key.
6165        let wasm_bootstrap_proof = build_wasm_proof("wasm-shared-bootstrap", None);
6166        let wasm_fields = browser_fields(&wasm_subject, Some(ISSUER));
6167        let wasm_bootstrap_resp = post_form(
6168            &app,
6169            "/oauth/token",
6170            &str_slice(&wasm_fields),
6171            Some(&wasm_bootstrap_proof),
6172            false,
6173        )
6174        .await;
6175        assert_eq!(
6176            wasm_bootstrap_resp.status(),
6177            axum::http::StatusCode::OK,
6178            "bootstrap exchange via the real wasm_token_exchange helpers must succeed"
6179        );
6180        let wasm_json = response_json(wasm_bootstrap_resp).await;
6181        let wasm_access = wasm_json["access_token"].as_str().unwrap().to_owned();
6182        let wasm_claims = jwt_claims(&wasm_access);
6183        assert_eq!(
6184            wasm_claims["cnf"]["jkt"].as_str(),
6185            Some(ed25519_dpop_jkt(&wasm_pubkey).as_str()),
6186            "minted cnf.jkt must equal ed25519_dpop_jkt(pubkey) — the exact check \
6187             VfsShell::connect relies on to make the token usable over the matching \
6188             RPC envelope signer"
6189        );
6190
6191        // use_dpop_nonce round trip: a second exchange from the SAME wasm key,
6192        // without a nonce, must now be required to retry — proving the server
6193        // half of the nonce lifecycle the WASM client's `decide_nonce_outcome`
6194        // reacts to is real, not asserted only in the pure unit tests.
6195        let wasm_subject_2 = state
6196            .policy_client
6197            .issue_token(&IssueToken {
6198                requested_scopes: Some(vec!["read:*:*".to_owned()]),
6199                ttl: Some(300),
6200                audience: Some(ISSUER.to_owned()),
6201                subject: Some("wasm-shared-fn-user-2".to_owned()),
6202                user_pub_key: None,
6203                dpop_jkt: None,
6204                issuer: None,
6205                tenant: Some("example.test".to_owned()),
6206                require_clearance: false,
6207                session_id: None,
6208                issuance_profile: IssueTokenProfile::Rfc8693,
6209                client_id: Some("hyprstream-oauth-client-1".to_owned()),
6210            })
6211            .await?
6212            .token;
6213        let wasm_no_nonce_proof = build_wasm_proof("wasm-shared-no-nonce", None);
6214        let wasm_fields_2 = browser_fields(&wasm_subject_2, Some(ISSUER));
6215        let wasm_nonce_required_resp = post_form(
6216            &app,
6217            "/oauth/token",
6218            &str_slice(&wasm_fields_2),
6219            Some(&wasm_no_nonce_proof),
6220            false,
6221        )
6222        .await;
6223        assert_eq!(
6224            wasm_nonce_required_resp.status(),
6225            axum::http::StatusCode::BAD_REQUEST
6226        );
6227        let wasm_fresh_nonce = wasm_nonce_required_resp
6228            .headers()
6229            .get("DPoP-Nonce")
6230            .and_then(|v| v.to_str().ok())
6231            .map(str::to_owned)
6232            .expect("use_dpop_nonce response must carry a fresh DPoP-Nonce");
6233        assert_eq!(
6234            response_json(wasm_nonce_required_resp).await["error"],
6235            "use_dpop_nonce"
6236        );
6237        // Retry with a fresh proof carrying the server nonce — matches exactly
6238        // what `decide_nonce_outcome` -> `NonceOutcome::RetryWithNonce` drives
6239        // the browser client to do.
6240        let wasm_retry_proof = build_wasm_proof("wasm-shared-retry", Some(&wasm_fresh_nonce));
6241        let wasm_retry_resp = post_form(
6242            &app,
6243            "/oauth/token",
6244            &str_slice(&wasm_fields_2),
6245            Some(&wasm_retry_proof),
6246            false,
6247        )
6248        .await;
6249        assert_eq!(
6250            wasm_retry_resp.status(),
6251            axum::http::StatusCode::OK,
6252            "nonce retry via the real wasm_token_exchange helpers must succeed"
6253        );
6254
6255        // The real composite token minted above authenticates to a protected
6256        // OAuth route. This failed when middleware routed every JWT through
6257        // the fixed EdDSA key.
6258        let generic_introspection = post_form_bearer(
6259            &app,
6260            "/oauth/introspect",
6261            &[("token", &generic_refresh_token)],
6262            &generic_access_token,
6263        )
6264        .await;
6265        let generic_introspection_status = generic_introspection.status();
6266        let generic_introspection_json = response_json(generic_introspection).await;
6267        assert_eq!(
6268            generic_introspection_status,
6269            axum::http::StatusCode::OK,
6270            "{generic_introspection_json}"
6271        );
6272        assert_eq!(generic_introspection_json["active"], true);
6273        assert_eq!(generic_introspection_json["sub"], "alice");
6274
6275        // JWT introspection uses the same composite/audience/issuer validator
6276        // and returns the signed grant scope rather than subject-wide policy.
6277        let access_introspection = post_form_bearer(
6278            &app,
6279            "/oauth/introspect",
6280            &[("token", &generic_access_token)],
6281            &generic_access_token,
6282        )
6283        .await;
6284        assert_eq!(access_introspection.status(), axum::http::StatusCode::OK);
6285        let access_introspection_json = response_json(access_introspection).await;
6286        assert_eq!(access_introspection_json["active"], true);
6287        assert_eq!(access_introspection_json["scope"], "read:*:*");
6288
6289        let snapshot = hyprstream_rpc::auth::global_composite_key_set().snapshot();
6290        let signing_pair = snapshot
6291            .active_signing_pair(hyprstream_rpc::auth::CompositePairRole::Policy)
6292            .unwrap();
6293        let (ml_signing, ed_signing) = signing_pair.signing_keys().unwrap();
6294        let now = chrono::Utc::now().timestamp();
6295        let wrong_audience = crate::auth::jwt::encode_composite_ml_dsa_65_ed25519(
6296            &hyprstream_rpc::auth::Claims::new("alice".to_owned(), now, now + 300)
6297                .with_issuer(GENERIC_ISSUER.to_owned())
6298                .with_audience(Some("https://other-resource.example.test".to_owned()))
6299                .with_scope(Some("read:*:*".to_owned())),
6300            &ml_signing,
6301            &ed_signing,
6302        );
6303        let rejected_audience = post_form_bearer(
6304            &app,
6305            "/oauth/introspect",
6306            &[("token", &generic_refresh_token)],
6307            &wrong_audience,
6308        )
6309        .await;
6310        assert_eq!(
6311            rejected_audience.status(),
6312            axum::http::StatusCode::UNAUTHORIZED
6313        );
6314
6315        // The same no-resource, non-DPoP grant must rotate as a true Bearer
6316        // with its original session and no borrowed login-key cnf claim.
6317        let generic_refresh = post_form(
6318            &app,
6319            "/oauth/token",
6320            &[
6321                ("grant_type", "refresh_token"),
6322                ("client_id", CLIENT_ID),
6323                ("refresh_token", &generic_refresh_token),
6324            ],
6325            None,
6326            false,
6327        )
6328        .await;
6329        assert_eq!(generic_refresh.status(), axum::http::StatusCode::OK);
6330        let refreshed_json = response_json(generic_refresh).await;
6331        assert_eq!(refreshed_json["token_type"], "Bearer");
6332        let refreshed_claims = jwt_claims(refreshed_json["access_token"].as_str().unwrap());
6333        assert_eq!(refreshed_claims["sub"], "alice");
6334        assert_eq!(refreshed_claims["sid"], generic_claims["sid"]);
6335        assert!(refreshed_claims.get("cnf").is_none());
6336
6337        let wrong_issuer = crate::auth::jwt::encode_composite_ml_dsa_65_ed25519(
6338            &hyprstream_rpc::auth::Claims::new("alice".to_owned(), now, now + 300)
6339                .with_issuer("https://other-issuer.example.test".to_owned())
6340                .with_audience(Some(ISSUER.to_owned()))
6341                .with_scope(Some("read:*:*".to_owned())),
6342            &ml_signing,
6343            &ed_signing,
6344        );
6345        let rejected_issuer = post_form_bearer(
6346            &app,
6347            "/oauth/introspect",
6348            &[("token", &wrong_issuer)],
6349            &generic_access_token,
6350        )
6351        .await;
6352        assert_eq!(rejected_issuer.status(), axum::http::StatusCode::OK);
6353        assert_eq!(response_json(rejected_issuer).await["active"], false);
6354
6355        // A real generic device flow retains the local username byte-for-byte
6356        // and the legacy Bearer response shape.
6357        let device = post_form(
6358            &app,
6359            "/oauth/device",
6360            &[
6361                ("client_id", CLIENT_ID),
6362                ("scope", "read:*:*"),
6363                ("resource", ISSUER),
6364            ],
6365            None,
6366            false,
6367        )
6368        .await;
6369        assert_eq!(device.status(), axum::http::StatusCode::OK);
6370        let device_json = response_json(device).await;
6371        let device_code = device_json["device_code"].as_str().unwrap();
6372        let user_code = device_json["user_code"].as_str().unwrap();
6373        let nonce_uri = format!(
6374            "/oauth/device/nonce?{}",
6375            encode_form(&[("user_code", user_code)])
6376        );
6377        let device_nonce = response_json(get(&app, &nonce_uri).await).await;
6378        let normalized_code = user_code.replace('-', "");
6379        let device_challenge = format!(
6380            "alice:{normalized_code}:{}",
6381            device_nonce["nonce"].as_str().unwrap()
6382        );
6383        let device_signature =
6384            STANDARD.encode(user_key.sign(device_challenge.as_bytes()).to_bytes());
6385        let approved = post_form(
6386            &app,
6387            "/oauth/device/verify",
6388            &[
6389                ("user_code", user_code),
6390                ("username", "alice"),
6391                ("signature", &device_signature),
6392            ],
6393            None,
6394            true,
6395        )
6396        .await;
6397        assert_eq!(approved.status(), axum::http::StatusCode::OK);
6398        let device_token = post_form(
6399            &app,
6400            "/oauth/token",
6401            &[
6402                ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
6403                ("client_id", CLIENT_ID),
6404                ("device_code", device_code),
6405            ],
6406            None,
6407            false,
6408        )
6409        .await;
6410        assert_eq!(device_token.status(), axum::http::StatusCode::OK);
6411        let device_token_json = response_json(device_token).await;
6412        assert_eq!(device_token_json["token_type"], "Bearer");
6413        assert!(device_token_json.get("sub").is_none());
6414        let device_claims = jwt_claims(device_token_json["access_token"].as_str().unwrap());
6415        assert_eq!(device_claims["sub"], "alice");
6416        assert_eq!(device_claims["iss"], GENERIC_ISSUER);
6417        assert_eq!(device_claims["aud"], ISSUER);
6418        assert_eq!(device_claims["scope"], "read:*:*");
6419
6420        policy_handle.stop().await?;
6421        Ok(())
6422    }
6423
6424    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
6425    async fn oauth_iroh_refuses_arbitrary_rpc_and_anonymous_moq_before_dispatch(
6426    ) -> anyhow::Result<()> {
6427        use hyprstream_rpc::envelope::{RequestEnvelope, SignedEnvelope};
6428        use hyprstream_rpc::transport::iroh_substrate::{
6429            IrohSubstrate, NoopHandler, ALPN_HYPRSTREAM_RPC, ALPN_MOQ_LITE,
6430        };
6431        use hyprstream_rpc::ToCapnp as _;
6432        use iroh::{EndpointAddr, TransportAddr};
6433        use moq_net::Client;
6434
6435        let oauth_signer = hyprstream_rpc::prelude::SigningKey::generate(&mut rand::rngs::OsRng);
6436        let transport_key = hyprstream_rpc::node_identity::derive_purpose_key(
6437            &oauth_signer,
6438            "hyprstream-iroh-transport-v1",
6439        );
6440        let server = build_oauth_iroh_substrate(transport_key.to_bytes()).await?;
6441        assert_ne!(
6442            server.endpoint_id().as_bytes(),
6443            oauth_signer.verifying_key().as_bytes(),
6444            "transport address must be domain-separated from the OAuth identity key"
6445        );
6446        let addr = EndpointAddr::from_parts(
6447            server.endpoint_id(),
6448            server
6449                .endpoint()
6450                .bound_sockets()
6451                .into_iter()
6452                .map(TransportAddr::Ip),
6453        );
6454        let client_key = hyprstream_rpc::prelude::SigningKey::generate(&mut rand::rngs::OsRng);
6455        let client = IrohSubstrate::new(
6456            client_key.to_bytes(),
6457            NoopHandler::new("client moq"),
6458            NoopHandler::new("client rpc"),
6459        )
6460        .await?;
6461
6462        // A valid envelope signed by an arbitrary, unenrolled key never reaches
6463        // OAuthRpcHandler: the
6464        // ALPN closes before any request processor/user CRUD dispatch exists.
6465        let signed_crud = SignedEnvelope::new_signed(
6466            RequestEnvelope::anonymous(b"oauth-user-crud".to_vec()),
6467            &client_key,
6468        );
6469        let mut message = capnp::message::Builder::new_default();
6470        signed_crud.write_to(
6471            &mut message.init_root::<hyprstream_rpc::common_capnp::signed_envelope::Builder>(),
6472        );
6473        let mut signed_crud_bytes = Vec::new();
6474        capnp::serialize::write_message(&mut signed_crud_bytes, &message)?;
6475        let rpc = client.connect(addr.clone(), ALPN_HYPRSTREAM_RPC).await?;
6476        if let Ok((mut send, mut recv)) = rpc.open_bi().await {
6477            let _ = send.write_all(&signed_crud_bytes).await;
6478            let _ = send.finish();
6479            let response =
6480                tokio::time::timeout(std::time::Duration::from_secs(2), recv.read_to_end(1024))
6481                    .await;
6482            assert!(
6483                !matches!(response, Ok(Ok(ref bytes)) if !bytes.is_empty()),
6484                "refused OAuth RPC ALPN must not produce a user-CRUD response"
6485            );
6486        }
6487
6488        let moq = client.connect(addr, ALPN_MOQ_LITE).await?;
6489        let session = web_transport_iroh::Session::raw(moq);
6490        assert!(
6491            Client::new().connect(session).await.is_err(),
6492            "anonymous OAuth MoQ carrier must not obtain publish/subscribe access"
6493        );
6494
6495        client.shutdown().await?;
6496        server.shutdown().await?;
6497        Ok(())
6498    }
6499
6500    #[test]
6501    fn test_protected_resource_metadata() {
6502        let meta = protected_resource_metadata("http://localhost:6790", "http://localhost:6791");
6503        assert_eq!(meta.resource, "http://localhost:6790");
6504        assert_eq!(meta.authorization_servers[0], "http://localhost:6791");
6505        assert_eq!(
6506            meta.bearer_methods_supported.as_deref(),
6507            Some(&["header".to_owned()][..])
6508        );
6509    }
6510
6511    /// #1113: the PDS is its own AS, so the self protected-resource document
6512    /// must advertise the atproto transition scopes AND point
6513    /// `authorization_servers` at itself (resource == issuer).
6514    #[test]
6515    fn test_self_protected_resource_advertises_atproto_profile() {
6516        // PDS = its own AS: resource and authorization_servers[0] are the same.
6517        let issuer = "https://pds.example.com";
6518        let meta = protected_resource_metadata(issuer, issuer);
6519        assert_eq!(meta.resource, issuer);
6520        assert_eq!(meta.authorization_servers, vec![issuer.to_owned()]);
6521
6522        // atproto transition scopes are advertised.
6523        let scopes = self_resource_scopes();
6524        assert!(
6525            scopes.contains(&"atproto".to_owned()),
6526            "missing atproto: {scopes:?}"
6527        );
6528        assert!(
6529            scopes.contains(&"transition:generic".to_owned()),
6530            "missing transition:generic: {scopes:?}"
6531        );
6532    }
6533
6534    #[tokio::test]
6535    async fn required_iroh_carrier_watcher_detects_endpoint_close() -> anyhow::Result<()> {
6536        use hyprstream_rpc::transport::iroh_substrate::{IrohSubstrate, NoopHandler};
6537
6538        let signing_key = hyprstream_rpc::prelude::SigningKey::generate(&mut rand::rngs::OsRng);
6539        let server = IrohSubstrate::new(
6540            signing_key.to_bytes(),
6541            NoopHandler::new("oauth watcher moq"),
6542            NoopHandler::new("oauth watcher rpc"),
6543        )
6544        .await?;
6545        // Endpoint::close is the same observable carrier failure that the
6546        // watcher must convert into a terminal service outcome.
6547        server.endpoint().close().await;
6548        let lost = tokio::time::timeout(
6549            std::time::Duration::from_secs(2),
6550            wait_for_required_iroh_carrier(&server),
6551        )
6552        .await?;
6553        assert!(lost, "closed required carrier must be reported as lost");
6554        server.shutdown().await?;
6555        Ok(())
6556    }
6557
6558    #[test]
6559    fn test_validate_redirect_uri_exact_match() {
6560        let registered = vec!["http://127.0.0.1:3000/callback".to_owned()];
6561        assert!(validate_redirect_uri(
6562            "http://127.0.0.1:3000/callback",
6563            &registered
6564        ));
6565        // Loopback URIs: port is ignored per RFC 8252, so different port still matches
6566        assert!(validate_redirect_uri(
6567            "http://127.0.0.1:4000/callback",
6568            &registered
6569        ));
6570        // Different path should NOT match
6571        assert!(!validate_redirect_uri(
6572            "http://127.0.0.1:3000/other",
6573            &registered
6574        ));
6575    }
6576
6577    #[test]
6578    fn test_validate_redirect_uri_loopback_port_ignored() {
6579        let registered = vec!["http://127.0.0.1:3000/callback".to_owned()];
6580        // Different port on loopback should match per RFC 8252
6581        assert!(validate_redirect_uri(
6582            "http://127.0.0.1:9999/callback",
6583            &registered
6584        ));
6585        // Non-loopback should require exact match
6586        let non_loopback = vec!["https://example.com:3000/callback".to_owned()];
6587        assert!(!validate_redirect_uri(
6588            "https://example.com:4000/callback",
6589            &non_loopback
6590        ));
6591    }
6592
6593    #[test]
6594    fn test_pkce_s256() {
6595        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
6596        use base64::Engine;
6597        use sha2::{Digest, Sha256};
6598
6599        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
6600        let expected_challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
6601
6602        let computed = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));
6603        assert_eq!(computed, expected_challenge);
6604    }
6605}