Skip to main content

agentmux_srv/server/reactive/
replay.rs

1//! One delivery per signed jekt (https://docs.agentmux.ai/internals/jekt-protocol/
2//! ยง5): a host, cross-channel or LAN signature that this instance has already
3//! delivered fails on a second delivery, the same rule the WAN path applies
4//! with `wan_seen_sigs` (`muxbus/wan_verify.rs`). A signature stays fresh for
5//! minutes; within that time it proves its sender for one delivery.
6//!
7//! Used by `deliver()` and by the files path (`jekt_files::receive`). The
8//! check and the reservation are one step under one lock, so two copies
9//! arriving together can't both pass. A message counts once it is delivered
10//! to a local agent or held here for one, by whichever copy; when no copy is
11//! taken (it is forwarded, or delivery fails), the reservation is dropped, so
12//! a forward that comes back here is still delivered once. Entries live
13//! longer than any signature's freshness window.
14
15use std::collections::HashMap;
16use std::sync::{Mutex, OnceLock};
17
18use super::InjectionRequest;
19
20/// Longer than every freshness window it guards (host and channel 300 s,
21/// LAN 600 s, either way), so a signature can't outlive its entry.
22const WINDOW_SECS: i64 = 1_260;
23/// Entries kept at most. Past this, with every entry still live, a new
24/// signed message fails rather than evict one a copy could then pass as.
25const MAX_ENTRIES: usize = 20_000;
26
27type Key = (String, String, String);
28
29struct Entry {
30    until: i64,
31    /// A copy of the message was delivered or held here: the entry stays.
32    taken: bool,
33}
34
35/// What [`Seen::reserve`] hands out for a signed message: its key, and whether
36/// this copy made the reservation (the first) or found it (a later copy).
37pub(super) struct Claim {
38    key: Key,
39    first: bool,
40}
41
42#[derive(Default)]
43pub(super) struct Seen {
44    entries: HashMap<Key, Entry>,
45}
46
47impl Seen {
48    fn key(req: &InjectionRequest) -> Option<Key> {
49        let msgid = req.request_id.as_deref().filter(|m| !m.is_empty())?;
50        let source = req.source_agent.as_deref().filter(|s| !s.is_empty())?;
51        Some((source.to_ascii_lowercase(), req.target_agent.to_ascii_lowercase(), msgid.to_string()))
52    }
53
54    fn signed(req: &InjectionRequest) -> bool {
55        [req.sig_verified, req.lan_verified, req.channel_verified].contains(&Some(true))
56    }
57
58    /// Carries a signature someone could capture and send again. A caller
59    /// proven by its token alone (`muxsh agent send`) carries none.
60    fn carries_signature(req: &InjectionRequest) -> bool {
61        [&req.jekt_sig, &req.lan_sig, &req.lan_sig_v2, &req.channel_sig, &req.channel_sig_v2]
62            .iter()
63            .any(|sig| sig.as_deref().is_some_and(|s| !s.is_empty()))
64    }
65
66    fn fail_verdicts(req: &mut InjectionRequest) {
67        for verdict in [&mut req.sig_verified, &mut req.lan_verified, &mut req.channel_verified] {
68            if *verdict == Some(true) {
69                *verdict = Some(false);
70            }
71        }
72    }
73
74    /// Check and reserve in one step. A signed message already seen here has
75    /// every verified verdict turned into a failure; a signed message not seen
76    /// yet is reserved. Either way the claim lets a delivered copy keep the
77    /// entry, so the first copy failing later can't free it for a third. A
78    /// signed message with no message id or sender can't be counted, so it
79    /// fails too (every signer sends both); one proven by its token alone
80    /// has nothing to replay and is left as it is.
81    pub(super) fn reserve(&mut self, req: &mut InjectionRequest, now: i64) -> Option<Claim> {
82        if !Self::signed(req) {
83            return None;
84        }
85        let Some(key) = Self::key(req) else {
86            if !Self::carries_signature(req) {
87                return None;
88            }
89            Self::fail_verdicts(req);
90            tracing::warn!(target = %req.target_agent, "signed jekt without a message id or sender; counted as failed");
91            return None;
92        };
93        if self.entries.get(&key).is_some_and(|e| e.until > now) {
94            Self::fail_verdicts(req);
95            tracing::warn!(source = %key.0, target = %key.1, msgid = %key.2, "signed jekt already delivered here; counted as failed");
96            return Some(Claim { key, first: false });
97        }
98        if self.entries.len() >= MAX_ENTRIES {
99            self.entries.retain(|_, e| e.until > now);
100            if self.entries.len() >= MAX_ENTRIES {
101                Self::fail_verdicts(req);
102                tracing::warn!(source = %key.0, target = %key.1, msgid = %key.2, "one-delivery memory full; signed jekt counted as failed");
103                return None;
104            }
105        }
106        self.entries.insert(key.clone(), Entry { until: now + WINDOW_SECS, taken: false });
107        Some(Claim { key, first: true })
108    }
109
110    /// A copy of the message was delivered or held here: keep its entry.
111    pub(super) fn taken(&mut self, claim: &Claim) {
112        if let Some(entry) = self.entries.get_mut(&claim.key) {
113            entry.taken = true;
114        }
115    }
116
117    /// The copy that made the reservation wasn't taken here: drop the entry,
118    /// unless another copy was.
119    pub(super) fn release(&mut self, claim: &Claim) {
120        if claim.first && self.entries.get(&claim.key).is_some_and(|e| !e.taken) {
121            self.entries.remove(&claim.key);
122        }
123    }
124}
125
126fn seen() -> &'static Mutex<Seen> {
127    static SEEN: OnceLock<Mutex<Seen>> = OnceLock::new();
128    SEEN.get_or_init(Default::default)
129}
130
131/// A claim in this process's memory, released on drop unless
132/// [`Reservation::delivered`] is called.
133pub(in crate::server) struct Reservation(Option<Claim>);
134
135impl Reservation {
136    /// The message reached a local agent, or is held here for one: keep it
137    /// counted.
138    pub(in crate::server) fn delivered(&mut self) {
139        if let Some(claim) = self.0.take() {
140            if let Ok(mut seen) = seen().lock() {
141                seen.taken(&claim);
142            }
143        }
144    }
145}
146
147impl Drop for Reservation {
148    fn drop(&mut self) {
149        if let Some(claim) = self.0.take() {
150            if let Ok(mut seen) = seen().lock() {
151                seen.release(&claim);
152            }
153        }
154    }
155}
156
157/// [`Seen::reserve`] against this process's memory.
158pub(in crate::server) fn reserve(req: &mut InjectionRequest, now: i64) -> Reservation {
159    Reservation(seen().lock().ok().and_then(|mut seen| seen.reserve(req, now)))
160}
161
162#[cfg(test)]
163#[path = "../tests/reactive/replay_tests.rs"]
164mod tests;