Skip to main content

vault_core/
users.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! User management, token management, and RBAC for UnENVerse.
4//!
5//! Users are stored in the SQLCipher-encrypted vault database — they can only
6//! be read or created when the owner has unlocked the vault (i.e. the vault key
7//! is in memory).  The owner is the only party who can manage users.
8//!
9//! # Auth modes
10//! - Username + password: stored as `SHA-256(salt || password)` with a 16-byte random salt.
11//! - Token: 32 random bytes returned as a 64-char hex string once; stored as `SHA-256(token)`.
12//!
13//! # Permission model
14//! Each permission has:
15//! - `scope_type`:  `"vault"` | `"project"` | `"category"`
16//! - `scope_value`: `"*"`, or a glob like `"wg0-*"` / `"Cloud/AWS"`
17//! - `permission`:  `"read"` | `"write"` (write implies read)
18//!
19//! Glob rules: `*` matches any sequence of characters (including empty); `?` matches one char.
20
21use crate::iso_now;
22use rand::Rng;
23use rusqlite::{Connection, OptionalExtension};
24use serde::{Deserialize, Serialize};
25use sha2::{Digest, Sha256};
26use std::collections::{HashMap, HashSet};
27
28/// One `(scope_type, scope_value)` pair from the `user_permissions` table.
29///
30/// Named because it appears three deep inside `PermissionsBySubject` below, and
31/// clippy's `type_complexity` is right that the nested form is unreadable.
32type Scope = (String, String);
33
34/// `subject id -> (read scopes, write scopes)`.
35///
36/// A write scope also grants read, so the read vector is the superset; see
37/// `load_all_permissions`, which pushes into both.
38type PermissionsBySubject = HashMap<String, (Vec<Scope>, Vec<Scope>)>;
39
40/// The `users` columns every lookup selects, in `SELECT` order:
41/// `id, username, password_hash, is_owner, created_at, last_seen_at, class_id,
42/// strict_write, totp_enabled`.
43///
44/// `password_hash` and `last_seen_at` are nullable — a user created by an
45/// administrator has no hash until first login, and has never been seen.
46type UserRow = (
47    String,
48    String,
49    Option<String>,
50    i32,
51    String,
52    Option<String>,
53    Option<String>,
54    i32,
55    i32,
56);
57
58// ── Public types ──────────────────────────────────────────────────────────────
59
60/// A named user class (role template) with capabilities and permissions.
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct UserClass {
63    pub id: String,
64    pub name: String,
65    pub description: String,
66    /// Can create/delete users and assign classes.
67    pub cap_manage_users: bool,
68    /// Can create/edit/delete user classes (admin-level).
69    pub cap_manage_classes: bool,
70    /// Can delete projects.
71    pub cap_delete_projects: bool,
72    pub strict_write: bool,
73    pub created_at: String,
74}
75
76/// A single permission row scoped to a user class (no user_id — applies to all class members).
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct ClassPermission {
79    pub class_id: String,
80    pub scope_type: String,
81    pub scope_value: String,
82    pub permission: String,
83}
84
85/// A vault user (password hash is never exposed via this struct).
86#[derive(Debug, Clone, Serialize, Deserialize)]
87pub struct UserRecord {
88    pub id: String,
89    pub username: String,
90    /// True when the user has a password set (can use username+password auth).
91    pub has_password: bool,
92    pub is_owner: bool,
93    pub created_at: String,
94    pub last_seen_at: Option<String>,
95    pub class_id: Option<String>,
96    pub strict_write: bool,
97    /// True when the user has a *confirmed* second factor. Enrollment alone does
98    /// not set it — see [`totp_enroll`] for why the two are separate.
99    pub totp_enabled: bool,
100}
101
102/// A stored API token descriptor.  The actual token is returned only on creation.
103#[derive(Debug, Clone, Serialize, Deserialize)]
104pub struct TokenRecord {
105    pub id: String,
106    pub user_id: String,
107    pub description: Option<String>,
108    pub created_at: String,
109    pub expires_at: Option<String>,
110}
111
112/// A single RBAC permission row.
113#[derive(Debug, Clone, Serialize, Deserialize)]
114pub struct PermissionRecord {
115    pub user_id: String,
116    /// `"vault"` | `"project"` | `"category"`
117    pub scope_type: String,
118    /// Glob pattern: `"*"`, `"wg0-*"`, `"Cloud/AWS"`, etc.
119    pub scope_value: String,
120    /// `"read"` | `"write"` (write implies read)
121    pub permission: String,
122}
123
124// ── Schema ────────────────────────────────────────────────────────────────────
125
126/// Creates all user-related tables (idempotent) and seeds default classes.
127pub fn init_users_schema(conn: &Connection) -> Result<(), String> {
128    conn.execute_batch(
129        "CREATE TABLE IF NOT EXISTS users (
130             id            TEXT PRIMARY KEY,
131             username      TEXT NOT NULL UNIQUE,
132             password_hash TEXT,
133             is_owner      INTEGER NOT NULL DEFAULT 0,
134             created_at    TEXT NOT NULL,
135             last_seen_at  TEXT
136         );
137         CREATE TABLE IF NOT EXISTS user_tokens (
138             id          TEXT PRIMARY KEY,
139             token_hash  TEXT NOT NULL UNIQUE,
140             user_id     TEXT NOT NULL,
141             description TEXT,
142             created_at  TEXT NOT NULL,
143             expires_at  TEXT
144         );
145         CREATE TABLE IF NOT EXISTS user_permissions (
146             user_id     TEXT NOT NULL,
147             scope_type  TEXT NOT NULL,
148             scope_value TEXT NOT NULL,
149             permission  TEXT NOT NULL,
150             PRIMARY KEY (user_id, scope_type, scope_value)
151         );
152         CREATE TABLE IF NOT EXISTS user_classes (
153             id                   TEXT PRIMARY KEY,
154             name                 TEXT NOT NULL UNIQUE,
155             description          TEXT NOT NULL DEFAULT '',
156             cap_manage_users     INTEGER NOT NULL DEFAULT 0,
157             cap_manage_classes   INTEGER NOT NULL DEFAULT 0,
158             cap_delete_projects  INTEGER NOT NULL DEFAULT 0,
159             created_at           TEXT NOT NULL
160         );
161         CREATE TABLE IF NOT EXISTS user_class_permissions (
162             class_id    TEXT NOT NULL,
163             scope_type  TEXT NOT NULL,
164             scope_value TEXT NOT NULL,
165             permission  TEXT NOT NULL,
166             PRIMARY KEY (class_id, scope_type, scope_value)
167         );
168         CREATE TABLE IF NOT EXISTS permission_expressions (
169             subject_kind TEXT NOT NULL,   -- 'user' | 'class'
170             subject_id   TEXT NOT NULL,
171             permission   TEXT NOT NULL,   -- 'read' | 'write'
172             expression   TEXT NOT NULL,
173             PRIMARY KEY (subject_kind, subject_id, permission)
174         );",
175    )
176    .map_err(|e| e.to_string())?;
177
178    // Schema migrations check the column first, so a real ALTER error cannot
179    // be mistaken for the duplicate-column case on an older vault.
180    crate::migrate_schema::add_column_if_missing(conn, "users", "class_id", "TEXT")?;
181    // Strict write scoping. Defaults to 0 — existing users keep the behaviour
182    // they had, because a migration that silently tightened permissions would
183    // break running deployments in a way nobody could attribute to an upgrade.
184    crate::migrate_schema::add_column_if_missing(
185        conn,
186        "users",
187        "strict_write",
188        "INTEGER NOT NULL DEFAULT 0",
189    )?;
190    crate::migrate_schema::add_column_if_missing(
191        conn,
192        "user_classes",
193        "strict_write",
194        "INTEGER NOT NULL DEFAULT 0",
195    )?;
196    // TOTP, three columns rather than one:
197    //   totp_secret     — base32, present from enrollment onwards
198    //   totp_enabled    — set only once a code has been confirmed
199    //   totp_last_step  — the anti-replay high-water mark
200    // Splitting secret from enabled is what makes enrollment two-phase: a secret
201    // that exists but is not enabled locks nobody out if the authenticator never
202    // actually took the QR-less manual entry.
203    crate::migrate_schema::add_column_if_missing(conn, "users", "totp_secret", "TEXT")?;
204    crate::migrate_schema::add_column_if_missing(
205        conn,
206        "users",
207        "totp_enabled",
208        "INTEGER NOT NULL DEFAULT 0",
209    )?;
210    crate::migrate_schema::add_column_if_missing(conn, "users", "totp_last_step", "INTEGER")?;
211
212    // Seed default classes if none exist
213    let class_count: i32 = conn
214        .query_row("SELECT COUNT(*) FROM user_classes", [], |r| r.get(0))
215        .unwrap_or(0);
216    if class_count == 0 {
217        seed_default_classes(conn)?;
218    }
219
220    // Must run *after* seeding: on a fresh database the seeded class permission
221    // rows are themselves what gets compiled into expressions. Run before, and
222    // the built-in Admin/Moderator/Viewer classes would end up with no rules at
223    // all — silently denying everything.
224    migrate_rows_to_expressions(conn)?;
225    Ok(())
226}
227
228// ── Permission expressions ────────────────────────────────────────────────────
229
230/// One-time compilation of the legacy `(scope_type, scope_value, permission)`
231/// rows into equivalent expressions.
232///
233/// Legacy rows always meant "any of these matches", so they compile to an OR
234/// chain — which reproduces the old read behaviour exactly. Guarded by a marker
235/// in `vault_meta` rather than by "is the table empty", so deliberately clearing
236/// every expression does not resurrect the old rules on the next start.
237fn migrate_rows_to_expressions(conn: &Connection) -> Result<(), String> {
238    let done: Option<String> = conn
239        .query_row(
240            "SELECT value FROM vault_meta WHERE key = 'perm_expr_migrated'",
241            [],
242            |r| r.get(0),
243        )
244        .optional()
245        .map_err(|e| e.to_string())?;
246    if done.is_some() {
247        return Ok(());
248    }
249
250    for (kind, table, id_col) in [
251        ("user", "user_permissions", "user_id"),
252        ("class", "user_class_permissions", "class_id"),
253    ] {
254        let sql = format!("SELECT {id_col}, scope_type, scope_value, permission FROM {table}");
255        let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
256        let rows: Vec<(String, String, String, String)> = stmt
257            .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))
258            .map_err(|e| e.to_string())?
259            .filter_map(Result::ok)
260            .collect();
261
262        // subject -> (read scopes, write scopes). Write also grants read.
263        let mut by_subject: PermissionsBySubject = HashMap::new();
264        for (sid, scope_type, scope_value, permission) in rows {
265            let e = by_subject.entry(sid).or_default();
266            e.0.push((scope_type.clone(), scope_value.clone()));
267            if permission == "write" {
268                e.1.push((scope_type, scope_value));
269            }
270        }
271
272        for (sid, (read_scopes, write_scopes)) in by_subject {
273            for (perm, scopes) in [("read", read_scopes), ("write", write_scopes)] {
274                let refs: Vec<(&str, &str)> = scopes
275                    .iter()
276                    .map(|(a, b)| (a.as_str(), b.as_str()))
277                    .collect();
278                if let Some(expr) = crate::permex::compile_scopes(refs) {
279                    conn.execute(
280                        "INSERT OR REPLACE INTO permission_expressions \
281                         (subject_kind, subject_id, permission, expression) VALUES (?1, ?2, ?3, ?4)",
282                        rusqlite::params![kind, sid, perm, expr.to_string()],
283                    ).map_err(|e| e.to_string())?;
284                }
285            }
286        }
287    }
288
289    conn.execute(
290        "INSERT OR REPLACE INTO vault_meta (key, value) VALUES ('perm_expr_migrated', ?1)",
291        rusqlite::params![iso_now()],
292    )
293    .map_err(|e| e.to_string())?;
294    Ok(())
295}
296
297/// Reads a stored expression for a subject, if any.
298pub fn get_permission_expr(
299    conn: &Connection,
300    subject_kind: &str,
301    subject_id: &str,
302    permission: &str,
303) -> Result<Option<String>, String> {
304    conn.query_row(
305        "SELECT expression FROM permission_expressions \
306         WHERE subject_kind = ?1 AND subject_id = ?2 AND permission = ?3",
307        rusqlite::params![subject_kind, subject_id, permission],
308        |r| r.get(0),
309    )
310    .optional()
311    .map_err(|e| e.to_string())
312}
313
314/// Stores an expression, or clears it when `expression` is empty/blank.
315///
316/// Validates by parsing first: an unparseable expression denies everything at
317/// evaluation time, so letting one be saved would silently lock a user out.
318pub fn set_permission_expr(
319    conn: &Connection,
320    subject_kind: &str,
321    subject_id: &str,
322    permission: &str,
323    expression: &str,
324) -> Result<(), String> {
325    if !matches!(subject_kind, "user" | "class") {
326        return Err(format!("unknown subject kind '{subject_kind}'"));
327    }
328    if !matches!(permission, "read" | "write") {
329        return Err(format!("unknown permission '{permission}'"));
330    }
331    if expression.trim().is_empty() {
332        conn.execute(
333            "DELETE FROM permission_expressions \
334             WHERE subject_kind = ?1 AND subject_id = ?2 AND permission = ?3",
335            rusqlite::params![subject_kind, subject_id, permission],
336        )
337        .map_err(|e| e.to_string())?;
338        return Ok(());
339    }
340    let parsed = crate::permex::parse(expression)?;
341    conn.execute(
342        "INSERT OR REPLACE INTO permission_expressions \
343         (subject_kind, subject_id, permission, expression) VALUES (?1, ?2, ?3, ?4)",
344        rusqlite::params![subject_kind, subject_id, permission, parsed.to_string()],
345    )
346    .map_err(|e| e.to_string())?;
347    Ok(())
348}
349
350/// Whether writes for this user must satisfy **every** scope rather than any.
351///
352/// True when the user *or* their class has it set. The OR is deliberate and is
353/// the fail-closed direction: a class that exists to constrain a group must not
354/// be looser than the group, and an individual asked to be strict must not be
355/// relaxed by their class.
356pub fn strict_write_for(conn: &Connection, user_id: &str) -> Result<bool, String> {
357    let user: i64 = conn
358        .query_row(
359            "SELECT COALESCE(strict_write, 0) FROM users WHERE id = ?1",
360            rusqlite::params![user_id],
361            |r| r.get(0),
362        )
363        .optional()
364        .map_err(|e| e.to_string())?
365        .unwrap_or(0);
366    if user != 0 {
367        return Ok(true);
368    }
369    let class: i64 = conn
370        .query_row(
371            "SELECT COALESCE(c.strict_write, 0) FROM users u \
372             JOIN user_classes c ON c.id = u.class_id WHERE u.id = ?1",
373            rusqlite::params![user_id],
374            |r| r.get(0),
375        )
376        .optional()
377        .map_err(|e| e.to_string())?
378        .unwrap_or(0);
379    Ok(class != 0)
380}
381
382/// Turn strict write scoping on or off for a user or a class.
383pub fn set_strict_write(
384    conn: &Connection,
385    subject_kind: &str,
386    subject_id: &str,
387    strict: bool,
388) -> Result<(), String> {
389    let table = match subject_kind {
390        "user" => "users",
391        "class" => "user_classes",
392        other => return Err(format!("unknown subject kind '{other}'")),
393    };
394    let n = conn
395        .execute(
396            &format!("UPDATE {table} SET strict_write = ?1 WHERE id = ?2"),
397            rusqlite::params![i64::from(strict), subject_id],
398        )
399        .map_err(|e| e.to_string())?;
400    if n == 0 {
401        return Err(format!("No such {subject_kind}: {subject_id}"));
402    }
403    Ok(())
404}
405
406/// Resolves what a user may actually do, combining their class and individual rules.
407///
408/// - Class and individual are **AND**ed, so a class exclusion cannot be undone
409///   by an individual grant.
410/// - `None` means no grant at all — callers must deny. Absent expressions are
411///   deliberately not treated as "no restriction": under AND that would give a
412///   user with no permissions whatsoever full access.
413/// - Write implies read, so the effective read rule is `read OR write`.
414/// - Under strict write scoping the write rule is narrowed further — see
415///   [`strict_write_for`] and [`crate::permex::require_all`].
416pub fn effective_permission_expr(
417    conn: &Connection,
418    user_id: &str,
419    permission: &str,
420) -> Result<Option<crate::permex::Expr>, String> {
421    let class_id: Option<String> = conn
422        .query_row(
423            "SELECT class_id FROM users WHERE id = ?1",
424            rusqlite::params![user_id],
425            |r| r.get(0),
426        )
427        .optional()
428        .map_err(|e| e.to_string())?
429        .flatten();
430
431    // Stored text is always re-parsed rather than trusted: a row edited outside
432    // the app must fail closed.
433    let load = |kind: &str, id: &str, perm: &str| -> Result<Option<crate::permex::Expr>, String> {
434        Ok(get_permission_expr(conn, kind, id, perm)?
435            .and_then(|src| crate::permex::parse(&src).ok()))
436    };
437
438    let raw = |perm: &str| -> Result<Option<crate::permex::Expr>, String> {
439        let individual = load("user", user_id, perm)?;
440        let class = match &class_id {
441            Some(cid) => load("class", cid, perm)?,
442            None => None,
443        };
444        Ok(crate::permex::combine(class, individual))
445    };
446
447    match permission {
448        // Strict mode narrows writes only. Reads keep ANY-match semantics
449        // deliberately: a user who cannot see an entry cannot review what they
450        // are about to change, and tightening reads here would make the strict
451        // user's own vault look empty.
452        "write" => Ok(raw("write")?.map(|e| {
453            if strict_write_for(conn, user_id).unwrap_or(false) {
454                crate::permex::require_all(e)
455            } else {
456                e
457            }
458        })),
459        // Note this reads the *unstrictified* write rule, so turning strict mode
460        // on never removes visibility — only the ability to change.
461        "read" => Ok(crate::permex::any_of(raw("read")?, raw("write")?)),
462        other => Err(format!("unknown permission '{other}'")),
463    }
464}
465
466/// Seeds the three built-in user classes: Admin, Moderator, Viewer.
467fn seed_default_classes(conn: &Connection) -> Result<(), String> {
468    let now = iso_now();
469
470    struct ClassSeed<'a> {
471        id: &'a str,
472        name: &'a str,
473        description: &'a str,
474        cap_manage_users: i32,
475        cap_manage_classes: i32,
476        cap_delete_projects: i32,
477        perms: &'a [(&'a str, &'a str, &'a str)], // (scope_type, scope_value, permission)
478    }
479
480    let seeds = [
481        ClassSeed {
482            id: "cls-admin",
483            name: "Admin",
484            description: "Full vault access. Can manage users and classes.",
485            cap_manage_users: 1,
486            cap_manage_classes: 1,
487            cap_delete_projects: 1,
488            perms: &[("vault", "*", "write")],
489        },
490        ClassSeed {
491            id: "cls-moderator",
492            name: "Moderator",
493            description: "Full vault access. Can manage users but not classes or project deletion.",
494            cap_manage_users: 1,
495            cap_manage_classes: 0,
496            cap_delete_projects: 0,
497            perms: &[("vault", "*", "write")],
498        },
499        ClassSeed {
500            id: "cls-viewer",
501            name: "Viewer",
502            description: "Read-only access to the entire vault.",
503            cap_manage_users: 0,
504            cap_manage_classes: 0,
505            cap_delete_projects: 0,
506            perms: &[("vault", "*", "read")],
507        },
508    ];
509
510    for s in &seeds {
511        conn.execute(
512            "INSERT OR IGNORE INTO user_classes (id, name, description, cap_manage_users, cap_manage_classes, cap_delete_projects, created_at) \
513             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
514            rusqlite::params![s.id, s.name, s.description, s.cap_manage_users, s.cap_manage_classes, s.cap_delete_projects, now],
515        ).map_err(|e| e.to_string())?;
516        for (scope_type, scope_value, permission) in s.perms {
517            conn.execute(
518                "INSERT OR IGNORE INTO user_class_permissions (class_id, scope_type, scope_value, permission) VALUES (?1, ?2, ?3, ?4)",
519                rusqlite::params![s.id, scope_type, scope_value, permission],
520            ).map_err(|e| e.to_string())?;
521        }
522    }
523    Ok(())
524}
525
526// ── Internal helpers ──────────────────────────────────────────────────────────
527
528/// Kept as a local name because this module reaches for it constantly; the one
529/// implementation is [`crate::new_uuid`], which the desktop app's TOTP import
530/// also calls. A second generator would be a second thing to get the version
531/// and variant bits wrong in.
532fn new_uuid() -> String {
533    crate::new_uuid()
534}
535
536/// Hashes `password` with Argon2id (m=32768, t=2, p=1) and returns a
537/// self-describing PHC string `$argon2id$v=19$...` suitable for long-term storage.
538///
539/// Uses lower cost params than the vault KDF to keep interactive login fast
540/// while still providing >200ms hash time on modern hardware.
541fn hash_password(password: &str) -> String {
542    use argon2::{Algorithm, Argon2, Params, PasswordHasher, Version};
543
544    let params = Params::new(32_768, 2, 1, None).expect("valid argon2 params");
545    let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
546    argon2
547        .hash_password(password.as_bytes())
548        .expect("argon2 hash")
549        .to_string()
550}
551
552/// Verifies `password` against `stored`.
553///
554/// Supports two on-disk formats:
555/// - **PHC** (`$argon2id$…`) — new default since Phase 5.1.
556/// - **Legacy SHA-256** (`<salt_hex>:<hash_hex>`) — written by Phase 5.0 and earlier.
557///
558/// Returns `true` only when the password matches.  Callers should re-hash with
559/// `hash_password` after a successful legacy verification to upgrade the stored hash.
560fn verify_password_hash(password: &str, stored: &str) -> bool {
561    if stored.starts_with("$argon2") {
562        use argon2::password_hash::phc::PasswordHash;
563        use argon2::{Argon2, PasswordVerifier};
564        let Ok(parsed) = PasswordHash::new(stored) else {
565            return false;
566        };
567        Argon2::default()
568            .verify_password(password.as_bytes(), &parsed)
569            .is_ok()
570    } else {
571        // Legacy: "<salt_hex>:<sha256_hex>" — upgrade on next login
572        let mut parts = stored.splitn(2, ':');
573        let (Some(salt_hex), Some(hash_hex)) = (parts.next(), parts.next()) else {
574            return false;
575        };
576        let Ok(salt) = hex::decode(salt_hex) else {
577            return false;
578        };
579        let Ok(expected) = hex::decode(hash_hex) else {
580            return false;
581        };
582        let mut h = Sha256::new();
583        h.update(&salt);
584        h.update(password.as_bytes());
585        let computed = h.finalize();
586        // Constant-time comparison — avoids timing side-channel on legacy hashes.
587        computed.len() == expected.len()
588            && computed
589                .iter()
590                .zip(expected.iter())
591                .fold(0u8, |acc, (a, b)| acc | (a ^ b))
592                == 0
593    }
594}
595
596/// Runs one Argon2 verification against a throwaway hash and discards the result.
597///
598/// An unknown username used to return in microseconds while a known one spent
599/// ~100 ms in Argon2, so the response time alone said which usernames exist. The
600/// dummy is made with [`hash_password`], so its cost parameters always match what
601/// a real user pays.
602fn spend_verify_time(password: &str) {
603    static DUMMY: std::sync::OnceLock<String> = std::sync::OnceLock::new();
604    let dummy = DUMMY.get_or_init(|| hash_password("unv-dummy-never-a-real-password"));
605    let _ = verify_password_hash(password, dummy);
606    #[cfg(test)]
607    DUMMY_VERIFIES.with(|c| c.set(c.get() + 1));
608}
609
610// Test hook: how many times the dummy verification ran on this thread (each
611// test has its own thread, so parallel tests cannot disturb the count).
612#[cfg(test)]
613thread_local! {
614    static DUMMY_VERIFIES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
615}
616
617fn sha256_hex(input: &str) -> String {
618    let mut h = Sha256::new();
619    h.update(input.as_bytes());
620    hex::encode(h.finalize())
621}
622
623fn touch_last_seen(conn: &Connection, user_id: &str) -> Result<(), String> {
624    conn.execute(
625        "UPDATE users SET last_seen_at = ?1 WHERE id = ?2",
626        rusqlite::params![iso_now(), user_id],
627    )
628    .map(|_| ())
629    .map_err(|e| e.to_string())
630}
631
632// ── User CRUD ─────────────────────────────────────────────────────────────────
633
634/// The shortest password a named user may be given, wherever it is set: the server, the CLI and
635/// the desktop all call [`check_user_password`], so a vault cannot be given a weaker account by
636/// choosing the other front end. The per-address limiter is the only other defence of an account.
637pub const MIN_USER_PASSWORD_CHARS: usize = 12;
638
639/// `Ok` for no password (a token-only user) and for one of at least [`MIN_USER_PASSWORD_CHARS`].
640pub fn check_user_password(password: Option<&str>) -> Result<(), String> {
641    match password {
642        Some(p) if p.chars().count() < MIN_USER_PASSWORD_CHARS => Err(format!(
643            "A password must be at least {MIN_USER_PASSWORD_CHARS} characters"
644        )),
645        _ => Ok(()),
646    }
647}
648
649/// Creates a new user.  Pass `password = None` for token-only auth.
650pub fn create_user(
651    conn: &Connection,
652    username: &str,
653    password: Option<&str>,
654    is_owner: bool,
655) -> Result<UserRecord, String> {
656    let id = new_uuid();
657    let now = iso_now();
658    let password_hash = password.map(hash_password);
659    conn.execute(
660        "INSERT INTO users (id, username, password_hash, is_owner, created_at) \
661         VALUES (?1, ?2, ?3, ?4, ?5)",
662        rusqlite::params![id, username, password_hash, is_owner as i32, now],
663    )
664    .map_err(|e| e.to_string())?;
665    Ok(UserRecord {
666        id,
667        username: username.to_string(),
668        has_password: password.is_some(),
669        is_owner,
670        created_at: now,
671        last_seen_at: None,
672        class_id: None,
673        strict_write: false,
674        totp_enabled: false,
675    })
676}
677
678/// Renames a user (owner or non-owner).  Fails if `new_username` is already taken.
679pub fn rename_user(conn: &Connection, user_id: &str, new_username: &str) -> Result<(), String> {
680    conn.execute(
681        "UPDATE users SET username = ?1 WHERE id = ?2",
682        rusqlite::params![new_username, user_id],
683    )
684    .map(|_| ())
685    .map_err(|e| e.to_string())
686}
687
688/// Updates (or clears) a user's password.
689pub fn set_user_password(
690    conn: &Connection,
691    user_id: &str,
692    password: Option<&str>,
693) -> Result<(), String> {
694    conn.execute(
695        "UPDATE users SET password_hash = ?1 WHERE id = ?2",
696        rusqlite::params![password.map(hash_password), user_id],
697    )
698    .map(|_| ())
699    .map_err(|e| e.to_string())
700}
701
702/// Verifies username + password.  Returns `None` on invalid credentials.
703pub fn verify_user_password(
704    conn: &Connection,
705    username: &str,
706    password: &str,
707) -> Result<Option<UserRecord>, String> {
708    let row: Option<UserRow> = conn
709        .query_row(
710            "SELECT id, username, password_hash, is_owner, created_at, last_seen_at, class_id, strict_write, totp_enabled \
711             FROM users WHERE username = ?1",
712            rusqlite::params![username],
713            |r| {
714                Ok((
715                    r.get(0)?,
716                    r.get(1)?,
717                    r.get(2)?,
718                    r.get(3)?,
719                    r.get(4)?,
720                    r.get(5)?,
721                    r.get(6)?,
722                    r.get(7)?,
723                    r.get(8)?,
724                ))
725            },
726        )
727        .optional()
728        .map_err(|e| e.to_string())?;
729
730    let Some((
731        id,
732        uname,
733        hash_opt,
734        is_owner_i,
735        created_at,
736        last_seen,
737        class_id,
738        strict_write,
739        totp_on,
740    )) = row
741    else {
742        spend_verify_time(password);
743        return Ok(None);
744    };
745    // A user with no password (token-only, or the owner row) simply cannot
746    // authenticate this way — that is an ordinary credential failure, not a
747    // server error.
748    //
749    // This previously returned Err, which the server turned into a 500 while a
750    // nonexistent username returned 401, and only the 401 path incremented the
751    // rate limiter. The 500-vs-401 difference was an unthrottled username
752    // enumeration oracle.
753    let Some(stored) = hash_opt else {
754        spend_verify_time(password);
755        return Ok(None);
756    };
757    if !verify_password_hash(password, &stored) {
758        return Ok(None);
759    }
760    // Transparent upgrade: rehash with Argon2id when the stored hash is legacy SHA-256.
761    if !stored.starts_with("$argon2") {
762        let new_hash = hash_password(password);
763        let _ = conn.execute(
764            "UPDATE users SET password_hash = ?1 WHERE id = ?2",
765            rusqlite::params![new_hash, id],
766        );
767    }
768    touch_last_seen(conn, &id)?;
769    Ok(Some(UserRecord {
770        id,
771        username: uname,
772        has_password: true,
773        is_owner: is_owner_i != 0,
774        created_at,
775        last_seen_at: last_seen,
776        class_id,
777        strict_write: strict_write != 0,
778        totp_enabled: totp_on != 0,
779    }))
780}
781
782/// Verifies a raw 64-char hex token.  Returns `None` if invalid or expired.
783pub fn verify_user_token(conn: &Connection, token: &str) -> Result<Option<UserRecord>, String> {
784    let token_hash = sha256_hex(token);
785    let now = iso_now();
786    let row: Option<UserRow> = conn
787        .query_row(
788            "SELECT u.id, u.username, u.password_hash, u.is_owner, u.created_at, u.last_seen_at, \
789                     u.class_id, u.strict_write, u.totp_enabled \
790             FROM user_tokens t JOIN users u ON u.id = t.user_id \
791             WHERE t.token_hash = ?1 AND (t.expires_at IS NULL OR t.expires_at > ?2)",
792            rusqlite::params![token_hash, now],
793            |r| {
794                Ok((
795                    r.get(0)?,
796                    r.get(1)?,
797                    r.get(2)?,
798                    r.get(3)?,
799                    r.get(4)?,
800                    r.get(5)?,
801                    r.get(6)?,
802                    r.get(7)?,
803                    r.get(8)?,
804                ))
805            },
806        )
807        .optional()
808        .map_err(|e| e.to_string())?;
809
810    let Some((
811        id,
812        uname,
813        hash_opt,
814        is_owner_i,
815        created_at,
816        last_seen,
817        class_id,
818        strict_write,
819        totp_on,
820    )) = row
821    else {
822        return Ok(None);
823    };
824    touch_last_seen(conn, &id)?;
825    Ok(Some(UserRecord {
826        id,
827        username: uname,
828        has_password: hash_opt.is_some(),
829        is_owner: is_owner_i != 0,
830        created_at,
831        last_seen_at: last_seen,
832        class_id,
833        strict_write: strict_write != 0,
834        totp_enabled: totp_on != 0,
835    }))
836}
837
838/// Lists all users, owners first, then by creation date.
839pub fn list_users(conn: &Connection) -> Result<Vec<UserRecord>, String> {
840    let mut stmt = conn
841        .prepare(
842            "SELECT id, username, password_hash, is_owner, created_at, last_seen_at, class_id, strict_write, totp_enabled \
843         FROM users ORDER BY is_owner DESC, created_at ASC",
844        )
845        .map_err(|e| e.to_string())?;
846    let rows: Vec<Result<UserRecord, _>> = stmt
847        .query_map([], |r| {
848            Ok(UserRecord {
849                id: r.get(0)?,
850                username: r.get(1)?,
851                has_password: r.get::<_, Option<String>>(2)?.is_some(),
852                is_owner: r.get::<_, i32>(3)? != 0,
853                created_at: r.get(4)?,
854                last_seen_at: r.get(5)?,
855                class_id: r.get(6)?,
856                strict_write: r.get::<_, i32>(7)? != 0,
857                totp_enabled: r.get::<_, i32>(8)? != 0,
858            })
859        })
860        .map_err(|e| e.to_string())?
861        .collect();
862    rows.into_iter()
863        .map(|r| r.map_err(|e| e.to_string()))
864        .collect()
865}
866
867// ── TOTP (second factor for sub-users) ────────────────────────────────────────
868
869/// What the UI and CLI need to draw a user's second-factor state.
870#[derive(Debug, Clone, Serialize, Deserialize)]
871pub struct TotpStatus {
872    /// A secret exists. Enrollment has started but may never have been confirmed.
873    pub enrolled: bool,
874    /// A code has been confirmed, and login now requires one.
875    pub enabled: bool,
876    /// Present **only** in the response to [`totp_enroll`]. Never returned by
877    /// [`totp_status`]: the secret is shown once, at the moment the user is
878    /// putting it into their authenticator, and a status endpoint that handed it
879    /// back would make every later read of the user list a way to clone the
880    /// factor.
881    pub secret: Option<String>,
882    /// The `otpauth://` URI for the same secret, on the same terms.
883    pub uri: Option<String>,
884}
885
886/// Refuses anything to do with TOTP for the vault owner.
887///
888/// The owner authenticates by deriving the SQLCipher key from the master
889/// password; there is no stored hash and no login form in that path, so a second
890/// factor here would be a control that gates nothing while appearing to gate
891/// everything. Enforced in `vault-core` rather than at each caller, because a
892/// check that lives in the server is one the CLI and the desktop app each have
893/// to remember separately.
894fn refuse_owner(conn: &Connection, user_id: &str) -> Result<(), String> {
895    let is_owner: i32 = conn
896        .query_row(
897            "SELECT is_owner FROM users WHERE id = ?1",
898            rusqlite::params![user_id],
899            |r| r.get(0),
900        )
901        .optional()
902        .map_err(|e| e.to_string())?
903        .ok_or_else(|| "no such user".to_string())?;
904    if is_owner != 0 {
905        return Err(
906            "the vault owner authenticates by deriving the vault key; a second factor \
907             there would gate nothing"
908                .into(),
909        );
910    }
911    Ok(())
912}
913
914/// Phase one of enrollment: mints a secret and returns it with its URI.
915///
916/// The factor is **not** enabled by this call. Enabling on enrollment locks out
917/// any user whose authenticator did not actually take the secret — which, with
918/// manual base32 entry and no QR code, is a routine outcome rather than an edge
919/// case. [`totp_confirm`] is what turns it on, and it requires a working code.
920///
921/// Re-enrolling an already-enabled user replaces the secret and switches the
922/// factor back off, so a half-finished re-enrollment cannot leave the account
923/// requiring a code nobody can generate.
924pub fn totp_enroll(conn: &Connection, user_id: &str, issuer: &str) -> Result<TotpStatus, String> {
925    refuse_owner(conn, user_id)?;
926    let username: String = conn
927        .query_row(
928            "SELECT username FROM users WHERE id = ?1",
929            rusqlite::params![user_id],
930            |r| r.get(0),
931        )
932        .map_err(|e| e.to_string())?;
933
934    let secret = crate::totp::generate_secret();
935    conn.execute(
936        "UPDATE users SET totp_secret = ?1, totp_enabled = 0, totp_last_step = NULL WHERE id = ?2",
937        rusqlite::params![secret, user_id],
938    )
939    .map_err(|e| e.to_string())?;
940
941    let uri = crate::totp::otpauth_uri(issuer, &username, &secret);
942    Ok(TotpStatus {
943        enrolled: true,
944        enabled: false,
945        secret: Some(secret),
946        uri: Some(uri),
947    })
948}
949
950/// Phase two: enables the factor once the user proves their authenticator works.
951///
952/// The confirming code's step is recorded, so the very code used to enable the
953/// factor cannot then be replayed to log in with it.
954///
955/// **`confirm` obeys the same anti-replay mark as `verify`, and never moves it
956/// backwards.** Passing `None` here — which the first version did — makes this a
957/// second oracle where one code works twice, and worse: re-confirming with a
958/// code from an *earlier* step wrote that lower step back, re-opening every step
959/// in between for replay on the login path. Enrollment is what clears the mark,
960/// and it does so deliberately (see [`totp_enroll`]).
961pub fn totp_confirm(conn: &Connection, user_id: &str, code: &str) -> Result<bool, String> {
962    refuse_owner(conn, user_id)?;
963    let row: Option<(Option<String>, Option<i64>)> = conn
964        .query_row(
965            "SELECT totp_secret, totp_last_step FROM users WHERE id = ?1",
966            rusqlite::params![user_id],
967            |r| Ok((r.get(0)?, r.get(1)?)),
968        )
969        .optional()
970        .map_err(|e| e.to_string())?;
971    let Some((secret, last_step)) = row else {
972        return Err("no such user".into());
973    };
974    let Some(secret) = secret else {
975        return Err("no enrollment in progress; run enroll first".into());
976    };
977    let last = last_step.and_then(|v| u64::try_from(v).ok());
978    let Some(accepted) = crate::totp::verify(&secret, code, last, crate::totp::now_unix()) else {
979        return Ok(false);
980    };
981    // Compare-and-swap on the replay mark: see `verify_user_totp`.
982    let moved = conn
983        .execute(
984            "UPDATE users SET totp_enabled = 1, totp_last_step = ?1 \
985             WHERE id = ?2 AND (totp_last_step IS NULL OR totp_last_step < ?1)",
986            rusqlite::params![accepted.step as i64, user_id],
987        )
988        .map_err(|e| e.to_string())?;
989    Ok(moved == 1)
990}
991
992/// Removes the factor entirely, secret included.
993///
994/// Clearing the secret rather than only the flag matters: leaving it behind
995/// means a later `totp_enable` could silently re-arm a secret the user believes
996/// they destroyed, on an authenticator entry they may have deleted.
997pub fn totp_disable(conn: &Connection, user_id: &str) -> Result<(), String> {
998    conn.execute(
999        "UPDATE users SET totp_secret = NULL, totp_enabled = 0, totp_last_step = NULL \
1000         WHERE id = ?1",
1001        rusqlite::params![user_id],
1002    )
1003    .map(|_| ())
1004    .map_err(|e| e.to_string())
1005}
1006
1007/// Reports enrollment and enabled state. Never returns the secret — see
1008/// [`TotpStatus::secret`].
1009pub fn totp_status(conn: &Connection, user_id: &str) -> Result<TotpStatus, String> {
1010    let (secret, enabled): (Option<String>, i32) = conn
1011        .query_row(
1012            "SELECT totp_secret, totp_enabled FROM users WHERE id = ?1",
1013            rusqlite::params![user_id],
1014            |r| Ok((r.get(0)?, r.get(1)?)),
1015        )
1016        .map_err(|e| e.to_string())?;
1017    Ok(TotpStatus {
1018        enrolled: secret.is_some(),
1019        enabled: enabled != 0,
1020        secret: None,
1021        uri: None,
1022    })
1023}
1024
1025/// Whether login for this user must present a code.
1026pub fn totp_required(conn: &Connection, user_id: &str) -> Result<bool, String> {
1027    let enabled: i32 = conn
1028        .query_row(
1029            "SELECT totp_enabled FROM users WHERE id = ?1",
1030            rusqlite::params![user_id],
1031            |r| r.get(0),
1032        )
1033        .optional()
1034        .map_err(|e| e.to_string())?
1035        .unwrap_or(0);
1036    Ok(enabled != 0)
1037}
1038
1039/// Verifies a login code and advances the anti-replay high-water mark.
1040///
1041/// Fails **closed**: a NULL secret on an enabled account returns `false` rather
1042/// than `true`. That exact inversion is in this project's bug history — the
1043/// Phase 5.1 implementation returned `Ok(true)` for a missing secret, which made
1044/// "enabled but unconfigured" the same as "authenticated".
1045///
1046/// The step is written back before the caller is told the code was good, so a
1047/// concurrent second attempt with the same code loses the race rather than
1048/// winning it.
1049pub fn verify_user_totp(conn: &Connection, user_id: &str, code: &str) -> Result<bool, String> {
1050    let row: Option<(Option<String>, i32, Option<i64>)> = conn
1051        .query_row(
1052            "SELECT totp_secret, totp_enabled, totp_last_step FROM users WHERE id = ?1",
1053            rusqlite::params![user_id],
1054            |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
1055        )
1056        .optional()
1057        .map_err(|e| e.to_string())?;
1058    let Some((secret, enabled, last_step)) = row else {
1059        return Ok(false);
1060    };
1061    if enabled == 0 {
1062        return Ok(false);
1063    }
1064    let Some(secret) = secret else {
1065        return Ok(false);
1066    };
1067    let last = last_step.and_then(|v| u64::try_from(v).ok());
1068    let Some(accepted) = crate::totp::verify(&secret, code, last, crate::totp::now_unix()) else {
1069        return Ok(false);
1070    };
1071    // The mark moves only forward, and only if nobody moved it since it was read above.
1072    // It was an unconditional UPDATE: two attempts with the same code both read the old
1073    // mark, both verified, both wrote and both were let in, and a slower attempt with an
1074    // OLDER code could write after a newer one and move the mark backwards, making the
1075    // newer code (seen by anyone watching) valid again.
1076    let moved = conn
1077        .execute(
1078            "UPDATE users SET totp_last_step = ?1 \
1079             WHERE id = ?2 AND (totp_last_step IS NULL OR totp_last_step < ?1)",
1080            rusqlite::params![accepted.step as i64, user_id],
1081        )
1082        .map_err(|e| e.to_string())?;
1083    Ok(moved == 1)
1084}
1085
1086/// Deletes a user plus all their tokens and permissions.
1087/// Returns `Err` if `user_id` belongs to the owner account.
1088pub fn delete_user(conn: &Connection, user_id: &str) -> Result<(), String> {
1089    let is_owner: Option<i32> = conn
1090        .query_row(
1091            "SELECT is_owner FROM users WHERE id = ?1",
1092            rusqlite::params![user_id],
1093            |r| r.get(0),
1094        )
1095        .optional()
1096        .map_err(|e| e.to_string())?;
1097    if is_owner == Some(1) {
1098        return Err("Cannot delete the owner account".to_string());
1099    }
1100    conn.execute(
1101        "DELETE FROM user_permissions WHERE user_id = ?1",
1102        rusqlite::params![user_id],
1103    )
1104    .map_err(|e| e.to_string())?;
1105    conn.execute(
1106        "DELETE FROM user_tokens WHERE user_id = ?1",
1107        rusqlite::params![user_id],
1108    )
1109    .map_err(|e| e.to_string())?;
1110    // The user's expressions would otherwise outlive them: the row was read by id alone,
1111    // so a deleted user's session kept its old grant.
1112    conn.execute(
1113        "DELETE FROM permission_expressions WHERE subject_kind = 'user' AND subject_id = ?1",
1114        rusqlite::params![user_id],
1115    )
1116    .map_err(|e| e.to_string())?;
1117    conn.execute(
1118        "DELETE FROM users WHERE id = ?1",
1119        rusqlite::params![user_id],
1120    )
1121    .map_err(|e| e.to_string())?;
1122    Ok(())
1123}
1124
1125// ── User class CRUD ───────────────────────────────────────────────────────────
1126
1127pub fn list_user_classes(conn: &Connection) -> Result<Vec<UserClass>, String> {
1128    let mut stmt = conn.prepare(
1129        "SELECT id, name, description, cap_manage_users, cap_manage_classes, cap_delete_projects, strict_write, created_at \
1130         FROM user_classes ORDER BY created_at ASC"
1131    ).map_err(|e| e.to_string())?;
1132    let rows: Vec<Result<UserClass, _>> = stmt
1133        .query_map([], |r| {
1134            Ok(UserClass {
1135                id: r.get(0)?,
1136                name: r.get(1)?,
1137                description: r.get(2)?,
1138                cap_manage_users: r.get::<_, i32>(3)? != 0,
1139                cap_manage_classes: r.get::<_, i32>(4)? != 0,
1140                cap_delete_projects: r.get::<_, i32>(5)? != 0,
1141                strict_write: r.get::<_, i32>(6)? != 0,
1142                created_at: r.get(7)?,
1143            })
1144        })
1145        .map_err(|e| e.to_string())?
1146        .collect();
1147    rows.into_iter()
1148        .map(|r| r.map_err(|e| e.to_string()))
1149        .collect()
1150}
1151
1152pub fn create_user_class(
1153    conn: &Connection,
1154    name: &str,
1155    description: &str,
1156    cap_manage_users: bool,
1157    cap_manage_classes: bool,
1158    cap_delete_projects: bool,
1159) -> Result<UserClass, String> {
1160    let id = new_uuid();
1161    let now = iso_now();
1162    conn.execute(
1163        "INSERT INTO user_classes (id, name, description, cap_manage_users, cap_manage_classes, cap_delete_projects, created_at) \
1164         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
1165        rusqlite::params![id, name, description, cap_manage_users as i32, cap_manage_classes as i32, cap_delete_projects as i32, now],
1166    ).map_err(|e| e.to_string())?;
1167    Ok(UserClass {
1168        id,
1169        name: name.to_string(),
1170        description: description.to_string(),
1171        cap_manage_users,
1172        cap_manage_classes,
1173        cap_delete_projects,
1174        strict_write: false,
1175        created_at: now,
1176    })
1177}
1178
1179pub fn update_user_class(
1180    conn: &Connection,
1181    class_id: &str,
1182    name: &str,
1183    description: &str,
1184    cap_manage_users: bool,
1185    cap_manage_classes: bool,
1186    cap_delete_projects: bool,
1187) -> Result<(), String> {
1188    conn.execute(
1189        "UPDATE user_classes SET name=?1, description=?2, cap_manage_users=?3, cap_manage_classes=?4, cap_delete_projects=?5 WHERE id=?6",
1190        rusqlite::params![name, description, cap_manage_users as i32, cap_manage_classes as i32, cap_delete_projects as i32, class_id],
1191    ).map(|_| ()).map_err(|e| e.to_string())
1192}
1193
1194/// How many users are assigned to this class.
1195pub fn class_member_count(conn: &Connection, class_id: &str) -> Result<i64, String> {
1196    conn.query_row(
1197        "SELECT COUNT(*) FROM users WHERE class_id = ?1",
1198        rusqlite::params![class_id],
1199        |r| r.get(0),
1200    )
1201    .map_err(|e| e.to_string())
1202}
1203
1204pub fn delete_user_class(conn: &Connection, class_id: &str) -> Result<(), String> {
1205    // A class is a restriction ANDed with each member's own expression. Deleting it
1206    // used to unassign its members, and a member with a broad individual expression
1207    // became unrestricted: removing a restriction is a decision about each member,
1208    // so they have to be moved first. The server refuses the same way.
1209    let members = class_member_count(conn, class_id)?;
1210    if members > 0 {
1211        return Err(format!(
1212            "The class still has {members} member(s). Assign them to another class first."
1213        ));
1214    }
1215    conn.execute(
1216        "DELETE FROM user_class_permissions WHERE class_id = ?1",
1217        rusqlite::params![class_id],
1218    )
1219    .map_err(|e| e.to_string())?;
1220    conn.execute(
1221        "DELETE FROM permission_expressions WHERE subject_kind = 'class' AND subject_id = ?1",
1222        rusqlite::params![class_id],
1223    )
1224    .map_err(|e| e.to_string())?;
1225    conn.execute(
1226        "DELETE FROM user_classes WHERE id = ?1",
1227        rusqlite::params![class_id],
1228    )
1229    .map(|_| ())
1230    .map_err(|e| e.to_string())
1231}
1232
1233pub fn get_class_permissions(
1234    conn: &Connection,
1235    class_id: &str,
1236) -> Result<Vec<ClassPermission>, String> {
1237    let mut stmt = conn.prepare(
1238        "SELECT class_id, scope_type, scope_value, permission FROM user_class_permissions WHERE class_id = ?1"
1239    ).map_err(|e| e.to_string())?;
1240    let rows: Vec<Result<ClassPermission, _>> = stmt
1241        .query_map(rusqlite::params![class_id], |r| {
1242            Ok(ClassPermission {
1243                class_id: r.get(0)?,
1244                scope_type: r.get(1)?,
1245                scope_value: r.get(2)?,
1246                permission: r.get(3)?,
1247            })
1248        })
1249        .map_err(|e| e.to_string())?
1250        .collect();
1251    rows.into_iter()
1252        .map(|r| r.map_err(|e| e.to_string()))
1253        .collect()
1254}
1255
1256pub fn set_class_permissions(
1257    conn: &Connection,
1258    class_id: &str,
1259    permissions: &[ClassPermission],
1260) -> Result<(), String> {
1261    conn.execute(
1262        "DELETE FROM user_class_permissions WHERE class_id = ?1",
1263        rusqlite::params![class_id],
1264    )
1265    .map_err(|e| e.to_string())?;
1266    for p in permissions {
1267        conn.execute(
1268            "INSERT INTO user_class_permissions (class_id, scope_type, scope_value, permission) VALUES (?1, ?2, ?3, ?4)",
1269            rusqlite::params![class_id, p.scope_type, p.scope_value, p.permission],
1270        ).map_err(|e| e.to_string())?;
1271    }
1272    Ok(())
1273}
1274
1275pub fn assign_user_class(
1276    conn: &Connection,
1277    user_id: &str,
1278    class_id: Option<&str>,
1279) -> Result<(), String> {
1280    conn.execute(
1281        "UPDATE users SET class_id = ?1 WHERE id = ?2",
1282        rusqlite::params![class_id, user_id],
1283    )
1284    .map(|_| ())
1285    .map_err(|e| e.to_string())
1286}
1287
1288/// Returns the capabilities of the user's class (None values mean no class = no extra capabilities).
1289pub fn get_user_capabilities(
1290    conn: &Connection,
1291    user_id: &str,
1292) -> Result<(bool, bool, bool), String> {
1293    let class_id: Option<String> = conn
1294        .query_row(
1295            "SELECT class_id FROM users WHERE id = ?1",
1296            rusqlite::params![user_id],
1297            |r| r.get(0),
1298        )
1299        .optional()
1300        .map_err(|e| e.to_string())?
1301        .flatten();
1302    if let Some(cid) = class_id {
1303        let row: Option<(i32, i32, i32)> = conn
1304            .query_row(
1305                "SELECT cap_manage_users, cap_manage_classes, cap_delete_projects FROM user_classes WHERE id = ?1",
1306                rusqlite::params![cid],
1307                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
1308            ).optional().map_err(|e| e.to_string())?;
1309        if let Some((u, c, d)) = row {
1310            return Ok((u != 0, c != 0, d != 0));
1311        }
1312    }
1313    Ok((false, false, false))
1314}
1315
1316// ── Authority hierarchy (Discord-style: owner > admin > moderator > user) ──────
1317
1318/// Derives an authority tier from capability flags. Higher acts on strictly lower.
1319/// - 3 = owner (master-password session; never a stored user row)
1320/// - 2 = admin     (`cap_manage_classes`)
1321/// - 1 = moderator (`cap_manage_users` only)
1322/// - 0 = user      (no management capabilities)
1323pub fn authority_tier(is_owner: bool, cap_manage_users: bool, cap_manage_classes: bool) -> i32 {
1324    if is_owner {
1325        3
1326    } else if cap_manage_classes {
1327        2
1328    } else if cap_manage_users {
1329        1
1330    } else {
1331        0
1332    }
1333}
1334
1335/// Authority tier implied by a class's stored capabilities. Returns 0 if unknown.
1336pub fn class_authority_tier(conn: &Connection, class_id: &str) -> Result<i32, String> {
1337    let row: Option<(i32, i32)> = conn
1338        .query_row(
1339            "SELECT cap_manage_users, cap_manage_classes FROM user_classes WHERE id = ?1",
1340            rusqlite::params![class_id],
1341            |r| Ok((r.get(0)?, r.get(1)?)),
1342        )
1343        .optional()
1344        .map_err(|e| e.to_string())?;
1345    Ok(row
1346        .map(|(u, c)| authority_tier(false, u != 0, c != 0))
1347        .unwrap_or(0))
1348}
1349
1350/// Returns the owning user id of a token, or `None` if the token id is unknown.
1351pub fn token_user_id(conn: &Connection, token_id: &str) -> Result<Option<String>, String> {
1352    conn.query_row(
1353        "SELECT user_id FROM user_tokens WHERE id = ?1",
1354        rusqlite::params![token_id],
1355        |r| r.get(0),
1356    )
1357    .optional()
1358    .map_err(|e| e.to_string())
1359}
1360
1361/// Authority tier of a stored user (by their class capabilities, or the `is_owner` flag).
1362/// Returns 0 for an unknown user id.
1363pub fn user_authority_tier(conn: &Connection, user_id: &str) -> Result<i32, String> {
1364    let is_owner: Option<i32> = conn
1365        .query_row(
1366            "SELECT is_owner FROM users WHERE id = ?1",
1367            rusqlite::params![user_id],
1368            |r| r.get(0),
1369        )
1370        .optional()
1371        .map_err(|e| e.to_string())?;
1372    let Some(owner_flag) = is_owner else {
1373        return Ok(0);
1374    };
1375    let (mu, mc, _) = get_user_capabilities(conn, user_id)?;
1376    Ok(authority_tier(owner_flag != 0, mu, mc))
1377}
1378
1379/// Ensures the vault has exactly one owner row and returns its id.
1380///
1381/// The owner is whoever can derive the SQLCipher key from the master password.
1382/// Before this existed the server represented them with the magic string
1383/// `"owner"`, which meant they appeared in no user list, carried no class, and
1384/// could not be named in an audit row.
1385///
1386/// The row is deliberately created with **`password_hash = NULL`**. Storing a
1387/// hash of the master password here would put an offline oracle for the vault
1388/// key back into the database — the exact hole removed from the desktop
1389/// `unlock_vault`. Proof of ownership stays "your password opened the
1390/// database"; `verify_user_password` refuses a NULL hash, so this row can never
1391/// be logged into via `/api/auth`.
1392pub fn ensure_owner_user(conn: &Connection) -> Result<String, String> {
1393    if let Some(id) = conn
1394        .query_row("SELECT id FROM users WHERE is_owner = 1 LIMIT 1", [], |r| {
1395            r.get::<_, String>(0)
1396        })
1397        .optional()
1398        .map_err(|e| e.to_string())?
1399    {
1400        return Ok(id);
1401    }
1402
1403    // `username` is UNIQUE, so fall back if a normal user already took "owner".
1404    let taken: bool = conn
1405        .query_row("SELECT 1 FROM users WHERE username = 'owner'", [], |r| {
1406            r.get::<_, i32>(0)
1407        })
1408        .optional()
1409        .map_err(|e| e.to_string())?
1410        .is_some();
1411    let id = new_uuid();
1412    let username = if taken {
1413        format!("owner-{}", &id[..8])
1414    } else {
1415        "owner".to_string()
1416    };
1417
1418    conn.execute(
1419        "INSERT INTO users (id, username, password_hash, is_owner, created_at) \
1420         VALUES (?1, ?2, NULL, 1, ?3)",
1421        rusqlite::params![id, username, iso_now()],
1422    )
1423    .map_err(|e| e.to_string())?;
1424    Ok(id)
1425}
1426
1427/// Outcome of [`seed_default_admin`].
1428pub enum AdminSeed {
1429    /// An `admin` user already existed — nothing was created.
1430    Exists,
1431    /// A new `admin` user (assigned the built-in `cls-admin` class) was created.
1432    /// `generated_password` is `Some` only when no env password was supplied and a
1433    /// random one was generated — the caller must surface it once.
1434    Created { generated_password: Option<String> },
1435}
1436
1437/// Idempotently seeds a default `admin` user assigned to the built-in `cls-admin`
1438/// class. Never hardcodes a credential: uses `env_password` when present, otherwise
1439/// generates a 128-bit random password the caller is responsible for displaying once.
1440pub fn seed_default_admin(
1441    conn: &Connection,
1442    env_password: Option<&str>,
1443) -> Result<AdminSeed, String> {
1444    // Seeded once. Every owner unlock used to create an `admin` whenever none was named
1445    // "admin", so an admin the owner had deleted or renamed came back on the next unlock,
1446    // with a known password when UNV_ADMIN_PASSWORD is set. The marker records that the
1447    // decision was made; an install that already has other users and no admin is treated
1448    // as having made it (the admin was removed on purpose).
1449    let marker = |conn: &Connection| -> Result<(), String> {
1450        conn.execute(
1451            "INSERT OR REPLACE INTO vault_meta (key, value) VALUES ('default_admin_seeded', '1')",
1452            [],
1453        )
1454        .map(|_| ())
1455        .map_err(|e| e.to_string())
1456    };
1457    let already: Option<String> = conn
1458        .query_row(
1459            "SELECT value FROM vault_meta WHERE key = 'default_admin_seeded'",
1460            [],
1461            |r| r.get(0),
1462        )
1463        .optional()
1464        .map_err(|e| e.to_string())?;
1465    if already.is_some() {
1466        return Ok(AdminSeed::Exists);
1467    }
1468    let exists: Option<String> = conn
1469        .query_row("SELECT id FROM users WHERE username = 'admin'", [], |r| {
1470            r.get(0)
1471        })
1472        .optional()
1473        .map_err(|e| e.to_string())?;
1474    let others: i64 = conn
1475        .query_row("SELECT COUNT(*) FROM users WHERE is_owner = 0", [], |r| {
1476            r.get(0)
1477        })
1478        .map_err(|e| e.to_string())?;
1479    if exists.is_some() || others > 0 {
1480        marker(conn)?;
1481        return Ok(AdminSeed::Exists);
1482    }
1483
1484    let (password, generated) = match env_password {
1485        Some(p) if !p.is_empty() => (p.to_string(), None),
1486        _ => {
1487            let mut raw = [0u8; 16];
1488            rand::rng().fill_bytes(&mut raw);
1489            let pw = hex::encode(raw);
1490            (pw.clone(), Some(pw))
1491        }
1492    };
1493
1494    let user = create_user(conn, "admin", Some(&password), false)?;
1495    assign_user_class(conn, &user.id, Some("cls-admin"))?;
1496    marker(conn)?;
1497    Ok(AdminSeed::Created {
1498        generated_password: generated,
1499    })
1500}
1501
1502/// Gives a LAN share someone to sign in as. Peers authenticate as named users, never with the
1503/// master password, so a vault with no such user would be advertised and unreachable (the
1504/// desktop used to refuse to start and send the owner off to the Users panel). Returns the
1505/// credentials of the account it created, to be shown once, or `None` when one already exists.
1506pub fn ensure_peer_account(conn: &Connection) -> Result<Option<(String, String)>, String> {
1507    if list_users(conn)?
1508        .iter()
1509        .any(|u| u.has_password && !u.is_owner)
1510    {
1511        return Ok(None);
1512    }
1513    let mut raw = [0u8; 12];
1514    rand::rng().fill_bytes(&mut raw);
1515    let password = hex::encode(raw);
1516    let taken: Vec<String> = list_users(conn)?.into_iter().map(|u| u.username).collect();
1517    let username = std::iter::once("guest".to_string())
1518        .chain((2..).map(|n| format!("guest{n}")))
1519        .find(|n| !taken.contains(n))
1520        .expect("an unbounded range has a free name");
1521    let user = create_user(conn, &username, Some(&password), false)?;
1522    assign_user_class(conn, &user.id, Some("cls-admin"))?;
1523    Ok(Some((username, password)))
1524}
1525
1526// ── Token management ──────────────────────────────────────────────────────────
1527
1528/// Creates a token for `user_id`.
1529/// Returns `(token_id, plaintext_token)` — the plaintext is shown **once**.
1530pub fn create_user_token(
1531    conn: &Connection,
1532    user_id: &str,
1533    description: Option<&str>,
1534    expires_at: Option<&str>,
1535) -> Result<(String, String), String> {
1536    let token_id = new_uuid();
1537    let mut raw = [0u8; 32];
1538    rand::rng().fill_bytes(&mut raw);
1539    let plaintext = hex::encode(raw);
1540    let token_hash = sha256_hex(&plaintext);
1541    conn.execute(
1542        "INSERT INTO user_tokens (id, token_hash, user_id, description, created_at, expires_at) \
1543         VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
1544        rusqlite::params![
1545            token_id,
1546            token_hash,
1547            user_id,
1548            description,
1549            iso_now(),
1550            expires_at
1551        ],
1552    )
1553    .map_err(|e| e.to_string())?;
1554    Ok((token_id, plaintext))
1555}
1556
1557/// Revokes a token by its UUID.
1558pub fn revoke_user_token(conn: &Connection, token_id: &str) -> Result<(), String> {
1559    conn.execute(
1560        "DELETE FROM user_tokens WHERE id = ?1",
1561        rusqlite::params![token_id],
1562    )
1563    .map(|_| ())
1564    .map_err(|e| e.to_string())
1565}
1566
1567/// Lists all tokens for a user (no hashes).
1568pub fn list_user_tokens(conn: &Connection, user_id: &str) -> Result<Vec<TokenRecord>, String> {
1569    let mut stmt = conn
1570        .prepare(
1571            "SELECT id, user_id, description, created_at, expires_at \
1572         FROM user_tokens WHERE user_id = ?1 ORDER BY created_at",
1573        )
1574        .map_err(|e| e.to_string())?;
1575    let rows: Vec<Result<TokenRecord, _>> = stmt
1576        .query_map(rusqlite::params![user_id], |r| {
1577            Ok(TokenRecord {
1578                id: r.get(0)?,
1579                user_id: r.get(1)?,
1580                description: r.get(2)?,
1581                created_at: r.get(3)?,
1582                expires_at: r.get(4)?,
1583            })
1584        })
1585        .map_err(|e| e.to_string())?
1586        .collect();
1587    rows.into_iter()
1588        .map(|r| r.map_err(|e| e.to_string()))
1589        .collect()
1590}
1591
1592// ── Permission management ─────────────────────────────────────────────────────
1593
1594/// Returns all permissions for a user.
1595pub fn get_user_permissions(
1596    conn: &Connection,
1597    user_id: &str,
1598) -> Result<Vec<PermissionRecord>, String> {
1599    let mut stmt = conn
1600        .prepare(
1601            "SELECT user_id, scope_type, scope_value, permission \
1602         FROM user_permissions WHERE user_id = ?1 \
1603         ORDER BY scope_type, scope_value",
1604        )
1605        .map_err(|e| e.to_string())?;
1606    let rows: Vec<Result<PermissionRecord, _>> = stmt
1607        .query_map(rusqlite::params![user_id], |r| {
1608            Ok(PermissionRecord {
1609                user_id: r.get(0)?,
1610                scope_type: r.get(1)?,
1611                scope_value: r.get(2)?,
1612                permission: r.get(3)?,
1613            })
1614        })
1615        .map_err(|e| e.to_string())?
1616        .collect();
1617    rows.into_iter()
1618        .map(|r| r.map_err(|e| e.to_string()))
1619        .collect()
1620}
1621
1622/// Atomically replaces all permissions for a user.
1623pub fn set_user_permissions(
1624    conn: &Connection,
1625    user_id: &str,
1626    permissions: &[PermissionRecord],
1627) -> Result<(), String> {
1628    conn.execute(
1629        "DELETE FROM user_permissions WHERE user_id = ?1",
1630        rusqlite::params![user_id],
1631    )
1632    .map_err(|e| e.to_string())?;
1633    for p in permissions {
1634        conn.execute(
1635            "INSERT INTO user_permissions (user_id, scope_type, scope_value, permission) \
1636             VALUES (?1, ?2, ?3, ?4)",
1637            rusqlite::params![user_id, p.scope_type, p.scope_value, p.permission],
1638        )
1639        .map_err(|e| e.to_string())?;
1640    }
1641    Ok(())
1642}
1643
1644// ── Vault filtering ───────────────────────────────────────────────────────────
1645
1646/// Standard wildcard matching: `*` = any sequence, `?` = one char.
1647pub fn glob_matches(pattern: &str, value: &str) -> bool {
1648    let (pb, vb) = (pattern.as_bytes(), value.as_bytes());
1649    let (mut pi, mut vi) = (0usize, 0usize);
1650    let (mut star_pi, mut star_vi) = (usize::MAX, 0usize);
1651    while vi < vb.len() {
1652        if pi < pb.len() && pb[pi] == b'*' {
1653            star_pi = pi;
1654            star_vi = vi;
1655            pi += 1;
1656        } else if pi < pb.len() && (pb[pi] == vb[vi] || pb[pi] == b'?') {
1657            pi += 1;
1658            vi += 1;
1659        } else if star_pi != usize::MAX {
1660            pi = star_pi + 1;
1661            star_vi += 1;
1662            vi = star_vi;
1663        } else {
1664            return false;
1665        }
1666    }
1667    while pi < pb.len() && pb[pi] == b'*' {
1668        pi += 1;
1669    }
1670    pi == pb.len()
1671}
1672
1673fn build_project_names(vault: &serde_json::Value) -> HashMap<String, String> {
1674    vault
1675        .get("projects")
1676        .and_then(|v| v.as_array())
1677        .map(|arr| {
1678            arr.iter()
1679                .filter_map(|p| {
1680                    Some((
1681                        p.get("id")?.as_str()?.to_string(),
1682                        p.get("name")?.as_str()?.to_string(),
1683                    ))
1684                })
1685                .collect()
1686        })
1687        .unwrap_or_default()
1688}
1689
1690/// Returns a filtered copy of `vault` containing only entries readable under `read`.
1691/// Also trims the `projects` and `user_categories` lists to what the visible
1692/// entries actually reference, so the taxonomy itself does not leak.
1693///
1694/// `read = None` means no grant at all and yields an empty vault.
1695pub fn filter_vault_for_user(
1696    vault: serde_json::Value,
1697    read: Option<&crate::permex::Expr>,
1698) -> serde_json::Value {
1699    let Some(expr) = read else {
1700        return serde_json::json!({ "api_keys": [], "user_categories": [], "projects": [] });
1701    };
1702
1703    let project_names = build_project_names(&vault);
1704    let empty = vec![];
1705    let api_keys = vault
1706        .get("api_keys")
1707        .and_then(|v| v.as_array())
1708        .unwrap_or(&empty);
1709
1710    let mut visible: Vec<serde_json::Value> = api_keys
1711        .iter()
1712        .filter(|e| {
1713            crate::permex::eval(
1714                expr,
1715                &crate::permex::EntryView::from_entry(e, &project_names),
1716            )
1717        })
1718        .cloned()
1719        .collect();
1720
1721    // A visible member must not disclose that its parent bundle exists when the
1722    // user cannot read that bundle. Present it as standalone; writes below
1723    // restore this association unless the user has explicit bundle access and
1724    // requests a membership change.
1725    let visible_bundle_ids: HashSet<String> = visible
1726        .iter()
1727        .filter(|entry| {
1728            entry.get("secretType").and_then(serde_json::Value::as_str) == Some("bundle")
1729        })
1730        .filter_map(|entry| {
1731            entry
1732                .get("id")
1733                .and_then(serde_json::Value::as_str)
1734                .map(str::to_owned)
1735        })
1736        .collect();
1737    for entry in &mut visible {
1738        let Some(bundle_id) = entry.get("bundle_id").and_then(serde_json::Value::as_str) else {
1739            continue;
1740        };
1741        if !visible_bundle_ids.contains(bundle_id) {
1742            if let Some(object) = entry.as_object_mut() {
1743                object.remove("bundle_id");
1744                object.remove("bundle_slot");
1745                object.remove("bundle_order");
1746            }
1747        }
1748    }
1749
1750    let visible_pids: HashSet<String> = visible
1751        .iter()
1752        .flat_map(|e| {
1753            e.get("projectIds")
1754                .and_then(|v| v.as_array())
1755                .unwrap_or(&empty)
1756                .iter()
1757                .filter_map(|v| v.as_str().map(|s| s.to_string()))
1758        })
1759        .collect();
1760
1761    let projects = vault
1762        .get("projects")
1763        .and_then(|v| v.as_array())
1764        .unwrap_or(&empty);
1765    let visible_projects: Vec<serde_json::Value> = projects
1766        .iter()
1767        .filter(|p| {
1768            p.get("id")
1769                .and_then(|v| v.as_str())
1770                .is_some_and(|id| id == "Universal" || visible_pids.contains(id))
1771        })
1772        .cloned()
1773        .collect();
1774
1775    // Don't leak the full category taxonomy: expose only category tags that a
1776    // visible entry actually carries (plus their slash-hierarchy parents so the
1777    // sidebar tree still renders).
1778    let visible_cats: HashSet<String> = visible
1779        .iter()
1780        .flat_map(|e| {
1781            e.get("categories")
1782                .and_then(|v| v.as_array())
1783                .unwrap_or(&empty)
1784                .iter()
1785                .filter_map(|v| v.as_str())
1786        })
1787        .flat_map(|c| {
1788            // "Cloud/AWS/Prod" -> ["Cloud", "Cloud/AWS", "Cloud/AWS/Prod"]
1789            let parts: Vec<&str> = c.split('/').collect();
1790            (1..=parts.len()).map(move |n| parts[..n].join("/"))
1791        })
1792        .collect();
1793    let user_categories: Vec<serde_json::Value> = vault
1794        .get("user_categories")
1795        .and_then(|v| v.as_array())
1796        .unwrap_or(&empty)
1797        .iter()
1798        .filter(|c| c.as_str().is_some_and(|s| visible_cats.contains(s)))
1799        .cloned()
1800        .collect();
1801
1802    serde_json::json!({
1803        "api_keys":        visible,
1804        "user_categories": user_categories,
1805        "projects":        visible_projects,
1806    })
1807}
1808
1809/// Is every entry currently referencing `pid` writable by this user?
1810///
1811/// The same ALL-scope rule entry writes already use: a container is writable
1812/// only when the user could write everything it holds. Anything weaker lets a
1813/// user with one entry in a shared project rename or delete the project for
1814/// everybody.
1815///
1816/// A project nothing references is vacuously writable, which is correct — it is
1817/// also invisible, so the caller only reaches this for one the user was served.
1818fn project_write_allowed(
1819    pid: &str,
1820    full_keys: &[serde_json::Value],
1821    writable: &dyn Fn(&serde_json::Value) -> bool,
1822) -> bool {
1823    full_keys
1824        .iter()
1825        .filter(|e| {
1826            e.get("projectIds")
1827                .and_then(|v| v.as_array())
1828                .is_some_and(|a| a.iter().any(|v| v.as_str() == Some(pid)))
1829        })
1830        .all(writable)
1831}
1832
1833/// The category equivalent of [`project_write_allowed`].
1834fn category_write_allowed(
1835    cat: &str,
1836    full_keys: &[serde_json::Value],
1837    writable: &dyn Fn(&serde_json::Value) -> bool,
1838) -> bool {
1839    full_keys
1840        .iter()
1841        .filter(|e| {
1842            e.get("categories")
1843                .and_then(|v| v.as_array())
1844                .is_some_and(|a| a.iter().any(|v| v.as_str() == Some(cat)))
1845        })
1846        .all(writable)
1847}
1848
1849/// Merges one collection of named, string-keyed objects (`projects`) or plain
1850/// strings (`user_categories`) from a sub-user's submission.
1851///
1852/// The submission is a *filtered* view, so "absent" is ambiguous: it means
1853/// either "deleted" or "you were never shown it". `served` — recomputed here
1854/// from the read expression, which is exactly what the client was handed —
1855/// resolves it. Anything outside `served` is preserved untouched; anything
1856/// inside it is honoured, subject to `allowed`.
1857fn merge_named_collection(
1858    full: &[serde_json::Value],
1859    submitted: &[serde_json::Value],
1860    served: &HashSet<String>,
1861    key_of: &dyn Fn(&serde_json::Value) -> Option<String>,
1862    allowed: &dyn Fn(&str) -> bool,
1863    what: &str,
1864) -> Result<Vec<serde_json::Value>, String> {
1865    let sub_map: HashMap<String, &serde_json::Value> = submitted
1866        .iter()
1867        .filter_map(|v| key_of(v).map(|k| (k, v)))
1868        .collect();
1869
1870    let mut out: Vec<serde_json::Value> = Vec::new();
1871    for item in full {
1872        let Some(k) = key_of(item) else {
1873            out.push(item.clone());
1874            continue;
1875        };
1876        if !served.contains(&k) {
1877            // The client never saw it, so it cannot have meant to change it.
1878            out.push(item.clone());
1879            continue;
1880        }
1881        match sub_map.get(&k) {
1882            Some(&sub) if sub == item => out.push(item.clone()),
1883            Some(&sub) => {
1884                if !allowed(&k) {
1885                    return Err(format!("Write permission denied for {what} '{k}'"));
1886                }
1887                out.push(sub.clone());
1888            }
1889            None => {
1890                if !allowed(&k) {
1891                    return Err(format!("Delete permission denied for {what} '{k}'"));
1892                }
1893                // omitted from a view that contained it → deleted
1894            }
1895        }
1896    }
1897
1898    // Genuinely new ones. A submitted key that exists in `full` but was not
1899    // served is deliberately *not* treated as new: it would overwrite something
1900    // the user was never allowed to see.
1901    let full_keys: HashSet<String> = full.iter().filter_map(key_of).collect();
1902    for item in submitted {
1903        if let Some(k) = key_of(item) {
1904            if !full_keys.contains(&k) {
1905                out.push(item.clone());
1906            }
1907        }
1908    }
1909    Ok(out)
1910}
1911
1912/// Merges a user's submitted vault data into the full vault, respecting write permissions.
1913///
1914/// - Entries the user submitted within their write scope → applied (add / update).
1915/// - Entries in the user's write scope that are absent from the submission → deleted.
1916/// - Entries outside the user's write scope → unchanged from `full_vault`.
1917/// - `projects` and `user_categories` are merged the same way, against what the
1918///   read expression would have served, with container writability defined as
1919///   "every entry inside it is writable".
1920///
1921/// Returns `Err` if the user's submission contains an entry outside their write
1922/// scope, or changes a project or category they may not change.
1923///
1924/// **`projects` and `user_categories` used to be dropped silently.** The merge
1925/// rebuilt `api_keys` only and took both collections from `full_vault`, and the
1926/// server answered `204 No Content`. A sub-user creating a project, renaming a
1927/// category, editing a WireGuard peer or adding a chunk got a success toast and
1928/// a UI that showed the change — because the frontend had already applied it to
1929/// its own copy — while the server persisted nothing. It surfaced on the next
1930/// reload, attributable to nothing.
1931pub fn merge_user_vault_write(
1932    full_vault: serde_json::Value,
1933    user_data: serde_json::Value,
1934    read: Option<&crate::permex::Expr>,
1935    write: Option<&crate::permex::Expr>,
1936) -> Result<serde_json::Value, String> {
1937    let project_names = build_project_names(&full_vault);
1938    let Some(write_expr) = write else {
1939        return Err("No write permissions".to_string());
1940    };
1941    let writable = |e: &serde_json::Value| {
1942        crate::permex::eval(
1943            write_expr,
1944            &crate::permex::EntryView::from_entry(e, &project_names),
1945        )
1946    };
1947
1948    let empty = vec![];
1949    let full_keys = full_vault
1950        .get("api_keys")
1951        .and_then(|v| v.as_array())
1952        .unwrap_or(&empty);
1953    let user_keys = user_data
1954        .get("api_keys")
1955        .and_then(|v| v.as_array())
1956        .unwrap_or(&empty);
1957    let readable = |entry: &serde_json::Value| {
1958        read.is_some_and(|expr| {
1959            crate::permex::eval(
1960                expr,
1961                &crate::permex::EntryView::from_entry(entry, &project_names),
1962            )
1963        })
1964    };
1965    let find_bundle = |id: &str| {
1966        full_keys.iter().chain(user_keys.iter()).find(|candidate| {
1967            candidate.get("id").and_then(serde_json::Value::as_str) == Some(id)
1968                && candidate
1969                    .get("secretType")
1970                    .and_then(serde_json::Value::as_str)
1971                    == Some("bundle")
1972        })
1973    };
1974
1975    // Identity comes from the shared `crate::entry_ck` so this merge and
1976    // `save_vault` can never disagree about what "the same entry" means. A
1977    // mismatch here would let a write-scoped entry alias one in an out-of-scope
1978    // project (overwrite/delete bypass).
1979    use crate::entry_ck;
1980
1981    // Validate: every submitted entry must satisfy the write expression.
1982    for entry in user_keys {
1983        let id = entry_ck(entry);
1984        let prior = full_keys.iter().find(|old| entry_ck(old) == id);
1985        // An entry the user can read but not write, sent back exactly as it was served, is
1986        // not a write. Checking every submitted entry refused a faithful save of the user's
1987        // own, untouched view.
1988        let unchanged = prior.is_some_and(|old| old == entry) && readable(entry);
1989        if !writable(entry) && !unchanged {
1990            return Err(format!(
1991                "Write permission denied for '{}'",
1992                entry
1993                    .get("provider")
1994                    .and_then(|v| v.as_str())
1995                    .unwrap_or("?")
1996            ));
1997        }
1998        let old_bundle = prior
1999            .and_then(|old| old.get("bundle_id"))
2000            .and_then(serde_json::Value::as_str);
2001        let new_bundle = entry.get("bundle_id").and_then(serde_json::Value::as_str);
2002        let hidden_parent_was_omitted = old_bundle
2003            .and_then(find_bundle)
2004            .is_some_and(|bundle| !readable(bundle))
2005            && entry.get("bundle_id").is_none();
2006        let effective_new_bundle = if hidden_parent_was_omitted {
2007            old_bundle
2008        } else {
2009            new_bundle
2010        };
2011        let old_slot = prior.and_then(|old| old.get("bundle_slot"));
2012        let new_slot = entry.get("bundle_slot");
2013        let old_order = prior.and_then(|old| old.get("bundle_order"));
2014        let new_order = entry.get("bundle_order");
2015        let association_unchanged =
2016            hidden_parent_was_omitted && new_slot.is_none() && new_order.is_none()
2017                || old_slot == new_slot && old_order == new_order;
2018        if old_bundle != effective_new_bundle || !association_unchanged {
2019            for bundle_id in [old_bundle, effective_new_bundle].into_iter().flatten() {
2020                let bundle = find_bundle(bundle_id);
2021                // A stale membership can be removed without permission on a
2022                // bundle that no longer exists.
2023                if bundle.is_none() && Some(bundle_id) == old_bundle {
2024                    continue;
2025                }
2026                if !bundle.is_some_and(writable) {
2027                    return Err(format!(
2028                        "Write permission denied for bundle membership in '{bundle_id}'"
2029                    ));
2030                }
2031            }
2032        }
2033    }
2034
2035    let user_map: HashMap<String, &serde_json::Value> =
2036        user_keys.iter().map(|e| (entry_ck(e), e)).collect();
2037
2038    let user_writable_cks: HashSet<String> = full_keys
2039        .iter()
2040        .filter(|e| writable(e))
2041        .map(entry_ck)
2042        .collect();
2043
2044    let full_cks: HashSet<String> = full_keys.iter().map(entry_ck).collect();
2045
2046    let mut result: Vec<serde_json::Value> = Vec::new();
2047
2048    // Keep current entries; apply user's changes to writable ones
2049    for entry in full_keys {
2050        let ck = entry_ck(entry);
2051        if user_writable_cks.contains(&ck) {
2052            if let Some(&user_entry) = user_map.get(&ck) {
2053                let hidden_parent_was_omitted = entry
2054                    .get("bundle_id")
2055                    .and_then(serde_json::Value::as_str)
2056                    .and_then(find_bundle)
2057                    .is_some_and(|bundle| !readable(bundle))
2058                    && user_entry.get("bundle_id").is_none();
2059                if hidden_parent_was_omitted {
2060                    let mut merged = user_entry.clone();
2061                    for key in ["bundle_id", "bundle_slot", "bundle_order"] {
2062                        if let Some(value) = entry.get(key) {
2063                            merged[key] = value.clone();
2064                        }
2065                    }
2066                    result.push(merged);
2067                } else {
2068                    result.push(user_entry.clone());
2069                }
2070            }
2071            // else: user deleted it — omit
2072        } else {
2073            result.push(entry.clone());
2074        }
2075    }
2076
2077    // Append genuinely new entries from user's submission
2078    for entry in user_keys {
2079        if !full_cks.contains(&entry_ck(entry)) {
2080            result.push(entry.clone());
2081        }
2082    }
2083
2084    // ── projects and user_categories ──────────────────────────────────────────
2085    //
2086    // Recompute what a GET would have handed this user. That is the only way to
2087    // read the submission correctly: it is a filtered document, so an absent
2088    // project means "deleted" when the user could see it and "never shown"
2089    // otherwise, and the two must not be confused.
2090    let served = filter_vault_for_user(full_vault.clone(), read);
2091    let served_projects: HashSet<String> = served
2092        .get("projects")
2093        .and_then(|v| v.as_array())
2094        .unwrap_or(&empty)
2095        .iter()
2096        .filter_map(|p| p.get("id").and_then(|v| v.as_str()).map(str::to_string))
2097        .collect();
2098    let served_cats: HashSet<String> = served
2099        .get("user_categories")
2100        .and_then(|v| v.as_array())
2101        .unwrap_or(&empty)
2102        .iter()
2103        .filter_map(|c| c.as_str().map(str::to_string))
2104        .collect();
2105
2106    // An *absent* key is not an empty one. A caller that PUTs only `api_keys` —
2107    // which the server's payload validation permits, and which any hand-rolled
2108    // agent client will do — means "I am not touching the taxonomy", not "delete
2109    // every project I can see". Only a key that is present is merged.
2110    let full_projects = full_vault
2111        .get("projects")
2112        .and_then(|v| v.as_array())
2113        .cloned()
2114        .unwrap_or_default();
2115    let merged_projects = match user_data.get("projects").and_then(|v| v.as_array()) {
2116        None => full_projects.clone(),
2117        Some(user_projects) => merge_named_collection(
2118            &full_projects,
2119            user_projects,
2120            &served_projects,
2121            &|p| p.get("id").and_then(|v| v.as_str()).map(str::to_string),
2122            // `Universal` is every user's shared default: "all its entries are mine" is
2123            // true by accident (a vault where only this user has entries), and renaming
2124            // or deleting it would break the next user's view.
2125            &|pid| pid != "Universal" && project_write_allowed(pid, full_keys, &writable),
2126            "project",
2127        )?,
2128    };
2129
2130    let full_cats = full_vault
2131        .get("user_categories")
2132        .and_then(|v| v.as_array())
2133        .cloned()
2134        .unwrap_or_default();
2135    let merged_cats = match user_data.get("user_categories").and_then(|v| v.as_array()) {
2136        None => full_cats.clone(),
2137        Some(user_cats) => merge_named_collection(
2138            &full_cats,
2139            user_cats,
2140            &served_cats,
2141            &|c| c.as_str().map(str::to_string),
2142            &|cat| category_write_allowed(cat, full_keys, &writable),
2143            "category",
2144        )?,
2145    };
2146
2147    let mut out = full_vault.clone();
2148    if let Some(obj) = out.as_object_mut() {
2149        obj.insert("api_keys".to_string(), serde_json::Value::Array(result));
2150        obj.insert(
2151            "projects".to_string(),
2152            serde_json::Value::Array(merged_projects),
2153        );
2154        obj.insert(
2155            "user_categories".to_string(),
2156            serde_json::Value::Array(merged_cats),
2157        );
2158    }
2159    Ok(out)
2160}
2161
2162// ── Tests ─────────────────────────────────────────────────────────────────────
2163
2164#[cfg(test)]
2165mod tests {
2166    use super::*;
2167    use serde_json::json;
2168
2169    // ── Glob matching ─────────────────────────────────────────────────────────
2170
2171    #[test]
2172    fn peer_account_is_created_once_and_can_sign_in() {
2173        let conn = scratch_conn("peer-account");
2174        let (name, pw) = ensure_peer_account(&conn)
2175            .unwrap()
2176            .expect("first call creates");
2177        assert_eq!(name, "guest");
2178        assert!(verify_user_password(&conn, &name, &pw).unwrap().is_some());
2179        // Bug it replaces: a second call (or any existing password user) must not add another.
2180        assert!(ensure_peer_account(&conn).unwrap().is_none());
2181    }
2182
2183    #[test]
2184    fn glob_exact_and_wildcards() {
2185        assert!(glob_matches("*", "anything"));
2186        assert!(glob_matches("*", ""));
2187        assert!(glob_matches("Cloud/AWS", "Cloud/AWS"));
2188        assert!(!glob_matches("Cloud/AWS", "Cloud/GCP"));
2189        assert!(glob_matches("wg0-*", "wg0-office"));
2190        assert!(!glob_matches("wg0-*", "wg1-office"));
2191        assert!(glob_matches("*-prod", "app-prod"));
2192        assert!(glob_matches("a?c", "abc"));
2193        assert!(!glob_matches("a?c", "ac"));
2194        assert!(glob_matches("a*b*c", "axxbyyc"));
2195    }
2196
2197    #[test]
2198    fn glob_does_not_match_prefix_by_accident() {
2199        // "Cloud" must not grant access to "CloudSecrets".
2200        assert!(!glob_matches("Cloud", "CloudSecrets"));
2201        assert!(glob_matches("Cloud*", "CloudSecrets"));
2202    }
2203
2204    // ── Password hashing ──────────────────────────────────────────────────────
2205
2206    #[test]
2207    fn argon2_hash_roundtrips_and_rejects_wrong_password() {
2208        let stored = hash_password("correct horse");
2209        assert!(
2210            stored.starts_with("$argon2id$"),
2211            "must emit PHC format, got {stored}"
2212        );
2213        assert!(verify_password_hash("correct horse", &stored));
2214        assert!(!verify_password_hash("wrong horse", &stored));
2215    }
2216
2217    #[test]
2218    fn hashes_are_salted_per_call() {
2219        assert_ne!(
2220            hash_password("same"),
2221            hash_password("same"),
2222            "identical passwords must not produce identical hashes"
2223        );
2224    }
2225
2226    #[test]
2227    fn legacy_sha256_hashes_still_verify() {
2228        // Phase 5.0 format: "<salt_hex>:<sha256(salt||password)_hex>"
2229        let salt = [0xABu8; 16];
2230        let mut h = Sha256::new();
2231        h.update(salt);
2232        h.update(b"legacy-pass");
2233        let legacy = format!("{}:{}", hex::encode(salt), hex::encode(h.finalize()));
2234        assert!(verify_password_hash("legacy-pass", &legacy));
2235        assert!(!verify_password_hash("nope", &legacy));
2236    }
2237
2238    #[test]
2239    fn malformed_hashes_are_rejected_not_accepted() {
2240        assert!(!verify_password_hash("x", ""));
2241        assert!(!verify_password_hash("x", "garbage"));
2242        assert!(!verify_password_hash("x", "$argon2id$broken"));
2243        assert!(!verify_password_hash("x", "nothex:alsonothex"));
2244    }
2245
2246    // ── Authority hierarchy ───────────────────────────────────────────────────
2247
2248    #[test]
2249    fn authority_tiers_are_ordered() {
2250        let owner = authority_tier(true, false, false);
2251        let admin = authority_tier(false, true, true);
2252        let moder = authority_tier(false, true, false);
2253        let user = authority_tier(false, false, false);
2254        assert!(
2255            owner > admin && admin > moder && moder > user,
2256            "owner {owner} > admin {admin} > moderator {moder} > user {user}"
2257        );
2258    }
2259
2260    // ── Write scoping ─────────────────────────────────────────────────────────
2261    //
2262    // Predicate-level semantics (wildcards, Universal, globs) are covered by the
2263    // permex tests. What matters here is that the merge honours the expression.
2264
2265    fn ex(src: &str) -> crate::permex::Expr {
2266        crate::permex::parse(src).unwrap()
2267    }
2268
2269    // ── Owner row ─────────────────────────────────────────────────────────────
2270
2271    fn scratch_conn(tag: &str) -> Connection {
2272        // A counter beside the process id, not the clock: two tests starting within one clock tick
2273        // (macOS has a coarse one) shared a directory and failed with "database is locked".
2274        let nanos = {
2275            use std::sync::atomic::{AtomicU64, Ordering};
2276            static SEQ: AtomicU64 = AtomicU64::new(0);
2277            format!(
2278                "{}-{}",
2279                std::process::id(),
2280                SEQ.fetch_add(1, Ordering::SeqCst)
2281            )
2282        };
2283        let dir = std::env::temp_dir().join(format!("unenverse-users-{tag}-{nanos}"));
2284        std::fs::create_dir_all(&dir).unwrap();
2285        let key = crate::derive_key("pw", b"0123456789abcdef").unwrap();
2286        let conn = crate::open_db(&dir.join("vault.db"), &key).unwrap();
2287        crate::init_schema(&conn).unwrap();
2288        conn
2289    }
2290
2291    #[test]
2292    fn owner_row_is_created_once_and_is_idempotent() {
2293        let conn = scratch_conn("owner");
2294        let a = ensure_owner_user(&conn).unwrap();
2295        let b = ensure_owner_user(&conn).unwrap();
2296        assert_eq!(a, b, "must not create a second owner");
2297        let owners: i32 = conn
2298            .query_row("SELECT COUNT(*) FROM users WHERE is_owner = 1", [], |r| {
2299                r.get(0)
2300            })
2301            .unwrap();
2302        assert_eq!(owners, 1);
2303    }
2304
2305    #[test]
2306    fn owner_row_has_no_password_and_cannot_be_logged_into() {
2307        let conn = scratch_conn("owner-nopw");
2308        ensure_owner_user(&conn).unwrap();
2309        // Storing a hash of the master password here would be an offline oracle
2310        // for the vault key, so the row must never have one.
2311        let hash: Option<String> = conn
2312            .query_row(
2313                "SELECT password_hash FROM users WHERE is_owner = 1",
2314                [],
2315                |r| r.get(0),
2316            )
2317            .unwrap();
2318        assert!(hash.is_none(), "owner row must have a NULL password_hash");
2319        assert!(verify_user_password(&conn, "owner", "anything")
2320            .unwrap()
2321            .is_none());
2322        assert!(verify_user_password(&conn, "owner", "").unwrap().is_none());
2323    }
2324
2325    #[test]
2326    fn passwordless_user_is_a_credential_failure_not_an_error() {
2327        // 500-vs-401 used to leak which usernames existed, unthrottled, because
2328        // only the Ok(None) path incremented the rate limiter.
2329        let conn = scratch_conn("nopw");
2330        create_user(&conn, "tokenonly", None, false).unwrap();
2331        let existing = verify_user_password(&conn, "tokenonly", "guess");
2332        let missing = verify_user_password(&conn, "ghost", "guess");
2333        assert!(existing.is_ok() && existing.unwrap().is_none());
2334        assert!(missing.is_ok() && missing.unwrap().is_none());
2335    }
2336
2337    /// Unknown and password-less usernames cost one Argon2 run, like a wrong
2338    /// password for a real user; before, they returned at once and the response
2339    /// time revealed which usernames exist.
2340    #[test]
2341    fn unknown_and_passwordless_usernames_pay_for_an_argon2_run() {
2342        let conn = scratch_conn("dummyverify");
2343        create_user(&conn, "tokenonly", None, false).unwrap();
2344        create_user(&conn, "real", Some("pw-real"), false).unwrap();
2345        let ran = || DUMMY_VERIFIES.with(|c| c.get());
2346
2347        let before = ran();
2348        assert!(verify_user_password(&conn, "ghost", "x").unwrap().is_none());
2349        assert_eq!(
2350            ran(),
2351            before + 1,
2352            "unknown username skipped the dummy verify"
2353        );
2354
2355        let before = ran();
2356        assert!(verify_user_password(&conn, "tokenonly", "x")
2357            .unwrap()
2358            .is_none());
2359        assert_eq!(
2360            ran(),
2361            before + 1,
2362            "password-less user skipped the dummy verify"
2363        );
2364
2365        // Control: a real user is verified against its own hash, not the dummy.
2366        let before = ran();
2367        assert!(verify_user_password(&conn, "real", "wrong")
2368            .unwrap()
2369            .is_none());
2370        assert!(
2371            verify_user_password(&conn, "real", "pw-real")
2372                .unwrap()
2373                .is_some(),
2374            "the real user still logs in"
2375        );
2376        assert_eq!(ran(), before, "a real user must not trigger the dummy path");
2377    }
2378
2379    /// Measurement, not a gate (wall-clock asserts are flaky): mean time for an
2380    /// unknown versus a known username over 50 attempts each.
2381    /// `cargo test -p vault-core --release unknown_username_timing -- --ignored --nocapture`
2382    #[test]
2383    #[ignore]
2384    fn unknown_username_timing() {
2385        let conn = scratch_conn("timing");
2386        create_user(&conn, "real", Some("pw-real"), false).unwrap();
2387        let mean = |name: &str| {
2388            let t = std::time::Instant::now();
2389            for _ in 0..50 {
2390                let _ = verify_user_password(&conn, name, "wrong-guess");
2391            }
2392            t.elapsed().as_secs_f64() * 1000.0 / 50.0
2393        };
2394        let (known, unknown) = (mean("real"), mean("ghost"));
2395        println!(
2396            "known {known:.1} ms, unknown {unknown:.1} ms, ratio {:.3}",
2397            unknown / known
2398        );
2399        assert!((unknown / known - 1.0).abs() < 0.10, "outside 10%");
2400    }
2401
2402    #[test]
2403    fn owner_username_collision_falls_back() {
2404        let conn = scratch_conn("collide");
2405        create_user(&conn, "owner", Some("pw"), false).unwrap();
2406        let id = ensure_owner_user(&conn).unwrap();
2407        let uname: String = conn
2408            .query_row(
2409                "SELECT username FROM users WHERE id = ?1",
2410                rusqlite::params![id],
2411                |r| r.get(0),
2412            )
2413            .unwrap();
2414        assert_ne!(
2415            uname, "owner",
2416            "must not collide with the existing UNIQUE username"
2417        );
2418        assert!(uname.starts_with("owner-"));
2419    }
2420
2421    #[test]
2422    fn owner_outranks_every_class() {
2423        let conn = scratch_conn("tier");
2424        let id = ensure_owner_user(&conn).unwrap();
2425        assert_eq!(user_authority_tier(&conn, &id).unwrap(), 3);
2426    }
2427
2428    // ── Permission expressions ────────────────────────────────────────────────
2429
2430    #[test]
2431    fn legacy_rows_are_migrated_into_expressions() {
2432        let conn = scratch_conn("permmig");
2433        let u = create_user(&conn, "u1", Some("pw"), false).unwrap();
2434        set_user_permissions(
2435            &conn,
2436            &u.id,
2437            &[
2438                PermissionRecord {
2439                    user_id: u.id.clone(),
2440                    scope_type: "project".into(),
2441                    scope_value: "Alpha".into(),
2442                    permission: "write".into(),
2443                },
2444                PermissionRecord {
2445                    user_id: u.id.clone(),
2446                    scope_type: "category".into(),
2447                    scope_value: "dev".into(),
2448                    permission: "read".into(),
2449                },
2450            ],
2451        )
2452        .unwrap();
2453        // Re-run the migration as a fresh database would.
2454        conn.execute(
2455            "DELETE FROM vault_meta WHERE key = 'perm_expr_migrated'",
2456            [],
2457        )
2458        .unwrap();
2459        migrate_rows_to_expressions(&conn).unwrap();
2460
2461        let read = get_permission_expr(&conn, "user", &u.id, "read")
2462            .unwrap()
2463            .unwrap();
2464        let write = get_permission_expr(&conn, "user", &u.id, "write")
2465            .unwrap()
2466            .unwrap();
2467        assert!(
2468            read.contains("project:Alpha") && read.contains("category:dev"),
2469            "read should be the OR of every row, got {read}"
2470        );
2471        assert!(
2472            write.contains("project:Alpha") && !write.contains("category:dev"),
2473            "write should only include write rows, got {write}"
2474        );
2475    }
2476
2477    #[test]
2478    fn migration_runs_once_only() {
2479        let conn = scratch_conn("permmig-once");
2480        let u = create_user(&conn, "u1", Some("pw"), false).unwrap();
2481        set_permission_expr(&conn, "user", &u.id, "read", "tag:mine").unwrap();
2482        set_user_permissions(
2483            &conn,
2484            &u.id,
2485            &[PermissionRecord {
2486                user_id: u.id.clone(),
2487                scope_type: "vault".into(),
2488                scope_value: "*".into(),
2489                permission: "write".into(),
2490            }],
2491        )
2492        .unwrap();
2493        migrate_rows_to_expressions(&conn).unwrap();
2494        // Already migrated at schema init, so the legacy rows must not clobber
2495        // an expression an admin has since written.
2496        assert_eq!(
2497            get_permission_expr(&conn, "user", &u.id, "read")
2498                .unwrap()
2499                .unwrap(),
2500            "tag:mine"
2501        );
2502    }
2503
2504    #[test]
2505    fn built_in_classes_get_expressions_on_a_fresh_vault() {
2506        // The seeded class rows must be compiled, or Admin/Viewer would silently
2507        // grant nothing at all.
2508        let conn = scratch_conn("permmig-seed");
2509        let admin = get_permission_expr(&conn, "class", "cls-admin", "write").unwrap();
2510        let viewer_read = get_permission_expr(&conn, "class", "cls-viewer", "read").unwrap();
2511        assert_eq!(admin.as_deref(), Some("vault:*"));
2512        assert_eq!(viewer_read.as_deref(), Some("vault:*"));
2513        assert!(
2514            get_permission_expr(&conn, "class", "cls-viewer", "write")
2515                .unwrap()
2516                .is_none(),
2517            "Viewer is read-only"
2518        );
2519    }
2520
2521    #[test]
2522    fn invalid_expressions_are_rejected_on_save() {
2523        let conn = scratch_conn("permbad");
2524        let u = create_user(&conn, "u1", Some("pw"), false).unwrap();
2525        assert!(set_permission_expr(&conn, "user", &u.id, "read", "project:a AND").is_err());
2526        assert!(set_permission_expr(&conn, "user", &u.id, "read", "bogus:a").is_err());
2527        assert!(
2528            get_permission_expr(&conn, "user", &u.id, "read")
2529                .unwrap()
2530                .is_none(),
2531            "a rejected expression must not be stored"
2532        );
2533    }
2534
2535    #[test]
2536    fn blank_expression_clears_the_rule() {
2537        let conn = scratch_conn("permclear");
2538        let u = create_user(&conn, "u1", Some("pw"), false).unwrap();
2539        set_permission_expr(&conn, "user", &u.id, "read", "tag:x").unwrap();
2540        set_permission_expr(&conn, "user", &u.id, "read", "   ").unwrap();
2541        assert!(get_permission_expr(&conn, "user", &u.id, "read")
2542            .unwrap()
2543            .is_none());
2544    }
2545
2546    #[test]
2547    fn effective_read_includes_write_because_write_implies_read() {
2548        let conn = scratch_conn("permeff");
2549        let u = create_user(&conn, "u1", Some("pw"), false).unwrap();
2550        set_permission_expr(&conn, "user", &u.id, "write", "project:Alpha").unwrap();
2551        let read = effective_permission_expr(&conn, &u.id, "read")
2552            .unwrap()
2553            .expect("write should imply read");
2554        assert!(read.to_string().contains("project:Alpha"));
2555    }
2556
2557    #[test]
2558    fn effective_expr_ands_class_with_individual() {
2559        let conn = scratch_conn("permand");
2560        let u = create_user(&conn, "u1", Some("pw"), false).unwrap();
2561        let cls = create_user_class(&conn, "Contractor", "", false, false, false).unwrap();
2562        assign_user_class(&conn, &u.id, Some(&cls.id)).unwrap();
2563        set_permission_expr(&conn, "class", &cls.id, "read", "NOT category:secret").unwrap();
2564        set_permission_expr(&conn, "user", &u.id, "read", "vault:*").unwrap();
2565
2566        let expr = effective_permission_expr(&conn, &u.id, "read")
2567            .unwrap()
2568            .unwrap();
2569        let pn: HashMap<String, String> = HashMap::new();
2570        let secret =
2571            json!({ "provider": "S", "categories": ["secret"], "projectIds": ["Universal"] });
2572        let plain =
2573            json!({ "provider": "P", "categories": ["dev"],    "projectIds": ["Universal"] });
2574        assert!(
2575            !crate::permex::eval(&expr, &crate::permex::EntryView::from_entry(&secret, &pn)),
2576            "the class exclusion must survive the individual grant"
2577        );
2578        assert!(crate::permex::eval(
2579            &expr,
2580            &crate::permex::EntryView::from_entry(&plain, &pn)
2581        ));
2582    }
2583
2584    #[test]
2585    fn a_user_with_no_rules_gets_nothing() {
2586        let conn = scratch_conn("permnone");
2587        let u = create_user(&conn, "u1", Some("pw"), false).unwrap();
2588        assert!(effective_permission_expr(&conn, &u.id, "read")
2589            .unwrap()
2590            .is_none());
2591        assert!(effective_permission_expr(&conn, &u.id, "write")
2592            .unwrap()
2593            .is_none());
2594    }
2595
2596    // ── Vault filtering ───────────────────────────────────────────────────────
2597
2598    fn sample_vault() -> serde_json::Value {
2599        json!({
2600            "api_keys": [
2601                { "id": "1", "provider": "Mine",   "categories": ["dev"],  "projectIds": ["Universal", "p1"] },
2602                { "id": "2", "provider": "Theirs", "categories": ["ops"],  "projectIds": ["Universal", "p2"] },
2603            ],
2604            "user_categories": ["dev", "ops", "secret/taxonomy"],
2605            "projects": [
2606                { "id": "Universal", "name": "Universal" },
2607                { "id": "p1", "name": "Alpha" },
2608                { "id": "p2", "name": "Beta" },
2609            ],
2610        })
2611    }
2612
2613    #[test]
2614    fn vault_scope_sees_everything_untouched() {
2615        let out = filter_vault_for_user(sample_vault(), Some(&ex("vault:*")));
2616        assert_eq!(out["api_keys"].as_array().unwrap().len(), 2);
2617    }
2618
2619    #[test]
2620    fn project_scope_hides_other_projects() {
2621        let out = filter_vault_for_user(sample_vault(), Some(&ex("project:Alpha")));
2622        let keys = out["api_keys"].as_array().unwrap();
2623        assert_eq!(keys.len(), 1);
2624        assert_eq!(keys[0]["provider"], "Mine");
2625    }
2626
2627    #[test]
2628    fn a_visible_bundle_member_does_not_reveal_an_unreadable_parent() {
2629        let mut full = sample_vault();
2630        full["api_keys"][0]["bundle_id"] = json!("private-bundle");
2631        full["api_keys"][0]["bundle_slot"] = json!("member");
2632        full["api_keys"][0]["bundle_order"] = json!(10);
2633        full["api_keys"].as_array_mut().unwrap().push(json!({
2634            "id": "private-bundle", "provider": "Private", "secretType": "bundle",
2635            "projectIds": ["Universal", "p2"]
2636        }));
2637
2638        let out = filter_vault_for_user(full, Some(&ex("project:Alpha")));
2639        let member = out["api_keys"]
2640            .as_array()
2641            .unwrap()
2642            .iter()
2643            .find(|entry| entry["id"] == "1")
2644            .unwrap();
2645        assert!(member.get("bundle_id").is_none());
2646        assert!(member.get("bundle_slot").is_none());
2647        assert!(member.get("bundle_order").is_none());
2648        assert!(!out["api_keys"]
2649            .as_array()
2650            .unwrap()
2651            .iter()
2652            .any(|e| e["id"] == "private-bundle"));
2653    }
2654
2655    #[test]
2656    fn filtering_does_not_leak_the_category_taxonomy() {
2657        let out = filter_vault_for_user(sample_vault(), Some(&ex("project:Alpha")));
2658        let cats: Vec<&str> = out["user_categories"]
2659            .as_array()
2660            .unwrap()
2661            .iter()
2662            .filter_map(|c| c.as_str())
2663            .collect();
2664        assert!(
2665            cats.contains(&"dev"),
2666            "categories on visible entries are kept"
2667        );
2668        assert!(
2669            !cats.contains(&"ops"),
2670            "categories only on hidden entries must not leak"
2671        );
2672        assert!(
2673            !cats.contains(&"secret/taxonomy"),
2674            "unused category names must not leak"
2675        );
2676    }
2677
2678    // ── Write merge ───────────────────────────────────────────────────────────
2679
2680    /// BUG: the write check ran on every submitted entry, so a faithful save of the user's
2681    /// own served view was refused whenever it held an entry they could read but not write.
2682    #[test]
2683    fn merge_accepts_an_unchanged_entry_the_user_can_only_read() {
2684        let full = sample_vault();
2685        let submitted = json!({ "api_keys": [
2686            { "id": "1", "provider": "Mine",   "categories": ["dev"],  "projectIds": ["Universal", "p1"] },
2687            { "id": "2", "provider": "Theirs", "categories": ["ops"],  "projectIds": ["Universal", "p2"] },
2688        ]});
2689        merge_user_vault_write(
2690            full,
2691            submitted,
2692            Some(&ex("vault:*")),
2693            Some(&ex("project:Alpha")),
2694        )
2695        .expect("an untouched read-only entry is not a write");
2696    }
2697
2698    /// The same entry, when the user could not even read it, is still refused: the check
2699    /// is "unchanged and visible to them", not "unchanged".
2700    #[test]
2701    fn merge_refuses_an_unchanged_entry_the_user_cannot_read() {
2702        let full = sample_vault();
2703        let submitted = json!({ "api_keys": [
2704            { "id": "2", "provider": "Theirs", "categories": ["ops"],  "projectIds": ["Universal", "p2"] },
2705        ]});
2706        merge_user_vault_write(
2707            full,
2708            submitted,
2709            Some(&ex("project:Alpha")),
2710            Some(&ex("project:Alpha")),
2711        )
2712        .expect_err("a hidden entry cannot be submitted");
2713    }
2714
2715    #[test]
2716    fn merge_rejects_submission_outside_write_scope() {
2717        let full = sample_vault();
2718        let submitted = json!({ "api_keys": [
2719            { "id": "2", "provider": "Theirs", "categories": ["ops", "changed-by-the-user"], "projectIds": ["Universal", "p2"] }
2720        ]});
2721        let err = merge_user_vault_write(
2722            full,
2723            submitted,
2724            Some(&ex("vault:*")),
2725            Some(&ex("project:Alpha")),
2726        )
2727        .expect_err("writing an out-of-scope entry must be refused");
2728        assert!(
2729            err.contains("Theirs"),
2730            "error should name the offending entry, got: {err}"
2731        );
2732    }
2733
2734    #[test]
2735    fn changing_bundle_membership_requires_write_access_to_both_entries() {
2736        let mut full = sample_vault();
2737        full["api_keys"].as_array_mut().unwrap().push(json!({
2738            "id": "bundle", "provider": "Restricted bundle", "secretType": "bundle",
2739            "projectIds": ["Universal", "p2"]
2740        }));
2741        let submitted = json!({ "api_keys": [
2742            { "id": "1", "provider": "Mine", "categories": ["dev"],
2743              "projectIds": ["Universal", "p1"], "bundle_id": "bundle" }
2744        ]});
2745        let err = merge_user_vault_write(
2746            full,
2747            submitted,
2748            Some(&ex("vault:*")),
2749            Some(&ex("project:Alpha")),
2750        )
2751        .expect_err("member write alone must not expose it through a restricted bundle");
2752        assert!(err.contains("bundle membership"), "unexpected error: {err}");
2753    }
2754
2755    #[test]
2756    fn unrelated_writes_preserve_membership_in_an_unreadable_bundle() {
2757        let mut full = sample_vault();
2758        full["api_keys"][0]["bundle_id"] = json!("private-bundle");
2759        full["api_keys"][0]["bundle_slot"] = json!("member");
2760        full["api_keys"][0]["bundle_order"] = json!(10);
2761        full["api_keys"].as_array_mut().unwrap().push(json!({
2762            "id": "private-bundle", "provider": "Private", "secretType": "bundle",
2763            "projectIds": ["Universal", "p2"]
2764        }));
2765        let read = ex("project:Alpha");
2766        let write = ex("project:Alpha");
2767        let mut submitted = filter_vault_for_user(full.clone(), Some(&read));
2768        submitted["api_keys"][0]["api_key"] = json!("updated");
2769
2770        let merged = merge_user_vault_write(full, submitted, Some(&read), Some(&write)).unwrap();
2771        let member = merged["api_keys"]
2772            .as_array()
2773            .unwrap()
2774            .iter()
2775            .find(|entry| entry["id"] == "1")
2776            .unwrap();
2777        assert_eq!(member["api_key"], "updated");
2778        assert_eq!(member["bundle_id"], "private-bundle");
2779        assert_eq!(member["bundle_slot"], "member");
2780        assert_eq!(member["bundle_order"], 10);
2781    }
2782
2783    #[test]
2784    fn merge_requires_some_write_permission() {
2785        let err = merge_user_vault_write(
2786            sample_vault(),
2787            json!({ "api_keys": [] }),
2788            Some(&ex("vault:*")),
2789            None,
2790        )
2791        .expect_err("read-only users must not be able to write at all");
2792        assert_eq!(err, "No write permissions");
2793    }
2794
2795    /// Write coverage for entry "Mine" — under ANY-match the project grant alone
2796    /// is sufficient, since the entry belongs to project Alpha.
2797
2798    #[test]
2799    fn merge_applies_in_scope_edits_and_preserves_the_rest() {
2800        let submitted = json!({ "api_keys": [
2801            { "id": "1", "provider": "Mine", "api_key": "updated",
2802              "categories": ["dev"], "projectIds": ["Universal", "p1"] }
2803        ]});
2804        let out = merge_user_vault_write(
2805            sample_vault(),
2806            submitted,
2807            Some(&ex("vault:*")),
2808            Some(&ex("project:Alpha")),
2809        )
2810        .unwrap();
2811        let keys = out["api_keys"].as_array().unwrap();
2812        assert_eq!(keys.len(), 2, "the out-of-scope entry must survive");
2813        let mine = keys.iter().find(|e| e["id"] == "1").unwrap();
2814        assert_eq!(mine["api_key"], "updated");
2815        assert!(
2816            keys.iter().any(|e| e["id"] == "2"),
2817            "Theirs must be untouched"
2818        );
2819    }
2820
2821    #[test]
2822    fn merge_deletes_in_scope_entries_omitted_from_the_submission() {
2823        let out = merge_user_vault_write(
2824            sample_vault(),
2825            json!({ "api_keys": [] }),
2826            Some(&ex("vault:*")),
2827            Some(&ex("project:Alpha")),
2828        )
2829        .unwrap();
2830        let keys = out["api_keys"].as_array().unwrap();
2831        assert_eq!(keys.len(), 1, "the in-scope entry is deleted");
2832        assert_eq!(keys[0]["id"], "2", "the out-of-scope entry is not");
2833    }
2834
2835    // ── projects and categories (regression: they used to vanish) ─────────────
2836    //
2837    // `merge_user_vault_write` rebuilt `api_keys` only and took `projects` and
2838    // `user_categories` straight from `full_vault`. The server then answered
2839    // 204. A sub-user creating a project or editing a chunk saw the change (the
2840    // frontend applies it to its own copy first) and the server kept nothing.
2841
2842    /// A read+write grant over Alpha, which is what a project-scoped sub-user has.
2843    fn alpha() -> (crate::permex::Expr, crate::permex::Expr) {
2844        (ex("project:Alpha"), ex("project:Alpha"))
2845    }
2846
2847    #[test]
2848    fn a_new_project_from_a_sub_user_is_persisted() {
2849        let (r, w) = alpha();
2850        let served = filter_vault_for_user(sample_vault(), Some(&r));
2851        let mut submitted = served.clone();
2852        submitted["projects"].as_array_mut().unwrap().push(json!({
2853            "id": "p9", "name": "Fresh", "project_type": "generic", "chunks": []
2854        }));
2855        let out = merge_user_vault_write(sample_vault(), submitted, Some(&r), Some(&w)).unwrap();
2856        let ids: Vec<&str> = out["projects"]
2857            .as_array()
2858            .unwrap()
2859            .iter()
2860            .filter_map(|p| p["id"].as_str())
2861            .collect();
2862        assert!(ids.contains(&"p9"), "the new project must survive: {ids:?}");
2863        assert!(ids.contains(&"p2"), "Beta, which they cannot see, must too");
2864    }
2865
2866    #[test]
2867    fn editing_a_project_they_fully_own_is_persisted() {
2868        // Alpha is referenced only by entry "Mine", which this user can write,
2869        // so the whole project is theirs to change — chunks included.
2870        let (r, w) = alpha();
2871        let mut submitted = filter_vault_for_user(sample_vault(), Some(&r));
2872        for p in submitted["projects"].as_array_mut().unwrap() {
2873            if p["id"] == "p1" {
2874                p["chunks"] = json!([{ "id": "c1", "name": "peer", "chunk_type": "wg_peer",
2875                                       "fields": [] }]);
2876            }
2877        }
2878        let out = merge_user_vault_write(sample_vault(), submitted, Some(&r), Some(&w)).unwrap();
2879        let alpha_out = out["projects"]
2880            .as_array()
2881            .unwrap()
2882            .iter()
2883            .find(|p| p["id"] == "p1")
2884            .unwrap();
2885        assert_eq!(
2886            alpha_out["chunks"][0]["name"], "peer",
2887            "the chunk the user added must be stored, not silently dropped"
2888        );
2889    }
2890
2891    #[test]
2892    fn a_project_they_do_not_fully_own_is_refused_not_silently_ignored() {
2893        // Universal is referenced by both entries, one of which is out of scope.
2894        // Under the same ALL-scope rule entry writes use, it is not theirs.
2895        let (r, w) = alpha();
2896        let mut submitted = filter_vault_for_user(sample_vault(), Some(&r));
2897        for p in submitted["projects"].as_array_mut().unwrap() {
2898            if p["id"] == "Universal" {
2899                p["name"] = json!("Hijacked");
2900            }
2901        }
2902        let err = merge_user_vault_write(sample_vault(), submitted, Some(&r), Some(&w))
2903            .expect_err("must refuse rather than accept-and-discard");
2904        assert!(err.contains("Universal"), "must name the refusal: {err}");
2905    }
2906
2907    // R12: when every entry in Universal happened to be the user's own, "all its
2908    // entries are writable" held vacuously and a sub-user could delete or rename the
2909    // shared default project.
2910    #[test]
2911    fn the_shared_universal_project_is_not_a_sub_users_to_delete_or_rename() {
2912        let mut vault = sample_vault();
2913        vault["api_keys"].as_array_mut().unwrap().remove(1); // only "Mine" is left in it
2914        let (r, w) = alpha();
2915        let mut gone = filter_vault_for_user(vault.clone(), Some(&r));
2916        gone["projects"]
2917            .as_array_mut()
2918            .unwrap()
2919            .retain(|p| p["id"] != "Universal");
2920        let err = merge_user_vault_write(vault.clone(), gone, Some(&r), Some(&w)).unwrap_err();
2921        assert!(err.contains("Universal"), "{err}");
2922        let mut renamed = filter_vault_for_user(vault.clone(), Some(&r));
2923        for p in renamed["projects"].as_array_mut().unwrap() {
2924            if p["id"] == "Universal" {
2925                p["name"] = json!("Mine now");
2926            }
2927        }
2928        assert!(merge_user_vault_write(vault, renamed, Some(&r), Some(&w)).is_err());
2929    }
2930
2931    #[test]
2932    fn a_project_the_user_cannot_see_survives_a_full_submission() {
2933        // The submission is a filtered document. Beta's absence from it means
2934        // "never shown", not "deleted" — confusing the two deletes other
2935        // people's projects on every sub-user save.
2936        let (r, w) = alpha();
2937        let submitted = filter_vault_for_user(sample_vault(), Some(&r));
2938        assert!(
2939            !submitted["projects"]
2940                .as_array()
2941                .unwrap()
2942                .iter()
2943                .any(|p| p["id"] == "p2"),
2944            "fixture precondition: Beta is not served to this user"
2945        );
2946        let out = merge_user_vault_write(sample_vault(), submitted, Some(&r), Some(&w)).unwrap();
2947        assert!(
2948            out["projects"]
2949                .as_array()
2950                .unwrap()
2951                .iter()
2952                .any(|p| p["id"] == "p2"),
2953            "Beta must survive"
2954        );
2955    }
2956
2957    #[test]
2958    fn a_hidden_category_is_neither_deleted_nor_overwritable() {
2959        let (r, w) = alpha();
2960        let mut submitted = filter_vault_for_user(sample_vault(), Some(&r));
2961        submitted["user_categories"]
2962            .as_array_mut()
2963            .unwrap()
2964            .push(json!("newcat"));
2965        let out = merge_user_vault_write(sample_vault(), submitted, Some(&r), Some(&w)).unwrap();
2966        let cats: Vec<&str> = out["user_categories"]
2967            .as_array()
2968            .unwrap()
2969            .iter()
2970            .filter_map(|c| c.as_str())
2971            .collect();
2972        assert!(cats.contains(&"newcat"), "the added category persists");
2973        assert!(
2974            cats.contains(&"secret/taxonomy"),
2975            "a category never served must not be pruned away: {cats:?}"
2976        );
2977        assert!(cats.contains(&"ops"), "nor one belonging to hidden entries");
2978    }
2979
2980    #[test]
2981    fn omitting_the_collections_entirely_changes_nothing() {
2982        // A hand-rolled agent client PUTs only `api_keys`. Absent must mean
2983        // "unchanged", never "empty" — otherwise one such call wipes the
2984        // taxonomy for everybody.
2985        let (r, w) = alpha();
2986        let out = merge_user_vault_write(
2987            sample_vault(),
2988            json!({ "api_keys": [
2989                { "id": "1", "provider": "Mine", "categories": ["dev"],
2990                  "projectIds": ["Universal", "p1"] }
2991            ]}),
2992            Some(&r),
2993            Some(&w),
2994        )
2995        .unwrap();
2996        assert_eq!(out["projects"].as_array().unwrap().len(), 3);
2997        assert_eq!(out["user_categories"].as_array().unwrap().len(), 3);
2998    }
2999
3000    #[test]
3001    fn a_sub_user_cannot_overwrite_a_project_by_guessing_its_id() {
3002        // p2 exists but was never served. Submitting it as if it were new must
3003        // not clobber it — that would be a read-scope bypass through the write
3004        // path.
3005        let (r, w) = alpha();
3006        let mut submitted = filter_vault_for_user(sample_vault(), Some(&r));
3007        submitted["projects"]
3008            .as_array_mut()
3009            .unwrap()
3010            .push(json!({ "id": "p2", "name": "Stolen" }));
3011        let out = merge_user_vault_write(sample_vault(), submitted, Some(&r), Some(&w)).unwrap();
3012        let betas: Vec<&serde_json::Value> = out["projects"]
3013            .as_array()
3014            .unwrap()
3015            .iter()
3016            .filter(|p| p["id"] == "p2")
3017            .collect();
3018        assert_eq!(betas.len(), 1, "must not duplicate it either");
3019        assert_eq!(betas[0]["name"], "Beta", "the real Beta is untouched");
3020    }
3021
3022    #[test]
3023    fn merge_cannot_alias_an_out_of_scope_entry_via_key_id() {
3024        // Identity includes key_id. If it did not, a writable entry could be
3025        // crafted to collide with an out-of-scope one and overwrite it.
3026        let full = json!({ "api_keys": [
3027            { "provider": "AWS", "account_name": "acct", "key_id": "locked",
3028              "api_key": "secret", "categories": ["ops"], "projectIds": ["Universal", "p2"] },
3029            { "provider": "AWS", "account_name": "acct", "key_id": "mine",
3030              "api_key": "ok",     "categories": ["dev"], "projectIds": ["Universal", "p1"] },
3031        ],
3032        "projects": [{ "id": "p1", "name": "Alpha" }, { "id": "p2", "name": "Beta" }]});
3033
3034        let submitted = json!({ "api_keys": [
3035            { "provider": "AWS", "account_name": "acct", "key_id": "mine",
3036              "api_key": "changed", "categories": ["dev"], "projectIds": ["Universal", "p1"] }
3037        ]});
3038        let out = merge_user_vault_write(
3039            full,
3040            submitted,
3041            Some(&ex("vault:*")),
3042            Some(&ex("project:Alpha")),
3043        )
3044        .unwrap();
3045        let keys = out["api_keys"].as_array().unwrap();
3046        let locked = keys.iter().find(|e| e["key_id"] == "locked").unwrap();
3047        assert_eq!(
3048            locked["api_key"], "secret",
3049            "the out-of-scope key must be untouched"
3050        );
3051    }
3052}
3053
3054#[cfg(test)]
3055mod strict_write_tests {
3056    use super::*;
3057    use crate::permex;
3058
3059    fn db() -> Connection {
3060        let c = Connection::open_in_memory().unwrap();
3061        // The user schema's expression migration writes a marker into
3062        // `vault_meta`, which the vault schema owns — so the vault schema comes
3063        // first here, exactly as it does in `unlock_vault`.
3064        crate::init_schema(&c).unwrap();
3065        init_users_schema(&c).unwrap();
3066        c
3067    }
3068
3069    /// The transform is the feature: an OR chain becomes an AND chain.
3070    #[test]
3071    fn require_all_turns_any_scope_into_every_scope() {
3072        let e = permex::parse("project:web OR project:api OR project:db").unwrap();
3073        let strict = permex::require_all(e);
3074        assert_eq!(
3075            strict.to_string(),
3076            "((project:web AND project:api) AND project:db)"
3077        );
3078    }
3079
3080    /// Explicit grouping an author wrote is left alone.
3081    ///
3082    /// `(a OR b) AND c` is a rule someone stated precisely. Rewriting its inner
3083    /// alternation would change a decision that was already made, and strictness
3084    /// is about the implicit OR that scope-joining introduced.
3085    #[test]
3086    fn require_all_does_not_rewrite_nested_groups() {
3087        let e = permex::parse("(project:web OR project:api) AND env:prod").unwrap();
3088        let before = e.to_string();
3089        assert_eq!(permex::require_all(e).to_string(), before);
3090    }
3091
3092    /// Strict mode narrows writes and leaves reads alone.
3093    ///
3094    /// Regression test for the tempting mistake: strictifying reads too. A user
3095    /// who cannot see an entry cannot review the change they are making, and
3096    /// their vault would appear empty the moment the flag went on.
3097    #[test]
3098    fn strict_mode_narrows_writes_only() {
3099        let c = db();
3100        let uid = create_user(&c, "alice", Some("password-1234"), false)
3101            .unwrap()
3102            .id;
3103        set_permission_expr(&c, "user", &uid, "write", "project:web OR project:api").unwrap();
3104
3105        let lax = effective_permission_expr(&c, &uid, "write")
3106            .unwrap()
3107            .unwrap();
3108        assert_eq!(lax.to_string(), "(project:web OR project:api)");
3109
3110        set_strict_write(&c, "user", &uid, true).unwrap();
3111        let strict = effective_permission_expr(&c, &uid, "write")
3112            .unwrap()
3113            .unwrap();
3114        assert_eq!(strict.to_string(), "(project:web AND project:api)");
3115
3116        // Read still sees either, via "write implies read".
3117        let read = effective_permission_expr(&c, &uid, "read")
3118            .unwrap()
3119            .unwrap();
3120        assert_eq!(read.to_string(), "(project:web OR project:api)");
3121    }
3122
3123    /// A class can impose strictness its members cannot shed.
3124    #[test]
3125    fn a_strict_class_makes_its_members_strict() {
3126        let c = db();
3127        let cid = create_user_class(&c, "Deployers", "", false, false, false)
3128            .unwrap()
3129            .id;
3130        let uid = create_user(&c, "bob", Some("password-1234"), false)
3131            .unwrap()
3132            .id;
3133        assign_user_class(&c, &uid, Some(&cid)).unwrap();
3134        set_permission_expr(&c, "user", &uid, "write", "project:web OR project:api").unwrap();
3135
3136        assert!(!strict_write_for(&c, &uid).unwrap());
3137        set_strict_write(&c, "class", &cid, true).unwrap();
3138        assert!(
3139            strict_write_for(&c, &uid).unwrap(),
3140            "a strict class must bind its members, or the class is not a boundary"
3141        );
3142    }
3143
3144    /// Existing users are untouched by the migration.
3145    ///
3146    /// A release that silently tightened permissions would break running
3147    /// deployments in a way nobody could attribute to the upgrade.
3148    #[test]
3149    fn strict_is_off_by_default() {
3150        let c = db();
3151        let uid = create_user(&c, "carol", Some("password-1234"), false)
3152            .unwrap()
3153            .id;
3154        assert!(!strict_write_for(&c, &uid).unwrap());
3155    }
3156
3157    /// Setting the flag on something that does not exist is an error, not a
3158    /// silent no-op that leaves an operator believing they hardened an account.
3159    #[test]
3160    fn setting_strict_on_a_missing_subject_fails() {
3161        let c = db();
3162        assert!(set_strict_write(&c, "user", "no-such-id", true).is_err());
3163        assert!(set_strict_write(&c, "banana", "x", true).is_err());
3164    }
3165}
3166
3167#[cfg(test)]
3168mod totp_user_tests {
3169    use super::*;
3170    use crate::totp;
3171
3172    fn db() -> Connection {
3173        let c = Connection::open_in_memory().unwrap();
3174        crate::init_schema(&c).unwrap();
3175        init_users_schema(&c).unwrap();
3176        c
3177    }
3178
3179    fn a_user(c: &Connection) -> String {
3180        create_user(c, "alice", Some("hunter2hunter2"), false)
3181            .unwrap()
3182            .id
3183    }
3184
3185    #[test]
3186    fn enrollment_does_not_enable_the_factor() {
3187        // Enabling on enrollment locks out anyone whose authenticator did not
3188        // actually take the manually-typed secret — with no QR code, that is a
3189        // routine outcome, not an edge case.
3190        let c = db();
3191        let id = a_user(&c);
3192        let st = totp_enroll(&c, &id, "UnENVerse").unwrap();
3193        assert!(st.enrolled && !st.enabled);
3194        assert!(st.secret.is_some() && st.uri.is_some());
3195        assert!(!totp_required(&c, &id).unwrap());
3196        // And a login code is refused while it is unconfirmed.
3197        let code = totp::totp_at(st.secret.as_ref().unwrap(), totp::now_unix()).unwrap();
3198        assert!(!verify_user_totp(&c, &id, &code).unwrap());
3199    }
3200
3201    #[test]
3202    fn confirming_enables_it_and_burns_the_confirming_code() {
3203        let c = db();
3204        let id = a_user(&c);
3205        let secret = totp_enroll(&c, &id, "UnENVerse").unwrap().secret.unwrap();
3206        let code = totp::totp_at(&secret, totp::now_unix()).unwrap();
3207
3208        assert!(totp_confirm(&c, &id, &code).unwrap());
3209        assert!(totp_required(&c, &id).unwrap());
3210        assert!(list_users(&c).unwrap().iter().any(|u| u.totp_enabled));
3211        // The code that enabled the factor must not then log the user in.
3212        assert!(!verify_user_totp(&c, &id, &code).unwrap());
3213    }
3214
3215    #[test]
3216    fn a_login_code_cannot_be_used_twice() {
3217        // The replay window without this is ninety seconds wide, which for a
3218        // second factor is the attack it exists to stop.
3219        let c = db();
3220        let id = a_user(&c);
3221        let secret = totp_enroll(&c, &id, "UnENVerse").unwrap().secret.unwrap();
3222        // Confirm with a code from the previous step so the current one is still
3223        // usable for the login this test is about.
3224        let prev = totp::totp_at(&secret, totp::now_unix() - totp::STEP_SECS).unwrap();
3225        assert!(totp_confirm(&c, &id, &prev).unwrap());
3226
3227        let code = totp::totp_at(&secret, totp::now_unix()).unwrap();
3228        assert!(verify_user_totp(&c, &id, &code).unwrap());
3229        assert!(!verify_user_totp(&c, &id, &code).unwrap());
3230    }
3231
3232    #[test]
3233    fn confirm_obeys_the_anti_replay_mark_and_never_moves_it_backwards() {
3234        // Found by an end-to-end run, not by the unit tests: `confirm` passed
3235        // `None` for the last accepted step, so the confirming code worked a
3236        // second time — and re-confirming with a code from an *earlier* step
3237        // wrote that lower step back, re-opening every step in between for
3238        // replay on the login path.
3239        let c = db();
3240        let id = a_user(&c);
3241        let secret = totp_enroll(&c, &id, "UnENVerse").unwrap().secret.unwrap();
3242        let now = totp::now_unix();
3243
3244        let code = totp::totp_at(&secret, now).unwrap();
3245        assert!(totp_confirm(&c, &id, &code).unwrap());
3246        assert!(
3247            !totp_confirm(&c, &id, &code).unwrap(),
3248            "the confirming code must not be accepted twice"
3249        );
3250
3251        let mark = || -> i64 {
3252            c.query_row(
3253                "SELECT totp_last_step FROM users WHERE id = ?1",
3254                rusqlite::params![id],
3255                |r| r.get(0),
3256            )
3257            .unwrap()
3258        };
3259        let after_confirm = mark();
3260        // An older code, still inside the skew window, must not be accepted and
3261        // must not drag the high-water mark back with it.
3262        let older = totp::totp_at(&secret, now - totp::STEP_SECS).unwrap();
3263        assert!(!totp_confirm(&c, &id, &older).unwrap());
3264        assert_eq!(mark(), after_confirm, "the mark moved backwards");
3265    }
3266
3267    #[test]
3268    fn an_enabled_factor_with_no_secret_fails_closed() {
3269        // This precise inversion is in the bug history: the Phase 5.1 code
3270        // returned Ok(true) for a NULL secret, making "enabled but unconfigured"
3271        // indistinguishable from "authenticated".
3272        let c = db();
3273        let id = a_user(&c);
3274        c.execute(
3275            "UPDATE users SET totp_enabled = 1, totp_secret = NULL WHERE id = ?1",
3276            rusqlite::params![id],
3277        )
3278        .unwrap();
3279        assert!(!verify_user_totp(&c, &id, "123456").unwrap());
3280        assert!(!verify_user_totp(&c, &id, "").unwrap());
3281    }
3282
3283    #[test]
3284    fn status_never_hands_the_secret_back() {
3285        // Otherwise every read of the user list is a way to clone the factor.
3286        let c = db();
3287        let id = a_user(&c);
3288        totp_enroll(&c, &id, "UnENVerse").unwrap();
3289        let st = totp_status(&c, &id).unwrap();
3290        assert!(st.enrolled && !st.enabled);
3291        assert!(st.secret.is_none() && st.uri.is_none());
3292    }
3293
3294    #[test]
3295    fn disabling_destroys_the_secret_rather_than_only_the_flag() {
3296        let c = db();
3297        let id = a_user(&c);
3298        let secret = totp_enroll(&c, &id, "UnENVerse").unwrap().secret.unwrap();
3299        let code = totp::totp_at(&secret, totp::now_unix()).unwrap();
3300        totp_confirm(&c, &id, &code).unwrap();
3301
3302        totp_disable(&c, &id).unwrap();
3303        let st = totp_status(&c, &id).unwrap();
3304        assert!(!st.enrolled, "a leftover secret could be silently re-armed");
3305        assert!(!st.enabled);
3306    }
3307
3308    #[test]
3309    fn re_enrolling_switches_the_factor_back_off() {
3310        // A half-finished re-enrollment must not leave the account demanding a
3311        // code that only the abandoned secret can produce.
3312        let c = db();
3313        let id = a_user(&c);
3314        let first = totp_enroll(&c, &id, "UnENVerse").unwrap().secret.unwrap();
3315        let code = totp::totp_at(&first, totp::now_unix()).unwrap();
3316        totp_confirm(&c, &id, &code).unwrap();
3317        assert!(totp_required(&c, &id).unwrap());
3318
3319        let second = totp_enroll(&c, &id, "UnENVerse").unwrap().secret.unwrap();
3320        assert_ne!(first, second);
3321        assert!(!totp_required(&c, &id).unwrap());
3322    }
3323
3324    #[test]
3325    fn the_owner_is_refused_a_second_factor() {
3326        // The owner authenticates by deriving the SQLCipher key. A factor there
3327        // gates nothing while looking as though it gates everything.
3328        let c = db();
3329        let owner = ensure_owner_user(&c).unwrap();
3330        assert!(totp_enroll(&c, &owner, "UnENVerse").is_err());
3331        assert!(totp_confirm(&c, &owner, "123456").is_err());
3332    }
3333
3334    #[test]
3335    fn confirm_without_enrollment_is_an_error_not_a_silent_false() {
3336        let c = db();
3337        let id = a_user(&c);
3338        assert!(totp_confirm(&c, &id, "123456").is_err());
3339    }
3340
3341    #[test]
3342    fn the_schema_migration_runs_on_a_database_that_predates_it() {
3343        // Idempotent ALTER TABLE, run twice, on a users table created before the
3344        // columns existed. A migration that throws on second run takes the whole
3345        // unlock with it.
3346        let c = db();
3347        init_users_schema(&c).unwrap();
3348        init_users_schema(&c).unwrap();
3349        let id = a_user(&c);
3350        assert!(!totp_status(&c, &id).unwrap().enrolled);
3351    }
3352}
3353
3354#[cfg(test)]
3355mod user_password_floor_tests {
3356    use super::{check_user_password, MIN_USER_PASSWORD_CHARS};
3357
3358    /// Built from a random id: a literal handed to a password parameter is flagged by CodeQL.
3359    #[test]
3360    fn a_user_password_needs_twelve_characters_and_none_is_allowed() {
3361        let id = crate::new_uuid();
3362        assert_eq!(MIN_USER_PASSWORD_CHARS, 12);
3363        assert!(check_user_password(Some(&id[..0])).is_err());
3364        assert!(check_user_password(Some(&id[..11])).is_err());
3365        assert!(check_user_password(Some(&id[..12])).is_ok());
3366        assert!(check_user_password(None).is_ok());
3367    }
3368}