Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-9926: reject credential ID baked into block prose in Workflow Copilot (#6097)
Andrew Neilsonf3461ec2af91
diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.pyindex 0b9306cb1..a6d8cd743 100644--- a/skyvern/forge/sdk/copilot/tools.py+++ b/skyvern/forge/sdk/copilot/tools.py@@ -224,21 +224,35 @@ def _extract_credential_ids_from_tool_value(value: Any) -> list[str]:return list(dict.fromkeys(found))+def _credential_parameter_slot_field(parameter: Any) -> str | None:+ """Return the field name that legitimately carries a `cred_xxx` value for+ this parameter dict, or None if the parameter is not a credential-binding+ slot. Two shapes resolve a credential at runtime: a top-level or block-level+ `parameter_type: credential` with the ID in `credential_id`, and a+ `parameter_type: workflow` + `workflow_parameter_type: credential_id` with+ the ID in `default_value`.+ """+ if not isinstance(parameter, dict):+ return None+ parameter_type = str(parameter.get("parameter_type") or "").lower()+ if parameter_type == "credential":+ return "credential_id"+ workflow_parameter_type = str(parameter.get("workflow_parameter_type") or "").lower()+ if parameter_type == "workflow" and workflow_parameter_type == WorkflowParameterType.CREDENTIAL_ID.value:+ return "default_value"+ return None++def _extract_credential_ids_from_workflow_parameters(parameters: Any) -> list[str]:if not isinstance(parameters, list):return []found: list[str] = []for parameter in parameters:- if not isinstance(parameter, dict):+ slot_field = _credential_parameter_slot_field(parameter)+ if slot_field is None:continue-- parameter_type = str(parameter.get("parameter_type") or "").lower()- workflow_parameter_type = str(parameter.get("workflow_parameter_type") or "").lower()- if parameter_type == "credential":- found.extend(_extract_credential_ids_from_tool_value(parameter.get("credential_id")))- elif parameter_type == "workflow" and workflow_parameter_type == WorkflowParameterType.CREDENTIAL_ID.value:- found.extend(_extract_credential_ids_from_tool_value(parameter.get("default_value")))+ found.extend(_extract_credential_ids_from_tool_value(parameter.get(slot_field)))return list(dict.fromkeys(found))@@ -262,21 +276,105 @@ def _extract_credential_ids_from_workflow_definition(workflow_definition: Any) -return _extract_credential_ids_from_workflow_parameters(definition.get("parameters"))-def _extract_credential_ids_from_workflow_yaml(workflow_yaml: str | None) -> list[str]:+def _parsed_workflow_definition(workflow_yaml: str | None) -> dict[str, Any] | None:if not workflow_yaml:- return []+ return Nonetry:parsed = safe_load_no_dates(workflow_yaml)except yaml.YAMLError:- return []+ return Noneif not isinstance(parsed, dict):- return []+ return Noneworkflow_definition = parsed.get("workflow_definition")if not isinstance(workflow_definition, dict):+ return None+ return workflow_definition+++def _extract_credential_ids_from_workflow_yaml(workflow_yaml: str | None) -> list[str]:+ workflow_definition = _parsed_workflow_definition(workflow_yaml)+ if workflow_definition is None:return []return _extract_credential_ids_from_workflow_parameters(workflow_definition.get("parameters"))+_MISBINDING_WORKFLOW_LOCATION = "workflow"+++def _credential_id_misbinding_findings(workflow_yaml: str | None) -> list[dict[str, str]]:+ workflow_definition = _parsed_workflow_definition(workflow_yaml)+ if workflow_definition is None:+ return []++ findings: list[dict[str, str]] = []++ def _scan_value(value: Any, location: str, field: str) -> None:+ if isinstance(value, str):+ for credential_id in _CREDENTIAL_ID_RE.findall(value):+ findings.append({"location": location, "field": field, "credential_id": credential_id})+ elif isinstance(value, list):+ for item in value:+ _scan_value(item, location, field)+ elif isinstance(value, dict):+ for nested_field, nested_value in value.items():+ _scan_value(nested_value, location, str(nested_field))++ def _scan_parameter(parameter: Any, location: str) -> None:+ if not isinstance(parameter, dict):+ return+ legal_slot_field = _credential_parameter_slot_field(parameter)+ for field_name, field_value in parameter.items():+ if field_name == legal_slot_field:+ continue+ _scan_value(field_value, location, str(field_name))++ for parameter in workflow_definition.get("parameters") or []:+ _scan_parameter(parameter, _MISBINDING_WORKFLOW_LOCATION)++ for block in _iter_yaml_blocks(workflow_definition.get("blocks")):+ label = str(block.get("label") or "<unlabeled>")+ for field_name, field_value in block.items():+ if field_name == "parameters":+ if isinstance(field_value, list):+ for parameter in field_value:+ _scan_parameter(parameter, label)+ continue+ if field_name == "loop_blocks":+ continue+ _scan_value(field_value, label, str(field_name))++ return findings+++def _credential_id_misbinding_error_message(findings: list[dict[str, str]]) -> str:+ grouped: dict[tuple[str, str], list[str]] = {}+ for finding in findings:+ key = (finding["location"], finding["credential_id"])+ grouped.setdefault(key, []).append(finding["field"])++ location_lines: list[str] = []+ for (location, credential_id), fields in grouped.items():+ unique_fields = list(dict.fromkeys(fields))+ joined = ", ".join(f"`{field}`" for field in unique_fields)+ scope = "workflow parameter" if location == _MISBINDING_WORKFLOW_LOCATION else f"block `{location}`"+ location_lines.append(f"- `{credential_id}` in {scope} field(s): {joined}")+ body = "\n".join(location_lines)++ return (+ "A credential ID is sitting in workflow fields that do not resolve it, so at runtime the agent types "+ "the literal ID into the page instead of the stored username/password:\n"+ f"{body}\n"+ "Fix BOTH halves before retrying:\n"+ "1. Bind the credential once: add a `credential` parameter (or a `workflow` parameter with "+ "`workflow_parameter_type: credential_id` and the ID in `default_value`) and reference its key from the "+ "login block's `parameter_keys`.\n"+ "2. Delete the credential ID string from every field listed above. `navigation_goal`, "+ "`complete_criterion`, `terminate_criterion` and similar fields are plain-language instructions — they "+ "must describe the outcome without naming the credential ID. Do NOT relocate the literal ID into another "+ "prose or list field; only the credential parameter slot may hold it."+ )++def _missing_credential_reference_tool_error(missing_credential_ids: list[str]) -> str:formatted_ids = ", ".join(f"`{credential_id}`" for credential_id in missing_credential_ids)id_word = "ID" if len(missing_credential_ids) == 1 else "IDs"@@ -1097,6 +1195,16 @@ async def _update_workflow(if credential_error is not None:return {"ok": False, "error": credential_error}+ misbinding_findings = _credential_id_misbinding_findings(workflow_yaml)+ if misbinding_findings:+ LOG.info(+ "copilot credential id misbinding rejected",+ organization_id=ctx.organization_id,+ workflow_id=ctx.workflow_id,+ findings=misbinding_findings,+ )+ return {"ok": False, "error": _credential_id_misbinding_error_message(misbinding_findings)}+output_policy_verdict = evaluate_output_policy(request_policy=getattr(ctx, "request_policy", None),workflow_yaml=workflow_yaml,diff --git a/tests/unit/test_copilot_tools_credential_id_misbinding.py b/tests/unit/test_copilot_tools_credential_id_misbinding.pynew file mode 100644index 000000000..95a9f8524--- /dev/null+++ b/tests/unit/test_copilot_tools_credential_id_misbinding.py@@ -0,0 +1,458 @@+from __future__ import annotations++import textwrap+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from skyvern.forge.sdk.copilot.runtime import AgentContext+from skyvern.forge.sdk.copilot.tools import (+ _credential_id_misbinding_error_message,+ _credential_id_misbinding_findings,+ _update_workflow,+)+++def _yaml(body: str) -> str:+ return textwrap.dedent(body).strip() + "\n"+++def test_credential_id_in_navigation_goal_is_flagged() -> None:+ yaml = _yaml(+ """+ title: Sign in+ workflow_definition:+ parameters: []+ blocks:+ - block_type: login+ label: login_to_portal+ url: https://authenticationtest.com/loginUserAndPassword/+ navigation_goal: Sign in with credential cred_527971855302737592 by entering its username and password.+ """+ )++ findings = _credential_id_misbinding_findings(yaml)++ assert findings == [+ {+ "location": "login_to_portal",+ "field": "navigation_goal",+ "credential_id": "cred_527971855302737592",+ }+ ]+++def test_credential_id_bound_through_workflow_parameter_is_allowed() -> None:+ yaml = _yaml(+ """+ title: Sign in+ workflow_definition:+ parameters:+ - key: login_credentials+ parameter_type: workflow+ workflow_parameter_type: credential_id+ default_value: cred_527971855302737592+ blocks:+ - block_type: login+ label: login_to_portal+ url: https://authenticationtest.com/loginUserAndPassword/+ parameter_keys: [login_credentials]+ """+ )++ assert _credential_id_misbinding_findings(yaml) == []+++def test_credential_id_bound_through_block_credential_parameter_is_allowed() -> None:+ yaml = _yaml(+ """+ title: Sign in+ workflow_definition:+ parameters: []+ blocks:+ - block_type: login+ label: login_to_portal+ url: https://authenticationtest.com/loginUserAndPassword/+ parameters:+ - parameter_type: credential+ key: login_credentials+ credential_id: cred_527971855302737592+ """+ )++ assert _credential_id_misbinding_findings(yaml) == []+++def test_credential_id_in_parameter_keys_list_is_flagged() -> None:+ yaml = _yaml(+ """+ title: Sign in+ workflow_definition:+ parameters: []+ blocks:+ - block_type: login+ label: login_to_portal+ url: https://authenticationtest.com/loginUserAndPassword/+ parameter_keys: [cred_527971855302737592]+ """+ )++ findings = _credential_id_misbinding_findings(yaml)++ assert findings == [+ {+ "location": "login_to_portal",+ "field": "parameter_keys",+ "credential_id": "cred_527971855302737592",+ }+ ]+++def test_credential_id_in_complete_and_terminate_criterion_is_flagged() -> None:+ yaml = _yaml(+ """+ title: Sign in+ workflow_definition:+ parameters: []+ blocks:+ - block_type: login+ label: login_to_portal+ navigation_goal: Sign in to the portal.+ complete_criterion: Logged in as cred_527971855302737592.+ terminate_criterion: Abort if cred_527971855302737592 cannot be used.+ """+ )++ findings = _credential_id_misbinding_findings(yaml)+ fields = {(f["location"], f["field"]) for f in findings}++ assert fields == {+ ("login_to_portal", "complete_criterion"),+ ("login_to_portal", "terminate_criterion"),+ }+++def test_credential_id_inside_loop_block_prose_is_flagged() -> None:+ yaml = _yaml(+ """+ title: Sign in+ workflow_definition:+ parameters: []+ blocks:+ - block_type: for_loop+ label: outer+ loop_blocks:+ - block_type: login+ label: inner_login+ navigation_goal: Log in with cred_527971855302737592.+ """+ )++ findings = _credential_id_misbinding_findings(yaml)++ assert findings == [+ {+ "location": "inner_login",+ "field": "navigation_goal",+ "credential_id": "cred_527971855302737592",+ }+ ]+++def test_credential_id_in_block_url_prose_is_flagged() -> None:+ yaml = _yaml(+ """+ title: Sign in+ workflow_definition:+ parameters: []+ blocks:+ - block_type: login+ label: login_to_portal+ url: https://authenticationtest.com/loginUserAndPassword/?cred_527971855302737592+ navigation_goal: Sign in.+ """+ )++ findings = _credential_id_misbinding_findings(yaml)++ assert findings == [+ {+ "location": "login_to_portal",+ "field": "url",+ "credential_id": "cred_527971855302737592",+ }+ ]+++def test_credential_id_used_both_legally_and_in_prose_reports_only_the_misbinding() -> None:+ yaml = _yaml(+ """+ title: Sign in+ workflow_definition:+ parameters:+ - key: login_credentials+ parameter_type: workflow+ workflow_parameter_type: credential_id+ default_value: cred_527971855302737592+ blocks:+ - block_type: login+ label: login_to_portal+ navigation_goal: Sign in with cred_527971855302737592.+ parameter_keys: [login_credentials]+ """+ )++ findings = _credential_id_misbinding_findings(yaml)++ assert findings == [+ {+ "location": "login_to_portal",+ "field": "navigation_goal",+ "credential_id": "cred_527971855302737592",+ }+ ]+++def test_workflow_without_credential_ids_is_inert() -> None:+ yaml = _yaml(+ """+ title: Visit+ workflow_definition:+ parameters: []+ blocks:+ - block_type: navigation+ label: visit+ url: https://example.com/+ navigation_goal: Open the homepage.+ """+ )++ assert _credential_id_misbinding_findings(yaml) == []+++def test_parameter_without_parameter_type_field_is_scanned() -> None:+ yaml = _yaml(+ """+ title: Sign in+ workflow_definition:+ parameters:+ - key: opaque+ description: stashed cred_527971855302737592 in a description+ blocks: []+ """+ )++ findings = _credential_id_misbinding_findings(yaml)++ assert findings == [+ {+ "location": "workflow",+ "field": "description",+ "credential_id": "cred_527971855302737592",+ }+ ]+++def test_jinja_reference_to_credential_parameter_is_not_flagged() -> None:+ yaml = _yaml(+ """+ title: Sign in+ workflow_definition:+ parameters:+ - key: login_credentials+ parameter_type: workflow+ workflow_parameter_type: credential_id+ default_value: cred_527971855302737592+ blocks:+ - block_type: login+ label: login_to_portal+ navigation_goal: Sign in using {{ login_credentials }}.+ parameter_keys: [login_credentials]+ """+ )++ assert _credential_id_misbinding_findings(yaml) == []+++def test_multiple_distinct_credential_ids_in_same_field_are_all_reported() -> None:+ yaml = _yaml(+ """+ title: Sign in+ workflow_definition:+ parameters: []+ blocks:+ - block_type: login+ label: login_to_portal+ navigation_goal: Try cred_111 then fall back to cred_222.+ """+ )++ findings = _credential_id_misbinding_findings(yaml)++ assert {f["credential_id"] for f in findings} == {"cred_111", "cred_222"}+ assert all(f["field"] == "navigation_goal" for f in findings)+++def test_malformed_or_empty_yaml_is_inert() -> None:+ assert _credential_id_misbinding_findings("") == []+ assert _credential_id_misbinding_findings("- not a workflow yaml\n") == []+ assert _credential_id_misbinding_findings(":: broken yaml ::") == []+++def test_error_message_names_block_label_field_and_credential_id() -> None:+ findings = [+ {+ "location": "login_to_portal",+ "field": "navigation_goal",+ "credential_id": "cred_527971855302737592",+ }+ ]++ message = _credential_id_misbinding_error_message(findings)++ assert "cred_527971855302737592" in message+ assert "navigation_goal" in message+ assert "login_to_portal" in message+ assert "credential parameter" in message.lower()+++def test_error_message_steers_delete_not_relocate() -> None:+ """The message must tell the agent to delete the ID from prose fields, not+ relocate it — a relocate-only reading drives multi-iteration reject loops+ when the agent keeps moving the ID between criterion/goal fields."""+ findings = [+ {"location": "login_to_portal", "field": "complete_criterion", "credential_id": "cred_111"},+ {"location": "login_to_portal", "field": "terminate_criterion", "credential_id": "cred_111"},+ ]++ message = _credential_id_misbinding_error_message(findings)+ lowered = message.lower()++ assert "delete" in lowered+ assert "complete_criterion" in message+ assert "terminate_criterion" in message+ assert "parameter_keys" in message+++def _ctx() -> MagicMock:+ ctx = MagicMock(spec=AgentContext)+ ctx.workflow_yaml = ""+ ctx.last_workflow_yaml = None+ ctx.workflow_id = "w_test"+ ctx.workflow_permanent_id = "wpid_test"+ ctx.organization_id = "o_test"+ ctx.allow_untested_workflow_draft = False+ ctx.request_policy = None+ return ctx+++async def test_update_workflow_rejects_credential_id_in_navigation_goal() -> None:+ submitted = _yaml(+ """+ title: Sign in+ workflow_definition:+ parameters: []+ blocks:+ - block_type: login+ label: login_to_portal+ url: https://authenticationtest.com/loginUserAndPassword/+ navigation_goal: Sign in with credential cred_527971855302737592 by entering its username and password.+ """+ )++ with (+ patch(+ "skyvern.forge.sdk.copilot.tools._credential_reference_validation_error",+ new=AsyncMock(return_value=None),+ ),+ patch("skyvern.forge.sdk.copilot.tools.app") as mock_app,+ ):+ mock_app.WORKFLOW_SERVICE.update_workflow_definition = AsyncMock()+ result = await _update_workflow({"workflow_yaml": submitted}, _ctx())++ assert result["ok"] is False+ assert "cred_527971855302737592" in result["error"]+ assert "navigation_goal" in result["error"]+ assert "login_to_portal" in result["error"]+ mock_app.WORKFLOW_SERVICE.update_workflow_definition.assert_not_called()+++async def test_update_workflow_allows_credential_id_in_credential_parameter_slot() -> None:+ submitted = _yaml(+ """+ title: Sign in+ workflow_definition:+ parameters:+ - key: login_credentials+ parameter_type: workflow+ workflow_parameter_type: credential_id+ default_value: cred_527971855302737592+ blocks:+ - block_type: login+ label: login_to_portal+ url: https://authenticationtest.com/loginUserAndPassword/+ parameter_keys: [login_credentials]+ navigation_goal: Sign in to the portal.+ """+ )++ with (+ patch(+ "skyvern.forge.sdk.copilot.tools._credential_reference_validation_error",+ new=AsyncMock(return_value=None),+ ),+ patch(+ "skyvern.forge.sdk.copilot.tools._process_workflow_yaml",+ return_value=MagicMock(+ title="Sign in",+ description=None,+ workflow_definition=MagicMock(),+ proxy_location=None,+ webhook_callback_url=None,+ persist_browser_session=False,+ browser_profile_id=None,+ model=None,+ max_screenshot_scrolls=None,+ extra_http_headers=None,+ run_with=None,+ ai_fallback=None,+ cache_key=None,+ run_sequentially=None,+ sequential_key=None,+ ),+ ),+ patch(+ "skyvern.forge.sdk.copilot.tools.resolve_copilot_created_by_stamp", new=AsyncMock(return_value="copilot")+ ),+ patch("skyvern.forge.sdk.copilot.tools._record_workflow_proxy_location_span"),+ patch("skyvern.forge.sdk.copilot.tools.app") as mock_app,+ ):+ mock_app.WORKFLOW_SERVICE.update_workflow_definition = AsyncMock()+ mock_app.DATABASE = MagicMock()+ result = await _update_workflow({"workflow_yaml": submitted}, _ctx())++ error_text = str(result.get("error", ""))+ assert "credential ID appeared" not in error_text, error_text+++def test_error_message_groups_multiple_findings() -> None:+ findings = [+ {+ "location": "login_to_portal",+ "field": "navigation_goal",+ "credential_id": "cred_111",+ },+ {+ "location": "login_to_portal",+ "field": "complete_criterion",+ "credential_id": "cred_111",+ },+ ]++ message = _credential_id_misbinding_error_message(findings)++ assert "navigation_goal" in message+ assert "complete_criterion" in message+ assert message.count("cred_111") >= 1