Skip to content

Automate browser based workflows with AI

SKY-10876 reject unresolved code sandbox names (#6563)

Andrew Neilson3ae0e91ba6c0
diff --git a/skyvern/forge/sdk/copilot/code_block_preflight.py b/skyvern/forge/sdk/copilot/code_block_preflight.py
index 162cad153..6878ea996 100644
--- a/skyvern/forge/sdk/copilot/code_block_preflight.py
+++ b/skyvern/forge/sdk/copilot/code_block_preflight.py
@@ -9,9 +9,12 @@ import sys
import tempfile
import textwrap
from dataclasses import dataclass
+from functools import cache
from pathlib import Path
from typing import Iterable
+from skyvern.forge.sdk.workflow.models.block import CodeBlock
+
@dataclass(frozen=True)
class CodeBlockPreflightDiagnostic:
@@ -24,6 +27,13 @@ _MYPY_ERROR_RE = re.compile(r"^(?P<path>.*?):(?P<line>\d+): (?P<severity>error):
_LOCATOR_NOT_CALLABLE_RE = re.compile(r'"Locator" not callable\s+\[operator\]')
+@cache
+def _sandbox_global_names() -> frozenset[str]:
+ # Keep this derived from the runtime sandbox, but resolve it lazily so the
+ # analyzer does not bind itself to CodeBlock import-time behavior.
+ return frozenset(name for name in CodeBlock.build_safe_vars() if not name.startswith("__")) | {"page"}
+
+
def preflight_code_block(
code: str,
*,
@@ -72,6 +82,51 @@ def preflight_code_block(
return _parse_mypy_output(stdout)
+def sandbox_unresolved_name_diagnostics(
+ code: str,
+ *,
+ parameter_keys: Iterable[str] = (),
+) -> list[CodeBlockPreflightDiagnostic]:
+ """Find names that the generated code-block sandbox cannot resolve.
+
+ This models the runtime wrapper from ``CodeBlock.generate_async_user_function``:
+ sandbox helpers and ``page`` are exec globals, while valid block parameter
+ keys become wrapper default-argument locals. The analysis is conservative;
+ ambiguous control-flow bindings do not satisfy later reads.
+ """
+
+ try:
+ tree = ast.parse(textwrap.dedent(code).strip() or "pass")
+ except SyntaxError:
+ return []
+
+ unresolved_names, class_names = _SandboxNameAnalyzer(parameter_keys=parameter_keys).analyze(tree.body)
+ if not unresolved_names and not class_names:
+ return []
+
+ names = sorted(unresolved_names)
+ rejected_classes = sorted(class_names)
+ detail_parts: list[str] = []
+ if names:
+ detail_parts.append(f"unresolved names: {', '.join(f'`{name}`' for name in names)}")
+ if rejected_classes:
+ detail_parts.append(
+ "class definitions unavailable in the code sandbox: " + ", ".join(f"`{name}`" for name in rejected_classes)
+ )
+ detail = "; ".join(detail_parts)
+ return [
+ CodeBlockPreflightDiagnostic(
+ code="SANDBOX_UNRESOLVED_NAME",
+ message=(
+ f"Code block references names that are unavailable in the runtime code sandbox or are not "
+ f"definitely initialized before use ({detail}). The sandbox provides `page`, declared code-block "
+ "parameter keys, and its explicit safe helper namespace; `Exception` is the only available "
+ "exception type."
+ ),
+ )
+ ]
+
+
def _static_ast_diagnostics(code: str) -> list[CodeBlockPreflightDiagnostic]:
try:
tree = ast.parse(_build_typed_module(code, parameter_keys=()))
@@ -104,6 +159,343 @@ def _static_ast_diagnostics(code: str) -> list[CodeBlockPreflightDiagnostic]:
return diagnostics
+class _SandboxNameAnalyzer:
+ def __init__(self, *, parameter_keys: Iterable[str], outer_names: Iterable[str] = ()) -> None:
+ self.parameter_names = {key for key in parameter_keys if _valid_python_identifier(key)}
+ self.outer_names = set(outer_names)
+ self.unresolved_names: set[str] = set()
+ self.class_names: set[str] = set()
+
+ def analyze(self, statements: list[ast.stmt]) -> tuple[set[str], set[str]]:
+ local_names = self._local_names(statements)
+ function_names = self._function_names(statements)
+ self._statements(
+ statements,
+ set(self.parameter_names),
+ local_names=local_names,
+ function_names=function_names,
+ )
+ return self.unresolved_names, self.class_names
+
+ def _report_name(self, name: str) -> None:
+ if not name.startswith("__"):
+ self.unresolved_names.add(name)
+
+ def _local_names(self, statements: list[ast.stmt]) -> set[str]:
+ names: set[str] = set()
+
+ class Collector(ast.NodeVisitor):
+ def visit_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
+ names.add(node.name)
+
+ visit_AsyncFunctionDef = visit_FunctionDef
+
+ def _skip_nested_scope(self, node: ast.AST) -> None:
+ return
+
+ visit_Lambda = visit_ListComp = visit_SetComp = visit_DictComp = visit_GeneratorExp = _skip_nested_scope
+
+ def visit_NamedExpr(self, node: ast.NamedExpr) -> None:
+ names.update(_target_names(node.target))
+ self.visit(node.value)
+
+ def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
+ if node.name:
+ names.add(node.name)
+ if node.type is not None:
+ self.visit(node.type)
+ for statement in node.body:
+ self.visit(statement)
+
+ def visit_Import(self, node: ast.Import) -> None:
+ for alias in node.names:
+ names.add(alias.asname or alias.name.split(".", 1)[0])
+
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
+ for alias in node.names:
+ names.add(alias.asname or alias.name)
+
+ def visit_ClassDef(self, node: ast.ClassDef) -> None:
+ names.add(node.name)
+
+ def visit_Name(self, node: ast.Name) -> None:
+ if isinstance(node.ctx, (ast.Store, ast.Del)):
+ names.add(node.id)
+
+ collector = Collector()
+ for statement in statements:
+ collector.visit(statement)
+ return names
+
+ def _function_names(self, statements: list[ast.stmt]) -> set[str]:
+ return {
+ statement.name for statement in statements if isinstance(statement, (ast.FunctionDef, ast.AsyncFunctionDef))
+ }
+
+ def _statements(
+ self,
+ statements: list[ast.stmt],
+ initialized: set[str],
+ *,
+ local_names: set[str],
+ function_names: set[str],
+ ) -> set[str]:
+ current = set(initialized)
+ for statement in statements:
+ current = self._statement(
+ statement,
+ current,
+ local_names=local_names,
+ function_names=function_names,
+ )
+ return current
+
+ def _statement(
+ self,
+ node: ast.stmt,
+ initialized: set[str],
+ *,
+ local_names: set[str],
+ function_names: set[str],
+ ) -> set[str]:
+ if isinstance(node, ast.Assign):
+ self._expr(node.value, initialized, local_names=local_names)
+ return self._store(node.targets, initialized)
+ if isinstance(node, ast.AnnAssign):
+ if node.value is not None:
+ self._expr(node.value, initialized, local_names=local_names)
+ return self._store([node.target], initialized)
+ return initialized
+ if isinstance(node, ast.AugAssign):
+ self._augmented_target_read(node.target, initialized, local_names=local_names)
+ self._expr(node.value, initialized, local_names=local_names)
+ return self._store([node.target], initialized)
+ if isinstance(node, ast.Delete):
+ return initialized - {name for target in node.targets for name in _target_names(target)}
+ if isinstance(node, (ast.For, ast.AsyncFor)):
+ self._expr(node.iter, initialized, local_names=local_names)
+ self._statements(
+ node.body,
+ self._store([node.target], initialized),
+ local_names=local_names,
+ function_names=function_names,
+ )
+ self._statements(
+ node.orelse,
+ set(initialized),
+ local_names=local_names,
+ function_names=function_names,
+ )
+ return initialized
+ if isinstance(node, ast.While):
+ self._expr(node.test, initialized, local_names=local_names)
+ self._statements(node.body, set(initialized), local_names=local_names, function_names=function_names)
+ self._statements(node.orelse, set(initialized), local_names=local_names, function_names=function_names)
+ return initialized
+ if isinstance(node, ast.If):
+ self._expr(node.test, initialized, local_names=local_names)
+ body = self._statements(node.body, set(initialized), local_names=local_names, function_names=function_names)
+ orelse = self._statements(
+ node.orelse,
+ set(initialized),
+ local_names=local_names,
+ function_names=function_names,
+ )
+ return body & orelse
+ if isinstance(node, (ast.With, ast.AsyncWith)):
+ current = set(initialized)
+ for item in node.items:
+ self._expr(item.context_expr, current, local_names=local_names)
+ if item.optional_vars is not None:
+ current = self._store([item.optional_vars], current)
+ return self._statements(node.body, current, local_names=local_names, function_names=function_names)
+ if isinstance(node, (ast.Try, ast.TryStar)):
+ normal = self._statements(
+ node.orelse,
+ self._statements(
+ node.body,
+ set(initialized),
+ local_names=local_names,
+ function_names=function_names,
+ ),
+ local_names=local_names,
+ function_names=function_names,
+ )
+ branches = [normal]
+ for handler in node.handlers:
+ if handler.type is not None:
+ self._expr(handler.type, initialized, local_names=local_names)
+ handler_state = set(initialized)
+ if handler.name:
+ handler_state.add(handler.name)
+ handler_state = self._statements(
+ handler.body,
+ handler_state,
+ local_names=local_names,
+ function_names=function_names,
+ )
+ if handler.name:
+ handler_state.discard(handler.name)
+ branches.append(handler_state)
+ return self._statements(
+ node.finalbody,
+ set.intersection(*branches),
+ local_names=local_names,
+ function_names=function_names,
+ )
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ for expr in _definition_expressions(node):
+ self._expr(expr, initialized, local_names=local_names)
+ self._analyze_nested_function(node, initialized, sibling_function_names=function_names)
+ return {*initialized, node.name}
+ if isinstance(node, ast.ClassDef):
+ self.class_names.add(node.name)
+ for expr in [*node.decorator_list, *node.bases, *[keyword.value for keyword in node.keywords]]:
+ self._expr(expr, initialized, local_names=local_names)
+ return initialized
+
+ for child in ast.iter_child_nodes(node):
+ if isinstance(child, ast.expr):
+ self._expr(child, initialized, local_names=local_names)
+ elif isinstance(child, ast.stmt):
+ initialized = self._statement(
+ child,
+ initialized,
+ local_names=local_names,
+ function_names=function_names,
+ )
+ return initialized
+
+ def _analyze_nested_function(
+ self,
+ node: ast.FunctionDef | ast.AsyncFunctionDef,
+ initialized: set[str],
+ *,
+ sibling_function_names: set[str],
+ ) -> None:
+ parameter_names = _argument_names(node.args)
+ nested = _SandboxNameAnalyzer(
+ parameter_keys=parameter_names,
+ outer_names=initialized | self.outer_names | sibling_function_names | {node.name},
+ )
+ unresolved_names, class_names = nested.analyze(node.body)
+ self.unresolved_names.update(unresolved_names)
+ self.class_names.update(class_names)
+
+ def _expr(self, node: ast.expr, initialized: set[str], *, local_names: set[str]) -> None:
+ if isinstance(node, ast.Name):
+ if isinstance(node.ctx, ast.Load):
+ if node.id in initialized:
+ return
+ if node.id in local_names:
+ self._report_name(node.id)
+ elif node.id not in _sandbox_global_names() and node.id not in self.outer_names:
+ self._report_name(node.id)
+ return
+ if isinstance(node, ast.NamedExpr):
+ self._expr(node.value, initialized, local_names=local_names)
+ # Named expressions bind into the surrounding scope immediately.
+ initialized.update(_target_names(node.target))
+ return
+ if isinstance(node, ast.Lambda):
+ for expr in [*node.args.defaults, *[default for default in node.args.kw_defaults if default is not None]]:
+ self._expr(expr, initialized, local_names=local_names)
+ parameters = _argument_names(node.args)
+ nested = _SandboxNameAnalyzer(parameter_keys=parameters, outer_names=initialized | self.outer_names)
+ nested._expr(node.body, set(parameters), local_names=nested._local_names([ast.Expr(value=node.body)]))
+ self.unresolved_names.update(nested.unresolved_names)
+ self.class_names.update(nested.class_names)
+ return
+ if isinstance(node, (ast.ListComp, ast.SetComp, ast.GeneratorExp)):
+ self._comprehension([node.elt], node.generators, initialized, local_names=local_names)
+ return
+ if isinstance(node, ast.DictComp):
+ self._comprehension([node.key, node.value], node.generators, initialized, local_names=local_names)
+ return
+ for child in ast.iter_child_nodes(node):
+ if isinstance(child, ast.expr):
+ self._expr(child, initialized, local_names=local_names)
+
+ def _comprehension(
+ self,
+ values: list[ast.expr],
+ generators: list[ast.comprehension],
+ initialized: set[str],
+ *,
+ local_names: set[str],
+ ) -> None:
+ comp_state = set(initialized)
+ comp_locals = set(local_names)
+ for generator in generators:
+ self._expr(generator.iter, comp_state, local_names=local_names)
+ comp_state = self._store([generator.target], comp_state)
+ comp_locals.update(_target_names(generator.target))
+ for condition in generator.ifs:
+ self._expr(condition, comp_state, local_names=comp_locals)
+ for value in values:
+ self._expr(value, comp_state, local_names=comp_locals)
+
+ def _store(self, targets: list[ast.expr], initialized: set[str]) -> set[str]:
+ next_initialized = set(initialized)
+ for target in targets:
+ next_initialized.update(_target_names(target))
+ return next_initialized
+
+ def _augmented_target_read(self, node: ast.expr, initialized: set[str], *, local_names: set[str]) -> None:
+ if isinstance(node, ast.Name):
+ if node.id not in initialized:
+ self._report_name(node.id)
+ return
+ self._expr(node, initialized, local_names=local_names)
+
+
+def _argument_names(args: ast.arguments) -> set[str]:
+ return {
+ arg.arg
+ for arg in [
+ *args.posonlyargs,
+ *args.args,
+ *args.kwonlyargs,
+ *([args.vararg] if args.vararg is not None else []),
+ *([args.kwarg] if args.kwarg is not None else []),
+ ]
+ }
+
+
+def _definition_expressions(node: ast.FunctionDef | ast.AsyncFunctionDef) -> list[ast.expr]:
+ args = node.args
+ annotations = [
+ arg.annotation
+ for arg in [
+ *args.posonlyargs,
+ *args.args,
+ *args.kwonlyargs,
+ *([args.vararg] if args.vararg is not None else []),
+ *([args.kwarg] if args.kwarg is not None else []),
+ ]
+ if arg.annotation is not None
+ ]
+ return [
+ *node.decorator_list,
+ *args.defaults,
+ *[default for default in args.kw_defaults if default is not None],
+ *annotations,
+ *([node.returns] if node.returns is not None else []),
+ ]
+
+
+def _target_names(node: ast.AST) -> set[str]:
+ names: set[str] = set()
+ if isinstance(node, ast.Name):
+ names.add(node.id)
+ elif isinstance(node, (ast.Tuple, ast.List)):
+ for element in node.elts:
+ names.update(_target_names(element))
+ elif isinstance(node, ast.Starred):
+ names.update(_target_names(node.value))
+ return names
+
+
def _wizard_step_selector_diagnostic(node: ast.Call) -> CodeBlockPreflightDiagnostic | None:
func = node.func
if not isinstance(func, ast.Attribute) or func.attr != "locator" or not node.args:
diff --git a/skyvern/forge/sdk/copilot/output_policy.py b/skyvern/forge/sdk/copilot/output_policy.py
index 44d374b21..6dacdb787 100644
--- a/skyvern/forge/sdk/copilot/output_policy.py
+++ b/skyvern/forge/sdk/copilot/output_policy.py
@@ -426,7 +426,14 @@ def evaluate_output_policy(
def format_output_policy_tool_error(verdict: OutputPolicyVerdict) -> str:
reasons = ", ".join(reason.value for reason in verdict.reason_codes) or "unknown"
- return f"Output policy blocked this Copilot output before persistence. Reason codes: {reasons}."
+ message = f"Output policy blocked this Copilot output before persistence. Reason codes: {reasons}."
+ if OutputPolicyReason.RAW_SECRET_LEAK in verdict.reason_codes:
+ message += (
+ " For saved credentials, bind a credential_id workflow parameter and reference fields as "
+ "`<key>.username`, `<key>.password`, or `<key>.totp`; do not split, concatenate, or obfuscate "
+ "literal secrets in workflow code or YAML."
+ )
+ return message
def _contains_raw_secret(value: Any) -> bool:
diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.py
index b09953fe1..fb91fac23 100644
--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py
+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py
@@ -14,6 +14,7 @@ from pydantic import AliasChoices, BaseModel, Field, ValidationError
from skyvern.forge import app
from skyvern.forge.sdk.copilot.attribution import resolve_copilot_created_by_stamp
+from skyvern.forge.sdk.copilot.code_block_preflight import sandbox_unresolved_name_diagnostics
from skyvern.forge.sdk.copilot.code_block_synthesis import (
artifact_dependency_id,
artifact_observation_ref_id,
@@ -34,6 +35,8 @@ from skyvern.forge.sdk.copilot.enforcement import (
from skyvern.forge.sdk.copilot.loop_detection import clear_failed_step_tracker_for_tools_in_ctx
from skyvern.forge.sdk.copilot.outcome_verification_trace import record_code_artifact_violations
from skyvern.forge.sdk.copilot.output_policy import (
+ OutputPolicyReason,
+ OutputPolicyVerdict,
evaluate_output_policy,
format_output_policy_tool_error,
output_policy_verdict_to_trace_data,
@@ -55,7 +58,6 @@ from ._shared import (
_proxy_location_trace_value,
_raw_yaml_proxy_location,
_workflow_definition_as_dict,
- _workflow_yaml_blocks_by_label,
)
from .banned_blocks import (
_banned_block_reject_message,
@@ -639,10 +641,17 @@ def _code_artifact_metadata_items(raw_metadata: Any) -> list[Any]:
def _workflow_yaml_code_blocks_by_label(workflow_yaml: str | None) -> dict[str, Mapping[str, Any]]:
+ if workflow_yaml is None:
+ return {}
+ parsed = parse_workflow_yaml(workflow_yaml)
+ if not isinstance(parsed, dict):
+ return {}
blocks: dict[str, Mapping[str, Any]] = {}
- for label, block in _workflow_yaml_blocks_by_label(workflow_yaml).items():
+ for block in workflow_blocks(parsed):
if _enum_or_string_name(block.get("block_type")) == BlockType.CODE.value:
- blocks[label] = block
+ label = block.get("label")
+ if isinstance(label, str) and label:
+ blocks[label] = block
return blocks
@@ -662,7 +671,12 @@ def _code_block_safety_errors(workflow_yaml: str | None, prior_yaml: str | None)
if not code.strip():
continue
prior_block = prior_blocks.get(label)
- if prior_block is not None and str(prior_block.get("code") or "") == code:
+ parameter_keys = _code_block_parameter_keys(block)
+ if (
+ prior_block is not None
+ and str(prior_block.get("code") or "") == code
+ and _code_block_parameter_keys(prior_block) == parameter_keys
+ ):
continue
try:
CodeBlock.is_safe_code(code)
@@ -671,12 +685,24 @@ def _code_block_safety_errors(workflow_yaml: str | None, prior_yaml: str | None)
except InsecureCodeDetected as exc:
errors.append(
f"Code block `{label}` failed the sandbox safety check: {exc}. Rewrite without import "
- "statements, dunder access, or private attributes; the sandbox already provides `page`, "
- "`json`, `re`, `html`, `asyncio.sleep`, and common builtins."
+ "statements, dunder access, or private attributes; the sandbox provides `page`, declared "
+ "code-block parameter keys, `json`, `re`, `html`, `asyncio.sleep`, and its explicit safe helper "
+ "namespace. `Exception` is the only available exception type."
)
+ unresolved_diagnostics = sandbox_unresolved_name_diagnostics(code, parameter_keys=parameter_keys)
+ errors.extend(
+ f"Code block `{label}` failed the sandbox name check: {item.message}" for item in unresolved_diagnostics
+ )
return errors
+def _code_block_parameter_keys(block: Mapping[str, Any]) -> frozenset[str]:
+ raw_keys = block.get("parameter_keys")
+ if not isinstance(raw_keys, list):
+ return frozenset()
+ return frozenset(key for key in raw_keys if isinstance(key, str) and key)
+
+
def _code_seam_rejection_user_summary(*, metadata_rejected: bool, code_rejected: bool) -> str:
if metadata_rejected and code_rejected:
return "I need to adjust the workflow's code and its verification details before testing."
@@ -1436,6 +1462,7 @@ async def _update_workflow(
tool_arguments=params,
)
if not output_policy_verdict.allowed:
+ _record_code_only_raw_secret_reject_span(ctx, output_policy_verdict)
LOG.info(
"copilot output policy tool body verdict",
**output_policy_verdict_to_trace_data(
@@ -1581,6 +1608,22 @@ def _record_workflow_proxy_location_span(workflow_yaml: str, workflow: Workflow)
pass
+def _record_code_only_raw_secret_reject_span(ctx: AgentContext, verdict: OutputPolicyVerdict) -> None:
+ if OutputPolicyReason.RAW_SECRET_LEAK not in verdict.reason_codes:
+ return
+ if _copilot_block_authoring_policy(ctx) != BlockAuthoringPolicy.CODE_ONLY_BROWSER:
+ return
+ with copilot_span(
+ "update_workflow_code_only_raw_secret_reject",
+ data={
+ "tool_name": "update_workflow",
+ "reason_code": OutputPolicyReason.RAW_SECRET_LEAK.value,
+ "block_authoring_policy": BlockAuthoringPolicy.CODE_ONLY_BROWSER.value,
+ },
+ ):
+ pass
+
+
def _record_workflow_update_result(
copilot_ctx: Any, result: dict[str, Any], prior_definition: object | None = None
) -> None:
diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.py
index 2d82eaea1..d3c98990f 100644
--- a/tests/unit/test_copilot_code_block_persist_seam.py
+++ b/tests/unit/test_copilot_code_block_persist_seam.py
@@ -9,6 +9,7 @@ import textwrap
from types import SimpleNamespace
import pytest
+import yaml
from skyvern.forge.sdk.copilot.blocker_signal import assert_clean_user_facing_text
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
@@ -51,6 +52,42 @@ _SAFE_CODE_YAML = _yaml(
"""
)
+
+def _code_yaml(
+ code: str,
+ *,
+ parameter_keys: list[str] | None = None,
+ workflow_param: bool = False,
+ nested: bool = False,
+) -> str:
+ block: dict[str, object] = {
+ "block_type": "code",
+ "label": "nested_search" if nested else "search_registry",
+ "code": textwrap.dedent(code).strip(),
+ }
+ if parameter_keys is not None:
+ block["parameter_keys"] = parameter_keys
+ definition: dict[str, object] = {"blocks": [block]}
+ if workflow_param:
+ definition["parameters"] = [
+ {
+ "parameter_type": "workflow",
+ "workflow_parameter_type": "string",
+ "key": "provider_query",
+ "default_value": "Taylor Brooks",
+ }
+ ]
+ if nested:
+ definition["blocks"] = [
+ {
+ "block_type": "conditional",
+ "label": "choose_path",
+ "branch_conditions": [{"condition": "{{ branch_name }} == 'search'", "blocks": [block]}],
+ }
+ ]
+ return yaml.safe_dump({"title": "Registry lookup", "workflow_definition": definition}, sort_keys=False)
+
+
_SUBMITTED_LITERAL_YAML = _yaml(
"""
title: Provider lookup
@@ -185,6 +222,8 @@ def _credential_code_yaml(*, code: str, credential_id: str = "cred_missing") ->
" blocks:\n"
" - block_type: code\n"
" label: login_with_saved_credential\n"
+ " parameter_keys:\n"
+ " - login_credential\n"
" code: |\n"
f"{indented_code}\n"
)
@@ -263,6 +302,141 @@ class TestCodeSafetySeam:
def test_safe_code_passes(self) -> None:
assert _code_block_safety_errors(_SAFE_CODE_YAML, None) == []
+ def test_unresolved_sandbox_names_are_seam_errors(self) -> None:
+ errors = _code_block_safety_errors(
+ _code_yaml(
+ """
+ raise RuntimeError("not available")
+ raise ValueError("not available")
+ value = getattr(page, "url", "")
+ """
+ ),
+ None,
+ )
+ assert len(errors) == 1
+ for expected in ("search_registry", "RuntimeError", "ValueError", "getattr", "Exception"):
+ assert expected in errors[0]
+ assert _code_block_safety_errors(_code_yaml('raise Exception("allowed")'), None) == []
+
+ def test_parameter_contracts_use_block_keys_only_and_recheck_key_changes(self) -> None:
+ errors = _code_block_safety_errors(_code_yaml("print(provider_query)", workflow_param=True), None)
+ assert len(errors) == 1
+ assert "provider_query" in errors[0]
+
+ assert (
+ _code_block_safety_errors(
+ _code_yaml("print(provider_query)", parameter_keys=["provider_query"], workflow_param=True),
+ None,
+ )
+ == []
+ )
+
+ prior = _code_yaml("print(provider_query)", parameter_keys=["provider_query"], workflow_param=True)
+ current = _code_yaml("print(provider_query)", parameter_keys=[], workflow_param=True)
+ errors = _code_block_safety_errors(current, prior)
+ assert len(errors) == 1
+ assert "provider_query" in errors[0]
+
+ def test_branch_nested_blocks_and_existing_safety_errors_are_checked(self) -> None:
+ errors = _code_block_safety_errors(_code_yaml('raise RuntimeError("nested")', nested=True), None)
+ assert len(errors) == 1
+ assert all(expected in errors[0] for expected in ("nested_search", "RuntimeError"))
+
+ errors = _code_block_safety_errors(
+ _code_yaml(
+ """
+ import asyncio
+ raise RuntimeError("not available")
+ """
+ ),
+ None,
+ )
+ joined = "\n".join(errors)
+ assert "Not allowed to import modules" in joined
+ assert "RuntimeError" in joined
+
+ def test_name_analysis_accepts_safe_locals_and_rejects_runtime_hazards(self) -> None:
+ assert (
+ _code_block_safety_errors(_code_yaml('value = "row"\ncount = 1\ncount += 1\nprint(value, count)'), None)
+ == []
+ )
+
+ errors = _code_block_safety_errors(
+ _code_yaml(
+ """
+ value: str
+ print(value)
+ count += 1
+ page = page
+ x = 1
+ del x
+ print(x)
+ if page:
+ branch_value = 1
+ print(branch_value)
+ class NotRunnable:
+ pass
+ """
+ ),
+ None,
+ )
+ joined = "\n".join(errors)
+ for expected in (
+ "value",
+ "count",
+ "x",
+ "branch_value",
+ "NotRunnable",
+ ):
+ assert expected in joined
+ assert "unresolved names: `branch_value`, `count`, `page`, `value`, `x`" in joined
+
+ def test_name_analysis_allows_recursive_helpers(self) -> None:
+ assert (
+ _code_block_safety_errors(
+ _code_yaml(
+ """
+ def fact(n):
+ if n <= 1:
+ return 1
+ return n * fact(n - 1)
+
+ def is_even(n):
+ if n == 0:
+ return True
+ return is_odd(n - 1)
+
+ def is_odd(n):
+ if n == 0:
+ return False
+ return is_even(n - 1)
+
+ print(fact(4), is_even(4))
+ """
+ ),
+ None,
+ )
+ == []
+ )
+
+ def test_name_analysis_handles_try_star_branching(self) -> None:
+ errors = _code_block_safety_errors(
+ _code_yaml(
+ """
+ try:
+ risky()
+ except* Exception as group:
+ recovered = group
+ print(recovered)
+ """
+ ),
+ None,
+ )
+ assert len(errors) == 1
+ assert "risky" in errors[0]
+ assert "recovered" in errors[0]
+ assert "group" not in errors[0]
+
def test_syntax_error_is_a_seam_error(self) -> None:
broken = _SAFE_CODE_YAML.replace('await page.goto("https://example.com/search")', "await page.goto(")
errors = _code_block_safety_errors(broken, None)
diff --git a/tests/unit/test_copilot_output_policy.py b/tests/unit/test_copilot_output_policy.py
index 53c1d5ca4..a9d2ab425 100644
--- a/tests/unit/test_copilot_output_policy.py
+++ b/tests/unit/test_copilot_output_policy.py
@@ -1799,6 +1799,8 @@ workflow_definition:
assert result["ok"] is False
assert "raw_secret_leak" in result["error"]
+ assert "<key>.password" in result["error"]
+ assert "do not split, concatenate, or obfuscate" in result["error"]
process_mock.assert_not_called()