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

@@ -18,6 +18,7 @@ fn every_registered_path_has_an_authorization_contract() {
include_str!("restore.rs"),
include_str!("catalog.rs"),
include_str!("session.rs"),
include_str!("oidc.rs"),
] {
for route in source.split(".route(").skip(1) {
let path = route.split('"').nth(1).expect("route literal");
@@ -36,7 +37,7 @@ async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() {
crate::state::HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault")
.await
.unwrap();
state.sessions = crate::admin::SessionGate::fixture();
state.sessions = crate::admin::SessionGate::fixture(state.db.clone());
state.admin.token = Some("synthetic-admin".into());
let outpost = uuid::Uuid::new_v4();
state

View File

@@ -1,11 +1,14 @@
mod catalog;
mod jobs;
mod oidc;
mod orbit;
mod restore;
mod routes;
mod session;
#[cfg(test)]
mod auth_contract;
#[cfg(test)]
mod oidc_tests;
pub use orbit::run_orbit_internal;
pub use routes::router;

View File

@@ -0,0 +1,160 @@
//! Browser SSO endpoints. Both are public GET navigations: the IdP redirects
//! the browser back here. No tokens are ever sent to the browser, and every
//! redirect target is fixed (`/`), so there is no `next` parameter to abuse.
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
use crate::oidc::OidcError;
use crate::state::HubState;
use axum::{
extract::{Query, State},
http::{header, HeaderMap, HeaderValue, StatusCode},
response::{IntoResponse, Redirect, Response},
routing::get,
Router,
};
use serde::Deserialize;
const CORRELATION: &str = "__Host-tessera-oidc";
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/auth/oidc/login", get(login))
.route("/api/v1/auth/oidc/callback", get(callback))
}
#[derive(Deserialize)]
struct CallbackQuery {
code: Option<String>,
state: Option<String>,
error: Option<String>,
}
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
/// Correlation cookie: SameSite=Lax so it survives the IdP's cross-site GET
/// redirect, while the session cookie itself stays Strict.
fn correlation_cookie(value: Option<&str>) -> HeaderValue {
let text = format!(
"{CORRELATION}={}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age={}",
value.unwrap_or_default(),
if value.is_some() { crate::db::oidc_login::TTL_SECS } else { 0 },
);
HeaderValue::from_str(&text).expect("cookie is ASCII")
}
fn no_store(headers: &mut HeaderMap) {
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
}
fn correlation_from(headers: &HeaderMap) -> Option<String> {
headers
.get_all(header::COOKIE)
.iter()
.filter_map(|h| h.to_str().ok())
.flat_map(|line| line.split(';'))
.find_map(|pair| {
let (name, value) = pair.trim().split_once('=')?;
(name == CORRELATION && !value.is_empty() && value.len() <= 128).then(|| value.to_string())
})
}
async fn login(State(state): State<HubState>) -> Response {
let Some(oidc) = state.oidc.clone() else { return StatusCode::NOT_FOUND.into_response() };
let begun = match oidc.begin().await {
Ok(begun) => begun,
Err(_) => return failure(&state, "unavailable", StatusCode::SERVICE_UNAVAILABLE).await,
};
let browser = uuid::Uuid::new_v4().to_string();
let stored = state.db.begin_oidc_login(&begun.state, &browser, &begun.nonce, &begun.verifier, now());
if !matches!(stored, Ok(true)) {
return failure(&state, "unavailable", StatusCode::SERVICE_UNAVAILABLE).await;
}
let mut response = Redirect::to(&begun.url).into_response();
no_store(response.headers_mut());
response.headers_mut().append(header::SET_COOKIE, correlation_cookie(Some(&browser)));
response
}
async fn callback(State(state): State<HubState>, headers: HeaderMap, Query(query): Query<CallbackQuery>) -> Response {
let Some(oidc) = state.oidc.clone() else { return StatusCode::NOT_FOUND.into_response() };
let outcome = complete(&state, &oidc, &headers, query).await;
let mut response = match outcome {
Ok(session) => {
let mut response = Redirect::to("/").into_response();
if let Ok(cookie) = super::session::session_cookie(Some(&session.id.to_string())) {
response.headers_mut().append(header::SET_COOKIE, cookie);
}
response
}
Err(code) => Redirect::to(&format!("/?auth_error={code}")).into_response(),
};
no_store(response.headers_mut());
// The correlation cookie is single-use whatever happened.
response.headers_mut().append(header::SET_COOKIE, correlation_cookie(None));
response
}
/// Returns the new session, or a fixed error code that is safe to show.
async fn complete(
state: &HubState,
oidc: &crate::oidc::OidcProvider,
headers: &HeaderMap,
query: CallbackQuery,
) -> Result<crate::admin::BrowserSession, &'static str> {
let request = uuid::Uuid::new_v4();
let audit = |principal: &Principal, outcome| {
let _ = state.db.audit_event(principal, AuditAction::Login, AuditResource::Session, outcome, request);
};
let Some(state_param) = query.state.as_deref() else {
audit(&Principal::Anonymous, AuditOutcome::Failed);
return Err("invalid_state");
};
let browser = correlation_from(headers);
let transaction = state.db.consume_oidc_login(state_param, browser.as_deref(), now());
let Ok(Some((nonce, verifier))) = transaction else {
audit(&Principal::Anonymous, AuditOutcome::Failed);
return Err("invalid_state");
};
if query.error.is_some() {
// The IdP refused (for example access_denied); nothing from it is echoed.
audit(&Principal::Anonymous, AuditOutcome::Failed);
return Err("denied");
}
let Some(code) = query.code.as_deref().filter(|c| !c.is_empty() && c.len() <= 2048) else {
audit(&Principal::Anonymous, AuditOutcome::Failed);
return Err("failed");
};
let identity = match oidc.finish(code, &nonce, &verifier).await {
Ok(identity) => identity,
Err(error) => {
audit(&Principal::Anonymous, AuditOutcome::Failed);
return Err(if matches!(error, OidcError::Unavailable) { "unavailable" } else { "failed" });
}
};
let admin = oidc.config.is_admin(&identity);
let now = now();
let session = state
.db
.upsert_user(&identity.issuer, &identity.subject, &identity.display_name, now)
.map_err(anyhow::Error::from)
.and_then(|user_id| state.sessions.create_oidc(&user_id, &identity.display_name, admin, now));
match session {
Ok(session) => {
audit(&session.principal(), AuditOutcome::Succeeded);
Ok(session)
}
Err(error) => {
tracing::warn!("OIDC session not created: {error:#}");
audit(&Principal::Anonymous, AuditOutcome::Failed);
Err("disabled")
}
}
}
async fn failure(state: &HubState, code: &'static str, status: StatusCode) -> Response {
let _ = state.db.audit_event(&Principal::Anonymous, AuditAction::Login, AuditResource::Session, AuditOutcome::Failed, uuid::Uuid::new_v4());
let mut response = (status, code).into_response();
no_store(response.headers_mut());
response
}

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);
}
}

View File

@@ -237,7 +237,7 @@ struct ReconstituteStartResponse {
pub(super) struct OperatorActor {
pub(super) name: String,
browser: bool,
principal: Principal,
pub(super) principal: Principal,
request_id: Uuid,
}
@@ -263,16 +263,18 @@ pub(super) fn require_admin_mutation(
authorize_operator(state, peer, headers, true)
}
fn authorize_operator(
pub(super) fn authorize_operator(
state: &HubState,
peer: SocketAddr,
headers: &HeaderMap,
mutation: bool,
) -> Result<OperatorActor, StatusCode> {
let request_id = Uuid::new_v4();
let attempted_actor = state.sessions.active(headers)
.map(|session| Principal::Emergency(session.actor)).unwrap_or(Principal::Anonymous);
let result = authorize_operator_inner(state, peer, headers, mutation, request_id);
// Resolve the session once: each lookup is a DB query and may slide the idle window.
let session = state.sessions.active(headers);
let attempted_actor = session.as_ref()
.map(|session| session.principal()).unwrap_or(Principal::Anonymous);
let result = authorize_operator_inner(state, peer, headers, mutation, request_id, session);
let actor = result.as_ref().map(|actor| &actor.principal).unwrap_or(&attempted_actor);
state.db.audit_event(actor, AuditAction::Authorization, AuditResource::Api,
if result.is_ok() { AuditOutcome::Allowed } else { AuditOutcome::Denied }, request_id)
@@ -282,16 +284,21 @@ fn authorize_operator(
fn authorize_operator_inner(
state: &HubState, peer: SocketAddr, headers: &HeaderMap, mutation: bool, request_id: Uuid,
session: Option<crate::admin::BrowserSession>,
) -> Result<OperatorActor, StatusCode> {
if state.admin.token.is_some() && state.admin.authorize(peer, headers).is_ok() {
return Ok(OperatorActor { name: "api-token".into(), browser: false,
principal: Principal::Service("legacy-admin-token"), request_id });
}
if let Some(session) = state.sessions.active(headers) {
if let Some(session) = session {
// Signed in is not the same as allowed: a user without a grant gets 403.
if !session.admin {
return Err(StatusCode::FORBIDDEN);
}
if mutation {
super::session::require_csrf(headers, &session.csrf.to_string())?;
}
return Ok(OperatorActor { principal: Principal::Emergency(session.actor.clone()),
return Ok(OperatorActor { principal: session.principal(),
name: session.actor, browser: true, request_id });
}
if !state.sessions.enabled() {
@@ -327,6 +334,7 @@ pub fn router(state: HubState) -> Router {
.merge(super::jobs::routes())
.merge(super::catalog::routes())
.merge(super::session::routes())
.merge(super::oidc::routes())
.merge(super::restore::routes())
.with_state(state);

View File

@@ -13,9 +13,11 @@ use std::net::SocketAddr;
#[derive(Serialize)]
struct Status {
login_enabled: bool,
oidc_enabled: bool,
authorized: bool,
actor: Option<String>,
csrf: Option<String>,
expires_at: Option<i64>,
}
#[derive(Deserialize)]
@@ -28,6 +30,7 @@ pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/operator/session", get(status).delete(logout))
.route("/api/v1/operator/login", post(login))
.route("/api/v1/me", get(me))
}
async fn status(
@@ -36,20 +39,52 @@ async fn status(
headers: HeaderMap,
) -> (HeaderMap, Json<Status>) {
let browser = state.sessions.active(&headers);
let authorized = browser.is_some()
|| (!state.sessions.enabled() && state.admin.token.is_none()
let authorized = browser.as_ref().is_some_and(|session| session.admin)
|| (browser.is_none() && !state.sessions.enabled() && state.admin.token.is_none()
&& state.admin.authorize(peer, &headers).is_ok());
(
no_store(),
Json(Status {
login_enabled: state.sessions.enabled(),
login_enabled: state.sessions.password_enabled(),
oidc_enabled: state.oidc.is_some(),
authorized,
actor: browser.as_ref().map(|session| session.actor.clone()),
expires_at: browser.as_ref().map(|session| session.expires_at),
csrf: browser.map(|session| session.csrf.to_string()),
}),
)
}
#[derive(Serialize)]
struct Me {
id: String,
kind: &'static str,
auth_method: &'static str,
display_name: String,
capabilities: Vec<&'static str>,
}
/// The caller's own identity. Every authenticated principal is an administrator
/// until scoped grants exist (M5), which is what `capabilities` reports.
async fn me(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(HeaderMap, Json<Me>), StatusCode> {
// A signed-in user without a grant still gets their identity (capabilities empty).
if let Some(session) = state.sessions.active(&headers) {
let (id, kind, auth_method) = session.principal().fields();
let capabilities = if session.admin { vec!["admin"] } else { vec![] };
return Ok((no_store(), Json(Me { id, kind, auth_method, display_name: session.actor, capabilities })));
}
let actor = super::routes::authorize_operator(&state, peer, &headers, false)?;
let (id, kind, auth_method) = actor.principal.fields();
Ok((
no_store(),
Json(Me { id, kind, auth_method, display_name: actor.name.clone(), capabilities: vec!["admin"] }),
))
}
async fn login(
State(state): State<HubState>,
headers: HeaderMap,
@@ -75,13 +110,15 @@ async fn login(
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut headers = no_store();
headers.insert(header::SET_COOKIE, cookie(Some(&session.id.to_string()))?);
headers.insert(header::SET_COOKIE, session_cookie(Some(&session.id.to_string()))?);
Ok((
headers,
Json(Status {
login_enabled: true,
oidc_enabled: state.oidc.is_some(),
authorized: true,
actor: Some(session.actor),
expires_at: Some(session.expires_at),
csrf: Some(session.csrf.to_string()),
}),
))
@@ -97,7 +134,7 @@ async fn logout(
.ok_or(StatusCode::UNAUTHORIZED)?;
require_csrf(&headers, &session.csrf.to_string())?;
state.sessions.remove(session.id);
state.db.audit_event(&Principal::Emergency(session.actor.clone()), AuditAction::Logout,
state.db.audit_event(&session.principal(), AuditAction::Logout,
AuditResource::Session, AuditOutcome::Succeeded, uuid::Uuid::new_v4())
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
state
@@ -106,7 +143,7 @@ async fn logout(
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut headers = no_store();
headers.insert(header::SET_COOKIE, cookie(None)?);
headers.insert(header::SET_COOKIE, session_cookie(None)?);
Ok((StatusCode::NO_CONTENT, headers))
}
@@ -128,7 +165,7 @@ fn no_store() -> HeaderMap {
headers
}
fn cookie(id: Option<&str>) -> Result<HeaderValue, StatusCode> {
pub(super) fn session_cookie(id: Option<&str>) -> Result<HeaderValue, StatusCode> {
let value = format!(
"{}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}",
SessionGate::COOKIE,
@@ -155,7 +192,7 @@ mod tests {
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault")
.await
.unwrap();
state.sessions = SessionGate::fixture();
state.sessions = SessionGate::fixture(state.db.clone());
state.admin.token = Some("fixture-api-token".into());
let app = crate::api::router(state.clone());
let request = |method: &str, uri: &str, body: &'static str| {
@@ -281,4 +318,58 @@ mod tests {
assert!(!values.contains(secret));
}
}
#[tokio::test]
async fn me_reports_the_caller_and_rejects_anonymous() {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault")
.await
.unwrap();
state.sessions = SessionGate::fixture(state.db.clone());
let app = crate::api::router(state);
let peer = || ConnectInfo("127.0.0.1:1234".parse::<SocketAddr>().unwrap());
let anonymous = app
.clone()
.oneshot(Request::builder().uri("/api/v1/me").extension(peer()).body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED);
let login = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/operator/login")
.extension(peer())
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"password":"fixture-operator-password"}"#))
.unwrap(),
)
.await
.unwrap();
let cookie = HeaderValue::from_str(
login.headers()[header::SET_COOKIE].to_str().unwrap().split(';').next().unwrap(),
)
.unwrap();
let me = app
.oneshot(
Request::builder()
.uri("/api/v1/me")
.extension(peer())
.header(header::COOKIE, cookie)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(me.status(), StatusCode::OK);
assert_eq!(me.headers()[header::CACHE_CONTROL], "no-store");
let body: serde_json::Value =
serde_json::from_slice(&to_bytes(me.into_body(), 4096).await.unwrap()).unwrap();
assert_eq!(body["id"], "emergency:fixture-operator");
assert_eq!(body["kind"], "user");
assert_eq!(body["auth_method"], "password");
assert_eq!(body["capabilities"][0], "admin");
assert!(!body.to_string().contains("csrf"));
}
}