Skip to main content

agentmux_srv_core/muxbus/cloud_subscriber/
delivery_steps.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The steps of `claim_and_deliver`: the claim, what is checked about each claimed message
5//! (signatures), the request it is delivered as, and its files.
6
7use super::*;
8
9/// What was checked about one claimed message: kept for the delivery and for noting it delivered.
10pub(super) struct Checked {
11    reagent_verified: Option<bool>,
12    /// The signature is genuine and failed only the age rules: the marker says `SIG=expired`.
13    reagent_expired: bool,
14    /// (signed message id, agent, delivery id) of a reagent-signed message that verified: recorded once it is delivered.
15    reagent_delivery: Option<(String, String, String)>,
16    /// The delivery a verified signed message already went to this agent as, when this is a second copy of it.
17    repeat_of: Option<String>,
18    wan_row: crate::muxbus::wan_verify::CarriedRow,
19    wan_store: Option<Arc<crate::backend::storage::wan_identity::WanIdentityStore>>,
20    wan_verdict: crate::muxbus::wan_verify::WanVerdict,
21}
22
23/// The files could not be fetched and the claim was given back to the relay.
24pub(super) struct GivenBack;
25
26/// Claim `all_ids`. `Err` is the outcome that ends the call: nothing was claimed. The token is the
27/// one the claim was made with, which a rejected agent credential changes to the shared one.
28#[allow(clippy::too_many_arguments)]
29pub(super) async fn claim(
30    base: &str,
31    agent_id: &str,
32    token: &str,
33    http: &reqwest::Client,
34    mstore: &Arc<Store>,
35    all_ids: &[String],
36    mut agent_token: String,
37    mut using_per_agent: bool,
38) -> Result<(AckResp, String), AgentSyncOutcome> {
39    let ack_url = format!("{}/reactive/ack", base);
40    let claimed: AckResp = loop {
41        // For telling a 409 from before a Take over apart (note_not_holder_since).
42        let claim_resp_started = std::time::Instant::now();
43        let claim_resp = match http
44            .post(&ack_url)
45            .header("Authorization", format!("Bearer {}", agent_token))
46            .header("X-Agent-ID", agent_id)
47            .header("X-Agent-Instance", crate::muxbus::wan_lease::instance_id())
48            .json(&serde_json::json!({ "injection_ids": all_ids }))
49            .send()
50            .await
51        {
52            Ok(r) => r,
53            Err(e) => {
54                tracing::warn!(agent_id = %agent_id, error = %e, "cloud_subscriber: claim request failed");
55                delivery_status::pull_failed(agent_id, "couldn't claim messages from the relay");
56                return Err(AgentSyncOutcome::Ok); // nothing claimed — retried on the next wake/poll
57            }
58        };
59
60        if is_credential_rejected(claim_resp.status()) {
61            if using_per_agent {
62                // Same reasoning as the /reactive/pending branch above:
63                // invalidate and retry THIS claim immediately with the
64                // shared token, rather than reconnecting the whole session
65                // or leaving this agent's already-fetched pending
66                // injections unclaimed until an unrelated broadcast fires.
67                invalidate_rejected_credential(agent_id, claim_resp.status(), mstore);
68                agent_token = shared_token_now(mstore, token).await;
69                using_per_agent = false;
70                continue;
71            }
72            return Err(shared_token_rejection_outcome(claim_resp.status(), agent_id));
73        }
74        if claim_resp.status() == reqwest::StatusCode::CONFLICT {
75            // The relay's lease fence on acks (the lease changed hands between
76            // this pull and this claim): same handling as a 409 on the pull —
77            // claim nothing, and fence the local holder (ReAgent P1 on #3746).
78            let body = claim_resp.json::<serde_json::Value>().await.unwrap_or_default();
79            if let Some(where_) = crate::muxbus::wan_lease::note_not_holder_since(agent_id, &body, claim_resp_started) {
80                crate::backend::agent_admission::fence_agent_named(agent_id, &where_);
81            }
82            return Err(AgentSyncOutcome::Ok);
83        }
84        if !claim_resp.status().is_success() {
85            tracing::warn!(
86                status = %claim_resp.status(),
87                agent_id = %agent_id,
88                "cloud_subscriber: claim request non-2xx"
89            );
90            delivery_status::pull_failed(agent_id, format!("the relay answered {} to a message claim", claim_resp.status().as_u16()));
91            return Err(AgentSyncOutcome::Ok); // nothing claimed — retried on the next wake/poll
92        }
93
94        break match claim_resp.json().await {
95            Ok(b) => b,
96            Err(e) => {
97                // The server processed the claim (status was 2xx) before this
98                // body failed to parse — some subset of `all_ids` may now be
99                // flipped to "delivered" server-side with no local delivery
100                // and no way for us to release them, since we don't know
101                // which ids succeeded or their delivered_at stamp (required
102                // by /reactive/release). We deliberately do NOT guess (e.g.
103                // via /reactive/status) and release whatever looks delivered:
104                // some of `all_ids` may have been legitimately claimed and
105                // delivered by a *different* concurrent poller (another
106                // channel/seat racing for the same agent_id), and blindly
107                // releasing those would reintroduce the exact duplicate-
108                // delivery bug this change exists to fix. Logging every
109                // affected id loudly is the safe tradeoff: rare silent
110                // message loss here, never a resurrected duplicate.
111                tracing::error!(
112                    agent_id = %agent_id,
113                    injection_ids = ?all_ids,
114                    error = %e,
115                    "cloud_subscriber: parse claim response failed — these injections may be claimed server-side with no local delivery and cannot be safely auto-recovered"
116                );
117                return Err(AgentSyncOutcome::Ok);
118            }
119        };
120    };
121    Ok((claimed, agent_token))
122}
123
124/// Drop the per-agent credential a claim was rejected with: a 403 (binding mismatch) records its
125/// failure, any other rejection clears only the cached token.
126fn invalidate_rejected_credential(agent_id: &str, status: reqwest::StatusCode, mstore: &Arc<Store>) {
127    if status == reqwest::StatusCode::FORBIDDEN {
128        crate::muxbus::agent_credentials::invalidate_binding_mismatched_credential(agent_id, mstore);
129    } else {
130        crate::muxbus::agent_credentials::invalidate_cached_token(agent_id, mstore);
131    }
132    tracing::warn!(
133        agent_id = %agent_id,
134        status = %status,
135        "cloud_subscriber: per-agent credential rejected on claim — invalidated, retrying with shared token",
136    );
137}
138
139/// Check one claimed message: a reagent signature, and the WAN signature of a same-account agent.
140pub(super) async fn verify(
141    inj: &PendingInj,
142    agent_id: &str,
143    token: &str,
144    http: &reqwest::Client,
145    mstore: &Arc<Store>,
146) -> Checked {
147    let reagent_verified = reagent_verdict(inj, agent_id, now_unix_secs());
148    let reagent_expired = reagent_expired(inj, agent_id, now_unix_secs());
149    // A verified signed message that already reached this agent under another delivery id is a second copy (the
150    // sender retried a call the relay had in fact taken, or a captured notice was sent again): not delivered again.
151    let reagent_delivery = match (reagent_verified, &inj.reagent_msg_id) {
152        (Some(true), Some(msg_id)) => Some((msg_id.clone(), agent_id.to_string(), inj.id.clone())),
153        _ => None,
154    };
155    let repeat_of = reagent_delivery
156        .as_ref()
157        .and_then(|(msg_id, agent, inj_id)| reagent_age::delivered_under_another(msg_id, agent, inj_id, now_unix_secs()));
158
159    // W3-S (§2.3): a same-account agent's WAN signature, verified here —
160    // before transcript-request resolution, and against the POLLED
161    // agent, never a row field. Every "couldn't check" is `None` and the
162    // message is delivered as today; only an active failure is
163    // `Some(false)`.
164    let wan_row = crate::muxbus::wan_verify::CarriedRow {
165        wan_sig: inj.wan_sig.clone(),
166        wan_msg_id: inj.wan_msg_id.clone(),
167        wan_ts_secs: inj.wan_ts_secs,
168        wan_source_agent: inj.wan_source_agent.clone(),
169        wan_target_agent: inj.wan_target_agent.clone(),
170        wan_source_host: inj.wan_source_host.clone(),
171        wan_source_channel: inj.wan_source_channel.clone(),
172        wan_key_fp: inj.wan_key_fp.clone(),
173        sender_same_account: inj.sender_same_account,
174    };
175    let wan_store = crate::backend::storage::wan_identity::global();
176    let wan_verdict = match (&wan_store, &inj.wan_sig) {
177        (Some(wan), Some(_)) => match wan.instance_ensure(&crate::backend::reactive::registry::local_host_label()) {
178            Ok(own) => {
179                let base_url = crate::muxbus::relay::rest_base_url();
180                let dir_token = shared_token_now(mstore, token).await;
181                let dir = crate::muxbus::wan_verify::Directory {
182                    base_url: &base_url,
183                    http,
184                    token: &dir_token,
185                    budget: &crate::muxbus::wan_verify::GLOBAL_BUDGET,
186                };
187                crate::muxbus::wan_verify::verify(
188                    wan,
189                    &own.instance_id,
190                    agent_id,
191                    inj.source_agent.as_deref().unwrap_or(""),
192                    &wan_row,
193                    &inj.message,
194                    now_unix_secs(),
195                    &dir,
196                )
197                .await
198            }
199            Err(e) => crate::muxbus::wan_verify::WanVerdict::unchecked("wan_no_local_instance", e.to_string()),
200        },
201        (None, Some(_)) => crate::muxbus::wan_verify::WanVerdict::unchecked("wan_no_local_store", "no wan.db attached"),
202        (_, None) => crate::muxbus::wan_verify::WanVerdict::default(),
203    };
204    log_wan_outcome(inj, &wan_verdict);
205    Checked { reagent_verified, reagent_expired, reagent_delivery, repeat_of, wan_row, wan_store, wan_verdict }
206}
207
208/// The verdict on a reagent-signed message; `None` when it carries no complete signature.
209pub(super) fn reagent_verdict(inj: &PendingInj, agent_id: &str, now: i64) -> Option<bool> {
210    // Verify a reagent-signed WAN message (see PendingInj's doc comment)
211    // before delivery. Only attempted when every one of the four
212    // signing fields is present — a partial set (e.g. a sig but no
213    // key_id) is treated the same as "not signed," not "signed but
214    // broken," since a legitimate sender always sends all four
215    // together. This verdict never changes TRUST; it renders as `SIG=`.
216    // `Some(false)` — a signature present but failed, or valid only
217    // under an untrusted key — forces TIER=sensitive (see
218    // InjectionRequest::reagent_verified,
219    // SPEC_JEKT_SENSITIVE_TIER_NARROWING_2026_08_15.md, and
220    // https://docs.agentmux.ai/internals/jekt-protocol/).
221    // `verify_trusted_reagent_jekt` yields `Some(true)` only
222    // under the trusted production key; a signature under any other
223    // registered key is `Some(false)`. `req.reagent_key_id` in `request` must still be carried
224    // through from `inj` so the marker's `SIG=` label and the SIG=verified
225    // rule-1b exception render correctly (reagentx P0 on PR #2576 — it
226    // wasn't, so relaxation silently never activated for
227    // the desktop app's WS delivery path despite `reagent_verified`
228    // being computed correctly).
229    //
230    // Anti-replay (reagentx P1 on PR #2570): a captured, validly-signed
231    // (reagent_sig, reagent_key_id, reagent_msg_id, reagent_ts_secs,
232    // message) tuple could otherwise be resubmitted under a brand-new
233    // injection `id` indefinitely and still render SIG=verified — same
234    // class of gap host-tier's `verify_jekt_signature` closed with
235    // `JEKT_SIG_MAX_AGE_SECS`. `REAGENT_SIG_MAX_AGE_SECS` is wider
236    // (600s vs. 300s) because this is real network delivery, not a
237    // same-machine call. A notice the relay held for a host that was off
238    // is older than that when it arrives: it is judged by `reagent_age`
239    // (its age when the relay accepted it, and a bound at delivery), not
240    // by delivery time alone, which read a genuine late notice as a
241    // forgery. A second copy of one already delivered is dropped by the
242    // caller (`Checked::repeat_of`), not rendered as a forgery.
243    reagent_checks(inj, agent_id, now).map(|(age_ok, signature_ok)| age_ok && signature_ok)
244}
245
246/// Whether a reagent-signed message's signature is genuine (under the trusted key) and fails only the age rules:
247/// it renders `SIG=expired`, not `SIG=invalid`. It is still `reagent_verified == Some(false)`, so it is still
248/// `TIER=sensitive` and still needs a stop.
249pub(super) fn reagent_expired(inj: &PendingInj, agent_id: &str, now: i64) -> bool {
250    reagent_checks(inj, agent_id, now) == Some((false, true))
251}
252
253/// What the age rules and the signature each say of a reagent-signed message, as (age ok, signature verifies
254/// under the trusted key); `None` when it carries no complete signature.
255fn reagent_checks(inj: &PendingInj, agent_id: &str, now: i64) -> Option<(bool, bool)> {
256    match (&inj.reagent_sig, &inj.reagent_key_id, &inj.reagent_msg_id, inj.reagent_ts_secs) {
257        (Some(sig), Some(key_id), Some(msg_id), Some(ts_secs)) => {
258            // The relay's own record of when it accepted the message: a notice that waited for a host that
259            // was off is judged by its age when it was accepted, within a bound at delivery, and once.
260            let accepted_secs = inj.created_at.as_deref().and_then(delivery_status::notes::parse_created_at).map(|ms| ms / 1000);
261            Some((
262                reagent_age::age_ok(ts_secs, accepted_secs, now),
263                agentmux_common::jekt_sign::verify_trusted_reagent_jekt(
264                    key_id,
265                    msg_id,
266                    inj.source_agent.as_deref().unwrap_or(""),
267                    agent_id,
268                    ts_secs,
269                    &inj.message,
270                    sig,
271                ),
272            ))
273        }
274        _ => None,
275    }
276}
277
278/// One line to the log for the WAN signature outcome of `inj`.
279fn log_wan_outcome(inj: &PendingInj, wan_verdict: &crate::muxbus::wan_verify::WanVerdict) {
280    // Every "couldn't check" renders exactly like an unsigned message
281    // (`TRUST=network-claimed`), so say which one happened at a level
282    // that is actually recorded. One line per WAN jekt.
283    if inj.wan_sig.is_some() {
284        let (verified, reason, detail) =
285            (wan_verdict.verified, wan_verdict.reason.unwrap_or(""), wan_verdict.detail.as_deref().unwrap_or(""));
286        if verified == Some(false) {
287            tracing::warn!(injection_id = %inj.id, source = ?inj.source_agent, reason, "wan verify: signature FAILED");
288        } else if !detail.is_empty() {
289            // A check that couldn't run for a known cause (directory
290            // refused or unreachable, no local store): the one line that
291            // reports it, at `warn` — `wan_verify::get_json` no longer
292            // logs each attempt.
293            tracing::warn!(
294                injection_id = %inj.id,
295                source = ?inj.source_agent,
296                verified = ?verified,
297                reason,
298                detail,
299                same_account = ?inj.sender_same_account,
300                "wan verify: outcome"
301            );
302        } else {
303            tracing::info!(
304                injection_id = %inj.id,
305                source = ?inj.source_agent,
306                verified = ?verified,
307                reason,
308                same_account = ?inj.sender_same_account,
309                "wan verify: outcome"
310            );
311        }
312    } else if inj.reagent_sig.is_none() {
313        tracing::info!(injection_id = %inj.id, source = ?inj.source_agent, "wan verify: arrived without a WAN signature");
314    }
315}
316
317/// The request a claimed message is delivered as, with the verdicts, its transcript-request fields and a
318/// note when it was late.
319pub(super) fn request(inj: &PendingInj, target: &str, checked: &Checked, mstore: &Arc<Store>) -> InjectionRequest {
320    let mut req = InjectionRequest {
321        reagent_verified: checked.reagent_verified,
322        reagent_expired: checked.reagent_expired,
323        wan_verified: checked.wan_verdict.verified,
324        wan_instance: checked.wan_verdict.instance.clone(),
325        wan_reason: checked.wan_verdict.reason.map(str::to_string),
326        wan_detail: checked.wan_verdict.detail.clone(),
327        ..wan_request(inj, target)
328    };
329    // Phase C (muxspect Phase B/C conversation visibility,
330    // SPEC_JEKT_TRANSCRIPT_REQUEST_TIER_RULES_2026_08_22.md): this WAN
331    // delivery path calls `Handler::inject_message` directly and never
332    // goes through `server/reactive.rs::handle_reactive_inject`/HTTP at
333    // all — without also resolving these two fields HERE, a
334    // WAN-delivered `transcript_request` would silently skip both the
335    // forced-TIER=sensitive rule and the escalate-forcing rule
336    // entirely, not just get a weaker version of them.
337    crate::muxbus::server_hooks::hooks().resolve_transcript_request_tier_fields(mstore, &mut req);
338    // Marked only after the verdicts and the transcript-request fields have read the message as sent.
339    let created_ms = inj.created_at.as_deref().and_then(delivery_status::notes::parse_created_at);
340    let late = delivery_status::notes::delayed_prefix(created_ms, now_ms());
341    if !late.is_empty() {
342        req.message = format!("{late}{}", req.message);
343    }
344    req
345}
346
347/// Fetch the files sent with `inj` into `req`. A relay that cannot be reached gives the claim back.
348pub(super) async fn attach_files(
349    base: &str,
350    http: &reqwest::Client,
351    agent_token: &str,
352    agent_id: &str,
353    inj: &PendingInj,
354    req: &mut InjectionRequest,
355    delivered_at: &str,
356) -> Result<(), GivenBack> {
357    // Files sent with it: fetched now that the claim is ours. A relay that
358    // can't be reached gives the claim back, for a retry with its files.
359    if let Some(files) = inj.files.clone() {
360        if let Err(e) =
361            crate::muxbus::server_hooks::hooks().fetch_files(base, http, agent_token, agent_id, req, files, inj.wan_msg_id.as_deref()).await
362        {
363            tracing::warn!(injection_id = %inj.id, error = %e, "cloud_subscriber: files not fetched; releasing for a retry");
364            release(base, http, agent_token, agent_id, &inj.id, delivered_at).await;
365            return Err(GivenBack);
366        }
367        crate::muxbus::server_hooks::hooks().prepare_files(req).await;
368    }
369    Ok(())
370}
371
372/// A verified signed notice this agent already got under another delivery id: the sender signs once and may send
373/// twice (a retry of a call the relay had taken), and a replay looks the same. Neither is shown: one warning names
374/// both ids, and the caller delivers nothing. False for every other message.
375pub(super) fn is_repeat(inj: &PendingInj, agent_id: &str, checked: &Checked) -> bool {
376    let Some(delivered_as) = &checked.repeat_of else { return false };
377    tracing::warn!(
378        injection_id = %inj.id,
379        delivered_as = %delivered_as,
380        agent_id = %agent_id,
381        "cloud_subscriber: a signed notice already delivered to this agent came again under another delivery id; not delivered again"
382    );
383    true
384}
385
386/// The review, checks or merge event `inj` makes once it is accepted (`backend::pr_flow`): only when its
387/// signature verified under the trusted key and is fresh, and it was pulled for the agent it is delivered to.
388pub(super) fn pr_flow(inj: &PendingInj, checked: &Checked, req: &InjectionRequest) -> Vec<crate::backend::pr_flow::Accepted> {
389    pr_flow_of(inj, checked.reagent_verified == Some(true), &req.target_agent)
390}
391
392/// [`pr_flow`] for a notice whose verdict is already read as `genuine`.
393fn pr_flow_of(inj: &PendingInj, genuine: bool, agent: &str) -> Vec<crate::backend::pr_flow::Accepted> {
394    let notice = crate::backend::pr_flow::Notice { id: &inj.id, agent, text: &inj.message, genuine };
395    crate::backend::pr_flow::accept_now(inj.flow.as_ref(), &notice)
396}
397
398/// Note a signature as seen, and the PR event the notice made, once its message is delivered.
399pub(super) fn record_delivered(checked: &Checked, pr_flow: &[crate::backend::pr_flow::Accepted]) {
400    crate::backend::pr_flow::note_all(pr_flow);
401    if let Some((msg_id, agent, inj_id)) = &checked.reagent_delivery {
402        reagent_age::record_delivered(msg_id, agent, inj_id, now_unix_secs());
403    }
404    if let Some(wan) = &checked.wan_store {
405        crate::muxbus::wan_verify::record_delivered(wan, &checked.wan_verdict, &checked.wan_row, now_unix_secs());
406    }
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412
413    // A signature made offline under the production `reagent-v1` key over ("msg-1", "github-consumer", "agentx",
414    // 1000, "hello"): the same fixture as `server/tests/reactive/verify_reagent_signature_tests.rs`.
415    const SIG: &str = "FCFjcvAzla329a39u8fFxOvRWaH1R2fUn8RsGtP9RaIbLbaS3aXgAQ7YB4ssWV5TDvAeGrwSkHfoeGi11iCPBg==";
416    const SIGNED_AT: i64 = 1_000;
417
418    fn notice(id: &str, created_at: Option<&str>, sig: &str) -> PendingInj {
419        serde_json::from_value(serde_json::json!({
420            "id": id,
421            "source_agent": "github-consumer",
422            "message": "hello",
423            "created_at": created_at,
424            "reagent_sig": sig,
425            "reagent_key_id": "reagent-v1",
426            "reagent_msg_id": "msg-1",
427            "reagent_ts_secs": SIGNED_AT,
428        }))
429        .unwrap()
430    }
431
432    // 1970-01-01T00:16:45Z, five seconds after the signature was made.
433    const ACCEPTED: &str = "1970-01-01T00:16:45Z";
434
435    #[test]
436    fn a_notice_signed_and_accepted_together_and_delivered_twenty_minutes_later_verifies() {
437        // Signed 16:46, accepted 16:46, delivered 17:06.
438        assert_eq!(reagent_verdict(&notice("inj-1", Some(ACCEPTED), SIG), "agentx", SIGNED_AT + 20 * 60), Some(true));
439    }
440
441    #[test]
442    fn a_relay_time_that_does_not_fit_falls_back_to_the_delivery_time_rule() {
443        let late = SIGNED_AT + 20 * 60;
444        // No time from the relay (an older relay).
445        assert_eq!(reagent_verdict(&notice("inj-1", None, SIG), "agentx", late), Some(false));
446        // Accepted in the future, or before it was signed (beyond skew).
447        assert_eq!(reagent_verdict(&notice("inj-1", Some("1970-01-01T01:00:00Z"), SIG), "agentx", late), Some(false));
448        assert_eq!(reagent_verdict(&notice("inj-1", Some("1970-01-01T00:00:00Z"), SIG), "agentx", late), Some(false));
449        // Accepted more than ten minutes after it was signed.
450        assert_eq!(reagent_verdict(&notice("inj-1", Some("1970-01-01T00:27:00Z"), SIG), "agentx", late), Some(false));
451        // Fresh at delivery needs no time from the relay.
452        assert_eq!(reagent_verdict(&notice("inj-1", None, SIG), "agentx", SIGNED_AT + 60), Some(true));
453    }
454
455    #[test]
456    fn a_notice_past_the_longest_hold_is_not_trusted_whatever_the_relay_says() {
457        let at_the_end = SIGNED_AT + reagent_age::SIG_MAX_HOLD_SECS;
458        assert_eq!(reagent_verdict(&notice("inj-1", Some(ACCEPTED), SIG), "agentx", at_the_end), Some(true));
459        assert_eq!(reagent_verdict(&notice("inj-1", Some(ACCEPTED), SIG), "agentx", at_the_end + 1), Some(false));
460    }
461
462    #[test]
463    fn a_genuine_signature_that_fails_only_the_age_rules_is_expired_not_invalid() {
464        let late = SIGNED_AT + 20 * 60;
465        // No time from the relay: past the delivery-time window, signature genuine. Still `Some(false)`, so still
466        // sensitive and stopped; only the label differs.
467        let held = notice("inj-1", None, SIG);
468        assert_eq!(reagent_verdict(&held, "agentx", late), Some(false));
469        assert!(reagent_expired(&held, "agentx", late));
470        // Past the longest hold, whatever the relay says.
471        assert!(reagent_expired(&notice("inj-1", Some(ACCEPTED), SIG), "agentx", SIGNED_AT + reagent_age::SIG_MAX_HOLD_SECS + 1));
472        // Not expired: it verifies, or its signature is not genuine, or it carries none.
473        assert!(!reagent_expired(&notice("inj-1", Some(ACCEPTED), SIG), "agentx", late));
474        assert!(!reagent_expired(&notice("inj-1", None, "AAAA"), "agentx", late));
475        assert!(!reagent_expired(&notice("inj-1", None, SIG), "agenty", late));
476        let mut unsigned = notice("inj-1", None, SIG);
477        unsigned.reagent_sig = None;
478        assert!(!reagent_expired(&unsigned, "agentx", late));
479    }
480
481    #[test]
482    fn a_second_copy_of_a_delivered_signed_message_still_verifies_and_is_dropped_not_shown_as_forged() {
483        let now = SIGNED_AT + 20 * 60;
484        // Not delivered yet: neither copy is a repeat, so a first attempt that never reached the agent does not
485        // use up its retry.
486        assert_eq!(reagent_age::delivered_under_another("msg-1", "agentx", "inj-retry", now), None);
487        // The first copy is delivered.
488        assert_eq!(reagent_verdict(&notice("inj-first", Some(ACCEPTED), SIG), "agentx", now), Some(true));
489        reagent_age::record_delivered("msg-1", "agentx", "inj-first", now);
490        // The second, under another delivery id: still a genuine signature, and a repeat of the first.
491        assert_eq!(reagent_verdict(&notice("inj-retry", Some(ACCEPTED), SIG), "agentx", now + 10), Some(true));
492        assert_eq!(reagent_age::delivered_under_another("msg-1", "agentx", "inj-retry", now + 10).as_deref(), Some("inj-first"));
493        // The same delivery claimed again (a release and re-claim) is not.
494        assert_eq!(reagent_age::delivered_under_another("msg-1", "agentx", "inj-first", now + 10), None);
495        // Another recipient of the same signed id is not.
496        assert_eq!(reagent_age::delivered_under_another("msg-1", "agenty", "inj-retry", now + 10), None);
497    }
498
499    fn flow_notice(message: &str, flow: serde_json::Value) -> PendingInj {
500        serde_json::from_value(serde_json::json!({ "id": "inj-1", "source_agent": "github-consumer", "message": message, "flow": flow })).unwrap()
501    }
502
503    #[test]
504    fn a_flow_object_of_any_shape_parses_and_is_applied_only_to_a_genuine_notice_about_its_pr() {
505        let object = serde_json::json!({ "kind": "checks", "repo_id": 9, "pr": 64, "state": "failing", "head": "abcdef0" });
506        let text = "[ci failed] PR #64: a title";
507        // The pull still parses when the object is a shape this build does not know.
508        for odd in [serde_json::json!("x"), serde_json::json!([1, 2]), serde_json::json!(null), serde_json::json!({ "kind": 3 })] {
509            assert!(pr_flow_of(&flow_notice(text, odd), true, "lazo").is_empty());
510        }
511        assert_eq!(pr_flow_of(&flow_notice(text, object.clone()), true, "lazo").len(), 1);
512        // A forged, stale or unsigned notice (not `Some(true)`) shows nothing.
513        assert!(pr_flow_of(&flow_notice(text, object.clone()), false, "lazo").is_empty());
514        // Another PR's number in the signed text, or none in its first line: nothing.
515        assert!(pr_flow_of(&flow_notice("[ci failed] PR #65: a title", object.clone()), true, "lazo").is_empty());
516        assert!(pr_flow_of(&flow_notice("hello", object), true, "lazo").is_empty());
517        // A row with no object at all (an older relay, or a notice with no state) is an ordinary notice.
518        let plain: PendingInj = serde_json::from_value(serde_json::json!({ "id": "inj-1", "message": text })).unwrap();
519        assert!(plain.flow.is_none() && pr_flow_of(&plain, true, "lazo").is_empty());
520    }
521
522    #[test]
523    fn a_bad_or_missing_signature_is_judged_exactly_as_before() {
524        let now = SIGNED_AT + 20 * 60;
525        // Wrong signature: present and failing.
526        assert_eq!(reagent_verdict(&notice("inj-1", Some(ACCEPTED), "AAAA"), "agentx", now), Some(false));
527        // Another agent's target: the signature covers who it was for.
528        assert_eq!(reagent_verdict(&notice("inj-1", Some(ACCEPTED), SIG), "agenty", now), Some(false));
529        // No signature at all is no verdict.
530        let mut unsigned = notice("inj-1", Some(ACCEPTED), SIG);
531        unsigned.reagent_sig = None;
532        assert_eq!(reagent_verdict(&unsigned, "agentx", now), None);
533    }
534}