Skip to content

Automate browser based workflows with AI

Bind terminal persistence and webhook callbacks (SKY-12887) (#7980)

Aaron Perez682692ee9b20
diff --git a/skyvern/forge/sdk/terminal_callback_binding.py b/skyvern/forge/sdk/terminal_callback_binding.py
new file mode 100644
index 000000000..8ab4f3cc9
--- /dev/null
+++ b/skyvern/forge/sdk/terminal_callback_binding.py
@@ -0,0 +1,243 @@
+"""Consumer-bound authorization for the two terminal browser-firewall sinks (SKY-12887).
+
+Completion/termination persistence and the outbound webhook callback are SENSITIVE SINKS, not
+bookkeeping. A terminal status write and a callback delivery must each bind to the exact task/run
+transition that authorizes them, computed immediately before the effective write or delivery — never
+carried from an earlier, now-stale decision.
+
+Two properties this module exists to guarantee:
+
+ * The terminal write binds to the EFFECTIVE action as it stands right now. A COMPLETE the agent
+ converted to a TERMINATE in place (``handle_complete_action`` rewrites ``action.action_type``)
+ is re-projected here and authorized as a TERMINATE — the authorization is derived from the live
+ action type, so a converted action cannot ride in on a stale COMPLETE authorization.
+ * The callback destination binds INDEPENDENTLY to the run's original authenticated configuration,
+ captured once at run creation. There is nowhere in this API to hand in a destination, so an
+ untrusted result payload can neither supply, rewrite, nor redirect where a webhook is sent.
+
+Everything here is fail-closed. The untrusted output of a run never enters this module, so it cannot
+create authority. A blocked, stale, replayed, wrong-run, or unmediated action yields no
+``AuthorizedTransition``; without one, neither the terminal write nor the callback can proceed. The
+callback destination and every protected value stay out of errors, reprs and tracebacks — the reason
+codes are the only surface a caller may log, and they carry no protected data BY CONSTRUCTION.
+
+Like :mod:`skyvern.forge.sdk.protected_reference`, this is the contract the enforcing sinks consume;
+wiring the concrete task, workflow-run and block writes to it is a separate integration step.
+"""
+
+from __future__ import annotations
+
+import secrets
+from dataclasses import dataclass
+from enum import StrEnum
+from typing import NoReturn
+
+from skyvern.forge.sdk.browser_action_policy import PolicyOutcome
+from skyvern.webeye.actions.action_types import ActionType
+
+#: An action that never carried an observation epoch was never mediated by the firewall's action
+#: path. Mirrors ``browser_action_preflight.UNSTAMPED_EPOCH``: no real epoch is negative, so a
+#: sentinel can never be mistaken for a mediated one.
+UNMEDIATED_EPOCH = -1
+
+
+class TerminalTransitionKind(StrEnum):
+ COMPLETE = "complete"
+ TERMINATE = "terminate"
+
+
+class TerminalBindingReason(StrEnum):
+ INCOMPLETE_BINDING = "incomplete_binding"
+ RUN_ALREADY_BOUND = "run_already_bound"
+ UNBOUND_RUN = "unbound_run"
+ WRONG_RUN = "wrong_run"
+ NOT_A_TERMINAL_ACTION = "not_a_terminal_action"
+ BLOCKED_ACTION = "blocked_action"
+ UNMEDIATED_TRANSITION = "unmediated_transition"
+ STALE_TRANSITION = "stale_transition"
+ REPLAYED_TRANSITION = "replayed_transition"
+ FORGED_AUTHORIZATION = "forged_authorization"
+
+
+class TerminalBindingError(RuntimeError):
+ """A safe failure containing no callback destination and no protected value."""
+
+ def __init__(self, reason: TerminalBindingReason) -> None:
+ self.reason = reason
+ super().__init__(reason.value)
+
+
+def _raise_safe_error(reason: TerminalBindingReason) -> NoReturn:
+ raise TerminalBindingError(reason)
+
+
+def _present(value: object) -> bool:
+ return isinstance(value, str) and bool(value.strip())
+
+
+def _mediated(epoch: object) -> bool:
+ return isinstance(epoch, int) and not isinstance(epoch, bool) and epoch >= 0
+
+
+_TERMINAL_KINDS: dict[ActionType, TerminalTransitionKind] = {
+ ActionType.COMPLETE: TerminalTransitionKind.COMPLETE,
+ ActionType.TERMINATE: TerminalTransitionKind.TERMINATE,
+}
+
+
+def project_terminal_transition(action_type: ActionType | str) -> TerminalTransitionKind | None:
+ """Re-project the effective terminal transition from an action type AS IT STANDS NOW.
+
+ Never memoize per action id: a handler can rewrite ``action_type`` in place (COMPLETE becomes
+ TERMINATE), so this must be read from the live value at the authorization site. Anything that is
+ not one of the two terminal actions — including an unknown or unusable value — projects to
+ ``None`` and is not a terminal transition.
+ """
+ try:
+ normalized = ActionType(action_type)
+ except (ValueError, TypeError):
+ return None
+ return _TERMINAL_KINDS.get(normalized)
+
+
+@dataclass(frozen=True, slots=True)
+class AuthorizedTransition:
+ """Opaque proof that an exact task/run terminal transition was authorized.
+
+ Gates both effective sinks: the terminal status write and, later, the outbound callback. It
+ never carries the callback destination — resolving one requires handing this proof back to the
+ broker that issued it, which alone holds the run's bound configuration.
+ """
+
+ transition_id: str
+ run_id: str
+ effective: TerminalTransitionKind
+
+
+@dataclass(frozen=True, slots=True, repr=False)
+class _RunBinding:
+ owner_id: str
+ callback_url: str | None
+
+ def __repr__(self) -> str:
+ # The default dataclass repr would render callback_url, which can embed credentials. Any
+ # frame holding a binding (in locals, or a persisted run artifact) must not leak it.
+ return f"_RunBinding(owner_id={self.owner_id!r}, callback={'set' if self.callback_url else 'none'})"
+
+
+class TerminalCallbackBroker:
+ """Binds terminal writes and webhook callbacks to authenticated run transitions.
+
+ A run is bound ONCE, at authenticated creation, with its owner and its original callback
+ destination. That binding is the single source of truth for the destination and cannot be
+ replaced mid-run — a second bind is refused so a control-plane change cannot rewrite a live
+ run's authority. Authorizing a terminal transition is single-use per run: a run transitions to
+ terminal exactly once, and the resulting proof delivers its callback exactly once.
+ """
+
+ def __init__(self) -> None:
+ self._runs: dict[str, _RunBinding] = {}
+ self._terminal_runs: set[str] = set()
+ self._authorized: dict[str, str] = {}
+ self._delivered_callbacks: set[str] = set()
+ self._issued_transition_ids: set[str] = set()
+
+ def __repr__(self) -> str:
+ return f"{type(self).__name__}(runs={len(self._runs)}, terminal={len(self._terminal_runs)})"
+
+ def bind_run(self, *, run_id: str, owner_id: str, callback_url: str | None = None) -> None:
+ """Record the run's authenticated identity and its original callback destination.
+
+ ``callback_url`` is the ONLY entry point for a webhook destination and comes from the
+ authenticated run configuration, not from any run output. ``None`` means the run has no
+ callback; a present-but-empty value is a misconfiguration and fails closed.
+ """
+ if not _present(run_id) or not _present(owner_id) or (callback_url is not None and not _present(callback_url)):
+ del self, run_id, owner_id, callback_url
+ _raise_safe_error(TerminalBindingReason.INCOMPLETE_BINDING)
+ if run_id in self._runs:
+ del self, run_id, owner_id, callback_url
+ _raise_safe_error(TerminalBindingReason.RUN_ALREADY_BOUND)
+ self._runs[run_id] = _RunBinding(owner_id=owner_id, callback_url=callback_url)
+
+ def authorize_terminal_transition(
+ self,
+ *,
+ run_id: str,
+ owner_id: str,
+ action_type: ActionType | str,
+ action_epoch: int | None,
+ current_epoch: int,
+ policy_outcome: PolicyOutcome,
+ ) -> AuthorizedTransition:
+ """Authorize the effective terminal transition, immediately before persistence.
+
+ The effective action is re-projected from ``action_type`` here, so a converted COMPLETE is
+ authorized as the TERMINATE it now is. No result payload is an input, so untrusted output
+ cannot create authority. Reasons are checked most-structural first: incomplete facts, an
+ unbound or wrong-owner run, a non-terminal or policy-blocked action, an unmediated or stale
+ transition, then a replayed one. Any failure raises and yields no proof — so a blocked,
+ stale, replayed, wrong-run or unmediated action produces neither a terminal write nor a
+ callback.
+ """
+ if (
+ not _present(run_id)
+ or not _present(owner_id)
+ or not isinstance(current_epoch, int)
+ or isinstance(current_epoch, bool)
+ ):
+ _raise_safe_error(TerminalBindingReason.INCOMPLETE_BINDING)
+ binding = self._runs.get(run_id)
+ if binding is None:
+ _raise_safe_error(TerminalBindingReason.UNBOUND_RUN)
+ if binding.owner_id != owner_id:
+ _raise_safe_error(TerminalBindingReason.WRONG_RUN)
+ effective = project_terminal_transition(action_type)
+ if effective is None:
+ _raise_safe_error(TerminalBindingReason.NOT_A_TERMINAL_ACTION)
+ if policy_outcome is not PolicyOutcome.ALLOWED:
+ _raise_safe_error(TerminalBindingReason.BLOCKED_ACTION)
+ if not _mediated(action_epoch):
+ _raise_safe_error(TerminalBindingReason.UNMEDIATED_TRANSITION)
+ if action_epoch != current_epoch:
+ _raise_safe_error(TerminalBindingReason.STALE_TRANSITION)
+ if run_id in self._terminal_runs:
+ _raise_safe_error(TerminalBindingReason.REPLAYED_TRANSITION)
+ self._terminal_runs.add(run_id)
+ transition_id = self._new_transition_id()
+ self._authorized[transition_id] = run_id
+ return AuthorizedTransition(transition_id=transition_id, run_id=run_id, effective=effective)
+
+ def resolve_callback(self, transition: AuthorizedTransition, *, run_id: str) -> str | None:
+ """Resolve the run's bound callback destination for an authorized terminal transition.
+
+ Takes no destination: the URL is exactly the one bound at run creation, so untrusted output
+ cannot supply, rewrite or redirect it. The proof must be one this broker issued for this
+ exact run, unused. Returns ``None`` when the run configured no callback — nothing to deliver,
+ not an error. Delivers at most once per transition.
+ """
+ if (
+ not isinstance(transition, AuthorizedTransition)
+ or not _present(transition.transition_id)
+ or not _present(run_id)
+ ):
+ _raise_safe_error(TerminalBindingReason.INCOMPLETE_BINDING)
+ authorized_run = self._authorized.get(transition.transition_id)
+ if authorized_run is None:
+ _raise_safe_error(TerminalBindingReason.FORGED_AUTHORIZATION)
+ if authorized_run != run_id:
+ _raise_safe_error(TerminalBindingReason.WRONG_RUN)
+ if transition.transition_id in self._delivered_callbacks:
+ _raise_safe_error(TerminalBindingReason.REPLAYED_TRANSITION)
+ binding = self._runs.get(run_id)
+ if binding is None:
+ _raise_safe_error(TerminalBindingReason.UNBOUND_RUN)
+ self._delivered_callbacks.add(transition.transition_id)
+ return binding.callback_url
+
+ def _new_transition_id(self) -> str:
+ while True:
+ transition_id = f"txn_{secrets.token_urlsafe(24)}"
+ if transition_id not in self._issued_transition_ids:
+ self._issued_transition_ids.add(transition_id)
+ return transition_id
diff --git a/tests/unit/test_terminal_callback_binding.py b/tests/unit/test_terminal_callback_binding.py
new file mode 100644
index 000000000..00521a461
--- /dev/null
+++ b/tests/unit/test_terminal_callback_binding.py
@@ -0,0 +1,432 @@
+import dataclasses
+import inspect
+import traceback
+
+import pytest
+
+from skyvern.forge.sdk import terminal_callback_binding as binding_module
+from skyvern.forge.sdk.browser_action_policy import PolicyOutcome
+from skyvern.forge.sdk.terminal_callback_binding import (
+ UNMEDIATED_EPOCH,
+ AuthorizedTransition,
+ TerminalBindingError,
+ TerminalBindingReason,
+ TerminalCallbackBroker,
+ TerminalTransitionKind,
+ project_terminal_transition,
+)
+from skyvern.webeye.actions.action_types import ActionType
+
+OWNER = "o_12887"
+OTHER_OWNER = "o_other_12887"
+RUN = "wr_12887"
+OTHER_RUN = "wr_other_12887"
+EPOCH = 7
+CALLBACK_SECRET = "tok-must-not-leak-2f9c"
+CALLBACK_URL = f"https://hooks.example.test/skyvern?token={CALLBACK_SECRET}"
+# The untrusted output of a run. It must never be an input that grants authority or names a
+# destination, so it never appears in any call below — the contract is that there is nowhere to put it.
+RESULT_PAYLOAD = "extracted-result-that-must-not-create-authority"
+
+
+def bound_broker(callback_url: str | None = CALLBACK_URL) -> TerminalCallbackBroker:
+ broker = TerminalCallbackBroker()
+ broker.bind_run(run_id=RUN, owner_id=OWNER, callback_url=callback_url)
+ return broker
+
+
+def authorize(
+ broker: TerminalCallbackBroker,
+ *,
+ run_id: str = RUN,
+ owner_id: str = OWNER,
+ action_type: ActionType | str = ActionType.COMPLETE,
+ action_epoch: int | None = EPOCH,
+ current_epoch: int = EPOCH,
+ policy_outcome: PolicyOutcome = PolicyOutcome.ALLOWED,
+) -> AuthorizedTransition:
+ return broker.authorize_terminal_transition(
+ run_id=run_id,
+ owner_id=owner_id,
+ action_type=action_type,
+ action_epoch=action_epoch,
+ current_epoch=current_epoch,
+ policy_outcome=policy_outcome,
+ )
+
+
+def assert_protected_data_absent_from_module_traceback(error: BaseException) -> None:
+ rendered = "".join(traceback.format_exception(error))
+ assert CALLBACK_URL not in rendered
+ assert CALLBACK_SECRET not in rendered
+ traceback_node = error.__traceback__
+ module_frames = 0
+ while traceback_node is not None:
+ if traceback_node.tb_frame.f_code.co_filename.endswith("/terminal_callback_binding.py"):
+ module_frames += 1
+ frame_locals = repr(traceback_node.tb_frame.f_locals)
+ assert CALLBACK_URL not in frame_locals
+ assert CALLBACK_SECRET not in frame_locals
+ traceback_node = traceback_node.tb_next
+ assert module_frames > 0
+
+
+class _MutableAction:
+ """Stand-in for an agent action whose ``action_type`` a handler rewrites in place."""
+
+ def __init__(self, action_type: ActionType) -> None:
+ self.action_type = action_type
+
+
+# --- re-projection of the effective terminal action (AC2) -------------------------------------
+
+
+def test_project_maps_the_two_terminal_actions() -> None:
+ assert project_terminal_transition(ActionType.COMPLETE) is TerminalTransitionKind.COMPLETE
+ assert project_terminal_transition(ActionType.TERMINATE) is TerminalTransitionKind.TERMINATE
+
+
+def test_project_normalizes_string_action_types() -> None:
+ assert project_terminal_transition("complete") is TerminalTransitionKind.COMPLETE
+ assert project_terminal_transition("terminate") is TerminalTransitionKind.TERMINATE
+
+
+ "action_type",
+ [ActionType.CLICK, ActionType.INPUT_TEXT, ActionType.GOTO_URL, ActionType.EXTRACT, "extract", "", "not_a_type"],
+)
+def test_project_returns_none_for_non_terminal_actions(action_type: ActionType | str) -> None:
+ assert project_terminal_transition(action_type) is None
+
+
[email protected]("action_type", [None, 7, object()])
+def test_project_fails_closed_on_unusable_action_types(action_type: object) -> None:
+ assert project_terminal_transition(action_type) is None
+
+
+def test_project_reflects_an_in_place_complete_to_terminate_conversion() -> None:
+ action = _MutableAction(ActionType.COMPLETE)
+ assert project_terminal_transition(action.action_type) is TerminalTransitionKind.COMPLETE
+ action.action_type = ActionType.TERMINATE
+ assert project_terminal_transition(action.action_type) is TerminalTransitionKind.TERMINATE
+
+
+# --- the authorized transition gates both the terminal write and the callback (AC1) -----------
+
+
+def test_authorization_binds_to_the_effective_action_and_run() -> None:
+ broker = bound_broker()
+
+ transition = authorize(broker, action_type=ActionType.COMPLETE)
+
+ assert isinstance(transition, AuthorizedTransition)
+ assert transition.effective is TerminalTransitionKind.COMPLETE
+ assert transition.run_id == RUN
+ assert transition.transition_id.startswith("txn_")
+
+
+def test_a_terminate_authorization_carries_the_terminate_effect() -> None:
+ broker = bound_broker()
+
+ transition = authorize(broker, action_type=ActionType.TERMINATE)
+
+ assert transition.effective is TerminalTransitionKind.TERMINATE
+
+
+def test_authorized_transition_resolves_the_bound_callback() -> None:
+ broker = bound_broker()
+
+ transition = authorize(broker)
+
+ assert broker.resolve_callback(transition, run_id=RUN) == CALLBACK_URL
+
+
+def test_distinct_runs_are_authorized_independently() -> None:
+ broker = TerminalCallbackBroker()
+ broker.bind_run(run_id=RUN, owner_id=OWNER, callback_url=CALLBACK_URL)
+ broker.bind_run(run_id=OTHER_RUN, owner_id=OWNER, callback_url=None)
+
+ first = authorize(broker, run_id=RUN)
+ second = authorize(broker, run_id=OTHER_RUN)
+
+ assert first.transition_id != second.transition_id
+ assert broker.resolve_callback(first, run_id=RUN) == CALLBACK_URL
+ assert broker.resolve_callback(second, run_id=OTHER_RUN) is None
+
+
+# --- a converted COMPLETE is authorized as the effective TERMINATE (AC2) -----------------------
+
+
+def test_a_converted_action_is_authorized_as_the_effective_terminate() -> None:
+ broker = bound_broker()
+ action = _MutableAction(ActionType.COMPLETE)
+ action.action_type = ActionType.TERMINATE
+
+ transition = authorize(broker, action_type=action.action_type)
+
+ assert transition.effective is TerminalTransitionKind.TERMINATE
+
+
+# --- untrusted result payloads cannot create authority or name a destination (AC3, AC5) --------
+
+
+def test_no_authorization_input_can_carry_an_untrusted_result_payload() -> None:
+ parameters = set(inspect.signature(TerminalCallbackBroker.authorize_terminal_transition).parameters)
+
+ for forbidden in ("result", "results", "payload", "extracted_information", "output", "data", "body"):
+ assert forbidden not in parameters
+
+
+def test_callback_resolution_exposes_no_destination_parameter() -> None:
+ parameters = set(inspect.signature(TerminalCallbackBroker.resolve_callback).parameters)
+
+ for forbidden in ("url", "target", "target_url", "destination", "callback_url", "webhook_url"):
+ assert forbidden not in parameters
+
+
+def test_only_run_binding_supplies_the_callback_destination() -> None:
+ bind_parameters = set(inspect.signature(TerminalCallbackBroker.bind_run).parameters)
+
+ assert "callback_url" in bind_parameters
+
+
+# --- the callback destination is the run's original authenticated configuration (AC4) ----------
+
+
+def test_callback_destination_is_exactly_the_bound_configuration() -> None:
+ broker = bound_broker(callback_url=CALLBACK_URL)
+
+ transition = authorize(broker)
+
+ assert broker.resolve_callback(transition, run_id=RUN) == CALLBACK_URL
+
+
+def test_a_run_without_a_callback_resolves_to_none_rather_than_erroring() -> None:
+ broker = bound_broker(callback_url=None)
+
+ transition = authorize(broker)
+
+ assert broker.resolve_callback(transition, run_id=RUN) is None
+
+
+# --- blocked / stale / replayed / wrong-run / unmediated produce neither write nor callback (AC6)
+
+
+ "policy_outcome", [PolicyOutcome.DENIED, PolicyOutcome.UNSUPPORTED, PolicyOutcome.NOT_ENROLLED]
+)
+def test_a_blocked_action_is_not_authorized(policy_outcome: PolicyOutcome) -> None:
+ broker = bound_broker()
+
+ with pytest.raises(TerminalBindingError) as caught:
+ authorize(broker, policy_outcome=policy_outcome)
+
+ assert caught.value.reason is TerminalBindingReason.BLOCKED_ACTION
+
+
[email protected]("action_epoch", [None, UNMEDIATED_EPOCH, -5])
+def test_an_unmediated_action_is_not_authorized(action_epoch: int | None) -> None:
+ broker = bound_broker()
+
+ with pytest.raises(TerminalBindingError) as caught:
+ authorize(broker, action_epoch=action_epoch, current_epoch=action_epoch if isinstance(action_epoch, int) else 0)
+
+ assert caught.value.reason is TerminalBindingReason.UNMEDIATED_TRANSITION
+
+
+def test_a_stale_action_is_not_authorized() -> None:
+ broker = bound_broker()
+
+ with pytest.raises(TerminalBindingError) as caught:
+ authorize(broker, action_epoch=EPOCH, current_epoch=EPOCH + 1)
+
+ assert caught.value.reason is TerminalBindingReason.STALE_TRANSITION
+
+
+def test_a_wrong_owner_is_not_authorized() -> None:
+ broker = bound_broker()
+
+ with pytest.raises(TerminalBindingError) as caught:
+ authorize(broker, owner_id=OTHER_OWNER)
+
+ assert caught.value.reason is TerminalBindingReason.WRONG_RUN
+
+
+def test_an_unbound_run_is_not_authorized() -> None:
+ broker = TerminalCallbackBroker()
+
+ with pytest.raises(TerminalBindingError) as caught:
+ authorize(broker, run_id=OTHER_RUN)
+
+ assert caught.value.reason is TerminalBindingReason.UNBOUND_RUN
+
+
+def test_a_non_terminal_action_is_not_authorized() -> None:
+ broker = bound_broker()
+
+ with pytest.raises(TerminalBindingError) as caught:
+ authorize(broker, action_type=ActionType.CLICK)
+
+ assert caught.value.reason is TerminalBindingReason.NOT_A_TERMINAL_ACTION
+
+
+def test_a_replayed_transition_is_not_authorized() -> None:
+ broker = bound_broker()
+ authorize(broker)
+
+ with pytest.raises(TerminalBindingError) as caught:
+ authorize(broker)
+
+ assert caught.value.reason is TerminalBindingReason.REPLAYED_TRANSITION
+
+
+def test_a_denied_action_leaves_nothing_a_callback_could_bind_to() -> None:
+ broker = bound_broker()
+ try:
+ authorize(broker, policy_outcome=PolicyOutcome.DENIED)
+ except TerminalBindingError:
+ pass
+ forged = AuthorizedTransition(transition_id="txn_forged", run_id=RUN, effective=TerminalTransitionKind.COMPLETE)
+
+ with pytest.raises(TerminalBindingError) as caught:
+ broker.resolve_callback(forged, run_id=RUN)
+
+ assert caught.value.reason is TerminalBindingReason.FORGED_AUTHORIZATION
+
+
+# --- callbacks cannot be forged, redirected to another run, or replayed ------------------------
+
+
+def test_a_forged_authorization_cannot_resolve_a_callback() -> None:
+ broker = bound_broker()
+ authorize(broker)
+ forged = AuthorizedTransition(transition_id="txn_forged", run_id=RUN, effective=TerminalTransitionKind.COMPLETE)
+
+ with pytest.raises(TerminalBindingError) as caught:
+ broker.resolve_callback(forged, run_id=RUN)
+
+ assert caught.value.reason is TerminalBindingReason.FORGED_AUTHORIZATION
+
+
+def test_a_tampered_run_on_a_real_authorization_cannot_resolve_a_callback() -> None:
+ broker = TerminalCallbackBroker()
+ broker.bind_run(run_id=RUN, owner_id=OWNER, callback_url=CALLBACK_URL)
+ broker.bind_run(run_id=OTHER_RUN, owner_id=OWNER, callback_url=None)
+ transition = authorize(broker, run_id=RUN)
+ tampered = dataclasses.replace(transition, run_id=OTHER_RUN)
+
+ with pytest.raises(TerminalBindingError) as caught:
+ broker.resolve_callback(tampered, run_id=OTHER_RUN)
+
+ assert caught.value.reason is TerminalBindingReason.WRONG_RUN
+
+
+def test_a_callback_is_deliverable_only_once() -> None:
+ broker = bound_broker()
+ transition = authorize(broker)
+ assert broker.resolve_callback(transition, run_id=RUN) == CALLBACK_URL
+
+ with pytest.raises(TerminalBindingError) as caught:
+ broker.resolve_callback(transition, run_id=RUN)
+
+ assert caught.value.reason is TerminalBindingReason.REPLAYED_TRANSITION
+
+
+# --- run binding is authenticated once and cannot be replaced mid-run -------------------------
+
+
[email protected]("fields", [{"run_id": ""}, {"run_id": " "}, {"owner_id": ""}, {"callback_url": " "}])
+def test_binding_fails_closed_on_incomplete_facts(fields: dict[str, str]) -> None:
+ arguments = {"run_id": RUN, "owner_id": OWNER, "callback_url": CALLBACK_URL, **fields}
+
+ with pytest.raises(TerminalBindingError) as caught:
+ TerminalCallbackBroker().bind_run(**arguments)
+
+ assert caught.value.reason is TerminalBindingReason.INCOMPLETE_BINDING
+ assert_protected_data_absent_from_module_traceback(caught.value)
+
+
+def test_rebinding_a_run_is_refused() -> None:
+ broker = bound_broker()
+
+ with pytest.raises(TerminalBindingError) as caught:
+ broker.bind_run(run_id=RUN, owner_id=OWNER, callback_url="https://hooks.example.test/other")
+
+ assert caught.value.reason is TerminalBindingReason.RUN_ALREADY_BOUND
+
+
+# --- opaque, unique capabilities --------------------------------------------------------------
+
+
+def test_transition_ids_are_opaque_and_unique() -> None:
+ broker = TerminalCallbackBroker()
+ broker.bind_run(run_id=RUN, owner_id=OWNER, callback_url=None)
+ broker.bind_run(run_id=OTHER_RUN, owner_id=OWNER, callback_url=None)
+
+ first = authorize(broker, run_id=RUN).transition_id
+ second = authorize(broker, run_id=OTHER_RUN).transition_id
+
+ assert first.startswith("txn_")
+ assert second.startswith("txn_")
+ assert first != second
+
+
+def test_transition_id_collision_retries_without_reusing_an_id(monkeypatch: pytest.MonkeyPatch) -> None:
+ generated = iter(["collision", "collision", "unique"])
+ monkeypatch.setattr(binding_module.secrets, "token_urlsafe", lambda _: next(generated))
+ broker = TerminalCallbackBroker()
+ broker.bind_run(run_id=RUN, owner_id=OWNER, callback_url=None)
+ broker.bind_run(run_id=OTHER_RUN, owner_id=OWNER, callback_url=None)
+
+ first = authorize(broker, run_id=RUN).transition_id
+ second = authorize(broker, run_id=OTHER_RUN).transition_id
+
+ assert first == "txn_collision"
+ assert second == "txn_unique"
+
+
+# --- decisions, capabilities and errors carry no protected data (AC7) --------------------------
+
+
+def test_the_broker_repr_hides_the_callback_destination() -> None:
+ broker = bound_broker()
+
+ assert CALLBACK_URL not in repr(broker)
+ assert CALLBACK_SECRET not in repr(broker)
+
+
+def test_an_authorized_transition_never_reveals_the_callback_destination() -> None:
+ broker = bound_broker()
+
+ transition = authorize(broker)
+
+ assert CALLBACK_URL not in repr(transition)
+ assert CALLBACK_SECRET not in repr(transition)
+
+
+def test_binding_errors_scrub_the_callback_destination_from_their_traceback() -> None:
+ with pytest.raises(TerminalBindingError) as caught:
+ TerminalCallbackBroker().bind_run(run_id=RUN, owner_id="", callback_url=CALLBACK_URL)
+
+ assert CALLBACK_URL not in str(caught.value)
+ assert CALLBACK_SECRET not in str(caught.value)
+ assert_protected_data_absent_from_module_traceback(caught.value)
+
+
+ "provoke",
+ [
+ lambda broker: broker.resolve_callback(
+ AuthorizedTransition("txn_forged", RUN, TerminalTransitionKind.COMPLETE), run_id=RUN
+ ),
+ lambda broker: authorize(broker, policy_outcome=PolicyOutcome.DENIED),
+ lambda broker: authorize(broker, action_epoch=None),
+ ],
+)
+def test_authorization_and_resolution_errors_scrub_their_traceback(provoke) -> None: # type: ignore[no-untyped-def]
+ broker = bound_broker()
+
+ with pytest.raises(TerminalBindingError) as caught:
+ provoke(broker)
+
+ assert_protected_data_absent_from_module_traceback(caught.value)