1use 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
82const PACK_HINT_MARKER: &str = "::pack=";
85
86const FLOW_HINT_MARKER: &str = "::flow=";
91
92const THREAD_HINT_MARKER: &str = "::thread=";
99
100const REPLY_HINT_MARKER: &str = "::reply=";
103
104const 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
119fn 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
132pub(crate) fn push_scope_markers(out: &mut String, scope: &ReplyScope) {
137 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
150fn 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#[derive(Debug, Clone, PartialEq, Eq)]
166pub(crate) struct ParsedCorrelation {
167 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
177pub(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
198fn 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
208pub(crate) const NONCE_HINT_MARKER: &str = "::n=";
211
212const NONCE_HEX_LEN: usize = 32;
215
216pub(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
224pub 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
244pub struct RuntimeSessionResumer {
246 runtime: Arc<StateMachineRuntime>,
247 mode: AdmissionMode,
248 watchdog_notifier: Option<crate::runner::dispatch_listener::WatchdogNotifier>,
249}
250
251#[derive(Clone, Copy, Debug, PartialEq, Eq)]
253pub(crate) enum AdmissionMode {
254 Lenient,
258 Strict,
264}
265
266impl RuntimeSessionResumer {
267 pub fn new(runtime: Arc<StateMachineRuntime>) -> Self {
273 Self {
274 runtime,
275 mode: AdmissionMode::Lenient,
276 watchdog_notifier: None,
277 }
278 }
279
280 #[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 pub fn strict(runtime: Arc<StateMachineRuntime>) -> Self {
295 Self {
296 runtime,
297 mode: AdmissionMode::Strict,
298 watchdog_notifier: None,
299 }
300 }
301
302 pub(crate) fn build_resume_envelope(
328 tenant: &TenantCtx,
329 correlation_id: &str,
330 output: Value,
331 ) -> IngressEnvelope {
332 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 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 flow_id,
366 flow_type: None,
367 action: None,
368 session_hint: Some(bare_hint.clone()),
374 provider,
375 channel,
376 conversation: conversation.clone(),
377 user,
378 entry_node: None,
380 activity_id: None,
381 timestamp: None,
382 messaging_endpoint_id: endpoint_id,
383 payload: output,
384 metadata: None,
385 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 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 crate::runner::dispatch_listener::retire_watchdog_on_admission(
445 self.watchdog_notifier.as_ref(),
446 correlation_id,
447 );
448 }
449 Admission::WrongGate => {
450 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 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#[derive(Debug, PartialEq, Eq)]
483pub(crate) enum Admission {
484 Resume,
486 WrongGate,
489 BadToken,
492}
493
494#[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
519pub(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
566fn split_pack_suffix(hint: &str) -> (String, Option<String>) {
570 split_marker(hint, PACK_HINT_MARKER)
571}
572
573fn 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 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 assert_eq!(
722 envelope.session_hint.as_deref(),
723 Some("demo:provider:chan:conv:user")
724 );
725 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 assert_eq!(envelope.flow_id, "wait.flow");
738 assert_eq!(envelope.pack_id.as_deref(), Some("greentic.demo"));
739 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 assert_eq!(envelope.flow_id, "wait.flow");
756 assert_eq!(envelope.pack_id.as_deref(), Some("greentic.demo"));
757 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 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 let old = "demo:provider:chan:conv:user::pack=greentic.demo::flow=wait.flow";
836 assert_eq!(split_dispatch_nonce(old), (old, None));
837 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 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 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 assert_eq!(admit_response(&mine, &r, None), Admission::Resume);
884 assert_eq!(
886 admit_response(&mine, &r, Some(&[untokened(Some(&mine))])),
887 Admission::Resume
888 );
889 assert_eq!(
891 admit_response(&mine, &r, Some(&[untokened(Some(&other))])),
892 Admission::WrongGate
893 );
894 assert_eq!(admit_response(&mine, &r, Some(&[])), Admission::WrongGate);
896 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 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 #[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 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 let parks = [tokened(&mine, &issued.fingerprint)];
989 assert_eq!(
990 admit_response_with(AdmissionMode::Strict, &mine, &r, Some(&parks)),
991 Admission::Resume
992 );
993 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 #[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}