feat: persistent sessions and OIDC sign-in (auth M2 + M3)

Sessions and users (M2)
- users and sessions tables in SQLite; only a digest of the session ID is stored
- idle 30 min / absolute 8 h deadlines, UPDATE-only touch, per-user revoke by generation
- emergency operator is a users row (issuer local:emergency); its sessions are
  bound to the operator hash fingerprint, so unsetting or rotating it ends them
- CSRF derived from the session ID; GET /api/v1/me

OIDC login (M3)
- openidconnect 4.1: authorization code + PKCE S256, static redirect URI, no redirects
- one-time login transactions bound to the browser by a Lax correlation cookie
- identity is (issuer, subject); admin only from configured subjects/groups;
  a signed-in user without a grant gets 403 on management APIs
- OIDC sessions are bound to the OIDC configuration fingerprint
- SSO button, no-access page and fixed error codes in the web UI
- tests against a mock IdP with signed and malformed tokens; rehearsed against
  Keycloak 26.1 in a real browser
- rsa 0.9 advisory (RUSTSEC-2023-0071) excepted with a written reason: runtime
  code only verifies signatures with public keys

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-14 13:43:09 +07:00
parent a9ebded5ba
commit 618681fa7f
23 changed files with 3695 additions and 139 deletions

View File

@@ -0,0 +1,552 @@
//! End-to-end OIDC login against a mock IdP. Tokens are hand-built and signed
//! with throwaway RSA keys generated in this process, so every negative case
//! (wrong nonce, issuer, audience, signature, `alg: none`, HS256, rotation) is
//! a real failure of verification, not of the fixture.
use crate::admin::SessionGate;
use crate::oidc::{OidcConfig, OidcProvider};
use crate::state::HubState;
use axum::body::{to_bytes, Body};
use axum::extract::ConnectInfo;
use axum::http::{header, Request, Response, StatusCode};
use base64::Engine;
use hmac::{Hmac, Mac};
use rsa::pkcs1v15::SigningKey;
use rsa::signature::{SignatureEncoding, Signer};
use rsa::traits::PublicKeyParts;
use rsa::RsaPrivateKey;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::net::SocketAddr;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use tower::ServiceExt;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, Request as MockRequest, Respond, ResponseTemplate};
const CLIENT_ID: &str = "tessera";
const CLIENT_SECRET: &str = "synthetic-client-secret";
const REDIRECT: &str = "https://hub.example/api/v1/auth/oidc/callback";
fn b64(bytes: impl AsRef<[u8]>) -> String {
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
}
/// Index 0 = the IdP's key, 1 = its rotated key, 2 = an attacker's key.
fn keys() -> &'static [RsaPrivateKey; 3] {
static KEYS: OnceLock<[RsaPrivateKey; 3]> = OnceLock::new();
KEYS.get_or_init(|| {
let mut rng = rand::rngs::OsRng;
[0, 1, 2].map(|_| RsaPrivateKey::new(&mut rng, 2048).unwrap())
})
}
#[derive(Clone)]
struct Scenario {
nonce: String,
challenge: String,
sub: Option<String>,
name: Option<String>,
email: Option<String>,
iss: Option<String>,
aud: Value,
azp: Option<String>,
exp_in: i64,
alg: &'static str,
signer: usize,
kid: &'static str,
groups: Option<Value>,
token_status: u16,
}
impl Default for Scenario {
fn default() -> Self {
Self {
nonce: String::new(),
challenge: String::new(),
sub: Some("admin-sub".into()),
name: Some("Ada Admin".into()),
email: None,
iss: None,
aud: json!(CLIENT_ID),
azp: None,
exp_in: 3600,
alg: "RS256",
signer: 0,
kid: "k1",
groups: None,
token_status: 200,
}
}
}
struct Idp {
server: MockServer,
scenario: Arc<Mutex<Scenario>>,
jwks: Arc<Mutex<Vec<(&'static str, usize)>>>,
}
struct TokenEndpoint {
scenario: Arc<Mutex<Scenario>>,
issuer: String,
}
fn sign(alg: &str, kid: &str, signer: usize, claims: &Value) -> String {
let header = json!({"alg": alg, "typ": "JWT", "kid": kid});
let signing_input = format!("{}.{}", b64(header.to_string()), b64(claims.to_string()));
let signature = match alg {
"RS256" => b64(SigningKey::<Sha256>::new(keys()[signer].clone()).sign(signing_input.as_bytes()).to_bytes()),
"HS256" => {
let mut mac = Hmac::<Sha256>::new_from_slice(CLIENT_SECRET.as_bytes()).unwrap();
mac.update(signing_input.as_bytes());
b64(mac.finalize().into_bytes())
}
_ => String::new(), // alg "none"
};
format!("{signing_input}.{signature}")
}
impl Respond for TokenEndpoint {
fn respond(&self, request: &MockRequest) -> ResponseTemplate {
let scenario = self.scenario.lock().unwrap().clone();
if scenario.token_status != 200 {
return ResponseTemplate::new(scenario.token_status);
}
let form: std::collections::HashMap<String, String> =
openidconnect::url::form_urlencoded::parse(&request.body).into_owned().collect();
// Real PKCE check: S256(code_verifier) must equal the challenge sent at /authorize.
let verifier = form.get("code_verifier").cloned().unwrap_or_default();
if b64(Sha256::digest(verifier.as_bytes())) != scenario.challenge || form.get("code").map(String::as_str) != Some("good-code") {
return ResponseTemplate::new(400).set_body_json(json!({"error": "invalid_grant"}));
}
let now = chrono::Utc::now().timestamp();
let mut claims = json!({
"iss": scenario.iss.clone().unwrap_or_else(|| self.issuer.clone()),
"aud": scenario.aud,
"exp": now + scenario.exp_in,
"iat": now,
"nonce": scenario.nonce,
});
let object = claims.as_object_mut().unwrap();
if let Some(sub) = &scenario.sub {
object.insert("sub".into(), json!(sub));
}
if let Some(name) = &scenario.name {
object.insert("preferred_username".into(), json!(name));
}
if let Some(email) = &scenario.email {
object.insert("email".into(), json!(email));
}
if let Some(azp) = &scenario.azp {
object.insert("azp".into(), json!(azp));
}
if let Some(groups) = &scenario.groups {
object.insert("groups".into(), groups.clone());
}
ResponseTemplate::new(200).set_body_json(json!({
"access_token": "synthetic-access-token-never-shown",
"token_type": "Bearer",
"expires_in": 3600,
"id_token": sign(scenario.alg, scenario.kid, scenario.signer, &claims),
}))
}
}
impl Idp {
async fn start() -> Self {
// Generate the RSA keys up front: inside a mock handler, a slow debug-build
// keygen would eat the hub's HTTP timeout.
tokio::task::spawn_blocking(|| { keys(); }).await.unwrap();
let server = MockServer::start().await;
let scenario = Arc::new(Mutex::new(Scenario::default()));
let jwks = Arc::new(Mutex::new(vec![("k1", 0usize)]));
let issuer = server.uri();
Mock::given(method("GET")).and(path("/.well-known/openid-configuration"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"issuer": issuer,
"authorization_endpoint": format!("{issuer}/authorize"),
"token_endpoint": format!("{issuer}/token"),
"jwks_uri": format!("{issuer}/jwks"),
"response_types_supported": ["code"],
"subject_types_supported": ["public"],
"id_token_signing_alg_values_supported": ["RS256"],
})))
.mount(&server).await;
let served = jwks.clone();
Mock::given(method("GET")).and(path("/jwks"))
.respond_with(move |_: &MockRequest| {
let keys_json: Vec<Value> = served.lock().unwrap().iter().map(|(kid, index)| {
let public = keys()[*index].to_public_key();
json!({"kty":"RSA","use":"sig","alg":"RS256","kid":kid,
"n": b64(public.n().to_bytes_be()), "e": b64(public.e().to_bytes_be())})
}).collect();
ResponseTemplate::new(200).set_body_json(json!({"keys": keys_json}))
})
.mount(&server).await;
Mock::given(method("POST")).and(path("/token"))
.respond_with(TokenEndpoint { scenario: scenario.clone(), issuer })
.mount(&server).await;
Self { server, scenario, jwks }
}
fn issuer(&self) -> String {
self.server.uri()
}
async fn hits(&self, route: &str) -> usize {
self.server.received_requests().await.unwrap().iter().filter(|r| r.url.path() == route).count()
}
}
struct Harness {
app: axum::Router,
state: HubState,
idp: Idp,
_dir: tempfile::TempDir,
}
fn config(idp: &Idp) -> OidcConfig {
let mut config = OidcConfig::new(&idp.issuer(), CLIENT_ID, CLIENT_SECRET, REDIRECT);
config.admin_subjects.insert("admin-sub".into());
config.admin_groups.insert("tessera-admins".into());
config
}
async fn harness_with(min_refresh: Duration) -> Harness {
let idp = Idp::start().await;
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap();
let config = config(&idp);
state.sessions = SessionGate::without_operator(state.db.clone()).with_oidc(&config.fingerprint());
state.oidc = Some(Arc::new(OidcProvider::new(config).unwrap().with_min_refresh(min_refresh)));
let app = crate::api::router(state.clone());
Harness { app, state, idp, _dir: dir }
}
async fn harness() -> Harness {
harness_with(Duration::from_secs(60)).await
}
fn get(uri: &str, cookies: &[String]) -> Request<Body> {
let mut request = Request::builder().uri(uri).extension(ConnectInfo("127.0.0.1:9000".parse::<SocketAddr>().unwrap()));
if !cookies.is_empty() {
request = request.header(header::COOKIE, cookies.join("; "));
}
request.body(Body::empty()).unwrap()
}
fn set_cookies(response: &Response<Body>) -> Vec<String> {
response.headers().get_all(header::SET_COOKIE).iter().map(|v| v.to_str().unwrap().to_string()).collect()
}
fn cookie_pair(set_cookie: &str) -> String {
set_cookie.split(';').next().unwrap().to_string()
}
fn location(response: &Response<Body>) -> String {
response.headers()[header::LOCATION].to_str().unwrap().to_string()
}
struct Started {
state: String,
correlation: String,
}
impl Harness {
async fn call(&self, request: Request<Body>) -> Response<Body> {
self.app.clone().oneshot(request).await.unwrap()
}
/// Visit /login, check the authorization request, and arm the IdP with the
/// nonce and PKCE challenge the hub generated.
async fn start(&self) -> Started {
let response = self.call(get("/api/v1/auth/oidc/login", &[])).await;
assert!(response.status().is_redirection(), "login redirects, got {}", response.status());
let target = openidconnect::url::Url::parse(&location(&response)).unwrap();
assert!(target.as_str().starts_with(&format!("{}/authorize", self.idp.issuer())));
let q: std::collections::HashMap<String, String> = target.query_pairs().into_owned().collect();
assert_eq!(q["response_type"], "code");
assert_eq!(q["client_id"], CLIENT_ID);
assert_eq!(q["redirect_uri"], REDIRECT);
assert_eq!(q["code_challenge_method"], "S256");
assert!(q["scope"].split(' ').any(|s| s == "openid"));
assert!(!q.contains_key("next") && !q.contains_key("client_secret"));
let cookies = set_cookies(&response);
assert_eq!(cookies.len(), 1);
for flag in ["HttpOnly", "Secure", "SameSite=Lax", "Path=/"] {
assert!(cookies[0].contains(flag), "{flag} in {}", cookies[0]);
}
assert!(cookies[0].starts_with("__Host-tessera-oidc="));
{
let mut scenario = self.idp.scenario.lock().unwrap();
scenario.nonce = q["nonce"].clone();
scenario.challenge = q["code_challenge"].clone();
}
Started { state: q["state"].clone(), correlation: cookie_pair(&cookies[0]) }
}
async fn callback(&self, started: &Started, query: &str) -> Response<Body> {
self.call(get(&format!("/api/v1/auth/oidc/callback?{query}"), &[started.correlation.clone()])).await
}
/// Full successful-or-not login with the current scenario.
async fn login(&self) -> (Response<Body>, Started) {
let started = self.start().await;
let response = self.callback(&started, &format!("code=good-code&state={}", started.state)).await;
(response, started)
}
fn mutate(&self, change: impl FnOnce(&mut Scenario)) {
change(&mut self.idp.scenario.lock().unwrap());
}
fn count(&self, table: &str) -> i64 {
rusqlite::Connection::open(self.state.data_dir.join("tessera.db"))
.unwrap()
.query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |r| r.get(0))
.unwrap()
}
fn query<T: rusqlite::types::FromSql>(&self, sql: &str) -> T {
rusqlite::Connection::open(self.state.data_dir.join("tessera.db")).unwrap().query_row(sql, [], |r| r.get(0)).unwrap()
}
}
fn session_cookie(response: &Response<Body>) -> String {
let cookies = set_cookies(response);
let session = cookies.iter().find(|c| c.starts_with("__Host-tessera-session=") && !c.contains("Max-Age=0")).expect("session cookie");
for flag in ["HttpOnly", "Secure", "SameSite=Strict"] {
assert!(session.contains(flag));
}
cookie_pair(session)
}
async fn json_body(response: Response<Body>) -> Value {
serde_json::from_slice(&to_bytes(response.into_body(), 1 << 20).await.unwrap()).unwrap()
}
#[tokio::test]
async fn an_admin_subject_signs_in_and_gets_a_session_but_never_a_token() {
let h = harness().await;
let (response, started) = h.login().await;
assert_eq!(response.status(), StatusCode::SEE_OTHER);
assert_eq!(location(&response), "/", "fixed redirect target");
let cookies = set_cookies(&response);
assert_eq!(cookies.len(), 2, "session cookie plus cleared correlation cookie: {cookies:?}");
assert!(cookies.iter().any(|c| c.starts_with("__Host-tessera-oidc=;") && c.contains("Max-Age=0")));
let session = session_cookie(&response);
let headers_text = format!("{:?}", response.headers());
assert!(!headers_text.contains("synthetic-access-token") && !headers_text.contains("eyJ"));
assert!(to_bytes(response.into_body(), 4096).await.unwrap().is_empty());
let me = h.call(get("/api/v1/me", &[session.clone()])).await;
assert_eq!(me.status(), StatusCode::OK);
let me = json_body(me).await;
assert_eq!(me["kind"], "user");
assert_eq!(me["auth_method"], "oidc");
assert!(me["id"].as_str().unwrap().starts_with("oidc:"));
assert_eq!(me["display_name"], "Ada Admin");
assert_eq!(me["capabilities"][0], "admin");
assert_eq!(h.call(get("/api/v1/orbits", &[session.clone()])).await.status(), StatusCode::OK);
// Identity is (issuer, subject); the transaction was consumed; the audit actor is the stable user id.
let issuer: String = h.query("SELECT issuer FROM users");
assert_eq!(issuer, h.idp.issuer());
assert_eq!(h.count("oidc_login"), 0);
let actor: String = h.query("SELECT actor_id FROM audit_events WHERE action='auth.login' AND outcome='succeeded'");
assert_eq!(actor, me["id"]);
// PKCE verified by the IdP and the code is not reusable by replaying the callback.
let replay = h.callback(&started, &format!("code=good-code&state={}", started.state)).await;
assert_eq!(location(&replay), "/?auth_error=invalid_state");
assert!(set_cookies(&replay).iter().all(|c| !c.starts_with("__Host-tessera-session=") || c.contains("Max-Age=0")));
assert_eq!(h.count("sessions"), 1);
}
#[tokio::test]
async fn a_signed_in_user_without_a_grant_gets_identity_but_no_api_access() {
let h = harness().await;
// Display name "operator" must not be mistaken for the emergency account.
h.mutate(|s| { s.sub = Some("plain-user".into()); s.name = Some("operator".into()); });
let (response, _) = h.login().await;
assert_eq!(location(&response), "/");
let session = session_cookie(&response);
let me = json_body(h.call(get("/api/v1/me", &[session.clone()])).await).await;
assert_eq!(me["capabilities"].as_array().unwrap().len(), 0);
assert!(me["id"].as_str().unwrap().starts_with("oidc:"), "{me}");
let status = json_body(h.call(get("/api/v1/operator/session", &[session.clone()])).await).await;
assert_eq!(status["authorized"], false);
assert_eq!(status["actor"], "operator");
assert!(status["csrf"].is_string(), "can still sign out");
assert_eq!(h.call(get("/api/v1/orbits", &[session.clone()])).await.status(), StatusCode::FORBIDDEN);
let denied_actor: String = h.query("SELECT actor_id FROM audit_events WHERE action='authorization.check' AND outcome='denied' ORDER BY id DESC LIMIT 1");
assert!(denied_actor.starts_with("oidc:"), "audited as the OIDC user, not emergency:operator: {denied_actor}");
let logout = Request::builder().method("DELETE").uri("/api/v1/operator/session")
.extension(ConnectInfo("127.0.0.1:9000".parse::<SocketAddr>().unwrap()))
.header(header::COOKIE, session.clone())
.header("x-tessera-csrf", status["csrf"].as_str().unwrap())
.body(Body::empty()).unwrap();
assert_eq!(h.call(logout).await.status(), StatusCode::NO_CONTENT);
assert_eq!(h.call(get("/api/v1/me", &[session])).await.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn admin_comes_from_a_verified_group_claim_and_a_bad_claim_grants_nothing() {
let h = harness().await;
for (groups, expect_admin) in [
(Some(json!(["dev", "tessera-admins"])), true),
(Some(json!("tessera-admins")), true),
(Some(json!(["dev"])), false),
(Some(json!({"tessera-admins": true})), false),
(Some(json!([["tessera-admins"]])), false),
(None, false),
] {
h.mutate(|s| { s.sub = Some("group-user".into()); s.groups = groups.clone(); });
let (response, _) = h.login().await;
let session = session_cookie(&response);
let expected = if expect_admin { StatusCode::OK } else { StatusCode::FORBIDDEN };
assert_eq!(h.call(get("/api/v1/orbits", &[session])).await.status(), expected, "{groups:?}");
}
}
#[tokio::test]
async fn the_same_email_under_a_different_subject_is_a_different_user() {
let h = harness().await;
for sub in ["sub-a", "sub-b", "sub-a"] {
h.mutate(|s| { s.sub = Some(sub.into()); s.email = Some("same@example.com".into()); });
let (response, _) = h.login().await;
assert_eq!(location(&response), "/");
}
assert_eq!(h.count("users"), 2, "two subjects, no linking by email; the repeat logs in as the first");
}
#[tokio::test]
async fn invalid_tokens_never_create_a_session_or_a_user() {
let _ = tracing_subscriber::fmt().with_test_writer().try_init();
let h = harness().await;
let cases: Vec<(&str, Box<dyn Fn(&mut Scenario)>)> = vec![
("wrong nonce", Box::new(|s| s.nonce = "not-the-nonce".into())),
("wrong issuer", Box::new(|s| s.iss = Some("https://evil.example".into()))),
("wrong audience", Box::new(|s| s.aud = json!("someone-else"))),
("extra audience without azp", Box::new(|s| s.aud = json!([CLIENT_ID, "other"]))),
("azp is another client", Box::new(|s| { s.aud = json!([CLIENT_ID, "other"]); s.azp = Some("other".into()); })),
("expired", Box::new(|s| s.exp_in = -3600)),
("signed by an attacker key", Box::new(|s| s.signer = 2)),
("alg none", Box::new(|s| s.alg = "none")),
("HS256 with the client secret", Box::new(|s| s.alg = "HS256")),
("no subject", Box::new(|s| s.sub = None)),
("empty subject", Box::new(|s| s.sub = Some(String::new()))),
];
for (name, change) in cases {
h.mutate(|s| *s = Scenario::default());
let started = h.start().await;
h.mutate(|s| change(s));
let response = h.callback(&started, &format!("code=good-code&state={}", started.state)).await;
let target = location(&response);
assert!(target == "/?auth_error=failed", "{name}: {target}");
assert!(set_cookies(&response).iter().all(|c| !c.starts_with("__Host-tessera-session=") || c.contains("Max-Age=0")), "{name}");
assert_eq!(h.count("sessions"), 0, "{name}");
assert_eq!(h.count("users"), 0, "{name}");
}
}
#[tokio::test]
async fn login_transactions_cannot_be_replayed_borrowed_or_forged() {
let h = harness().await;
// Another browser (no / wrong correlation cookie) holding the right state.
let started = h.start().await;
let no_cookie = h.call(get(&format!("/api/v1/auth/oidc/callback?code=good-code&state={}", started.state), &[])).await;
assert_eq!(location(&no_cookie), "/?auth_error=invalid_state");
let again = h.callback(&started, &format!("code=good-code&state={}", started.state)).await;
assert_eq!(location(&again), "/?auth_error=invalid_state", "a failed attempt burns the transaction");
let started = h.start().await;
let wrong = Started { state: started.state.clone(), correlation: "__Host-tessera-oidc=forged".into() };
assert_eq!(location(&h.callback(&wrong, &format!("code=good-code&state={}", started.state)).await), "/?auth_error=invalid_state");
// Unknown, missing and mismatched state.
let started = h.start().await;
assert_eq!(location(&h.callback(&started, "code=good-code&state=made-up").await), "/?auth_error=invalid_state");
assert_eq!(location(&h.callback(&started, "code=good-code").await), "/?auth_error=invalid_state");
// Expired transaction.
let started = h.start().await;
rusqlite::Connection::open(h.state.data_dir.join("tessera.db")).unwrap().execute("UPDATE oidc_login SET expires_at = 1", []).unwrap();
assert_eq!(location(&h.callback(&started, &format!("code=good-code&state={}", started.state)).await), "/?auth_error=invalid_state");
// The IdP reporting an error: shown as a fixed code, nothing echoed, transaction consumed.
let started = h.start().await;
let denied = h.callback(&started, &format!("error=access_denied&error_description=secret-detail&state={}", started.state)).await;
assert_eq!(location(&denied), "/?auth_error=denied");
assert!(!format!("{:?}", denied.headers()).contains("secret-detail"));
assert_eq!(h.count("oidc_login"), 0);
assert_eq!(h.count("sessions"), 0);
// A wrong code is rejected by the IdP.
let started = h.start().await;
assert_eq!(location(&h.callback(&started, &format!("code=bad-code&state={}", started.state)).await), "/?auth_error=failed");
assert_eq!(h.count("sessions"), 0);
let failed: i64 = h.query("SELECT COUNT(*) FROM audit_events WHERE action='auth.login' AND outcome='failed' AND actor_id='anonymous'");
assert!(failed >= 6);
}
#[tokio::test]
async fn rotated_signing_keys_are_picked_up_but_refreshes_are_rate_limited() {
let h = harness_with(Duration::from_millis(1)).await;
let (first, _) = h.login().await;
assert_eq!(location(&first), "/");
assert_eq!(h.idp.hits("/jwks").await, 1);
// The IdP rotates: new key and kid, old key withdrawn. The cached key set is stale.
*h.idp.jwks.lock().unwrap() = vec![("k2", 1)];
h.mutate(|s| { s.signer = 1; s.kid = "k2"; });
tokio::time::sleep(Duration::from_millis(5)).await;
let (after, _) = h.login().await;
assert_eq!(location(&after), "/", "refreshed once and verified with the new key");
assert_eq!(h.idp.hits("/jwks").await, 2);
// With the default 60s gap, a flood of bad signatures cannot hammer the IdP.
let limited = harness().await;
for _ in 0..4 {
limited.mutate(|s| *s = Scenario::default());
let started = limited.start().await;
limited.mutate(|s| s.signer = 2);
let r = limited.callback(&started, &format!("code=good-code&state={}", started.state)).await;
assert_eq!(location(&r), "/?auth_error=failed");
}
assert!(limited.idp.hits("/.well-known/openid-configuration").await <= 2);
}
#[tokio::test]
async fn an_idp_outage_degrades_to_fixed_errors_and_never_a_session() {
// Cold start with the IdP down: no redirect, no transaction stored.
let cold = harness().await;
cold.idp.server.reset().await;
let down = cold.call(get("/api/v1/auth/oidc/login", &[])).await;
assert_eq!(down.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(cold.count("oidc_login"), 0);
// Warm cache, then the token endpoint dies mid-login.
let h = harness().await;
let (ok, _) = h.login().await;
assert_eq!(location(&ok), "/");
h.mutate(|s| s.token_status = 500);
let started = h.start().await; // metadata is cached, so /login still works
let response = h.callback(&started, &format!("code=good-code&state={}", started.state)).await;
assert!(response.status().is_redirection());
assert!(location(&response).starts_with("/?auth_error="));
h.idp.server.reset().await;
let started = h.start().await;
let response = h.callback(&started, &format!("code=good-code&state={}", started.state)).await;
assert!(location(&response).starts_with("/?auth_error="), "{}", location(&response));
}
#[tokio::test]
async fn oidc_endpoints_are_absent_when_oidc_is_not_configured() {
let dir = tempfile::tempdir().unwrap();
let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault").await.unwrap();
let app = crate::api::router(state);
for uri in ["/api/v1/auth/oidc/login", "/api/v1/auth/oidc/callback?code=x&state=y"] {
assert_eq!(app.clone().oneshot(get(uri, &[])).await.unwrap().status(), StatusCode::NOT_FOUND);
}
}