Skip to content

Commit f0eafc6

Browse files
committed
fix(sdk): a step-up can no longer switch accounts, and refreshes keep the original sign-in
A step-up records the session's sub in its sealed pending-login cookie, and the callback fails, keeping the session unrevoked, when the new sign-in names another account than that or than the session it would replace. The callback redeems the code before revoking the replaced session, so it can check. Apps using Client directly can pin a login with AuthorizeRequest::id_token_hint. Client::refresh takes the sign-in's ID token claims and enforces OIDC Core 12.2: the same sub, auth_time and acr, and no other nonce; the session keeps the sign-in's nonce when a refresh returns none. Client::userinfo takes the claims and requires the same sub. New shared reasons: subject_mismatch and authentication_changed. Breaking: Client::refresh and Client::userinfo take the ID token's claims, AuthorizeRequest gains id_token_hint, and TokenError and OAuthError gain variants.
1 parent 1466f5c commit f0eafc6

14 files changed

Lines changed: 598 additions & 86 deletions

File tree

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

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -91,19 +91,25 @@ async fn sdk_login_client_runs_against_the_provider() {
9191
assert!(access.scopes.contains(Scope::OfflineAccess.as_str()));
9292

9393
let user = client
94-
.userinfo(&tokens.access_token)
94+
.userinfo(&tokens.access_token, id_token.claims())
9595
.await
9696
.expect("UserInfo");
9797
assert_eq!(user.sub, flow.user_id.to_string());
9898
assert!(user.profile.email.is_some());
9999

100-
// A confidential client keeps its refresh token, so a refresh returns none.
100+
// A confidential client keeps its refresh token, so a refresh returns none. Auth
101+
// carries the sign-in over to the refreshed ID token (OIDC Core §12.2), which
102+
// the SDK requires.
101103
let first = tokens.refresh_token.expect("refresh token");
102-
let refreshed = client.refresh(&first).await.expect("refresh");
104+
let refreshed = client
105+
.refresh(&first, id_token.claims())
106+
.await
107+
.expect("refresh");
108+
assert!(refreshed.id_token.is_some());
103109
assert!(refreshed.refresh_token.is_none());
104110
client.revoke(&first).await.expect("revoke");
105111
assert!(matches!(
106-
client.refresh(&first).await,
112+
client.refresh(&first, id_token.claims()).await,
107113
Err(OAuthError::Rejected { response, .. })
108114
if response.error == OAuthCode::InvalidGrant
109115
));

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,8 @@ pub(super) struct Login {
197197
/// the push fails. A browser keeps up to three logins at once, in slots chosen by
198198
/// their `state`; a login that lands in a taken slot replaces the one there.
199199
/// - `GET /callback` completes the login its `state` names and starts a session,
200-
/// first revoking the refresh token of the session it replaces.
200+
/// revoking the refresh token of the session it replaces first. A step-up must
201+
/// sign in the same user as that session, or it fails and keeps the session.
201202
/// - `POST /logout` revokes the session's refresh token at auth, clears the cookie,
202203
/// and redirects to RP-initiated logout.
203204
/// - `POST /backchannel-logout`, only with [`Self::on_backchannel_logout`].

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

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
1010
use super::{Login, SessionCookie, SignedIn, layer::RequestSession};
1111
use crate::{
12-
OAuthError,
12+
OAuthError, TokenError,
1313
axum::{StoredLogin, bearer::ErrorChain},
1414
protocol::oauth::{ErrorCode, ErrorResponse},
1515
};
@@ -32,7 +32,8 @@ enum Refresh {
3232
/// Auth could not be asked, or answered with an error other than a refusal: the
3333
/// session goes on as it was, and a later request tries again.
3434
Kept,
35-
/// Auth refused the refresh token, or named another user: the session is over.
35+
/// Auth refused the refresh token, or named another user or sign-in: the session
36+
/// is over.
3637
Ended,
3738
}
3839

@@ -113,19 +114,21 @@ impl Login {
113114
let Some(refresh_token) = login.refresh_token() else {
114115
return Refresh::Kept;
115116
};
116-
let refreshing = self.client.refresh(refresh_token);
117+
let refreshing = self.client.refresh(refresh_token, login.claims());
117118
let Ok(refreshed) = tokio::time::timeout(REFRESH_DEADLINE, refreshing).await else {
118119
tracing::warn!("session refresh timed out");
119120
return Refresh::Kept;
120121
};
121122
match refreshed {
122-
Ok(tokens) => login.refreshed(tokens).map_or_else(
123-
|| {
124-
tracing::warn!("refresh returned an ID token for another user");
125-
Refresh::Ended
126-
},
127-
|refreshed| Refresh::Refreshed(Box::new(refreshed)),
128-
),
123+
Ok(tokens) => Refresh::Refreshed(Box::new(login.refreshed(tokens))),
124+
// The new ID token names another user or another sign-in (OIDC Core
125+
// §12.2): the session cannot go on as either.
126+
Err(OAuthError::IdToken(
127+
error @ (TokenError::SubjectMismatch { .. } | TokenError::AuthenticationChanged(_)),
128+
)) => {
129+
tracing::warn!(error = %ErrorChain(&error), "a refresh changed the signed-in user or sign-in");
130+
Refresh::Ended
131+
}
129132
// Auth refused the refresh token: the grant is over.
130133
Err(
131134
error @ OAuthError::Rejected {

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

Lines changed: 58 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ impl Login {
4747
/// `GET /login`: keeps a pending login in a sealed cookie and redirects to auth.
4848
pub(super) async fn start(
4949
State(login): State<Arc<Self>>,
50+
headers: HeaderMap,
5051
Query(query): Query<StartQuery>,
5152
) -> Response {
5253
let return_to = query
@@ -86,10 +87,18 @@ impl Login {
8687
}
8788
};
8889
let name = login.cookies.pending(pending.state());
90+
// A step-up strengthens the session it starts from, so it is pinned to its
91+
// user. The session holds no raw ID token to send as `id_token_hint`, so auth
92+
// may let another account sign in; the callback refuses it.
93+
let subject = match login.open_session(&headers) {
94+
SessionCookie::Open(session) if query.step_up => Some(session.subject().to_owned()),
95+
_ => None,
96+
};
8997
let mut pending = PendingAuthorization {
9098
login: pending,
9199
return_to,
92100
step_up: query.step_up,
101+
subject,
93102
expires_at: login.now() + PENDING_LIFETIME,
94103
};
95104
// A `return_to` too long for the cookie returns home instead, or to the root
@@ -173,26 +182,21 @@ impl Login {
173182
}
174183

175184
/// Completes `pending` from `callback` and starts its session. The session the
176-
/// browser had, in `headers`, is replaced, and its refresh token revoked first,
177-
/// so no copy of it, nor a response still in flight that sets it back, outlives
178-
/// its access token. If auth cannot revoke it, the sign-in stops before the code
179-
/// is redeemed, with 502, and the browser keeps its session.
185+
/// browser had, in `headers`, is replaced, and its refresh token revoked before
186+
/// the new session is set, so no copy of it, nor a response still in flight that
187+
/// sets it back, outlives its access token. If auth cannot revoke it, the sign-in
188+
/// fails with 502 and the browser keeps its session; the code is spent, so the
189+
/// user starts again.
190+
///
191+
/// A step-up must sign in the user it started from, and the one whose session it
192+
/// replaces, as after switching accounts in another tab: otherwise it fails, and
193+
/// the session it would replace is kept, its refresh token unrevoked.
180194
async fn complete(
181195
&self,
182196
headers: &HeaderMap,
183197
pending: PendingAuthorization,
184198
callback: &CallbackParams,
185199
) -> Response {
186-
if let SessionCookie::Open(previous) = self.open_session(headers)
187-
&& let Some(refresh_token) = previous.refresh_token()
188-
&& !self.revoke(refresh_token).await
189-
{
190-
return (
191-
StatusCode::BAD_GATEWAY,
192-
"Signing in could not end your previous session; start again.",
193-
)
194-
.into_response();
195-
}
196200
let tokens = match self.client.complete(pending.login, callback).await {
197201
Ok(tokens) => tokens,
198202
Err(error) => {
@@ -208,6 +212,37 @@ impl Login {
208212
let Some(stored) = StoredLogin::new(tokens, self.now() + self.lifetime) else {
209213
return StatusCode::BAD_GATEWAY.into_response();
210214
};
215+
let previous = match self.open_session(headers) {
216+
SessionCookie::Open(previous) => Some(previous),
217+
_ => None,
218+
};
219+
let replaced = previous.as_ref().map(|previous| previous.subject());
220+
if pending.step_up
221+
&& [pending.subject.as_deref(), replaced]
222+
.into_iter()
223+
.flatten()
224+
.any(|subject| subject != stored.subject())
225+
{
226+
tracing::debug!("a step-up signed in another account");
227+
self.abandon(&stored).await;
228+
return (
229+
StatusCode::BAD_REQUEST,
230+
"Sign-in failed: this step-up signed in another account than this session's.",
231+
)
232+
.into_response();
233+
}
234+
if let Some(refresh_token) = previous
235+
.as_ref()
236+
.and_then(|previous| previous.refresh_token())
237+
&& !self.revoke(refresh_token).await
238+
{
239+
self.abandon(&stored).await;
240+
return (
241+
StatusCode::BAD_GATEWAY,
242+
"Signing in could not end your previous session; start again.",
243+
)
244+
.into_response();
245+
}
211246
let session = match self.session_cookie(&stored) {
212247
Ok(session) => session,
213248
Err(error) => {
@@ -237,6 +272,15 @@ impl Login {
237272
response
238273
}
239274

275+
/// Revokes the grant of `login`, a sign-in the callback refuses after redeeming
276+
/// its code, so it does not live on at auth unused. A failure is logged by
277+
/// [`Self::revoke`] and changes nothing: the refusal stands either way.
278+
async fn abandon(&self, login: &StoredLogin) {
279+
if let Some(refresh_token) = login.refresh_token() {
280+
self.revoke(refresh_token).await;
281+
}
282+
}
283+
240284
/// Revokes `refresh_token` at auth, within [`REVOCATION_DEADLINE`], so a hanging
241285
/// auth cannot hold up the sign-in or logout around it. Returns whether auth
242286
/// revoked it, logging why not.

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

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ pub struct StoredLogin(pub(super) LoginData);
3434
#[derive(Clone, Debug, Serialize, Deserialize)]
3535
pub(super) struct LoginData {
3636
/// The validated claims of the sign-in's ID token, or of the latest refresh that
37-
/// returned one.
37+
/// returned one, which kept the sign-in's `sub`, `auth_time` and `acr`, and its
38+
/// `nonce` even when it returned none (OIDC Core §12.2).
3839
claims: IdTokenClaims,
3940
/// The latest access token.
4041
access_token: BearerToken,
@@ -73,20 +74,22 @@ impl StoredLogin {
7374
}))
7475
}
7576

76-
/// This session after a refresh returned `tokens`. An absent ID token or refresh
77-
/// token keeps the current one. `None` if a new ID token names another user or
78-
/// issuer (OIDC Core §12.2).
79-
pub(super) fn refreshed(&self, tokens: Tokens) -> Option<Self> {
77+
/// This session after a refresh returned `tokens`, which
78+
/// [`Client::refresh`](crate::Client::refresh) checked against its claims (OIDC
79+
/// Core §12.2). An absent ID token or refresh token keeps the current one, and a
80+
/// new ID token without a `nonce` keeps the sign-in's, which the next refresh is
81+
/// checked against.
82+
pub(super) fn refreshed(&self, tokens: Tokens) -> Self {
8083
let current = &self.0;
8184
let claims = match tokens.id_token {
8285
Some(id_token) => {
83-
let claims = id_token.into_claims();
84-
(claims.sub == current.claims.sub && claims.iss == current.claims.iss)
85-
.then_some(claims)?
86+
let mut claims = id_token.into_claims();
87+
claims.nonce = claims.nonce.or_else(|| current.claims.nonce.clone());
88+
claims
8689
}
8790
None => current.claims.clone(),
8891
};
89-
Some(Self(LoginData {
92+
Self(LoginData {
9093
claims,
9194
access_token: tokens.access_token,
9295
expires_at: tokens.expires_at,
@@ -95,7 +98,7 @@ impl StoredLogin {
9598
.refresh_token
9699
.or_else(|| current.refresh_token.clone()),
97100
ends_at: current.ends_at,
98-
}))
101+
})
99102
}
100103

101104
/// The validated claims of the sign-in's ID token, or of the latest refresh that
@@ -158,6 +161,9 @@ pub(super) struct PendingAuthorization {
158161
pub(super) return_to: ReturnTo,
159162
/// Whether the login steps up, so the return to `return_to` is its retry.
160163
pub(super) step_up: bool,
164+
/// The user a step-up started from, whom its new sign-in must name too.
165+
#[serde(default, skip_serializing_if = "Option::is_none")]
166+
pub(super) subject: Option<String>,
161167
/// When the login expires, checked as well as the cookie's `Max-Age`, which a
162168
/// copied cookie escapes.
163169
pub(super) expires_at: DateTime<Utc>,

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

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,3 +283,115 @@ async fn signed_in_refuses_unsafe_requests_from_other_origins() {
283283
}
284284
}
285285
}
286+
287+
/// Another account than the session's.
288+
const OTHER: &str = "01936f3e-8c00-7000-8000-000000000009";
289+
290+
/// A step-up must sign in the user it started from, and the one whose session it
291+
/// replaces: otherwise it fails with 400 and keeps that session, its refresh token
292+
/// unrevoked, while the grant it was refused revokes. An ordinary sign-in may switch
293+
/// accounts.
294+
#[tokio::test]
295+
async fn step_ups_stay_on_the_signed_in_account() {
296+
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
297+
let app = login_app(&endpoint.issuer(&clock()));
298+
let session = sign_in(&app, USER).await;
299+
let step_up = "%2F&step_up=true";
300+
let refused = |response: &Response| {
301+
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
302+
assert_eq!(
303+
set_cookie(response, SESSION_COOKIE),
304+
None,
305+
"the session is kept"
306+
);
307+
};
308+
309+
// Started from the session, then completed as another account.
310+
let login = Started::at(&app, step_up, std::slice::from_ref(&session)).await;
311+
let both = [login.cookie.clone(), session.clone()];
312+
refused(&login.complete(&app, OTHER, &both).await);
313+
// Started from the session, which another tab then signed out of: the pin alone
314+
// stops another account.
315+
let login = Started::at(&app, step_up, std::slice::from_ref(&session)).await;
316+
refused(
317+
&login
318+
.complete(&app, OTHER, std::slice::from_ref(&login.cookie))
319+
.await,
320+
);
321+
// Started without a session, then completed beside another account's.
322+
let login = Started::at(&app, step_up, &[]).await;
323+
let both = [login.cookie.clone(), session.clone()];
324+
refused(&login.complete(&app, OTHER, &both).await);
325+
// The session's grant is `refresh-0`; each refused sign-in's, revoked, the next.
326+
assert_eq!(
327+
*endpoint.revoked.lock().expect("revoked"),
328+
["refresh-1", "refresh-2", "refresh-3"]
329+
);
330+
331+
let login = Started::at(&app, step_up, std::slice::from_ref(&session)).await;
332+
let both = [login.cookie.clone(), session.clone()];
333+
let response = login.complete(&app, USER, &both).await;
334+
assert_eq!(response.status(), StatusCode::SEE_OTHER);
335+
assert_eq!(
336+
endpoint
337+
.revoked
338+
.lock()
339+
.expect("revoked")
340+
.last()
341+
.map(String::as_str),
342+
Some("refresh-0"),
343+
"the replaced session's grant"
344+
);
345+
346+
let login = Started::at(&app, "%2F", std::slice::from_ref(&session)).await;
347+
let both = [login.cookie.clone(), session];
348+
let response = login.complete(&app, OTHER, &both).await;
349+
assert_eq!(
350+
response.status(),
351+
StatusCode::SEE_OTHER,
352+
"an ordinary sign-in"
353+
);
354+
}
355+
356+
/// A login with `id_token_hint` sends it to auth, and completes only for the user it
357+
/// names; another user's grant is revoked as it is refused.
358+
#[tokio::test]
359+
async fn hinted_logins_complete_only_for_the_hinted_user() {
360+
let endpoint = TokenEndpoint::start(Duration::ZERO).await;
361+
let client = client(&endpoint.issuer(&clock()));
362+
let hint: crate::IdToken =
363+
serde_json::from_value(json!({ "claims": id_claims(USER), "raw": "id-0" }))
364+
.expect("ID token");
365+
let request = crate::AuthorizeRequest {
366+
id_token_hint: Some(hint),
367+
..crate::AuthorizeRequest::default()
368+
};
369+
for (sub, completes) in [(OTHER, false), (USER, true)] {
370+
let (url, pending) = client.authorize(&request).await.expect("authorize");
371+
let parameter = |name: &str| {
372+
url.query_pairs()
373+
.find_map(|(key, value)| (key == name).then(|| value.into_owned()))
374+
.expect("parameter")
375+
};
376+
assert_eq!(parameter("id_token_hint"), "id-0");
377+
let callback = crate::CallbackParams {
378+
code: Some(code(sub, &parameter("nonce"))),
379+
state: Some(parameter("state")),
380+
iss: Some("https://auth.example.com".into()),
381+
..crate::CallbackParams::default()
382+
};
383+
let completed = client.complete(pending, &callback).await;
384+
assert_eq!(completed.is_ok(), completes, "{sub}");
385+
let revoked = endpoint.revoked.lock().expect("revoked").clone();
386+
assert_eq!(revoked, ["refresh-0"], "only the refused grant, {sub}");
387+
if let Err(error) = completed {
388+
assert_eq!(
389+
error.code(),
390+
crate::SdkError::new(
391+
crate::protocol::sdk::ErrorCategory::InvalidToken,
392+
crate::protocol::sdk::ErrorReason::SubjectMismatch
393+
)
394+
);
395+
}
396+
}
397+
}

0 commit comments

Comments
 (0)