diff --git a/TODO.md b/TODO.md index cee5cbf..3edda80 100644 --- a/TODO.md +++ b/TODO.md @@ -53,13 +53,13 @@ Design: [`plan.md`](plan.md) · Review fixes: [`plan/review.md`](plan/review.md) - [ ] **C7** *(nice-to-have)* Smoke test against the Podman socket ### WS-D auth + DB · [card](plan/workstreams/WS-D-auth.md) -- [ ] **D1** `db.rs`: open-or-create, dir `0700`, WAL, `busy_timeout`, embedded migrations -- [ ] **D2** Migration for `tokens(id, name UNIQUE, token_hash UNIQUE, created_at, revoked_at, last_used_at)` -- [ ] **D3** `tokens.rs`: create (32 random bytes, `slinuxm_` prefix, printed once), list, revoke. Uses runtime queries. -- [ ] **D4** `slinuxm token create|list|revoke` CLI wired via the Phase 0 stub -- [ ] **D5** Bearer middleware: sha256 + indexed lookup of non-revoked tokens. 401 + `WWW-Authenticate` JSON on failure. -- [ ] **D6** Middleware exposed as a layer for the protected router only. `/healthz` stays public. -- [ ] **D7** Tests: create, accept, revoke, reject. Unknown token is rejected. Startup refuses auth-off + non-loopback. +- [x] **D1** `db.rs`: open-or-create, dir `0700`, WAL, `busy_timeout`, embedded migrations +- [x] **D2** Migration for `tokens(id, name UNIQUE, token_hash UNIQUE, created_at, revoked_at, last_used_at)` +- [x] **D3** `tokens.rs`: create (32 random bytes, `slinuxm_` prefix, printed once), list, revoke. Uses runtime queries. +- [x] **D4** `slinuxm token create|list|revoke` CLI wired via the Phase 0 stub +- [x] **D5** Bearer middleware: sha256 + indexed lookup of non-revoked tokens. 401 + `WWW-Authenticate` JSON on failure. +- [x] **D6** Middleware exposed as a layer for the protected router only. `/healthz` stays public. +- [x] **D7** Tests: create, accept, revoke, reject. Unknown token is rejected. Startup refuses auth-off + non-loopback. ## Phase 2 — Surfaces (parallel) diff --git a/migrations/0001_tokens.sql b/migrations/0001_tokens.sql new file mode 100644 index 0000000..5c04306 --- /dev/null +++ b/migrations/0001_tokens.sql @@ -0,0 +1,8 @@ +CREATE TABLE tokens ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL UNIQUE, + token_hash TEXT NOT NULL UNIQUE, + created_at TEXT NOT NULL, + revoked_at TEXT, + last_used_at TEXT +); diff --git a/plan/workstreams/WS-D-auth.md b/plan/workstreams/WS-D-auth.md index e28f54a..f21eab8 100644 --- a/plan/workstreams/WS-D-auth.md +++ b/plan/workstreams/WS-D-auth.md @@ -51,3 +51,4 @@ Tick these in [`TODO.md`](../../TODO.md). ## Log - 2026-10-15: Card created. +- 2026-10-15: Implemented on branch `ws-d/auth-db`. Token fns take `&SqlitePool` (`create`, `list`, `revoke`, `verify`); `db::migrate` is public for in-memory test pools. `last_used_at` is throttled to once a minute. Lookup is by sha256 hex hash with `slinuxm_` prefix pre-check. diff --git a/src/auth/mod.rs b/src/auth/mod.rs index 9f823f0..c9c2988 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -1,25 +1,53 @@ //! Bearer-token auth (WS-D owns `src/auth/`). //! -//! STUB: signature is final. Failures respond `401` with -//! `WWW-Authenticate: Bearer` and the standard JSON error body (DEC-4), for -//! both REST and `/mcp`. Apply the layer to the protected router only. +//! Failures respond `401` with `WWW-Authenticate: Bearer` and the standard +//! JSON error body (DEC-4), for both REST and `/mcp`. Apply the layer to the +//! protected router only; `/healthz` stays outside it. pub mod tokens; use std::convert::Infallible; use axum::extract::{Request, State}; +use axum::http::header; use axum::middleware::{self, Next}; -use axum::response::Response; +use axum::response::{IntoResponse, Response}; use axum::routing::Route; use tower::{Layer, Service}; +use crate::error::AppError; use crate::state::AppState; /// Verify `Authorization: Bearer ` (sha256 + indexed lookup). /// When `config.auth.enabled` is false this passes requests through. -async fn require_token(State(_state): State, _req: Request, _next: Next) -> Response { - todo!("WS-D D5") +async fn require_token(State(state): State, req: Request, next: Next) -> Response { + if !state.config.auth.enabled { + return next.run(req).await; + } + let presented = req + .headers() + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| { + let (scheme, rest) = v.split_once(' ')?; + scheme.eq_ignore_ascii_case("bearer").then_some(rest.trim()) + }) + .filter(|t| !t.is_empty()); + let Some(token) = presented else { + return AppError::Unauthorized("missing or malformed bearer token".into()).into_response(); + }; + let Some(pool) = state.db.as_ref() else { + return AppError::Unavailable("token database is not available".into()).into_response(); + }; + match tokens::verify(pool, token).await { + Ok(true) => next.run(req).await, + Ok(false) => AppError::Unauthorized("invalid or revoked token".into()).into_response(), + Err(e) => { + // The error never contains the presented token. + tracing::error!(error = %e, "token verification failed"); + AppError::Unavailable("token verification failed".into()).into_response() + } + } } /// Layer for `Router::layer` on the protected router (`/api/v1`, `/mcp`). @@ -38,3 +66,181 @@ pub fn layer( + 'static { middleware::from_fn_with_state(state, require_token) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::Config; + use crate::sources::fake::fake_state; + use axum::body::Body; + use axum::http::{Request as HttpRequest, StatusCode}; + use axum::routing::get; + use axum::Router; + use sqlx::sqlite::SqlitePoolOptions; + use tower::ServiceExt; + + async fn pool() -> sqlx::SqlitePool { + let p = SqlitePoolOptions::new() + .max_connections(1) + .connect("sqlite::memory:") + .await + .unwrap(); + crate::db::migrate(&p).await.unwrap(); + p + } + + fn app(state: AppState) -> Router { + Router::new() + .route("/api/v1/x", get(|| async { "ok" })) + .layer(layer(state)) + .route("/healthz", get(|| async { "ok" })) + } + + async fn status(app: &Router, path: &str, auth: Option<&str>) -> (StatusCode, bool) { + let mut r = HttpRequest::builder().uri(path); + if let Some(a) = auth { + r = r.header("authorization", a); + } + let resp = app + .clone() + .oneshot(r.body(Body::empty()).unwrap()) + .await + .unwrap(); + ( + resp.status(), + resp.headers().contains_key(header::WWW_AUTHENTICATE), + ) + } + + #[tokio::test] + async fn create_accept_revoke_reject() { + let pool = pool().await; + let mut state = fake_state(Config::default()); + state.db = Some(pool.clone()); + let app = app(state); + + let token = tokens::create(&pool, "ci").await.unwrap(); + assert!(token.starts_with("slinuxm_")); + let bearer = format!("Bearer {token}"); + assert_eq!( + status(&app, "/api/v1/x", Some(&bearer)).await.0, + StatusCode::OK + ); + + let l = tokens::list(&pool).await.unwrap(); + assert_eq!(l.len(), 1); + assert!(l[0].last_used_at.is_some()); + + assert_eq!( + tokens::revoke(&pool, "ci").await.unwrap(), + tokens::Revoked::Now + ); + assert_eq!( + tokens::revoke(&pool, "ci").await.unwrap(), + tokens::Revoked::Already + ); + assert_eq!( + tokens::revoke(&pool, "zz").await.unwrap(), + tokens::Revoked::NotFound + ); + assert_eq!( + status(&app, "/api/v1/x", Some(&bearer)).await, + (StatusCode::UNAUTHORIZED, true) + ); + } + + #[tokio::test] + async fn rejects_unknown_garbage_and_missing() { + let pool = pool().await; + let mut state = fake_state(Config::default()); + state.db = Some(pool.clone()); + let app = app(state); + for a in [ + None, + Some("Bearer"), + Some("Bearer "), + Some("Bearer garbage"), + Some("Bearer slinuxm_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"), + Some("Basic dXNlcjpwdw=="), + ] { + assert_eq!( + status(&app, "/api/v1/x", a).await, + (StatusCode::UNAUTHORIZED, true), + "{a:?}" + ); + } + assert_eq!(status(&app, "/healthz", None).await.0, StatusCode::OK); + tokens::create(&pool, "a").await.unwrap(); + assert!(tokens::create(&pool, "a").await.is_err()); + } + + #[tokio::test] + async fn disabled_is_passthrough() { + let mut c = Config::default(); + c.auth.enabled = false; + let app = app(fake_state(c)); + assert_eq!(status(&app, "/api/v1/x", None).await.0, StatusCode::OK); + } + + #[test] + fn startup_refuses_auth_off_non_loopback() { + let mut c = Config::default(); + c.auth.enabled = false; + c.server.bind = "0.0.0.0".parse().unwrap(); + assert!(c.validate().is_err()); + } + + #[tokio::test] + async fn fails_closed_without_db() { + let mut state = fake_state(Config::default()); + state.db = None; + let app = app(state); + let (st, _) = status(&app, "/api/v1/x", Some("Bearer slinuxm_abc")).await; + assert_eq!(st, StatusCode::SERVICE_UNAVAILABLE); + } + + #[tokio::test] + async fn db_error_is_503() { + let p = pool().await; + let mut state = fake_state(Config::default()); + state.db = Some(p.clone()); + let app = app(state); + p.close().await; + let (st, _) = status(&app, "/api/v1/x", Some("Bearer slinuxm_abc")).await; + assert_eq!(st, StatusCode::SERVICE_UNAVAILABLE); + } + + #[tokio::test] + async fn scheme_is_case_insensitive() { + let p = pool().await; + let mut state = fake_state(Config::default()); + state.db = Some(p.clone()); + let app = app(state); + let t = tokens::create(&p, "c").await.unwrap(); + for scheme in ["bearer", "BEARER", "Bearer"] { + let h = format!("{scheme} {t}"); + assert_eq!(status(&app, "/api/v1/x", Some(&h)).await.0, StatusCode::OK); + } + } + + #[tokio::test] + async fn last_used_is_throttled() { + let p = pool().await; + let t = tokens::create(&p, "t").await.unwrap(); + assert!(tokens::verify(&p, &t).await.unwrap()); + let first = tokens::list(&p).await.unwrap()[0].last_used_at.clone(); + assert!(first.is_some()); + assert!(tokens::verify(&p, &t).await.unwrap()); + assert_eq!(tokens::list(&p).await.unwrap()[0].last_used_at, first); + } + + #[tokio::test] + async fn token_names_are_trimmed_and_validated() { + let p = pool().await; + tokens::create(&p, " ci ").await.unwrap(); + assert_eq!(tokens::list(&p).await.unwrap()[0].name, "ci"); + assert!(tokens::create(&p, "ci").await.is_err()); + assert!(tokens::create(&p, "a\nb").await.is_err()); + assert!(tokens::create(&p, " ").await.is_err()); + } +} diff --git a/src/auth/tokens.rs b/src/auth/tokens.rs index 8bb17db..69a4289 100644 --- a/src/auth/tokens.rs +++ b/src/auth/tokens.rs @@ -1,14 +1,22 @@ //! Token CRUD and the `slinuxm token` CLI (WS-D owns this file). //! -//! STUB: `TokenCmd` and `run` signatures are final. Tokens have the prefix -//! `slinuxm_`, 32 random bytes, only the sha256 hash is stored, and the -//! plaintext is printed once on create. +//! Tokens have the prefix `slinuxm_` and 32 random bytes. Only the sha256 hex +//! digest is stored; the plaintext is printed once on create. -use anyhow::Result; +use anyhow::{bail, Context, Result}; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; use clap::Subcommand; +use rand::rngs::SysRng; +use rand::TryRng; +use sha2::{Digest, Sha256}; +use sqlx::SqlitePool; use crate::config::Config; +pub const TOKEN_PREFIX: &str = "slinuxm_"; +const TS_FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ"; + #[derive(Debug, Clone, Subcommand)] pub enum TokenCmd { /// Create a token and print it once. @@ -22,7 +30,155 @@ pub enum TokenCmd { Revoke { name: String }, } +/// A token row without its hash. +#[derive(Debug, Clone, sqlx::FromRow)] +pub struct TokenInfo { + pub name: String, + pub created_at: String, + pub revoked_at: Option, + pub last_used_at: Option, +} + +/// Hex sha256 of a token string. +pub fn hash_token(token: &str) -> String { + Sha256::digest(token.as_bytes()) + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +/// UTC timestamp in a fixed-width format that sorts lexicographically. +fn now_string() -> String { + jiff::Timestamp::now().strftime(TS_FORMAT).to_string() +} + +/// Create a token and return the plaintext (shown once, never stored). +pub async fn create(pool: &SqlitePool, name: &str) -> Result { + let name = name.trim(); + if name.is_empty() { + bail!("token name must not be empty"); + } + if name.chars().any(char::is_control) { + bail!("token name must not contain control characters"); + } + let mut bytes = [0u8; 32]; + SysRng + .try_fill_bytes(&mut bytes) + .map_err(|e| anyhow::anyhow!("OS RNG failure: {e}"))?; + let token = format!("{TOKEN_PREFIX}{}", URL_SAFE_NO_PAD.encode(bytes)); + let res = sqlx::query("INSERT INTO tokens (name, token_hash, created_at) VALUES (?, ?, ?)") + .bind(name) + .bind(hash_token(&token)) + .bind(now_string()) + .execute(pool) + .await; + match res { + Ok(_) => Ok(token), + Err(sqlx::Error::Database(e)) if e.is_unique_violation() => { + bail!("a token named {name:?} already exists") + } + Err(e) => Err(e).context("inserting token"), + } +} + +/// List tokens by creation order. Hashes are never selected. +pub async fn list(pool: &SqlitePool) -> Result> { + sqlx::query_as::<_, TokenInfo>( + "SELECT name, created_at, revoked_at, last_used_at FROM tokens ORDER BY id", + ) + .fetch_all(pool) + .await + .context("listing tokens") +} + +/// Outcome of [`revoke`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Revoked { + Now, + Already, + NotFound, +} + +pub async fn revoke(pool: &SqlitePool, name: &str) -> Result { + let r = sqlx::query("UPDATE tokens SET revoked_at = ? WHERE name = ? AND revoked_at IS NULL") + .bind(now_string()) + .bind(name) + .execute(pool) + .await + .context("revoking token")?; + if r.rows_affected() > 0 { + return Ok(Revoked::Now); + } + let exists: Option = sqlx::query_scalar("SELECT id FROM tokens WHERE name = ?") + .bind(name) + .fetch_optional(pool) + .await + .context("looking up token")?; + Ok(if exists.is_some() { + Revoked::Already + } else { + Revoked::NotFound + }) +} + +/// Check a presented token. The DB matches on the hash (the secret itself is +/// never compared), and `last_used_at` is touched at most once a minute. +pub async fn verify(pool: &SqlitePool, token: &str) -> Result { + if !token.starts_with(TOKEN_PREFIX) { + return Ok(false); + } + let id: Option = + sqlx::query_scalar("SELECT id FROM tokens WHERE token_hash = ? AND revoked_at IS NULL") + .bind(hash_token(token)) + .fetch_optional(pool) + .await + .context("token lookup")?; + let Some(id) = id else { return Ok(false) }; + let cutoff = (jiff::Timestamp::now() - std::time::Duration::from_secs(60)) + .strftime(TS_FORMAT) + .to_string(); + // Best effort: a failed touch must not reject a valid token. + let _ = sqlx::query( + "UPDATE tokens SET last_used_at = ? WHERE id = ? AND (last_used_at IS NULL OR last_used_at < ?)", + ) + .bind(now_string()) + .bind(id) + .bind(cutoff) + .execute(pool) + .await; + Ok(true) +} + /// Execute a token subcommand against the DB at `config.auth.db_path`. -pub async fn run(_cmd: TokenCmd, _config: &Config) -> Result<()> { - todo!("WS-D D3/D4") +pub async fn run(cmd: TokenCmd, config: &Config) -> Result<()> { + let pool = crate::db::open(config).await?; + match cmd { + TokenCmd::Create { name } => { + let token = create(&pool, &name).await?; + println!("{token}"); + eprintln!("Token {name:?} created. Store it now: it cannot be shown again."); + } + TokenCmd::List => { + println!( + "{:<24} {:<22} {:<22} LAST USED", + "NAME", "CREATED", "REVOKED" + ); + for t in list(&pool).await? { + println!( + "{:<24} {:<22} {:<22} {}", + t.name, + t.created_at, + t.revoked_at.as_deref().unwrap_or("-"), + t.last_used_at.as_deref().unwrap_or("-") + ); + } + } + TokenCmd::Revoke { name } => match revoke(&pool, &name).await? { + Revoked::Now => println!("Token {name:?} revoked."), + Revoked::Already => println!("Token {name:?} was already revoked."), + Revoked::NotFound => bail!("no token named {name:?}"), + }, + } + pool.close().await; + Ok(()) } diff --git a/src/db.rs b/src/db.rs index 757dd4a..886f1a0 100644 --- a/src/db.rs +++ b/src/db.rs @@ -1,14 +1,141 @@ //! SQLite pool for access tokens (WS-D owns this file). -//! -//! STUB: signature is final. Use runtime queries (DEC-3), WAL mode and a busy -//! timeout, create the directory `0700`, run embedded migrations. -use anyhow::Result; +use std::path::Path; +use std::time::Duration; + +use anyhow::{Context, Result}; +use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions}; use sqlx::SqlitePool; use crate::config::Config; /// Open (creating if needed) `config.auth.db_path` and migrate. -pub async fn open(_config: &Config) -> Result { - todo!("WS-D D1") +pub async fn open(config: &Config) -> Result { + let path = &config.auth.db_path; + if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) { + create_private_dir(dir)?; + } + let opts = SqliteConnectOptions::new() + .filename(path) + .create_if_missing(true) + .journal_mode(SqliteJournalMode::Wal) + .busy_timeout(Duration::from_secs(5)); + let pool = SqlitePoolOptions::new() + .max_connections(4) + .connect_with(opts) + .await + .with_context(|| format!("opening token database {}", path.display()))?; + migrate(&pool).await?; + restrict_files(path); + Ok(pool) +} + +/// Make the DB and its WAL/SHM sidecars owner-only (0600). +fn restrict_files(db: &Path) { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + for suffix in ["", "-wal", "-shm"] { + let mut name = db.as_os_str().to_owned(); + name.push(suffix); + let p = std::path::PathBuf::from(name); + if p.exists() { + if let Err(e) = std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600)) + { + tracing::warn!(path = %p.display(), error = %e, "could not chmod 0600"); + } + } + } + } + #[cfg(not(unix))] + let _ = db; +} + +/// Run the embedded migrations. +pub async fn migrate(pool: &SqlitePool) -> Result<()> { + sqlx::migrate!("./migrations") + .run(pool) + .await + .context("running database migrations") +} + +fn create_private_dir(dir: &Path) -> Result<()> { + if dir.exists() { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(dir)?.permissions().mode(); + if mode & 0o077 != 0 { + if let Err(e) = + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)) + { + tracing::warn!(dir = %dir.display(), mode = format!("{:o}", mode & 0o777), error = %e, + "state directory is accessible to others and could not be tightened"); + } + } + } + return Ok(()); + } + let mut b = std::fs::DirBuilder::new(); + b.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + b.mode(0o700); + } + b.create(dir) + .with_context(|| format!("creating {}", dir.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn creates_dir_0700_and_migrates() { + use rand::TryRng; + let mut r = [0u8; 8]; + rand::rngs::SysRng.try_fill_bytes(&mut r).unwrap(); + let tmp = std::env::temp_dir().join(format!( + "slinuxm-dbtest-{}", + r.iter().map(|b| format!("{b:02x}")).collect::() + )); + let mut c = Config::default(); + c.auth.db_path = tmp.join("state/db.sqlite"); + let pool = open(&c).await.unwrap(); + let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM tokens") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(n, 0); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let m = std::fs::metadata(tmp.join("state")).unwrap(); + assert_eq!(m.permissions().mode() & 0o777, 0o700); + for f in ["db.sqlite", "db.sqlite-wal", "db.sqlite-shm"] { + let p = tmp.join("state").join(f); + if p.exists() { + let m = std::fs::metadata(&p).unwrap().permissions().mode(); + assert_eq!(m & 0o777, 0o600, "{f}"); + } + } + assert!(tmp.join("state/db.sqlite").exists()); + } + // a looser existing dir is tightened on reopen + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let d = tmp.join("state"); + std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o755)).unwrap(); + drop(pool); + open(&c).await.unwrap(); + let m = std::fs::metadata(&d).unwrap().permissions().mode(); + assert_eq!(m & 0o777, 0o700); + } + #[cfg(not(unix))] + drop(pool); + open(&c).await.unwrap(); + std::fs::remove_dir_all(tmp).ok(); + } }