Skip to main content

hyprstream_core/services/oauth/
authorize.rs

1//! OAuth 2.1 Authorization Endpoint.
2//!
3//! Handles the authorization code flow with PKCE (S256) and Ed25519 user authentication.
4//! - GET /oauth/authorize — validates params, renders Ed25519 challenge form
5//! - POST /oauth/authorize — verifies Ed25519 signature, generates auth code and redirects
6//!
7//! The consent page was replaced with an Ed25519 challenge-response form. The nonce is
8//! stored server-side (`OAuthState::pending_nonces`, 5-min TTL) and embedded as a hidden
9//! form field. On POST, the server verifies the nonce was issued by itself and consumes it
10//! (single-use). Challenge format:
11//!   `"{fingerprint}:{nonce}:{code_challenge}"`
12//! The `code_challenge` binding prevents the signature from being reused against a different
13//! PKCE session; the server-side nonce store enforces TTL and prevents replay. The client
14//! never asserts a username — the server resolves it from `fingerprint` via the
15//! `pubkey:{fingerprint} → username` reverse index in the UserStore.
16
17use std::sync::Arc;
18use std::time::{Duration, Instant};
19
20use axum::{
21    extract::{rejection::FormRejection, Query, State},
22    http::StatusCode,
23    response::{Html, IntoResponse, Redirect, Response},
24    Form,
25};
26use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
27use rand::RngCore;
28use serde::Deserialize;
29
30use super::challenge;
31use super::device::html_escape;
32use super::identity_registration::IdentityApiError;
33use super::registration::{resolve_cimd_client, validate_redirect_uri};
34use super::state::{OAuthState, PendingAuthCode};
35use crate::auth::{AccountKeyCustody, HostedAccountProvisionError};
36
37const SIGNUP_ACTION: &str = "signup";
38const AUTHORIZE_ACTION: &str = "authorize";
39const SIGNUP_PROOF_DOMAIN: &[u8] = b"hyprstream-cold-signup-v1\0";
40
41/// Authorization request query parameters
42#[derive(Debug, Clone, Deserialize)]
43pub struct AuthorizeParams {
44    pub client_id: String,
45    pub redirect_uri: String,
46    pub code_challenge: String,
47    pub code_challenge_method: String,
48    pub response_type: String,
49    #[serde(default)]
50    pub state: Option<String>,
51    #[serde(default)]
52    pub scope: Option<String>,
53    /// RFC 8707 resource indicator
54    #[serde(default)]
55    pub resource: Option<String>,
56    /// OIDC nonce — echoed into id_token (OpenID Connect Core 1.0, Section 3.1.2.1)
57    #[serde(default)]
58    pub nonce: Option<String>,
59    /// DPoP key thumbprint (`jkt`) bound at PAR (#1113 rev2 finding 3). When
60    /// the atproto profile is active this is REQUIRED and the token endpoint
61    /// must receive a DPoP proof from the same key.
62    #[serde(default)]
63    pub dpop_jkt: Option<String>,
64    /// RFC 7638 thumbprint of the client-assertion key verified at PAR
65    /// (#1146 T3.3). When set, token redemption must present a
66    /// `client_assertion` signed by the same key.
67    #[serde(default)]
68    pub client_assertion_jkt: Option<String>,
69}
70
71/// Loosely-typed authorize query.
72///
73/// Accepts either inline parameters (the original authorize URL form) or a
74/// `request_uri` reference to a Pushed Authorization Request (RFC 9126).
75/// When `request_uri` is present, the inline parameters (except `client_id`)
76/// are ignored and the pushed snapshot is used instead.
77#[derive(Debug, Deserialize)]
78pub struct AuthorizeQuery {
79    #[serde(default)]
80    pub request_uri: Option<String>,
81    #[serde(default)]
82    pub client_id: Option<String>,
83    #[serde(default)]
84    pub redirect_uri: Option<String>,
85    #[serde(default)]
86    pub code_challenge: Option<String>,
87    #[serde(default)]
88    pub code_challenge_method: Option<String>,
89    #[serde(default)]
90    pub response_type: Option<String>,
91    #[serde(default)]
92    pub state: Option<String>,
93    #[serde(default)]
94    pub scope: Option<String>,
95    #[serde(default)]
96    pub resource: Option<String>,
97    #[serde(default)]
98    pub nonce: Option<String>,
99}
100
101/// Consent form submission (Ed25519 challenge-response).
102///
103/// The client supplies its key fingerprint (not a username). The server
104/// resolves the username from the `pubkey:{fingerprint} → username` reverse
105/// index, then verifies the signature. The challenge string is
106/// `"{fingerprint}:{nonce}:{code_challenge}"`.
107#[derive(Debug, Deserialize)]
108pub struct ConsentForm {
109    /// Omitted/`authorize` authenticates an existing account. `signup`
110    /// provisions a new hosted account inside this same authorize transaction.
111    #[serde(default)]
112    pub action: Option<String>,
113    pub client_id: String,
114    pub redirect_uri: String,
115    pub code_challenge: String,
116    pub scope: String,
117    #[serde(default)]
118    pub state: Option<String>,
119    #[serde(default)]
120    pub resource: Option<String>,
121    /// Ed25519 nonce (from hidden form field; validated server-side against pending_nonces)
122    pub nonce: String,
123    /// SSH-style key fingerprint (`SHA256:...`) of the signing key.
124    pub fingerprint: String,
125    /// Base64-encoded Ed25519 signature
126    pub signature: String,
127    /// Requested one-label hosted-account handle. Signup action only.
128    #[serde(default)]
129    pub handle: Option<String>,
130    /// Standard-base64 raw or SSH-wire Ed25519 public key. Signup action only.
131    #[serde(default)]
132    pub account_public_key: Option<String>,
133    /// OIDC nonce (passed through from authorize request, stored in auth code)
134    #[serde(default)]
135    pub oidc_nonce: Option<String>,
136}
137
138/// GET /oauth/authorize — validate params and render Ed25519 challenge form
139pub async fn authorize_get(
140    State(state): State<Arc<OAuthState>>,
141    Query(query): Query<AuthorizeQuery>,
142) -> Response {
143    // Resolve params: either from a Pushed Authorization Request (RFC 9126)
144    // referenced by `request_uri`, or from inline query parameters.
145    let params = match resolve_authorize_query(&state, query).await {
146        Ok(p) => p,
147        Err(resp) => return resp,
148    };
149
150    // Validate response_type
151    if params.response_type != "code" {
152        return error_response(
153            StatusCode::BAD_REQUEST,
154            "unsupported_response_type",
155            "Only response_type=code is supported",
156        );
157    }
158
159    // Validate code_challenge_method
160    if params.code_challenge_method != "S256" {
161        return error_response(
162            StatusCode::BAD_REQUEST,
163            "invalid_request",
164            "Only code_challenge_method=S256 is supported",
165        );
166    }
167
168    if params.code_challenge.is_empty() {
169        return error_response(
170            StatusCode::BAD_REQUEST,
171            "invalid_request",
172            "code_challenge is required (PKCE mandatory per OAuth 2.1)",
173        );
174    }
175
176    // Require UserStore for identity verification
177    if !state.has_user_store() {
178        return Html(render_error_page(
179            "Server Not Configured",
180            "This server is not configured for local user authentication. \
181             Contact your administrator to set up the user credential store.",
182        ))
183        .into_response();
184    }
185
186    // Resolve client
187    let (client_name, redirect_uris) = if params.client_id.starts_with("https://") {
188        // Client ID Metadata Document flow (cache-aside via cimd_cache).
189        match resolve_cimd_client(&state, &params.client_id).await {
190            Ok(client) => (
191                client
192                    .client_name
193                    .unwrap_or_else(|| params.client_id.clone()),
194                client.redirect_uris,
195            ),
196            Err(e) => {
197                return error_response(
198                    StatusCode::BAD_REQUEST,
199                    "invalid_client",
200                    &format!("Failed to resolve client metadata: {}", e),
201                );
202            }
203        }
204    } else {
205        // Dynamic registration lookup
206        let clients = state.clients.read().await;
207        match clients.get(&params.client_id) {
208            Some(client) => (
209                client
210                    .client_name
211                    .clone()
212                    .unwrap_or_else(|| params.client_id.clone()),
213                client.redirect_uris.clone(),
214            ),
215            None => {
216                return error_response(
217                    StatusCode::BAD_REQUEST,
218                    "invalid_client",
219                    "Unknown client_id. Register first via POST /oauth/register",
220                );
221            }
222        }
223    };
224
225    // Validate redirect_uri
226    if !validate_redirect_uri(&params.redirect_uri, &redirect_uris) {
227        return error_response(
228            StatusCode::BAD_REQUEST,
229            "invalid_redirect_uri",
230            "redirect_uri does not match registered URIs",
231        );
232    }
233
234    // Determine scopes
235    let scopes = params
236        .scope
237        .as_deref()
238        .unwrap_or(&state.default_scopes.join(" "))
239        .to_owned();
240    let mut effective_request = params.clone();
241    effective_request.scope = Some(scopes.clone());
242    let effective_scopes = match validate_authorize_scopes(&state, &effective_request).await {
243        Ok(scopes) => scopes,
244        Err(response) => return response,
245    };
246    if super::state::atproto_profile_active(&effective_scopes)
247        && effective_request.dpop_jkt.is_none()
248    {
249        return error_response(
250            StatusCode::BAD_REQUEST,
251            "invalid_request",
252            "The atproto profile requires a Pushed Authorization Request with a DPoP proof.",
253        );
254    }
255
256    // Extract redirect hostname for display
257    let redirect_host = url::Url::parse(&params.redirect_uri)
258        .ok()
259        .and_then(|u| u.host_str().map(std::borrow::ToOwned::to_owned))
260        .unwrap_or_else(|| params.redirect_uri.clone());
261
262    // MCP spec § Localhost Redirect URI Risks: warn when the registered
263    // client only ever uses loopback redirect URIs. Such a client cannot
264    // be distinguished from another process on the same host binding the
265    // same loopback range, so users should be told explicitly that the
266    // app they're authorizing only proves local-machine presence.
267    let localhost_warning = compute_localhost_warning(&redirect_uris);
268
269    // Generate a nonce, store it server-side (5-min TTL, single-use on POST).
270    let nonce = issue_nonce(&state).await;
271    // Bind the complete resolved request to the consent nonce. Hidden form
272    // fields are transport echoes only and cannot change authority on POST.
273    state.pending_authorize_bindings.write().await.insert(
274        nonce.clone(),
275        super::state::AuthorizeBinding {
276            request: effective_request.clone(),
277        },
278    );
279
280    // The provider choice is an explicit approval of the displayed client,
281    // redirect and scopes. The link carries only the server-side consent nonce.
282    // ATProto's key-bound profile requires local signing and is never offered.
283    let provider_buttons = if super::state::atproto_profile_active(&effective_scopes)
284        || effective_request.dpop_jkt.is_some()
285        || effective_request.client_assertion_jkt.is_some()
286    {
287        String::new()
288    } else {
289        let mut providers: Vec<_> = state
290            .external_providers
291            .iter()
292            .filter(|(_, provider)| {
293                matches!(provider.provisioning, crate::config::ProvisioningMode::Deny)
294            })
295            .collect();
296        providers.sort_by_key(|(slug, _)| *slug);
297        providers
298            .into_iter()
299            .map(|(slug, provider)| {
300                let name = provider.display_name.as_deref().unwrap_or(slug);
301                format!(
302                    "<form method=\"post\" action=\"/oauth/external/authorize/{}\"><input type=\"hidden\" name=\"login_challenge\" value=\"{}\"><button type=\"submit\">Authorize and sign in with {}</button></form>",
303                    urlencoding::encode(slug),
304                    nonce,
305                    html_escape(name),
306                )
307            })
308            .collect::<String>()
309    };
310
311    // Render challenge form
312    let html = render_challenge_page(
313        &client_name,
314        &scopes,
315        &redirect_host,
316        &effective_request.client_id,
317        &effective_request.redirect_uri,
318        &effective_request.code_challenge,
319        effective_request.state.as_deref().unwrap_or(""),
320        effective_request.resource.as_deref().unwrap_or(""),
321        &nonce,
322        effective_request.nonce.as_deref().unwrap_or(""),
323        None,
324        localhost_warning.as_deref(),
325        &provider_buttons,
326    );
327
328    Html(html).into_response()
329}
330
331fn nonempty(value: Option<&str>) -> Option<&str> {
332    value.filter(|value| !value.is_empty())
333}
334
335fn consent_form_matches_request(form: &ConsentForm, request: &AuthorizeParams) -> bool {
336    form.client_id == request.client_id
337        && form.redirect_uri == request.redirect_uri
338        && form.code_challenge == request.code_challenge
339        && form.scope == request.scope.as_deref().unwrap_or("")
340        && nonempty(form.state.as_deref()) == nonempty(request.state.as_deref())
341        && nonempty(form.resource.as_deref()) == nonempty(request.resource.as_deref())
342        && nonempty(form.oidc_nonce.as_deref()) == nonempty(request.nonce.as_deref())
343}
344
345/// Domain-separated proof signed by the new vault key.
346///
347/// NUL delimiters make the byte contract unambiguous. The fingerprint is
348/// derived again from `account_public_key` before verification, so the proof
349/// binds the actual key as well as handle, single-use authorize nonce, and
350/// PAR/PKCE transaction.
351fn signup_proof_challenge(
352    handle: &str,
353    fingerprint: &str,
354    nonce: &str,
355    code_challenge: &str,
356) -> Vec<u8> {
357    let mut challenge = Vec::with_capacity(
358        SIGNUP_PROOF_DOMAIN.len()
359            + handle.len()
360            + fingerprint.len()
361            + nonce.len()
362            + code_challenge.len()
363            + 4,
364    );
365    challenge.extend_from_slice(SIGNUP_PROOF_DOMAIN);
366    for component in [handle, fingerprint, nonce, code_challenge] {
367        challenge.extend_from_slice(component.as_bytes());
368        challenge.push(0);
369    }
370    challenge
371}
372
373/// Baseline tenant policy rows for a newly provisioned hosted account.
374///
375/// Two classes, both idempotent (`add_policy_with_domain` deduplicates):
376///
377/// 1. The reviewed MCP delegated-bearer exchange (`mcp_service.rs`
378///    `delegated_resource_bearer`) mints the caller's own subject through
379///    `PolicyClient::issue_token`; explicit-subject issuance checks that the
380///    caller (`service:mcp`) holds `policy:IssueToken manage` in the token's
381///    target tenant (`services/policy.rs` IssueToken check). The
382///    always-injected base rule `service:mcp, *, policy:*, *`
383///    (`auth/policy_templates.rs` SERVICE_BASE_POLICIES, re-injected after
384///    every reload) already satisfies that check in every tenant today, so
385///    the row seeded here is explicit per-tenant deployment data — auditable
386///    per hosted tenant, and load-bearing the moment the broad base rule is
387///    narrowed — recorded at the one authoritative point where a hosted
388///    tenant gains a member.
389/// 2. When the operator configured the canonical 9P read export, the account
390///    needs the HolderGate pair — `model:{repo} query` and
391///    `registry:{repo-uuid} query` (`remote_registry_mount.rs` HolderGate) —
392///    to read the export the deployment selected for it.
393async fn seed_hosted_tenant_policy_baseline_with(
394    pm: &crate::auth::PolicyManager,
395    did: &str,
396    tenant: &str,
397    canonical_read: Option<&crate::config::NinepCanonicalReadConfig>,
398) -> anyhow::Result<()> {
399    pm.add_policy_with_domain(
400        "service:mcp",
401        tenant,
402        "policy:IssueToken",
403        "manage",
404        "allow",
405    )
406    .await?;
407    if let Some(export) = canonical_read {
408        for resource in [
409            format!("model:{}", export.repo_name),
410            format!("registry:{}", export.repo_id),
411        ] {
412            pm.add_policy_with_domain(did, tenant, &resource, "query", "allow")
413                .await?;
414        }
415    }
416    pm.save().await?;
417    Ok(())
418}
419
420/// Seed a new hosted tenant's baseline rows through the shared PolicyManager.
421/// Best-effort like the OIDC JIT provisioning path (`oidc_callback.rs`): the
422/// account is already durably activated when this runs, so failures are
423/// logged, never returned as a second signup failure mode.
424async fn seed_hosted_tenant_policy_baseline(
425    did: &str,
426    tenant: &str,
427    canonical_read: Option<&crate::config::NinepCanonicalReadConfig>,
428) {
429    let Some(pm) = crate::auth::global_policy_manager() else {
430        tracing::error!(
431            did,
432            tenant,
433            "Hosted-tenant policy baseline not seeded: PolicyManager unavailable"
434        );
435        return;
436    };
437    if let Err(error) =
438        seed_hosted_tenant_policy_baseline_with(&pm, did, tenant, canonical_read).await
439    {
440        tracing::error!(did, tenant, %error, "Hosted-tenant policy baseline seeding failed");
441    }
442}
443
444/// POST /oauth/authorize — verify Ed25519 signature, issue auth code
445pub async fn authorize_post(
446    State(state): State<Arc<OAuthState>>,
447    submitted: Result<Form<ConsentForm>, FormRejection>,
448) -> Response {
449    let Form(form) = match submitted {
450        Ok(form) => form,
451        Err(_) => {
452            return error_response(
453                StatusCode::BAD_REQUEST,
454                "invalid_request",
455                "Authorization form is missing or malformed",
456            );
457        }
458    };
459    // Validate and consume the nonce. Rejects forged nonces and enforces the 5-min TTL.
460    // Single-use: remove from pending_nonces whether valid or expired.
461    let (nonce_valid, authorize_binding) = {
462        let mut nonces = state.pending_nonces.write().await;
463        match nonces.remove(&form.nonce) {
464            Some(expiry) => {
465                let valid = Instant::now() < expiry;
466                // Consume the PAR-bound DPoP jkt alongside the nonce (#1113 rev2).
467                let binding = state
468                    .pending_authorize_bindings
469                    .write()
470                    .await
471                    .remove(&form.nonce);
472                (valid, binding)
473            }
474            None => (false, None),
475        }
476    };
477    let Some(authorize_binding) = authorize_binding else {
478        return error_response(
479            StatusCode::BAD_REQUEST,
480            "invalid_request",
481            "Authorization request is missing or already consumed",
482        );
483    };
484    let effective = &authorize_binding.request;
485
486    if !nonce_valid {
487        // Re-render only from the server-side snapshot; the submitted form is untrusted.
488        let Some((client_name, redirect_host, localhost_warning)) =
489            derive_display_info(&state, &effective.client_id, &effective.redirect_uri).await
490        else {
491            return Html(render_error_page(
492                "Invalid Request",
493                "Unknown client or redirect URI. Please restart the authorization flow.",
494            ))
495            .into_response();
496        };
497        let fresh_nonce = issue_nonce(&state).await;
498        // #1113 rev2 F3: re-stash the binding on error-retry so the PAR
499        // key binding survives a nonce-expired re-render.
500        state
501            .pending_authorize_bindings
502            .write()
503            .await
504            .insert(fresh_nonce.clone(), authorize_binding.clone());
505        let html = render_challenge_page(
506            &client_name,
507            effective.scope.as_deref().unwrap_or(""),
508            &redirect_host,
509            &effective.client_id,
510            &effective.redirect_uri,
511            &effective.code_challenge,
512            effective.state.as_deref().unwrap_or(""),
513            effective.resource.as_deref().unwrap_or(""),
514            &fresh_nonce,
515            effective.nonce.as_deref().unwrap_or(""),
516            Some("Authorization request expired. Please try again."),
517            localhost_warning.as_deref(),
518            "",
519        );
520        return Html(html).into_response();
521    }
522
523    if !consent_form_matches_request(&form, effective) {
524        return error_response(
525            StatusCode::BAD_REQUEST,
526            "invalid_request",
527            "Authorization request parameters changed after consent was displayed",
528        );
529    }
530
531    // Validate the complete server-bound request before any irreversible
532    // signup mutation (authority allocation burns a permanent handle).
533    let granted_scopes = match validate_authorize_scopes(&state, effective).await {
534        Ok(scopes) => scopes,
535        Err(response) => return response,
536    };
537    let require_atproto = super::state::atproto_profile_active(&granted_scopes);
538    let resource = effective
539        .resource
540        .as_ref()
541        .filter(|value| !value.is_empty())
542        .cloned();
543
544    // Get user store
545    let user_store = match state.user_store_reader() {
546        Some(store) => store,
547        None => {
548            return Html(render_error_page(
549                "Server Not Configured",
550                "User credential store not configured on this server.",
551            ))
552            .into_response();
553        }
554    };
555
556    let action = form.action.as_deref().unwrap_or(AUTHORIZE_ACTION);
557    let (resolved_username, verifying_key) = if action == SIGNUP_ACTION {
558        // Cold signup is deliberately reachable only from an ATProto PAR:
559        // `effective` is the server-side snapshot consumed with this nonce,
560        // including the DPoP thumbprint verified by /oauth/par.
561        let Some(dpop_jkt) = effective.dpop_jkt.as_deref() else {
562            return error_response(
563                StatusCode::BAD_REQUEST,
564                "invalid_request",
565                "Signup requires an ATProto Pushed Authorization Request bound to DPoP",
566            );
567        };
568        if !require_atproto {
569            return error_response(
570                StatusCode::BAD_REQUEST,
571                "invalid_scope",
572                "Signup requires the atproto OAuth profile",
573            );
574        }
575        let Some(registration_api) = state.identity_registration_api.as_deref() else {
576            return error_response(
577                StatusCode::SERVICE_UNAVAILABLE,
578                "temporarily_unavailable",
579                "Hosted-account minting is not configured",
580            );
581        };
582        if let Err(error) = registration_api.check_oauth_signup_rate(dpop_jkt) {
583            return match error {
584                IdentityApiError::RateLimited => error_response(
585                    StatusCode::TOO_MANY_REQUESTS,
586                    "rate_limited",
587                    "Signup rate limit exceeded",
588                ),
589                _ => error_response(
590                    StatusCode::BAD_REQUEST,
591                    "invalid_request",
592                    "Signup authorization binding is invalid",
593                ),
594            };
595        }
596        let Some(handle) = form.handle.as_deref().filter(|value| !value.is_empty()) else {
597            return error_response(
598                StatusCode::BAD_REQUEST,
599                "invalid_request",
600                "Signup handle is required",
601            );
602        };
603        let Some(hosted_zone) = state.hosted_account_zone.as_ref() else {
604            return error_response(
605                StatusCode::SERVICE_UNAVAILABLE,
606                "temporarily_unavailable",
607                "Hosted-account zone is not configured",
608            );
609        };
610        let expected_did = match hosted_zone.host_for_label(handle) {
611            Ok(host) => format!("did:web:{host}"),
612            Err(_) => {
613                return error_response(
614                    StatusCode::BAD_REQUEST,
615                    "invalid_request",
616                    "Signup handle is not a valid hosted-account label",
617                );
618            }
619        };
620        let Some(account_public_key) = form
621            .account_public_key
622            .as_deref()
623            .filter(|value| !value.is_empty())
624        else {
625            return error_response(
626                StatusCode::BAD_REQUEST,
627                "invalid_request",
628                "Signup account_public_key is required",
629            );
630        };
631
632        let signup_challenge = signup_proof_challenge(
633            handle,
634            &form.fingerprint,
635            &form.nonce,
636            &effective.code_challenge,
637        );
638        let verifying_key = match challenge::verify_unregistered_ed25519_response(
639            account_public_key,
640            &form.fingerprint,
641            &signup_challenge,
642            &form.signature,
643        ) {
644            Ok(key) => key,
645            Err(error) => {
646                return error_response(StatusCode::BAD_REQUEST, "invalid_proof", error.message());
647            }
648        };
649
650        // The credential store is the first durable uniqueness commit. It
651        // stages the exact handle/DID/key binding inactive, or resumes that
652        // same verified pair. No authority reservation or PDS generation is
653        // published before this succeeds.
654        let provisioned = match user_store
655            .provision_hosted_account(
656                handle,
657                &expected_did,
658                verifying_key,
659                AccountKeyCustody::SelfCustody,
660            )
661            .await
662        {
663            Ok(provisioned) if provisioned.fingerprint == form.fingerprint => provisioned,
664            Ok(provisioned) => {
665                tracing::error!(
666                    expected = %form.fingerprint,
667                    actual = %provisioned.fingerprint,
668                    handle,
669                    "Credential store returned a mismatched signup key"
670                );
671                return error_response(
672                    StatusCode::INTERNAL_SERVER_ERROR,
673                    "server_error",
674                    "Hosted-account credential binding failed",
675                );
676            }
677            Err(HostedAccountProvisionError::AccountAlreadyExists) => {
678                return error_response(
679                    StatusCode::CONFLICT,
680                    "handle_unavailable",
681                    "Requested hosted-account handle is unavailable",
682                );
683            }
684            Err(HostedAccountProvisionError::KeyAlreadyBound) => {
685                return error_response(
686                    StatusCode::CONFLICT,
687                    "key_already_bound",
688                    "Account public key is already bound",
689                );
690            }
691            Err(HostedAccountProvisionError::Backend(error)) => {
692                tracing::error!(%error, handle, "Atomic hosted-account AS provisioning failed");
693                return error_response(
694                    StatusCode::INTERNAL_SERVER_ERROR,
695                    "server_error",
696                    "Hosted-account credential binding failed",
697                );
698            }
699        };
700
701        tracing::debug!(
702            handle,
703            resumed = provisioned.resumed,
704            "Hosted-account credential transaction is staged"
705        );
706
707        let minted =
708            match registration_api.mint_for_oauth_signup(handle, dpop_jkt, &form.fingerprint) {
709                Ok(result) => result,
710                Err(IdentityApiError::RateLimited) => {
711                    return error_response(
712                        StatusCode::TOO_MANY_REQUESTS,
713                        "rate_limited",
714                        "Signup rate limit exceeded",
715                    );
716                }
717                Err(error) => {
718                    // The staged credential binding is intentionally retained:
719                    // an exact retry can resume the authority/PDS transaction.
720                    // Authority conflicts after staging indicate inconsistent
721                    // backend state and are never a client-trusted 409.
722                    tracing::error!(?error, handle, "Hosted-account signup mint failed");
723                    return error_response(
724                        StatusCode::INTERNAL_SERVER_ERROR,
725                        "server_error",
726                        "Hosted-account minting failed",
727                    );
728                }
729            };
730        if expected_did.as_str() != minted.did {
731            tracing::error!(
732                requested_handle = handle,
733                minted_did = %minted.did,
734                "Authority returned a DID outside the configured host-form account zone"
735            );
736            return error_response(
737                StatusCode::INTERNAL_SERVER_ERROR,
738                "server_error",
739                "Hosted-account authority binding is invalid",
740            );
741        }
742        if let Err(error) = user_store
743            .activate_hosted_account(
744                handle,
745                &minted.did,
746                &form.fingerprint,
747                AccountKeyCustody::SelfCustody,
748            )
749            .await
750        {
751            tracing::error!(?error, handle, "Hosted-account final AS activation failed");
752            return error_response(
753                StatusCode::INTERNAL_SERVER_ERROR,
754                "server_error",
755                "Hosted-account activation failed",
756            );
757        }
758        if let Err(error) = state.refresh_hosted_account_index_after_signup().await {
759            tracing::error!(%error, handle, "Hosted-account index refresh after signup failed");
760            return error_response(
761                StatusCode::INTERNAL_SERVER_ERROR,
762                "server_error",
763                "Hosted-account activation could not be verified",
764            );
765        }
766        let signed_tenant = match state.hosted_account_tenant(&minted.did).await {
767            Ok(Some(signed_tenant)) => signed_tenant,
768            Ok(None) => {
769                tracing::error!(handle, did = %minted.did, "New hosted account is absent from its authority-owned index");
770                return error_response(
771                    StatusCode::INTERNAL_SERVER_ERROR,
772                    "server_error",
773                    "Hosted-account activation could not be verified",
774                );
775            }
776            Err(error) => {
777                tracing::error!(%error, handle, did = %minted.did, "New hosted account authority binding could not be verified");
778                return error_response(
779                    StatusCode::INTERNAL_SERVER_ERROR,
780                    "server_error",
781                    "Hosted-account activation could not be verified",
782                );
783            }
784        };
785        // Record the new tenant's baseline rows: explicit per-tenant
786        // deployment data for the reviewed MCP delegated exchange (the
787        // always-injected base wildcard already admits it today; this row
788        // pins the dependency per tenant), plus the HolderGate canary-read
789        // baseline. The account is already durably activated, so seeding
790        // follows the OIDC JIT precedent: best-effort, error-logged, never a
791        // second signup failure mode.
792        seed_hosted_tenant_policy_baseline(
793            &minted.did,
794            &signed_tenant,
795            state.ninep_canonical_read.as_ref(),
796        )
797        .await;
798        (handle.to_owned(), verifying_key)
799    } else if action == AUTHORIZE_ACTION {
800        // Existing-account authorize challenge:
801        // "{fingerprint}:{nonce}:{code_challenge}".
802        let challenge_str = format!(
803            "{}:{}:{}",
804            form.fingerprint, form.nonce, effective.code_challenge
805        );
806        match challenge::verify_ed25519_response_by_fingerprint(
807            user_store.as_ref(),
808            &form.fingerprint,
809            &challenge_str,
810            &form.signature,
811        )
812        .await
813        {
814            Ok((username, verifying_key)) => match user_store.get_profile(&username).await {
815                Ok(Some(profile)) if profile.active != Some(false) => (username, verifying_key),
816                Ok(Some(_)) => {
817                    return error_response(
818                        StatusCode::FORBIDDEN,
819                        "access_denied",
820                        "Account is not active",
821                    );
822                }
823                Ok(None) => {
824                    tracing::error!(
825                        username,
826                        "Credential reverse index resolved to a missing user profile"
827                    );
828                    return error_response(
829                        StatusCode::INTERNAL_SERVER_ERROR,
830                        "server_error",
831                        "Account credential binding is inconsistent",
832                    );
833                }
834                Err(error) => {
835                    tracing::error!(%error, username, "UserStore activation check failed");
836                    return error_response(
837                        StatusCode::INTERNAL_SERVER_ERROR,
838                        "server_error",
839                        "Account activation could not be verified",
840                    );
841                }
842            },
843            Err(e) => {
844                if matches!(e, challenge::ChallengeError::UserStoreError(_)) {
845                    tracing::error!(fingerprint = %form.fingerprint, "UserStore lookup error during authorize");
846                }
847                // Validate redirect_uri and re-derive client display info from the registry.
848                // Never trust the POST body for display values; return an error page if
849                // the client or redirect_uri is no longer valid.
850                let Some((client_name, redirect_host, localhost_warning)) =
851                    derive_display_info(&state, &effective.client_id, &effective.redirect_uri)
852                        .await
853                else {
854                    return Html(render_error_page(
855                        "Invalid Request",
856                        "Unknown client or redirect URI. Please restart the authorization flow.",
857                    ))
858                    .into_response();
859                };
860                let fresh_nonce = issue_nonce(&state).await;
861                state
862                    .pending_authorize_bindings
863                    .write()
864                    .await
865                    .insert(fresh_nonce.clone(), authorize_binding.clone());
866                let html = render_challenge_page(
867                    &client_name,
868                    effective.scope.as_deref().unwrap_or(""),
869                    &redirect_host,
870                    &effective.client_id,
871                    &effective.redirect_uri,
872                    &effective.code_challenge,
873                    effective.state.as_deref().unwrap_or(""),
874                    effective.resource.as_deref().unwrap_or(""),
875                    &fresh_nonce,
876                    effective.nonce.as_deref().unwrap_or(""),
877                    Some(e.message()),
878                    localhost_warning.as_deref(),
879                    "",
880                );
881                return Html(html).into_response();
882            }
883        }
884    } else {
885        return error_response(
886            StatusCode::BAD_REQUEST,
887            "invalid_request",
888            "Unknown authorize action",
889        );
890    };
891
892    // Signature valid — generate auth code
893    let mut code_bytes = [0u8; 32];
894    rand::rngs::OsRng.fill_bytes(&mut code_bytes);
895    let code = URL_SAFE_NO_PAD.encode(code_bytes);
896
897    let pending = PendingAuthCode {
898        code: code.clone(),
899        client_id: effective.client_id.clone(),
900        redirect_uri: effective.redirect_uri.clone(),
901        code_challenge: effective.code_challenge.clone(),
902        scopes: granted_scopes,
903        oidc_nonce: effective.nonce.clone(),
904        resource,
905        created_at: Instant::now(),
906        expires_at: Instant::now() + Duration::from_secs(60),
907        username: resolved_username.clone(),
908        verifying_key: Some(verifying_key),
909        // PAR-bound DPoP key thumbprint (#1113 rev2 finding 3).
910        dpop_jkt: effective.dpop_jkt.clone(),
911        // PAR-bound client-assertion key thumbprint (#1146 T3.3).
912        client_assertion_jkt: effective.client_assertion_jkt.clone(),
913    };
914
915    state
916        .pending_codes
917        .write()
918        .await
919        .insert(code.clone(), pending);
920
921    tracing::info!(
922        client_id = %effective.client_id,
923        username = %resolved_username,
924        fingerprint = %form.fingerprint,
925        redirect_uri = %effective.redirect_uri,
926        "Authorization code issued, redirecting"
927    );
928
929    // Build redirect URL using url::Url to ensure proper percent-encoding of `state`.
930    // #1113 rev2 F5: append `iss` (the issuer) to the redirect per RFC 9207
931    // / OAuth 2.1 authorization-response-iss-parameter. The AS advertises
932    // `authorization_response_iss_parameter_supported: true` — the stock
933    // atproto client throws "iss missing" if it's absent.
934    let redirect_iss = if require_atproto {
935        state.atproto_issuer_url()
936    } else {
937        state.issuer_url.clone()
938    };
939    let redirect_url = match build_authorize_redirect_url(
940        &effective.redirect_uri,
941        &code,
942        effective.state.as_deref(),
943        &redirect_iss,
944    ) {
945        Ok(u) => u,
946        Err(_) => {
947            return error_response(
948                StatusCode::INTERNAL_SERVER_ERROR,
949                "server_error",
950                "Invalid redirect_uri",
951            );
952        }
953    };
954
955    Redirect::to(&redirect_url).into_response()
956}
957
958/// Resolve an `AuthorizeQuery` into a concrete `AuthorizeParams`.
959///
960/// Two paths:
961/// - **PAR (RFC 9126):** if `request_uri` is set, look it up in
962///   `pending_par_requests`, check TTL, consume (single-use), and return the
963///   stored snapshot. If a `client_id` is also present on the URL, it must
964///   match the pushed snapshot's `client_id` (RFC 9126 §4).
965/// - **Inline:** require the same fields the legacy URL form required.
966async fn resolve_authorize_query(
967    state: &OAuthState,
968    query: AuthorizeQuery,
969) -> Result<AuthorizeParams, Response> {
970    if let Some(request_uri) = query.request_uri.as_deref() {
971        let entry = {
972            let mut store = state.pending_par_requests.write().await;
973            store.remove(request_uri)
974        };
975        let Some(entry) = entry else {
976            return Err(error_response(
977                StatusCode::BAD_REQUEST,
978                "invalid_request",
979                "Unknown or already-consumed request_uri",
980            ));
981        };
982        if entry.is_expired() {
983            return Err(error_response(
984                StatusCode::BAD_REQUEST,
985                "invalid_request",
986                "request_uri expired",
987            ));
988        }
989        // RFC 9126 §4: client_id MAY appear alongside request_uri; if present,
990        // it MUST match the pushed snapshot.
991        if let Some(client_id) = query.client_id.as_deref() {
992            if client_id != entry.params.client_id {
993                return Err(error_response(
994                    StatusCode::BAD_REQUEST,
995                    "invalid_request",
996                    "client_id does not match pushed authorization request",
997                ));
998            }
999        }
1000        return Ok(entry.params);
1001    }
1002
1003    // Enforce PAR-required mode (RFC 9126 §10.1): when the server requires PAR,
1004    // inline parameters without a request_uri must be rejected.
1005    if state.require_pushed_authorization_requests {
1006        return Err(error_response(
1007            StatusCode::BAD_REQUEST,
1008            "invalid_request",
1009            "This server requires a Pushed Authorization Request (RFC 9126). \
1010             Submit your authorization parameters to /oauth/par first and use the returned request_uri.",
1011        ));
1012    }
1013    // #1113 rev2 F6: the atproto profile mandates PAR — an inline (non-PAR)
1014    // authorization request that includes the `atproto` scope is rejected.
1015    // This keeps inline non-atproto auth working while enforcing the atproto
1016    // strict profile (DPoP binding at PAR).
1017    if let Some(ref scope_str) = query.scope {
1018        if super::state::atproto_profile_active(
1019            &scope_str
1020                .split_whitespace()
1021                .map(str::to_owned)
1022                .collect::<Vec<_>>(),
1023        ) {
1024            return Err(error_response(
1025                StatusCode::BAD_REQUEST,
1026                "invalid_request",
1027                "The atproto profile requires a Pushed Authorization Request (RFC 9126) with a DPoP proof.",
1028            ));
1029        }
1030    }
1031
1032    // Inline path: enforce the originally-required fields.
1033    let AuthorizeQuery {
1034        client_id,
1035        redirect_uri,
1036        code_challenge,
1037        code_challenge_method,
1038        response_type,
1039        state: state_param,
1040        scope,
1041        resource,
1042        nonce,
1043        ..
1044    } = query;
1045    let missing = |field: &str| {
1046        error_response(
1047            StatusCode::BAD_REQUEST,
1048            "invalid_request",
1049            &format!("{field} is required"),
1050        )
1051    };
1052    Ok(AuthorizeParams {
1053        client_id: client_id.ok_or_else(|| missing("client_id"))?,
1054        redirect_uri: redirect_uri.ok_or_else(|| missing("redirect_uri"))?,
1055        code_challenge: code_challenge.ok_or_else(|| missing("code_challenge"))?,
1056        code_challenge_method: code_challenge_method
1057            .ok_or_else(|| missing("code_challenge_method"))?,
1058        response_type: response_type.ok_or_else(|| missing("response_type"))?,
1059        state: state_param,
1060        scope,
1061        resource,
1062        nonce,
1063        dpop_jkt: None,
1064        client_assertion_jkt: None,
1065    })
1066}
1067
1068fn fresh_nonce() -> String {
1069    let mut nonce_bytes = [0u8; 32];
1070    rand::rngs::OsRng.fill_bytes(&mut nonce_bytes);
1071    URL_SAFE_NO_PAD.encode(nonce_bytes)
1072}
1073
1074/// Generate a fresh nonce and record it in `pending_nonces` with a 5-min expiry.
1075async fn issue_nonce(state: &OAuthState) -> String {
1076    let nonce = fresh_nonce();
1077    let expiry = Instant::now() + Duration::from_secs(300);
1078    state
1079        .pending_nonces
1080        .write()
1081        .await
1082        .insert(nonce.clone(), expiry);
1083    nonce
1084}
1085
1086/// Re-derive client display name and redirect host from the registry, validating
1087/// that `redirect_uri` is registered for the client.
1088///
1089/// Returns `None` if the client is not in the registry or `redirect_uri` is not
1090/// among its registered URIs — callers must return an error page in that case.
1091/// This ensures that POST body values are never trusted for UI display without
1092/// first being validated against the canonical server-side registry.
1093pub(crate) async fn derive_display_info(
1094    state: &OAuthState,
1095    client_id: &str,
1096    redirect_uri: &str,
1097) -> Option<(String, String, Option<String>)> {
1098    // CIMD-shaped client_ids (HTTPS URLs) live in cimd_cache; DCR-issued
1099    // UUIDs live in state.clients. Try CIMD first since the cache hit
1100    // path is cheap and CIMD URLs never collide with DCR UUIDs.
1101    let client = if client_id.starts_with("https://") {
1102        state.cimd_cache.get(client_id).await?
1103    } else {
1104        state.clients.read().await.get(client_id)?.clone()
1105    };
1106
1107    // Validate redirect_uri against the client's registered URIs before displaying it.
1108    if !validate_redirect_uri(redirect_uri, &client.redirect_uris) {
1109        return None;
1110    }
1111
1112    let client_name = client
1113        .client_name
1114        .clone()
1115        .unwrap_or_else(|| client_id.to_owned());
1116    let redirect_host = url::Url::parse(redirect_uri)
1117        .ok()
1118        .and_then(|u| u.host_str().map(std::borrow::ToOwned::to_owned))
1119        .unwrap_or_else(|| redirect_uri.to_owned());
1120    let localhost_warning = compute_localhost_warning(&client.redirect_uris);
1121    Some((client_name, redirect_host, localhost_warning))
1122}
1123
1124/// Resolve a client's declared scope tokens for `invalid_scope` validation
1125/// (#1113 rev2 finding 4). CIMD-shaped client_ids (HTTPS URLs) resolve via
1126/// the CIMD cache; DCR UUIDs via the registry.
1127///
1128/// #1146 T1.1: a CIMD cache miss RE-RESOLVES the client (policy check +
1129/// metadata re-fetch) instead of silently dropping the declared scope
1130/// ceiling — an aged-out cache entry must never degrade to "no
1131/// restriction". Returns `None` (fail closed) when the client cannot be
1132/// resolved at all; `Some(vec![])` only when a resolved client declared
1133/// no scope ceiling.
1134async fn resolve_client_declared_scopes(
1135    state: &OAuthState,
1136    client_id: &str,
1137) -> Option<Vec<String>> {
1138    let client = if client_id.starts_with("https://") {
1139        match state.cimd_cache.get(client_id).await {
1140            Some(c) => c,
1141            // Cache miss: re-resolve rather than dropping the ceiling.
1142            // resolve_cimd_client re-runs the federation:register policy
1143            // check and re-fetches metadata; any failure fails closed.
1144            None => resolve_cimd_client(state, client_id).await.ok()?,
1145        }
1146    } else {
1147        state.clients.read().await.get(client_id)?.clone()
1148    };
1149    Some(client.declared_scopes())
1150}
1151
1152/// Validate the requested scopes against current server and client policy.
1153/// Reused before rendering provider choices and before external provisioning.
1154pub(crate) async fn validate_authorize_scopes(
1155    state: &OAuthState,
1156    request: &AuthorizeParams,
1157) -> Result<Vec<String>, Response> {
1158    let requested: Vec<String> = request
1159        .scope
1160        .as_deref()
1161        .unwrap_or("")
1162        .split_whitespace()
1163        .map(str::to_owned)
1164        .collect();
1165    let Some(declared) = resolve_client_declared_scopes(state, &request.client_id).await else {
1166        return Err(error_response(
1167            StatusCode::BAD_REQUEST,
1168            "invalid_scope",
1169            "Requested scope is not supported or not declared by the client",
1170        ));
1171    };
1172    super::state::validate_requested_scopes(
1173        &requested,
1174        &state.server_supported_scopes(),
1175        if declared.is_empty() {
1176            None
1177        } else {
1178            Some(&declared)
1179        },
1180        super::state::atproto_profile_active(&requested),
1181    )
1182    .map_err(|_| {
1183        error_response(
1184            StatusCode::BAD_REQUEST,
1185            "invalid_scope",
1186            "Requested scope is not supported or not declared by the client",
1187        )
1188    })
1189}
1190
1191/// Build the authorization redirect URL (#1113 rev2 F5).
1192/// Pure function so the `iss` query parameter is unit-testable without
1193/// constructing an OAuthState. RFC 9207 / OAuth 2.1 iss-parameter support
1194/// requires `iss` on every authorization-code redirect.
1195pub(crate) fn build_authorize_redirect_url(
1196    redirect_uri: &str,
1197    code: &str,
1198    state: Option<&str>,
1199    iss: &str,
1200) -> Result<String, ()> {
1201    let mut u = url::Url::parse(redirect_uri).map_err(|_| ())?;
1202    {
1203        let mut q = u.query_pairs_mut();
1204        q.append_pair("code", code);
1205        q.append_pair("iss", iss);
1206        if let Some(s) = state {
1207            q.append_pair("state", s);
1208        }
1209    }
1210    Ok(u.to_string())
1211}
1212
1213/// Build the consent-screen localhost warning when every registered
1214/// redirect URI is loopback. Returns `None` if at least one non-loopback
1215/// URI is registered (the client can prove ownership via that URI).
1216///
1217/// MCP 2025-11-25 § Localhost Redirect URI Risks: a malicious app on the
1218/// same host can claim any localhost port, so a localhost-only client
1219/// cannot be cryptographically distinguished from an impostor. Users
1220/// SHOULD see a clear warning.
1221fn compute_localhost_warning(redirect_uris: &[String]) -> Option<String> {
1222    if redirect_uris.is_empty() {
1223        return None;
1224    }
1225    let all_loopback = redirect_uris
1226        .iter()
1227        .all(|u| super::registration::is_loopback_uri(u));
1228    if !all_loopback {
1229        return None;
1230    }
1231    Some(format!(
1232        "This application only redirects to localhost. \
1233         Any program running on this machine can claim to be it — \
1234         only authorize if you started this flow yourself. \
1235         ({} loopback URI{} registered)",
1236        redirect_uris.len(),
1237        if redirect_uris.len() == 1 { "" } else { "s" },
1238    ))
1239}
1240
1241fn error_response(status: StatusCode, error: &str, description: &str) -> Response {
1242    (
1243        status,
1244        axum::Json(serde_json::json!({
1245            "error": error,
1246            "error_description": description,
1247        })),
1248    )
1249        .into_response()
1250}
1251
1252/// Render an error page (HTML) for configuration errors.
1253fn render_error_page(title: &str, message: &str) -> String {
1254    format!(
1255        r#"<!DOCTYPE html>
1256<html lang="en">
1257<head>
1258<meta charset="utf-8">
1259<meta name="viewport" content="width=device-width, initial-scale=1">
1260<title>{title_esc} — hyprstream</title>
1261<style>
1262  body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
1263         max-width: 480px; margin: 60px auto; padding: 0 20px; color: #1a1a1a; background: #fafafa; }}
1264  .card {{ background: #fff; border-radius: 12px; padding: 32px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }}
1265  h1 {{ font-size: 1.4rem; margin: 0 0 8px; color: #cc0000; }}
1266  p {{ color: #555; line-height: 1.5; }}
1267</style>
1268</head>
1269<body>
1270<div class="card">
1271  <h1>{title_esc}</h1>
1272  <p>{message_esc}</p>
1273</div>
1274</body>
1275</html>"#,
1276        title_esc = html_escape(title),
1277        message_esc = html_escape(message),
1278    )
1279}
1280
1281/// Render the Ed25519 challenge form (replaces the old Approve/Deny consent page).
1282#[allow(clippy::too_many_arguments)]
1283fn render_challenge_page(
1284    client_name: &str,
1285    scopes: &str,
1286    redirect_host: &str,
1287    client_id: &str,
1288    redirect_uri: &str,
1289    code_challenge: &str,
1290    state: &str,
1291    resource: &str,
1292    nonce: &str,
1293    oidc_nonce: &str,
1294    error: Option<&str>,
1295    localhost_warning: Option<&str>,
1296    provider_buttons: &str,
1297) -> String {
1298    let error_html = match error {
1299        Some(msg) => format!(r#"<div class="error">{}</div>"#, html_escape(msg)),
1300        None => String::new(),
1301    };
1302    let warning_html = match localhost_warning {
1303        Some(msg) => format!(r#"<div class="warn">{}</div>"#, html_escape(msg)),
1304        None => String::new(),
1305    };
1306
1307    format!(
1308        r#"<!DOCTYPE html>
1309<html lang="en">
1310<head>
1311<meta charset="utf-8">
1312<meta name="viewport" content="width=device-width, initial-scale=1">
1313<title>Authorize — hyprstream</title>
1314<style>
1315  body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
1316         max-width: 520px; margin: 60px auto; padding: 0 20px; color: #1a1a1a; background: #fafafa; }}
1317  .card {{ background: #fff; border-radius: 12px; padding: 32px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }}
1318  h1 {{ font-size: 1.4rem; margin: 0 0 8px; }}
1319  .client {{ color: #0066cc; font-weight: 600; }}
1320  .scopes {{ background: #f5f5f5; border-radius: 8px; padding: 12px 16px; margin: 16px 0;
1321             font-family: monospace; font-size: 0.9rem; }}
1322  .redirect {{ font-size: 0.85rem; color: #666; margin: 12px 0; }}
1323  .error {{ background: #fff0f0; color: #cc0000; border-radius: 8px; padding: 12px 16px;
1324            margin: 12px 0; font-size: 0.9rem; }}
1325  .warn {{ background: #fff7e6; color: #8a5a00; border-left: 3px solid #d4960c;
1326           border-radius: 0 8px 8px 0; padding: 12px 14px; margin: 12px 0; font-size: 0.88rem; }}
1327  .step {{ background: #f0f6ff; border-left: 3px solid #0066cc; padding: 10px 14px;
1328           margin: 12px 0; border-radius: 0 6px 6px 0; font-size: 0.88rem; color: #333; }}
1329  code {{ background: #f0f0f0; padding: 2px 6px; border-radius: 4px; font-size: 0.9em; word-break: break-all; }}
1330  label {{ display: block; margin-top: 16px; color: #333; font-size: 0.9rem; font-weight: 500; }}
1331  input[type=text] {{ width: 100%; padding: 10px; font-size: 0.9rem; border: 2px solid #ddd;
1332                       border-radius: 8px; box-sizing: border-box; margin-top: 4px; }}
1333  input[type=text]:focus {{ border-color: #0066cc; outline: none; }}
1334  button {{ width: 100%; padding: 12px; border: none; border-radius: 8px; font-size: 1rem;
1335           cursor: pointer; font-weight: 500; background: #0066cc; color: #fff; margin-top: 24px; }}
1336  button:hover {{ background: #0052a3; }}
1337</style>
1338</head>
1339<body>
1340<div class="card">
1341  <h1>Authorize Application</h1>
1342  <p><span class="client">{client_name_esc}</span> wants to access your hyprstream resources.</p>
1343  <div class="scopes">
1344    <strong>Requested scopes:</strong><br>
1345    {scopes_display}
1346  </div>
1347  <p class="redirect">Will redirect to: <code>{redirect_host_esc}</code></p>
1348  {warning_html}
1349  {error_html}
1350  {provider_buttons}
1351  <div class="step">
1352    <strong>Sign the challenge on your workstation:</strong><br/>
1353    <code>hyprstream sign-challenge --nonce {nonce_esc} --code-challenge {code_challenge_esc}</code><br/>
1354    Copy the printed <em>Fingerprint</em> and <em>Signature</em> below.
1355  </div>
1356  <form method="post" action="/oauth/authorize">
1357    <input type="hidden" name="action" value="authorize">
1358    <input type="hidden" name="client_id" value="{client_id_val}">
1359    <input type="hidden" name="redirect_uri" value="{redirect_uri_val}">
1360    <input type="hidden" name="code_challenge" value="{code_challenge_val}">
1361    <input type="hidden" name="scope" value="{scope_val}">
1362    <input type="hidden" name="state" value="{state_val}">
1363    <input type="hidden" name="resource" value="{resource_val}">
1364    <input type="hidden" name="nonce" value="{nonce_val}">
1365    <input type="hidden" name="oidc_nonce" value="{oidc_nonce_val}">
1366    <label>Key fingerprint (SHA256:...):
1367      <input type="text" name="fingerprint" required autocomplete="off" autofocus
1368             placeholder="SHA256:..." spellcheck="false"/>
1369    </label>
1370    <label>Signature (base64, 88 chars):
1371      <input type="text" name="signature" required size="88" autocomplete="off"
1372             placeholder="base64-encoded Ed25519 signature"/>
1373    </label>
1374    <button type="submit">Authorize</button>
1375  </form>
1376</div>
1377</body>
1378</html>"#,
1379        client_name_esc = html_escape(client_name),
1380        scopes_display = scopes
1381            .split_whitespace()
1382            .map(|s| format!("<code>{}</code>", html_escape(s)))
1383            .collect::<Vec<_>>()
1384            .join(", "),
1385        redirect_host_esc = html_escape(redirect_host),
1386        warning_html = warning_html,
1387        error_html = error_html,
1388        provider_buttons = provider_buttons,
1389        nonce_esc = html_escape(nonce),
1390        code_challenge_esc = html_escape(code_challenge),
1391        client_id_val = html_escape(client_id),
1392        redirect_uri_val = html_escape(redirect_uri),
1393        code_challenge_val = html_escape(code_challenge),
1394        scope_val = html_escape(scopes),
1395        state_val = html_escape(state),
1396        resource_val = html_escape(resource),
1397        nonce_val = html_escape(nonce),
1398        oidc_nonce_val = html_escape(oidc_nonce),
1399    )
1400}
1401
1402#[cfg(test)]
1403#[allow(clippy::unwrap_used, clippy::expect_used)]
1404mod tests {
1405    use super::*;
1406    use ed25519_dalek::Signer as _;
1407
1408    #[test]
1409    fn localhost_warning_fires_when_all_loopback() {
1410        let uris = vec![
1411            "http://127.0.0.1:3000/cb".to_owned(),
1412            "http://localhost:8080/cb".to_owned(),
1413        ];
1414        let warn = compute_localhost_warning(&uris).unwrap();
1415        assert!(warn.contains("localhost"));
1416        assert!(warn.contains('2'), "should mention the count");
1417    }
1418
1419    #[test]
1420    fn localhost_warning_suppressed_when_any_public_uri() {
1421        let uris = vec![
1422            "http://127.0.0.1:3000/cb".to_owned(),
1423            "https://app.example.com/cb".to_owned(),
1424        ];
1425        assert!(compute_localhost_warning(&uris).is_none());
1426    }
1427
1428    #[test]
1429    fn localhost_warning_singular_count_grammar() {
1430        let uris = vec!["http://localhost:3000/cb".to_owned()];
1431        let warn = compute_localhost_warning(&uris).unwrap();
1432        assert!(warn.contains("1 loopback URI registered"));
1433    }
1434
1435    #[test]
1436    fn localhost_warning_empty_returns_none() {
1437        assert!(compute_localhost_warning(&[]).is_none());
1438    }
1439
1440    #[test]
1441    fn signup_proof_challenge_is_domain_separated_and_transaction_bound() {
1442        let authorize_nonce = fresh_nonce();
1443        let other_nonce = fresh_nonce();
1444        let challenge =
1445            signup_proof_challenge("alice", "SHA256:key", &authorize_nonce, "pkce-challenge");
1446        assert!(challenge.starts_with(SIGNUP_PROOF_DOMAIN));
1447        assert_ne!(
1448            challenge,
1449            signup_proof_challenge("bob", "SHA256:key", &authorize_nonce, "pkce-challenge")
1450        );
1451        assert_ne!(
1452            challenge,
1453            signup_proof_challenge("alice", "SHA256:key", &other_nonce, "pkce-challenge")
1454        );
1455        assert_ne!(
1456            challenge,
1457            signup_proof_challenge("alice", "SHA256:key", &authorize_nonce, "other-pkce")
1458        );
1459    }
1460
1461    #[tokio::test]
1462    async fn signup_resumes_after_crash_after_genesis_before_activation() -> anyhow::Result<()> {
1463        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
1464
1465        use async_trait::async_trait;
1466        use base64::engine::general_purpose::STANDARD;
1467        use hyprstream_rpc::rpc_client::RpcClientImpl;
1468        use hyprstream_rpc::signer::LocalSigner;
1469        use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
1470
1471        use crate::auth::{RocksDbUserStore, UserStore};
1472        use crate::services::oauth::identity_registration::{
1473            DidWebOriginAllowlist, FederatedIdentityIntake, HostedRegistrationMint,
1474            IdentityConnectTimeResolver, IdentityRegistrationApi, RegistrationGenesisSigner,
1475        };
1476
1477        struct SignupMint {
1478            calls: AtomicUsize,
1479            fail_after_publish_once: AtomicBool,
1480        }
1481        impl HostedRegistrationMint for SignupMint {
1482            fn mint(
1483                &self,
1484                request: &hyprstream_pds_service::hosted_account_mint::HostedAccountRegistrationRequest,
1485                _signer: &dyn hyprstream_pds_service::hosted_account_mint::HostedAccountGenesisSigner,
1486            ) -> anyhow::Result<
1487                hyprstream_pds_service::hosted_account_mint::HostedAccountRegistrationResult,
1488            > {
1489                self.calls.fetch_add(1, Ordering::SeqCst);
1490                if self.fail_after_publish_once.swap(false, Ordering::SeqCst) {
1491                    anyhow::bail!("simulated crash after durable PDS genesis publication");
1492                }
1493                Ok(
1494                    hyprstream_pds_service::hosted_account_mint::HostedAccountRegistrationResult {
1495                        handle: format!("at://{}.accounts.example.test", request.handle()),
1496                        did: format!("did:web:{}.accounts.example.test", request.handle()),
1497                        pds_endpoint: "https://pds.example.test".to_owned(),
1498                        quic_url: "https://pds.example.test:4433".to_owned(),
1499                        cert_hash: "fixture-cert-hash".to_owned(),
1500                    },
1501                )
1502            }
1503        }
1504
1505        struct UnusedSigner;
1506        impl RegistrationGenesisSigner for UnusedSigner {
1507            fn sign_genesis(
1508                &self,
1509                _caller: &str,
1510                _operator_manual: bool,
1511                _unsigned: &hyprstream_pds::UnsignedGenesisDidOp,
1512            ) -> anyhow::Result<hyprstream_pds::DidOpSignature> {
1513                anyhow::bail!("fake mint must not invoke the signer")
1514            }
1515        }
1516
1517        struct UnusedIntake;
1518        #[async_trait]
1519        impl FederatedIdentityIntake for UnusedIntake {
1520            async fn intake(
1521                &self,
1522                _did: &str,
1523            ) -> anyhow::Result<hyprstream_pds_service::federation_intake::InventoryEntry>
1524            {
1525                anyhow::bail!("federation intake is outside this test")
1526            }
1527        }
1528
1529        struct UnusedResolver;
1530        impl IdentityConnectTimeResolver for UnusedResolver {
1531            fn recognizes(&self, _did: &str) -> bool {
1532                false
1533            }
1534
1535            fn resolve(
1536                &self,
1537                _did: &str,
1538            ) -> anyhow::Result<hyprstream_discovery::ConnectTimeDiscovery> {
1539                anyhow::bail!("connect-time resolution is outside this test")
1540            }
1541
1542            fn hosted_tenant(&self, did: &str) -> anyhow::Result<Option<String>> {
1543                anyhow::ensure!(
1544                    did == "did:web:alice.accounts.example.test",
1545                    "unexpected hosted DID in signup fixture"
1546                );
1547                Ok(Some("accounts.example.test".to_owned()))
1548            }
1549        }
1550
1551        let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x51; 32]);
1552        let remote_key = ed25519_dalek::SigningKey::from_bytes(&[0x52; 32]).verifying_key();
1553        let make_client = || {
1554            Arc::new(
1555                RpcClientImpl::new(
1556                    LocalSigner::new(signing_key.clone()),
1557                    LazyUdsTransport::new("/dev/null/oauth-signup-authorize-test.sock".into()),
1558                    Some(remote_key),
1559                )
1560                .with_response_verify_policy(hyprstream_rpc::crypto::CryptoPolicy::Classical),
1561            )
1562        };
1563        let mut config = crate::config::OAuthConfig::default();
1564        config.external_url = Some("https://pds.example.test".to_owned());
1565        let user_dir = tempfile::TempDir::new()?;
1566        let user_store = Arc::new(RocksDbUserStore::open(user_dir.path())?);
1567        let mint = Arc::new(SignupMint {
1568            calls: AtomicUsize::new(0),
1569            fail_after_publish_once: AtomicBool::new(true),
1570        });
1571        let identity_api = Arc::new(IdentityRegistrationApi::new(
1572            mint.clone(),
1573            Arc::new(UnusedSigner),
1574            Arc::new(UnusedIntake),
1575            Arc::new(UnusedResolver),
1576            DidWebOriginAllowlist::new(std::iter::empty::<&str>())?,
1577            Arc::new(crate::server::middleware::RateLimiter::new(10, 60)),
1578        ));
1579        let state = Arc::new(
1580            OAuthState::new(
1581                &config,
1582                hyprstream_rpc_std::policy_client::PolicyClient::new(make_client()),
1583                hyprstream_rpc_std::discovery_client::DiscoveryClient::new(make_client()),
1584                signing_key.verifying_key().to_bytes(),
1585            )
1586            .with_user_store(crate::auth::ProductionUserStore::for_test(
1587                user_store.clone(),
1588            ))
1589            .with_identity_registration_api(identity_api)
1590            .with_hosted_account_zone(crate::account::AccountZone::new("accounts.example.test")?),
1591        );
1592        state.clients.write().await.insert(
1593            "signup-client".to_owned(),
1594            super::super::state::RegisteredClient {
1595                client_id: "signup-client".to_owned(),
1596                redirect_uris: vec!["https://client.example/callback".to_owned()],
1597                client_name: Some("Signup Client".to_owned()),
1598                client_uri: None,
1599                logo_uri: None,
1600                grant_types: vec!["authorization_code".to_owned()],
1601                response_types: vec!["code".to_owned()],
1602                token_endpoint_auth_method: Some("none".to_owned()),
1603                jwks: None,
1604                jwks_uri: None,
1605                hyprstream_node_did: None,
1606                scope: Some("atproto".to_owned()),
1607                dpop_bound_access_tokens: Some(true),
1608                is_cimd: false,
1609                registered_at: Instant::now(),
1610            },
1611        );
1612
1613        let nonce = fresh_nonce();
1614        let code_challenge = "signup-pkce-challenge".to_owned();
1615        let request = AuthorizeParams {
1616            client_id: "signup-client".to_owned(),
1617            redirect_uri: "https://client.example/callback".to_owned(),
1618            code_challenge: code_challenge.clone(),
1619            code_challenge_method: "S256".to_owned(),
1620            response_type: "code".to_owned(),
1621            state: Some("signup-state".to_owned()),
1622            scope: Some("atproto".to_owned()),
1623            resource: Some("https://pds.example.test".to_owned()),
1624            nonce: None,
1625            dpop_jkt: Some("par-verified-dpop-thumbprint".to_owned()),
1626            client_assertion_jkt: None,
1627        };
1628        state
1629            .pending_nonces
1630            .write()
1631            .await
1632            .insert(nonce.clone(), Instant::now() + Duration::from_secs(300));
1633        state.pending_authorize_bindings.write().await.insert(
1634            nonce.clone(),
1635            super::super::state::AuthorizeBinding { request },
1636        );
1637
1638        let vault_key = ed25519_dalek::SigningKey::from_bytes(&[0x53; 32]);
1639        let public_key = STANDARD.encode(vault_key.verifying_key().as_bytes());
1640        let fingerprint = crate::auth::pubkey_fingerprint(&vault_key.verifying_key());
1641        let challenge = signup_proof_challenge("alice", &fingerprint, &nonce, &code_challenge);
1642        let signature = STANDARD.encode(vault_key.sign(&challenge).to_bytes());
1643        let response = authorize_post(
1644            State(state.clone()),
1645            Ok(Form(ConsentForm {
1646                action: Some(SIGNUP_ACTION.to_owned()),
1647                client_id: "signup-client".to_owned(),
1648                redirect_uri: "https://client.example/callback".to_owned(),
1649                code_challenge,
1650                scope: "atproto".to_owned(),
1651                state: Some("signup-state".to_owned()),
1652                resource: Some("https://pds.example.test".to_owned()),
1653                nonce,
1654                fingerprint: fingerprint.clone(),
1655                signature,
1656                handle: Some("alice".to_owned()),
1657                account_public_key: Some(public_key),
1658                oidc_nonce: None,
1659            })),
1660        )
1661        .await;
1662
1663        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
1664        assert_eq!(mint.calls.load(Ordering::SeqCst), 1);
1665        let staged = user_store.get_profile("alice").await?.unwrap();
1666        assert_eq!(staged.active, Some(false));
1667        assert_eq!(
1668            user_store.get_pubkey_user(&fingerprint).await?,
1669            Some("alice".to_owned())
1670        );
1671        assert!(state.pending_codes.read().await.is_empty());
1672
1673        // A fresh, fully verified OAuth authorize transaction for the exact
1674        // same handle/key resumes minting and performs final activation.
1675        let retry_nonce = fresh_nonce();
1676        let retry_code_challenge = "signup-pkce-challenge-retry".to_owned();
1677        let retry_request = AuthorizeParams {
1678            client_id: "signup-client".to_owned(),
1679            redirect_uri: "https://client.example/callback".to_owned(),
1680            code_challenge: retry_code_challenge.clone(),
1681            code_challenge_method: "S256".to_owned(),
1682            response_type: "code".to_owned(),
1683            state: Some("signup-state-retry".to_owned()),
1684            scope: Some("atproto".to_owned()),
1685            resource: Some("https://pds.example.test".to_owned()),
1686            nonce: None,
1687            dpop_jkt: Some("par-verified-dpop-thumbprint".to_owned()),
1688            client_assertion_jkt: None,
1689        };
1690        state.pending_nonces.write().await.insert(
1691            retry_nonce.clone(),
1692            Instant::now() + Duration::from_secs(300),
1693        );
1694        state.pending_authorize_bindings.write().await.insert(
1695            retry_nonce.clone(),
1696            super::super::state::AuthorizeBinding {
1697                request: retry_request,
1698            },
1699        );
1700        let retry_challenge =
1701            signup_proof_challenge("alice", &fingerprint, &retry_nonce, &retry_code_challenge);
1702        let retry_signature = STANDARD.encode(vault_key.sign(&retry_challenge).to_bytes());
1703        let retry_response = authorize_post(
1704            State(state.clone()),
1705            Ok(Form(ConsentForm {
1706                action: Some(SIGNUP_ACTION.to_owned()),
1707                client_id: "signup-client".to_owned(),
1708                redirect_uri: "https://client.example/callback".to_owned(),
1709                code_challenge: retry_code_challenge,
1710                scope: "atproto".to_owned(),
1711                state: Some("signup-state-retry".to_owned()),
1712                resource: Some("https://pds.example.test".to_owned()),
1713                nonce: retry_nonce,
1714                fingerprint: fingerprint.clone(),
1715                signature: retry_signature,
1716                handle: Some("alice".to_owned()),
1717                account_public_key: Some(STANDARD.encode(vault_key.verifying_key().as_bytes())),
1718                oidc_nonce: None,
1719            })),
1720        )
1721        .await;
1722
1723        assert_eq!(retry_response.status(), StatusCode::SEE_OTHER);
1724        assert_eq!(mint.calls.load(Ordering::SeqCst), 2);
1725        let profile = user_store.get_profile("alice").await?.unwrap();
1726        assert_eq!(
1727            profile.atproto_did.as_deref(),
1728            Some("did:web:alice.accounts.example.test")
1729        );
1730        assert_eq!(profile.key_custody, Some(AccountKeyCustody::SelfCustody));
1731        assert_eq!(profile.active, Some(true));
1732        assert!(profile.external_identities.is_empty());
1733        assert_eq!(
1734            user_store.get_pubkey_user(&fingerprint).await?,
1735            Some("alice".to_owned())
1736        );
1737        let codes = state.pending_codes.read().await;
1738        assert_eq!(codes.len(), 1);
1739        let pending = codes.values().next().unwrap();
1740        assert_eq!(pending.username, "alice");
1741        assert_eq!(
1742            pending.dpop_jkt.as_deref(),
1743            Some("par-verified-dpop-thumbprint")
1744        );
1745        assert!(state.sessions.get("nonexistent").await.is_none());
1746        Ok(())
1747    }
1748
1749    /// #1113 rev2 F5: the authorization redirect URL MUST include `iss`
1750    /// (RFC 9207). The stock atproto client throws "iss missing" when
1751    /// `authorization_response_iss_parameter_supported: true` is advertised.
1752    #[test]
1753    fn authorize_redirect_includes_iss_parameter() {
1754        let url = build_authorize_redirect_url(
1755            "https://client.example/cb",
1756            "authcode123",
1757            Some("xyz"),
1758            "https://pds.example.com",
1759        )
1760        .unwrap();
1761        let parsed = url::Url::parse(&url).unwrap();
1762        assert_eq!(
1763            parsed.query_pairs().find(|(k, _)| k == "iss"),
1764            Some(("iss".into(), "https://pds.example.com".into())),
1765            "redirect MUST include iss: {url}"
1766        );
1767        assert_eq!(
1768            parsed.query_pairs().find(|(k, _)| k == "code"),
1769            Some(("code".into(), "authcode123".into()))
1770        );
1771    }
1772
1773    #[test]
1774    fn external_oidc_redirect_preserves_existing_query_and_encodes_state() {
1775        let url = build_authorize_redirect_url(
1776            "https://client.example/cb?existing=1#fragment",
1777            "code",
1778            Some("a&b=c"),
1779            "https://issuer.example",
1780        )
1781        .unwrap();
1782        let parsed = url::Url::parse(&url).unwrap();
1783        assert_eq!(parsed.fragment(), Some("fragment"));
1784        let pairs: Vec<_> = parsed.query_pairs().collect();
1785        assert!(pairs.contains(&("existing".into(), "1".into())));
1786        assert!(pairs.contains(&("code".into(), "code".into())));
1787        assert!(pairs.contains(&("state".into(), "a&b=c".into())));
1788        assert!(pairs.contains(&("iss".into(), "https://issuer.example".into())));
1789    }
1790
1791    /// #1113 rev2 F5: iss is canonicalized to exact origin (no trailing slash).
1792    #[test]
1793    fn authorize_redirect_iss_is_canonical_origin() {
1794        let url = build_authorize_redirect_url(
1795            "https://client.example/cb",
1796            "code",
1797            None,
1798            "https://pds.example.com",
1799        )
1800        .unwrap();
1801        let parsed = url::Url::parse(&url).unwrap();
1802        let iss = parsed
1803            .query_pairs()
1804            .find(|(k, _)| k == "iss")
1805            .map(|(_, v)| v.to_string())
1806            .unwrap();
1807        assert_eq!(iss, "https://pds.example.com");
1808        assert!(
1809            !iss.ends_with('/'),
1810            "iss must be origin (no trailing slash)"
1811        );
1812    }
1813
1814    /// #1146 T1.1: `resolve_client_declared_scopes` must re-resolve a CIMD
1815    /// client on cache miss and fail closed (`None`) when the client cannot
1816    /// be resolved — never silently degrade to "no scope restriction".
1817    #[tokio::test]
1818    async fn external_oidc_scope_validation_and_client_resolution_fail_closed() {
1819        use hyprstream_rpc::crypto::CryptoPolicy;
1820        use hyprstream_rpc::rpc_client::RpcClientImpl;
1821        use hyprstream_rpc::signer::LocalSigner;
1822        use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
1823
1824        let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x41; 32]);
1825        let remote_key = ed25519_dalek::SigningKey::from_bytes(&[0x42; 32]).verifying_key();
1826        let make_client = || {
1827            Arc::new(
1828                RpcClientImpl::new(
1829                    LocalSigner::new(signing_key.clone()),
1830                    LazyUdsTransport::new("/dev/null/oauth-scope-resolve-test.sock".into()),
1831                    Some(remote_key),
1832                )
1833                .with_response_verify_policy(CryptoPolicy::Classical),
1834            )
1835        };
1836        let mut config = crate::config::OAuthConfig::default();
1837        config.default_scopes.push("openid".to_owned());
1838        let state = OAuthState::new(
1839            &config,
1840            hyprstream_rpc_std::policy_client::PolicyClient::new(make_client()),
1841            hyprstream_rpc_std::discovery_client::DiscoveryClient::new(make_client()),
1842            signing_key.verifying_key().to_bytes(),
1843        );
1844
1845        let make_registered = |client_id: &str, scope: Option<&str>, is_cimd: bool| {
1846            crate::services::oauth::state::RegisteredClient {
1847                client_id: client_id.to_owned(),
1848                redirect_uris: vec!["https://app.example.com/cb".to_owned()],
1849                client_name: None,
1850                client_uri: None,
1851                logo_uri: None,
1852                grant_types: vec![],
1853                response_types: vec![],
1854                token_endpoint_auth_method: None,
1855                jwks: None,
1856                jwks_uri: None,
1857                hyprstream_node_did: None,
1858                scope: scope.map(str::to_owned),
1859                dpop_bound_access_tokens: None,
1860                is_cimd,
1861                registered_at: Instant::now(),
1862            }
1863        };
1864
1865        // Unknown DCR client → fail closed (was: empty vec = no restriction).
1866        assert!(
1867            resolve_client_declared_scopes(&state, "no-such-client")
1868                .await
1869                .is_none(),
1870            "unknown DCR client must fail closed"
1871        );
1872
1873        // CIMD cache miss on an unresolvable client_id → re-resolve attempt
1874        // fails (policy RPC unreachable / fetch fails) → fail closed.
1875        assert!(
1876            resolve_client_declared_scopes(&state, "https://unresolvable.example.test/cimd.json")
1877                .await
1878                .is_none(),
1879            "unresolvable CIMD client must fail closed, not drop the ceiling"
1880        );
1881
1882        // DCR registry hit → declared scopes (empty vec = declared no ceiling).
1883        state.clients.write().await.insert(
1884            "dcr-client".to_owned(),
1885            make_registered("dcr-client", Some("atproto"), false),
1886        );
1887        assert_eq!(
1888            resolve_client_declared_scopes(&state, "dcr-client").await,
1889            Some(vec!["atproto".to_owned()])
1890        );
1891
1892        // CIMD cache hit → declared scopes.
1893        let cimd_id = "https://app.example.com/client.json";
1894        state
1895            .cimd_cache
1896            .insert(
1897                make_registered(cimd_id, Some("atproto"), true),
1898                Duration::from_secs(300),
1899            )
1900            .await;
1901        assert_eq!(
1902            resolve_client_declared_scopes(&state, cimd_id).await,
1903            Some(vec!["atproto".to_owned()])
1904        );
1905
1906        // Provider choices must receive the same scope ceiling as local POST.
1907        state.clients.write().await.insert(
1908            "dcr-client".to_owned(),
1909            make_registered("dcr-client", Some("openid"), false),
1910        );
1911        let request = AuthorizeParams {
1912            client_id: "dcr-client".to_owned(),
1913            redirect_uri: "https://app.example.com/cb".to_owned(),
1914            code_challenge: "challenge".to_owned(),
1915            code_challenge_method: "S256".to_owned(),
1916            response_type: "code".to_owned(),
1917            state: None,
1918            scope: Some("openid".to_owned()),
1919            resource: None,
1920            nonce: None,
1921            dpop_jkt: None,
1922            client_assertion_jkt: None,
1923        };
1924        assert_eq!(
1925            validate_authorize_scopes(&state, &request).await.unwrap(),
1926            vec!["openid".to_owned()]
1927        );
1928        let mut excessive = request.clone();
1929        excessive.scope = Some("openid write".to_owned());
1930        assert!(validate_authorize_scopes(&state, &excessive).await.is_err());
1931        let mut unknown = request;
1932        unknown.client_id = "unknown-client".to_owned();
1933        assert!(validate_authorize_scopes(&state, &unknown).await.is_err());
1934    }
1935
1936    fn has_row(
1937        rules: &[Vec<String>],
1938        subject: &str,
1939        domain: &str,
1940        resource: &str,
1941        action: &str,
1942    ) -> bool {
1943        rules.iter().any(|rule| {
1944            rule.len() == 5
1945                && rule[0] == subject
1946                && rule[1] == domain
1947                && rule[2] == resource
1948                && rule[3] == action
1949                && rule[4] == "allow"
1950        })
1951    }
1952
1953    #[tokio::test]
1954    async fn hosted_tenant_baseline_seeds_explicit_mcp_row_only_in_that_tenant(
1955    ) -> anyhow::Result<()> {
1956        let dir = tempfile::TempDir::new()?;
1957        let pm = crate::auth::PolicyManager::new(dir.path()).await?;
1958        let did = "did:web:alice.acct.example.test";
1959        let tenant = "acct.example.test";
1960        seed_hosted_tenant_policy_baseline_with(&pm, did, tenant, None).await?;
1961        let rules = pm.get_policy().await;
1962        assert!(
1963            has_row(&rules, "service:mcp", tenant, "policy:IssueToken", "manage"),
1964            "new tenant must hold the explicit IssueToken row (deployment data; the base wildcard already covers the exchange)"
1965        );
1966        assert!(
1967            !has_row(
1968                &rules,
1969                "service:mcp",
1970                "other.example.test",
1971                "policy:IssueToken",
1972                "manage"
1973            ),
1974            "no explicit grant in unrelated tenants"
1975        );
1976        assert!(
1977            !has_row(&rules, did, tenant, "model:canary", "query"),
1978            "no HolderGate rows without a configured export"
1979        );
1980        Ok(())
1981    }
1982
1983    #[tokio::test]
1984    async fn hosted_tenant_baseline_seeds_holdergate_rows_for_configured_export(
1985    ) -> anyhow::Result<()> {
1986        let dir = tempfile::TempDir::new()?;
1987        let pm = crate::auth::PolicyManager::new(dir.path()).await?;
1988        let did = "did:web:alice.acct.example.test";
1989        let tenant = "acct.example.test";
1990        let export = crate::config::NinepCanonicalReadConfig {
1991            repo_name: "canary".to_owned(),
1992            repo_id: "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed".to_owned(),
1993            worktree: "main".to_owned(),
1994        };
1995        seed_hosted_tenant_policy_baseline_with(&pm, did, tenant, Some(&export)).await?;
1996        assert!(
1997            pm.check_with_domain(did, tenant, "model:canary", "query")
1998                .await,
1999            "HolderGate model row must authorize the new account"
2000        );
2001        assert!(
2002            pm.check_with_domain(
2003                did,
2004                tenant,
2005                "registry:1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed",
2006                "query"
2007            )
2008            .await,
2009            "HolderGate registry-uuid row must authorize the new account"
2010        );
2011        assert!(
2012            !pm.check_with_domain(
2013                "did:web:bob.acct.example.test",
2014                tenant,
2015                "model:canary",
2016                "query"
2017            )
2018            .await,
2019            "other accounts in the tenant get no HolderGate row"
2020        );
2021        assert!(
2022            !pm.check_with_domain(did, "other.example.test", "model:canary", "query")
2023                .await,
2024            "the row must not leak into other tenants"
2025        );
2026        Ok(())
2027    }
2028
2029    #[tokio::test]
2030    async fn hosted_tenant_baseline_is_idempotent() -> anyhow::Result<()> {
2031        let dir = tempfile::TempDir::new()?;
2032        let pm = crate::auth::PolicyManager::new(dir.path()).await?;
2033        let did = "did:web:alice.acct.example.test";
2034        let tenant = "acct.example.test";
2035        seed_hosted_tenant_policy_baseline_with(&pm, did, tenant, None).await?;
2036        let once = pm.get_policy().await;
2037        seed_hosted_tenant_policy_baseline_with(&pm, did, tenant, None).await?;
2038        assert_eq!(
2039            once,
2040            pm.get_policy().await,
2041            "resumed signup must not duplicate rows"
2042        );
2043        Ok(())
2044    }
2045}