Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Bind credential fill to the live page origin (#7967)
Aaron Perezfdb42f3804b0
diff --git a/skyvern/core/script_generations/skyvern_page.py b/skyvern/core/script_generations/skyvern_page.pyindex 2e3bfb23e..7da2efe3b 100644--- a/skyvern/core/script_generations/skyvern_page.py+++ b/skyvern/core/script_generations/skyvern_page.py@@ -546,6 +546,7 @@ class SkyvernPage(Page):totp_identifier: str | None = None,totp_url: str | None = None,_skip_element_prep: bool = False,+ _direct_fill_release_guard: Callable[[str | None], None] | None = None,**kwargs: Any,) -> str: ...@@ -561,6 +562,7 @@ class SkyvernPage(Page):totp_identifier: str | None = None,totp_url: str | None = None,_skip_element_prep: bool = False,+ _direct_fill_release_guard: Callable[[str | None], None] | None = None,**kwargs: Any,) -> str: ...@@ -577,6 +579,7 @@ class SkyvernPage(Page):totp_url: str | None = None,recoverable_marker_id: int | None = None,_skip_element_prep: bool = False,+ _direct_fill_release_guard: Callable[[str | None], None] | None = None,**kwargs: Any,) -> str:"""Fill an input field using a CSS selector, AI-powered prompt matching, or both.@@ -594,6 +597,8 @@ class SkyvernPage(Page):mode: When ``"direct"``, perform a raw Playwright fill with no AIfallback or element preparation. The action is still recordedin the DB so it appears in the timeline.+ _direct_fill_release_guard: Internal synchronous guard invoked with the+ resolved element frame URL immediately before a direct fill.totp_identifier: TOTP identifier for time-based one-time password fields.totp_url: URL to fetch TOTP codes from for authentication.@@ -633,11 +638,25 @@ class SkyvernPage(Page):)timeout = kwargs.pop("timeout", settings.BROWSER_ACTION_TIMEOUT_MS)locator = self._locator_scope.locator(selector).first- await locator.fill(value, timeout=timeout, **kwargs)- # locator.fill already emits `input`; only the change/blur a JS gate may also need are missing.+ element = None+ if _direct_fill_release_guard is not None:+ element = await locator.element_handle(timeout=timeout)+ if element is None:+ raise RuntimeError("Direct fill could not resolve an element before the release check.")+ owner_frame = await element.owner_frame()+ _direct_fill_release_guard(owner_frame.url if owner_frame is not None else None)+ # A document-bound handle cannot re-resolve onto a page/frame that navigates after+ # the guard. It detaches and fails instead of releasing the value on the new origin.+ await element.fill(value, timeout=timeout, **kwargs)+ else:+ await locator.fill(value, timeout=timeout, **kwargs)+ # Direct fill already emits `input`; only the change/blur a JS gate may also need are missing.for event_name in ("change", "blur"):try:- await locator.dispatch_event(event_name, timeout=timeout)+ if element is not None:+ await element.dispatch_event(event_name)+ else:+ await locator.dispatch_event(event_name, timeout=timeout)except Exception:LOG.debug("direct fill: dispatch_event failed", dispatched_event=event_name, exc_info=True)return valuediff --git a/skyvern/forge/sdk/copilot/tools/credential_fill.py b/skyvern/forge/sdk/copilot/tools/credential_fill.pyindex 16e52b251..d9099c46d 100644--- a/skyvern/forge/sdk/copilot/tools/credential_fill.py+++ b/skyvern/forge/sdk/copilot/tools/credential_fill.py@@ -1,11 +1,13 @@from __future__ import annotations-from typing import Any+from dataclasses import dataclass+from typing import Any, Callableimport structlogfrom skyvern.cli.core.session_manager import get_pagefrom skyvern.forge import app+from skyvern.forge.sdk.browser_action_policy import canonicalize_originfrom skyvern.forge.sdk.copilot.config import BlockAuthoringPolicyfrom skyvern.forge.sdk.copilot.credential_resolution import load_credentials, url_partsfrom skyvern.forge.sdk.copilot.loop_detection import record_tool_step_result_for_ctx@@ -44,6 +46,11 @@ _CREDENTIAL_FILL_FIELDS = frozenset({"username", "password", "totp"})_CREDENTIAL_FILL_TIMEOUT_MS = 15000+@dataclass(frozen=True)+class _CredentialFillOriginGrant:+ intended_url: str++async def _normalize_totp_config_for_organization(totp_secret: str, organization_id: str) -> str:enterprise_totp_secret = await app.AGENT_FUNCTION.parse_enterprise_totp_secret(totp_secret,@@ -93,7 +100,30 @@ def _still_on_admitted_site(current_url: str | None, admitted_url: str) -> bool:"""admitted_parts = url_parts(admitted_url)current_parts = url_parts(current_url or "")- return bool(current_parts and admitted_parts and current_parts[2] == admitted_parts[2])+ admitted_origin = canonicalize_origin(admitted_parts[2]) if admitted_parts else None+ current_origin = canonicalize_origin(current_parts[2]) if current_parts else None+ return bool(current_origin and admitted_origin and current_origin == admitted_origin)+++class _CredentialFillOriginMismatchError(Exception):+ pass+++def _credential_fill_origin_mismatch_error() -> str:+ return (+ "The browser left this credential's intended login origin before it could be filled. "+ "Re-inspect the current page and fill again if the sign-in is still in progress there."+ )+++def _credential_fill_release_guard(intended_url: str) -> Callable[[str | None], None]:+ """Bind the fill grant to the resolved element's document at the release seam."""++ def guard(target_url: str | None) -> None:+ if not _still_on_admitted_site(target_url, intended_url):+ raise _CredentialFillOriginMismatchError++ return guarddef _credential_fill_authority_error(copilot_ctx: AgentContext, credential_id: str) -> str | None:@@ -112,25 +142,51 @@ def _credential_fill_authority_error(copilot_ctx: AgentContext, credential_id: sreturn None-async def _credential_fill_gate_error(copilot_ctx: AgentContext, credential_id: str) -> tuple[str | None, str | None]:- """Refuse only after asking the live page whether it vouches for this credential.+def _resolved_credential_intended_url(policy: RequestPolicy, credential_id: str) -> str | None:+ admitted_url = policy.live_page_admitted_urls.get(credential_id)+ if admitted_url:+ return admitted_url+ return next(+ (+ credential.tested_url+ for credential in policy.resolved_credentials+ if credential.credential_id == credential_id and credential.tested_url+ ),+ None,+ )+++def _missing_credential_origin_error(credential_id: str) -> str:+ return (+ f"Credential `{credential_id}` has no intended login origin, so it cannot be filled into the live browser. "+ "Test the saved credential against its login page to bind it to that site, then inspect the page and retry."+ )+- Returns the refusal (if any) and the page URL that justified an admission, so the caller can- confirm the browser is still on that page before the secret is typed.+async def _credential_fill_origin_grant(+ copilot_ctx: AgentContext, credential_id: str+) -> tuple[_CredentialFillOriginGrant | None, str | None]:+ """Authorize a fill only when it has a concrete intended origin.++ The returned grant is the capability consumed at the release seam. A credential that reached+ ``resolved_credentials`` through a path without either a tested URL or a live-page admission+ receives no grant, so a missing origin cannot silently disable the final comparison."""prerequisite_error = _credential_fill_prerequisite_error(copilot_ctx, credential_id)if prerequisite_error:- return prerequisite_error, None+ return None, prerequisite_errorpolicy = copilot_ctx.request_policyauthority_error = _credential_fill_authority_error(copilot_ctx, credential_id)if not authority_error:- # A grant the live page made stays bound to that page: re-checking only the call that- # made it would let the retry after a redirect inherit authority it never earned.- admitted = policy.live_page_admitted_urls.get(credential_id) if isinstance(policy, RequestPolicy) else None- return None, admitted+ if not isinstance(policy, RequestPolicy):+ return None, _missing_credential_origin_error(credential_id)+ intended_url = _resolved_credential_intended_url(policy, credential_id)+ if not intended_url:+ return None, _missing_credential_origin_error(credential_id)+ return _CredentialFillOriginGrant(intended_url), Noneif not isinstance(policy, RequestPolicy):- return authority_error, None+ return None, authority_errorasync def load_once() -> list[Credential]:if copilot_ctx.org_credentials_for_turn is None:@@ -144,9 +200,17 @@ async def _credential_fill_gate_error(copilot_ctx: AgentContext, credential_id:page_url=await _live_working_page_url(copilot_ctx) or "",load_org_credentials=load_once,)+ if admission.admitted and admission.page_url:+ return _CredentialFillOriginGrant(admission.page_url), Noneif admission.admitted:- return None, admission.page_url- return admission.steer or authority_error, None+ return None, _missing_credential_origin_error(credential_id)+ return None, admission.steer or authority_error+++async def _credential_fill_gate_error(copilot_ctx: AgentContext, credential_id: str) -> tuple[str | None, str | None]:+ """Compatibility view of the origin-grant gate for tests and policy callers."""+ grant, error = await _credential_fill_origin_grant(copilot_ctx, credential_id)+ return error, grant.intended_url if grant else Noneasync def _resolve_credential_fill_value(@@ -255,15 +319,15 @@ async def _fill_credential_field_impl(return finish({"ok": False, "error": "fill_credential_field requires a CSS selector for the input field."})if field not in _CREDENTIAL_FILL_FIELDS:return finish({"ok": False, "error": "fill_credential_field `field` must be one of: username, password, totp."})- policy_error, admitted_page = await _credential_fill_gate_error(copilot_ctx, credential_id)- if policy_error:+ origin_grant, policy_error = await _credential_fill_origin_grant(copilot_ctx, credential_id)+ if policy_error or origin_grant is None:LOG.info("copilot fill_credential_field rejected tool-side",credential_id=credential_id,field=field,organization_id=copilot_ctx.organization_id,)- return finish({"ok": False, "error": policy_error})+ return finish({"ok": False, "error": policy_error or _missing_credential_origin_error(credential_id)})value, credential_name, resolve_error = await _resolve_credential_fill_value(copilot_ctx, credential_id, field)if resolve_error or value is None:@@ -276,20 +340,15 @@ async def _fill_credential_field_impl(try:async with mcp_browser_context(copilot_ctx):page, _ = await get_page(session_id=copilot_ctx.browser_session_id)- # Checked on the page about to be filled, with nothing awaited in between: the vault read- # and the evidence capture above both give a redirect room to move the browser.- if admitted_page and not _still_on_admitted_site(page.url, admitted_page):- return finish(- {- "ok": False,- "error": (- "The browser left the site whose login page authorized this credential "- "before it could be filled. Re-inspect the current page and fill again if "- "the sign-in is still in progress there."- ),- }- )- await page.fill(selector, value, mode="direct", timeout=_CREDENTIAL_FILL_TIMEOUT_MS)+ await page.fill(+ selector,+ value,+ mode="direct",+ timeout=_CREDENTIAL_FILL_TIMEOUT_MS,+ _direct_fill_release_guard=_credential_fill_release_guard(origin_grant.intended_url),+ )+ except _CredentialFillOriginMismatchError:+ return finish({"ok": False, "error": _credential_fill_origin_mismatch_error()})except Exception as exc:error_text = scrub_secrets_from_text(copilot_ctx, _scrub_secret_from_text(str(exc), value))LOG.info(diff --git a/tests/unit/test_copilot_fill_credential_field.py b/tests/unit/test_copilot_fill_credential_field.pyindex e39015bf4..6fd651798 100644--- a/tests/unit/test_copilot_fill_credential_field.py+++ b/tests/unit/test_copilot_fill_credential_field.py@@ -30,8 +30,10 @@ _FAKE_TOTP_SEED = "JBSWY3DPEHPK3PXP"_FIXTURE_LOGIN_URL = "https://authenticationtest.com/simpleFormAuth/"-def _resolved_credential(credential_id: str = "cred_123") -> SimpleNamespace:- return SimpleNamespace(credential_id=credential_id, name="authtest simple")+def _resolved_credential(+ credential_id: str = "cred_123", tested_url: str | None = _FIXTURE_LOGIN_URL+) -> SimpleNamespace:+ return SimpleNamespace(credential_id=credential_id, name="authtest simple", tested_url=tested_url)def _policy(**overrides: Any) -> RequestPolicy:@@ -66,6 +68,24 @@ def _ctx(**overrides: Any) -> SimpleNamespace:class TestCredentialFillPolicyGate:+ def test_origin_comparison_uses_browser_origin_semantics(self) -> None:+ assert credential_fill_module._still_on_admitted_site(+ "https://example.com/account",+ "https://example.com:443/login",+ )+ assert credential_fill_module._still_on_admitted_site(+ "https://example.com/account",+ "example.com/login",+ )+ assert not credential_fill_module._still_on_admitted_site(+ "http://example.com/account",+ "https://example.com/login",+ )+ assert not credential_fill_module._still_on_admitted_site(+ "https://example.com:8443/account",+ "https://example.com/login",+ )+def test_rejects_outside_code_only_mode(self) -> None:ctx = _ctx(block_authoring_policy=BlockAuthoringPolicy.STANDARD)error = tools_module._credential_fill_prerequisite_error(ctx, "cred_123")@@ -308,13 +328,22 @@ class TestResolveCredentialFillValue:class _FakePage:- def __init__(self, fill_error: Exception | None = None, url: str = _FIXTURE_LOGIN_URL) -> None:+ def __init__(+ self,+ fill_error: Exception | None = None,+ url: str = _FIXTURE_LOGIN_URL,+ release_url: str | None = None,+ ) -> None:self.url = url+ self.release_url = release_urlself.fill_calls: list[tuple[Any, ...]] = []self.fill_kwargs: list[dict[str, Any]] = []self._fill_error = fill_errorasync def fill(self, *args: Any, **kwargs: Any) -> None:+ release_guard = kwargs.get("_direct_fill_release_guard")+ if release_guard is not None:+ release_guard(self.release_url if self.release_url is not None else self.url)self.fill_calls.append(args)self.fill_kwargs.append(kwargs)if self._fill_error is not None:@@ -583,12 +612,96 @@ class TestCredentialFillLivePageAdmission:load_mock.assert_not_awaited()@pytest.mark.asyncio- async def test_already_resolved_credential_short_circuits_without_a_page_read(self) -> None:+ async def test_already_resolved_credential_uses_its_tested_url_without_a_page_read(self) -> None:+ policy = RequestPolicy(resolved_credentials=[_resolved_credential()])+ ctx = _ctx(request_policy=policy)+ load_mock = AsyncMock()+ with (+ patch("skyvern.forge.app.DATABASE.credentials.get_credentials", new=load_mock),+ patch.object(+ credential_fill_module,+ "_live_working_page_url",+ AsyncMock(return_value="https://analytics.example.com/login"),+ ),+ ):+ error, intended_url = await credential_fill_module._credential_fill_gate_error(ctx, "cred_123")++ assert error is None+ assert intended_url == _FIXTURE_LOGIN_URL+ load_mock.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_resolved_credential_is_blocked_on_a_different_live_origin(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Mutation guard: deleting the release-time origin comparison must make this fail."""+ page = _FakePage(url="https://elsewhere.example.com/collect")+ _wire_impl(monkeypatch, page)++ result = await tools_module._fill_credential_field_impl(_ctx(), "#passwordInput", "cred_123", "password")++ assert result["ok"] is False+ assert page.fill_calls == []++ @pytest.mark.asyncio+ async def test_resolved_credential_redirect_immediately_before_fill_is_blocked(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Mutation guard: moving the comparison before the final awaited work must make this fail."""+ page = _FakePage()+ _wire_impl(monkeypatch, page)++ async def redirect_after_approval(_ctx: Any) -> None:+ page.url = "https://elsewhere.example.com/collect"++ monkeypatch.setattr(credential_fill_module, "_capture_scout_source_url", redirect_after_approval)++ result = await tools_module._fill_credential_field_impl(_ctx(), "#passwordInput", "cred_123", "password")++ assert result["ok"] is False+ assert page.fill_calls == []++ @pytest.mark.asyncio+ async def test_resolved_credential_navigation_during_target_resolution_is_blocked(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Mutation guard: a caller-side check before locator auto-wait must make this fail."""+ page = _FakePage(+ url=_FIXTURE_LOGIN_URL,+ release_url="https://elsewhere.example.com/collect",+ )+ _wire_impl(monkeypatch, page)++ result = await tools_module._fill_credential_field_impl(_ctx(), "#passwordInput", "cred_123", "password")++ assert result["ok"] is False+ assert page.fill_calls == []++ @pytest.mark.asyncio+ async def test_resolved_credential_without_an_intended_origin_fails_closed(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Mutation guard: changing missing-origin denial back to a skip must make this fail."""+ page = _FakePage()+ _wire_impl(monkeypatch, page)+ ctx = _ctx(request_policy=RequestPolicy(resolved_credentials=[_resolved_credential(tested_url=None)]))++ result = await tools_module._fill_credential_field_impl(ctx, "#passwordInput", "cred_123", "password")++ assert result["ok"] is False+ assert "intended login origin" in result["error"]+ assert page.fill_calls == []++ @pytest.mark.asyncio+ async def test_live_page_admitted_credential_short_circuits_without_an_org_lookup(self) -> None:error, _, load_mock = await self._gate(credential_id="cred_123",page_url="https://analytics.example.com/login",org_credentials=[],- policy=RequestPolicy(resolved_credentials=[_resolved_credential()]),+ policy=RequestPolicy(+ resolved_credentials=[_resolved_credential(tested_url=None)],+ live_page_admitted_urls={"cred_123": _FIXTURE_LOGIN_URL},+ ),)assert error is Nonediff --git a/tests/unit/test_script_skyvern_page.py b/tests/unit/test_script_skyvern_page.pyindex 8577f72fc..96de26853 100644--- a/tests/unit/test_script_skyvern_page.py+++ b/tests/unit/test_script_skyvern_page.py@@ -2206,6 +2206,23 @@ async def test_fill_multipage_form_allows_unmapped_optional_file_page_to_stop(mo# =============================================================================+class _RecordingElementHandle:+ def __init__(self, frame_url: str) -> None:+ self.calls: list[tuple[str, str | None]] = []+ self._frame = SimpleNamespace(url=frame_url)++ async def owner_frame(self) -> SimpleNamespace:+ self.calls.append(("owner_frame", None))+ return self._frame++ async def fill(self, value: str, **kwargs: object) -> None:+ self.calls.append(("fill", value))++ async def dispatch_event(self, event_name: str, **kwargs: object) -> None:+ assert kwargs == {}+ self.calls.append(("dispatch_event", event_name))++class _RecordingLocator:"""A fake Playwright locator that records fill/dispatch_event calls in order.@@ -2220,14 +2237,20 @@ class _RecordingLocator:click_error: Exception | None = None,dispatch_error: Exception | None = None,gate_on_change: bool = False,+ element_handle: _RecordingElementHandle | None = None,) -> None:self.calls: list[tuple[str, str | None]] = []self.first = selfself._click_error = click_errorself._dispatch_error = dispatch_errorself._gate_on_change = gate_on_change+ self._element_handle = element_handleself.enabled = False+ async def element_handle(self, **kwargs: object) -> _RecordingElementHandle | None:+ self.calls.append(("element_handle", None))+ return self._element_handle+async def wait_for(self, *, state: str, **kwargs: object) -> None:self.calls.append(("wait_for", state))@@ -2410,6 +2433,55 @@ async def test_direct_fill_dispatch_failure_does_not_regress_fill(mock_scraped_passert result == "hunter2"+async def test_guarded_direct_fill_checks_the_resolved_element_frame_before_release(mock_ai):+ """A credential guard sees the actual recipient frame and the locator cannot retarget."""+ element_handle = _RecordingElementHandle("https://login.example.com/embedded")+ locator = _RecordingLocator(element_handle=element_handle)+ skyvern_page = _skyvern_page_with_locator(mock_ai, locator)+ guarded_urls: list[str | None] = []++ result = await skyvern_page.fill(+ "#password",+ "hunter2",+ mode="direct",+ _direct_fill_release_guard=guarded_urls.append,+ )++ assert result == "hunter2"+ assert guarded_urls == ["https://login.example.com/embedded"]+ assert locator.calls == [("element_handle", None)]+ assert element_handle.calls == [+ ("owner_frame", None),+ ("fill", "hunter2"),+ ("dispatch_event", "change"),+ ("dispatch_event", "blur"),+ ]+++async def test_guarded_direct_fill_never_releases_to_a_cross_origin_element_frame(mock_ai):+ """Mutation guard: removing/moving the element-frame guard must make this fail."""+ element_handle = _RecordingElementHandle("https://attacker.example/collect")+ locator = _RecordingLocator(element_handle=element_handle)+ skyvern_page = _skyvern_page_with_locator(mock_ai, locator)++ def reject_cross_origin(frame_url: str | None) -> None:+ if frame_url != "https://login.example.com/embedded":+ raise RuntimeError("cross-origin release blocked")++ with pytest.raises(RuntimeError, match="cross-origin release blocked"):+ await skyvern_page.fill(+ "#password",+ "hunter2",+ mode="direct",+ _direct_fill_release_guard=reject_cross_origin,+ )++ assert locator.calls == [("element_handle", None)]+ assert element_handle.calls == [("owner_frame", None)]++# =============================================================================# Tests for selector fallback prep opt-out — SKY-12096#