Files
tessera/crates/tessera-hub/src/db/sessions.rs
Adnan Zahir c938afe1b5
Some checks failed
ci / rust (push) Has been cancelled
ci / supply-chain (push) Has been cancelled
ci / web (push) Has been cancelled
feat: access console with a permission tree, grouped grants and effective access
Backend: grants accept a list of permissions; PUT /access/grants edits or renews a set atomically; refusals carry a reason; the grant list includes refresh grants per relation and the administrator-only permissions; users keep their last groups and admin flag; the emergency operator cannot hold grants.

Frontend: the Access screen shows the grantable permissions as a checkbox tree with dependencies, rows grouped by person or group, orbit and end date, expiry and no-effect states, and what each person can do right now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 20:20:25 +07:00

388 lines
15 KiB
Rust

//! 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,
/// Groups verified at sign-in (JSON in the table).
pub groups: Vec<String>,
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")?;
super::ensure_column(conn, "sessions", "groups", "TEXT NOT NULL DEFAULT '[]'")?;
// What the identity provider said at the user's last sign-in, kept after the session ends so the
// access screens can still say who is an administrator and which groups a person comes through.
super::ensure_column(conn, "users", "last_groups", "TEXT NOT NULL DEFAULT '[]'")?;
super::ensure_column(conn, "users", "last_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.
#[allow(clippy::too_many_arguments)]
pub fn create_session(
&self,
id: &str,
user_id: &str,
auth_method: &str,
credential_fp: Option<&str>,
admin: bool,
groups: &[String],
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,groups)
SELECT ?1, id, generation, ?3, ?4, ?5, ?5, ?5, ?6, ?7, ?8 FROM users WHERE id=?2 AND active=1",
params![session_digest(id), user_id, auth_method, credential_fp, now, now + ABSOLUTE_SECS, admin, serde_json::to_string(groups)?],
)?;
if inserted == 1 {
conn.execute(
"UPDATE users SET last_groups=?2, last_admin=?3 WHERE id=?1",
params![user_id, serde_json::to_string(groups)?, 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,s.groups
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)?,
groups: serde_json::from_str(&row.get::<_, String>(7)?).unwrap_or_default(),
},
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(())
}
/// 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());
}
}