//! End-to-end tests of the provider through the router: the redirect rules, PKCE, code and refresh //! reuse, client binding, and the ID token checked against the published key set. use std::time::Duration; use base64::prelude::{BASE64_STANDARD, BASE64_URL_SAFE_NO_PAD, Engine as _}; use http::header::{AUTHORIZATION, CONTENT_TYPE, COOKIE, LOCATION}; use im_core::jwt::{self, PublishedKey}; use im_core::model::Client; use im_core::oauth::pkce_s256; use im_core::password::hash_password; use im_core::store::clients::NewClient; use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState}; use im_core::token::{generate_token, hash_token}; use serde_json::Value; use topcoat::router::response::Response; use topcoat::router::{Body, StatusCode, to_bytes}; use super::{encode_value, one, parse_pairs}; use crate::boot::{router, test_state}; use crate::state::AppState; /// The registered redirect URI of the test client. const REDIRECT: &str = "http://127.0.0.1:17651/auth/callback"; /// The registered post-logout URI of the test client. const POST_LOGOUT: &str = "http://127.0.0.1:17651/signed-out"; /// The cookie name the browser sends: the `__Host-` prefix is added by the jar. const SESSION_COOKIE: &str = "__Host-im_session"; /// A client with a secret, a person, and a live browser session of that person. struct Fixture { _dir: tempfile::TempDir, state: AppState, client: Client, secret: String, user_id: String, cookie: String, } async fn fixture() -> Fixture { let (dir, state) = test_state().await; crate::oidc::signing::maintain(&state.store, &state.key) .await .expect("signing key"); let secret = generate_token(); let uris = vec![REDIRECT.to_owned()]; let post_logout = vec![POST_LOGOUT.to_owned()]; let client = state .store .create_client(&NewClient { name: "Files", secret_hash: &hash_token(&secret), redirect_uris: &uris, post_logout_redirect_uris: &post_logout, backchannel_logout_uri: None, allowed_scopes: "openid profile email", service_key: Some("in"), }) .await .expect("client"); let hash = hash_password("the current password").expect("hash"); let user = state .store .create_user("ada@example.com", "Ada", &hash, false) .await .expect("user"); let cookie = generate_token(); state .store .create_session( &NewSession { user_id: &user.id, decided_on: SignInState::of(&user), token_hash: &hash_token(&cookie), csrf_token: &generate_token(), amr: "pwd", ip: None, user_agent: None, idle: SESSION_IDLE, max_age: Duration::from_secs(3600), }, 10, ) .await .expect("session") .expect("not refused"); Fixture { _dir: dir, state, client, secret, user_id: user.id, cookie, } } /// Sends a request through the whole router and returns the status, headers and body text. async fn send( state: &AppState, request: http::Request, ) -> (StatusCode, http::HeaderMap, String) { let response: Response = router(state.clone()).handle(request).await; let status = response.status(); let headers = response.headers().clone(); let bytes = to_bytes(response.into_body(), 1024 * 1024) .await .expect("body"); ( status, headers, String::from_utf8_lossy(&bytes).into_owned(), ) } /// The `/authorize` path for a request, with the given method and challenge. fn authorize_path(client_id: &str, redirect: &str, challenge: &str, method: &str) -> String { format!( "/authorize?response_type=code&client_id={client_id}&redirect_uri={}\ &scope=openid%20profile%20email&state=s1&nonce=n1&code_challenge={challenge}\ &code_challenge_method={method}", encode_value(redirect) ) } /// Runs `/authorize` as the signed-in person and returns the code from the redirect. async fn code_for(f: &Fixture, client: &Client, verifier: &str) -> String { let path = authorize_path(&client.id, REDIRECT, &pkce_s256(verifier), "S256"); let request = http::Request::get(path) .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) .body(Body::empty()) .expect("request"); let (status, headers, _) = send(&f.state, request).await; assert_eq!(status, StatusCode::SEE_OTHER); let location = headers[LOCATION].to_str().expect("location").to_owned(); assert!(location.starts_with(&format!("{REDIRECT}?")), "{location}"); let query = location.split_once('?').expect("query").1; let pairs = parse_pairs(query.as_bytes()).expect("pairs"); assert_eq!(one(&pairs, "state"), Some("s1")); assert_eq!(one(&pairs, "iss"), Some(f.state.config.base_url.as_str())); one(&pairs, "code").expect("code").to_owned() } /// Posts a form to `/token` with `client_secret_basic` for `client`. async fn token_with(f: &Fixture, client: &Client, secret: &str, body: &str) -> (StatusCode, Value) { let basic = BASE64_STANDARD.encode(format!("{}:{}", client.id, secret)); let request = http::Request::post("/token") .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .header(AUTHORIZATION, format!("Basic {basic}")) .body(Body::from(body.to_owned())) .expect("request"); let (status, _, text) = send(&f.state, request).await; (status, serde_json::from_str(&text).unwrap_or(Value::Null)) } /// The form body of an authorization-code exchange. fn code_body(code: &str, verifier: &str) -> String { format!( "grant_type=authorization_code&code={code}&redirect_uri={}&code_verifier={verifier}", encode_value(REDIRECT) ) } #[tokio::test] async fn an_unregistered_redirect_uri_is_never_redirected_to() { let f = fixture().await; let challenge = pkce_s256(&generate_token()); for bad in [ "http://127.0.0.1:17651/auth/callback/evil", "http://127.0.0.1:17651/auth/callback/", "http://127.0.0.1:17651/Auth/callback", "http://127.0.0.1:17651@evil.example/auth/callback", "http://127.0.0.1:17651/auth/callback?x=1", "https://127.0.0.1:17651/auth/callback", "http://127.0.0.1:17651/auth/callback#x", ] { let request = http::Request::get(authorize_path(&f.client.id, bad, &challenge, "S256")) .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) .body(Body::empty()) .expect("request"); let (status, headers, _) = send(&f.state, request).await; assert_eq!(status, StatusCode::BAD_REQUEST, "{bad}"); assert!(headers.get(LOCATION).is_none(), "redirected for {bad}"); } } #[tokio::test] async fn plain_pkce_is_refused_through_the_registered_redirect() { let f = fixture().await; let verifier = generate_token(); let request = http::Request::get(authorize_path(&f.client.id, REDIRECT, &verifier, "plain")) .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) .body(Body::empty()) .expect("request"); let (status, headers, _) = send(&f.state, request).await; assert_eq!(status, StatusCode::SEE_OTHER); let location = headers[LOCATION].to_str().expect("location"); assert!(location.starts_with(REDIRECT), "{location}"); assert!(location.contains("error=invalid_request"), "{location}"); assert!(!location.contains("code="), "{location}"); } #[tokio::test] async fn a_code_is_single_use_and_its_reuse_revokes_the_refresh_token() { let f = fixture().await; let verifier = generate_token(); let code = code_for(&f, &f.client, &verifier).await; let body = code_body(&code, &verifier); let (status, first) = token_with(&f, &f.client, &f.secret, &body).await; assert_eq!(status, StatusCode::OK, "{first}"); let refresh = first["refresh_token"].as_str().expect("refresh").to_owned(); let (status, second) = token_with(&f, &f.client, &f.secret, &body).await; assert_eq!(status, StatusCode::BAD_REQUEST); assert_eq!(second["error"], "invalid_grant"); let refresh_body = format!("grant_type=refresh_token&refresh_token={refresh}"); let (status, third) = token_with(&f, &f.client, &f.secret, &refresh_body).await; assert_eq!(status, StatusCode::BAD_REQUEST, "{third}"); assert_eq!(third["error"], "invalid_grant"); } #[tokio::test] async fn a_code_for_another_client_is_refused_and_still_usable_by_its_own() { let f = fixture().await; let other_secret = generate_token(); let uris = vec![REDIRECT.to_owned()]; let other = f .state .store .create_client(&NewClient { name: "Board", secret_hash: &hash_token(&other_secret), redirect_uris: &uris, post_logout_redirect_uris: &[], backchannel_logout_uri: None, allowed_scopes: "openid profile email", service_key: Some("iz"), }) .await .expect("client"); let verifier = generate_token(); let code = code_for(&f, &f.client, &verifier).await; let body = code_body(&code, &verifier); let (status, wrong) = token_with(&f, &other, &other_secret, &body).await; assert_eq!(status, StatusCode::BAD_REQUEST); assert_eq!(wrong["error"], "invalid_grant"); let (status, right) = token_with(&f, &f.client, &f.secret, &body).await; assert_eq!(status, StatusCode::OK, "{right}"); } #[tokio::test] async fn a_reused_refresh_token_revokes_the_whole_family() { let f = fixture().await; let verifier = generate_token(); let code = code_for(&f, &f.client, &verifier).await; let (_, first) = token_with(&f, &f.client, &f.secret, &code_body(&code, &verifier)).await; let r1 = first["refresh_token"].as_str().expect("r1").to_owned(); let (status, rotated) = token_with( &f, &f.client, &f.secret, &format!("grant_type=refresh_token&refresh_token={r1}"), ) .await; assert_eq!(status, StatusCode::OK, "{rotated}"); let r2 = rotated["refresh_token"].as_str().expect("r2").to_owned(); // Presenting the rotated token again is reuse: the successor dies too. let (status, reused) = token_with( &f, &f.client, &f.secret, &format!("grant_type=refresh_token&refresh_token={r1}"), ) .await; assert_eq!(status, StatusCode::BAD_REQUEST); assert_eq!(reused["error"], "invalid_grant"); let (status, successor) = token_with( &f, &f.client, &f.secret, &format!("grant_type=refresh_token&refresh_token={r2}"), ) .await; assert_eq!(status, StatusCode::BAD_REQUEST, "{successor}"); } #[tokio::test] async fn the_id_token_verifies_against_the_published_key_and_carries_the_nonce() { let f = fixture().await; let verifier = generate_token(); let code = code_for(&f, &f.client, &verifier).await; let (status, tokens) = token_with(&f, &f.client, &f.secret, &code_body(&code, &verifier)).await; assert_eq!(status, StatusCode::OK, "{tokens}"); let id_token = tokens["id_token"].as_str().expect("id_token"); let request = http::Request::get("/jwks.json") .body(Body::empty()) .expect("request"); let (status, _, jwks) = send(&f.state, request).await; assert_eq!(status, StatusCode::OK); let keys: Vec = serde_json::from_str::(&jwks).expect("jwks")["keys"] .as_array() .expect("keys") .iter() .filter_map(|jwk| { let raw = BASE64_URL_SAFE_NO_PAD.decode(jwk["x"].as_str()?).ok()?; PublishedKey::new(jwk["kid"].as_str()?.to_owned(), &raw) }) .collect(); let claims = jwt::verify(&keys, id_token).expect("signature verifies"); let now = im_core::time::unix_now(); jwt::check_claims(&claims, &f.state.config.base_url, &f.client.id, now).expect("claims"); assert_eq!(claims["nonce"], "n1"); assert_eq!(claims["sub"], f.user_id.as_str()); assert_eq!(claims["amr"], serde_json::json!(["pwd"])); } /// Posts a form to `path` with `client_secret_basic` for `client`. async fn post_as( f: &Fixture, path: &str, client: &Client, secret: &str, body: &str, ) -> (StatusCode, Value) { let basic = BASE64_STANDARD.encode(format!("{}:{}", client.id, secret)); let request = http::Request::post(path) .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .header(AUTHORIZATION, format!("Basic {basic}")) .body(Body::from(body.to_owned())) .expect("request"); let (status, _, text) = send(&f.state, request).await; (status, serde_json::from_str(&text).unwrap_or(Value::Null)) } /// A client that is a family service with the given key and allowed scopes. Returns it with its secret. async fn service(f: &Fixture, key: &str, scopes: &str) -> (Client, String) { let secret = generate_token(); let client = f .state .store .create_client(&NewClient { name: key, secret_hash: &hash_token(&secret), redirect_uris: &[], post_logout_redirect_uris: &[], backchannel_logout_uri: None, allowed_scopes: scopes, service_key: Some(key), }) .await .expect("service client"); (client, secret) } #[tokio::test] async fn client_credentials_refuses_a_scope_beyond_the_allowed_ones() { let f = fixture().await; let (caller, secret) = service(&f, "iz", "directory.read").await; let (status, body) = post_as( &f, "/token", &caller, &secret, "grant_type=client_credentials&scope=files.service&audience=im", ) .await; assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); assert_eq!(body["error"], "invalid_scope"); } #[tokio::test] async fn client_credentials_refuses_an_unknown_audience() { let f = fixture().await; let (caller, secret) = service(&f, "iz", "directory.read").await; let (status, body) = post_as( &f, "/token", &caller, &secret, "grant_type=client_credentials&scope=directory.read&audience=nowhere", ) .await; assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); assert_eq!(body["error"], "invalid_target"); } #[tokio::test] async fn introspection_reports_a_token_inactive_for_any_client_but_its_own() { let f = fixture().await; let (caller, caller_secret) = service(&f, "iz", "directory.read").await; let (other, other_secret) = service(&f, "board", "directory.read").await; let (status, issued) = post_as( &f, "/token", &caller, &caller_secret, "grant_type=client_credentials&scope=directory.read&audience=im", ) .await; assert_eq!(status, StatusCode::OK, "{issued}"); let token = issued["access_token"].as_str().expect("token"); let body = format!("token={token}"); let (status, own) = post_as(&f, "/introspect", &caller, &caller_secret, &body).await; assert_eq!(status, StatusCode::OK); assert_eq!(own["active"], true, "{own}"); let (status, foreign) = post_as(&f, "/introspect", &other, &other_secret, &body).await; assert_eq!(status, StatusCode::OK); assert_eq!(foreign, serde_json::json!({ "active": false })); } #[tokio::test] async fn a_revoked_access_token_is_refused_by_userinfo_and_introspection() { let f = fixture().await; let verifier = generate_token(); let code = code_for(&f, &f.client, &verifier).await; let (status, issued) = token_with(&f, &f.client, &f.secret, &code_body(&code, &verifier)).await; assert_eq!(status, StatusCode::OK, "{issued}"); let access = issued["access_token"] .as_str() .expect("access token") .to_owned(); let userinfo = || { let request = http::Request::get("/userinfo") .header(AUTHORIZATION, format!("Bearer {access}")) .body(Body::empty()) .expect("request"); send(&f.state, request) }; assert_eq!(userinfo().await.0, StatusCode::OK); let (status, _) = post_as( &f, "/revoke", &f.client, &f.secret, &format!("token={access}"), ) .await; assert_eq!(status, StatusCode::OK); assert_eq!(userinfo().await.0, StatusCode::UNAUTHORIZED); let (status, answer) = post_as( &f, "/introspect", &f.client, &f.secret, &format!("token={access}"), ) .await; assert_eq!(status, StatusCode::OK); assert_eq!(answer, serde_json::json!({ "active": false })); } /// The ID token of a fresh sign-in of the fixture's person, and the code exchange's session id. async fn id_token_of(f: &Fixture) -> String { let verifier = generate_token(); let code = code_for(f, &f.client, &verifier).await; let (status, tokens) = token_with(f, &f.client, &f.secret, &code_body(&code, &verifier)).await; assert_eq!(status, StatusCode::OK, "{tokens}"); tokens["id_token"].as_str().expect("id_token").to_owned() } /// The CSRF token of the fixture's browser session. async fn csrf_of(f: &Fixture) -> String { f.state .store .session_by_token_hash(&hash_token(&f.cookie)) .await .expect("lookup") .expect("session") .csrf_token } #[tokio::test] async fn logout_redirects_only_to_the_registered_post_logout_uri() { let f = fixture().await; let hint = encode_value(&id_token_of(&f).await); let unregistered = encode_value("http://127.0.0.1:17651/elsewhere"); let body = format!( "csrf={}&id_token_hint={hint}&post_logout_redirect_uri={unregistered}&state=abc", csrf_of(&f).await ); let request = http::Request::post("/logout") .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .body(Body::from(body)) .expect("request"); let (status, headers, body) = send(&f.state, request).await; assert_eq!(status, StatusCode::OK, "{body}"); assert!( headers.get(LOCATION).is_none(), "redirected to an unregistered URI" ); // The hint names the browser's own session, so it ends even though nothing is redirected. let live = f .state .store .session_by_token_hash(&hash_token(&f.cookie)) .await .expect("lookup"); assert!(live.is_none(), "the session did not end"); } #[tokio::test] async fn logout_with_the_registered_uri_redirects_and_carries_the_state() { let f = fixture().await; let hint = encode_value(&id_token_of(&f).await); let registered = encode_value(POST_LOGOUT); let body = format!( "csrf={}&id_token_hint={hint}&post_logout_redirect_uri={registered}&state=abc", csrf_of(&f).await ); let request = http::Request::post("/logout") .header(COOKIE, format!("{SESSION_COOKIE}={}", f.cookie)) .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .body(Body::from(body)) .expect("request"); let (status, headers, _) = send(&f.state, request).await; assert_eq!(status, StatusCode::SEE_OTHER); let location = headers[LOCATION].to_str().expect("location"); assert_eq!(location, format!("{POST_LOGOUT}?state=abc")); }