Phase 1: app, Kanidm login, people, passports, addresses, audit log
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 42s

visa.buildfor.life keeps the immigration records of the foreigners B4L
looks after. This first phase is the base the deadlines and extension
packs build on (docs/PLAN.md, phases 2 to 7).

- One Rust binary (axum 0.8, minijinja, sqlx on PostgreSQL) with its
  templates, static files and migrations compiled in.
- Login through Kanidm (OpenID Connect with PKCE and a nonce, ES256),
  client visa-web, group visa; sessions in PostgreSQL keyed by the
  SHA-256 of the cookie. VISA_INSECURE_NO_LOGIN=1 for loopback
  development only.
- Same-site check and form token on every POST; a CSP without inline
  script or style; security headers.
- People: list with filter, page, create, edit, archive, restore.
- Passports from the machine-readable zone with check digits (ICAO
  9303 TD3); expiry warnings at 12 and 6 months.
- Addresses in Thailand in the order Thai forms use, with the house
  master and the TM.30 receipt.
- Append-only audit log of every view and change, with the names of the
  changed fields but never their values (PDPA); the Activity page.
- Invented demo people (visa seed-demo, refused when login is on).
- 40 tests: unit tests, pages with demo data, the forms, the audit log
  and the whole login against a fake OpenID provider.
- CI: gitleaks over the history, fmt, clippy and the tests against
  PostgreSQL 18; the pre-commit secret scan.
This commit is contained in:
grabowski committed 2026-11-17 16:58:48 +07:00
commit 2e009700a9
56 files changed
+11193

No files matched your search

+204
View File
@@ -0,0 +1,204 @@
//! Sessions in PostgreSQL, pending logins in memory.
//!
//! A session survives a restart (deploys do not sign anyone out). The table
//! holds the SHA-256 of the cookie's value, never the value itself.
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use anyhow::Result;
use axum::http::HeaderMap;
use axum::http::header::COOKIE;
use serde::Serialize;
use sqlx::PgPool;
use crate::oidc::random_token;
/// `__Host-`: Secure, Path=/ and no Domain, so no other name under
/// buildfor.life can set or read it.
pub const SESSION_COOKIE: &str = "__Host-visa";
/// Binds a login in progress to the browser that started it.
pub const FLOW_COOKIE: &str = "__Host-visa-login";
pub const SESSION_TTL: Duration = Duration::from_secs(12 * 3600);
pub const FLOW_TTL: Duration = Duration::from_secs(600);
const MAX_FLOWS: usize = 1000;
#[derive(Clone, Debug, Serialize)]
pub struct User {
pub login: String,
pub name: String,
/// Local development without login.
pub local: bool,
/// The session's token for forms (CSRF); templates get it as `csrf`.
#[serde(skip)]
pub csrf: String,
}
impl User {
pub fn local(csrf: &str) -> User {
User {
login: "local".into(),
name: "Local development".into(),
local: true,
csrf: csrf.to_string(),
}
}
}
#[derive(Clone, Debug)]
pub struct Flow {
pub state: String,
pub nonce: String,
pub verifier: String,
/// Where to go after the login.
pub next: String,
created: Instant,
}
#[derive(Default)]
pub struct Flows {
flows: Mutex<HashMap<String, Flow>>,
}
impl Flows {
/// A new login; None when too many are pending (someone hammering /login).
pub fn start(&self, next: String) -> Option<Flow> {
let mut flows = self.flows.lock().unwrap_or_else(|e| e.into_inner());
flows.retain(|_, f| f.created.elapsed() < FLOW_TTL);
if flows.len() >= MAX_FLOWS {
return None;
}
let flow = Flow {
state: random_token(),
nonce: random_token(),
verifier: random_token(),
next,
created: Instant::now(),
};
flows.insert(flow.state.clone(), flow.clone());
Some(flow)
}
/// The pending login for this state, once.
pub fn take(&self, state: &str) -> Option<Flow> {
let mut flows = self.flows.lock().unwrap_or_else(|e| e.into_inner());
flows
.remove(state)
.filter(|f| f.created.elapsed() < FLOW_TTL)
}
}
fn hash(id: &str) -> Vec<u8> {
ring::digest::digest(&ring::digest::SHA256, id.as_bytes())
.as_ref()
.to_vec()
}
/// Creates a session; returns the cookie's value.
pub async fn create(db: &PgPool, login: &str, name: &str) -> Result<String> {
let id = random_token();
let ttl = chrono::TimeDelta::seconds(SESSION_TTL.as_secs() as i64);
sqlx::query("DELETE FROM sessions WHERE expires_at < now()")
.execute(db)
.await?;
sqlx::query(
"INSERT INTO sessions (id_hash, login, name, csrf, expires_at) \
VALUES ($1, $2, $3, $4, now() + $5)",
)
.bind(hash(&id))
.bind(login)
.bind(name)
.bind(random_token())
.bind(ttl)
.execute(db)
.await?;
Ok(id)
}
pub async fn get(db: &PgPool, id: &str) -> Result<Option<User>> {
let row: Option<(String, String, String)> = sqlx::query_as(
"SELECT login, name, csrf FROM sessions WHERE id_hash = $1 AND expires_at > now()",
)
.bind(hash(id))
.fetch_optional(db)
.await?;
Ok(row.map(|(login, name, csrf)| User {
login,
name,
local: false,
csrf,
}))
}
pub async fn remove(db: &PgPool, id: &str) -> Result<()> {
sqlx::query("DELETE FROM sessions WHERE id_hash = $1")
.bind(hash(id))
.execute(db)
.await?;
Ok(())
}
pub fn cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
for value in headers.get_all(COOKIE) {
let Ok(text) = value.to_str() else {
continue;
};
for part in text.split(';') {
if let Some((k, v)) = part.trim().split_once('=')
&& k == name
{
return Some(v.to_string());
}
}
}
None
}
pub fn set_cookie(name: &str, value: &str, max_age: Duration) -> String {
format!(
"{name}={value}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age={}",
max_age.as_secs()
)
}
pub fn clear_cookie(name: &str) -> String {
format!("{name}=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0")
}
/// Compares two tokens in time independent of where they differ.
pub fn same_token(a: &str, b: &str) -> bool {
let (a, b) = (a.as_bytes(), b.as_bytes());
if a.len() != b.len() || a.is_empty() {
return false;
}
a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::HeaderValue;
#[test]
fn flows_are_single_use() {
let f = Flows::default();
let flow = f.start("/people/3".into()).unwrap();
assert_eq!(f.take(&flow.state).unwrap().next, "/people/3");
assert!(f.take(&flow.state).is_none());
}
#[test]
fn cookies_and_tokens() {
let mut h = HeaderMap::new();
h.append(COOKIE, HeaderValue::from_static("a=1; __Host-visa=abc"));
assert_eq!(cookie_value(&h, SESSION_COOKIE).as_deref(), Some("abc"));
assert_eq!(cookie_value(&h, FLOW_COOKIE), None);
assert!(set_cookie(SESSION_COOKIE, "x", SESSION_TTL).contains("Max-Age=43200"));
assert!(same_token("abc", "abc"));
assert!(!same_token("abc", "abd"));
assert!(!same_token("abc", "ab"));
assert!(!same_token("", ""));
assert_eq!(hash("x").len(), 32);
}
}