//! Outpost pairing codes and upload credentials. //! //! Neither the pairing code nor the upload token is stored in clear: only a //! SHA-256 digest of each. The token is generated at claim time and handed to //! the agent exactly once. Both are high-entropy random values, so a plain //! digest lookup is appropriate (there is nothing to brute-force offline). use super::*; use rand::RngCore; use sha2::{Digest, Sha256}; pub const DEFAULT_LIFETIME_DAYS: i64 = 365; /// Lifetime of a newly issued or migrated credential (`TESSERA_OUTPOST_TOKEN_DAYS`). pub fn lifetime_secs() -> i64 { std::env::var("TESSERA_OUTPOST_TOKEN_DAYS") .ok() .and_then(|v| v.trim().parse::().ok()) .filter(|days| (1..=3650).contains(days)) .unwrap_or(DEFAULT_LIFETIME_DAYS) * 86_400 } pub fn digest(kind: &str, secret: &str) -> String { hex::encode(Sha256::digest(format!("tessera-{kind}-v1:{secret}"))) } /// 256 random bits from the OS CSPRNG, hex encoded. pub fn new_token() -> String { let mut bytes = [0u8; 32]; rand::rngs::OsRng.fill_bytes(&mut bytes); hex::encode(bytes) } #[derive(Debug)] pub struct Issued { pub token: String, pub outpost_id: String, pub expires_at: i64, /// Set for a rotation: until when the previous credential still works. pub previous_valid_until: Option, } pub(super) fn migrate(conn: &Connection) -> Result<()> { conn.execute_batch( "CREATE TABLE IF NOT EXISTS pairing_codes ( code_digest TEXT PRIMARY KEY, outpost_id TEXT NOT NULL, expires_at INTEGER NOT NULL, consumed_at INTEGER ); CREATE TABLE IF NOT EXISTS outpost_credentials ( id TEXT PRIMARY KEY, outpost_id TEXT NOT NULL, token_digest TEXT NOT NULL UNIQUE, state TEXT NOT NULL CHECK(state IN ('active','revoked')), created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, revoked_at INTEGER, source TEXT NOT NULL DEFAULT 'pairing' ); CREATE INDEX IF NOT EXISTS outpost_credentials_outpost ON outpost_credentials(outpost_id, state);", )?; let legacy: bool = conn.query_row( "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='wormhole_tokens')", [], |row| row.get(0), )?; if legacy { migrate_legacy(conn)?; } Ok(()) } /// One-time move of `wormhole_tokens` (clear-text token and code) into digests. /// /// * Active tokens keep working: they get a fresh lifetime from now. The old /// `expires_at` was the *pairing code's* expiry and says nothing about the token. /// * Unclaimed codes keep their own expiry; their pre-minted token is discarded. /// * `secure_delete` is on for this connection while the clear text is dropped, /// so freed pages are zeroed instead of left in the file. Old backups and /// copies of the database still contain the tokens: rotate them. fn migrate_legacy(conn: &Connection) -> Result<()> { let now = chrono::Utc::now().timestamp(); let lifetime = lifetime_secs(); conn.execute_batch("PRAGMA secure_delete = ON;")?; let result = (|| -> Result<()> { conn.execute_batch("BEGIN IMMEDIATE")?; let moved = (|| -> Result<(usize, usize)> { let mut active = 0; let mut codes = 0; let rows: Vec<(String, String, String, String, Option, String)> = { let mut stmt = conn.prepare("SELECT token, outpost_id, code, state, outpost_name, expires_at FROM wormhole_tokens")?; let mapped = stmt.query_map([], |r| { Ok(( r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, )) })?; mapped.collect::>()? }; for (token, outpost, code, state, name, expires) in rows { if state == "active" { conn.execute( "INSERT OR IGNORE INTO outposts(id, name, pairing_state) VALUES (?1, ?2, 'active')", params![outpost, name], )?; conn.execute( "INSERT OR IGNORE INTO outpost_credentials(id,outpost_id,token_digest,state,created_at,expires_at,source) VALUES (?1,?2,?3,'active',?4,?5,'migrated')", params![Uuid::new_v4().to_string(), outpost, digest("outpost-token", &token), now, now + lifetime], )?; active += 1; } else if state == "code_shown" { let expires_at = chrono::DateTime::parse_from_rfc3339(&expires) .map(|t| t.timestamp()) .unwrap_or(0); conn.execute( "INSERT OR IGNORE INTO pairing_codes(code_digest,outpost_id,expires_at) VALUES (?1,?2,?3)", params![digest("pairing-code", &code), outpost, expires_at], )?; codes += 1; } } conn.execute_batch("DROP TABLE wormhole_tokens")?; Ok((active, codes)) })(); match moved { Ok((active, codes)) => { conn.execute_batch("COMMIT")?; tracing::warn!( "migrated {active} Outpost token(s) and {codes} pairing code(s) to digests; \ copies of the old database still hold the clear-text tokens, so rotate them" ); Ok(()) } Err(error) => { let _ = conn.execute_batch("ROLLBACK"); Err(error) } } })(); conn.execute_batch("PRAGMA secure_delete = OFF;")?; result } impl Db { pub fn insert_pairing(&self, outpost_id: &str, code: &str, expires_at: i64) -> Result<()> { let conn = self.conn.lock().unwrap(); conn.execute( "DELETE FROM pairing_codes WHERE expires_at <= ?1 OR consumed_at IS NOT NULL", params![expires_at - 86_400], )?; conn.execute( "INSERT INTO pairing_codes(code_digest, outpost_id, expires_at) VALUES (?1, ?2, ?3)", params![digest("pairing-code", code), outpost_id, expires_at], )?; Ok(()) } /// Consume a pairing code and mint the upload token. The single UPDATE … /// RETURNING is what makes a code usable once; the `Db` mutex additionally /// serialises callers. The token exists in clear only in the return value. pub fn claim_pairing( &self, code: &str, outpost_name: &str, now: i64, ) -> Result> { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction()?; let outpost: Option = tx .query_row( "UPDATE pairing_codes SET consumed_at = ?2 WHERE code_digest = ?1 AND consumed_at IS NULL AND expires_at > ?2 RETURNING outpost_id", params![digest("pairing-code", code), now], |row| row.get(0), ) .optional()?; let Some(outpost) = outpost else { return Ok(None); }; let token = new_token(); let expires_at = now + lifetime_secs(); tx.execute( "INSERT INTO outposts(id, name, last_seen, pairing_state) VALUES (?1, ?2, ?3, 'active') ON CONFLICT(id) DO UPDATE SET name = excluded.name, last_seen = excluded.last_seen, pairing_state = 'active'", params![outpost, outpost_name, chrono::Utc::now().to_rfc3339()], )?; tx.execute( "INSERT INTO outpost_credentials(id,outpost_id,token_digest,state,created_at,expires_at,source) VALUES (?1,?2,?3,'active',?4,?5,'pairing')", params![Uuid::new_v4().to_string(), outpost, digest("outpost-token", &token), now, expires_at], )?; tx.commit()?; Ok(Some(Issued { token, outpost_id: outpost, expires_at, previous_valid_until: None, })) } /// The Outpost a presented token belongs to, if it is active and unexpired. pub fn upload_token_outpost(&self, token: &str, now: i64) -> Result> { let conn = self.conn.lock().unwrap(); Ok(conn .query_row( "SELECT outpost_id FROM outpost_credentials WHERE token_digest = ?1 AND state = 'active' AND expires_at > ?2", params![digest("outpost-token", token), now], |row| row.get(0), ) .optional()?) } /// Issue a new credential for a paired Outpost. Older active credentials keep /// working for `grace_secs` (0 = they stop immediately), so an operator has a /// bounded window to put the new token on the agent. Returns `None` for an /// unknown or revoked Outpost: it must be paired again. pub fn rotate_credential( &self, outpost: &str, grace_secs: i64, now: i64, ) -> Result> { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction()?; let paired: bool = tx.query_row( "SELECT EXISTS(SELECT 1 FROM outposts WHERE id = ?1 AND pairing_state = 'active')", params![outpost], |row| row.get(0), )?; if !paired { return Ok(None); } let until = now + grace_secs.max(0); tx.execute( "UPDATE outpost_credentials SET expires_at = MIN(expires_at, ?3) WHERE outpost_id = ?1 AND state = 'active' AND expires_at > ?2", params![outpost, now, until], )?; let token = new_token(); let expires_at = now + lifetime_secs(); tx.execute( "INSERT INTO outpost_credentials(id,outpost_id,token_digest,state,created_at,expires_at,source) VALUES (?1,?2,?3,'active',?4,?5,'rotation')", params![Uuid::new_v4().to_string(), outpost, digest("outpost-token", &token), now, expires_at], )?; tx.commit()?; Ok(Some(Issued { token, outpost_id: outpost.to_string(), expires_at, previous_valid_until: (grace_secs > 0).then_some(until), })) } /// Revoke every credential of an Outpost, effective on its next request. /// Returns false when the Outpost is unknown. pub fn revoke_outpost(&self, outpost: &str, now: i64) -> Result { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction()?; tx.execute( "UPDATE outpost_credentials SET state='revoked', revoked_at=?2 WHERE outpost_id=?1 AND state='active'", params![outpost, now], )?; let known = tx.execute( "UPDATE outposts SET pairing_state='revoked' WHERE id=?1", params![outpost], )? == 1; // Anything that overwrites through, or reads from, this Outpost must stop working with it. tx.execute( "UPDATE orbit_relations SET active=0, deactivated_at=?2, deactivated_reason='outpost_revoked' WHERE active=1 AND (target_id IN (SELECT id FROM restore_targets WHERE outpost_id=?1) OR source_application_id IN (SELECT application_id FROM capture_profiles WHERE outpost_id=?1))", params![outpost, now], )?; tx.commit()?; Ok(known) } /// Test fixture: a paired Outpost whose token is a chosen string. #[cfg(test)] pub fn insert_test_credential(&self, token: &str, outpost: &str, name: &str) { let conn = self.conn.lock().unwrap(); let now = chrono::Utc::now().timestamp(); conn.execute( "INSERT INTO outposts(id, name, last_seen, pairing_state) VALUES (?1, ?2, ?3, 'active') ON CONFLICT(id) DO UPDATE SET pairing_state='active'", params![outpost, name, chrono::Utc::now().to_rfc3339()], ) .unwrap(); conn.execute( "INSERT INTO outpost_credentials(id,outpost_id,token_digest,state,created_at,expires_at,source) VALUES (?1,?2,?3,'active',?4,?5,'pairing')", params![Uuid::new_v4().to_string(), outpost, digest("outpost-token", token), now, now + lifetime_secs()], ) .unwrap(); } } #[cfg(test)] mod tests { use super::*; async fn db() -> (tempfile::TempDir, Db, std::path::PathBuf) { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("t.db"); let db = Db::connect(&path).await.unwrap(); db.migrate().await.unwrap(); (dir, db, path) } /// Every byte SQLite may have left on disk for this database. fn disk_bytes(path: &std::path::Path) -> Vec { let mut all = Vec::new(); for suffix in ["", "-wal", "-journal", "-shm"] { let mut name = path.as_os_str().to_owned(); name.push(suffix); if let Ok(bytes) = std::fs::read(std::path::PathBuf::from(name)) { all.extend(bytes); } } all } fn contains(haystack: &[u8], needle: &str) -> bool { haystack .windows(needle.len()) .any(|w| w == needle.as_bytes()) } #[tokio::test] async fn the_code_and_token_are_never_stored_in_clear() { let (_dir, db, path) = db().await; let outpost = Uuid::new_v4().to_string(); db.insert_pairing(&outpost, "ABCDEFGH2345", 10_000).unwrap(); let issued = db .claim_pairing("ABCDEFGH2345", "agent", 100) .unwrap() .unwrap(); assert_eq!(issued.token.len(), 64); assert_eq!( db.upload_token_outpost(&issued.token, 101) .unwrap() .as_deref(), Some(outpost.as_str()) ); drop(db); let bytes = disk_bytes(&path); assert!( contains(&bytes, "agent"), "sanity: the scan really reads the database file" ); assert!( !contains(&bytes, &issued.token), "token in the database file" ); assert!( !contains(&bytes, "ABCDEFGH2345"), "pairing code in the database file" ); } #[tokio::test] async fn a_code_works_once_and_only_before_it_expires() { let (_dir, db, _) = db().await; let outpost = Uuid::new_v4().to_string(); db.insert_pairing(&outpost, "CODE-ONE", 1_000).unwrap(); assert!(db.claim_pairing("WRONG", "a", 10).unwrap().is_none()); assert!(db.claim_pairing("CODE-ONE", "a", 10).unwrap().is_some()); assert!( db.claim_pairing("CODE-ONE", "a", 11).unwrap().is_none(), "replay" ); db.insert_pairing(&outpost, "CODE-TWO", 1_000).unwrap(); assert!( db.claim_pairing("CODE-TWO", "a", 1_000).unwrap().is_none(), "expired at its deadline" ); } #[tokio::test] async fn concurrent_claims_of_one_code_yield_exactly_one_token() { // The Db mutex serialises these, so this shows the statement is atomic // (one consumer per code), not that SQLite arbitrates a race. let (_dir, db, _) = db().await; db.insert_pairing(&Uuid::new_v4().to_string(), "RACE-CODE", 1_000_000) .unwrap(); let handles: Vec<_> = (0..8) .map(|_| { let db = db.clone(); std::thread::spawn(move || db.claim_pairing("RACE-CODE", "a", 5).unwrap().is_some()) }) .collect(); let winners = handles .into_iter() .map(|h| h.join().unwrap()) .filter(|won| *won) .count(); assert_eq!(winners, 1); } #[tokio::test] async fn revoked_and_expired_tokens_are_rejected_on_the_next_lookup() { let (_dir, db, _) = db().await; let outpost = Uuid::new_v4().to_string(); db.insert_pairing(&outpost, "C", 1_000).unwrap(); let issued = db.claim_pairing("C", "agent", 10).unwrap().unwrap(); assert!(db .upload_token_outpost(&issued.token, issued.expires_at - 1) .unwrap() .is_some()); assert!( db.upload_token_outpost(&issued.token, issued.expires_at) .unwrap() .is_none(), "expiry" ); assert!(db .upload_token_outpost(&issued.token, 20) .unwrap() .is_some()); assert!(db.revoke_outpost(&outpost, 21).unwrap()); assert!( db.upload_token_outpost(&issued.token, 22) .unwrap() .is_none(), "revoked" ); assert!( db.rotate_credential(&outpost, 60, 23).unwrap().is_none(), "a revoked Outpost must be paired again" ); assert!(!db.revoke_outpost(&Uuid::new_v4().to_string(), 1).unwrap()); } #[tokio::test] async fn rotation_has_an_explicit_grace_window() { let (_dir, db, _) = db().await; let outpost = Uuid::new_v4().to_string(); db.insert_pairing(&outpost, "C", 1_000).unwrap(); let first = db.claim_pairing("C", "agent", 10).unwrap().unwrap(); let second = db.rotate_credential(&outpost, 300, 100).unwrap().unwrap(); assert_eq!(second.previous_valid_until, Some(400)); assert_ne!(first.token, second.token); assert!( db.upload_token_outpost(&first.token, 399) .unwrap() .is_some(), "old token inside the grace window" ); assert!( db.upload_token_outpost(&first.token, 400) .unwrap() .is_none(), "and not after it" ); assert!(db .upload_token_outpost(&second.token, 400) .unwrap() .is_some()); // grace 0 cuts the old token at once let third = db.rotate_credential(&outpost, 0, 500).unwrap().unwrap(); assert_eq!(third.previous_valid_until, None); assert!(db .upload_token_outpost(&second.token, 500) .unwrap() .is_none()); assert!(db .upload_token_outpost(&third.token, 500) .unwrap() .is_some()); // an unknown outpost cannot be rotated into existence assert!(db .rotate_credential(&Uuid::new_v4().to_string(), 0, 1) .unwrap() .is_none()); } /// A pre-M4 database: clear-text tokens and codes in `wormhole_tokens`. fn legacy_database(path: &std::path::Path) { let conn = Connection::open(path).unwrap(); conn.execute_batch( "CREATE TABLE outposts (id TEXT PRIMARY KEY, name TEXT, last_seen TEXT, pairing_state TEXT NOT NULL DEFAULT 'unpaired'); CREATE TABLE wormhole_tokens (token TEXT PRIMARY KEY, outpost_id TEXT NOT NULL, code TEXT NOT NULL, state TEXT NOT NULL, expires_at TEXT NOT NULL, outpost_name TEXT);", ) .unwrap(); // paired long ago: the *code* expiry is in the past and must not become the token expiry conn.execute("INSERT INTO wormhole_tokens VALUES ('LEGACY-ACTIVE-TOKEN-0001','11111111-1111-1111-1111-111111111111','LEGACYCODE1','active','2020-01-01T00:00:00+00:00','old-agent')", []).unwrap(); let future = (chrono::Utc::now() + chrono::Duration::minutes(5)).to_rfc3339(); conn.execute("INSERT INTO wormhole_tokens VALUES ('PREMINTED-TOKEN-0002','22222222-2222-2222-2222-222222222222','LEGACYCODE2','code_shown',?1,NULL)", params![future]).unwrap(); conn.execute("INSERT INTO wormhole_tokens VALUES ('PREMINTED-TOKEN-0003','33333333-3333-3333-3333-333333333333','LEGACYCODE3','code_shown','2020-01-01T00:00:00+00:00',NULL)", []).unwrap(); } #[tokio::test] async fn legacy_clear_text_tokens_are_migrated_in_place_and_scrubbed() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("legacy.db"); legacy_database(&path); let db = Db::connect(&path).await.unwrap(); db.migrate().await.unwrap(); let now = chrono::Utc::now().timestamp(); // the paired agent keeps working with its existing token assert_eq!( db.upload_token_outpost("LEGACY-ACTIVE-TOKEN-0001", now) .unwrap() .as_deref(), Some("11111111-1111-1111-1111-111111111111") ); assert!(db .upload_token_outpost("LEGACY-ACTIVE-TOKEN-0001", now + lifetime_secs() + 10) .unwrap() .is_none()); // an unclaimed code can still be claimed once, but its pre-minted token is gone let claimed = db .claim_pairing("LEGACYCODE2", "new-agent", now) .unwrap() .unwrap(); assert_ne!(claimed.token, "PREMINTED-TOKEN-0002"); assert!(db .upload_token_outpost("PREMINTED-TOKEN-0002", now) .unwrap() .is_none()); assert!( db.claim_pairing("LEGACYCODE3", "late-agent", now) .unwrap() .is_none(), "expired code stays expired" ); // the old table and every clear-text copy are gone, including freed pages let exists: bool = db .conn .lock() .unwrap() .query_row( "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE name='wormhole_tokens')", [], |r| r.get(0), ) .unwrap(); assert!(!exists); let state: String = db.conn.lock().unwrap() .query_row("SELECT pairing_state FROM outposts WHERE id='11111111-1111-1111-1111-111111111111'", [], |r| r.get(0)).unwrap(); assert_eq!(state, "active"); drop(db); let bytes = disk_bytes(&path); assert!( contains(&bytes, "old-agent") || contains(&bytes, "new-agent"), "sanity: the scan really reads the database file" ); for secret in [ "LEGACY-ACTIVE-TOKEN-0001", "PREMINTED-TOKEN-0002", "PREMINTED-TOKEN-0003", "LEGACYCODE1", "LEGACYCODE2", "LEGACYCODE3", ] { assert!(!contains(&bytes, secret), "{secret} still on disk"); } // migrating again changes nothing let again = Db::connect(&path).await.unwrap(); again.migrate().await.unwrap(); assert!(again .upload_token_outpost("LEGACY-ACTIVE-TOKEN-0001", now) .unwrap() .is_some()); } }