Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-12732: Stop the copilot from putting real passwords into generated login code (#7630)
Andrew Neilson85dd46a9ce67
diff --git a/skyvern/forge/sdk/copilot/credential_literal_rebind.py b/skyvern/forge/sdk/copilot/credential_literal_rebind.pynew file mode 100644index 000000000..32c0add30--- /dev/null+++ b/skyvern/forge/sdk/copilot/credential_literal_rebind.py@@ -0,0 +1,186 @@+from __future__ import annotations++import re+from dataclasses import dataclass+from typing import Any, Callable, Mapping, Sequence++import yaml++from skyvern.forge.sdk.copilot.code_block_synthesis import _CREDENTIAL_FIELDS, CREDENTIAL_FILL_TOOL_NAME+from skyvern.forge.sdk.copilot.workflow_credential_utils import credential_param_ids++_IDENTIFIER_RE = re.compile(r"[A-Za-z_]\w*")+_STRING_ASSIGN_TMPL = r"^[ \t]*{name}[ \t]*=[ \t]*(?P<q>['\"])(?:\\.|(?!(?P=q)).)*(?P=q)[ \t]*\n?"+++@dataclass(frozen=True)+class CredentialRebindResult:+ workflow_yaml: str+ changed: bool+ rebound: tuple[str, ...]+++def scouted_credential_targets(scout_trajectory: Sequence[Mapping[str, Any]] | None) -> dict[str, tuple[str, str]]:+ """Map each scouted selector to the (credential_id, field) that `fill_credential_field` typed into it."""+ targets: dict[str, tuple[str, str]] = {}+ for interaction in scout_trajectory or []:+ if not isinstance(interaction, Mapping):+ continue+ if str(interaction.get("tool_name") or "").strip() != CREDENTIAL_FILL_TOOL_NAME:+ continue+ selector = str(interaction.get("selector") or "").strip()+ credential_id = str(interaction.get("credential_id") or "").strip()+ field = str(interaction.get("credential_field") or "").strip()+ if not selector or not credential_id or field not in _CREDENTIAL_FIELDS:+ continue+ targets.setdefault(selector, (credential_id, field))+ return targets+++def _existing_param_key(parameters: Sequence[object], credential_id: str) -> str | None:+ for key, credential_ids in credential_param_ids(parameters).items():+ if credential_id in credential_ids:+ return key+ return None+++def _mint_param_key(credential_id: str, used: set[str]) -> str:+ suffix = re.sub(r"\W", "", credential_id)[-8:] or "login"+ candidate = f"credential_{suffix}"+ index = 2+ while candidate in used:+ candidate = f"credential_{suffix}_{index}"+ index += 1+ used.add(candidate)+ return candidate+++def _drop_dead_string_assignment(code: str, name: str) -> str:+ pattern = re.compile(_STRING_ASSIGN_TMPL.format(name=re.escape(name)), re.MULTILINE)+ match = pattern.search(code)+ if not match:+ return code+ remaining = code[: match.start()] + code[match.end() :]+ # `credential_x.username` must not count as a use of a local named `username`.+ if re.search(r"(?<![\w.])" + re.escape(name) + r"\b", remaining):+ return code+ return remaining+++def _rebind_block_code(+ code: str, targets: Mapping[str, tuple[str, str]], param_key_for: Callable[[str], str]+) -> tuple[str, list[str], set[str]]:+ rebound: list[str] = []+ used_params: set[str] = set()+ replaced_identifiers: set[str] = set()+ new_code = code++ for selector, (credential_id, field) in targets.items():+ param_key = param_key_for(credential_id)+ access = f"{param_key}.{field}"+ selector_pattern = re.escape(selector)+ patterns = (+ re.compile(r"(\.(?:fill|type)\(\s*['\"]" + selector_pattern + r"['\"]\s*,\s*)([^),]+?)(\s*\))"),+ re.compile(+ r"(\.locator\(\s*['\"]" + selector_pattern + r"['\"]\s*\)\s*\.(?:fill|type)\(\s*)([^),]+?)(\s*\))"+ ),+ )++ def _substitute(match: re.Match[str]) -> str:+ argument = match.group(2).strip()+ if argument == access:+ used_params.add(param_key)+ return match.group(0)+ if _IDENTIFIER_RE.fullmatch(argument):+ replaced_identifiers.add(argument)+ rebound.append(f"{param_key}.{field}")+ used_params.add(param_key)+ return match.group(1) + access + match.group(3)++ for pattern in patterns:+ new_code = pattern.sub(_substitute, new_code)++ for identifier in replaced_identifiers:+ new_code = _drop_dead_string_assignment(new_code, identifier)++ return new_code, rebound, used_params+++def rebind_scouted_credential_literals(+ workflow_yaml: str | None, scout_trajectory: Sequence[Mapping[str, Any]] | None+) -> CredentialRebindResult:+ """Rewrite raw credential literals in authored code blocks into credential-parameter access.++ Any fill/type whose selector was scouted by `fill_credential_field` is rebound to+ `<credential_param>.<field>` regardless of which author wrote the code, so a leaked literal+ cannot reach persistence.+ """+ empty = CredentialRebindResult(workflow_yaml=workflow_yaml or "", changed=False, rebound=())+ if not workflow_yaml or not workflow_yaml.strip():+ return empty+ targets = scouted_credential_targets(scout_trajectory)+ if not targets:+ return empty+ try:+ parsed = yaml.safe_load(workflow_yaml)+ except yaml.YAMLError:+ return empty+ if not isinstance(parsed, dict):+ return empty+ workflow_definition = parsed.get("workflow_definition")+ if not isinstance(workflow_definition, dict):+ return empty+ blocks = workflow_definition.get("blocks")+ if not isinstance(blocks, list):+ return empty++ parameters = workflow_definition.get("parameters")+ parameters = parameters if isinstance(parameters, list) else []+ used_keys = {str(p.get("key")) for p in parameters if isinstance(p, dict) and p.get("key")}+ assigned: dict[str, str] = {}++ def param_key_for(credential_id: str) -> str:+ if credential_id in assigned:+ return assigned[credential_id]+ key = _existing_param_key(parameters, credential_id) or _mint_param_key(credential_id, used_keys)+ assigned[credential_id] = key+ return key++ all_rebound: list[str] = []+ minted_for: set[str] = set()++ for block in blocks:+ if not isinstance(block, dict):+ continue+ code = block.get("code")+ if not isinstance(code, str) or not code.strip():+ continue+ new_code, rebound, used_params = _rebind_block_code(code, targets, param_key_for)+ if not rebound:+ continue+ block["code"] = new_code+ all_rebound.extend(rebound)+ parameter_keys = block.get("parameter_keys")+ parameter_keys = list(parameter_keys) if isinstance(parameter_keys, list) else []+ for key in sorted(used_params):+ if key not in parameter_keys:+ parameter_keys.append(key)+ block["parameter_keys"] = parameter_keys+ minted_for.update(used_params)++ if not all_rebound:+ return empty++ for credential_id, key in assigned.items():+ if key not in minted_for:+ continue+ if _existing_param_key(parameters, credential_id):+ continue+ parameters.append({"key": key, "parameter_type": "credential", "credential_id": credential_id})+ workflow_definition["parameters"] = parameters++ return CredentialRebindResult(+ workflow_yaml=yaml.safe_dump(parsed, sort_keys=False),+ changed=True,+ rebound=tuple(all_rebound),+ )diff --git a/skyvern/forge/sdk/copilot/tools/guardrails.py b/skyvern/forge/sdk/copilot/tools/guardrails.pyindex 1bcfb1d1b..4654c9c32 100644--- a/skyvern/forge/sdk/copilot/tools/guardrails.py+++ b/skyvern/forge/sdk/copilot/tools/guardrails.py@@ -1,5 +1,6 @@from __future__ import annotations+import hashlibimport jsonfrom typing import Any@@ -8,14 +9,22 @@ from agents import ToolGuardrailFunctionOutput, ToolInputGuardrail, ToolInputGuafrom skyvern.forge.sdk.copilot.blocker_signal import BlockerKind, CopilotToolBlockerSignal, RecoveryHintfrom skyvern.forge.sdk.copilot.build_phase import _phase_blocker_signal+from skyvern.forge.sdk.copilot.build_test_outcome import (+ record_build_test_outcome,+ recorded_outcome_from_author_time_reject,+)from skyvern.forge.sdk.copilot.composition_evidence import (composition_page_evidence_error,turn_has_scout_interaction,workflow_target_url,)from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy+from skyvern.forge.sdk.copilot.credential_literal_rebind import rebind_scouted_credential_literals+from skyvern.forge.sdk.copilot.enforcement import _record_code_authoring_guardrail_rejectfrom skyvern.forge.sdk.copilot.loop_detection import record_consecutive_tool_result_boundary_for_ctxfrom skyvern.forge.sdk.copilot.output_policy import (+ OutputPolicyReason,+ OutputPolicyVerdict,evaluate_output_policy,format_output_policy_tool_error,output_policy_verdict_to_trace_data,@@ -85,19 +94,83 @@ def _workflow_yaml_output_policy_guardrail(data: ToolInputGuardrailData) -> Tool)LOG.info("copilot output policy tool guardrail verdict", **trace_data)if not verdict.allowed:+ rebound_yaml = _rebound_credential_yaml(tool_context, workflow_yaml, verdict, tool_arguments)+ if rebound_yaml is not None:+ rebound_trace = {**trace_data, "allowed": True, "credential_literals_rebound": True}+ LOG.info("copilot output policy rebound scouted credential literals", **rebound_trace)+ return ToolGuardrailFunctionOutput.allow(output_info=rebound_trace)error = format_output_policy_tool_error(verdict)tool_name = getattr(tool_context, "tool_name", None)+ copilot_ctx = getattr(tool_context, "context", None)if isinstance(tool_name, str) and tool_name:record_consecutive_tool_result_boundary_for_ctx(- getattr(tool_context, "context", None),+ copilot_ctx,tool_name,{"ok": False, "error": error},arguments=tool_arguments,)+ _record_output_policy_guardrail_churn(copilot_ctx, tool_name, workflow_yaml, verdict)return ToolGuardrailFunctionOutput.reject_content(error, output_info=trace_data)return ToolGuardrailFunctionOutput.allow(output_info=trace_data)+def _rebound_credential_yaml(+ tool_context: Any,+ workflow_yaml: str | None,+ verdict: OutputPolicyVerdict,+ tool_arguments: dict[str, Any],+) -> str | None:+ """Rebind scouted credential literals so a leak the seam can repair never becomes a reject.++ Returns the rebound YAML only when it independently clears the output policy, so the+ raw_secret_leak clamp still fails closed on anything the deterministic rebind cannot fix.+ """+ if OutputPolicyReason.RAW_SECRET_LEAK not in verdict.reason_codes:+ return None+ ctx = getattr(tool_context, "context", None)+ if not isinstance(ctx, AgentContext):+ return None+ result = rebind_scouted_credential_literals(workflow_yaml, ctx.scout_trajectory)+ if not result.changed:+ return None+ recheck = evaluate_output_policy(+ request_policy=ctx.request_policy,+ workflow_yaml=result.workflow_yaml,+ tool_arguments={**tool_arguments, "workflow_yaml": result.workflow_yaml},+ )+ if not recheck.allowed:+ return None+ tool_arguments["workflow_yaml"] = result.workflow_yaml+ try:+ tool_context.tool_arguments = json.dumps(tool_arguments)+ except (AttributeError, TypeError, ValueError):+ LOG.warning("copilot rebound credential yaml could not be written back to tool arguments")+ return None+ return result.workflow_yaml+++def _record_output_policy_guardrail_churn(+ ctx: object, tool_name: str, workflow_yaml: str | None, verdict: OutputPolicyVerdict+) -> None:+ if not isinstance(ctx, AgentContext):+ return+ structural_payload = {+ "surface": "output_policy_tool_input",+ "tool": tool_name,+ "reason_codes": sorted(reason.value for reason in verdict.reason_codes),+ "workflow_yaml_hash": hashlib.sha256((workflow_yaml or "").encode("utf-8")).hexdigest(),+ }+ record_build_test_outcome(+ ctx,+ recorded_outcome_from_author_time_reject(+ reason_code="output_policy_reject",+ attempted_tool=tool_name,+ structural_payload=structural_payload,+ ),+ )+ _record_code_authoring_guardrail_reject(ctx, defer_churn_stop=True)++_WORKFLOW_YAML_OUTPUT_POLICY_GUARDRAIL = ToolInputGuardrail(guardrail_function=_workflow_yaml_output_policy_guardrail,name="workflow_yaml_output_policy_guardrail",diff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.pyindex 641c284e7..fa664ce82 100644--- a/tests/unit/test_copilot_code_block_synthesis.py+++ b/tests/unit/test_copilot_code_block_synthesis.py@@ -4193,3 +4193,52 @@ class TestSharedSubmitPredicate:]gap = credential_scout_gap(trajectory, [(frozenset({"cred_1"}), frozenset({"username"}))], requires_submit=True)assert gap.missing_submit is False+++_LOGIN_HOST = "https://authenticationtest.com/login"+_INLINE_SECRET_SENTINEL = "Hunter2Portal!"+++def test_credential_fill_trajectory_binds_param_access_and_omits_literals() -> None:+ trajectory = [+ _credential_fill(+ selector="#username", credential_id="cred_x", credential_field="username", source_url=_LOGIN_HOST+ ),+ _credential_fill(+ selector="#password", credential_id="cred_x", credential_field="password", source_url=_LOGIN_HOST+ ),+ _interaction("click", selector="button[type=submit]", source_url=_LOGIN_HOST),+ ]++ result = synthesize_code_block(trajectory, strict_selectors=True)++ assert result is not None+ credential_param = next(param for param in result.parameters if param.get("credential_id") == "cred_x")+ credential_key = credential_param["key"]+ assert f"{credential_key}.username" in result.code+ assert f"{credential_key}.password" in result.code+ assert _INLINE_SECRET_SENTINEL not in result.code+++def test_type_text_secret_bypass_is_not_carried_into_synthesized_block() -> None:+ trajectory = [+ _credential_fill(+ selector="#username", credential_id="cred_x", credential_field="username", source_url=_LOGIN_HOST+ ),+ _interaction(+ "type_text",+ selector="#password",+ source_url=_LOGIN_HOST,+ typed_value="",+ raw_typed_value=_INLINE_SECRET_SENTINEL,+ typed_length=len(_INLINE_SECRET_SENTINEL),+ role="textbox",+ ),+ ]++ result = synthesize_code_block(trajectory, strict_selectors=True)++ assert result is not None+ assert _INLINE_SECRET_SENTINEL not in result.code+ credential_param = next(param for param in result.parameters if param.get("credential_id") == "cred_x")+ assert f"{credential_param['key']}.username" in result.code