Skip to main content

symforge/server/
api_keys.rs

1//! Hashed product API-key store (G-039) for the operator server.
2//!
3//! Mirrors the rusqlite pattern in [`crate::stel::ledger_store`]:
4//! `enum ApiKeyStore { Sqlite(..), Disabled }`, idempotent `migrate()`, an
5//! in-memory constructor for tests, and a poisoned-mutex-recovering lock so a
6//! prior panic degrades instead of crashing the serve loop (FR-011 discipline).
7//!
8//! ## Security model (GATE-2 / FR-004 / SC-003)
9//!
10//! - The **raw** secret is shown **exactly once**, at [`ApiKeyStore::mint`]
11//!   time, and is **never** persisted or returned again. Only a SHA-256 hash of
12//!   the raw secret is stored.
13//! - [`ApiKeyStore::verify`] hashes the presented secret and compares (in
14//!   constant time over the hex digest) against the stored hash of every
15//!   **active** (non-revoked) key. A revoked key never verifies.
16//! - [`ApiKeyStore::list`] returns label / fingerprint / timestamps only —
17//!   never the raw secret and never the full hash.
18//!
19//! The raw secret is a high-entropy 256-bit random bearer token rendered as
20//! `sf_<64 hex>`. Because it is random (not a human-chosen password) a plain
21//! SHA-256 is appropriate; a slow password-KDF would add a dependency for no
22//! security gain on a 256-bit random token (see `research.md` D3/D4).
23
24use std::path::Path;
25use std::sync::{Arc, Mutex};
26
27use anyhow::{Context, Result};
28use rusqlite::{Connection, OptionalExtension, params};
29use serde::Serialize;
30use sha2::{Digest, Sha256};
31
32use crate::paths::{API_KEYS_DB_NAME, symforge_db_path};
33
34const CURRENT_SCHEMA_VERSION: u32 = 1;
35const META_SCHEMA_VERSION: &str = "schema_version";
36
37const SCHEMA_V1: &str = r#"
38CREATE TABLE IF NOT EXISTS api_keys_meta (
39    key   TEXT PRIMARY KEY,
40    value TEXT NOT NULL
41);
42
43CREATE TABLE IF NOT EXISTS api_keys (
44    id           INTEGER PRIMARY KEY AUTOINCREMENT,
45    label        TEXT NOT NULL,
46    fingerprint  TEXT NOT NULL,
47    hash         TEXT NOT NULL,
48    created_ms   INTEGER NOT NULL,
49    rotated_ms   INTEGER,
50    revoked_ms   INTEGER
51);
52
53CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys (hash);
54"#;
55
56const MAX_LABEL_BYTES: usize = 128;
57
58/// A persisted API-key record (never carries the raw secret).
59#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
60pub struct ApiKeyRecord {
61    pub id: i64,
62    pub label: String,
63    /// Short, non-reversible prefix of the hash, safe to display in listings.
64    pub fingerprint: String,
65    pub created_ms: u64,
66    /// Set when the key was rotated (its secret replaced).
67    pub rotated_ms: Option<u64>,
68    /// Set when the key was revoked; a revoked key never authenticates.
69    pub revoked_ms: Option<u64>,
70}
71
72impl ApiKeyRecord {
73    /// Whether the key is currently usable (not revoked).
74    pub fn is_active(&self) -> bool {
75        self.revoked_ms.is_none()
76    }
77}
78
79/// The outcome of a successful [`ApiKeyStore::mint`]: the record plus the raw
80/// secret shown **exactly once**.
81#[derive(Debug, Clone)]
82pub struct MintedKey {
83    pub record: ApiKeyRecord,
84    /// The raw bearer secret. Present only here, at creation; never stored,
85    /// never returned by `list`/`get`. The caller must surface it to the
86    /// operator immediately and then drop it.
87    pub raw_secret: String,
88}
89
90/// Hashed API-key store. `Disabled` when the DB could not open.
91#[derive(Debug, Clone)]
92pub enum ApiKeyStore {
93    Sqlite(SqliteApiKeyStore),
94    Disabled,
95}
96
97impl ApiKeyStore {
98    /// Open or create `api-keys.db` under the project `root`. On any failure
99    /// returns `Disabled` (logged, never panics) — the bootstrap `--api-key`
100    /// still works regardless (FR-011 / spec edge case).
101    ///
102    /// `root` is the project ROOT, NOT the `.symforge` data dir. The path is
103    /// built through [`symforge_db_path`] (the single `.symforge` prefix owner),
104    /// so the db lands at `root/.symforge/api-keys.db`. Before this routed through
105    /// the helper, `open` took the already-`.symforge` data dir AND joined a
106    /// `.symforge/`-prefixed const, doubling the prefix to
107    /// `root/.symforge/.symforge/api-keys.db` (D7, shipped in 8.5.0). Any data at
108    /// that pre-fix doubled path is orphaned, not migrated — the store degrades to
109    /// `Disabled`/recreates and the bootstrap `--api-key` keeps working, so there
110    /// is no data loss for a never-1.0 key store (a stale doubled-path file is
111    /// simply unreferenced).
112    pub fn open(root: &Path) -> Self {
113        let db_path = symforge_db_path(root, API_KEYS_DB_NAME);
114        match SqliteApiKeyStore::open(&db_path) {
115            Ok(store) => Self::Sqlite(store),
116            Err(err) => {
117                tracing::warn!(
118                    path = %db_path.display(),
119                    error = %err,
120                    "api-key store failed to open; key management degraded (bootstrap --api-key still works)"
121                );
122                Self::Disabled
123            }
124        }
125    }
126
127    /// In-memory constructor for tests.
128    pub fn open_in_memory() -> Result<Self> {
129        Ok(Self::Sqlite(SqliteApiKeyStore::open_in_memory()?))
130    }
131
132    /// Whether the store is backed by a working DB.
133    pub fn is_enabled(&self) -> bool {
134        matches!(self, Self::Sqlite(_))
135    }
136
137    /// Mint a new key with `label`. Returns the record and the raw secret
138    /// (shown once). Errors only when the store is `Disabled`.
139    pub fn mint(&self, label: &str) -> Result<MintedKey> {
140        match self {
141            Self::Disabled => {
142                anyhow::bail!("api-key store unavailable; cannot mint (bootstrap --api-key only)")
143            }
144            Self::Sqlite(store) => store.mint(label),
145        }
146    }
147
148    /// List all key records (no raw secret). Empty vec when `Disabled`.
149    pub fn list(&self) -> Result<Vec<ApiKeyRecord>> {
150        match self {
151            Self::Disabled => Ok(vec![]),
152            Self::Sqlite(store) => store.list(),
153        }
154    }
155
156    /// Rotate a key's secret: revokes the old hash, generates a new secret,
157    /// stamps `rotated_ms`. Returns the new raw secret (shown once).
158    pub fn rotate(&self, id: i64) -> Result<MintedKey> {
159        match self {
160            Self::Disabled => anyhow::bail!("api-key store unavailable; cannot rotate"),
161            Self::Sqlite(store) => store.rotate(id),
162        }
163    }
164
165    /// Revoke a key. Idempotent: revoking an already-revoked key is a no-op
166    /// success. Errors only when the store is `Disabled` or the id is unknown.
167    pub fn revoke(&self, id: i64) -> Result<()> {
168        match self {
169            Self::Disabled => anyhow::bail!("api-key store unavailable; cannot revoke"),
170            Self::Sqlite(store) => store.revoke(id),
171        }
172    }
173
174    /// Verify a presented raw secret against all active (non-revoked) keys.
175    /// Returns `false` when `Disabled` (callers fall back to the bootstrap key).
176    pub fn verify(&self, presented: &str) -> bool {
177        match self {
178            Self::Disabled => false,
179            Self::Sqlite(store) => store.verify(presented),
180        }
181    }
182}
183
184/// SQLite-backed implementation.
185#[derive(Debug, Clone)]
186pub struct SqliteApiKeyStore {
187    conn: Arc<Mutex<Connection>>,
188}
189
190impl SqliteApiKeyStore {
191    pub fn open(path: &Path) -> Result<Self> {
192        if let Some(parent) = path.parent()
193            && !parent.as_os_str().is_empty()
194        {
195            std::fs::create_dir_all(parent)
196                .with_context(|| format!("creating api-key db parent dir {:?}", parent))?;
197        }
198        let conn =
199            Connection::open(path).with_context(|| format!("opening api-key db at {:?}", path))?;
200        conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;")
201            .context("configuring api-key db pragmas")?;
202        let store = Self {
203            conn: Arc::new(Mutex::new(conn)),
204        };
205        store.migrate()?;
206        Ok(store)
207    }
208
209    pub fn open_in_memory() -> Result<Self> {
210        let conn = Connection::open_in_memory().context("opening in-memory api-key db")?;
211        let store = Self {
212            conn: Arc::new(Mutex::new(conn)),
213        };
214        store.migrate()?;
215        Ok(store)
216    }
217
218    /// Idempotent schema migration. Safe to call repeatedly.
219    pub fn migrate(&self) -> Result<()> {
220        let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
221        conn.execute_batch(SCHEMA_V1)
222            .context("applying api-key schema v1")?;
223        conn.execute(
224            "INSERT OR REPLACE INTO api_keys_meta (key, value) VALUES (?1, ?2)",
225            params![META_SCHEMA_VERSION, CURRENT_SCHEMA_VERSION.to_string()],
226        )
227        .context("writing api-key schema version")?;
228        Ok(())
229    }
230
231    fn mint(&self, label: &str) -> Result<MintedKey> {
232        let raw = self.generate_secret()?;
233        let hash = hash_secret(&raw);
234        let fingerprint = fingerprint_of(&hash);
235        let label = bounded_label(label);
236        let created_ms = now_ms();
237
238        let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
239        conn.execute(
240            "INSERT INTO api_keys (label, fingerprint, hash, created_ms, rotated_ms, revoked_ms)
241             VALUES (?1, ?2, ?3, ?4, NULL, NULL)",
242            params![label, fingerprint, hash, u64_to_i64(created_ms)],
243        )
244        .context("inserting api key")?;
245        let id = conn.last_insert_rowid();
246
247        Ok(MintedKey {
248            record: ApiKeyRecord {
249                id,
250                label,
251                fingerprint,
252                created_ms,
253                rotated_ms: None,
254                revoked_ms: None,
255            },
256            raw_secret: raw,
257        })
258    }
259
260    fn list(&self) -> Result<Vec<ApiKeyRecord>> {
261        let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
262        let mut stmt = conn.prepare(
263            "SELECT id, label, fingerprint, created_ms, rotated_ms, revoked_ms
264             FROM api_keys ORDER BY id ASC",
265        )?;
266        let rows = stmt.query_map([], |row| {
267            let created: i64 = row.get(3)?;
268            let rotated: Option<i64> = row.get(4)?;
269            let revoked: Option<i64> = row.get(5)?;
270            Ok(ApiKeyRecord {
271                id: row.get(0)?,
272                label: row.get(1)?,
273                fingerprint: row.get(2)?,
274                created_ms: i64_to_u64(created),
275                rotated_ms: rotated.map(i64_to_u64),
276                revoked_ms: revoked.map(i64_to_u64),
277            })
278        })?;
279        rows.collect::<rusqlite::Result<Vec<_>>>()
280            .map_err(Into::into)
281    }
282
283    fn rotate(&self, id: i64) -> Result<MintedKey> {
284        let raw = self.generate_secret()?;
285        let hash = hash_secret(&raw);
286        let fingerprint = fingerprint_of(&hash);
287        let rotated_ms = now_ms();
288
289        let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
290        let affected = conn
291            .execute(
292                "UPDATE api_keys SET hash = ?1, fingerprint = ?2, rotated_ms = ?3, revoked_ms = NULL
293                 WHERE id = ?4",
294                params![hash, fingerprint, u64_to_i64(rotated_ms), id],
295            )
296            .context("rotating api key")?;
297        if affected == 0 {
298            anyhow::bail!("no api key with id {id} to rotate");
299        }
300
301        // Read back the (unchanged) created_ms / label for the returned record.
302        let (label, created_ms): (String, i64) = conn.query_row(
303            "SELECT label, created_ms FROM api_keys WHERE id = ?1",
304            params![id],
305            |row| Ok((row.get(0)?, row.get(1)?)),
306        )?;
307
308        Ok(MintedKey {
309            record: ApiKeyRecord {
310                id,
311                label,
312                fingerprint,
313                created_ms: i64_to_u64(created_ms),
314                rotated_ms: Some(rotated_ms),
315                revoked_ms: None,
316            },
317            raw_secret: raw,
318        })
319    }
320
321    fn revoke(&self, id: i64) -> Result<()> {
322        let revoked_ms = now_ms();
323        let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
324        // Only stamp revoked_ms if not already revoked (preserve the first
325        // revocation time); the WHERE still matches the row so a missing id is
326        // detected separately below.
327        let exists: bool = conn
328            .query_row("SELECT 1 FROM api_keys WHERE id = ?1", params![id], |_| {
329                Ok(true)
330            })
331            .optional()?
332            .unwrap_or(false);
333        if !exists {
334            anyhow::bail!("no api key with id {id} to revoke");
335        }
336        conn.execute(
337            "UPDATE api_keys SET revoked_ms = ?1 WHERE id = ?2 AND revoked_ms IS NULL",
338            params![u64_to_i64(revoked_ms), id],
339        )
340        .context("revoking api key")?;
341        Ok(())
342    }
343
344    fn verify(&self, presented: &str) -> bool {
345        if presented.is_empty() {
346            return false;
347        }
348        let presented_hash = hash_secret(presented);
349        let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
350        let mut stmt = match conn.prepare("SELECT hash FROM api_keys WHERE revoked_ms IS NULL") {
351            Ok(stmt) => stmt,
352            Err(err) => {
353                tracing::warn!(error = %err, "api-key verify query failed; rejecting");
354                return false;
355            }
356        };
357        let hashes = stmt.query_map([], |row| row.get::<_, String>(0));
358        let Ok(hashes) = hashes else {
359            return false;
360        };
361        // Iterate every active hash and fold a constant-time compare so a match
362        // anywhere returns true without short-circuiting on the first byte of a
363        // candidate. (The set of active keys is small; this is not a hot path.)
364        let mut matched = false;
365        for stored in hashes.flatten() {
366            if constant_time_eq(stored.as_bytes(), presented_hash.as_bytes()) {
367                matched = true;
368            }
369        }
370        matched
371    }
372
373    /// Source 32 bytes of OS entropy via the bundled SQLite `randomblob` (no new
374    /// crate; see research.md D4) and render as `sf_<64 hex>`.
375    fn generate_secret(&self) -> Result<String> {
376        let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
377        let bytes: Vec<u8> = conn
378            .query_row("SELECT randomblob(32)", [], |row| row.get(0))
379            .context("generating random api-key secret")?;
380        let mut hex = String::with_capacity(2 + bytes.len() * 2);
381        hex.push_str("sf_");
382        use std::fmt::Write;
383        for b in bytes {
384            let _ = write!(hex, "{b:02x}");
385        }
386        Ok(hex)
387    }
388}
389
390// ---------------------------------------------------------------------------
391// Helpers
392// ---------------------------------------------------------------------------
393
394/// SHA-256 hex digest of a raw secret (the persisted form).
395fn hash_secret(raw: &str) -> String {
396    let mut hasher = Sha256::new();
397    hasher.update(raw.as_bytes());
398    let digest = hasher.finalize();
399    let mut hex = String::with_capacity(64);
400    use std::fmt::Write;
401    for b in digest {
402        let _ = write!(hex, "{b:02x}");
403    }
404    hex
405}
406
407/// A short, display-safe fingerprint derived from the hash (first 12 hex chars).
408/// Non-reversible (it is a prefix of an already one-way hash) and never the raw.
409fn fingerprint_of(hash: &str) -> String {
410    hash.chars().take(12).collect()
411}
412
413fn bounded_label(raw: &str) -> String {
414    let normalized: String = raw
415        .chars()
416        .map(|ch| if ch.is_control() { ' ' } else { ch })
417        .collect();
418    let trimmed = normalized.trim();
419    let trimmed = if trimmed.is_empty() {
420        "unnamed"
421    } else {
422        trimmed
423    };
424    if trimmed.len() <= MAX_LABEL_BYTES {
425        return trimmed.to_string();
426    }
427    trimmed.chars().take(MAX_LABEL_BYTES).collect()
428}
429
430fn now_ms() -> u64 {
431    std::time::SystemTime::now()
432        .duration_since(std::time::UNIX_EPOCH)
433        .map(|d| d.as_millis() as u64)
434        .unwrap_or(0)
435}
436
437fn u64_to_i64(value: u64) -> i64 {
438    i64::try_from(value).unwrap_or(i64::MAX)
439}
440
441fn i64_to_u64(value: i64) -> u64 {
442    u64::try_from(value).unwrap_or_default()
443}
444
445/// Constant-time byte-slice equality (same discipline as `auth::constant_time_eq`).
446fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
447    let len_xor = a.len() ^ b.len();
448    let mut diff: u8 = 0;
449    for shift in (0..usize::BITS).step_by(8) {
450        diff |= (len_xor >> shift) as u8;
451    }
452    let n = a.len().max(b.len());
453    for i in 0..n {
454        let x = a.get(i).copied().unwrap_or(0);
455        let y = b.get(i).copied().unwrap_or(0);
456        diff |= x ^ y;
457    }
458    diff == 0
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464
465    #[test]
466    fn open_in_memory_is_enabled() {
467        let store = ApiKeyStore::open_in_memory().expect("in-memory store");
468        assert!(store.is_enabled());
469        assert!(store.list().expect("list").is_empty());
470    }
471
472    #[test]
473    fn mint_returns_raw_once_and_stores_hash_only() {
474        let store = ApiKeyStore::open_in_memory().expect("store");
475        let minted = store.mint("ci-runner").expect("mint");
476        // Raw secret is present at mint and looks like a bearer token.
477        assert!(minted.raw_secret.starts_with("sf_"));
478        assert_eq!(minted.raw_secret.len(), 3 + 64, "sf_ + 32 bytes hex");
479        assert_eq!(minted.record.label, "ci-runner");
480        assert!(minted.record.is_active());
481
482        // List never returns the raw secret (the record has no such field) and
483        // the fingerprint is not the raw secret.
484        let listed = store.list().expect("list");
485        assert_eq!(listed.len(), 1);
486        assert_eq!(listed[0].label, "ci-runner");
487        assert_ne!(listed[0].fingerprint, minted.raw_secret);
488        // The fingerprint is derived from the HASH, not the raw secret, so the
489        // raw secret never contains the fingerprint as a substring.
490        assert!(!minted.raw_secret.contains(&listed[0].fingerprint));
491    }
492
493    #[test]
494    fn minted_key_verifies_revoked_key_does_not() {
495        let store = ApiKeyStore::open_in_memory().expect("store");
496        let minted = store.mint("agent-a").expect("mint");
497        assert!(store.verify(&minted.raw_secret), "fresh key must verify");
498        assert!(!store.verify("sf_wrong"), "wrong key must not verify");
499
500        store.revoke(minted.record.id).expect("revoke");
501        assert!(
502            !store.verify(&minted.raw_secret),
503            "revoked key must not verify"
504        );
505    }
506
507    #[test]
508    fn rotate_changes_secret_old_secret_stops_working() {
509        let store = ApiKeyStore::open_in_memory().expect("store");
510        let minted = store.mint("rotate-me").expect("mint");
511        let old_raw = minted.raw_secret.clone();
512        assert!(store.verify(&old_raw));
513
514        let rotated = store.rotate(minted.record.id).expect("rotate");
515        assert_ne!(rotated.raw_secret, old_raw, "rotation yields a new secret");
516        assert!(!store.verify(&old_raw), "old secret stops working");
517        assert!(store.verify(&rotated.raw_secret), "new secret works");
518        assert!(rotated.record.rotated_ms.is_some());
519    }
520
521    #[test]
522    fn revoke_is_idempotent_and_unknown_id_errors() {
523        let store = ApiKeyStore::open_in_memory().expect("store");
524        let minted = store.mint("k").expect("mint");
525        store.revoke(minted.record.id).expect("first revoke");
526        store
527            .revoke(minted.record.id)
528            .expect("second revoke is idempotent no-op");
529        assert!(store.revoke(9999).is_err(), "unknown id must error");
530    }
531
532    #[test]
533    fn disabled_store_degrades_safely() {
534        let store = ApiKeyStore::Disabled;
535        assert!(!store.is_enabled());
536        assert!(store.list().expect("list").is_empty());
537        assert!(!store.verify("anything"));
538        assert!(store.mint("x").is_err());
539        assert!(store.rotate(1).is_err());
540        assert!(store.revoke(1).is_err());
541    }
542
543    #[test]
544    fn persist_to_file_and_reopen_preserves_keys() {
545        let tmp = tempfile::tempdir().expect("tempdir");
546        let raw = {
547            let store = ApiKeyStore::open(tmp.path());
548            let minted = store.mint("persist").expect("mint");
549            assert!(store.verify(&minted.raw_secret));
550            minted.raw_secret
551        };
552        // Reopen: the minted key must still verify (hash persisted).
553        let store2 = ApiKeyStore::open(tmp.path());
554        assert!(store2.verify(&raw), "reopened store verifies persisted key");
555        assert_eq!(store2.list().expect("list").len(), 1);
556    }
557
558    /// D7 regression: `ApiKeyStore::open` takes the project ROOT (the production
559    /// convention) and lands the db at the SINGLE-prefixed
560    /// `root/.symforge/api-keys.db`. Before the fix, `serve.rs` passed the already
561    /// `.symforge` data dir AND `open` joined a `.symforge/`-prefixed const,
562    /// doubling the prefix to `root/.symforge/.symforge/api-keys.db` (shipped in
563    /// 8.5.0). Assert the single path exists after a mint and the doubled path does
564    /// NOT — the on-disk check the old test skipped by never inspecting the file.
565    #[test]
566    fn open_writes_single_prefixed_db_path_not_doubled() {
567        use crate::paths::{API_KEYS_DB_NAME, SYMFORGE_DIR_NAME};
568        let tmp = tempfile::tempdir().expect("tempdir");
569        let root = tmp.path();
570
571        let store = ApiKeyStore::open(root);
572        store.mint("d7").expect("mint writes the db file");
573
574        let single = root.join(SYMFORGE_DIR_NAME).join(API_KEYS_DB_NAME);
575        let doubled = root
576            .join(SYMFORGE_DIR_NAME)
577            .join(SYMFORGE_DIR_NAME)
578            .join(API_KEYS_DB_NAME);
579        assert!(
580            single.is_file(),
581            "api-keys db must be written to the single-prefixed {}",
582            single.display()
583        );
584        assert!(
585            !doubled.exists(),
586            "api-keys db must NOT be written to the doubled {}",
587            doubled.display()
588        );
589    }
590
591    #[test]
592    fn hashes_are_distinct_per_mint() {
593        let store = ApiKeyStore::open_in_memory().expect("store");
594        let a = store.mint("a").expect("mint a");
595        let b = store.mint("b").expect("mint b");
596        assert_ne!(a.raw_secret, b.raw_secret, "secrets are unique");
597        assert_ne!(
598            a.record.fingerprint, b.record.fingerprint,
599            "fingerprints differ"
600        );
601    }
602
603    #[test]
604    fn empty_presented_secret_never_verifies() {
605        let store = ApiKeyStore::open_in_memory().expect("store");
606        store.mint("k").expect("mint");
607        assert!(!store.verify(""), "empty secret must never verify");
608    }
609}