Skip to main content

hyprstream_core/services/oauth/
par.rs

1//! Pushed Authorization Requests (RFC 9126).
2//!
3//! POST /oauth/par lets the client push the authorization request parameters
4//! out-of-band, then navigate the browser to `/oauth/authorize?request_uri=...`
5//! with a short, opaque reference. Required by atproto OAuth; also avoids URL
6//! length and referer-leakage problems with long inline parameters.
7//!
8//! Flow:
9//! 1. Client POSTs the same parameters it would pass to GET /oauth/authorize.
10//! 2. Server validates them up front (same checks the GET handler does:
11//!    response_type, PKCE method, client metadata resolution, redirect_uri).
12//! 3. On success, the server generates a URN of the form
13//!    `urn:ietf:params:oauth:request_uri:<random-id>` (RFC 9126 §2.2,
14//!    RFC-standard form used by atproto OAuth clients) and stores the
15//!    validated `AuthorizeParams` snapshot keyed by it. 60s TTL.
16//! 4. Returns `{ "request_uri": "...", "expires_in": 60 }` with HTTP 201.
17//!
18//! The /oauth/authorize GET handler resolves `request_uri` by consuming the
19//! entry (single-use per spec) and proceeding as if the params had been inline.
20
21use std::sync::Arc;
22use std::time::Instant;
23
24use axum::{
25    extract::State,
26    http::{HeaderMap, StatusCode},
27    response::{IntoResponse, Response},
28    Form, Json,
29};
30use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
31use rand::RngCore;
32use serde::{Deserialize, Serialize};
33
34use super::authorize::AuthorizeParams;
35use super::registration::{resolve_cimd_client, validate_redirect_uri};
36use super::state::{OAuthState, PushedAuthRequest};
37
38/// PAR request lifetime. RFC 9126 recommends short-lived (e.g. <= 60s).
39pub const PAR_TTL_SECS: u64 = 60;
40
41/// PAR form body. Same shape as `AuthorizeParams`, but accepted as a form POST.
42///
43/// Per RFC 9126 §2.1 the body is `application/x-www-form-urlencoded` with the
44/// same parameters that would appear on the authorize URL.
45#[derive(Debug, Deserialize)]
46pub struct ParForm {
47    pub client_id: String,
48    pub redirect_uri: String,
49    pub code_challenge: String,
50    pub code_challenge_method: String,
51    pub response_type: String,
52    #[serde(default)]
53    pub state: Option<String>,
54    #[serde(default)]
55    pub scope: Option<String>,
56    #[serde(default)]
57    pub resource: Option<String>,
58    #[serde(default)]
59    pub nonce: Option<String>,
60    /// RFC 7523 client assertion — REQUIRED at PAR for confidential
61    /// (`private_key_jwt`) clients: the atproto OAuth profile authenticates
62    /// confidential clients during the authorization request, which for a
63    /// PAR-mandatory profile is here (#1146 T3.3).
64    #[serde(default)]
65    pub client_assertion: Option<String>,
66    #[serde(default)]
67    pub client_assertion_type: Option<String>,
68}
69
70/// PAR success response body (RFC 9126 §2.2).
71#[derive(Debug, Serialize)]
72pub struct ParResponse {
73    pub request_uri: String,
74    pub expires_in: u64,
75}
76
77/// PAR error body (RFC 9126 §2.3 — same shape as OAuth token errors).
78#[derive(Debug, Serialize)]
79struct ParError {
80    error: &'static str,
81    #[serde(skip_serializing_if = "Option::is_none")]
82    error_description: Option<String>,
83}
84
85/// Build a PAR error response. `description` is `Some(...)` only when
86/// the message is client-actionable (refers to the client's own
87/// request). Server-internal failures pass `None`; the public response
88/// then carries only the OAuth error code. See `token_error` for the
89/// same rationale at the token endpoint.
90fn par_error(status: StatusCode, error: &'static str, description: Option<&str>) -> Response {
91    (
92        status,
93        Json(ParError {
94            error,
95            error_description: description.map(str::to_owned),
96        }),
97    )
98        .into_response()
99}
100
101/// POST /oauth/par
102///
103/// Validates the pushed authorization request and returns a `request_uri` the
104/// client should navigate the browser to via `/oauth/authorize?request_uri=...`.
105pub async fn push_authorization_request(
106    State(state): State<Arc<OAuthState>>,
107    req_headers: HeaderMap,
108    Form(form): Form<ParForm>,
109) -> Response {
110    // Validate response_type
111    if form.response_type != "code" {
112        return par_error(
113            StatusCode::BAD_REQUEST,
114            "unsupported_response_type",
115            Some("Only response_type=code is supported"),
116        );
117    }
118
119    // Validate PKCE method
120    if form.code_challenge_method != "S256" {
121        return par_error(
122            StatusCode::BAD_REQUEST,
123            "invalid_request",
124            Some("Only code_challenge_method=S256 is supported"),
125        );
126    }
127    if form.code_challenge.is_empty() {
128        return par_error(
129            StatusCode::BAD_REQUEST,
130            "invalid_request",
131            Some("code_challenge is required (PKCE mandatory per OAuth 2.1)"),
132        );
133    }
134
135    // Resolve client (CIMD or dynamically registered) and pull redirect URIs.
136    let registered_client = if form.client_id.starts_with("https://") {
137        match resolve_cimd_client(&state, &form.client_id).await {
138            Ok(client) => Some(client),
139            Err(e) => {
140                // The resolver's error spans federation:register policy
141                // denial, PolicyService RPC outage, and CIMD doc fetch
142                // failures — all of which describe internal trust
143                // state to the unauthenticated PAR caller. Log full
144                // detail; respond opaquely.
145                tracing::warn!(
146                    client_id = %form.client_id,
147                    error = %e,
148                    "CIMD resolution failed during PAR"
149                );
150                return par_error(StatusCode::BAD_REQUEST, "invalid_client", None);
151            }
152        }
153    } else {
154        let clients = state.clients.read().await;
155        match clients.get(&form.client_id) {
156            Some(client) => Some(client.clone()),
157            None => {
158                return par_error(
159                    StatusCode::BAD_REQUEST,
160                    "invalid_client",
161                    Some("Unknown client_id. Register first via POST /oauth/register"),
162                );
163            }
164        }
165    };
166
167    let registered_client = match registered_client {
168        Some(c) => c,
169        None => {
170            return par_error(StatusCode::BAD_REQUEST, "invalid_client", None);
171        }
172    };
173
174    if !validate_redirect_uri(&form.redirect_uri, &registered_client.redirect_uris) {
175        return par_error(
176            StatusCode::BAD_REQUEST,
177            "invalid_redirect_uri",
178            Some("redirect_uri does not match registered URIs"),
179        );
180    }
181
182    // #1113 rev2 finding 4: validate requested scope against server-supported
183    // ∩ client-declared. Garbage / undeclared tokens → invalid_scope.
184    let requested_scopes: Vec<String> = form
185        .scope
186        .as_deref()
187        .unwrap_or(&state.default_scopes.join(" "))
188        .split_whitespace()
189        .map(str::to_owned)
190        .collect();
191    let client_declared = registered_client.declared_scopes();
192    let require_atproto = super::state::atproto_profile_active(&requested_scopes);
193    let granted_scopes = match super::state::validate_requested_scopes(
194        &requested_scopes,
195        &state.server_supported_scopes(),
196        if client_declared.is_empty() {
197            None
198        } else {
199            Some(&client_declared)
200        },
201        require_atproto,
202    ) {
203        Ok(g) => g,
204        Err(_) => {
205            return par_error(
206                StatusCode::BAD_REQUEST,
207                "invalid_scope",
208                Some("Requested scope is not supported or not declared by the client"),
209            );
210        }
211    };
212    // `atproto` activates the strict profile — echo back the granted scope
213    // string into the stored snapshot so authorize/token see the exact set.
214    let granted_scope_str = granted_scopes.join(" ");
215
216    // #1146 T3.3 (+T1.2): authenticate confidential clients at PAR. The
217    // atproto OAuth profile authenticates confidential clients during the
218    // authorization request — which, for a PAR-mandatory profile, is here.
219    // The assertion audience is the AS ISSUER (atproto mandate; the token
220    // endpoint additionally accepts the RFC 7523 endpoint-URL form, PAR
221    // does not). The verified key's RFC 7638 thumbprint is bound into the
222    // snapshot so token redemption and refresh must use the SAME key.
223    let client_assertion_jkt = {
224        let needs_auth = super::client_auth::requires_private_key_jwt(&registered_client);
225        let has_assertion = form.client_assertion.is_some() && form.client_assertion_type.is_some();
226        if needs_auth && !has_assertion {
227            return par_error(
228                StatusCode::UNAUTHORIZED,
229                "invalid_client",
230                Some("client_assertion required"),
231            );
232        }
233        if has_assertion {
234            let assertion = form
235                .client_assertion
236                .as_deref()
237                .unwrap_or_else(|| unreachable!());
238            let atype = form
239                .client_assertion_type
240                .as_deref()
241                .unwrap_or_else(|| unreachable!());
242            let issuer = state.issuer_for_scopes(&granted_scopes);
243            match super::client_auth::verify_client_assertion(
244                &state,
245                &registered_client,
246                atype,
247                assertion,
248                std::slice::from_ref(&issuer),
249            )
250            .await
251            {
252                Ok(verified) => Some(verified.key_jkt),
253                Err(e) => {
254                    // Opaque response, detailed log — same rationale as
255                    // the token endpoint's invalid_client handling.
256                    tracing::warn!(
257                        client_id = %form.client_id,
258                        error = %e,
259                        "client_assertion verification failed at PAR"
260                    );
261                    return par_error(StatusCode::UNAUTHORIZED, "invalid_client", None);
262                }
263            }
264        } else {
265            None
266        }
267    };
268
269    // #1113 rev2 finding 3: atproto profile requires DPoP. Capture and verify
270    // the DPoP proof at PAR, bind its `jkt` into the authorization request so
271    // the token endpoint can require a proof from the SAME key. Non-atproto
272    // requests keep DPoP optional (RFC 9449 general behavior).
273    let dpop_jkt = if require_atproto {
274        let dpop_header = req_headers
275            .get("DPoP")
276            .and_then(|v| v.to_str().ok())
277            .map(str::to_owned);
278        let dpop_header = match dpop_header {
279            Some(h) => h,
280            None => {
281                return par_error(
282                    StatusCode::BAD_REQUEST,
283                    "invalid_request",
284                    Some("atproto profile requires a DPoP proof header"),
285                );
286            }
287        };
288        let atproto_issuer = state.atproto_issuer_url();
289        let par_endpoint = format!("{}/oauth/par", atproto_issuer.trim_end_matches('/'));
290        match super::dpop::verify_dpop_proof(&dpop_header, "POST", &par_endpoint, None) {
291            Ok(proof) => {
292                // Record the jkt so future token-endpoint proofs from this
293                // key are nonce-bound (RFC 9449 §8). Single-use jti check.
294                if !state.check_and_record_dpop_jti(&proof.jti, proof.iat) {
295                    return par_error(
296                        StatusCode::BAD_REQUEST,
297                        "invalid_dpop_proof",
298                        Some("DPoP proof jti already used"),
299                    );
300                }
301                state.mark_dpop_client_nonced(&proof.jkt).await;
302                Some(proof.jkt)
303            }
304            Err(e) => {
305                tracing::warn!(error = %e, "DPoP proof verification failed at PAR");
306                return par_error(StatusCode::BAD_REQUEST, "invalid_dpop_proof", None);
307            }
308        }
309    } else {
310        None
311    };
312
313    // Build the AuthorizeParams snapshot to store.
314    let params = AuthorizeParams {
315        client_id: form.client_id,
316        redirect_uri: form.redirect_uri,
317        code_challenge: form.code_challenge,
318        code_challenge_method: form.code_challenge_method,
319        response_type: form.response_type,
320        state: form.state,
321        scope: Some(granted_scope_str),
322        resource: form.resource,
323        nonce: form.nonce,
324        dpop_jkt: dpop_jkt.clone(),
325        client_assertion_jkt,
326    };
327
328    // Generate a random URN. RFC 9126 §2.2 / atproto OAuth use the standard
329    // `urn:ietf:params:oauth:request_uri:` namespace.
330    let mut id_bytes = [0u8; 24];
331    rand::rngs::OsRng.fill_bytes(&mut id_bytes);
332    let id = URL_SAFE_NO_PAD.encode(id_bytes);
333    let request_uri = format!("urn:ietf:params:oauth:request_uri:{id}");
334
335    let expires_at = Instant::now() + std::time::Duration::from_secs(PAR_TTL_SECS);
336    state.pending_par_requests.write().await.insert(
337        request_uri.clone(),
338        PushedAuthRequest { params, expires_at },
339    );
340
341    // #1113 rev2 finding 3: when DPoP was bound, issue a fresh server nonce
342    // and return it in the `DPoP-Nonce` header so the client can include it
343    // in subsequent proofs (matches the atproto client's PAR response handling).
344    let dpop_nonce = if dpop_jkt.is_some() {
345        Some(state.issue_dpop_nonce().await)
346    } else {
347        None
348    };
349
350    let mut resp = (
351        StatusCode::CREATED,
352        Json(ParResponse {
353            request_uri,
354            expires_in: PAR_TTL_SECS,
355        }),
356    )
357        .into_response();
358    if let Some(nonce) = dpop_nonce {
359        if let Ok(val) = axum::http::HeaderValue::from_str(&nonce) {
360            resp.headers_mut().insert("DPoP-Nonce", val);
361        }
362    }
363    resp
364}