Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Tell Copilot how to read a saved generic secret in a code block (SKY-16181) (#8533)
Andrew Neilson12f052832b77
diff --git a/skyvern/forge/sdk/copilot/tools/banned_blocks.py b/skyvern/forge/sdk/copilot/tools/banned_blocks.pyindex 74f972ea3..7a0dbd601 100644--- a/skyvern/forge/sdk/copilot/tools/banned_blocks.py+++ b/skyvern/forge/sdk/copilot/tools/banned_blocks.py@@ -3,16 +3,45 @@ from __future__ import annotationsfrom collections.abc import Mappingfrom dataclasses import dataclassfrom enum import StrEnum-from typing import Any+from typing import Any, NamedTuplefrom skyvern.forge.sdk.copilot.block_type_aliases import normalize_copilot_block_type_aliasfrom skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy, normalize_block_authoring_policyfrom skyvern.forge.sdk.copilot.runtime import AgentContextfrom skyvern.forge.sdk.copilot.tracing_setup import copilot_span+from skyvern.forge.sdk.schemas.credentials import CredentialType, TotpTypefrom ._shared import _parse_workflow_blocks+class CredentialCodeAccessors(NamedTuple):+ fields: tuple[str, ...]+ otp: str | None = None+ magic_link: str | None = None+++# What authored code can read off a bound credential parameter, by the saved record's type;+# credit-card accessors are not advertised here.+CREDENTIAL_CODE_ACCESSORS: Mapping[CredentialType, CredentialCodeAccessors] = {+ CredentialType.PASSWORD: CredentialCodeAccessors(+ fields=("<key>.username", "<key>.password"),+ otp="await <key>.otp()",+ magic_link="await <key>.magic_link(page)",+ ),+ CredentialType.SECRET: CredentialCodeAccessors(fields=("<key>.secret_value",)),+}+ONE_TIME_CODE_TOTP_TYPES = frozenset({TotpType.AUTHENTICATOR, TotpType.EMAIL, TotpType.TEXT})+++def credential_code_accessors(credential_type: CredentialType, totp_type: TotpType) -> tuple[str, ...]:+ accessors = CREDENTIAL_CODE_ACCESSORS.get(credential_type)+ if accessors is None:+ return ()+ if totp_type not in ONE_TIME_CODE_TOTP_TYPES:+ return accessors.fields+ return accessors.fields + tuple(name for name in (accessors.otp, accessors.magic_link) if name)++class CopilotBlockPolicyStatus(StrEnum):BANNED = "banned"CODE_NATIVE_PENDING = "code_native_pending"@@ -272,6 +301,25 @@ def _code_only_browser_validation_guidance() -> str:)+def _saved_credential_guidance() -> str:+ accessors = CREDENTIAL_CODE_ACCESSORS[CredentialType.PASSWORD]+ username, password = accessors.fields+ otp, magic_link = accessors.otp, accessors.magic_link+ return (+ "For saved credentials: bind the credential as a workflow parameter with workflow_parameter_type "+ "credential_id and the credential ID in default_value. At runtime the parameter key resolves to a credential "+ f"object. For a `password` credential, read {username} and {password}, use {otp} for authenticator, email, "+ f"or SMS one-time codes, and use {magic_link} when the scouted page offers an emailed sign-in link; that "+ "broker navigates the page without exposing the sign-in link to authored code. Never put literal secret "+ "values in code; scout password-credential fields with fill_credential_field, which does not fill secrets."+ )+++def _secret_credential_guidance() -> str:+ (secret_value,) = CREDENTIAL_CODE_ACCESSORS[CredentialType.SECRET].fields+ return f"A `secret` credential is read with {secret_value}; it carries no username or password."++def _code_only_browser_schema_guidance() -> list[str]:return ["Use one focused code block per durable browser goal, such as open, search, submit, expand, or extract.",@@ -281,7 +329,8 @@ def _code_only_browser_schema_guidance() -> list[str]:_code_only_browser_validation_guidance(),"Keep block outputs JSON-safe and include visible evidence text when extracting records, products, totals, confirmations, or identifiers.","Wait for the value the block returns, not for a URL or a navigation. A page reaches its final URL while it is still rendering, so a URL check passes before the value exists and a navigation wait fails on a page that has already arrived.",- "For saved credentials: bind the credential as a workflow parameter with workflow_parameter_type credential_id and the credential ID in default_value. At runtime the parameter key resolves to a credential object — read <key>.username and <key>.password, use await <key>.otp() for authenticator, email, or SMS one-time codes, and use await <key>.magic_link(page) when the scouted page offers an emailed sign-in link; that broker navigates the page without exposing the sign-in link to authored code. Never put literal secret values in code; scout credential fields with fill_credential_field.",+ _saved_credential_guidance(),+ _secret_credential_guidance(),"The Code runtime provides await solve_captcha(page) for a platform-managed verification challenge observed while scouting; this is an available capability, not a required step for every login.","The Code runtime provides await clear_browser_data(page) when a site needs a clean session before it will sign in: it drops every cookie in the run's browser and all stored data for the page's current origin, and returns nothing. Read page.url first and navigate back to it afterwards. Browser settings pages (chrome://...) cannot be navigated to; this helper is the way to clear state. A workflow parameter named clear_browser_data shadows the helper in both executors. Before calling the helper in that case, rename the parameter to an unused name, preserve its value/default, and update its block bindings, code/template references, and caller-supplied run input keys.","For file attachment: bind the file as a workflow parameter with workflow_parameter_type file_url, then call await attach_authorized_file(page, <file_parameter>, <observed_selector>). The parameter is a handle, not a path: pass it only to that helper. Attaching puts the file's contents in the page, where page scripts and page.evaluate can read them, so attach it only to the page that should receive it. It accepts only that run's materialized file, uploads at most 10 MB, and returns filename and size.",diff --git a/skyvern/forge/sdk/copilot/tools/credentials.py b/skyvern/forge/sdk/copilot/tools/credentials.pyindex 6c8c3ed1e..20958b444 100644--- a/skyvern/forge/sdk/copilot/tools/credentials.py+++ b/skyvern/forge/sdk/copilot/tools/credentials.py@@ -30,13 +30,14 @@ from skyvern.forge.sdk.copilot.workflow_credential_utils import ()from skyvern.forge.sdk.copilot.workflow_yaml import dump_workflow_yamlfrom skyvern.forge.sdk.schemas.copilot_turn_outcome import ConnectedAccountChoice-from skyvern.forge.sdk.schemas.credentials import Credential, TotpType+from skyvern.forge.sdk.schemas.credentials import Credential, CredentialType, TotpTypefrom skyvern.forge.sdk.schemas.google_oauth import GoogleOAuthCredentialBasefrom skyvern.forge.sdk.services import google_oauth_servicefrom skyvern.forge.sdk.workflow.models.parameter import WorkflowParameterTypefrom skyvern.utils.yaml_loader import safe_load_no_datesfrom ._shared import _iter_yaml_blocks, _workflow_definition_as_dict+from .banned_blocks import CREDENTIAL_CODE_ACCESSORS, ONE_TIME_CODE_TOTP_TYPES, credential_code_accessorsLOG = structlog.get_logger()@@ -767,12 +768,15 @@ def _serialize_credential(credential: Credential) -> dict[str, Any]:"credential_type": str(credential.credential_type),"tested_url": credential.tested_url,}+ accessors = credential_code_accessors(credential.credential_type, credential.totp_type)+ if accessors:+ entry["code"] = {"workflow_parameter_type": "credential_id", "accessors": list(accessors)}if credential.username:entry["username"] = credential.usernameentry["totp_type"] = str(credential.totp_type) if credential.totp_type else Noneif credential.totp_identifier:entry["totp_identifier"] = credential.totp_identifier- if credential.totp_type in {TotpType.AUTHENTICATOR, TotpType.EMAIL, TotpType.TEXT}:+ if credential.totp_type in ONE_TIME_CODE_TOTP_TYPES:scouting: dict[str, Any]if credential.totp_type == TotpType.AUTHENTICATOR:scouting = {@@ -788,7 +792,7 @@ def _serialize_credential(credential: Credential) -> dict[str, Any]:"scouting": scouting,"code": {"workflow_parameter_type": "credential_id",- "accessor": "await <credential_parameter_key>.otp()",+ "accessor": CREDENTIAL_CODE_ACCESSORS[CredentialType.PASSWORD].otp,},}elif credential.card_last4:diff --git a/tests/unit/test_copilot_banned_block_policy.py b/tests/unit/test_copilot_banned_block_policy.pyindex c7b5e7518..6ff43ff49 100644--- a/tests/unit/test_copilot_banned_block_policy.py+++ b/tests/unit/test_copilot_banned_block_policy.py@@ -42,6 +42,7 @@ from skyvern.forge.sdk.copilot.tools.banned_blocks import (_COPILOT_CODE_ONLY_BROWSER_BANNED_BLOCK_TYPES,_TASK_V3_PURE_BANNED_BLOCK_TYPES,_TASK_V3_PURE_TASK_BLOCK_TYPES,+ CREDENTIAL_CODE_ACCESSORS,CopilotBlockPolicyStatus,_code_only_browser_authoring_prompt,_code_only_browser_schema_guidance,@@ -584,6 +585,22 @@ def test_code_only_schema_guidance_exposes_credential_runtime_without_otp_procedassert "Transient disappearance of the OTP field" not in guidance+def test_code_only_schema_guidance_exposes_secret_credential_runtime_accessor() -> None:+ lines = _code_only_browser_schema_guidance()+ secret_line = next(line for line in lines if line.startswith("A `secret` credential"))+ password_line = next(line for line in lines if line.startswith("For saved credentials"))++ assert "<key>.secret_value" in secret_line+ assert "otp()" not in secret_line+ assert "magic_link" not in secret_line+ assert "fill_credential_field" not in secret_line+ assert "<key>.secret_value" not in password_line+ assert "fill_credential_field" in password_line+ for accessors in CREDENTIAL_CODE_ACCESSORS.values():+ for accessor in (*accessors.fields, accessors.otp, accessors.magic_link):+ assert accessor is None or accessor in "\n".join(lines)++def test_code_only_schema_guidance_states_the_cold_run_starting_condition() -> None:guidance = "\n".join(_code_only_browser_schema_guidance())entry = next(line for line in _code_only_browser_schema_guidance() if line.startswith("A saved run executes"))diff --git a/tests/unit/test_copilot_tools_list_credentials.py b/tests/unit/test_copilot_tools_list_credentials.pyindex c9fb4aa11..275acfd68 100644--- a/tests/unit/test_copilot_tools_list_credentials.py+++ b/tests/unit/test_copilot_tools_list_credentials.py@@ -1,3 +1,4 @@+import jsonfrom datetime import datetimefrom types import SimpleNamespacefrom unittest.mock import AsyncMock, patch@@ -52,7 +53,7 @@ def test_omits_the_identifier_when_the_credential_carries_none() -> None:},"code": {"workflow_parameter_type": "credential_id",- "accessor": "await <credential_parameter_key>.otp()",+ "accessor": "await <key>.otp()",},}@@ -66,7 +67,7 @@ def test_email_otp_is_code_only_during_scouting() -> None:"scouting": {"available": False, "reason": "workflow_run_context_required"},"code": {"workflow_parameter_type": "credential_id",- "accessor": "await <credential_parameter_key>.otp()",+ "accessor": "await <key>.otp()",},}@@ -87,14 +88,52 @@ def test_serializes_metadata_only_so_no_secret_or_vault_material_reaches_the_age"name","credential_type","tested_url",+ "code","username","totp_type","totp_identifier","one_time_code",}+ assert entry["code"]["accessors"] == [+ "<key>.username",+ "<key>.password",+ "await <key>.otp()",+ "await <key>.magic_link(page)",+ ]+ assert entry["one_time_code"]["code"]["accessor"] in entry["code"]["accessors"]assert not any(SECRET_MARKER in str(value) for value in entry.values())[email protected]("totp_type", [TotpType.NONE, TotpType.PASSKEY])+def test_a_password_credential_without_a_one_time_code_source_advertises_no_otp_accessor(+ totp_type: TotpType,+) -> None:+ entry = _serialize_credential(_password_credential(totp_type=totp_type))++ assert entry["code"]["accessors"] == ["<key>.username", "<key>.password"]+ assert "one_time_code" not in entry+++def test_a_secret_credential_advertises_only_secret_value_and_never_its_value() -> None:+ entry = _serialize_credential(+ _password_credential(+ credential_type=CredentialType.SECRET,+ username=None,+ secret_label="fixture api key",+ item_id=SECRET_MARKER,+ user_context=SECRET_MARKER,+ )+ )++ assert set(entry) == {"credential_id", "name", "credential_type", "tested_url", "code", "secret_label"}+ assert entry["credential_type"] == "secret"+ assert entry["code"] == {"workflow_parameter_type": "credential_id", "accessors": ["<key>.secret_value"]}+ serialized = json.dumps(entry)+ assert SECRET_MARKER not in serialized+ for guessed in ("username", "password", "api_key", "token"):+ assert guessed not in serialized++async def _resolve(reference: str, policy: RequestPolicy, inventory: list[Credential]) -> dict[str, object]:ctx = SimpleNamespace(organization_id="o_test_org", request_policy=policy)with patch.object(credentials_module, "load_credentials", AsyncMock(return_value=inventory)):