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

fix: role creation skips bits still present in archive visibility masks

Roles deleted before role_bit_allocations existed can leave their bits in archive
masks, so a new role could inherit their hidden entries. Role creation now ORs the
visibility masks of every mounted archive and skips those bits.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
TheGeneralist 2026-10-10 10:49:22 +02:00
parent e300ebf1a0
commit 14d630caa3
Signed by: thegeneralist01
SSH key fingerprint: SHA256:pp9qddbCNmVNoSjevdvQvM5z0DHN7LTa8qBMbcMq/R4
4 changed files with 119 additions and 9 deletions

View file

@ -1626,19 +1626,48 @@ pub fn grantable_role_bits(conn: &Connection) -> Result<u32> {
Ok(bits)
}
/// Returns the bitwise OR of every visibility mask stored in an archive:
/// `collection_entries.visibility_bits` and `collections.default_visibility_bits`.
/// Bits in this mask may still belong to a role that no longer exists, so role creation
/// must not hand them out again (see `create_custom_role_avoiding`).
pub fn used_visibility_bits(conn: &Connection) -> Result<u32> {
let mut stmt = conn.prepare(
"SELECT visibility_bits FROM collection_entries
UNION
SELECT default_visibility_bits FROM collections",
)?;
let bits = stmt
.query_map([], |row| row.get::<_, i64>(0))?
.try_fold(0u32, |acc, b| b.map(|b| acc | (b as u32)))?;
Ok(bits)
}
/// Creates a new custom role (level=2). Equivalent to `create_custom_role_avoiding` with
/// no reserved bits.
pub fn create_custom_role(conn: &Connection, slug: &str, name: &str) -> Result<RoleRecord> {
create_custom_role_avoiding(conn, slug, name, 0)
}
/// Creates a new custom role (level=2). Its bit_position is one above the highest bit
/// ever allocated (min 4), counting deleted roles via `role_bit_allocations`, so a bit
/// is never reused. Fails once bit 31 is allocated (`maximum number of custom roles
/// reached`); because bits are never freed, that is a lifetime cap per instance.
/// Returns the created RoleRecord.
pub fn create_custom_role(conn: &Connection, slug: &str, name: &str) -> Result<RoleRecord> {
/// is never reused. Bits set in `reserved_mask` (typically `used_visibility_bits` of the
/// mounted archives, which can carry bits of roles deleted before allocations were
/// recorded) are skipped and recorded as allocated. Fails once bit 31 is allocated
/// (`maximum number of custom roles reached`); because bits are never freed, that is a
/// lifetime cap per instance. Returns the created RoleRecord.
pub fn create_custom_role_avoiding(
conn: &Connection,
slug: &str,
name: &str,
reserved_mask: u32,
) -> Result<RoleRecord> {
if slug.is_empty() || !slug.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
anyhow::bail!(
"role slug must be non-empty and contain only ASCII letters, digits, or hyphens"
);
}
let tx = conn.unchecked_transaction()?;
let next_bit: i64 = tx.query_row(
let mut next_bit: i64 = tx.query_row(
"SELECT COALESCE(MAX(bit_position) + 1, 4) FROM (
SELECT bit_position FROM role_bit_allocations
UNION ALL
@ -1647,11 +1676,19 @@ pub fn create_custom_role(conn: &Connection, slug: &str, name: &str) -> Result<R
[],
|r| r.get(0),
)?;
let now = now_timestamp();
while next_bit < 32 && reserved_mask & (1u32 << next_bit) != 0 {
tx.execute(
"INSERT OR IGNORE INTO role_bit_allocations (bit_position, role_uid, allocated_at)
VALUES (?1, 'reserved', ?2)",
params![next_bit, now],
)?;
next_bit += 1;
}
if next_bit >= 32 {
anyhow::bail!("maximum number of custom roles reached");
}
let role_uid = public_id("role");
let now = now_timestamp();
tx.execute(
"INSERT INTO roles (role_uid, slug, name, level, bit_position, is_builtin)
VALUES (?1, ?2, ?3, 2, ?4, 0)",
@ -4491,6 +4528,45 @@ mod tests {
assert_eq!(d.bit_position, 7);
}
#[test]
fn role_creation_skips_bits_still_present_in_archive_masks() {
// Upgraded instance: bit 5 was used by a role deleted before allocations were
// recorded, so auth knows only bit 4, but a stored archive mask still carries bit 5.
let archive = conn();
let collection_id = ensure_default_collection(&archive).unwrap();
let entry = create_entry_fixture(&archive, "private", None, None);
add_entry_to_collection(&archive, collection_id, entry.id, 2).unwrap();
archive
.execute(
"UPDATE collection_entries SET visibility_bits = 32 WHERE entry_id = ?1",
[entry.id],
)
.unwrap();
let reserved = used_visibility_bits(&archive).unwrap();
assert_eq!(reserved & (1 << 5), 1 << 5);
let auth = make_auth_conn_for_mgmt();
create_custom_role(&auth, "a", "A").unwrap();
let b = create_custom_role_avoiding(&auth, "b", "B", reserved).unwrap();
assert_eq!(b.bit_position, 6);
// The skipped bit is recorded, so a plain create also moves past it.
let c = create_custom_role(&auth, "c", "C").unwrap();
assert_eq!(c.bit_position, 7);
}
#[test]
fn used_visibility_bits_covers_entry_and_collection_masks() {
let archive = conn();
assert_eq!(used_visibility_bits(&archive).unwrap() & !2, 0);
archive
.execute(
"UPDATE collections SET default_visibility_bits = 64 WHERE id = ?1",
[ensure_default_collection(&archive).unwrap()],
)
.unwrap();
assert_eq!(used_visibility_bits(&archive).unwrap() & 64, 64);
}
#[test]
fn migration_backfills_allocations_for_existing_custom_roles() {
let mut conn = make_auth_conn_for_mgmt();

View file

@ -698,3 +698,30 @@ async fn a_role_created_after_deleting_one_never_inherits_its_hidden_entries() {
.await;
assert_eq!(status, StatusCode::OK);
}
#[tokio::test]
async fn a_role_created_on_an_upgraded_instance_skips_bits_still_in_archive_masks() {
// Upgraded instance: bit 5 belonged to a role deleted before allocations were recorded,
// so auth has no allocation for it, but `Hidden note`'s stored mask still carries it.
let w = world().await;
set_visibility_bits(&w.f, &w.hidden, 1 << 5);
let owner = owner_session(&w.f.auth_path);
let (status, role) = send_json(
&w.f.router,
"POST",
"/api/admin/roles",
Some(&owner),
Some(&json!({"slug": "reviewers", "name": "Reviewers"})),
)
.await;
assert_eq!(status, StatusCode::CREATED, "{role}");
assert_ne!(role["bit_position"].as_u64(), Some(5), "stale archive bit reissued");
let dave = make_role_session(&w.f.auth_path, "dave", &["user", "reviewers"]);
let (status, _) = send_json(
&w.f.router, "GET", &entry_path(&w.hidden, ""), Some(&dave), None,
)
.await;
assert_eq!(status, StatusCode::NOT_FOUND, "stale archive bit must not grant access");
}

View file

@ -3291,8 +3291,15 @@ async fn admin_create_role(
) -> Result<(StatusCode, Json<database::RoleRecord>), ApiError> {
auth_user.require_role(ROLE_ADMIN)?;
let conn = database::open_auth_db(&state.auth_db_path)?;
let role =
database::create_custom_role(&conn, &body.slug, &body.name).map_err(ApiError::from)?;
// Stored archive masks can still carry bits of roles deleted before allocations were
// recorded, so skip every bit any mounted archive uses. Fail closed if one cannot be read.
let mut reserved = 0u32;
for archive in &state.registry.archives {
let archive_conn = database::open_or_initialize(&archive.archive_path)?;
reserved |= database::used_visibility_bits(&archive_conn)?;
}
let role = database::create_custom_role_avoiding(&conn, &body.slug, &body.name, reserved)
.map_err(ApiError::from)?;
Ok((StatusCode::CREATED, Json(role)))
}

View file

@ -276,7 +276,7 @@ Follow the `oneshot` style in `routes.rs` `mod tests`, helpers from `test_suppor
## 5. Entry access rules (added after review of the first implementation)
The first implementation hid entries only in lists and search; fetching by uid still worked. These rules close that gap.
The first implementation hid entries only in lists and search; fetching by uid still worked. These rules close that gap. Role creation also skips any bit present in the stored visibility masks of the mounted archives.
1. **Hidden means 404.** For a logged-in caller who is neither ADMIN nor OWNER, every endpoint that takes an entry uid answers `404 entry not found` when none of the entry's collection memberships (or its parent entry's) has `visibility_bits & caller_bits != 0`. This covers entry detail, artifacts, summary (GET and POST), tags (GET, POST, DELETE), entry collections, media token, favicon, PATCH and DELETE entry, thread title, rearchive, and collection add, remove and visibility. `GET /api/archives/:id/blobs/:sha256` allows a blob when at least one entry that uses it is visible. Guests keep `is_entry_publicly_accessible`. Rearchive of an unknown entry is `404` for everyone.
2. **Tag counts.** `GET .../tags` counts only entries the caller can see. Tag names remain visible to every signed-in user.