From 0833a6a2f20f00e5c56838270f91cbb964bd2c0d Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Fri, 9 Oct 2026 19:42:52 +0200 Subject: [PATCH] fix: enforce entry visibility on every by-uid endpoint Hiding an entry from a role (collection membership bits) only filtered the list, search and children queries; the entry could still be fetched, edited, deleted, summarized or tagged by uid, and its artifacts and blobs downloaded. - database::caller_can_access_entry / caller_can_access_blob share one SQL predicate with the list queries (children inherit the parent's membership; ADMIN/OWNER see everything; requires_auth only gates guests) - routes::ensure_entry_visible gates entry detail, summary GET/POST, artifacts, media tokens, favicon, tags, entry collections, rename, delete, thread title, rearchive and collection membership; blobs use the blob rule - hidden entries are a 404, indistinguishable from unknown uids - tag tree counts only include entries visible to the caller - rearchive of an unknown entry is now a 404 for everyone (no doomed job row) - test_support: guest_session is a true guest-only account; shared HTTP fixture helpers moved out of jobs.rs Co-Authored-By: Claude Sonnet 5.5 --- crates/archivr-core/src/archive.rs | 153 +++++++- crates/archivr-core/src/database.rs | 49 +++ crates/archivr-server/src/entry_access.rs | 409 ++++++++++++++++++++++ crates/archivr-server/src/jobs.rs | 156 ++------- crates/archivr-server/src/main.rs | 2 + crates/archivr-server/src/routes.rs | 60 +++- crates/archivr-server/src/test_support.rs | 160 ++++++++- 7 files changed, 852 insertions(+), 137 deletions(-) create mode 100644 crates/archivr-server/src/entry_access.rs diff --git a/crates/archivr-core/src/archive.rs b/crates/archivr-core/src/archive.rs index cea910c..5e1d86b 100644 --- a/crates/archivr-core/src/archive.rs +++ b/crates/archivr-core/src/archive.rs @@ -953,22 +953,28 @@ pub fn create_tag(conn: &rusqlite::Connection, full_path: &str) -> Result { /// Returns the full tag tree with root nodes at the top level and children nested. /// Each node includes a direct entry count and a subtree count (unique entries -/// assigned to the tag itself or any descendant). -pub fn list_tag_tree(conn: &rusqlite::Connection) -> Result> { +/// assigned to the tag itself or any descendant). Tags are an archive-wide taxonomy that +/// every logged-in user sees, but the counts only include entries visible to `caller_bits` +/// (see `database::entry_visible_to_caller_sql`), so they cannot reveal hidden entries. +pub fn list_tag_tree(conn: &rusqlite::Connection, caller_bits: u32) -> Result> { use std::collections::HashMap; let records = database::list_all_tags(conn)?; + let visible = database::entry_visible_to_caller_sql("e", "?1"); // Fetch direct entry counts for all tags in a single query. let mut counts: HashMap = HashMap::new(); { - let mut stmt = conn.prepare( - "SELECT t.tag_uid, COUNT(eta.entry_id) \ + let mut stmt = conn.prepare(&format!( + "SELECT t.tag_uid, COUNT(e.id) \ FROM tags t \ LEFT JOIN entry_tag_assignments eta ON eta.tag_id = t.id \ + LEFT JOIN archived_entries e ON e.id = eta.entry_id AND {visible} \ GROUP BY t.id", - )?; - for row in stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))? { + ))?; + for row in stmt.query_map([caller_bits as i64], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)) + })? { let (uid, cnt) = row?; counts.insert(uid, cnt); } @@ -979,20 +985,23 @@ pub fn list_tag_tree(conn: &rusqlite::Connection) -> Result> { // a parent and a child is counted only once. let mut subtree_counts: HashMap = HashMap::new(); { - let mut stmt = conn.prepare( + let mut stmt = conn.prepare(&format!( "WITH RECURSIVE descendants(ancestor_id, descendant_id) AS ( \ SELECT id, id FROM tags \ UNION ALL \ SELECT d.ancestor_id, t.id \ FROM tags t JOIN descendants d ON t.parent_tag_id = d.descendant_id \ ) \ - SELECT t.tag_uid, COUNT(DISTINCT eta.entry_id) \ + SELECT t.tag_uid, COUNT(DISTINCT e.id) \ FROM tags t \ JOIN descendants d ON d.ancestor_id = t.id \ LEFT JOIN entry_tag_assignments eta ON eta.tag_id = d.descendant_id \ + LEFT JOIN archived_entries e ON e.id = eta.entry_id AND {visible} \ GROUP BY t.id", - )?; - for row in stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))? { + ))?; + for row in stmt.query_map([caller_bits as i64], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)) + })? { let (uid, cnt) = row?; subtree_counts.insert(uid, cnt); } @@ -1802,7 +1811,7 @@ mod tests { create_tag(&conn, "/science/cs").unwrap(); create_tag(&conn, "/art").unwrap(); - let tree = list_tag_tree(&conn).unwrap(); + let tree = list_tag_tree(&conn, 12).unwrap(); assert_eq!(tree.len(), 2, "expected two root nodes"); let science = tree @@ -1848,7 +1857,7 @@ mod tests { assign_entry_tag(&conn, &e1.entry_uid, "/science/cs/algorithms").unwrap(); assign_entry_tag(&conn, &e2.entry_uid, "/science").unwrap(); - let tree = list_tag_tree(&conn).unwrap(); + let tree = list_tag_tree(&conn, 12).unwrap(); let science = tree.iter().find(|n| n.tag.slug == "science").unwrap(); let cs = science .children @@ -1891,7 +1900,7 @@ mod tests { assign_entry_tag(&conn, &e.entry_uid, "/science").unwrap(); assign_entry_tag(&conn, &e.entry_uid, "/science/cs").unwrap(); - let tree = list_tag_tree(&conn).unwrap(); + let tree = list_tag_tree(&conn, 12).unwrap(); let science = tree.iter().find(|n| n.tag.slug == "science").unwrap(); assert_eq!( @@ -1902,6 +1911,124 @@ mod tests { assert_eq!(science.children[0].subtree_count, 1, "cs subtree = 1"); } + /// Sets the visibility bits of every `collection_entries` row of an entry. + fn set_entry_visibility(conn: &rusqlite::Connection, entry_uid: &str, bits: u32) { + conn.execute( + "UPDATE collection_entries SET visibility_bits = ?1 \ + WHERE entry_id = (SELECT id FROM archived_entries WHERE entry_uid = ?2)", + rusqlite::params![bits as i64, entry_uid], + ) + .unwrap(); + } + + const USER: u32 = 2; + const ADMIN: u32 = 4; + const OWNER: u32 = 8; + const CUSTOM_ROLE: u32 = 16; + + #[test] + fn caller_can_access_entry_follows_the_list_visibility_rule() { + let (conn, user_id, run_id) = make_tag_test_db(); + let open = make_entry_in_db(&conn, user_id, run_id, None, None, "Open", "https://e.test/open"); + let hidden = make_entry_in_db(&conn, user_id, run_id, None, None, "Hidden", "https://e.test/hidden"); + // Hidden from plain users; visible only to the custom role. + set_entry_visibility(&conn, &hidden.entry_uid, CUSTOM_ROLE); + + let can = |uid: &str, bits: u32| database::caller_can_access_entry(&conn, uid, bits).unwrap(); + assert!(can(&open.entry_uid, USER)); + assert!(!can(&hidden.entry_uid, USER), "plain user must not reach a hidden entry"); + assert!(can(&hidden.entry_uid, USER | CUSTOM_ROLE), "overlapping role bit grants access"); + assert!(can(&hidden.entry_uid, ADMIN), "admins see everything"); + assert!(can(&hidden.entry_uid, OWNER), "owners see everything"); + assert!(!can("no-such-uid", ADMIN), "unknown entries are never accessible"); + assert!(!can(&open.entry_uid, 0), "no role bits, no access"); + } + + #[test] + fn caller_can_access_child_entries_through_their_parent() { + let (conn, user_id, run_id) = make_tag_test_db(); + let parent = make_entry_in_db(&conn, user_id, run_id, None, None, "Playlist", "https://e.test/pl"); + let child = make_entry_in_db( + &conn, user_id, run_id, Some(parent.id), Some(parent.id), "Video", "https://e.test/pl/v1", + ); + let can = |uid: &str, bits: u32| database::caller_can_access_entry(&conn, uid, bits).unwrap(); + + // The child inherits the parent's membership... + assert!(can(&child.entry_uid, USER)); + // ...so hiding the parent hides the child, matching list_child_entries. + set_entry_visibility(&conn, &parent.entry_uid, CUSTOM_ROLE); + assert!(!can(&child.entry_uid, USER)); + assert!(can(&child.entry_uid, USER | CUSTOM_ROLE)); + + // An individually shared child (its own membership row, private by default) is + // reachable even when the parent is hidden. + set_entry_visibility(&conn, &child.entry_uid, USER); + assert!(can(&child.entry_uid, USER)); + assert!(!can(&parent.entry_uid, USER), "sharing the child does not expose the parent"); + } + + #[test] + fn caller_can_access_blob_needs_one_visible_entry() { + let (conn, user_id, run_id) = make_tag_test_db(); + let a = make_entry_in_db(&conn, user_id, run_id, None, None, "A", "https://e.test/a"); + let b = make_entry_in_db(&conn, user_id, run_id, None, None, "B", "https://e.test/b"); + let blob = |sha: &str| database::BlobRecord { + sha256: sha.to_string(), + byte_size: 1, + mime_type: None, + extension: None, + raw_relpath: format!("raw/{sha}"), + }; + let shared = database::upsert_blob(&conn, &blob("aa")).unwrap(); + let only_b = database::upsert_blob(&conn, &blob("bb")).unwrap(); + database::upsert_blob(&conn, &blob("orphan")).unwrap(); + for (entry, blob_id) in [(&a, shared), (&b, shared), (&b, only_b)] { + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id: entry.id, + artifact_role: "media".to_string(), + storage_area: "raw".to_string(), + relpath: "x".to_string(), + blob_id: Some(blob_id), + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); + } + set_entry_visibility(&conn, &b.entry_uid, CUSTOM_ROLE); + + let can = |sha: &str, bits: u32| database::caller_can_access_blob(&conn, sha, bits).unwrap(); + assert!(can("aa", USER), "a blob shared with a visible entry stays readable"); + assert!(!can("bb", USER), "a blob only a hidden entry uses is not readable"); + assert!(can("bb", USER | CUSTOM_ROLE)); + assert!(!can("orphan", USER), "unreferenced blobs are admin-only"); + assert!(can("orphan", ADMIN)); + assert!(can("bb", OWNER)); + assert!(!can("missing", ADMIN), "unknown blobs are never accessible"); + } + + #[test] + fn tag_tree_counts_only_entries_visible_to_the_caller() { + let (conn, user_id, run_id) = make_tag_test_db(); + let open = make_entry_in_db(&conn, user_id, run_id, None, None, "Open", "https://e.test/o"); + let hidden = make_entry_in_db(&conn, user_id, run_id, None, None, "Hidden", "https://e.test/h"); + assign_entry_tag(&conn, &open.entry_uid, "/topic/sub").unwrap(); + assign_entry_tag(&conn, &hidden.entry_uid, "/topic/sub").unwrap(); + assign_entry_tag(&conn, &hidden.entry_uid, "/topic").unwrap(); + set_entry_visibility(&conn, &hidden.entry_uid, CUSTOM_ROLE); + + let counts = |bits: u32| { + let tree = list_tag_tree(&conn, bits).unwrap(); + let topic = tree.iter().find(|n| n.tag.slug == "topic").unwrap(); + (topic.entry_count, topic.subtree_count, topic.children[0].entry_count) + }; + assert_eq!(counts(ADMIN), (1, 2, 2), "admins count everything"); + assert_eq!(counts(USER), (0, 1, 1), "hidden entries are not counted for plain users"); + assert_eq!(counts(USER | CUSTOM_ROLE), (1, 2, 2)); + } + #[test] fn assign_entry_tag_is_idempotent() { let (conn, user_id, run_id) = make_tag_test_db(); diff --git a/crates/archivr-core/src/database.rs b/crates/archivr-core/src/database.rs index 35d668d..a6dd40c 100644 --- a/crates/archivr-core/src/database.rs +++ b/crates/archivr-core/src/database.rs @@ -3335,6 +3335,55 @@ pub fn is_entry_publicly_accessible(conn: &Connection, entry_uid: &str) -> Resul Ok(count > 0) } +/// SQL predicate: the archived entry aliased `entry_alias` is visible to a logged-in caller +/// whose role bits are bound to the parameter `bits_param` (e.g. `"?2"`). +/// +/// This is the rule `archive::list_entries_for_collection` and `archive::list_child_entries` +/// apply: ADMIN/OWNER (bits 12) see every entry, everyone else needs a `collection_entries` +/// row — for the entry itself or, for a child entry, for its parent — whose `visibility_bits` +/// overlap theirs. `requires_auth` is not consulted: it only gates guests. +pub(crate) fn entry_visible_to_caller_sql(entry_alias: &str, bits_param: &str) -> String { + format!( + "(CAST({bits} AS INTEGER) & 12 != 0 \ + OR EXISTS (SELECT 1 FROM collection_entries vce \ + WHERE vce.entry_id = {e}.id \ + AND vce.visibility_bits & CAST({bits} AS INTEGER) != 0) \ + OR EXISTS (SELECT 1 FROM collection_entries vcp \ + WHERE vcp.entry_id = {e}.parent_entry_id \ + AND vcp.visibility_bits & CAST({bits} AS INTEGER) != 0))", + e = entry_alias, + bits = bits_param, + ) +} + +/// True when a logged-in caller with `caller_bits` may read the entry `entry_uid`. Use this +/// to gate every by-uid entry endpoint so an entry hidden from a role in the lists cannot be +/// fetched directly either. False for an unknown entry. Guests are gated separately by +/// [`is_entry_publicly_accessible`]. +pub fn caller_can_access_entry(conn: &Connection, entry_uid: &str, caller_bits: u32) -> Result { + let sql = format!( + "SELECT EXISTS (SELECT 1 FROM archived_entries e WHERE e.entry_uid = ?1 AND {})", + entry_visible_to_caller_sql("e", "?2") + ); + Ok(conn.query_row(&sql, params![entry_uid, caller_bits as i64], |row| row.get(0))?) +} + +/// True when a logged-in caller with `caller_bits` may read the blob `sha256`: ADMIN/OWNER can +/// read any blob; everyone else needs at least one entry referencing the blob that they can +/// see (blobs are content-addressed, so one blob can back several entries). A blob no entry +/// references is admin-only. False for an unknown blob. +pub fn caller_can_access_blob(conn: &Connection, sha256: &str, caller_bits: u32) -> Result { + let sql = format!( + "SELECT EXISTS (SELECT 1 FROM blobs b WHERE b.sha256 = ?1 AND (\ + CAST(?2 AS INTEGER) & 12 != 0 \ + OR EXISTS (SELECT 1 FROM entry_artifacts a \ + JOIN archived_entries e ON e.id = a.entry_id \ + WHERE a.blob_id = b.id AND {})))", + entry_visible_to_caller_sql("e", "?2") + ); + Ok(conn.query_row(&sql, params![sha256, caller_bits as i64], |row| row.get(0))?) +} + /// Renames a collection and/or updates its default_visibility_bits. /// Returns true if updated, false if not found. /// Refuses to rename the '_default_' collection but allows changing its diff --git a/crates/archivr-server/src/entry_access.rs b/crates/archivr-server/src/entry_access.rs new file mode 100644 index 0000000..083285a --- /dev/null +++ b/crates/archivr-server/src/entry_access.rs @@ -0,0 +1,409 @@ +//! Router-level tests: an entry hidden from a role (via its collection membership bits) is +//! hidden from every by-uid endpoint too, not just from the list and search queries. +//! Hidden entries are indistinguishable from missing ones (404). +//! +//! Cast: `admin` (sees everything), `alice` (plain user), `carol` (user + custom role +//! `editors`, bit 16). Two text entries are captured by the admin; `Hidden note`'s +//! membership is narrowed to the `editors` bit, so alice cannot see it and carol can. + +use archivr_core::database; +use axum::http::StatusCode; +use serde_json::{Value, json}; + +use crate::test_support::{ + Fixture, admin_session, fixture, guest_session, make_role_session, send, send_json, + text_capture, wait_job, +}; + +const EDITORS_BIT: u32 = 16; + +struct World { + f: Fixture, + admin: String, + alice: String, + carol: String, + open: String, + hidden: String, + open_sha: String, + hidden_sha: String, +} + +fn entry_uid_by_title(f: &Fixture, title: &str) -> String { + let conn = database::open_or_initialize(&f.archive_path).unwrap(); + conn.query_row( + "SELECT entry_uid FROM archived_entries WHERE title = ?1", + [title], + |r| r.get(0), + ) + .unwrap() +} + +fn blob_sha_of(f: &Fixture, entry_uid: &str) -> String { + let conn = database::open_or_initialize(&f.archive_path).unwrap(); + conn.query_row( + "SELECT b.sha256 FROM entry_artifacts a \ + JOIN blobs b ON b.id = a.blob_id \ + JOIN archived_entries e ON e.id = a.entry_id \ + WHERE e.entry_uid = ?1", + [entry_uid], + |r| r.get(0), + ) + .unwrap() +} + +async fn world() -> World { + let f = fixture(); + let admin = admin_session(&f.auth_path); + { + let conn = database::open_auth_db(&f.auth_path).unwrap(); + let role = database::create_custom_role(&conn, "editors", "Editors").unwrap(); + assert_eq!(1u32 << role.bit_position, EDITORS_BIT); + } + let alice = make_role_session(&f.auth_path, "alice", &["user"]); + let carol = make_role_session(&f.auth_path, "carol", &["user", "editors"]); + + text_capture(&f, &admin, "Open note").await; + text_capture(&f, &admin, "Hidden note").await; + let open = entry_uid_by_title(&f, "Open note"); + let hidden = entry_uid_by_title(&f, "Hidden note"); + { + let conn = database::open_or_initialize(&f.archive_path).unwrap(); + conn.execute( + "UPDATE collection_entries SET visibility_bits = ?1 \ + WHERE entry_id = (SELECT id FROM archived_entries WHERE entry_uid = ?2)", + rusqlite::params![EDITORS_BIT as i64, hidden], + ) + .unwrap(); + } + let open_sha = blob_sha_of(&f, &open); + let hidden_sha = blob_sha_of(&f, &hidden); + World { f, admin, alice, carol, open, hidden, open_sha, hidden_sha } +} + +fn entry_path(uid: &str, suffix: &str) -> String { + format!("/api/archives/test/entries/{uid}{suffix}") +} + +/// One by-uid request template: method, path suffix after the entry uid, JSON body, and the +/// status a caller who CAN see the entry gets. +type Case = (&'static str, &'static str, Option, StatusCode); + +/// Endpoints that are safe to repeat against a visible entry (no destructive side effects). +fn safe_cases() -> Vec { + vec![ + ("GET", "", None, StatusCode::OK), + ("GET", "/summary", None, StatusCode::OK), + ("GET", "/artifacts/0", None, StatusCode::OK), + ("POST", "/artifacts/0/media-token", None, StatusCode::OK), + ("GET", "/tags", None, StatusCode::OK), + ("GET", "/collections", None, StatusCode::OK), + // Provider "bogus" is a 400 once the entry gate has passed. + ( + "POST", + "/summary", + Some(json!({"provider": "bogus"})), + StatusCode::BAD_REQUEST, + ), + ( + "POST", + "/thread-title", + Some(json!({"provider": "bogus"})), + StatusCode::BAD_REQUEST, + ), + ] +} + +#[tokio::test] +async fn hidden_entry_is_not_found_on_every_by_uid_endpoint() { + let w = world().await; + let hidden = &w.hidden; + + let mut cases = safe_cases(); + cases.extend([ + ("GET", "/favicon", None, StatusCode::NOT_FOUND), + ("PATCH", "", Some(json!({"title": "pwned"})), StatusCode::NO_CONTENT), + ("DELETE", "", None, StatusCode::NO_CONTENT), + ("POST", "/tags", Some(json!({"tag_path": "/secret"})), StatusCode::CREATED), + ("POST", "/rearchive", None, StatusCode::ACCEPTED), + ]); + for (method, suffix, body, _) in &cases { + let uri = entry_path(hidden, suffix); + let (status, json) = send_json(&w.f.router, method, &uri, Some(&w.alice), body.as_ref()).await; + assert_eq!(status, StatusCode::NOT_FOUND, "alice {method} {uri}"); + assert_eq!(json["error"], "entry not found", "alice {method} {uri}"); + } + + // Nothing was changed behind the 404s. + let conn = database::open_or_initialize(&w.f.archive_path).unwrap(); + let (title, tags): (String, i64) = conn + .query_row( + "SELECT title, (SELECT COUNT(*) FROM entry_tag_assignments) \ + FROM archived_entries WHERE entry_uid = ?1", + [hidden], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .expect("entry must still exist"); + assert_eq!(title, "Hidden note"); + assert_eq!(tags, 0); + let jobs: i64 = conn + .query_row("SELECT COUNT(*) FROM capture_jobs", [], |r| r.get(0)) + .unwrap(); + assert_eq!(jobs, 2, "rearchive of a hidden entry must not create a job"); + + // The tag-removal route is gated too (the tag need not exist for the gate to answer). + let (status, json) = send_json( + &w.f.router, + "DELETE", + &entry_path(hidden, "/tags/tag_x"), + Some(&w.alice), + None, + ) + .await; + assert_eq!((status, json["error"].as_str()), (StatusCode::NOT_FOUND, Some("entry not found"))); +} + +#[tokio::test] +async fn visible_entry_passes_the_gate() { + let w = world().await; + // A plain user on the open entry, the editor and the admin on the hidden one. + for (who, cookie, uid) in [ + ("alice/open", &w.alice, &w.open), + ("carol/hidden", &w.carol, &w.hidden), + ("admin/hidden", &w.admin, &w.hidden), + ("admin/open", &w.admin, &w.open), + ] { + for (method, suffix, body, expected) in safe_cases() { + let uri = entry_path(uid, suffix); + let (status, json) = send_json(&w.f.router, method, &uri, Some(cookie), body.as_ref()).await; + assert_eq!(status, expected, "{who} {method} {uri}: {json}"); + } + } +} + +#[tokio::test] +async fn visible_entry_can_be_written_by_whoever_sees_it() { + let w = world().await; + // carol (editors) may rename and tag the hidden entry; alice may do the same to the open one. + for (cookie, uid, title) in [(&w.carol, &w.hidden, "Renamed by carol"), (&w.alice, &w.open, "Renamed by alice")] { + let (status, _) = send_json( + &w.f.router, + "PATCH", + &entry_path(uid, ""), + Some(cookie), + Some(&json!({"title": title})), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + let (status, _) = send_json( + &w.f.router, + "POST", + &entry_path(uid, "/tags"), + Some(cookie), + Some(&json!({"tag_path": "/mine"})), + ) + .await; + assert_eq!(status, StatusCode::CREATED); + } + // Rearchive passes the gate for the editor (the background job then fails: not a tweet). + let (status, body) = + send_json(&w.f.router, "POST", &entry_path(&w.hidden, "/rearchive"), Some(&w.carol), None).await; + assert_eq!(status, StatusCode::ACCEPTED); + wait_job(&w.f.archive_path, body["job_uid"].as_str().unwrap()).await; +} + +#[tokio::test] +async fn hidden_entry_cannot_be_deleted_by_a_plain_user_but_can_by_the_editor() { + let w = world().await; + let (status, _) = send(&w.f.router, "DELETE", &entry_path(&w.hidden, ""), Some(&w.alice), None).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _) = send(&w.f.router, "DELETE", &entry_path(&w.hidden, ""), Some(&w.carol), None).await; + assert_eq!(status, StatusCode::NO_CONTENT); + let (status, _) = send(&w.f.router, "GET", &entry_path(&w.hidden, ""), Some(&w.admin), None).await; + assert_eq!(status, StatusCode::NOT_FOUND, "the entry is really gone"); +} + +#[tokio::test] +async fn blobs_follow_the_entries_that_use_them() { + let w = world().await; + let blob = |sha: &str| format!("/api/archives/test/blobs/{sha}"); + + let (status, body) = send(&w.f.router, "GET", &blob(&w.open_sha), Some(&w.alice), None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(String::from_utf8_lossy(&body), "body of Open note"); + + let (status, body) = send_json(&w.f.router, "GET", &blob(&w.hidden_sha), Some(&w.alice), None).await; + assert_eq!((status, body["error"].as_str()), (StatusCode::NOT_FOUND, Some("blob not found"))); + + for cookie in [&w.carol, &w.admin] { + let (status, body) = send(&w.f.router, "GET", &blob(&w.hidden_sha), Some(cookie), None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(String::from_utf8_lossy(&body), "body of Hidden note"); + } + + // Once the open entry also uses the hidden entry's blob, alice may read it: she can see + // an entry that references it. + { + let conn = database::open_or_initialize(&w.f.archive_path).unwrap(); + conn.execute( + "UPDATE entry_artifacts SET blob_id = (SELECT id FROM blobs WHERE sha256 = ?1) \ + WHERE entry_id = (SELECT id FROM archived_entries WHERE entry_uid = ?2)", + rusqlite::params![w.hidden_sha, w.open], + ) + .unwrap(); + } + let (status, _) = send(&w.f.router, "GET", &blob(&w.hidden_sha), Some(&w.alice), None).await; + assert_eq!(status, StatusCode::OK); + + // A blob no entry references is admin-only; unknown blobs are 404 for everyone. + { + let conn = database::open_or_initialize(&w.f.archive_path).unwrap(); + conn.execute("DELETE FROM entry_artifacts", []).unwrap(); + } + let (status, _) = send(&w.f.router, "GET", &blob(&w.hidden_sha), Some(&w.alice), None).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _) = send(&w.f.router, "GET", &blob("nope"), Some(&w.admin), None).await; + assert_eq!(status, StatusCode::NOT_FOUND); +} + +#[tokio::test] +async fn media_tokens_are_only_issued_for_visible_entries() { + let w = world().await; + let issue = |cookie: &str| { + let uri = entry_path(&w.hidden, "/artifacts/0/media-token"); + let router = w.f.router.clone(); + let cookie = cookie.to_string(); + async move { send_json(&router, "POST", &uri, Some(&cookie), None).await } + }; + let (status, _) = issue(&w.alice).await; + assert_eq!(status, StatusCode::NOT_FOUND); + + let (status, issued) = issue(&w.carol).await; + assert_eq!(status, StatusCode::OK); + // The token is a capability URL: it works without a session... + let url = issued["url"].as_str().unwrap(); + let (status, body) = send(&w.f.router, "GET", url, None, None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(String::from_utf8_lossy(&body), "body of Hidden note"); + // ...but a session without access gets nothing from the plain URL. + let plain = entry_path(&w.hidden, "/artifacts/0"); + let (status, _) = send(&w.f.router, "GET", &plain, Some(&w.alice), None).await; + assert_eq!(status, StatusCode::NOT_FOUND); +} + +#[tokio::test] +async fn anonymous_requests_keep_the_existing_guest_rules() { + let w = world().await; + // The default collection requires auth, so nothing is public: the existing 401. + for uid in [&w.open, &w.hidden] { + let (status, _) = send(&w.f.router, "GET", &entry_path(uid, ""), None, None).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + } +} + +#[tokio::test] +async fn a_guest_role_account_sees_only_entries_shared_with_the_guest_bit() { + let w = world().await; + // A signed-in account holding only the guest role has role bits 1: it is an + // authenticated caller, so the same visibility rule as everyone else applies. + let guest = guest_session(&w.f.auth_path); + for uid in [&w.open, &w.hidden] { + let (status, _) = send(&w.f.router, "GET", &entry_path(uid, ""), Some(&guest), None).await; + assert_eq!(status, StatusCode::NOT_FOUND, "bits 2 / 16 do not overlap the guest bit"); + } + { + let conn = database::open_or_initialize(&w.f.archive_path).unwrap(); + conn.execute( + "UPDATE collection_entries SET visibility_bits = 3 \ + WHERE entry_id = (SELECT id FROM archived_entries WHERE entry_uid = ?1)", + [&w.open], + ) + .unwrap(); + } + let (status, _) = send(&w.f.router, "GET", &entry_path(&w.open, ""), Some(&guest), None).await; + assert_eq!(status, StatusCode::OK, "an entry shared with bit 1 is readable by guest accounts"); +} + +#[tokio::test] +async fn hidden_parent_lists_no_children_and_tag_counts_hide_it() { + let w = world().await; + // Children listing already filters per child; a hidden parent simply has none for alice. + let (status, list) = send_json(&w.f.router, "GET", &entry_path(&w.hidden, "/children"), Some(&w.alice), None).await; + assert_eq!((status, list), (StatusCode::OK, json!([]))); + + // Tag both entries; the tag tree counts only what the caller can see. + for uid in [&w.open, &w.hidden] { + let (status, _) = send_json( + &w.f.router, + "POST", + &entry_path(uid, "/tags"), + Some(&w.admin), + Some(&json!({"tag_path": "/shared"})), + ) + .await; + assert_eq!(status, StatusCode::CREATED); + } + let count_for = |cookie: String| { + let router = w.f.router.clone(); + async move { + let (status, tree) = send_json(&router, "GET", "/api/archives/test/tags", Some(&cookie), None).await; + assert_eq!(status, StatusCode::OK); + let node = tree + .as_array() + .unwrap() + .iter() + .find(|n| n["tag"]["slug"] == "shared") + .expect("tag is listed for every logged-in user") + .clone(); + (node["entry_count"].as_i64().unwrap(), node["subtree_count"].as_i64().unwrap()) + } + }; + assert_eq!(count_for(w.alice.clone()).await, (1, 1)); + assert_eq!(count_for(w.carol.clone()).await, (2, 2)); + assert_eq!(count_for(w.admin.clone()).await, (2, 2)); +} + +#[tokio::test] +async fn collection_membership_endpoints_are_gated_by_entry_visibility() { + let w = world().await; + let (status, created) = send_json( + &w.f.router, + "POST", + "/api/archives/test/collections", + Some(&w.alice), + Some(&json!({"name": "Shelf", "slug": "shelf"})), + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let coll = created["collection_uid"].as_str().unwrap().to_string(); + let members = format!("/api/archives/test/collections/{coll}/entries"); + + // alice: the open entry works, the hidden one is not found. + let (status, _) = send_json( + &w.f.router, "POST", &members, Some(&w.alice), + Some(&json!({"entry_uid": w.open, "visibility_bits": 2})), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + let (status, body) = send_json( + &w.f.router, "POST", &members, Some(&w.alice), + Some(&json!({"entry_uid": w.hidden, "visibility_bits": 2})), + ) + .await; + assert_eq!((status, body["error"].as_str()), (StatusCode::NOT_FOUND, Some("entry not found"))); + for (method, body) in [("PATCH", Some(json!({"visibility_bits": 3}))), ("DELETE", None)] { + let uri = format!("{members}/{}", w.hidden); + let (status, _) = send_json(&w.f.router, method, &uri, Some(&w.alice), body.as_ref()).await; + assert_eq!(status, StatusCode::NOT_FOUND, "alice {method} {uri}"); + } + + // carol can manage the hidden entry's membership. + let (status, _) = send_json( + &w.f.router, "POST", &members, Some(&w.carol), + Some(&json!({"entry_uid": w.hidden, "visibility_bits": EDITORS_BIT})), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + let uri = format!("{members}/{}", w.hidden); + let (status, _) = send_json(&w.f.router, "DELETE", &uri, Some(&w.carol), None).await; + assert_eq!(status, StatusCode::NO_CONTENT); +} diff --git a/crates/archivr-server/src/jobs.rs b/crates/archivr-server/src/jobs.rs index 6481cc4..5eb59a8 100644 --- a/crates/archivr-server/src/jobs.rs +++ b/crates/archivr-server/src/jobs.rs @@ -151,134 +151,21 @@ pub(crate) fn get_job_detail( #[cfg(test)] mod tests { - use std::path::{Path as FsPath, PathBuf}; + use std::path::Path as FsPath; 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, + Fixture, admin_session, body_json, fixture, get, guest_session, make_api_token, + make_role_session, make_test_session, post_json, text_capture, user_uid, wait_job, }; - 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() @@ -292,7 +179,7 @@ mod tests { 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 guest = guest_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( @@ -437,13 +324,38 @@ mod tests { 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"]); + // Rearchive records its job (a non-tweet entry then fails in the background), but an + // unknown entry is a 404 and leaves no job behind. + let dave = make_role_session(&f.auth_path, "dave", &["user"]); let dave_uid = user_uid(&f.auth_path, "dave"); - let (s, body) = post_json( + let jobs_before = { + let conn = database::open_or_initialize(&f.archive_path).unwrap(); + conn.query_row("SELECT COUNT(*) FROM capture_jobs", [], |r| r.get::<_, i64>(0)) + .unwrap() + }; + let (s, _) = post_json( &f.router, "/api/archives/test/entries/ent_missing/rearchive", - ("cookie", &carol), + ("cookie", &dave), + &json!({}), + ) + .await; + assert_eq!(s, StatusCode::NOT_FOUND); + let entry_uid: String = { + let conn = database::open_or_initialize(&f.archive_path).unwrap(); + assert_eq!( + conn.query_row("SELECT COUNT(*) FROM capture_jobs", [], |r| r.get::<_, i64>(0)) + .unwrap(), + jobs_before, + "a 404 rearchive must not create a job" + ); + conn.query_row("SELECT entry_uid FROM archived_entries LIMIT 1", [], |r| r.get(0)) + .unwrap() + }; + let (s, body) = post_json( + &f.router, + &format!("/api/archives/test/entries/{entry_uid}/rearchive"), + ("cookie", &dave), &json!({}), ) .await; @@ -527,7 +439,7 @@ mod tests { 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 guest = guest_session(&f.auth_path); let (s, _) = get( &f.router, "/api/archives/test/capture_jobs/job_x", diff --git a/crates/archivr-server/src/main.rs b/crates/archivr-server/src/main.rs index 21bb452..fbdbcf6 100644 --- a/crates/archivr-server/src/main.rs +++ b/crates/archivr-server/src/main.rs @@ -2,6 +2,8 @@ mod admin_users; mod auth; mod credentials; mod effective_config; +#[cfg(test)] +mod entry_access; mod guards; mod jobs; mod registry; diff --git a/crates/archivr-server/src/routes.rs b/crates/archivr-server/src/routes.rs index 400c212..5f7f49d 100644 --- a/crates/archivr-server/src/routes.rs +++ b/crates/archivr-server/src/routes.rs @@ -581,6 +581,7 @@ async fn entry_detail( return Err(ApiError::unauthorized("login required")); } } + ensure_entry_visible(&conn, &auth_user, &entry_uid)?; let mut detail = archive::get_entry_detail(&conn, &entry_uid)? .ok_or(ApiError::not_found("entry not found"))?; if matches!(auth_user, AuthUser::Guest) { @@ -623,6 +624,7 @@ async fn entry_summary_handler( { return Err(ApiError::unauthorized("login required")); } + ensure_entry_visible(&conn, &auth_user, &entry_uid)?; let entry_id = database::entry_id_for_uid(&conn, &entry_uid)? .ok_or(ApiError::not_found("entry not found"))?; let (summary, attempt) = if matches!(auth_user, AuthUser::Guest) { @@ -667,6 +669,12 @@ async fn request_entry_summary_handler( ) -> Result<(StatusCode, Json), ApiError> { auth_user.require_role(ROLE_USER)?; let mounted = mounted_archive(&state, &archive_id)?; + // A hidden entry is not found: it must not be summarized, nor probe provider config. + ensure_entry_visible( + &database::open_or_initialize(&mounted.archive_path)?, + &auth_user, + &entry_uid, + )?; let archive_paths = archive::read_archive_paths(&mounted.archive_path).map_err(ApiError::from)?; @@ -941,6 +949,10 @@ async fn serve_artifact( let mounted = mounted_archive(&state, &archive_id)?; let paths = archive::read_archive_paths(&mounted.archive_path)?; let conn = database::open_or_initialize(&mounted.archive_path)?; + if !token_valid { + // A media token was only issued after this check passed (issue_media_token). + ensure_entry_visible(&conn, &auth_user, &entry_uid)?; + } let detail = archive::get_entry_detail(&conn, &entry_uid)? .ok_or(ApiError::not_found("entry not found"))?; let artifact = detail @@ -969,6 +981,7 @@ async fn issue_media_token( // Verify the artifact actually exists before issuing a token. let mounted = mounted_archive(&state, &archive_id)?; let conn = database::open_or_initialize(&mounted.archive_path)?; + ensure_entry_visible(&conn, &auth_user, &entry_uid)?; let detail = archive::get_entry_detail(&conn, &entry_uid)? .ok_or(ApiError::not_found("entry not found"))?; if artifact_index >= detail.artifacts.len() { @@ -1010,6 +1023,7 @@ async fn serve_entry_favicon( let mounted = mounted_archive(&state, &archive_id)?; let paths = archive::read_archive_paths(&mounted.archive_path)?; let conn = database::open_or_initialize(&mounted.archive_path)?; + ensure_entry_visible(&conn, &auth_user, &entry_uid)?; let detail = archive::get_entry_detail(&conn, &entry_uid)? .ok_or(ApiError::not_found("entry not found"))?; let artifact = detail @@ -1035,6 +1049,11 @@ async fn serve_blob( let mounted = mounted_archive(&state, &archive_id)?; let paths = archive::read_archive_paths(&mounted.archive_path)?; let conn = database::open_or_initialize(&mounted.archive_path)?; + // Blobs are content-addressed and shared between entries: readable when the caller can + // see at least one entry that uses the blob (ADMIN/OWNER: any existing blob). + if !database::caller_can_access_blob(&conn, &sha256, auth_to_caller_bits(&auth_user))? { + return Err(ApiError::not_found("blob not found")); + } let blob = database::get_blob_by_sha256(&conn, &sha256)? .ok_or(ApiError::not_found("blob not found"))?; let file_path = paths.store_path.join(&blob.raw_relpath); @@ -1110,7 +1129,7 @@ async fn list_tags( auth_user.require_auth()?; let mounted = mounted_archive(&state, &archive_id)?; let conn = database::open_or_initialize(&mounted.archive_path)?; - Ok(Json(archive::list_tag_tree(&conn)?)) + Ok(Json(archive::list_tag_tree(&conn, auth_to_caller_bits(&auth_user))?)) } async fn create_tag_handler( @@ -1137,6 +1156,7 @@ async fn list_entry_tags( auth_user.require_auth()?; let mounted = mounted_archive(&state, &archive_id)?; let conn = database::open_or_initialize(&mounted.archive_path)?; + ensure_entry_visible(&conn, &auth_user, &entry_uid)?; match archive::get_entry_tags(&conn, &entry_uid)? { Some(tags) => Ok(Json(tags)), None => Err(ApiError::not_found("entry not found")), @@ -1155,6 +1175,7 @@ async fn assign_entry_tag_handler( } let mounted = mounted_archive(&state, &archive_id)?; let conn = database::open_or_initialize(&mounted.archive_path)?; + ensure_entry_visible(&conn, &auth_user, &entry_uid)?; match archive::assign_entry_tag(&conn, &entry_uid, &body.tag_path)? { Some(tag) => Ok((StatusCode::CREATED, Json(tag))), None => Err(ApiError::not_found("entry not found")), @@ -1169,6 +1190,7 @@ async fn remove_entry_tag_handler( auth_user.require_role(ROLE_USER)?; let mounted = mounted_archive(&state, &archive_id)?; let conn = database::open_or_initialize(&mounted.archive_path)?; + ensure_entry_visible(&conn, &auth_user, &entry_uid)?; if archive::remove_entry_tag(&conn, &entry_uid, &tag_uid)? { Ok(StatusCode::NO_CONTENT) } else { @@ -1240,6 +1262,7 @@ async fn patch_entry_handler( auth_user.require_role(ROLE_USER)?; let mounted = mounted_archive(&state, &archive_id)?; let conn = database::open_or_initialize(&mounted.archive_path)?; + ensure_entry_visible(&conn, &auth_user, &entry_uid)?; let title = body .title .as_deref() @@ -1263,6 +1286,7 @@ async fn delete_entry_handler( auth_user.require_role(ROLE_USER)?; let mounted = mounted_archive(&state, &archive_id)?; let mut conn = database::open_or_initialize(&mounted.archive_path)?; + ensure_entry_visible(&conn, &auth_user, &entry_uid)?; // Transaction: if any step fails (cascade update, FK null, or delete), nothing is committed. let tx = conn.transaction()?; let found = database::delete_entry(&tx, &entry_uid)?; @@ -1407,6 +1431,11 @@ async fn generate_thread_title_handler( ) -> Result, ApiError> { auth_user.require_role(ROLE_USER)?; let mounted = mounted_archive(&state, &archive_id)?; + ensure_entry_visible( + &database::open_or_initialize(&mounted.archive_path)?, + &auth_user, + &entry_uid, + )?; let paths = archive::read_archive_paths(&mounted.archive_path).map_err(ApiError::from)?; let settings = database::get_instance_settings(&database::open_auth_db(&state.auth_db_path)?)?; let cfg = thread_title::title_provider_from_env( @@ -2091,6 +2120,11 @@ 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)?; + ensure_entry_visible(&conn, &auth_user, &entry_uid)?; + // Unknown (and, above, hidden) entries are a 404 for every caller; no doomed job row. + if database::entry_id_for_uid(&conn, &entry_uid)?.is_none() { + return Err(ApiError::not_found("entry not found")); + } 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); @@ -3246,6 +3280,26 @@ pub(crate) fn auth_to_caller_bits(auth: &AuthUser) -> u32 { } } +/// Gate for every by-uid entry endpoint: a logged-in caller who cannot see the entry in the +/// lists (`database::caller_can_access_entry`) gets the same 404 as for an unknown uid, so +/// hiding an entry from a role also hides it from direct requests. ADMIN/OWNER always pass +/// without a query. Guests are a no-op here: endpoints that allow them check +/// `is_entry_publicly_accessible` themselves. +pub(crate) fn ensure_entry_visible( + conn: &rusqlite::Connection, + auth: &AuthUser, + entry_uid: &str, +) -> Result<(), ApiError> { + if let AuthUser::Authenticated { role_bits, .. } = auth { + if role_bits & (ROLE_ADMIN | ROLE_OWNER) == 0 + && !database::caller_can_access_entry(conn, entry_uid, *role_bits)? + { + return Err(ApiError::not_found("entry not found")); + } + } + Ok(()) +} + pub(crate) fn mounted_archive<'a>( state: &'a AppState, archive_id: &str, @@ -3456,6 +3510,7 @@ async fn add_entry_to_collection_handler( "cannot manually add entries to the default collection", )); } + ensure_entry_visible(&conn, &auth, &body.entry_uid)?; let entry_id: i64 = conn .query_row( "SELECT id FROM archived_entries WHERE entry_uid = ?1", @@ -3483,6 +3538,7 @@ async fn remove_entry_from_collection_handler( "cannot manually remove entries from the default collection", )); } + ensure_entry_visible(&conn, &auth, &entry_uid)?; let entry_id: i64 = conn .query_row( "SELECT id FROM archived_entries WHERE entry_uid = ?1", @@ -3509,6 +3565,7 @@ async fn update_entry_visibility_handler( let conn = database::open_or_initialize(&mounted.archive_path)?; let coll = database::get_collection_by_uid(&conn, &coll_uid)? .ok_or(ApiError::not_found("collection not found"))?; + ensure_entry_visible(&conn, &auth, &entry_uid)?; let entry_id: i64 = conn .query_row( "SELECT id FROM archived_entries WHERE entry_uid = ?1", @@ -3533,6 +3590,7 @@ async fn list_entry_collections_handler( auth_user.require_auth()?; let mounted = mounted_archive(&state, &archive_id)?; let conn = database::open_or_initialize(&mounted.archive_path)?; + ensure_entry_visible(&conn, &auth_user, &entry_uid)?; match archive::get_entry_collections(&conn, &entry_uid)? { Some(memberships) => Ok(Json(memberships)), None => Err(ApiError::not_found("entry not found")), diff --git a/crates/archivr-server/src/test_support.rs b/crates/archivr-server/src/test_support.rs index c4bb6fc..25c73af 100644 --- a/crates/archivr-server/src/test_support.rs +++ b/crates/archivr-server/src/test_support.rs @@ -96,7 +96,24 @@ pub(crate) fn user_session(auth_path: &Path) -> String { /// 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"]) + make_role_session(auth_path, "test-guest", &["guest"]); + let conn = database::open_auth_db(auth_path).unwrap(); + let user_id: i64 = conn + .query_row( + "SELECT id FROM users WHERE username = 'test-guest'", + [], + |r| r.get(0), + ) + .unwrap(); + // create_user always grants `user`; a guest-only account must not have it. remove_role + // invalidates the user's sessions, so the session is created afterwards. + database::remove_role(&conn, user_id, "user").unwrap(); + let bits = database::compute_role_bits(&conn, user_id).unwrap(); + assert_eq!(bits, auth::ROLE_GUEST, "guest_session must hold only the guest role"); + format!( + "session={}", + database::create_session(&conn, user_id, bits, None).unwrap() + ) } /// Creates an API token for the existing user `username` and returns the raw @@ -236,3 +253,144 @@ mod tests { let _ = base.merge(extra); } } + +// ---- HTTP fixture shared by router-level tests ---- + +use axum::{Router, http::{Request, StatusCode}}; +use serde_json::{Value, json}; +use tower::ServiceExt; + +pub(crate) struct Fixture { + pub(crate) _dir: tempfile::TempDir, + pub(crate) router: Router, + pub(crate) archive_path: PathBuf, + pub(crate) auth_path: PathBuf, +} + +pub(crate) fn fixture() -> Fixture { + let dir = tempfile::tempdir().unwrap(); + let (registry, archive_path, auth_path) = make_test_registry(&dir); + let router = crate::routes::app(registry, auth_path.clone()); + Fixture { + _dir: dir, + router, + archive_path, + auth_path, + } +} + +pub(crate) fn user_uid(auth_path: &Path, 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() +} + +pub(crate) 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) +} + +pub(crate) 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) +} + +pub(crate) async fn wait_job(archive_path: &Path, 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. +pub(crate) 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 +} + + +/// Sends `method uri` with an optional session cookie and optional JSON body; returns the +/// status and the raw response bytes (artifacts and blobs are not JSON). +pub(crate) async fn send( + router: &Router, + method: &str, + uri: &str, + cookie: Option<&str>, + payload: Option<&Value>, +) -> (StatusCode, Vec) { + let mut req = Request::builder().method(method).uri(uri); + if let Some(c) = cookie { + req = req.header("cookie", c); + } + let body = match payload { + Some(p) => { + req = req.header("content-type", "application/json"); + json_body(p) + } + None => Body::empty(), + }; + let resp = router.clone().oneshot(req.body(body).unwrap()).await.unwrap(); + let status = resp.status(); + let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap(); + (status, bytes.to_vec()) +} + +/// Like [`send`], parsing the body as JSON (`Value::Null` when empty or not JSON). +pub(crate) async fn send_json( + router: &Router, + method: &str, + uri: &str, + cookie: Option<&str>, + payload: Option<&Value>, +) -> (StatusCode, Value) { + let (status, bytes) = send(router, method, uri, cookie, payload).await; + (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null)) +}