1use std::path::{Path, PathBuf};
37use std::sync::Mutex;
38use std::time::Duration;
39
40use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
41use rusqlite::{params, Connection, OptionalExtension};
42
43use super::agent_lan_keys::random_seed_bytes;
44use super::error::StoreError;
45
46pub mod pins;
47pub mod revocations;
48
49const SCHEMA_VERSION: i64 = 5;
57
58const SCHEMA: &str = "
59 CREATE TABLE IF NOT EXISTS wan_meta (
60 key TEXT PRIMARY KEY,
61 value INTEGER NOT NULL
62 );
63 -- One row, ever. `singleton` pins it so a concurrent first mint
64 -- collides instead of creating a second instance.
65 CREATE TABLE IF NOT EXISTS wan_instance (
66 singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
67 public_key TEXT NOT NULL,
68 private_key TEXT NOT NULL,
69 instance_id TEXT NOT NULL,
70 host_hint TEXT NOT NULL,
71 created_at INTEGER NOT NULL
72 );
73 CREATE TABLE IF NOT EXISTS wan_agent_keys (
74 agent_id TEXT PRIMARY KEY,
75 public_key TEXT NOT NULL,
76 private_key TEXT NOT NULL,
77 created_at INTEGER NOT NULL,
78 -- 1 when the key was carried over from objects.db's
79 -- db_agent_wan_keys rather than minted here.
80 imported INTEGER NOT NULL DEFAULT 0,
81 -- D1b: the fingerprint of the certificate confirmed published to the
82 -- cloud directory, and when. Superseded by wan_agent_key_publications
83 -- (v3), which records WHICH directory; no longer read or written here.
84 published_fp TEXT,
85 published_at INTEGER
86 );
87 -- v3: which key fingerprint each directory is confirmed to hold. A
88 -- directory is a relay plus the account it was published under
89 -- (`wan_publish::directory_id`). A sign-in to another relay or account
90 -- simply has no row yet, so the key is pending there — no reset needed,
91 -- whichever process or channel of this file did the publishing.
92 CREATE TABLE IF NOT EXISTS wan_agent_key_publications (
93 agent_id TEXT NOT NULL,
94 directory TEXT NOT NULL,
95 key_fp TEXT NOT NULL,
96 published_at INTEGER NOT NULL,
97 PRIMARY KEY (agent_id, directory)
98 );
99 -- v2 (D2, receiver side) --
100 -- Directory records fetched for verification. Self-certifying and
101 -- content-addressed by the key fingerprint, so a cached record never
102 -- expires; re-checked against its chain on every use.
103 CREATE TABLE IF NOT EXISTS wan_peer_records (
104 instance_id TEXT NOT NULL,
105 agent_id TEXT NOT NULL,
106 channel TEXT NOT NULL,
107 key_fp TEXT NOT NULL,
108 record TEXT NOT NULL,
109 fetched_at INTEGER NOT NULL,
110 PRIMARY KEY (instance_id, agent_id, channel, key_fp)
111 );
112 -- Every verified instance, recorded on first sight (§2.6). approved_at is
113 -- written only by the host-gated approval window, which ships disabled;
114 -- revoked_at is sticky.
115 CREATE TABLE IF NOT EXISTS wan_known_instances (
116 instance_id TEXT PRIMARY KEY,
117 host_hint TEXT NOT NULL,
118 first_seen_at INTEGER NOT NULL,
119 approved_at INTEGER,
120 revoked_at INTEGER,
121 revocation_checked_at INTEGER
122 );
123 -- The install pinned to speak for an agent name on a channel: the first
124 -- one the account's presence list shows, moved only by the operator's
125 -- window. conflict_* remembers the last other install that was refused.
126 CREATE TABLE IF NOT EXISTS wan_agent_instance_pins (
127 agent_id TEXT NOT NULL,
128 channel TEXT NOT NULL,
129 instance_id TEXT NOT NULL,
130 host_hint TEXT NOT NULL,
131 pinned_at INTEGER NOT NULL,
132 conflict_instance_id TEXT,
133 conflict_host_hint TEXT,
134 conflict_at INTEGER,
135 conflict_count INTEGER,
136 PRIMARY KEY (agent_id, channel)
137 );
138 -- v5: a key this install replaced or removed, and a directory that was
139 -- confirmed to hold it. Written in the same transaction as the delete;
140 -- removed once that directory has the signed revocation.
141 CREATE TABLE IF NOT EXISTS wan_key_retirements (
142 agent_id TEXT NOT NULL,
143 key_fp TEXT NOT NULL,
144 directory TEXT NOT NULL,
145 retired_at INTEGER NOT NULL,
146 PRIMARY KEY (agent_id, key_fp, directory)
147 );
148 -- v5: verified revocations of any install's agent key. Sticky, and kept
149 -- across sign-outs: the notice is signed by the instance and names the
150 -- key, so it holds under any account.
151 CREATE TABLE IF NOT EXISTS wan_revoked_keys (
152 instance_id TEXT NOT NULL,
153 agent_id TEXT NOT NULL,
154 channel TEXT NOT NULL,
155 key_fp TEXT NOT NULL,
156 revoked_at INTEGER NOT NULL,
157 record TEXT NOT NULL,
158 learned_at INTEGER NOT NULL,
159 PRIMARY KEY (instance_id, agent_id, channel, key_fp)
160 );
161 -- (instance, agent, msgid) already delivered (§2.5). Written after
162 -- successful local delivery; pruned once the message could no longer
163 -- pass freshness.
164 CREATE TABLE IF NOT EXISTS wan_seen_sigs (
165 instance_id TEXT NOT NULL,
166 agent_id TEXT NOT NULL,
167 msg_id TEXT NOT NULL,
168 expires_at INTEGER NOT NULL,
169 PRIMARY KEY (instance_id, agent_id, msg_id)
170 );
171";
172
173#[derive(Clone, PartialEq, Eq)]
176pub struct WanInstance {
177 pub instance_id: String,
178 pub public_key: [u8; 32],
179 pub private_key: [u8; 32],
180 pub host_hint: String,
184 pub created_at: i64,
185}
186
187impl std::fmt::Debug for WanInstance {
188 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189 f.debug_struct("WanInstance")
190 .field("instance_id", &self.instance_id)
191 .field("host_hint", &self.host_hint)
192 .field("created_at", &self.created_at)
193 .finish_non_exhaustive()
194 }
195}
196
197#[derive(Clone, PartialEq, Eq)]
201pub struct WanAgentKey {
202 pub public_key: String,
203 pub private_key: String,
204 pub imported: bool,
205 pub created_at: i64,
209}
210
211impl std::fmt::Debug for WanAgentKey {
212 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213 f.debug_struct("WanAgentKey")
214 .field("public_key", &self.public_key)
215 .field("imported", &self.imported)
216 .field("created_at", &self.created_at)
217 .finish_non_exhaustive()
218 }
219}
220
221impl WanAgentKey {
222 pub fn public_key_bytes(&self) -> Option<[u8; 32]> {
224 decode_32(&self.public_key)
225 }
226
227}
228
229#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231pub struct KnownInstance {
232 pub approved_at: Option<i64>,
233 pub revoked_at: Option<i64>,
234 pub revocation_checked_at: Option<i64>,
235}
236
237pub struct WanIdentityStore {
238 conn: Mutex<Connection>,
239}
240
241static GLOBAL: std::sync::OnceLock<std::sync::Arc<WanIdentityStore>> = std::sync::OnceLock::new();
242
243pub fn install_global(store: std::sync::Arc<WanIdentityStore>) {
247 let _ = GLOBAL.set(store);
248}
249
250pub fn global() -> Option<std::sync::Arc<WanIdentityStore>> {
251 GLOBAL.get().cloned()
252}
253
254pub fn resolve_wan_identity_path() -> Option<PathBuf> {
258 agentmux_common::DataPaths::from_env().map(|paths| paths.wan_identity_dir().join("wan.db"))
259}
260
261pub fn sanitize_host_hint(hostname: &str) -> String {
266 let hint: String = hostname
267 .trim()
268 .to_lowercase()
269 .chars()
270 .map(|c| if c.is_ascii_lowercase() || c.is_ascii_digit() || c == '.' || c == '-' { c } else { '-' })
271 .take(48)
272 .collect();
273 if hint.is_empty() {
274 "unknown".to_string()
275 } else {
276 hint
277 }
278}
279
280fn decode_32(b64: &str) -> Option<[u8; 32]> {
281 BASE64.decode(b64).ok()?.try_into().ok()
282}
283
284const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
285
286fn is_busy(e: &rusqlite::Error) -> bool {
287 matches!(
288 e,
289 rusqlite::Error::SqliteFailure(f, _)
290 if matches!(f.code, rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked)
291 )
292}
293
294fn retry_while_busy<T>(mut op: impl FnMut() -> Result<T, rusqlite::Error>) -> Result<T, rusqlite::Error> {
297 let deadline = std::time::Instant::now() + BUSY_TIMEOUT;
298 let mut backoff = Duration::from_millis(5);
299 loop {
300 match op() {
301 Err(e) if is_busy(&e) && std::time::Instant::now() < deadline => {
302 std::thread::sleep(backoff);
303 backoff = (backoff * 2).min(Duration::from_millis(100));
304 }
305 result => return result,
306 }
307 }
308}
309
310#[cfg(unix)]
311fn restrict_permissions(dir: &Path, file: &Path) {
312 use std::os::unix::fs::PermissionsExt;
313 let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
314 let _ = std::fs::set_permissions(file, std::fs::Permissions::from_mode(0o600));
315}
316
317#[cfg(not(unix))]
320fn restrict_permissions(_dir: &Path, _file: &Path) {}
321
322impl WanIdentityStore {
323 pub fn open(path: &Path) -> Result<Self, StoreError> {
327 if let Some(dir) = path.parent() {
328 std::fs::create_dir_all(dir).map_err(|e| StoreError::Other(format!("wan-identity dir: {e}")))?;
329 }
330 let conn = Connection::open(path)?;
331 conn.busy_timeout(BUSY_TIMEOUT)?;
332 retry_while_busy(|| {
339 conn.pragma_update(None, "journal_mode", "WAL")?;
340 conn.execute_batch(&format!("BEGIN IMMEDIATE; {SCHEMA} COMMIT;")).inspect_err(|_| {
343 let _ = conn.execute_batch("ROLLBACK;");
344 })?;
345 conn.execute(
346 "INSERT INTO wan_meta (key, value) VALUES ('schema_version', ?1) \
347 ON CONFLICT(key) DO UPDATE SET value = MAX(value, excluded.value)",
348 params![SCHEMA_VERSION],
349 )?;
350 Ok(())
351 })?;
352 if let Some(dir) = path.parent() {
353 restrict_permissions(dir, path);
354 }
355 Ok(Self { conn: Mutex::new(conn) })
356 }
357
358 #[cfg(test)]
360 pub fn schema_version(&self) -> Result<i64, StoreError> {
361 let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
362 Ok(conn.query_row("SELECT value FROM wan_meta WHERE key = 'schema_version'", [], |r| r.get(0))?)
363 }
364
365 pub fn instance_ensure(&self, hostname: &str) -> Result<WanInstance, StoreError> {
368 let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
369 if let Some(existing) = Self::instance_load(&conn)? {
370 return Ok(existing);
371 }
372 let (public_key, private_key) = agentmux_common::jekt_sign::generate_wan_keypair(random_seed_bytes());
373 conn.execute(
374 "INSERT OR IGNORE INTO wan_instance \
375 (singleton, public_key, private_key, instance_id, host_hint, created_at) \
376 VALUES (1, ?1, ?2, ?3, ?4, ?5)",
377 params![
378 BASE64.encode(public_key),
379 BASE64.encode(private_key),
380 agentmux_common::jekt_sign::wan_instance_id(&public_key),
381 sanitize_host_hint(hostname),
382 agentmux_common::time::now_secs(),
383 ],
384 )?;
385 Self::instance_load(&conn)?.ok_or_else(|| StoreError::Other("wan_instance row missing after mint".into()))
388 }
389
390 fn instance_load(conn: &Connection) -> Result<Option<WanInstance>, StoreError> {
391 let row = conn
392 .query_row(
393 "SELECT public_key, private_key, instance_id, host_hint, created_at FROM wan_instance WHERE singleton = 1",
394 [],
395 |r| {
396 Ok((
397 r.get::<_, String>(0)?,
398 r.get::<_, String>(1)?,
399 r.get::<_, String>(2)?,
400 r.get::<_, String>(3)?,
401 r.get::<_, i64>(4)?,
402 ))
403 },
404 )
405 .optional()?;
406 let Some((public_b64, private_b64, instance_id, host_hint, created_at)) = row else {
407 return Ok(None);
408 };
409 let (Some(public_key), Some(private_key)) = (decode_32(&public_b64), decode_32(&private_b64)) else {
410 return Err(StoreError::Other("wan_instance holds a malformed key".into()));
411 };
412 if agentmux_common::jekt_sign::wan_instance_id(&public_key) != instance_id {
415 return Err(StoreError::Other("wan_instance id does not match its key".into()));
416 }
417 Ok(Some(WanInstance { instance_id, public_key, private_key, host_hint, created_at }))
418 }
419
420 pub fn agent_key_load(&self, agent_id: &str) -> Result<Option<WanAgentKey>, StoreError> {
422 let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
423 Self::agent_key_load_locked(&conn, &agent_id.to_lowercase())
424 }
425
426 const AGENT_KEY_COLUMNS: &'static str = "public_key, private_key, imported, created_at";
427
428 fn agent_key_from_row(r: &rusqlite::Row<'_>, offset: usize) -> rusqlite::Result<WanAgentKey> {
429 Ok(WanAgentKey {
430 public_key: r.get(offset)?,
431 private_key: r.get(offset + 1)?,
432 imported: r.get::<_, i64>(offset + 2)? != 0,
433 created_at: r.get(offset + 3)?,
434 })
435 }
436
437 fn agent_key_load_locked(conn: &Connection, key: &str) -> Result<Option<WanAgentKey>, StoreError> {
438 Ok(conn
439 .query_row(
440 &format!("SELECT {} FROM wan_agent_keys WHERE agent_id = ?1", Self::AGENT_KEY_COLUMNS),
441 params![key],
442 |r| Self::agent_key_from_row(r, 0),
443 )
444 .optional()?)
445 }
446
447 pub fn agent_keys_unpublished(&self, directory: &str) -> Result<Vec<(String, WanAgentKey)>, StoreError> {
450 let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
451 let mut stmt = conn.prepare(&format!(
452 "SELECT k.agent_id, {}, p.key_fp FROM wan_agent_keys k \
453 LEFT JOIN wan_agent_key_publications p ON p.agent_id = k.agent_id AND p.directory = ?1 \
454 ORDER BY k.agent_id",
455 Self::AGENT_KEY_COLUMNS.split(", ").map(|c| format!("k.{c}")).collect::<Vec<_>>().join(", ")
456 ))?;
457 let rows = stmt.query_map(params![directory], |r| {
458 Ok((r.get::<_, String>(0)?, Self::agent_key_from_row(r, 1)?, r.get::<_, Option<String>>(5)?))
459 })?;
460 let mut out = Vec::new();
461 for row in rows {
462 let (agent_id, key, published_fp) = row?;
463 if !Self::fp_matches(&key, published_fp.as_deref()) {
464 out.push((agent_id, key));
465 }
466 }
467 Ok(out)
468 }
469
470 pub fn agent_key_is_published_to(&self, agent_id: &str, key: &WanAgentKey, directory: &str) -> Result<bool, StoreError> {
473 let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
474 let fp: Option<String> = conn
475 .query_row(
476 "SELECT key_fp FROM wan_agent_key_publications WHERE agent_id = ?1 AND directory = ?2",
477 params![agent_id.to_lowercase(), directory],
478 |r| r.get(0),
479 )
480 .optional()?;
481 Ok(Self::fp_matches(key, fp.as_deref()))
482 }
483
484 fn fp_matches(key: &WanAgentKey, published_fp: Option<&str>) -> bool {
485 match (key.public_key_bytes(), published_fp) {
486 (Some(public), Some(fp)) => agentmux_common::jekt_sign::wan_key_fingerprint(&public) == fp,
487 _ => false,
488 }
489 }
490
491 pub fn agent_key_mark_published(&self, agent_id: &str, public_key: &str, directory: &str) -> Result<bool, StoreError> {
498 let Some(public) = decode_32(public_key) else { return Ok(false) };
499 let fp = agentmux_common::jekt_sign::wan_key_fingerprint(&public);
500 let agent_id = agent_id.to_lowercase();
501 let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
502 let updated = conn.execute(
503 "INSERT INTO wan_agent_key_publications (agent_id, directory, key_fp, published_at) \
504 SELECT ?1, ?2, ?3, ?4 WHERE EXISTS \
505 (SELECT 1 FROM wan_agent_keys WHERE agent_id = ?1 AND public_key = ?5) \
506 ON CONFLICT (agent_id, directory) DO UPDATE SET key_fp = excluded.key_fp, published_at = excluded.published_at",
507 params![agent_id, directory, fp, agentmux_common::time::now_secs(), public_key],
508 )?;
509 Ok(updated > 0)
510 }
511
512 pub fn agent_key_ensure(&self, agent_id: &str, import: Option<(&str, &str)>) -> Result<WanAgentKey, StoreError> {
519 let key = agent_id.to_lowercase();
520 let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
521 if let Some(existing) = Self::agent_key_load_locked(&conn, &key)? {
522 return Ok(existing);
523 }
524 let valid_import = import.filter(|(public_b64, private_b64)| {
526 match (decode_32(public_b64), decode_32(private_b64)) {
527 (Some(public), Some(private)) => agentmux_common::jekt_sign::generate_wan_keypair(private).0 == public,
528 _ => false,
529 }
530 });
531 let (public_key, private_key, imported) = match valid_import {
532 Some((public_b64, private_b64)) => (public_b64.to_string(), private_b64.to_string(), true),
533 None => {
534 let (public, private) = agentmux_common::jekt_sign::generate_wan_keypair(random_seed_bytes());
535 (BASE64.encode(public), BASE64.encode(private), false)
536 }
537 };
538 conn.execute(
539 "INSERT OR IGNORE INTO wan_agent_keys (agent_id, public_key, private_key, created_at, imported) \
540 VALUES (?1, ?2, ?3, ?4, ?5)",
541 params![key, public_key, private_key, agentmux_common::time::now_secs(), imported as i64],
542 )?;
543 Self::agent_key_load_locked(&conn, &key)?
544 .ok_or_else(|| StoreError::Other("wan_agent_keys row missing after mint".into()))
545 }
546
547 pub fn peer_record_get(
553 &self,
554 instance_id: &str,
555 agent_id: &str,
556 channel: &str,
557 key_fp: &str,
558 ) -> Result<Option<agentmux_common::jekt_sign::WanKeyRecord>, StoreError> {
559 let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
560 let json: Option<String> = conn
561 .query_row(
562 "SELECT record FROM wan_peer_records \
563 WHERE instance_id = ?1 AND agent_id = ?2 AND channel = ?3 AND key_fp = ?4",
564 params![instance_id.to_lowercase(), agent_id.to_lowercase(), channel, key_fp],
565 |r| r.get(0),
566 )
567 .optional()?;
568 Ok(json.and_then(|j| serde_json::from_str(&j).ok()))
569 }
570
571 pub fn peer_record_put(&self, record: &agentmux_common::jekt_sign::WanKeyRecord) -> Result<(), StoreError> {
573 let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
574 conn.execute(
575 "INSERT OR REPLACE INTO wan_peer_records \
576 (instance_id, agent_id, channel, key_fp, record, fetched_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
577 params![
578 record.instance_id,
579 record.agent_id,
580 record.channel,
581 record.key_fp,
582 serde_json::to_string(record)?,
583 agentmux_common::time::now_secs(),
584 ],
585 )?;
586 Ok(())
587 }
588
589 pub fn peer_cache_clear(&self) -> Result<(), StoreError> {
591 let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
592 conn.execute("DELETE FROM wan_peer_records", [])?;
593 conn.execute("DELETE FROM wan_agent_instance_pins", [])?;
595 Ok(())
596 }
597
598 pub fn known_instance_observe(&self, instance_id: &str, host_hint: &str, now: i64) -> Result<KnownInstance, StoreError> {
601 let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
602 conn.execute(
603 "INSERT OR IGNORE INTO wan_known_instances (instance_id, host_hint, first_seen_at) VALUES (?1, ?2, ?3)",
604 params![instance_id, host_hint, now],
605 )?;
606 Ok(conn.query_row(
607 "SELECT approved_at, revoked_at, revocation_checked_at FROM wan_known_instances WHERE instance_id = ?1",
608 params![instance_id],
609 |r| {
610 Ok(KnownInstance {
611 approved_at: r.get(0)?,
612 revoked_at: r.get(1)?,
613 revocation_checked_at: r.get(2)?,
614 })
615 },
616 )?)
617 }
618
619 pub fn known_instance_get(&self, instance_id: &str) -> Result<Option<KnownInstance>, StoreError> {
621 let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
622 match conn.query_row(
623 "SELECT approved_at, revoked_at, revocation_checked_at FROM wan_known_instances WHERE instance_id = ?1",
624 params![instance_id],
625 |r| Ok(KnownInstance { approved_at: r.get(0)?, revoked_at: r.get(1)?, revocation_checked_at: r.get(2)? }),
626 ) {
627 Ok(k) => Ok(Some(k)),
628 Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
629 Err(e) => Err(e.into()),
630 }
631 }
632
633 pub fn known_instance_record_revocation_check(
636 &self,
637 instance_id: &str,
638 revoked: bool,
639 now: i64,
640 ) -> Result<(), StoreError> {
641 let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
642 conn.execute(
643 "UPDATE wan_known_instances SET revocation_checked_at = ?2, \
644 revoked_at = CASE WHEN ?3 THEN COALESCE(revoked_at, ?2) ELSE revoked_at END \
645 WHERE instance_id = ?1",
646 params![instance_id, now, revoked],
647 )?;
648 Ok(())
649 }
650
651 pub fn seen_sig_contains(&self, instance_id: &str, agent_id: &str, msg_id: &str) -> Result<bool, StoreError> {
653 let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
654 Ok(conn
655 .query_row(
656 "SELECT 1 FROM wan_seen_sigs WHERE instance_id = ?1 AND agent_id = ?2 AND msg_id = ?3",
657 params![instance_id.to_lowercase(), agent_id.to_lowercase(), msg_id],
658 |_| Ok(()),
659 )
660 .optional()?
661 .is_some())
662 }
663
664 pub fn seen_sig_record(
669 &self,
670 instance_id: &str,
671 agent_id: &str,
672 msg_id: &str,
673 expires_at: i64,
674 now: i64,
675 ) -> Result<(), StoreError> {
676 let conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
677 conn.execute(
678 "INSERT OR IGNORE INTO wan_seen_sigs (instance_id, agent_id, msg_id, expires_at) VALUES (?1, ?2, ?3, ?4)",
679 params![instance_id.to_lowercase(), agent_id.to_lowercase(), msg_id, expires_at],
680 )?;
681 conn.execute("DELETE FROM wan_seen_sigs WHERE expires_at < ?1", params![now])?;
682 Ok(())
683 }
684
685 pub fn agent_keys_delete(&self, names: &[String]) -> Result<usize, StoreError> {
694 let mut conn = self.conn.lock().unwrap_or_else(|e| e.into_inner());
695 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
696 let now = agentmux_common::time::now_secs();
697 let mut removed = 0;
698 for name in names {
699 let name = name.to_lowercase();
700 Self::retire_agent_key_locked(&tx, &name, now)?;
701 removed += tx.execute("DELETE FROM wan_agent_keys WHERE agent_id = ?1", params![name])?;
702 }
703 tx.commit()?;
704 Ok(removed)
705 }
706}
707
708#[cfg(any(test, feature = "test-support"))]
712pub fn attach_temp_wan_identity(store: &super::store::Store) -> (tempfile::TempDir, std::sync::Arc<WanIdentityStore>) {
713 let dir = tempfile::tempdir().unwrap();
714 let wan = std::sync::Arc::new(WanIdentityStore::open(&dir.path().join("wan.db")).unwrap());
715 store.set_wan_identity(wan.clone());
716 (dir, wan)
717}
718
719#[cfg(test)]
720mod tests {
721 use super::*;
722 use std::sync::Arc;
723
724 fn temp_store() -> (tempfile::TempDir, WanIdentityStore) {
725 let dir = tempfile::tempdir().unwrap();
726 let store = WanIdentityStore::open(&dir.path().join("wan-identity").join("wan.db")).unwrap();
727 (dir, store)
728 }
729
730 #[test]
731 fn an_instance_is_minted_once_and_its_id_is_its_key_hash() {
732 let (_dir, store) = temp_store();
733 let first = store.instance_ensure("narko").unwrap();
734 assert_eq!(first.instance_id, agentmux_common::jekt_sign::wan_instance_id(&first.public_key));
735 assert_eq!(first.instance_id.len(), agentmux_common::jekt_sign::WAN_INSTANCE_ID_LEN);
736 assert_eq!(
737 agentmux_common::jekt_sign::generate_wan_keypair(first.private_key).0,
738 first.public_key,
739 "the stored private key must be the public key's seed"
740 );
741 assert_eq!(store.instance_ensure("narko").unwrap(), first);
742 }
743
744 #[test]
745 fn the_instance_survives_reopening_as_after_an_upgrade() {
746 let dir = tempfile::tempdir().unwrap();
748 let path = dir.path().join("wan.db");
749 let before = WanIdentityStore::open(&path).unwrap().instance_ensure("narko").unwrap();
750 let after = WanIdentityStore::open(&path).unwrap().instance_ensure("narko").unwrap();
751 assert_eq!(before, after);
752 }
753
754 #[test]
755 fn the_host_hint_is_fixed_at_mint_and_does_not_follow_a_rename() {
756 let (_dir, store) = temp_store();
757 let minted = store.instance_ensure("Narko").unwrap();
758 assert_eq!(minted.host_hint, "narko");
759 assert_eq!(store.instance_ensure("renamed-box").unwrap().host_hint, "narko");
760 }
761
762 #[test]
763 fn host_hints_are_sanitised_to_what_receivers_accept() {
764 assert_eq!(sanitize_host_hint("Narko"), "narko");
765 assert_eq!(sanitize_host_hint("DESKTOP_AB12 (2)"), "desktop-ab12--2-");
766 assert_eq!(sanitize_host_hint(""), "unknown");
767 assert_eq!(sanitize_host_hint(&"x".repeat(60)).len(), 48);
768 for host in ["Narko", "DESKTOP_AB12 (2)", "", "münchen", &"x".repeat(60)] {
769 assert!(agentmux_common::jekt_sign::is_valid_wan_host_hint(&sanitize_host_hint(host)), "{host:?}");
770 }
771 }
772
773 #[test]
774 fn two_processes_minting_at_once_converge_on_one_instance() {
775 let dir = tempfile::tempdir().unwrap();
776 let path = Arc::new(dir.path().join("wan.db"));
777 let handles: Vec<_> = (0..8)
779 .map(|i| {
780 let path = path.clone();
781 std::thread::spawn(move || {
782 WanIdentityStore::open(&path).unwrap().instance_ensure(&format!("host{i}")).unwrap().instance_id
783 })
784 })
785 .collect();
786 let ids: Vec<String> = handles.into_iter().map(|h| h.join().unwrap()).collect();
787 assert!(ids.windows(2).all(|w| w[0] == w[1]), "instances diverged: {ids:?}");
788 }
789
790 #[test]
791 fn two_processes_minting_one_agent_at_once_converge_on_one_key() {
792 let dir = tempfile::tempdir().unwrap();
793 let path = Arc::new(dir.path().join("wan.db"));
794 let handles: Vec<_> = (0..8)
795 .map(|_| {
796 let path = path.clone();
797 std::thread::spawn(move || {
798 WanIdentityStore::open(&path).unwrap().agent_key_ensure("camper", None).unwrap().public_key
799 })
800 })
801 .collect();
802 let keys: Vec<String> = handles.into_iter().map(|h| h.join().unwrap()).collect();
803 assert!(keys.windows(2).all(|w| w[0] == w[1]), "agent keys diverged");
804 }
805
806 #[test]
807 fn an_older_binary_opens_a_newer_file() {
808 let dir = tempfile::tempdir().unwrap();
809 let path = dir.path().join("wan.db");
810 {
811 let conn = Connection::open(&path).unwrap();
814 conn.execute_batch(SCHEMA).unwrap();
815 conn.execute_batch(
816 "INSERT INTO wan_meta (key, value) VALUES ('schema_version', 7);
817 CREATE TABLE wan_future (x INTEGER);
818 ALTER TABLE wan_agent_keys ADD COLUMN future_col TEXT;",
819 )
820 .unwrap();
821 }
822 let store = WanIdentityStore::open(&path).unwrap();
823 assert_eq!(store.schema_version().unwrap(), 7, "an older binary must not lower the stamp");
824 store.instance_ensure("narko").unwrap();
825 store.agent_key_ensure("camper", None).unwrap();
826 }
827
828 #[test]
829 fn a_store_that_cannot_open_is_an_error_not_a_fallback() {
830 let dir = tempfile::tempdir().unwrap();
831 let path = dir.path().join("wan.db");
833 std::fs::create_dir_all(&path).unwrap();
834 assert!(WanIdentityStore::open(&path).is_err());
835 assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1, "nothing minted elsewhere");
836 }
837
838 #[test]
839 fn an_agent_key_is_imported_once_then_kept() {
840 let (_dir, store) = temp_store();
841 let (public, private) = agentmux_common::jekt_sign::generate_wan_keypair([7; 32]);
842 let (public_b64, private_b64) = (BASE64.encode(public), BASE64.encode(private));
843 let imported = store.agent_key_ensure("Camper", Some((&public_b64, &private_b64))).unwrap();
844 assert!(imported.imported);
845 assert_eq!(imported.public_key, public_b64);
846
847 let (other_public, other_private) = agentmux_common::jekt_sign::generate_wan_keypair([8; 32]);
849 let again = store
850 .agent_key_ensure("camper", Some((&BASE64.encode(other_public), &BASE64.encode(other_private))))
851 .unwrap();
852 assert_eq!(again, imported);
853 }
854
855 #[test]
856 fn a_malformed_or_mismatched_import_is_minted_over() {
857 let (_dir, store) = temp_store();
858 let (public, _) = agentmux_common::jekt_sign::generate_wan_keypair([7; 32]);
859 let (_, other_private) = agentmux_common::jekt_sign::generate_wan_keypair([8; 32]);
860 let key = store
861 .agent_key_ensure("camper", Some((&BASE64.encode(public), &BASE64.encode(other_private))))
862 .unwrap();
863 assert!(!key.imported);
864 assert_ne!(key.public_key, BASE64.encode(public));
865 let key2 = store.agent_key_ensure("lark", Some(("not base64", "x"))).unwrap();
866 assert!(!key2.imported);
867 }
868
869 #[test]
870 fn deleting_an_agents_keys_lets_a_new_agent_of_that_name_get_a_new_key() {
871 let (_dir, store) = temp_store();
872 let old = store.agent_key_ensure("camper", None).unwrap();
873 store.agent_key_ensure("lark", None).unwrap();
874 assert_eq!(store.agent_keys_delete(&["Camper".to_string(), "nobody".to_string()]).unwrap(), 1);
875 assert!(store.agent_key_load("camper").unwrap().is_none());
876 assert!(store.agent_key_load("lark").unwrap().is_some(), "other agents are untouched");
877 assert_ne!(store.agent_key_ensure("camper", None).unwrap().public_key, old.public_key);
878 }
879
880 #[test]
881 fn a_key_published_to_one_directory_is_pending_in_another() {
882 let (_dir, store) = temp_store();
886 let camper = store.agent_key_ensure("camper", None).unwrap();
887 let (old, new) = ("https://relay#old-account", "https://relay#new-account");
888 assert!(store.agent_key_mark_published("camper", &camper.public_key, old).unwrap());
889
890 assert!(store.agent_keys_unpublished(old).unwrap().is_empty());
891 assert!(store.agent_key_is_published_to("camper", &camper, old).unwrap());
892 let pending: Vec<String> = store.agent_keys_unpublished(new).unwrap().into_iter().map(|(id, _)| id).collect();
893 assert_eq!(pending, vec!["camper".to_string()]);
894 assert!(!store.agent_key_is_published_to("camper", &camper, new).unwrap());
895
896 assert!(store.agent_key_mark_published("camper", &camper.public_key, new).unwrap());
897 assert!(store.agent_keys_unpublished(new).unwrap().is_empty());
898 assert!(store.agent_key_is_published_to("Camper", &camper, old).unwrap(), "the old mark stays: case-insensitive, both directories hold it");
899 }
900
901 #[test]
902 fn a_publication_that_returns_after_a_sign_in_marks_the_directory_it_went_to() {
903 let (_dir, store) = temp_store();
908 let camper = store.agent_key_ensure("camper", None).unwrap();
909 let (old, new) = ("https://relay#old-account", "https://relay#new-account");
910 let other = WanIdentityStore::open(&_dir.path().join("wan-identity").join("wan.db")).unwrap();
912 assert!(other.agent_key_mark_published("camper", &camper.public_key, old).unwrap());
913 assert_eq!(store.agent_keys_unpublished(new).unwrap().len(), 1);
914 }
915
916 #[test]
917 fn marks_written_before_v3_count_for_no_directory() {
918 let (_dir, store) = temp_store();
921 let camper = store.agent_key_ensure("camper", None).unwrap();
922 {
923 let conn = store.conn.lock().unwrap();
924 conn.execute("UPDATE wan_agent_keys SET published_fp = 'x', published_at = 1 WHERE agent_id = 'camper'", []).unwrap();
925 }
926 assert_eq!(store.agent_keys_unpublished("https://relay#acct").unwrap().len(), 1);
927 assert!(!store.agent_key_is_published_to("camper", &camper, "https://relay#acct").unwrap());
928 assert_eq!(store.schema_version().unwrap(), 5);
929 }
930
931 #[test]
932 fn debug_output_never_contains_a_private_key() {
933 let (_dir, store) = temp_store();
934 let instance = store.instance_ensure("narko").unwrap();
935 let agent = store.agent_key_ensure("camper", None).unwrap();
936 assert!(!format!("{instance:?}").contains(&BASE64.encode(instance.private_key)));
937 assert!(!format!("{agent:?}").contains(&agent.private_key));
938 }
939
940 #[cfg(unix)]
941 #[test]
942 fn the_file_is_owner_only() {
943 use std::os::unix::fs::PermissionsExt;
944 let (dir, _store) = temp_store();
945 let file = dir.path().join("wan-identity").join("wan.db");
946 assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600);
947 }
948}