//! The login gate, and the whole login through a fake OpenID provider: a //! member of `visa` gets a session, anyone else a refusal. use std::collections::HashMap; use std::sync::{Arc, Mutex}; use axum::Json; use axum::extract::State; use axum::http::StatusCode; use axum::routing::{get, post}; use base64::Engine as _; use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64; use ring::signature::{ECDSA_P256_SHA256_FIXED_SIGNING, EcdsaKeyPair, KeyPair}; use serde_json::{Value, json}; use sqlx::PgPool; use visa::config::Auth; use visa::oidc::Provider; use crate::common::{App, oidc_config, with_auth}; fn app(pool: PgPool, issuer: &str) -> App { with_auth(pool, Auth::Oidc(oidc_config(issuer))) } #[sqlx::test(migrator = "visa::db::MIGRATOR")] async fn the_gate_sends_people_to_the_login(pool: PgPool) { let app = app(pool, "https://id.test/oauth2/openid/visa-web"); let r = app.get("/people/3?x=1").await; assert_eq!(r.status, StatusCode::SEE_OTHER); assert_eq!(r.location(), "/login?next=/people/3%3Fx%3D1"); // htmx gets a header instead of the provider's page let r = app.get_with("/people", &[("hx-request", "true")]).await; assert_eq!(r.status, StatusCode::OK); assert_eq!(r.headers["hx-redirect"], "/login?next=/people"); // open without a session assert_eq!(app.get("/healthz").await.status, StatusCode::OK); assert_eq!(app.get("/static/app.css").await.status, StatusCode::OK); assert_eq!(app.get("/signed-out").await.status, StatusCode::OK); // the provider has not answered yet assert_eq!( app.get("/login").await.status, StatusCode::SERVICE_UNAVAILABLE ); // a login answer without this browser's flow cookie let r = app.get("/auth/callback?code=c&state=s").await; assert_eq!(r.status, StatusCode::BAD_REQUEST); assert!(r.text().contains("started elsewhere")); } #[sqlx::test(migrator = "visa::db::MIGRATOR")] async fn a_session_lets_in_and_sign_out_ends_it(pool: PgPool) { let app = app(pool.clone(), "https://id.test/oauth2/openid/visa-web"); let id = visa::session::create(&pool, "grabowski", "Alexander Grabowski") .await .unwrap(); let cookie = format!("__Host-visa={id}"); let r = app.get_with("/people", &[("cookie", &cookie)]).await; assert_eq!(r.status, StatusCode::OK, "{}", r.body); assert!(r.text().contains("Signed in as") && r.text().contains("Alexander Grabowski")); // the session's token, as the page carries it let csrf: String = sqlx::query_scalar("SELECT csrf FROM sessions") .fetch_one(&pool) .await .unwrap(); assert!(r.body.contains(&format!("value=\"{csrf}\""))); // forms need the same site and the session's token let new = [("surname", "Doe"), ("first_name", "Jane")]; let with = |site: &'static str| { vec![ ("cookie", cookie.clone()), ("sec-fetch-site", site.to_string()), ] }; let send = |form: Vec<(&'static str, String)>, headers: Vec<(&'static str, String)>| { let app = &app; async move { let f: Vec<(&str, &str)> = form.iter().map(|(k, v)| (*k, v.as_str())).collect(); let h: Vec<(&str, &str)> = headers.iter().map(|(k, v)| (*k, v.as_str())).collect(); app.post_raw("/people", &f, &h).await } }; let form = |token: &str| { let mut f: Vec<(&'static str, String)> = new.iter().map(|(k, v)| (*k, v.to_string())).collect(); f.push(("csrf", token.to_string())); f }; let r = send(form(&csrf), with("cross-site")).await; assert_eq!(r.status, StatusCode::FORBIDDEN); assert!(r.text().contains("another site")); let r = send(form("forged"), with("same-origin")).await; assert_eq!(r.status, StatusCode::FORBIDDEN); assert!(r.text().contains("The form has expired")); let no_header = vec![("cookie", cookie.clone())]; assert_eq!( send(form(&csrf), no_header).await.status, StatusCode::FORBIDDEN ); let r = send(form(&csrf), with("same-origin")).await; assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); let actor: String = sqlx::query_scalar("SELECT actor FROM audit_log WHERE action = 'create'") .fetch_one(&pool) .await .unwrap(); assert_eq!(actor, "grabowski"); // sign out: the session row goes, the cookie is cleared let r = app .post_raw( "/logout", &[("csrf", &csrf)], &[("cookie", &cookie), ("sec-fetch-site", "same-origin")], ) .await; assert_eq!(r.status, StatusCode::SEE_OTHER); assert_eq!(r.location(), "/signed-out"); assert!( r.headers["set-cookie"] .to_str() .unwrap() .contains("Max-Age=0") ); let n: i64 = sqlx::query_scalar("SELECT count(*) FROM sessions") .fetch_one(&pool) .await .unwrap(); assert_eq!(n, 0); assert_eq!( app.get_with("/people", &[("cookie", &cookie)]).await.status, StatusCode::SEE_OTHER ); } // ------------------------------------------------- a fake OpenID provider struct Fake { issuer: String, key: EcdsaKeyPair, x: String, y: String, /// What the next token says. nonce: Mutex, groups: Mutex>, /// The token requests it got. requests: Mutex>>, } async fn jwks(State(f): State>) -> Json { Json(json!({"keys": [{"kty": "EC", "crv": "P-256", "kid": "k1", "x": f.x, "y": f.y}]})) } async fn token( State(f): State>, headers: axum::http::HeaderMap, axum::Form(form): axum::Form>, ) -> Json { let auth = headers["authorization"].to_str().unwrap().to_string(); let mut seen = form.clone(); seen.insert("authorization".into(), auth); f.requests.lock().unwrap().push(seen); let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs(); let claims = json!({ "iss": f.issuer, "aud": "visa-web", "sub": "uuid-of-alex", "exp": now + 300, "iat": now, "nonce": *f.nonce.lock().unwrap(), "preferred_username": "grabowski", "name": "Alexander Grabowski", "groups": *f.groups.lock().unwrap(), }); let header = json!({"alg": "ES256", "typ": "JWT", "kid": "k1"}); let input = format!( "{}.{}", B64.encode(header.to_string()), B64.encode(claims.to_string()) ); let rng = ring::rand::SystemRandom::new(); let sig = f.key.sign(&rng, input.as_bytes()).unwrap(); Json(json!({ "access_token": "at", "token_type": "Bearer", "id_token": format!("{input}.{}", B64.encode(sig.as_ref())), })) } /// Starts the provider on a free port; returns it and its issuer URL. async fn fake_provider() -> Arc { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let base = format!("http://{}", listener.local_addr().unwrap()); let rng = ring::rand::SystemRandom::new(); let pkcs8 = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, &rng).unwrap(); let key = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, pkcs8.as_ref(), &rng).unwrap(); let public = key.public_key().as_ref().to_vec(); let fake = Arc::new(Fake { issuer: format!("{base}/oauth2/openid/visa-web"), x: B64.encode(&public[1..33]), y: B64.encode(&public[33..65]), key, nonce: Mutex::new(String::new()), groups: Mutex::new(vec![]), requests: Mutex::new(vec![]), }); let issuer = fake.issuer.clone(); let discovery = json!({ "issuer": issuer, "authorization_endpoint": format!("{base}/ui/oauth2"), "token_endpoint": format!("{base}/oauth2/token"), "jwks_uri": format!("{base}/oauth2/openid/visa-web/public_key.jwk"), }); let router = axum::Router::new() .route( "/oauth2/openid/visa-web/.well-known/openid-configuration", get(move || async move { Json(discovery) }), ) .route("/oauth2/openid/visa-web/public_key.jwk", get(jwks)) .route("/oauth2/token", post(token)) .with_state(fake.clone()); tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); fake } fn query(url: &str) -> HashMap { let q = url.split_once('?').map(|x| x.1).unwrap_or(""); form_urlencoded::parse(q.as_bytes()).into_owned().collect() } fn cookie_of(set_cookie: &str) -> String { set_cookie.split(';').next().unwrap().to_string() } /// /login, then the provider's answer at /auth/callback. async fn sign_in(app: &App, fake: &Fake, groups: &[&str]) -> crate::common::Resp { let r = app.get("/login?next=/people").await; assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); let to = r.location().to_string(); assert!(to.contains("/ui/oauth2?"), "{to}"); let q = query(&to); assert_eq!(q["client_id"], "visa-web"); assert_eq!(q["redirect_uri"], "https://visa.test/auth/callback"); assert_eq!(q["code_challenge_method"], "S256"); assert_eq!(q["scope"], "openid profile email groups"); let flow = cookie_of(r.headers["set-cookie"].to_str().unwrap()); assert!(flow.starts_with("__Host-visa-login=")); *fake.nonce.lock().unwrap() = q["nonce"].clone(); *fake.groups.lock().unwrap() = groups.iter().map(|g| g.to_string()).collect(); app.get_with( &format!("/auth/callback?code=the-code&state={}", q["state"]), &[("cookie", &flow)], ) .await } #[sqlx::test(migrator = "visa::db::MIGRATOR")] async fn a_member_signs_in_through_the_provider(pool: PgPool) { let fake = fake_provider().await; let app = app(pool.clone(), &fake.issuer); let http = reqwest::Client::new(); app.st .set_provider(Provider::discover(&http, &fake.issuer).await.unwrap()); let r = sign_in(&app, &fake, &["visa@id.test", "b4l@id.test"]).await; assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); assert_eq!(r.location(), "/people"); let cookies: Vec = r .headers .get_all("set-cookie") .iter() .map(|v| v.to_str().unwrap().to_string()) .collect(); let session = cookies .iter() .find(|c| c.starts_with("__Host-visa=")) .expect("a session cookie"); assert!( session.contains("Secure") && session.contains("HttpOnly") && session.contains("SameSite=Lax") ); let page = app .get_with("/people", &[("cookie", &cookie_of(session))]) .await; assert_eq!(page.status, StatusCode::OK); assert!(page.text().contains("Alexander Grabowski")); // the token request carried the code, the PKCE verifier and the secret let req = fake.requests.lock().unwrap()[0].clone(); assert_eq!(req["code"], "the-code"); assert_eq!(req["grant_type"], "authorization_code"); assert_eq!(req["code_verifier"].len(), 43); assert!(req["authorization"].starts_with("Basic ")); let signed_in: i64 = sqlx::query_scalar( "SELECT count(*) FROM audit_log WHERE action = 'sign-in' AND actor = 'grabowski'", ) .fetch_one(&pool) .await .unwrap(); assert_eq!(signed_in, 1); // the cookie value is not stored, only its hash let stored: Vec = sqlx::query_scalar("SELECT id_hash FROM sessions") .fetch_one(&pool) .await .unwrap(); let value = cookie_of(session) .trim_start_matches("__Host-visa=") .to_string(); assert_ne!(stored, value.as_bytes()); } #[sqlx::test(migrator = "visa::db::MIGRATOR")] async fn someone_outside_the_group_is_refused(pool: PgPool) { let fake = fake_provider().await; let app = app(pool.clone(), &fake.issuer); let http = reqwest::Client::new(); app.st .set_provider(Provider::discover(&http, &fake.issuer).await.unwrap()); // a group whose name only starts like "visa" does not count let r = sign_in(&app, &fake, &["b4l@id.test", "visas@id.test"]).await; assert_eq!(r.status, StatusCode::FORBIDDEN); assert!(r.text().contains("not in the group visa"), "{}", r.text()); assert!(r.headers.get("set-cookie").is_none()); let n: i64 = sqlx::query_scalar("SELECT count(*) FROM sessions") .fetch_one(&pool) .await .unwrap(); assert_eq!(n, 0); }