Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Strip metadata from signed artifact URLs and redact signature params from logs and traces (#7504)
Aaron Perez66c964b2f396
diff --git a/skyvern/forge/request_logging.py b/skyvern/forge/request_logging.pyindex f9ee1ee65..49ecc0dae 100644--- a/skyvern/forge/request_logging.py+++ b/skyvern/forge/request_logging.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+import reimport timeimport typing@@ -39,6 +40,13 @@ _BINARY_PLACEHOLDER = "<binary>"_REDACTED = "****"_LOGGABLE_CONTENT_TYPES = {"text/", "application/json"}_STREAMING_CONTENT_TYPE = "text/event-stream"+# Matches a signed artifact-content URL (absolute or path-relative) anywhere in a+# string and captures everything up to — but excluding — its query, so re.sub can+# drop the capability params (expiry/kid/sig) while leaving surrounding text and+# non-artifact URLs untouched. Query runs to the next whitespace/quote/angle bracket.+_ARTIFACT_CONTENT_URL_QUERY_RE = re.compile(+ r"((?:[a-zA-Z][a-zA-Z0-9+.\-]*://[^/\s\"'<>]+)?/v1/artifacts/[^/\s\"'<>]+/content/?)\?[^\s\"'<>]*"+)# Exact field names that are always redacted. Use a set for O(1) lookup# instead of regex substring matching to avoid false positives like@@ -97,6 +105,7 @@ def _sanitize_body(request: Request, body: bytes, content_type: str | None) -> stext = body.decode("utf-8", errors="replace")except Exception:return _BINARY_PLACEHOLDER+ text = _redact_loggable_body(text)if len(text) > _MAX_BODY_LENGTH:return text[:_MAX_BODY_LENGTH] + "...[truncated]"return text@@ -106,13 +115,19 @@ def _is_sensitive_key(key: str) -> bool:return key.lower() in _SENSITIVE_FIELDS+def _strip_artifact_url_query(value: str) -> str:+ return _ARTIFACT_CONTENT_URL_QUERY_RE.sub(r"\1", value)++def redact_sensitive_fields(obj: typing.Any, _depth: int = 0) -> typing.Any:- """Redact dict values whose *key name* exactly matches a known sensitive field.+ """Redact sensitive fields and strip capability queries from artifact URLs.- Uses exact-match (case-insensitive) rather than substring/regex to avoid- false positives on fields like ``credential_id``, ``author``, or+ Field names use exact-match (case-insensitive) rather than substring/regex+ to avoid false positives on fields like ``credential_id``, ``author``, or``page_token`` which contain sensitive substrings but are not secrets."""+ if isinstance(obj, str):+ return _strip_artifact_url_query(obj)if _depth > 20:# Stop recursing but still redact sensitive keys at this levelif isinstance(obj, dict):@@ -127,6 +142,15 @@ def redact_sensitive_fields(obj: typing.Any, _depth: int = 0) -> typing.Any:return obj+def _redact_loggable_body(text: str) -> str:+ try:+ parsed = json.loads(text)+ except (json.JSONDecodeError, TypeError):+ return _strip_artifact_url_query(text)+ redacted = redact_sensitive_fields(parsed)+ return json.dumps(redacted) if redacted != parsed else text++def _is_loggable_content_type(content_type: str | None) -> bool:if not content_type:return True # assume text when header is missing@@ -142,12 +166,7 @@ def _sanitize_response_body(request: Request, body_str: str | None, content_typereturn ""if not _is_loggable_content_type(content_type):return _BINARY_PLACEHOLDER- try:- parsed = json.loads(body_str)- redacted = redact_sensitive_fields(parsed)- text = json.dumps(redacted)- except (json.JSONDecodeError, TypeError):- text = body_str+ text = _redact_loggable_body(body_str)if len(text) > _MAX_BODY_LENGTH:return text[:_MAX_BODY_LENGTH] + "...[truncated]"return textdiff --git a/skyvern/forge/sdk/artifact/manager.py b/skyvern/forge/sdk/artifact/manager.pyindex 2608b3480..a4536e917 100644--- a/skyvern/forge/sdk/artifact/manager.py+++ b/skyvern/forge/sdk/artifact/manager.py@@ -1212,8 +1212,8 @@ class ArtifactManager:and carries expiry/kid/sig query parameters so the endpoint can authenticaterequests without an org-level API key.- artifact_name and artifact_type are appended as informational query params- for client use only — they are not part of the signature.+ Metadata query parameters are retained only on the API-authenticated unsigned+ fallback. Signed URLs carry authorization fields only."""base = settings.SKYVERN_BASE_URL.rstrip("/")if settings.ARTIFACT_CONTENT_HMAC_KEYRING:@@ -1222,8 +1222,6 @@ class ArtifactManager:base_url=base,artifact_id=artifact_id,keyring=keyring,- artifact_name=artifact_name,- artifact_type=artifact_type,expiry_seconds=expiry_seconds,)path = f"{base}/v1/artifacts/{artifact_id}/content"@@ -1248,8 +1246,8 @@ class ArtifactManager:storage backend's presigned URL (S3 / Azure SAS / local URI)."""if _bundling_enabled() or artifact.bundle_key:- # Frontend parses ``artifact_name`` out of the URL query for the- # download-files display. Bundled members carry the in-ZIP filename+ # Legacy unsigned URLs expose ``artifact_name`` for download display.+ # Bundled members carry the in-ZIP filename# in ``bundle_key``; non-bundled artifacts have it as the URI# basename. Without this fallback the path basename is just# "content" and the UI falls back to a literal "download" label.diff --git a/skyvern/forge/sdk/artifact/signing.py b/skyvern/forge/sdk/artifact/signing.pyindex f9d7ea216..cf0fe11e4 100644--- a/skyvern/forge/sdk/artifact/signing.py+++ b/skyvern/forge/sdk/artifact/signing.py@@ -132,9 +132,8 @@ def sign_artifact_url(The signature is URL-safe base64 (no padding), 43 characters for SHA-256.- ``artifact_name`` and ``artifact_type`` are appended as informational query- params for client use only — they are not part of the canonical string or- signature.+ ``artifact_name`` and ``artifact_type`` are accepted for call-site+ compatibility but intentionally omitted from the capability URL."""kid = keyring.current_kidsecret_bytes = keyring.get_secret_bytes(kid)@@ -146,12 +145,7 @@ def sign_artifact_url(path = _ARTIFACT_CONTENT_PATH_TEMPLATE.format(artifact_id=artifact_id)canonical = _canonical_string("GET", path, expiry, kid)sig = _hmac_b64(secret_bytes, canonical)- sig_params: dict[str, str | int] = {"expiry": expiry, "kid": kid, "sig": sig}- if artifact_name is not None:- sig_params["artifact_name"] = artifact_name- if artifact_type is not None:- sig_params["artifact_type"] = artifact_type- params = urlencode(sig_params)+ params = urlencode({"expiry": expiry, "kid": kid, "sig": sig})return f"{base_url.rstrip('/')}{path}?{params}"diff --git a/tests/unit/test_artifact_signing.py b/tests/unit/test_artifact_signing.pyindex c4ba0a319..eadc7b049 100644--- a/tests/unit/test_artifact_signing.py+++ b/tests/unit/test_artifact_signing.py@@ -158,6 +158,19 @@ class TestSignArtifactUrl:expiry = int(qs["expiry"][0])assert before + ARTIFACT_URL_EXPIRY_SECONDS <= expiry <= after + ARTIFACT_URL_EXPIRY_SECONDS+ def test_url_omits_artifact_metadata(self) -> None:+ from urllib.parse import parse_qs, urlparse++ url = sign_artifact_url(+ _BASE_URL,+ _ARTIFACT_ID,+ _make_keyring(),+ artifact_name="sensitive-screenshot.png",+ artifact_type="screenshot_action",+ )++ assert set(parse_qs(urlparse(url).query)) == {"expiry", "kid", "sig"}+def test_sig_is_url_safe_base64_no_padding(self) -> None:kr = _make_keyring()url = sign_artifact_url(_BASE_URL, _ARTIFACT_ID, kr)diff --git a/tests/unit/test_request_logging.py b/tests/unit/test_request_logging.pyindex 096c23083..0de57e3d2 100644--- a/tests/unit/test_request_logging.py+++ b/tests/unit/test_request_logging.py@@ -214,6 +214,49 @@ class TestRedactSensitiveFields:assert redact_sensitive_fields(42) == 42assert redact_sensitive_fields(None) is None+ def test_strips_signed_artifact_url_queries_only(self) -> None:+ data = {+ "artifact_url": (+ "https://api.skyvern.com/v1/artifacts/art_synthetic/content/?expiry=1800000600&kid=k1&sig=signed-secret"+ ),+ "other_url": "https://example.com/report?view=full",+ }++ assert redact_sensitive_fields(data) == {+ "artifact_url": "https://api.skyvern.com/v1/artifacts/art_synthetic/content/",+ "other_url": "https://example.com/report?view=full",+ }++ def test_strips_signed_artifact_url_embedded_mid_string(self) -> None:+ data = {+ "input": (+ "fetched https://api.skyvern.com/v1/artifacts/art_embed/content"+ "?expiry=1800000600&kid=k1&sig=embedded-secret then parsed it"+ ),+ }++ assert redact_sensitive_fields(data) == {+ "input": "fetched https://api.skyvern.com/v1/artifacts/art_embed/content then parsed it",+ }++ def test_strips_multiple_embedded_signed_urls_preserving_other_urls(self) -> None:+ data = {+ "input": (+ "a /v1/artifacts/art_a/content?sig=secret-a and "+ "https://api.skyvern.com/v1/artifacts/art_b/content?sig=secret-b but "+ "https://example.com/report?view=full stays"+ ),+ }++ result = redact_sensitive_fields(data)+ assert "secret-a" not in result["input"]+ assert "secret-b" not in result["input"]+ assert result["input"] == (+ "a /v1/artifacts/art_a/content and "+ "https://api.skyvern.com/v1/artifacts/art_b/content but "+ "https://example.com/report?view=full stays"+ )+# ---------------------------------------------------------------------------# _is_loggable_content_type@@ -292,6 +335,16 @@ class TestSanitizeResponseBody:result = _sanitize_response_body(request, "plain text response", "text/plain")assert result == "plain text response"+ def test_strips_embedded_signed_artifact_url_from_plain_text(self) -> None:+ request = _make_request()+ body = (+ "download failed for https://api.skyvern.com/v1/artifacts/art_err/content"+ "?expiry=1800000600&kid=k1&sig=plain-secret after 3 retries"+ )+ result = _sanitize_response_body(request, body, "text/plain")+ assert "plain-secret" not in result+ assert result == ("download failed for https://api.skyvern.com/v1/artifacts/art_err/content after 3 retries")+def test_truncates_long_body(self) -> None:request = _make_request()long_body = "x" * (_MAX_BODY_LENGTH + 500)@@ -390,7 +443,12 @@ def _make_app() -> FastAPI:@app.post("/tasks")async def create_task() -> dict:- return {"created": True}+ return {+ "created": True,+ "artifact_url": (+ "https://api.skyvern.com/v1/artifacts/art_response/content?expiry=1800000300&kid=k1&sig=response-secret"+ ),+ }@app.get("/missing")async def missing() -> dict:@@ -471,6 +529,27 @@ class TestMiddlewareLogVolume:assert log_mock.warning.call_args.args[0] == "api.raw_request"assert log_mock.warning.call_args.kwargs["status_code"] == 403+ def test_artifact_url_queries_are_redacted_from_logged_bodies(self, log_mock: MagicMock) -> None:+ client = TestClient(_make_app())+ response = client.post(+ "/tasks",+ json={+ "file_url": (+ "https://api.skyvern.com/v1/artifacts/art_request/content/"+ "?expiry=1800000300&kid=k1&sig=request-secret"+ )+ },+ )++ assert response.status_code == 200+ logged = log_mock.info.call_args.kwargs+ assert json.loads(logged["body"])["file_url"] == ("https://api.skyvern.com/v1/artifacts/art_request/content/")+ assert json.loads(logged["response_body"])["artifact_url"] == (+ "https://api.skyvern.com/v1/artifacts/art_response/content"+ )+ assert "request-secret" not in repr(logged)+ assert "response-secret" not in repr(logged)+def test_exception_path_is_logged_as_error(self, log_mock: MagicMock) -> None:client = TestClient(_make_app(), raise_server_exceptions=False)response = client.get("/boom")