1use 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
37const FETCH_TIMEOUT: Duration = Duration::from_secs(2);
40
41const REVOCATION_REFRESH_SECS: i64 = 60 * 60;
44
45const KEY_FEED_REFRESH_SECS: i64 = 5 * 60;
49
50const KEY_FEED_UNSUPPORTED_SECS: i64 = 60 * 60;
52
53const KEY_FEED_MAX_PAGES: usize = 4;
55
56const FETCHES_PER_MINUTE: u32 = 60;
60
61#[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#[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 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 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
114pub 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 Gone(serde_json::Value),
129 Unavailable(String),
131}
132
133pub 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
160pub static GLOBAL_BUDGET: FetchBudget = FetchBudget::new(FETCHES_PER_MINUTE);
162
163async 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 Err(e) => Fetched::Unavailable(format!("directory record doesn't parse: {e}")),
189 }
190 }
191 Ok(r) => cause = format!("directory answered {}", r.status()),
198 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 #[serde(default)]
233 revocation: Option<jekt_sign::WanRevocation>,
234}
235
236async 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 Fetched::NotFound => Some(false),
256 Fetched::Gone(_) => None,
258 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
266fn 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
284async 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 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 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
336fn 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
342fn 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 #[serde(default)]
366 gone: bool,
367}
368
369async 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
387pub 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
398pub async fn instance_is_revoked(dir: &Directory<'_>, instance_id: &str) -> Option<bool> {
401 fetch_revoked(dir, instance_id).await
402}
403
404pub 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
415enum PinCheck {
417 Allowed,
419 Mismatch(String),
421 Unavailable(String),
423}
424
425async 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
466async 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#[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 let (Some(sig), Some(key_fp)) = (row.wan_sig.as_deref(), row.wan_key_fp.as_deref()) else {
513 return WanVerdict::default();
514 };
515 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 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 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 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#[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
644pub(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;