Skip to content

Automate browser based workflows with AI

Task V3: hide signed URLs rendered into the goal, system guidance or starting URL behind opaque tokens (SKY-16412) (#8581)

pedrohsdb955d8b972d91
diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.py
index ab101cdec..3f90d2059 100644
--- a/skyvern/forge/taskv3/engine.py
+++ b/skyvern/forge/taskv3/engine.py
@@ -51,7 +51,7 @@ from skyvern.forge.taskv3.loop import (
make_finish_tool,
run_agent_tool_loop,
)
-from skyvern.forge.taskv3.opaque_refs import OpaqueUrlRefs, mask_opaque_urls
+from skyvern.forge.taskv3.opaque_refs import OpaqueUrlRefs, is_signed_url, mask_opaque_urls
from skyvern.forge.taskv3.tools import (
BlankWorkingPageGuard,
PageProvider,
@@ -116,7 +116,7 @@ Rules:
OPAQUE_URL_GUIDANCE = """
-Some values in the data provided are shown as `opaque_url_xxxxxxxx` instead of a real URL: these are references to URLs from the task data, resolved to their real value backend-side. Pass one verbatim - unchanged, unshortened, never invented - as the `file` argument of `file_upload`, the `url` argument of `navigate`, the `value` argument of `select_combobox`, or as text to `type`."""
+Some URLs in your instructions or the data provided are shown as `opaque_url_xxxxxxxx` instead of the real URL: these are references to URLs from the task, resolved to their real value backend-side. Pass one verbatim - unchanged, unshortened, never invented - as the `file` argument of `file_upload`, the `url` argument of `navigate`, the `value` argument of `select_combobox`, or as text to `type`."""
DOWNLOAD_COMPLETION_GUIDANCE = """
This task completes automatically once a file download finishes -- trigger the download and let it land; do not call finish(status=completed) yourself. If the download cannot be triggered, call finish with status=failed or status=terminated and say why."""
@@ -229,7 +229,19 @@ async def run_task_v3_agent_loop(
# retype verbatim into a tool call; masking them here and resolving inside the tool handlers
# (the same boundary credential placeholders already use) avoids that. Page-free runs have no
# tools to resolve a token with, so the payload stays verbatim for the model to judge directly.
- refs = mask_opaque_urls(parameters) if not page_free else OpaqueUrlRefs(masked=parameters, refs={})
+ # Workflow templates render a file parameter straight into the goal, the system guidance and the
+ # block URL, so every model-facing text is minted into the same refs as the payload.
+ model_starting_url = starting_url
+ if page_free:
+ refs = OpaqueUrlRefs(masked=parameters, refs={})
+ model_goal = goal
+ else:
+ refs = mask_opaque_urls(parameters)
+ model_goal = refs.mint_in_text(goal)
+ extra_system_guidance = refs.mint_in_text(extra_system_guidance)
+ # One whole URL, not prose: the text scan would stop at a legal path character such as "'".
+ if starting_url and is_signed_url(starting_url):
+ model_starting_url = refs.derive(starting_url)
# The single model-facing masking boundary reads these off the task context (the chokepoint
# hide_from_model already runs on every tool result), so a resolved ref echoed by any tool —
# success or error — is rewritten to its token by membership, without each tool opting in. Set
@@ -378,7 +390,7 @@ async def run_task_v3_agent_loop(
outcome = await run_agent_tool_loop(
llm_caller=llm_caller,
system_prompt=system_prompt,
- user_prompt=build_user_prompt(goal, refs.masked, starting_url),
+ user_prompt=build_user_prompt(model_goal, refs.masked, model_starting_url),
tools=tools,
max_turns=max_turns,
max_tool_calls=max_tool_calls,
diff --git a/skyvern/forge/taskv3/opaque_refs.py b/skyvern/forge/taskv3/opaque_refs.py
index 7426bb8c9..16a41be90 100644
--- a/skyvern/forge/taskv3/opaque_refs.py
+++ b/skyvern/forge/taskv3/opaque_refs.py
@@ -212,6 +212,18 @@ class OpaqueUrlRefs:
self.refs[token] = url
return token
+ def mint_in_text(self, text: str) -> str:
+ """Mint a ref for every signed URL inside free ``text`` and return the text with each replaced by
+ its token. Unlike mask(), this is by shape: it is how a URL first gains payload provenance."""
+
+ def _mint(match: re.Match[str]) -> str:
+ # Sentence punctuation after a URL is not part of it and would fail the signature charset.
+ url = match.group(0).rstrip(_TRAILING_PUNCTUATION)
+ trailing = match.group(0)[len(url) :]
+ return (self.derive(url) if is_signed_url(url) else url) + trailing
+
+ return _URL_IN_TEXT_RE.sub(_mint, text)
+
def mask(self, text: str) -> str:
"""Replace every occurrence of a known payload signed-URL in ``text`` with its opaque token —
the inverse of resolve(). Masking is by PROVENANCE, not URL shape: only a URL we minted from
@@ -256,33 +268,21 @@ def mask_opaque_urls(parameters: dict[str, Any] | None) -> OpaqueUrlRefs:
"""Replace every signed-URL string value in ``parameters`` with a deterministic opaque token.
Never mutates ``parameters``; other values are copied unchanged."""
+ result = OpaqueUrlRefs(masked=None, refs={})
if parameters is None:
- return OpaqueUrlRefs(masked=None, refs={})
-
- refs: dict[str, str] = {}
-
- def _mask_url(url: str) -> str:
- token = _token_for(url)
- refs[token] = url
- return token
-
- def _mask_in_text(match: re.Match[str]) -> str:
- # Sentence punctuation after a URL is not part of it and would fail the signature charset.
- url = match.group(0).rstrip(_TRAILING_PUNCTUATION)
- trailing = match.group(0)[len(url) :]
- return (_mask_url(url) if is_signed_url(url) else url) + trailing
+ return result
def _mask(value: Any) -> Any:
if isinstance(value, str):
if is_signed_url(value):
- return _mask_url(value)
+ return result.derive(value)
# A free-form payload string (e.g. task_data prose) can carry the URL inline.
- return _URL_IN_TEXT_RE.sub(_mask_in_text, value)
+ return result.mint_in_text(value)
if isinstance(value, dict):
return {key: _mask(val) for key, val in value.items()}
if isinstance(value, (list, tuple)):
return type(value)(_mask(val) for val in value)
return value
- masked = _mask(parameters)
- return OpaqueUrlRefs(masked=masked, refs=refs)
+ result.masked = _mask(parameters)
+ return result
diff --git a/tests/unit/test_taskv3_engine.py b/tests/unit/test_taskv3_engine.py
index 5555230aa..4171ac6b9 100644
--- a/tests/unit/test_taskv3_engine.py
+++ b/tests/unit/test_taskv3_engine.py
@@ -28,6 +28,7 @@ from skyvern.forge.taskv3.engine import (
DEFAULT_MAX_TURNS,
MAX_TOOL_CALLS_PER_ACTION_STEP,
MAX_TURNS_PER_ACTION_STEP,
+ OPAQUE_URL_GUIDANCE,
SYSTEM_PROMPT,
coerce_v3_parameters,
run_task_v3_agent_loop,
@@ -42,7 +43,7 @@ from skyvern.forge.taskv3.loop import (
ToolSpec,
_ProgressEvidence,
)
-from skyvern.forge.taskv3.opaque_refs import mask_opaque_urls
+from skyvern.forge.taskv3.opaque_refs import OpaqueUrlRefs, mask_opaque_urls
from skyvern.forge.taskv3.tools import PAGE_UNAVAILABLE_ERROR
from tests.unit.test_taskv3_loop import _ScriptedCaller
from tests.unit.test_taskv3_tools import (
@@ -870,6 +871,79 @@ async def test_signed_payload_url_reaches_model_only_as_a_token(monkeypatch: pyt
assert outcome.extracted_output == {"uploaded": [signed_url], "note": f"used {signed_url}"}
+async def test_signed_url_rendered_into_model_facing_text_reaches_model_only_as_a_resolvable_token(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # A workflow template renders a file parameter into the goal, the system guidance and the block URL,
+ # with no payload carrying it. Each must get the same treatment as the payload: token in, real URL out.
+ signature = "f1e2d3c4b5a697887766554433221100aabbccddeeff00112233445566778899"
+ cover_signature = "99887766554433221100ffeeddccbbaa00112233445566778899aabbccddeeff"
+ query = "?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20260824T000000Z&X-Amz-Expires=2700&X-Amz-SignedHeaders=host"
+ signed_url = f"https://files.example.test/uploads/0123456789abcdef/resume.pdf{query}&X-Amz-Signature={signature}"
+ cover_url = (
+ f"https://files.example.test/uploads/0123456789abcdef/cover.pdf{query}&X-Amz-Signature={cover_signature}"
+ )
+ start_signature = "00112233445566778899aabbccddeeff99887766554433221100ffeeddccbbaa"
+ start_url = f"https://files.example.test/uploads/O'Brien/posting.pdf{query}&X-Amz-Signature={start_signature}"
+ plain_url = "https://portfolio.example.test/jo"
+ goal = f"Fill out the application.\n\nresume: {signed_url}\nportfolio: {plain_url}.\n"
+ # Distinct URLs, so each token can only resolve through the refs minted from its own text.
+ token = OpaqueUrlRefs(masked=None, refs={}).mint_in_text(signed_url)
+ cover_token = OpaqueUrlRefs(masked=None, refs={}).mint_in_text(cover_url)
+ # The apostrophe is a legal path character that ends a prose URL match.
+ start_token = OpaqueUrlRefs(masked=None, refs={}).derive(start_url)
+ assert len({token, cover_token, start_token}) == 3 and cover_token.startswith("opaque_url_")
+
+ import skyvern.utils.url_validators as urlv
+
+ monkeypatch.setattr(urlv, "validate_fetch_url", lambda url: url)
+ captured_sources: list[str] = []
+
+ async def fake_download_file(source: str, output_dir: str | None = None, organization_id: str | None = None) -> str:
+ captured_sources.append(source)
+ request_info = aiohttp.RequestInfo(url=yarl.URL(source), method="GET", headers={}, real_url=yarl.URL(source))
+ raise aiohttp.ClientResponseError(request_info=request_info, history=(), status=400, message="Bad Request")
+
+ import skyvern.forge.sdk.api.files as files_module
+
+ monkeypatch.setattr(files_module, "download_file", fake_download_file)
+
+ caller = _ScriptedCaller(
+ [
+ [("file_upload", {"selector": "#cv", "file": token})],
+ [("file_upload", {"selector": "#cover", "file": cover_token})],
+ [("navigate", {"url": start_token})],
+ [("finish", {"status": "failed", "reason": "upload rejected"})],
+ ]
+ )
+ page = _FakePage()
+ skyvern_context.set(SkyvernContext(task_id="tsk_goal"))
+ try:
+ outcome = await run_task_v3_agent_loop(
+ page_provider=_fixed_page_provider(page),
+ llm_caller=caller,
+ goal=goal,
+ parameters=None,
+ starting_url=start_url,
+ extra_system_guidance=f"Always attach the cover letter at {cover_url}",
+ )
+ finally:
+ skyvern_context.reset()
+
+ user_prompt = next(m["content"] for m in outcome.messages if m.get("role") == "user")
+ assert f"resume: {token}\n" in user_prompt
+ assert f"You start on: {start_token}" in user_prompt
+ assert f"portfolio: {plain_url}." in user_prompt # nosemgrep: incomplete-url-substring-sanitization
+ system_prompt = next(m["content"] for m in outcome.messages if m.get("role") == "system")
+ assert f"Always attach the cover letter at {cover_token}" in system_prompt
+ assert OPAQUE_URL_GUIDANCE in system_prompt
+ transcript = json.dumps(outcome.messages)
+ assert all(sig not in transcript for sig in (signature, cover_signature, start_signature))
+ assert captured_sources == [signed_url, cover_url]
+ assert page.url == start_url
+
+
@pytest.mark.asyncio
async def test_business_identifier_value_under_a_non_signing_key_stays_readable() -> None:
# A token-shaped VALUE under an ordinary business KEY (order id, not a signing param) must never be
@@ -927,21 +1001,21 @@ async def test_hash_route_job_url_is_not_masked() -> None:
@pytest.mark.asyncio
async def test_page_free_mode_does_not_mask_signed_urls() -> None:
- # Page-free mode has no tools to resolve an opaque_url_ token, so the payload stays verbatim.
+ # Page-free mode has no tools to resolve an opaque_url_ token, so every model-facing URL stays verbatim.
signed_url = "https://files.example.test/uploads/x?token=eyJhbGciOiJIUzI1NiJ9c2lnbmVkQ29ycmVjdEhvcnNl"
caller = _ScriptedCaller([[("finish", {"status": "completed", "reason": "criteria hold"})]])
outcome = await run_task_v3_agent_loop(
page_provider=_fixed_page_provider(_FakePage()), # never consulted: page_free has no tools
llm_caller=caller,
- goal="assess",
+ goal=f"assess {signed_url}",
+ starting_url=signed_url,
page_free=True,
parameters={"u": signed_url},
max_turns=4,
)
user_message = next(m for m in outcome.messages if m.get("role") == "user")["content"]
- assert (
- signed_url in user_message and "opaque_url_" not in user_message
- ) # nosemgrep: incomplete-url-substring-sanitization
+ assert f"assess {signed_url}" in user_message # nosemgrep: incomplete-url-substring-sanitization
+ assert "opaque_url_" not in user_message
@pytest.mark.asyncio