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,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
}