Skip to content

Automate browser based workflows with AI

SKY-14046 Let Copilot test-run a workflow whose login step already has a saved credential (#8214)

Andrew Neilson4caac995acce
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index c98996633..56f6528b0 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -270,6 +270,7 @@ class RequestPolicyGuardrailInputs:
workflow_run_id: str | None = None
browser_session_id: str | None = None
fix_origin: bool = False
+ persisted_workflow_yaml: str | None = None
stored_completion_criteria: StoredCriteriaSnapshot | None = None
# Unlike chat_history_messages, this is not truncated to the prompt window: a site is grounded
# by the user having written it, which does not expire when the message leaves that window.
@@ -3396,6 +3397,7 @@ def _build_copilot_input_guardrails(
handler=policy_inputs.request_policy_handler,
config=getattr(ctx, "copilot_config", None) if isinstance(ctx, CopilotContext) else None,
prior_user_messages=policy_inputs.prior_user_messages,
+ persisted_workflow_yaml=policy_inputs.persisted_workflow_yaml,
)
if isinstance(ctx, CopilotContext):
_store_request_policy_on_context(
@@ -3708,6 +3710,7 @@ async def run_copilot_agent(
stored_completion_criteria: StoredCriteriaSnapshot | None = None,
prior_turn_outcome: TurnOutcome | None = None,
persist_canonical_user_message: Callable[[str], Awaitable[None]] | None = None,
+ persisted_workflow_yaml: str | None = None,
) -> AgentResult:
# One id per turn — passed to every downstream AgentResult and
# CopilotContext so the envelope and terminal frames correlate. The
@@ -3749,6 +3752,7 @@ async def run_copilot_agent(
stored_completion_criteria=stored_completion_criteria,
prior_turn_outcome=prior_turn_outcome,
persist_canonical_user_message=persist_canonical_user_message,
+ persisted_workflow_yaml=persisted_workflow_yaml,
)
return result
except Exception as exc:
@@ -3825,6 +3829,7 @@ async def _run_copilot_turn_impl(
stored_completion_criteria: StoredCriteriaSnapshot | None = None,
prior_turn_outcome: TurnOutcome | None = None,
persist_canonical_user_message: Callable[[str], Awaitable[None]] | None = None,
+ persisted_workflow_yaml: str | None = None,
) -> AgentResult:
copilot_config = config or CopilotConfig(security_rules=security_rules)
# Protect historical rows created before canonical safe-turn persistence existed. A semantic
@@ -3933,6 +3938,7 @@ async def _run_copilot_turn_impl(
workflow_run_id=getattr(chat_request, "workflow_run_id", None),
browser_session_id=getattr(chat_request, "browser_session_id", None),
fix_origin=getattr(chat_request, "fix_origin", False),
+ persisted_workflow_yaml=persisted_workflow_yaml,
stored_completion_criteria=stored_completion_criteria,
)
request_policy_guardrails = _build_copilot_input_guardrails(
diff --git a/skyvern/forge/sdk/copilot/output_policy.py b/skyvern/forge/sdk/copilot/output_policy.py
index ed692d861..b671d4966 100644
--- a/skyvern/forge/sdk/copilot/output_policy.py
+++ b/skyvern/forge/sdk/copilot/output_policy.py
@@ -25,6 +25,7 @@ from skyvern.forge.sdk.copilot.workflow_credential_utils import (
block_credential_ids,
credential_param_ids,
parse_workflow_yaml,
+ saved_credential_ids,
url_origin,
workflow_blocks,
workflow_credential_ids_from_parsed,
@@ -853,12 +854,7 @@ def _allowed_unresolved_credential_ids(request_policy: RequestPolicy) -> set[str
def _existing_workflow_credential_ids(request_policy: RequestPolicy) -> set[str]:
- # Saved credential IDs are issued with the cred_ prefix; skip anything else defensively.
- return {
- credential_id
- for credential_id in request_policy.existing_workflow_credential_ids
- if isinstance(credential_id, str) and credential_id.startswith("cred_")
- }
+ return saved_credential_ids(request_policy.existing_workflow_credential_ids)
def _existing_workflow_broadens_credential_scope(
diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.py
index 1af17c240..64328e1c2 100644
--- a/skyvern/forge/sdk/copilot/request_policy.py
+++ b/skyvern/forge/sdk/copilot/request_policy.py
@@ -837,6 +837,9 @@ class RequestPolicy:
user_site_url_sources: dict[str, int] = field(default_factory=dict)
credential_ask_candidate_ids: list[str] = field(default_factory=list)
existing_workflow_credential_ids: list[str] = field(default_factory=list)
+ # Read from the saved workflow row, never from the submitted YAML. The submission is the live
+ # canvas, which carries a copilot proposal the user has not accepted, so it cannot grant a run.
+ persisted_workflow_credential_ids: list[str] = field(default_factory=list)
# Sorted at the trace/JSON boundary; YAML traversal uses sets.
existing_workflow_credential_origins: dict[str, list[str]] = field(default_factory=dict)
classifier_status: str = "not_run"
@@ -4388,6 +4391,7 @@ async def _build_request_policy_bootstrap(
global_llm_context: str,
organization_id: str,
prior_user_messages: Sequence[WorkflowCopilotChatHistoryMessage] = (),
+ persisted_workflow_yaml: str | None = None,
_preclassified_policy: RequestPolicy | None = None,
) -> RequestPolicy:
"""Build the deterministic request safety record without model-backed policy inference."""
@@ -4403,6 +4407,7 @@ async def _build_request_policy_bootstrap(
completion_contract_status="absent",
canonical_user_message=(redact_raw_secrets_for_prompt(user_message) if raw_secret_present else user_message),
)
+ policy.persisted_workflow_credential_ids = sorted(workflow_credential_ids(persisted_workflow_yaml or ""))
policy.existing_workflow_credential_ids = sorted(workflow_credential_ids(workflow_yaml))
policy.existing_workflow_credential_origins = {
credential_id: sorted(origins) for credential_id, origins in workflow_credential_origins(workflow_yaml).items()
@@ -4479,6 +4484,7 @@ async def build_request_policy_trust_floor(
handler: LLMAPIHandler | None,
config: CopilotConfig | None = None,
prior_user_messages: Sequence[WorkflowCopilotChatHistoryMessage] = (),
+ persisted_workflow_yaml: str | None = None,
) -> RequestPolicy:
del config
safety = await _screen_raw_secret_safety(user_message, handler, organization_id=organization_id)
@@ -4516,6 +4522,7 @@ async def build_request_policy_trust_floor(
global_llm_context=global_llm_context,
organization_id=organization_id,
prior_user_messages=prior_user_messages,
+ persisted_workflow_yaml=persisted_workflow_yaml,
_preclassified_policy=policy,
)
LOG.info(
diff --git a/skyvern/forge/sdk/copilot/tools/credentials.py b/skyvern/forge/sdk/copilot/tools/credentials.py
index 6f15087d9..d56dc7b4f 100644
--- a/skyvern/forge/sdk/copilot/tools/credentials.py
+++ b/skyvern/forge/sdk/copilot/tools/credentials.py
@@ -18,6 +18,7 @@ from skyvern.forge.sdk.copilot.runtime import AgentContext
from skyvern.forge.sdk.copilot.workflow_credential_utils import (
block_credential_ids,
credential_param_ids,
+ saved_credential_ids,
workflow_blocks,
)
from skyvern.forge.sdk.schemas.credentials import Credential
@@ -226,14 +227,22 @@ def _unapproved_credential_reference_tool_error(unapproved_credential_ids: list[
)
+def _saved_workflow_credential_ids(request_policy: RequestPolicy) -> set[str]:
+ # Read from the saved workflow row at turn start. Deliberately not the submitted YAML: that is the
+ # live canvas, which carries a copilot proposal until the user accepts or rejects it, so a binding
+ # the model staged would come back as authority on the next turn.
+ return saved_credential_ids(request_policy.persisted_workflow_credential_ids)
+
+
def _approved_run_credential_ids(request_policy: RequestPolicy | None) -> set[str]:
if request_policy is None:
return set()
- return {
+ resolved = {
credential.credential_id
for credential in request_policy.resolved_credentials
if isinstance(getattr(credential, "credential_id", None), str)
}
+ return resolved | _saved_workflow_credential_ids(request_policy)
def _credential_run_approval_error(credential_ids: list[str], request_policy: RequestPolicy | None) -> str | None:
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index 8dc92370b..0bc024e8a 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -1607,12 +1607,10 @@ async def _run_blocks_and_collect_debug(
tool_credential_ids + _extract_credential_ids_from_workflow_definition(workflow.workflow_definition)
)
)
- approval_credential_ids = list(
- dict.fromkeys(
- tool_credential_ids
- + _extract_credential_ids_for_labels(workflow.workflow_definition, labels_that_may_execute)
- )
+ definition_credential_ids = _extract_credential_ids_for_labels(
+ workflow.workflow_definition, labels_that_may_execute
)
+ approval_credential_ids = list(dict.fromkeys(tool_credential_ids + definition_credential_ids))
credential_approval_error = _credential_run_approval_error(
approval_credential_ids,
getattr(ctx, "request_policy", None),
diff --git a/skyvern/forge/sdk/copilot/workflow_credential_utils.py b/skyvern/forge/sdk/copilot/workflow_credential_utils.py
index 5e10af3d2..ac8db8581 100644
--- a/skyvern/forge/sdk/copilot/workflow_credential_utils.py
+++ b/skyvern/forge/sdk/copilot/workflow_credential_utils.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import re
-from collections.abc import Mapping
+from collections.abc import Iterable, Mapping
from typing import Any
from urllib.parse import urlparse
@@ -41,6 +41,11 @@ def url_origin(url: str) -> str | None:
return f"{parsed.scheme.lower()}://{netloc}"
+def saved_credential_ids(candidates: Iterable[str]) -> set[str]:
+ # Saved credential IDs are issued with the cred_ prefix; skip anything else defensively.
+ return {candidate for candidate in candidates if isinstance(candidate, str) and candidate.startswith("cred_")}
+
+
def credential_params(parameters: Any) -> dict[str, str]:
if not isinstance(parameters, list):
return {}
diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.py
index e19020d98..c6d76575b 100644
--- a/skyvern/forge/sdk/routes/workflow_copilot.py
+++ b/skyvern/forge/sdk/routes/workflow_copilot.py
@@ -1622,6 +1622,20 @@ def _strip_runtime_block_fields(block: dict[str, Any]) -> dict[str, Any]:
return cleaned
+def _run_grant_workflow_yaml(workflow: Workflow | None) -> str | None:
+ """The YAML the pre-dispatch credential gate may grant a run from.
+
+ Derived only from the stored workflow row. The submitted YAML is the live canvas and carries
+ copilot proposals the user has not accepted, so it must never reach this value.
+ """
+ if workflow is None:
+ return None
+ definition = workflow.workflow_definition
+ if definition is None or not definition.blocks:
+ return None
+ return _workflow_to_copilot_yaml(workflow)
+
+
def _workflow_to_copilot_yaml(workflow: Workflow) -> str:
workflow_data = workflow.model_dump(mode="json", exclude_none=True)
workflow_definition = deepcopy(workflow_data.get("workflow_definition") or {})
@@ -1938,10 +1952,7 @@ async def _new_copilot_chat_post(
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Workflow not found")
chat_request.workflow_id = original_workflow.workflow_id
- persisted_workflow_yaml: str | None = None
- persisted_definition = original_workflow.workflow_definition
- if persisted_definition is not None and persisted_definition.blocks:
- persisted_workflow_yaml = _workflow_to_copilot_yaml(original_workflow)
+ persisted_workflow_yaml = _run_grant_workflow_yaml(original_workflow)
_ensure_copilot_workflow_yaml(
chat_request,
@@ -2072,6 +2083,7 @@ async def _new_copilot_chat_post(
stored_completion_criteria=None,
prior_turn_outcome=prior_turn_outcome,
persist_canonical_user_message=persist_canonical_user_message,
+ persisted_workflow_yaml=persisted_workflow_yaml,
)
agent_result.turn_outcome = _with_current_copilot_code_mode_metadata(
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 03de1c870..18260f8b4 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -63,6 +63,7 @@ from skyvern.forge.sdk.copilot.request_policy import (
TRANSCRIPT_ANCHOR_CHAR_CAP,
CompletionCriterion,
RequestPolicy,
+ _build_request_policy_bootstrap,
build_classifier_fallback_floor,
build_transcript_context,
is_fallback_floor_criterion,
@@ -77,7 +78,10 @@ from skyvern.forge.sdk.copilot.tools.completion import (
_completion_verification_criteria,
_completion_verification_from_run_result,
)
-from skyvern.forge.sdk.copilot.tools.credentials import _credential_run_approval_error
+from skyvern.forge.sdk.copilot.tools.credentials import (
+ _credential_run_approval_error,
+ _extract_credential_ids_for_labels,
+)
from skyvern.forge.sdk.copilot.turn_context import TranscriptContext, TurnContextPacket
from skyvern.forge.sdk.copilot.turn_halt import (
CopilotTurnHalt,
@@ -87,13 +91,14 @@ from skyvern.forge.sdk.copilot.turn_halt import (
)
from skyvern.forge.sdk.copilot.turn_origin import TurnOrigin
from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence
-from skyvern.forge.sdk.copilot.workflow_credential_utils import workflow_blocks
+from skyvern.forge.sdk.copilot.workflow_credential_utils import workflow_blocks, workflow_credential_ids
from skyvern.forge.sdk.routes.workflow_copilot import CHAT_HISTORY_CONTEXT_MESSAGES
from skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind, TurnOutcome
from skyvern.forge.sdk.schemas.workflow_copilot import (
WorkflowCopilotChatHistoryMessage,
WorkflowCopilotChatSender,
)
+from skyvern.utils.yaml_loader import safe_load_no_dates
from tests.unit.copilot_test_helpers import make_copilot_ctx as _ctx
from tests.unit.copilot_test_helpers import make_verified_goal_contract as _verified_goal_contract
@@ -1176,6 +1181,7 @@ class TestRequestPolicyInputGuardrail:
handler=policy_inputs.request_policy_handler,
config=None,
prior_user_messages=policy_inputs.prior_user_messages,
+ persisted_workflow_yaml=None,
)
@pytest.mark.asyncio
@@ -3108,6 +3114,165 @@ workflow_definition:
assert "unapproved_credential_reference" in error
assert "cred_X" in error
+ def test_saved_workflow_binding_is_not_unapproved_for_a_run(self) -> None:
+ saved_yaml = """
+workflow_definition:
+ parameters:
+ - parameter_type: workflow
+ workflow_parameter_type: credential_id
+ key: login_credential
+ default_value: cred_bound
+ blocks:
+ - label: login
+ block_type: login
+ url: https://example.com/login
+ parameter_keys:
+ - login_credential
+"""
+ policy = RequestPolicy(
+ resolved_credentials=[],
+ persisted_workflow_credential_ids=sorted(workflow_credential_ids(saved_yaml)),
+ )
+ assert policy.persisted_workflow_credential_ids == ["cred_bound"]
+
+ assert _credential_run_approval_error(["cred_bound"], policy) is None
+ assert policy.resolved_credentials == []
+
+ def test_credential_added_this_turn_stays_unapproved_for_a_run(self) -> None:
+ policy = RequestPolicy(
+ resolved_credentials=[],
+ persisted_workflow_credential_ids=["cred_bound"],
+ )
+
+ error = _credential_run_approval_error(["cred_bound", "cred_added_this_turn"], policy)
+ assert error is not None
+ assert "unapproved_credential_reference" in error
+ assert "cred_added_this_turn" in error
+ assert "cred_bound" not in error
+
+ def test_turn_start_snapshot_does_not_follow_the_workflow_through_the_turn(self) -> None:
+ workflow_yaml = """
+workflow_definition:
+ parameters:
+ - parameter_type: workflow
+ workflow_parameter_type: credential_id
+ key: login_credential
+ default_value: cred_bound
+{extra_parameter} blocks:
+ - label: login
+ block_type: login
+ url: https://example.com/login
+ parameter_keys:
+ - login_credential
+"""
+ policy = RequestPolicy(
+ resolved_credentials=[],
+ persisted_workflow_credential_ids=sorted(workflow_credential_ids(workflow_yaml.format(extra_parameter=""))),
+ )
+
+ this_turn_ids = sorted(
+ workflow_credential_ids(
+ workflow_yaml.format(
+ extra_parameter=""" - parameter_type: workflow
+ workflow_parameter_type: credential_id
+ key: added_credential
+ default_value: cred_added_this_turn
+"""
+ )
+ )
+ )
+ assert this_turn_ids == ["cred_added_this_turn", "cred_bound"]
+ assert policy.persisted_workflow_credential_ids == ["cred_bound"]
+
+ error = _credential_run_approval_error(this_turn_ids, policy)
+ assert error is not None
+ assert "unapproved_credential_reference" in error
+ assert "cred_added_this_turn" in error
+
+ def test_chat_mentioned_credential_stays_unapproved_without_a_workflow_binding(self) -> None:
+ policy = RequestPolicy(
+ resolved_credentials=[],
+ persisted_workflow_credential_ids=[],
+ credential_refs=["cred_mentioned"],
+ )
+
+ error = _credential_run_approval_error(["cred_mentioned"], policy)
+ assert error is not None
+ assert "unapproved_credential_reference" in error
+ assert "cred_mentioned" in error
+
+ def test_saved_binding_holds_when_the_run_executes_no_credentialed_block(self) -> None:
+ # SKY-14047 scopes the ids a run demands approval for to the blocks that will execute, so a
+ # turn adding one block and testing only that block presents an empty executing slice. The
+ # binding's authority comes from the saved workflow, not from that slice.
+ policy = RequestPolicy(
+ resolved_credentials=[],
+ persisted_workflow_credential_ids=["cred_bound"],
+ )
+
+ assert _credential_run_approval_error(["cred_bound"], policy) is None
+
+ def test_binding_staged_by_an_unaccepted_proposal_approves_nothing(self) -> None:
+ # The submitted YAML is the live canvas, which still shows a proposal the user never
+ # accepted, so on the next turn it comes back non-empty carrying the model's binding.
+ # Only the saved workflow grants a run, so the staged id is not authority.
+ policy = RequestPolicy(
+ resolved_credentials=[],
+ existing_workflow_credential_ids=["cred_staged_by_model"],
+ persisted_workflow_credential_ids=[],
+ )
+
+ error = _credential_run_approval_error(["cred_staged_by_model"], policy)
+ assert error is not None
+ assert "unapproved_credential_reference" in error
+ assert "cred_staged_by_model" in error
+
+ @pytest.mark.asyncio
+ async def test_mutating_the_workflow_mid_turn_does_not_approve_the_injected_credential(self) -> None:
+ turn_start_yaml = """
+workflow_definition:
+ parameters:
+ - parameter_type: workflow
+ workflow_parameter_type: credential_id
+ key: login_credential
+ default_value: cred_bound
+ blocks:
+ - label: login
+ block_type: login
+ url: https://example.com/login
+ parameter_keys:
+ - login_credential
+"""
+ policy = await _build_request_policy_bootstrap(
+ user_message="add a step and test run it",
+ workflow_yaml=turn_start_yaml,
+ chat_history=[],
+ global_llm_context="",
+ organization_id="o_test",
+ persisted_workflow_yaml=turn_start_yaml,
+ )
+ assert policy.persisted_workflow_credential_ids == ["cred_bound"]
+
+ mutated_definition = safe_load_no_dates(turn_start_yaml)["workflow_definition"]
+ mutated_definition["parameters"].append(
+ {
+ "parameter_type": "workflow",
+ "workflow_parameter_type": "credential_id",
+ "key": "injected_credential",
+ "default_value": "cred_injected_mid_turn",
+ }
+ )
+ mutated_definition["blocks"][0]["parameter_keys"].append("injected_credential")
+
+ definition_ids = _extract_credential_ids_for_labels(mutated_definition, ["login"])
+ assert "cred_injected_mid_turn" in definition_ids
+
+ error = _credential_run_approval_error(definition_ids, policy)
+ assert error is not None
+ assert "unapproved_credential_reference" in error
+ assert "cred_injected_mid_turn" in error
+ assert "cred_bound" not in error
+
@pytest.mark.asyncio
async def test_missing_tool_credential_reference_returns_blocking_error(self, monkeypatch) -> None:
from skyvern.forge.sdk.copilot.tools import _credential_reference_validation_error
diff --git a/tests/unit/test_workflow_copilot_route_helpers.py b/tests/unit/test_workflow_copilot_route_helpers.py
index f4d0eb5ef..72ebf87c8 100644
--- a/tests/unit/test_workflow_copilot_route_helpers.py
+++ b/tests/unit/test_workflow_copilot_route_helpers.py
@@ -19,6 +19,7 @@ from unittest.mock import MagicMock
import pytest
from pydantic import ValidationError
+from skyvern.forge.sdk.copilot.workflow_credential_utils import workflow_credential_ids
from skyvern.forge.sdk.routes.workflow_copilot import (
_blockless_submission_fallback,
_effective_auto_accept,
@@ -26,6 +27,7 @@ from skyvern.forge.sdk.routes.workflow_copilot import (
_normalize_copilot_yaml,
_prior_copilot_workflow_yaml,
_proposal_disposition,
+ _run_grant_workflow_yaml,
_should_commit_staged_workflow,
_should_restore_persisted_workflow,
_workflow_copilot_ingress_log_fields,
@@ -35,6 +37,12 @@ from skyvern.forge.sdk.schemas.workflow_copilot import (
WorkflowCopilotChatSender,
WorkflowCopilotStreamResponseUpdate,
)
+from skyvern.forge.sdk.workflow.models.parameter import (
+ OutputParameter,
+ WorkflowParameter,
+ WorkflowParameterType,
+)
+from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowDefinition
from skyvern.schemas.runs import ProxyLocation
@@ -531,3 +539,76 @@ def test_narrative_payload_tolerates_keys_persisted_before_the_field_was_removed
assert message.narrative_payload is not None
assert "mode" not in message.narrative_payload
+
+
+def _credential_bound_workflow(credential_id: str) -> Any:
+ """A saved workflow row whose login block binds ``credential_id``."""
+ parameter = WorkflowParameter(
+ parameter_type="workflow",
+ workflow_parameter_type=WorkflowParameterType.CREDENTIAL_ID,
+ key="login_credential",
+ workflow_parameter_id="wp_1",
+ workflow_id="w_1",
+ default_value=credential_id,
+ created_at=datetime.now(timezone.utc),
+ modified_at=datetime.now(timezone.utc),
+ )
+ return Workflow(
+ workflow_id="w_1",
+ organization_id="o_1",
+ title="saved",
+ workflow_permanent_id="wpid_1",
+ version=1,
+ proxy_location=ProxyLocation.NONE,
+ is_saved_task=False,
+ workflow_definition=WorkflowDefinition(
+ parameters=[parameter],
+ blocks=[
+ {
+ "label": "login",
+ "block_type": "login",
+ "url": "https://example.com/login",
+ "parameter_keys": ["login_credential"],
+ "output_parameter": OutputParameter(
+ output_parameter_id="op_1",
+ key="login_output",
+ workflow_id="w_1",
+ created_at=datetime.now(timezone.utc),
+ modified_at=datetime.now(timezone.utc),
+ ),
+ }
+ ],
+ ),
+ created_at=datetime.now(timezone.utc),
+ modified_at=datetime.now(timezone.utc),
+ )
+
+
+def test_run_grant_yaml_carries_the_saved_rows_credential() -> None:
+ grant_yaml = _run_grant_workflow_yaml(_credential_bound_workflow("cred_saved"))
+
+ assert grant_yaml is not None
+ assert workflow_credential_ids(grant_yaml) == {"cred_saved"}
+
+
+def test_run_grant_yaml_ignores_a_binding_that_exists_only_on_the_submitted_canvas() -> None:
+ """The authority boundary: the grant reads the workflow row, never the submission.
+
+ A copilot proposal sits on the canvas until the user accepts it, so the next turn resubmits
+ it as a non-empty ``workflow_yaml``. If that ever reached the grant, a binding the model
+ staged would authorize its own run.
+ """
+ saved_row = _credential_bound_workflow("cred_saved")
+ # What the frontend would submit next turn: the canvas, still showing a staged proposal.
+ submitted_canvas_yaml = _run_grant_workflow_yaml(_credential_bound_workflow("cred_staged_by_model"))
+ assert submitted_canvas_yaml is not None
+ assert workflow_credential_ids(submitted_canvas_yaml) == {"cred_staged_by_model"}
+
+ grant_yaml = _run_grant_workflow_yaml(saved_row)
+
+ assert grant_yaml is not None
+ assert workflow_credential_ids(grant_yaml) == {"cred_saved"}
+
+
+def test_run_grant_yaml_is_none_when_the_row_has_no_blocks() -> None:
+ assert _run_grant_workflow_yaml(None) is None