mirror of
https://github.com/thegeneralist01/archivr
synced 2026-12-04 18:56:44 +01:00
feat: R0 foundation for MCP API extensions
Schema: capture_jobs.created_by (+index) and api_tokens.scope migrations; create_api_token takes expiry/scope, get_user_for_token returns token_uid, create_capture_job_as, get_user_uid. Module stubs for the R1-R4 streams merged into app_with_state, implemented guards.rs, test_support helpers, pub(crate) route helpers, and the contract spec. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2f58aeff6a
commit
b2b746af49
16 changed files with 930 additions and 29 deletions
2
crates/archivr-core/src/auth_credentials.rs
Normal file
2
crates/archivr-core/src/auth_credentials.rs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
//! Auth-DB credential helpers (session listing/revocation, token scope).
|
||||
//! Stub: filled in by the credentials stream.
|
||||
2
crates/archivr-core/src/auth_users.rs
Normal file
2
crates/archivr-core/src/auth_users.rs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
//! Auth-DB user management (delete, password reset, per-user session/token
|
||||
//! revocation). Stub: filled in by the admin-users and credentials streams.
|
||||
2
crates/archivr-core/src/capture_jobs.rs
Normal file
2
crates/archivr-core/src/capture_jobs.rs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
//! Capture-job listing and scoping queries (`created_by` filters, per-job items).
|
||||
//! Stub: filled in by the jobs stream.
|
||||
|
|
@ -97,6 +97,9 @@ pub struct ApiTokenRecord {
|
|||
pub name: String,
|
||||
pub created_at: String,
|
||||
pub last_used_at: Option<String>,
|
||||
pub expires_at: Option<String>,
|
||||
/// `full` or `read`; read-scope tokens may only issue GET/HEAD requests.
|
||||
pub scope: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
|
|
@ -394,7 +397,8 @@ pub fn initialize_schema(conn: &Connection) -> Result<()> {
|
|||
error_text TEXT,
|
||||
notes_json TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
updated_at TEXT NOT NULL,
|
||||
created_by TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS entry_summaries (
|
||||
id INTEGER PRIMARY KEY,
|
||||
|
|
@ -530,6 +534,13 @@ pub fn initialize_schema(conn: &Connection) -> Result<()> {
|
|||
// Migration: add notes_json column to existing capture_jobs tables.
|
||||
// Silently ignored when the column already exists (idempotent).
|
||||
let _ = conn.execute("ALTER TABLE capture_jobs ADD COLUMN notes_json TEXT", []);
|
||||
// Migration: add created_by (auth-DB `user_uid` of the submitter; NULL for
|
||||
// pre-migration and CLI rows). The index follows the ALTER so legacy tables
|
||||
// have the column by the time it is created.
|
||||
let _ = conn.execute("ALTER TABLE capture_jobs ADD COLUMN created_by TEXT", []);
|
||||
conn.execute_batch(
|
||||
"CREATE INDEX IF NOT EXISTS idx_capture_jobs_created_by ON capture_jobs(created_by);",
|
||||
)?;
|
||||
// Provider responses may resolve a requested alias to a concrete model.
|
||||
// Keep that display-only value outside the cache key.
|
||||
let _ = conn.execute(
|
||||
|
|
@ -688,7 +699,8 @@ pub fn initialize_auth_schema(conn: &Connection) -> Result<()> {
|
|||
name TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
last_used_at TEXT,
|
||||
expires_at TEXT
|
||||
expires_at TEXT,
|
||||
scope TEXT NOT NULL DEFAULT 'full'
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_api_tokens_user_id ON api_tokens(user_id);
|
||||
|
||||
|
|
@ -745,6 +757,12 @@ pub fn initialize_auth_schema(conn: &Connection) -> Result<()> {
|
|||
[],
|
||||
);
|
||||
|
||||
// Add scope column to api_tokens if not present ('full' | 'read'; idempotent migration)
|
||||
let _ = conn.execute(
|
||||
"ALTER TABLE api_tokens ADD COLUMN scope TEXT NOT NULL DEFAULT 'full'",
|
||||
[],
|
||||
);
|
||||
|
||||
// Add ublock_enabled column to instance_settings if not present (idempotent migration)
|
||||
let _ = conn.execute(
|
||||
"ALTER TABLE instance_settings ADD COLUMN ublock_enabled INTEGER NOT NULL DEFAULT 1",
|
||||
|
|
@ -930,32 +948,40 @@ pub fn delete_expired_sessions(conn: &Connection) -> Result<usize> {
|
|||
}
|
||||
|
||||
/// Creates an API token. `token_hash` is SHA3-256 hex of the raw token.
|
||||
/// `expires_at` is an RFC 3339 timestamp (None = never expires); `scope` is
|
||||
/// `full` or `read`.
|
||||
pub fn create_api_token(
|
||||
conn: &Connection,
|
||||
user_id: i64,
|
||||
token_hash: &str,
|
||||
name: &str,
|
||||
expires_at: Option<&str>,
|
||||
scope: &str,
|
||||
) -> Result<String> {
|
||||
let token_uid = public_id("tok");
|
||||
conn.execute(
|
||||
"INSERT INTO api_tokens (token_uid, user_id, token_hash, name, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
params![token_uid, user_id, token_hash, name, now_timestamp()],
|
||||
"INSERT INTO api_tokens (token_uid, user_id, token_hash, name, created_at, expires_at, scope)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
|
||||
params![token_uid, user_id, token_hash, name, now_timestamp(), expires_at, scope],
|
||||
)?;
|
||||
Ok(token_uid)
|
||||
}
|
||||
|
||||
/// Returns the user_id for a given token hash, if the token is valid and user is active.
|
||||
pub fn get_user_for_token(conn: &Connection, token_hash: &str) -> Result<Option<i64>> {
|
||||
/// Returns `(user_id, token_uid)` for a given token hash, if the token is valid
|
||||
/// (unexpired) and its user is active.
|
||||
pub fn get_user_for_token(
|
||||
conn: &Connection,
|
||||
token_hash: &str,
|
||||
) -> Result<Option<(i64, String)>> {
|
||||
let now = now_timestamp();
|
||||
conn.query_row(
|
||||
"SELECT t.user_id FROM api_tokens t
|
||||
"SELECT t.user_id, t.token_uid 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),
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.optional()
|
||||
.map_err(Into::into)
|
||||
|
|
@ -980,7 +1006,7 @@ pub fn delete_api_token(conn: &Connection, token_uid: &str, user_id: i64) -> Res
|
|||
|
||||
pub fn list_user_tokens(conn: &Connection, user_id: i64) -> Result<Vec<ApiTokenRecord>> {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT token_uid, name, created_at, last_used_at
|
||||
"SELECT token_uid, name, created_at, last_used_at, expires_at, scope
|
||||
FROM api_tokens WHERE user_id = ?1 ORDER BY created_at DESC",
|
||||
)?;
|
||||
let records = stmt
|
||||
|
|
@ -990,6 +1016,8 @@ pub fn list_user_tokens(conn: &Connection, user_id: i64) -> Result<Vec<ApiTokenR
|
|||
name: row.get(1)?,
|
||||
created_at: row.get(2)?,
|
||||
last_used_at: row.get(3)?,
|
||||
expires_at: row.get(4)?,
|
||||
scope: row.get(5)?,
|
||||
})
|
||||
})?
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
|
@ -1314,6 +1342,17 @@ pub fn invalidate_user_sessions(conn: &Connection, user_id: i64) -> Result<usize
|
|||
Ok(n)
|
||||
}
|
||||
|
||||
/// Returns the `user_uid` for an integer user id, or None if not found.
|
||||
pub fn get_user_uid(conn: &Connection, user_id: i64) -> Result<Option<String>> {
|
||||
conn.query_row(
|
||||
"SELECT user_uid FROM users WHERE id = ?1",
|
||||
[user_id],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Returns the integer id for a user_uid, or None if not found.
|
||||
pub fn get_user_id_by_uid(conn: &Connection, user_uid: &str) -> Result<Option<i64>> {
|
||||
conn.query_row(
|
||||
|
|
@ -1613,12 +1652,22 @@ pub fn ensure_default_user(conn: &Connection) -> Result<i64> {
|
|||
|
||||
/// Creates a pending capture job. Returns the new `job_uid`.
|
||||
pub fn create_capture_job(conn: &Connection, archive_id: &str) -> Result<String> {
|
||||
create_capture_job_as(conn, archive_id, None)
|
||||
}
|
||||
|
||||
/// Creates a pending capture job attributed to `created_by` (the submitter's
|
||||
/// auth-DB `user_uid`; None for CLI/legacy callers). Returns the new `job_uid`.
|
||||
pub fn create_capture_job_as(
|
||||
conn: &Connection,
|
||||
archive_id: &str,
|
||||
created_by: Option<&str>,
|
||||
) -> Result<String> {
|
||||
let job_uid = public_id("job");
|
||||
let now = now_timestamp();
|
||||
conn.execute(
|
||||
"INSERT INTO capture_jobs (job_uid, archive_id, run_uid, status, error_text, created_at, updated_at)
|
||||
VALUES (?1, ?2, NULL, 'pending', NULL, ?3, ?3)",
|
||||
rusqlite::params![job_uid, archive_id, now],
|
||||
"INSERT INTO capture_jobs (job_uid, archive_id, run_uid, status, error_text, created_at, updated_at, created_by)
|
||||
VALUES (?1, ?2, NULL, 'pending', NULL, ?3, ?3, ?4)",
|
||||
rusqlite::params![job_uid, archive_id, now, created_by],
|
||||
)?;
|
||||
Ok(job_uid)
|
||||
}
|
||||
|
|
@ -4036,9 +4085,78 @@ mod tests {
|
|||
fn token_hash_round_trips() {
|
||||
let conn = make_auth_conn();
|
||||
let user_id = create_owner(&conn, "alice", "pw").unwrap();
|
||||
create_api_token(&conn, user_id, "hash_abc", "My Token").unwrap();
|
||||
let found_id = get_user_for_token(&conn, "hash_abc").unwrap();
|
||||
assert_eq!(found_id, Some(user_id));
|
||||
let token_uid =
|
||||
create_api_token(&conn, user_id, "hash_abc", "My Token", None, "full").unwrap();
|
||||
let found = get_user_for_token(&conn, "hash_abc").unwrap();
|
||||
assert_eq!(found, Some((user_id, token_uid)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_expiry_and_scope_round_trip() {
|
||||
let conn = make_auth_conn();
|
||||
let user_id = create_owner(&conn, "alice", "pw").unwrap();
|
||||
let past = (chrono::Utc::now() - chrono::Duration::days(1)).to_rfc3339();
|
||||
let future = (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339();
|
||||
create_api_token(&conn, user_id, "h_expired", "old", Some(&past), "full").unwrap();
|
||||
create_api_token(&conn, user_id, "h_live", "new", Some(&future), "read").unwrap();
|
||||
assert!(get_user_for_token(&conn, "h_expired").unwrap().is_none());
|
||||
assert!(get_user_for_token(&conn, "h_live").unwrap().is_some());
|
||||
let tokens = list_user_tokens(&conn, user_id).unwrap();
|
||||
let live = tokens.iter().find(|t| t.name == "new").unwrap();
|
||||
assert_eq!(live.scope, "read");
|
||||
assert_eq!(live.expires_at.as_deref(), Some(future.as_str()));
|
||||
let old = tokens.iter().find(|t| t.name == "old").unwrap();
|
||||
assert_eq!(old.scope, "full");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_user_uid_round_trips_and_misses() {
|
||||
let conn = make_auth_conn();
|
||||
let user_id = create_owner(&conn, "alice", "pw").unwrap();
|
||||
let uid = get_user_uid(&conn, user_id).unwrap().unwrap();
|
||||
assert_eq!(get_user_id_by_uid(&conn, &uid).unwrap(), Some(user_id));
|
||||
assert!(get_user_uid(&conn, user_id + 1000).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initialize_auth_schema_migrates_scope_for_existing_api_tokens() {
|
||||
let c = Connection::open_in_memory().unwrap();
|
||||
// Legacy tables: api_tokens without scope (users/roles arrive via the init).
|
||||
c.execute_batch(
|
||||
"CREATE TABLE api_tokens (
|
||||
id INTEGER PRIMARY KEY,
|
||||
token_uid TEXT NOT NULL UNIQUE,
|
||||
user_id INTEGER NOT NULL,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
name TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
last_used_at TEXT,
|
||||
expires_at TEXT
|
||||
);
|
||||
INSERT INTO api_tokens (token_uid, user_id, token_hash, name, created_at)
|
||||
VALUES ('tok-legacy', 1, 'h', 'legacy', 't');",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
initialize_auth_schema(&c).unwrap();
|
||||
initialize_auth_schema(&c).unwrap();
|
||||
|
||||
let has_column: i64 = c
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM pragma_table_info('api_tokens') WHERE name = 'scope'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(has_column, 1);
|
||||
let scope: String = c
|
||||
.query_row(
|
||||
"SELECT scope FROM api_tokens WHERE token_uid = 'tok-legacy'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(scope, "full", "legacy tokens keep full access");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -5103,6 +5221,72 @@ mod tests {
|
|||
assert_eq!(has_resolved_model, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initialize_schema_migrates_created_by_for_existing_capture_jobs() {
|
||||
let c = Connection::open_in_memory().unwrap();
|
||||
// Legacy table: no created_by, no notes_json.
|
||||
c.execute_batch(
|
||||
"CREATE TABLE capture_jobs (
|
||||
id INTEGER PRIMARY KEY,
|
||||
job_uid TEXT NOT NULL UNIQUE,
|
||||
archive_id TEXT NOT NULL,
|
||||
run_uid TEXT,
|
||||
status TEXT NOT NULL CHECK (status IN ('pending','running','completed','failed')) DEFAULT 'pending',
|
||||
error_text TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
INSERT INTO capture_jobs (job_uid, archive_id, status, created_at, updated_at)
|
||||
VALUES ('job-legacy', 'a', 'completed', 't', 't');",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
initialize_schema(&c).unwrap();
|
||||
initialize_schema(&c).unwrap();
|
||||
|
||||
let has_column: i64 = c
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM pragma_table_info('capture_jobs') WHERE name = 'created_by'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(has_column, 1);
|
||||
let has_index: i64 = c
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM sqlite_master WHERE type='index' AND name='idx_capture_jobs_created_by'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(has_index, 1);
|
||||
let legacy_owner: Option<String> = c
|
||||
.query_row(
|
||||
"SELECT created_by FROM capture_jobs WHERE job_uid = 'job-legacy'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(legacy_owner.is_none(), "pre-migration rows stay NULL-owned");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_capture_job_as_records_submitter() {
|
||||
let c = conn();
|
||||
let owned = create_capture_job_as(&c, "a", Some("usr-1")).unwrap();
|
||||
let anon = create_capture_job(&c, "a").unwrap();
|
||||
let by = |uid: &str| -> Option<String> {
|
||||
c.query_row(
|
||||
"SELECT created_by FROM capture_jobs WHERE job_uid = ?1",
|
||||
[uid],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(by(&owned).as_deref(), Some("usr-1"));
|
||||
assert_eq!(by(&anon), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_summary_lifecycle_pending_running_completed() {
|
||||
let c = conn();
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
pub mod capture;
|
||||
pub mod archive;
|
||||
pub mod auth_credentials;
|
||||
pub mod auth_users;
|
||||
pub mod capture_jobs;
|
||||
pub mod database;
|
||||
pub mod downloader;
|
||||
pub mod hash;
|
||||
|
|
|
|||
7
crates/archivr-server/src/admin_users.rs
Normal file
7
crates/archivr-server/src/admin_users.rs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
use axum::Router;
|
||||
|
||||
use crate::routes::AppState;
|
||||
|
||||
pub fn routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
}
|
||||
|
|
@ -81,7 +81,9 @@ 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)) = database::get_user_for_token(&conn, &token_hash) {
|
||||
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) {
|
||||
return Ok(AuthUser::Authenticated { user_id, role_bits });
|
||||
}
|
||||
|
|
|
|||
7
crates/archivr-server/src/credentials.rs
Normal file
7
crates/archivr-server/src/credentials.rs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
use axum::Router;
|
||||
|
||||
use crate::routes::AppState;
|
||||
|
||||
pub fn routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
}
|
||||
7
crates/archivr-server/src/effective_config.rs
Normal file
7
crates/archivr-server/src/effective_config.rs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
use axum::Router;
|
||||
|
||||
use crate::routes::AppState;
|
||||
|
||||
pub fn routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
}
|
||||
127
crates/archivr-server/src/guards.rs
Normal file
127
crates/archivr-server/src/guards.rs
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
//! Shared authorization guards for user/role/token management endpoints.
|
||||
//!
|
||||
//! Callers still do their own coarse role check (`require_role(ROLE_ADMIN)`);
|
||||
//! these guards add the target-aware rules on top.
|
||||
#![allow(dead_code)] // consumed by the admin_users / credentials streams
|
||||
use rusqlite::Connection;
|
||||
|
||||
use crate::auth::{ROLE_ADMIN, ROLE_OWNER};
|
||||
use crate::routes::ApiError;
|
||||
|
||||
/// Strict management rule: only an OWNER may act on a target that holds the
|
||||
/// OWNER **or** ADMIN bit. Admins may manage everyone else. 403 otherwise.
|
||||
pub fn ensure_can_manage(caller_bits: u32, target_bits: u32) -> Result<(), ApiError> {
|
||||
if target_bits & (ROLE_OWNER | ROLE_ADMIN) != 0 && caller_bits & ROLE_OWNER == 0 {
|
||||
return Err(ApiError::forbidden(
|
||||
"only an owner can manage owners and admins",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rejects an action aimed at the caller's own account (409).
|
||||
pub fn ensure_not_self(caller_id: i64, target_id: i64) -> Result<(), ApiError> {
|
||||
if caller_id == target_id {
|
||||
return Err(ApiError::conflict("you cannot do this to your own account"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rejects an action that would leave the instance without an *active* owner
|
||||
/// (409). Passes when the target is not an active owner, or when another
|
||||
/// active owner remains.
|
||||
pub fn ensure_not_last_owner(conn: &Connection, target_id: i64) -> Result<(), ApiError> {
|
||||
let active_owners = |exclude_target: bool| -> Result<i64, ApiError> {
|
||||
let sql = format!(
|
||||
"SELECT COUNT(*) FROM user_roles ur
|
||||
JOIN roles r ON r.id = ur.role_id
|
||||
JOIN users u ON u.id = ur.user_id
|
||||
WHERE r.slug = 'owner' AND u.status = 'active'{}",
|
||||
if exclude_target { " AND u.id != ?1" } else { " AND u.id = ?1" }
|
||||
);
|
||||
Ok(conn.query_row(&sql, [target_id], |row| row.get(0))?)
|
||||
};
|
||||
let target_is_active_owner = active_owners(false)? > 0;
|
||||
if target_is_active_owner && active_owners(true)? == 0 {
|
||||
return Err(ApiError::conflict("cannot remove the last active owner"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::auth::{ROLE_GUEST, ROLE_USER};
|
||||
use archivr_core::database;
|
||||
use axum::http::StatusCode;
|
||||
|
||||
fn auth_conn() -> Connection {
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
database::initialize_auth_schema(&conn).unwrap();
|
||||
conn
|
||||
}
|
||||
|
||||
fn add_owner(conn: &Connection, username: &str, creator: i64) -> i64 {
|
||||
let uid = database::create_user(conn, username, None, "dummy", creator).unwrap();
|
||||
let id = database::get_user_id_by_uid(conn, &uid).unwrap().unwrap();
|
||||
database::assign_role(conn, id, "owner", creator).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manage_rule_requires_owner_for_owner_and_admin_targets() {
|
||||
let user = ROLE_USER;
|
||||
let admin = ROLE_USER | ROLE_ADMIN;
|
||||
let owner = ROLE_USER | ROLE_ADMIN | ROLE_OWNER;
|
||||
// Admin vs plain user / guest / custom-role user: allowed.
|
||||
assert!(ensure_can_manage(admin, user).is_ok());
|
||||
assert!(ensure_can_manage(admin, ROLE_GUEST).is_ok());
|
||||
assert!(ensure_can_manage(admin, user | 1 << 4).is_ok());
|
||||
// Admin vs admin and admin vs owner: 403.
|
||||
for target in [admin, owner, ROLE_ADMIN, ROLE_OWNER] {
|
||||
let err = ensure_can_manage(admin, target).unwrap_err();
|
||||
assert_eq!(err.status, StatusCode::FORBIDDEN);
|
||||
}
|
||||
// Owner may manage everyone.
|
||||
for target in [user, admin, owner] {
|
||||
assert!(ensure_can_manage(owner, target).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn not_self_conflicts_only_on_same_id() {
|
||||
assert!(ensure_not_self(1, 2).is_ok());
|
||||
let err = ensure_not_self(3, 3).unwrap_err();
|
||||
assert_eq!(err.status, StatusCode::CONFLICT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_owner_guard_counts_only_active_owners() {
|
||||
let conn = auth_conn();
|
||||
let first = database::create_owner(&conn, "first", "pw").unwrap();
|
||||
// Sole owner: blocked.
|
||||
assert_eq!(
|
||||
ensure_not_last_owner(&conn, first).unwrap_err().status,
|
||||
StatusCode::CONFLICT
|
||||
);
|
||||
// A plain user is never a "last owner".
|
||||
let uid = database::create_user(&conn, "plain", None, "dummy", first).unwrap();
|
||||
let plain = database::get_user_id_by_uid(&conn, &uid).unwrap().unwrap();
|
||||
assert!(ensure_not_last_owner(&conn, plain).is_ok());
|
||||
|
||||
// Second owner makes either removable.
|
||||
let second = add_owner(&conn, "second", first);
|
||||
assert!(ensure_not_last_owner(&conn, first).is_ok());
|
||||
assert!(ensure_not_last_owner(&conn, second).is_ok());
|
||||
|
||||
// Disable the second owner: it no longer counts, so the first is last again.
|
||||
let second_uid = database::get_user_uid(&conn, second).unwrap().unwrap();
|
||||
assert!(database::set_user_status(&conn, &second_uid, "disabled").unwrap());
|
||||
assert_eq!(
|
||||
ensure_not_last_owner(&conn, first).unwrap_err().status,
|
||||
StatusCode::CONFLICT
|
||||
);
|
||||
// A disabled owner is not an active owner: touching it is fine.
|
||||
assert!(ensure_not_last_owner(&conn, second).is_ok());
|
||||
}
|
||||
}
|
||||
7
crates/archivr-server/src/jobs.rs
Normal file
7
crates/archivr-server/src/jobs.rs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
use axum::Router;
|
||||
|
||||
use crate::routes::AppState;
|
||||
|
||||
pub fn routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
}
|
||||
|
|
@ -1,6 +1,14 @@
|
|||
mod admin_users;
|
||||
mod auth;
|
||||
mod credentials;
|
||||
mod effective_config;
|
||||
mod guards;
|
||||
mod jobs;
|
||||
mod registry;
|
||||
mod routes;
|
||||
#[cfg(test)]
|
||||
mod test_support;
|
||||
mod token_scope;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use std::{net::SocketAddr, path::PathBuf};
|
||||
|
|
|
|||
|
|
@ -70,7 +70,7 @@ pub(crate) struct MediaToken {
|
|||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
registry: Arc<ServerRegistry>,
|
||||
pub(crate) registry: Arc<ServerRegistry>,
|
||||
pub auth_db_path: Arc<std::path::PathBuf>,
|
||||
pub login_attempts: Arc<Mutex<HashMap<IpAddr, VecDeque<Instant>>>>,
|
||||
pub media_tokens: Arc<Mutex<HashMap<String, MediaToken>>>,
|
||||
|
|
@ -425,6 +425,14 @@ pub fn app_with_state(state: AppState) -> Router {
|
|||
get(blob_cleanup_scan_handler).delete(blob_cleanup_delete_handler),
|
||||
)
|
||||
.route("/api/util/resolve-tco", post(resolve_tco_handler))
|
||||
// Workstream routers (admin_users, credentials, jobs, effective_config).
|
||||
// Axum 0.7 merges different methods on an existing path but panics on a
|
||||
// duplicate path+method, so streams extending an existing path edit the
|
||||
// existing handler in place (see the contract spec).
|
||||
.merge(crate::admin_users::routes())
|
||||
.merge(crate::credentials::routes())
|
||||
.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(),
|
||||
|
|
@ -2901,7 +2909,7 @@ async fn create_token(
|
|||
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)?;
|
||||
let token_uid = database::create_api_token(&conn, user_id, &token_hash, &body.name, None, "full")?;
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(serde_json::json!({
|
||||
|
|
@ -3088,14 +3096,14 @@ async fn admin_create_role(
|
|||
Ok((StatusCode::CREATED, Json(role)))
|
||||
}
|
||||
|
||||
fn auth_to_caller_bits(auth: &AuthUser) -> u32 {
|
||||
pub(crate) fn auth_to_caller_bits(auth: &AuthUser) -> u32 {
|
||||
match auth {
|
||||
AuthUser::Authenticated { role_bits, .. } => *role_bits,
|
||||
AuthUser::Guest => ROLE_GUEST,
|
||||
}
|
||||
}
|
||||
|
||||
fn mounted_archive<'a>(
|
||||
pub(crate) fn mounted_archive<'a>(
|
||||
state: &'a AppState,
|
||||
archive_id: &str,
|
||||
) -> Result<&'a MountedArchive, ApiError> {
|
||||
|
|
@ -3109,26 +3117,26 @@ fn mounted_archive<'a>(
|
|||
|
||||
#[derive(Debug)]
|
||||
pub struct ApiError {
|
||||
status: StatusCode,
|
||||
message: String,
|
||||
pub(crate) status: StatusCode,
|
||||
pub(crate) message: String,
|
||||
}
|
||||
|
||||
impl ApiError {
|
||||
fn not_found(message: &str) -> Self {
|
||||
pub(crate) fn not_found(message: &str) -> Self {
|
||||
Self {
|
||||
status: StatusCode::NOT_FOUND,
|
||||
message: message.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn bad_request(message: &str) -> Self {
|
||||
pub(crate) fn bad_request(message: &str) -> Self {
|
||||
Self {
|
||||
status: StatusCode::BAD_REQUEST,
|
||||
message: message.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn internal(message: &str) -> Self {
|
||||
pub(crate) fn internal(message: &str) -> Self {
|
||||
Self {
|
||||
status: StatusCode::INTERNAL_SERVER_ERROR,
|
||||
message: message.to_string(),
|
||||
|
|
@ -3149,7 +3157,7 @@ impl ApiError {
|
|||
}
|
||||
}
|
||||
|
||||
fn conflict(message: &str) -> Self {
|
||||
pub(crate) fn conflict(message: &str) -> Self {
|
||||
Self {
|
||||
status: StatusCode::CONFLICT,
|
||||
message: message.to_string(),
|
||||
|
|
@ -3535,8 +3543,15 @@ mod tests {
|
|||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
database::create_api_token(&conn, uid, &auth::hash_token("capture-token"), "Extension")
|
||||
.unwrap();
|
||||
database::create_api_token(
|
||||
&conn,
|
||||
uid,
|
||||
&auth::hash_token("capture-token"),
|
||||
"Extension",
|
||||
None,
|
||||
"full",
|
||||
)
|
||||
.unwrap();
|
||||
let mut settings = database::get_instance_settings(&conn).unwrap();
|
||||
settings.ublock_enabled = false;
|
||||
settings.cookie_ext_enabled = false;
|
||||
|
|
@ -3854,6 +3869,8 @@ mod tests {
|
|||
uid,
|
||||
&auth::hash_token("text-title-token"),
|
||||
"Extension",
|
||||
None,
|
||||
"full",
|
||||
)
|
||||
.unwrap();
|
||||
let mut settings = database::get_instance_settings(&conn).unwrap();
|
||||
|
|
|
|||
238
crates/archivr-server/src/test_support.rs
Normal file
238
crates/archivr-server/src/test_support.rs
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
//! Shared helpers for server tests (`#[cfg(test)]` only). Copied from
|
||||
//! `routes.rs`'s `mod tests` so new stream modules can reuse them without
|
||||
//! touching that file; the originals there are unchanged.
|
||||
#![allow(dead_code)] // helpers are consumed by the stream modules' tests
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use archivr_core::database;
|
||||
use axum::body::Body;
|
||||
|
||||
use crate::auth;
|
||||
use crate::registry::{MountedArchive, ServerRegistry};
|
||||
|
||||
/// One archive ("test") + auth DB seeded with owner `testowner`.
|
||||
/// Returns `(registry, archive_path, auth_db_path)`.
|
||||
pub(crate) fn make_test_registry(
|
||||
dir: &tempfile::TempDir,
|
||||
) -> (ServerRegistry, PathBuf, PathBuf) {
|
||||
let paths = archivr_core::archive::initialize_archive(
|
||||
dir.path(),
|
||||
&dir.path().join("store"),
|
||||
"test",
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
let auth_path = dir.path().join("auth.sqlite");
|
||||
{
|
||||
let conn = database::open_auth_db(&auth_path).unwrap();
|
||||
database::create_owner(&conn, "testowner", "dummy").unwrap();
|
||||
}
|
||||
let registry = ServerRegistry {
|
||||
archives: vec![MountedArchive {
|
||||
id: "test".to_string(),
|
||||
label: "Test".to_string(),
|
||||
archive_path: paths.archive_path.clone(),
|
||||
}],
|
||||
bind: None,
|
||||
auth_db_path: None,
|
||||
};
|
||||
(registry, paths.archive_path, auth_path)
|
||||
}
|
||||
|
||||
/// Creates a session for the seeded 'testowner' and returns the cookie string.
|
||||
pub(crate) fn make_test_session(auth_path: &Path) -> String {
|
||||
let conn = database::open_auth_db(auth_path).unwrap();
|
||||
let user_id: i64 = conn
|
||||
.query_row(
|
||||
"SELECT id FROM users WHERE username = 'testowner'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
let role_bits = database::compute_role_bits(&conn, user_id).unwrap();
|
||||
let sess_uid = database::create_session(&conn, user_id, role_bits, None).unwrap();
|
||||
format!("session={}", sess_uid)
|
||||
}
|
||||
|
||||
/// Creates an active user holding `roles` (assign_role adds the cumulative ones:
|
||||
/// user for any non-guest, admin for owner) and returns a session cookie.
|
||||
pub(crate) fn make_role_session(auth_path: &Path, username: &str, roles: &[&str]) -> String {
|
||||
let conn = database::open_auth_db(auth_path).unwrap();
|
||||
let owner_id: i64 = conn
|
||||
.query_row(
|
||||
"SELECT id FROM users WHERE username = 'testowner'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
let uid = database::create_user(&conn, username, None, "dummy", owner_id).unwrap();
|
||||
let user_id = database::get_user_id_by_uid(&conn, &uid).unwrap().unwrap();
|
||||
for role in roles {
|
||||
database::assign_role(&conn, user_id, role, owner_id).unwrap();
|
||||
}
|
||||
// assign_role deletes sessions, so create the session afterwards.
|
||||
let bits = database::compute_role_bits(&conn, user_id).unwrap();
|
||||
format!(
|
||||
"session={}",
|
||||
database::create_session(&conn, user_id, bits, None).unwrap()
|
||||
)
|
||||
}
|
||||
|
||||
/// Cookie for the seeded owner `testowner`.
|
||||
pub(crate) fn owner_session(auth_path: &Path) -> String {
|
||||
make_test_session(auth_path)
|
||||
}
|
||||
|
||||
/// Creates user `test-admin` (roles: admin + cumulative user) and returns its cookie.
|
||||
/// Fixed username: call at most once per auth DB (use `make_role_session` for more).
|
||||
pub(crate) fn admin_session(auth_path: &Path) -> String {
|
||||
make_role_session(auth_path, "test-admin", &["admin"])
|
||||
}
|
||||
|
||||
/// Creates user `test-user` (role: user) and returns its cookie. Once per auth DB.
|
||||
pub(crate) fn user_session(auth_path: &Path) -> String {
|
||||
make_role_session(auth_path, "test-user", &["user"])
|
||||
}
|
||||
|
||||
/// Creates user `test-guest` (role: guest only) and returns its cookie. Once per auth DB.
|
||||
pub(crate) fn guest_session(auth_path: &Path) -> String {
|
||||
make_role_session(auth_path, "test-guest", &["guest"])
|
||||
}
|
||||
|
||||
/// Creates an API token for the existing user `username` and returns the raw
|
||||
/// token (send as `Authorization: Bearer <raw>`). `expires` is an RFC 3339
|
||||
/// timestamp (None = never; a past value yields an already-expired token);
|
||||
/// `scope` is `"full"` or `"read"`.
|
||||
pub(crate) fn make_api_token(
|
||||
auth_path: &Path,
|
||||
username: &str,
|
||||
expires: Option<&str>,
|
||||
scope: &str,
|
||||
) -> String {
|
||||
let conn = database::open_auth_db(auth_path).unwrap();
|
||||
let user_id: i64 = conn
|
||||
.query_row(
|
||||
"SELECT id FROM users WHERE username = ?1",
|
||||
[username],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
let raw = auth::generate_token();
|
||||
database::create_api_token(
|
||||
&conn,
|
||||
user_id,
|
||||
&auth::hash_token(&raw),
|
||||
"test token",
|
||||
expires,
|
||||
scope,
|
||||
)
|
||||
.unwrap();
|
||||
raw
|
||||
}
|
||||
|
||||
pub(crate) async fn body_json(response: axum::response::Response) -> serde_json::Value {
|
||||
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
serde_json::from_slice(&bytes).unwrap()
|
||||
}
|
||||
|
||||
pub(crate) fn json_body(payload: &serde_json::Value) -> Body {
|
||||
Body::from(serde_json::to_vec(payload).unwrap())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::routes::app;
|
||||
use axum::http::{Request, StatusCode};
|
||||
use tower::ServiceExt;
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_helpers_and_bearer_token_authenticate() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (registry, _, auth_path) = make_test_registry(&dir);
|
||||
let owner = owner_session(&auth_path);
|
||||
let admin = admin_session(&auth_path);
|
||||
let user = user_session(&auth_path);
|
||||
let guest = guest_session(&auth_path);
|
||||
let token = make_api_token(&auth_path, "test-user", None, "full");
|
||||
|
||||
let me = |cookie: Option<String>, bearer: Option<String>| {
|
||||
let registry = registry.clone();
|
||||
let auth_path = auth_path.clone();
|
||||
async move {
|
||||
let mut b = Request::builder().uri("/api/auth/me");
|
||||
if let Some(c) = cookie {
|
||||
b = b.header("cookie", c);
|
||||
}
|
||||
if let Some(t) = bearer {
|
||||
b = b.header("authorization", format!("Bearer {t}"));
|
||||
}
|
||||
let resp = app(registry, auth_path)
|
||||
.oneshot(b.body(Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let status = resp.status();
|
||||
(status, body_json(resp).await)
|
||||
}
|
||||
};
|
||||
for (cookie, role_bit) in [(owner, 8u64), (admin, 4), (user, 2), (guest, 1)] {
|
||||
let (status, body) = me(Some(cookie), None).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert!(body["role_bits"].as_u64().unwrap() & role_bit != 0, "{body}");
|
||||
}
|
||||
let (status, body) = me(None, Some(token)).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body["username"], "test-user");
|
||||
|
||||
// Back-dated token expiry is rejected as unauthenticated.
|
||||
let past = (chrono::Utc::now() - chrono::Duration::days(1)).to_rfc3339();
|
||||
let expired = make_api_token(&auth_path, "test-user", Some(&past), "full");
|
||||
let (status, _) = me(None, Some(expired)).await;
|
||||
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
// Axum 0.7.9 `Router::merge` semantics, pinned for the stream modules.
|
||||
async fn status_of(router: axum::Router, method: &str, uri: &str) -> StatusCode {
|
||||
router
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method(method)
|
||||
.uri(uri)
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.status()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn merge_adds_new_methods_to_an_existing_path() {
|
||||
use axum::routing::{delete, get, post};
|
||||
let base = axum::Router::new().route("/api/auth/tokens", get(|| async { "list" }).post(|| async { "create" }));
|
||||
// A merged router adding DELETE (a new method) on the same path: fine.
|
||||
let extra = axum::Router::new().route("/api/auth/tokens", delete(|| async { "revoke-all" }));
|
||||
let merged = base.merge(extra);
|
||||
assert_eq!(status_of(merged.clone(), "GET", "/api/auth/tokens").await, StatusCode::OK);
|
||||
assert_eq!(status_of(merged.clone(), "POST", "/api/auth/tokens").await, StatusCode::OK);
|
||||
assert_eq!(status_of(merged.clone(), "DELETE", "/api/auth/tokens").await, StatusCode::OK);
|
||||
assert_eq!(status_of(merged, "PUT", "/api/auth/tokens").await, StatusCode::METHOD_NOT_ALLOWED);
|
||||
// Same for routes registered by two merged routers on one new path.
|
||||
let a = axum::Router::new().route("/x", get(|| async { "a" }));
|
||||
let b = axum::Router::new().route("/x", post(|| async { "b" }));
|
||||
let merged = a.merge(b);
|
||||
assert_eq!(status_of(merged.clone(), "GET", "/x").await, StatusCode::OK);
|
||||
assert_eq!(status_of(merged, "POST", "/x").await, StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "Overlapping method route")]
|
||||
fn merge_panics_when_the_same_method_is_registered_twice() {
|
||||
use axum::routing::get;
|
||||
let base = axum::Router::<()>::new().route("/api/auth/tokens", get(|| async { "list" }));
|
||||
let extra = axum::Router::new().route("/api/auth/tokens", get(|| async { "dup" }));
|
||||
let _ = base.merge(extra);
|
||||
}
|
||||
}
|
||||
25
crates/archivr-server/src/token_scope.rs
Normal file
25
crates/archivr-server/src/token_scope.rs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
//! 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
|
||||
use axum::{
|
||||
Router,
|
||||
extract::{Request, State},
|
||||
middleware::Next,
|
||||
response::Response,
|
||||
};
|
||||
|
||||
use crate::routes::AppState;
|
||||
|
||||
pub fn routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
}
|
||||
|
||||
/// Middleware stub: currently a pass-through.
|
||||
pub async fn enforce_read_scope(
|
||||
State(_state): State<AppState>,
|
||||
req: Request,
|
||||
next: Next,
|
||||
) -> Response {
|
||||
next.run(req).await
|
||||
}
|
||||
263
docs/superpowers/specs/2026-10-08-mcp-api-extensions.md
Normal file
263
docs/superpowers/specs/2026-10-08-mcp-api-extensions.md
Normal file
|
|
@ -0,0 +1,263 @@
|
|||
# Spec: Archivr API extensions for the MCP server
|
||||
|
||||
- **Status:** Contract (R0 foundation landed; endpoints are implemented by streams R1-R4).
|
||||
- **Date:** 2026-10-08
|
||||
- **Audience:** the Archivr (Rust) streams R1-R4 and the MCP (TypeScript) streams M0-M5. The MCP server is built against this document with a mocked `fetch`; the Rust streams implement it. Anything not written here is not part of the contract.
|
||||
- **Read first:** `AGENTS.md`, `ARCHIVR-MENTAL-MODEL.md`.
|
||||
|
||||
## 0. Conventions
|
||||
|
||||
- Base path `/api`. JSON in and out unless noted. Timestamps are RFC 3339 strings (`2026-10-08T12:34:56.789+00:00`). `uid` values are opaque strings.
|
||||
- **Auth.** Session cookie (`session`) or `Authorization: Bearer <raw_token>`. The MCP uses Bearer.
|
||||
- **Errors.** Body is always `{"error": "<message>"}`. Status codes: `400` validation, `401` unauthenticated, `403` role/ownership/scope, `404` missing, `409` state conflict (self-target, last owner, update already running), `500` unexpected.
|
||||
- **Role bits** (`u32`, from `/api/auth/me.role_bits`): `GUEST=1`, `USER=2`, `ADMIN=4`, `OWNER=8`; custom roles take bits from `16` up. Owners also hold `admin` and `user`; admins also hold `user`.
|
||||
- **Role column** below: `any` = authenticated (any role incl. guest), `USER`/`ADMIN`/`OWNER` = caller must hold that bit, `own` = authenticated, acts only on the caller's own resources.
|
||||
- `nullable` means the key is always present and may be `null`. `optional` means the key may be absent.
|
||||
- **Never returned by any endpoint, ever:** `session_uid` (it is the cookie value), `password_hash`, `token_hash`, raw secrets/env values flagged `secret`, cookie-rule cookie values in MCP output.
|
||||
|
||||
### 0.1 Guard order for endpoints that target another user
|
||||
|
||||
For every endpoint that takes a `:uid` of a target user (U1-U5 and the hardened status/roles endpoints), checks run in this order, and the first failure wins:
|
||||
|
||||
1. Caller role (`401` / `403`).
|
||||
2. Target lookup (`404 user not found`).
|
||||
3. `ensure_not_self(caller_id, target_id)` -> `409` (only where the table says "self-guard").
|
||||
4. `ensure_can_manage(caller_bits, target_bits)` -> `403`: **OWNER bit required if the target holds the OWNER or ADMIN bit** (strict rule). Admins manage plain/custom-role users only.
|
||||
5. `ensure_not_last_owner(conn, target_id)` -> `409` (only where the table says "last-owner guard"): fails if the target is an *active* owner and no other *active* owner exists.
|
||||
|
||||
(Self before can-manage, so an admin targeting themselves gets `409`, not `403`.)
|
||||
|
||||
## 1. New and extended endpoints
|
||||
|
||||
### 1.1 Users (admin) - R1 and R2
|
||||
|
||||
| # | Method + path | Role | Guards |
|
||||
|---|---|---|---|
|
||||
| U1 | `DELETE /api/admin/users/:uid` | ADMIN | self, can-manage, last-owner |
|
||||
| U2 | `POST /api/admin/users/:uid/password` | ADMIN | self, can-manage |
|
||||
| U3 | `DELETE /api/admin/users/:uid/sessions` | ADMIN | self, can-manage |
|
||||
| U4 | `GET /api/admin/users/:uid/tokens` | ADMIN | can-manage |
|
||||
| U5 | `DELETE /api/admin/users/:uid/tokens/:token_uid` | ADMIN | can-manage |
|
||||
|
||||
**U1.** No body. Transaction: `UPDATE user_roles SET assigned_by_user_id = NULL WHERE assigned_by_user_id = <target>` (the FK has no `ON DELETE`), then delete the user; sessions, tokens and `user_roles` rows cascade. Response `204`, no body. Errors: 401/403/404/409.
|
||||
|
||||
**U2.** Request `{"new_password": string (>= 8 chars), "revoke_tokens": boolean (optional, default false)}`. Always deletes all of the target's sessions; with `revoke_tokens: true` also deletes all their API tokens. Response `200`:
|
||||
```json
|
||||
{"user_uid": "usr_...", "sessions_revoked": 2, "tokens_revoked": 0}
|
||||
```
|
||||
Errors: `400` (`new_password` shorter than 8, or blank), 401/403/404/409 (self: use `PATCH /api/auth/me`).
|
||||
|
||||
**U3.** No body. Deletes all of the target's sessions. Response `200` `{"revoked": <integer>}`.
|
||||
|
||||
**U4.** Response `200`, array (newest first), never contains hashes or raw tokens:
|
||||
```json
|
||||
[{"token_uid": "tok_...", "name": "string", "created_at": "ts", "last_used_at": "ts|null", "expires_at": "ts|null", "scope": "full|read"}]
|
||||
```
|
||||
|
||||
**U5.** Response `204`. `404` if the token does not exist **or does not belong to `:uid`**.
|
||||
|
||||
### 1.2 Roles (admin) - R1
|
||||
|
||||
| # | Method + path | Role |
|
||||
|---|---|---|
|
||||
| R1 | `PATCH /api/admin/roles/:slug` | ADMIN |
|
||||
| R2 | `DELETE /api/admin/roles/:slug` | OWNER |
|
||||
|
||||
**R1.** Request `{"name": string}` (trimmed, non-empty). Custom roles only; the slug is immutable. Response `200`, the updated role:
|
||||
```json
|
||||
{"role_uid": "string", "slug": "string", "name": "string", "level": 0, "bit_position": 4, "is_builtin": false}
|
||||
```
|
||||
Errors: `400` blank name or a built-in role (`guest/user/admin/owner`), 401/403/404 (unknown slug).
|
||||
|
||||
**R2.** No body. Custom roles only (`400` for built-ins, `404` unknown). One transaction: delete the role's `user_roles` rows, delete the sessions of every holder (their cached `role_bits` are stale), clear the role's bit from `instance_settings.reorder_children_role_bits`, delete the role. Response `204`.
|
||||
|
||||
### 1.3 Own sessions - R2
|
||||
|
||||
`session_handle` = first 16 hex characters of `hash_token(session_uid)` (the SHA3-256 hex helper already used for API tokens). The handle is stable and not reversible to the cookie. **`session_uid` is never returned.**
|
||||
|
||||
| # | Method + path | Role |
|
||||
|---|---|---|
|
||||
| S1 | `GET /api/auth/sessions` | own |
|
||||
| S2 | `DELETE /api/auth/sessions/:handle` | own |
|
||||
| S3 | `DELETE /api/auth/sessions` | own |
|
||||
|
||||
**S1.** Response `200`, array (newest `last_seen_at` first), only the caller's sessions:
|
||||
```json
|
||||
[{"session_handle": "0123456789abcdef", "created_at": "ts", "last_seen_at": "ts", "expires_at": "ts", "user_agent": "string|null", "current": true}]
|
||||
```
|
||||
`current` is true for the session whose cookie made this request; it is `false` for every row on Bearer-authenticated requests.
|
||||
|
||||
**S2.** `204`. `404` if the handle matches none of the caller's sessions (another user's handle is also `404`). Deleting the current session is allowed (equivalent to logout; the cookie is not cleared by this call).
|
||||
|
||||
**S3.** Revokes all of the caller's sessions **except the current one** (all of them on a Bearer request). Response `200` `{"revoked": <integer>}`.
|
||||
|
||||
### 1.4 Own tokens and identity - R2 (extend existing handlers in place)
|
||||
|
||||
| # | Method + path | Role |
|
||||
|---|---|---|
|
||||
| T1 | `POST /api/auth/tokens` (extended) | own |
|
||||
| T2 | `GET /api/auth/tokens` (extended) | own |
|
||||
| M1 | `GET /api/auth/me` (extended, additive) | any |
|
||||
|
||||
**T1.** Request:
|
||||
```json
|
||||
{"name": "string (required, non-blank)", "expires_in_days": "integer 1..=3650 | null (optional; absent/null = never expires)", "scope": "\"full\" | \"read\" (optional, default \"full\")"}
|
||||
```
|
||||
Response `201`:
|
||||
```json
|
||||
{"token_uid": "tok_...", "raw_token": "string (shown once)", "name": "string", "expires_at": "ts|null", "scope": "full|read"}
|
||||
```
|
||||
Errors: `400` blank name, `expires_in_days` out of range, unknown `scope`. A `read` token cannot call this endpoint (see 3.8).
|
||||
|
||||
**T2.** Response `200`, array (newest first), same item shape as U4.
|
||||
|
||||
**T1/T2 unchanged:** `DELETE /api/auth/tokens/:token_uid` -> `204` / `404`.
|
||||
|
||||
**M1.** Existing fields stay: `role_bits: integer`, `username: string`, `display_name: string|null`, `humanize_slugs: boolean`, `can_reorder_children: boolean`. Added:
|
||||
```json
|
||||
{"user_uid": "usr_...", "roles": ["user", "admin"]}
|
||||
```
|
||||
`roles` = the caller's role slugs.
|
||||
|
||||
### 1.5 Capture jobs and runs - R3
|
||||
|
||||
| # | Method + path | Role |
|
||||
|---|---|---|
|
||||
| J1 | `GET /api/archives/:id/capture_jobs?status&limit&offset&created_by` | USER |
|
||||
| J2 | `GET /api/archives/:id/capture_jobs/:job_uid` (extended) | USER |
|
||||
| J3 | `GET /api/archives/:id/runs` (filtered) | any authenticated |
|
||||
|
||||
Job and run visibility: a caller sees a job if they created it (`capture_jobs.created_by == their user_uid`) or hold ADMIN. Rows with `created_by IS NULL` (pre-migration jobs, CLI-created) are visible to ADMIN only.
|
||||
|
||||
**J1.** Query: `status` (optional; `pending|running|completed|failed`, else `400`), `limit` (default 50, max 200, clamped), `offset` (default 0), `created_by` (optional user_uid; ADMIN may filter by anyone, a non-admin may only pass their own uid, otherwise `403`). Ordered `created_at DESC, id DESC`. Response `200`:
|
||||
```json
|
||||
[{"job_uid": "job_...", "archive_id": "string", "run_uid": "string|null", "status": "pending|running|completed|failed",
|
||||
"error_text": "string|null", "notes_json": "string|null", "created_at": "ts", "updated_at": "ts", "created_by": "usr_...|null"}]
|
||||
```
|
||||
Errors: 400, 401, 403, 404 (unknown archive).
|
||||
|
||||
**J2.** Existing response fields unchanged (`job_uid, archive_id, run_uid, status, error_text, notes_json, created_at, updated_at`). Added:
|
||||
```json
|
||||
{"entry_uids": ["ent_..."],
|
||||
"items": [{"item_uid": "string", "ordinal": 0, "requested_locator": "string", "canonical_locator": "string|null",
|
||||
"source_kind": "string", "entity_kind": "string", "status": "pending|in_progress|completed|failed",
|
||||
"error_text": "string|null", "entry_uid": "string|null"}]}
|
||||
```
|
||||
`items` come from `archive_run_items` of the job's run (empty while `run_uid` is null), ordered by `ordinal`; `entry_uid` is the produced entry (`produced_entry_id`), and `entry_uids` is the de-duplicated non-null list in item order. A caller who is neither the creator nor ADMIN gets `404` (not `403`), so job existence is not disclosed. `created_by` is also included.
|
||||
|
||||
**J3.** Response unchanged in shape (array of run summaries):
|
||||
```json
|
||||
[{"run_uid": "string", "started_at": "ts", "finished_at": "ts|null", "status": "in_progress|completed|failed",
|
||||
"requested_count": 0, "discovered_count": 0, "completed_count": 0, "failed_count": 0, "error_summary": "string|null"}]
|
||||
```
|
||||
but filtered: a run is visible if the caller is ADMIN, **or** created the job that owns the run (`capture_jobs.run_uid`), **or** can see at least one entry produced by the run's items (reuse the existing entry-visibility/collection filter). Runs with no job row (pre-migration) follow entry access only. Authenticated-only (guests still get `401`).
|
||||
|
||||
### 1.6 Archive info and effective config - R4
|
||||
|
||||
| # | Method + path | Role |
|
||||
|---|---|---|
|
||||
| I1 | `GET /api/archives/:id/info` | ADMIN |
|
||||
| I2 | `GET /api/admin/effective-config` | ADMIN |
|
||||
|
||||
**I1.** Counts and sizes only; no filesystem paths. Response `200`:
|
||||
```json
|
||||
{"archive_id": "string", "label": "string",
|
||||
"entry_count": 0, "root_entry_count": 0, "artifact_count": 0, "blob_count": 0, "blob_bytes": 0,
|
||||
"tag_count": 0, "collection_count": 0, "run_count": 0, "summary_count": 0,
|
||||
"job_counts": {"pending": 0, "running": 0, "completed": 0, "failed": 0}}
|
||||
```
|
||||
Errors: 401/403/404 (unknown archive).
|
||||
|
||||
**I2.** Read-only view of env-derived configuration, from a static `ENV_VARS` table in `effective_config.rs` (every `ARCHIVR_*` variable the code reads; a unit test greps the crates' source for `ARCHIVR_*` literals and fails on drift). Response `200`:
|
||||
```json
|
||||
{"env_vars": [{"name": "ARCHIVR_ANTHROPIC_API_KEY", "group": "summaries", "description": "string",
|
||||
"secret": true, "default": "string|null", "set": true, "value": "string|null"}],
|
||||
"summary_providers": [{"kind": "anthropic_http", "configured": true, "model": "string|null", "error": "string|null"}],
|
||||
"title_models": {"anthropic_http": {"model": "string", "source": "instance|env|default"}}}
|
||||
```
|
||||
- `secret: true` entries never carry a value: `value` is `null`, only `set` (true when the variable is set and non-empty) is reported.
|
||||
- Non-secret `value` is the effective string, or `null` when unset. URL-valued variables lose userinfo and query string (`https://user:pw@host/p?k=v` -> `https://host/p`).
|
||||
- `group` is one of `server`, `tools`, `summaries`, `titles`, `transcription`.
|
||||
- `summary_providers[].error` is the (secret-free) reason `provider_from_env` fails, e.g. which variable is missing.
|
||||
|
||||
## 2. Hardening of existing endpoints
|
||||
|
||||
Behavior changes to endpoints that already exist (R1 owns status/roles, R2 owns auth, R3 owns capture/archives):
|
||||
|
||||
1. `PATCH /api/admin/users/:uid/status`: runs the guard sequence of 0.1 with self-guard and last-owner guard. Disabling oneself -> `409`; disabling the last active owner -> `409`; ADMIN targeting an OWNER/ADMIN -> `403`. `status: "active"` re-enable needs only can-manage.
|
||||
2. `POST /api/admin/users/:uid/roles` (`{"role_slug": ...}`) and `DELETE /api/admin/users/:uid/roles/:role_slug`: granting or removing `owner` **or** `admin` requires OWNER (`403` otherwise); can-manage applies to the target; unknown role slug -> `404` (currently `500`); removing `owner` from the last active owner -> `409` (currently `500`).
|
||||
3. `POST /api/archives/:id/captures`: a `file://` locator is accepted **only** if it points at a staged upload previously created through `POST /api/archives/:id/uploads` (under the archive's `temp/uploads/`); any other `file://` locator (e.g. `file:///etc/passwd`) -> `400`. The CLI is unaffected. (`rearchive`, text capture unchanged.)
|
||||
4. Bearer auth now calls `touch_token`: `api_tokens.last_used_at` is set on use, throttled so it is written at most once per 60 s per token. Visible in T2/U4.
|
||||
5. `PATCH /api/auth/me`: `new_password` must be >= 8 characters (`400`), and a successful password change deletes every *other* session of the user (the caller's current session survives).
|
||||
6. `GET /api/archives` (unauthenticated today): `archive_path` is omitted from each item unless the caller is ADMIN. Items are `{"id", "label"}` for everyone else. (The admin view in the frontend reads `archive_path` as an admin, so it keeps working.)
|
||||
7. **Read-scope tokens**: Bearer requests authenticated by a token with `scope = "read"` get `403 {"error": "read-only token"}` on any method other than `GET`, `HEAD`, `OPTIONS`. Cookie sessions are unaffected. Implemented as middleware in `token_scope.rs`.
|
||||
8. Bearer tokens past `expires_at` are rejected: the request is treated as unauthenticated (`401` on endpoints that require auth). (Already enforced in `database::get_user_for_token`; covered by a regression test.)
|
||||
9. `capture_jobs.created_by` is now recorded (the submitter's `user_uid`) by `capture_handler`, text capture, and rearchive via `database::create_capture_job_as`; other callers keep `create_capture_job` (NULL owner).
|
||||
|
||||
Out of scope (not proposed): entry metadata edits beyond title, job cancel, server-side entry pagination, frontend/UI updates, admin edit of email/display name.
|
||||
|
||||
## 3. Foundation delivered by R0 (what the streams build on)
|
||||
|
||||
### 3.1 Schema (existing convention: `let _ = ALTER TABLE ... ADD COLUMN`, no version table)
|
||||
|
||||
- `capture_jobs.created_by TEXT` (auth `users.user_uid`; NULL for legacy/CLI rows) + `idx_capture_jobs_created_by`. In `initialize_schema`; the index is created *after* the `ALTER` so legacy tables migrate.
|
||||
- `api_tokens.scope TEXT NOT NULL DEFAULT 'full'` (`full` | `read`). In `initialize_auth_schema`. `api_tokens.expires_at` already existed.
|
||||
- Migration tests: `initialize_schema_migrates_created_by_for_existing_capture_jobs`, `initialize_auth_schema_migrates_scope_for_existing_api_tokens` (legacy table built by hand, init run twice).
|
||||
|
||||
### 3.2 `archivr_core::database` signatures
|
||||
|
||||
```rust
|
||||
pub struct ApiTokenRecord { token_uid, name, created_at, last_used_at: Option<String>, expires_at: Option<String>, scope: String }
|
||||
pub fn create_api_token(conn, user_id: i64, token_hash: &str, name: &str, expires_at: Option<&str>, scope: &str) -> Result<String>;
|
||||
pub fn get_user_for_token(conn, token_hash: &str) -> Result<Option<(i64 /*user_id*/, String /*token_uid*/)>>;
|
||||
pub fn touch_token(conn, token_uid: &str) -> Result<()>; // existing; not yet called from auth
|
||||
pub fn create_capture_job_as(conn, archive_id: &str, created_by: Option<&str>) -> Result<String>;
|
||||
pub fn create_capture_job(conn, archive_id: &str) -> Result<String>; // delegates with None
|
||||
pub fn get_user_uid(conn, user_id: i64) -> Result<Option<String>>;
|
||||
```
|
||||
|
||||
`list_user_tokens` and therefore the existing `GET /api/auth/tokens` response gained `expires_at` and `scope` (additive; this is T2). `CaptureJobRecord` is unchanged (add `created_by` there in R3 if needed).
|
||||
|
||||
### 3.3 Module stubs
|
||||
|
||||
Core: `auth_users.rs`, `auth_credentials.rs`, `capture_jobs.rs` (empty, declared in `lib.rs`). Server: `admin_users`, `credentials`, `jobs`, `effective_config` (each `pub fn routes() -> Router<AppState>` returning `Router::new()`, merged in `app_with_state`), `token_scope` (stub `routes()` plus a pass-through `enforce_read_scope` middleware signature; not wired yet), `guards` (implemented, see 0.1), `test_support` (`#[cfg(test)]`).
|
||||
|
||||
### 3.4 `guards.rs` (implemented)
|
||||
|
||||
```rust
|
||||
pub fn ensure_can_manage(caller_bits: u32, target_bits: u32) -> Result<(), ApiError>; // 403
|
||||
pub fn ensure_not_self(caller_id: i64, target_id: i64) -> Result<(), ApiError>; // 409
|
||||
pub fn ensure_not_last_owner(conn: &rusqlite::Connection, target_id: i64) -> Result<(), ApiError>; // 409, auth DB conn
|
||||
```
|
||||
|
||||
### 3.5 `routes.rs` visibility
|
||||
|
||||
`AppState.registry` is `pub(crate)`; `ApiError::{not_found, bad_request, internal, conflict}` and the `status`/`message` fields are `pub(crate)` (`unauthorized`/`forbidden` were already `pub`); `mounted_archive(&AppState, &str)` and `auth_to_caller_bits(&AuthUser)` are `pub(crate)`. Role checks are the existing `AuthUser::{require_auth, require_role, has_role}`. `ROLE_*` consts are re-exported from `routes` and live in `auth`.
|
||||
|
||||
### 3.6 Test helpers (`crates/archivr-server/src/test_support.rs`)
|
||||
|
||||
```rust
|
||||
pub(crate) fn make_test_registry(&TempDir) -> (ServerRegistry, PathBuf /*archive*/, PathBuf /*auth db*/); // owner "testowner" seeded
|
||||
pub(crate) fn make_test_session(&Path) -> String; // owner cookie
|
||||
pub(crate) fn make_role_session(&Path, username: &str, roles: &[&str]) -> String;
|
||||
pub(crate) fn owner_session(&Path) -> String; admin_session / user_session / guest_session (fixed usernames test-admin / test-user / test-guest; once per auth DB)
|
||||
pub(crate) fn make_api_token(&Path, username: &str, expires: Option<&str>, scope: &str) -> String; // raw token
|
||||
pub(crate) async fn body_json(Response) -> serde_json::Value;
|
||||
pub(crate) fn json_body(&serde_json::Value) -> Body;
|
||||
```
|
||||
The originals in `routes.rs` `mod tests` are untouched (copies, not moves).
|
||||
|
||||
### 3.7 Axum `Router::merge` finding (axum 0.7.9, verified by tests in `test_support.rs`)
|
||||
|
||||
- Merging routers that register **different methods on the same path** works: the method routers are combined (`GET`+`POST` on `/api/auth/tokens` from the base router plus `DELETE` on the same path from a merged router gives all three, and other methods return `405`). The same holds for two merged routers that each add one method to a brand-new path.
|
||||
- Registering the **same method on the same path twice** (e.g. a second `GET /api/auth/tokens`) **panics at router construction** ("Overlapping method route"), i.e. at server startup and in every test that builds the app.
|
||||
- Consequences for the streams: (a) new paths and new methods on existing paths may go in the stream's own `routes()`; (b) **extending an existing handler (T1, T2, M1, J2, `PATCH /api/auth/me`, the status/roles/capture hardening, `GET /api/archives`) must be done by editing the handler in `routes.rs` in place**, never by re-registering the same method+path from a stream module; (c) `.merge(...)` calls sit before `.fallback_service(...)` and the `.layer(...)`s in `app_with_state`, so streams' routes get the existing middleware (`setup_guard`, `login_rate_limit`, `security_headers`).
|
||||
- Current paths by owner: `DELETE /api/admin/users/:uid`, `.../password`, `.../sessions`, `.../tokens[/:token_uid]`, `PATCH|DELETE /api/admin/roles/:slug`, `/api/auth/sessions[/:handle]`, `/api/archives/:id/capture_jobs` (list), `/api/archives/:id/info`, `/api/admin/effective-config` are all **new paths** (no existing registration at the same path), so streams can add them via `routes()` without conflict. `/api/admin/users/:uid` (bare) does not exist today.
|
||||
|
||||
### 3.8 Read-scope reminder
|
||||
|
||||
A `read` token cannot create tokens, change passwords, or capture (all non-GET). It can poll jobs and read everything its user can read.
|
||||
|
||||
## 4. Test requirements (all streams)
|
||||
|
||||
Follow the `oneshot` style in `routes.rs` `mod tests`, helpers from `test_support.rs`. For every new endpoint: guest 401, USER 403, ADMIN 200/201/204. For user-targeting endpoints additionally: ADMIN-vs-OWNER 403, ADMIN-vs-ADMIN 403, self 409, last-owner 409 where applicable. Regressions: user delete after assigning roles (FK `assigned_by_user_id`), `session_uid` never in any response body, secret canary env value absent from effective-config, back-dated `expires_at` -> 401, read-scope token 403 on POST, job and run scoping between two users, `file:///etc/hosts` capture -> 400, disabled/deleted user's tokens and sessions stop working.
|
||||
Loading…
Add table
Add a link
Reference in a new issue