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

fix: re-check access every time a media token is used

A media token now records the account that issued it, and each use re-checks that account's status and access to the entry. Revoking access or disabling or deleting the user takes effect immediately instead of when the token expires.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
TheGeneralist 2026-10-09 22:47:32 +02:00
parent 65aeb82728
commit 848f1b1e56
5 changed files with 180 additions and 23 deletions

View file

@ -422,7 +422,7 @@ pending or failed; rows with no completed summary contribute no summary-derived
**Capture job visibility.** `capture_jobs.created_by` stores the creator's `user_uid`. Job endpoints show a caller only jobs they created unless they hold ADMIN; rows with no creator are admin-only. `GET /api/archives/:id/runs` follows access: admins see all runs, other callers see runs whose job they created or that produced at least one entry they can see.
**Entry visibility.** An entry is visible to a logged-in caller when ADMIN/OWNER, or when the caller's role bits overlap `collection_entries.visibility_bits` of one of its collections (or of its parent entry's). List and search use `database::entry_visible_to_caller_sql`; every by-uid endpoint (detail, artifacts, summary, tags, collections, media token, favicon, patch/delete, rearchive, thread title) calls `routes::ensure_entry_visible`, which answers `404` for a hidden entry so it cannot be told apart from a missing one. `/blobs/:sha256` applies the same rule through the entries that use the blob, and `list_tag_tree` counts only visible entries (tag names themselves stay visible to every signed-in user). Guests keep the separate `is_entry_publicly_accessible` rule. Signed-in role bits always include the guest bit, so custom roles start at bit 16. A non-admin cannot change or remove a collection membership in a way that leaves the entry invisible to their own roles (`apply_without_self_lockout`, `400`). Media tokens are capability URLs valid for two hours and are not revoked when an entry is hidden afterwards.
**Entry visibility.** An entry is visible to a logged-in caller when ADMIN/OWNER, or when the caller's role bits overlap `collection_entries.visibility_bits` of one of its collections (or of its parent entry's). List and search use `database::entry_visible_to_caller_sql`; every by-uid endpoint (detail, artifacts, summary, tags, collections, media token, favicon, patch/delete, rearchive, thread title) calls `routes::ensure_entry_visible`, which answers `404` for a hidden entry so it cannot be told apart from a missing one. `/blobs/:sha256` applies the same rule through the entries that use the blob, and `list_tag_tree` counts only visible entries (tag names themselves stay visible to every signed-in user). Guests keep the separate `is_entry_publicly_accessible` rule. Signed-in role bits always include the guest bit, so custom roles start at bit 16. A non-admin cannot change or remove a collection membership in a way that leaves the entry invisible to their own roles (`apply_without_self_lockout`, `400`). A media token is re-checked on every use against the issuer's current status, roles and access to the entry, so hiding the entry or disabling/deleting the issuer stops it immediately; it still expires after two hours.
**Capture job to run link.** `CaptureConfig.job_uid` is set by the server for API captures; the run is written onto `capture_jobs.run_uid` the moment it is created (`database::link_capture_job_run`), so the creator can see an in-progress run. Rearchive passes `None`.

View file

@ -902,6 +902,16 @@ pub fn compute_role_bits(conn: &Connection, user_id: i64) -> Result<u32> {
Ok(bits)
}
/// True when the user row exists and its status is `active`. A disabled or deleted user is not.
/// Used to re-check credentials that were issued earlier (media tokens) against current state.
pub fn user_is_active(conn: &Connection, user_id: i64) -> Result<bool> {
Ok(conn.query_row(
"SELECT EXISTS (SELECT 1 FROM users WHERE id = ?1 AND status = 'active')",
[user_id],
|row| row.get(0),
)?)
}
/// Returns a new session_uid (UUID).
pub fn create_session(
conn: &Connection,
@ -4396,6 +4406,21 @@ mod tests {
assert!(alice.role_slugs.contains(&"user".to_string()));
}
#[test]
fn user_is_active_reflects_status_and_existence() {
let conn = make_auth_conn_for_mgmt();
let owner_id = create_owner(&conn, "owner", "hash").unwrap();
let uid = create_user(&conn, "dave", None, "hash", owner_id).unwrap();
let dave_id = get_user_id_by_uid(&conn, &uid).unwrap().unwrap();
assert!(user_is_active(&conn, dave_id).unwrap());
set_user_status(&conn, &uid, "disabled").unwrap();
assert!(!user_is_active(&conn, dave_id).unwrap());
set_user_status(&conn, &uid, "active").unwrap();
assert!(user_is_active(&conn, dave_id).unwrap());
conn.execute("DELETE FROM users WHERE id = ?1", [dave_id]).unwrap();
assert!(!user_is_active(&conn, dave_id).unwrap(), "a deleted user is not active");
}
#[test]
fn set_status_disables_user_and_kills_sessions() {
let conn = make_auth_conn_for_mgmt();

View file

@ -12,7 +12,7 @@ use serde_json::{Value, json};
use crate::test_support::{
Fixture, admin_session, fixture, guest_session, make_role_session, owner_session, send, send_json,
text_capture, wait_job,
text_capture, user_uid, wait_job,
};
const EDITORS_BIT: u32 = 16;
@ -290,6 +290,112 @@ async fn media_tokens_are_only_issued_for_visible_entries() {
assert_eq!(status, StatusCode::NOT_FOUND);
}
fn set_visibility_bits(f: &Fixture, entry_uid: &str, bits: u32) {
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![bits as i64, entry_uid],
)
.unwrap();
}
fn visibility_bits(f: &Fixture, entry_uid: &str) -> u32 {
let conn = database::open_or_initialize(&f.archive_path).unwrap();
let bits: i64 = conn
.query_row(
"SELECT visibility_bits FROM collection_entries \
WHERE entry_id = (SELECT id FROM archived_entries WHERE entry_uid = ?1)",
[entry_uid],
|r| r.get(0),
)
.unwrap();
bits as u32
}
async fn issue_media_token(w: &World, cookie: &str, entry_uid: &str) -> String {
let uri = entry_path(entry_uid, "/artifacts/0/media-token");
let (status, issued) = send_json(&w.f.router, "POST", &uri, Some(cookie), None).await;
assert_eq!(status, StatusCode::OK);
issued["url"].as_str().unwrap().to_string()
}
#[tokio::test]
async fn media_token_is_rechecked_on_every_use() {
let w = world().await;
let url = issue_media_token(&w, &w.alice, &w.open).await;
for _ in 0..2 {
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 Open note");
}
// The issuer loses access to the entry: the still-unexpired token stops working.
let original = visibility_bits(&w.f, &w.open);
set_visibility_bits(&w.f, &w.open, EDITORS_BIT);
let (status, _) = send(&w.f.router, "GET", &url, None, None).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
// Access restored: the same token works again.
set_visibility_bits(&w.f, &w.open, original);
let (status, _) = send(&w.f.router, "GET", &url, None, None).await;
assert_eq!(status, StatusCode::OK);
}
#[tokio::test]
async fn media_token_stops_working_when_its_issuer_is_disabled() {
let w = world().await;
let url = issue_media_token(&w, &w.alice, &w.open).await;
let alice_uid = user_uid(&w.f.auth_path, "alice");
let (status, _) = send_json(
&w.f.router,
"PATCH",
&format!("/api/admin/users/{alice_uid}/status"),
Some(&w.admin),
Some(&json!({"status": "disabled"})),
)
.await;
assert_eq!(status, StatusCode::OK);
let (status, _) = send(&w.f.router, "GET", &url, None, None).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn media_token_stops_working_when_its_issuer_is_deleted() {
let w = world().await;
let dave = make_role_session(&w.f.auth_path, "dave", &["user"]);
let url = issue_media_token(&w, &dave, &w.open).await;
let dave_uid = user_uid(&w.f.auth_path, "dave");
let (status, _) = send(
&w.f.router,
"DELETE",
&format!("/api/admin/users/{dave_uid}"),
Some(&w.admin),
None,
)
.await;
assert_eq!(status, StatusCode::NO_CONTENT);
let (status, _) = send(&w.f.router, "GET", &url, None, None).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn an_admin_issued_media_token_for_a_hidden_entry_keeps_working() {
let w = world().await;
let url = issue_media_token(&w, &w.admin, &w.hidden).await;
// Alice cannot see the entry at all, but the admin issuer still can.
let (status, _) = send(&w.f.router, "GET", &entry_path(&w.hidden, ""), Some(&w.alice), None).await;
assert_eq!(status, StatusCode::NOT_FOUND);
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");
}
#[tokio::test]
async fn anonymous_requests_keep_the_existing_guest_rules() {
let w = world().await;

View file

@ -66,6 +66,8 @@ pub(crate) struct MediaToken {
archive_id: String,
entry_uid: String,
artifact_index: usize,
/// The account that issued the token. Its status and access are re-checked on every use.
user_id: i64,
expires_at: std::time::Instant,
}
@ -924,35 +926,37 @@ async fn serve_artifact(
req: Request,
) -> Result<Response, ApiError> {
// Auth: valid scoped token OR authenticated session OR publicly accessible entry.
// A token present but invalid/expired falls back to session/public check so that
// A token present but invalid/expired/revoked falls back to session/public check so that
// a logged-in browser player keeps working after a token expires.
let token_valid = params.token.as_deref().map_or(false, |tok| {
let token_issuer = params.token.as_deref().and_then(|tok| {
let tokens = state.media_tokens.lock();
tokens.get(tok).map_or(false, |t| {
t.archive_id == archive_id
&& t.entry_uid == entry_uid
&& t.artifact_index == artifact_index
&& t.expires_at > std::time::Instant::now()
})
tokens
.get(tok)
.filter(|t| {
t.archive_id == archive_id
&& t.entry_uid == entry_uid
&& t.artifact_index == artifact_index
&& t.expires_at > std::time::Instant::now()
})
.map(|t| t.user_id)
});
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)?;
let token_valid = match token_issuer {
Some(issuer_id) => media_token_issuer_can_view(&state, &conn, issuer_id, &entry_uid)?,
None => false,
};
if !token_valid {
if matches!(auth_user, AuthUser::Guest) {
let mounted_check = mounted_archive(&state, &archive_id)?;
let conn_check = database::open_or_initialize(&mounted_check.archive_path)?;
if !database::is_entry_publicly_accessible(&conn_check, &entry_uid)? {
if !database::is_entry_publicly_accessible(&conn, &entry_uid)? {
return Err(ApiError::unauthorized("login required"));
}
} else {
auth_user.require_auth()?;
ensure_entry_visible(&conn, &auth_user, &entry_uid)?;
}
}
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
@ -971,13 +975,14 @@ async fn serve_artifact(
///
/// Requires an authenticated session. Returns a short-lived signed URL that
/// allows unauthenticated GET of the specified artifact — intended for Cast /
/// AirPlay devices that cannot carry the browser's session cookie.
/// AirPlay devices that cannot carry the browser's session cookie. The token is
/// tied to the issuing account and re-checked on every use (see `serve_artifact`).
async fn issue_media_token(
State(state): State<AppState>,
auth_user: AuthUser,
Path((archive_id, entry_uid, artifact_index)): Path<(String, String, usize)>,
) -> Result<Json<MediaTokenResponse>, ApiError> {
auth_user.require_auth()?;
let (user_id, _) = auth_user.require_auth()?;
// 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)?;
@ -999,6 +1004,7 @@ async fn issue_media_token(
archive_id: archive_id.clone(),
entry_uid: entry_uid.clone(),
artifact_index,
user_id,
expires_at: now + MEDIA_TOKEN_TTL,
},
);
@ -3313,6 +3319,26 @@ pub(crate) fn ensure_entry_visible(
Ok(())
}
/// Re-checks a media token against its issuer's current state: the account must still exist and
/// be active, and its current roles must still see the entry. ADMIN/OWNER bypass the query, the
/// same as `ensure_entry_visible`.
fn media_token_issuer_can_view(
state: &AppState,
conn: &rusqlite::Connection,
issuer_id: i64,
entry_uid: &str,
) -> Result<bool, ApiError> {
let auth_conn = database::open_auth_db(&state.auth_db_path)?;
if !database::user_is_active(&auth_conn, issuer_id)? {
return Ok(false);
}
let role_bits = database::compute_role_bits(&auth_conn, issuer_id)?;
if role_bits & (ROLE_ADMIN | ROLE_OWNER) != 0 {
return Ok(true);
}
Ok(database::caller_can_access_entry(conn, entry_uid, role_bits)?)
}
/// Runs `change` (a mutation of collection memberships or their visibility touching `entry_uids`)
/// and, for callers who are not admins, rolls it back with a 400 when it would leave any of those
/// entries hidden from the caller's own roles. Without this a plain user could hide an entry from

View file

@ -283,5 +283,5 @@ The first implementation hid entries only in lists and search; fetching by uid s
3. **No self-lockout.** A non-admin whose `PATCH .../collections/:c/entries/:uid` or `DELETE` would leave the entry invisible to the caller's own roles gets `400` and nothing changes. Admins and owners are exempt.
4. **Run link at job start.** `CaptureConfig.job_uid` carries the job into the capture; `capture_jobs.run_uid` is written as soon as the run exists, so `GET .../runs` shows the creator an in-progress run (rule J3). Rearchive passes no job uid.
5. **Default collection.** `DELETE .../collections/<default>` answers `400`.
6. **Known limit.** A media token issued before an entry was hidden stays valid until it expires (two hours).
6. **Media tokens are re-checked.** A media token is re-checked on every use against the issuer's current status, roles and access to the entry, so hiding the entry or disabling/deleting the issuer stops it immediately. It still expires after two hours.