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:
5
.cargo/audit.toml
Normal file
5
.cargo/audit.toml
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
# Mirrors deny.toml. Reason: Tessera only verifies RSA signatures with public keys
|
||||||
|
# (openidconnect core/crypto.rs); runtime code never performs RSA private-key operations
|
||||||
|
# (test fixtures sign tokens with throwaway keys).
|
||||||
|
[advisories]
|
||||||
|
ignore = ["RUSTSEC-2023-0071"]
|
||||||
1616
Cargo.lock
generated
1616
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -35,6 +35,7 @@ uuid.workspace = true
|
|||||||
hex.workspace = true
|
hex.workspace = true
|
||||||
sha2.workspace = true
|
sha2.workspace = true
|
||||||
base64 = "0.22"
|
base64 = "0.22"
|
||||||
|
openidconnect = { version = "=4.1.0", default-features = false, features = ["reqwest", "rustls-tls"] }
|
||||||
tempfile.workspace = true
|
tempfile.workspace = true
|
||||||
indexmap = "=2.2.6"
|
indexmap = "=2.2.6"
|
||||||
hyper = { version = "=1.12.0", features = ["server", "http1"] }
|
hyper = { version = "=1.12.0", features = ["server", "http1"] }
|
||||||
@@ -45,4 +46,7 @@ tower = { workspace = true }
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
rcgen = "=0.13.2"
|
rcgen = "=0.13.2"
|
||||||
|
wiremock = "=0.6.5"
|
||||||
|
rsa = { version = "=0.9.10", features = ["sha2"] }
|
||||||
|
hmac.workspace = true
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
|
|||||||
@@ -167,36 +167,69 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Issuer of the break-glass operator row. It is not an `https://` URL, so no
|
||||||
|
/// OIDC provider can ever produce an identity that maps onto it.
|
||||||
|
pub const EMERGENCY_ISSUER: &str = "local:emergency";
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct SessionGate {
|
pub struct SessionGate {
|
||||||
config: Option<std::sync::Arc<OperatorConfig>>,
|
config: Option<std::sync::Arc<OperatorConfig>>,
|
||||||
state: std::sync::Arc<std::sync::Mutex<SessionState>>,
|
db: crate::db::Db,
|
||||||
}
|
/// Fingerprint of the OIDC configuration (issuer, client, admin mapping).
|
||||||
|
/// OIDC sessions only count while the same configuration is active.
|
||||||
#[derive(Default)]
|
oidc_fp: Option<String>,
|
||||||
struct SessionState {
|
attempts: std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<std::time::Instant>>>,
|
||||||
sessions: std::collections::HashMap<uuid::Uuid, BrowserSession>,
|
|
||||||
attempts: std::collections::VecDeque<std::time::Instant>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct OperatorConfig {
|
struct OperatorConfig {
|
||||||
name: String,
|
name: String,
|
||||||
password_hash: String,
|
password_hash: String,
|
||||||
|
/// Sessions are bound to this value, so unsetting or rotating the operator
|
||||||
|
/// hash invalidates every emergency session even though they persist.
|
||||||
|
fingerprint: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct BrowserSession {
|
pub struct BrowserSession {
|
||||||
pub id: uuid::Uuid,
|
pub id: uuid::Uuid,
|
||||||
pub csrf: uuid::Uuid,
|
pub csrf: String,
|
||||||
pub actor: String,
|
pub actor: String,
|
||||||
expires: std::time::Instant,
|
/// Read by per-user revoke and the OIDC login path (M3/M5).
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub user_id: String,
|
||||||
|
pub auth_method: String,
|
||||||
|
/// May use the management API. A signed-in user without a grant is `false`.
|
||||||
|
pub admin: bool,
|
||||||
|
pub expires_at: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BrowserSession {
|
||||||
|
/// Audit identity. Never derived from IdP-supplied names: OIDC users are
|
||||||
|
/// identified by their stable user id, so a username of "operator" cannot
|
||||||
|
/// be mistaken for the emergency account.
|
||||||
|
pub fn principal(&self) -> crate::auth::Principal {
|
||||||
|
match self.auth_method.as_str() {
|
||||||
|
"oidc" => crate::auth::Principal::Oidc(self.user_id.clone()),
|
||||||
|
_ => crate::auth::Principal::Emergency(self.actor.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fingerprint(password_hash: &str) -> String {
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
hex::encode(Sha256::digest(format!("tessera-operator-credential-v1:{password_hash}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unix_now() -> i64 {
|
||||||
|
chrono::Utc::now().timestamp()
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SessionGate {
|
impl SessionGate {
|
||||||
pub const COOKIE: &str = "__Host-tessera-session";
|
pub const COOKIE: &str = "__Host-tessera-session";
|
||||||
pub const DURATION: std::time::Duration = std::time::Duration::from_secs(8 * 3600);
|
pub const DURATION: std::time::Duration =
|
||||||
|
std::time::Duration::from_secs(crate::db::sessions::ABSOLUTE_SECS as u64);
|
||||||
|
|
||||||
pub fn from_env() -> anyhow::Result<Self> {
|
pub fn from_env(db: crate::db::Db, oidc_fp: Option<String>) -> anyhow::Result<Self> {
|
||||||
let config = match std::env::var("TESSERA_OPERATOR_PASSWORD_HASH") {
|
let config = match std::env::var("TESSERA_OPERATOR_PASSWORD_HASH") {
|
||||||
Ok(password_hash) => {
|
Ok(password_hash) => {
|
||||||
let name =
|
let name =
|
||||||
@@ -215,6 +248,7 @@ impl SessionGate {
|
|||||||
"operator password requires Argon2id"
|
"operator password requires Argon2id"
|
||||||
);
|
);
|
||||||
Some(std::sync::Arc::new(OperatorConfig {
|
Some(std::sync::Arc::new(OperatorConfig {
|
||||||
|
fingerprint: fingerprint(&password_hash),
|
||||||
name,
|
name,
|
||||||
password_hash,
|
password_hash,
|
||||||
}))
|
}))
|
||||||
@@ -222,62 +256,132 @@ impl SessionGate {
|
|||||||
Err(std::env::VarError::NotPresent) => None,
|
Err(std::env::VarError::NotPresent) => None,
|
||||||
Err(_) => anyhow::bail!("operator password hash must be UTF-8"),
|
Err(_) => anyhow::bail!("operator password hash must be UTF-8"),
|
||||||
};
|
};
|
||||||
Ok(Self {
|
Ok(Self { config, db, oidc_fp, attempts: Default::default() })
|
||||||
config,
|
|
||||||
state: Default::default(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Any browser login method is configured (emergency password and/or OIDC).
|
||||||
pub fn enabled(&self) -> bool {
|
pub fn enabled(&self) -> bool {
|
||||||
|
self.config.is_some() || self.oidc_fp.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The emergency password form is available.
|
||||||
|
pub fn password_enabled(&self) -> bool {
|
||||||
self.config.is_some()
|
self.config.is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn active(&self, headers: &HeaderMap) -> Option<BrowserSession> {
|
pub fn active(&self, headers: &HeaderMap) -> Option<BrowserSession> {
|
||||||
|
self.active_at(headers, unix_now())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn active_at(&self, headers: &HeaderMap, now: i64) -> Option<BrowserSession> {
|
||||||
let id = cookie_id(headers)?;
|
let id = cookie_id(headers)?;
|
||||||
let mut state = self.state.lock().unwrap();
|
let stored = match self.db.lookup_session(&id.to_string(), now) {
|
||||||
state
|
Ok(found) => found?,
|
||||||
.sessions
|
Err(error) => {
|
||||||
.retain(|_, session| session.expires > std::time::Instant::now());
|
tracing::error!("session lookup failed: {error:#}");
|
||||||
state.sessions.get(&id).cloned()
|
return None;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// Sessions only count while the credential/configuration that created
|
||||||
|
// them is still the active one, so unsetting or rotating either revokes them.
|
||||||
|
let expected = match stored.auth_method.as_str() {
|
||||||
|
"password" => self.config.as_ref().map(|config| config.fingerprint.as_str()),
|
||||||
|
"oidc" => self.oidc_fp.as_deref(),
|
||||||
|
_ => None,
|
||||||
|
}?;
|
||||||
|
if stored.credential_fp.as_deref() != Some(expected) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(BrowserSession {
|
||||||
|
id,
|
||||||
|
csrf: crate::db::sessions::csrf_token(&id.to_string()),
|
||||||
|
actor: stored.display_name,
|
||||||
|
user_id: stored.user_id,
|
||||||
|
auth_method: stored.auth_method,
|
||||||
|
admin: stored.admin,
|
||||||
|
expires_at: stored.expires_at,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn login(&self, headers: &HeaderMap, password: &str) -> Result<BrowserSession, StatusCode> {
|
pub fn login(&self, headers: &HeaderMap, password: &str) -> Result<BrowserSession, StatusCode> {
|
||||||
use argon2::PasswordVerifier;
|
use argon2::PasswordVerifier;
|
||||||
let config = self.config.as_ref().ok_or(StatusCode::NOT_FOUND)?;
|
let config = self.config.as_ref().ok_or(StatusCode::NOT_FOUND)?;
|
||||||
{
|
{
|
||||||
let mut state = self.state.lock().unwrap();
|
let mut attempts = self.attempts.lock().unwrap();
|
||||||
state
|
attempts.retain(|attempt| attempt.elapsed() < std::time::Duration::from_secs(60));
|
||||||
.attempts
|
if attempts.len() >= 10 {
|
||||||
.retain(|attempt| attempt.elapsed() < std::time::Duration::from_secs(60));
|
|
||||||
if state.attempts.len() >= 10 {
|
|
||||||
return Err(StatusCode::TOO_MANY_REQUESTS);
|
return Err(StatusCode::TOO_MANY_REQUESTS);
|
||||||
}
|
}
|
||||||
state.attempts.push_back(std::time::Instant::now());
|
attempts.push_back(std::time::Instant::now());
|
||||||
}
|
}
|
||||||
let hash = argon2::PasswordHash::new(&config.password_hash)
|
let hash = argon2::PasswordHash::new(&config.password_hash)
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
argon2::Argon2::default()
|
argon2::Argon2::default()
|
||||||
.verify_password(password.as_bytes(), &hash)
|
.verify_password(password.as_bytes(), &hash)
|
||||||
.map_err(|_| StatusCode::UNAUTHORIZED)?;
|
.map_err(|_| StatusCode::UNAUTHORIZED)?;
|
||||||
if let Some(id) = cookie_id(headers) {
|
let internal = |error: anyhow::Error| {
|
||||||
self.remove(id);
|
tracing::error!("session create failed: {error:#}");
|
||||||
}
|
StatusCode::INTERNAL_SERVER_ERROR
|
||||||
let session = BrowserSession {
|
|
||||||
id: uuid::Uuid::new_v4(),
|
|
||||||
csrf: uuid::Uuid::new_v4(),
|
|
||||||
actor: config.name.clone(),
|
|
||||||
expires: std::time::Instant::now() + Self::DURATION,
|
|
||||||
};
|
};
|
||||||
let mut state = self.state.lock().unwrap();
|
// A new ID on every login: a pre-existing cookie never survives (fixation).
|
||||||
state
|
if let Some(old) = cookie_id(headers) {
|
||||||
.sessions
|
self.remove(old);
|
||||||
.retain(|_, session| session.expires > std::time::Instant::now());
|
}
|
||||||
state.sessions.insert(session.id, session.clone());
|
let now = unix_now();
|
||||||
Ok(session)
|
let user_id = self
|
||||||
|
.db
|
||||||
|
.upsert_user(EMERGENCY_ISSUER, &config.name, &config.name, now)
|
||||||
|
.map_err(internal)?;
|
||||||
|
let id = uuid::Uuid::new_v4();
|
||||||
|
let created = self
|
||||||
|
.db
|
||||||
|
.create_session(&id.to_string(), &user_id, "password", Some(&config.fingerprint), true, now)
|
||||||
|
.map_err(internal)?;
|
||||||
|
if !created {
|
||||||
|
// Inactive user row: the break-glass account has been disabled.
|
||||||
|
return Err(StatusCode::UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
Ok(BrowserSession {
|
||||||
|
id,
|
||||||
|
csrf: crate::db::sessions::csrf_token(&id.to_string()),
|
||||||
|
actor: config.name.clone(),
|
||||||
|
user_id,
|
||||||
|
auth_method: "password".into(),
|
||||||
|
admin: true,
|
||||||
|
expires_at: now + crate::db::sessions::ABSOLUTE_SECS,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start an OIDC-backed session for a verified identity. The caller has
|
||||||
|
/// already validated the ID token; `admin` comes from the configured mapping.
|
||||||
|
pub fn create_oidc(
|
||||||
|
&self,
|
||||||
|
user_id: &str,
|
||||||
|
display_name: &str,
|
||||||
|
admin: bool,
|
||||||
|
now: i64,
|
||||||
|
) -> anyhow::Result<BrowserSession> {
|
||||||
|
let fp = self.oidc_fp.as_deref().ok_or_else(|| anyhow::anyhow!("OIDC is not configured"))?;
|
||||||
|
let id = uuid::Uuid::new_v4();
|
||||||
|
anyhow::ensure!(
|
||||||
|
self.db.create_session(&id.to_string(), user_id, "oidc", Some(fp), admin, now)?,
|
||||||
|
"user is disabled"
|
||||||
|
);
|
||||||
|
Ok(BrowserSession {
|
||||||
|
id,
|
||||||
|
csrf: crate::db::sessions::csrf_token(&id.to_string()),
|
||||||
|
actor: display_name.to_string(),
|
||||||
|
user_id: user_id.to_string(),
|
||||||
|
auth_method: "oidc".into(),
|
||||||
|
admin,
|
||||||
|
expires_at: now + crate::db::sessions::ABSOLUTE_SECS,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove(&self, id: uuid::Uuid) {
|
pub fn remove(&self, id: uuid::Uuid) {
|
||||||
self.state.lock().unwrap().sessions.remove(&id);
|
if let Err(error) = self.db.revoke_session(&id.to_string()) {
|
||||||
|
tracing::error!("session revoke failed: {error:#}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,25 +419,147 @@ pub fn print_operator_hash() -> anyhow::Result<()> {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
impl SessionGate {
|
impl SessionGate {
|
||||||
pub fn fixture() -> Self {
|
pub fn fixture(db: crate::db::Db) -> Self {
|
||||||
use argon2::password_hash::{PasswordHasher, SaltString};
|
use argon2::password_hash::{PasswordHasher, SaltString};
|
||||||
let salt = SaltString::encode_b64(b"synthetic-fixture").unwrap();
|
let salt = SaltString::encode_b64(b"synthetic-fixture").unwrap();
|
||||||
let password_hash = argon2::Argon2::default()
|
let password_hash = argon2::Argon2::default()
|
||||||
.hash_password(b"fixture-operator-password", &salt)
|
.hash_password(b"fixture-operator-password", &salt)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.to_string();
|
.to_string();
|
||||||
|
Self::with_hash(db, "fixture-operator", password_hash)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_hash(db: crate::db::Db, name: &str, password_hash: String) -> Self {
|
||||||
Self {
|
Self {
|
||||||
config: Some(std::sync::Arc::new(OperatorConfig {
|
config: Some(std::sync::Arc::new(OperatorConfig {
|
||||||
name: "fixture-operator".into(),
|
name: name.into(),
|
||||||
|
fingerprint: fingerprint(&password_hash),
|
||||||
password_hash,
|
password_hash,
|
||||||
})),
|
})),
|
||||||
state: Default::default(),
|
db,
|
||||||
|
oidc_fp: None,
|
||||||
|
attempts: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Same database, no operator configured (hash unset after a restart).
|
||||||
|
pub fn without_operator(db: crate::db::Db) -> Self {
|
||||||
|
Self { config: None, db, oidc_fp: None, attempts: Default::default() }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_oidc(mut self, fingerprint: &str) -> Self {
|
||||||
|
self.oidc_fp = Some(fingerprint.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
pub fn expire(&self) {
|
pub fn expire(&self) {
|
||||||
for session in self.state.lock().unwrap().sessions.values_mut() {
|
self.db.expire_all_sessions();
|
||||||
session.expires = std::time::Instant::now();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod session_gate_tests {
|
||||||
|
use super::*;
|
||||||
|
use axum::http::HeaderValue;
|
||||||
|
|
||||||
|
fn hash(password: &str, salt: &[u8]) -> String {
|
||||||
|
use argon2::password_hash::{PasswordHasher, SaltString};
|
||||||
|
argon2::Argon2::default()
|
||||||
|
.hash_password(password.as_bytes(), &SaltString::encode_b64(salt).unwrap())
|
||||||
|
.unwrap()
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cookie(session: &BrowserSession) -> HeaderMap {
|
||||||
|
let mut headers = HeaderMap::new();
|
||||||
|
headers.insert(
|
||||||
|
axum::http::header::COOKIE,
|
||||||
|
HeaderValue::from_str(&format!("{}={}", SessionGate::COOKIE, session.id)).unwrap(),
|
||||||
|
);
|
||||||
|
headers
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn db() -> (tempfile::TempDir, crate::db::Db) {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let db = crate::db::Db::connect(&dir.path().join("t.db")).await.unwrap();
|
||||||
|
db.migrate().await.unwrap();
|
||||||
|
(dir, db)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_session_outlives_a_restart_only_with_the_same_operator_credential() {
|
||||||
|
let (_dir, db) = db().await;
|
||||||
|
let first = SessionGate::with_hash(db.clone(), "ops", hash("correct-horse-battery", b"salt-number-one"));
|
||||||
|
let session = first.login(&HeaderMap::new(), "correct-horse-battery").unwrap();
|
||||||
|
// restart with the same credential: still valid
|
||||||
|
let restarted = SessionGate::with_hash(db.clone(), "ops", hash("correct-horse-battery", b"salt-number-one"));
|
||||||
|
assert!(restarted.active(&cookie(&session)).is_some());
|
||||||
|
// hash rotated after a suspected compromise: old cookie is dead
|
||||||
|
let rotated = SessionGate::with_hash(db.clone(), "ops", hash("another-long-password", b"salt-number-two"));
|
||||||
|
assert!(rotated.active(&cookie(&session)).is_none());
|
||||||
|
// emergency login disabled by unsetting the hash: old cookie is dead
|
||||||
|
assert!(SessionGate::without_operator(db.clone()).active(&cookie(&session)).is_none());
|
||||||
|
// and it comes back only if the exact credential is configured again
|
||||||
|
assert!(restarted.active(&cookie(&session)).is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn login_replaces_a_presented_session_id() {
|
||||||
|
let (_dir, db) = db().await;
|
||||||
|
let gate = SessionGate::with_hash(db, "ops", hash("correct-horse-battery", b"salt-number-one"));
|
||||||
|
let old = gate.login(&HeaderMap::new(), "correct-horse-battery").unwrap();
|
||||||
|
let new = gate.login(&cookie(&old), "correct-horse-battery").unwrap();
|
||||||
|
assert_ne!(old.id, new.id);
|
||||||
|
assert!(gate.active(&cookie(&old)).is_none());
|
||||||
|
assert!(gate.active(&cookie(&new)).is_some());
|
||||||
|
assert_eq!(old.user_id, new.user_id, "same break-glass user row across logins");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn absolute_expiry_and_user_revoke_apply_to_the_gate() {
|
||||||
|
let (_dir, db) = db().await;
|
||||||
|
let gate = SessionGate::with_hash(db.clone(), "ops", hash("correct-horse-battery", b"salt-number-one"));
|
||||||
|
let session = gate.login(&HeaderMap::new(), "correct-horse-battery").unwrap();
|
||||||
|
let now = unix_now();
|
||||||
|
assert!(gate.active_at(&cookie(&session), now + 60).is_some());
|
||||||
|
assert!(gate.active_at(&cookie(&session), now + crate::db::sessions::ABSOLUTE_SECS).is_none());
|
||||||
|
assert_eq!(db.revoke_user_sessions(&session.user_id).unwrap(), 1);
|
||||||
|
assert!(gate.active(&cookie(&session)).is_none());
|
||||||
|
assert!(gate.login(&HeaderMap::new(), "correct-horse-battery").is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_csrf_token_is_stable_for_a_session_and_not_the_cookie() {
|
||||||
|
let (_dir, db) = db().await;
|
||||||
|
let gate = SessionGate::with_hash(db, "ops", hash("correct-horse-battery", b"salt-number-one"));
|
||||||
|
let session = gate.login(&HeaderMap::new(), "correct-horse-battery").unwrap();
|
||||||
|
let again = gate.active(&cookie(&session)).unwrap();
|
||||||
|
assert_eq!(session.csrf, again.csrf);
|
||||||
|
assert!(!session.csrf.contains(&session.id.to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn oidc_sessions_end_when_the_oidc_configuration_changes_or_is_removed() {
|
||||||
|
let (_dir, db) = db().await;
|
||||||
|
let user = db.upsert_user("https://idp.example", "alice", "Alice", unix_now()).unwrap();
|
||||||
|
let gate = SessionGate::without_operator(db.clone()).with_oidc("fp-a");
|
||||||
|
let session = gate.create_oidc(&user, "Alice", true, unix_now()).unwrap();
|
||||||
|
assert_eq!(session.principal().fields().0, format!("oidc:{user}"));
|
||||||
|
assert!(gate.active(&cookie(&session)).is_some());
|
||||||
|
// admin mapping changed (different fingerprint) or OIDC switched off: dead
|
||||||
|
assert!(SessionGate::without_operator(db.clone()).with_oidc("fp-b").active(&cookie(&session)).is_none());
|
||||||
|
assert!(SessionGate::without_operator(db.clone()).active(&cookie(&session)).is_none());
|
||||||
|
// configuration restored: the same session is valid again
|
||||||
|
assert!(SessionGate::without_operator(db).with_oidc("fp-a").active(&cookie(&session)).is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_oidc_display_name_never_becomes_the_emergency_principal() {
|
||||||
|
let (_dir, db) = db().await;
|
||||||
|
let user = db.upsert_user("https://idp.example", "mallory", "operator", unix_now()).unwrap();
|
||||||
|
let session = SessionGate::without_operator(db).with_oidc("fp").create_oidc(&user, "operator", false, unix_now()).unwrap();
|
||||||
|
let (id, kind, method) = session.principal().fields();
|
||||||
|
assert_eq!((kind, method), ("user", "oidc"));
|
||||||
|
assert!(id.starts_with("oidc:") && !id.contains("emergency"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ fn every_registered_path_has_an_authorization_contract() {
|
|||||||
include_str!("restore.rs"),
|
include_str!("restore.rs"),
|
||||||
include_str!("catalog.rs"),
|
include_str!("catalog.rs"),
|
||||||
include_str!("session.rs"),
|
include_str!("session.rs"),
|
||||||
|
include_str!("oidc.rs"),
|
||||||
] {
|
] {
|
||||||
for route in source.split(".route(").skip(1) {
|
for route in source.split(".route(").skip(1) {
|
||||||
let path = route.split('"').nth(1).expect("route literal");
|
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")
|
crate::state::HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault")
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
state.sessions = crate::admin::SessionGate::fixture();
|
state.sessions = crate::admin::SessionGate::fixture(state.db.clone());
|
||||||
state.admin.token = Some("synthetic-admin".into());
|
state.admin.token = Some("synthetic-admin".into());
|
||||||
let outpost = uuid::Uuid::new_v4();
|
let outpost = uuid::Uuid::new_v4();
|
||||||
state
|
state
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
mod catalog;
|
mod catalog;
|
||||||
mod jobs;
|
mod jobs;
|
||||||
|
mod oidc;
|
||||||
mod orbit;
|
mod orbit;
|
||||||
mod restore;
|
mod restore;
|
||||||
mod routes;
|
mod routes;
|
||||||
mod session;
|
mod session;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod auth_contract;
|
mod auth_contract;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod oidc_tests;
|
||||||
|
|
||||||
pub use orbit::run_orbit_internal;
|
pub use orbit::run_orbit_internal;
|
||||||
pub use routes::router;
|
pub use routes::router;
|
||||||
|
|||||||
160
crates/tessera-hub/src/api/oidc.rs
Normal file
160
crates/tessera-hub/src/api/oidc.rs
Normal 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
|
||||||
|
}
|
||||||
552
crates/tessera-hub/src/api/oidc_tests.rs
Normal file
552
crates/tessera-hub/src/api/oidc_tests.rs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -237,7 +237,7 @@ struct ReconstituteStartResponse {
|
|||||||
pub(super) struct OperatorActor {
|
pub(super) struct OperatorActor {
|
||||||
pub(super) name: String,
|
pub(super) name: String,
|
||||||
browser: bool,
|
browser: bool,
|
||||||
principal: Principal,
|
pub(super) principal: Principal,
|
||||||
request_id: Uuid,
|
request_id: Uuid,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -263,16 +263,18 @@ pub(super) fn require_admin_mutation(
|
|||||||
authorize_operator(state, peer, headers, true)
|
authorize_operator(state, peer, headers, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn authorize_operator(
|
pub(super) fn authorize_operator(
|
||||||
state: &HubState,
|
state: &HubState,
|
||||||
peer: SocketAddr,
|
peer: SocketAddr,
|
||||||
headers: &HeaderMap,
|
headers: &HeaderMap,
|
||||||
mutation: bool,
|
mutation: bool,
|
||||||
) -> Result<OperatorActor, StatusCode> {
|
) -> Result<OperatorActor, StatusCode> {
|
||||||
let request_id = Uuid::new_v4();
|
let request_id = Uuid::new_v4();
|
||||||
let attempted_actor = state.sessions.active(headers)
|
// Resolve the session once: each lookup is a DB query and may slide the idle window.
|
||||||
.map(|session| Principal::Emergency(session.actor)).unwrap_or(Principal::Anonymous);
|
let session = state.sessions.active(headers);
|
||||||
let result = authorize_operator_inner(state, peer, headers, mutation, request_id);
|
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);
|
let actor = result.as_ref().map(|actor| &actor.principal).unwrap_or(&attempted_actor);
|
||||||
state.db.audit_event(actor, AuditAction::Authorization, AuditResource::Api,
|
state.db.audit_event(actor, AuditAction::Authorization, AuditResource::Api,
|
||||||
if result.is_ok() { AuditOutcome::Allowed } else { AuditOutcome::Denied }, request_id)
|
if result.is_ok() { AuditOutcome::Allowed } else { AuditOutcome::Denied }, request_id)
|
||||||
@@ -282,16 +284,21 @@ fn authorize_operator(
|
|||||||
|
|
||||||
fn authorize_operator_inner(
|
fn authorize_operator_inner(
|
||||||
state: &HubState, peer: SocketAddr, headers: &HeaderMap, mutation: bool, request_id: Uuid,
|
state: &HubState, peer: SocketAddr, headers: &HeaderMap, mutation: bool, request_id: Uuid,
|
||||||
|
session: Option<crate::admin::BrowserSession>,
|
||||||
) -> Result<OperatorActor, StatusCode> {
|
) -> Result<OperatorActor, StatusCode> {
|
||||||
if state.admin.token.is_some() && state.admin.authorize(peer, headers).is_ok() {
|
if state.admin.token.is_some() && state.admin.authorize(peer, headers).is_ok() {
|
||||||
return Ok(OperatorActor { name: "api-token".into(), browser: false,
|
return Ok(OperatorActor { name: "api-token".into(), browser: false,
|
||||||
principal: Principal::Service("legacy-admin-token"), request_id });
|
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 {
|
if mutation {
|
||||||
super::session::require_csrf(headers, &session.csrf.to_string())?;
|
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 });
|
name: session.actor, browser: true, request_id });
|
||||||
}
|
}
|
||||||
if !state.sessions.enabled() {
|
if !state.sessions.enabled() {
|
||||||
@@ -327,6 +334,7 @@ pub fn router(state: HubState) -> Router {
|
|||||||
.merge(super::jobs::routes())
|
.merge(super::jobs::routes())
|
||||||
.merge(super::catalog::routes())
|
.merge(super::catalog::routes())
|
||||||
.merge(super::session::routes())
|
.merge(super::session::routes())
|
||||||
|
.merge(super::oidc::routes())
|
||||||
.merge(super::restore::routes())
|
.merge(super::restore::routes())
|
||||||
.with_state(state);
|
.with_state(state);
|
||||||
|
|
||||||
|
|||||||
@@ -13,9 +13,11 @@ use std::net::SocketAddr;
|
|||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
struct Status {
|
struct Status {
|
||||||
login_enabled: bool,
|
login_enabled: bool,
|
||||||
|
oidc_enabled: bool,
|
||||||
authorized: bool,
|
authorized: bool,
|
||||||
actor: Option<String>,
|
actor: Option<String>,
|
||||||
csrf: Option<String>,
|
csrf: Option<String>,
|
||||||
|
expires_at: Option<i64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
@@ -28,6 +30,7 @@ pub(super) fn routes() -> Router<HubState> {
|
|||||||
Router::new()
|
Router::new()
|
||||||
.route("/api/v1/operator/session", get(status).delete(logout))
|
.route("/api/v1/operator/session", get(status).delete(logout))
|
||||||
.route("/api/v1/operator/login", post(login))
|
.route("/api/v1/operator/login", post(login))
|
||||||
|
.route("/api/v1/me", get(me))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn status(
|
async fn status(
|
||||||
@@ -36,20 +39,52 @@ async fn status(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
) -> (HeaderMap, Json<Status>) {
|
) -> (HeaderMap, Json<Status>) {
|
||||||
let browser = state.sessions.active(&headers);
|
let browser = state.sessions.active(&headers);
|
||||||
let authorized = browser.is_some()
|
let authorized = browser.as_ref().is_some_and(|session| session.admin)
|
||||||
|| (!state.sessions.enabled() && state.admin.token.is_none()
|
|| (browser.is_none() && !state.sessions.enabled() && state.admin.token.is_none()
|
||||||
&& state.admin.authorize(peer, &headers).is_ok());
|
&& state.admin.authorize(peer, &headers).is_ok());
|
||||||
(
|
(
|
||||||
no_store(),
|
no_store(),
|
||||||
Json(Status {
|
Json(Status {
|
||||||
login_enabled: state.sessions.enabled(),
|
login_enabled: state.sessions.password_enabled(),
|
||||||
|
oidc_enabled: state.oidc.is_some(),
|
||||||
authorized,
|
authorized,
|
||||||
actor: browser.as_ref().map(|session| session.actor.clone()),
|
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()),
|
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(
|
async fn login(
|
||||||
State(state): State<HubState>,
|
State(state): State<HubState>,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
@@ -75,13 +110,15 @@ async fn login(
|
|||||||
.await
|
.await
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
let mut headers = no_store();
|
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((
|
Ok((
|
||||||
headers,
|
headers,
|
||||||
Json(Status {
|
Json(Status {
|
||||||
login_enabled: true,
|
login_enabled: true,
|
||||||
|
oidc_enabled: state.oidc.is_some(),
|
||||||
authorized: true,
|
authorized: true,
|
||||||
actor: Some(session.actor),
|
actor: Some(session.actor),
|
||||||
|
expires_at: Some(session.expires_at),
|
||||||
csrf: Some(session.csrf.to_string()),
|
csrf: Some(session.csrf.to_string()),
|
||||||
}),
|
}),
|
||||||
))
|
))
|
||||||
@@ -97,7 +134,7 @@ async fn logout(
|
|||||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||||
require_csrf(&headers, &session.csrf.to_string())?;
|
require_csrf(&headers, &session.csrf.to_string())?;
|
||||||
state.sessions.remove(session.id);
|
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())
|
AuditResource::Session, AuditOutcome::Succeeded, uuid::Uuid::new_v4())
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
state
|
state
|
||||||
@@ -106,7 +143,7 @@ async fn logout(
|
|||||||
.await
|
.await
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
let mut headers = no_store();
|
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))
|
Ok((StatusCode::NO_CONTENT, headers))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,7 +165,7 @@ fn no_store() -> HeaderMap {
|
|||||||
headers
|
headers
|
||||||
}
|
}
|
||||||
|
|
||||||
fn cookie(id: Option<&str>) -> Result<HeaderValue, StatusCode> {
|
pub(super) fn session_cookie(id: Option<&str>) -> Result<HeaderValue, StatusCode> {
|
||||||
let value = format!(
|
let value = format!(
|
||||||
"{}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}",
|
"{}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}",
|
||||||
SessionGate::COOKIE,
|
SessionGate::COOKIE,
|
||||||
@@ -155,7 +192,7 @@ mod tests {
|
|||||||
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault")
|
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault")
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
state.sessions = SessionGate::fixture();
|
state.sessions = SessionGate::fixture(state.db.clone());
|
||||||
state.admin.token = Some("fixture-api-token".into());
|
state.admin.token = Some("fixture-api-token".into());
|
||||||
let app = crate::api::router(state.clone());
|
let app = crate::api::router(state.clone());
|
||||||
let request = |method: &str, uri: &str, body: &'static str| {
|
let request = |method: &str, uri: &str, body: &'static str| {
|
||||||
@@ -281,4 +318,58 @@ mod tests {
|
|||||||
assert!(!values.contains(secret));
|
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"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ use uuid::Uuid;
|
|||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub enum Principal {
|
pub enum Principal {
|
||||||
Emergency(String),
|
Emergency(String),
|
||||||
|
/// OIDC user, by stable `users.id` (never by a name supplied by the IdP).
|
||||||
|
Oidc(String),
|
||||||
Service(&'static str),
|
Service(&'static str),
|
||||||
Outpost(Uuid),
|
Outpost(Uuid),
|
||||||
Anonymous,
|
Anonymous,
|
||||||
@@ -14,6 +16,7 @@ impl Principal {
|
|||||||
pub fn fields(&self) -> (String, &'static str, &'static str) {
|
pub fn fields(&self) -> (String, &'static str, &'static str) {
|
||||||
match self {
|
match self {
|
||||||
Self::Emergency(name) => (format!("emergency:{name}"), "user", "password"),
|
Self::Emergency(name) => (format!("emergency:{name}"), "user", "password"),
|
||||||
|
Self::Oidc(id) => (format!("oidc:{id}"), "user", "oidc"),
|
||||||
Self::Service(id) => (id.to_string(), "service", "api_token"),
|
Self::Service(id) => (id.to_string(), "service", "api_token"),
|
||||||
Self::Outpost(id) => (id.to_string(), "outpost", "outpost_token"),
|
Self::Outpost(id) => (id.to_string(), "outpost", "outpost_token"),
|
||||||
Self::Anonymous => ("anonymous".into(), "anonymous", "none"),
|
Self::Anonymous => ("anonymous".into(), "anonymous", "none"),
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
mod jobs;
|
mod jobs;
|
||||||
mod restore;
|
mod restore;
|
||||||
mod audit;
|
mod audit;
|
||||||
|
pub mod sessions;
|
||||||
|
pub(crate) mod oidc_login;
|
||||||
pub(crate) use restore::restore_target_mismatch;
|
pub(crate) use restore::restore_target_mismatch;
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
@@ -104,6 +106,8 @@ impl Db {
|
|||||||
jobs::migrate(&conn)?;
|
jobs::migrate(&conn)?;
|
||||||
restore::migrate(&conn)?;
|
restore::migrate(&conn)?;
|
||||||
audit::migrate(&conn)?;
|
audit::migrate(&conn)?;
|
||||||
|
sessions::migrate(&conn)?;
|
||||||
|
oidc_login::migrate(&conn)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
99
crates/tessera-hub/src/db/oidc_login.rs
Normal file
99
crates/tessera-hub/src/db/oidc_login.rs
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
//! One-time OIDC login transactions (state, nonce, PKCE verifier) bound to the
|
||||||
|
//! browser that started them.
|
||||||
|
use super::*;
|
||||||
|
use crate::db::sessions::session_digest;
|
||||||
|
|
||||||
|
pub const TTL_SECS: i64 = 600;
|
||||||
|
/// `/login` is a public GET that inserts a row; bound the table.
|
||||||
|
const MAX_PENDING: i64 = 500;
|
||||||
|
|
||||||
|
pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||||
|
conn.execute_batch(
|
||||||
|
"CREATE TABLE IF NOT EXISTS oidc_login (
|
||||||
|
state_digest TEXT PRIMARY KEY,
|
||||||
|
browser_digest TEXT NOT NULL,
|
||||||
|
nonce TEXT NOT NULL,
|
||||||
|
pkce_verifier TEXT NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL
|
||||||
|
);",
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Db {
|
||||||
|
/// Store a transaction. Returns false when too many are pending.
|
||||||
|
pub fn begin_oidc_login(&self, state: &str, browser: &str, nonce: &str, verifier: &str, now: i64) -> Result<bool> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
conn.execute("DELETE FROM oidc_login WHERE expires_at <= ?1", params![now])?;
|
||||||
|
let pending: i64 = conn.query_row("SELECT COUNT(*) FROM oidc_login", [], |r| r.get(0))?;
|
||||||
|
if pending >= MAX_PENDING {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO oidc_login(state_digest,browser_digest,nonce,pkce_verifier,expires_at) VALUES (?1,?2,?3,?4,?5)",
|
||||||
|
params![session_digest(state), session_digest(browser), nonce, verifier, now + TTL_SECS],
|
||||||
|
)?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Atomically consume the transaction for `state`. Any attempt burns it,
|
||||||
|
/// including one from a browser that does not hold the correlation cookie,
|
||||||
|
/// so a leaked `state` cannot be retried. Returns `(nonce, verifier)` only
|
||||||
|
/// for the right browser, before expiry, exactly once.
|
||||||
|
pub fn consume_oidc_login(&self, state: &str, browser: Option<&str>, now: i64) -> Result<Option<(String, String)>> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
let row: Option<(String, String, String, i64)> = conn
|
||||||
|
.query_row(
|
||||||
|
"DELETE FROM oidc_login WHERE state_digest=?1 RETURNING browser_digest,nonce,pkce_verifier,expires_at",
|
||||||
|
params![session_digest(state)],
|
||||||
|
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
|
||||||
|
)
|
||||||
|
.optional()?;
|
||||||
|
Ok(row.and_then(|(bound, nonce, verifier, expires)| {
|
||||||
|
(browser.is_some_and(|b| session_digest(b) == bound) && expires > now).then_some((nonce, verifier))
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
async fn db() -> (tempfile::TempDir, Db) {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let db = Db::connect(&dir.path().join("t.db")).await.unwrap();
|
||||||
|
db.migrate().await.unwrap();
|
||||||
|
(dir, db)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_transaction_is_single_use_and_bound_to_its_browser() {
|
||||||
|
let (_dir, db) = db().await;
|
||||||
|
assert!(db.begin_oidc_login("s1", "b1", "n", "v", 100).unwrap());
|
||||||
|
assert_eq!(db.consume_oidc_login("s1", Some("b1"), 101).unwrap(), Some(("n".into(), "v".into())));
|
||||||
|
assert_eq!(db.consume_oidc_login("s1", Some("b1"), 102).unwrap(), None, "replay");
|
||||||
|
db.begin_oidc_login("s2", "b2", "n", "v", 100).unwrap();
|
||||||
|
assert_eq!(db.consume_oidc_login("s2", Some("other"), 101).unwrap(), None, "wrong browser");
|
||||||
|
assert_eq!(db.consume_oidc_login("s2", Some("b2"), 102).unwrap(), None, "burned by the failed attempt");
|
||||||
|
db.begin_oidc_login("s3", "b3", "n", "v", 100).unwrap();
|
||||||
|
assert_eq!(db.consume_oidc_login("s3", None, 101).unwrap(), None, "no cookie");
|
||||||
|
db.begin_oidc_login("s4", "b4", "n", "v", 100).unwrap();
|
||||||
|
assert_eq!(db.consume_oidc_login("s4", Some("b4"), 100 + TTL_SECS).unwrap(), None, "expired");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn only_digests_of_state_and_browser_are_keys_and_pending_rows_are_capped() {
|
||||||
|
let (_dir, db) = db().await;
|
||||||
|
db.begin_oidc_login("raw-state", "raw-browser", "n", "v", 1).unwrap();
|
||||||
|
let (state, browser): (String, String) = db
|
||||||
|
.conn.lock().unwrap()
|
||||||
|
.query_row("SELECT state_digest,browser_digest FROM oidc_login", [], |r| Ok((r.get(0)?, r.get(1)?)))
|
||||||
|
.unwrap();
|
||||||
|
assert!(!state.contains("raw-state") && !browser.contains("raw-browser"));
|
||||||
|
for i in 0..MAX_PENDING {
|
||||||
|
let _ = db.begin_oidc_login(&format!("s{i}"), "b", "n", "v", 1);
|
||||||
|
}
|
||||||
|
assert!(!db.begin_oidc_login("one-too-many", "b", "n", "v", 1).unwrap());
|
||||||
|
assert!(db.begin_oidc_login("after-expiry", "b", "n", "v", 1 + TTL_SECS).unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
281
crates/tessera-hub/src/db/sessions.rs
Normal file
281
crates/tessera-hub/src/db/sessions.rs
Normal file
@@ -0,0 +1,281 @@
|
|||||||
|
//! Persistent users and browser sessions.
|
||||||
|
//!
|
||||||
|
//! Only a digest of the session ID is stored. Revocation is explicit (rows are
|
||||||
|
//! deleted in a transaction and the user's generation is bumped) because SQLite
|
||||||
|
//! foreign keys are not enabled on this connection.
|
||||||
|
use super::*;
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
pub const IDLE_SECS: i64 = 30 * 60;
|
||||||
|
pub const ABSOLUTE_SECS: i64 = 8 * 3600;
|
||||||
|
/// `last_seen` is only rewritten when it is this stale, to avoid a write per request.
|
||||||
|
const TOUCH_AFTER_SECS: i64 = 60;
|
||||||
|
|
||||||
|
/// Digest used as the primary key; the raw session ID never reaches the database.
|
||||||
|
pub fn session_digest(id: &str) -> String {
|
||||||
|
hex::encode(Sha256::digest(format!("tessera-session-v1:{id}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// CSRF token derived from the session ID with a different domain prefix, so it
|
||||||
|
/// can be shown to the page without being usable as the stored digest.
|
||||||
|
pub fn csrf_token(id: &str) -> String {
|
||||||
|
hex::encode(Sha256::digest(format!("tessera-csrf-v1:{id}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct StoredSession {
|
||||||
|
pub user_id: String,
|
||||||
|
pub display_name: String,
|
||||||
|
pub auth_method: String,
|
||||||
|
pub credential_fp: Option<String>,
|
||||||
|
pub admin: bool,
|
||||||
|
pub expires_at: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||||
|
conn.execute_batch(
|
||||||
|
"CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
issuer TEXT NOT NULL,
|
||||||
|
subject TEXT NOT NULL,
|
||||||
|
display_name TEXT NOT NULL,
|
||||||
|
active INTEGER NOT NULL DEFAULT 1 CHECK(active IN (0,1)),
|
||||||
|
generation INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
last_login_at INTEGER,
|
||||||
|
UNIQUE(issuer, subject)
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS sessions (
|
||||||
|
token_digest TEXT PRIMARY KEY,
|
||||||
|
user_id TEXT NOT NULL,
|
||||||
|
generation INTEGER NOT NULL,
|
||||||
|
auth_method TEXT NOT NULL,
|
||||||
|
credential_fp TEXT,
|
||||||
|
auth_time INTEGER NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
last_seen INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS sessions_user ON sessions(user_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS sessions_expiry ON sessions(expires_at);",
|
||||||
|
)?;
|
||||||
|
// Added after the first M2 build; default 0 keeps old rows without admin rights.
|
||||||
|
super::ensure_column(conn, "sessions", "admin", "INTEGER NOT NULL DEFAULT 0")?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Db {
|
||||||
|
/// Find or create the user for a stable `(issuer, subject)` identity.
|
||||||
|
pub fn upsert_user(&self, issuer: &str, subject: &str, display_name: &str, now: i64) -> Result<String> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO users(id,issuer,subject,display_name,created_at,last_login_at)
|
||||||
|
VALUES (?1,?2,?3,?4,?5,?5)
|
||||||
|
ON CONFLICT(issuer,subject) DO UPDATE SET display_name=excluded.display_name, last_login_at=excluded.last_login_at",
|
||||||
|
params![Uuid::new_v4().to_string(), issuer, subject, display_name, now],
|
||||||
|
)?;
|
||||||
|
Ok(conn.query_row(
|
||||||
|
"SELECT id FROM users WHERE issuer=?1 AND subject=?2",
|
||||||
|
params![issuer, subject],
|
||||||
|
|row| row.get(0),
|
||||||
|
)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a session for an active user. Returns false when the user is
|
||||||
|
/// missing or inactive. Expired rows are purged opportunistically.
|
||||||
|
pub fn create_session(
|
||||||
|
&self,
|
||||||
|
id: &str,
|
||||||
|
user_id: &str,
|
||||||
|
auth_method: &str,
|
||||||
|
credential_fp: Option<&str>,
|
||||||
|
admin: bool,
|
||||||
|
now: i64,
|
||||||
|
) -> Result<bool> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
conn.execute("DELETE FROM sessions WHERE expires_at <= ?1 OR last_seen + ?2 <= ?1", params![now, IDLE_SECS])?;
|
||||||
|
let inserted = conn.execute(
|
||||||
|
"INSERT INTO sessions(token_digest,user_id,generation,auth_method,credential_fp,auth_time,created_at,last_seen,expires_at,admin)
|
||||||
|
SELECT ?1, id, generation, ?3, ?4, ?5, ?5, ?5, ?6, ?7 FROM users WHERE id=?2 AND active=1",
|
||||||
|
params![session_digest(id), user_id, auth_method, credential_fp, now, now + ABSOLUTE_SECS, admin],
|
||||||
|
)?;
|
||||||
|
Ok(inserted == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validate a session in one statement (user active, generation current,
|
||||||
|
/// absolute and idle deadlines), then slide the idle window. The touch is an
|
||||||
|
/// UPDATE only, so a stale write can never recreate a revoked row.
|
||||||
|
pub fn lookup_session(&self, id: &str, now: i64) -> Result<Option<StoredSession>> {
|
||||||
|
let digest = session_digest(id);
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
let found: Option<(StoredSession, i64)> = conn
|
||||||
|
.query_row(
|
||||||
|
"SELECT s.user_id,u.display_name,s.auth_method,s.credential_fp,s.expires_at,s.last_seen,s.admin
|
||||||
|
FROM sessions s JOIN users u ON u.id=s.user_id
|
||||||
|
WHERE s.token_digest=?1 AND u.active=1 AND s.generation=u.generation
|
||||||
|
AND s.expires_at>?2 AND s.last_seen+?3>?2",
|
||||||
|
params![digest, now, IDLE_SECS],
|
||||||
|
|row| {
|
||||||
|
Ok((
|
||||||
|
StoredSession {
|
||||||
|
user_id: row.get(0)?,
|
||||||
|
display_name: row.get(1)?,
|
||||||
|
auth_method: row.get(2)?,
|
||||||
|
credential_fp: row.get(3)?,
|
||||||
|
expires_at: row.get(4)?,
|
||||||
|
admin: row.get(6)?,
|
||||||
|
},
|
||||||
|
row.get(5)?,
|
||||||
|
))
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.optional()?;
|
||||||
|
let Some((session, last_seen)) = found else { return Ok(None) };
|
||||||
|
if now - last_seen >= TOUCH_AFTER_SECS {
|
||||||
|
conn.execute("UPDATE sessions SET last_seen=?2 WHERE token_digest=?1", params![digest, now])?;
|
||||||
|
}
|
||||||
|
Ok(Some(session))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn revoke_session(&self, id: &str) -> Result<()> {
|
||||||
|
self.conn.lock().unwrap().execute("DELETE FROM sessions WHERE token_digest=?1", params![session_digest(id)])?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Used by the per-user revoke endpoint planned for M5 (admin).
|
||||||
|
#[allow(dead_code)]
|
||||||
|
/// Invalidate every session of a user, including any created concurrently
|
||||||
|
/// from the previous generation. Returns the number of rows removed.
|
||||||
|
pub fn revoke_user_sessions(&self, user_id: &str) -> Result<usize> {
|
||||||
|
let mut conn = self.conn.lock().unwrap();
|
||||||
|
let tx = conn.transaction()?;
|
||||||
|
tx.execute("UPDATE users SET generation=generation+1 WHERE id=?1", params![user_id])?;
|
||||||
|
let removed = tx.execute("DELETE FROM sessions WHERE user_id=?1", params![user_id])?;
|
||||||
|
tx.commit()?;
|
||||||
|
Ok(removed)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub fn expire_all_sessions(&self) {
|
||||||
|
self.conn.lock().unwrap().execute("UPDATE sessions SET expires_at=0", []).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub fn session_rows(&self) -> i64 {
|
||||||
|
self.conn.lock().unwrap().query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0)).unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
async fn db() -> (tempfile::TempDir, Db) {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let db = Db::connect(&dir.path().join("t.db")).await.unwrap();
|
||||||
|
db.migrate().await.unwrap();
|
||||||
|
(dir, db)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn idle_and_absolute_deadlines_use_the_supplied_clock() {
|
||||||
|
let (_dir, db) = db().await;
|
||||||
|
let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap();
|
||||||
|
assert!(db.create_session("a", &user, "password", Some("fp"), true, 1000).unwrap());
|
||||||
|
assert!(db.lookup_session("a", 1000 + IDLE_SECS - 1).unwrap().is_some());
|
||||||
|
// sliding: the touch above moved last_seen, so a request just inside the
|
||||||
|
// new idle window is still fine, one beyond it is not
|
||||||
|
assert!(db.lookup_session("a", 1000 + 2 * IDLE_SECS - 2).unwrap().is_some());
|
||||||
|
assert!(db.lookup_session("a", 1000 + 3 * IDLE_SECS).unwrap().is_none());
|
||||||
|
assert!(db.create_session("b", &user, "password", None, true, 5000).unwrap());
|
||||||
|
let mut now = 5000;
|
||||||
|
while now + IDLE_SECS - 10 < 5000 + ABSOLUTE_SECS {
|
||||||
|
now += IDLE_SECS - 10;
|
||||||
|
assert!(db.lookup_session("b", now).unwrap().is_some(), "active at {now}");
|
||||||
|
}
|
||||||
|
// keeps being used, yet the absolute deadline still ends it
|
||||||
|
assert!(db.lookup_session("b", 5000 + ABSOLUTE_SECS).unwrap().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn only_a_digest_is_stored_and_csrf_is_not_the_key() {
|
||||||
|
let (_dir, db) = db().await;
|
||||||
|
let user = db.upsert_user("local:emergency", "ops", "ops", 1).unwrap();
|
||||||
|
db.create_session("raw-session-id", &user, "password", None, true, 1).unwrap();
|
||||||
|
let conn = db.conn.lock().unwrap();
|
||||||
|
let key: String = conn.query_row("SELECT token_digest FROM sessions", [], |r| r.get(0)).unwrap();
|
||||||
|
assert_ne!(key, "raw-session-id");
|
||||||
|
assert_eq!(key, session_digest("raw-session-id"));
|
||||||
|
assert_ne!(key, csrf_token("raw-session-id"));
|
||||||
|
let stored: String = conn
|
||||||
|
.query_row("SELECT group_concat(token_digest||user_id||auth_method||coalesce(credential_fp,'')) FROM sessions", [], |r| r.get(0))
|
||||||
|
.unwrap();
|
||||||
|
assert!(!stored.contains("raw-session-id"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn revoked_sessions_cannot_be_resurrected_by_a_late_touch() {
|
||||||
|
let (_dir, db) = db().await;
|
||||||
|
let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap();
|
||||||
|
db.create_session("a", &user, "password", None, true, 1000).unwrap();
|
||||||
|
db.revoke_session("a").unwrap();
|
||||||
|
assert!(db.lookup_session("a", 1000 + 2 * TOUCH_AFTER_SECS).unwrap().is_none());
|
||||||
|
assert_eq!(db.session_rows(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn per_user_revoke_ends_all_sessions_and_allows_a_new_login() {
|
||||||
|
let (_dir, db) = db().await;
|
||||||
|
let one = db.upsert_user("https://idp.example", "alice", "Alice", 10).unwrap();
|
||||||
|
let two = db.upsert_user("https://idp.example", "bob", "Bob", 10).unwrap();
|
||||||
|
for id in ["a1", "a2"] {
|
||||||
|
db.create_session(id, &one, "oidc", None, true, 10).unwrap();
|
||||||
|
}
|
||||||
|
db.create_session("b1", &two, "oidc", None, true, 10).unwrap();
|
||||||
|
assert_eq!(db.revoke_user_sessions(&one).unwrap(), 2);
|
||||||
|
assert!(db.lookup_session("a1", 11).unwrap().is_none());
|
||||||
|
assert!(db.lookup_session("a2", 11).unwrap().is_none());
|
||||||
|
assert!(db.lookup_session("b1", 11).unwrap().is_some());
|
||||||
|
assert!(db.create_session("a3", &one, "oidc", None, true, 12).unwrap());
|
||||||
|
assert!(db.lookup_session("a3", 13).unwrap().is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn inactive_users_have_no_valid_or_new_sessions() {
|
||||||
|
let (_dir, db) = db().await;
|
||||||
|
let user = db.upsert_user("https://idp.example", "carol", "Carol", 10).unwrap();
|
||||||
|
db.create_session("c1", &user, "oidc", None, true, 10).unwrap();
|
||||||
|
db.conn.lock().unwrap().execute("UPDATE users SET active=0 WHERE id=?1", params![user]).unwrap();
|
||||||
|
assert!(db.lookup_session("c1", 11).unwrap().is_none());
|
||||||
|
assert!(!db.create_session("c2", &user, "oidc", None, true, 11).unwrap());
|
||||||
|
assert!(!db.create_session("c3", "no-such-user", "oidc", None, true, 11).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn issuer_and_subject_identify_the_user_not_the_display_name() {
|
||||||
|
let (_dir, db) = db().await;
|
||||||
|
let first = db.upsert_user("https://idp.example", "sub-1", "Sam", 1).unwrap();
|
||||||
|
let again = db.upsert_user("https://idp.example", "sub-1", "Samuel", 2).unwrap();
|
||||||
|
let other_subject = db.upsert_user("https://idp.example", "sub-2", "Sam", 3).unwrap();
|
||||||
|
let other_issuer = db.upsert_user("https://other.example", "sub-1", "Sam", 4).unwrap();
|
||||||
|
assert_eq!(first, again);
|
||||||
|
assert_ne!(first, other_subject);
|
||||||
|
assert_ne!(first, other_issuer);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn sessions_survive_reopening_the_database_but_expired_ones_do_not() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join("t.db");
|
||||||
|
{
|
||||||
|
let db = Db::connect(&path).await.unwrap();
|
||||||
|
db.migrate().await.unwrap();
|
||||||
|
let user = db.upsert_user("local:emergency", "ops", "ops", 1000).unwrap();
|
||||||
|
db.create_session("live", &user, "password", Some("fp"), true, 1000).unwrap();
|
||||||
|
db.create_session("old", &user, "password", Some("fp"), true, 1000).unwrap();
|
||||||
|
}
|
||||||
|
let db = Db::connect(&path).await.unwrap();
|
||||||
|
db.migrate().await.unwrap();
|
||||||
|
assert!(db.lookup_session("live", 1000 + 60).unwrap().is_some());
|
||||||
|
assert!(db.lookup_session("old", 1000 + ABSOLUTE_SECS + 1).unwrap().is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ mod auth;
|
|||||||
mod api;
|
mod api;
|
||||||
mod db;
|
mod db;
|
||||||
mod mtls;
|
mod mtls;
|
||||||
|
mod oidc;
|
||||||
mod scheduler;
|
mod scheduler;
|
||||||
mod state;
|
mod state;
|
||||||
mod upload;
|
mod upload;
|
||||||
|
|||||||
466
crates/tessera-hub/src/oidc.rs
Normal file
466
crates/tessera-hub/src/oidc.rs
Normal file
@@ -0,0 +1,466 @@
|
|||||||
|
//! OpenID Connect relying party: authorization code flow with PKCE.
|
||||||
|
//!
|
||||||
|
//! Protocol work (discovery, token exchange, ID-token signature, issuer,
|
||||||
|
//! audience, expiry and nonce checks) is done by the `openidconnect` crate.
|
||||||
|
//! This module owns configuration, key/metadata refresh policy and the mapping
|
||||||
|
//! from verified claims to a Tessera identity. Tokens never leave this module:
|
||||||
|
//! the caller only receives an [`Identity`].
|
||||||
|
use anyhow::{bail, Context, Result};
|
||||||
|
use openidconnect::core::{
|
||||||
|
CoreAuthenticationFlow, CoreClient, CoreProviderMetadata,
|
||||||
|
};
|
||||||
|
use openidconnect::reqwest;
|
||||||
|
use openidconnect::{
|
||||||
|
AccessTokenHash, AuthorizationCode, ClientId, ClientSecret, CsrfToken, EndpointMaybeSet,
|
||||||
|
EndpointNotSet, EndpointSet, IssuerUrl, Nonce, OAuth2TokenResponse, PkceCodeChallenge,
|
||||||
|
PkceCodeVerifier, RedirectUrl, Scope, TokenResponse,
|
||||||
|
};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
use tokio::sync::{Mutex, RwLock};
|
||||||
|
|
||||||
|
pub const CALLBACK_PATH: &str = "/api/v1/auth/oidc/callback";
|
||||||
|
/// How long discovery metadata and signing keys are trusted without a refresh.
|
||||||
|
const METADATA_TTL: Duration = Duration::from_secs(600);
|
||||||
|
/// Minimum gap between refresh attempts, so unknown `kid`s cannot hammer the IdP.
|
||||||
|
const REFRESH_MIN_INTERVAL: Duration = Duration::from_secs(60);
|
||||||
|
|
||||||
|
type Client = CoreClient<
|
||||||
|
EndpointSet,
|
||||||
|
EndpointNotSet,
|
||||||
|
EndpointNotSet,
|
||||||
|
EndpointNotSet,
|
||||||
|
EndpointMaybeSet,
|
||||||
|
EndpointMaybeSet,
|
||||||
|
>;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct OidcConfig {
|
||||||
|
pub issuer: String,
|
||||||
|
pub client_id: String,
|
||||||
|
client_secret: String,
|
||||||
|
pub redirect_url: String,
|
||||||
|
pub admin_subjects: BTreeSet<String>,
|
||||||
|
pub admin_groups: BTreeSet<String>,
|
||||||
|
pub groups_claim: String,
|
||||||
|
pub ca_file: Option<PathBuf>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OidcConfig {
|
||||||
|
/// Read `TESSERA_OIDC_*`. `Ok(None)` when no issuer is configured.
|
||||||
|
/// A plain-http issuer is only accepted for a loopback host while
|
||||||
|
/// `TESSERA_LOCAL_DEVELOPMENT` is on.
|
||||||
|
pub fn from_env(local_development: bool) -> Result<Option<Self>> {
|
||||||
|
let var = |name: &str| std::env::var(name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty());
|
||||||
|
let Some(issuer) = var("TESSERA_OIDC_ISSUER") else { return Ok(None) };
|
||||||
|
let need = |name: &str| var(name).with_context(|| format!("{name} is required when TESSERA_OIDC_ISSUER is set"));
|
||||||
|
let list = |name: &str| -> BTreeSet<String> {
|
||||||
|
var(name).map(|v| v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()).unwrap_or_default()
|
||||||
|
};
|
||||||
|
let config = Self {
|
||||||
|
issuer,
|
||||||
|
client_id: need("TESSERA_OIDC_CLIENT_ID")?,
|
||||||
|
client_secret: need("TESSERA_OIDC_CLIENT_SECRET")?,
|
||||||
|
redirect_url: need("TESSERA_OIDC_REDIRECT_URL")?,
|
||||||
|
admin_subjects: list("TESSERA_OIDC_ADMIN_SUBJECTS"),
|
||||||
|
admin_groups: list("TESSERA_OIDC_ADMIN_GROUPS"),
|
||||||
|
groups_claim: var("TESSERA_OIDC_GROUPS_CLAIM").unwrap_or_else(|| "groups".into()),
|
||||||
|
ca_file: var("TESSERA_OIDC_CA_FILE").map(PathBuf::from),
|
||||||
|
};
|
||||||
|
config.validate(local_development)?;
|
||||||
|
Ok(Some(config))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validate(&self, allow_loopback_http: bool) -> Result<()> {
|
||||||
|
check_url("TESSERA_OIDC_ISSUER", &self.issuer, allow_loopback_http)?;
|
||||||
|
check_url("TESSERA_OIDC_REDIRECT_URL", &self.redirect_url, allow_loopback_http)?;
|
||||||
|
let redirect = url_parts(&self.redirect_url)?;
|
||||||
|
if redirect.path() != CALLBACK_PATH || redirect.query().is_some() || redirect.fragment().is_some() {
|
||||||
|
bail!("TESSERA_OIDC_REDIRECT_URL must end with exactly {CALLBACK_PATH}");
|
||||||
|
}
|
||||||
|
if self.admin_subjects.is_empty() && self.admin_groups.is_empty() {
|
||||||
|
bail!("OIDC needs TESSERA_OIDC_ADMIN_SUBJECTS or TESSERA_OIDC_ADMIN_GROUPS; otherwise nobody could administer the hub");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Test constructor; the secret stays private to this module.
|
||||||
|
#[cfg(test)]
|
||||||
|
pub fn new(issuer: &str, client_id: &str, client_secret: &str, redirect_url: &str) -> Self {
|
||||||
|
Self {
|
||||||
|
issuer: issuer.into(),
|
||||||
|
client_id: client_id.into(),
|
||||||
|
client_secret: client_secret.into(),
|
||||||
|
redirect_url: redirect_url.into(),
|
||||||
|
admin_subjects: BTreeSet::new(),
|
||||||
|
admin_groups: BTreeSet::new(),
|
||||||
|
groups_claim: "groups".into(),
|
||||||
|
ca_file: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Identifies this configuration for session binding. It covers who may
|
||||||
|
/// administer, so removing an admin and restarting demotes their session.
|
||||||
|
/// The client secret is deliberately excluded: rotating it needs no logout.
|
||||||
|
pub fn fingerprint(&self) -> String {
|
||||||
|
let mut hash = Sha256::new();
|
||||||
|
hash.update(b"tessera-oidc-v1");
|
||||||
|
for part in [self.issuer.as_str(), &self.client_id, &self.groups_claim] {
|
||||||
|
hash.update([0]);
|
||||||
|
hash.update(part.as_bytes());
|
||||||
|
}
|
||||||
|
for set in [&self.admin_subjects, &self.admin_groups] {
|
||||||
|
hash.update([1]);
|
||||||
|
for item in set.iter() {
|
||||||
|
hash.update([0]);
|
||||||
|
hash.update(item.as_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hex::encode(hash.finalize())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Admin comes only from configuration matched against verified claims.
|
||||||
|
/// A missing or malformed group claim never grants anything.
|
||||||
|
pub fn is_admin(&self, identity: &Identity) -> bool {
|
||||||
|
self.admin_subjects.contains(&identity.subject)
|
||||||
|
|| identity.groups.iter().any(|group| self.admin_groups.contains(group))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn url_parts(value: &str) -> Result<openidconnect::url::Url> {
|
||||||
|
openidconnect::url::Url::parse(value).with_context(|| format!("invalid URL {value}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_url(name: &str, value: &str, allow_loopback_http: bool) -> Result<()> {
|
||||||
|
let url = url_parts(value).with_context(|| name.to_string())?;
|
||||||
|
match url.scheme() {
|
||||||
|
"https" => Ok(()),
|
||||||
|
"http" if allow_loopback_http
|
||||||
|
&& matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")) => Ok(()),
|
||||||
|
_ => bail!("{name} must be an https:// URL (plain http is only accepted for loopback with TESSERA_LOCAL_DEVELOPMENT)"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A verified identity. Display name is an attribute only, never an identifier.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Identity {
|
||||||
|
pub issuer: String,
|
||||||
|
pub subject: String,
|
||||||
|
pub display_name: String,
|
||||||
|
pub groups: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum OidcError {
|
||||||
|
/// IdP could not be reached and nothing usable is cached.
|
||||||
|
Unavailable,
|
||||||
|
/// The IdP response failed a protocol check.
|
||||||
|
Rejected,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Cached {
|
||||||
|
client: Arc<Client>,
|
||||||
|
fetched_at: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct OidcProvider {
|
||||||
|
pub config: OidcConfig,
|
||||||
|
http: reqwest::Client,
|
||||||
|
cache: RwLock<Option<Cached>>,
|
||||||
|
/// Serialises refreshes; never held while the cache lock is held.
|
||||||
|
refresh: Mutex<Option<Instant>>,
|
||||||
|
min_refresh: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Begin {
|
||||||
|
pub url: String,
|
||||||
|
pub state: String,
|
||||||
|
pub nonce: String,
|
||||||
|
pub verifier: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OidcProvider {
|
||||||
|
pub fn new(config: OidcConfig) -> Result<Self> {
|
||||||
|
let mut builder = reqwest::Client::builder()
|
||||||
|
// Following redirects would turn discovery/JWKS fetches into an SSRF primitive.
|
||||||
|
.redirect(reqwest::redirect::Policy::none())
|
||||||
|
.connect_timeout(Duration::from_secs(5))
|
||||||
|
.timeout(Duration::from_secs(15));
|
||||||
|
if let Some(path) = &config.ca_file {
|
||||||
|
let pem = std::fs::read(path).with_context(|| format!("read {}", path.display()))?;
|
||||||
|
builder = builder.add_root_certificate(reqwest::Certificate::from_pem(&pem).context("TESSERA_OIDC_CA_FILE")?);
|
||||||
|
}
|
||||||
|
Ok(Self {
|
||||||
|
http: builder.build().context("build OIDC HTTP client")?,
|
||||||
|
config,
|
||||||
|
cache: RwLock::new(None),
|
||||||
|
refresh: Mutex::new(None),
|
||||||
|
min_refresh: REFRESH_MIN_INTERVAL,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub fn with_min_refresh(mut self, gap: Duration) -> Self {
|
||||||
|
self.min_refresh = gap;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn discover(&self) -> Result<Client> {
|
||||||
|
let metadata = CoreProviderMetadata::discover_async(IssuerUrl::new(self.config.issuer.clone())?, &self.http).await?;
|
||||||
|
Ok(CoreClient::from_provider_metadata(
|
||||||
|
metadata,
|
||||||
|
ClientId::new(self.config.client_id.clone()),
|
||||||
|
Some(ClientSecret::new(self.config.client_secret.clone())),
|
||||||
|
)
|
||||||
|
.set_redirect_uri(RedirectUrl::new(self.config.redirect_url.clone())?))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cached client, refreshed when stale. On refresh failure a previously
|
||||||
|
/// fetched client keeps working (IdP outage), a missing one is `Unavailable`.
|
||||||
|
/// `force` re-fetches keys for an unknown `kid` but is rate limited.
|
||||||
|
async fn client(&self, force: bool) -> Result<Arc<Client>, OidcError> {
|
||||||
|
let current = {
|
||||||
|
let guard = self.cache.read().await;
|
||||||
|
guard.as_ref().map(|c| (c.client.clone(), c.fetched_at))
|
||||||
|
};
|
||||||
|
let fresh = |at: Instant| at.elapsed() < METADATA_TTL;
|
||||||
|
if let Some((client, at)) = ¤t {
|
||||||
|
if fresh(*at) && !force {
|
||||||
|
return Ok(client.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut last_attempt = self.refresh.lock().await;
|
||||||
|
// Someone else may have refreshed while we waited for the lock.
|
||||||
|
let cached = self.cache.read().await.as_ref().map(|c| (c.client.clone(), c.fetched_at));
|
||||||
|
if let Some((client, at)) = &cached {
|
||||||
|
if fresh(*at) && !force {
|
||||||
|
return Ok(client.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Without any cached client, retry sooner so recovery after an outage is quick.
|
||||||
|
let gap = if cached.is_some() { self.min_refresh } else { self.min_refresh.min(Duration::from_secs(5)) };
|
||||||
|
if last_attempt.is_some_and(|t| t.elapsed() < gap) {
|
||||||
|
return cached.map(|(c, _)| c).ok_or(OidcError::Unavailable);
|
||||||
|
}
|
||||||
|
*last_attempt = Some(Instant::now());
|
||||||
|
match self.discover().await {
|
||||||
|
Ok(client) => {
|
||||||
|
let client = Arc::new(client);
|
||||||
|
*self.cache.write().await = Some(Cached { client: client.clone(), fetched_at: Instant::now() });
|
||||||
|
Ok(client)
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
tracing::warn!("OIDC discovery failed: {error:#}");
|
||||||
|
current.map(|(c, _)| c).ok_or(OidcError::Unavailable)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build the authorization redirect. The caller stores `state`, `nonce` and
|
||||||
|
/// `verifier` as a one-time login transaction bound to the browser.
|
||||||
|
pub async fn begin(&self) -> Result<Begin, OidcError> {
|
||||||
|
let client = self.client(false).await?;
|
||||||
|
let (challenge, verifier) = PkceCodeChallenge::new_random_sha256();
|
||||||
|
let (url, state, nonce) = client
|
||||||
|
.authorize_url(CoreAuthenticationFlow::AuthorizationCode, CsrfToken::new_random, Nonce::new_random)
|
||||||
|
.add_scope(Scope::new("profile".into()))
|
||||||
|
.set_pkce_challenge(challenge)
|
||||||
|
.url();
|
||||||
|
Ok(Begin {
|
||||||
|
url: url.to_string(),
|
||||||
|
state: state.secret().clone(),
|
||||||
|
nonce: nonce.secret().clone(),
|
||||||
|
verifier: verifier.secret().clone(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Exchange the code and verify the ID token. Details go to the log; the
|
||||||
|
/// caller only sees `Unavailable` or `Rejected`.
|
||||||
|
pub async fn finish(&self, code: &str, nonce: &str, verifier: &str) -> Result<Identity, OidcError> {
|
||||||
|
let client = self.client(false).await?;
|
||||||
|
let response = client
|
||||||
|
.exchange_code(AuthorizationCode::new(code.to_string()))
|
||||||
|
.map_err(|_| OidcError::Unavailable)?
|
||||||
|
.set_pkce_verifier(PkceCodeVerifier::new(verifier.to_string()))
|
||||||
|
.request_async(&self.http)
|
||||||
|
.await
|
||||||
|
.map_err(|error| {
|
||||||
|
tracing::warn!("OIDC token exchange failed: {error}");
|
||||||
|
match error {
|
||||||
|
openidconnect::RequestTokenError::Request(_) => OidcError::Unavailable,
|
||||||
|
_ => OidcError::Rejected,
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
let id_token = response.id_token().ok_or_else(|| {
|
||||||
|
tracing::warn!("OIDC token response has no ID token");
|
||||||
|
OidcError::Rejected
|
||||||
|
})?;
|
||||||
|
let nonce = Nonce::new(nonce.to_string());
|
||||||
|
let mut client = client;
|
||||||
|
for attempt in 0..2 {
|
||||||
|
match verify(&client, id_token, response.access_token(), &nonce, &self.config.groups_claim) {
|
||||||
|
Ok(identity) => return Ok(identity),
|
||||||
|
// Keys may have rotated since the last fetch: refresh once and retry.
|
||||||
|
Err(Verify::Signature) if attempt == 0 => client = self.client(true).await?,
|
||||||
|
Err(_) => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(OidcError::Rejected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Verify {
|
||||||
|
Signature,
|
||||||
|
Other,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All checks on one ID token: signature, issuer, audience, expiry and nonce
|
||||||
|
/// (library), access-token hash, then mapping to an owned [`Identity`].
|
||||||
|
fn verify(
|
||||||
|
client: &Client,
|
||||||
|
id_token: &openidconnect::core::CoreIdToken,
|
||||||
|
access_token: &openidconnect::AccessToken,
|
||||||
|
nonce: &Nonce,
|
||||||
|
groups_claim: &str,
|
||||||
|
) -> Result<Identity, Verify> {
|
||||||
|
let verifier = client.id_token_verifier();
|
||||||
|
let claims = id_token.claims(&verifier, nonce).map_err(|error| {
|
||||||
|
tracing::warn!("OIDC ID token rejected: {error}");
|
||||||
|
if matches!(error, openidconnect::ClaimsVerificationError::SignatureVerification(_)) {
|
||||||
|
Verify::Signature
|
||||||
|
} else {
|
||||||
|
Verify::Other
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
if let Some(expected) = claims.access_token_hash() {
|
||||||
|
let actual = id_token
|
||||||
|
.signing_alg()
|
||||||
|
.ok()
|
||||||
|
.and_then(|alg| id_token.signing_key(&verifier).ok().map(|key| (alg, key)))
|
||||||
|
.and_then(|(alg, key)| AccessTokenHash::from_token(access_token, alg, key).ok());
|
||||||
|
if actual.as_ref() != Some(expected) {
|
||||||
|
tracing::warn!("OIDC access token hash mismatch");
|
||||||
|
return Err(Verify::Other);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let subject = claims.subject().as_str().to_string();
|
||||||
|
if subject.is_empty() || subject.len() > 255 {
|
||||||
|
tracing::warn!("OIDC ID token has an unusable subject");
|
||||||
|
return Err(Verify::Other);
|
||||||
|
}
|
||||||
|
let display_name = claims
|
||||||
|
.preferred_username()
|
||||||
|
.map(|n| n.as_str().to_string())
|
||||||
|
.or_else(|| claims.name().and_then(|n| n.get(None)).map(|n| n.as_str().to_string()))
|
||||||
|
.unwrap_or_else(|| subject.clone())
|
||||||
|
.chars()
|
||||||
|
.take(128)
|
||||||
|
.collect();
|
||||||
|
// The signature was verified by `claims()` above, so reading one more
|
||||||
|
// claim from the same token is safe. Missing or malformed means no groups.
|
||||||
|
let groups = groups_from_token(&id_token.to_string(), groups_claim);
|
||||||
|
Ok(Identity { issuer: claims.issuer().as_str().to_string(), subject, display_name, groups })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn groups_from_token(jwt: &str, claim: &str) -> Vec<String> {
|
||||||
|
use base64::Engine;
|
||||||
|
let Some(payload) = jwt.split('.').nth(1) else { return vec![] };
|
||||||
|
let Ok(bytes) = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload) else { return vec![] };
|
||||||
|
let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) else { return vec![] };
|
||||||
|
match value.get(claim) {
|
||||||
|
Some(serde_json::Value::String(one)) => vec![one.clone()],
|
||||||
|
Some(serde_json::Value::Array(items)) => {
|
||||||
|
items.iter().filter_map(|item| item.as_str().map(str::to_string)).collect()
|
||||||
|
}
|
||||||
|
_ => vec![],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn config() -> OidcConfig {
|
||||||
|
let mut config = OidcConfig::new("https://idp.example/realm", "tessera", "secret", "https://hub.example/api/v1/auth/oidc/callback");
|
||||||
|
config.admin_subjects.insert("admin-sub".into());
|
||||||
|
config
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn http_issuers_are_rejected_unless_loopback_in_local_development() {
|
||||||
|
let mut c = config();
|
||||||
|
assert!(c.validate(false).is_ok());
|
||||||
|
c.issuer = "http://idp.example".into();
|
||||||
|
assert!(c.validate(false).is_err());
|
||||||
|
assert!(c.validate(true).is_err(), "non-loopback http stays rejected");
|
||||||
|
c.issuer = "http://localhost:8080/realms/t".into();
|
||||||
|
assert!(c.validate(false).is_err());
|
||||||
|
assert!(c.validate(true).is_ok(), "loopback http issuer in local development");
|
||||||
|
c.redirect_url = "http://hub.example/api/v1/auth/oidc/callback".into();
|
||||||
|
assert!(c.validate(true).is_err(), "non-loopback http redirect stays rejected");
|
||||||
|
c.redirect_url = "http://localhost:8787/api/v1/auth/oidc/callback".into();
|
||||||
|
assert!(c.validate(true).is_ok());
|
||||||
|
assert!(c.validate(false).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn redirect_url_must_be_the_exact_callback_and_an_admin_mapping_is_required() {
|
||||||
|
let mut c = config();
|
||||||
|
c.redirect_url = "https://hub.example/other".into();
|
||||||
|
assert!(c.validate(false).is_err());
|
||||||
|
c.redirect_url = "https://hub.example/api/v1/auth/oidc/callback?x=1".into();
|
||||||
|
assert!(c.validate(false).is_err());
|
||||||
|
let mut c = config();
|
||||||
|
c.admin_subjects.clear();
|
||||||
|
assert!(c.validate(false).is_err(), "no way to administer");
|
||||||
|
c.admin_groups.insert("tessera-admins".into());
|
||||||
|
assert!(c.validate(false).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn admin_mapping_uses_subject_or_verified_group_only() {
|
||||||
|
let mut c = config();
|
||||||
|
c.admin_groups.insert("tessera-admins".into());
|
||||||
|
let id = |sub: &str, groups: &[&str]| Identity {
|
||||||
|
issuer: "i".into(),
|
||||||
|
subject: sub.into(),
|
||||||
|
display_name: "operator".into(),
|
||||||
|
groups: groups.iter().map(|g| g.to_string()).collect(),
|
||||||
|
};
|
||||||
|
assert!(c.is_admin(&id("admin-sub", &[])));
|
||||||
|
assert!(c.is_admin(&id("someone", &["tessera-admins"])));
|
||||||
|
assert!(!c.is_admin(&id("someone", &["other"])));
|
||||||
|
assert!(!c.is_admin(&id("someone", &[])), "missing groups claim grants nothing");
|
||||||
|
assert!(!c.is_admin(&id("operator", &[])), "display name is not an identifier");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fingerprint_changes_with_the_admin_mapping_but_not_the_client_secret() {
|
||||||
|
let base = config();
|
||||||
|
let mut rotated = config();
|
||||||
|
rotated.client_secret = "new-secret".into();
|
||||||
|
assert_eq!(base.fingerprint(), rotated.fingerprint());
|
||||||
|
let mut demoted = config();
|
||||||
|
demoted.admin_subjects.clear();
|
||||||
|
demoted.admin_subjects.insert("someone-else".into());
|
||||||
|
assert_ne!(base.fingerprint(), demoted.fingerprint());
|
||||||
|
let mut renamed = config();
|
||||||
|
renamed.groups_claim = "roles".into();
|
||||||
|
assert_ne!(base.fingerprint(), renamed.fingerprint());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn groups_accept_a_string_or_array_and_ignore_anything_else() {
|
||||||
|
use base64::Engine;
|
||||||
|
let jwt = |json: &str| format!("h.{}.s", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json));
|
||||||
|
assert_eq!(groups_from_token(&jwt(r#"{"groups":["a","b"]}"#), "groups"), ["a", "b"]);
|
||||||
|
assert_eq!(groups_from_token(&jwt(r#"{"groups":"solo"}"#), "groups"), ["solo"]);
|
||||||
|
assert!(groups_from_token(&jwt(r#"{"groups":{"a":1}}"#), "groups").is_empty());
|
||||||
|
assert!(groups_from_token(&jwt(r#"{"groups":[1,null]}"#), "groups").is_empty());
|
||||||
|
assert!(groups_from_token(&jwt(r#"{"other":["a"]}"#), "groups").is_empty());
|
||||||
|
assert!(groups_from_token("not-a-jwt", "groups").is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -40,6 +40,7 @@ pub struct HubState {
|
|||||||
pub active_orbits: Arc<Mutex<HashSet<Uuid>>>,
|
pub active_orbits: Arc<Mutex<HashSet<Uuid>>>,
|
||||||
pub admin: AdminGate,
|
pub admin: AdminGate,
|
||||||
pub sessions: SessionGate,
|
pub sessions: SessionGate,
|
||||||
|
pub oidc: Option<std::sync::Arc<crate::oidc::OidcProvider>>,
|
||||||
pub wormhole_mtls: bool,
|
pub wormhole_mtls: bool,
|
||||||
/// Token uploads are accepted on this listener. Plain HTTP turns this off
|
/// Token uploads are accepted on this listener. Plain HTTP turns this off
|
||||||
/// when wormhole mTLS is required, so those routes are not a bypass.
|
/// when wormhole mTLS is required, so those routes are not a bypass.
|
||||||
@@ -61,15 +62,18 @@ impl HubState {
|
|||||||
Vault::init(&vault_path, vault_pass)?
|
Vault::init(&vault_path, vault_pass)?
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let admin = AdminGate::from_env()?;
|
||||||
|
let oidc_config = crate::oidc::OidcConfig::from_env(admin.local_development)?;
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
db,
|
db: db.clone(),
|
||||||
data_dir,
|
data_dir,
|
||||||
offsite: None,
|
offsite: None,
|
||||||
vault: Arc::new(RwLock::new(vault)),
|
vault: Arc::new(RwLock::new(vault)),
|
||||||
reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())),
|
reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())),
|
||||||
active_orbits: Arc::new(Mutex::new(HashSet::new())),
|
active_orbits: Arc::new(Mutex::new(HashSet::new())),
|
||||||
admin: AdminGate::from_env()?,
|
admin,
|
||||||
sessions: SessionGate::from_env()?,
|
sessions: SessionGate::from_env(db.clone(), oidc_config.as_ref().map(|c| c.fingerprint()))?,
|
||||||
|
oidc: oidc_config.map(|c| crate::oidc::OidcProvider::new(c).map(Arc::new)).transpose()?,
|
||||||
wormhole_mtls: false,
|
wormhole_mtls: false,
|
||||||
accept_plain_upload: true,
|
accept_plain_upload: true,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -6,6 +6,9 @@ all-features = false
|
|||||||
version = 2
|
version = 2
|
||||||
# Unmaintained warnings are tracked, not ignored silently; see tasks/auth-plan.md (M1).
|
# Unmaintained warnings are tracked, not ignored silently; see tasks/auth-plan.md (M1).
|
||||||
unmaintained = "workspace"
|
unmaintained = "workspace"
|
||||||
|
ignore = [
|
||||||
|
{ id = "RUSTSEC-2023-0071", reason = "Marvin attack concerns RSA private-key operations. Tessera only verifies ID-token signatures with public keys (openidconnect core/crypto.rs); runtime code never calls an RSA private-key operation; only test fixtures sign tokens with throwaway keys. No patched rsa 0.9 exists. Revisit when openidconnect moves to rsa >= 0.10." },
|
||||||
|
]
|
||||||
|
|
||||||
[licenses]
|
[licenses]
|
||||||
version = 2
|
version = 2
|
||||||
@@ -13,6 +16,7 @@ allow = [
|
|||||||
"MIT", "MIT-0", "Apache-2.0", "Apache-2.0 WITH LLVM-exception", "ISC",
|
"MIT", "MIT-0", "Apache-2.0", "Apache-2.0 WITH LLVM-exception", "ISC",
|
||||||
"BSD-2-Clause", "BSD-3-Clause", "Unicode-3.0", "Zlib", "CC0-1.0",
|
"BSD-2-Clause", "BSD-3-Clause", "Unicode-3.0", "Zlib", "CC0-1.0",
|
||||||
"BSL-1.0", "Unlicense",
|
"BSL-1.0", "Unlicense",
|
||||||
|
"CDLA-Permissive-2.0", # webpki-roots: Mozilla CA data
|
||||||
"AGPL-3.0-or-later", # Tessera's own crates
|
"AGPL-3.0-or-later", # Tessera's own crates
|
||||||
]
|
]
|
||||||
confidence-threshold = 0.9
|
confidence-threshold = 0.9
|
||||||
|
|||||||
@@ -173,3 +173,43 @@ tessera legacy-import --bucket legacy-bucket --prefix billing/ --orbit-id ORBIT_
|
|||||||
Repeat without `--inventory-only` to import. The JSON report includes the source key, ETag, size, last-modified timestamp, and Tessera snapshot ID. Conditional reads reject changed objects between listing and download. A persistent receipt prevents reimport after local retention and GC. [AWS S3 CLI inventory](https://docs.aws.amazon.com/cli/latest/reference/s3api/list-objects-v2.html), [AWS S3 conditional download](https://docs.aws.amazon.com/cli/latest/reference/s3api/get-object.html).
|
Repeat without `--inventory-only` to import. The JSON report includes the source key, ETag, size, last-modified timestamp, and Tessera snapshot ID. Conditional reads reject changed objects between listing and download. A persistent receipt prevents reimport after local retention and GC. [AWS S3 CLI inventory](https://docs.aws.amazon.com/cli/latest/reference/s3api/list-objects-v2.html), [AWS S3 conditional download](https://docs.aws.amazon.com/cli/latest/reference/s3api/get-object.html).
|
||||||
|
|
||||||
Add `--history /path/to/consistent-history.sqlite` to archive a consistent SQLite export of the old job history. Save the reported history ID and retrieve it with `tessera legacy-history HISTORY_UUID history.sqlite` on the vault host. Inspect the retrieved copy read-only. Legacy SQL archives retain their original bytes and can be applied to a temporary database with the matching engine client.
|
Add `--history /path/to/consistent-history.sqlite` to archive a consistent SQLite export of the old job history. Save the reported history ID and retrieve it with `tessera legacy-history HISTORY_UUID history.sqlite` on the vault host. Inspect the retrieved copy read-only. Legacy SQL archives retain their original bytes and can be applied to a temporary database with the matching engine client.
|
||||||
|
|
||||||
|
## OIDC sign-in (single issuer)
|
||||||
|
|
||||||
|
Set `TESSERA_OIDC_ISSUER` to enable browser SSO (authorization code + PKCE S256,
|
||||||
|
Tessera is a confidential client). When it is set, these are also required:
|
||||||
|
|
||||||
|
| Variable | Meaning |
|
||||||
|
| --- | --- |
|
||||||
|
| `TESSERA_OIDC_CLIENT_ID`, `TESSERA_OIDC_CLIENT_SECRET` | Client registered at the IdP. The secret is only read from the environment and never logged. |
|
||||||
|
| `TESSERA_OIDC_REDIRECT_URL` | Public, static callback, exactly `https://<hub>/api/v1/auth/oidc/callback`. It is never derived from `Host` or `X-Forwarded-*`. |
|
||||||
|
| `TESSERA_OIDC_ADMIN_SUBJECTS` | Comma-separated `sub` values that may administer the hub. |
|
||||||
|
| `TESSERA_OIDC_ADMIN_GROUPS` | Comma-separated group names that may administer the hub. |
|
||||||
|
| `TESSERA_OIDC_GROUPS_CLAIM` | ID-token claim that carries groups (default `groups`; string or array of strings). |
|
||||||
|
| `TESSERA_OIDC_CA_FILE` | Optional PEM bundle for an IdP behind a private CA. |
|
||||||
|
|
||||||
|
At least one admin subject or group is mandatory, otherwise startup fails: with
|
||||||
|
no mapping nobody could administer the hub. Issuer and redirect URL must be
|
||||||
|
`https://`; plain http is accepted only for a loopback host together with
|
||||||
|
`TESSERA_LOCAL_DEVELOPMENT=true`.
|
||||||
|
|
||||||
|
Behaviour to know about:
|
||||||
|
|
||||||
|
- Users are identified by `(issuer, subject)`, never by email or display name.
|
||||||
|
There is no auto-link by email and no first-user-becomes-admin.
|
||||||
|
- A user who signs in but matches no admin mapping gets a "No access yet" page and
|
||||||
|
`403` on every management API. They can still call `GET /api/v1/me` and sign out.
|
||||||
|
- Group membership is read at sign-in. A change at the IdP applies at the next
|
||||||
|
sign-in, at most 8 hours later (absolute session limit); there is no back-channel
|
||||||
|
logout or SCIM yet.
|
||||||
|
- Changing the issuer, client ID, admin subjects/groups or groups claim ends every
|
||||||
|
existing OIDC session. Rotating the client secret does not.
|
||||||
|
- Sign-out ends the Tessera session only. The IdP session stays, so the next
|
||||||
|
"Sign in with SSO" may not ask for a password. RP-initiated logout is not implemented.
|
||||||
|
- ID tokens must be signed with RS256 (the library default). An IdP that signs
|
||||||
|
with another algorithm is rejected until that is made configurable.
|
||||||
|
- The emergency operator password keeps working beside SSO and is shown under
|
||||||
|
"Emergency operator sign-in" when SSO is on.
|
||||||
|
- No IdP token is stored or sent to the browser; the browser only receives the
|
||||||
|
Tessera session cookie.
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,9 @@ admin/browser. Semua status/data job hanya di scope owner/admin yang berizin.
|
|||||||
| /api-doc/openapi.json | GET | public | — | — | schema tanpa config/secret |
|
| /api-doc/openapi.json | GET | public | — | — | schema tanpa config/secret |
|
||||||
| /api/v1/operator/session | GET | public | — | current session | status, actor, CSRF sesi sendiri; no-store |
|
| /api/v1/operator/session | GET | public | — | current session | status, actor, CSRF sesi sendiri; no-store |
|
||||||
| /api/v1/operator/session | DELETE | human | session.self | current session | tidak ada; CSRF wajib |
|
| /api/v1/operator/session | DELETE | human | session.self | current session | tidak ada; CSRF wajib |
|
||||||
|
| /api/v1/me | GET | human | session.self | current principal | id, kind, auth method, display name, capabilities; no-store |
|
||||||
|
| /api/v1/auth/oidc/login | GET | public | — | OIDC configured | redirect to the IdP; sets one-time Lax correlation cookie; 404 when OIDC is off |
|
||||||
|
| /api/v1/auth/oidc/callback | GET | public | — | login transaction + correlation cookie | redirect to `/`; session cookie only on success, fixed error code otherwise; no tokens |
|
||||||
| /api/v1/operator/login | POST | public | — | emergency account | cookie opaque dan CSRF; limiter, no-store |
|
| /api/v1/operator/login | POST | public | — | emergency account | cookie opaque dan CSRF; limiter, no-store |
|
||||||
| /api/v1/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter |
|
| /api/v1/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter |
|
||||||
| /api/v1/snapshots/:id | DELETE | human | snapshot.delete | snapshot→orbit | tidak ada; cek pin |
|
| /api/v1/snapshots/:id | DELETE | human | snapshot.delete | snapshot→orbit | tidak ada; cek pin |
|
||||||
|
|||||||
@@ -24,25 +24,30 @@ Bukti: `cargo test --workspace` hijau (jumlah tes sama dengan sebelum upgrade),
|
|||||||
Belum terbukti: build image Docker `rust:1.89`, dan tes Restic ignored. Belum ada CI di repo, jadi gate ini baru jalan manual (`cargo audit`, `cargo deny check`).
|
Belum terbukti: build image Docker `rust:1.89`, dan tes Restic ignored. Belum ada CI di repo, jadi gate ini baru jalan manual (`cargo audit`, `cargo deny check`).
|
||||||
Sisa catatan: `rsa` 0.9 (RUSTSEC-2023-0071) baru muncul saat `openidconnect` masuk di M3; dikecualikan dengan alasan reachability di sana, bukan sekarang.
|
Sisa catatan: `rsa` 0.9 (RUSTSEC-2023-0071) baru muncul saat `openidconnect` masuk di M3; dikecualikan dengan alasan reachability di sana, bukan sekarang.
|
||||||
|
|
||||||
## M2 — User dan sesi persisten
|
## M2 — User dan sesi persisten (selesai di working tree, belum di-commit, 14 November 2026)
|
||||||
|
|
||||||
Hasil: identitas per orang dan sesi yang bertahan setelah restart.
|
Hasil: identitas per orang dan sesi yang bertahan setelah restart.
|
||||||
- Tabel `users` (UNIQUE issuer+subject, status aktif) dan `sessions` (digest ID, user, CSRF, created/last_seen/expires, auth_time, auth method, revocation generation).
|
- Tabel `users` (UNIQUE issuer+subject, `active`, `generation`) dan `sessions` (digest SHA-256 dari ID, user, generation, auth method, credential fingerprint, auth_time, last_seen, expires_at) di `db/sessions.rs`. Store sendiri di rusqlite, bukan `tower-sessions`.
|
||||||
- Store sesi sendiri di rusqlite, bukan `tower-sessions`: UPDATE-only save, key digest, idle 30 menit dan absolute 8 jam, revoke per sesi dan per user, rotasi ID saat login. Alasan: adapter yang aman sudah meniru hampir semua logika library, dan library membawa `axum-core` ganda.
|
- Validasi sesi satu statement: user aktif, generation cocok, absolute 8 jam, idle 30 menit; geser idle lewat UPDATE-only (tidak bisa menghidupkan baris yang sudah dicabut). Revoke per user menaikkan generation dan menghapus baris dalam satu transaksi. Foreign key SQLite tidak aktif di koneksi ini, jadi tidak diandalkan.
|
||||||
- Ganti `SessionGate` in-memory. Akun darurat (password) tetap login lewat jalur yang sama sebagai principal `Emergency`.
|
- Akun darurat adalah baris user dengan issuer `local:emergency` (bukan URL, tidak bisa ditabrak issuer OIDC). Sesi password terikat ke fingerprint hash operator: hash dilepas atau diganti saat restart membuat cookie lama mati. Ini menjaga perilaku lama (restart memutus sesi) sekarang sesi persisten.
|
||||||
- `GET /me` mengembalikan identitas dan capabilities aman.
|
- CSRF diturunkan dari ID sesi dengan prefix berbeda dari digest penyimpanan, jadi tidak perlu disimpan dan tidak bisa dipakai sebagai kunci.
|
||||||
Selesai bila: tes fake clock (idle/absolute), session fixation, CSRF, revoke saat request konkuren tidak menghidupkan sesi lagi, restart mempertahankan sesi valid dan menolak yang kedaluwarsa.
|
- `authorize_operator` melakukan satu lookup sesi per request (sebelumnya dua).
|
||||||
|
- `GET /api/v1/me` (identitas, kind, auth method, nama, capabilities; no-store) masuk kontrak endpoint. `GET /operator/session` kini juga mengembalikan `expires_at`.
|
||||||
|
Bukti: `cargo test --workspace` hijau (hub 33 tes, naik dari 21: deadline dengan clock injeksi, hanya digest tersimpan, touch setelah revoke, revoke per user lalu login ulang, user nonaktif, restart/reopen DB, hash diganti/dilepas, fixation, `/me`); `cargo audit` 0 vulnerability, `cargo deny` ok. Proses nyata: login, restart dengan hash sama → 200, hash diganti → 401, hash dilepas → cookie tidak dianggap sesi, hash asli lagi → sesi pulih.
|
||||||
|
Belum ada: endpoint HTTP revoke per user dan nonaktifkan user (fungsi store `revoke_user_sessions` sudah ada dan dites; endpoint admin menunggu M5), pembersihan sesi kedaluwarsa hanya terjadi saat ada login baru, dan limiter login masih in-memory (M4).
|
||||||
|
|
||||||
## M3 — Login OIDC
|
## M3 — Login OIDC (selesai di working tree, belum di-commit, 14 November 2026)
|
||||||
|
|
||||||
Hasil: SSO berfungsi; ini inti permintaan.
|
Hasil: SSO berfungsi sebagai login utama; akun darurat tetap ada.
|
||||||
- `openidconnect` 4.x, confidential client, Authorization Code + PKCE S256, redirect URI statis dari config, redirect HTTP dimatikan untuk discovery/token/JWKS.
|
- `openidconnect` 4.1 (reqwest + rustls), confidential client, code + PKCE S256, redirect URI statis, redirect HTTP dimatikan, timeout connect 5 detik dan total 15 detik. Konfigurasi `TESSERA_OIDC_*` divalidasi saat startup (https wajib, http hanya loopback + local development, mapping admin wajib). Dokumentasi ada di `docs/DATABASE-CAPTURE.md`.
|
||||||
- Transaksi login singkat, sekali pakai, terikat cookie korelasi SameSite=Lax terpisah. Validasi state, nonce, iss, aud, exp, alg allowlist; JWKS di-cache dengan refresh terbatas.
|
- Transaksi login satu kali pakai (digest state dan cookie korelasi SameSite=Lax terpisah, TTL 10 menit, maksimal 500 baris). Percobaan apa pun, termasuk dari browser tanpa cookie, menghanguskan transaksi.
|
||||||
- User dibuat/dicocokkan lewat (issuer, subject), tanpa auto-link email, tanpa auto-admin. User baru tanpa grant mendapat halaman "belum punya akses".
|
- Verifikasi ID token oleh library: signature RS256, iss, aud (audiens lain ditolak), azp, exp, nonce, access-token hash. Metadata dan JWKS di-cache 10 menit; saat IdP mati cache lama tetap dipakai; kegagalan signature memicu satu refresh (dibatasi 60 detik) lalu coba ulang.
|
||||||
- Admin ditentukan config eksplisit: daftar subject atau satu claim grup. Claim grup hilang tidak menambah hak.
|
- Identitas (issuer, subject) tanpa auto-link email. Admin hanya dari config (subject atau grup di claim terverifikasi; claim hilang atau salah bentuk tidak memberi apa pun). User tanpa grant mendapat sesi tapi `403` di semua API manajemen; `/me`, status sesi, dan logout tetap jalan. Principal audit `oidc:<users.id>`, tidak pernah dari nama IdP.
|
||||||
- Endpoint: `/auth/oidc/login`, `/auth/oidc/callback`, logout lokal (+ RP-initiated logout bila IdP mendukung).
|
- Sesi OIDC terikat ke fingerprint config (issuer, client, mapping admin): mengubah mapping atau mematikan OIDC mengakhiri sesi.
|
||||||
- UI: tombol SSO di `OperatorGate`, login darurat dipisah, halaman tanpa akses.
|
- UI: tombol "Sign in with SSO", form password darurat dipisah, halaman "No access yet", pesan error dari kode tetap (`auth_error`).
|
||||||
Selesai bila: tes wiremock untuk signature/alg/iss/aud/nonce/state salah, replay callback, token kedaluwarsa, JWKS rotasi dan outage; satu lari nyata dengan Keycloak fixture lewat browser (cookie lintas situs, logout, user tanpa grant).
|
Bukti: `cargo test --workspace` hijau (hub 51 tes, stabil 5/5 run). Tes end-to-end dengan IdP palsu dan token yang ditandatangani kunci RSA uji: admin lewat subject dan grup, user tanpa grant, claim grup rusak, email sama subject beda, nonce/issuer/audience/azp/expired/signature penyerang/alg none/HS256 salah, replay/cookie salah/state palsu/transaksi kedaluwarsa, rotasi JWKS dan pembatasan refresh, IdP mati (cold dan warm), OIDC nonaktif → 404. `cargo audit` hanya warning `proc-macro-error`; `rsa` dikecualikan dengan alasan tertulis (`deny.toml`, `.cargo/audit.toml`). Rehearsal nyata: Keycloak 26.1 di Docker + hub nyata + browser: login Alice (grup admin) → UI terbuka, `/me` oidc admin; Bob → "No access yet", `/orbits` 403; logout lokal; pesan error callback palsu. Cookie `__Host-` Secure bekerja di `http://localhost`. DB dan log tidak memuat token, secret, atau password.
|
||||||
|
Belum ada / batas: RP-initiated logout dan back-channel logout (logout hanya mengakhiri sesi Tessera, sesi IdP tetap), re-auth dan `max_age` untuk akses sensitif, ES256/PS256 (hanya RS256), limiter pada `/login` dan `/callback` (M4; yang ada hanya batas 500 transaksi pending), revokasi perubahan grup IdP hanya saat sign-in berikutnya (maksimal 8 jam), uji dengan IdP organisasi target, uji logout/MFA di IdP target.
|
||||||
|
Catatan operasional: image Keycloak 26.1 tertinggal di Docker lokal (~500 MB), container sudah dihapus.
|
||||||
|
|
||||||
## M4 — Hardening kredensial
|
## M4 — Hardening kredensial
|
||||||
|
|
||||||
|
|||||||
@@ -52,9 +52,11 @@ export type CreateOrbitInput = {
|
|||||||
|
|
||||||
export type OperatorSession = {
|
export type OperatorSession = {
|
||||||
login_enabled: boolean;
|
login_enabled: boolean;
|
||||||
|
oidc_enabled: boolean;
|
||||||
authorized: boolean;
|
authorized: boolean;
|
||||||
actor: string | null;
|
actor: string | null;
|
||||||
csrf: string | null;
|
csrf: string | null;
|
||||||
|
expires_at: number | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
let csrf: string | null = null;
|
let csrf: string | null = null;
|
||||||
|
|||||||
@@ -1,8 +1,25 @@
|
|||||||
import { useState, type FormEvent, type ReactNode } from "react";
|
import { useEffect, useState, type FormEvent, type ReactNode } from "react";
|
||||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { fetchOperatorSession, loginOperator, logoutOperator } from "../../api";
|
import { fetchOperatorSession, loginOperator, logoutOperator } from "../../api";
|
||||||
import { Button } from "../ui/Button";
|
import { Button } from "../ui/Button";
|
||||||
|
|
||||||
|
const SSO_ERRORS: Record<string, string> = {
|
||||||
|
invalid_state: "That sign-in expired or was started in another browser. Please try again.",
|
||||||
|
denied: "The identity provider declined the sign-in.",
|
||||||
|
unavailable: "The identity provider is unreachable. Try again shortly.",
|
||||||
|
disabled: "This account is disabled.",
|
||||||
|
failed: "Sign-in could not be completed. Ask an administrator if it keeps happening.",
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Read the fixed error code the SSO callback leaves in the URL, then remove it. */
|
||||||
|
function useSsoError() {
|
||||||
|
const [code] = useState(() => new URLSearchParams(window.location.search).get("auth_error"));
|
||||||
|
useEffect(() => {
|
||||||
|
if (code) window.history.replaceState(null, "", window.location.pathname);
|
||||||
|
}, [code]);
|
||||||
|
return code ? SSO_ERRORS[code] ?? SSO_ERRORS.failed : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
export function OperatorGate({
|
export function OperatorGate({
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
@@ -17,6 +34,7 @@ export function OperatorGate({
|
|||||||
});
|
});
|
||||||
const [pending, setPending] = useState(false);
|
const [pending, setPending] = useState(false);
|
||||||
const [error, setError] = useState<string>();
|
const [error, setError] = useState<string>();
|
||||||
|
const ssoError = useSsoError();
|
||||||
|
|
||||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -37,34 +55,57 @@ export function OperatorGate({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (session.isSuccess && session.data.authorized) {
|
async function signOut() {
|
||||||
const actor = session.data.actor ?? undefined;
|
if (!session.isSuccess) return;
|
||||||
return children({
|
|
||||||
actor,
|
|
||||||
onLogout: actor ? async () => {
|
|
||||||
await queryClient.cancelQueries({ queryKey: ["operator-session"] });
|
await queryClient.cancelQueries({ queryKey: ["operator-session"] });
|
||||||
await logoutOperator();
|
await logoutOperator();
|
||||||
queryClient.setQueryData(["operator-session"], {
|
queryClient.setQueryData(["operator-session"], {
|
||||||
login_enabled: true, authorized: false, actor: null, csrf: null,
|
login_enabled: session.data.login_enabled, oidc_enabled: session.data.oidc_enabled,
|
||||||
|
authorized: false, actor: null, csrf: null, expires_at: null,
|
||||||
});
|
});
|
||||||
queryClient.removeQueries({ predicate: (query) => query.queryKey[0] !== "operator-session" });
|
queryClient.removeQueries({ predicate: (query) => query.queryKey[0] !== "operator-session" });
|
||||||
} : undefined,
|
}
|
||||||
});
|
|
||||||
|
if (session.isSuccess && session.data.authorized) {
|
||||||
|
const actor = session.data.actor ?? undefined;
|
||||||
|
return children({ actor, onLogout: actor ? signOut : undefined });
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="vault-app flex min-h-screen items-center justify-center p-5">
|
<main className="vault-app flex min-h-screen items-center justify-center p-5">
|
||||||
<section className="w-full max-w-sm rounded-2xl border border-space-700 bg-space-900 p-6 sm:p-8">
|
<section className="w-full max-w-sm rounded-2xl border border-space-700 bg-space-900 p-6 sm:p-8">
|
||||||
<p className="instrument-label mb-3">Tessera / Backup control</p>
|
<p className="instrument-label mb-3">Tessera / Backup control</p>
|
||||||
<h1 className="text-2xl font-semibold text-star-100">Operator sign-in</h1>
|
<h1 className="text-2xl font-semibold text-star-100">Sign in</h1>
|
||||||
{session.isPending ? <p role="status" className="mt-4 text-star-300">Connecting to the hub…</p>
|
{session.isPending ? <p role="status" className="mt-4 text-star-300">Connecting to the hub…</p>
|
||||||
: session.isError ? (
|
: session.isError ? (
|
||||||
<div className="mt-4 space-y-3">
|
<div className="mt-4 space-y-3">
|
||||||
<p role="alert" className="text-star-300">Could not reach the hub.</p>
|
<p role="alert" className="text-star-300">Could not reach the hub.</p>
|
||||||
<Button onClick={() => void session.refetch()}>Try again</Button>
|
<Button onClick={() => void session.refetch()}>Try again</Button>
|
||||||
</div>
|
</div>
|
||||||
) : session.data.login_enabled ? (
|
) : session.data.actor ? (
|
||||||
<form onSubmit={submit} className="mt-5 space-y-4">
|
<div className="mt-4 space-y-4">
|
||||||
|
<h2 className="text-lg font-semibold text-star-100">No access yet</h2>
|
||||||
|
<p role="status" className="text-star-300">
|
||||||
|
You are signed in as {session.data.actor}, but this account has not been granted access to Tessera.
|
||||||
|
Ask an administrator to add you, then sign in again.
|
||||||
|
</p>
|
||||||
|
<Button onClick={() => void signOut()}>Sign out</Button>
|
||||||
|
</div>
|
||||||
|
) : session.data.login_enabled || session.data.oidc_enabled ? (
|
||||||
|
<div className="mt-5 space-y-5">
|
||||||
|
{ssoError && <p role="alert" className="text-sm text-orbit-red">{ssoError}</p>}
|
||||||
|
{session.data.oidc_enabled && (
|
||||||
|
<a href="/api/v1/auth/oidc/login"
|
||||||
|
className="block w-full rounded-xl bg-star-100 px-4 py-2 text-center font-medium text-space-950">
|
||||||
|
Sign in with SSO
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
{session.data.login_enabled && (
|
||||||
|
<details open={!session.data.oidc_enabled} className="group">
|
||||||
|
{session.data.oidc_enabled && (
|
||||||
|
<summary className="cursor-pointer text-sm text-star-300">Emergency operator sign-in</summary>
|
||||||
|
)}
|
||||||
|
<form onSubmit={submit} className="mt-3 space-y-4">
|
||||||
<label className="block text-sm text-star-300">
|
<label className="block text-sm text-star-300">
|
||||||
Operator password
|
Operator password
|
||||||
<input type="password" name="password" autoComplete="current-password" required
|
<input type="password" name="password" autoComplete="current-password" required
|
||||||
@@ -75,6 +116,9 @@ export function OperatorGate({
|
|||||||
{pending ? "Signing in…" : "Sign in"}
|
{pending ? "Signing in…" : "Sign in"}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
) : <p className="mt-4 text-star-300">Browser sign-in is disabled on this hub.</p>}
|
) : <p className="mt-4 text-star-300">Browser sign-in is disabled on this hub.</p>}
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
Reference in New Issue
Block a user