diff --git a/apps/auth-service/src/keys/tests.rs b/apps/auth-service/src/keys/tests.rs index 53086719e..111ac2e96 100644 --- a/apps/auth-service/src/keys/tests.rs +++ b/apps/auth-service/src/keys/tests.rs @@ -12,10 +12,13 @@ use axum::{ body::Body, http::{Request, StatusCode}, }; -use serde_json::{Value, json}; +use serde_json::json; use sourceorigin_common::{ events::Actor, - protocol::jwt::{Jwk, TokenType}, + protocol::{ + claims::AccessTokenClaims, + jwt::{Jwk, TokenType}, + }, }; use sourceorigin_crypto::KeyEncryptionKey; use sourceorigin_repository::{EventFilter, InsertSigningKey}; @@ -129,7 +132,7 @@ fn hint(keys: &KeySet) -> String { let now = Utc::now().timestamp(); keys.sign( TokenType::Id, - &json!({"iss": ISSUER, "aud": "client", "iat": now - 600, "exp": now - 300}), + &json!({"iss": ISSUER, "sub": "user", "aud": "client", "iat": now - 600, "exp": now - 300}), ) .expect("sign hint") } @@ -139,7 +142,9 @@ fn access_token(keys: &KeySet) -> String { let now = Utc::now().timestamp(); keys.sign( TokenType::Access, - &json!({"iss": ISSUER, "iat": now, "exp": now + 300}), + &json!({"iss": ISSUER, "sub": "user", "aud": "client", "client_id": "client", + "jti": "01936f3e-8c00-7000-8000-000000000003", "scope": "openid", "iat": now, + "exp": now + 300}), ) .expect("sign token") } @@ -223,7 +228,7 @@ async fn rotation_takes_each_step_once_on_schedule() { let keys = key_set(&store, &mut tx).await; assert_eq!(keys.signer().kid(), second.as_str()); assert!( - keys.verify::(&first_token, TokenType::Access, ISSUER) + keys.verify::(&first_token, TokenType::Access, ISSUER, Utc::now()) .is_ok(), "a retiring key's tokens verify" ); @@ -246,11 +251,12 @@ async fn rotation_takes_each_step_once_on_schedule() { let keys = key_set(&store, &mut tx).await; assert!(keys.jwks().keys.iter().all(|key| key.kid != first.as_str())); assert!(matches!( - keys.verify::(&first_token, TokenType::Access, ISSUER), + keys.verify::(&first_token, TokenType::Access, ISSUER, Utc::now()), Err(CryptoError::UnknownKey) )); assert!( - keys.verify_id_token_hint(&first_hint, ISSUER).is_ok(), + keys.verify_id_token_hint(&first_hint, ISSUER, Utc::now()) + .is_ok(), "a retired key's hints verify" ); @@ -268,7 +274,7 @@ async fn rotation_takes_each_step_once_on_schedule() { assert!(matches!( key_set(&store, &mut tx) .await - .verify_id_token_hint(&first_hint, ISSUER), + .verify_id_token_hint(&first_hint, ISSUER, Utc::now()), Err(CryptoError::UnknownKey) )); let first_changes = [Generated, Activated, Retiring, Retired, Deleted]; @@ -350,11 +356,11 @@ async fn revoking_a_key_removes_it_and_replaces_the_signer() { let keys = key_set(&store, &mut tx).await; assert_eq!(keys.signer().kid(), replacement.as_str()); assert!(matches!( - keys.verify::(&token, TokenType::Access, ISSUER), + keys.verify::(&token, TokenType::Access, ISSUER, Utc::now()), Err(CryptoError::UnknownKey) )); assert!(matches!( - keys.verify_id_token_hint(&revoked_hint, ISSUER), + keys.verify_id_token_hint(&revoked_hint, ISSUER, Utc::now()), Err(CryptoError::UnknownKey) )); assert_eq!(kids(&keys), [replacement.to_string()]); diff --git a/apps/auth-service/src/oidc/hint.rs b/apps/auth-service/src/oidc/hint.rs index 3c6d24eb2..0c1f25671 100644 --- a/apps/auth-service/src/oidc/hint.rs +++ b/apps/auth-service/src/oidc/hint.rs @@ -1,9 +1,9 @@ //! The `id_token_hint` authorization and logout both read: an ID token auth signed, //! read the same way by both. -use super::{Claim, OAuthCode, OAuthError, OidcApplication, Reject}; -use serde_json::Value; -use sourceorigin_common::{ClientId, SessionId, UserId}; +use super::{OAuthCode, OAuthError, OidcApplication, Reject}; +use chrono::Utc; +use sourceorigin_common::{ClientId, SessionId, UserId, protocol::claims::Audience}; use sourceorigin_crypto::CryptoError; /// What a verified `id_token_hint` says: the client auth issued it to, and the @@ -19,8 +19,9 @@ pub(super) struct IdTokenHint { /// Why an `id_token_hint` was not read. pub(super) enum HintError { - /// Auth can't verify the token: it is malformed, forged, or signed by a key - /// auth no longer keeps. Logout goes on without it; authorization refuses it. + /// Auth can't verify the token: it is malformed, forged, signed by a key auth + /// no longer keeps, or names another issuer or a future `nbf` or `iat`. Logout + /// goes on without it; authorization refuses it. Unverified(CryptoError), /// The request is refused: auth's keys are unavailable, or auth signed the /// token but its claims are not ones auth issues. @@ -45,45 +46,41 @@ impl From for OAuthError { } impl OidcApplication { - /// Reads an `id_token_hint`, signed by a published or retired key. Expiry - /// doesn't count: an expired ID token still names its account, and - /// RP-Initiated Logout §2 asks logout to accept one. It must still have a - /// numeric `exp`, and its `sub` must be an account ID. + /// Reads an `id_token_hint`, signed by a published or retired key, whose issuer + /// and times pass the shared check. Expiry doesn't count: an expired ID token + /// still names its account, and RP-Initiated Logout §2 asks logout to accept + /// one. Its claims must still decode as an ID token's, a numeric `exp` + /// included, name one client, and its `sub` must be an account ID. pub(super) fn id_token_hint(&self, token: &str) -> Result { let claims = self .keys .current() .map_err(OAuthError::from)? - .verify_id_token_hint(token, &self.issuer) - .map_err(HintError::Unverified)?; - let text = |claim: Claim| claims.get(claim.as_str()).and_then(Value::as_str); - let client = text(Claim::Audience) - .unwrap_or_default() - .parse() - .map_err(|error| { - OAuthCode::InvalidRequest - .reject_with("id_token_hint audience is not a client ID", error) + .verify_id_token_hint(token, &self.issuer, Utc::now()) + .map_err(|error| match error { + CryptoError::InvalidClaims(error) => HintError::Refused( + OAuthCode::InvalidRequest + .reject_with(format!("id_token_hint claims are invalid: {error}"), error), + ), + error => HintError::Unverified(error), })?; - if claims - .get(Claim::ExpiresAt.as_str()) - .and_then(Value::as_i64) - .is_none() - { + let Audience::One(client) = &claims.aud else { return Err(OAuthCode::InvalidRequest - .reject("id_token_hint has no numeric exp claim") + .reject("id_token_hint audience is not a client ID") .into()); - } - let user = text(Claim::Subject) - .ok_or_else(|| OAuthCode::InvalidRequest.reject("id_token_hint has no sub claim"))? - .parse() - .map_err(|error| { - OAuthCode::InvalidRequest - .reject_with("id_token_hint sub claim is not an account ID", error) - })?; + }; + let client = client.parse().map_err(|error| { + OAuthCode::InvalidRequest + .reject_with("id_token_hint audience is not a client ID", error) + })?; + let user = claims.sub.parse().map_err(|error| { + OAuthCode::InvalidRequest + .reject_with("id_token_hint sub claim is not an account ID", error) + })?; Ok(IdTokenHint { client, user, - session: text(Claim::Session).and_then(|sid| sid.parse().ok()), + session: claims.authentication.sid, }) } } diff --git a/apps/auth-service/src/oidc/tests/authorization.rs b/apps/auth-service/src/oidc/tests/authorization.rs index 8f5d640b0..1836e45e6 100644 --- a/apps/auth-service/src/oidc/tests/authorization.rs +++ b/apps/auth-service/src/oidc/tests/authorization.rs @@ -39,6 +39,7 @@ async fn public_consent_pkce_claim_scoping_and_replay() { .expect("token response contains an ID token"), TokenType::Id, &flow.app.issuer, + Utc::now(), ) .expect("verify scoped ID token"); assert_eq!(claims.nonce.as_deref(), Some("test-nonce")); diff --git a/apps/auth-service/src/oidc/tests/errors.rs b/apps/auth-service/src/oidc/tests/errors.rs index 59253a81f..e7433bbc0 100644 --- a/apps/auth-service/src/oidc/tests/errors.rs +++ b/apps/auth-service/src/oidc/tests/errors.rs @@ -3,6 +3,7 @@ //! and auth's page for a request whose redirect URI isn't verified yet. use super::*; +use chrono::Timelike; /// The scenario's authorization request with `pairs` set, replacing any of the /// same name, and those named in `removed` left out. @@ -153,37 +154,46 @@ async fn token_endpoint_errors_follow_rfc_6749() { } /// An access token without the `openid` scope is refused at `UserInfo` with -/// `insufficient_scope`, at 403, naming the scope it needs. +/// `insufficient_scope`, at 403, naming the scope it needs. An expired one is +/// refused with `invalid_token`, and the description names when it expired. #[tokio::test] #[ignore = "requires TEST_DATABASE_URL"] -async fn userinfo_needs_the_openid_scope() { +async fn userinfo_needs_the_openid_scope_and_an_unexpired_token() { let flow = Flow::new(false, true).await; let keys = flow.app.keys.current().expect("keys"); - let token = keys - .sign( - TokenType::Access, - &sourceorigin_common::protocol::claims::AccessTokenClaims { - iss: flow.app.issuer.clone(), - sub: flow.user_id.to_string(), - aud: sourceorigin_common::protocol::claims::Audience::One("api".into()), - client_id: flow.client.id.clone(), - jti: sourceorigin_common::TokenId::new(), - scope: "profile".parse().expect("scopes"), - iat: Utc::now(), - exp: Utc::now() + chrono::Duration::minutes(5), - nbf: None, - authentication: - sourceorigin_common::protocol::claims::AuthenticationClaims::default(), - act: None, - cnf: None, - profile: sourceorigin_common::protocol::claims::ProfileClaims::default(), - extra: (), - }, - ) - .expect("access token"); - let bearer = format!("{} {token}", AuthScheme::Bearer); + let now = Utc::now().with_nanosecond(0).expect("whole seconds"); + let access_token = |scope: &str, exp| { + let token = keys + .sign( + TokenType::Access, + &sourceorigin_common::protocol::claims::AccessTokenClaims { + iss: flow.app.issuer.clone(), + sub: flow.user_id.to_string(), + aud: sourceorigin_common::protocol::claims::Audience::One("api".into()), + client_id: flow.client.id.clone(), + jti: sourceorigin_common::TokenId::new(), + scope: scope.parse().expect("scopes"), + iat: now - chrono::Duration::minutes(10), + exp, + nbf: None, + authentication: + sourceorigin_common::protocol::claims::AuthenticationClaims::default(), + act: None, + cnf: None, + profile: sourceorigin_common::protocol::claims::ProfileClaims::default(), + extra: (), + }, + ) + .expect("access token"); + format!("{} {token}", AuthScheme::Bearer) + }; let response = flow - .request(Method::GET, routes::oidc::USERINFO, &[], Some(&bearer)) + .request( + Method::GET, + routes::oidc::USERINFO, + &[], + Some(&access_token("profile", now + chrono::Duration::minutes(5))), + ) .await; assert_eq!(response.status(), StatusCode::FORBIDDEN); assert_eq!( @@ -194,4 +204,21 @@ async fn userinfo_needs_the_openid_scope() { json(response).await["error"], OAuthCode::InsufficientScope.as_str() ); + + let expired = now - chrono::Duration::minutes(1); + let response = flow + .request( + Method::GET, + routes::oidc::USERINFO, + &[], + Some(&access_token(Scope::OpenId.as_str(), expired)), + ) + .await; + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + let body = json(response).await; + assert_eq!(body["error"], OAuthCode::InvalidToken.as_str()); + assert_eq!( + body["error_description"], + format!("access token is invalid: token expired at {expired}") + ); } diff --git a/apps/auth-service/src/oidc/tests/logout.rs b/apps/auth-service/src/oidc/tests/logout.rs index d88e1b047..43c4b2ce8 100644 --- a/apps/auth-service/src/oidc/tests/logout.rs +++ b/apps/auth-service/src/oidc/tests/logout.rs @@ -4,7 +4,7 @@ use super::*; use crate::deliveries::{BackchannelLogoutSender, OutboundClient, Sender}; use sourceorigin_common::SessionId; use sourceorigin_common::clients::{BackchannelLogoutUri, ClientOwner}; -use sourceorigin_common::protocol::claims::BACKCHANNEL_LOGOUT_EVENT; +use sourceorigin_common::protocol::claims::{BACKCHANNEL_LOGOUT_EVENT, LogoutTokenClaims}; use sourceorigin_repository::BackchannelLogout; use std::{collections::HashMap, sync::Mutex}; @@ -106,13 +106,14 @@ async fn logout_posts_a_logout_token_to_the_clients_of_the_session() { assert_eq!(client, told.id); let [token] = <[_; 1]>::try_from(posted.lock().expect("posted tokens").clone()) .expect("one token posted"); - let claims: Value = flow + let claims: LogoutTokenClaims = flow .app .keys .current() .expect("fresh keys") - .verify(&token, TokenType::Logout, &flow.app.issuer) + .verify(&token, TokenType::Logout, &flow.app.issuer, Utc::now()) .expect("a logout token signed by auth"); + let claims = serde_json::to_value(claims).expect("claims"); let issued_at = claims["iat"].as_i64().expect("iat"); assert!( (issued_at - Utc::now().timestamp()).abs() < 60, @@ -347,9 +348,10 @@ async fn a_hint_naming_another_account_says_so() { } /// Authorization and logout read an `id_token_hint` alike: both refuse one auth -/// signed without a numeric `exp`, or whose `sub` is no account ID. Logout still -/// accepts an expired one, as RP-Initiated Logout §2 asks, and goes back to the -/// application it names. +/// signed whose claims don't decode as an ID token's, such as one without a +/// numeric `exp` or `iat` or with a `sid` that is no session ID, or whose `sub` is +/// no account ID. Logout still accepts an expired one, as RP-Initiated Logout §2 +/// asks, and goes back to the application it names. #[tokio::test] #[ignore = "requires TEST_DATABASE_URL"] async fn authorization_and_logout_read_a_hint_alike() { @@ -366,9 +368,18 @@ async fn authorization_and_logout_read_a_hint_alike() { }; let mut no_exp = expired.clone(); no_exp.as_object_mut().expect("claims").remove("exp"); + let mut no_iat = expired.clone(); + no_iat.as_object_mut().expect("claims").remove("iat"); + let mut no_session = expired.clone(); + no_session["sid"] = json!("not-a-session"); let mut no_account = expired.clone(); no_account["sub"] = json!("not-an-account"); - for claims in [no_exp, no_account] { + for (claims, description) in [ + (no_exp, "id_token_hint claims are invalid"), + (no_iat, "id_token_hint claims are invalid"), + (no_session, "id_token_hint claims are invalid"), + (no_account, "id_token_hint sub claim is not an account ID"), + ] { let hint = sign(&claims); let authorized = flow .authorize_with( @@ -378,11 +389,16 @@ async fn authorization_and_logout_read_a_hint_alike() { &[("id_token_hint", &hint)], ) .await; + let redirect = flow.client_redirect(&authorized); assert_eq!( - parameter(&flow.client_redirect(&authorized), "error"), + parameter(&redirect, "error"), OAuthCode::InvalidRequest.as_str(), "{claims}" ); + assert!( + parameter(&redirect, "error_description").starts_with(description), + "{claims}" + ); let logout = flow .request( Method::POST, diff --git a/apps/auth-service/src/oidc/tests/mod.rs b/apps/auth-service/src/oidc/tests/mod.rs index e6fe7680f..e4fa2ebfe 100644 --- a/apps/auth-service/src/oidc/tests/mod.rs +++ b/apps/auth-service/src/oidc/tests/mod.rs @@ -331,7 +331,7 @@ impl Flow { async fn id_token(&self, response: Response) -> (Value, Value) { assert_eq!(response.status(), StatusCode::OK); let tokens = json(response).await; - let claims = self + let claims: IdTokenClaims = self .app .keys .current() @@ -340,9 +340,10 @@ impl Flow { tokens["id_token"].as_str().expect("ID token"), TokenType::Id, &self.app.issuer, + Utc::now(), ) .expect("verify ID token"); - (tokens, claims) + (tokens, serde_json::to_value(claims).expect("claims")) } /// The scenario's account, as the owner of its browser session. async fn owner(&self) -> crate::account::Owner { diff --git a/apps/auth-service/src/oidc/tests/tokens.rs b/apps/auth-service/src/oidc/tests/tokens.rs index f7c9aa52c..f7b4d91f7 100644 --- a/apps/auth-service/src/oidc/tests/tokens.rs +++ b/apps/auth-service/src/oidc/tests/tokens.rs @@ -40,6 +40,7 @@ async fn confidential_refresh_keeps_its_token_logout_and_client_binding() { .expect("token response contains an ID token"), TokenType::Id, &flow.app.issuer, + Utc::now(), ) .expect("verify confidential client ID token"); assert_eq!( @@ -97,6 +98,7 @@ async fn confidential_refresh_keeps_its_token_logout_and_client_binding() { .expect("refresh response contains an ID token"), TokenType::Id, &flow.app.issuer, + Utc::now(), ) .expect("verify narrowed ID token"); assert!(narrowed_claims.profile.email.is_none()); diff --git a/apps/auth-service/src/oidc/token.rs b/apps/auth-service/src/oidc/token.rs index 2c4910ad4..c03be9d71 100644 --- a/apps/auth-service/src/oidc/token.rs +++ b/apps/auth-service/src/oidc/token.rs @@ -638,7 +638,7 @@ impl OidcApplication { let claims: AccessTokenClaims = self .keys .current()? - .verify(token, TokenType::Access, &self.issuer) + .verify(token, TokenType::Access, &self.issuer, Utc::now()) .map_err(|error| { invalid( OAuthCode::InvalidToken diff --git a/crates/common/src/protocol/claims.rs b/crates/common/src/protocol/claims.rs index 7bebc0596..2b4c06365 100644 --- a/crates/common/src/protocol/claims.rs +++ b/crates/common/src/protocol/claims.rs @@ -244,6 +244,10 @@ pub struct AccessTokenClaims { } /// Claims of an ID token (OIDC Core §2), signed with `typ: JWT`. +/// +/// Decoding must stay backward-compatible: auth reads every `id_token_hint` it +/// signed as these claims, even expired or signed by a retired key, so a field +/// made stricter would refuse every older hint at authorization and logout. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(test, derive(ts_rs::TS), ts(optional_fields))] pub struct IdTokenClaims { diff --git a/crates/crypto/src/lib.rs b/crates/crypto/src/lib.rs index a00607eb0..274e41251 100644 --- a/crates/crypto/src/lib.rs +++ b/crates/crypto/src/lib.rs @@ -23,6 +23,7 @@ use aws_lc_rs::{ }; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use secrecy::{ExposeSecret, SecretBox, SecretString, zeroize::Zeroizing}; +use sourceorigin_common::protocol::registered::ClaimsError; use std::fmt; use thiserror::Error; @@ -65,15 +66,18 @@ pub enum CryptoError { /// A JWT segment contains malformed JSON. #[error("invalid JWT JSON")] Json(#[from] serde_json::Error), - /// A token has invalid framing, headers or claims. - #[error("JWT framing, headers or claims are invalid")] + /// A token has invalid framing or headers. + #[error("JWT framing or headers are invalid")] InvalidToken, /// A JWT signature did not verify. #[error("JWT signature is invalid")] Signature, - /// A JWT has expired. - #[error("JWT has expired")] - Expired, + /// A signed JWT's claims are missing or have the wrong type. + #[error("JWT claims are invalid")] + InvalidClaims(#[source] serde_json::Error), + /// A signed JWT's issuer or times fail the shared check, which names the claim. + #[error(transparent)] + Claims(#[from] ClaimsError), /// A JWT names a key outside the key set: unknown, revoked or deleted. #[error("JWT names a key outside the key set")] UnknownKey, diff --git a/crates/crypto/src/signing/mod.rs b/crates/crypto/src/signing/mod.rs index a8a936c39..0674c9b5f 100644 --- a/crates/crypto/src/signing/mod.rs +++ b/crates/crypto/src/signing/mod.rs @@ -12,12 +12,13 @@ use base64::{ Engine, engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}, }; -use chrono::Utc; +use chrono::{DateTime, Utc}; use secrecy::zeroize::Zeroizing; use serde::{Deserialize, Serialize, de::DeserializeOwned}; -use serde_json::Value; -use sourceorigin_common::protocol::jwt::{ - Algorithm, Claim, Jwk, JwkSet, KeyId, KeyType, KeyUse, TokenType, +use sourceorigin_common::protocol::{ + claims::IdTokenClaims, + jwt::{Algorithm, Jwk, JwkSet, KeyId, KeyType, KeyUse, TokenType}, + registered::{Expiry, RegisteredClaims, Validation}, }; use std::{borrow::Cow, collections::BTreeSet}; @@ -27,8 +28,6 @@ const GENERATED_RSA_SIZE: KeySize = KeySize::Rsa3072; const PKCS8_LABEL: &str = "PRIVATE KEY"; /// The PEM label of a public key. const PUBLIC_KEY_LABEL: &str = "PUBLIC KEY"; -/// Maximum tolerated future issuance time. -const ISSUED_AT_SKEW_SECONDS: i64 = 30; /// Protected JOSE header. It is the only header auth writes and the only one it /// accepts back: unknown fields, `crit` included, fail parsing. @@ -137,14 +136,17 @@ impl PublicKey { } } - /// Verifies the signature, type, issuer and issue time of a token naming this - /// key, but not its expiry, and returns its claims. - fn verified( + /// Verifies the type and signature of a token naming this key, decodes its + /// claims as `T`, and checks them at `now` as auth checks its own tokens: from + /// `issuer`, of any audience and nonce, expiring as `expiry` says. + fn verified( &self, token: &Token<'_>, typ: TokenType, issuer: &str, - ) -> Result { + expiry: Expiry, + now: DateTime, + ) -> Result { if token.header.typ != typ || !self.signs_with(token.header.alg) { return Err(CryptoError::InvalidToken); } @@ -154,15 +156,16 @@ impl PublicKey { VerifyError::Unusable(defect) => CryptoError::UnusableKey(defect), VerifyError::BadSignature => CryptoError::Signature, })?; - let claims: Value = serde_json::from_slice(token.compact.payload())?; - if claims[Claim::Issuer.as_str()] != issuer - || claims - .get(Claim::IssuedAt.as_str()) - .and_then(Value::as_i64) - .is_none_or(|iat| iat > Utc::now().timestamp() + ISSUED_AT_SKEW_SECONDS) - { - return Err(CryptoError::InvalidToken); + let claims: T = + serde_json::from_slice(token.compact.payload()).map_err(CryptoError::InvalidClaims)?; + Validation { + issuers: &[issuer], + audience: None, + nonce: None, + expiry, + now, } + .check(&claims)?; Ok(claims) } } @@ -370,42 +373,49 @@ impl KeySet { &self.jwks } - /// Verifies a compact token signed by a published key, including its expiry, - /// and decodes its claims as `T`. + /// Verifies a compact token signed by a published key and decodes its claims + /// as `T`, which pass the shared check at `now`: `issuer`, no leeway on `exp` + /// ([`Expiry::Strict`]), and the leeway on `nbf` and `iat`. Any audience will + /// do: auth reads its own tokens, whoever they are for. /// /// # Errors - /// Returns [`CryptoError::UnknownKey`] for a key outside the published ones; - /// otherwise preserves provider and decoding failures and rejects invalid - /// signatures or claims. - pub fn verify( + /// Returns [`CryptoError::UnknownKey`] for a key outside the published ones, + /// [`CryptoError::InvalidClaims`] for claims that do not decode as `T`, and + /// [`CryptoError::Claims`] for claims that fail the check; otherwise preserves + /// provider and decoding failures and rejects invalid signatures. + pub fn verify( &self, token: &str, token_type: TokenType, issuer: &str, + now: DateTime, ) -> Result { let token = Token::parse(token)?; - let claims = Self::find(&self.published, &token)?.verified(&token, token_type, issuer)?; - if claims - .get(Claim::ExpiresAt.as_str()) - .and_then(Value::as_i64) - .is_none_or(|exp| exp <= Utc::now().timestamp()) - { - return Err(CryptoError::Expired); - } - Ok(serde_json::from_value(claims)?) + Self::find(&self.published, &token)?.verified( + &token, + token_type, + issuer, + Expiry::Strict, + now, + ) } - /// Verifies an ID token hint signed by a published or retired key, without - /// requiring it to be unexpired. + /// Verifies an ID token hint signed by a published or retired key, and checks + /// its claims at `now` as [`Self::verify`] does, except that it may have + /// expired ([`Expiry::Ignored`]). /// /// # Errors - /// Returns [`CryptoError::UnknownKey`] for a key outside the set; otherwise - /// preserves provider and decoding failures and rejects invalid signatures or claims. - pub fn verify_id_token_hint(&self, token: &str, issuer: &str) -> Result { + /// As [`Self::verify`], with retired keys among the known ones. + pub fn verify_id_token_hint( + &self, + token: &str, + issuer: &str, + now: DateTime, + ) -> Result { let token = Token::parse(token)?; Self::find(&self.published, &token) .or_else(|_| Self::find(&self.retired, &token))? - .verified(&token, TokenType::Id, issuer) + .verified(&token, TokenType::Id, issuer, Expiry::Ignored, now) } /// The key among `keys` that `token` names. diff --git a/crates/crypto/src/signing/tests.rs b/crates/crypto/src/signing/tests.rs index b023a7382..9b81202b0 100644 --- a/crates/crypto/src/signing/tests.rs +++ b/crates/crypto/src/signing/tests.rs @@ -1,53 +1,95 @@ //! JWT policy, tampering, protected-header trust boundaries and key selection. use super::*; -use serde_json::json; +use serde_json::{Value, json}; +use sourceorigin_common::protocol::{claims::AccessTokenClaims, registered::ClaimsError}; -/// Signing enforces token types, signatures, issuer and expiry, while logout permits expired hints. +/// The issuer every token here names. +const ISSUER: &str = "https://auth.example"; + +/// The instant every check here runs at: long past, so a check reading the system +/// clock would refuse every token. +fn now() -> DateTime { + DateTime::from_timestamp(1_767_225_600, 0).expect("time") +} + +/// ID token claims, issued at [`now`] and valid for five minutes, with `changes`. +/// They also hold the claims an access token needs, so they sign one too. +fn claims(changes: &Value) -> Value { + let now = now().timestamp(); + let mut claims = json!({"iss":ISSUER,"sub":"user","aud":"client","iat":now,"exp":now+300, + "client_id":"client","jti":"01936f3e-8c00-7000-8000-000000000003","scope":"openid"}); + for (claim, value) in changes.as_object().expect("changes") { + claims[claim] = value.clone(); + } + claims +} + +/// Verification checks the type, signature and issuer, and the times at the time +/// it is given: `exp` without leeway, except for hints, which may have expired, +/// and `nbf` and `iat` with it. #[test] -fn rsa_verifies_signatures_types_expiry_and_logout_hints() { +fn verifies_types_signatures_issuers_and_times_at_the_given_time() { let keys = KeySet::single(Rs256Key::generate("test").expect("generate RSA test key")); - let now = Utc::now().timestamp(); - let claims = - json!({"iss":"https://auth.example","sub":"user","aud":"client","iat":now-60,"exp":now-1}); - let expired = keys - .sign(TokenType::Id, &claims) - .expect("sign expired ID token hint"); - assert!( - keys.verify::(&expired, TokenType::Id, "https://auth.example") - .is_err() - ); - assert!( - keys.verify_id_token_hint(&expired, "https://auth.example") - .is_ok() - ); - assert!( - keys.verify_id_token_hint(&expired, "https://evil.example") - .is_err() - ); - let mut valid = claims; - valid["exp"] = json!(now + 300); + let at = |seconds: i64| now() + chrono::TimeDelta::seconds(seconds); + let verify = |claims: &Value| { + let token = keys.sign(TokenType::Id, claims).expect("sign"); + ( + keys.verify::(&token, TokenType::Id, ISSUER, now()), + keys.verify_id_token_hint(&token, ISSUER, now()), + ) + }; + let (token, hint) = verify(&claims(&json!({}))); + assert_eq!(token.expect("verify").sub, "user"); + assert_eq!(hint.expect("hint").sub, "user"); + + // Expired a second ago: refused as a token, read as a hint. + let (token, hint) = verify(&claims(&json!({"exp": at(-1).timestamp()}))); + assert!(matches!( + token, + Err(CryptoError::Claims(ClaimsError::Expired(exp))) if exp == at(-1) + )); + assert!(hint.is_ok()); + for changes in [ + json!({"iss": "https://evil.example"}), + json!({"nbf": at(31).timestamp()}), + json!({"iat": at(31).timestamp()}), + ] { + let (token, hint) = verify(&claims(&changes)); + assert!(matches!(token, Err(CryptoError::Claims(_))), "{changes}"); + assert!(matches!(hint, Err(CryptoError::Claims(_))), "{changes}"); + } + for changes in [ + json!({"nbf": at(30).timestamp()}), + json!({"iat": at(30).timestamp()}), + ] { + let (token, hint) = verify(&claims(&changes)); + assert!(token.is_ok() && hint.is_ok(), "{changes} within the leeway"); + } + let mut no_exp = claims(&json!({})); + no_exp.as_object_mut().expect("claims").remove("exp"); + let (token, hint) = verify(&no_exp); + assert!(matches!(token, Err(CryptoError::InvalidClaims(_)))); + assert!(matches!(hint, Err(CryptoError::InvalidClaims(_)))); + let token = keys - .sign(TokenType::Access, &valid) + .sign(TokenType::Access, &claims(&json!({}))) .expect("sign access token"); assert!( - keys.verify::(&token, TokenType::Access, "https://auth.example") + keys.verify::(&token, TokenType::Access, ISSUER, now()) .is_ok() ); - assert!( - keys.verify::(&token, TokenType::Id, "https://auth.example") - .is_err() - ); + assert!(matches!( + keys.verify::(&token, TokenType::Id, ISSUER, now()), + Err(CryptoError::InvalidToken) + )); let mut bytes = token.into_bytes(); let n = bytes.len(); bytes[n - 10] = if bytes[n - 10] == b'A' { b'B' } else { b'A' }; - assert!( - keys.verify::( - std::str::from_utf8(&bytes).expect("modified compact token remains ASCII"), - TokenType::Access, - "https://auth.example" - ) - .is_err() - ); + let tampered = std::str::from_utf8(&bytes).expect("modified compact token remains ASCII"); + assert!(matches!( + keys.verify::(tampered, TokenType::Access, ISSUER, now()), + Err(CryptoError::Signature) + )); } /// Even correctly RSA-signed inputs cannot choose an algorithm, type, key or critical extension. @@ -55,8 +97,7 @@ fn rsa_verifies_signatures_types_expiry_and_logout_hints() { fn rejects_algorithm_confusion_and_unrecognized_headers() { let keys = KeySet::single(Rs256Key::generate("headers").expect("RSA key")); let key = keys.signer(); - let now = Utc::now().timestamp(); - let claims = json!({"iss":"https://auth.example", "iat":now, "exp":now+300}); + let claims = claims(&json!({})); for (field, value) in [ ("alg", json!("none")), ("alg", json!("HS256")), @@ -78,7 +119,7 @@ fn rejects_algorithm_confusion_and_unrecognized_headers() { let token = key.signed(&input).expect("signature"); assert!( matches!( - keys.verify::(&token, TokenType::Id, "https://auth.example"), + keys.verify::(&token, TokenType::Id, ISSUER, now()), Err(CryptoError::InvalidToken | CryptoError::UnknownKey | CryptoError::Json(_)) ), "accepted {field}" @@ -92,7 +133,7 @@ fn rejects_algorithm_confusion_and_unrecognized_headers() { crate::Digest::hmac(key.public_key().pem().as_bytes(), input.as_bytes()).encoded(); let token = format!("{input}.{signature}"); assert!(matches!( - keys.verify::(&token, TokenType::Id, "https://auth.example"), + keys.verify::(&token, TokenType::Id, ISSUER, now()), Err(CryptoError::Json(_)) )); } @@ -103,8 +144,7 @@ fn rejects_algorithm_confusion_and_unrecognized_headers() { fn key_set_verifies_by_kid_and_limits_retired_keys_to_hints() { let [retiring, active, retired, unknown] = ["retiring", "active", "retired", "unknown"] .map(|kid| Rs256Key::generate(kid).expect("key")); - let now = Utc::now().timestamp(); - let claims = json!({"iss":"https://auth.example", "aud":"client", "iat":now, "exp":now+300}); + let claims = claims(&json!({})); let [by_retiring, by_retired, by_unknown] = [&retiring, &retired, &unknown].map(|key| key.sign(TokenType::Id, &claims).expect("sign")); // A signer must be published, or verifiers could not check its tokens. @@ -117,24 +157,21 @@ fn key_set_verifies_by_kid_and_limits_retired_keys_to_hints() { let by_active = keys.sign(TokenType::Id, &claims).expect("sign"); for token in [&by_active, &by_retiring] { assert!( - keys.verify::(token, TokenType::Id, "https://auth.example") - .is_ok() - ); - assert!( - keys.verify_id_token_hint(token, "https://auth.example") + keys.verify::(token, TokenType::Id, ISSUER, now()) .is_ok() ); + assert!(keys.verify_id_token_hint(token, ISSUER, now()).is_ok()); } assert!(matches!( - keys.verify::(&by_retired, TokenType::Id, "https://auth.example"), + keys.verify::(&by_retired, TokenType::Id, ISSUER, now()), Err(CryptoError::UnknownKey) )); assert!( - keys.verify_id_token_hint(&by_retired, "https://auth.example") + keys.verify_id_token_hint(&by_retired, ISSUER, now()) .is_ok() ); assert!(matches!( - keys.verify_id_token_hint(&by_unknown, "https://auth.example"), + keys.verify_id_token_hint(&by_unknown, ISSUER, now()), Err(CryptoError::UnknownKey) )); let kids: Vec<_> = keys diff --git a/crates/crypto/src/tests.rs b/crates/crypto/src/tests.rs index b39364bb0..1f7cb0d13 100644 --- a/crates/crypto/src/tests.rs +++ b/crates/crypto/src/tests.rs @@ -1,6 +1,10 @@ //! Known vectors and boundary tests for each primitive. use super::*; -use sourceorigin_common::protocol::jwt::TokenType; +use chrono::Timelike; +use sourceorigin_common::protocol::{ + claims::{Audience, AuthenticationClaims, IdTokenClaims, ProfileClaims}, + jwt::TokenType, +}; /// Random secrets round-trip and reject malformed encodings without exposing bytes. #[test] @@ -135,13 +139,24 @@ fn jwt_persistence_and_trust_boundaries() { let pem = key.private_key_pem().expect("export PEM"); let restored = Rs256Key::from_pem("persistent", &pem).expect("restore key"); assert_eq!(key.jwks(), restored.jwks()); - let now = chrono::Utc::now().timestamp(); - let claims = serde_json::json!({"iss":"https://auth.example", "iat":now, "exp":now+300}); + let now = chrono::Utc::now(); + let claims = IdTokenClaims { + iss: "https://auth.example".into(), + sub: "user".into(), + aud: Audience::One("client".into()), + azp: None, + iat: now.with_nanosecond(0).expect("whole seconds"), + exp: now.with_nanosecond(0).expect("whole seconds") + chrono::TimeDelta::minutes(5), + nbf: None, + nonce: None, + authentication: AuthenticationClaims::default(), + profile: ProfileClaims::default(), + }; let token = key.sign(TokenType::Id, &claims).expect("sign"); let restored = KeySet::single(restored); assert_eq!( restored - .verify::(&token, TokenType::Id, "https://auth.example") + .verify::(&token, TokenType::Id, "https://auth.example", now) .expect("verify"), claims ); @@ -153,7 +168,7 @@ fn jwt_persistence_and_trust_boundaries() { ); assert!( unrelated - .verify::(&token, TokenType::Id, "https://auth.example") + .verify::(&token, TokenType::Id, "https://auth.example", now) .is_err() ); let key = KeySet::single(key); @@ -164,24 +179,24 @@ fn jwt_persistence_and_trust_boundaries() { "x".repeat(16385), ] { assert!( - key.verify::(&token, TokenType::Id, "https://auth.example") + key.verify::(&token, TokenType::Id, "https://auth.example", now) .is_err() ); } for (field, invalid) in [ - ("iat", serde_json::json!(now + 60)), + ("iat", serde_json::json!(now.timestamp() + 60)), ("iat", serde_json::json!("not a timestamp")), ("iat", serde_json::Value::Null), ("exp", serde_json::json!("not a timestamp")), ("exp", serde_json::Value::Null), ] { - let mut invalid_claims = claims.clone(); + let mut invalid_claims = serde_json::to_value(&claims).expect("claims"); invalid_claims[field] = invalid; let token = key .sign(TokenType::Id, &invalid_claims) .expect("sign malformed claims"); assert!( - key.verify::(&token, TokenType::Id, "https://auth.example") + key.verify::(&token, TokenType::Id, "https://auth.example", now) .is_err() ); } diff --git a/docs/dev/architecture/oidc.md b/docs/dev/architecture/oidc.md index d8b05ee01..4542dff87 100644 --- a/docs/dev/architecture/oidc.md +++ b/docs/dev/architecture/oidc.md @@ -266,12 +266,14 @@ it ([back-channel logout](sessions.md#back-channel-logout)). Authorization and logout read an `id_token_hint` the same way (`OidcApplication::id_token_hint`, in `src/oidc/hint.rs`). Auth must have signed -it, with a published or retired key, as an ID token from its own issuer. Expiry -doesn't count: an expired ID token still names its account, and RP-Initiated -Logout §2 asks logout to accept one. It must still have a numeric `exp`, a -client ID as its audience and an account ID as its `sub`; otherwise the request -is refused with `invalid_request`. The two differ only on a hint auth can't -verify: authorization refuses it, and logout goes on without it. +it, with a published or retired key, as an ID token from its own issuer whose +`nbf` and `iat` are not in the future, by the check every token auth reads passes +(`protocol::registered` in `sourceorigin-common`). Expiry doesn't count: an +expired ID token still names its account, and RP-Initiated Logout §2 asks logout +to accept one. Its claims must still decode as an ID token's, a numeric `exp` +included, with one client ID as its audience and an account ID as its `sub`; +otherwise the request is refused with `invalid_request`. The two differ only on a +hint auth can't verify: authorization refuses it, and logout goes on without it. ## Discovery diff --git a/packages/auth/src/protocol.ts b/packages/auth/src/protocol.ts index b7cf0fe9d..4a6552715 100644 --- a/packages/auth/src/protocol.ts +++ b/packages/auth/src/protocol.ts @@ -97,6 +97,10 @@ email_verified?: boolean, }; /** * Claims of an ID token (OIDC Core §2), signed with `typ: JWT`. + * + * Decoding must stay backward-compatible: auth reads every `id_token_hint` it + * signed as these claims, even expired or signed by a retired key, so a field + * made stricter would refuse every older hint at authorization and logout. */ export type IdTokenClaims = { /**