Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 16 additions & 10 deletions apps/auth-service/src/keys/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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")
}
Expand All @@ -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")
}
Expand Down Expand Up @@ -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::<Value>(&first_token, TokenType::Access, ISSUER)
keys.verify::<AccessTokenClaims>(&first_token, TokenType::Access, ISSUER, Utc::now())
.is_ok(),
"a retiring key's tokens verify"
);
Expand All @@ -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::<Value>(&first_token, TokenType::Access, ISSUER),
keys.verify::<AccessTokenClaims>(&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"
);

Expand All @@ -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];
Expand Down Expand Up @@ -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::<Value>(&token, TokenType::Access, ISSUER),
keys.verify::<AccessTokenClaims>(&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()]);
Expand Down
63 changes: 30 additions & 33 deletions apps/auth-service/src/oidc/hint.rs
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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.
Expand All @@ -45,45 +46,41 @@ impl From<HintError> 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<IdTokenHint, HintError> {
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,
})
}
}
1 change: 1 addition & 0 deletions apps/auth-service/src/oidc/tests/authorization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
Expand Down
79 changes: 53 additions & 26 deletions apps/auth-service/src/oidc/tests/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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!(
Expand All @@ -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}")
);
}
32 changes: 24 additions & 8 deletions apps/auth-service/src/oidc/tests/logout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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() {
Expand All @@ -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(
Expand All @@ -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,
Expand Down
5 changes: 3 additions & 2 deletions apps/auth-service/src/oidc/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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 {
Expand Down
Loading