Skip to content

Commit 473f2bf

Browse files
PiquelChipsclaude
andauthored
feat(sdk): the Rust SDK signs in clients that must push their requests (#240)
Closes #236 Auth lets a client require pushed authorization requests (`--require-par`) and refuses that client's front-channel requests. The Rust SDK never pushed, so an app using it couldn't sign in with such a client. The SDK now pushes whenever discovery advertises the PAR endpoint, as the TypeScript SDK does. ## How - `Client::authorize` is now `async` and returns `Result<(Url, PendingLogin), LoginError>`. With PAR advertised, it pushes the request, authenticated as at the token endpoint (Basic for confidential clients, `client_id` for public ones). It then returns `/oauth/authorize?client_id=…&request_uri=…`. `PendingLogin` is unchanged. - `LoginError::Push(OAuthError)` reports a refused push, keeping its OAuth `error`. `LoginError::Randomness` replaces the bare `rand::Error`. - The axum `/login` route answers 502 when the push fails. - Discovery also requires the PAR endpoint to use https, like every other endpoint. - Any 2xx status from auth counts as success, since PAR answers 201. - `docs/architecture/sdk.md` states the rule: SDKs push whenever discovery advertises the endpoint. - **Decision for review:** `LoginError::Randomness` reports the shared category `network`, since none covers a local failure. The alternative is a new category in the shared error types. ## Since review - **Exact statuses:** each endpoint must answer with its own success status, 201 for the push and 200 for the others, matching the TypeScript SDK. - **`request_uri`:** an empty or whitespace one is refused (`pushes_need_a_created_request_uri`). - **Revocation:** its 200 body is ignored (RFC 7009 §2.2). - **Tests:** the unit test checks that a pushed request carries `acr_values` and `max_age`. ## Proof - `authorize_pushes_when_advertised` and `refused_pushes_keep_the_oauth_error` run against a mock PAR endpoint. - `sdk_login_routes_push_for_clients_that_must` (database-backed) signs a `require_pushed_authorization_requests` client in through the axum routes against real auth. - The step-up test now resumes through `/oauth/authorize/resume`, because a `request_uri` works once. - Clippy and rustdoc with warnings denied, nextest (27), doc tests (48) and the full `just db test` (307) all pass. Reviewed with review-loop: 5 rounds with 5× Claude Opus 5.5 on xhigh, over the whole stack and #240. Verdict: approved > [!NOTE] > Written by Claude Opus 5.5 in Claude Code and reviewed by GPT 6.1 Sol and Claude Opus 5.5 (via T3 Code) 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Rust SDK authorization flow `Client::authorize` is now asynchronous and returns `Result<(Url, PendingLogin), LoginError>`. It uses fallible OS randomness to create the state, nonce, and PKCE verifier. `PendingLogin` is unchanged, so these values remain server-side. When issuer discovery advertises `pushed_authorization_request_endpoint`, the SDK sends the authorization request there using the client’s token-endpoint authentication. The browser URL contains only `client_id` and the returned `request_uri`. When discovery does not advertise PAR, the SDK retains the query-string authorization flow. `LoginError` adds `Randomness` and `Push` variants. A rejected push retains its OAuth error. Randomness failures map to the shared `network` category. Successful HTTP responses with any 2xx status are accepted by the shared response reader. ## Axum login routes The `/login` route awaits `Client::authorize`. It returns 500 when OS randomness is unavailable and 502 when authorization fails, including a failed push. The route documentation describes the possible push and the 502 response. ## Discovery validation Issuer metadata validation now rejects a non-HTTPS pushed authorization endpoint with `DiscoveryError::InsecureEndpoint`. The existing checks remain unchanged when discovery does not advertise that endpoint. ## Tests and support SDK tests cover pushing to an advertised endpoint, limiting the browser URL to `client_id` and `request_uri`, preserving OAuth errors from rejected pushes, and rejecting completion with a different client as `ForeignLogin`. The auth-service integration tests cover login for clients that require PAR. The step-up test resumes the claimed authorization transaction through the provider’s resume endpoint. Test support now shares metadata loading and local server setup helpers. The auth-service step-up test also checks that the pushed request carries the step-up requirement. ## Documentation The SDK architecture guide documents the PAR behavior, client authentication, redirect parameters, and error categories. The `Client::authorize` documentation and examples reflect the asynchronous API. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent d3d2e45 commit 473f2bf

8 files changed

Lines changed: 366 additions & 97 deletions

File tree

‎apps/auth-service/src/oidc/tests.rs‎

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1959,6 +1959,7 @@ async fn sdk_login_client_runs_against_the_provider() {
19591959
scopes: "profile email offline_access".parse().expect("scopes"),
19601960
..AuthorizeRequest::default()
19611961
})
1962+
.await
19621963
.expect("authorization URL");
19631964

19641965
let mixed_up = CallbackParams {
@@ -2348,6 +2349,24 @@ async fn sdk_login_routes_run_against_the_provider() {
23482349
assert_eq!(after.status(), StatusCode::SEE_OTHER);
23492350
}
23502351

2352+
/// A client required to push its authorization requests signs in through the SDK's
2353+
/// login routes, which push them, so the browser carries only the `request_uri`.
2354+
#[tokio::test]
2355+
#[ignore = "requires TEST_DATABASE_URL"]
2356+
async fn sdk_login_routes_push_for_clients_that_must() {
2357+
let mut app = LoginApp::start().await;
2358+
app.flow.client.require_pushed_authorization_requests = true;
2359+
crate::tests::replace(&app.flow.app.database, &app.flow.client)
2360+
.await
2361+
.expect("require pushed requests");
2362+
let (pending, authorize) = app.start_login("/auth/login", None).await;
2363+
let names: Vec<_> = authorize.query_pairs().map(|(name, _)| name).collect();
2364+
assert_eq!(names, ["client_id", "request_uri"]);
2365+
let browser = app.authorize(&authorize).await;
2366+
let callback = app.finish_login(browser, pending, None).await;
2367+
assert_eq!(LoginApp::location(&callback), "/");
2368+
}
2369+
23512370
/// A passkey confirmation within five minutes.
23522371
struct RecentPasskey;
23532372

@@ -2375,10 +2394,9 @@ async fn sdk_step_up_runs_against_the_provider() {
23752394
login,
23762395
"/auth/login?return_to=%2Fsettings&acr_values=phr&max_age=300&step_up=true"
23772396
);
2397+
// The pushed request carries `acr_values` and `max_age`: the social session is
2398+
// too weak for them, so the provider asks for a passkey.
23782399
let (pending, authorize) = app.start_login(&login, Some(&first)).await;
2379-
assert_eq!(parameter(&authorize, "acr_values"), "phr");
2380-
assert_eq!(parameter(&authorize, "max_age"), "300");
2381-
// The social session is too weak, so the provider asks for a passkey.
23822400
let prompt = app.authorize(&authorize).await;
23832401
assert_eq!(location(&prompt).path(), routes::page::LOGIN);
23842402

@@ -2403,7 +2421,20 @@ async fn sdk_step_up_runs_against_the_provider() {
24032421
.confirm_passkey(session, PasskeyId::new(), Utc::now())
24042422
.await
24052423
.expect("passkey confirmation");
2406-
let browser = app.authorize(&authorize).await;
2424+
// The pushed request was claimed, so the browser resumes its transaction.
2425+
let transaction = parameter(&location(&prompt), "transaction");
2426+
let browser = app
2427+
.flow
2428+
.request(
2429+
Method::GET,
2430+
&format!(
2431+
"{}?transaction={transaction}",
2432+
routes::oidc::AUTHORIZE_RESUME
2433+
),
2434+
&[],
2435+
None,
2436+
)
2437+
.await;
24072438
let callback = app.finish_login(browser, pending, Some(&first)).await;
24082439
assert_eq!(LoginApp::location(&callback), "/settings");
24092440
let second = LoginApp::cookie(&callback, "__Host-piquel-session");

‎crates/auth-sdk/src/axum/login.rs‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ use super::{
77
session::{BackendError, Lease, LeaseId, PendingAuthorization, Session, SessionKey, Sessions},
88
};
99
use crate::{
10-
Acr, AuthenticationPolicy, AuthorizeRequest, CallbackParams, Client, IdToken, Scopes,
11-
StepUpRequirement, TokenError, UserId,
10+
Acr, AuthenticationPolicy, AuthorizeRequest, CallbackParams, Client, IdToken, LoginError,
11+
Scopes, StepUpRequirement, TokenError, UserId,
1212
};
1313
use axum::{
1414
Extension, Form, Json, Router,
@@ -149,7 +149,8 @@ struct Login {
149149
/// Server-side login for apps: the routes, and the layer the session extractors need.
150150
///
151151
/// - `GET /login?return_to=…` stores a pending login under a fresh random key and
152-
/// redirects to auth.
152+
/// redirects to auth, pushing the request first when auth advertises it
153+
/// ([`Client::authorize`]). It answers 502 if the push fails.
153154
/// - `GET /callback` completes it, then starts a session under another fresh key,
154155
/// ending any session the browser already had.
155156
/// - `POST /logout` deletes the session and redirects to RP-initiated logout.
@@ -377,11 +378,25 @@ impl Login {
377378
step_up,
378379
..AuthorizeRequest::default()
379380
};
380-
let (Ok((url, pending)), Ok(key)) =
381-
(login.client.authorize(&request), SessionKey::generate())
382-
else {
381+
let randomness_unavailable = || {
383382
tracing::error!("operating system randomness is unavailable");
384-
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
383+
StatusCode::INTERNAL_SERVER_ERROR.into_response()
384+
};
385+
let Ok(key) = SessionKey::generate() else {
386+
return randomness_unavailable();
387+
};
388+
let (url, pending) = match login.client.authorize(&request).await {
389+
Ok(started) => started,
390+
Err(LoginError::Randomness(_)) => return randomness_unavailable(),
391+
// Auth refused or could not take the pushed request.
392+
Err(error) => {
393+
tracing::warn!(error = %ErrorChain(&error), "sign-in could not start");
394+
return (
395+
StatusCode::BAD_GATEWAY,
396+
format!("Sign-in could not start: {error}."),
397+
)
398+
.into_response();
399+
}
385400
};
386401
let pending = PendingAuthorization {
387402
login: pending,

‎crates/auth-sdk/src/axum/tests.rs‎

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use crate::{
77
AuthenticationPolicy, ClientConfig, ClientId, Credentials, Issuer, KeyCache, KeySet, Resource,
88
SessionId, StepUpRequirement, SystemClock,
99
http::Http,
10-
tests::{Case, issuer, vector_token},
10+
tests::{Case, issuer, metadata, serve, vector_token},
1111
};
1212
use ::axum::{
1313
Router,
@@ -23,7 +23,6 @@ use piquel_common::{
2323
protocol::{
2424
challenge::BearerChallenge,
2525
claims::{Absent, Audience, LogoutEvents, LogoutTokenClaims},
26-
metadata::ServerMetadata,
2726
},
2827
};
2928
use serde_json::json;
@@ -258,11 +257,7 @@ impl TokenEndpoint {
258257
}
259258
}),
260259
);
261-
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
262-
.await
263-
.expect("bind token endpoint");
264-
let address = listener.local_addr().expect("address");
265-
tokio::spawn(async move { ::axum::serve(listener, router).await });
260+
let address = serve(router).await;
266261
Self {
267262
url: format!("http://{address}/token").parse().expect("URL"),
268263
calls,
@@ -272,12 +267,7 @@ impl TokenEndpoint {
272267

273268
/// The vectors' issuer, with its token endpoint replaced and the system clock.
274269
fn issuer_with_token_endpoint(token_endpoint: Url) -> Issuer {
275-
let discovery = Case::all("discovery")
276-
.into_iter()
277-
.find(|case| case.name.ends_with("/valid.json"))
278-
.expect("discovery vector");
279-
let mut metadata: ServerMetadata =
280-
serde_json::from_value(discovery.input("document").clone()).expect("metadata");
270+
let mut metadata = metadata();
281271
metadata.token_endpoint = token_endpoint;
282272
let jwks = serde_json::to_vec(token_case("access-valid").input("jwks")).expect("JWKS");
283273
Issuer::with_keys(

0 commit comments

Comments
 (0)