Skip to main content

greentic_runner_host/runner/
runtime_session_resumer.rs

1//! Production [`SessionResumer`] that resumes a paused flow by feeding a
2//! synthesized [`IngressEnvelope`] back through the runtime ingress entry
3//! ([`StateMachineRuntime::handle`]).
4//!
5//! ## How a resume is keyed (verified against `engine/runtime.rs`)
6//!
7//! When a `sorla.call await` node pauses, `PackFlowAdapter::call` persists the
8//! wait via `FlowResumeStore::save(envelope, wait)`. The wait is keyed by
9//! `build_store_ctx`, which derives:
10//!   * a **store hint** = `session_hint` (else `canonical_session_hint`), and
11//!     when `pack_id` is present, suffixed with `::pack=<pack_id>`;
12//!   * a **user id** = `sha256(store_hint)` (see `derive_user_id`);
13//!   * a **reply scope** = the envelope's `ReplyScope` (whose `scope_hash`
14//!     covers `conversation`/`thread`/`reply_to`).
15//!
16//! To resume, `FlowResumeStore::fetch(envelope)` re-derives the same triplet,
17//! so the synthesized envelope MUST reproduce the *exact* store hint and reply
18//! scope used at save time. The dispatch correlation id echoed in the response
19//! is `ctx.session_id` — the canonical session hint (optionally carrying the
20//! `::pack=<id>` suffix). This resumer splits that suffix off, sets the BARE
21//! hint as `session_hint` (so `build_store_ctx` re-appends the pack suffix
22//! exactly once), carries the recovered `pack_id`, and rebuilds the reply scope
23//! by parsing the conversation out of the canonical hint
24//! (`tenant:provider:channel:conversation:user`).
25//!
26//! ### Keying + routing caveat (IMPORTANT — see PR notes)
27//!
28//! Resuming through `handle` requires the synthesized envelope to (a) ROUTE via
29//! `StateMachine::step`, which needs a *registered* `(pack_id, flow_id)`, and
30//! (b) KEY the saved wait via `FlowResumeStore::fetch`, which needs the store
31//! hint (`<bare hint>::pack=<pack_id>`) and the reply scope (`scope_hash` over
32//! `conversation`/`thread`/`reply_to`).
33//!
34//! The dispatch wire contract ([`greentic_types::RuntimeDispatchResponse`] plus
35//! the `Greentic-*` headers) carries only `(tenant, env, correlation_id)`. The
36//! correlation id is the canonical session hint, which embeds the conversation
37//! (4th `:`-segment) but NOT the `pack_id` or `flow_id` needed to route.
38//!
39//! This resumer recovers `pack_id` from a `::pack=<id>` suffix (the convention
40//! pinned by `tests/sorla_node.rs`, where `ctx.session_id` carries it) and
41//! `flow_id` from an additional `::flow=<id>` marker. For production resume to
42//! work, the dispatch side must therefore emit a correlation id of the form
43//! `<bare hint>::pack=<pack_id>::flow=<flow_id>` (or the wire contract must be
44//! extended to carry pack/flow, or a server-side `correlation_id → (pack, flow,
45//! scope)` map must exist). A bare canonical hint alone is NOT resumable.
46//!
47//! Waits whose original inbound used a non-empty `thread`/`reply_to` ARE
48//! resumable: `execute_sorla_call` appends `::thread=<t>`/`::reply=<r>` markers
49//! (each omitted when empty), and this resumer strips them and feeds them back
50//! into the synthesized `ReplyScope` so `fetch` recomputes the same
51//! `scope_hash` `save` used. The no-thread case is unchanged (no markers
52//! emitted → `thread`/`reply_to` stay `None`).
53//!
54//! ### The per-dispatch nonce (`::n=`, approval runtime only)
55//!
56//! An `approval.call` correlation id ends with `::n=<32 lowercase hex>`, minted
57//! per dispatch, so two approvals in one conversation are two ids at the
58//! responder (greentic-designer-admin UNIQUE-indexes the id). It is always the
59//! LAST segment and is stripped FIRST here, before any other marker, so the
60//! store hint and reply scope — and therefore the saved wait's key — are
61//! exactly what they were without it. The park stays keyed per conversation.
62//!
63//! The nonce is what lets a response be matched to its OWN gate: the parked
64//! snapshot records the id each pending approval was published under, and
65//! [`RuntimeSessionResumer::resume`] refuses a nonced response that names a
66//! different one (an earlier gate's late decision, or its watchdog `timeout`
67//! arriving after the conversation moved on) instead of feeding it to
68//! whichever gate is parked now. An id with no nonce (every other runtime, and
69//! any id minted before this segment existed) parses and resumes exactly as
70//! before and is never verified.
71
72use anyhow::Result;
73use async_trait::async_trait;
74use greentic_types::{ReplyScope, TenantCtx};
75use serde_json::Value;
76use std::sync::Arc;
77
78use super::dispatch_listener::{ResumeOutcome, SessionResumer};
79use crate::engine::runtime::{IngressEnvelope, StateMachineRuntime};
80use crate::runner::engine::{ParkedApproval, response_authenticates};
81
82/// Marker appended to a store hint when a pack id is known (mirrors
83/// `build_store_ctx` in `engine/runtime.rs`).
84const PACK_HINT_MARKER: &str = "::pack=";
85
86/// Marker carrying the routing flow id in the correlation id. Unlike `::pack=`,
87/// this is NOT part of the store hint — it is consumed only to route the resume
88/// envelope through `StateMachine::step`, which requires a registered
89/// `(pack_id, flow_id)`. It is stripped before the store hint is derived.
90const FLOW_HINT_MARKER: &str = "::flow=";
91
92/// Marker carrying the originating inbound `ReplyScope.thread`. The store key
93/// (`FlowResumeStore::save`) hashes the reply scope's `thread`/`reply_to`, so a
94/// wait saved against a non-empty thread is only re-keyable if the resumer
95/// reproduces that thread. The dispatch side (`execute_sorla_call`) appends this
96/// marker (omitting it when the thread is empty). It is stripped before the
97/// store hint is derived and fed back into the synthesized `ReplyScope`.
98const THREAD_HINT_MARKER: &str = "::thread=";
99
100/// Marker carrying the originating inbound `ReplyScope.reply_to`. See
101/// [`THREAD_HINT_MARKER`]; same contract for `reply_to`.
102const REPLY_HINT_MARKER: &str = "::reply=";
103
104/// Lossless (base64url, no padding) variants of the thread / reply / conversation
105/// markers. A raw value is only emitted verbatim (`::thread=<t>`) when it is a
106/// plain token; anything containing `:` or other punctuation is encoded so it
107/// cannot collide with the `::` marker delimiter or the `:`-split hint.
108const THREAD_B64_MARKER: &str = "::thr64=";
109const REPLY_B64_MARKER: &str = "::rpl64=";
110const CONVERSATION_B64_MARKER: &str = "::cnv64=";
111
112fn is_plain_token(value: &str) -> bool {
113    !value.is_empty()
114        && value
115            .bytes()
116            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
117}
118
119/// Encode one marker value: verbatim when it is a plain token (backward
120/// compatible with the original wire form), base64url otherwise.
121fn push_marker(out: &mut String, raw_marker: &str, b64_marker: &str, value: &str) {
122    use base64::Engine as _;
123    if is_plain_token(value) {
124        out.push_str(raw_marker);
125        out.push_str(value);
126    } else {
127        out.push_str(b64_marker);
128        out.push_str(&base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(value.as_bytes()));
129    }
130}
131
132/// Append the conversation / thread / reply markers for `scope` to a
133/// correlation id (each omitted when empty). The conversation is carried
134/// explicitly so the resumer never has to re-derive it by splitting the hint
135/// on `:` (lossy when a segment contains `:`).
136pub(crate) fn push_scope_markers(out: &mut String, scope: &ReplyScope) {
137    // A plain-token conversation is recovered from the hint exactly; only a
138    // conversation the `:`-split would mangle needs the explicit marker.
139    if !scope.conversation.is_empty() && !is_plain_token(&scope.conversation) {
140        push_marker(out, "::cnv=", CONVERSATION_B64_MARKER, &scope.conversation);
141    }
142    if let Some(thread) = scope.thread.as_deref().filter(|v| !v.is_empty()) {
143        push_marker(out, THREAD_HINT_MARKER, THREAD_B64_MARKER, thread);
144    }
145    if let Some(reply_to) = scope.reply_to.as_deref().filter(|v| !v.is_empty()) {
146        push_marker(out, REPLY_HINT_MARKER, REPLY_B64_MARKER, reply_to);
147    }
148}
149
150/// Strip a trailing raw-or-base64 marker pair (`raw_marker` / `b64_marker`).
151/// A base64 marker whose payload does not decode as UTF-8 is left in place.
152fn split_value_marker(value: &str, raw_marker: &str, b64_marker: &str) -> (String, Option<String>) {
153    use base64::Engine as _;
154    if let Some((prefix, captured)) = value.rsplit_once(b64_marker)
155        && !captured.is_empty()
156        && let Ok(bytes) = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(captured)
157        && let Ok(decoded) = String::from_utf8(bytes)
158    {
159        return (prefix.to_string(), Some(decoded));
160    }
161    split_marker(value, raw_marker)
162}
163
164/// A dispatch correlation id decomposed into its parts.
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub(crate) struct ParsedCorrelation {
167    /// The store hint with every marker removed.
168    pub bare_hint: String,
169    pub pack_id: Option<String>,
170    pub flow_id: Option<String>,
171    pub conversation: Option<String>,
172    pub thread: Option<String>,
173    pub reply_to: Option<String>,
174    pub nonce: Option<String>,
175}
176
177/// Parse a correlation id by stripping markers from the END, in the reverse of
178/// the order they were appended. The bare hint may itself contain `::` (for
179/// example the `ep=<eid>::` endpoint prefix), so it is never split on `::`.
180pub(crate) fn parse_correlation(correlation_id: &str) -> ParsedCorrelation {
181    let (without_nonce, nonce) = split_dispatch_nonce(correlation_id);
182    let (rest, reply_to) = split_value_marker(without_nonce, REPLY_HINT_MARKER, REPLY_B64_MARKER);
183    let (rest, thread) = split_value_marker(&rest, THREAD_HINT_MARKER, THREAD_B64_MARKER);
184    let (rest, conversation) = split_value_marker(&rest, "::cnv=", CONVERSATION_B64_MARKER);
185    let (rest, flow_id) = split_marker(&rest, FLOW_HINT_MARKER);
186    let (bare_hint, pack_id) = split_pack_suffix(&rest);
187    ParsedCorrelation {
188        bare_hint,
189        pack_id,
190        flow_id,
191        conversation,
192        thread,
193        reply_to,
194        nonce: nonce.map(str::to_string),
195    }
196}
197
198/// Split the optional `ep=<eid>::` endpoint prefix off a canonical hint.
199fn split_endpoint_prefix(hint: &str) -> (Option<&str>, &str) {
200    if let Some(rest) = hint.strip_prefix("ep=")
201        && let Some((eid, tail)) = rest.split_once("::")
202    {
203        return (Some(eid), tail);
204    }
205    (None, hint)
206}
207
208/// Marker for the per-dispatch nonce an `approval` correlation id ends with.
209/// Always the LAST segment; see the module docs.
210pub(crate) const NONCE_HINT_MARKER: &str = "::n=";
211
212/// Length of a nonce value: 16 random bytes, hex-encoded (the width of a v4
213/// UUID in its `simple` form).
214const NONCE_HEX_LEN: usize = 32;
215
216/// Mint a fresh per-dispatch nonce: 32 lowercase hex characters.
217pub(crate) fn new_dispatch_nonce() -> String {
218    use rand::{RngExt, rng};
219    let mut bytes = [0u8; NONCE_HEX_LEN / 2];
220    rng().fill(&mut bytes);
221    hex::encode(bytes)
222}
223
224/// Split a trailing `::n=<nonce>` off `correlation_id`.
225///
226/// Strict on purpose: only a LAST segment of exactly 32 lowercase hex
227/// characters is a nonce. Anything else — including a thread or reply value
228/// that happens to contain `::n=` — leaves the id unchanged, so an id without
229/// a nonce parses exactly as it always did.
230pub fn split_dispatch_nonce(correlation_id: &str) -> (&str, Option<&str>) {
231    match correlation_id.rsplit_once(NONCE_HINT_MARKER) {
232        Some((prefix, nonce))
233            if nonce.len() == NONCE_HEX_LEN
234                && nonce
235                    .bytes()
236                    .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) =>
237        {
238            (prefix, Some(nonce))
239        }
240        _ => (correlation_id, None),
241    }
242}
243
244/// Resumes paused flow sessions by driving the runtime ingress entry.
245pub struct RuntimeSessionResumer {
246    runtime: Arc<StateMachineRuntime>,
247    mode: AdmissionMode,
248    watchdog_notifier: Option<crate::runner::dispatch_listener::WatchdogNotifier>,
249}
250
251/// How strictly a NONCED response must match the park before it resumes.
252#[derive(Clone, Copy, Debug, PartialEq, Eq)]
253pub(crate) enum AdmissionMode {
254    /// The NATS rail's rule: a nonced response with NOTHING parked is left to
255    /// the runtime (which then starts a fresh run), and a park recorded before
256    /// ids were stored may take any nonced response.
257    Lenient,
258    /// The HTTP approval inbox's rule (`runner::approval_http`): a nonced
259    /// response resumes ONLY a parked approval recorded under exactly that id.
260    /// Nothing parked, or a park without a recorded id, is
261    /// [`Admission::WrongGate`] — a decision fetched for a gate that is gone
262    /// must never start a fresh run from the flow's entrypoint.
263    Strict,
264}
265
266impl RuntimeSessionResumer {
267    /// Build a resumer over the live runtime ingress handle.
268    ///
269    /// `runtime` is the same [`StateMachineRuntime`] that serves inbound
270    /// ingress; resuming routes through its `handle` so the existing
271    /// `FlowResumeStore::fetch` + `FlowEngine::resume` path runs unchanged.
272    pub fn new(runtime: Arc<StateMachineRuntime>) -> Self {
273        Self {
274            runtime,
275            mode: AdmissionMode::Lenient,
276            watchdog_notifier: None,
277        }
278    }
279
280    /// Announce every admitted response to other replicas (so they retire
281    /// their watchdog for it) at admission, before the resumed flow runs.
282    #[must_use]
283    pub fn with_watchdog_notifier(
284        mut self,
285        notifier: crate::runner::dispatch_listener::WatchdogNotifier,
286    ) -> Self {
287        self.watchdog_notifier = Some(notifier);
288        self
289    }
290
291    /// A resumer for the HTTP approval inbox: a nonced response resumes only
292    /// the approval parked under exactly that id, and NEVER falls through to a
293    /// fresh run when nothing is parked (see [`AdmissionMode::Strict`]).
294    pub fn strict(runtime: Arc<StateMachineRuntime>) -> Self {
295        Self {
296            runtime,
297            mode: AdmissionMode::Strict,
298            watchdog_notifier: None,
299        }
300    }
301
302    /// Build the [`IngressEnvelope`] that re-keys the saved wait.
303    ///
304    /// Split out (and `pub(crate)`) so it can be unit-tested without a broker.
305    ///
306    /// * `session_hint` is set to the bare canonical hint so
307    ///   `FlowResumeStore::fetch` re-derives the same store key (with the pack
308    ///   suffix re-appended exactly once by `build_store_ctx`).
309    /// * `pack_id` is recovered from the `::pack=<id>` suffix when present so
310    ///   `StateMachineRuntime::handle` (which requires a `pack_id`) succeeds and
311    ///   the store hint is reproduced identically.
312    /// * `flow_id` is recovered from the `::flow=<id>` marker when present so the
313    ///   resume routes through `StateMachine::step` (which requires a registered
314    ///   `(pack_id, flow_id)`). The saved wait's snapshot then supplies the real
315    ///   resume flow/node. When absent, the bare pack id is used as a fallback
316    ///   flow id (only relevant when no wait is found).
317    /// * the reply scope's `conversation` is parsed from the canonical hint so
318    ///   the scope hash matches the saved wait.
319    /// * `payload` carries the runtime `output` as the resume flow input.
320    ///
321    /// NOTE: the dispatch wire contract ([`greentic_types::RuntimeDispatchResponse`]
322    /// plus headers) carries only `(tenant, env, correlation_id)`. Routing a
323    /// resume requires `pack_id` AND `flow_id`; this resumer recovers them from
324    /// the `::pack=`/`::flow=` markers in the correlation id. Until those markers
325    /// are emitted at dispatch time (or the response carries the fields), a bare
326    /// canonical hint cannot be resumed — see the module docs.
327    pub(crate) fn build_resume_envelope(
328        tenant: &TenantCtx,
329        correlation_id: &str,
330        output: Value,
331    ) -> IngressEnvelope {
332        // Strip markers in the REVERSE of the order they were appended at
333        // dispatch (`pack`, `flow`, `thread`, `reply`, `n`) so each
334        // `rsplit_once` sees its own marker last. Each marker is optional —
335        // absent markers leave the string unchanged (back-compat with the
336        // no-thread and no-nonce cases). The nonce is NOT part of the store
337        // key: dropping it here is what keeps the park keyed per conversation.
338        let parsed = parse_correlation(correlation_id);
339        let bare_hint = parsed.bare_hint;
340        let pack_id = parsed.pack_id;
341        let (endpoint_id, hint_body) = split_endpoint_prefix(&bare_hint);
342        let endpoint_id = endpoint_id.map(str::to_string);
343        let parts: Vec<&str> = hint_body.splitn(5, ':').collect();
344        let provider = parts.get(1).map(|segment| segment.to_string());
345        let channel = parts.get(2).map(|segment| segment.to_string());
346        // The explicit conversation marker wins over the lossy `:`-split.
347        let conversation = parsed
348            .conversation
349            .or_else(|| parts.get(3).map(|segment| segment.to_string()));
350        let user = parts.get(4).map(|segment| segment.to_string());
351        let thread = parsed.thread;
352        let reply_to = parsed.reply_to;
353        let flow_marker = parsed.flow_id;
354
355        let flow_id = flow_marker
356            .or_else(|| pack_id.clone())
357            .unwrap_or_else(|| "resume.flow".to_string());
358
359        IngressEnvelope {
360            tenant: tenant.tenant_id.to_string(),
361            env: Some(tenant.env.to_string()),
362            pack_id,
363            // Routes the resume into `PackFlowAdapter::call`; the saved wait's
364            // snapshot overrides the actual resume flow/node from there.
365            flow_id,
366            flow_type: None,
367            action: None,
368            // The store hint is `session_hint` (+ `::pack=<pack_id>` re-appended
369            // by `build_store_ctx`). We set the BARE hint here and carry the pack
370            // id separately so the suffix is reproduced exactly once — setting
371            // the suffixed correlation id here AND `pack_id` would double-suffix
372            // and miss the saved wait.
373            session_hint: Some(bare_hint.clone()),
374            provider,
375            channel,
376            conversation: conversation.clone(),
377            user,
378            // A session resume re-enters through its snapshot, not a card nav target.
379            entry_node: None,
380            activity_id: None,
381            timestamp: None,
382            messaging_endpoint_id: endpoint_id,
383            payload: output,
384            metadata: None,
385            // Reproduce the EXACT reply scope used at save time so
386            // `FlowResumeStore::fetch` recomputes the same `scope_hash`. The
387            // conversation comes from the bare hint; thread/reply_to are
388            // recovered from the `::thread=`/`::reply=` markers (absent markers
389            // → `None`, matching the no-thread case).
390            reply_scope: conversation.map(|conversation| ReplyScope {
391                conversation,
392                thread,
393                reply_to,
394                correlation: None,
395            }),
396        }
397    }
398}
399
400#[async_trait]
401impl SessionResumer for RuntimeSessionResumer {
402    async fn resume(&self, tenant: TenantCtx, correlation_id: &str, output: Value) -> Result<()> {
403        self.resume_checked(tenant, correlation_id, output)
404            .await
405            .map(|_| ())
406    }
407
408    async fn resume_checked(
409        &self,
410        tenant: TenantCtx,
411        correlation_id: &str,
412        output: Value,
413    ) -> Result<ResumeOutcome> {
414        let nonced = split_dispatch_nonce(correlation_id).1.is_some();
415        let envelope = Self::build_resume_envelope(&tenant, correlation_id, output.clone());
416        // Read for EVERY response, not only nonced ones: a sender that omits
417        // the nonce must not skip the token check. A read failure is fatal for
418        // a nonced (approval) response, as before; for any other response it
419        // falls through to the runtime, where the approval gate re-checks the
420        // token itself before deciding anything.
421        // Check-then-resume under the session's turn lock: the park read for
422        // admission and the resume that consumes it must be one unit, or a
423        // user turn (or a duplicate response) can resume the same snapshot in
424        // between. The nested `handle` re-enters the lock on this task and
425        // skips it.
426        let runtime = &self.runtime;
427        let lock_key = runtime.turn_lock_key(&envelope);
428        runtime
429            .with_turn_lock(lock_key, async {
430            let parked = match self.runtime.parked_approvals(&envelope).await {
431                Ok(parked) => parked,
432                Err(error) if !nonced => {
433                    tracing::warn!(%error, correlation_id = %crate::log_safe::log_safe(correlation_id), "could not read the parked flow before resuming; the gate re-checks the response itself");
434                    None
435                }
436                Err(error) => return Err(error),
437            };
438            match admit_response_with(self.mode, correlation_id, &output, parked.as_deref()) {
439                Admission::Resume => {
440                    // Retire the deadline watchdog at admission, BEFORE the resumed
441                    // flow runs: `handle` runs it until it next parks, and that
442                    // park may register a new watchdog under this same
443                    // (deterministic) id which a later cancel would kill.
444                    crate::runner::dispatch_listener::retire_watchdog_on_admission(
445                        self.watchdog_notifier.as_ref(),
446                        correlation_id,
447                    );
448                }
449                Admission::WrongGate => {
450                    // Not an error: the response is real, it just no longer has a
451                    // gate to land on. Resuming would hand an earlier gate's
452                    // decision (or its watchdog's late `timeout`) to a different
453                    // gate — or to whatever the conversation is parked on now.
454                    tracing::warn!(
455                        correlation_id = %crate::log_safe::log_safe(correlation_id),
456                        "dropping approval response: it does not match the approval this conversation is parked on"
457                    );
458                    return Ok(ResumeOutcome::Dropped);
459                }
460                Admission::BadToken => {
461                    // A security event: whoever sent this does not hold the token
462                    // the gate was issued (or is replaying a spent one). The gate
463                    // stays parked. The token is never logged.
464                    tracing::warn!(
465                        correlation_id = %crate::log_safe::log_safe(correlation_id),
466                        "dropping approval response: its decision_token is missing or does not match the one the parked approval was issued"
467                    );
468                    return Ok(ResumeOutcome::Dropped);
469                }
470            }
471            self.runtime
472                .handle(envelope)
473                .await
474                .map(|_| ResumeOutcome::Admitted)
475            })
476            .await
477    }
478}
479
480/// What the resumer does with a dispatch response, decided before the runtime
481/// sees it.
482#[derive(Debug, PartialEq, Eq)]
483pub(crate) enum Admission {
484    /// Hand it to the runtime.
485    Resume,
486    /// A NONCED approval response for an approval this conversation is not
487    /// parked on (greentic-runner#793).
488    WrongGate,
489    /// The approval it would land on was issued a `decision_token` and the
490    /// response does not carry it (greentic-runner#794).
491    BadToken,
492}
493
494/// Decide whether `response`, published under `correlation_id`, may resume
495/// the conversation's park.
496///
497/// `parked` is `None` when nothing is parked: that case is left to the runtime
498/// exactly as before these checks existed (a spent token cannot resurrect a
499/// gate — its mark is gone — and a fresh run re-dispatches rather than
500/// deciding).
501///
502/// Otherwise the candidates are the parked approvals the response could land
503/// on: for a nonced id, those published under this exact id (or recorded
504/// before ids were, which cannot be told apart); for an id with no nonce, all
505/// of them. A nonced response with no candidate is [`Admission::WrongGate`].
506/// A response resumes when some candidate was issued no token (a legacy park)
507/// or its token matches one; otherwise it is [`Admission::BadToken`]. An id
508/// with no nonce and no parked approval (the conversation waits on something
509/// else) is left to the runtime, as before.
510#[cfg(test)]
511pub(crate) fn admit_response(
512    correlation_id: &str,
513    response: &Value,
514    parked: Option<&[ParkedApproval]>,
515) -> Admission {
516    admit_response_with(AdmissionMode::Lenient, correlation_id, response, parked)
517}
518
519/// [`admit_response`] under an explicit [`AdmissionMode`]. `Strict` changes
520/// only the NONCED cases: nothing parked is [`Admission::WrongGate`] rather
521/// than [`Admission::Resume`], and a park must have recorded exactly this id.
522pub(crate) fn admit_response_with(
523    mode: AdmissionMode,
524    correlation_id: &str,
525    response: &Value,
526    parked: Option<&[ParkedApproval]>,
527) -> Admission {
528    let nonced = split_dispatch_nonce(correlation_id).1.is_some();
529    let strict = nonced && mode == AdmissionMode::Strict;
530    let Some(parked) = parked else {
531        return if strict {
532            Admission::WrongGate
533        } else {
534            Admission::Resume
535        };
536    };
537    let candidates: Vec<&ParkedApproval> = parked
538        .iter()
539        .filter(|park| {
540            if !nonced {
541                return true;
542            }
543            match park.correlation_id.as_deref() {
544                Some(recorded) => recorded == correlation_id,
545                None => !strict,
546            }
547        })
548        .collect();
549    if candidates.is_empty() {
550        return if nonced {
551            Admission::WrongGate
552        } else {
553            Admission::Resume
554        };
555    }
556    if candidates
557        .iter()
558        .any(|park| response_authenticates(response, park))
559    {
560        Admission::Resume
561    } else {
562        Admission::BadToken
563    }
564}
565
566/// Split a store hint into its bare canonical hint and the pack id encoded in
567/// the trailing `::pack=<id>` marker (if any). Mirrors the suffix added by
568/// `build_store_ctx`.
569fn split_pack_suffix(hint: &str) -> (String, Option<String>) {
570    split_marker(hint, PACK_HINT_MARKER)
571}
572
573/// Split `value` on the LAST occurrence of `marker`, returning the prefix and
574/// the captured (non-empty) trailing segment. When the marker is absent or the
575/// captured value is empty, the input is returned unchanged with `None`.
576fn split_marker(value: &str, marker: &str) -> (String, Option<String>) {
577    match value.rsplit_once(marker) {
578        Some((prefix, captured)) if !captured.is_empty() => {
579            (prefix.to_string(), Some(captured.to_string()))
580        }
581        _ => (value.to_string(), None),
582    }
583}
584
585#[cfg(test)]
586mod tests {
587    use super::*;
588    use greentic_types::{EnvId, TenantId};
589    use serde_json::json;
590    use std::str::FromStr;
591
592    fn tenant_ctx() -> TenantCtx {
593        TenantCtx::new(
594            EnvId::from_str("local").unwrap(),
595            TenantId::from_str("demo").unwrap(),
596        )
597    }
598
599    fn roundtrip(hint: &str, scope: ReplyScope) -> ParsedCorrelation {
600        let mut corr = format!("{hint}::pack=p.1::flow=f.1");
601        push_scope_markers(&mut corr, &scope);
602        parse_correlation(&corr)
603    }
604
605    #[test]
606    fn correlation_roundtrips_hostile_thread_reply_and_conversation() {
607        let scope = ReplyScope {
608            conversation: "conv:with::colons".into(),
609            thread: Some("t::flow=evil:1".into()),
610            reply_to: Some("r::pack=x::n=abc".into()),
611            correlation: None,
612        };
613        let parsed = roundtrip("demo:prov:chan:conv:with::colons:user", scope.clone());
614        assert_eq!(parsed.bare_hint, "demo:prov:chan:conv:with::colons:user");
615        assert_eq!(parsed.pack_id.as_deref(), Some("p.1"));
616        assert_eq!(parsed.flow_id.as_deref(), Some("f.1"));
617        assert_eq!(parsed.conversation.as_deref(), Some("conv:with::colons"));
618        assert_eq!(parsed.thread, scope.thread);
619        assert_eq!(parsed.reply_to, scope.reply_to);
620    }
621
622    #[test]
623    fn correlation_keeps_an_endpoint_prefixed_hint_intact() {
624        let scope = ReplyScope {
625            conversation: "conv".into(),
626            thread: Some("th".into()),
627            reply_to: None,
628            correlation: None,
629        };
630        let parsed = roundtrip("ep=eid-1::demo:prov:chan:conv:user", scope);
631        assert_eq!(parsed.bare_hint, "ep=eid-1::demo:prov:chan:conv:user");
632        // Plain tokens stay in the original, readable wire form.
633        let mut corr = String::new();
634        push_scope_markers(
635            &mut corr,
636            &ReplyScope {
637                conversation: "conv".into(),
638                thread: Some("th".into()),
639                reply_to: Some("rp".into()),
640                correlation: None,
641            },
642        );
643        assert_eq!(corr, "::thread=th::reply=rp");
644    }
645
646    #[test]
647    fn legacy_raw_markers_still_parse() {
648        let parsed = parse_correlation("demo:p:c:conv:u::pack=pk::flow=fl::thread=T1::reply=R1");
649        assert_eq!(parsed.bare_hint, "demo:p:c:conv:u");
650        assert_eq!(parsed.thread.as_deref(), Some("T1"));
651        assert_eq!(parsed.reply_to.as_deref(), Some("R1"));
652        assert_eq!(parsed.pack_id.as_deref(), Some("pk"));
653    }
654
655    #[test]
656    fn resume_envelope_recovers_endpoint_prefix_and_odd_conversation() {
657        let scope = ReplyScope {
658            conversation: "a:b".into(),
659            thread: None,
660            reply_to: None,
661            correlation: None,
662        };
663        let mut corr = "ep=eid::demo:prov:chan:a:b:user::pack=p::flow=f".to_string();
664        push_scope_markers(&mut corr, &scope);
665        let envelope =
666            RuntimeSessionResumer::build_resume_envelope(&tenant_ctx(), &corr, json!(null));
667        assert_eq!(envelope.messaging_endpoint_id.as_deref(), Some("eid"));
668        assert_eq!(
669            envelope.reply_scope.map(|scope| scope.conversation),
670            Some("a:b".to_string())
671        );
672        assert_eq!(
673            envelope.session_hint.as_deref(),
674            Some("ep=eid::demo:prov:chan:a:b:user")
675        );
676    }
677
678    #[test]
679    fn build_resume_envelope_sets_session_hint_to_correlation_id() {
680        let envelope = RuntimeSessionResumer::build_resume_envelope(
681            &tenant_ctx(),
682            "demo:provider:chan:conv:user",
683            json!({ "ok": true }),
684        );
685        assert_eq!(
686            envelope.session_hint.as_deref(),
687            Some("demo:provider:chan:conv:user")
688        );
689        assert_eq!(envelope.payload, json!({ "ok": true }));
690        assert_eq!(envelope.tenant, "demo");
691        assert_eq!(envelope.env.as_deref(), Some("local"));
692    }
693
694    #[test]
695    fn build_resume_envelope_parses_conversation_into_reply_scope() {
696        let envelope = RuntimeSessionResumer::build_resume_envelope(
697            &tenant_ctx(),
698            "demo:provider:chan:conv:user",
699            json!(null),
700        );
701        let scope = envelope.reply_scope.expect("reply scope from conversation");
702        assert_eq!(scope.conversation, "conv");
703        assert!(scope.thread.is_none());
704        assert!(scope.correlation.is_none());
705        assert_eq!(envelope.conversation.as_deref(), Some("conv"));
706        assert_eq!(envelope.provider.as_deref(), Some("provider"));
707        assert_eq!(envelope.channel.as_deref(), Some("chan"));
708        assert_eq!(envelope.user.as_deref(), Some("user"));
709    }
710
711    #[test]
712    fn build_resume_envelope_recovers_pack_id_from_suffix() {
713        let envelope = RuntimeSessionResumer::build_resume_envelope(
714            &tenant_ctx(),
715            "demo:provider:chan:conv:user::pack=greentic.demo",
716            json!(null),
717        );
718        assert_eq!(envelope.pack_id.as_deref(), Some("greentic.demo"));
719        // session_hint is the BARE hint; `build_store_ctx` re-appends the pack
720        // suffix exactly once, so it must not be carried here.
721        assert_eq!(
722            envelope.session_hint.as_deref(),
723            Some("demo:provider:chan:conv:user")
724        );
725        // conversation is still parsed from the bare hint, not the suffix.
726        assert_eq!(envelope.conversation.as_deref(), Some("conv"));
727    }
728
729    #[test]
730    fn build_resume_envelope_recovers_pack_and_flow_for_routing() {
731        let envelope = RuntimeSessionResumer::build_resume_envelope(
732            &tenant_ctx(),
733            "demo:provider:chan:conv:user::pack=greentic.demo::flow=wait.flow",
734            json!(null),
735        );
736        // flow id routes the resume; pack id keys it.
737        assert_eq!(envelope.flow_id, "wait.flow");
738        assert_eq!(envelope.pack_id.as_deref(), Some("greentic.demo"));
739        // the flow marker is stripped before deriving the store hint.
740        assert_eq!(
741            envelope.session_hint.as_deref(),
742            Some("demo:provider:chan:conv:user")
743        );
744        assert_eq!(envelope.conversation.as_deref(), Some("conv"));
745    }
746
747    #[test]
748    fn build_resume_envelope_recovers_thread_and_reply_into_scope() {
749        let envelope = RuntimeSessionResumer::build_resume_envelope(
750            &tenant_ctx(),
751            "demo:provider:chan:conv:user::pack=greentic.demo::flow=wait.flow::thread=topic-7::reply=msg-42",
752            json!(null),
753        );
754        // routing markers still recovered with thread/reply present.
755        assert_eq!(envelope.flow_id, "wait.flow");
756        assert_eq!(envelope.pack_id.as_deref(), Some("greentic.demo"));
757        // bare hint is clean of every marker.
758        assert_eq!(
759            envelope.session_hint.as_deref(),
760            Some("demo:provider:chan:conv:user")
761        );
762        let scope = envelope.reply_scope.expect("reply scope with thread/reply");
763        assert_eq!(scope.conversation, "conv");
764        assert_eq!(scope.thread.as_deref(), Some("topic-7"));
765        assert_eq!(scope.reply_to.as_deref(), Some("msg-42"));
766    }
767
768    #[test]
769    fn build_resume_envelope_recovers_thread_without_reply() {
770        let envelope = RuntimeSessionResumer::build_resume_envelope(
771            &tenant_ctx(),
772            "demo:provider:chan:conv:user::pack=greentic.demo::flow=wait.flow::thread=topic-7",
773            json!(null),
774        );
775        let scope = envelope.reply_scope.expect("reply scope with thread");
776        assert_eq!(scope.thread.as_deref(), Some("topic-7"));
777        assert!(scope.reply_to.is_none());
778        assert_eq!(
779            envelope.session_hint.as_deref(),
780            Some("demo:provider:chan:conv:user")
781        );
782    }
783
784    #[test]
785    fn build_resume_envelope_without_markers_leaves_thread_and_reply_none() {
786        // Back-compat: the no-thread gold path must keep thread/reply_to None.
787        let envelope = RuntimeSessionResumer::build_resume_envelope(
788            &tenant_ctx(),
789            "demo:provider:chan:conv:user::pack=greentic.demo::flow=wait.flow",
790            json!(null),
791        );
792        let scope = envelope.reply_scope.expect("reply scope from conversation");
793        assert!(scope.thread.is_none());
794        assert!(scope.reply_to.is_none());
795    }
796
797    #[test]
798    fn split_pack_suffix_handles_missing_and_empty_marker() {
799        assert_eq!(
800            split_pack_suffix("a:b:c:d:e"),
801            ("a:b:c:d:e".to_string(), None)
802        );
803        assert_eq!(
804            split_pack_suffix("a:b:c:d:e::pack=p"),
805            ("a:b:c:d:e".to_string(), Some("p".to_string()))
806        );
807        assert_eq!(
808            split_pack_suffix("a:b:c:d:e::pack="),
809            ("a:b:c:d:e::pack=".to_string(), None)
810        );
811    }
812
813    const NONCE: &str = "0123456789abcdef0123456789abcdef";
814
815    #[test]
816    fn new_dispatch_nonce_is_32_lowercase_hex_and_fresh() {
817        let a = new_dispatch_nonce();
818        let b = new_dispatch_nonce();
819        assert_eq!(a.len(), 32);
820        assert!(
821            a.bytes()
822                .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
823        );
824        assert_ne!(a, b, "two dispatches must not share a nonce");
825        let id = format!("h::pack=p::flow=f{NONCE_HINT_MARKER}{a}");
826        assert_eq!(
827            split_dispatch_nonce(&id),
828            ("h::pack=p::flow=f", Some(a.as_str()))
829        );
830    }
831
832    #[test]
833    fn split_dispatch_nonce_leaves_ids_without_a_nonce_unchanged() {
834        // No marker at all: the old format.
835        let old = "demo:provider:chan:conv:user::pack=greentic.demo::flow=wait.flow";
836        assert_eq!(split_dispatch_nonce(old), (old, None));
837        // A reply value that happens to contain `::n=` is not a nonce.
838        let reply = "a:b:c:d:e::pack=p::flow=f::reply=x::n=not-hex";
839        assert_eq!(split_dispatch_nonce(reply), (reply, None));
840        // Wrong length / upper case are not nonces either.
841        let short = "h::pack=p::n=abc";
842        assert_eq!(split_dispatch_nonce(short), (short, None));
843        let upper = format!("h::pack=p::n={}", NONCE.to_uppercase());
844        assert_eq!(split_dispatch_nonce(&upper), (upper.as_str(), None));
845    }
846
847    #[test]
848    fn a_nonce_does_not_change_the_resume_key() {
849        // The park is keyed per conversation: with or without the nonce the
850        // synthesized envelope must be identical, or the saved wait is missed.
851        let base = "demo:provider:chan:conv:user::pack=greentic.demo::flow=wait.flow::thread=topic-7::reply=msg-42";
852        let with_nonce = format!("{base}::n={NONCE}");
853        let plain = RuntimeSessionResumer::build_resume_envelope(&tenant_ctx(), base, json!(1));
854        let nonced =
855            RuntimeSessionResumer::build_resume_envelope(&tenant_ctx(), &with_nonce, json!(1));
856        assert_eq!(nonced.session_hint, plain.session_hint);
857        assert_eq!(
858            nonced.session_hint.as_deref(),
859            Some("demo:provider:chan:conv:user")
860        );
861        assert_eq!(nonced.pack_id, plain.pack_id);
862        assert_eq!(nonced.flow_id, "wait.flow");
863        let (scope, plain_scope) = (nonced.reply_scope.unwrap(), plain.reply_scope.unwrap());
864        assert_eq!(scope.thread.as_deref(), Some("topic-7"));
865        assert_eq!(
866            scope.reply_to.as_deref(),
867            Some("msg-42"),
868            "the nonce must not leak into reply_to"
869        );
870        assert_eq!(scope.scope_hash(), plain_scope.scope_hash());
871    }
872
873    #[test]
874    fn a_nonced_response_resumes_only_its_own_parked_approval() {
875        let mine = format!("h::pack=p::flow=f::n={NONCE}");
876        let other = format!("h::pack=p::flow=f::n={}", "f".repeat(32));
877        let untokened = |id: Option<&str>| ParkedApproval {
878            correlation_id: id.map(str::to_string),
879            token_fingerprint: None,
880        };
881        let r = json!({"ok": true, "output": {"decision": "approved"}});
882        // Nothing parked: left to the runtime, unchanged.
883        assert_eq!(admit_response(&mine, &r, None), Admission::Resume);
884        // Parked on this very approval.
885        assert_eq!(
886            admit_response(&mine, &r, Some(&[untokened(Some(&mine))])),
887            Admission::Resume
888        );
889        // Parked on a DIFFERENT approval in the same conversation.
890        assert_eq!(
891            admit_response(&mine, &r, Some(&[untokened(Some(&other))])),
892            Admission::WrongGate
893        );
894        // Parked, but not on any approval (e.g. a card after the gate passed).
895        assert_eq!(admit_response(&mine, &r, Some(&[])), Admission::WrongGate);
896        // A legacy mark with no recorded id cannot be verified: not refused.
897        assert_eq!(
898            admit_response(&mine, &r, Some(&[untokened(None)])),
899            Admission::Resume
900        );
901    }
902
903    fn tokened(id: &str, fingerprint: &str) -> ParkedApproval {
904        ParkedApproval {
905            correlation_id: Some(id.to_string()),
906            token_fingerprint: Some(fingerprint.to_string()),
907        }
908    }
909
910    fn response(token: Option<&str>) -> Value {
911        match token {
912            Some(token) => {
913                json!({"ok": true, "output": {"decision": "approved", "decision_token": token}})
914            }
915            None => json!({"ok": true, "output": {"decision": "approved"}}),
916        }
917    }
918
919    #[test]
920    fn a_tokened_park_resumes_only_on_the_right_token() {
921        use crate::runner::approval_token::issue;
922        let mine = format!("h::pack=p::flow=f::n={NONCE}");
923        let issued = issue();
924        let parks = [tokened(&mine, &issued.fingerprint)];
925        assert_eq!(
926            admit_response(&mine, &response(Some(&issued.token)), Some(&parks)),
927            Admission::Resume
928        );
929        assert_eq!(
930            admit_response(&mine, &response(Some(&issue().token)), Some(&parks)),
931            Admission::BadToken,
932            "a wrong token is refused"
933        );
934        assert_eq!(
935            admit_response(&mine, &response(None), Some(&parks)),
936            Admission::BadToken,
937            "a missing token is refused"
938        );
939    }
940
941    #[test]
942    fn dropping_the_nonce_does_not_skip_the_token_check() {
943        // The derived, guessable id with no `::n=`: the attack from #794.
944        use crate::runner::approval_token::issue;
945        let issued = issue();
946        let parks = [tokened(
947            &format!("h::pack=p::flow=f::n={NONCE}"),
948            &issued.fingerprint,
949        )];
950        let guessed = "h::pack=p::flow=f";
951        assert_eq!(
952            admit_response(guessed, &response(None), Some(&parks)),
953            Admission::BadToken
954        );
955        assert_eq!(
956            admit_response(guessed, &response(Some(&issued.token)), Some(&parks)),
957            Admission::Resume
958        );
959    }
960
961    /// The HTTP approval inbox's rule: a decision it fetched for a gate that is
962    /// no longer parked must never fall through to a fresh run.
963    #[test]
964    fn strict_mode_never_resumes_a_nonced_response_with_nothing_parked() {
965        use crate::runner::approval_token::issue;
966        let mine = format!("h::pack=p::flow=f::n={NONCE}");
967        let issued = issue();
968        let r = response(Some(&issued.token));
969        assert_eq!(
970            admit_response_with(AdmissionMode::Strict, &mine, &r, None),
971            Admission::WrongGate,
972            "nothing parked: a fresh run would re-execute the flow and raise a second approval"
973        );
974        assert_eq!(
975            admit_response_with(AdmissionMode::Strict, &mine, &r, Some(&[])),
976            Admission::WrongGate
977        );
978        // A park recorded without an id cannot be proven to be this gate.
979        let legacy = ParkedApproval {
980            correlation_id: None,
981            token_fingerprint: None,
982        };
983        assert_eq!(
984            admit_response_with(AdmissionMode::Strict, &mine, &r, Some(&[legacy])),
985            Admission::WrongGate
986        );
987        // Parked under exactly this id, with the right token: resumes.
988        let parks = [tokened(&mine, &issued.fingerprint)];
989        assert_eq!(
990            admit_response_with(AdmissionMode::Strict, &mine, &r, Some(&parks)),
991            Admission::Resume
992        );
993        // Parked under another nonce: dropped.
994        let other = format!("h::pack=p::flow=f::n={}", "f".repeat(32));
995        let parks = [tokened(&other, &issued.fingerprint)];
996        assert_eq!(
997            admit_response_with(AdmissionMode::Strict, &mine, &r, Some(&parks)),
998            Admission::WrongGate
999        );
1000    }
1001
1002    /// Strict mode changes nothing for an id without a nonce, and lenient mode
1003    /// (NATS) keeps today's fall-through.
1004    #[test]
1005    fn strict_mode_leaves_unnonced_ids_and_lenient_mode_unchanged() {
1006        let r = json!({"ok": true});
1007        assert_eq!(
1008            admit_response_with(AdmissionMode::Strict, "h::pack=p::flow=f", &r, None),
1009            Admission::Resume
1010        );
1011        let mine = format!("h::pack=p::flow=f::n={NONCE}");
1012        assert_eq!(
1013            admit_response_with(AdmissionMode::Lenient, &mine, &r, None),
1014            Admission::Resume
1015        );
1016    }
1017}