hyprstream_core/services/oauth/
par.rs1use 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
38pub const PAR_TTL_SECS: u64 = 60;
40
41#[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 #[serde(default)]
65 pub client_assertion: Option<String>,
66 #[serde(default)]
67 pub client_assertion_type: Option<String>,
68}
69
70#[derive(Debug, Serialize)]
72pub struct ParResponse {
73 pub request_uri: String,
74 pub expires_in: u64,
75}
76
77#[derive(Debug, Serialize)]
79struct ParError {
80 error: &'static str,
81 #[serde(skip_serializing_if = "Option::is_none")]
82 error_description: Option<String>,
83}
84
85fn 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
101pub async fn push_authorization_request(
106 State(state): State<Arc<OAuthState>>,
107 req_headers: HeaderMap,
108 Form(form): Form<ParForm>,
109) -> Response {
110 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 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 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 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, ®istered_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 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 let granted_scope_str = granted_scopes.join(" ");
215
216 let client_assertion_jkt = {
224 let needs_auth = super::client_auth::requires_private_key_jwt(®istered_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 ®istered_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 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 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 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 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 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 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}