diff --git a/crates/archivr-core/src/database.rs b/crates/archivr-core/src/database.rs index 83bf6fd..4d38841 100644 --- a/crates/archivr-core/src/database.rs +++ b/crates/archivr-core/src/database.rs @@ -749,6 +749,17 @@ pub fn initialize_auth_schema(conn: &Connection) -> Result<()> { ordinal INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL ); + + -- Every custom-role bit ever handed out, including bits whose role was deleted. + -- Bits are never reused: archives store visibility masks + -- (collection_entries.visibility_bits) that still carry a deleted role's bit, + -- so a new role given that bit would inherit access to the old hidden entries. + -- No foreign key on purpose: the row must outlive the roles row it describes. + CREATE TABLE IF NOT EXISTS role_bit_allocations ( + bit_position INTEGER PRIMARY KEY, + role_uid TEXT NOT NULL, + allocated_at TEXT NOT NULL + ); "#, )?; // Add display_name column to users if not present (idempotent migration) @@ -798,6 +809,15 @@ pub fn initialize_auth_schema(conn: &Connection) -> Result<()> { ); } + // Backfill allocations for custom roles created before role_bit_allocations existed. + // Roles deleted before this migration left no record here, so their bits cannot be + // recovered from the auth DB. + conn.execute( + "INSERT OR IGNORE INTO role_bit_allocations (bit_position, role_uid, allocated_at) + SELECT bit_position, role_uid, ?1 FROM roles WHERE bit_position >= 4", + [now_timestamp()], + )?; + Ok(()) } @@ -1593,7 +1613,10 @@ pub fn grantable_role_bits(conn: &Connection) -> Result { Ok(bits) } -/// Creates a new custom role (level=2, bit_position = max existing + 1, min 4). +/// 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 { if slug.is_empty() || !slug.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { @@ -1601,8 +1624,13 @@ pub fn create_custom_role(conn: &Connection, slug: &str, name: &str) -> Result= 4", + let tx = conn.unchecked_transaction()?; + let next_bit: i64 = tx.query_row( + "SELECT COALESCE(MAX(bit_position) + 1, 4) FROM ( + SELECT bit_position FROM role_bit_allocations + UNION ALL + SELECT bit_position FROM roles + ) WHERE bit_position >= 4", [], |r| r.get(0), )?; @@ -1610,11 +1638,18 @@ pub fn create_custom_role(conn: &Connection, slug: &str, name: &str) -> Result