Skip to main content

hyprstream_core/services/oauth/
state.rs

1//! OAuth 2.1 server state management.
2//!
3//! Manages registered clients, pending authorization codes, refresh tokens,
4//! and delegates token issuance to PolicyService via ZMQ.
5
6use anyhow::Context as _;
7use base64::Engine as _;
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10use std::sync::Arc;
11use std::time::{Duration, Instant};
12use tokio::sync::RwLock;
13
14use super::token_store::TokenStore;
15use super::user_service::UserService;
16use crate::auth::user_store::UserStore;
17use crate::config::OAuthConfig;
18use hyprstream_rpc_std::discovery_client::DiscoveryClient;
19use hyprstream_rpc_std::policy_client::PolicyClient;
20use hyprstream_util::{InsertIfAbsentNoEvictResult, TtlCache};
21
22use super::replay_key::ReplayKey;
23
24#[derive(Clone, Debug)]
25pub struct PublicGitCanaryRecord {
26    pub did: String,
27    pub rkey: String,
28}
29
30/// Result of attempting to admit a DPoP proof to its replay barrier.
31///
32/// The token endpoint needs this distinction so a saturated barrier remains
33/// separately metered and rate-limited instead of being logged as a replay.
34#[derive(Clone, Copy, Debug, Eq, PartialEq)]
35pub(crate) enum DpopJtiAdmission {
36    Inserted,
37    Duplicate,
38    Full,
39    InvalidLifetime,
40}
41
42impl DpopJtiAdmission {
43    pub(crate) fn is_inserted(self) -> bool {
44        self == Self::Inserted
45    }
46}
47
48/// Read-only resolver used by the ATProto service-auth exchange perimeter.
49#[async_trait::async_trait]
50pub trait AtprotoDidDocumentResolver: Send + Sync {
51    async fn resolve_document(&self, did: &str) -> anyhow::Result<serde_json::Value>;
52}
53
54struct HttpAtprotoDidDocumentResolver {
55    plc: hyprstream_rpc::did_plc::DidPlcResolver<hyprstream_rpc::did_plc::HttpPlcFetcher>,
56    web: hyprstream_rpc::did_web::HttpDidDocFetcher,
57}
58
59#[async_trait::async_trait]
60impl AtprotoDidDocumentResolver for HttpAtprotoDidDocumentResolver {
61    async fn resolve_document(&self, did: &str) -> anyhow::Result<serde_json::Value> {
62        if hyprstream_rpc::did_plc::is_did_plc(did) {
63            return self.plc.resolve_document(did).await;
64        }
65        if did.starts_with("did:web:") {
66            use hyprstream_rpc::did_web::DidDocFetcher as _;
67            let url = hyprstream_rpc::did_web::did_web_to_url(did)?;
68            let doc = self.web.fetch(&url).await?;
69            anyhow::ensure!(
70                doc.get("id").and_then(serde_json::Value::as_str) == Some(did),
71                "did:web document id does not match requested DID"
72            );
73            return Ok(doc);
74        }
75        anyhow::bail!("unsupported ATProto account DID method")
76    }
77}
78
79struct DenyAtprotoDidDocumentResolver(String);
80
81#[async_trait::async_trait]
82impl AtprotoDidDocumentResolver for DenyAtprotoDidDocumentResolver {
83    async fn resolve_document(&self, _did: &str) -> anyhow::Result<serde_json::Value> {
84        anyhow::bail!("ATProto DID resolver is unavailable: {}", self.0)
85    }
86}
87
88fn atproto_did_resolver(config: &OAuthConfig) -> Arc<dyn AtprotoDidDocumentResolver> {
89    let build = (|| -> anyhow::Result<HttpAtprotoDidDocumentResolver> {
90        let ttl = Duration::from_secs(config.atproto_did_cache_ttl_secs);
91        let base = url::Url::parse(&config.atproto_plc_directory_url)?;
92        let plc_config = hyprstream_rpc::did_plc::PlcResolverConfig::new(base, ttl)?;
93        Ok(HttpAtprotoDidDocumentResolver {
94            plc: hyprstream_rpc::did_plc::DidPlcResolver::new(plc_config)?,
95            web: hyprstream_rpc::did_web::HttpDidDocFetcher::new(ttl)?,
96        })
97    })();
98    match build {
99        Ok(resolver) => Arc::new(resolver),
100        Err(error) => {
101            tracing::error!(%error, "ATProto DID resolver configuration rejected");
102            Arc::new(DenyAtprotoDidDocumentResolver(error.to_string()))
103        }
104    }
105}
106
107/// Extract RSA public key components (n, e) from PKCS#8 DER and build a JWK.
108///
109/// Uses simple_asn1 (transitive dep of jsonwebtoken) for DER parsing.
110fn extract_rsa_jwk_from_der(pkcs8_der: &[u8], kid: &str) -> Option<serde_json::Value> {
111    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
112
113    // PKCS#8 wraps the RSA key. We need to extract n and e from the inner
114    // RSA public key. Rather than parsing ASN.1 manually, use jsonwebtoken
115    // to create an EncodingKey and then use openssl to extract components.
116    //
117    // Shell out to openssl for public key component extraction.
118    let temp = tempfile::NamedTempFile::new().ok()?;
119    std::fs::write(temp.path(), pkcs8_der).ok()?;
120
121    let output = std::process::Command::new("openssl")
122        .args([
123            "pkey",
124            "-inform",
125            "DER",
126            "-in",
127            temp.path().to_str()?,
128            "-noout",
129            "-text",
130        ])
131        .stdout(std::process::Stdio::piped())
132        .stderr(std::process::Stdio::null())
133        .output()
134        .ok()?;
135
136    // Parse modulus and exponent from openssl text output.
137    // This is fragile but avoids adding ASN.1 parsing dependencies.
138    let text = String::from_utf8_lossy(&output.stdout);
139    let mut n_hex = String::new();
140    let mut in_modulus = false;
141
142    for line in text.lines() {
143        let trimmed = line.trim();
144        if trimmed.starts_with("Modulus:") || trimmed == "modulus:" {
145            in_modulus = true;
146            continue;
147        }
148        if trimmed.starts_with("Exponent:") || trimmed.starts_with("publicExponent:") {
149            in_modulus = false;
150            // Extract exponent (usually 65537 = 0x10001)
151            // We'll use the standard value
152            continue;
153        }
154        if in_modulus {
155            // Lines like "    00:ab:cd:..."
156            let hex_part: String = trimmed.chars().filter(char::is_ascii_hexdigit).collect();
157            n_hex.push_str(&hex_part);
158        }
159    }
160
161    if n_hex.is_empty() {
162        return None;
163    }
164
165    // Strip leading zero byte if present (ASN.1 unsigned integer padding)
166    if n_hex.starts_with("00") && n_hex.len() > 2 {
167        n_hex = n_hex[2..].to_owned();
168    }
169
170    let n_bytes = hex::decode(&n_hex).ok()?;
171    let e_bytes = vec![0x01, 0x00, 0x01]; // 65537
172
173    let n_b64 = URL_SAFE_NO_PAD.encode(&n_bytes);
174    let e_b64 = URL_SAFE_NO_PAD.encode(&e_bytes);
175
176    Some(serde_json::json!({
177        "kty": "RSA",
178        "use": "sig",
179        "alg": "RS256",
180        "kid": kid,
181        "n": n_b64,
182        "e": e_b64,
183    }))
184}
185
186/// A dynamically registered OAuth client (RFC 7591) or Client ID Metadata Document client.
187///
188/// Field set tracks
189/// [draft-ietf-oauth-client-id-metadata-document-00] §4 (Client Metadata
190/// Document) and [RFC 7591] §2 (Client Metadata): only the fields hyprstream
191/// actually consumes are kept; unknown fields in the source document are
192/// dropped at parse time.
193#[derive(Debug, Clone)]
194pub struct RegisteredClient {
195    pub client_id: String,
196    pub redirect_uris: Vec<String>,
197    pub client_name: Option<String>,
198    /// Homepage / informational URI. Shown on the consent screen.
199    pub client_uri: Option<String>,
200    /// Logo URL. Shown on the consent screen.
201    pub logo_uri: Option<String>,
202    /// Grant types this client is permitted to use. Empty = AS default
203    /// (`authorization_code` + `refresh_token`).
204    pub grant_types: Vec<String>,
205    /// Response types this client is permitted to request. Empty = `code`.
206    pub response_types: Vec<String>,
207    /// Token endpoint client auth method. `"none"` = public client (PKCE
208    /// is mandatory). `"private_key_jwt"` requires a non-empty `jwks` /
209    /// `jwks_uri`.
210    pub token_endpoint_auth_method: Option<String>,
211    /// Inlined JWKS (CIMD §4 / RFC 7591 §2). Mutually exclusive with
212    /// `jwks_uri` per RFC 7591. Used for `private_key_jwt` client auth and
213    /// future request-object signing.
214    pub jwks: Option<serde_json::Value>,
215    /// JWKS endpoint URL — alternative to inline `jwks`.
216    pub jwks_uri: Option<String>,
217    /// Optional host `did:key` supplied by a PDS attachment client. Validated
218    /// during registration and retained for PDS identity association.
219    pub hyprstream_node_did: Option<String>,
220    /// Space-separated scope tokens the client declared at registration
221    /// (RFC 7591 / RFC 6749 §3.3). Requested scopes at PAR/authorize are
222    /// validated as a subset of this (#1113 rev2). `None` → treated as
223    /// "no client-side restriction" (the client declared no ceiling).
224    pub scope: Option<String>,
225    /// atproto OAuth: confidential clients set `dpop_bound_access_tokens:
226    /// true` in their metadata document. Parsed and retained here (#1146);
227    /// enforcement (rejecting confidential clients that omit it on the
228    /// atproto profile) is follow-up work.
229    pub dpop_bound_access_tokens: Option<bool>,
230    /// True if this client was registered via Client ID Metadata Document (HTTPS URL client_id)
231    pub is_cimd: bool,
232    pub registered_at: Instant,
233}
234
235impl RegisteredClient {
236    /// The client's declared scope tokens, parsed from [`Self::scope`].
237    /// Empty when the client declared no scopes (no client-side restriction).
238    pub fn declared_scopes(&self) -> Vec<String> {
239        self.scope
240            .as_deref()
241            .map(|s| s.split_whitespace().map(str::to_owned).collect())
242            .unwrap_or_default()
243    }
244}
245
246/// A Pushed Authorization Request (RFC 9126) awaiting consumption.
247///
248/// Holds the already-validated authorize parameters keyed by the `request_uri`
249/// returned to the client. Single-use, short TTL.
250#[derive(Debug, Clone)]
251pub struct PushedAuthRequest {
252    pub params: super::authorize::AuthorizeParams,
253    pub expires_at: Instant,
254}
255
256impl PushedAuthRequest {
257    pub fn is_expired(&self) -> bool {
258        Instant::now() > self.expires_at
259    }
260}
261
262/// Server-side state stashed between `authorize_get` and `authorize_post`,
263/// keyed by the consent nonce. Carries the complete resolved authorization
264/// request so hidden form fields never become mutable authority on POST.
265#[derive(Debug, Clone)]
266pub struct AuthorizeBinding {
267    pub request: super::authorize::AuthorizeParams,
268}
269
270#[cfg(all(test, feature = "postgres"))]
271#[path = "federate_model_tests.rs"]
272mod federate_model_tests;
273
274#[cfg(all(test, feature = "postgres"))]
275#[path = "federate_tui_tests.rs"]
276mod federate_tui_tests;
277
278#[cfg(test)]
279#[allow(clippy::unwrap_used)]
280mod tests {
281    use super::*;
282    use crate::auth::user_store::UserProfile;
283    use async_trait::async_trait;
284    use hyprstream_rpc::crypto::CryptoPolicy;
285    use rand::rngs::OsRng;
286
287    #[cfg(feature = "postgres")]
288    #[test]
289    fn federate_issuer_is_disabled_at_construction() {
290        assert!(state_for_replay_barrier_tests().federate_issuer.is_none());
291    }
292
293    #[cfg(feature = "postgres")]
294    pub(super) fn composite_signer_fixture(
295        version: u64,
296        pairs: Vec<hyprstream_rpc::auth::CompositeKeyPair>,
297    ) -> (
298        tempfile::TempDir,
299        std::sync::Arc<hyprstream_rpc::auth::CompositeKeySet>,
300    ) {
301        use hyprstream_rpc::auth::CompositeKeySet;
302
303        let dir = tempfile::tempdir().unwrap();
304        let digest = format!("federate-test-generation-{version}");
305        let ledger = dir.path().join("ledger.json");
306        let committed = dir.path().join("committed.json");
307        let prefix = dir.path().join("committed-ledger");
308        let key_set = std::sync::Arc::new(CompositeKeySet::default());
309        key_set.configure_authority(
310            ledger.clone(),
311            committed.clone(),
312            prefix.clone(),
313            dir.path().join("ledger.lock"),
314        );
315        key_set.publish(version, digest.clone(), pairs).unwrap();
316        let generation = prefix.with_file_name(format!(
317            "{}-{version}-{digest}.json",
318            prefix.file_name().unwrap().to_str().unwrap()
319        ));
320        let contents = serde_json::json!({"version": version, "component_digest": digest});
321        std::fs::write(&ledger, serde_json::to_vec(&contents).unwrap()).unwrap();
322        std::fs::write(&generation, serde_json::to_vec(&contents).unwrap()).unwrap();
323        std::fs::write(&committed, serde_json::to_vec(&contents).unwrap()).unwrap();
324        (dir, key_set)
325    }
326
327    #[cfg(feature = "postgres")]
328    pub(super) fn oauth_signing_pair(seed: u8) -> hyprstream_rpc::auth::CompositeKeyPair {
329        use std::sync::Arc;
330        let ed = Arc::new(ed25519_dalek::SigningKey::from_bytes(&[seed; 32]));
331        let (pq, _) = hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair();
332        let pq = Arc::new(pq);
333        let kid = hyprstream_rpc::auth::composite_kid(
334            &ml_dsa::Keypair::verifying_key(&*pq),
335            &ed.verifying_key(),
336        );
337        hyprstream_rpc::auth::CompositeKeyPair::signing(
338            kid,
339            pq,
340            ed,
341            hyprstream_rpc::auth::CompositePairRole::OAuth,
342            hyprstream_rpc::auth::CompositePairState::Active,
343            0,
344            i64::MAX,
345        )
346    }
347
348    #[cfg(feature = "postgres")]
349    #[tokio::test]
350    async fn federate_signer_uses_authorized_hybrid_oauth_pair() {
351        let pair = oauth_signing_pair(0x43);
352        let (dir, key_set) = composite_signer_fixture(1, vec![pair.clone()]);
353        let signer = super::HybridFederateSigner::new(key_set).unwrap();
354        let now = chrono::Utc::now().timestamp();
355        let claims = hyprstream_rpc::auth::claims::Claims::new(
356            "did:plc:abcdefghijklmnopqrstuvwx".to_owned(),
357            now,
358            now + 60,
359        )
360        .with_issuer("https://local".to_owned())
361        .with_jti();
362
363        let token = super::super::federate_host::FederateSigner::sign(&signer, &claims)
364            .await
365            .unwrap();
366        let dispatch = hyprstream_rpc::auth::parse_composite_dispatch(&token, &["at+jwt"]).unwrap();
367        assert_eq!(dispatch.kid(), pair.kid());
368        let verified = hyprstream_rpc::auth::jwt::decode_composite(
369            &token,
370            pair.ml_dsa(),
371            pair.ed25519(),
372            None,
373            &dispatch,
374        )
375        .unwrap();
376        assert_eq!(verified.sub, claims.sub);
377        drop(dir);
378    }
379
380    #[cfg(feature = "postgres")]
381    #[tokio::test]
382    async fn federate_signer_uses_new_committed_pair_after_rotation() {
383        use hyprstream_rpc::auth::{CompositePairRole, CompositePairState};
384        let first = oauth_signing_pair(0x44);
385        let second = oauth_signing_pair(0x45);
386        let old_kid = first.kid().to_owned();
387        let (dir, key_set) = composite_signer_fixture(1, vec![first.clone()]);
388        let signer = super::HybridFederateSigner::new(std::sync::Arc::clone(&key_set)).unwrap();
389        let now = chrono::Utc::now().timestamp();
390        let claims = hyprstream_rpc::auth::claims::Claims::new(
391            "did:plc:abcdefghijklmnopqrstuvwx".to_owned(),
392            now,
393            now + 60,
394        )
395        .with_issuer("https://local".to_owned())
396        .with_jti();
397        let before = super::super::federate_host::FederateSigner::sign(&signer, &claims)
398            .await
399            .unwrap();
400        let before_dispatch =
401            hyprstream_rpc::auth::parse_composite_dispatch(&before, &["at+jwt"]).unwrap();
402        assert_eq!(before_dispatch.kid(), old_kid);
403
404        let (first_pq, first_ed) = first.signing_keys().unwrap();
405        let draining = hyprstream_rpc::auth::CompositeKeyPair::signing(
406            first.kid().to_owned(),
407            first_pq,
408            first_ed,
409            CompositePairRole::OAuth,
410            CompositePairState::Drain,
411            0,
412            i64::MAX,
413        );
414        let (version, digest) = (2, "federate-test-generation-2");
415        key_set
416            .publish(version, digest.to_owned(), vec![draining, second.clone()])
417            .unwrap();
418        let prefix = dir.path().join("committed-ledger");
419        let generation = prefix.with_file_name(format!("committed-ledger-{version}-{digest}.json"));
420        let contents = serde_json::json!({"version": version, "component_digest": digest});
421        std::fs::write(
422            dir.path().join("ledger.json"),
423            serde_json::to_vec(&contents).unwrap(),
424        )
425        .unwrap();
426        std::fs::write(generation, serde_json::to_vec(&contents).unwrap()).unwrap();
427        std::fs::write(
428            dir.path().join("committed.json"),
429            serde_json::to_vec(&contents).unwrap(),
430        )
431        .unwrap();
432
433        let after = super::super::federate_host::FederateSigner::sign(&signer, &claims)
434            .await
435            .unwrap();
436        let after_dispatch =
437            hyprstream_rpc::auth::parse_composite_dispatch(&after, &["at+jwt"]).unwrap();
438        assert_eq!(after_dispatch.kid(), second.kid());
439        assert_ne!(after_dispatch.kid(), old_kid);
440        let verified = hyprstream_rpc::auth::jwt::decode_composite(
441            &after,
442            second.ml_dsa(),
443            second.ed25519(),
444            None,
445            &after_dispatch,
446        )
447        .unwrap();
448        assert_eq!(verified.sub, claims.sub);
449    }
450
451    #[cfg(feature = "postgres")]
452    #[tokio::test]
453    async fn federate_signer_fails_closed_without_oauth_signing_key() {
454        let empty = std::sync::Arc::new(hyprstream_rpc::auth::CompositeKeySet::default());
455        assert!(super::HybridFederateSigner::new(empty).is_err());
456    }
457
458    #[cfg(feature = "postgres")]
459    #[tokio::test]
460    async fn federate_routes_deny_without_policy_adapter() {
461        let state = Arc::new(state_for_replay_barrier_tests());
462        let challenge = super::super::federate_host::challenge(
463            axum::extract::State(Arc::clone(&state)),
464            axum::http::HeaderMap::new(),
465            axum::body::Bytes::from_static(b"{}"),
466        )
467        .await;
468        assert_eq!(
469            challenge.status(),
470            axum::http::StatusCode::SERVICE_UNAVAILABLE
471        );
472        let exchange = super::super::federate_host::exchange(
473            &state,
474            &axum::http::HeaderMap::new(),
475            b"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange",
476        )
477        .await;
478        assert_eq!(
479            exchange.status(),
480            axum::http::StatusCode::SERVICE_UNAVAILABLE
481        );
482    }
483
484    fn state_with_user_store(store: Arc<dyn UserStore>) -> OAuthState {
485        use hyprstream_rpc::rpc_client::RpcClientImpl;
486        use hyprstream_rpc::signer::LocalSigner;
487        use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
488
489        let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x41; 32]);
490        let remote_key = ed25519_dalek::SigningKey::from_bytes(&[0x42; 32]).verifying_key();
491        let make_client = || {
492            Arc::new(
493                RpcClientImpl::new(
494                    LocalSigner::new(signing_key.clone()),
495                    LazyUdsTransport::new("/dev/null/oauth-eligibility-test.sock".into()),
496                    Some(remote_key),
497                )
498                .with_response_verify_policy(CryptoPolicy::Classical),
499            )
500        };
501        let mut config = OAuthConfig::default();
502        config.external_url = Some("https://pds.example.test".to_owned());
503        OAuthState::new(
504            &config,
505            PolicyClient::new(make_client()),
506            DiscoveryClient::new(make_client()),
507            signing_key.verifying_key().to_bytes(),
508        )
509        .with_user_store(crate::auth::ProductionUserStore::for_test(store))
510    }
511
512    fn state_for_replay_barrier_tests() -> OAuthState {
513        use hyprstream_rpc::rpc_client::RpcClientImpl;
514        use hyprstream_rpc::signer::LocalSigner;
515        use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
516
517        let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x43; 32]);
518        let remote_key = ed25519_dalek::SigningKey::from_bytes(&[0x44; 32]).verifying_key();
519        let make_client = || {
520            Arc::new(
521                RpcClientImpl::new(
522                    LocalSigner::new(signing_key.clone()),
523                    LazyUdsTransport::new("/dev/null/replay-barrier-test.sock".into()),
524                    Some(remote_key),
525                )
526                .with_response_verify_policy(CryptoPolicy::Classical),
527            )
528        };
529        OAuthState::new(
530            &OAuthConfig::default(),
531            PolicyClient::new(make_client()),
532            DiscoveryClient::new(make_client()),
533            signing_key.verifying_key().to_bytes(),
534        )
535    }
536
537    #[test]
538    fn replay_callers_keep_seen_jtis_after_a_full_barrier() {
539        let mut state = state_for_replay_barrier_tests();
540        state.dpop_jti_seen = TtlCache::new(2, 16);
541        let now = chrono::Utc::now().timestamp();
542
543        assert_eq!(
544            state.check_and_record_dpop_jti_admission("dpop-first", now),
545            DpopJtiAdmission::Inserted
546        );
547        assert_eq!(
548            state.check_and_record_dpop_jti_admission("dpop-second", now),
549            DpopJtiAdmission::Inserted
550        );
551        assert_eq!(
552            state.check_and_record_dpop_jti_admission("dpop-fresh-when-full", now),
553            DpopJtiAdmission::Full,
554            "a fresh DPoP JTI must be refused once the barrier is full"
555        );
556        assert_eq!(
557            state.check_and_record_dpop_jti_admission("dpop-first", now),
558            DpopJtiAdmission::Duplicate,
559            "a full barrier must not evict an earlier DPoP JTI"
560        );
561
562        state.assertion_jti_seen = TtlCache::new(2, 16);
563        let exp = now + 60;
564        assert!(state.check_and_record_assertion_jti("client", "assertion-first", exp));
565        assert!(state.check_and_record_assertion_jti("client", "assertion-second", exp));
566        assert!(
567            !state.check_and_record_assertion_jti("client", "assertion-fresh-when-full", exp),
568            "a fresh client assertion JTI must be refused once the barrier is full"
569        );
570        assert!(
571            !state.check_and_record_assertion_jti("client", "assertion-first", exp),
572            "a full barrier must not evict an earlier client assertion JTI"
573        );
574    }
575
576    #[test]
577    fn replay_caps_cover_maximum_admitted_future_skew() {
578        assert_eq!(OAuthState::DPOP_JTI_MAX_ENTRIES, 216_000);
579        assert_eq!(OAuthState::ASSERTION_JTI_MAX_ENTRIES, 43_200);
580
581        let state = state_for_replay_barrier_tests();
582        let now = chrono::Utc::now().timestamp();
583        assert!(state.check_and_record_dpop_jti("dpop-future-skew", now + 60));
584        assert!(state.check_and_record_assertion_jti("client", "assertion-future-skew", now + 360));
585    }
586
587    #[test]
588    fn extreme_replay_expirations_are_rejected_without_consuming_capacity() {
589        let mut state = state_for_replay_barrier_tests();
590        state.assertion_jti_seen = TtlCache::new(1, 16);
591        assert!(!state.check_and_record_assertion_jti("client", "min", i64::MIN));
592        assert!(!state.check_and_record_assertion_jti("client", "max", i64::MAX));
593        assert!(state.check_and_record_assertion_jti(
594            "client",
595            "ordinary",
596            chrono::Utc::now().timestamp() + 60
597        ));
598
599        state.atproto_service_jti_seen = TtlCache::new(1, 16);
600        assert!(!state.check_and_record_atproto_service_jti("did:plc:test", "min", i64::MIN));
601        assert!(!state.check_and_record_atproto_service_jti("did:plc:test", "max", i64::MAX));
602        assert!(state.check_and_record_atproto_service_jti(
603            "did:plc:test",
604            "ordinary",
605            chrono::Utc::now().timestamp() + 60
606        ));
607    }
608
609    struct KeyReadErrorStore {
610        profile: UserProfile,
611        fail_key_read: bool,
612    }
613
614    #[async_trait]
615    impl UserStore for KeyReadErrorStore {
616        async fn get_profile(&self, _username: &str) -> anyhow::Result<Option<UserProfile>> {
617            Ok(Some(self.profile.clone()))
618        }
619
620        async fn register(&self, _username: &str) -> anyhow::Result<String> {
621            anyhow::bail!("not used")
622        }
623
624        async fn set_profile(
625            &self,
626            _username: &str,
627            _profile: crate::auth::UserProfilePatch,
628        ) -> anyhow::Result<()> {
629            anyhow::bail!("not used")
630        }
631
632        async fn remove(&self, _username: &str) -> anyhow::Result<bool> {
633            anyhow::bail!("not used")
634        }
635
636        async fn list_users(&self) -> anyhow::Result<Vec<String>> {
637            Ok(Vec::new())
638        }
639
640        async fn search(
641            &self,
642            _filter: &crate::auth::user_store::UserFilter,
643        ) -> anyhow::Result<Vec<(String, UserProfile)>> {
644            anyhow::bail!("not used")
645        }
646
647        async fn set_active(&self, _username: &str, _active: bool) -> anyhow::Result<()> {
648            anyhow::bail!("not used")
649        }
650
651        async fn list_pubkeys(
652            &self,
653            _username: &str,
654        ) -> anyhow::Result<Vec<crate::auth::user_store::PubkeyEntry>> {
655            if self.fail_key_read {
656                anyhow::bail!("synthetic key read failure")
657            }
658            Ok(vec![crate::auth::user_store::PubkeyEntry {
659                fingerprint: "key1".to_owned(),
660                pubkey: ed25519_dalek::VerifyingKey::from_bytes(&[1u8; 32])?,
661                label: None,
662                created_at: 0,
663                last_used_at: None,
664                algorithm: crate::auth::user_store::KeyAlgorithm::Ed25519,
665                pq_pubkey: None,
666            }])
667        }
668
669        async fn add_pubkey(
670            &self,
671            _username: &str,
672            _pubkey: ed25519_dalek::VerifyingKey,
673            _label: Option<String>,
674        ) -> anyhow::Result<String> {
675            anyhow::bail!("not used")
676        }
677
678        async fn add_pubkey_hybrid(
679            &self,
680            _username: &str,
681            _pubkey: ed25519_dalek::VerifyingKey,
682            _ml_dsa_vk: Vec<u8>,
683            _label: Option<String>,
684        ) -> anyhow::Result<String> {
685            anyhow::bail!("not used")
686        }
687
688        async fn remove_pubkey(&self, _username: &str, _fingerprint: &str) -> anyhow::Result<bool> {
689            anyhow::bail!("not used")
690        }
691
692        async fn get_pubkey_user(&self, _fingerprint: &str) -> anyhow::Result<Option<String>> {
693            anyhow::bail!("not used")
694        }
695
696        async fn touch_pubkey(&self, _username: &str, _fingerprint: &str) -> anyhow::Result<()> {
697            anyhow::bail!("not used")
698        }
699    }
700
701    #[test]
702    fn mesh_kem_derivation_failure_fails_closed_under_hybrid() {
703        let key = ed25519_dalek::SigningKey::generate(&mut OsRng);
704        let err = mesh_kem_public_for_policy(&key, CryptoPolicy::Hybrid, |_| {
705            Err(anyhow::anyhow!("synthetic derivation failure"))
706        })
707        .unwrap_err();
708
709        assert!(
710            err.to_string().contains("Hybrid policy"),
711            "unexpected error: {err:?}",
712        );
713    }
714
715    #[test]
716    fn mesh_kem_derivation_failure_is_empty_under_classical() {
717        let key = ed25519_dalek::SigningKey::generate(&mut OsRng);
718        let public = mesh_kem_public_for_policy(&key, CryptoPolicy::Classical, |_| {
719            Err(anyhow::anyhow!("synthetic derivation failure"))
720        })
721        .unwrap();
722
723        assert!(public.is_none());
724    }
725
726    /// #1113 rev2 / #1124: a local username has NO atproto identity →
727    /// rejected (fail closed). Synthesizing a path-form did:web is
728    /// spec-invalid and was removed; provisioning is tracked in #1124.
729    #[test]
730    fn subject_did_for_local_username_rejected() {
731        let err = subject_did_for("https://pds.example.com", "alice").unwrap_err();
732        assert_eq!(err, SubjectDidError::NoAtprotoIdentity);
733    }
734
735    /// #1113 rev2: a valid `did:plc` is accepted (real atproto account DID).
736    #[test]
737    fn subject_did_for_did_plc_accepted() {
738        assert_eq!(
739            subject_did_for("https://x", "did:plc:abcdefghijklmnqrstuvwx2p").unwrap(),
740            "did:plc:abcdefghijklmnqrstuvwx2p"
741        );
742    }
743
744    /// #1113 rev2: a host-form `did:web:host[:port]` (NO path) is accepted.
745    #[test]
746    fn subject_did_for_host_form_did_web_accepted() {
747        assert_eq!(
748            subject_did_for("https://x", "did:web:pds.example.com").unwrap(),
749            "did:web:pds.example.com"
750        );
751        assert_eq!(
752            subject_did_for("https://x", "did:web:127.0.0.1:6791").unwrap(),
753            "did:web:127.0.0.1:6791"
754        );
755    }
756
757    /// #1113 rev2: a path-form did:web (rejected by the atproto DID profile)
758    /// is rejected — the atproto DID profile forbids path components.
759    #[test]
760    fn subject_did_for_path_form_did_web_rejected() {
761        let err = subject_did_for("https://x", "did:web:pds.example.com:users:alice").unwrap_err();
762        assert_eq!(err, SubjectDidError::PathFormDidWeb);
763    }
764
765    /// #1113 correction: `did:at9p` and other non-plc/non-web DID methods
766    /// are NOT eligible for atproto OAuth tokens.
767    #[test]
768    fn subject_did_for_at9p_fails_closed() {
769        let err = subject_did_for("https://pds.example.com", "did:at9p:abc").unwrap_err();
770        assert_eq!(err, SubjectDidError::UnsupportedMethod);
771    }
772
773    /// #1113 rev2: a malformed did:plc (empty body) is rejected.
774    #[test]
775    fn subject_did_for_malformed_plc_rejected() {
776        let err = subject_did_for("https://x", "did:plc:").unwrap_err();
777        assert_eq!(err, SubjectDidError::MalformedDid);
778    }
779
780    /// #1113 r4: a SHORT did:plc (e.g. 9 chars) is rejected — @atproto/did
781    /// requires exactly 24 base32 chars. The old fixture `did:plc:abc123xyz`
782    /// passed validation but failed the real schema.
783    #[test]
784    fn subject_did_for_short_plc_rejected() {
785        let err = subject_did_for("https://x", "did:plc:abc123xyz").unwrap_err();
786        assert_eq!(err, SubjectDidError::MalformedDid);
787    }
788
789    /// #1113 r5: a classical account WITH a mapped did:plc succeeds —
790    /// the mapped DID is returned (the positive success path).
791    #[test]
792    fn atproto_eligibility_mapped_did_plc_succeeds() {
793        use crate::auth::user_store::{KeyAlgorithm, PubkeyEntry, UserProfile};
794        let pubkeys = vec![PubkeyEntry {
795            fingerprint: "key1".into(),
796            pubkey: ed25519_dalek::VerifyingKey::from_bytes(&[1u8; 32]).unwrap(),
797            label: None,
798            created_at: 0,
799            last_used_at: None,
800            algorithm: KeyAlgorithm::Ed25519,
801            pq_pubkey: None,
802        }];
803        let mut profile = UserProfile::default();
804        profile.atproto_did = Some("did:plc:abcdefghijklmnqrstuvwx2p".into());
805        let did = evaluate_atproto_eligibility(&pubkeys, Some(&profile), "https://x").unwrap();
806        assert_eq!(did, "did:plc:abcdefghijklmnqrstuvwx2p");
807    }
808
809    #[test]
810    fn atproto_eligibility_rejects_inactive_account() {
811        use crate::auth::user_store::{KeyAlgorithm, PubkeyEntry, UserProfile};
812        let pubkeys = vec![PubkeyEntry {
813            fingerprint: "key1".into(),
814            pubkey: ed25519_dalek::VerifyingKey::from_bytes(&[1u8; 32]).unwrap(),
815            label: None,
816            created_at: 0,
817            last_used_at: None,
818            algorithm: KeyAlgorithm::Ed25519,
819            pq_pubkey: None,
820        }];
821        let mut profile = UserProfile::default();
822        profile.active = Some(false);
823        profile.atproto_did = Some("did:plc:abcdefghijklmnqrstuvwx2p".into());
824        let err = evaluate_atproto_eligibility(&pubkeys, Some(&profile), "https://x").unwrap_err();
825        assert_eq!(err, SubjectDidError::InactiveAccount);
826    }
827
828    /// #1113 r5: a classical account WITHOUT a mapping fails closed.
829    #[test]
830    fn atproto_eligibility_no_mapping_fails_closed() {
831        use crate::auth::user_store::{KeyAlgorithm, PubkeyEntry, UserProfile};
832        let pubkeys = vec![PubkeyEntry {
833            fingerprint: "key1".into(),
834            pubkey: ed25519_dalek::VerifyingKey::from_bytes(&[1u8; 32]).unwrap(),
835            label: None,
836            created_at: 0,
837            last_used_at: None,
838            algorithm: KeyAlgorithm::Ed25519,
839            pq_pubkey: None,
840        }];
841        let profile = UserProfile::default();
842        let err = evaluate_atproto_eligibility(&pubkeys, Some(&profile), "https://x").unwrap_err();
843        assert_eq!(err, SubjectDidError::NoAtprotoIdentity);
844    }
845
846    /// #1113 r5: an at9p-backed account is rejected from the atproto profile
847    /// — inspected via the key mapping, not the subject string.
848    #[test]
849    fn atproto_eligibility_at9p_account_rejected() {
850        use crate::auth::user_store::{KeyAlgorithm, PubkeyEntry, UserProfile};
851        let pubkeys = vec![PubkeyEntry {
852            fingerprint: "pq-key".into(),
853            pubkey: ed25519_dalek::VerifyingKey::from_bytes(&[1u8; 32]).unwrap(),
854            label: None,
855            created_at: 0,
856            last_used_at: None,
857            algorithm: KeyAlgorithm::HybridEd25519MlDsa65,
858            pq_pubkey: Some(vec![0u8; 1952]), // ML-DSA-65 public key bytes
859        }];
860        let mut profile = UserProfile::default();
861        // Even with a mapped DID, the at9p key algorithm rejects first.
862        profile.atproto_did = Some("did:plc:abcdefghijklmnqrstuvwx2p".into());
863        let err = evaluate_atproto_eligibility(&pubkeys, Some(&profile), "https://x").unwrap_err();
864        assert_eq!(err, SubjectDidError::At9pBackedAccount);
865    }
866
867    /// #1113 r5: the default production backend must retain the mapped DID,
868    /// and the real account lookup (keys + profile) must reach the success
869    /// path after closing and reopening RocksDB.
870    #[cfg(feature = "rocksdb")]
871    #[tokio::test]
872    async fn atproto_eligibility_succeeds_after_rocksdb_roundtrip() {
873        use crate::auth::rocksdb_store::RocksDbUserStore;
874        use crate::auth::user_store::UserProfile;
875        use tempfile::TempDir;
876
877        let dir = TempDir::new().unwrap();
878        let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x33; 32]);
879        {
880            let store = RocksDbUserStore::open(dir.path()).unwrap();
881            store.register("alice").await.unwrap();
882            store
883                .add_pubkey(
884                    "alice",
885                    signing_key.verifying_key(),
886                    Some("login".to_owned()),
887                )
888                .await
889                .unwrap();
890            store
891                .set_profile(
892                    "alice",
893                    UserProfile {
894                        atproto_did: Some("did:plc:abcdefghijklmnqrstuvwx2p".to_owned()),
895                        ..Default::default()
896                    }
897                    .into(),
898                )
899                .await
900                .unwrap();
901        }
902
903        let reopened: Arc<dyn UserStore> = Arc::new(RocksDbUserStore::open(dir.path()).unwrap());
904        assert_eq!(
905            reopened
906                .get_profile("alice")
907                .await
908                .unwrap()
909                .unwrap()
910                .atproto_did
911                .as_deref(),
912            Some("did:plc:abcdefghijklmnqrstuvwx2p")
913        );
914        let state = state_with_user_store(reopened);
915        assert_eq!(
916            state
917                .check_atproto_account_eligibility("alice")
918                .await
919                .unwrap(),
920            "did:plc:abcdefghijklmnqrstuvwx2p"
921        );
922    }
923
924    /// #1113 r5: a profile read that would otherwise succeed cannot mask a
925    /// key-store failure. The account is rejected rather than downgraded to
926    /// an apparently keyless identity.
927    #[tokio::test]
928    async fn atproto_eligibility_key_read_error_fails_closed() {
929        let store = Arc::new(KeyReadErrorStore {
930            profile: UserProfile {
931                atproto_did: Some("did:plc:abcdefghijklmnqrstuvwx2p".to_owned()),
932                ..Default::default()
933            },
934            fail_key_read: true,
935        });
936        let state = state_with_user_store(store);
937        assert_eq!(
938            state
939                .check_atproto_account_eligibility("alice")
940                .await
941                .unwrap_err(),
942            SubjectDidError::NoAtprotoIdentity
943        );
944    }
945
946    /// #1113 rev2 finding 7: atproto profile activates only when `atproto` is
947    /// in the granted set — device/generic flows without it stay non-atproto.
948    #[test]
949    fn atproto_profile_detection() {
950        assert!(atproto_profile_active(&["atproto".to_owned()]));
951        assert!(atproto_profile_active(&[
952            "atproto".to_owned(),
953            "read:*:*".to_owned()
954        ]));
955        assert!(!atproto_profile_active(&["read:*:*".to_owned()]));
956        assert!(!atproto_profile_active(&[]));
957    }
958
959    #[tokio::test]
960    async fn authorize_binding_sweep_tracks_live_nonces() {
961        let store = Arc::new(KeyReadErrorStore {
962            profile: UserProfile::default(),
963            fail_key_read: true,
964        });
965        let state = state_with_user_store(store);
966        let binding = AuthorizeBinding {
967            request: crate::services::oauth::authorize::AuthorizeParams {
968                client_id: "client".to_owned(),
969                redirect_uri: "https://client.example/callback".to_owned(),
970                code_challenge: "challenge".to_owned(),
971                code_challenge_method: "S256".to_owned(),
972                response_type: "code".to_owned(),
973                state: None,
974                scope: Some("read:*:*".to_owned()),
975                resource: None,
976                nonce: None,
977                dpop_jkt: None,
978                client_assertion_jkt: None,
979            },
980        };
981        let now = Instant::now();
982        state
983            .pending_nonces
984            .write()
985            .await
986            .insert("live".to_owned(), now + Duration::from_secs(60));
987        state
988            .pending_nonces
989            .write()
990            .await
991            .insert("expired".to_owned(), now - Duration::from_secs(1));
992        let mut bindings = state.pending_authorize_bindings.write().await;
993        bindings.insert("live".to_owned(), binding.clone());
994        bindings.insert("expired".to_owned(), binding.clone());
995        bindings.insert("orphan".to_owned(), binding);
996        drop(bindings);
997
998        state.sweep_authorize_sessions(now).await;
999
1000        let bindings = state.pending_authorize_bindings.read().await;
1001        assert_eq!(bindings.len(), 1);
1002        assert!(bindings.contains_key("live"));
1003    }
1004
1005    #[tokio::test]
1006    async fn inactive_linked_hosted_account_is_rejected_during_token_binding_resolution() {
1007        let store = Arc::new(KeyReadErrorStore {
1008            profile: UserProfile {
1009                active: Some(false),
1010                atproto_did: Some("did:plc:abcdefghijklmnqrstuvwx2p".to_owned()),
1011                ..Default::default()
1012            },
1013            fail_key_read: false,
1014        });
1015        let state = state_with_user_store(store);
1016        assert_eq!(
1017            state
1018                .check_atproto_account_eligibility("alice")
1019                .await
1020                .unwrap_err(),
1021            SubjectDidError::InactiveAccount
1022        );
1023    }
1024
1025    /// #1113 rev2 finding 4: requested scopes are validated against the
1026    /// server-supported ∩ client-declared sets; garbage/undeclared tokens
1027    /// yield invalid_scope and the actual granted set is returned.
1028    #[test]
1029    fn validate_requested_scopes_rejects_garbage() {
1030        let server = [
1031            "atproto".to_owned(),
1032            "transition:generic".to_owned(),
1033            "read:*:*".to_owned(),
1034        ];
1035        let res = validate_requested_scopes(
1036            &["atproto".to_owned(), "bogus".to_owned()],
1037            &server,
1038            None,
1039            true,
1040        );
1041        assert_eq!(res.unwrap_err(), ScopeError::InvalidScope);
1042    }
1043
1044    /// #1113 rev2 finding 4: the granted set is the intersection of requested
1045    /// with server-supported, intersected with the client's declared scopes.
1046    #[test]
1047    fn validate_requested_scopes_intersects_client_declared() {
1048        let server = [
1049            "atproto".to_owned(),
1050            "transition:generic".to_owned(),
1051            "read:*:*".to_owned(),
1052        ];
1053        let declared = ["atproto".to_owned(), "read:*:*".to_owned()];
1054        let granted = validate_requested_scopes(
1055            &["atproto".to_owned(), "read:*:*".to_owned()],
1056            &server,
1057            Some(&declared),
1058            true,
1059        )
1060        .unwrap();
1061        assert_eq!(granted, vec!["atproto".to_owned(), "read:*:*".to_owned()]);
1062        // Client did NOT declare transition:generic → requesting it is invalid.
1063        let res = validate_requested_scopes(
1064            &["atproto".to_owned(), "transition:generic".to_owned()],
1065            &server,
1066            Some(&declared),
1067            true,
1068        );
1069        assert_eq!(res.unwrap_err(), ScopeError::InvalidScope);
1070    }
1071
1072    /// #1113 rev2 finding 4: when the atproto profile is requested, `atproto`
1073    /// MUST survive into the granted set, else AtprotoRequired.
1074    #[test]
1075    fn validate_requested_scopes_requires_atproto_when_profile_active() {
1076        let server = ["atproto".to_owned(), "read:*:*".to_owned()];
1077        let res = validate_requested_scopes(&["read:*:*".to_owned()], &server, None, true);
1078        assert_eq!(res.unwrap_err(), ScopeError::AtprotoRequired);
1079        // Non-atproto request (require_atproto=false) does not require it.
1080        let granted =
1081            validate_requested_scopes(&["read:*:*".to_owned()], &server, None, false).unwrap();
1082        assert_eq!(granted, vec!["read:*:*".to_owned()]);
1083    }
1084
1085    /// #1113 rev2 finding 5: the issuer is canonicalized to an exact origin
1086    /// (scheme://host[:port]) — trailing slash and path are stripped so
1087    /// endpoint URLs and the token `iss` are well-formed.
1088    #[test]
1089    fn canonical_issuer_origin_strips_path_and_slash() {
1090        assert_eq!(
1091            canonical_issuer_origin("https://pds.example.com/").as_deref(),
1092            Some("https://pds.example.com")
1093        );
1094        assert_eq!(
1095            canonical_issuer_origin("https://pds.example.com/oauth/par").as_deref(),
1096            Some("https://pds.example.com")
1097        );
1098        assert_eq!(
1099            canonical_issuer_origin("http://127.0.0.1:6791").as_deref(),
1100            Some("http://127.0.0.1:6791")
1101        );
1102        assert!(canonical_issuer_origin("pds.example.com").is_none());
1103    }
1104
1105    #[test]
1106    fn atproto_service_did_matches_browser_origin_encoding() {
1107        assert_eq!(
1108            atproto_service_did_for_origin("https://pds.example.test").as_deref(),
1109            Some("did:web:pds.example.test")
1110        );
1111        assert_eq!(
1112            atproto_service_did_for_origin("https://pds.example.test/oauth/par").as_deref(),
1113            Some("did:web:pds.example.test")
1114        );
1115        assert_eq!(
1116            atproto_service_did_for_origin("https://pds.example.test:443/oauth/par").as_deref(),
1117            Some("did:web:pds.example.test")
1118        );
1119        assert_eq!(
1120            atproto_service_did_for_origin("https://pds.example.test:8443/oauth/par").as_deref(),
1121            Some("did:web:pds.example.test%3A8443")
1122        );
1123        assert_eq!(
1124            atproto_service_did_for_origin("http://127.0.0.1:6791").as_deref(),
1125            Some("did:web:127.0.0.1%3A6791")
1126        );
1127        assert!(atproto_service_did_for_origin("https://[::1]:8443").is_none());
1128        assert!(atproto_service_did_for_origin("ftp://pds.example.test").is_none());
1129    }
1130
1131    /// #1113 rev2 F4/F6: the default grant set (omitted-scope fallback) must
1132    /// NOT include `atproto` — those scopes are supported-but-explicit. A
1133    /// client that omits `scope` must NOT silently activate the strict profile.
1134    #[test]
1135    fn default_scopes_do_not_include_atproto() {
1136        let cfg = crate::config::OAuthConfig::default();
1137        assert!(
1138            !cfg.default_scopes.iter().any(|s| s == "atproto"),
1139            "default_scopes must NOT include atproto (supported-but-explicit): {:?}",
1140            cfg.default_scopes
1141        );
1142        // But server_supported_scopes DOES include it.
1143        let supported = advertised_scopes_for_test(&cfg.default_scopes);
1144        assert!(supported.iter().any(|s| s == "atproto"));
1145        assert!(supported.iter().any(|s| s == "transition:generic"));
1146    }
1147
1148    /// Helper mirroring the advertised_scopes logic for test assertions.
1149    fn advertised_scopes_for_test(default_scopes: &[String]) -> Vec<String> {
1150        let mut scopes = default_scopes.to_vec();
1151        for s in &["atproto", "transition:generic"] {
1152            if !scopes.iter().any(|x| x == *s) {
1153                scopes.push((*s).to_owned());
1154            }
1155        }
1156        scopes
1157    }
1158}
1159
1160/// A pending authorization code awaiting token exchange.
1161#[derive(Debug, Clone)]
1162pub struct PendingAuthCode {
1163    pub code: String,
1164    pub client_id: String,
1165    pub redirect_uri: String,
1166    pub code_challenge: String,
1167    pub scopes: Vec<String>,
1168    /// RFC 8707 resource indicator (the audience for the token)
1169    pub resource: Option<String>,
1170    /// OIDC nonce — echoed into the id_token when scope includes "openid".
1171    pub oidc_nonce: Option<String>,
1172    pub created_at: Instant,
1173    pub expires_at: Instant,
1174    /// Authenticated username from Ed25519 challenge-response on the consent page.
1175    /// Used as the JWT `sub` claim for the issued token.
1176    pub username: String,
1177    /// Ed25519 verifying key verified during challenge-response.
1178    /// Included in the JWT `pub_key` claim to bind the user's key identity.
1179    pub verifying_key: Option<ed25519_dalek::VerifyingKey>,
1180    /// DPoP key thumbprint bound at PAR (#1113 rev2 finding 3). When the
1181    /// atproto profile is active, the token endpoint must receive a DPoP
1182    /// proof from the same key.
1183    pub dpop_jkt: Option<String>,
1184    /// RFC 7638 thumbprint of the client-assertion key verified at PAR
1185    /// (#1146 T3.3). When set, the token endpoint must receive a
1186    /// `client_assertion` signed by the same key, and the binding is
1187    /// carried into the issued refresh token.
1188    pub client_assertion_jkt: Option<String>,
1189}
1190
1191impl PendingAuthCode {
1192    pub fn is_expired(&self) -> bool {
1193        Instant::now() > self.expires_at
1194    }
1195}
1196
1197/// Pending external OIDC authentication flow.
1198///
1199/// Stores the original hyprstream authorize request so it can be resumed
1200/// after the user authenticates with the external provider.
1201#[derive(Debug, Clone)]
1202pub struct PendingExternalAuth {
1203    pub provider_slug: String,
1204    pub external_state: String,
1205    pub external_nonce: String,
1206    /// Provider kind, carried through for dispatch in the callback handler.
1207    pub provider_kind: crate::config::ProviderKind,
1208    /// Whether PKCE was sent to the external provider.
1209    pub pkce_supported: bool,
1210    pub pkce_verifier: String,
1211    pub client_secret: Option<String>,
1212    pub token_endpoint: String,
1213    /// Complete request validated at /oauth/authorize, including PAR bindings.
1214    pub original_request: Option<super::authorize::AuthorizeParams>,
1215    /// Present only when the user explicitly selected the Federate owner-link
1216    /// action from a valid local browser session. It pins both the session and
1217    /// target account until the callback revalidates them.
1218    pub federate_owner_link: Option<PendingFederateOwnerLink>,
1219    pub created_at: Instant,
1220    pub expires_at: Instant,
1221}
1222
1223#[derive(Debug, Clone)]
1224pub struct PendingFederateOwnerLink {
1225    pub session_id: String,
1226    pub owner_did: String,
1227    pub username: String,
1228    pub hosted_did: String,
1229    pub tenant: String,
1230    pub return_origin: String,
1231}
1232
1233/// Status of a pending device authorization code (RFC 8628).
1234#[derive(Debug, Clone, PartialEq, Eq)]
1235pub enum DeviceCodeStatus {
1236    /// User has not yet approved or denied.
1237    Pending,
1238    /// User approved the authorization request.
1239    Approved,
1240    /// User denied the authorization request.
1241    Denied,
1242}
1243
1244/// A pending device authorization code (RFC 8628).
1245#[derive(Debug, Clone)]
1246pub struct PendingDeviceCode {
1247    pub device_code: String,
1248    pub user_code: String,
1249    pub client_id: String,
1250    pub scopes: Vec<String>,
1251    /// RFC 8707 resource indicator (the audience for the token)
1252    pub resource: Option<String>,
1253    pub status: DeviceCodeStatus,
1254    pub created_at: Instant,
1255    pub expires_at: Instant,
1256    /// Minimum polling interval in seconds
1257    pub interval: u64,
1258    /// Last time the client polled for this code
1259    pub last_polled: Option<Instant>,
1260    /// Random nonce for challenge-response auth (43 chars base64url of 32 bytes)
1261    pub nonce: String,
1262    /// Username of the person who approved this code (set on POST /verify success)
1263    pub approved_by: Option<String>,
1264    /// Ed25519 verifying key verified during device challenge-response.
1265    /// Included in the JWT `pub_key` claim to bind the user's key identity.
1266    pub verifying_key: Option<ed25519_dalek::VerifyingKey>,
1267}
1268
1269impl PendingDeviceCode {
1270    pub fn is_expired(&self) -> bool {
1271        Instant::now() > self.expires_at
1272    }
1273}
1274
1275/// A stored refresh token entry (OAuth 2.1 rotation).
1276#[derive(Debug, Clone, Serialize, Deserialize)]
1277pub struct RefreshTokenEntry {
1278    pub client_id: String,
1279    /// JWT subject (username) of the token owner.
1280    pub username: String,
1281    pub scopes: Vec<String>,
1282    pub resource: Option<String>,
1283    /// Unix timestamp (seconds) at which this token expires.
1284    pub expires_at_unix: i64,
1285    /// Ed25519 verifying key bytes bound to this token (cnf key continuity on refresh).
1286    pub verifying_key_bytes: Option<[u8; 32]>,
1287    /// RFC 9449 JWK thumbprint. When set, refresh requires a DPoP proof from
1288    /// this exact key; it is carried forward during refresh-token rotation.
1289    #[serde(default)]
1290    pub dpop_jkt: Option<String>,
1291    /// RFC 7638 thumbprint of the client-assertion key this session was
1292    /// issued under (#1146 T3.3). When set, refresh requires a
1293    /// `client_assertion` verified by the same key — refresh cannot switch
1294    /// to another registered key, and removing the key from the client's
1295    /// JWKS revokes the session. Carried forward during rotation.
1296    #[serde(default)]
1297    pub client_assertion_jkt: Option<String>,
1298    /// Present only for UCAN-grant refresh tokens (`client_id` `ucan-grant:{sub}`).
1299    ///
1300    /// MAC #547 / B1 (#673): refresh of a UCAN grant is NOT a free re-mint — the
1301    /// refresh path must re-run the S6 gate chain (`evaluate_refresh`) against the
1302    /// grant, because the ceiling may have been amended or revoked since the
1303    /// access token was minted (ZSP: access is re-evaluated on refresh). That
1304    /// requires persisting the grant + the requested access so the refresh path
1305    /// can re-present them. `None` for every non-UCAN-grant refresh token, which
1306    /// keeps the generic OAuth 2.1 rotation path unchanged.
1307    #[serde(default)]
1308    pub ucan_grant: Option<UcanGrantRefresh>,
1309    /// OIDC session ID (`sid`) of the interactive session this refresh token
1310    /// belongs to. The same session spans every rotation (distinct credential
1311    /// IDs, one stable sid — v16 §3.3); the refresh path checks it against
1312    /// the session authority before consuming the single-use token, so a
1313    /// revoked session cannot refresh. `None` only on pre-session records.
1314    #[serde(default)]
1315    pub session_id: Option<String>,
1316}
1317
1318/// Re-evaluation context persisted alongside a UCAN-grant refresh token so the
1319/// refresh path can re-present the grant to `evaluate_refresh` (MAC #547 / B1
1320/// #673). Carrying the grant itself (not just an id) lets the gate chain
1321/// re-check the ceiling against current state on every refresh.
1322#[derive(Debug, Clone, Serialize, Deserialize)]
1323pub struct UcanGrantRefresh {
1324    /// `base64url(CBOR)` of the UCAN grant, re-presented to `evaluate_refresh`
1325    /// verbatim (the same encoding the client sent as `subject_token`).
1326    pub grant_cbor_b64: String,
1327    /// BLAKE3 content id (hex) of the CBOR grant. Binds this refresh entry to
1328    /// exactly the grant it was minted from and is checked on every refresh so
1329    /// a corrupted/substituted stored blob fails closed.
1330    pub grant_cid: String,
1331    /// The RFC 8693 requested `scope` (the S3 `action:resource:identifier`
1332    /// triple) used to rebuild the `GrantRequest` on refresh.
1333    pub requested_scope: Option<String>,
1334    /// The RFC 8707 `audience` resource indicator, if any.
1335    pub audience: Option<String>,
1336}
1337
1338impl RefreshTokenEntry {
1339    pub fn is_expired(&self) -> bool {
1340        chrono::Utc::now().timestamp() > self.expires_at_unix
1341    }
1342}
1343
1344/// Shared OAuth server state.
1345pub struct OAuthState {
1346    /// Public HTTPS projection signer. It authenticates the representation,
1347    /// not the accepted-current Registry/Model response keys inside it.
1348    pub(crate) browser_provisioning_signer: Option<Arc<hyprstream_rpc::crypto::SigningKey>>,
1349    pub(crate) browser_provisioning_rate_limiter: Arc<crate::server::middleware::RateLimiter>,
1350    /// Exact Federate host exchange remains disabled until an authenticated
1351    /// Policy admission adapter and composite signer are installed together.
1352    #[cfg(feature = "postgres")]
1353    pub(crate) federate_issuer: Option<Arc<super::federate_host::FederateIssuer>>,
1354    /// Dynamically-registered (RFC 7591) clients keyed by issued UUID
1355    /// client_id. CIMD clients live in `cimd_cache` instead — DCR
1356    /// entries have no TTL and outlive cache evictions, so storage is
1357    /// separated.
1358    pub clients: RwLock<HashMap<String, RegisteredClient>>,
1359    /// CIMD metadata cache. CIMD documents (HTTPS-URL client_ids) are
1360    /// fetched + verified once, then cached respecting HTTP cache
1361    /// headers, bounded TTL and capacity. See `cimd_cache` module.
1362    pub cimd_cache: Arc<super::cimd_cache::CimdCache>,
1363    /// JWKS-URI fetch cache for `private_key_jwt` client auth. Keyed by
1364    /// the absolute URL; value is `(parsed_jwks_json, fetched_at)`.
1365    /// Entries expire after `client_jwks_uri_cache_ttl_secs` and are
1366    /// evicted lazily on read. Capacity is implicitly bounded by the
1367    /// number of registered clients with jwks_uri (typically small).
1368    pub jwks_uri_cache: RwLock<HashMap<String, (serde_json::Value, Instant)>>,
1369    /// TTL for the `jwks_uri_cache`. Copied from
1370    /// [`OAuthConfig::client_jwks_uri_cache_ttl_secs`] at construction.
1371    pub client_jwks_uri_cache_ttl: Duration,
1372    /// Pending authorization codes (single-use, 60s TTL)
1373    pub pending_codes: RwLock<HashMap<String, PendingAuthCode>>,
1374    /// Pending authorize nonces (single-use, 5-min TTL).
1375    /// Proves a nonce was issued by this server and hasn't been replayed.
1376    pub pending_nonces: RwLock<HashMap<String, Instant>>,
1377    /// Complete resolved authorization requests, keyed and consumed alongside
1378    /// the consent nonce so browser-carried fields are never authority.
1379    pub pending_authorize_bindings: RwLock<HashMap<String, AuthorizeBinding>>,
1380    /// Pending Pushed Authorization Requests (RFC 9126), keyed by `request_uri`.
1381    /// Single-use, 60s TTL. In-memory is correct here — no value to persistence.
1382    pub pending_par_requests: RwLock<HashMap<String, super::state::PushedAuthRequest>>,
1383    /// Pending device authorization codes (RFC 8628), keyed by device_code
1384    pub pending_device_codes: RwLock<HashMap<String, PendingDeviceCode>>,
1385    /// Reverse lookup: user_code -> device_code
1386    pub device_code_by_user_code: RwLock<HashMap<String, String>>,
1387    /// Persistent refresh token store. Keyed by opaque token string.
1388    /// None when no credentials path is configured (tokens silently lost on restart).
1389    pub token_db: Option<Arc<dyn TokenStore>>,
1390    /// PolicyClient for JWT token issuance via ZMQ
1391    pub policy_client: PolicyClient,
1392    /// DiscoveryClient for resolving service QUIC endpoints via ZMQ
1393    pub discovery_client: DiscoveryClient,
1394    /// Issuer URL (e.g., "http://localhost:6791")
1395    pub issuer_url: String,
1396    /// Deployment-owned account-zone apex. User tokens may carry only a tenant
1397    /// derived from a hosted DID under this exact configured zone.
1398    pub hosted_account_zone: Option<crate::account::AccountZone>,
1399    /// Operator-selected canonical 9P read export. When set, hosted-account
1400    /// signup seeds the new account's HolderGate baseline rows
1401    /// (`model:{repo} query`, `registry:{repo-uuid} query`) in its tenant.
1402    pub ninep_canonical_read: Option<crate::config::NinepCanonicalReadConfig>,
1403    /// Default scopes for new clients
1404    pub default_scopes: Vec<String>,
1405    /// Access token TTL in seconds
1406    pub token_ttl: u32,
1407    /// Refresh token TTL in seconds
1408    pub refresh_token_ttl: u32,
1409    /// When true, `/oauth/authorize` rejects inline params and requires a `request_uri`
1410    /// from a prior `/oauth/par` call (RFC 9126). Advertised in server metadata.
1411    pub require_pushed_authorization_requests: bool,
1412    /// HTTP client for fetching Client ID Metadata Documents
1413    pub http_client: reqwest::Client,
1414    /// Raw Ed25519 verifying key bytes (32 bytes) for the JWKS endpoint.
1415    pub verifying_key_bytes: [u8; 32],
1416    /// User credential store for Ed25519 challenge-response device verification.
1417    /// Now backed by `user_service`. Legacy code uses `user_store_reader()`.
1418    /// Kept as Option for backward-compatible `is_none()` checks.
1419    pub user_service: Option<Arc<UserService>>,
1420    /// Authority-owned hosted-account records used to resolve an ATProto DID
1421    /// to its local tenant binding. `None` means every ATProto identity is
1422    /// federated-only for tenant exchange purposes.
1423    pub hosted_account_store: Option<Arc<hyprstream_pds_service::AccountRecordStore>>,
1424    /// Authenticated registration/intake wire adapter. `None` keeps every
1425    /// identity mutation endpoint fail-closed with 503 after authentication.
1426    pub identity_registration_api:
1427        Option<Arc<super::identity_registration::IdentityRegistrationApi>>,
1428    /// Ed25519 signing key for signing entity configurations (OpenID Federation 1.0).
1429    /// `None` when not configured.
1430    pub signing_key: Option<ed25519_dalek::SigningKey>,
1431    /// Named root-DID identity slots (drain/active/lead).
1432    ///
1433    /// This store is seeded from `signing_key` on first deployment, then rotated
1434    /// independently with bounded overlap. The root DID publisher snapshots all
1435    /// three roles; entity statements sign with the active role.
1436    pub root_identity_key_store: Option<Arc<crate::auth::SigningKeyStore>>,
1437    /// OpenID Federation 1.0 Trust Anchor URLs.
1438    /// Included as `authority_hints` in the entity configuration JWT.
1439    pub authority_hints: Vec<String>,
1440    /// Pending external OIDC authentication flows (keyed by external state).
1441    pub pending_external_auths: RwLock<HashMap<String, PendingExternalAuth>>,
1442    /// Provider configuration fixed at server construction for a consistent
1443    /// authorize page, upstream start, and callback verification.
1444    pub external_providers: HashMap<String, crate::config::OidcProviderConfig>,
1445    /// OIDC discovery cache for external providers.
1446    pub oidc_discovery: super::oidc_discovery::SharedDiscoveryCache,
1447    /// Server-side session store for browser login flow.
1448    pub sessions: super::session::SessionStore,
1449    /// In-memory `com.atproto.*` XRPC read slice repo store (#1112). Populated
1450    /// by the write path (#910) and tests; the read endpoints consult it
1451    /// directly. Default-empty so existing construction sites need no change.
1452    pub xrpc_repos: Arc<super::xrpc::XrpcRepoStore>,
1453    /// Optional native-authorized public repository writer. No public write
1454    /// routes are mounted while this is absent.
1455    pub public_repo_writer: Option<Arc<crate::services::public_repo::PublicRepoWriter>>,
1456    /// Production hosted-account writer. It resolves the requested DID and
1457    /// signs through AccountRecordStore without exposing private key bytes.
1458    pub hosted_public_repo_writer:
1459        Option<Arc<crate::services::public_repo::HostedAccountPublicRepoWriter>>,
1460    /// One explicitly enabled Registry/PDS record. Its DID and rkey are fixed
1461    /// at startup; public callers cannot select another Discovery target.
1462    pub public_git_canary_record: Option<PublicGitCanaryRecord>,
1463    /// Optional native account resolver for the protected standard
1464    /// `com.atproto.server.getSession` route.
1465    pub atproto_session_resolver: Option<Arc<dyn super::xrpc::AtprotoSessionResolver>>,
1466    /// When `true`, the XRPC read-slice routes (`/xrpc/…`) are mounted on the
1467    /// OAuth router (#1112). Copied from `OAuthConfig::xrpc_read_slice`.
1468    pub xrpc_read_slice: bool,
1469    /// Optional loopback-only sidecar port for the fixed public Git canary.
1470    /// `None` keeps the Git routes absent from the public router.
1471    pub public_git_canary_backend_port: Option<u16>,
1472    /// Deployment static well-known directory (#1137 serving half). When set,
1473    /// this OAuth instance terminates the deployment's did:web host: it serves
1474    /// `<dir>/did.json` in place of the dynamic node document, plus
1475    /// `<dir>/at9p/<cid>.cbor`,
1476    /// `<dir>/deployment/deployment-authority.log.json`, and
1477    /// `<dir>/deployment/registry-service.jwt`. All four are public,
1478    /// integrity-anchored bytes — see
1479    /// `deployment_well_known.rs`. Copied from
1480    /// `OAuthConfig::deployment_well_known_dir`.
1481    pub deployment_well_known_dir: Option<std::path::PathBuf>,
1482    /// RSA encoding key for RS256 id_token signing (optional, loaded from secrets).
1483    pub rsa_encoding_key: Option<jsonwebtoken::EncodingKey>,
1484    /// RSA public key as JWK JSON (for the JWKS endpoint).
1485    pub rsa_jwk: Option<serde_json::Value>,
1486    /// RSA key kid (for the JWT header).
1487    pub rsa_kid: Option<String>,
1488    /// Seen DPoP JTIs for replay prevention (RFC 9449 §11.1). Backed by
1489    /// the shared `TtlCache` with atomic check-and-record — see
1490    /// `check_and_record_dpop_jti`. A BLAKE3-256 digest retains a fixed-size
1491    /// key; TTL = iat + 120s per entry.
1492    pub dpop_jti_seen: TtlCache<ReplayKey, ()>,
1493    /// Seen client-assertion JTIs for replay prevention (RFC 7523 §3 /
1494    /// atproto OAuth; #1146 T3.3). Keyed by a BLAKE3-256 digest of
1495    /// `{client_id}\u{1f}{jti}`; TTL = the assertion's remaining `exp`
1496    /// lifetime. See
1497    /// `check_and_record_assertion_jti`.
1498    pub assertion_jti_seen: TtlCache<ReplayKey, ()>,
1499    /// One-use ATProto service-auth JTIs, keyed by a BLAKE3-256 digest of the
1500    /// issuer/JTI composite and retained until the source assertion expires.
1501    pub atproto_service_jti_seen: TtlCache<ReplayKey, ()>,
1502    /// Validated did:plc/did:web document source for service-auth keys.
1503    pub atproto_did_resolver: Arc<dyn AtprotoDidDocumentResolver>,
1504    /// Server-issued DPoP nonces. Value = expiry unix timestamp.
1505    pub dpop_nonces: RwLock<HashMap<String, i64>>,
1506    /// Per-client (keyed by DPoP `jkt` thumbprint) nonce-issuance state.
1507    /// Once a jkt appears here, RFC 9449 §8 enforcement kicks in: subsequent
1508    /// proofs from the same key MUST carry a server-issued nonce. Value =
1509    /// expiry unix timestamp (matches nonce TTL; entry pruned when expired
1510    /// to allow re-bootstrap after silence).
1511    pub dpop_clients_seen: RwLock<HashMap<String, i64>>,
1512    /// Trusted external OIDC issuers for the JWT bearer grant (RFC 7523).
1513    pub trusted_issuers: std::collections::HashMap<String, crate::config::TrustedIssuerConfig>,
1514    /// CA JWT signing key for browser WIT issuance (POST /oauth/wit).
1515    /// Derived from the root CA key via derive_purpose_key("hyprstream-jwt-v1").
1516    /// None when credentials are unavailable (WIT endpoint returns 503).
1517    pub ca_jwt_key: Option<Arc<ed25519_dalek::SigningKey>>,
1518    /// Anonymous device identity store.
1519    pub device_store: Option<Arc<dyn crate::auth::DeviceStore>>,
1520    /// Unix timestamp of when the JWT signing key became active (nbf for JWKS entry).
1521    pub jwt_key_nbf: i64,
1522    /// Unix timestamp of when the JWT signing key expires (exp for JWKS entry).
1523    /// Default: jwt_key_nbf + 14 days.
1524    pub jwt_key_exp: i64,
1525    /// Multi-slot JWT signing key store for rotation (drain/active/lead lifecycle).
1526    /// When present, JWKS serves all slots and issuance uses the active key.
1527    pub signing_key_store: Option<Arc<crate::auth::SigningKeyStore>>,
1528    /// Shared JWT ID blocklist for access token revocation (shared with PolicyService).
1529    /// ES256 (P-256) signing key rotation store for JWKS and DPoP/atproto interop.
1530    pub es256_key_store: Option<Arc<crate::auth::Es256SigningKeyStore>>,
1531    /// ML-DSA-65 signing key rotation store for PQ-hybrid JWT issuance.
1532    pub ml_dsa_key_store: Option<Arc<crate::auth::MlDsaSigningKeyStore>>,
1533    /// MAC #547 / B2 (#674): the tamper-evident audit sink the S6 grant path
1534    /// (`mac::exchange::audited_evaluate_grant`/`audited_evaluate_refresh`)
1535    /// records every decision through. `None` means the grant-path audit
1536    /// trail is not configured — the grant path treats that as fail-closed
1537    /// (deny, not "audit best-effort") rather than minting unaudited tokens.
1538    /// Production wiring is [`crate::mac::audit::WalAuditStore`] + an
1539    /// [`crate::mac::audit::cose::OwnedCoseAuditSigner`] (see the `oauth`
1540    /// service factory).
1541    pub audit_sink: Option<Arc<dyn crate::mac::audit::AuditSink>>,
1542    /// QUIC/WebTransport cert hashes (SHA-256 of leaf DER, `sha2-256` multihash encoding).
1543    /// Published in the DID-doc `#quic` service entry so peers can pin the cert (#185).
1544    /// A set so cert rotation can publish old + new simultaneously.
1545    pub quic_cert_hashes: Vec<[u8; 32]>,
1546    /// Public QUIC URI (`https://host:port`) for the DID-doc service entry (#185).
1547    /// None until the QUIC server is started and the cert hash is known.
1548    pub quic_public_uri: Option<String>,
1549    /// Raw ML-DSA-65 verifying-key bytes (1952 bytes) for the node's mesh
1550    /// post-quantum signing key (#157). Published as the `#mesh-pq` Multikey
1551    /// verification method in the root DID document. Derived from the same
1552    /// Ed25519 key as [`Self::signing_key`] (via `derive_mesh_mldsa_key`), so
1553    /// the published VM equals the key the node signs mesh responses with.
1554    /// `None` when the entity signing key is not configured.
1555    pub mesh_pq_verifying_key: Option<Vec<u8>>,
1556    /// The node's `#mesh-kem` hybrid keyAgreement public material (S1 / #552):
1557    /// one ML-KEM-768-hybrid recipient public (X25519 + ML-KEM-768 encapsulation
1558    /// keys, suite `HyKemX25519MlKem768`). Published as the `keyAgreement`
1559    /// verification methods in the root DID document. Derived from the same
1560    /// Ed25519 key as [`Self::signing_key`] (via `derive_mesh_kem_recipient`),
1561    /// so the published keys equal what the node decapsulates `#mesh-kem`
1562    /// envelopes with. `None` when the entity signing key is not configured,
1563    /// or when derivation failed under Classical policy (Hybrid fails closed
1564    /// during `with_signing_key`).
1565    pub mesh_kem_public: Option<hyprstream_rpc::crypto::hybrid_kem::RecipientPublic>,
1566    /// Self-certifying at9p capsule rendered from the same live signing key as
1567    /// the root did:web document, never from deployment-provisioned bytes.
1568    pub(crate) at9p_identity: Option<super::did_document::RenderedAt9pIdentity>,
1569    /// #282: the node's iroh endpoint id (its Ed25519 `node_id`, 32 bytes),
1570    /// published only as an `IrohTransport` service entry when bound. It is not
1571    /// a verification method or JWKS key (#1031).
1572    pub iroh_node_id: Option<[u8; 32]>,
1573    /// #282: iroh relay URLs to advertise in the `IrohTransport` entry's
1574    /// `relays`. Empty = rely on pkarr/DNS discovery for reachability (the
1575    /// peer resolves direct paths by node_id alone).
1576    pub iroh_relays: Vec<String>,
1577}
1578
1579fn mesh_kem_public_for_policy(
1580    key: &ed25519_dalek::SigningKey,
1581    policy: hyprstream_rpc::crypto::CryptoPolicy,
1582    derive: impl FnOnce(
1583        &ed25519_dalek::SigningKey,
1584    ) -> anyhow::Result<hyprstream_rpc::crypto::hybrid_kem::RecipientKeypair>,
1585) -> anyhow::Result<Option<hyprstream_rpc::crypto::hybrid_kem::RecipientPublic>> {
1586    match derive(key) {
1587        Ok(kem_kp) => Ok(Some(kem_kp.public())),
1588        Err(e) if policy.uses_pq() => Err(e)
1589            .context("failed to derive #mesh-kem hybrid keyAgreement identity under Hybrid policy"),
1590        Err(e) => {
1591            tracing::warn!(
1592                error = %e,
1593                "failed to derive #mesh-kem hybrid keyAgreement identity under Classical policy; \
1594                 root DID document will publish an empty keyAgreement relationship",
1595            );
1596            Ok(None)
1597        }
1598    }
1599}
1600
1601/// Federate session signer using the currently committed hybrid OAuth key pair.
1602#[cfg(feature = "postgres")]
1603struct HybridFederateSigner {
1604    key_set: std::sync::Arc<hyprstream_rpc::auth::CompositeKeySet>,
1605}
1606
1607#[cfg(feature = "postgres")]
1608impl HybridFederateSigner {
1609    fn new(key_set: std::sync::Arc<hyprstream_rpc::auth::CompositeKeySet>) -> anyhow::Result<Self> {
1610        let snapshot = key_set
1611            .mint_snapshot()
1612            .context("committed OAuth composite signing authority is unavailable")?;
1613        anyhow::ensure!(
1614            snapshot
1615                .active_signing_pair(hyprstream_rpc::auth::CompositePairRole::OAuth)
1616                .is_some(),
1617            "no authorized active OAuth composite signing pair"
1618        );
1619        Ok(Self { key_set })
1620    }
1621}
1622
1623#[async_trait::async_trait]
1624#[cfg(feature = "postgres")]
1625impl super::federate_host::FederateSigner for HybridFederateSigner {
1626    async fn sign(&self, claims: &hyprstream_rpc::auth::claims::Claims) -> anyhow::Result<String> {
1627        let snapshot = self
1628            .key_set
1629            .mint_snapshot()
1630            .context("committed OAuth composite signing authority is unavailable")?;
1631        let (pq, ed) = snapshot
1632            .active_signing_pair(hyprstream_rpc::auth::CompositePairRole::OAuth)
1633            .and_then(hyprstream_rpc::auth::CompositeKeyPair::signing_keys)
1634            .ok_or_else(|| anyhow::anyhow!("no authorized active OAuth composite signing pair"))?;
1635        Ok(crate::auth::jwt::encode_composite_ml_dsa_65_ed25519(
1636            claims, &pq, &ed,
1637        ))
1638    }
1639}
1640
1641impl OAuthState {
1642    /// Install the FederateIssuer for the Federate login path. The optional
1643    /// configured TUI client class (W1.3) joins the verifier's accepted
1644    /// classes; `None` keeps staging-only behavior (default-deny for the
1645    /// TUI class).
1646    #[cfg(feature = "postgres")]
1647    pub(crate) fn install_federate_issuer(
1648        &mut self,
1649        admission: std::sync::Arc<dyn super::federate_host::FederateAdmission>,
1650        signer: std::sync::Arc<dyn super::federate_host::FederateSigner>,
1651        tui_client: Option<super::federate_source::ClientClass>,
1652    ) -> anyhow::Result<()> {
1653        let host = super::federate_source::FederateHost::new(&self.issuer_url)?;
1654        let issuer =
1655            super::federate_host::FederateIssuer::new(admission, signer, host, tui_client)?;
1656        self.federate_issuer = Some(std::sync::Arc::new(issuer));
1657        Ok(())
1658    }
1659
1660    /// Use the currently committed OAuth composite pair for access tokens.
1661    #[cfg(feature = "postgres")]
1662    pub(crate) async fn federate_signer(
1663        &self,
1664    ) -> anyhow::Result<std::sync::Arc<dyn super::federate_host::FederateSigner>> {
1665        Ok(std::sync::Arc::new(HybridFederateSigner::new(
1666            hyprstream_rpc::auth::global_composite_key_set(),
1667        )?))
1668    }
1669    const MAX_CLIENT_ASSERTION_REPLAY_SECS: i64 = 360;
1670    const MAX_ATPROTO_SERVICE_ASSERTION_REPLAY_SECS: i64 = 3_600;
1671    /// DPoP admits iat up to 60 seconds in the future and retains through
1672    /// iat + 120 seconds: 180 seconds at 1,000 proofs/s plus 20% headroom.
1673    /// Fixed BLAKE3-256 digest keys plan 216,000 entries at about 26.4 MiB.
1674    const DPOP_JTI_MAX_ENTRIES: usize = 216_000;
1675    /// Inline reap budget per access (heap pops). Bounds tail latency.
1676    const DPOP_JTI_REAP_BUDGET: usize = 64;
1677    /// Client assertions admit iat up to 60 seconds future and live for at
1678    /// most 300 seconds from iat: 360 seconds at 100/s plus 20% headroom.
1679    /// Fixed digest keys plan 43,200 entries at about 5.3 MiB.
1680    const ASSERTION_JTI_MAX_ENTRIES: usize = 43_200;
1681    /// Inline reap budget per access (heap pops). Bounds tail latency.
1682    const ASSERTION_JTI_REAP_BUDGET: usize = 64;
1683
1684    pub fn new(
1685        config: &OAuthConfig,
1686        policy_client: PolicyClient,
1687        discovery_client: DiscoveryClient,
1688        verifying_key_bytes: [u8; 32],
1689    ) -> Self {
1690        Self {
1691            browser_provisioning_signer: None,
1692            browser_provisioning_rate_limiter: Arc::new(
1693                crate::server::middleware::RateLimiter::new(60, 60),
1694            ),
1695            #[cfg(feature = "postgres")]
1696            federate_issuer: None,
1697            clients: RwLock::new(HashMap::new()),
1698            pending_authorize_bindings: RwLock::new(HashMap::new()),
1699            cimd_cache: Arc::new(super::cimd_cache::CimdCache::new(
1700                super::cimd_cache::CimdCacheConfig::default(),
1701            )),
1702            jwks_uri_cache: RwLock::new(HashMap::new()),
1703            client_jwks_uri_cache_ttl: Duration::from_secs(config.client_jwks_uri_cache_ttl_secs),
1704            pending_codes: RwLock::new(HashMap::new()),
1705            pending_nonces: RwLock::new(HashMap::new()),
1706            pending_par_requests: RwLock::new(HashMap::new()),
1707            pending_device_codes: RwLock::new(HashMap::new()),
1708            device_code_by_user_code: RwLock::new(HashMap::new()),
1709            token_db: None,
1710            policy_client,
1711            discovery_client,
1712            issuer_url: config.issuer_url(),
1713            hosted_account_zone: None,
1714            ninep_canonical_read: None,
1715            default_scopes: config.default_scopes.clone(),
1716            token_ttl: config.token_ttl_seconds,
1717            refresh_token_ttl: config.refresh_token_ttl_seconds,
1718            require_pushed_authorization_requests: config.require_pushed_authorization_requests,
1719            http_client: reqwest::Client::builder()
1720                .timeout(Duration::from_secs(10))
1721                .build()
1722                .unwrap_or_default(),
1723            verifying_key_bytes,
1724            user_service: None,
1725            hosted_account_store: None,
1726            identity_registration_api: None,
1727            signing_key: None,
1728            root_identity_key_store: None,
1729            authority_hints: config.authority_hints.clone(),
1730            pending_external_auths: RwLock::new(HashMap::new()),
1731            external_providers: config.oidc_providers.clone(),
1732            oidc_discovery: std::sync::Arc::new(
1733                super::oidc_discovery::OidcDiscoveryCache::default(),
1734            ),
1735            sessions: super::session::SessionStore::default(),
1736            xrpc_repos: Arc::new(super::xrpc::XrpcRepoStore::new()),
1737            public_repo_writer: None,
1738            hosted_public_repo_writer: None,
1739            public_git_canary_record: None,
1740            atproto_session_resolver: None,
1741            xrpc_read_slice: config.xrpc_read_slice,
1742            public_git_canary_backend_port: config.public_git_canary_backend_port,
1743            deployment_well_known_dir: config.deployment_well_known_dir.clone(),
1744            rsa_encoding_key: None,
1745            rsa_jwk: None,
1746            rsa_kid: None,
1747            dpop_jti_seen: TtlCache::new(Self::DPOP_JTI_MAX_ENTRIES, Self::DPOP_JTI_REAP_BUDGET),
1748            assertion_jti_seen: TtlCache::new(
1749                Self::ASSERTION_JTI_MAX_ENTRIES,
1750                Self::ASSERTION_JTI_REAP_BUDGET,
1751            ),
1752            atproto_service_jti_seen: TtlCache::new(
1753                // ATProto service assertions can live for one hour. This is a
1754                // 64 MiB per-barrier memory budget, not an unsupported
1755                // traffic estimate. The fixed digest cache uses 120 bytes per
1756                // live entry on 64-bit targets (64-byte map allocation at its
1757                // 7/8 load factor + 56-byte heap node), rounded to 128 bytes
1758                // for planning. At this cap its geometric map and heap arrays
1759                // each top out at 524,288 slots: roughly 56.5 MiB including
1760                // HashMap control bytes, below the 64 MiB budget. Full barriers
1761                // fail closed and are metered.
1762                432_000,
1763                Self::ASSERTION_JTI_REAP_BUDGET,
1764            ),
1765            atproto_did_resolver: atproto_did_resolver(config),
1766            dpop_nonces: RwLock::new(HashMap::new()),
1767            dpop_clients_seen: RwLock::new(HashMap::new()),
1768            trusted_issuers: config.trusted_issuers.clone(),
1769            ca_jwt_key: None,
1770            device_store: None,
1771            jwt_key_nbf: chrono::Utc::now().timestamp(),
1772            jwt_key_exp: chrono::Utc::now().timestamp() + 14 * 86400,
1773            signing_key_store: None,
1774            es256_key_store: None,
1775            ml_dsa_key_store: None,
1776            audit_sink: None,
1777            quic_cert_hashes: Vec::new(),
1778            quic_public_uri: None,
1779            mesh_pq_verifying_key: None,
1780            mesh_kem_public: None,
1781            at9p_identity: None,
1782            iroh_node_id: None,
1783            iroh_relays: Vec::new(),
1784        }
1785    }
1786
1787    pub(crate) fn with_browser_provisioning_signer(
1788        mut self,
1789        signing_key: hyprstream_rpc::crypto::SigningKey,
1790    ) -> Self {
1791        self.browser_provisioning_signer = Some(Arc::new(signing_key));
1792        self
1793    }
1794
1795    /// Attach the anonymous device store.
1796    pub fn with_device_store(mut self, store: Arc<dyn crate::auth::DeviceStore>) -> Self {
1797        self.device_store = Some(store);
1798        self
1799    }
1800
1801    /// Override ATProto DID resolution with a validated fixture or private resolver.
1802    pub fn with_atproto_did_resolver(
1803        mut self,
1804        resolver: Arc<dyn AtprotoDidDocumentResolver>,
1805    ) -> Self {
1806        self.atproto_did_resolver = resolver;
1807        self
1808    }
1809
1810    /// Attach the authority-owned hosted-account record store.
1811    pub fn with_hosted_account_store(
1812        mut self,
1813        store: Arc<hyprstream_pds_service::AccountRecordStore>,
1814    ) -> Self {
1815        self.hosted_account_store = Some(store);
1816        self
1817    }
1818
1819    /// Install the explicit native-authorized public repository writer. This
1820    /// opt-in is required before standard XRPC repository writes are exposed.
1821    pub fn with_public_repo_writer(
1822        mut self,
1823        writer: Arc<crate::services::public_repo::PublicRepoWriter>,
1824    ) -> Self {
1825        self.public_repo_writer = Some(writer);
1826        self
1827    }
1828
1829    pub fn with_hosted_public_repo_writer(
1830        mut self,
1831        writer: Arc<crate::services::public_repo::HostedAccountPublicRepoWriter>,
1832    ) -> Self {
1833        self.hosted_public_repo_writer = Some(writer);
1834        self
1835    }
1836
1837    pub fn with_public_git_canary_record(mut self, record: PublicGitCanaryRecord) -> Self {
1838        self.public_git_canary_record = Some(record);
1839        self
1840    }
1841
1842    /// Install the explicit native account resolver used by standard
1843    /// `com.atproto.server.getSession`. The resolver owns handle, DID-document
1844    /// and lifecycle truth; no session route is mounted without it.
1845    pub fn with_atproto_session_resolver(
1846        mut self,
1847        resolver: Arc<dyn super::xrpc::AtprotoSessionResolver>,
1848    ) -> Self {
1849        self.atproto_session_resolver = Some(resolver);
1850        self
1851    }
1852
1853    /// Attach the authenticated hosted-account registration/intake adapter.
1854    pub fn with_identity_registration_api(
1855        mut self,
1856        api: Arc<super::identity_registration::IdentityRegistrationApi>,
1857    ) -> Self {
1858        self.identity_registration_api = Some(api);
1859        self
1860    }
1861
1862    /// Resolve a signed ATProto subject DID to its hosted local tenant.
1863    ///
1864    /// The request tenant is deliberately absent from this API. A missing
1865    /// store or record is a federated-only identity (`Ok(None)`); store
1866    /// corruption, authorization failure, and ambiguous bindings are errors.
1867    pub async fn hosted_account_tenant(&self, did: &str) -> Result<Option<String>, String> {
1868        if let Some(store) = &self.hosted_account_store {
1869            return store
1870                .resolve_tenant_for_hosted_did(
1871                    &hyprstream_rpc::Subject::new(
1872                        hyprstream_pds_service::OAUTH_ACCOUNT_RESOLVER_SUBJECT,
1873                    ),
1874                    did,
1875                )
1876                .await
1877                .map_err(|error| format!("hosted account tenant resolution failed: {error}"));
1878        }
1879        match &self.identity_registration_api {
1880            Some(api) => api
1881                .hosted_tenant(did)
1882                .map_err(|error| format!("hosted account tenant resolution failed: {error:#}")),
1883            None => Ok(None),
1884        }
1885    }
1886
1887    /// Refresh the authority-owned hosted-DID index after OAuth signup has
1888    /// durably published and activated an account. This is a no-op when the
1889    /// production hosted-account store is not configured, preserving the
1890    /// existing non-local-store path.
1891    pub async fn refresh_hosted_account_index_after_signup(&self) -> Result<(), String> {
1892        let Some(store) = &self.hosted_account_store else {
1893            return Ok(());
1894        };
1895        super::refresh_hosted_did_index_after_publish(
1896            Arc::clone(store),
1897            hyprstream_rpc::Subject::new(hyprstream_pds_service::OAUTH_ACCOUNT_RESOLVER_SUBJECT),
1898            std::time::Duration::from_secs(30),
1899        )
1900        .await
1901        .map_err(|error| format!("hosted account index refresh after signup failed: {error}"))
1902    }
1903
1904    /// Host service DID accepted in ATProto service-auth `aud`.
1905    pub fn atproto_service_did(&self) -> Option<String> {
1906        atproto_service_did_for_origin(&self.issuer_url)
1907    }
1908
1909    /// Set JWT signing key validity window for the JWKS endpoint.
1910    pub fn with_jwt_key_timestamps(mut self, nbf: i64, exp: i64) -> Self {
1911        self.jwt_key_nbf = nbf;
1912        self.jwt_key_exp = exp;
1913        self
1914    }
1915
1916    /// Attach the CA JWT signing key for browser WIT issuance (`POST /oauth/wit`).
1917    pub fn with_ca_jwt_key(mut self, key: ed25519_dalek::SigningKey) -> Self {
1918        self.ca_jwt_key = Some(Arc::new(key));
1919        self
1920    }
1921
1922    /// Attach the multi-slot signing key store (rotation).
1923    ///
1924    /// When set, JWKS serves all slots and WIT issuance uses the active key.
1925    pub fn with_signing_key_store(mut self, store: Arc<crate::auth::SigningKeyStore>) -> Self {
1926        self.signing_key_store = Some(store);
1927        self
1928    }
1929
1930    /// Attach the independently persisted root-DID identity rotation set.
1931    pub fn with_root_identity_key_store(
1932        mut self,
1933        store: Arc<crate::auth::SigningKeyStore>,
1934    ) -> Self {
1935        self.root_identity_key_store = Some(store);
1936        self
1937    }
1938
1939    /// Attach the ES256 (P-256) key rotation store.
1940    pub fn with_es256_key_store(mut self, store: Arc<crate::auth::Es256SigningKeyStore>) -> Self {
1941        self.es256_key_store = Some(store);
1942        self
1943    }
1944
1945    /// Attach the ML-DSA-65 key rotation store.
1946    pub fn with_ml_dsa_key_store(mut self, store: Arc<crate::auth::MlDsaSigningKeyStore>) -> Self {
1947        self.ml_dsa_key_store = Some(store);
1948        self
1949    }
1950
1951    /// Attach the S6 grant-path audit sink (B2, #674). Without this, the
1952    /// grant path fails closed on every request rather than minting tokens
1953    /// with no audit trail.
1954    pub fn with_audit_sink(mut self, sink: Arc<dyn crate::mac::audit::AuditSink>) -> Self {
1955        self.audit_sink = Some(sink);
1956        self
1957    }
1958
1959    /// Set the node's QUIC transport info for DID-doc publication (#185).
1960    ///
1961    /// `cert_hashes` is the set of SHA-256 cert DER hashes currently in use
1962    /// (old + new during rotation). `public_uri` is `https://host:port` that
1963    /// external peers dial.
1964    pub fn with_quic_transport(mut self, public_uri: String, cert_hashes: Vec<[u8; 32]>) -> Self {
1965        self.quic_public_uri = Some(public_uri);
1966        self.quic_cert_hashes = cert_hashes;
1967        self
1968    }
1969
1970    /// Set the node's iroh transport info for DID-doc publication (#282).
1971    ///
1972    /// Call this only when the iroh substrate is actually bound: it makes
1973    /// `root_did_document` advertise an `IrohTransport` service entry. The
1974    /// `node_id` is reachability metadata, never a DID verification method.
1975    /// `relays` may be empty — peers then resolve reachability by node_id alone
1976    /// via iroh's pkarr/DNS discovery.
1977    pub fn with_iroh_transport(mut self, node_id: [u8; 32], relays: Vec<String>) -> Self {
1978        self.iroh_node_id = Some(node_id);
1979        self.iroh_relays = relays;
1980        self
1981    }
1982
1983    /// Return the verifying key to use for JWT bearer token validation.
1984    ///
1985    /// Prefers the active slot from the signing key store; falls back to the
1986    /// legacy `verifying_key_bytes` field (policy-service-issued key).
1987    pub async fn jwt_bearer_verifying_key(&self) -> Option<ed25519_dalek::VerifyingKey> {
1988        if let Some(store) = &self.signing_key_store {
1989            if let Some(bytes) = store.active_verifying_key_bytes().await {
1990                return ed25519_dalek::VerifyingKey::from_bytes(&bytes).ok();
1991            }
1992        }
1993        ed25519_dalek::VerifyingKey::from_bytes(&self.verifying_key_bytes).ok()
1994    }
1995
1996    /// Return the active JWT signing key for token issuance (WIT/ADT).
1997    ///
1998    /// Prefers the active slot from the signing key store; falls back to `ca_jwt_key`.
1999    pub async fn active_jwt_signing_key(&self) -> Option<Arc<ed25519_dalek::SigningKey>> {
2000        if let Some(store) = &self.signing_key_store {
2001            if let Some(key) = store.active_key().await {
2002                return Some(key);
2003            }
2004        }
2005        self.ca_jwt_key.clone()
2006    }
2007
2008    /// Active root-DID signing key, falling back to the pre-rotation singleton.
2009    pub async fn active_root_identity_signing_key(&self) -> Option<Arc<ed25519_dalek::SigningKey>> {
2010        if let Some(store) = &self.root_identity_key_store {
2011            if let Some(key) = store.active_key().await {
2012                return Some(key);
2013            }
2014        }
2015        self.signing_key.clone().map(Arc::new)
2016    }
2017
2018    /// Attach an account store admitted by the sole production construction
2019    /// boundary.
2020    pub fn with_user_store(mut self, store: crate::auth::ProductionUserStore) -> Self {
2021        self.user_service = Some(Arc::new(UserService::new(store)));
2022        self
2023    }
2024
2025    /// Bind token issuance to the account zone this deployment actually hosts.
2026    pub fn with_hosted_account_zone(mut self, zone: crate::account::AccountZone) -> Self {
2027        self.hosted_account_zone = Some(zone);
2028        self
2029    }
2030
2031    /// Attach the operator-selected canonical 9P read export so hosted-account
2032    /// signup can seed the HolderGate baseline rows for new accounts.
2033    pub fn with_ninep_canonical_read(
2034        mut self,
2035        export: crate::config::NinepCanonicalReadConfig,
2036    ) -> Self {
2037        self.ninep_canonical_read = Some(export);
2038        self
2039    }
2040
2041    /// Attach a pre-built `UserService`. Used when the service is constructed externally
2042    /// (e.g., for testing or when the store is shared across services).
2043    #[cfg(test)]
2044    pub(crate) fn with_user_service(mut self, service: Arc<UserService>) -> Self {
2045        self.user_service = Some(service);
2046        self
2047    }
2048
2049    /// Get read access to the user store via the UserService.
2050    /// Returns None if no user store is configured.
2051    pub(crate) fn user_store_reader(&self) -> Option<Arc<dyn UserStore>> {
2052        self.user_service.as_ref().map(|s| s.store())
2053    }
2054
2055    /// Backward-compatible check: returns true if a user store is configured.
2056    pub fn has_user_store(&self) -> bool {
2057        self.user_service.is_some()
2058    }
2059
2060    /// Attach the signing key for OpenID Federation 1.0 entity configuration signing.
2061    ///
2062    /// Also derives and stores the node's mesh ML-DSA-65 verifying key (#157)
2063    /// from this same Ed25519 key, so the root DID document's `#mesh-pq`
2064    /// Multikey verification method matches the post-quantum key the mesh signs
2065    /// with (`derive_mesh_mldsa_key`), and the node's `#mesh-kem` hybrid
2066    /// keyAgreement public material (S1 / #552, `derive_mesh_kem_recipient`) so
2067    /// peers can anchor a recipient key that matches what this node decapsulates
2068    /// with. A `#mesh-kem` derivation failure is fail-closed under Hybrid
2069    /// policy: startup returns an error rather than publishing a root DID
2070    /// document with an empty `keyAgreement` relationship. Under Classical
2071    /// policy, the failure is logged and `mesh_kem_public` stays unset.
2072    pub fn with_signing_key(
2073        mut self,
2074        key: ed25519_dalek::SigningKey,
2075        policy: hyprstream_rpc::crypto::CryptoPolicy,
2076    ) -> anyhow::Result<Self> {
2077        let pq_sk = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&key);
2078        self.mesh_pq_verifying_key =
2079            Some(hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&pq_sk));
2080        match super::did_document::render_at9p_identity(&self.issuer_url, &key, &pq_sk) {
2081            Ok(identity) => self.at9p_identity = Some(identity),
2082            Err(error) => {
2083                tracing::warn!(
2084                    %error,
2085                    issuer = %self.issuer_url,
2086                    "skipping at9p identity publication"
2087                );
2088                self.at9p_identity = None;
2089            }
2090        }
2091        self.mesh_kem_public = mesh_kem_public_for_policy(&key, policy, |key| {
2092            hyprstream_rpc::node_identity::derive_mesh_kem_recipient(key)
2093        })?;
2094        self.signing_key = Some(key);
2095        Ok(self)
2096    }
2097
2098    /// Inject a pre-built token store implementation.
2099    pub fn with_token_store_impl(&mut self, store: Arc<dyn TokenStore>) {
2100        self.token_db = Some(store);
2101    }
2102
2103    /// Persist a refresh token entry to the store.
2104    pub async fn put_refresh_token(
2105        &self,
2106        token: &str,
2107        entry: &RefreshTokenEntry,
2108        ttl_secs: u64,
2109    ) -> anyhow::Result<()> {
2110        let Some(ref store) = self.token_db else {
2111            tracing::warn!("Refresh token store not configured — token will not survive restart");
2112            return Ok(());
2113        };
2114        store.put(token, entry, ttl_secs).await
2115    }
2116
2117    /// Look up a refresh token. Returns `None` if not found or expired (lazy expiry).
2118    pub async fn get_refresh_token(
2119        &self,
2120        token: &str,
2121    ) -> anyhow::Result<Option<RefreshTokenEntry>> {
2122        let Some(ref store) = self.token_db else {
2123            return Ok(None);
2124        };
2125        store.get(token).await
2126    }
2127
2128    /// Atomically claim a refresh token for one-time rotation. Only one caller
2129    /// across all OAuth replicas can receive a given entry.
2130    pub async fn take_refresh_token(
2131        &self,
2132        token: &str,
2133    ) -> anyhow::Result<Option<RefreshTokenEntry>> {
2134        let Some(ref store) = self.token_db else {
2135            return Ok(None);
2136        };
2137        store.take(token).await
2138    }
2139
2140    /// Remove a refresh token (revocation / rotation).
2141    pub async fn delete_refresh_token(&self, token: &str) -> anyhow::Result<()> {
2142        let Some(ref store) = self.token_db else {
2143            return Ok(());
2144        };
2145        store.delete(token).await
2146    }
2147
2148    /// Check a DPoP JTI for replay and record it if new.
2149    ///
2150    /// Returns `true` when the JTI is fresh (caller should proceed).
2151    /// Returns `false` when the JTI is a replay or the fail-closed barrier is full.
2152    /// Expired entries are pruned opportunistically on each call.
2153    pub fn check_and_record_dpop_jti(&self, jti: &str, iat: i64) -> bool {
2154        self.check_and_record_dpop_jti_admission(jti, iat)
2155            .is_inserted()
2156    }
2157
2158    /// Check a DPoP JTI while retaining the fail-closed admission outcome for
2159    /// callers that must distinguish an actual replay from a full barrier.
2160    pub(crate) fn check_and_record_dpop_jti_admission(
2161        &self,
2162        jti: &str,
2163        iat: i64,
2164    ) -> DpopJtiAdmission {
2165        let now = chrono::Utc::now().timestamp();
2166        // Window ends at iat + 120s (±60s skew + 60s buffer); TTL = remainder.
2167        let Some(ttl_secs) = iat
2168            .checked_add(120)
2169            .and_then(|deadline| deadline.checked_sub(now))
2170            .filter(|remaining| *remaining > 0 && *remaining <= 180)
2171            .and_then(|remaining| u64::try_from(remaining).ok())
2172        else {
2173            return DpopJtiAdmission::InvalidLifetime;
2174        };
2175        let result = self.dpop_jti_seen.insert_if_absent_no_evict(
2176            super::replay_key::dpop_jti(jti),
2177            (),
2178            Duration::from_secs(ttl_secs),
2179        );
2180        if result != InsertIfAbsentNoEvictResult::Inserted {
2181            super::replay_metrics::record_rejection(super::replay_metrics::DPOP, result);
2182            if super::replay_metrics::should_warn_full(super::replay_metrics::DPOP, result) {
2183                tracing::warn!("DPoP replay barrier is full; refusing fresh proof");
2184            }
2185        }
2186        match result {
2187            InsertIfAbsentNoEvictResult::Inserted => DpopJtiAdmission::Inserted,
2188            InsertIfAbsentNoEvictResult::Duplicate => DpopJtiAdmission::Duplicate,
2189            InsertIfAbsentNoEvictResult::Full => DpopJtiAdmission::Full,
2190        }
2191    }
2192
2193    /// Atomically consume an ATProto service-auth assertion identifier.
2194    pub fn check_and_record_atproto_service_jti(&self, issuer: &str, jti: &str, exp: i64) -> bool {
2195        let Some(ttl_secs) = exp
2196            .checked_sub(chrono::Utc::now().timestamp())
2197            .filter(|remaining| {
2198                *remaining > 0 && *remaining <= Self::MAX_ATPROTO_SERVICE_ASSERTION_REPLAY_SECS
2199            })
2200            .and_then(|remaining| u64::try_from(remaining).ok())
2201        else {
2202            return false;
2203        };
2204        let result = self.atproto_service_jti_seen.insert_if_absent_no_evict(
2205            super::replay_key::atproto_service_assertion_jti(issuer, jti),
2206            (),
2207            Duration::from_secs(ttl_secs),
2208        );
2209        if result != InsertIfAbsentNoEvictResult::Inserted {
2210            super::replay_metrics::record_rejection(
2211                super::replay_metrics::ATPROTO_SERVICE_ASSERTION,
2212                result,
2213            );
2214            if super::replay_metrics::should_warn_full(
2215                super::replay_metrics::ATPROTO_SERVICE_ASSERTION,
2216                result,
2217            ) {
2218                tracing::warn!(
2219                    "ATProto service-assertion replay barrier is full; refusing fresh assertion"
2220                );
2221            }
2222        }
2223        result == InsertIfAbsentNoEvictResult::Inserted
2224    }
2225
2226    /// Check a client-assertion JTI for replay and record it if new
2227    /// (#1146 T3.3; RFC 7523 §3 — an AS MUST NOT accept the same `jti`
2228    /// more than once).
2229    ///
2230    /// Keyed by `{client_id}\u{1f}{jti}` so distinct clients cannot
2231    /// collide on the same identifier. The entry lives until the
2232    /// assertion's own `exp`, after which a replayed assertion would be
2233    /// rejected as expired anyway.
2234    ///
2235    /// Returns `true` when the JTI is fresh (caller should proceed);
2236    /// `false` when it is a replay or the fail-closed barrier is full.
2237    pub fn check_and_record_assertion_jti(&self, client_id: &str, jti: &str, exp: i64) -> bool {
2238        let now = chrono::Utc::now().timestamp();
2239        let Some(ttl_secs) = exp
2240            .checked_sub(now)
2241            .filter(|remaining| {
2242                *remaining > 0 && *remaining <= Self::MAX_CLIENT_ASSERTION_REPLAY_SECS
2243            })
2244            .and_then(|remaining| u64::try_from(remaining).ok())
2245        else {
2246            return false;
2247        };
2248        let result = self.assertion_jti_seen.insert_if_absent_no_evict(
2249            super::replay_key::client_assertion_jti(client_id, jti),
2250            (),
2251            Duration::from_secs(ttl_secs),
2252        );
2253        if result != InsertIfAbsentNoEvictResult::Inserted {
2254            super::replay_metrics::record_rejection(
2255                super::replay_metrics::CLIENT_ASSERTION,
2256                result,
2257            );
2258            if super::replay_metrics::should_warn_full(
2259                super::replay_metrics::CLIENT_ASSERTION,
2260                result,
2261            ) {
2262                tracing::warn!("client-assertion replay barrier is full; refusing fresh assertion");
2263            }
2264        }
2265        result == InsertIfAbsentNoEvictResult::Inserted
2266    }
2267
2268    /// Issue a fresh server-side DPoP nonce (RFC 9449 §8).
2269    ///
2270    /// Returns the base64url nonce string that should be placed in the
2271    /// `DPoP-Nonce` response header. Stored with a 5-minute TTL.
2272    pub async fn issue_dpop_nonce(&self) -> String {
2273        use rand::RngCore;
2274        let mut bytes = [0u8; 16];
2275        rand::rngs::OsRng.fill_bytes(&mut bytes);
2276        let nonce = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes);
2277        let expiry = chrono::Utc::now().timestamp() + 300; // 5-minute TTL
2278        self.dpop_nonces.write().await.insert(nonce.clone(), expiry);
2279        nonce
2280    }
2281
2282    /// Validate a DPoP nonce issued by this server. Returns `true` if valid and unexpired.
2283    pub async fn verify_dpop_nonce(&self, nonce: &str) -> bool {
2284        let now = chrono::Utc::now().timestamp();
2285        let store = self.dpop_nonces.read().await;
2286        store.get(nonce).is_some_and(|&exp| exp > now)
2287    }
2288
2289    /// RFC 9449 §8 nonce-enforcement bookkeeping: has this client (`jkt`)
2290    /// previously been issued a nonce that has not yet expired? If so the
2291    /// next DPoP proof from this key MUST include a valid nonce.
2292    pub async fn dpop_client_requires_nonce(&self, jkt: &str) -> bool {
2293        let now = chrono::Utc::now().timestamp();
2294        let mut store = self.dpop_clients_seen.write().await;
2295        store.retain(|_, exp| *exp > now);
2296        store.contains_key(jkt)
2297    }
2298
2299    /// Record that this client (`jkt`) has been issued a server nonce.
2300    /// Future proofs from this key are required to carry one (sliding 5-min
2301    /// window per nonce TTL).
2302    pub async fn mark_dpop_client_nonced(&self, jkt: &str) {
2303        let expiry = chrono::Utc::now().timestamp() + 300;
2304        self.dpop_clients_seen
2305            .write()
2306            .await
2307            .insert(jkt.to_owned(), expiry);
2308    }
2309
2310    /// Validate the JWT `sub` claim for an atproto-conformant access token
2311    /// (#1113 rev2 / #1124 split).
2312    ///
2313    /// atproto OAuth requires the access token's `sub` to be a real,
2314    /// resolvable atproto account DID: `did:plc:<opaque>` or host-form
2315    /// `did:web:<host>[:port]` (NO path component — the atproto DID profile
2316    /// rejects `did:web:host:users:alice`). A hyprstream-local account
2317    /// (enrolled by Ed25519 username) has no atproto DID yet; provisioning
2318    /// is tracked in #1124. Such accounts are REJECTED from the atproto
2319    /// profile (fail closed), never minted a spec-invalid path-form alias.
2320    pub fn subject_did(&self, subject: &str) -> Result<String, SubjectDidError> {
2321        subject_did_for(&self.issuer_url, subject)
2322    }
2323
2324    /// Origin-only issuer required by the atproto OAuth profile.
2325    pub fn atproto_issuer_url(&self) -> String {
2326        canonical_issuer_origin(&self.issuer_url).unwrap_or_else(|| self.issuer_url.clone())
2327    }
2328
2329    /// Select the issuer used at a profile-sensitive mint/redirect boundary.
2330    pub fn issuer_for_scopes(&self, scopes: &[String]) -> String {
2331        if atproto_profile_active(scopes) {
2332            self.atproto_issuer_url()
2333        } else {
2334            self.issuer_url.clone()
2335        }
2336    }
2337
2338    /// Check whether an account is eligible for the atproto OAuth profile
2339    /// and return the account's mapped atproto DID (#1113 r5 / #1124 split).
2340    ///
2341    /// This inspects the ACCOUNT/KEY MAPPING, not the subject string:
2342    /// 1. Rejects at9p-backed accounts (any key with
2343    ///    [`KeyAlgorithm::HybridEd25519MlDsa65`] → [`SubjectDidError::At9pBackedAccount`]).
2344    /// 2. Looks up the account's MAPPED atproto DID from the profile's
2345    ///    `atproto_did` field. If present and valid → returns it (success).
2346    /// 3. An account without a mapped DID fails closed
2347    ///    ([`SubjectDidError::NoAtprotoIdentity`]).
2348    ///
2349    /// PROVISIONING mappings (creating did:plc, etc.) is #1124 — out of scope.
2350    /// The LOOKUP + success path exists here so the atproto OAuth profile can
2351    /// emit the mapped DID as `sub` when an account has one.
2352    pub async fn check_atproto_account_eligibility(
2353        &self,
2354        username: &str,
2355    ) -> Result<String, SubjectDidError> {
2356        let user_store = self
2357            .user_store_reader()
2358            .ok_or(SubjectDidError::NoAtprotoIdentity)?;
2359
2360        // Fail closed: a malformed/transient key-store read must never be
2361        // reinterpreted as "this account has no keys". Doing so can hide a
2362        // HybridEd25519MlDsa65 (at9p) binding and incorrectly admit a mapped
2363        // profile to the atproto OAuth profile.
2364        let pubkeys = user_store.list_pubkeys(username).await.map_err(|error| {
2365            tracing::warn!(%username, %error, "atproto eligibility key lookup failed closed");
2366            SubjectDidError::NoAtprotoIdentity
2367        })?;
2368        let profile = user_store.get_profile(username).await.ok().flatten();
2369
2370        evaluate_atproto_eligibility(&pubkeys, profile.as_ref(), &self.issuer_url)
2371    }
2372
2373    /// The full set of scopes this AS supports (#1113 rev2 F4).
2374    /// Extends `default_scopes` (the omitted-scope grant set) with the
2375    /// atproto transition scopes, which are supported-but-explicit: a client
2376    /// must request them to activate the strict profile; omitting `scope`
2377    /// grants only `default_scopes`.
2378    pub fn server_supported_scopes(&self) -> Vec<String> {
2379        let mut scopes = self.default_scopes.clone();
2380        for atproto_scope in &["atproto", "transition:generic"] {
2381            if !scopes.iter().any(|s| s == *atproto_scope) {
2382                scopes.push((*atproto_scope).to_owned());
2383            }
2384        }
2385        scopes
2386    }
2387
2388    /// Attach an RSA key for RS256 id_token signing (OIDC interop).
2389    ///
2390    /// `rsa_der` is the PKCS#8 DER-encoded RSA private key.
2391    pub fn with_rsa_key(mut self, rsa_der: &[u8]) -> Self {
2392        // Build encoding key
2393        self.rsa_encoding_key = Some(jsonwebtoken::EncodingKey::from_rsa_der(rsa_der));
2394
2395        // Extract public key components for JWKS using jsonwebtoken's DecodingKey
2396        if let Some(mut jwk) = extract_rsa_jwk_from_der(rsa_der, "") {
2397            let n = jwk.get("n").and_then(|v| v.as_str()).unwrap_or_default();
2398            let e = jwk.get("e").and_then(|v| v.as_str()).unwrap_or_default();
2399            let kid = super::jwks::compute_rsa_kid(n, e);
2400            if let Some(obj) = jwk.as_object_mut() {
2401                obj.insert("kid".to_owned(), serde_json::Value::String(kid.clone()));
2402            }
2403            self.rsa_kid = Some(kid);
2404            self.rsa_jwk = Some(jwk);
2405        }
2406
2407        self
2408    }
2409
2410    /// Spawn a background task that sweeps expired codes every 30 seconds.
2411    pub fn spawn_code_sweeper(self: &Arc<Self>) {
2412        let state = Arc::clone(self);
2413        tokio::spawn(async move {
2414            loop {
2415                tokio::time::sleep(Duration::from_secs(30)).await;
2416
2417                // Sweep expired auth codes
2418                {
2419                    let mut codes = state.pending_codes.write().await;
2420                    codes.retain(|_, code| !code.is_expired());
2421                }
2422
2423                // Sweep expired authorize nonces and their request snapshots.
2424                state.sweep_authorize_sessions(Instant::now()).await;
2425
2426                // Sweep expired PAR requests (60s TTL)
2427                {
2428                    let mut par = state.pending_par_requests.write().await;
2429                    par.retain(|_, req| !req.is_expired());
2430                }
2431
2432                // Sweep expired device codes
2433                {
2434                    let mut device_codes = state.pending_device_codes.write().await;
2435                    let mut user_code_map = state.device_code_by_user_code.write().await;
2436                    device_codes.retain(|_, dc| {
2437                        if dc.is_expired() {
2438                            user_code_map.remove(&dc.user_code);
2439                            false
2440                        } else {
2441                            true
2442                        }
2443                    });
2444                }
2445
2446                // Sweep expired DPoP JTIs and nonces
2447                {
2448                    let now = chrono::Utc::now().timestamp();
2449                    // dpop_jti_seen reaps expired entries on access; sweep the
2450                    // nonce + client-dedup maps only.
2451                    state.dpop_nonces.write().await.retain(|_, exp| *exp > now);
2452                    state
2453                        .dpop_clients_seen
2454                        .write()
2455                        .await
2456                        .retain(|_, exp| *exp > now);
2457                }
2458
2459                // Sweep expired external auth flows
2460                {
2461                    let now = Instant::now();
2462                    let mut auths = state.pending_external_auths.write().await;
2463                    auths.retain(|_, auth| auth.expires_at > now);
2464                }
2465
2466                // Sweep expired sessions
2467                state.sessions.sweep().await;
2468            }
2469        });
2470    }
2471
2472    async fn sweep_authorize_sessions(&self, now: Instant) {
2473        let mut nonces = self.pending_nonces.write().await;
2474        nonces.retain(|_, expiry| *expiry > now);
2475        let mut bindings = self.pending_authorize_bindings.write().await;
2476        bindings.retain(|nonce, _| nonces.contains_key(nonce));
2477    }
2478}
2479
2480/// Evaluate atproto account eligibility from the account's stored keys and
2481/// profile (#1113 r5 / #1124 split). Free-function form so it is unit-testable
2482/// without constructing an OAuthState or UserStore.
2483///
2484/// - at9p-backed account (any key with `HybridEd25519MlDsa65`) → reject.
2485/// - account with a mapped `atproto_did` on its profile → validate and return.
2486/// - account without a mapping → `NoAtprotoIdentity` (fail closed, #1124).
2487pub fn evaluate_atproto_eligibility(
2488    pubkeys: &[crate::auth::user_store::PubkeyEntry],
2489    profile: Option<&crate::auth::user_store::UserProfile>,
2490    issuer_url: &str,
2491) -> Result<String, SubjectDidError> {
2492    use crate::auth::user_store::KeyAlgorithm;
2493
2494    // 1. Reject at9p-backed accounts by inspecting the key algorithm.
2495    if pubkeys
2496        .iter()
2497        .any(|pk| pk.algorithm == KeyAlgorithm::HybridEd25519MlDsa65)
2498    {
2499        return Err(SubjectDidError::At9pBackedAccount);
2500    }
2501
2502    if profile.is_some_and(|profile| profile.active == Some(false)) {
2503        return Err(SubjectDidError::InactiveAccount);
2504    }
2505
2506    // 2. Look up the account's MAPPED atproto DID from the profile.
2507    if let Some(did) = profile.and_then(|p| p.atproto_did.as_deref()) {
2508        return subject_did_for(issuer_url, did);
2509    }
2510
2511    // 3. No mapped atproto DID — fail closed.
2512    Err(SubjectDidError::NoAtprotoIdentity)
2513}
2514
2515/// Validate that a subject is a real, resolvable atproto account DID (#1113
2516/// rev2 → #1124 split).
2517///
2518/// The atproto DID profile (`@atproto/did`) accepts only:
2519/// - `did:plc:<opaque>` — the registered PLC-directory form.
2520/// - `did:web:<host>[:port]` — the **host-form only** (NO path component);
2521///   `did:web:host:users:alice` is explicitly rejected by the atproto DID
2522///   profile.
2523///
2524/// Hyprstream-local accounts (enrolled by Ed25519 username) do NOT yet carry
2525/// a real atproto DID — provisioning one is tracked in #1124. Such accounts
2526/// are REJECTED from the atproto profile (fail closed with
2527/// [`SubjectDidError::NoAtprotoIdentity`]) rather than being minted a
2528/// spec-invalid path-form did:web. This function performs DID-form
2529/// validation, not a string-prefix match — an at9p-backed account whose
2530/// enrolled identifier is a plain username is rejected just like any other
2531/// non-DID subject.
2532pub fn subject_did_for(_issuer_url: &str, subject: &str) -> Result<String, SubjectDidError> {
2533    // did:plc — the only non-`did:web` atproto method. A valid did:plc
2534    // identifier has exactly 24 chars of base32-lowercase (a-z, 2-7), per
2535    // the atproto PLC spec. The vendored @atproto/did schema rejects shorter
2536    // suffixes like `did:plc:abc123xyz` (9 chars; @atproto/did rejects
2537    // anything shorter than 24 base32 chars).
2538    if let Some(rest) = subject.strip_prefix("did:plc:") {
2539        if rest.len() == 24 && rest.chars().all(|c| matches!(c, 'a'..='z' | '2'..='7')) {
2540            return Ok(subject.to_owned());
2541        }
2542        return Err(SubjectDidError::MalformedDid);
2543    }
2544    // did:web — host-form only. The atproto DID profile rejects path
2545    // components (`/`-segments encoded as extra colon groups are allowed by
2546    // the base did:web spec, but atproto's narrower profile does not). A
2547    // host-form did:web has exactly one path segment after the method:
2548    // `did:web:<host>[:port]`. Reject `did:web:<host>:users:...` (path form).
2549    if let Some(rest) = subject.strip_prefix("did:web:") {
2550        if rest.is_empty() {
2551            return Err(SubjectDidError::MalformedDid);
2552        }
2553        // atproto host-form: no `/`, no `:`-delimited path beyond host[:port].
2554        // A path-form did:web (e.g. `did:web:host:users:alice`) carries
2555        // additional colon segments; reject it.
2556        if rest.contains('/') {
2557            return Err(SubjectDidError::PathFormDidWeb);
2558        }
2559        let segment_count = rest.split(':').count();
2560        // host[:port] → 1 or 2 segments. ≥3 implies a path form.
2561        if segment_count > 2 {
2562            return Err(SubjectDidError::PathFormDidWeb);
2563        }
2564        return Ok(subject.to_owned());
2565    }
2566    // Any other did: method (did:at9p, did:key, ...) is NOT eligible.
2567    if subject.starts_with("did:") {
2568        return Err(SubjectDidError::UnsupportedMethod);
2569    }
2570    // A non-DID subject (local username) has no atproto identity — fail
2571    // closed. Provisioning real DIDs for hosted accounts is tracked in #1124.
2572    Err(SubjectDidError::NoAtprotoIdentity)
2573}
2574
2575/// Errors raised by [`subject_did_for`] / [`OAuthState::subject_did`].
2576#[derive(Debug, thiserror::Error, PartialEq, Eq)]
2577pub enum SubjectDidError {
2578    /// The subject carries a DID method that is not eligible for atproto
2579    /// OAuth tokens (e.g. `did:at9p`, `did:key`). The token path fails closed.
2580    #[error("DID method not eligible for atproto OAuth tokens")]
2581    UnsupportedMethod,
2582    /// A did:plc/did:web identifier is malformed (empty or illegal body).
2583    #[error("malformed atproto DID")]
2584    MalformedDid,
2585    /// A path-form did:web (e.g. `did:web:host:users:alice`) is rejected by
2586    /// the atproto DID profile — only host-form did:web is accepted.
2587    #[error("path-form did:web rejected by atproto DID profile")]
2588    PathFormDidWeb,
2589    /// A non-DID subject (local username) has no atproto identity. Real
2590    /// atproto DID provisioning for hosted accounts is tracked in #1124.
2591    #[error("account has no atproto identity; provisioning tracked in #1124")]
2592    NoAtprotoIdentity,
2593    /// The account is at9p-backed (enrolled with a hybrid PQ key) —
2594    /// inspected via the account/key mapping, not the subject string.
2595    /// at9p accounts are not eligible for atproto OAuth tokens.
2596    #[error("at9p-backed account not eligible for atproto OAuth")]
2597    At9pBackedAccount,
2598    /// The hosted account was deactivated after an external login or while a
2599    /// refresh credential was being resolved. Recheck at token issuance.
2600    #[error("hosted account is inactive")]
2601    InactiveAccount,
2602}
2603
2604/// The atproto transition scope name. Its presence in a granted scope set
2605/// activates the strict atproto OAuth profile (#1113 rev2): DPoP-mandatory,
2606/// DID subject, `token_type: DPoP` response, scope enforcement.
2607pub const ATPROTO_SCOPE: &str = "atproto";
2608
2609/// True when the granted scope set activates the atproto strict profile.
2610pub fn atproto_profile_active(scopes: &[String]) -> bool {
2611    scopes.iter().any(|s| s == ATPROTO_SCOPE)
2612}
2613
2614/// Normalize a single scope token. RFC 6749 §3.3 scope tokens are `1*(%x21 /
2615/// %x23-5B / %x5D-7E)` — no space, no `"`, no control chars. Returns `None`
2616/// for tokens that are empty or contain characters outside the allowed set.
2617pub fn normalize_scope_token(tok: &str) -> Option<&str> {
2618    if tok.is_empty() {
2619        return None;
2620    }
2621    if tok.bytes().all(|b| b >= 0x21 && b != b'"' && b != 0x7f) {
2622        Some(tok)
2623    } else {
2624        None
2625    }
2626}
2627
2628/// Validate a requested scope set against the server-supported and (optionally)
2629/// client-declared scopes (#1113 rev2 finding 4).
2630///
2631/// Returns the **actual granted set** (the intersection of requested with the
2632/// server-supported set, intersected with `client_declared` when provided),
2633/// preserving the server's canonical ordering of the supported scopes.
2634///
2635/// - Unknown / undeclared / malformed requested tokens yield
2636///   [`ScopeError::InvalidScope`] (RFC 6749 §4.1.2.1 / §3.3) so the caller
2637///   rejects with `invalid_scope`.
2638/// - When `require_atproto` is true (the atproto profile), the granted set
2639///   MUST contain [`ATPROTO_SCOPE`]; otherwise [`ScopeError::AtprotoRequired`].
2640pub fn validate_requested_scopes(
2641    requested: &[String],
2642    server_supported: &[String],
2643    client_declared: Option<&[String]>,
2644    require_atproto: bool,
2645) -> Result<Vec<String>, ScopeError> {
2646    // The set the client is permitted to ask for.
2647    let allowed: Vec<&str> = match client_declared {
2648        Some(declared) if !declared.is_empty() => server_supported
2649            .iter()
2650            .filter(|s| declared.iter().any(|d| d == *s))
2651            .map(String::as_str)
2652            .collect(),
2653        _ => server_supported.iter().map(String::as_str).collect(),
2654    };
2655
2656    let mut granted: Vec<String> = Vec::new();
2657    for tok in requested {
2658        let tok = normalize_scope_token(tok).ok_or(ScopeError::InvalidScope)?;
2659        if !allowed.contains(&tok) {
2660            return Err(ScopeError::InvalidScope);
2661        }
2662        if !granted.iter().any(|g| g == tok) {
2663            granted.push(tok.to_owned());
2664        }
2665    }
2666    if require_atproto && !granted.iter().any(|s| s == ATPROTO_SCOPE) {
2667        return Err(ScopeError::AtprotoRequired);
2668    }
2669    Ok(granted)
2670}
2671
2672/// Errors raised by [`validate_requested_scopes`].
2673#[derive(Debug, thiserror::Error, PartialEq, Eq)]
2674pub enum ScopeError {
2675    /// A requested scope token is unknown, undeclared by the client, or
2676    /// malformed → reject with OAuth `invalid_scope` (RFC 6749 §3.3).
2677    #[error("invalid or unsupported scope")]
2678    InvalidScope,
2679    /// The atproto profile is active but `atproto` is not in the granted set.
2680    #[error("atproto scope required for this profile")]
2681    AtprotoRequired,
2682}
2683
2684/// Canonicalize an issuer/external URL to an exact origin (scheme://host[:port])
2685/// with no trailing slash and no path (#1113 rev2 finding 5). Returns `None`
2686/// when the URL has no scheme or authority.
2687pub fn canonical_issuer_origin(issuer_url: &str) -> Option<String> {
2688    let (scheme, rest) = issuer_url.split_once("://")?;
2689    if scheme.is_empty() {
2690        return None;
2691    }
2692    let authority = rest.split('/').next()?;
2693    if authority.is_empty() {
2694        return None;
2695    }
2696    Some(format!("{scheme}://{authority}"))
2697}
2698
2699/// Convert the configured OAuth URL to the host-form `did:web` service DID
2700/// used by public identity documents, discovery verification, and ATProto
2701/// service-auth audiences. This conversion is stateless and does not resolve
2702/// or mint hosted account identities.
2703///
2704/// For supported DNS/IPv4 origins this mirrors the browser's
2705/// `originToDidWeb`: URL parsing normalizes an explicit default port away,
2706/// while a non-default port is retained and its domain-segment separator is
2707/// encoded as `%3A`. IPv6 is rejected until client and server share one
2708/// canonical DID representation for it.
2709pub(crate) fn atproto_service_did_for_origin(issuer_url: &str) -> Option<String> {
2710    let url = url::Url::parse(issuer_url).ok()?;
2711    if !matches!(url.scheme(), "http" | "https")
2712        || !url.username().is_empty()
2713        || url.password().is_some()
2714    {
2715        return None;
2716    }
2717    let host = match url.host()? {
2718        url::Host::Domain(domain) => domain.to_owned(),
2719        url::Host::Ipv4(address) => address.to_string(),
2720        url::Host::Ipv6(_) => return None,
2721    };
2722    Some(match url.port() {
2723        Some(port) => format!("did:web:{host}%3A{port}"),
2724        None => format!("did:web:{host}"),
2725    })
2726}