Skip to main content

agentmux_srv_core/muxbus/
wan_verify.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Verify a same-account agent's WAN signature on a cloud-delivered jekt
5//! (`SPEC_WAN_JEKT_VERIFICATION_2026_09_24.md` §2.3–2.6, step D2).
6//!
7//! Runs in `cloud_subscriber::delivery::claim_and_deliver`, before transcript-request
8//! resolution, for each claimed injection. The checks run in the §2.3 order
9//! and every "couldn't check" outcome is `None` — only an active failure
10//! (envelope moved, certificate chain broken, record for something else,
11//! signature bad, replay) is `Some(false)`, the forced-sensitive red flag. A
12//! directory that is down or slow gives `None` and the message is delivered
13//! anyway: never `/reactive/release`, because nothing re-wakes a released row
14//! and it could expire undelivered (§1.2).
15//!
16//! **Replaced keys.** An install that replaces an agent's key signs a
17//! [`WanKeyRevocation`] for the old one. A message signed by a fingerprint
18//! this install holds a revocation of is `Some(false)` (`wan_key_revoked`),
19//! whatever its timestamp says, and the key is not looked up again. A revocation
20//! is learned from the directory's answer for the key (HTTP 410 with the signed
21//! notice) or from the account's feed, read at most every
22//! [`KEY_FEED_REFRESH_SECS`] while signed messages arrive; each must verify
23//! before it is kept (`wan_identity::revocations`).
24//!
25//! The HTTP entry point never reaches this: an HTTP caller's self-declared
26//! `delivery_tier: "wan"` can't set `wan_verified` (`skip_deserializing`).
27
28use std::sync::Mutex;
29use std::time::{Duration, Instant};
30
31use agentmux_common::jekt_sign::{self, WanCarried, WanCheckFailure, WanKeyRecord};
32use crate::muxbus::wan_key_revocation::WanKeyRevocation;
33
34use crate::backend::reactive::types::{WanInstanceInfo, WanInstanceStatus};
35use crate::backend::storage::wan_identity::WanIdentityStore;
36
37/// Directory fetch timeout (§2.3): verification runs per message on the sync
38/// path, so a slow directory must not hold delivery up for long.
39const FETCH_TIMEOUT: Duration = Duration::from_secs(2);
40
41/// How stale an instance's revocation status may be before it is re-checked
42/// on the next message from it (§2.3: hourly).
43const REVOCATION_REFRESH_SECS: i64 = 60 * 60;
44
45/// How long after reading the account's key revocation feed it may be read
46/// again, on the next signed message. This bounds how long a receiver that
47/// cached a key keeps accepting it after its install replaced it.
48const KEY_FEED_REFRESH_SECS: i64 = 5 * 60;
49
50/// How long a cloud without the feed route is left alone.
51const KEY_FEED_UNSUPPORTED_SECS: i64 = 60 * 60;
52
53/// Pages of the feed read in one go; the rest waits for the next read.
54const KEY_FEED_MAX_PAGES: usize = 4;
55
56/// Global fetch budget: at most this many directory requests per minute, so
57/// a flood of signed messages can't turn this install into a directory
58/// hammer. An exhausted budget reads as "unavailable" → `None`.
59const FETCHES_PER_MINUTE: u32 = 60;
60
61/// The carried fields of one pending row, as the cloud returned them.
62#[derive(Debug, Clone, Default)]
63pub(crate) struct CarriedRow {
64    pub wan_sig: Option<String>,
65    pub wan_msg_id: Option<String>,
66    pub wan_ts_secs: Option<i64>,
67    pub wan_source_agent: Option<String>,
68    pub wan_target_agent: Option<String>,
69    pub wan_source_host: Option<String>,
70    pub wan_source_channel: Option<String>,
71    pub wan_key_fp: Option<String>,
72    pub sender_same_account: Option<bool>,
73}
74
75/// The §2.3 outcome, ready to copy onto the `InjectionRequest`.
76#[derive(Debug, Clone, PartialEq, Eq, Default)]
77pub(crate) struct WanVerdict {
78    pub verified: Option<bool>,
79    pub instance: Option<WanInstanceInfo>,
80    pub reason: Option<&'static str>,
81    /// What exactly went wrong behind `reason`, when it has a cause worth
82    /// reading (the directory's HTTP status, a transport or parse error).
83    /// Diagnostics only: logged and audited, never part of the verdict.
84    pub detail: Option<String>,
85}
86
87impl WanVerdict {
88    fn none(reason: &'static str) -> Self {
89        Self { verified: None, instance: None, reason: Some(reason), detail: None }
90    }
91
92    /// "Couldn't check", with the cause. For the receiver's own setup
93    /// failures too, which happen before [`verify`] can run.
94    pub(crate) fn unchecked(reason: &'static str, detail: impl Into<String>) -> Self {
95        Self { verified: None, instance: None, reason: Some(reason), detail: Some(detail.into()) }
96    }
97
98    fn failed(reason: &'static str) -> Self {
99        Self { verified: Some(false), instance: None, reason: Some(reason), detail: None }
100    }
101
102    fn from_failure(f: WanCheckFailure) -> Self {
103        let reason = match f {
104            WanCheckFailure::EnvelopeMismatch => "wan_envelope_mismatch",
105            WanCheckFailure::Stale => "wan_sig_stale",
106            WanCheckFailure::CertInvalid => "wan_cert_invalid",
107            WanCheckFailure::RecordMismatch => "wan_record_mismatch",
108            WanCheckFailure::BadSignature => "wan_sig_invalid",
109        };
110        Self { verified: f.verdict(), instance: None, reason: Some(reason), detail: None }
111    }
112}
113
114/// Where the directory is and how to reach it. Tests point `base_url` at a
115/// stub and bring their own budget.
116pub struct Directory<'a> {
117    pub base_url: &'a str,
118    pub http: &'a reqwest::Client,
119    pub token: &'a str,
120    pub budget: &'a FetchBudget,
121}
122
123enum Fetched<T> {
124    Found(T),
125    NotFound,
126    /// HTTP 410: the directory no longer serves this. For a key, the body
127    /// carries the revocation the install signed.
128    Gone(serde_json::Value),
129    /// Why, for the verdict's `detail`: the last attempt's cause.
130    Unavailable(String),
131}
132
133/// A fixed-window request budget ([`FETCHES_PER_MINUTE`]).
134pub struct FetchBudget {
135    limit: u32,
136    window: Mutex<Option<(Instant, u32)>>,
137}
138
139impl FetchBudget {
140    pub(crate) const fn new(limit: u32) -> Self {
141        Self { limit, window: Mutex::new(None) }
142    }
143
144    fn take(&self) -> bool {
145        let mut window = self.window.lock().unwrap_or_else(|e| e.into_inner());
146        let now = Instant::now();
147        let (start, used) = window.get_or_insert((now, 0));
148        if now.duration_since(*start) >= Duration::from_secs(60) {
149            *start = now;
150            *used = 0;
151        }
152        if *used >= self.limit {
153            return false;
154        }
155        *used += 1;
156        true
157    }
158}
159
160/// The one budget every production verification shares.
161pub static GLOBAL_BUDGET: FetchBudget = FetchBudget::new(FETCHES_PER_MINUTE);
162
163/// One GET with the §2.3 retry rule: an unavailable directory gets one
164/// immediate retry; a 404 is an answer, not a failure.
165async fn get_json<T: serde::de::DeserializeOwned>(dir: &Directory<'_>, url: &str) -> Fetched<T> {
166    let mut cause = String::new();
167    for _attempt in 0..2 {
168        if !dir.budget.take() {
169            return Fetched::Unavailable("directory fetch budget exhausted".to_string());
170        }
171        let resp = dir
172            .http
173            .get(url)
174            .header("Authorization", format!("Bearer {}", dir.token))
175            .timeout(FETCH_TIMEOUT)
176            .send()
177            .await;
178        match resp {
179            Ok(r) if r.status() == reqwest::StatusCode::NOT_FOUND => return Fetched::NotFound,
180            Ok(r) if r.status() == reqwest::StatusCode::GONE => {
181                return Fetched::Gone(r.json::<serde_json::Value>().await.unwrap_or_default());
182            }
183            Ok(r) if r.status().is_success() => {
184                return match r.json::<T>().await {
185                    Ok(v) => Fetched::Found(v),
186                    // A 200 we can't parse is the cloud's problem; it can't
187                    // be a verification failure on the sender's part.
188                    Err(e) => Fetched::Unavailable(format!("directory record doesn't parse: {e}")),
189                }
190            }
191            // Still "couldn't check", but never silently: a directory that
192            // rejects this install's token turned every WAN jekt
193            // `network-claimed` with nothing in the log to say why. The cause
194            // is returned, not logged per attempt: the caller logs it once
195            // (`cloud_subscriber`'s "wan verify: outcome" at `warn`,
196            // `fetch_revoked` below) and the verdict carries it to the audit.
197            Ok(r) => cause = format!("directory answered {}", r.status()),
198            // `without_url`: the query names the sender's instance and key.
199            Err(e) => cause = format!("directory unreachable: {}", e.without_url()),
200        }
201    }
202    Fetched::Unavailable(cause)
203}
204
205async fn fetch_record(dir: &Directory<'_>, carried: &WanCarried<'_>) -> Fetched<WanKeyRecord> {
206    fetch_record_for(dir, carried.source_agent, carried.source_host, carried.source_channel, carried.key_fp).await
207}
208
209async fn fetch_record_for(dir: &Directory<'_>, agent: &str, instance: &str, channel: &str, key_fp: &str) -> Fetched<WanKeyRecord> {
210    let mut url = match reqwest::Url::parse(dir.base_url) {
211        Ok(u) => u,
212        Err(e) => return Fetched::Unavailable(format!("bad directory URL: {e}")),
213    };
214    match url.path_segments_mut() {
215        Ok(mut segs) => {
216            segs.pop_if_empty().push("agents").push(&agent.to_lowercase()).push("wan-key");
217        }
218        Err(_) => return Fetched::Unavailable("bad directory URL: cannot be a base".to_string()),
219    }
220    url.query_pairs_mut()
221        .append_pair("instance", &instance.to_lowercase())
222        .append_pair("channel", channel)
223        .append_pair("fp", key_fp);
224    get_json(dir, url.as_str()).await
225}
226
227#[derive(serde::Deserialize)]
228struct InstanceStatusResp {
229    revoked: bool,
230    /// The signed record behind `revoked` (§2.2). The directory returns it
231    /// whenever it says an instance is revoked.
232    #[serde(default)]
233    revocation: Option<jekt_sign::WanRevocation>,
234}
235
236/// Whether `instance_id` is revoked, `None` when that can't be told.
237///
238/// A revocation is sticky and turns every later message from the install into
239/// a sensitive one, so a bare `revoked: true` is not enough: the directory has
240/// to hand over the revocation itself, and it has to be the one the instance
241/// signed with its own key for this id. An answer that says revoked without it
242/// is not acted on.
243async fn fetch_revoked(dir: &Directory<'_>, instance_id: &str) -> Option<bool> {
244    let url = format!("{}/wan-instances/{}", dir.base_url.trim_end_matches('/'), instance_id);
245    match get_json::<InstanceStatusResp>(dir, &url).await {
246        Fetched::Found(s) if !s.revoked => Some(false),
247        Fetched::Found(s) => match s.revocation {
248            Some(r) if r.old_instance_id == instance_id && r.verify() => Some(true),
249            _ => {
250                tracing::warn!(instance_id, "wan verify: the directory says an instance is revoked without a revocation it signed: not acted on");
251                None
252            }
253        },
254        // An older cloud with no such route: not known to be revoked.
255        Fetched::NotFound => Some(false),
256        // Not an answer this route gives.
257        Fetched::Gone(_) => None,
258        // No verdict carries this one, so it is the only place to say it.
259        Fetched::Unavailable(cause) => {
260            tracing::warn!(instance_id, cause = %cause, "wan verify: revocation check couldn't reach the directory");
261            None
262        }
263    }
264}
265
266/// The revocation a 410 carries, if it is one the install signed for exactly
267/// this key. Anything else is not acted on: the directory can say a key is
268/// gone, but only the install can retire it.
269fn gone_revocation(body: &serde_json::Value, instance: &str, agent: &str, channel: &str, key_fp: &str) -> Option<WanKeyRevocation> {
270    let revocation: WanKeyRevocation = serde_json::from_value(body.get("revocation")?.clone()).ok()?;
271    (revocation.names(instance, agent, channel, key_fp) && revocation.verify()).then_some(revocation)
272}
273
274#[derive(serde::Deserialize)]
275struct KeyRevocationFeed {
276    #[serde(default)]
277    revocations: Vec<WanKeyRevocation>,
278    #[serde(default)]
279    next_since: Option<i64>,
280    #[serde(default)]
281    more: bool,
282}
283
284/// Read the account's key revocations the directory has received since the
285/// last read, keep those that verify, and drop the cached records they name.
286/// At most once per [`KEY_FEED_REFRESH_SECS`] per directory; a failed read is
287/// not retried sooner, so a down directory costs one request per interval.
288async fn refresh_key_revocations(wan: &WanIdentityStore, dir: &Directory<'_>, now: i64) {
289    let directory = crate::muxbus::wan_publish::directory_id(dir.base_url, &crate::muxbus::pkce::token_sub(dir.token));
290    let Ok((mut since, checked_at)) = wan.key_revocation_feed_state(&directory) else { return };
291    if now.saturating_sub(checked_at) < KEY_FEED_REFRESH_SECS {
292        return;
293    }
294    let _ = wan.key_revocation_feed_note(&directory, now, None);
295    for _ in 0..KEY_FEED_MAX_PAGES {
296        let url = format!("{}/wan-key-revocations?since={since}", dir.base_url.trim_end_matches('/'));
297        match get_json::<KeyRevocationFeed>(dir, &url).await {
298            Fetched::Found(feed) => {
299                let mut all_kept = true;
300                for revocation in &feed.revocations {
301                    match wan.revoked_key_put(revocation, now) {
302                        Ok(true) => {}
303                        Ok(false) => tracing::warn!("wan verify: the directory's key revocation feed held one that does not verify: ignored"),
304                        Err(e) => {
305                            tracing::warn!(error = %e, "wan verify: could not keep a key revocation");
306                            all_kept = false;
307                        }
308                    }
309                }
310                // A revocation that could not be stored must be read again:
311                // the cursor stays where it was, and the next read retries.
312                if !all_kept {
313                    return;
314                }
315                let next = feed.next_since.unwrap_or(since).max(since);
316                let _ = wan.key_revocation_feed_note(&directory, now, Some(next));
317                if !feed.more || next == since {
318                    return;
319                }
320                since = next;
321            }
322            // A cloud without the feed: ask again in an hour.
323            Fetched::NotFound => {
324                let _ = wan.key_revocation_feed_note(&directory, now + KEY_FEED_UNSUPPORTED_SECS - KEY_FEED_REFRESH_SECS, None);
325                return;
326            }
327            Fetched::Gone(_) => return,
328            Fetched::Unavailable(cause) => {
329                tracing::warn!(cause = %cause, "wan verify: the key revocation feed couldn't be read");
330                return;
331            }
332        }
333    }
334}
335
336/// Whether this install holds a verified revocation of the key. `Err` when
337/// that can't be told.
338fn key_is_revoked(wan: &WanIdentityStore, instance: &str, agent: &str, channel: &str, key_fp: &str) -> Result<bool, String> {
339    wan.revoked_key_exists(instance, agent, channel, key_fp).map_err(|e| e.to_string())
340}
341
342/// What a 410 for this key means: refused if the install signed its
343/// retirement (kept, so the next message needn't ask), otherwise a directory
344/// answer that can't be acted on.
345fn gone_verdict(wan: &WanIdentityStore, body: &serde_json::Value, instance: &str, agent: &str, channel: &str, key_fp: &str, now: i64) -> WanVerdict {
346    match gone_revocation(body, instance, agent, channel, key_fp) {
347        Some(revocation) => {
348            let _ = wan.revoked_key_put(&revocation, now);
349            WanVerdict::failed("wan_key_revoked")
350        }
351        None => WanVerdict::unchecked("wan_key_unavailable", "directory answered 410 without a revocation the install signed for this key"),
352    }
353}
354
355#[derive(serde::Deserialize)]
356struct PresenceList {
357    #[serde(default)]
358    instances: Vec<PresenceRow>,
359}
360
361#[derive(serde::Deserialize)]
362struct PresenceRow {
363    instance_id: String,
364    /// A tombstone: the install said goodbye and is listed only as offline.
365    #[serde(default)]
366    gone: bool,
367}
368
369/// Whether the account's presence list shows `instance_id` as a live install.
370/// The directory lists only installs that published a record signed by their
371/// own key and that are not revoked, so this is what separates an install of
372/// the account from a key someone merely published. `None` when the list
373/// couldn't be read.
374async fn fetch_listed(dir: &Directory<'_>, instance_id: &str) -> Option<bool> {
375    let url = format!("{}/wan-instances", dir.base_url.trim_end_matches('/'));
376    match get_json::<PresenceList>(dir, &url).await {
377        Fetched::Found(list) => Some(list.instances.iter().any(|row| !row.gone && row.instance_id == instance_id)),
378        Fetched::NotFound => Some(false),
379        Fetched::Gone(_) => None,
380        Fetched::Unavailable(cause) => {
381            tracing::warn!(instance_id, cause = %cause, "wan verify: the presence list couldn't be read");
382            None
383        }
384    }
385}
386
387/// Whether `instance_id` is a live, unrevoked install of the signed-in account:
388/// listed in its presence list and not revoked (the standard a WAN sender's
389/// install is held to). `None` when that can't be told.
390pub async fn instance_is_live_install(dir: &Directory<'_>, instance_id: &str) -> Option<bool> {
391    if fetch_listed(dir, instance_id).await? {
392        fetch_revoked(dir, instance_id).await.map(|revoked| !revoked)
393    } else {
394        Some(false)
395    }
396}
397
398/// Whether the directory holds a revocation `instance_id` signed itself (the
399/// standard WAN verification applies). `None` when that can't be told.
400pub async fn instance_is_revoked(dir: &Directory<'_>, instance_id: &str) -> Option<bool> {
401    fetch_revoked(dir, instance_id).await
402}
403
404/// The install `from` handed over to: the successor named in the revocation `from` signed with its own
405/// key, which the directory serves. `None` when `from` is not revoked, the directory holds no revocation
406/// it signed, or the directory could not be read.
407pub async fn instance_handed_over_to(dir: &Directory<'_>, from: &str) -> Option<String> {
408    let url = format!("{}/wan-instances/{}", dir.base_url.trim_end_matches('/'), from);
409    match get_json::<InstanceStatusResp>(dir, &url).await {
410        Fetched::Found(s) if s.revoked => s.revocation.filter(|r| r.old_instance_id == from && r.verify()).map(|r| r.new_instance_id),
411        _ => None,
412    }
413}
414
415/// What the pin said about the install that signed a message.
416enum PinCheck {
417    /// Pinned to this install, or not pinnable yet.
418    Allowed,
419    /// The name is pinned to another install.
420    Mismatch(String),
421    /// The pin store couldn't be read.
422    Unavailable(String),
423}
424
425/// `(agent, channel)` is pinned to the first install the account's presence
426/// list shows speaking for it. A message from another install for a pinned
427/// name fails; a name with no pin is pinned only once its install is listed,
428/// so a key published by something that is not an install of the account
429/// pins nothing. This install's own agents never go through here.
430async fn check_agent_instance_pin(
431    wan: &WanIdentityStore,
432    record: &WanKeyRecord,
433    agent: &str,
434    channel: &str,
435    dir: &Directory<'_>,
436    now: i64,
437) -> PinCheck {
438    let hint = if jekt_sign::is_valid_wan_host_hint(&record.host_hint) { record.host_hint.as_str() } else { "?" };
439    let pinned = match wan.agent_instance_pin_get(agent, channel) {
440        Ok(p) => p,
441        Err(e) => return PinCheck::Unavailable(e.to_string()),
442    };
443    let pin = match pinned {
444        Some(pin) => pin,
445        None => {
446            if fetch_listed(dir, &record.instance_id).await != Some(true) {
447                return PinCheck::Allowed;
448            }
449            match wan.agent_instance_pin_get_or_set(agent, channel, &record.instance_id, hint, now) {
450                Ok(pin) => pin,
451                Err(e) => return PinCheck::Unavailable(e.to_string()),
452            }
453        }
454    };
455    if pin.instance_id == record.instance_id {
456        return PinCheck::Allowed;
457    }
458    let _ = wan.agent_instance_pin_note_conflict(agent, channel, &record.instance_id, hint, now);
459    PinCheck::Mismatch(format!(
460        "pinned to {}, this came from {}",
461        jekt_sign::wan_instance_display_label(&pin.host_hint, &pin.instance_id),
462        jekt_sign::wan_instance_display_label(hint, &record.instance_id),
463    ))
464}
465
466/// The instance's status (§2.6). This install is approved implicitly. Any
467/// other instance is approved only through the host-gated window, which
468/// ships disabled, so it stays `new`.
469/// Revocation is checked on first sight and at most hourly after.
470async fn instance_status(
471    wan: &WanIdentityStore,
472    own_instance_id: &str,
473    record: &WanKeyRecord,
474    dir: &Directory<'_>,
475    now: i64,
476) -> WanInstanceStatus {
477    let hint = if jekt_sign::is_valid_wan_host_hint(&record.host_hint) { record.host_hint.as_str() } else { "?" };
478    let Ok(mut known) = wan.known_instance_observe(&record.instance_id, hint, now) else {
479        return WanInstanceStatus::New;
480    };
481    let due = known.revocation_checked_at.is_none_or(|t| now.saturating_sub(t) >= REVOCATION_REFRESH_SECS);
482    if known.revoked_at.is_none() && due {
483        if let Some(revoked) = fetch_revoked(dir, &record.instance_id).await {
484            let _ = wan.known_instance_record_revocation_check(&record.instance_id, revoked, now);
485            if revoked {
486                known.revoked_at = Some(now);
487            }
488        }
489    }
490    if known.revoked_at.is_some() {
491        WanInstanceStatus::Revoked
492    } else if record.instance_id == own_instance_id {
493        WanInstanceStatus::Approved
494    } else {
495        WanInstanceStatus::New
496    }
497}
498
499/// The §2.3 table, in order.
500#[allow(clippy::too_many_arguments)]
501pub(crate) async fn verify(
502    wan: &WanIdentityStore,
503    own_instance_id: &str,
504    polled_agent_id: &str,
505    row_source_agent: &str,
506    row: &CarriedRow,
507    message: &str,
508    now: i64,
509    dir: &Directory<'_>,
510) -> WanVerdict {
511    // No signature (or no lookup hint): nothing to check.
512    let (Some(sig), Some(key_fp)) = (row.wan_sig.as_deref(), row.wan_key_fp.as_deref()) else {
513        return WanVerdict::default();
514    };
515    // Cross-account, legacy, or a cloud that doesn't say.
516    if row.sender_same_account != Some(true) {
517        return WanVerdict::none("wan_not_same_account");
518    }
519    let (Some(msg_id), Some(ts_secs), Some(source_agent), Some(target_agent), Some(source_host), Some(source_channel)) = (
520        row.wan_msg_id.as_deref(),
521        row.wan_ts_secs,
522        row.wan_source_agent.as_deref(),
523        row.wan_target_agent.as_deref(),
524        row.wan_source_host.as_deref(),
525        row.wan_source_channel.as_deref(),
526    ) else {
527        // The cloud stores all eight or none; a partial set is not a
528        // signature anyone made.
529        return WanVerdict::none("wan_fields_incomplete");
530    };
531    let carried = WanCarried {
532        sig,
533        msg_id,
534        ts_secs,
535        source_agent,
536        target_agent,
537        source_host,
538        source_channel,
539        key_fp,
540    };
541    if let Err(f) = jekt_sign::check_wan_envelope(&carried, row_source_agent, polled_agent_id, now) {
542        return WanVerdict::from_failure(f);
543    }
544
545    // A key its install retired is refused before anything else is read for it.
546    refresh_key_revocations(wan, dir, now).await;
547    match key_is_revoked(wan, source_host, source_agent, source_channel, key_fp) {
548        Ok(false) => {}
549        Ok(true) => return WanVerdict::failed("wan_key_revoked"),
550        Err(cause) => return WanVerdict::unchecked("wan_revocation_unavailable", cause),
551    }
552
553    let record = match wan.peer_record_get(source_host, source_agent, source_channel, key_fp) {
554        Ok(Some(cached)) => cached,
555        _ => match fetch_record(dir, &carried).await {
556            Fetched::Found(record) => record,
557            Fetched::NotFound => return WanVerdict::none("wan_key_not_found"),
558            Fetched::Gone(body) => return gone_verdict(wan, &body, source_host, source_agent, source_channel, key_fp, now),
559            Fetched::Unavailable(cause) => return WanVerdict::unchecked("wan_key_unavailable", cause),
560        },
561    };
562    if let Err(f) = jekt_sign::verify_wan_against_record(&carried, &record, message) {
563        return WanVerdict::from_failure(f);
564    }
565    // Only a record that passed its chain is ever cached.
566    let _ = wan.peer_record_put(&record);
567
568    if wan.seen_sig_contains(&record.instance_id, source_agent, msg_id).unwrap_or(false) {
569        return WanVerdict::failed("wan_sig_replay");
570    }
571
572    if record.instance_id != own_instance_id {
573        match check_agent_instance_pin(wan, &record, source_agent, source_channel, dir, now).await {
574            PinCheck::Allowed => {}
575            PinCheck::Mismatch(detail) => {
576                return WanVerdict { detail: Some(detail), ..WanVerdict::failed("wan_instance_pin_mismatch") };
577            }
578            PinCheck::Unavailable(cause) => return WanVerdict::unchecked("wan_pin_unavailable", cause),
579        }
580    }
581
582    let status = instance_status(wan, own_instance_id, &record, dir, now).await;
583    WanVerdict {
584        verified: Some(true),
585        instance: Some(WanInstanceInfo {
586            id: record.instance_id.clone(),
587            label: jekt_sign::wan_instance_display_label(&record.host_hint, &record.instance_id),
588            status,
589        }),
590        reason: None,
591        detail: None,
592    }
593}
594
595/// A *receiver's* record, for a sender sealing files to it
596/// (`server::jekt_cloud`, file transfer spec §7): `agent`'s key on install
597/// `instance`, channel `channel`, fingerprint `key_fp`, as the agent's lease
598/// named them. Only a record whose chain holds is returned or cached, and
599/// never one of a revoked install. `Err` says why not, to follow the agent's
600/// name.
601#[allow(clippy::too_many_arguments)]
602pub async fn recipient_record(
603    wan: &WanIdentityStore,
604    own_instance_id: &str,
605    dir: &Directory<'_>,
606    agent: &str,
607    instance: &str,
608    channel: &str,
609    key_fp: &str,
610    now: i64,
611) -> Result<WanKeyRecord, String> {
612    const RETIRED: &str = "has a key its install retired; wait for the agent's new one";
613    refresh_key_revocations(wan, dir, now).await;
614    if key_is_revoked(wan, instance, agent, channel, key_fp).map_err(|e| format!("couldn't be checked for a retired key ({e})"))? {
615        return Err(RETIRED.to_string());
616    }
617    let record = match wan.peer_record_get(instance, agent, channel, key_fp) {
618        Ok(Some(cached)) => cached,
619        _ => match fetch_record_for(dir, agent, instance, channel, key_fp).await {
620            Fetched::Found(record) => record,
621            Fetched::NotFound => return Err("has no key in the account's key directory yet; try again in a minute".to_string()),
622            Fetched::Gone(body) => {
623                return Err(match gone_revocation(&body, instance, agent, channel, key_fp) {
624                    Some(revocation) => {
625                        let _ = wan.revoked_key_put(&revocation, now);
626                        RETIRED.to_string()
627                    }
628                    None => "couldn't be looked up in the account's key directory (it answered 410 without a revocation that checks out)".to_string(),
629                });
630            }
631            Fetched::Unavailable(cause) => return Err(format!("couldn't be looked up in the account's key directory ({cause})")),
632        },
633    };
634    if record.check_chain().is_none() {
635        return Err("has a key record whose certificate doesn't check out".to_string());
636    }
637    let _ = wan.peer_record_put(&record);
638    if instance_status(wan, own_instance_id, &record, dir, now).await == WanInstanceStatus::Revoked {
639        return Err("runs on an install its owner revoked".to_string());
640    }
641    Ok(record)
642}
643
644/// After a verified message was delivered locally: remember it, so the same
645/// (instance, agent, msgid) is a replay from now on (§2.5). Not before
646/// delivery — the relay's own release-and-redeliver must not look like one.
647pub(crate) fn record_delivered(wan: &WanIdentityStore, verdict: &WanVerdict, row: &CarriedRow, now: i64) {
648    let (Some(instance), Some(agent), Some(msg_id), Some(ts)) = (
649        verdict.instance.as_ref(),
650        row.wan_source_agent.as_deref(),
651        row.wan_msg_id.as_deref(),
652        row.wan_ts_secs,
653    ) else {
654        return;
655    };
656    if verdict.verified != Some(true) {
657        return;
658    }
659    if let Err(e) = wan.seen_sig_record(&instance.id, agent, msg_id, ts.saturating_add(jekt_sign::WAN_SIG_MAX_AGE_SECS), now) {
660        tracing::warn!(error = %e, "wan verify: could not record a delivered signature — a replay of it would verify");
661    }
662}
663
664#[cfg(test)]
665mod key_revocation_tests;
666#[cfg(test)]
667mod tests;