1
Fork 0
mirror of https://github.com/thegeneralist01/archivr synced 2026-12-04 18:56:44 +01:00

feat: R2 credentials: sessions, token options, read scope, admin password

Own sessions (S1-S3), admin password/sessions/tokens (U2-U5), token
expiry/scope on POST /api/auth/tokens, user_uid/roles on /api/auth/me,
throttled touch_token on Bearer auth, patch_me min length + other-session
invalidation, and read-scope token enforcement middleware.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
TheGeneralist 2026-10-08 12:32:20 +02:00
parent 4f6e87373e
commit 7e80ac069f
Signed by: thegeneralist01
SSH key fingerprint: SHA256:pp9qddbCNmVNoSjevdvQvM5z0DHN7LTa8qBMbcMq/R4
5 changed files with 1196 additions and 20 deletions

View file

@ -1,2 +1,279 @@
//! Auth-DB credential helpers (session listing/revocation, token scope).
//! Stub: filled in by the credentials stream.
//! Auth-DB credential helpers: session listing/revocation by handle, API token
//! revocation, password resets, role slugs and the throttled token touch.
//!
//! `session_uid` is the value of the `session` cookie, so nothing in this
//! module hands it back to callers; sessions are addressed by a stable,
//! non-reversible `session_handle` (first 16 hex chars of its SHA3-256 hash).
use anyhow::Result;
use chrono::Utc;
use rusqlite::{Connection, OptionalExtension, params};
use crate::hash::hash_bytes;
/// Length of a `session_handle` in hex characters.
pub const SESSION_HANDLE_LEN: usize = 16;
/// Public view of a session. Never carries `session_uid`.
#[derive(Debug, Clone, serde::Serialize)]
pub struct SessionInfo {
pub session_handle: String,
pub created_at: String,
pub last_seen_at: String,
pub expires_at: String,
pub user_agent: Option<String>,
}
/// Stable handle for a session: first 16 hex chars of `hash(session_uid)`.
pub fn session_handle(session_uid: &str) -> String {
hash_bytes(session_uid.as_bytes())[..SESSION_HANDLE_LEN].to_string()
}
/// Lists a user's unexpired sessions, newest `last_seen_at` first.
pub fn list_user_sessions(conn: &Connection, user_id: i64) -> Result<Vec<SessionInfo>> {
let now = Utc::now().to_rfc3339();
let mut stmt = conn.prepare(
"SELECT session_uid, created_at, last_seen_at, expires_at, user_agent
FROM sessions WHERE user_id = ?1 AND expires_at > ?2
ORDER BY last_seen_at DESC, id DESC",
)?;
let rows = stmt
.query_map(params![user_id, now], |row| {
let session_uid: String = row.get(0)?;
Ok(SessionInfo {
session_handle: session_handle(&session_uid),
created_at: row.get(1)?,
last_seen_at: row.get(2)?,
expires_at: row.get(3)?,
user_agent: row.get(4)?,
})
})?
.collect::<Result<Vec<_>, _>>()?;
Ok(rows)
}
/// Deletes the user's session with the given handle. Returns false when the
/// handle matches none of that user's sessions.
pub fn delete_user_session_by_handle(
conn: &Connection,
user_id: i64,
handle: &str,
) -> Result<bool> {
let mut stmt = conn.prepare("SELECT session_uid FROM sessions WHERE user_id = ?1")?;
let uids = stmt
.query_map([user_id], |row| row.get::<_, String>(0))?
.collect::<Result<Vec<_>, _>>()?;
for uid in uids {
if session_handle(&uid) == handle {
conn.execute("DELETE FROM sessions WHERE session_uid = ?1", [&uid])?;
return Ok(true);
}
}
Ok(false)
}
/// Deletes every session of the user except `keep_session_uid` (all of them
/// when `None`). Returns the number of sessions deleted.
pub fn delete_other_sessions(
conn: &Connection,
user_id: i64,
keep_session_uid: Option<&str>,
) -> Result<usize> {
let n = match keep_session_uid {
Some(keep) => conn.execute(
"DELETE FROM sessions WHERE user_id = ?1 AND session_uid != ?2",
params![user_id, keep],
)?,
None => conn.execute("DELETE FROM sessions WHERE user_id = ?1", [user_id])?,
};
Ok(n)
}
/// Deletes all API tokens of a user. Returns the number deleted.
pub fn delete_user_tokens(conn: &Connection, user_id: i64) -> Result<usize> {
Ok(conn.execute("DELETE FROM api_tokens WHERE user_id = ?1", [user_id])?)
}
/// Admin password reset: sets the new hash, deletes all of the user's sessions
/// and, if asked, all their API tokens, in one transaction.
/// Returns `(sessions_revoked, tokens_revoked)`.
pub fn reset_user_password(
conn: &Connection,
user_id: i64,
new_hash: &str,
revoke_tokens: bool,
) -> Result<(usize, usize)> {
let tx = conn.unchecked_transaction()?;
tx.execute(
"UPDATE users SET password_hash = ?1 WHERE id = ?2",
params![new_hash, user_id],
)?;
let sessions = delete_other_sessions(&tx, user_id, None)?;
let tokens = if revoke_tokens {
delete_user_tokens(&tx, user_id)?
} else {
0
};
tx.commit()?;
Ok((sessions, tokens))
}
/// Role slugs held by the user, lowest bit first. A user with no role rows is
/// reported as `["guest"]` (the guest bit is always part of their role bits).
pub fn list_user_role_slugs(conn: &Connection, user_id: i64) -> Result<Vec<String>> {
let mut stmt = conn.prepare(
"SELECT r.slug FROM user_roles ur JOIN roles r ON r.id = ur.role_id
WHERE ur.user_id = ?1 ORDER BY r.bit_position ASC",
)?;
let mut slugs = stmt
.query_map([user_id], |row| row.get::<_, String>(0))?
.collect::<Result<Vec<_>, _>>()?;
if slugs.is_empty() {
slugs.push("guest".to_string());
}
Ok(slugs)
}
/// Scope (`full` | `read`) of a valid token: unexpired and its user active.
pub fn token_scope_for_hash(conn: &Connection, token_hash: &str) -> Result<Option<String>> {
let now = Utc::now().to_rfc3339();
conn.query_row(
"SELECT t.scope FROM api_tokens t
JOIN users u ON u.id = t.user_id
WHERE t.token_hash = ?1
AND u.status = 'active'
AND (t.expires_at IS NULL OR t.expires_at > ?2)",
params![token_hash, now],
|row| row.get(0),
)
.optional()
.map_err(Into::into)
}
/// Sets `last_used_at` for a token unless it was already set within the last
/// `min_interval_secs`. Returns true when a write happened.
pub fn touch_token_throttled(
conn: &Connection,
token_uid: &str,
min_interval_secs: i64,
) -> Result<bool> {
let now = Utc::now();
let cutoff = (now - chrono::Duration::seconds(min_interval_secs)).to_rfc3339();
let n = conn.execute(
"UPDATE api_tokens SET last_used_at = ?1
WHERE token_uid = ?2
AND (last_used_at IS NULL OR julianday(last_used_at) <= julianday(?3))",
params![now.to_rfc3339(), token_uid, cutoff],
)?;
Ok(n > 0)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::database;
fn setup() -> (Connection, i64, i64) {
let conn = Connection::open_in_memory().unwrap();
database::initialize_auth_schema(&conn).unwrap();
conn.execute_batch("PRAGMA foreign_keys = ON;").unwrap();
let owner = database::create_owner(&conn, "owner", "pw").unwrap();
let uid = database::create_user(&conn, "bob", None, "pw", owner).unwrap();
let bob = database::get_user_id_by_uid(&conn, &uid).unwrap().unwrap();
(conn, owner, bob)
}
#[test]
fn handle_is_sixteen_hex_and_stable_and_not_the_uid() {
let h = session_handle("sess_abc");
assert_eq!(h.len(), 16);
assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
assert_eq!(h, session_handle("sess_abc"));
assert_ne!(h, session_handle("sess_abd"));
}
#[test]
fn list_and_delete_sessions_by_handle_are_scoped_to_user() {
let (conn, owner, bob) = setup();
let s1 = database::create_session(&conn, bob, 2, Some("ua")).unwrap();
let s2 = database::create_session(&conn, bob, 2, None).unwrap();
let other = database::create_session(&conn, owner, 8, None).unwrap();
let listed = list_user_sessions(&conn, bob).unwrap();
assert_eq!(listed.len(), 2);
let json = serde_json::to_string(&listed).unwrap();
assert!(!json.contains(&s1) && !json.contains(&s2));
// Another user's handle is not deletable through bob.
assert!(!delete_user_session_by_handle(&conn, bob, &session_handle(&other)).unwrap());
assert!(database::get_session(&conn, &other).unwrap().is_some());
assert!(delete_user_session_by_handle(&conn, bob, &session_handle(&s1)).unwrap());
assert!(database::get_session(&conn, &s1).unwrap().is_none());
assert!(database::get_session(&conn, &s2).unwrap().is_some());
}
#[test]
fn delete_other_sessions_keeps_only_the_given_one() {
let (conn, _, bob) = setup();
let keep = database::create_session(&conn, bob, 2, None).unwrap();
database::create_session(&conn, bob, 2, None).unwrap();
database::create_session(&conn, bob, 2, None).unwrap();
assert_eq!(delete_other_sessions(&conn, bob, Some(&keep)).unwrap(), 2);
assert_eq!(list_user_sessions(&conn, bob).unwrap().len(), 1);
assert_eq!(delete_other_sessions(&conn, bob, None).unwrap(), 1);
assert!(list_user_sessions(&conn, bob).unwrap().is_empty());
}
#[test]
fn reset_password_clears_sessions_and_optionally_tokens() {
let (conn, _, bob) = setup();
database::create_session(&conn, bob, 2, None).unwrap();
database::create_api_token(&conn, bob, "h1", "t", None, "full").unwrap();
let (s, t) = reset_user_password(&conn, bob, "newhash", false).unwrap();
assert_eq!((s, t), (1, 0));
assert_eq!(
database::get_user_password_hash(&conn, bob).unwrap().as_deref(),
Some("newhash")
);
database::create_session(&conn, bob, 2, None).unwrap();
let (s, t) = reset_user_password(&conn, bob, "newhash2", true).unwrap();
assert_eq!((s, t), (1, 1));
assert!(database::list_user_tokens(&conn, bob).unwrap().is_empty());
}
#[test]
fn touch_token_is_throttled() {
let (conn, _, bob) = setup();
let tok = database::create_api_token(&conn, bob, "h", "t", None, "full").unwrap();
assert!(touch_token_throttled(&conn, &tok, 60).unwrap());
assert!(!touch_token_throttled(&conn, &tok, 60).unwrap());
// Back-date last use beyond the interval: touched again.
let old = (Utc::now() - chrono::Duration::seconds(120)).to_rfc3339();
conn.execute(
"UPDATE api_tokens SET last_used_at = ?1 WHERE token_uid = ?2",
params![old, tok],
)
.unwrap();
assert!(touch_token_throttled(&conn, &tok, 60).unwrap());
}
#[test]
fn scope_lookup_honours_expiry() {
let (conn, _, bob) = setup();
database::create_api_token(&conn, bob, "hr", "t", None, "read").unwrap();
let past = (Utc::now() - chrono::Duration::days(1)).to_rfc3339();
database::create_api_token(&conn, bob, "hx", "t", Some(&past), "read").unwrap();
assert_eq!(token_scope_for_hash(&conn, "hr").unwrap().as_deref(), Some("read"));
assert_eq!(token_scope_for_hash(&conn, "hx").unwrap(), None);
assert_eq!(token_scope_for_hash(&conn, "nope").unwrap(), None);
}
#[test]
fn role_slugs_follow_bit_order() {
let (conn, owner, bob) = setup();
assert_eq!(list_user_role_slugs(&conn, owner).unwrap(), ["user", "admin", "owner"]);
assert_eq!(list_user_role_slugs(&conn, bob).unwrap(), ["user"]);
conn.execute("DELETE FROM user_roles WHERE user_id = ?1", [bob]).unwrap();
assert_eq!(list_user_role_slugs(&conn, bob).unwrap(), ["guest"]);
}
}

View file

@ -6,7 +6,10 @@ use axum_extra::extract::CookieJar;
use rand::RngCore;
use crate::routes::{ApiError, AppState};
use archivr_core::database;
use archivr_core::{auth_credentials, database};
/// Minimum seconds between `api_tokens.last_used_at` writes for one token.
const TOKEN_TOUCH_INTERVAL_SECS: i64 = 60;
// Role bit constants
pub const ROLE_GUEST: u32 = 1; // bit 0
@ -81,10 +84,16 @@ impl FromRequestParts<AppState> for AuthUser {
if let Some(raw_token) = header_str.strip_prefix("Bearer ") {
let token_hash = hash_token(raw_token);
if let Ok(conn) = database::open_auth_db(auth_db_path) {
if let Ok(Some((user_id, _token_uid))) =
if let Ok(Some((user_id, token_uid))) =
database::get_user_for_token(&conn, &token_hash)
{
if let Ok(role_bits) = database::compute_role_bits(&conn, user_id) {
// Throttled: writes last_used_at at most once per 60s per token.
let _ = auth_credentials::touch_token_throttled(
&conn,
&token_uid,
TOKEN_TOUCH_INTERVAL_SECS,
);
return Ok(AuthUser::Authenticated { user_id, role_bits });
}
}

View file

@ -1,7 +1,821 @@
use axum::Router;
//! Credential management endpoints: own sessions (S1-S3) and the admin
//! password / session / API token operations on other users (U2-U5).
//! T1/T2/M1 live in `routes.rs` because they extend existing handlers.
use axum::{
Json, Router,
extract::{Path, State},
http::StatusCode,
routing::{delete, get, post},
};
use axum_extra::extract::CookieJar;
use rusqlite::Connection;
use crate::routes::AppState;
use crate::auth::{self, AuthUser, ROLE_ADMIN};
use crate::guards::{ensure_can_manage, ensure_not_self};
use crate::routes::{ApiError, AppState};
use archivr_core::{auth_credentials, database};
pub fn routes() -> Router<AppState> {
Router::new()
.route(
"/api/auth/sessions",
get(list_sessions).delete(revoke_other_sessions),
)
.route("/api/auth/sessions/:handle", delete(revoke_session))
.route("/api/admin/users/:uid/password", post(admin_reset_password))
.route("/api/admin/users/:uid/sessions", delete(admin_revoke_sessions))
.route("/api/admin/users/:uid/tokens", get(admin_list_tokens))
.route(
"/api/admin/users/:uid/tokens/:token_uid",
delete(admin_revoke_token),
)
}
/// Value of the caller's `session` cookie, if any.
fn cookie_session_uid(jar: &CookieJar) -> Option<&str> {
jar.get("session").map(|c| c.value())
}
async fn list_sessions(
State(state): State<AppState>,
auth_user: AuthUser,
jar: CookieJar,
) -> Result<Json<serde_json::Value>, ApiError> {
let (user_id, _) = auth_user.require_auth()?;
let conn = database::open_auth_db(&state.auth_db_path)?;
let current = cookie_session_uid(&jar).map(auth_credentials::session_handle);
let rows: Vec<serde_json::Value> = auth_credentials::list_user_sessions(&conn, user_id)?
.into_iter()
.map(|s| {
let is_current = current.as_deref() == Some(s.session_handle.as_str());
serde_json::json!({
"session_handle": s.session_handle,
"created_at": s.created_at,
"last_seen_at": s.last_seen_at,
"expires_at": s.expires_at,
"user_agent": s.user_agent,
"current": is_current,
})
})
.collect();
Ok(Json(serde_json::Value::Array(rows)))
}
async fn revoke_session(
State(state): State<AppState>,
auth_user: AuthUser,
Path(handle): Path<String>,
) -> Result<StatusCode, ApiError> {
let (user_id, _) = auth_user.require_auth()?;
let conn = database::open_auth_db(&state.auth_db_path)?;
if auth_credentials::delete_user_session_by_handle(&conn, user_id, &handle)? {
Ok(StatusCode::NO_CONTENT)
} else {
Err(ApiError::not_found("session not found"))
}
}
async fn revoke_other_sessions(
State(state): State<AppState>,
auth_user: AuthUser,
jar: CookieJar,
) -> Result<Json<serde_json::Value>, ApiError> {
let (user_id, _) = auth_user.require_auth()?;
let conn = database::open_auth_db(&state.auth_db_path)?;
// On Bearer requests the cookie (if any) is not one of this user's live
// sessions, so nothing is spared.
let revoked =
auth_credentials::delete_other_sessions(&conn, user_id, cookie_session_uid(&jar))?;
Ok(Json(serde_json::json!({ "revoked": revoked })))
}
/// Shared prefix of the admin target endpoints: role check, target lookup
/// (404), optional self-guard (409), can-manage (403), in the spec's order.
/// Returns the target's integer id.
fn resolve_target(
conn: &Connection,
auth_user: &AuthUser,
target_uid: &str,
self_guard: bool,
) -> Result<i64, ApiError> {
auth_user.require_role(ROLE_ADMIN)?;
let (caller_id, caller_bits) = auth_user.require_auth()?;
let target_id = database::get_user_id_by_uid(conn, target_uid)?
.ok_or_else(|| ApiError::not_found("user not found"))?;
if self_guard {
ensure_not_self(caller_id, target_id)?;
}
ensure_can_manage(caller_bits, database::compute_role_bits(conn, target_id)?)?;
Ok(target_id)
}
#[derive(Debug, serde::Deserialize)]
struct ResetPasswordBody {
new_password: String,
#[serde(default)]
revoke_tokens: bool,
}
async fn admin_reset_password(
State(state): State<AppState>,
auth_user: AuthUser,
Path(uid): Path<String>,
Json(body): Json<ResetPasswordBody>,
) -> Result<Json<serde_json::Value>, ApiError> {
let conn = database::open_auth_db(&state.auth_db_path)?;
let target_id = resolve_target(&conn, &auth_user, &uid, true)?;
if body.new_password.trim().is_empty() {
return Err(ApiError::bad_request("new_password must not be blank"));
}
if body.new_password.chars().count() < 8 {
return Err(ApiError::bad_request(
"new_password must be at least 8 characters",
));
}
let new_hash = auth::hash_password(&body.new_password).map_err(ApiError::from)?;
let (sessions_revoked, tokens_revoked) =
auth_credentials::reset_user_password(&conn, target_id, &new_hash, body.revoke_tokens)?;
Ok(Json(serde_json::json!({
"user_uid": uid,
"sessions_revoked": sessions_revoked,
"tokens_revoked": tokens_revoked,
})))
}
async fn admin_revoke_sessions(
State(state): State<AppState>,
auth_user: AuthUser,
Path(uid): Path<String>,
) -> Result<Json<serde_json::Value>, ApiError> {
let conn = database::open_auth_db(&state.auth_db_path)?;
let target_id = resolve_target(&conn, &auth_user, &uid, true)?;
let revoked = database::invalidate_user_sessions(&conn, target_id)?;
Ok(Json(serde_json::json!({ "revoked": revoked })))
}
async fn admin_list_tokens(
State(state): State<AppState>,
auth_user: AuthUser,
Path(uid): Path<String>,
) -> Result<Json<Vec<database::ApiTokenRecord>>, ApiError> {
let conn = database::open_auth_db(&state.auth_db_path)?;
let target_id = resolve_target(&conn, &auth_user, &uid, false)?;
Ok(Json(database::list_user_tokens(&conn, target_id)?))
}
async fn admin_revoke_token(
State(state): State<AppState>,
auth_user: AuthUser,
Path((uid, token_uid)): Path<(String, String)>,
) -> Result<StatusCode, ApiError> {
let conn = database::open_auth_db(&state.auth_db_path)?;
let target_id = resolve_target(&conn, &auth_user, &uid, false)?;
if database::delete_api_token(&conn, &token_uid, target_id)? {
Ok(StatusCode::NO_CONTENT)
} else {
Err(ApiError::not_found("token not found"))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::registry::ServerRegistry;
use crate::routes::app;
use crate::test_support::*;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use serde_json::{Value, json};
use std::path::PathBuf;
use tower::ServiceExt;
struct Env {
_dir: tempfile::TempDir,
registry: ServerRegistry,
auth: PathBuf,
}
impl Env {
fn new() -> Self {
let dir = tempfile::tempdir().unwrap();
let (registry, _, auth) = make_test_registry(&dir);
Env { _dir: dir, registry, auth }
}
/// `who`: a `session=...` cookie string, or `Bearer:<raw>` for a token.
async fn call(
&self,
method: &str,
uri: &str,
who: Option<&str>,
body: Option<Value>,
) -> (StatusCode, Value) {
let mut b = Request::builder().method(method).uri(uri);
if let Some(w) = who {
b = match w.strip_prefix("Bearer:") {
Some(tok) => b.header("authorization", format!("Bearer {tok}")),
None => b.header("cookie", w),
};
}
let req = match body {
Some(v) => b.header("content-type", "application/json").body(json_body(&v)),
None => b.body(Body::empty()),
}
.unwrap();
let resp = app(self.registry.clone(), self.auth.clone())
.oneshot(req)
.await
.unwrap();
let status = resp.status();
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
let value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
(status, value)
}
fn conn(&self) -> rusqlite::Connection {
database::open_auth_db(&self.auth).unwrap()
}
fn user_id(&self, username: &str) -> i64 {
self.conn()
.query_row("SELECT id FROM users WHERE username = ?1", [username], |r| r.get(0))
.unwrap()
}
fn user_uid(&self, username: &str) -> String {
database::get_user_uid(&self.conn(), self.user_id(username)).unwrap().unwrap()
}
/// A user with a real argon2 password hash; returns their user_uid.
fn real_user(&self, username: &str, password: &str, roles: &[&str]) -> String {
let conn = self.conn();
let owner = self.user_id("testowner");
let hash = auth::hash_password(password).unwrap();
let uid = database::create_user(&conn, username, None, &hash, owner).unwrap();
let id = database::get_user_id_by_uid(&conn, &uid).unwrap().unwrap();
for r in roles {
database::assign_role(&conn, id, r, owner).unwrap();
}
uid
}
fn new_session(&self, username: &str) -> String {
let conn = self.conn();
let id = self.user_id(username);
let bits = database::compute_role_bits(&conn, id).unwrap();
format!(
"session={}",
database::create_session(&conn, id, bits, Some("test-agent")).unwrap()
)
}
fn session_alive(&self, cookie: &str) -> bool {
let uid = cookie.strip_prefix("session=").unwrap();
database::get_session(&self.conn(), uid).unwrap().is_some()
}
}
fn token_uid_of(env: &Env, username: &str) -> String {
let id = env.user_id(username);
database::list_user_tokens(&env.conn(), id).unwrap()[0].token_uid.clone()
}
fn handle_of(cookie: &str) -> String {
auth_credentials::session_handle(cookie.strip_prefix("session=").unwrap())
}
// ---- S1-S3 ----
#[tokio::test]
async fn sessions_list_flags_current_and_never_leaks_session_uid() {
let env = Env::new();
let owner = owner_session(&env.auth);
let second = env.new_session("testowner");
let (st, _) = env.call("GET", "/api/auth/sessions", None, None).await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
let (st, body) = env.call("GET", "/api/auth/sessions", Some(&owner), None).await;
assert_eq!(st, StatusCode::OK);
let rows = body.as_array().unwrap();
assert_eq!(rows.len(), 2);
let currents: Vec<_> = rows.iter().filter(|r| r["current"] == true).collect();
assert_eq!(currents.len(), 1);
assert_eq!(currents[0]["session_handle"], handle_of(&owner));
let other = rows.iter().find(|r| r["current"] == false).unwrap();
assert_eq!(other["session_handle"], handle_of(&second));
assert_eq!(other["user_agent"], "test-agent");
for r in rows {
let keys: std::collections::BTreeSet<_> =
r.as_object().unwrap().keys().map(String::as_str).collect();
assert_eq!(
keys,
[
"created_at",
"current",
"expires_at",
"last_seen_at",
"session_handle",
"user_agent"
]
.into_iter()
.collect()
);
assert_eq!(r["session_handle"].as_str().unwrap().len(), 16);
}
// No raw session_uid anywhere in the response text.
let text = body.to_string();
for cookie in [&owner, &second] {
assert!(!text.contains(cookie.strip_prefix("session=").unwrap()));
}
// Bearer request: no row is "current".
let tok = make_api_token(&env.auth, "testowner", None, "full");
let (st, body) = env
.call("GET", "/api/auth/sessions", Some(&format!("Bearer:{tok}")), None)
.await;
assert_eq!(st, StatusCode::OK);
assert!(body.as_array().unwrap().iter().all(|r| r["current"] == false));
for cookie in [&owner, &second] {
assert!(!body.to_string().contains(cookie.strip_prefix("session=").unwrap()));
}
}
#[tokio::test]
async fn sessions_list_only_the_callers_own_sessions() {
let env = Env::new();
let owner = owner_session(&env.auth);
let user = user_session(&env.auth);
let (_, body) = env.call("GET", "/api/auth/sessions", Some(&user), None).await;
assert_eq!(body.as_array().unwrap().len(), 1);
assert_eq!(body[0]["session_handle"], handle_of(&user));
assert!(!body.to_string().contains(&handle_of(&owner)));
}
#[tokio::test]
async fn revoke_session_by_handle_kills_that_cookie() {
let env = Env::new();
let owner = owner_session(&env.auth);
let other = env.new_session("testowner");
let user = user_session(&env.auth);
let uri = |c: &str| format!("/api/auth/sessions/{}", handle_of(c));
let (st, _) = env.call("DELETE", &uri(&other), None, None).await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
// Another user's handle, and an unknown one: 404, nothing deleted.
for u in [uri(&user), "/api/auth/sessions/0000000000000000".to_string()] {
let (st, _) = env.call("DELETE", &u, Some(&owner), None).await;
assert_eq!(st, StatusCode::NOT_FOUND);
}
assert!(env.session_alive(&user));
let (st, _) = env.call("DELETE", &uri(&other), Some(&owner), None).await;
assert_eq!(st, StatusCode::NO_CONTENT);
assert!(!env.session_alive(&other));
let (st, _) = env.call("GET", "/api/auth/me", Some(&other), None).await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
assert!(env.session_alive(&owner));
// Deleting the current session is allowed (logout equivalent).
let (st, _) = env.call("DELETE", &uri(&owner), Some(&owner), None).await;
assert_eq!(st, StatusCode::NO_CONTENT);
assert!(!env.session_alive(&owner));
}
#[tokio::test]
async fn revoke_other_sessions_spares_current_cookie_but_not_for_bearer() {
let env = Env::new();
let owner = owner_session(&env.auth);
let a = env.new_session("testowner");
let b = env.new_session("testowner");
let user = user_session(&env.auth);
let (st, _) = env.call("DELETE", "/api/auth/sessions", None, None).await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
let (st, body) = env.call("DELETE", "/api/auth/sessions", Some(&owner), None).await;
assert_eq!(st, StatusCode::OK);
assert_eq!(body, json!({"revoked": 2}));
assert!(env.session_alive(&owner) && !env.session_alive(&a) && !env.session_alive(&b));
assert!(env.session_alive(&user));
let tok = make_api_token(&env.auth, "testowner", None, "full");
let (st, body) = env
.call("DELETE", "/api/auth/sessions", Some(&format!("Bearer:{tok}")), None)
.await;
assert_eq!(st, StatusCode::OK);
assert_eq!(body, json!({"revoked": 1}));
assert!(!env.session_alive(&owner));
}
// ---- U2-U5 ----
/// Runs `method /api/admin/users/<uid><tail>` as every caller class and
/// checks the guard ladder against a plain-user target. Returns the env
/// (users `test-admin`, `admin2`, `test-user`, `test-guest`, owner exist).
async fn check_guards(method: &str, tail: &str, body: Option<Value>, self_guard: bool) -> Env {
let env = Env::new();
let owner = owner_session(&env.auth);
let admin = admin_session(&env.auth);
let user = user_session(&env.auth);
let guest = guest_session(&env.auth);
make_role_session(&env.auth, "admin2", &["admin"]);
let target = env.user_uid("test-user");
let uri = |uid: &str| format!("/api/admin/users/{uid}{tail}");
let (st, _) = env.call(method, &uri(&target), None, body.clone()).await;
assert_eq!(st, StatusCode::UNAUTHORIZED, "guest");
for (who, name) in [(&user, "user"), (&guest, "guest-role")] {
let (st, _) = env.call(method, &uri(&target), Some(who), body.clone()).await;
assert_eq!(st, StatusCode::FORBIDDEN, "{name}");
}
let (st, _) = env.call(method, &uri("usr_nope"), Some(&admin), body.clone()).await;
assert_eq!(st, StatusCode::NOT_FOUND, "unknown target");
// Admin vs owner and admin vs another admin: 403.
for t in ["testowner", "admin2"] {
let (st, v) = env
.call(method, &uri(&env.user_uid(t)), Some(&admin), body.clone())
.await;
assert_eq!(st, StatusCode::FORBIDDEN, "admin vs {t}: {v}");
}
// Self: 409 (for an admin that beats the 403 can-manage check).
if self_guard {
for (who, name) in [(&admin, "test-admin"), (&owner, "testowner")] {
let (st, v) = env
.call(method, &uri(&env.user_uid(name)), Some(who), body.clone())
.await;
assert_eq!(st, StatusCode::CONFLICT, "self {name}: {v}");
}
}
env
}
#[tokio::test]
async fn admin_password_guards_and_validation() {
let body = json!({"new_password": "longenough"});
let env = check_guards("POST", "/password", Some(body.clone()), true).await;
let admin = env.new_session("test-admin");
let target = env.user_uid("test-user");
let uri = format!("/api/admin/users/{target}/password");
for bad in [json!({"new_password": "short"}), json!({"new_password": " "})] {
let (st, _) = env.call("POST", &uri, Some(&admin), Some(bad)).await;
assert_eq!(st, StatusCode::BAD_REQUEST);
}
// Owner may reset an admin's password.
let owner = owner_session(&env.auth);
let admin_uid = env.user_uid("admin2");
let (st, v) = env
.call(
"POST",
&format!("/api/admin/users/{admin_uid}/password"),
Some(&owner),
Some(body),
)
.await;
assert_eq!(st, StatusCode::OK, "{v}");
}
#[tokio::test]
async fn admin_password_reset_logs_in_with_new_password_and_kills_sessions() {
let env = Env::new();
let admin = admin_session(&env.auth);
let uid = env.real_user("victim", "old-password", &["user"]);
let old_session = env.new_session("victim");
let tok = make_api_token(&env.auth, "victim", None, "full");
let pw_uri = format!("/api/admin/users/{uid}/password");
// Without revoke_tokens: sessions die, tokens survive.
let (st, v) = env
.call("POST", &pw_uri, Some(&admin), Some(json!({"new_password": "brand-new-pw"})))
.await;
assert_eq!(st, StatusCode::OK);
assert_eq!(v, json!({"user_uid": uid, "sessions_revoked": 1, "tokens_revoked": 0}));
assert!(!env.session_alive(&old_session));
let (st, _) = env.call("GET", "/api/auth/me", Some(&old_session), None).await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
let bearer = format!("Bearer:{tok}");
let (st, _) = env.call("GET", "/api/auth/me", Some(&bearer), None).await;
assert_eq!(st, StatusCode::OK);
let login = |pw: &str| json!({"username": "victim", "password": pw});
let (st, _) = env
.call("POST", "/api/auth/login", None, Some(login("old-password")))
.await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
let (st, _) = env
.call("POST", "/api/auth/login", None, Some(login("brand-new-pw")))
.await;
assert_eq!(st, StatusCode::OK);
// With revoke_tokens: the token dies too.
let (st, v) = env
.call(
"POST",
&pw_uri,
Some(&admin),
Some(json!({"new_password": "another-pw-1", "revoke_tokens": true})),
)
.await;
assert_eq!(st, StatusCode::OK);
assert_eq!(v["tokens_revoked"], 1);
assert_eq!(v["sessions_revoked"], 1, "the login above made one session");
let (st, _) = env.call("GET", "/api/auth/me", Some(&bearer), None).await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn admin_revoke_sessions_guards_and_ok() {
let env = check_guards("DELETE", "/sessions", None, true).await;
let admin = env.new_session("test-admin");
let target = env.user_uid("test-user");
let s1 = env.new_session("test-user");
let (st, v) = env
.call("DELETE", &format!("/api/admin/users/{target}/sessions"), Some(&admin), None)
.await;
assert_eq!(st, StatusCode::OK);
assert!(v["revoked"].as_u64().unwrap() >= 2, "{v}");
assert!(!env.session_alive(&s1));
}
#[tokio::test]
async fn admin_list_tokens_guards_and_ok() {
let env = check_guards("GET", "/tokens", None, false).await;
let admin = env.new_session("test-admin");
make_api_token(&env.auth, "test-user", None, "read");
let target = env.user_uid("test-user");
let (st, v) = env
.call("GET", &format!("/api/admin/users/{target}/tokens"), Some(&admin), None)
.await;
assert_eq!(st, StatusCode::OK);
let rows = v.as_array().unwrap();
assert_eq!(rows.len(), 1);
let keys: std::collections::BTreeSet<_> =
rows[0].as_object().unwrap().keys().map(String::as_str).collect();
assert_eq!(
keys,
["created_at", "expires_at", "last_used_at", "name", "scope", "token_uid"]
.into_iter()
.collect()
);
assert_eq!(rows[0]["scope"], "read");
assert!(!v.to_string().contains("token_hash"));
// No self-guard here (spec: can-manage only): an owner may list their own.
let owner = owner_session(&env.auth);
let me = env.user_uid("testowner");
let (st, _) = env
.call("GET", &format!("/api/admin/users/{me}/tokens"), Some(&owner), None)
.await;
assert_eq!(st, StatusCode::OK);
}
#[tokio::test]
async fn admin_revoke_token_guards_ok_and_ownership() {
let env = Env::new();
let admin = admin_session(&env.auth);
let user = user_session(&env.auth);
make_role_session(&env.auth, "other", &["user"]);
let raw = make_api_token(&env.auth, "test-user", None, "full");
make_api_token(&env.auth, "other", None, "full");
let target = env.user_uid("test-user");
let tok_uid = token_uid_of(&env, "test-user");
let other_tok = token_uid_of(&env, "other");
let uri = |u: &str, t: &str| format!("/api/admin/users/{u}/tokens/{t}");
let (st, _) = env.call("DELETE", &uri(&target, &tok_uid), None, None).await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
let (st, _) = env.call("DELETE", &uri(&target, &tok_uid), Some(&user), None).await;
assert_eq!(st, StatusCode::FORBIDDEN);
let (st, _) = env.call("DELETE", &uri("usr_nope", &tok_uid), Some(&admin), None).await;
assert_eq!(st, StatusCode::NOT_FOUND);
// Admin vs owner target: 403.
let owner_uid = env.user_uid("testowner");
let (st, _) = env.call("DELETE", &uri(&owner_uid, &tok_uid), Some(&admin), None).await;
assert_eq!(st, StatusCode::FORBIDDEN);
// A token owned by someone else, or unknown: 404, and it survives.
for t in [other_tok.as_str(), "tok_nope"] {
let (st, _) = env.call("DELETE", &uri(&target, t), Some(&admin), None).await;
assert_eq!(st, StatusCode::NOT_FOUND);
}
assert_eq!(database::list_user_tokens(&env.conn(), env.user_id("other")).unwrap().len(), 1);
let bearer = format!("Bearer:{raw}");
let (st, _) = env.call("GET", "/api/auth/me", Some(&bearer), None).await;
assert_eq!(st, StatusCode::OK);
let (st, _) = env.call("DELETE", &uri(&target, &tok_uid), Some(&admin), None).await;
assert_eq!(st, StatusCode::NO_CONTENT);
let (st, _) = env.call("GET", "/api/auth/me", Some(&bearer), None).await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
}
// ---- T1/T2/M1, touch, scope ----
#[tokio::test]
async fn create_token_options_validation_and_listing() {
let env = Env::new();
let owner = owner_session(&env.auth);
let (st, _) = env
.call("POST", "/api/auth/tokens", None, Some(json!({"name": "x"})))
.await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
// Omitted options keep the old behaviour (full, never expires).
let (st, v) = env
.call("POST", "/api/auth/tokens", Some(&owner), Some(json!({"name": "plain"})))
.await;
assert_eq!(st, StatusCode::CREATED);
assert_eq!(v["scope"], "full");
assert_eq!(v["name"], "plain");
assert_eq!(v["expires_at"], Value::Null);
assert!(v["raw_token"].as_str().is_some() && v["token_uid"].as_str().is_some());
for bad in [
json!({"name": " "}),
json!({"name": "x", "expires_in_days": 0}),
json!({"name": "x", "expires_in_days": 3651}),
json!({"name": "x", "expires_in_days": -1}),
json!({"name": "x", "scope": "admin"}),
] {
let (st, _) = env
.call("POST", "/api/auth/tokens", Some(&owner), Some(bad.clone()))
.await;
assert_eq!(st, StatusCode::BAD_REQUEST, "{bad}");
}
let (st, v) = env
.call(
"POST",
"/api/auth/tokens",
Some(&owner),
Some(json!({"name": "ro", "expires_in_days": 30, "scope": "read"})),
)
.await;
assert_eq!(st, StatusCode::CREATED);
assert_eq!(v["scope"], "read");
let exp = chrono::DateTime::parse_from_rfc3339(v["expires_at"].as_str().unwrap()).unwrap();
let days = (exp.with_timezone(&chrono::Utc) - chrono::Utc::now()).num_days();
assert!((29..=30).contains(&days), "{days}");
let raw = v["raw_token"].as_str().unwrap().to_string();
let (st, _) = env
.call("GET", "/api/auth/me", Some(&format!("Bearer:{raw}")), None)
.await;
assert_eq!(st, StatusCode::OK);
let (st, list) = env.call("GET", "/api/auth/tokens", Some(&owner), None).await;
assert_eq!(st, StatusCode::OK);
let rows = list.as_array().unwrap();
assert_eq!(rows.len(), 2);
for r in rows {
for k in ["token_uid", "name", "created_at", "last_used_at", "expires_at", "scope"] {
assert!(r.get(k).is_some(), "missing {k}");
}
}
assert!(!list.to_string().contains(&raw));
}
#[tokio::test]
async fn backdated_token_expiry_is_401_through_the_router() {
let env = Env::new();
let past = (chrono::Utc::now() - chrono::Duration::days(1)).to_rfc3339();
let expired = make_api_token(&env.auth, "testowner", Some(&past), "full");
let (st, _) = env
.call("GET", "/api/auth/me", Some(&format!("Bearer:{expired}")), None)
.await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
let future = (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339();
let ok = make_api_token(&env.auth, "testowner", Some(&future), "full");
let (st, _) = env
.call("GET", "/api/auth/me", Some(&format!("Bearer:{ok}")), None)
.await;
assert_eq!(st, StatusCode::OK);
}
#[tokio::test]
async fn bearer_use_sets_last_used_at_throttled() {
let env = Env::new();
let raw = make_api_token(&env.auth, "testowner", None, "full");
let tok_uid = token_uid_of(&env, "testowner");
let last_used = |env: &Env| -> Option<String> {
env.conn()
.query_row(
"SELECT last_used_at FROM api_tokens WHERE token_uid = ?1",
[&tok_uid],
|r| r.get(0),
)
.unwrap()
};
assert_eq!(last_used(&env), None);
let bearer = format!("Bearer:{raw}");
env.call("GET", "/api/auth/me", Some(&bearer), None).await;
let first = last_used(&env).expect("last_used_at set after a Bearer call");
env.call("GET", "/api/auth/me", Some(&bearer), None).await;
assert_eq!(last_used(&env).unwrap(), first, "second call within 60s is throttled");
// After 60s it is refreshed.
let old = (chrono::Utc::now() - chrono::Duration::seconds(120)).to_rfc3339();
env.conn()
.execute("UPDATE api_tokens SET last_used_at = ?1", [&old])
.unwrap();
env.call("GET", "/api/auth/me", Some(&bearer), None).await;
assert_ne!(last_used(&env).unwrap(), old);
// Visible via T2.
let owner = owner_session(&env.auth);
let (_, list) = env.call("GET", "/api/auth/tokens", Some(&owner), None).await;
assert!(list[0]["last_used_at"].is_string());
}
#[tokio::test]
async fn read_scope_token_cannot_mutate_but_can_read() {
let env = Env::new();
let owner = owner_session(&env.auth);
let ro = format!("Bearer:{}", make_api_token(&env.auth, "testowner", None, "read"));
let full = format!("Bearer:{}", make_api_token(&env.auth, "testowner", None, "full"));
let (st, _) = env.call("GET", "/api/auth/me", Some(&ro), None).await;
assert_eq!(st, StatusCode::OK);
let (st, _) = env.call("GET", "/api/auth/tokens", Some(&ro), None).await;
assert_eq!(st, StatusCode::OK);
let attempts = [
("POST", "/api/auth/tokens", Some(json!({"name": "escalate"}))),
("DELETE", "/api/auth/tokens/tok_x", None),
("PATCH", "/api/auth/me", Some(json!({"display_name": "x"}))),
("DELETE", "/api/auth/sessions", None),
(
"POST",
"/api/archives/test/captures",
Some(json!({"locator": "local:/x"})),
),
];
for (m, uri, body) in attempts {
let (st, v) = env.call(m, uri, Some(&ro), body).await;
assert_eq!(st, StatusCode::FORBIDDEN, "{m} {uri}");
assert_eq!(v["error"], "read-only token");
}
let (_, list) = env.call("GET", "/api/auth/tokens", Some(&owner), None).await;
assert_eq!(list.as_array().unwrap().len(), 2, "no token was created");
// Full tokens and cookie sessions are unaffected.
let (st, _) = env
.call("POST", "/api/auth/tokens", Some(&full), Some(json!({"name": "ok"})))
.await;
assert_eq!(st, StatusCode::CREATED);
let (st, _) = env
.call("POST", "/api/auth/tokens", Some(&owner), Some(json!({"name": "ok2"})))
.await;
assert_eq!(st, StatusCode::CREATED);
// An unauthenticated mutation is still 401, not 403.
let (st, _) = env
.call(
"POST",
"/api/auth/tokens",
Some("Bearer:garbage"),
Some(json!({"name": "x"})),
)
.await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn auth_me_reports_user_uid_and_roles() {
let env = Env::new();
let owner = owner_session(&env.auth);
let admin = admin_session(&env.auth);
let (st, v) = env.call("GET", "/api/auth/me", Some(&owner), None).await;
assert_eq!(st, StatusCode::OK);
assert_eq!(v["user_uid"], env.user_uid("testowner"));
assert_eq!(v["roles"], json!(["user", "admin", "owner"]));
assert!(v["role_bits"].is_u64() && v["username"] == "testowner");
let (_, v) = env.call("GET", "/api/auth/me", Some(&admin), None).await;
assert_eq!(v["roles"], json!(["user", "admin"]));
}
// ---- patch_me ----
#[tokio::test]
async fn patch_me_password_rules_and_session_invalidation() {
let env = Env::new();
env.real_user("pat", "old-password", &["user"]);
let current = env.new_session("pat");
let other = env.new_session("pat");
let patch = |new: &str| json!({"current_password": "old-password", "new_password": new});
let (st, _) = env
.call("PATCH", "/api/auth/me", Some(&current), Some(patch("short")))
.await;
assert_eq!(st, StatusCode::BAD_REQUEST);
assert!(env.session_alive(&other), "rejected change must not touch sessions");
let (st, _) = env
.call("PATCH", "/api/auth/me", Some(&current), Some(patch("new-password-1")))
.await;
assert_eq!(st, StatusCode::NO_CONTENT);
assert!(env.session_alive(&current));
assert!(!env.session_alive(&other));
let (st, _) = env
.call(
"POST",
"/api/auth/login",
None,
Some(json!({"username": "pat", "password": "new-password-1"})),
)
.await;
assert_eq!(st, StatusCode::OK);
}
}

View file

@ -435,6 +435,10 @@ pub fn app_with_state(state: AppState) -> Router {
.merge(crate::jobs::routes())
.merge(crate::effective_config::routes())
.fallback_service(ServeDir::new(&static_dir).not_found_service(ServeFile::new(static_dir.join("index.html"))))
.layer(axum::middleware::from_fn_with_state(
state.clone(),
crate::token_scope::enforce_read_scope,
))
.layer(axum::middleware::from_fn_with_state(
state.clone(),
setup_guard,
@ -1540,6 +1544,10 @@ struct SetupBody {
#[derive(Debug, serde::Deserialize)]
struct CreateTokenBody {
name: String,
/// 1..=3650; absent/null = never expires.
expires_in_days: Option<i64>,
/// `full` (default) or `read`.
scope: Option<String>,
}
#[derive(Debug, serde::Deserialize)]
@ -2378,7 +2386,11 @@ async fn auth_me(
.map_err(|e| ApiError::from(anyhow::anyhow!("db error: {e}")))?;
let humanize_slugs = humanize_slugs_int != 0;
let settings = database::get_instance_settings(&conn)?;
let user_uid = database::get_user_uid(&conn, user_id)?;
let roles = archivr_core::auth_credentials::list_user_role_slugs(&conn, user_id)?;
Ok(Json(serde_json::json!({
"user_uid": user_uid,
"roles": roles,
"role_bits": role_bits,
"username": username,
"display_name": display_name,
@ -2390,6 +2402,7 @@ async fn auth_me(
async fn patch_me(
State(state): State<AppState>,
auth_user: AuthUser,
jar: CookieJar,
Json(body): Json<UpdateProfileBody>,
) -> Result<StatusCode, ApiError> {
let (user_id, _) = auth_user.require_auth()?;
@ -2405,8 +2418,19 @@ async fn patch_me(
if !auth::verify_password(current_pw, &hash).map_err(ApiError::from)? {
return Err(ApiError::unauthorized("current password is incorrect"));
}
if new_pw.chars().count() < 8 {
return Err(ApiError::bad_request(
"new_password must be at least 8 characters",
));
}
let new_hash = auth::hash_password(new_pw).map_err(ApiError::from)?;
database::update_user_password(&conn, user_id, &new_hash)?;
// Every other session is stale now; the caller's own cookie session survives.
archivr_core::auth_credentials::delete_other_sessions(
&conn,
user_id,
jar.get("session").map(|c| c.value()),
)?;
}
if let Some(ref dn) = body.display_name {
@ -2956,16 +2980,40 @@ async fn create_token(
if body.name.trim().is_empty() {
return Err(ApiError::bad_request("token name is required"));
}
let scope = body.scope.as_deref().unwrap_or("full");
if scope != "full" && scope != "read" {
return Err(ApiError::bad_request("scope must be 'full' or 'read'"));
}
let expires_at = match body.expires_in_days {
None => None,
Some(days) if (1..=3650).contains(&days) => Some(
(chrono::Utc::now() + chrono::Duration::days(days)).to_rfc3339(),
),
Some(_) => {
return Err(ApiError::bad_request(
"expires_in_days must be between 1 and 3650",
));
}
};
let raw_token = auth::generate_token();
let token_hash = auth::hash_token(&raw_token);
let conn = database::open_auth_db(&state.auth_db_path)?;
let token_uid = database::create_api_token(&conn, user_id, &token_hash, &body.name, None, "full")?;
let token_uid = database::create_api_token(
&conn,
user_id,
&token_hash,
&body.name,
expires_at.as_deref(),
scope,
)?;
Ok((
StatusCode::CREATED,
Json(serde_json::json!({
"token_uid": token_uid,
"raw_token": raw_token,
"name": body.name,
"expires_at": expires_at,
"scope": scope,
})),
))
}

View file

@ -1,25 +1,53 @@
//! Read-scope API token enforcement: Bearer requests from `scope = 'read'`
//! tokens get 403 on anything but GET/HEAD. Stub: the credentials stream
//! implements `enforce_read_scope` and wires it as a layer in `app_with_state`.
#![allow(dead_code)] // not wired yet
//! Read-scope API token enforcement: Bearer requests authenticated by a token
//! with `scope = 'read'` get 403 on anything but GET/HEAD/OPTIONS. Cookie
//! sessions are unaffected. Wired as a layer in `app_with_state`.
use axum::{
Router,
extract::{Request, State},
http::Method,
middleware::Next,
response::Response,
response::{IntoResponse, Response},
};
use axum_extra::extract::CookieJar;
use crate::routes::AppState;
use crate::auth::hash_token;
use crate::routes::{ApiError, AppState};
use archivr_core::{auth_credentials, database};
pub fn routes() -> Router<AppState> {
Router::new()
}
/// Middleware stub: currently a pass-through.
/// Rejects mutating requests authenticated by a read-scope Bearer token.
///
/// The token is only resolved for non-safe methods, so reads cost nothing
/// extra. A valid session cookie wins over a Bearer header (same precedence
/// as the `AuthUser` extractor), so cookie requests are never affected.
pub async fn enforce_read_scope(
State(_state): State<AppState>,
State(state): State<AppState>,
req: Request,
next: Next,
) -> Response {
if matches!(*req.method(), Method::GET | Method::HEAD | Method::OPTIONS) {
return next.run(req).await;
}
let raw_token = req
.headers()
.get("Authorization")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "));
if let Some(raw_token) = raw_token {
if let Ok(conn) = database::open_auth_db(&state.auth_db_path) {
let jar = CookieJar::from_headers(req.headers());
let cookie_session_valid = jar
.get("session")
.map(|c| matches!(database::get_session(&conn, c.value()), Ok(Some(_))))
.unwrap_or(false);
if !cookie_session_valid {
if let Ok(Some(scope)) =
auth_credentials::token_scope_for_hash(&conn, &hash_token(raw_token))
{
if scope == "read" {
return ApiError::forbidden("read-only token").into_response();
}
}
}
}
}
next.run(req).await
}