From 7b4a35feee7ae2da522030e80a7eaa3b1e1e6f15 Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:31:42 +0200 Subject: [PATCH] feat: R3 capture job listing, scoped job detail, access-based runs, file:// guard, archive_path redaction - created_by recorded by capture, text capture and rearchive handlers - J1 GET /api/archives/:id/capture_jobs (jobs.rs), J2 entry_uids/items on job detail - J3 runs filtered by admin / job creator / entry access, optional limit/offset - H4 file:// locators must reference a staged upload (400 otherwise) - H5 GET /api/archives omits archive_path for non-admins Co-Authored-By: Claude Sonnet 5.5 --- crates/archivr-core/src/archive.rs | 83 ++- crates/archivr-core/src/capture_jobs.rs | 183 +++++- crates/archivr-core/src/database.rs | 5 +- crates/archivr-server/src/jobs.rs | 776 +++++++++++++++++++++++- crates/archivr-server/src/routes.rs | 112 +++- 5 files changed, 1110 insertions(+), 49 deletions(-) diff --git a/crates/archivr-core/src/archive.rs b/crates/archivr-core/src/archive.rs index 0293cb1..cea910c 100644 --- a/crates/archivr-core/src/archive.rs +++ b/crates/archivr-core/src/archive.rs @@ -90,6 +90,8 @@ pub struct CaptureJobSummary { pub notes_json: Option, pub created_at: String, pub updated_at: String, + /// Submitter's auth-DB `user_uid`; null for CLI/legacy jobs. + pub created_by: Option, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] @@ -371,6 +373,20 @@ pub fn get_entry_detail( })) } +fn run_summary_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(RunSummary { + run_uid: row.get(0)?, + started_at: row.get(1)?, + finished_at: row.get(2)?, + status: row.get(3)?, + requested_count: row.get(4)?, + discovered_count: row.get(5)?, + completed_count: row.get(6)?, + failed_count: row.get(7)?, + error_summary: row.get(8)?, + }) +} + pub fn list_runs(conn: &rusqlite::Connection) -> Result> { let mut stmt = conn.prepare( "SELECT run_uid, started_at, finished_at, status, requested_count, @@ -379,24 +395,64 @@ pub fn list_runs(conn: &rusqlite::Connection) -> Result> { ORDER BY started_at DESC, id DESC", )?; let runs = stmt - .query_map([], |row| { - Ok(RunSummary { - run_uid: row.get(0)?, - started_at: row.get(1)?, - finished_at: row.get(2)?, - status: row.get(3)?, - requested_count: row.get(4)?, - discovered_count: row.get(5)?, - completed_count: row.get(6)?, - failed_count: row.get(7)?, - error_summary: row.get(8)?, - }) - })? + .query_map([], run_summary_from_row)? .collect::>>()?; Ok(runs) } +/// Runs the caller may see, newest first. A run is visible when the caller holds +/// ADMIN/OWNER (bits 12), or created the capture job that owns the run +/// (`capture_jobs.run_uid`, `created_by == caller_user_uid`), or can see at least one +/// entry the run produced. Entry visibility is the rule `list_entries_for_collection` / +/// `list_child_entries` apply: a `collection_entries` row of the entry (or, for a child +/// entry, of its parent) whose `visibility_bits` overlap `caller_bits`. +/// `limit = None` returns everything after `offset`. +pub fn list_runs_for_caller( + conn: &rusqlite::Connection, + caller_bits: u32, + caller_user_uid: Option<&str>, + limit: Option, + offset: i64, +) -> Result> { + let mut stmt = conn.prepare( + "SELECT r.run_uid, r.started_at, r.finished_at, r.status, r.requested_count, + r.discovered_count, r.completed_count, r.failed_count, r.error_summary + FROM archive_runs r + WHERE CAST(?1 AS INTEGER) & 12 != 0 + OR EXISTS ( + SELECT 1 FROM capture_jobs j + WHERE j.run_uid = r.run_uid AND j.created_by = ?2 + ) + OR EXISTS ( + SELECT 1 FROM archive_run_items i + JOIN archived_entries e ON e.id = i.produced_entry_id + WHERE i.run_id = r.id + AND ( + EXISTS ( + SELECT 1 FROM collection_entries ce + WHERE ce.entry_id = e.id + AND ce.visibility_bits & CAST(?1 AS INTEGER) != 0 + ) + OR EXISTS ( + SELECT 1 FROM collection_entries ce_p + WHERE ce_p.entry_id = e.parent_entry_id + AND ce_p.visibility_bits & CAST(?1 AS INTEGER) != 0 + ) + ) + ) + ORDER BY r.started_at DESC, r.id DESC + LIMIT ?3 OFFSET ?4", + )?; + let runs = stmt + .query_map( + rusqlite::params![caller_bits as i64, caller_user_uid, limit.unwrap_or(-1), offset], + run_summary_from_row, + )? + .collect::>>()?; + Ok(runs) +} + pub fn get_capture_job( conn: &rusqlite::Connection, job_uid: &str, @@ -411,6 +467,7 @@ pub fn get_capture_job( notes_json: r.notes_json, created_at: r.created_at, updated_at: r.updated_at, + created_by: r.created_by, }), ) } diff --git a/crates/archivr-core/src/capture_jobs.rs b/crates/archivr-core/src/capture_jobs.rs index dec695e..1cd1ffa 100644 --- a/crates/archivr-core/src/capture_jobs.rs +++ b/crates/archivr-core/src/capture_jobs.rs @@ -1,2 +1,183 @@ //! Capture-job listing and scoping queries (`created_by` filters, per-job items). -//! Stub: filled in by the jobs stream. +use anyhow::Result; +use rusqlite::Connection; + +use crate::archive::CaptureJobSummary; + +/// Valid `capture_jobs.status` values (the table's CHECK constraint). +pub const JOB_STATUSES: [&str; 4] = ["pending", "running", "completed", "failed"]; +/// Default and maximum page size for `list_capture_jobs`. +pub const JOB_LIST_DEFAULT_LIMIT: i64 = 50; +pub const JOB_LIST_MAX_LIMIT: i64 = 200; +/// Maximum number of per-item rows returned by `list_job_items`. +pub const JOB_ITEMS_MAX: usize = 200; + +/// Lists capture jobs newest first (`created_at DESC, id DESC`). +/// +/// `created_by = Some(uid)` restricts to jobs submitted by that user (this is how a +/// non-admin is scoped; it also excludes NULL-owner rows); `None` returns every job. +/// `limit` is clamped to 1..=200, `offset` to >= 0. +pub fn list_capture_jobs( + conn: &Connection, + status: Option<&str>, + created_by: Option<&str>, + limit: i64, + offset: i64, +) -> Result> { + let limit = limit.clamp(1, JOB_LIST_MAX_LIMIT); + let offset = offset.max(0); + let mut stmt = conn.prepare( + "SELECT job_uid, archive_id, run_uid, status, error_text, notes_json, + created_at, updated_at, created_by + FROM capture_jobs + WHERE (?1 IS NULL OR status = ?1) + AND (?2 IS NULL OR created_by = ?2) + ORDER BY created_at DESC, id DESC + LIMIT ?3 OFFSET ?4", + )?; + let rows = stmt + .query_map(rusqlite::params![status, created_by, limit, offset], |row| { + Ok(CaptureJobSummary { + job_uid: row.get(0)?, + archive_id: row.get(1)?, + run_uid: row.get(2)?, + status: row.get(3)?, + error_text: row.get(4)?, + notes_json: row.get(5)?, + created_at: row.get(6)?, + updated_at: row.get(7)?, + created_by: row.get(8)?, + }) + })? + .collect::>>()?; + Ok(rows) +} + +/// One `archive_run_items` row of a job's run. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct JobItem { + pub item_uid: String, + pub ordinal: i64, + pub requested_locator: String, + pub canonical_locator: Option, + pub source_kind: String, + pub entity_kind: String, + pub status: String, + pub error_text: Option, + /// Produced entry (`produced_entry_id` resolved to its `entry_uid`). + pub entry_uid: Option, +} + +/// Items and produced entries of a job's run. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct JobItems { + /// De-duplicated non-null `entry_uid`s over *all* items, in item order. + pub entry_uids: Vec, + /// At most `JOB_ITEMS_MAX` items ordered by `ordinal`. + pub items: Vec, + pub items_truncated: bool, +} + +/// Items of the run `run_uid` (empty when the run is unknown). Mirrors the spec's J2. +pub fn list_job_items(conn: &Connection, run_uid: &str) -> Result { + let mut stmt = conn.prepare( + "SELECT i.item_uid, i.ordinal, i.requested_locator, i.canonical_locator, + i.source_kind, i.entity_kind, i.status, i.error_text, e.entry_uid + FROM archive_run_items i + JOIN archive_runs r ON r.id = i.run_id + LEFT JOIN archived_entries e ON e.id = i.produced_entry_id + WHERE r.run_uid = ?1 + ORDER BY i.ordinal ASC, i.id ASC", + )?; + let all = stmt + .query_map([run_uid], |row| { + Ok(JobItem { + item_uid: row.get(0)?, + ordinal: row.get(1)?, + requested_locator: row.get(2)?, + canonical_locator: row.get(3)?, + source_kind: row.get(4)?, + entity_kind: row.get(5)?, + status: row.get(6)?, + error_text: row.get(7)?, + entry_uid: row.get(8)?, + }) + })? + .collect::>>()?; + + let mut entry_uids: Vec = Vec::new(); + for uid in all.iter().filter_map(|i| i.entry_uid.as_ref()) { + if !entry_uids.contains(uid) { + entry_uids.push(uid.clone()); + } + } + let items_truncated = all.len() > JOB_ITEMS_MAX; + let items = all.into_iter().take(JOB_ITEMS_MAX).collect(); + Ok(JobItems { + entry_uids, + items, + items_truncated, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database; + + fn conn() -> Connection { + let conn = Connection::open_in_memory().unwrap(); + database::initialize_schema(&conn).unwrap(); + conn + } + + #[test] + fn list_filters_by_owner_status_and_pages() { + let conn = conn(); + let a1 = database::create_capture_job_as(&conn, "t", Some("usr_a")).unwrap(); + let a2 = database::create_capture_job_as(&conn, "t", Some("usr_a")).unwrap(); + let _b = database::create_capture_job_as(&conn, "t", Some("usr_b")).unwrap(); + let _legacy = database::create_capture_job(&conn, "t").unwrap(); + database::update_capture_job_status(&conn, &a1, "failed", None, Some("x"), None).unwrap(); + + assert_eq!(list_capture_jobs(&conn, None, None, 50, 0).unwrap().len(), 4); + let mine = list_capture_jobs(&conn, None, Some("usr_a"), 50, 0).unwrap(); + assert_eq!(mine.len(), 2); + assert!(mine.iter().all(|j| j.created_by.as_deref() == Some("usr_a"))); + let failed = list_capture_jobs(&conn, Some("failed"), Some("usr_a"), 50, 0).unwrap(); + assert_eq!(failed.len(), 1); + assert_eq!(failed[0].job_uid, a1); + // newest first, offset pages through + let page = list_capture_jobs(&conn, None, Some("usr_a"), 1, 0).unwrap(); + assert_eq!(page[0].job_uid, a2); + let page2 = list_capture_jobs(&conn, None, Some("usr_a"), 1, 1).unwrap(); + assert_eq!(page2[0].job_uid, a1); + // limit is clamped to >= 1 + assert_eq!(list_capture_jobs(&conn, None, None, 0, 0).unwrap().len(), 1); + } + + #[test] + fn job_items_resolve_entry_uids_and_dedupe() { + let conn = conn(); + let user_id = database::ensure_default_user(&conn).unwrap(); + let run = database::create_archive_run(&conn, user_id, 1).unwrap(); + for ordinal in 0..2 { + database::create_archive_run_item( + &conn, + run.id, + None, + ordinal, + "text:x", + None, + "text", + "text", + ) + .unwrap(); + } + let items = list_job_items(&conn, &run.run_uid).unwrap(); + assert_eq!(items.items.len(), 2); + assert!(items.entry_uids.is_empty()); + assert!(!items.items_truncated); + assert!(list_job_items(&conn, "run_missing").unwrap().items.is_empty()); + } +} diff --git a/crates/archivr-core/src/database.rs b/crates/archivr-core/src/database.rs index f91a7b4..35d668d 100644 --- a/crates/archivr-core/src/database.rs +++ b/crates/archivr-core/src/database.rs @@ -112,6 +112,8 @@ pub struct CaptureJobRecord { pub notes_json: Option, pub created_at: String, pub updated_at: String, + /// Auth-DB `user_uid` of the submitter; None for CLI/legacy jobs. + pub created_by: Option, } /// One row of `entry_summaries` — a regenerable LLM summary of an entry. @@ -1694,7 +1696,7 @@ pub fn update_capture_job_status( /// Returns a capture job by uid. pub fn get_capture_job(conn: &Connection, job_uid: &str) -> Result> { conn.query_row( - "SELECT job_uid, archive_id, run_uid, status, error_text, notes_json, created_at, updated_at + "SELECT job_uid, archive_id, run_uid, status, error_text, notes_json, created_at, updated_at, created_by FROM capture_jobs WHERE job_uid = ?1", [job_uid], |row| { @@ -1707,6 +1709,7 @@ pub fn get_capture_job(conn: &Connection, job_uid: &str) -> Result Router { - Router::new() + Router::new().route( + "/api/archives/:archive_id/capture_jobs", + get(list_capture_jobs_handler), + ) +} + +/// Resolves the caller's auth-DB `user_uid` (sessions and Bearer tokens both map to a +/// user). `None` for guests or an unknown user id. +pub(crate) fn caller_user_uid( + state: &AppState, + auth: &AuthUser, +) -> Result, ApiError> { + match auth { + AuthUser::Authenticated { user_id, .. } => { + let conn = database::open_auth_db(&state.auth_db_path)?; + Ok(database::get_user_uid(&conn, *user_id)?) + } + AuthUser::Guest => Ok(None), + } +} + +/// Parses an optional integer query parameter; non-integers are a 400 (JSON error body). +pub(crate) fn parse_int_param(name: &str, raw: Option<&str>) -> Result, ApiError> { + match raw { + None => Ok(None), + Some(s) => s + .trim() + .parse::() + .map(Some) + .map_err(|_| ApiError::bad_request(&format!("{name} must be an integer"))), + } +} + +#[derive(Debug, serde::Deserialize, Default)] +struct JobListQuery { + status: Option, + limit: Option, + offset: Option, + created_by: Option, +} + +/// `GET /api/archives/:archive_id/capture_jobs` (J1). +async fn list_capture_jobs_handler( + State(state): State, + auth: AuthUser, + Path(archive_id): Path, + Query(q): Query, +) -> Result>, ApiError> { + auth.require_role(ROLE_USER)?; + if let Some(status) = q.status.as_deref() { + if !capture_jobs::JOB_STATUSES.contains(&status) { + return Err(ApiError::bad_request( + "invalid status: must be pending, running, completed, or failed", + )); + } + } + let limit = parse_int_param("limit", q.limit.as_deref())? + .unwrap_or(capture_jobs::JOB_LIST_DEFAULT_LIMIT); + let offset = parse_int_param("offset", q.offset.as_deref())?.unwrap_or(0); + let mounted = mounted_archive(&state, &archive_id)?; + let caller_uid = caller_user_uid(&state, &auth)? + .ok_or_else(|| ApiError::unauthorized("login required"))?; + let is_admin = auth.has_role(ROLE_ADMIN); + + // `None` = no owner filter (admin only); a non-admin is always scoped to themselves. + let owner: Option = match q.created_by.as_deref() { + None | Some("all") if is_admin => None, + None | Some("all") | Some("me") => Some(caller_uid), + Some(uid) if uid == caller_uid => Some(caller_uid), + Some(uid) if is_admin => Some(uid.to_string()), + Some(_) => { + return Err(ApiError::forbidden( + "you can only list your own capture jobs", + )); + } + }; + + let conn = database::open_or_initialize(&mounted.archive_path)?; + Ok(Json(capture_jobs::list_capture_jobs( + &conn, + q.status.as_deref(), + owner.as_deref(), + limit, + offset, + )?)) +} + +/// `GET .../capture_jobs/:job_uid` response (J2): the existing job fields plus the +/// produced entries and per-item outcomes of the job's run. +#[derive(Debug, serde::Serialize)] +pub(crate) struct CaptureJobDetail { + #[serde(flatten)] + job: archive::CaptureJobSummary, + entry_uids: Vec, + items: Vec, + items_truncated: bool, +} + +/// Loads a job for `GET .../capture_jobs/:job_uid`. A caller who neither created the job +/// nor holds ADMIN gets 404, so the job's existence is not disclosed. +pub(crate) fn get_job_detail( + state: &AppState, + auth: &AuthUser, + archive_path: &FsPath, + job_uid: &str, +) -> Result { + let conn = database::open_or_initialize(archive_path)?; + let job = archive::get_capture_job(&conn, job_uid)? + .ok_or_else(|| ApiError::not_found("capture job not found"))?; + if !auth.has_role(ROLE_ADMIN) { + let caller_uid = caller_user_uid(state, auth)?; + if caller_uid.is_none() || job.created_by != caller_uid { + return Err(ApiError::not_found("capture job not found")); + } + } + let items = match job.run_uid.as_deref() { + Some(run_uid) => capture_jobs::list_job_items(&conn, run_uid)?, + None => capture_jobs::JobItems { + entry_uids: Vec::new(), + items: Vec::new(), + items_truncated: false, + }, + }; + Ok(CaptureJobDetail { + job, + entry_uids: items.entry_uids, + items: items.items, + items_truncated: items.items_truncated, + }) +} + +#[cfg(test)] +mod tests { + use std::path::{Path as FsPath, PathBuf}; + + use archivr_core::database; + use axum::{ + Router, + body::Body, + http::{Request, StatusCode}, + }; + use serde_json::{Value, json}; + use tower::ServiceExt; + + use crate::routes::app; + use crate::test_support::{ + admin_session, body_json, json_body, make_api_token, make_role_session, make_test_registry, + make_test_session, + }; + + struct Fixture { + _dir: tempfile::TempDir, + router: Router, + archive_path: PathBuf, + auth_path: PathBuf, + } + + fn fixture() -> Fixture { + let dir = tempfile::tempdir().unwrap(); + let (registry, archive_path, auth_path) = make_test_registry(&dir); + let router = app(registry, auth_path.clone()); + Fixture { + _dir: dir, + router, + archive_path, + auth_path, + } + } + + /// Session whose cached role bits are GUEST only. (`guest_session` in test_support + /// still holds the `user` role because `create_user` always grants it.) + fn guest_only_session(auth_path: &FsPath) -> String { + make_role_session(auth_path, "guest-only", &["guest"]); + let conn = database::open_auth_db(auth_path).unwrap(); + let user_id: i64 = conn + .query_row("SELECT id FROM users WHERE username = 'guest-only'", [], |r| r.get(0)) + .unwrap(); + conn.execute("DELETE FROM sessions WHERE user_id = ?1", [user_id]).unwrap(); + format!( + "session={}", + database::create_session(&conn, user_id, 1, None).unwrap() + ) + } + + fn user_uid(auth_path: &FsPath, username: &str) -> String { + let conn = database::open_auth_db(auth_path).unwrap(); + conn.query_row( + "SELECT user_uid FROM users WHERE username = ?1", + [username], + |r| r.get(0), + ) + .unwrap() + } + + async fn get(router: &Router, uri: &str, cookie: Option<&str>) -> (StatusCode, Value) { + let mut req = Request::builder().uri(uri); + if let Some(c) = cookie { + req = req.header("cookie", c); + } + let resp = router + .clone() + .oneshot(req.body(Body::empty()).unwrap()) + .await + .unwrap(); + let status = resp.status(); + (status, body_json(resp).await) + } + + async fn post_json( + router: &Router, + uri: &str, + auth_header: (&str, &str), + payload: &Value, + ) -> (StatusCode, Value) { + let resp = router + .clone() + .oneshot( + Request::builder() + .method("POST") + .uri(uri) + .header("content-type", "application/json") + .header(auth_header.0, auth_header.1) + .body(json_body(payload)) + .unwrap(), + ) + .await + .unwrap(); + let status = resp.status(); + (status, body_json(resp).await) + } + + async fn wait_job(archive_path: &FsPath, job_uid: &str) -> String { + tokio::time::timeout(std::time::Duration::from_secs(10), async { + loop { + let conn = database::open_or_initialize(archive_path).unwrap(); + let job = database::get_capture_job(&conn, job_uid).unwrap().unwrap(); + if job.status != "pending" && job.status != "running" { + break job.status; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .expect("capture job should finish") + } + + /// Submits a text capture as `cookie` and waits for the job; returns the job uid. + async fn text_capture(f: &Fixture, cookie: &str, title: &str) -> String { + let (status, body) = post_json( + &f.router, + "/api/archives/test/captures/text", + ("cookie", cookie), + &json!({"title": title, "body": format!("body of {title}"), "mime": "text/plain"}), + ) + .await; + assert_eq!(status, StatusCode::ACCEPTED, "{body}"); + let job_uid = body["job_uid"].as_str().unwrap().to_string(); + assert_eq!(wait_job(&f.archive_path, &job_uid).await, "completed"); + job_uid + } + + fn uids(list: &Value) -> Vec { + list.as_array() + .unwrap() + .iter() + .map(|j| j["job_uid"].as_str().unwrap().to_string()) + .collect() + } + + #[tokio::test] + async fn job_list_requires_user_role() { + let f = fixture(); + let (s, _) = get(&f.router, "/api/archives/test/capture_jobs", None).await; + assert_eq!(s, StatusCode::UNAUTHORIZED); + let guest = guest_only_session(&f.auth_path); + let (s, _) = get(&f.router, "/api/archives/test/capture_jobs", Some(&guest)).await; + assert_eq!(s, StatusCode::FORBIDDEN); + let (s, _) = get( + &f.router, + "/api/archives/nope/capture_jobs", + Some(&make_test_session(&f.auth_path)), + ) + .await; + assert_eq!(s, StatusCode::NOT_FOUND); + } + + #[tokio::test] + async fn users_only_see_their_own_jobs_and_admin_sees_all() { + let f = fixture(); + let alice = make_role_session(&f.auth_path, "alice", &["user"]); + let bob = make_role_session(&f.auth_path, "bob", &["user"]); + let admin = admin_session(&f.auth_path); + let alice_uid = user_uid(&f.auth_path, "alice"); + let bob_uid = user_uid(&f.auth_path, "bob"); + + let alice_job = text_capture(&f, &alice, "alice note").await; + let bob_job = text_capture(&f, &bob, "bob note").await; + let legacy_job = { + let conn = database::open_or_initialize(&f.archive_path).unwrap(); + database::create_capture_job(&conn, "test").unwrap() + }; + + let (s, list) = get(&f.router, "/api/archives/test/capture_jobs", Some(&alice)).await; + assert_eq!(s, StatusCode::OK); + assert_eq!(uids(&list), vec![alice_job.clone()]); + assert_eq!(list[0]["created_by"], alice_uid); + let (_, list) = get(&f.router, "/api/archives/test/capture_jobs", Some(&bob)).await; + assert_eq!(uids(&list), vec![bob_job.clone()]); + + // GET by uid: someone else's job and NULL-owner jobs are 404, not 403. + let base = "/api/archives/test/capture_jobs"; + let (s, _) = get(&f.router, &format!("{base}/{bob_job}"), Some(&alice)).await; + assert_eq!(s, StatusCode::NOT_FOUND); + let (s, _) = get(&f.router, &format!("{base}/{legacy_job}"), Some(&alice)).await; + assert_eq!(s, StatusCode::NOT_FOUND); + let (s, own) = get(&f.router, &format!("{base}/{alice_job}"), Some(&alice)).await; + assert_eq!(s, StatusCode::OK); + assert_eq!(own["created_by"], alice_uid); + + // Admin sees everything, including the NULL-owner row. + let (s, all) = get(&f.router, base, Some(&admin)).await; + assert_eq!(s, StatusCode::OK); + let all = uids(&all); + for j in [&alice_job, &bob_job, &legacy_job] { + assert!(all.contains(j), "admin should see {j}"); + } + for j in [&alice_job, &bob_job, &legacy_job] { + let (s, _) = get(&f.router, &format!("{base}/{j}"), Some(&admin)).await; + assert_eq!(s, StatusCode::OK); + } + let (_, mine) = get(&f.router, &format!("{base}?created_by=me"), Some(&admin)).await; + assert!(uids(&mine).is_empty()); + let (_, bobs) = get( + &f.router, + &format!("{base}?created_by={bob_uid}"), + Some(&admin), + ) + .await; + assert_eq!(uids(&bobs), vec![bob_job.clone()]); + + // Non-admins may only ask for themselves. + let (s, _) = get( + &f.router, + &format!("{base}?created_by={bob_uid}"), + Some(&alice), + ) + .await; + assert_eq!(s, StatusCode::FORBIDDEN); + let (s, l) = get(&f.router, &format!("{base}?created_by=me"), Some(&alice)).await; + assert_eq!((s, uids(&l)), (StatusCode::OK, vec![alice_job.clone()])); + let (s, l) = get(&f.router, &format!("{base}?created_by=all"), Some(&alice)).await; + assert_eq!((s, uids(&l)), (StatusCode::OK, vec![alice_job.clone()])); + let (s, l) = get( + &f.router, + &format!("{base}?created_by={alice_uid}"), + Some(&alice), + ) + .await; + assert_eq!((s, uids(&l)), (StatusCode::OK, vec![alice_job])); + } + + #[tokio::test] + async fn job_list_status_limit_and_offset() { + let f = fixture(); + let alice = make_role_session(&f.auth_path, "alice", &["user"]); + let alice_uid = user_uid(&f.auth_path, "alice"); + let (first, second, failed) = { + let conn = database::open_or_initialize(&f.archive_path).unwrap(); + let a = database::create_capture_job_as(&conn, "test", Some(&alice_uid)).unwrap(); + let b = database::create_capture_job_as(&conn, "test", Some(&alice_uid)).unwrap(); + let c = database::create_capture_job_as(&conn, "test", Some(&alice_uid)).unwrap(); + database::update_capture_job_status(&conn, &c, "failed", None, Some("boom"), None) + .unwrap(); + (a, b, c) + }; + let base = "/api/archives/test/capture_jobs"; + + let (s, l) = get(&f.router, base, Some(&alice)).await; + assert_eq!(s, StatusCode::OK); + assert_eq!(uids(&l), vec![failed.clone(), second.clone(), first.clone()]); + + let (_, l) = get(&f.router, &format!("{base}?status=failed"), Some(&alice)).await; + assert_eq!(uids(&l), vec![failed.clone()]); + assert_eq!(l[0]["error_text"], "boom"); + let (_, l) = get(&f.router, &format!("{base}?status=pending"), Some(&alice)).await; + assert_eq!(uids(&l), vec![second.clone(), first.clone()]); + + let (_, l) = get(&f.router, &format!("{base}?limit=1"), Some(&alice)).await; + assert_eq!(uids(&l), vec![failed.clone()]); + let (_, l) = get(&f.router, &format!("{base}?limit=1&offset=1"), Some(&alice)).await; + assert_eq!(uids(&l), vec![second]); + let (s, l) = get(&f.router, &format!("{base}?limit=100000"), Some(&alice)).await; + assert_eq!((s, l.as_array().unwrap().len()), (StatusCode::OK, 3)); + + for bad in ["status=bogus", "limit=abc", "offset=x"] { + let (s, body) = get(&f.router, &format!("{base}?{bad}"), Some(&alice)).await; + assert_eq!(s, StatusCode::BAD_REQUEST, "{bad}"); + assert!(body["error"].is_string()); + } + } + + #[tokio::test] + async fn token_and_session_callers_are_recorded_as_job_creators() { + let f = fixture(); + let _ = make_role_session(&f.auth_path, "carol", &["user"]); + let carol_uid = user_uid(&f.auth_path, "carol"); + let token = make_api_token(&f.auth_path, "carol", None, "full"); + + let (s, body) = post_json( + &f.router, + "/api/archives/test/captures/text", + ("authorization", &format!("Bearer {token}")), + &json!({"title": "t", "body": "b", "mime": "text/plain"}), + ) + .await; + assert_eq!(s, StatusCode::ACCEPTED); + let job_uid = body["job_uid"].as_str().unwrap(); + wait_job(&f.archive_path, job_uid).await; + + // Rearchive of an unknown entry still records its job (then fails in the background). + let carol = make_role_session(&f.auth_path, "dave", &["user"]); + let dave_uid = user_uid(&f.auth_path, "dave"); + let (s, body) = post_json( + &f.router, + "/api/archives/test/entries/ent_missing/rearchive", + ("cookie", &carol), + &json!({}), + ) + .await; + assert_eq!(s, StatusCode::ACCEPTED); + let rearchive_job = body["job_uid"].as_str().unwrap(); + + let conn = database::open_or_initialize(&f.archive_path).unwrap(); + let by = |uid: &str| database::get_capture_job(&conn, uid).unwrap().unwrap().created_by; + assert_eq!(by(job_uid), Some(carol_uid)); + assert_eq!(by(rearchive_job), Some(dave_uid)); + } + + #[tokio::test] + async fn job_detail_has_entry_uids_and_items_after_text_capture() { + let f = fixture(); + let alice = make_role_session(&f.auth_path, "alice", &["user"]); + let job_uid = text_capture(&f, &alice, "detail note").await; + + let (s, job) = get( + &f.router, + &format!("/api/archives/test/capture_jobs/{job_uid}"), + Some(&alice), + ) + .await; + assert_eq!(s, StatusCode::OK); + // Existing fields unchanged. + assert_eq!(job["job_uid"], job_uid); + assert_eq!(job["archive_id"], "test"); + assert_eq!(job["status"], "completed"); + assert!(job["run_uid"].is_string()); + for key in ["error_text", "notes_json", "created_at", "updated_at"] { + assert!(job.get(key).is_some(), "{key} must stay present"); + } + assert_eq!(job["created_by"], user_uid(&f.auth_path, "alice")); + + let entry_uids = job["entry_uids"].as_array().unwrap(); + assert_eq!(entry_uids.len(), 1); + let items = job["items"].as_array().unwrap(); + assert_eq!(items.len(), 1); + assert_eq!(items[0]["entry_uid"], entry_uids[0]); + assert_eq!(items[0]["status"], "completed"); + assert!(items[0]["requested_locator"].is_string()); + assert!(items[0].get("error_text").is_some()); + assert_eq!(job["items_truncated"], false); + + // The entry really exists. + let (s, _) = get( + &f.router, + &format!( + "/api/archives/test/entries/{}", + entry_uids[0].as_str().unwrap() + ), + Some(&alice), + ) + .await; + assert_eq!(s, StatusCode::OK); + + // A job whose run has not been linked yet has empty lists. + let pending = { + let conn = database::open_or_initialize(&f.archive_path).unwrap(); + database::create_capture_job_as( + &conn, + "test", + Some(&user_uid(&f.auth_path, "alice")), + ) + .unwrap() + }; + let (s, p) = get( + &f.router, + &format!("/api/archives/test/capture_jobs/{pending}"), + Some(&alice), + ) + .await; + assert_eq!(s, StatusCode::OK); + assert_eq!(p["entry_uids"], json!([])); + assert_eq!(p["items"], json!([])); + } + + #[tokio::test] + async fn job_detail_requires_user_role() { + let f = fixture(); + let (s, _) = get(&f.router, "/api/archives/test/capture_jobs/job_x", None).await; + assert_eq!(s, StatusCode::UNAUTHORIZED); + let guest = guest_only_session(&f.auth_path); + let (s, _) = get( + &f.router, + "/api/archives/test/capture_jobs/job_x", + Some(&guest), + ) + .await; + assert_eq!(s, StatusCode::FORBIDDEN); + let admin = admin_session(&f.auth_path); + let (s, _) = get( + &f.router, + "/api/archives/test/capture_jobs/job_x", + Some(&admin), + ) + .await; + assert_eq!(s, StatusCode::NOT_FOUND); + } + + fn hide_all_entries_from_users(archive_path: &FsPath) { + let conn = database::open_or_initialize(archive_path).unwrap(); + // ADMIN|OWNER only + conn.execute("UPDATE collection_entries SET visibility_bits = 12", []) + .unwrap(); + } + + fn run_uids(list: &Value) -> Vec { + list.as_array() + .unwrap() + .iter() + .map(|r| r["run_uid"].as_str().unwrap().to_string()) + .collect() + } + + fn run_of(archive_path: &FsPath, job_uid: &str) -> String { + let conn = database::open_or_initialize(archive_path).unwrap(); + database::get_capture_job(&conn, job_uid) + .unwrap() + .unwrap() + .run_uid + .unwrap() + } + + #[tokio::test] + async fn runs_are_visible_by_admin_creator_or_entry_access() { + let f = fixture(); + let alice = make_role_session(&f.auth_path, "alice", &["user"]); + let bob = make_role_session(&f.auth_path, "bob", &["user"]); + let admin = admin_session(&f.auth_path); + let runs = "/api/archives/test/runs"; + + let (s, _) = get(&f.router, runs, None).await; + assert_eq!(s, StatusCode::UNAUTHORIZED); + + let alice_run = run_of(&f.archive_path, &text_capture(&f, &alice, "a").await); + let bob_run = run_of(&f.archive_path, &text_capture(&f, &bob, "b").await); + + // Entry-access path: default collection entries are visible to USER (bit 2), so + // both users currently see both runs; the response is still a plain array. + let (s, l) = get(&f.router, runs, Some(&alice)).await; + assert_eq!(s, StatusCode::OK); + let seen = run_uids(&l); + assert!(seen.contains(&alice_run) && seen.contains(&bob_run)); + assert!(l[0].get("started_at").is_some() && l[0].get("error_summary").is_some()); + + // Remove entry access: only the creator (and admins) see each run. + hide_all_entries_from_users(&f.archive_path); + let (_, l) = get(&f.router, runs, Some(&alice)).await; + assert_eq!(run_uids(&l), vec![alice_run.clone()]); + let (_, l) = get(&f.router, runs, Some(&bob)).await; + assert_eq!(run_uids(&l), vec![bob_run.clone()]); + let (_, l) = get(&f.router, runs, Some(&admin)).await; + let seen = run_uids(&l); + assert!(seen.contains(&alice_run) && seen.contains(&bob_run)); + + // A third user with no job and no entry access sees nothing. + let eve = make_role_session(&f.auth_path, "eve", &["user"]); + let (s, l) = get(&f.router, runs, Some(&eve)).await; + assert_eq!((s, run_uids(&l).len()), (StatusCode::OK, 0)); + + // Entry access alone is enough: grant bit 2 again on Bob's entry only. + { + let conn = database::open_or_initialize(&f.archive_path).unwrap(); + conn.execute( + "UPDATE collection_entries SET visibility_bits = 2 WHERE entry_id IN ( + SELECT i.produced_entry_id FROM archive_run_items i + JOIN archive_runs r ON r.id = i.run_id WHERE r.run_uid = ?1)", + [&bob_run], + ) + .unwrap(); + } + let (_, l) = get(&f.router, runs, Some(&eve)).await; + assert_eq!(run_uids(&l), vec![bob_run.clone()]); + let (_, l) = get(&f.router, runs, Some(&alice)).await; + let seen = run_uids(&l); + assert!(seen.contains(&alice_run) && seen.contains(&bob_run)); + + // Runs without a job row (pre-migration) follow entry access only. + { + let conn = database::open_or_initialize(&f.archive_path).unwrap(); + conn.execute("DELETE FROM capture_jobs", []).unwrap(); + } + let (_, l) = get(&f.router, runs, Some(&alice)).await; + assert_eq!(run_uids(&l), vec![bob_run.clone()]); + let (_, l) = get(&f.router, runs, Some(&admin)).await; + assert_eq!(run_uids(&l).len(), 2); + } + + #[tokio::test] + async fn runs_support_limit_and_offset() { + let f = fixture(); + let admin = admin_session(&f.auth_path); + let first = run_of(&f.archive_path, &text_capture(&f, &admin, "one").await); + let second = run_of(&f.archive_path, &text_capture(&f, &admin, "two").await); + let runs = "/api/archives/test/runs"; + + let (_, all) = get(&f.router, runs, Some(&admin)).await; + assert_eq!(run_uids(&all), vec![second.clone(), first.clone()]); + let (_, l) = get(&f.router, &format!("{runs}?limit=1"), Some(&admin)).await; + assert_eq!(run_uids(&l), vec![second]); + let (_, l) = get(&f.router, &format!("{runs}?limit=1&offset=1"), Some(&admin)).await; + assert_eq!(run_uids(&l), vec![first]); + let (s, _) = get(&f.router, &format!("{runs}?limit=abc"), Some(&admin)).await; + assert_eq!(s, StatusCode::BAD_REQUEST); + } + + fn multipart_upload(filename: &str, content: &str) -> Request { + let body = format!( + "--XBOUNDARY\r\nContent-Disposition: form-data; name=\"file\"; \ + filename=\"{filename}\"\r\nContent-Type: text/plain\r\n\r\n{content}\r\n--XBOUNDARY--\r\n" + ); + Request::builder() + .method("POST") + .uri("/api/archives/test/uploads") + .header("content-type", "multipart/form-data; boundary=XBOUNDARY") + .body(Body::from(body)) + .unwrap() + } + + async fn capture_locator(f: &Fixture, cookie: &str, locator: &str) -> (StatusCode, Value) { + post_json( + &f.router, + "/api/archives/test/captures", + ("cookie", cookie), + &json!({"locator": locator}), + ) + .await + } + + #[tokio::test] + async fn file_locators_must_reference_a_staged_upload() { + let f = fixture(); + let alice = make_role_session(&f.auth_path, "alice", &["user"]); + + let (s, body) = capture_locator(&f, &alice, "file:///etc/hosts").await; + assert_eq!(s, StatusCode::BAD_REQUEST); + assert_eq!(body["error"], "file:// locators must reference a staged upload"); + + // Path traversal out of the staging dir and nonexistent files are rejected too. + let paths = archivr_core::archive::read_archive_paths(&f.archive_path).unwrap(); + let staging = paths.store_path.join("temp").join("uploads"); + std::fs::create_dir_all(&staging).unwrap(); + let (s, _) = capture_locator( + &f, + &alice, + &format!("file://{}/../../../../../../../../etc/hosts", staging.display()), + ) + .await; + assert_eq!(s, StatusCode::BAD_REQUEST); + let (s, _) = capture_locator( + &f, + &alice, + &format!("file://{}/missing/none.txt", staging.display()), + ) + .await; + assert_eq!(s, StatusCode::BAD_REQUEST); + // A real file just outside the staging dir. + let outside = paths.store_path.join("temp").join("outside.txt"); + std::fs::write(&outside, "secret").unwrap(); + let (s, _) = capture_locator(&f, &alice, &format!("file://{}", outside.display())).await; + assert_eq!(s, StatusCode::BAD_REQUEST); + + // Rejected requests must not leave job rows behind. + { + let conn = database::open_or_initialize(&f.archive_path).unwrap(); + let n: i64 = conn + .query_row("SELECT COUNT(*) FROM capture_jobs", [], |r| r.get(0)) + .unwrap(); + assert_eq!(n, 0); + } + + // The normal upload -> capture flow still works. + let mut upload = multipart_upload("hello.txt", "hello staged world"); + upload + .headers_mut() + .insert("cookie", alice.parse().unwrap()); + let resp = f.router.clone().oneshot(upload).await.unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let locator = body_json(resp).await["locator"] + .as_str() + .unwrap() + .to_string(); + assert!(locator.starts_with("file://")); + let (s, body) = capture_locator(&f, &alice, &locator).await; + assert_eq!(s, StatusCode::ACCEPTED, "{body}"); + let job_uid = body["job_uid"].as_str().unwrap(); + assert_eq!(wait_job(&f.archive_path, job_uid).await, "completed"); + } + + #[tokio::test] + async fn list_archives_redacts_archive_path_for_non_admins() { + let f = fixture(); + let expected = f.archive_path.to_string_lossy().to_string(); + + let (s, anon) = get(&f.router, "/api/archives", None).await; + assert_eq!(s, StatusCode::OK); + assert_eq!(anon, json!([{"id": "test", "label": "Test"}])); + + for (name, roles) in [("guesty", vec!["guest"]), ("usery", vec!["user"])] { + let cookie = make_role_session(&f.auth_path, name, &roles); + let (_, list) = get(&f.router, "/api/archives", Some(&cookie)).await; + assert_eq!(list, json!([{"id": "test", "label": "Test"}]), "{name}"); + } + + let admin = admin_session(&f.auth_path); + let (_, list) = get(&f.router, "/api/archives", Some(&admin)).await; + assert_eq!(list[0]["id"], "test"); + assert_eq!(list[0]["archive_path"], expected.as_str()); + let owner = make_test_session(&f.auth_path); + let (_, list) = get(&f.router, "/api/archives", Some(&owner)).await; + assert_eq!(list[0]["archive_path"], expected.as_str()); + + // Bearer admin tokens count too. + let token = make_api_token(&f.auth_path, "test-admin", None, "full"); + let resp = f + .router + .clone() + .oneshot( + Request::builder() + .uri("/api/archives") + .header("authorization", format!("Bearer {token}")) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(body_json(resp).await[0]["archive_path"], expected.as_str()); + } } diff --git a/crates/archivr-server/src/routes.rs b/crates/archivr-server/src/routes.rs index 38fbe11..e7e4ba6 100644 --- a/crates/archivr-server/src/routes.rs +++ b/crates/archivr-server/src/routes.rs @@ -51,6 +51,7 @@ pub use crate::auth::{AuthUser, ROLE_ADMIN, ROLE_GUEST, ROLE_OWNER, ROLE_USER}; use crate::registry::{MountedArchive, ServerRegistry}; use axum_extra::extract::CookieJar; use rusqlite::OptionalExtension; +use crate::jobs; const LOGIN_WINDOW: Duration = Duration::from_secs(15 * 60); const LOGIN_MAX_ATTEMPTS: usize = 5; @@ -463,8 +464,30 @@ fn static_dir() -> PathBuf { .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("static")) } -async fn list_archives(State(state): State) -> Json> { - Json(state.registry.archives.clone()) +/// `GET /api/archives` item. `archive_path` (a server filesystem path) is only +/// included for ADMIN callers. +#[derive(serde::Serialize)] +struct ArchiveListItem { + id: String, + label: String, + #[serde(skip_serializing_if = "Option::is_none")] + archive_path: Option, +} + +async fn list_archives(State(state): State, auth: AuthUser) -> Json> { + let is_admin = auth.has_role(ROLE_ADMIN); + Json( + state + .registry + .archives + .iter() + .map(|a| ArchiveListItem { + id: a.id.clone(), + label: a.label.clone(), + archive_path: is_admin.then(|| a.archive_path.clone()), + }) + .collect(), + ) } #[derive(Debug, serde::Deserialize, Default)] @@ -842,11 +865,31 @@ async fn list_runs( State(state): State, auth_user: AuthUser, Path(archive_id): Path, + Query(page): Query, ) -> Result>, ApiError> { - auth_user.require_auth()?; + let (_, role_bits) = auth_user.require_auth()?; + let limit = jobs::parse_int_param("limit", page.limit.as_deref())?.map(|n| n.max(0)); + let offset = jobs::parse_int_param("offset", page.offset.as_deref())? + .unwrap_or(0) + .max(0); let mounted = mounted_archive(&state, &archive_id)?; + let caller_uid = jobs::caller_user_uid(&state, &auth_user)?; let conn = database::open_or_initialize(&mounted.archive_path)?; - Ok(Json(archive::list_runs(&conn)?)) + // Visibility follows access: admins see all runs; others see runs whose capture job + // they created or that produced at least one entry they can see. + Ok(Json(archive::list_runs_for_caller( + &conn, + role_bits, + caller_uid.as_deref(), + limit, + offset, + )?)) +} + +#[derive(Debug, serde::Deserialize, Default)] +struct RunsPageQuery { + limit: Option, + offset: Option, } const MEDIA_TOKEN_TTL: Duration = Duration::from_secs(2 * 60 * 60); // 2 h @@ -1593,9 +1636,36 @@ async fn capture_handler( let archive_paths = archive::read_archive_paths(&mounted.archive_path).map_err(ApiError::from)?; + let locator = body.locator.trim().to_string(); + // A file:// locator is accepted only for a file staged by upload_handler under + // temp/uploads/ (it is also tracked for cleanup). Anything else would let an API + // caller capture and read back arbitrary server files, e.g. file:///etc/passwd. + // Canonicalize both sides to prevent path-traversal via `..` components in the locator. + // Same pattern as artifact serving. The staged file must already exist on disk + // (it was written by upload_handler), so canonicalize() will resolve symlinks correctly. + let staged_upload_path: Option = if locator.starts_with("file://") { + let file_path = std::path::PathBuf::from(locator.trim_start_matches("file://")); + let staging_dir = archive_paths.store_path.join("temp").join("uploads"); + match (file_path.canonicalize(), staging_dir.canonicalize()) { + (Ok(canonical_file), Ok(canonical_staging)) + if canonical_file.starts_with(&canonical_staging) => + { + Some(canonical_file) + } + _ => { + return Err(ApiError::bad_request( + "file:// locators must reference a staged upload", + )); + } + } + } else { + None + }; + // Create job record in the archive DB. let conn = database::open_or_initialize(&mounted.archive_path)?; - let job_uid = database::create_capture_job(&conn, &archive_id)?; + let created_by = jobs::caller_user_uid(&state, &auth_user)?; + let job_uid = database::create_capture_job_as(&conn, &archive_id, created_by.as_deref())?; drop(conn); // Load cookie rules and global uBlock / cookie-ext settings from the auth DB. let (cookie_rules, global_ublock, global_cookie_ext, global_modal_closer) = { @@ -1632,25 +1702,6 @@ async fn capture_handler( }; // Spawn background capture. - let locator = body.locator.trim().to_string(); - // If the locator is a file:// path staged under temp/uploads/, track it for cleanup. - // Canonicalize both sides to prevent path-traversal via `..` components in the locator. - // Same pattern as artifact serving (line ~631). The staged file must already exist on disk - // (it was written by upload_handler), so canonicalize() will resolve symlinks correctly. - let staged_upload_path: Option = if locator.starts_with("file://") { - let file_path = std::path::PathBuf::from(locator.trim_start_matches("file://")); - let staging_dir = archive_paths.store_path.join("temp").join("uploads"); - match (file_path.canonicalize(), staging_dir.canonicalize()) { - (Ok(canonical_file), Ok(canonical_staging)) - if canonical_file.starts_with(&canonical_staging) => - { - Some(canonical_file) - } - _ => None, - } - } else { - None - }; let quality = body.quality.clone(); let archive_path = mounted.archive_path.clone(); let job_uid_bg = job_uid.clone(); @@ -1779,7 +1830,8 @@ async fn capture_text_handler( // Create job record in the archive DB. let conn = database::open_or_initialize(&mounted.archive_path)?; - let job_uid = database::create_capture_job(&conn, &archive_id)?; + let created_by = jobs::caller_user_uid(&state, &auth_user)?; + let job_uid = database::create_capture_job_as(&conn, &archive_id, created_by.as_deref())?; drop(conn); // Spawn background text capture. @@ -1996,13 +2048,10 @@ async fn get_capture_job_handler( State(state): State, auth_user: AuthUser, Path((archive_id, job_uid)): Path<(String, String)>, -) -> Result, ApiError> { +) -> Result, ApiError> { auth_user.require_role(ROLE_USER)?; let mounted = mounted_archive(&state, &archive_id)?; - let conn = database::open_or_initialize(&mounted.archive_path)?; - archive::get_capture_job(&conn, &job_uid)? - .map(Json) - .ok_or_else(|| ApiError::not_found("capture job not found")) + jobs::get_job_detail(&state, &auth_user, &mounted.archive_path, &job_uid).map(Json) } /// POST /api/archives/:archive_id/entries/:entry_uid/rearchive @@ -2026,7 +2075,8 @@ async fn rearchive_handler( // Create a capture job record so the client can poll for completion. let conn = database::open_or_initialize(&mounted.archive_path)?; - let job_uid = database::create_capture_job(&conn, &archive_id)?; + let created_by = jobs::caller_user_uid(&state, &auth_user)?; + let job_uid = database::create_capture_job_as(&conn, &archive_id, created_by.as_deref())?; drop(conn); // Load cookie rules from the auth DB (needed for Twitter credentials resolution).