Skip to main content

hyprstream_core/services/oauth/
federate_host.rs

1//! Fixed Federate browser exchange. The OAuth runner installs the issuer only
2//! in PostgreSQL builds after constructing its authenticated Policy adapter and
3//! the currently committed composite signer; downstream Policy handlers still
4//! deny until their own session-store runtime is fully configured.
5#![allow(dead_code)] // The production adapter is a separate B1 activation packet.
6
7#[cfg(feature = "postgres")]
8use std::collections::BTreeMap;
9use std::sync::Arc;
10#[cfg(feature = "postgres")]
11use std::time::Duration;
12
13use axum::{
14    body::Bytes,
15    extract::State,
16    http::{header, HeaderMap, StatusCode},
17    response::{IntoResponse, Response},
18    Json,
19};
20#[cfg(feature = "postgres")]
21use base64::{engine::general_purpose::URL_SAFE_NO_PAD as B64, Engine as _};
22#[cfg(feature = "postgres")]
23use rand::RngCore as _;
24use serde::Serialize;
25#[cfg(feature = "postgres")]
26use tokio::sync::Mutex;
27
28#[cfg(feature = "postgres")]
29use super::{
30    federate_exchange::{AnyChallengeRequest, ExchangeRequest},
31    federate_source::{AuthorityBinding, Challenge, Source, VerifiedPossession, Verifier},
32};
33use super::{federate_source, state::OAuthState};
34
35#[cfg(feature = "postgres")]
36const MAX_PENDING: usize = 128;
37
38#[cfg(feature = "postgres")]
39use hyprstream_rpc::auth::Claims;
40#[cfg(feature = "postgres")]
41use hyprstream_session_store::Session;
42
43/// Policy owns source-to-account mapping and the durable source/session commit.
44/// Its production implementation must authenticate the OAuth service caller.
45#[cfg(feature = "postgres")]
46#[async_trait::async_trait]
47pub(crate) trait FederateAdmission: Send + Sync {
48    async fn prepare(
49        &self,
50        source: &Source,
51        requested: &str,
52        challenge_id: [u8; 32],
53        created_at: u64,
54    ) -> anyhow::Result<PreparedDecision>;
55    async fn commit(
56        &self,
57        evidence: VerifiedPossession,
58        policy_handle: Vec<u8>,
59    ) -> anyhow::Result<Session>;
60}
61
62/// Policy's decision stays opaque to OAuth. Only the enrolled Policy adapter
63/// can validate this handle at redeem; it is never sent to the browser.
64#[cfg(feature = "postgres")]
65pub(crate) struct PreparedDecision {
66    pub binding: AuthorityBinding,
67    pub policy_handle: Vec<u8>,
68}
69
70/// The signer uses the current OAuth access-token key, not a browser key.
71/// It is called only after Policy returns the committed session record.
72#[cfg(feature = "postgres")]
73#[async_trait::async_trait]
74pub(crate) trait FederateSigner: Send + Sync {
75    async fn sign(&self, claims: &Claims) -> anyhow::Result<String>;
76}
77
78#[cfg(feature = "postgres")]
79/// The pending challenge leg of either flow (W1b): the code-flow envelope or
80/// the device envelope, pinned with its challenge and Policy handle until
81/// the exchange leg repeats the exact flow profile.
82struct Pending {
83    request: AnyChallengeRequest,
84    challenge: Challenge,
85    policy_handle: Vec<u8>,
86}
87
88/// The OAuthState slot defaults to None until the production OAuth factory
89/// installs this with its Policy adapter and access-token signer. When absent,
90/// both routes fail before source, challenge or token state changes.
91#[cfg(feature = "postgres")]
92pub(crate) struct FederateIssuer {
93    verifier: Verifier,
94    admission: Arc<dyn FederateAdmission>,
95    signer: Arc<dyn FederateSigner>,
96    pending: Mutex<BTreeMap<[u8; 32], Pending>>,
97}
98
99#[cfg(feature = "postgres")]
100impl FederateIssuer {
101    pub(crate) fn new(
102        admission: Arc<dyn FederateAdmission>,
103        signer: Arc<dyn FederateSigner>,
104        host: federate_source::FederateHost,
105        tui_client: Option<federate_source::ClientClass>,
106    ) -> Result<Self, federate_source::Error> {
107        let mut verifier = Verifier::for_host(host)?;
108        if let Some(class) = tui_client {
109            verifier = verifier.with_client_class(class);
110        }
111        Ok(Self {
112            verifier,
113            admission,
114            signer,
115            pending: Mutex::new(BTreeMap::new()),
116        })
117    }
118
119    /// The configured TUI client id, for the `/oauth/token` federate form
120    /// reservation (W1.3). `None` = staging-only routing, previous behavior.
121    pub(crate) fn tui_client_id(&self) -> Option<&str> {
122        self.verifier.tui_client_id()
123    }
124
125    async fn challenge(
126        &self,
127        headers: &HeaderMap,
128        body: &[u8],
129        now: u64,
130    ) -> Result<ChallengeResponse, federate_source::Error> {
131        let request = AnyChallengeRequest::parse_for_host(
132            body,
133            self.verifier.host()?,
134            self.verifier.tui_client(),
135        )?;
136        if !origin_for_class(headers, request.client_id(), self.verifier.tui_client_id())? {
137            return Err(federate_source::Error::Invalid);
138        }
139        let source = request.verify_source(&self.verifier, now).await?;
140        let mut id = [0u8; 32];
141        rand::rngs::OsRng.fill_bytes(&mut id);
142        let prepared = tokio::time::timeout(
143            Duration::from_secs(2),
144            self.admission
145                .prepare(&source, request.requested_scope(), id, now),
146        )
147        .await
148        .map_err(|_| federate_source::Error::Unavailable)?;
149        let prepared = prepared.map_err(|_| federate_source::Error::Unavailable)?;
150        if prepared.policy_handle.is_empty() || prepared.policy_handle.len() > 4096 {
151            return Err(federate_source::Error::Unavailable);
152        }
153        if prepared.binding.requested != request.requested_scope() {
154            return Err(federate_source::Error::Unavailable);
155        }
156        let challenge = source.challenge(prepared.binding, id, now)?;
157        let response = ChallengeResponse {
158            challenge_id: B64.encode(challenge.challenge_id()),
159            // The class's own profile string: a TUI-class challenge must
160            // answer federate-tui-v1, not the www v1 pin. The W1b device
161            // variant answers its own device profile; the exchange leg must
162            // repeat exactly this string, pinning both legs to one flow.
163            profile: match &request {
164                AnyChallengeRequest::Code(_) => super::federate_exchange::resolve_wire_class(
165                    request.client_id(),
166                    self.verifier.tui_client(),
167                )?
168                .profile(),
169                AnyChallengeRequest::Device(_) => federate_source::TUI_DEVICE_PROFILE,
170            },
171            expires_in: challenge.expires_at() - now,
172            granted_scope: challenge.granted_scope().to_owned(),
173            transcript_b64u: B64.encode(challenge.transcript()),
174        };
175        let mut pending = self.pending.lock().await;
176        pending.retain(|_, entry| entry.challenge.expires_at() > now);
177        if pending.len() >= MAX_PENDING || pending.contains_key(&id) {
178            return Err(federate_source::Error::Unavailable);
179        }
180        pending.insert(
181            id,
182            Pending {
183                request,
184                challenge,
185                policy_handle: prepared.policy_handle,
186            },
187        );
188        Ok(response)
189    }
190
191    async fn exchange(
192        &self,
193        headers: &HeaderMap,
194        body: &[u8],
195        now: u64,
196    ) -> Result<super::federate_exchange::ExchangeResponse, federate_source::Error> {
197        let request = ExchangeRequest::parse_for_host(
198            body,
199            self.verifier.host()?,
200            self.verifier.tui_client(),
201        )?;
202        if !origin_for_class(headers, request.client_id(), self.verifier.tui_client_id())? {
203            return Err(federate_source::Error::Invalid);
204        }
205        let id = request.challenge_id()?;
206        // Remove before network calls: a duplicate or uncertain retry cannot
207        // race the same challenge to a second Policy commit.
208        let pending = self
209            .pending
210            .lock()
211            .await
212            .remove(&id)
213            .ok_or(federate_source::Error::Invalid)?;
214        // The exchange must stay in the class the challenge was prepared
215        // under: a submitted client_id/hs_profile pair naming the OTHER
216        // class is cross-class substitution — it would apply the wrong
217        // Origin context pin (already checked above for the submitted
218        // class) while the proof, Policy commit, and mint all bind the
219        // challenge's original class. The one-use handle is already
220        // consumed above, so a mismatch denies the attempt entirely.
221        if pending.request.client_id() != request.client_id()
222            || pending.request.requested_scope() != request.requested_scope()
223            || pending.request.subject_token() != request.subject_token()
224        {
225            return Err(federate_source::Error::Invalid);
226        }
227        // The exchange must stay in the exact flow the challenge was
228        // prepared under (W1b): a device-profile challenge is redeemed only
229        // by a device-profile exchange and a code-flow challenge only by
230        // the class profile, so neither leg can reinterpret the other's
231        // commitment binding or claim set.
232        if pending.request.profile() != request.hs_profile() {
233            return Err(federate_source::Error::Invalid);
234        }
235        let (expected, ed_key, pq_key) = pending.challenge.expected_session();
236        let source = pending.request.verify_source(&self.verifier, now).await?;
237        let (source_issuer, source_subject) = source.provenance();
238        let source_issuer = source_issuer.to_owned();
239        let source_subject = source_subject.to_owned();
240        let (ed, pq) = request.signatures()?;
241        let verified = pending.challenge.verify(source, &id, &ed, &pq, now)?;
242        let committed = tokio::time::timeout(
243            Duration::from_secs(2),
244            self.admission.commit(verified, pending.policy_handle),
245        )
246        .await
247        .map_err(|_| federate_source::Error::Unavailable)?;
248        let committed = committed.map_err(|_| federate_source::Error::Unavailable)?;
249        if committed.account_id != expected.account
250            || committed.subject != expected.subject
251            || committed.tenant != expected.tenant
252            || committed.scopes.join(" ") != expected.granted
253            || committed.grant_revision != expected.revision
254            || committed.ed_public != ed_key
255            || committed.pq_public != pq_key
256        {
257            return Err(federate_source::Error::Unavailable);
258        }
259        let now = i64::try_from(now).map_err(|_| federate_source::Error::Invalid)?;
260        // TUI-class credentials take NORMAL JWT verification at dispatch,
261        // where svc.rs (v16 §3.3) fails closed on an unknown `sid` for a
262        // local sid-carrying token. Publish the committed session to the
263        // session authority BEFORE minting, or every TUI credential would
264        // deny at dispatch. Fail-closed: no registry or failed registration,
265        // no token. The www class never takes the normal path (it dispatches
266        // through the deferred branch) and is deliberately not registered.
267        if Some(committed.client_id.as_str()) == self.verifier.tui_client_id() {
268            let registry = hyprstream_rpc::auth::global_session_registry()
269                .ok_or(federate_source::Error::Unavailable)?;
270            register_tui_session(registry.as_ref(), &committed, now).await?;
271        }
272        let claims = super::federate_exchange::authorized_committed_claims_for_host(
273            &committed,
274            now,
275            &source_issuer,
276            &source_subject,
277            crate::mac::exchange_enrollment_resolver().as_ref(),
278            self.verifier.host()?,
279            self.verifier.tui_client_id(),
280        )?;
281        let token = tokio::time::timeout(Duration::from_secs(2), self.signer.sign(&claims))
282            .await
283            .map_err(|_| federate_source::Error::Unavailable)?;
284        let token = token.map_err(|_| federate_source::Error::Unavailable)?;
285        let response_now = chrono::Utc::now().timestamp();
286        super::federate_exchange::ExchangeResponse::committed_for_host(
287            token,
288            &committed,
289            response_now,
290            &source_issuer,
291            &source_subject,
292            self.verifier.host()?,
293            self.verifier.tui_client_id(),
294        )
295    }
296}
297
298/// Publish a committed TUI-class session to the session authority (W1.3).
299/// Interactive kind, active, expiring with the session; fail-closed on any
300/// registration error (no session record, no minted credential).
301#[cfg(feature = "postgres")]
302async fn register_tui_session(
303    registry: &dyn hyprstream_rpc::auth::SessionRegistry,
304    committed: &Session,
305    now: i64,
306) -> Result<(), federate_source::Error> {
307    registry
308        .register_session(
309            hyprstream_rpc::auth::SessionKey::oidc(committed.host.clone(), committed.sid.clone()),
310            hyprstream_rpc::auth::SessionState {
311                subject: committed.subject.clone(),
312                tenant: committed.tenant.clone(),
313                kind: hyprstream_rpc::auth::SessionKind::Interactive,
314                created_at: now,
315                expires_at: committed.expires_at,
316                status: hyprstream_rpc::auth::ActiveOrRevoked::Active,
317                clearance_epoch: 0,
318            },
319        )
320        .await
321        .map_err(|_| federate_source::Error::Unavailable)
322}
323
324#[derive(Serialize)]
325struct ChallengeResponse {
326    challenge_id: String,
327    profile: &'static str,
328    expires_in: u64,
329    granted_scope: String,
330    transcript_b64u: String,
331}
332
333/// Class-aware origin rule (W1.3 native-client HTTP contract).
334///
335/// * www staging class (browser): exactly one `Origin` header, byte-equal
336///   to the pinned website origin — unchanged from the browser-only rule.
337/// * TUI class (native client): the www `Origin` header must be ABSENT.
338///   A native TUI client never sends a browser `Origin`; if any `Origin`
339///   is present the request is denied, so a web page cannot pose as the
340///   native TUI client (defense in depth under the mandatory holder
341///   possession proof — the origin check is a context pin, not the auth).
342/// * Any other client id: denied (no accepted class resolved).
343fn origin_for_class(
344    headers: &HeaderMap,
345    client_id: &str,
346    tui_client: Option<&str>,
347) -> Result<bool, federate_source::Error> {
348    let origin_count = headers.get_all(header::ORIGIN).iter().count();
349    if client_id == federate_source::CLIENT {
350        return Ok(origin_count == 1
351            && headers
352                .get(header::ORIGIN)
353                .and_then(|value| value.to_str().ok())
354                == Some(federate_source::WEBSITE));
355    }
356    if Some(client_id) == tui_client {
357        return Ok(origin_count == 0);
358    }
359    Err(federate_source::Error::Invalid)
360}
361
362fn content_type(headers: &HeaderMap, expected: &str) -> bool {
363    headers.get_all(header::CONTENT_TYPE).iter().count() == 1
364        && headers
365            .get(header::CONTENT_TYPE)
366            .and_then(|value| value.to_str().ok())
367            == Some(expected)
368}
369
370fn unavailable() -> Response {
371    (
372        StatusCode::SERVICE_UNAVAILABLE,
373        Json(serde_json::json!({"error":"temporarily_unavailable"})),
374    )
375        .into_response()
376}
377
378fn denied() -> Response {
379    (
380        StatusCode::BAD_REQUEST,
381        Json(serde_json::json!({"error":"invalid_grant"})),
382    )
383        .into_response()
384}
385
386pub(crate) async fn challenge(
387    State(state): State<Arc<OAuthState>>,
388    headers: HeaderMap,
389    body: Bytes,
390) -> Response {
391    #[cfg(feature = "postgres")]
392    if let Some(issuer) = &state.federate_issuer {
393        // Content type stays a route-level format pin for both classes; the
394        // class-aware origin rule is applied inside the issuer after the
395        // wire client_id resolves to an accepted class.
396        if !content_type(&headers, "application/json") {
397            return denied();
398        }
399        let now = chrono::Utc::now().timestamp();
400        let Ok(now) = u64::try_from(now) else {
401            return denied();
402        };
403        return match issuer.challenge(&headers, &body, now).await {
404            Ok(response) => (
405                [
406                    (header::CACHE_CONTROL, "no-store"),
407                    (header::PRAGMA, "no-cache"),
408                ],
409                Json(response),
410            )
411                .into_response(),
412            Err(federate_source::Error::Unavailable) => unavailable(),
413            Err(_) => denied(),
414        };
415    }
416    let _ = (state, headers, body);
417    unavailable()
418}
419
420pub(crate) async fn exchange(state: &OAuthState, headers: &HeaderMap, body: &[u8]) -> Response {
421    #[cfg(feature = "postgres")]
422    if let Some(issuer) = &state.federate_issuer {
423        // Content type stays a route-level format pin for both classes; the
424        // class-aware origin rule is applied inside the issuer after the
425        // wire client_id resolves to an accepted class.
426        if !content_type(headers, "application/x-www-form-urlencoded") {
427            return denied();
428        }
429        let now = chrono::Utc::now().timestamp();
430        let Ok(now) = u64::try_from(now) else {
431            return denied();
432        };
433        return match issuer.exchange(headers, body, now).await {
434            Ok(response) => (
435                [
436                    (header::CACHE_CONTROL, "no-store"),
437                    (header::PRAGMA, "no-cache"),
438                ],
439                Json(response),
440            )
441                .into_response(),
442            Err(federate_source::Error::Unavailable) => unavailable(),
443            Err(_) => denied(),
444        };
445    }
446    let _ = (state, headers, body);
447    unavailable()
448}
449
450#[cfg(test)]
451#[allow(clippy::unwrap_used, clippy::expect_used)]
452mod tests {
453    use super::*;
454
455    const TUI_CLIENT: &str = "hyprstream-tui-staging";
456
457    #[test]
458    fn exact_origin_and_content_type() {
459        let mut headers = HeaderMap::new();
460        headers.insert(
461            header::ORIGIN,
462            axum::http::HeaderValue::from_static(federate_source::WEBSITE),
463        );
464        headers.insert(
465            header::CONTENT_TYPE,
466            axum::http::HeaderValue::from_static("application/json"),
467        );
468        assert!(content_type(&headers, "application/json"));
469        // www class: the exact single website origin, and nothing else.
470        assert!(origin_for_class(&headers, federate_source::CLIENT, Some(TUI_CLIENT)).unwrap());
471        headers.append(
472            header::ORIGIN,
473            axum::http::HeaderValue::from_static("https://attacker.invalid"),
474        );
475        assert!(!origin_for_class(&headers, federate_source::CLIENT, Some(TUI_CLIENT)).unwrap());
476        // TUI class: no Origin header at all; any Origin (including the
477        // website's own) is denied, and an unconfigured client is denied.
478        let mut native = HeaderMap::new();
479        assert!(origin_for_class(&native, TUI_CLIENT, Some(TUI_CLIENT)).unwrap());
480        native.insert(
481            header::ORIGIN,
482            axum::http::HeaderValue::from_static(federate_source::WEBSITE),
483        );
484        assert!(!origin_for_class(&native, TUI_CLIENT, Some(TUI_CLIENT)).unwrap());
485        native.clear();
486        native.insert(
487            header::ORIGIN,
488            axum::http::HeaderValue::from_static("https://attacker.invalid"),
489        );
490        assert!(!origin_for_class(&native, TUI_CLIENT, Some(TUI_CLIENT)).unwrap());
491        let none = HeaderMap::new();
492        assert!(origin_for_class(&none, "unknown-client", Some(TUI_CLIENT)).is_err());
493        assert!(origin_for_class(&none, TUI_CLIENT, None).is_err());
494        // The www origin pin still holds with no TUI class configured.
495        let mut www = HeaderMap::new();
496        www.insert(
497            header::ORIGIN,
498            axum::http::HeaderValue::from_static(federate_source::WEBSITE),
499        );
500        assert!(origin_for_class(&www, federate_source::CLIENT, None).unwrap());
501    }
502
503    #[cfg(feature = "postgres")]
504    #[tokio::test]
505    async fn tui_session_registration_is_interactive_active_and_fail_closed() {
506        use hyprstream_rpc::auth::SessionRegistry as _;
507        let registry = hyprstream_rpc::auth::InMemorySessionRegistry::new();
508        let now = chrono::Utc::now().timestamp();
509        let session = hyprstream_session_store::Session {
510            host: "https://tui-host.test".into(),
511            sid: "tui-sid-1".into(),
512            account_id: "account".into(),
513            subject: "did:plc:abcdefghijklmnopqrstuvwx".into(),
514            tenant: "tenant-a".into(),
515            client_id: TUI_CLIENT.into(),
516            resource: "https://tui-host.test".into(),
517            scopes: vec!["connect:tui:session".into()],
518            grant_revision: "revision-1".into(),
519            ed_public: [3; 32],
520            pq_public: vec![4; 1952],
521            generation: [5; 32],
522            collision_inventory_id: [5; 32],
523            proof_epoch: 1,
524            expires_at: now + 120,
525        };
526        register_tui_session(&registry, &session, now)
527            .await
528            .expect("TUI session registration");
529        let key = hyprstream_rpc::auth::SessionKey::oidc("https://tui-host.test", "tui-sid-1");
530        assert!(
531            !registry.is_revoked(&key).await,
532            "registered session is active"
533        );
534        let state = registry.session_state(&key).await.expect("session state");
535        assert_eq!(state.subject, "did:plc:abcdefghijklmnopqrstuvwx");
536        assert_eq!(state.tenant, "tenant-a");
537        assert_eq!(state.kind, hyprstream_rpc::auth::SessionKind::Interactive);
538        assert_eq!(state.expires_at, now + 120);
539        // A duplicate sid registration fails closed (session identifiers are
540        // never reassigned, v16 §3.3) and surfaces as Unavailable (no mint).
541        assert!(matches!(
542            register_tui_session(&registry, &session, now).await,
543            Err(federate_source::Error::Unavailable)
544        ));
545    }
546    // ── Finding-3 fixtures: the exchange stays in the challenge's class ────
547
548    #[cfg(feature = "postgres")]
549    mod exchange_class_binding {
550        //! End-to-end through the real FederateIssuer: challenge in one
551        //! class, exchange submitted as the other. Both directions must
552        //! deny before source re-verification, possession, or Policy
553        //! commit. Offline RSA/JWKS fixtures only (disposable test key).
554        #![allow(clippy::unwrap_used, clippy::expect_used)]
555        use super::*;
556        use ed25519_dalek::Signer as _;
557        use hyprstream_rpc::crypto::pq::{ml_dsa_sign, ml_dsa_sk_from_seed, ml_dsa_sk_to_vk_bytes};
558        use serde_json::{json, Value};
559        use sha2::Digest as _;
560
561        const NOW: u64 = 1_800_000_000;
562        const CODE: &str = "TEST-CODE-NOT-LIVE";
563        const TUI_AUD: &str = "hyprstream-tui-aud";
564        const SCOPE: &str = "connect:tui:session";
565        const MODULUS: &str = "C97781230C20F14C2EB47FDD3AFBB4821EAC87003FF1A8240D1E840EE743E3EAF7A5F204503E15CFB42751AEDB97D76BE41DF559834957D283E4AC097283D18D19A12DCE56434FCA31BFC9635E721798A3D6AACC55FC8CAD559F74D66549EFC160AAD48DA9A2F860CCEA515DFEEEFA930E10B8BA5414CB26034B7352E53C7AAD5C4CE24528615705C737B7D4B554B1B4CE1A52F2D3439B42F67324B4F007691E46BE826EC6DC7CC65DD58FBF183B86DF537889EDBA5866BFD911A2AA27181C9EBD14C6DBACA28E3A37153BCD0018071101E6EA5A900812D194E6220A672EDB9FCA2C24C5486DCF981C3A2C9DC20B95E3D14875F9AF20993751BB8CBB6020678D";
566
567        fn encoding_key() -> jsonwebtoken::EncodingKey {
568            let pem: String = include_str!("federate_source/test-rsa.pem")
569                .lines()
570                .filter(|s| !s.starts_with('-'))
571                .collect();
572            jsonwebtoken::EncodingKey::from_rsa_der(
573                &base64::engine::general_purpose::STANDARD
574                    .decode(pem)
575                    .unwrap(),
576            )
577        }
578
579        fn jwks() -> Value {
580            json!({"keys":[{"kty":"RSA","kid":"fixture","alg":"RS256","use":"sig","n":B64.encode(hex::decode(MODULUS).unwrap()),"e":"AQAB"}]})
581        }
582
583        fn token(claims: &Value) -> String {
584            let mut header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256);
585            header.kid = Some("fixture".into());
586            jsonwebtoken::encode(&header, claims, &encoding_key()).unwrap()
587        }
588
589        struct StubAdmission {
590            commits: Arc<std::sync::atomic::AtomicUsize>,
591        }
592        #[async_trait::async_trait]
593        impl FederateAdmission for StubAdmission {
594            async fn prepare(
595                &self,
596                _source: &Source,
597                _requested: &str,
598                _challenge_id: [u8; 32],
599                _created_at: u64,
600            ) -> anyhow::Result<PreparedDecision> {
601                Ok(PreparedDecision {
602                    binding: AuthorityBinding {
603                        account: "account".into(),
604                        subject: "did:plc:abcdefghijklmnopqrstuvwx".into(),
605                        tenant: "tenant-a".into(),
606                        requested: SCOPE.into(),
607                        granted: SCOPE.into(),
608                        revision: "rev-1".into(),
609                    },
610                    policy_handle: vec![1; 32],
611                })
612            }
613            async fn commit(
614                &self,
615                _evidence: VerifiedPossession,
616                _policy_handle: Vec<u8>,
617            ) -> anyhow::Result<Session> {
618                self.commits
619                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
620                anyhow::bail!("sentinel: reached Policy commit")
621            }
622        }
623
624        struct StubSigner;
625        #[async_trait::async_trait]
626        impl FederateSigner for StubSigner {
627            async fn sign(&self, _claims: &Claims) -> anyhow::Result<String> {
628                anyhow::bail!("sentinel: reached mint")
629            }
630        }
631
632        fn class_parts(tui: bool) -> (federate_source::ClientClass, &'static str, &'static str) {
633            if tui {
634                (
635                    federate_source::ClientClass::new(TUI_CLIENT, TUI_AUD, None).unwrap(),
636                    federate_source::TUI_PROFILE,
637                    TUI_AUD,
638                )
639            } else {
640                (
641                    federate_source::ClientClass::staging(),
642                    "federate-session-v1",
643                    federate_source::CLIENT,
644                )
645            }
646        }
647
648        struct Prepared {
649            issuer: FederateIssuer,
650            commits: Arc<std::sync::atomic::AtomicUsize>,
651            challenge_id: String,
652            transcript: Vec<u8>,
653            subject_token: String,
654        }
655
656        /// Run a full challenge in the given class against a real issuer
657        /// (real Verifier + offline JWKS, stub admission/signer).
658        async fn prepare_challenge(tui: bool) -> Prepared {
659            let (class, profile, aud) = class_parts(tui);
660            let host = federate_source::FederateHost::new(federate_source::HOST).unwrap();
661            let commits = Arc::new(std::sync::atomic::AtomicUsize::new(0));
662            let admission = Arc::new(StubAdmission {
663                commits: Arc::clone(&commits),
664            });
665            let mut issuer = FederateIssuer::new(
666                admission,
667                Arc::new(StubSigner),
668                host.clone(),
669                Some(federate_source::ClientClass::new(TUI_CLIENT, TUI_AUD, None).unwrap()),
670            )
671            .unwrap();
672            issuer.verifier.set_test_responses(
673                (0..4)
674                    .map(|_| Ok(serde_json::to_vec(&jwks()).unwrap()))
675                    .collect(),
676            );
677
678            let login_random = B64.encode([11; 32]);
679            let state = B64.encode([12; 32]);
680            let pkce = B64.encode([13; 32]);
681            let ed = ed25519_dalek::SigningKey::from_bytes(&[7; 32]);
682            let pq = ml_dsa_sk_from_seed(&[8; 32]);
683            let ed_public = B64.encode(ed.verifying_key().as_bytes());
684            let pq_public = B64.encode(ml_dsa_sk_to_vk_bytes(&pq));
685            let commitment = federate_source::Commitment::for_class(
686                host.clone(),
687                &class,
688                &login_random,
689                &state,
690                &pkce,
691                &ed_public,
692                &pq_public,
693            )
694            .unwrap();
695            let claims = json!({
696                "iss": federate_source::ISSUER,
697                "aud": aud,
698                "azp": class.client_id(),
699                "sub": "opaque-sub",
700                "jti": "source-id",
701                "iat": NOW,
702                "exp": NOW + 300,
703                "nonce": commitment.nonce(),
704                "c_hash": B64.encode(&sha2::Sha256::digest(CODE.as_bytes())[..16]),
705                "federated_claims": {"connector_id":"atproto","user_id":"did:plc:abcdefghijklmnopqrstuvwx"},
706            });
707            let subject_token = token(&claims);
708            let body = serde_json::to_vec(&json!({
709                "profile": profile,
710                "client_id": class.client_id(),
711                "subject_token": subject_token,
712                "subject_token_type": "urn:ietf:params:oauth:token-type:id_token",
713                "authorization_code": CODE,
714                "resource": federate_source::HOST,
715                "scope": SCOPE,
716                "login_random": login_random,
717                "state": state,
718                "pkce_challenge": pkce,
719                "ed25519_public": ed_public,
720                "ml_dsa65_public": pq_public,
721            }))
722            .unwrap();
723            let mut headers = HeaderMap::new();
724            if !tui {
725                headers.insert(
726                    header::ORIGIN,
727                    axum::http::HeaderValue::from_static(federate_source::WEBSITE),
728                );
729            }
730            let response = issuer.challenge(&headers, &body, NOW).await.unwrap();
731            Prepared {
732                issuer,
733                commits,
734                challenge_id: response.challenge_id,
735                transcript: B64.decode(response.transcript_b64u).unwrap(),
736                subject_token,
737            }
738        }
739
740        fn exchange_form(prepared: &Prepared, tui: bool, transcript: &[u8]) -> String {
741            let (_class, profile, _aud) = class_parts(tui);
742            let ed = ed25519_dalek::SigningKey::from_bytes(&[7; 32]);
743            let pq = ml_dsa_sk_from_seed(&[8; 32]);
744            let ed_sig = ed.sign(transcript);
745            let pq_sig = ml_dsa_sign(&pq, transcript);
746            url::form_urlencoded::Serializer::new(String::new())
747                .append_pair(
748                    "grant_type",
749                    "urn:ietf:params:oauth:grant-type:token-exchange",
750                )
751                .append_pair("hs_profile", profile)
752                .append_pair(
753                    "client_id",
754                    if tui {
755                        TUI_CLIENT
756                    } else {
757                        federate_source::CLIENT
758                    },
759                )
760                .append_pair(
761                    "subject_token_type",
762                    "urn:ietf:params:oauth:token-type:id_token",
763                )
764                .append_pair("subject_token", &prepared.subject_token)
765                .append_pair(
766                    "requested_token_type",
767                    "urn:ietf:params:oauth:token-type:access_token",
768                )
769                .append_pair("resource", federate_source::HOST)
770                .append_pair("scope", SCOPE)
771                .append_pair("challenge_id", &prepared.challenge_id)
772                .append_pair("ed25519_signature", &B64.encode(ed_sig.to_bytes()))
773                .append_pair("ml_dsa65_signature", &B64.encode(pq_sig))
774                .finish()
775        }
776
777        #[tokio::test]
778        async fn exchange_stays_in_the_challenge_class_both_directions() {
779            // www challenge redeemed as TUI (native, no Origin): denied
780            // before Policy commit.
781            let prepared = prepare_challenge(false).await;
782            let form = exchange_form(&prepared, true, &prepared.transcript);
783            let result = prepared
784                .issuer
785                .exchange(&HeaderMap::new(), form.as_bytes(), NOW)
786                .await;
787            assert!(matches!(result, Err(federate_source::Error::Invalid)));
788            assert_eq!(
789                prepared.commits.load(std::sync::atomic::Ordering::SeqCst),
790                0
791            );
792
793            // TUI challenge redeemed as www (website Origin): denied before
794            // Policy commit.
795            let prepared = prepare_challenge(true).await;
796            let form = exchange_form(&prepared, false, &prepared.transcript);
797            let mut headers = HeaderMap::new();
798            headers.insert(
799                header::ORIGIN,
800                axum::http::HeaderValue::from_static(federate_source::WEBSITE),
801            );
802            let result = prepared
803                .issuer
804                .exchange(&headers, form.as_bytes(), NOW)
805                .await;
806            assert!(matches!(result, Err(federate_source::Error::Invalid)));
807            assert_eq!(
808                prepared.commits.load(std::sync::atomic::Ordering::SeqCst),
809                0
810            );
811
812            // Control: a same-class exchange passes the class binding and
813            // reaches Policy commit (the stub's sentinel error).
814            let prepared = prepare_challenge(true).await;
815            let form = exchange_form(&prepared, true, &prepared.transcript);
816            let result = prepared
817                .issuer
818                .exchange(&HeaderMap::new(), form.as_bytes(), NOW)
819                .await;
820            let reached = prepared.commits.load(std::sync::atomic::Ordering::SeqCst);
821            assert_eq!(
822                reached,
823                1,
824                "matched-class exchange must reach Policy commit: {:?}",
825                result.as_ref().err()
826            );
827            assert!(matches!(result, Err(federate_source::Error::Unavailable)));
828        }
829
830        // ── W1b: the device flow through the real issuer ──────────────────
831
832        const DEVICE_CODE: &str = "TEST-DEVICE-CODE-NOT-LIVE";
833
834        fn device_token(ed_public: &str) -> String {
835            token(&json!({
836                "iss": federate_source::ISSUER,
837                "aud": TUI_AUD,
838                "azp": TUI_CLIENT,
839                "sub": "opaque-sub",
840                "jti": "source-id",
841                "iat": NOW,
842                "exp": NOW + 300,
843                "binding_key": ed_public,
844                "federated_claims": {"connector_id":"atproto","user_id":"did:plc:abcdefghijklmnopqrstuvwx"},
845            }))
846        }
847
848        fn device_body(
849            subject_token: &str,
850            login_random: &str,
851            ed_public: &str,
852            pq_public: &str,
853        ) -> Vec<u8> {
854            serde_json::to_vec(&json!({
855                "profile": federate_source::TUI_DEVICE_PROFILE,
856                "client_id": TUI_CLIENT,
857                "subject_token": subject_token,
858                "subject_token_type": "urn:ietf:params:oauth:token-type:id_token",
859                "device_code": DEVICE_CODE,
860                "resource": federate_source::HOST,
861                "scope": SCOPE,
862                "login_random": login_random,
863                "ed25519_public": ed_public,
864                "ml_dsa65_public": pq_public,
865            }))
866            .unwrap()
867        }
868
869        async fn prepare_device_challenge() -> Prepared {
870            let host = federate_source::FederateHost::new(federate_source::HOST).unwrap();
871            let commits = Arc::new(std::sync::atomic::AtomicUsize::new(0));
872            let admission = Arc::new(StubAdmission {
873                commits: Arc::clone(&commits),
874            });
875            let mut issuer = FederateIssuer::new(
876                admission,
877                Arc::new(StubSigner),
878                host.clone(),
879                Some(federate_source::ClientClass::new(TUI_CLIENT, TUI_AUD, None).unwrap()),
880            )
881            .unwrap();
882            issuer.verifier.set_test_responses(
883                (0..4)
884                    .map(|_| Ok(serde_json::to_vec(&jwks()).unwrap()))
885                    .collect(),
886            );
887            let login_random = B64.encode([21; 32]);
888            let ed = ed25519_dalek::SigningKey::from_bytes(&[7; 32]);
889            let pq = ml_dsa_sk_from_seed(&[8; 32]);
890            let ed_public = B64.encode(ed.verifying_key().as_bytes());
891            let pq_public = B64.encode(ml_dsa_sk_to_vk_bytes(&pq));
892            let subject_token = device_token(&ed_public);
893            let body = device_body(&subject_token, &login_random, &ed_public, &pq_public);
894            // Native client: no Origin header at all.
895            let response = issuer
896                .challenge(&HeaderMap::new(), &body, NOW)
897                .await
898                .unwrap();
899            // The challenge answers the device profile, pinning the flow for
900            // the exchange leg.
901            assert_eq!(response.profile, federate_source::TUI_DEVICE_PROFILE);
902            Prepared {
903                issuer,
904                commits,
905                challenge_id: response.challenge_id,
906                transcript: B64.decode(response.transcript_b64u).unwrap(),
907                subject_token,
908            }
909        }
910
911        fn device_exchange_form(
912            prepared: &Prepared,
913            hs_profile: &str,
914            transcript: &[u8],
915        ) -> String {
916            let ed = ed25519_dalek::SigningKey::from_bytes(&[7; 32]);
917            let pq = ml_dsa_sk_from_seed(&[8; 32]);
918            let ed_sig = ed.sign(transcript);
919            let pq_sig = ml_dsa_sign(&pq, transcript);
920            url::form_urlencoded::Serializer::new(String::new())
921                .append_pair(
922                    "grant_type",
923                    "urn:ietf:params:oauth:grant-type:token-exchange",
924                )
925                .append_pair("hs_profile", hs_profile)
926                .append_pair("client_id", TUI_CLIENT)
927                .append_pair(
928                    "subject_token_type",
929                    "urn:ietf:params:oauth:token-type:id_token",
930                )
931                .append_pair("subject_token", &prepared.subject_token)
932                .append_pair(
933                    "requested_token_type",
934                    "urn:ietf:params:oauth:token-type:access_token",
935                )
936                .append_pair("resource", federate_source::HOST)
937                .append_pair("scope", SCOPE)
938                .append_pair("challenge_id", &prepared.challenge_id)
939                .append_pair("ed25519_signature", &B64.encode(ed_sig.to_bytes()))
940                .append_pair("ml_dsa65_signature", &B64.encode(pq_sig))
941                .finish()
942        }
943
944        #[tokio::test]
945        async fn device_challenge_and_exchange_reach_policy_commit() {
946            let prepared = prepare_device_challenge().await;
947            let form = device_exchange_form(
948                &prepared,
949                federate_source::TUI_DEVICE_PROFILE,
950                &prepared.transcript,
951            );
952            let result = prepared
953                .issuer
954                .exchange(&HeaderMap::new(), form.as_bytes(), NOW)
955                .await;
956            assert_eq!(
957                prepared.commits.load(std::sync::atomic::Ordering::SeqCst),
958                1,
959                "device-flow exchange must reach Policy commit: {:?}",
960                result.as_ref().err()
961            );
962            assert!(matches!(result, Err(federate_source::Error::Unavailable)));
963        }
964
965        #[tokio::test]
966        async fn device_and_code_flows_cannot_substitute_for_each_other() {
967            // Device challenge redeemed with the class profile: denied
968            // before Policy commit by the flow pin.
969            let prepared = prepare_device_challenge().await;
970            let form = device_exchange_form(
971                &prepared,
972                federate_source::TUI_PROFILE,
973                &prepared.transcript,
974            );
975            let result = prepared
976                .issuer
977                .exchange(&HeaderMap::new(), form.as_bytes(), NOW)
978                .await;
979            assert!(matches!(result, Err(federate_source::Error::Invalid)));
980            assert_eq!(
981                prepared.commits.load(std::sync::atomic::Ordering::SeqCst),
982                0
983            );
984
985            // Code-flow TUI challenge redeemed with the device profile: the
986            // exchange parses (the TUI class accepts both profile strings)
987            // but the pending challenge pins the code flow, so this denies
988            // before Policy commit.
989            let prepared = prepare_challenge(true).await;
990            let form = device_exchange_form(
991                &prepared,
992                federate_source::TUI_DEVICE_PROFILE,
993                &prepared.transcript,
994            );
995            let result = prepared
996                .issuer
997                .exchange(&HeaderMap::new(), form.as_bytes(), NOW)
998                .await;
999            assert!(matches!(result, Err(federate_source::Error::Invalid)));
1000            assert_eq!(
1001                prepared.commits.load(std::sync::atomic::Ordering::SeqCst),
1002                0
1003            );
1004        }
1005
1006        #[tokio::test]
1007        async fn device_challenge_requires_the_signed_binding_key_claim() {
1008            let host = federate_source::FederateHost::new(federate_source::HOST).unwrap();
1009            let commits = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1010            let mut issuer = FederateIssuer::new(
1011                Arc::new(StubAdmission {
1012                    commits: Arc::clone(&commits),
1013                }),
1014                Arc::new(StubSigner),
1015                host.clone(),
1016                Some(federate_source::ClientClass::new(TUI_CLIENT, TUI_AUD, None).unwrap()),
1017            )
1018            .unwrap();
1019            issuer.verifier.set_test_responses(
1020                (0..4)
1021                    .map(|_| Ok(serde_json::to_vec(&jwks()).unwrap()))
1022                    .collect(),
1023            );
1024            let ed = ed25519_dalek::SigningKey::from_bytes(&[7; 32]);
1025            let pq = ml_dsa_sk_from_seed(&[8; 32]);
1026            let ed_public = B64.encode(ed.verifying_key().as_bytes());
1027            let pq_public = B64.encode(ml_dsa_sk_to_vk_bytes(&pq));
1028            let login_random = B64.encode([21; 32]);
1029
1030            // A code-flow token (nonce/c_hash, no binding_key) under the
1031            // device envelope: the challenge denies before Policy prepare.
1032            let code_flow_token = token(&json!({
1033                "iss": federate_source::ISSUER,
1034                "aud": TUI_AUD,
1035                "azp": TUI_CLIENT,
1036                "sub": "opaque-sub",
1037                "jti": "source-id",
1038                "iat": NOW,
1039                "exp": NOW + 300,
1040                "nonce": "hsn1.unrelated",
1041                "c_hash": B64.encode(&sha2::Sha256::digest(CODE.as_bytes())[..16]),
1042                "federated_claims": {"connector_id":"atproto","user_id":"did:plc:abcdefghijklmnopqrstuvwx"},
1043            }));
1044            let body = device_body(&code_flow_token, &login_random, &ed_public, &pq_public);
1045            assert!(matches!(
1046                issuer.challenge(&HeaderMap::new(), &body, NOW).await,
1047                Err(federate_source::Error::Invalid)
1048            ));
1049
1050            // A binding_key naming a different holder key denies the same way.
1051            let foreign = device_token(
1052                &B64.encode(
1053                    ed25519_dalek::SigningKey::from_bytes(&[77; 32])
1054                        .verifying_key()
1055                        .as_bytes(),
1056                ),
1057            );
1058            let body = device_body(&foreign, &login_random, &ed_public, &pq_public);
1059            assert!(matches!(
1060                issuer.challenge(&HeaderMap::new(), &body, NOW).await,
1061                Err(federate_source::Error::Invalid)
1062            ));
1063
1064            // The staging class never accepts the device profile.
1065            let staging = serde_json::json!({
1066                "profile": federate_source::TUI_DEVICE_PROFILE,
1067                "client_id": federate_source::CLIENT,
1068                "subject_token": device_token(&ed_public),
1069                "subject_token_type": "urn:ietf:params:oauth:token-type:id_token",
1070                "device_code": DEVICE_CODE,
1071                "resource": federate_source::HOST,
1072                "scope": SCOPE,
1073                "login_random": login_random,
1074                "ed25519_public": ed_public,
1075                "ml_dsa65_public": pq_public,
1076            });
1077            let mut headers = HeaderMap::new();
1078            headers.insert(
1079                header::ORIGIN,
1080                axum::http::HeaderValue::from_static(federate_source::WEBSITE),
1081            );
1082            assert!(matches!(
1083                issuer
1084                    .challenge(
1085                        &headers,
1086                        serde_json::to_vec(&staging).unwrap().as_slice(),
1087                        NOW
1088                    )
1089                    .await,
1090                Err(federate_source::Error::Invalid)
1091            ));
1092            assert_eq!(commits.load(std::sync::atomic::Ordering::SeqCst), 0);
1093        }
1094    }
1095}