Skip to content

Automate browser based workflows with AI

SKY-14047 Copilot: require credential approval only for the blocks a test run will execute (#8204)

Andrew Neilsone7434da6e531
diff --git a/skyvern/forge/sdk/copilot/tools/credentials.py b/skyvern/forge/sdk/copilot/tools/credentials.py
index a5bf1653c..6f15087d9 100644
--- a/skyvern/forge/sdk/copilot/tools/credentials.py
+++ b/skyvern/forge/sdk/copilot/tools/credentials.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import re
+from collections.abc import Collection
from typing import Any
import structlog
@@ -14,7 +15,11 @@ from skyvern.forge.sdk.copilot.credential_resolution import (
)
from skyvern.forge.sdk.copilot.request_policy import RequestPolicy
from skyvern.forge.sdk.copilot.runtime import AgentContext
-from skyvern.forge.sdk.copilot.workflow_credential_utils import workflow_blocks
+from skyvern.forge.sdk.copilot.workflow_credential_utils import (
+ block_credential_ids,
+ credential_param_ids,
+ workflow_blocks,
+)
from skyvern.forge.sdk.schemas.credentials import Credential
from skyvern.forge.sdk.workflow.models.parameter import WorkflowParameterType
from skyvern.utils.yaml_loader import safe_load_no_dates
@@ -93,6 +98,39 @@ def _extract_credential_ids_from_workflow_definition(workflow_definition: Any) -
return list(dict.fromkeys(found))
+def _extract_credential_ids_for_labels(workflow_definition: Any, labels: Collection[str]) -> list[str]:
+ """Credential IDs reachable from the blocks named by `labels` and their descendants, plus any
+ top-level credential parameter no block claims; falls back to the whole-document set when the
+ label set is empty or a label does not resolve. Sound only while the runtime exposes a
+ credential solely to blocks that declare it (WorkflowRunContext.credential_template_entries)."""
+ definition = _workflow_definition_as_dict(workflow_definition)
+ selected_labels = set(labels)
+ if not selected_labels:
+ return _extract_credential_ids_from_workflow_definition(definition)
+
+ parsed = {"workflow_definition": definition}
+ selected_blocks = workflow_blocks(parsed, selected_labels=selected_labels)
+ if selected_labels - {block.get("label") for block in selected_blocks}:
+ return _extract_credential_ids_from_workflow_definition(definition)
+
+ credential_params_by_key = credential_param_ids(definition.get("parameters"))
+
+ def block_ids(block: dict[str, Any]) -> list[str]:
+ return _extract_credential_ids_from_workflow_parameters(block.get("parameters")) + sorted(
+ block_credential_ids(block, credential_params_by_key)
+ )
+
+ claimed_by_any_block = {credential_id for block in workflow_blocks(parsed) for credential_id in block_ids(block)}
+ found = [
+ credential_id
+ for credential_id in _extract_credential_ids_from_workflow_parameters(definition.get("parameters"))
+ if credential_id not in claimed_by_any_block
+ ]
+ for block in selected_blocks:
+ found.extend(block_ids(block))
+ return list(dict.fromkeys(found))
+
+
def _parsed_workflow_definition(workflow_yaml: str | None) -> dict[str, Any] | None:
if not workflow_yaml:
return None
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index 9d8d57b4c..7bf168b47 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -149,6 +149,7 @@ from .composition_capture import (
from .credentials import (
_credential_ids_validation_error,
_credential_run_approval_error,
+ _extract_credential_ids_for_labels,
_extract_credential_ids_from_tool_value,
_extract_credential_ids_from_workflow_definition,
)
@@ -1602,14 +1603,20 @@ async def _run_blocks_and_collect_debug(
selected_labels=set(labels_that_may_execute),
)
+ tool_credential_ids = _extract_credential_ids_from_tool_value(params.get("parameters") or {})
credential_ids = list(
dict.fromkeys(
- _extract_credential_ids_from_tool_value(params.get("parameters") or {})
- + _extract_credential_ids_from_workflow_definition(workflow.workflow_definition)
+ 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)
)
)
credential_approval_error = _credential_run_approval_error(
- credential_ids,
+ approval_credential_ids,
getattr(ctx, "request_policy", None),
)
if credential_approval_error is not None:
diff --git a/skyvern/forge/sdk/copilot/workflow_credential_utils.py b/skyvern/forge/sdk/copilot/workflow_credential_utils.py
index 6193ff7d6..5e10af3d2 100644
--- a/skyvern/forge/sdk/copilot/workflow_credential_utils.py
+++ b/skyvern/forge/sdk/copilot/workflow_credential_utils.py
@@ -94,42 +94,47 @@ def credential_param_ids(parameters: Any) -> dict[str, set[str]]:
return out
-def workflow_blocks(parsed: dict[str, Any]) -> list[dict[str, Any]]:
+def workflow_blocks(parsed: dict[str, Any], selected_labels: set[str] | None = None) -> list[dict[str, Any]]:
+ """With `selected_labels`, collect only blocks whose label is in the set plus their
+ descendants — a selected `for_loop` drags its `loop_blocks` in, since loop children are
+ not themselves named in an executing label set."""
workflow_definition = parsed.get("workflow_definition")
if not isinstance(workflow_definition, dict):
return []
collected: list[dict[str, Any]] = []
- def visit_branch(branch: dict[str, Any]) -> None:
+ def visit_branch(branch: dict[str, Any], inherited: bool) -> None:
for key in _NESTED_BLOCK_LIST_KEYS:
- visit(branch.get(key))
+ visit(branch.get(key), inherited)
for branch_key in _BRANCH_LIST_KEYS:
branches = branch.get(branch_key)
if not isinstance(branches, list):
continue
for nested_branch in branches:
if isinstance(nested_branch, dict):
- visit_branch(nested_branch)
+ visit_branch(nested_branch, inherited)
- def visit(blocks: Any) -> None:
+ def visit(blocks: Any, inherited: bool) -> None:
if not isinstance(blocks, list):
return
for block in blocks:
if not isinstance(block, dict):
continue
- collected.append(block)
+ selected = inherited or selected_labels is None or block.get("label") in selected_labels
+ if selected:
+ collected.append(block)
for key in _NESTED_BLOCK_LIST_KEYS:
- visit(block.get(key))
+ visit(block.get(key), selected)
for branch_key in _BRANCH_LIST_KEYS:
branches = block.get(branch_key)
if not isinstance(branches, list):
continue
for branch in branches:
if isinstance(branch, dict):
- visit_branch(branch)
+ visit_branch(branch, selected)
- visit(workflow_definition.get("blocks"))
+ visit(workflow_definition.get("blocks"), False)
return collected
diff --git a/skyvern/forge/sdk/workflow/context_manager.py b/skyvern/forge/sdk/workflow/context_manager.py
index b6c13e12a..479f01c31 100644
--- a/skyvern/forge/sdk/workflow/context_manager.py
+++ b/skyvern/forge/sdk/workflow/context_manager.py
@@ -1,6 +1,6 @@
import copy
import re
-from collections.abc import Mapping
+from collections.abc import Iterable, Mapping
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Self
@@ -447,6 +447,37 @@ class WorkflowRunContext:
properties={"organization_id": self.organization_id},
)
+ def credential_template_entries(
+ self,
+ declared_parameter_keys: Iterable[str],
+ *,
+ resolve_credential_dicts: bool,
+ ) -> dict[str, Any]:
+ """Template entries for the credential parameters a block declares. Secrets never enter
+ template data for parameters the block did not declare — the same boundary the block
+ execution namespace applies — so the copilot approval gate can scope to declared references."""
+ entries: dict[str, Any] = {}
+ for key in declared_parameter_keys:
+ value = self.values.get(key)
+ if not isinstance(value, dict) or "context" not in value:
+ continue
+ has_password_shape = "username" in value and "password" in value
+ if not has_password_shape and "secret_value" not in value:
+ continue
+ entries[f"{key}_real_username"] = self.secrets.get(value.get("username", ""), "")
+ entries[f"{key}_real_password"] = self.secrets.get(value.get("password", ""), "")
+ if resolve_credential_dicts:
+ resolved_credential = value.copy()
+ for credential_field, credential_placeholder in value.items():
+ if credential_field == "context":
+ continue
+ secret_value = self.get_original_secret_value_or_none(credential_placeholder)
+ if secret_value is not None:
+ resolved_credential[credential_field] = secret_value
+ resolved_credential.pop("context", None)
+ entries[key] = resolved_credential
+ return entries
+
def get_original_secret_value_or_none(self, secret_id_or_value: Any) -> Any:
"""
Get the original secret value from the secrets dict. If the secret id is not found, return None.
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 0bab26999..03b7ad856 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -885,44 +885,15 @@ class Block(BaseModel, abc.ABC):
include_secrets = False
if include_secrets:
- template_data.update(workflow_run_context.secrets)
-
- # Create easier-to-access entries for credentials
- # Look for credential parameters and create real_username/real_password entries
- # First collect all credential parameters to avoid modifying dict during iteration
- credential_params = []
- for key, value in list(template_data.items()):
- if isinstance(value, dict) and "context" in value:
- # PASSWORD credential: has username and password
- if "username" in value and "password" in value:
- credential_params.append((key, value))
- # SECRET credential: has secret_value
- elif "secret_value" in value:
- credential_params.append((key, value))
-
- # Now add the real_username/real_password entries
- for key, value in credential_params:
- username_secret_id = value.get("username", "")
- password_secret_id = value.get("password", "")
-
- # Get the actual values from the secrets
- real_username = template_data.get(username_secret_id, "")
- real_password = template_data.get(password_secret_id, "")
-
- # Add easier-to-access entries
- template_data[f"{key}_real_username"] = real_username
- template_data[f"{key}_real_password"] = real_password
-
- if is_safe_block_for_secrets:
- resolved_credential = value.copy()
- for credential_field, credential_placeholder in value.items():
- if credential_field == "context":
- continue
- secret_value = workflow_run_context.get_original_secret_value_or_none(credential_placeholder)
- if secret_value is not None:
- resolved_credential[credential_field] = secret_value
- resolved_credential.pop("context", None)
- template_data[key] = resolved_credential
+ # parameters is declared per block type, not on the Block base; get_all_parameters
+ # is not a plain accessor (some overrides resolve run context) so read the field.
+ declared_parameters: list[PARAMETER_TYPE] = getattr(self, "parameters", None) or []
+ declared_keys = [parameter.key for parameter in declared_parameters if parameter.key]
+ template_data.update(
+ workflow_run_context.credential_template_entries(
+ declared_keys, resolve_credential_dicts=is_safe_block_for_secrets
+ )
+ )
if self.label in template_data:
current_value = template_data[self.label]
@@ -12425,6 +12396,18 @@ class BranchEvaluationContext:
return snapshot
+ def _declared_parameter_keys(self) -> list[str]:
+ ctx = self.workflow_run_context
+ workflow = ctx.workflow if ctx is not None else None
+ if workflow is None or workflow.workflow_definition is None:
+ return []
+ for block in get_all_blocks(workflow.workflow_definition.blocks):
+ if block.label == self.block_label:
+ # parameters is declared per block type, not on the Block base
+ parameters = getattr(block, "parameters", None) or []
+ return [parameter.key for parameter in parameters if parameter.key]
+ return []
+
def build_template_data(self) -> dict[str, Any]:
"""Build Jinja template data mirroring block parameter rendering context."""
if self.workflow_run_context is None:
@@ -12439,20 +12422,9 @@ class BranchEvaluationContext:
ctx = self.workflow_run_context
template_data = ctx.values.copy()
if ctx.include_secrets_in_templates:
- template_data.update(ctx.secrets)
-
- credential_params: list[tuple[str, dict[str, Any]]] = []
- for key, value in template_data.items():
- if isinstance(value, dict) and "context" in value and "username" in value and "password" in value:
- credential_params.append((key, value))
-
- for key, value in credential_params:
- username_secret_id = value.get("username", "")
- password_secret_id = value.get("password", "")
- real_username = template_data.get(username_secret_id, "")
- real_password = template_data.get(password_secret_id, "")
- template_data[f"{key}_real_username"] = real_username
- template_data[f"{key}_real_password"] = real_password
+ template_data.update(
+ ctx.credential_template_entries(self._declared_parameter_keys(), resolve_credential_dicts=False)
+ )
if self.block_label:
block_reference_data: dict[str, Any] = ctx.get_block_metadata(self.block_label)
diff --git a/tests/unit/fake_workflow_run_context.py b/tests/unit/fake_workflow_run_context.py
index e76531941..f3cda4f5d 100644
--- a/tests/unit/fake_workflow_run_context.py
+++ b/tests/unit/fake_workflow_run_context.py
@@ -9,6 +9,8 @@ from __future__ import annotations
from typing import Any
+from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
+
class FakeWorkflowRunContext:
def __init__(
@@ -33,6 +35,7 @@ class FakeWorkflowRunContext:
self.workflow_run_id = "wf-run-id"
self.browser_session_id: str | None = None
self.workflow_run_outputs: dict[str, Any] = dict(workflow_run_outputs or {})
+ self.workflow = None
def get_block_metadata(self, label: str | None) -> dict[str, Any]:
if not label:
@@ -62,3 +65,11 @@ class FakeWorkflowRunContext:
def mask_secrets_in_data(self, data: Any, mask: str = "*****") -> Any:
return data
+
+ def get_original_secret_value_or_none(self, secret_id_or_value: Any) -> Any:
+ if isinstance(secret_id_or_value, str) and secret_id_or_value in self.secrets:
+ return self.secrets[secret_id_or_value]
+ return None
+
+ # Borrow the real implementation so scoping behavior cannot drift from production.
+ credential_template_entries = WorkflowRunContext.credential_template_entries
diff --git a/tests/unit/test_code_block_sandbox.py b/tests/unit/test_code_block_sandbox.py
index bc8d9f7b1..79c691d6f 100644
--- a/tests/unit/test_code_block_sandbox.py
+++ b/tests/unit/test_code_block_sandbox.py
@@ -15,11 +15,21 @@ import pytest
from skyvern.config import settings
from skyvern.forge.sdk.workflow.code_block_safety import is_safe_script_code
-from skyvern.forge.sdk.workflow.exceptions import InsecureCodeDetected
-from skyvern.forge.sdk.workflow.models.block import CODE_BLOCK_TAB_OPEN_FAILURE_REASON, CodeBlock
-from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterType
+from skyvern.forge.sdk.workflow.exceptions import InsecureCodeDetected, MissingJinjaVariables
+from skyvern.forge.sdk.workflow.models.block import (
+ CODE_BLOCK_TAB_OPEN_FAILURE_REASON,
+ BranchEvaluationContext,
+ CodeBlock,
+)
+from skyvern.forge.sdk.workflow.models.parameter import (
+ OutputParameter,
+ ParameterType,
+ WorkflowParameter,
+ WorkflowParameterType,
+)
from skyvern.schemas.workflows import BlockStatus
from skyvern.webeye.browser_artifacts import BrowserArtifacts
+from tests.unit.fake_workflow_run_context import FakeWorkflowRunContext
# ---------------------------------------------------------------------------
# is_safe_code — rejection tests
@@ -1894,3 +1904,87 @@ class TestIsSafeCodeClassStatements:
def test_script_path_keeps_metaclass_support(self) -> None:
is_safe_script_code("class Weird(metaclass=type):\n pass")
+
+
+class TestCodeBlockTemplateSecretScoping:
+ """Template data carries secrets only for credential parameters the block declares (SKY-14047),
+ mirroring the execution namespace, so a block cannot render another block's credential."""
+
+ DECLARED_KEY = "declared_cred"
+ UNDECLARED_KEY = "other_cred"
+
+ @staticmethod
+ def _workflow_parameter(key: str) -> WorkflowParameter:
+ now = datetime.now(timezone.utc)
+ return WorkflowParameter(
+ workflow_parameter_id=f"wp_{key}",
+ workflow_parameter_type=WorkflowParameterType.CREDENTIAL_ID,
+ workflow_id="w_test",
+ key=key,
+ created_at=now,
+ modified_at=now,
+ )
+
+ def _block(self) -> CodeBlock:
+ now = datetime.now(timezone.utc)
+ output_parameter = OutputParameter(
+ parameter_type=ParameterType.OUTPUT,
+ key="scoping_output",
+ description="",
+ output_parameter_id="op_scoping",
+ workflow_id="w_test",
+ created_at=now,
+ modified_at=now,
+ )
+ return CodeBlock(
+ label="scoped_code",
+ code="value = 'ok'",
+ output_parameter=output_parameter,
+ parameters=[self._workflow_parameter(self.DECLARED_KEY)],
+ )
+
+ def _context(self) -> FakeWorkflowRunContext:
+ return FakeWorkflowRunContext(
+ values={
+ self.DECLARED_KEY: {"context": "login", "username": "ph_u1", "password": "ph_p1"},
+ self.UNDECLARED_KEY: {"context": "other", "username": "ph_u2", "password": "ph_p2"},
+ },
+ secrets={
+ "ph_u1": "alice",
+ "ph_p1": "declared-secret",
+ "ph_u2": "bob",
+ "ph_p2": "undeclared-secret",
+ },
+ include_secrets_in_templates=True,
+ )
+
+ def test_declared_credential_renders_real_values(self) -> None:
+ rendered = self._block().format_block_parameter_template_from_workflow_run_context(
+ "{{ declared_cred_real_password }}|{{ declared_cred.username }}", self._context()
+ )
+ assert rendered == "declared-secret|alice"
+
+ def test_undeclared_credential_never_renders_its_secret(self) -> None:
+ try:
+ rendered = self._block().format_block_parameter_template_from_workflow_run_context(
+ "{{ other_cred_real_password }}", self._context()
+ )
+ except MissingJinjaVariables:
+ return
+ assert "undeclared-secret" not in rendered
+
+ def test_undeclared_credential_dict_stays_placeholder(self) -> None:
+ rendered = self._block().format_block_parameter_template_from_workflow_run_context(
+ "{{ other_cred.password }}", self._context()
+ )
+ assert rendered == "ph_p2"
+
+ def test_branch_evaluation_template_data_merges_no_undeclared_secrets(self) -> None:
+ template_data = BranchEvaluationContext(
+ workflow_run_context=self._context(), block_label="cond"
+ ).build_template_data()
+
+ assert "ph_p1" not in template_data
+ assert "ph_p2" not in template_data
+ assert not any(key.endswith("_real_password") for key in template_data)
+ assert template_data[self.UNDECLARED_KEY]["password"] == "ph_p2"
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index f68a90a3b..50d19e019 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -6,6 +6,7 @@ import asyncio
import json
from datetime import datetime, timezone
from types import SimpleNamespace
+from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -69,6 +70,8 @@ from skyvern.forge.sdk.copilot.request_policy import (
)
from skyvern.forge.sdk.copilot.request_slots import PROMPT_NAME as REQUEST_SLOTS_PROMPT_NAME
from skyvern.forge.sdk.copilot.run_outcome import TERMINAL_CHALLENGE_BLOCKER_REASON_CODE, RecordedRunOutcome
+from skyvern.forge.sdk.copilot.tools import _run_blocks_and_collect_debug
+from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module
from skyvern.forge.sdk.copilot.tools.completion import (
_authored_output_contract_criteria,
_completion_verification_criteria,
@@ -84,6 +87,7 @@ 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.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 (
@@ -3215,6 +3219,8 @@ class TestRunBlocksCredentialApproval:
*,
parameters: list[dict[str, object]] | None = None,
blocks: list[dict[str, object]] | None = None,
+ output_labels: set[str] | None = None,
+ finally_block_label: str | None = None,
) -> SimpleNamespace:
workflow_parameters = parameters
if workflow_parameters is None and credential_id is not None:
@@ -3226,13 +3232,17 @@ class TestRunBlocksCredentialApproval:
"default_value": credential_id,
}
]
+ known_labels = output_labels or {"login"}
+ workflow_definition: dict[str, object] = {
+ "parameters": workflow_parameters or [],
+ "blocks": blocks or [{"label": "login"}],
+ }
+ if finally_block_label is not None:
+ workflow_definition["finally_block_label"] = finally_block_label
return SimpleNamespace(
workflow_id="wf-1",
- workflow_definition={
- "parameters": workflow_parameters or [],
- "blocks": blocks or [{"label": "login"}],
- },
- get_output_parameter=lambda label: SimpleNamespace(label=label) if label == "login" else None,
+ workflow_definition=workflow_definition,
+ get_output_parameter=lambda label: SimpleNamespace(label=label) if label in known_labels else None,
)
@staticmethod
@@ -3475,6 +3485,280 @@ class TestRunBlocksCredentialApproval:
database.organizations.get_organization.assert_awaited_once_with(organization_id="org-1")
+class TestRunBlocksCredentialApprovalFrontierScope:
+ CREDENTIAL_ID = "cred_frontier_login"
+
+ EXPANDED_LOGIN_BLOCK: dict[str, object] = {
+ "label": "login",
+ "block_type": "login",
+ "url": "https://app.example.com/",
+ "parameters": [
+ {
+ "parameter_type": "workflow",
+ "workflow_parameter_type": "credential_id",
+ "key": "credentials",
+ "default_value": CREDENTIAL_ID,
+ }
+ ],
+ }
+
+ PARAMETER_KEY_LOGIN_BLOCK: dict[str, object] = {
+ "label": "login",
+ "block_type": "login",
+ "url": "https://app.example.com/",
+ "parameter_keys": ["credentials"],
+ }
+
+ CODE_BLOCK: dict[str, object] = {"label": "check_page_health", "block_type": "code"}
+
+ @classmethod
+ def _workflow(
+ cls,
+ blocks: list[dict[str, object]],
+ *,
+ output_labels: set[str],
+ finally_block_label: str | None = None,
+ ) -> SimpleNamespace:
+ return TestRunBlocksCredentialApproval._workflow(
+ parameters=[
+ {
+ "parameter_type": "workflow",
+ "workflow_parameter_type": "credential_id",
+ "key": "credentials",
+ "default_value": cls.CREDENTIAL_ID,
+ }
+ ],
+ blocks=blocks,
+ output_labels=output_labels,
+ finally_block_label=finally_block_label,
+ )
+
+ @staticmethod
+ async def _run(monkeypatch, workflow: SimpleNamespace, block_labels: list[str], **db_kwargs) -> tuple:
+ database = TestRunBlocksCredentialApproval._db(workflow=workflow, **db_kwargs)
+ monkeypatch.setattr(run_execution_module.app, "DATABASE", database)
+ monkeypatch.setattr(
+ run_execution_module.app,
+ "WORKFLOW_SERVICE",
+ SimpleNamespace(
+ prepare_workflow=AsyncMock(side_effect=AssertionError("prepare_workflow called")),
+ execute_workflow=AsyncMock(side_effect=AssertionError("execute_workflow called")),
+ ),
+ )
+ result = await _run_blocks_and_collect_debug(
+ {"block_labels": block_labels, "parameters": {}},
+ _ctx(request_policy=RequestPolicy(resolved_credentials=[])),
+ )
+ return result, database
+
+ @pytest.mark.asyncio
+ async def test_credential_free_frontier_raises_no_unapproved_credential_error(self, monkeypatch) -> None:
+ workflow = self._workflow(
+ [self.EXPANDED_LOGIN_BLOCK, self.CODE_BLOCK],
+ output_labels={"login", "check_page_health"},
+ )
+ result, database = await self._run(
+ monkeypatch,
+ workflow,
+ ["check_page_health"],
+ credentials=[SimpleNamespace(credential_id=self.CREDENTIAL_ID)],
+ organization_lookup=None,
+ )
+
+ assert "unapproved_credential_reference" not in (result.get("error") or "")
+ assert result["error"] == "Organization not found"
+ database.credentials.get_credentials_by_ids.assert_awaited_once_with(
+ [self.CREDENTIAL_ID], organization_id="org-1"
+ )
+
+ @pytest.mark.asyncio
+ async def test_expanded_block_credential_in_frontier_is_unapproved(self, monkeypatch) -> None:
+ workflow = self._workflow(
+ [self.EXPANDED_LOGIN_BLOCK, self.CODE_BLOCK],
+ output_labels={"login", "check_page_health"},
+ )
+ result, _ = await self._run(monkeypatch, workflow, ["login", "check_page_health"])
+
+ assert result["ok"] is False
+ assert "unapproved_credential_reference" in result["error"]
+ assert self.CREDENTIAL_ID in result["error"]
+
+ @pytest.mark.asyncio
+ async def test_parameter_key_block_credential_in_frontier_is_unapproved(self, monkeypatch) -> None:
+ workflow = self._workflow(
+ [self.PARAMETER_KEY_LOGIN_BLOCK, self.CODE_BLOCK],
+ output_labels={"login", "check_page_health"},
+ )
+ result, _ = await self._run(monkeypatch, workflow, ["login", "check_page_health"])
+
+ assert result["ok"] is False
+ assert "unapproved_credential_reference" in result["error"]
+ assert self.CREDENTIAL_ID in result["error"]
+
+ @pytest.mark.asyncio
+ async def test_parameter_key_block_credential_outside_frontier_is_not_unapproved(self, monkeypatch) -> None:
+ workflow = self._workflow(
+ [self.PARAMETER_KEY_LOGIN_BLOCK, self.CODE_BLOCK],
+ output_labels={"login", "check_page_health"},
+ )
+ result, _ = await self._run(
+ monkeypatch,
+ workflow,
+ ["check_page_health"],
+ credentials=[SimpleNamespace(credential_id=self.CREDENTIAL_ID)],
+ organization_lookup=None,
+ )
+
+ assert result["error"] == "Organization not found"
+
+ @pytest.mark.asyncio
+ async def test_frontier_code_block_declaring_the_login_credential_is_unapproved(self, monkeypatch) -> None:
+ workflow = self._workflow(
+ [
+ self.PARAMETER_KEY_LOGIN_BLOCK,
+ {"label": "check_page_health", "block_type": "code", "parameter_keys": ["credentials"]},
+ ],
+ output_labels={"login", "check_page_health"},
+ )
+ result, _ = await self._run(monkeypatch, workflow, ["check_page_health"])
+
+ assert result["ok"] is False
+ assert "unapproved_credential_reference" in result["error"]
+ assert self.CREDENTIAL_ID in result["error"]
+
+ @pytest.mark.asyncio
+ async def test_direct_block_credential_id_in_frontier_is_unapproved(self, monkeypatch) -> None:
+ workflow = self._workflow(
+ [
+ {"label": "login", "block_type": "google_sheets_read", "credential_id": self.CREDENTIAL_ID},
+ self.CODE_BLOCK,
+ ],
+ output_labels={"login", "check_page_health"},
+ )
+ result, _ = await self._run(monkeypatch, workflow, ["login"])
+
+ assert result["ok"] is False
+ assert "unapproved_credential_reference" in result["error"]
+ assert self.CREDENTIAL_ID in result["error"]
+
+ @pytest.mark.asyncio
+ async def test_credential_inside_executing_loop_child_is_unapproved(self, monkeypatch) -> None:
+ workflow = self._workflow(
+ [
+ {"label": "iterate", "block_type": "for_loop", "loop_blocks": [self.EXPANDED_LOGIN_BLOCK]},
+ self.CODE_BLOCK,
+ ],
+ output_labels={"iterate", "check_page_health"},
+ )
+ result, _ = await self._run(monkeypatch, workflow, ["iterate"])
+
+ assert result["ok"] is False
+ assert "unapproved_credential_reference" in result["error"]
+ assert self.CREDENTIAL_ID in result["error"]
+
+ @pytest.mark.asyncio
+ async def test_credential_on_finally_block_outside_frontier_is_unapproved(self, monkeypatch) -> None:
+ workflow = self._workflow(
+ [self.CODE_BLOCK, self.EXPANDED_LOGIN_BLOCK],
+ output_labels={"login", "check_page_health"},
+ finally_block_label="login",
+ )
+ result, _ = await self._run(monkeypatch, workflow, ["check_page_health"])
+
+ assert result["ok"] is False
+ assert "unapproved_credential_reference" in result["error"]
+ assert self.CREDENTIAL_ID in result["error"]
+
+ @pytest.mark.asyncio
+ async def test_unresolvable_frontier_label_falls_back_to_whole_document_unapproved_ids(self, monkeypatch) -> None:
+ workflow = TestRunBlocksCredentialApproval._workflow(
+ parameters=[
+ {
+ "parameter_type": "workflow",
+ "workflow_parameter_type": "credential_id",
+ "key": "credentials",
+ "default_value": self.CREDENTIAL_ID,
+ }
+ ],
+ blocks=[self.EXPANDED_LOGIN_BLOCK, self.CODE_BLOCK],
+ output_labels={"login", "check_page_health", "drifted_label"},
+ )
+ result, _ = await self._run(monkeypatch, workflow, ["check_page_health", "drifted_label"])
+
+ assert result["ok"] is False
+ assert "unapproved_credential_reference" in result["error"]
+ assert self.CREDENTIAL_ID in result["error"]
+
+ @pytest.mark.asyncio
+ async def test_unclaimed_top_level_credential_parameter_stays_unapproved(self, monkeypatch) -> None:
+ workflow = self._workflow([self.CODE_BLOCK], output_labels={"check_page_health"})
+ result, _ = await self._run(monkeypatch, workflow, ["check_page_health"])
+
+ assert result["ok"] is False
+ assert "unapproved_credential_reference" in result["error"]
+ assert self.CREDENTIAL_ID in result["error"]
+
+ @pytest.mark.asyncio
+ async def test_existence_check_still_sees_credentials_outside_the_frontier(self, monkeypatch) -> None:
+ workflow = self._workflow(
+ [self.EXPANDED_LOGIN_BLOCK, self.CODE_BLOCK],
+ output_labels={"login", "check_page_health"},
+ )
+ result, database = await self._run(monkeypatch, workflow, ["check_page_health"], credentials=[])
+
+ assert result["ok"] is False
+ assert "not found in this organization" in result["error"]
+ assert self.CREDENTIAL_ID in result["error"]
+ database.credentials.get_credentials_by_ids.assert_awaited_once_with(
+ [self.CREDENTIAL_ID], organization_id="org-1"
+ )
+
+
+class TestWorkflowBlocksSelectedLabels:
+ PARSED: dict[str, Any] = {
+ "workflow_definition": {
+ "blocks": [
+ {"label": "first", "block_type": "code"},
+ {
+ "label": "iterate",
+ "block_type": "for_loop",
+ "loop_blocks": [
+ {"label": "nested_login", "block_type": "login"},
+ {
+ "label": "nested_branch",
+ "branch_conditions": [
+ {"condition": "c", "blocks": [{"label": "deep", "block_type": "code"}]}
+ ],
+ },
+ ],
+ },
+ {"label": "last", "block_type": "code"},
+ ]
+ }
+ }
+
+ def test_selected_labels_none_is_identical_to_the_unscoped_walk(self) -> None:
+ assert workflow_blocks(self.PARSED, selected_labels=None) == workflow_blocks(self.PARSED)
+ assert [block["label"] for block in workflow_blocks(self.PARSED)] == [
+ "first",
+ "iterate",
+ "nested_login",
+ "nested_branch",
+ "deep",
+ "last",
+ ]
+
+ def test_selected_block_drags_its_descendants(self) -> None:
+ labels = [block["label"] for block in workflow_blocks(self.PARSED, selected_labels={"iterate"})]
+
+ assert labels == ["iterate", "nested_login", "nested_branch", "deep"]
+
+ def test_unselected_ancestor_still_yields_a_selected_descendant(self) -> None:
+ labels = [block["label"] for block in workflow_blocks(self.PARSED, selected_labels={"deep"})]
+
+ assert labels == ["deep"]
+
+
class TestResponseTypeClassificationRuleReachesAgent:
"""Pin the classifier rule that selects ASK_QUESTION when `user_response` asks the user for required input — the agent.py null-out gate keys on `resp_type == "ASK_QUESTION"` and depends on this prompt text."""