Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Copilot: stop asking permission for a saved login the workflow already provides (#SKY-13514) (#8061)
Andrew Neilson036e245719e2
diff --git a/skyvern/forge/sdk/copilot/credential_resolution.py b/skyvern/forge/sdk/copilot/credential_resolution.pyindex 46015c4a2..8079c23f7 100644--- a/skyvern/forge/sdk/copilot/credential_resolution.py+++ b/skyvern/forge/sdk/copilot/credential_resolution.py@@ -75,6 +75,42 @@ def loggable_origin(url: str) -> str:return f"{parsed.scheme.lower()}://{parsed.hostname}{port}"+def is_resolved_page_url(url: str) -> bool:+ """Whether this is an absolute page URL a URL match may be computed against.++ Scheme-less input is not a page. The `https://` normalization these matchers apply would turn+ any bare token — a prompt sentinel, a tool-argument echo, a placeholder — into a hostname that+ matches nothing, and the resulting "no match" reads as a fact about the org's saved credentials.+ """+ try:+ parsed = urlparse(url)+ except ValueError:+ # A malformed authority (`http://[`) raises here, and callers run this ahead of their own+ # resolver guard, so raising would abort the observing tool rather than decline its input.+ return False+ # Keyed on `hostname` where `url_parts` keys the whole netloc, so `https://[email protected]`+ # passes here and still matches no saved credential there; netloc would not harden this.+ return parsed.scheme in {"http", "https"} and bool(parsed.hostname)+++def unresolved_page_url_for_log(url: str) -> str:+ """What a value that is not a page URL points at: its host, else its scheme, else the bare token.++ Userinfo, query, fragment, params and path are the parts a URL carries content in, and content+ is where a secret rides, so the identity a log may name is only ever the components above them.+ A value too malformed to parse has no identity to name, and the outcome field carries that.+ """+ try:+ parsed = urlparse(url)+ except ValueError:+ return ""+ if parsed.hostname:+ return f"{parsed.scheme.lower()}://{parsed.hostname}"[:64] if parsed.scheme else f"//{parsed.hostname}"[:64]+ if parsed.scheme:+ return f"{parsed.scheme.lower()}:"[:64]+ return parsed.path[:64]++def deduplicate_credentials(credentials: list[Credential]) -> list[Credential]:by_id: dict[str, Credential] = {}for credential in credentials:diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.pyindex d021555f0..b07bdc92f 100644--- a/skyvern/forge/sdk/copilot/request_policy.py+++ b/skyvern/forge/sdk/copilot/request_policy.py@@ -28,10 +28,14 @@ from skyvern.forge.sdk.copilot.credential_resolution import (CredentialResolutionTier,)from skyvern.forge.sdk.copilot.credential_resolution import deduplicate_credentials as _deduplicate_credentials+from skyvern.forge.sdk.copilot.credential_resolution import (+ is_resolved_page_url,+)from skyvern.forge.sdk.copilot.credential_resolution import load_credentials as _load_credentialsfrom skyvern.forge.sdk.copilot.credential_resolution import (loggable_origin,resolve_by_url,+ unresolved_page_url_for_log,)from skyvern.forge.sdk.copilot.credential_resolution import url_parts as _url_partsfrom skyvern.forge.sdk.copilot.llm_errors import is_retriable_llm_error@@ -565,7 +569,7 @@ class RequestSlotAnchorCorrectionDecisionV1:LiveCredentialSeam = Literal["fill", "page_observation"]-LivePageResolutionVerdict = Literal["resolved", "ambiguous", "no_match", "declined"]+LivePageResolutionVerdict = Literal["resolved", "ambiguous", "no_match", "declined", "abstain"]@dataclass(frozen=True)@@ -5195,6 +5199,44 @@ def _live_page_log_allowed(policy: RequestPolicy, page_url: str, seam: LiveCredereturn True+def live_page_credentials_admissible(policy: RequestPolicy) -> bool:+ """Whether this turn may bind a saved credential from a live page at all.++ Callers that must pay for evidence — a browser read, a credential load — check this first so a+ turn that could never admit does not buy the evidence to decide it.+ """+ return not policy.raw_secret_detected and policy.allow_run_blocks+++def _live_page_url_abstains(+ policy: RequestPolicy,+ *,+ organization_id: str,+ page_url: str,+ seam: LiveCredentialSeam,+ credential_id: str | None = None,+) -> bool:+ """Whether the seam was handed something that is not a page, and must make no claim about it.++ `no_match` is a factual statement about the org's saved credentials. From an unresolvable input+ the seam has looked at no page at all, so it is not entitled to make one.+ """+ if not page_url or is_resolved_page_url(page_url):+ return False+ if _live_page_log_allowed(policy, page_url, seam, "abstain"):+ LOG.info(+ "copilot credential live-page admission",+ outcome="abstain",+ seam=seam,+ organization_id=organization_id,+ credential_id=credential_id,+ page_url=unresolved_page_url_for_log(page_url),+ tier=None,+ candidate_credential_ids=[],+ )+ return True++async def _resolve_live_page_credentials(policy: RequestPolicy,*,@@ -5205,7 +5247,7 @@ async def _resolve_live_page_credentials(credential_id: str | None = None,) -> CredentialResolution | None:"""Ask the live page which saved credentials it vouches for, or None when a precondition declines."""- if policy.raw_secret_detected or not policy.allow_run_blocks or not page_url:+ if not live_page_credentials_admissible(policy) or not page_url:return Noneif _is_passwordless_email_signin(policy):# Turn-start resolution excludes this shape from every URL tier because a site that signs in@@ -5255,6 +5297,8 @@ async def resolve_credential_for_live_page(Same discriminator and same records as the fill seam; the difference is only that nocredential was requested, so a sole match is the answer rather than something to check against."""+ if _live_page_url_abstains(policy, organization_id=organization_id, page_url=page_url, seam="page_observation"):+ return LivePageResolutionRecord(verdict="abstain", page_url=page_url)resolution = await _resolve_live_page_credentials(policy,organization_id=organization_id,@@ -5319,6 +5363,14 @@ async def admit_credential_for_live_page("""if not credential_id:return LiveCredentialAdmission(False)+ if _live_page_url_abstains(+ policy,+ organization_id=organization_id,+ page_url=page_url,+ seam="fill",+ credential_id=credential_id,+ ):+ return LiveCredentialAdmission(False)resolution = await _resolve_live_page_credentials(policy,organization_id=organization_id,diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.pyindex 7cfea645a..04a02ec4b 100644--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py@@ -22,7 +22,7 @@ from skyvern.forge.sdk.copilot.config import (download_scout_act_required_for_policy,)from skyvern.forge.sdk.copilot.context import CopilotContext-from skyvern.forge.sdk.copilot.credential_resolution import load_credentials+from skyvern.forge.sdk.copilot.credential_resolution import is_resolved_page_url, load_credentialsfrom skyvern.forge.sdk.copilot.enforcement import (_requested_output_labels_by_path,requested_output_extraction_plan,@@ -38,7 +38,11 @@ from skyvern.forge.sdk.copilot.output_designation_resolution import (render_candidates,render_requested_paths,)-from skyvern.forge.sdk.copilot.request_policy import RequestPolicy, resolve_credential_for_live_page+from skyvern.forge.sdk.copilot.request_policy import (+ RequestPolicy,+ live_page_credentials_admissible,+ resolve_credential_for_live_page,+)from skyvern.forge.sdk.copilot.request_slots import is_canonical_request_slot_pathfrom skyvern.forge.sdk.copilot.runtime import AgentContext, ScoutedInteractionfrom skyvern.forge.sdk.copilot.secret_redaction import redact_raw_secrets_for_prompt@@ -46,7 +50,11 @@ from skyvern.forge.sdk.copilot.secret_scrub import registered_scrub_valuesfrom skyvern.forge.sdk.copilot.typed_value_policy import safe_typed_default_value, should_reject_type_text_valuefrom skyvern.forge.sdk.schemas.credentials import Credential-from ._shared import _DISCOVERY_PER_CALL_TIMEOUT_SECONDS, _composition_get_structured_evidence+from ._shared import (+ _DISCOVERY_PER_CALL_TIMEOUT_SECONDS,+ _composition_get_structured_evidence,+ _fallback_page_info,+)from .banned_blocks import (_CODE_ONLY_SELECTOR_ACTION_TOOLS,_CODE_ONLY_TARGET_EVIDENCE_KEYS,@@ -467,10 +475,16 @@ async def _bind_login_credential_for_observed_url(ctx: AgentContext, url: str, rreturnpolicy = ctx.request_policy- if not isinstance(policy, RequestPolicy):+ if not isinstance(policy, RequestPolicy) or not live_page_credentials_admissible(policy):returnorganization_id = ctx.organization_id+ if not is_resolved_page_url(url):+ # A `current_page` inspection stamps its placeholder when the URL read raced the capture.+ # The match is against the page the browser actually reached, so read it again rather than+ # hand over a token no page vouches for.+ url, _ = await _fallback_page_info(ctx)+async def load_once() -> list[Credential]:if ctx.org_credentials_for_turn is None:ctx.org_credentials_for_turn = await load_credentials(organization_id)@@ -496,6 +510,9 @@ async def _bind_login_credential_for_observed_url(ctx: AgentContext, url: str, rcredential = record.candidates[0]result["resolved_login_credential_id"] = credential.credential_idresult["resolved_login_credential_name"] = credential.name+ # The observation may name a placeholder while the match ran against the page read after it,+ # so the page the credential was matched on is reported rather than left to be inferred.+ result["resolved_login_page_url"] = urlelif record.verdict == "ambiguous":result["candidate_login_credentials"] = [{"credential_id": candidate.credential_id, "name": candidate.name} for candidate in record.candidatesdiff --git a/tests/unit/test_copilot_fill_credential_field.py b/tests/unit/test_copilot_fill_credential_field.pyindex 431470848..80e1e42cc 100644--- a/tests/unit/test_copilot_fill_credential_field.py+++ b/tests/unit/test_copilot_fill_credential_field.py@@ -14,6 +14,7 @@ from typing import Any, AsyncIteratorfrom unittest.mock import AsyncMock, patchimport pytest+from structlog.testing import capture_logsfrom skyvern.forge import appfrom skyvern.forge.sdk.copilot import tools as tools_module@@ -21,6 +22,7 @@ from skyvern.forge.sdk.copilot.build_phase import _BROWSER_PRIMITIVE_TOOLSfrom skyvern.forge.sdk.copilot.config import BlockAuthoringPolicyfrom skyvern.forge.sdk.copilot.request_policy import RequestPolicyfrom skyvern.forge.sdk.copilot.tools import credential_fill as credential_fill_module+from skyvern.forge.sdk.copilot.tools import mcp_hooks as mcp_hooks_modulefrom skyvern.forge.sdk.copilot.tools import scouting as scouting_modulefrom skyvern.forge.sdk.schemas.credentials import CredentialType, CredentialVaultType, PasswordCredential, TotpType@@ -1112,6 +1114,108 @@ class TestObservationSeamCredentialBinding:assert result["ok"] is Falseassert page.fill_calls == []+ @pytest.mark.asyncio+ async def test_a_placeholder_observation_url_is_resolved_to_the_live_page_before_binding(self) -> None:+ policy = RequestPolicy()+ ctx = _ctx(request_policy=policy)+ result: dict[str, Any] = {"ok": True}++ with (+ patch.object(mcp_hooks_module, "_fallback_page_info", AsyncMock(return_value=(_FIXTURE_LOGIN_URL, ""))),+ patch(+ "skyvern.forge.app.DATABASE.credentials.get_credentials",+ new=AsyncMock(return_value=[_org_credential("cred_analytics", "analytics", _FIXTURE_LOGIN_URL)]),+ ),+ ):+ await mcp_hooks_module._bind_login_credential_for_observed_url(ctx, "current_page", result)++ assert result["resolved_login_credential_id"] == "cred_analytics"+ assert result["resolved_login_page_url"] == _FIXTURE_LOGIN_URL+ assert policy.live_page_admitted_urls == {"cred_analytics": _FIXTURE_LOGIN_URL}++ @pytest.mark.asyncio+ async def test_a_resolved_page_matching_nothing_still_binds_nothing(self) -> None:+ policy = RequestPolicy()+ ctx = _ctx(request_policy=policy)+ result: dict[str, Any] = {"ok": True}++ with (+ patch.object(mcp_hooks_module, "_fallback_page_info", AsyncMock(return_value=(_FIXTURE_LOGIN_URL, ""))),+ patch(+ "skyvern.forge.app.DATABASE.credentials.get_credentials",+ new=AsyncMock(return_value=[_org_credential("cred_billing", "billing", _DECOY_LOGIN_URL)]),+ ),+ ):+ await mcp_hooks_module._bind_login_credential_for_observed_url(ctx, "current_page", result)++ assert "resolved_login_credential_id" not in result+ assert "resolved_login_page_url" not in result+ assert policy.resolved_credentials == []++ @pytest.mark.asyncio+ async def test_a_resolved_page_matching_two_credentials_offers_both_and_binds_neither(self) -> None:+ policy = RequestPolicy()+ ctx = _ctx(request_policy=policy)+ result: dict[str, Any] = {"ok": True}++ with (+ patch.object(mcp_hooks_module, "_fallback_page_info", AsyncMock(return_value=(_FIXTURE_LOGIN_URL, ""))),+ patch(+ "skyvern.forge.app.DATABASE.credentials.get_credentials",+ new=AsyncMock(+ return_value=[+ _org_credential("cred_one", "analytics one", _FIXTURE_LOGIN_URL),+ _org_credential("cred_two", "analytics two", _FIXTURE_LOGIN_URL),+ ]+ ),+ ),+ ):+ await mcp_hooks_module._bind_login_credential_for_observed_url(ctx, "current_page", result)++ assert result["candidate_login_credentials"] == [+ {"credential_id": "cred_one", "name": "analytics one"},+ {"credential_id": "cred_two", "name": "analytics two"},+ ]+ assert "resolved_login_credential_id" not in result+ assert policy.resolved_credentials == []++ @pytest.mark.asyncio+ async def test_a_turn_without_run_authority_never_reads_the_live_page(self) -> None:+ policy = RequestPolicy(allow_run_blocks=False)+ ctx = _ctx(request_policy=policy)+ reread = AsyncMock(return_value=(_FIXTURE_LOGIN_URL, ""))++ with patch.object(mcp_hooks_module, "_fallback_page_info", reread):+ await mcp_hooks_module._bind_login_credential_for_observed_url(ctx, "current_page", {"ok": True})++ reread.assert_not_awaited()++ @pytest.mark.asyncio+ @pytest.mark.parametrize("observed_url", ["current_page", "http://[", "http://[::1"])+ # No URL at all is absence of evidence; one that is not a page is evidence about no page. The+ # seam separates them, and neither may become a claim about the org's credentials.+ @pytest.mark.parametrize(("reread_url", "outcome"), [("", "declined"), ("about:blank", "abstain")])+ async def test_an_unresolvable_observation_url_reads_no_credentials_at_all(+ self, observed_url: str, reread_url: str, outcome: str+ ) -> None:+ policy = RequestPolicy()+ ctx = _ctx(request_policy=policy)+ result: dict[str, Any] = {"ok": True}+ load_mock = AsyncMock(return_value=[_org_credential("cred_analytics", "analytics", _FIXTURE_LOGIN_URL)])++ with (+ capture_logs() as logs,+ patch.object(mcp_hooks_module, "_fallback_page_info", AsyncMock(return_value=(reread_url, ""))),+ patch("skyvern.forge.app.DATABASE.credentials.get_credentials", new=load_mock),+ ):+ await mcp_hooks_module._bind_login_credential_for_observed_url(ctx, observed_url, result)++ emitted = [entry for entry in logs if entry["event"] == "copilot credential live-page admission"]+ assert [(entry["seam"], entry["outcome"]) for entry in emitted] == [("page_observation", outcome)]+ assert "resolved_login_credential_id" not in result+ assert policy.resolved_credentials == []+ load_mock.assert_not_awaited()+@pytest.mark.asyncioasync def test_two_matches_surface_both_ids_and_bind_nothing(self) -> None:policy = RequestPolicy()diff --git a/tests/unit/test_copilot_request_policy_workflow_credentials.py b/tests/unit/test_copilot_request_policy_workflow_credentials.pyindex c4f39a878..94170e927 100644--- a/tests/unit/test_copilot_request_policy_workflow_credentials.py+++ b/tests/unit/test_copilot_request_policy_workflow_credentials.py@@ -2994,6 +2994,51 @@ class TestLivePageCredentialAdmission:emitted = [entry for entry in logs if entry["event"] == "copilot credential live-page admission"]assert [(entry["seam"], entry["outcome"]) for entry in emitted] == [("fill", "admitted")]+ @pytest.mark.asyncio+ async def test_an_input_that_is_not_a_page_abstains_and_never_steers_the_user(self) -> None:+ with capture_logs() as logs:+ admission, load_mock = await _admit(+ RequestPolicy(),+ credential_id="cred_analytics",+ page_url="current_page",+ org_credentials=[_cred("analytics", "cred_analytics", _SAVED_LOGIN_URL)],+ )++ emitted = [entry for entry in logs if entry["event"] == "copilot credential live-page admission"]+ assert admission.admitted is False+ assert admission.steer is None+ assert [(entry["seam"], entry["outcome"]) for entry in emitted] == [("fill", "abstain")]+ load_mock.assert_not_awaited()++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("page_url", "logged_identity"),+ [+ # Userinfo, query, fragment, params and path each carry the secret; none is identity.+ ("scout:hunter2@current_page", "scout:"),+ ("data:text/html,hunter2", "data:"),+ ("current_page;jsessionid=hunter2", "current_page"),+ ("custom://current_page?token=hunter2", "custom://current_page"),+ ("custom://current_page#token=hunter2", "custom://current_page"),+ ("custom://current_page/reset/hunter2", "custom://current_page"),+ ("custom://current_page/x%3Ftoken=hunter2", "custom://current_page"),+ ],+ )+ async def test_an_unresolvable_input_never_carries_a_secret_into_the_log(+ self, page_url: str, logged_identity: str+ ) -> None:+ with capture_logs() as logs:+ await _admit(+ RequestPolicy(),+ credential_id="cred_analytics",+ page_url=page_url,+ org_credentials=[_cred("analytics", "cred_analytics", _SAVED_LOGIN_URL)],+ )++ emitted = [entry for entry in logs if entry["event"] == "copilot credential live-page admission"]+ assert "hunter2" not in emitted[0]["page_url"]+ assert emitted[0]["page_url"] == logged_identity+async def _resolve_live_page(policy: RequestPolicy,@@ -3067,6 +3112,37 @@ class TestLivePageCredentialObservation:assert policy.resolved_credentials == []assert policy.live_page_admitted_urls == {}+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("page_url", "logged_identity"),+ [+ ("current_page", "current_page"),+ ("about:blank", "about:"),+ ("//analytics.example.com/login", "//analytics.example.com"),+ # Too malformed to parse, so there is no identity to name and the outcome carries it.+ ("http://[", ""),+ ("http://[::1", ""),+ ],+ )+ async def test_an_input_that_is_not_a_page_abstains_instead_of_claiming_no_match(+ self, page_url: str, logged_identity: str+ ) -> None:+ policy = RequestPolicy()+ with capture_logs() as logs:+ record, load_mock = await _resolve_live_page(+ policy,+ page_url=page_url,+ org_credentials=[_cred("analytics", "cred_analytics", _SAVED_LOGIN_URL)],+ )++ emitted = [entry for entry in logs if entry["event"] == "copilot credential live-page admission"]+ assert record.verdict == "abstain"+ assert [(entry["seam"], entry["outcome"]) for entry in emitted] == [("page_observation", "abstain")]+ assert emitted[0]["page_url"] == logged_identity+ assert policy.resolved_credentials == []+ assert policy.live_page_resolution is None+ load_mock.assert_not_awaited()+@pytest.mark.asyncioasync def test_a_card_credential_never_binds_as_a_login(self) -> None:policy = RequestPolicy()