WS-D: token DB, token CLI and bearer auth middleware

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YShymaPrXmc3KYRUg2HMSs
This commit is contained in:
ariandClaude Sonnet 5.5 committed 2026-10-15 17:58:58 -04:00
1 parent 2687ef5c33
commit b6c814a18f
6 files changed
+406 -25

No files matched your search

+7 -7
View File
@@ -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)
+8
View File
@@ -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
);
+1
View File
@@ -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.
+158 -6
View File
@@ -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 <token>` (sha256 + indexed lookup).
/// When `config.auth.enabled` is false this passes requests through.
async fn require_token(State(_state): State<AppState>, _req: Request, _next: Next) -> Response {
todo!("WS-D D5")
async fn require_token(State(state): State<AppState>, 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,127 @@ 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());
}
}
+158 -6
View File
@@ -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,151 @@ 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<String>,
pub last_used_at: Option<String>,
}
/// 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<String> {
if name.trim().is_empty() {
bail!("token name must not be empty");
}
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<Vec<TokenInfo>> {
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<Revoked> {
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<i64> = 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<bool> {
if !token.starts_with(TOKEN_PREFIX) {
return Ok(false);
}
let id: Option<i64> =
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(())
}
+74 -6
View File
@@ -1,14 +1,82 @@
//! 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<SqlitePool> {
todo!("WS-D D1")
pub async fn open(config: &Config) -> Result<SqlitePool> {
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?;
Ok(pool)
}
/// 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() {
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() {
let tmp = std::env::temp_dir().join(format!("slinuxm-dbtest-{}", std::process::id()));
std::fs::remove_dir_all(&tmp).ok();
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);
}
// reopening an existing DB works
drop(pool);
open(&c).await.unwrap();
std::fs::remove_dir_all(tmp).ok();
}
}