Skip to main content

agentmux_srv_core/muxbus/
wan_publish.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Publish each agent's WAN key to the account's cloud key directory,
5//! certified by this install's instance key
6//! (`SPEC_WAN_JEKT_VERIFICATION_2026_09_24.md` §2.2, step D1b).
7//!
8//! A receiver can verify a WAN jekt only against a key it can fetch, and it
9//! trusts that key only because this install's instance key signed it — so
10//! the directory never has to be trusted, only reachable. The cloud checks
11//! the same chain on `PUT` (hygiene); the receiver checks it again.
12//!
13//! **When.** The spawn path nudges the publisher after it provisions a key
14//! ([`nudge`]); a background loop also re-runs every [`RETRY_SECS`] so a key
15//! that failed to publish (logged out, cloud down) is retried, and every
16//! [`IDLE_RECHECK_SECS`] when idle, because a sign-in in another channel can
17//! change the directory without nudging this process. A cloud that
18//! answers 404 predates the directory (C1 not deployed): retried at most
19//! hourly, never hot.
20//!
21//! **Which token.** The shared account token (`load_valid_token`), not a
22//! per-agent M2M token — a per-agent client may be unowned, and the
23//! directory is keyed by account.
24//!
25//! **Retired keys.** When this install replaces an agent's key, `wan.db` writes
26//! down a retirement for each directory that held the old one
27//! (`wan_identity::revocations`). The same pass signs a
28//! [`WanKeyRevocation`] for each with the instance key and puts it there, and the
29//! retirement goes once the directory has it. The revocation is also kept
30//! locally at once, so this install refuses the old key even while the
31//! directory is out of reach.
32//!
33//! Nothing here ever makes a jekt fail: until a key is confirmed published,
34//! the relay simply sends that agent's jekts unsigned
35//! (`relay::wan_sign_at_origin`, condition 2).
36
37use std::sync::{Arc, OnceLock};
38use std::time::Duration;
39
40use agentmux_common::jekt_sign::WanKeyRecord;
41use crate::muxbus::wan_key_revocation::WanKeyRevocation;
42
43use crate::backend::storage::store::Store;
44use crate::backend::storage::wan_identity::{WanAgentKey, WanIdentityStore, WanInstance};
45
46/// Background retry interval while any key is unpublished.
47const RETRY_SECS: u64 = 5 * 60;
48
49/// Retry interval after the cloud said it has no directory (HTTP 404).
50const NOT_SUPPORTED_RETRY_SECS: u64 = 60 * 60;
51
52/// How often an idle publisher looks again. A sign-in in another channel
53/// (the MuxBus login is shared) changes the directory this one should
54/// publish to, but only nudges its own process (Codex P2 on #3994), so an
55/// idle publisher can't wait on nudges alone.
56const IDLE_RECHECK_SECS: u64 = 5 * 60;
57
58const PUBLISH_TIMEOUT_SECS: u64 = 10;
59
60/// Which directory a publication is for: the relay's REST base plus the
61/// account (the token's `sub`). The directory is keyed by account, and a
62/// relay move or a sign-in to another account is a directory that has never
63/// seen this install's keys — so `wan.db` records publications per this id,
64/// and a key counts as published only to the directory it went to.
65pub fn directory_id(base_url: &str, account_sub: &str) -> String {
66    format!("{}#{}", base_url.trim_end_matches('/'), account_sub)
67}
68
69static NUDGE: OnceLock<Arc<tokio::sync::Notify>> = OnceLock::new();
70
71fn nudge_handle() -> Arc<tokio::sync::Notify> {
72    NUDGE.get_or_init(|| Arc::new(tokio::sync::Notify::new())).clone()
73}
74
75/// Ask the publisher to run a pass soon — called by the spawn path after it
76/// provisions an agent's WAN key. Cheap and safe to call with no publisher
77/// running.
78pub fn nudge() {
79    nudge_handle().notify_one();
80}
81
82/// This agent key's directory record, certified by the instance. Channel is
83/// the one the agent signs as (`AGENTMUX_CHANNEL`, `local_channel_id`), and
84/// `issued_at` is the key's creation time, so the same key always yields the
85/// same record.
86pub(crate) fn certify(
87    instance: &WanInstance,
88    agent_id: &str,
89    channel: &str,
90    key: &WanAgentKey,
91) -> Option<WanKeyRecord> {
92    WanKeyRecord::certify(
93        &instance.private_key,
94        agent_id,
95        channel,
96        &key.public_key_bytes()?,
97        &instance.host_hint,
98        key.created_at,
99    )
100}
101
102#[derive(Debug, PartialEq, Eq)]
103pub(crate) enum PublishOutcome {
104    Published,
105    /// HTTP 404: this cloud has no key directory yet.
106    NotSupported,
107    Failed(String),
108}
109
110/// `PUT /agents/:agent_id/wan-key`. A pure HTTP operation, like
111/// `relay::relay_inject`, so tests can point it at a stub.
112pub(crate) async fn publish_record(
113    base_url: &str,
114    http: &reqwest::Client,
115    token: &str,
116    record: &WanKeyRecord,
117) -> PublishOutcome {
118    let url = format!("{}/agents/{}/wan-key", base_url.trim_end_matches('/'), record.agent_id);
119    let resp = http
120        .put(&url)
121        .header("Authorization", format!("Bearer {token}"))
122        .timeout(Duration::from_secs(PUBLISH_TIMEOUT_SECS))
123        .json(record)
124        .send()
125        .await;
126    match resp {
127        Ok(r) if r.status().is_success() => PublishOutcome::Published,
128        Ok(r) if r.status() == reqwest::StatusCode::NOT_FOUND => PublishOutcome::NotSupported,
129        Ok(r) => {
130            let status = r.status();
131            PublishOutcome::Failed(format!("HTTP {status}: {}", r.text().await.unwrap_or_default()))
132        }
133        Err(e) => PublishOutcome::Failed(format!("unreachable: {e}")),
134    }
135}
136
137/// `PUT /agents/:agent_id/wan-key/revocation`: tell the directory a key was
138/// retired. The same outcomes as [`publish_record`]; a 404 here means the
139/// cloud has no revocation route (it may still have the key directory).
140pub(crate) async fn publish_revocation(
141    base_url: &str,
142    http: &reqwest::Client,
143    token: &str,
144    revocation: &WanKeyRevocation,
145) -> PublishOutcome {
146    let url = format!("{}/agents/{}/wan-key/revocation", base_url.trim_end_matches('/'), revocation.agent_id);
147    let resp = http
148        .put(&url)
149        .header("Authorization", format!("Bearer {token}"))
150        .timeout(Duration::from_secs(PUBLISH_TIMEOUT_SECS))
151        .json(revocation)
152        .send()
153        .await;
154    match resp {
155        Ok(r) if r.status().is_success() => PublishOutcome::Published,
156        Ok(r) if r.status() == reqwest::StatusCode::NOT_FOUND => PublishOutcome::NotSupported,
157        Ok(r) => {
158            let status = r.status();
159            PublishOutcome::Failed(format!("HTTP {status}: {}", r.text().await.unwrap_or_default()))
160        }
161        Err(e) => PublishOutcome::Failed(format!("unreachable: {e}")),
162    }
163}
164
165/// Result of one pass over the unpublished keys and the retired ones.
166#[derive(Debug, Default, PartialEq, Eq)]
167pub(crate) struct PassResult {
168    pub published: usize,
169    /// Retired keys the directory now has the revocation of.
170    pub revoked: usize,
171    pub not_supported: bool,
172    /// The cloud has the key directory but no revocation route: retirements
173    /// wait, and are tried again hourly.
174    pub revocations_not_supported: bool,
175    pub failed: usize,
176    /// Keys still unpublished, and retirements still owed, after the pass.
177    pub remaining: usize,
178}
179
180/// Tell `directory` about every key this install retired that it held. Each
181/// revocation is kept locally before it is sent. Stops at the first 404.
182#[allow(clippy::too_many_arguments)]
183async fn publish_retirements(
184    wan: &WanIdentityStore,
185    instance: &WanInstance,
186    channel: &str,
187    base_url: &str,
188    http: &reqwest::Client,
189    token: &str,
190    directory: &str,
191    result: &mut PassResult,
192) {
193    let pending = match wan.retirements_pending(directory) {
194        Ok(p) => p,
195        Err(e) => {
196            tracing::warn!(error = %e, "wan publish: could not read retired keys from wan.db");
197            result.failed += 1;
198            return;
199        }
200    };
201    for retirement in pending {
202        let Some(revocation) =
203            WanKeyRevocation::sign(&instance.private_key, &retirement.agent_id, channel, &retirement.key_fp, retirement.retired_at)
204        else {
205            tracing::warn!(agent = %retirement.agent_id, "wan publish: could not sign a key revocation — skipped");
206            result.failed += 1;
207            continue;
208        };
209        if let Err(e) = wan.revoked_key_put(&revocation, agentmux_common::time::now_secs()) {
210            tracing::warn!(agent = %retirement.agent_id, error = %e, "wan publish: could not keep a key revocation locally");
211        }
212        match publish_revocation(base_url, http, token, &revocation).await {
213            PublishOutcome::Published => match wan.retirement_done(&retirement.agent_id, &retirement.key_fp, directory) {
214                Ok(()) => result.revoked += 1,
215                Err(e) => {
216                    tracing::warn!(agent = %retirement.agent_id, error = %e, "wan publish: could not record a revocation as sent");
217                    result.failed += 1;
218                }
219            },
220            PublishOutcome::NotSupported => {
221                result.revocations_not_supported = true;
222                return;
223            }
224            PublishOutcome::Failed(e) => {
225                tracing::warn!(agent = %retirement.agent_id, error = %e, "wan publish: directory rejected or unreachable for a key revocation");
226                result.failed += 1;
227            }
228        }
229    }
230}
231
232/// Publish every key `wan` doesn't yet have confirmed. Stops at the first
233/// 404 — the whole directory is missing, not one record.
234pub(crate) async fn publish_pending(
235    wan: &WanIdentityStore,
236    instance: &WanInstance,
237    channel: &str,
238    base_url: &str,
239    http: &reqwest::Client,
240    token: &str,
241    directory: &str,
242) -> PassResult {
243    let pending = match wan.agent_keys_unpublished(directory) {
244        Ok(p) => p,
245        Err(e) => {
246            tracing::warn!(error = %e, "wan publish: could not read wan.db");
247            return PassResult { failed: 1, ..Default::default() };
248        }
249    };
250    let mut result = PassResult::default();
251    // Retired keys first: a key that should no longer be trusted is the more urgent news.
252    publish_retirements(wan, instance, channel, base_url, http, token, directory, &mut result).await;
253    for (agent_id, key) in &pending {
254        let Some(record) = certify(instance, agent_id, channel, key) else {
255            tracing::warn!(agent = %agent_id, "wan publish: malformed key in wan.db — skipped");
256            result.failed += 1;
257            continue;
258        };
259        match publish_record(base_url, http, token, &record).await {
260            // Marked for `directory`, the one this PUT went to, even if a
261            // sign-in to another account has landed since: the new directory
262            // still sees the key as pending.
263            PublishOutcome::Published => match wan.agent_key_mark_published(agent_id, &key.public_key, directory) {
264                Ok(true) => result.published += 1,
265                // The key changed under us (agent deleted and recreated
266                // mid-PUT); the new key is picked up next pass. The directory
267                // took the old one all the same, and nothing else knows it
268                // did, so it is retired for this directory now.
269                Ok(false) => {
270                    if let Err(e) = wan.retirement_add(agent_id, &key.public_key, directory, agentmux_common::time::now_secs()) {
271                        tracing::warn!(agent = %agent_id, error = %e, "wan publish: could not retire a key replaced mid-publish");
272                        result.failed += 1;
273                    }
274                }
275                Err(e) => {
276                    tracing::warn!(agent = %agent_id, error = %e, "wan publish: could not record publication");
277                    result.failed += 1;
278                }
279            },
280            PublishOutcome::NotSupported => {
281                result.not_supported = true;
282                break;
283            }
284            PublishOutcome::Failed(e) => {
285                tracing::warn!(agent = %agent_id, error = %e, "wan publish: directory rejected or unreachable");
286                result.failed += 1;
287            }
288        }
289    }
290    result.remaining = wan.agent_keys_unpublished(directory).map(|p| p.len()).unwrap_or(pending.len());
291    if !result.revocations_not_supported {
292        result.remaining += wan.retirements_pending(directory).map(|p| p.len()).unwrap_or(0);
293    }
294    result
295}
296
297/// Start the background publisher. No-op without a `wan.db`. Runs a pass on
298/// start, on every [`nudge`], every [`RETRY_SECS`] while keys remain, and every
299/// [`IDLE_RECHECK_SECS`] when none do;
300/// after a 404 it waits [`NOT_SUPPORTED_RETRY_SECS`] (nudges included, so a
301/// burst of spawns can't turn an old cloud into a hot loop).
302pub fn spawn(mstore: Arc<Store>, id_store: Arc<Store>) {
303    let Some(wan) = mstore.wan_identity() else { return };
304    let notify = nudge_handle();
305    tokio::spawn(async move {
306        let http = crate::http_client::client();
307        loop {
308            let wait = run_pass(&wan, &id_store, &http).await;
309            match wait {
310                Wait::NotSupported => tokio::time::sleep(Duration::from_secs(NOT_SUPPORTED_RETRY_SECS)).await,
311                Wait::Retry => {
312                    tokio::select! {
313                        _ = notify.notified() => {}
314                        _ = tokio::time::sleep(Duration::from_secs(RETRY_SECS)) => {}
315                    }
316                }
317                Wait::Idle => {
318                    tokio::select! {
319                        _ = notify.notified() => {}
320                        _ = tokio::time::sleep(Duration::from_secs(IDLE_RECHECK_SECS)) => {}
321                    }
322                }
323            }
324        }
325    });
326}
327
328enum Wait {
329    /// Everything is published to the current directory: sleep until a
330    /// nudge, or [`IDLE_RECHECK_SECS`] in case the account changed elsewhere.
331    Idle,
332    Retry,
333    NotSupported,
334}
335
336async fn run_pass(wan: &Arc<WanIdentityStore>, id_store: &Arc<Store>, http: &reqwest::Client) -> Wait {
337    let instance = match wan.instance_ensure(&crate::backend::reactive::registry::local_host_label()) {
338        Ok(i) => i,
339        Err(e) => {
340            tracing::warn!(error = %e, "wan publish: no instance");
341            return Wait::Retry;
342        }
343    };
344    let Some(scheduler) = crate::broker::get_global() else { return Wait::Retry };
345    let Some(token) = crate::muxbus::cloud_subscriber::load_valid_token(id_store, &scheduler).await else {
346        tracing::debug!("wan publish: not logged in to muxbus — keys stay unpublished");
347        return Wait::Retry;
348    };
349    let account = crate::muxbus::pkce::token_sub(&token);
350    if account.is_empty() {
351        tracing::warn!("wan publish: the account token names no account — keys stay unpublished");
352        return Wait::Retry;
353    }
354    let base_url = crate::muxbus::relay::rest_base_url();
355    let directory = directory_id(&base_url, &account);
356    let nothing_owed = wan.agent_keys_unpublished(&directory).map(|p| p.is_empty()).unwrap_or(false)
357        && wan.retirements_pending(&directory).map(|p| p.is_empty()).unwrap_or(false);
358    if nothing_owed {
359        return Wait::Idle;
360    }
361    let result = publish_pending(
362        wan,
363        &instance,
364        &crate::backend::reactive::registry::local_channel_id(),
365        &base_url,
366        http,
367        &token,
368        &directory,
369    )
370    .await;
371    if result.published > 0 {
372        tracing::info!(published = result.published, instance = %instance.instance_id, "wan publish: agent keys published");
373    }
374    if result.revoked > 0 {
375        tracing::info!(revoked = result.revoked, instance = %instance.instance_id, "wan publish: retired agent keys revoked");
376    }
377    if result.not_supported {
378        tracing::info!("wan publish: cloud has no WAN key directory yet — retrying hourly");
379        Wait::NotSupported
380    } else if result.remaining > 0 {
381        Wait::Retry
382    } else if result.revocations_not_supported {
383        tracing::info!("wan publish: cloud has no key revocation route yet — retrying hourly");
384        Wait::NotSupported
385    } else {
386        Wait::Idle
387    }
388}
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393
394    /// (agent id from the path, Authorization header, body) per PUT.
395    type Seen = Vec<(String, Option<String>, serde_json::Value)>;
396
397    struct Stub {
398        seen: Arc<std::sync::Mutex<Seen>>,
399        /// The same, for `PUT /agents/:agent_id/wan-key/revocation`.
400        revoked: Arc<std::sync::Mutex<Seen>>,
401        _guard: tokio_util::sync::DropGuard,
402        url: String,
403    }
404
405    /// A stub directory that answers `status` to every PUT and records it.
406    async fn stub_directory(status: axum::http::StatusCode) -> Stub {
407        stub_with_revocations(status, axum::http::StatusCode::OK).await
408    }
409
410    /// As [`stub_directory`], answering `revocation_status` to a key revocation.
411    async fn stub_with_revocations(status: axum::http::StatusCode, revocation_status: axum::http::StatusCode) -> Stub {
412        stub_full(status, revocation_status, None).await
413    }
414
415    /// As [`stub_with_revocations`], running `during_put` while a key PUT is in flight.
416    async fn stub_full(
417        status: axum::http::StatusCode,
418        revocation_status: axum::http::StatusCode,
419        during_put: Option<Arc<dyn Fn() + Send + Sync>>,
420    ) -> Stub {
421        let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
422        let revoked = Arc::new(std::sync::Mutex::new(Vec::new()));
423        let (sink, revoked_sink) = (seen.clone(), revoked.clone());
424        let app = axum::Router::new()
425            .route(
426                "/agents/:agent_id/wan-key",
427                axum::routing::put(
428                    move |axum::extract::Path(agent_id): axum::extract::Path<String>,
429                          headers: axum::http::HeaderMap,
430                          body: axum::Json<serde_json::Value>| {
431                        let sink = sink.clone();
432                        let during_put = during_put.clone();
433                        async move {
434                            let auth = headers.get("authorization").and_then(|v| v.to_str().ok()).map(str::to_string);
435                            sink.lock().unwrap().push((agent_id, auth, body.0));
436                            if let Some(hook) = &during_put {
437                                hook();
438                            }
439                            (status, "{}")
440                        }
441                    },
442                ),
443            )
444            .route(
445                "/agents/:agent_id/wan-key/revocation",
446                axum::routing::put(
447                    move |axum::extract::Path(agent_id): axum::extract::Path<String>,
448                          headers: axum::http::HeaderMap,
449                          body: axum::Json<serde_json::Value>| {
450                        let sink = revoked_sink.clone();
451                        async move {
452                            let auth = headers.get("authorization").and_then(|v| v.to_str().ok()).map(str::to_string);
453                            sink.lock().unwrap().push((agent_id, auth, body.0));
454                            (revocation_status, "{}")
455                        }
456                    },
457                ),
458            );
459        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
460        let addr = listener.local_addr().unwrap();
461        let token = tokio_util::sync::CancellationToken::new();
462        let child = token.clone();
463        tokio::spawn(async move {
464            let _ = axum::serve(listener, app).with_graceful_shutdown(async move { child.cancelled().await }).await;
465        });
466        Stub { seen, revoked, _guard: token.drop_guard(), url: format!("http://{addr}") }
467    }
468
469    const DIR: &str = "https://relay.test#acct";
470
471    fn published(wan: &WanIdentityStore, agent_id: &str, directory: &str) -> bool {
472        let key = wan.agent_key_load(agent_id).unwrap().unwrap();
473        wan.agent_key_is_published_to(agent_id, &key, directory).unwrap()
474    }
475
476    fn temp_wan() -> (tempfile::TempDir, WanIdentityStore, WanInstance) {
477        let dir = tempfile::tempdir().unwrap();
478        let wan = WanIdentityStore::open(&dir.path().join("wan.db")).unwrap();
479        let instance = wan.instance_ensure("narko").unwrap();
480        (dir, wan, instance)
481    }
482
483    #[test]
484    fn a_certified_record_passes_the_chain_and_is_stable_across_calls() {
485        let (_dir, wan, instance) = temp_wan();
486        let key = wan.agent_key_ensure("Camper", None).unwrap();
487        let record = certify(&instance, "camper", "stable", &key).unwrap();
488        assert!(record.check_chain().is_some());
489        assert_eq!(record.instance_id, instance.instance_id);
490        assert_eq!(record.issued_at, key.created_at);
491        assert_eq!(record.host_hint, "narko");
492        assert_eq!(certify(&instance, "camper", "stable", &key), Some(record), "same key → same record");
493    }
494
495    #[tokio::test]
496    async fn a_pass_publishes_every_pending_key_and_marks_it() {
497        let stub = stub_directory(axum::http::StatusCode::OK).await;
498        let (_dir, wan, instance) = temp_wan();
499        wan.agent_key_ensure("camper", None).unwrap();
500        wan.agent_key_ensure("lark", None).unwrap();
501
502        let result = publish_pending(&wan, &instance, "stable", &stub.url, &reqwest::Client::new(), "tok", DIR).await;
503        assert_eq!(result, PassResult { published: 2, remaining: 0, ..Default::default() });
504        assert!(published(&wan, "camper", DIR));
505
506        let seen = stub.seen.lock().unwrap().clone();
507        assert_eq!(seen.len(), 2);
508        for (agent_id, auth, body) in seen {
509            assert_eq!(auth.as_deref(), Some("Bearer tok"));
510            let record: WanKeyRecord = serde_json::from_value(body).unwrap();
511            assert_eq!(record.agent_id, agent_id, "the path names the record's agent");
512            assert!(record.check_chain().is_some(), "what goes on the wire passes the cloud's chain check");
513            assert_eq!(record.channel, "stable");
514        }
515
516        // Nothing left: a second pass sends nothing.
517        let again = publish_pending(&wan, &instance, "stable", &stub.url, &reqwest::Client::new(), "tok", DIR).await;
518        assert_eq!(again, PassResult::default());
519        assert_eq!(stub.seen.lock().unwrap().len(), 2);
520    }
521
522    #[tokio::test]
523    async fn a_404_means_no_directory_and_stops_the_pass() {
524        let stub = stub_directory(axum::http::StatusCode::NOT_FOUND).await;
525        let (_dir, wan, instance) = temp_wan();
526        wan.agent_key_ensure("camper", None).unwrap();
527        wan.agent_key_ensure("lark", None).unwrap();
528        let result = publish_pending(&wan, &instance, "stable", &stub.url, &reqwest::Client::new(), "tok", DIR).await;
529        assert!(result.not_supported);
530        assert_eq!(result.remaining, 2);
531        assert_eq!(stub.seen.lock().unwrap().len(), 1, "one 404 is enough to know");
532    }
533
534    #[tokio::test]
535    async fn a_rejection_leaves_the_key_unpublished_for_the_next_pass() {
536        let stub = stub_directory(axum::http::StatusCode::BAD_REQUEST).await;
537        let (_dir, wan, instance) = temp_wan();
538        wan.agent_key_ensure("camper", None).unwrap();
539        let result = publish_pending(&wan, &instance, "stable", &stub.url, &reqwest::Client::new(), "tok", DIR).await;
540        assert_eq!(result, PassResult { failed: 1, remaining: 1, ..Default::default() });
541        assert!(!published(&wan, "camper", DIR));
542    }
543
544    #[tokio::test]
545    async fn an_unreachable_directory_is_a_failure_not_a_hang() {
546        let url = {
547            let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
548            format!("http://{}", l.local_addr().unwrap())
549        };
550        let (_dir, wan, instance) = temp_wan();
551        wan.agent_key_ensure("camper", None).unwrap();
552        let result = publish_pending(&wan, &instance, "stable", &url, &reqwest::Client::new(), "tok", DIR).await;
553        assert_eq!(result.failed, 1);
554        assert_eq!(result.remaining, 1);
555    }
556
557    #[test]
558    fn a_publication_marks_only_the_key_it_was_for() {
559        let (_dir, wan, _instance) = temp_wan();
560        let old = wan.agent_key_ensure("camper", None).unwrap();
561        // Agent deleted and recreated while the PUT was in flight.
562        wan.agent_keys_delete(&["camper".to_string()]).unwrap();
563        let new = wan.agent_key_ensure("camper", None).unwrap();
564        assert!(!wan.agent_key_mark_published("camper", &old.public_key, DIR).unwrap());
565        assert!(!published(&wan, "camper", DIR));
566        assert!(wan.agent_key_mark_published("camper", &new.public_key, DIR).unwrap());
567        assert!(published(&wan, "camper", DIR));
568    }
569
570    #[tokio::test]
571    async fn a_sign_in_to_another_account_publishes_every_key_again() {
572        // The relay moved (or the user signed in to another account): the
573        // new directory has never seen these keys. Before directory-bound
574        // marks, the old marks made this pass a no-op and every jekt from
575        // here arrived unverified.
576        let stub = stub_directory(axum::http::StatusCode::OK).await;
577        let (_dir, wan, instance) = temp_wan();
578        wan.agent_key_ensure("camper", None).unwrap();
579        let old = directory_id(&stub.url, "old-account");
580        let new = directory_id(&stub.url, "new-account");
581        let first = publish_pending(&wan, &instance, "stable", &stub.url, &reqwest::Client::new(), "tok", &old).await;
582        assert_eq!(first.published, 1);
583
584        let second = publish_pending(&wan, &instance, "stable", &stub.url, &reqwest::Client::new(), "tok2", &new).await;
585        assert_eq!(second, PassResult { published: 1, remaining: 0, ..Default::default() });
586        assert!(published(&wan, "camper", &new));
587        assert!(published(&wan, "camper", &old), "the old directory's record stays true");
588        assert_eq!(stub.seen.lock().unwrap().len(), 2);
589    }
590
591    /// camper's key is published to `DIR`, then replaced by a new one.
592    fn replaced_after_publishing(wan: &WanIdentityStore) -> String {
593        let old = wan.agent_key_ensure("camper", None).unwrap();
594        assert!(wan.agent_key_mark_published("camper", &old.public_key, DIR).unwrap());
595        let fp = agentmux_common::jekt_sign::wan_key_fingerprint(&old.public_key_bytes().unwrap());
596        wan.agent_keys_delete(&["camper".to_string()]).unwrap();
597        wan.agent_key_ensure("camper", None).unwrap();
598        fp
599    }
600
601    #[tokio::test]
602    async fn a_replaced_key_is_revoked_at_the_directory_that_held_it() {
603        let stub = stub_directory(axum::http::StatusCode::OK).await;
604        let (_dir, wan, instance) = temp_wan();
605        let old_fp = replaced_after_publishing(&wan);
606
607        let result = publish_pending(&wan, &instance, "stable", &stub.url, &reqwest::Client::new(), "tok", DIR).await;
608        assert_eq!(result, PassResult { published: 1, revoked: 1, remaining: 0, ..Default::default() });
609
610        let sent = stub.revoked.lock().unwrap().clone();
611        assert_eq!(sent.len(), 1);
612        let (agent_id, auth, body) = sent[0].clone();
613        assert_eq!((agent_id.as_str(), auth.as_deref()), ("camper", Some("Bearer tok")));
614        let revocation: WanKeyRevocation = serde_json::from_value(body).unwrap();
615        assert!(revocation.verify(), "what goes on the wire passes the cloud's check");
616        assert!(revocation.names(&instance.instance_id, "camper", "stable", &old_fp));
617        assert!(wan.retirements_pending(DIR).unwrap().is_empty());
618        assert!(wan.revoked_key_exists(&instance.instance_id, "camper", "stable", &old_fp).unwrap(), "refused here too");
619        // The new key is not the revoked one.
620        let current = wan.agent_key_load("camper").unwrap().unwrap();
621        let current_fp = agentmux_common::jekt_sign::wan_key_fingerprint(&current.public_key_bytes().unwrap());
622        assert!(!wan.revoked_key_exists(&instance.instance_id, "camper", "stable", &current_fp).unwrap());
623
624        // Nothing is owed any more: a second pass sends nothing.
625        let again = publish_pending(&wan, &instance, "stable", &stub.url, &reqwest::Client::new(), "tok", DIR).await;
626        assert_eq!(again, PassResult::default());
627        assert_eq!(stub.revoked.lock().unwrap().len(), 1);
628    }
629
630    #[tokio::test]
631    async fn a_revocation_that_failed_is_sent_again_unchanged() {
632        let down = stub_with_revocations(axum::http::StatusCode::OK, axum::http::StatusCode::SERVICE_UNAVAILABLE).await;
633        let up = stub_directory(axum::http::StatusCode::OK).await;
634        let (_dir, wan, instance) = temp_wan();
635        replaced_after_publishing(&wan);
636
637        let first = publish_pending(&wan, &instance, "stable", &down.url, &reqwest::Client::new(), "tok", DIR).await;
638        assert_eq!(first.revoked, 0);
639        assert_eq!(first.failed, 1);
640        assert_eq!(first.remaining, 1, "still owed");
641        assert_eq!(wan.retirements_pending(DIR).unwrap().len(), 1);
642
643        let second = publish_pending(&wan, &instance, "stable", &up.url, &reqwest::Client::new(), "tok", DIR).await;
644        assert_eq!(second.revoked, 1);
645        assert_eq!(second.remaining, 0);
646        assert_eq!(down.revoked.lock().unwrap()[0].2, up.revoked.lock().unwrap()[0].2, "the same signed record, not a new one");
647    }
648
649    #[tokio::test]
650    async fn this_install_refuses_the_retired_key_even_when_the_directory_cannot_be_reached() {
651        let url = {
652            let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
653            format!("http://{}", l.local_addr().unwrap())
654        };
655        let (_dir, wan, instance) = temp_wan();
656        let old_fp = replaced_after_publishing(&wan);
657        let result = publish_pending(&wan, &instance, "stable", &url, &reqwest::Client::new(), "tok", DIR).await;
658        assert!(result.failed >= 1);
659        assert_eq!(wan.retirements_pending(DIR).unwrap().len(), 1, "still owed to the directory");
660        assert!(wan.revoked_key_exists(&instance.instance_id, "camper", "stable", &old_fp).unwrap());
661    }
662
663    #[tokio::test]
664    async fn a_key_replaced_while_its_first_publish_is_in_flight_is_still_revoked() {
665        let (_dir, wan, instance) = temp_wan();
666        let wan = Arc::new(wan);
667        let first = wan.agent_key_ensure("camper", None).unwrap();
668        let sent_fp = agentmux_common::jekt_sign::wan_key_fingerprint(&first.public_key_bytes().unwrap());
669        // The agent is deleted after the directory has the PUT, before the
670        // publisher can record it.
671        let hook_wan = wan.clone();
672        let hook: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
673            hook_wan.agent_keys_delete(&["camper".to_string()]).unwrap();
674        });
675        let stub = stub_full(axum::http::StatusCode::OK, axum::http::StatusCode::OK, Some(hook)).await;
676
677        let pass = publish_pending(&wan, &instance, "stable", &stub.url, &reqwest::Client::new(), "tok", DIR).await;
678        assert_eq!(pass.published, 0, "the key it published is gone, so nothing counts as published");
679        let owed = wan.retirements_pending(DIR).unwrap();
680        assert_eq!(owed.len(), 1, "the directory holds a key that must be retired");
681        assert_eq!(owed[0].key_fp, sent_fp);
682
683        let next = publish_pending(&wan, &instance, "stable", &stub.url, &reqwest::Client::new(), "tok", DIR).await;
684        assert_eq!(next.revoked, 1);
685        let sent = stub.revoked.lock().unwrap().clone();
686        let revocation: WanKeyRevocation = serde_json::from_value(sent[0].2.clone()).unwrap();
687        assert!(revocation.verify() && revocation.names(&instance.instance_id, "camper", "stable", &sent_fp));
688    }
689
690    #[tokio::test]
691    async fn a_rotation_done_offline_is_revoked_after_a_restart() {
692        let dir = tempfile::tempdir().unwrap();
693        let path = dir.path().join("wan.db");
694        let old_fp;
695        let instance_id;
696        {
697            // Rotated while the relay cannot be reached: nothing is delivered.
698            let url = {
699                let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
700                format!("http://{}", l.local_addr().unwrap())
701            };
702            let wan = WanIdentityStore::open(&path).unwrap();
703            let instance = wan.instance_ensure("narko").unwrap();
704            instance_id = instance.instance_id.clone();
705            old_fp = replaced_after_publishing(&wan);
706            let offline = publish_pending(&wan, &instance, "stable", &url, &reqwest::Client::new(), "tok", DIR).await;
707            assert_eq!(offline.revoked, 0);
708        } // the process ends: the store is closed
709
710        let wan = WanIdentityStore::open(&path).unwrap();
711        let instance = wan.instance_ensure("narko").unwrap();
712        assert_eq!(instance.instance_id, instance_id, "the same install");
713        let owed = wan.retirements_pending(DIR).unwrap();
714        assert_eq!(owed.len(), 1, "still owed after the restart");
715        assert_eq!(owed[0].key_fp, old_fp);
716
717        let stub = stub_directory(axum::http::StatusCode::OK).await;
718        let result = publish_pending(&wan, &instance, "stable", &stub.url, &reqwest::Client::new(), "tok", DIR).await;
719        assert_eq!(result.revoked, 1);
720        let sent = stub.revoked.lock().unwrap().clone();
721        let revocation: WanKeyRevocation = serde_json::from_value(sent[0].2.clone()).unwrap();
722        assert!(revocation.verify() && revocation.names(&instance_id, "camper", "stable", &old_fp));
723        assert!(wan.retirements_pending(DIR).unwrap().is_empty(), "cleared only once the directory has it");
724    }
725
726    #[tokio::test]
727    async fn a_cloud_without_the_revocation_route_still_gets_the_keys_and_is_asked_again_later() {
728        let stub = stub_with_revocations(axum::http::StatusCode::OK, axum::http::StatusCode::NOT_FOUND).await;
729        let (_dir, wan, instance) = temp_wan();
730        replaced_after_publishing(&wan);
731        let result = publish_pending(&wan, &instance, "stable", &stub.url, &reqwest::Client::new(), "tok", DIR).await;
732        assert_eq!(result.published, 1, "the new key is published all the same");
733        assert!(result.revocations_not_supported);
734        assert!(!result.not_supported);
735        assert_eq!(result.remaining, 0, "not counted, or the pass would run hot");
736        assert_eq!(wan.retirements_pending(DIR).unwrap().len(), 1, "kept for when the route exists");
737    }
738
739    #[tokio::test]
740    async fn another_directory_is_not_told_about_a_key_it_never_held() {
741        let stub = stub_directory(axum::http::StatusCode::OK).await;
742        let (_dir, wan, instance) = temp_wan();
743        replaced_after_publishing(&wan);
744        let other = directory_id(&stub.url, "other-account");
745        let result = publish_pending(&wan, &instance, "stable", &stub.url, &reqwest::Client::new(), "tok2", &other).await;
746        assert_eq!(result.revoked, 0);
747        assert!(stub.revoked.lock().unwrap().is_empty());
748        assert_eq!(wan.retirements_pending(DIR).unwrap().len(), 1, "DIR is still owed");
749    }
750
751    #[test]
752    fn a_directory_is_the_relay_plus_the_account() {
753        assert_eq!(directory_id("https://relay.example/", "sub-1"), "https://relay.example#sub-1");
754        assert_ne!(directory_id("https://relay.example", "sub-1"), directory_id("https://relay.example", "sub-2"));
755        assert_ne!(directory_id("https://a.example", "sub-1"), directory_id("https://b.example", "sub-1"));
756    }
757}