Skip to content

Commit c19bba1

Browse files
authored
refactor(common): auth and both SDKs share the token and pushed authorization responses (#578)
Part of #544. Stacked on #577: it branches from `refactor/544-boundary-sdk-constants` and targets it. The token and pushed authorization endpoints' answers were defined three times: - auth serialized private structs (`oidc/token.rs`, `oidc/authorize/pushed.rs`); - the Rust SDK deserialized its own private copies (`client.rs`); - the TypeScript SDK decoded untyped shapes (`client.ts`). Nothing tied them together. Auth's `expires_in` was an `i64` and the SDK's a `u32`. Both are now `TokenResponse` and `PushedAuthorization` in `sourceorigin_common::protocol::oauth`. Auth and the Rust SDK use them, `protocol.ts` declares them, and the TypeScript decoders are typed `json.Decoder<TokenResponse>` and `json.Decoder<PushedAuthorization>`. - **`expires_in` is a `u32`.** That is what both SDKs accept, so their behaviour stays the same. Auth's `ACCESS_TOKEN_SECONDS` and `PUSHED_REQUEST_SECONDS` become `u32` too, widened where they meet `i64` durations. Auth still sends 300 and 60. - **`token_type` is a `String`.** The SDKs compare it without regard to case, so the shared field stays open. Auth writes `AuthScheme::Bearer`'s spelling. - **The pushed answer's `expires_in` is never read.** Auth always sends it; the Rust SDK skips it when deserializing (`skip_deserializing`), as its old private struct did, and the TS decoder ignores it, so neither SDK refuses a response over it. - **Token counting moved.** It was a method on auth's old struct and is now `OidcApplication::count_issued`. - Tests merged or removed: none. - Files edited outside the SDK area: `apps/auth-service/src/oidc/{mod.rs,token.rs,authorize/pushed.rs,authorize/parameters.rs}` and `apps/auth-service/src/keys/mod.rs`, which needs the one `as i64` widening in its `const` key-retirement window. **Proof the rest is unchanged:** - `cargo semver-checks` for `sourceorigin-common` and `sourceorigin-auth`: no semver update required. - `just db test`: 497/497 pass, including the token endpoint and PAR tests that assert the JSON bodies. - `.d.ts` comparison: `protocol.d.ts` gains only the two types; the entry points match `main`. - Checks: clippy (with and without `--all-features`) for `auth-service`, `sourceorigin-common` and `sourceorigin-auth`; rustdoc, doc tests and `just test -p`; `just rust unused`; `just web check`/`lint`/`unused`/`test` (172/172); `just docs`. > [!NOTE] > Written by Claude Opus 5.5 in Claude Code and reviewed by Claude Opus 5.5 (via T3 Code)
1 parent dc45109 commit c19bba1

18 files changed

Lines changed: 165 additions & 108 deletions

File tree

‎.gitattributes‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
crates/database/.sqlx/** linguist-generated
88
# The SDK test vectors, written by `just sdk-vectors`; the keys and README are not.
99
tests/sdk-vectors/**/*.json linguist-generated
10-
# The TypeScript SDK's wire types, written by `just sdk-types`.
10+
# The TypeScript SDK's wire types and shared constants, written by `just sdk-types`.
1111
packages/auth/src/protocol.ts linguist-generated
1212
# The CLI and configuration references, written by `just docs reference`.
1313
docs/dev/operations/cli-commands.md linguist-generated

‎apps/auth-service/src/keys/mod.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ const PRE_PUBLICATION: TimeDelta = TimeDelta::hours(24);
4141
/// How long a `retiring` key stays published: the longest token lifetime, plus
4242
/// the JWKS cache lifetime for verifiers that fetched keys just before it stopped.
4343
const RETIRING_WINDOW: TimeDelta =
44-
TimeDelta::seconds(ACCESS_TOKEN_SECONDS + PublicDocument::MAX_AGE_SECONDS);
44+
TimeDelta::seconds(ACCESS_TOKEN_SECONDS as i64 + PublicDocument::MAX_AGE_SECONDS);
4545
/// How long a retired key verifies `id_token_hint`s: the longest session.
4646
const RETIRED_WINDOW: TimeDelta = TimeDelta::days(SESSION_LIFETIME_DAYS as i64);
4747
/// How often every replica advances rotation and reloads its key set: also the

‎apps/auth-service/src/oidc/authorize/parameters.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ impl AuthorizationParameters {
8989
self.max_age()?;
9090
let interaction = self.interaction()?;
9191
let lifetime = if pushed {
92-
Duration::seconds(PUSHED_REQUEST_SECONDS)
92+
Duration::seconds(PUSHED_REQUEST_SECONDS.into())
9393
} else {
9494
Duration::minutes(AUTHORIZATION_REQUEST_MINUTES)
9595
};

‎apps/auth-service/src/oidc/authorize/pushed.rs‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use axum::{
1515
http::{HeaderMap, StatusCode},
1616
};
1717
use chrono::{Duration, Utc};
18-
use serde::Serialize;
18+
use sourceorigin_common::protocol::oauth::PushedAuthorization;
1919
use sourceorigin_repository::{OidcRepository, StoredAuthorizationRequest};
2020
use url::Url;
2121

@@ -26,15 +26,6 @@ const UNKNOWN_REQUEST_URI: &str =
2626
/// pushed request's [`OpaqueToken`].
2727
const REQUEST_URI_PREFIX: &str = "urn:ietf:params:oauth:request_uri:";
2828

29-
/// The pushed authorization endpoint's answer (RFC 9126 §2.2).
30-
#[derive(Serialize)]
31-
pub(in crate::oidc) struct PushedAuthorization {
32-
/// What the browser brings to the authorization endpoint, with `client_id`.
33-
request_uri: String,
34-
/// Seconds until `request_uri` expires.
35-
expires_in: i64,
36-
}
37-
3829
impl OidcApplication {
3930
/// Stores a request pushed by an authenticated client (RFC 9126 §2), validated
4031
/// as at the authorization endpoint, and returns the `request_uri` the browser
@@ -65,7 +56,7 @@ impl OidcApplication {
6556
StatusCode::CREATED,
6657
Json(PushedAuthorization {
6758
request_uri: format!("{REQUEST_URI_PREFIX}{token}"),
68-
expires_in: PUSHED_REQUEST_SECONDS,
59+
expires_in: Some(PUSHED_REQUEST_SECONDS),
6960
}),
7061
))
7162
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ use std::sync::Arc;
5858
use url::Url;
5959

6060
/// Lifetime of signed access and ID tokens; kept short because they cannot be revoked.
61-
pub(crate) const ACCESS_TOKEN_SECONDS: i64 = 300;
61+
pub(crate) const ACCESS_TOKEN_SECONDS: u32 = 300;
6262
/// Maximum byte length of `state` and `nonce`.
6363
const MAX_STATE_BYTES: usize = 512;
6464
/// Maximum length of the base64 part of an HTTP Basic header.
@@ -70,7 +70,7 @@ const MAX_SCOPES: usize = 16;
7070
/// How long a pending authorization waits for login and consent.
7171
const AUTHORIZATION_REQUEST_MINUTES: i64 = 10;
7272
/// How long a pushed request waits for the browser to bring its `request_uri`.
73-
const PUSHED_REQUEST_SECONDS: i64 = 60;
73+
const PUSHED_REQUEST_SECONDS: u32 = 60;
7474
/// How long an authorization code stays redeemable.
7575
const AUTHORIZATION_CODE_MINUTES: i64 = 2;
7676
/// Developer documentation advertised in the metadata.

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

Lines changed: 11 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use axum::{
1414
http::{HeaderMap, HeaderName, StatusCode, header},
1515
};
1616
use chrono::{DateTime, Duration, Utc};
17-
use serde::{Deserialize, Serialize};
17+
use serde::Deserialize;
1818
use sourceorigin_common::{
1919
ClientId, SessionId, TokenId, UserId,
2020
events::{CodeRedemptionFailure, DomainEvent, EventContext, GrantRevocation},
@@ -24,7 +24,7 @@ use sourceorigin_common::{
2424
AccessTokenClaims, Audience, AuthenticationClaims, IdTokenClaims, ProfileClaims,
2525
UserInfo,
2626
},
27-
oauth,
27+
oauth::{self, TokenResponse},
2828
},
2929
};
3030
use sourceorigin_repository::{
@@ -116,34 +116,14 @@ impl TokenForm {
116116
}
117117
}
118118

119-
/// Existing OAuth token JSON, omitting tokens not issued by the grant.
120-
#[derive(Serialize)]
121-
pub(super) struct TokenResponse {
122-
/// Short-lived signed bearer token for the resource audience.
123-
access_token: String,
124-
/// HTTP authentication scheme for the issued access token.
125-
token_type: AuthScheme,
126-
/// Access token lifetime in seconds.
127-
expires_in: i64,
128-
/// Space-separated scopes requested or granted.
129-
scope: oauth::Scopes,
130-
/// Signed client-bound identity token, present only for openid grants.
131-
#[serde(skip_serializing_if = "Option::is_none")]
132-
id_token: Option<String>,
133-
/// Opaque refresh token: the first of a grant refresh policy permits, or the
134-
/// replacement of a rotated one. A client that keeps its token gets none.
135-
#[serde(skip_serializing_if = "Option::is_none")]
136-
refresh_token: Option<String>,
137-
}
138-
139-
impl TokenResponse {
140-
/// Counts each token issued by `grant`, once its transaction committed, by
141-
/// the response field it is sent in.
142-
fn count(&self, grant: GrantType) {
119+
impl OidcApplication {
120+
/// Counts each token `grant` issued in `tokens`, once its transaction committed,
121+
/// by the response field it is sent in.
122+
fn count_issued(grant: GrantType, tokens: &TokenResponse) {
143123
let issued = [
144124
("access_token", true),
145-
("id_token", self.id_token.is_some()),
146-
("refresh_token", self.refresh_token.is_some()),
125+
("id_token", tokens.id_token.is_some()),
126+
("refresh_token", tokens.refresh_token.is_some()),
147127
];
148128
for (token, _) in issued.into_iter().filter(|(_, issued)| *issued) {
149129
TOKENS_ISSUED.add(1, &[("grant_type", grant.as_str()), ("token_type", token)]);
@@ -191,7 +171,7 @@ impl TokenGrant<'_> {
191171
authentication,
192172
} = self;
193173
let issued_at = Utc::now();
194-
let expires_at = issued_at + Duration::seconds(ACCESS_TOKEN_SECONDS);
174+
let expires_at = issued_at + Duration::seconds(ACCESS_TOKEN_SECONDS.into());
195175
let authentication = AuthenticationClaims {
196176
sid: Some(*session),
197177
auth_time: Some(authentication.auth_time),
@@ -249,7 +229,7 @@ impl TokenGrant<'_> {
249229
};
250230
Ok(TokenResponse {
251231
access_token,
252-
token_type: AuthScheme::Bearer,
232+
token_type: AuthScheme::Bearer.as_str().to_owned(),
253233
expires_in: ACCESS_TOKEN_SECONDS,
254234
scope: scopes.wire().clone(),
255235
id_token,
@@ -292,7 +272,7 @@ impl OidcApplication {
292272
GrantType::AuthorizationCode => app.exchange_code(form, &client.id, &context).await,
293273
GrantType::RefreshToken => app.refresh(form, &client, &context).await,
294274
}?;
295-
tokens.count(grant);
275+
Self::count_issued(grant, &tokens);
296276
// After the grant committed, outside its transaction: concurrent refreshes
297277
// of one client each hold their family and share-lock the client, so the
298278
// hourly write, which needs the client exclusively, would deadlock them if

‎crates/auth-sdk/src/client.rs‎

Lines changed: 2 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ use sourceorigin_common::{
1515
claims::{IdTokenClaims, LogoutTokenClaims, UserInfo},
1616
jwt::TokenType,
1717
oauth::{
18-
CodeChallengeMethod, ErrorResponse, GrantType, Prompt, ResponseType, Scope, Scopes,
18+
CodeChallengeMethod, ErrorResponse, GrantType, Prompt, PushedAuthorization,
19+
ResponseType, Scope, Scopes, TokenResponse,
1920
},
2021
sdk::{ErrorCategory, ErrorReason, SdkError},
2122
step_up::StepUpRequirement,
@@ -563,31 +564,6 @@ impl fmt::Debug for CallbackParams {
563564
}
564565
}
565566

566-
/// The token endpoint's success response.
567-
#[derive(Deserialize)]
568-
struct TokenResponse {
569-
/// The access token.
570-
access_token: String,
571-
/// Must be `Bearer`.
572-
token_type: String,
573-
/// Access token lifetime, in seconds.
574-
expires_in: u32,
575-
/// Granted scopes.
576-
scope: Scopes,
577-
/// ID token, with `openid`.
578-
id_token: Option<String>,
579-
/// Refresh token, with `offline_access`.
580-
refresh_token: Option<String>,
581-
}
582-
583-
/// The pushed authorization endpoint's success response (RFC 9126 §2.2). Its
584-
/// `expires_in` is not needed: the browser is redirected at once.
585-
#[derive(Deserialize)]
586-
struct PushedAuthorization {
587-
/// What the browser brings to the authorization endpoint, with `client_id`.
588-
request_uri: String,
589-
}
590-
591567
/// What the client shares across clones.
592568
struct ClientInner {
593569
/// The issuer it signs in with.

‎crates/common/src/protocol/constants.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@ super::sdk_constants! {
3636
/// Most bytes read from any response. Metadata, key sets and token responses are a
3737
/// few kilobytes.
3838
pub const MAX_RESPONSE_BYTES: usize = 256 * 1024;
39-
/// Longest a request may take, from sending it to its last body byte, whatever the
40-
/// HTTP client's own timeout.
39+
/// Longest a request may take, from connecting or sending it to its last body
40+
/// byte, whatever the HTTP client's own timeout.
4141
pub const REQUEST_DEADLINE: Duration = Duration::from_secs(10);
4242

4343
/// Access tokens this close to expiry are refreshed first.

‎crates/common/src/protocol/oauth.rs‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,42 @@ pub struct ErrorResponse {
464464
pub error_description: Option<ErrorDescription>,
465465
}
466466

467+
/// The token endpoint's success response (RFC 6749 §5.1), omitting the tokens the
468+
/// grant did not issue.
469+
// It holds credentials, so it has no `Debug`.
470+
#[derive(Serialize, Deserialize)]
471+
#[cfg_attr(test, derive(ts_rs::TS), ts(optional_fields))]
472+
pub struct TokenResponse {
473+
/// Short-lived signed bearer token for the resource audience.
474+
pub access_token: String,
475+
/// The access token's HTTP authentication scheme: auth sends `Bearer`, which
476+
/// clients compare without regard to case.
477+
pub token_type: String,
478+
/// Access token lifetime, in seconds.
479+
pub expires_in: u32,
480+
/// Granted scopes.
481+
pub scope: Scopes,
482+
/// Signed client-bound identity token, with the `openid` scope.
483+
#[serde(default, skip_serializing_if = "Option::is_none")]
484+
pub id_token: Option<String>,
485+
/// Opaque refresh token: the first of a grant refresh policy permits, or the
486+
/// replacement of a rotated one. A client that keeps its token gets none.
487+
#[serde(default, skip_serializing_if = "Option::is_none")]
488+
pub refresh_token: Option<String>,
489+
}
490+
491+
/// The pushed authorization endpoint's success response (RFC 9126 §2.2).
492+
#[derive(Debug, Serialize, Deserialize)]
493+
#[cfg_attr(test, derive(ts_rs::TS), ts(optional_fields))]
494+
pub struct PushedAuthorization {
495+
/// What the browser brings to the authorization endpoint, with `client_id`.
496+
pub request_uri: String,
497+
/// Seconds until `request_uri` expires. Auth always sends it; clients redirect
498+
/// the browser at once, so they ignore it.
499+
#[serde(skip_deserializing, skip_serializing_if = "Option::is_none")]
500+
pub expires_in: Option<u32>,
501+
}
502+
467503
#[cfg(test)]
468504
mod tests {
469505
//! Scope list syntax.

‎crates/common/src/protocol/typescript.rs‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Writes `packages/auth/src/protocol.ts`, the TypeScript SDK's declarations of these
2-
//! wire types, with ts-rs. Without `UPDATE_SDK_TYPES=1` it only compares, so
3-
//! `just test` fails while the committed file is stale; `just sdk-types` rewrites it.
2+
//! wire types and of the constants `sdk_constants!` declares, with ts-rs. Without
3+
//! `UPDATE_SDK_TYPES=1` it only compares, so `just test` fails while the committed
4+
//! file is stale; `just sdk-types` rewrites it.
45
//!
56
//! The structs derive `TS` under `cfg(test)`, so ts-rs stays a dev-dependency. Types
67
//! that serialize by hand implement it here, from the same values serde writes:
@@ -22,7 +23,8 @@ use super::{
2223
metadata::ServerMetadata,
2324
oauth::{
2425
ClientAuthMethod, CodeChallengeMethod, ErrorCode, ErrorDescription, ErrorResponse,
25-
GrantType, Prompt, ResponseMode, ResponseType, Scope, Scopes, SubjectType,
26+
GrantType, Prompt, PushedAuthorization, ResponseMode, ResponseType, Scope, Scopes,
27+
SubjectType, TokenResponse,
2628
},
2729
sdk::{ErrorCategory, ErrorReason, SdkError},
2830
step_up::StepUpRequirement,
@@ -35,7 +37,8 @@ use ts_rs::{Config, TS};
3537
/// Opens the generated file.
3638
const HEADER: &str = "\
3739
// Generated from sourceorigin_common::protocol by `just sdk-types`. Do not edit.
38-
// The wire types auth and every SDK share; docs/dev/architecture/sdk.md describes them.
40+
// The wire types and constants auth and every SDK share; docs/dev/architecture/sdk.md
41+
// describes them.
3942
";
4043

4144
/// Implements `TS` for a type declared in the generated file.
@@ -195,6 +198,8 @@ macro_rules! milliseconds {
195198
number!(u8, usize);
196199
milliseconds!(TimeDelta => num_milliseconds, Duration => as_millis);
197200

201+
/// Writes strings as their own literal type, with Rust's escapes, so a string
202+
/// constant must need none, as `union`'s spellings do.
198203
impl Literal for &str {
199204
fn ty(&self) -> Option<&'static str> {
200205
None
@@ -269,7 +274,7 @@ impl Declarations {
269274
self.text.push_str("\n/**\n");
270275
for line in docs.lines() {
271276
self.text.push_str(" * ");
272-
self.text.push_str(line.trim());
277+
self.text.push_str(line.strip_prefix(' ').unwrap_or(line));
273278
self.text.push('\n');
274279
}
275280
let ty = ty.map(|ty| format!(": {ty}")).unwrap_or_default();
@@ -372,6 +377,8 @@ fn generate() -> String {
372377
.closed::<Scope>()
373378
.add::<ErrorCode>()
374379
.add::<ErrorResponse>()
380+
.add::<TokenResponse>()
381+
.add::<PushedAuthorization>()
375382
// challenge
376383
.add::<BearerChallenge>()
377384
.add::<BearerError>()

0 commit comments

Comments
 (0)