Something went wrong. Try again.
An OIDC provider for AT Protocol OAuth. Rust port of apenwarr/atlogin.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337use crate::support::*;use std::sync::Arc;
use axum::http::{StatusCode, header};use base64::Engine;use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};use jiff::{SignedDuration, Timestamp};use ratlogin::clients::{ClientId, ClientPolicy, NewClient, RedirectUri};use ratlogin::flows::AuthorizationCode;use ratlogin::keys::SigningAlgorithm;use ratlogin::oidc::{PkceChallenge, Scope};use ratlogin::web::router;use sha2::{Digest, Sha256};use url::Url;
#[tokio::test]async fn token_expiry_pkce_and_identity() -> TestResult { let verifier = "a".repeat(43); let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())); let challenge = PkceChallenge::parse(&challenge, "S256")?; let minute = SignedDuration::from_mins(1); let cases = [ ("good", minute, Some(&challenge), verifier.clone(), None), ( "expired", -minute, Some(&challenge), verifier.clone(), Some("invalid_grant"), ), ( "wrong verifier", minute, Some(&challenge), "b".repeat(43), Some("invalid_grant"), ), ( "missing verifier", minute, Some(&challenge), String::new(), Some("invalid_grant"), ), ( "verifier without a challenge", minute, None, verifier.clone(), Some("invalid_request"), ), ]; for (name, lifetime, challenge, presented, error) in cases { let state = fixture()?; let code = state.flows.issue_code(AuthorizationCode { nonce: Some("expected-nonce".to_owned()), challenge: challenge.cloned(), expires_at: Timestamp::now() + lifetime, ..code_record()? })?; let (status, _, body) = redeem(router(Arc::clone(&state)), &code, &presented).await?; if let Some(error) = error { assert_eq!(status, StatusCode::BAD_REQUEST, "{name}: {body}"); assert_eq!(error_code(&body)?, error, "{name}: {body}"); continue; } assert_eq!(status, StatusCode::OK, "{name}: {body}");
let response: serde_json::Value = serde_json::from_str(&body)?; assert_eq!(response["scope"], "openid profile groups", "{name}"); let id_token = response["id_token"].as_str().ok_or("missing id_token")?; assert_eq!( jsonwebtoken::decode_header(id_token)?.typ.as_deref(), Some("JWT") ); let claims = jwt_payload(id_token)?; assert_eq!(claims["nonce"], "expected-nonce"); assert!(claims["auth_time"].is_i64(), "{claims}"); assert!(claims.get("email").is_none(), "{claims}"); assert_eq!( claims["groups"], serde_json::json!(["did:plc:aaaaaaaaaaaaaaaaaaaaaaaa"]) );
state.flows.sweep(Timestamp::now())?; let access_token = response["access_token"] .as_str() .ok_or("missing access_token")?; let (status, _, body) = userinfo(&state, &format!("Bearer {access_token}")).await?; assert_eq!( status, StatusCode::OK, "userinfo depended on expired flow: {body}" ); assert!( body.contains(r#""groups":["did:plc:aaaaaaaaaaaaaaaaaaaaaaaa"]"#), "{body}" );
let (status, _, body) = redeem(router(Arc::clone(&state)), &code, &presented).await?; assert_eq!(status, StatusCode::BAD_REQUEST, "code reusable"); assert_eq!(error_code(&body)?, "invalid_grant", "{body}"); } Ok(())}
#[tokio::test]async fn codes_cannot_be_redeemed_by_another_client_or_redirect() -> TestResult { let state = fixture_with( config_for([ client("client", REDIRECT, ClientPolicy::default())?, client("other", "https://other.example/cb", ClientPolicy::default())?, ])?, None, )?;
let code = state.flows.issue_code(code_record()?)?; let (status, _, body) = redeem_as( router(Arc::clone(&state)), &basic("other", &SECRET)?, &token_form(&code, ""), ) .await?; assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); assert_eq!(error_code(&body)?, "invalid_grant"); let (status, _, _) = redeem(router(Arc::clone(&state)), &code, "").await?; assert_eq!( status, StatusCode::BAD_REQUEST, "a substituted code must be burned" );
let code = state.flows.issue_code(code_record()?)?; let mut form = token_form(&code, ""); set(&mut form, "redirect_uri", "https://client.example/cb/other"); let (status, _, body) = redeem_as( router(Arc::clone(&state)), &basic("client", &SECRET)?, &form, ) .await?; assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); assert_eq!(error_code(&body)?, "invalid_grant"); Ok(())}
#[tokio::test]async fn token_endpoint_authenticates_clients_and_reports_standard_errors() -> TestResult { let state = fixture()?; let secret = String::from_utf8(SECRET.to_vec())?; let encoded_secret: String = SECRET.iter().map(|byte| format!("%{byte:02X}")).collect(); let percent_encoded = format!( "Basic {}", STANDARD.encode(format!("client:{encoded_secret}")) ); let good = basic("client", &SECRET)?; let cases = [ ( "wrong secret", basic("client", b"wrong")?, vec![], StatusCode::UNAUTHORIZED, "invalid_client", ), ( "not base64", "Basic not-base64!".to_owned(), vec![], StatusCode::UNAUTHORIZED, "invalid_client", ), ( "unsupported grant", good.clone(), vec![("grant_type", "client_credentials")], StatusCode::BAD_REQUEST, "unsupported_grant_type", ), ( "unknown code", good.clone(), vec![("code", "no-such-code")], StatusCode::BAD_REQUEST, "invalid_grant", ), ( "two authentication methods", good.clone(), vec![("client_secret", secret.as_str())], StatusCode::BAD_REQUEST, "invalid_request", ), ( "another client_id in the body", good.clone(), vec![("client_id", "other")], StatusCode::BAD_REQUEST, "invalid_request", ), ( "percent-encoded credentials", percent_encoded, vec![], StatusCode::OK, "", ), ( "credentials in the body", String::new(), vec![("client_id", "client"), ("client_secret", secret.as_str())], StatusCode::OK, "", ), ( "a wrong secret in the body", String::new(), vec![("client_id", "client"), ("client_secret", "wrong")], StatusCode::UNAUTHORIZED, "invalid_client", ), ( "the same client_id in the body", good.clone(), vec![("client_id", "client")], StatusCode::OK, "", ), ]; let mut code = state.flows.issue_code(code_record()?)?; for (name, authorization, fields, expected, error) in cases { let mut form = token_form(&code, ""); for (key, value) in fields { set(&mut form, key, value); } let (status, headers, body) = redeem_as(router(Arc::clone(&state)), &authorization, &form).await?; assert_eq!(status, expected, "{name}: {body}"); assert_eq!( header_str(&headers, header::CACHE_CONTROL), Some("no-store"), "{name}" ); if expected == StatusCode::OK { code = state.flows.issue_code(code_record()?)?; continue; } assert_eq!(error_code(&body)?, error, "{name}: {body}"); assert_eq!( headers.contains_key(header::WWW_AUTHENTICATE), expected == StatusCode::UNAUTHORIZED, "{name}" ); }
let mut duplicated = token_form(&code, ""); duplicated.push(("code".to_owned(), "again".to_owned())); let (status, _, body) = redeem_as(router(Arc::clone(&state)), &good, &duplicated).await?; assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); assert_eq!(error_code(&body)?, "invalid_request");
let (status, _, _) = redeem(router(Arc::clone(&state)), &code, "").await?; assert_eq!( status, StatusCode::OK, "the real code was untouched by the failures" ); Ok(())}
#[tokio::test]async fn stored_clients_authenticate_like_configured_ones() -> TestResult { let state = fixture_with(config()?, Some(identity()?.did))?; let redirect = "https://stored.example/cb"; let secret = state.clients.store().create( NewClient { id: ClientId::new("stored"), redirect_uris: vec![RedirectUri::parse(redirect)?], policy: ClientPolicy { signing: SigningAlgorithm::Rs256, ..ClientPolicy::default() }, }, Timestamp::now(), )?; let code = state.flows.issue_code(AuthorizationCode { client_id: ClientId::new("stored"), redirect_uri: Url::parse(redirect)?, ..code_record()? })?; let mut form = token_form(&code, ""); set(&mut form, "redirect_uri", redirect); let (status, _, body) = redeem_as( router(Arc::clone(&state)), &basic("stored", secret.as_bytes())?, &form, ) .await?; assert_eq!(status, StatusCode::OK, "{body}"); Ok(())}
#[tokio::test]async fn userinfo_honours_the_granted_scopes_and_the_bearer_scheme() -> TestResult { let state = fixture()?; let code = state.flows.issue_code(AuthorizationCode { nonce: Some("expected-nonce".to_owned()), scopes: vec![Scope::OpenId], ..code_record()? })?; let (status, _, body) = redeem(router(Arc::clone(&state)), &code, "").await?; assert_eq!(status, StatusCode::OK, "{body}"); let response: serde_json::Value = serde_json::from_str(&body)?; assert_eq!(response["scope"], "openid"); let access_token = response["access_token"].as_str().ok_or("missing token")?; let (status, _, body) = userinfo(&state, &format!("bearer {access_token}")).await?; assert_eq!(status, StatusCode::OK, "{body}"); let claims: serde_json::Value = serde_json::from_str(&body)?; assert_eq!(claims["sub"], "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa"); assert!(claims.get("name").is_none(), "{claims}"); assert!(claims.get("preferred_username").is_none(), "{claims}"); assert!(claims.get("groups").is_none(), "{claims}");
let (status, headers, _) = get(router(Arc::clone(&state)), "/userinfo").await?; assert_eq!(status, StatusCode::UNAUTHORIZED); assert_eq!( header_str(&headers, header::WWW_AUTHENTICATE), Some(r#"Bearer realm="ratlogin""#) ); let (status, headers, _) = userinfo(&state, "Bearer nope").await?; assert_eq!(status, StatusCode::UNAUTHORIZED); assert_eq!( header_str(&headers, header::WWW_AUTHENTICATE), Some(r#"Bearer realm="ratlogin", error="invalid_token""#) ); Ok(())}