Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(SKY-8861): per-org artifact URL expiry config (backend) (#5685)
Shuchang Zheng157521fd3cab
diff --git a/alembic/versions/2026_04_27_1542-a5fe08ea4990_add_artifact_url_expiry_seconds_to_organizations.py b/alembic/versions/2026_04_27_1542-a5fe08ea4990_add_artifact_url_expiry_seconds_to_organizations.pynew file mode 100644index 000000000..77295cce4--- /dev/null+++ b/alembic/versions/2026_04_27_1542-a5fe08ea4990_add_artifact_url_expiry_seconds_to_organizations.py@@ -0,0 +1,30 @@+"""add artifact_url_expiry_seconds to organizations++Revision ID: a5fe08ea4990+Revises: 2d0f9407ffac+Create Date: 2026-04-27T15:42:35.263273+00:00++"""++from typing import Sequence, Union++import sqlalchemy as sa++from alembic import op++# revision identifiers, used by Alembic.+revision: str = "a5fe08ea4990"+down_revision: Union[str, None] = "2d0f9407ffac"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.add_column(+ "organizations",+ sa.Column("artifact_url_expiry_seconds", sa.Integer(), nullable=True),+ )+++def downgrade() -> None:+ op.drop_column("organizations", "artifact_url_expiry_seconds")diff --git a/skyvern/forge/sdk/artifact/manager.py b/skyvern/forge/sdk/artifact/manager.pyindex 61db0024b..367922dac 100644--- a/skyvern/forge/sdk/artifact/manager.py+++ b/skyvern/forge/sdk/artifact/manager.py@@ -12,7 +12,12 @@ import structlogfrom skyvern.config import settingsfrom skyvern.forge import appfrom skyvern.forge.sdk.artifact.models import Artifact, ArtifactType, LogEntityType-from skyvern.forge.sdk.artifact.signing import parse_keyring, sign_artifact_url+from skyvern.forge.sdk.artifact.signing import (+ ARTIFACT_URL_EXPIRY_SECONDS,+ effective_artifact_url_expiry_seconds,+ parse_keyring,+ sign_artifact_url,+)from skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.db.id import generate_artifact_idfrom skyvern.forge.sdk.db.models import ArtifactModel@@ -940,6 +945,7 @@ class ArtifactManager:artifact_id: str,artifact_name: str | None = None,artifact_type: str | None = None,+ expiry_seconds: int | None = None,) -> str:"""Return a signed ``/v1/artifacts/{id}/content`` URL for any artifact.@@ -947,18 +953,37 @@ class ArtifactManager:``STORAGE.get_share_link``. This method always builds the Skyvern-originsigned URL regardless of ``bundle_key`` — used for DOWNLOAD artifactsso webhook payloads stay short and clients hit our origin.++ ``expiry_seconds`` overrides the URL's TTL; when None, the global+ default applies. Callers with an organization in scope should resolve+ the per-org override via :meth:`resolve_artifact_url_expiry_seconds`+ once and pass the result here."""return self._bundle_content_url(artifact_id=artifact_id,artifact_name=artifact_name,artifact_type=artifact_type,+ expiry_seconds=expiry_seconds,)+ async def resolve_artifact_url_expiry_seconds(self, organization_id: str | None) -> int:+ """Look up the org's artifact-URL TTL override; fall back to the global default.++ One DB hit per call — typically resolved once per batch of URLs (e.g.+ all downloads for a run) and passed into ``build_signed_content_url``.+ """+ if organization_id is None:+ return ARTIFACT_URL_EXPIRY_SECONDS+ org = await app.DATABASE.organizations.get_organization(organization_id=organization_id)+ per_org = org.artifact_url_expiry_seconds if org else None+ return effective_artifact_url_expiry_seconds(per_org)+def _bundle_content_url(self,artifact_id: str,artifact_name: str | None = None,artifact_type: str | None = None,+ expiry_seconds: int | None = None,) -> str:"""Return an absolute URL for a bundled artifact served via the content endpoint.@@ -978,6 +1003,7 @@ class ArtifactManager:keyring=keyring,artifact_name=artifact_name,artifact_type=artifact_type,+ expiry_seconds=expiry_seconds,)path = f"{base}/v1/artifacts/{artifact_id}/content"extra: dict[str, str] = {}@@ -989,10 +1015,12 @@ class ArtifactManager:async def get_share_link(self, artifact: Artifact) -> str | None:if artifact.bundle_key:+ expiry_seconds = await self.resolve_artifact_url_expiry_seconds(artifact.organization_id)return self._bundle_content_url(artifact.artifact_id,artifact_name=artifact.bundle_key,artifact_type=artifact.artifact_type,+ expiry_seconds=expiry_seconds,)return await app.STORAGE.get_share_link(artifact)@@ -1011,12 +1039,19 @@ class ArtifactManager:non_bundle_indices: list[int] = []non_bundle_artifacts: list[Artifact] = []+ # Resolve the per-org TTL once. All artifacts in a single batch share an+ # org (callers always look up by run/workflow scope), so one DB hit+ # covers every bundled URL we mint below.+ organization_id = artifacts[0].organization_id if artifacts else None+ bundled_expiry_seconds = await self.resolve_artifact_url_expiry_seconds(organization_id)+for i, artifact in enumerate(artifacts):if artifact.bundle_key:result[i] = self._bundle_content_url(artifact.artifact_id,artifact_name=artifact.bundle_key,artifact_type=artifact.artifact_type,+ expiry_seconds=bundled_expiry_seconds,)else:non_bundle_indices.append(i)diff --git a/skyvern/forge/sdk/artifact/signing.py b/skyvern/forge/sdk/artifact/signing.pyindex 4cfcd882b..dcb70db0f 100644--- a/skyvern/forge/sdk/artifact/signing.py+++ b/skyvern/forge/sdk/artifact/signing.py@@ -31,10 +31,35 @@ from urllib.parse import urlencodefrom pydantic import BaseModel, model_validator-ARTIFACT_URL_EXPIRY_SECONDS = 12 * 60 * 60 # 12 hours+ARTIFACT_URL_EXPIRY_SECONDS = 12 * 60 * 60 # 12 hours — global default when no per-org override.++# Bounds for the per-org override. 1 hour minimum keeps URLs useful for webhook+# consumers that retry across short outages; 7 days maximum follows the AWS S3+# presigned-URL cap so customers used to S3 don't get surprised. The route+# validates inbound values against these and the helper below clamps to them+# defensively in case a stray DB write puts garbage in the column.+ARTIFACT_URL_EXPIRY_SECONDS_MIN = 60 * 60 # 1 hour+ARTIFACT_URL_EXPIRY_SECONDS_MAX = 7 * 24 * 60 * 60 # 7 days+_ARTIFACT_CONTENT_PATH_TEMPLATE = "/v1/artifacts/{artifact_id}/content"+def effective_artifact_url_expiry_seconds(per_org_value: int | None) -> int:+ """Return the TTL to mint a signed artifact URL with.++ Falls back to ``ARTIFACT_URL_EXPIRY_SECONDS`` when ``per_org_value`` is+ None. Clamps to ``[ARTIFACT_URL_EXPIRY_SECONDS_MIN, ARTIFACT_URL_EXPIRY_SECONDS_MAX]``+ so an out-of-range stored value still produces a sane URL rather than+ refusing to serve.+ """+ if per_org_value is None:+ return ARTIFACT_URL_EXPIRY_SECONDS+ return max(+ ARTIFACT_URL_EXPIRY_SECONDS_MIN,+ min(ARTIFACT_URL_EXPIRY_SECONDS_MAX, per_org_value),+ )++class HmacKeyEntry(BaseModel):secret: str"""HMAC secret as a plain string."""@@ -90,23 +115,29 @@ def sign_artifact_url(keyring: ArtifactHmacKeyring,artifact_name: str | None = None,artifact_type: str | None = None,+ expiry_seconds: int | None = None,) -> str:"""Return a fully-signed URL for the artifact content endpoint.- Signs with keyring.current_kid. The URL is valid for- ARTIFACT_URL_EXPIRY_SECONDS (12 hours) from the time this function is called.+ Signs with ``keyring.current_kid``. The URL is valid for ``expiry_seconds``+ from the time this function is called. When ``expiry_seconds`` is None,+ falls back to the global ``ARTIFACT_URL_EXPIRY_SECONDS`` (12 hours).+ Callers wanting a per-org override should resolve it via+ :func:`effective_artifact_url_expiry_seconds` before calling here.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 appended as informational query+ params for client use only — they are not part of the canonical string or+ signature."""kid = keyring.current_kidsecret_bytes = keyring.get_secret_bytes(kid)if secret_bytes is None:raise ValueError(f"No secret found for kid '{kid}'")- expiry = int(time.time()) + ARTIFACT_URL_EXPIRY_SECONDS+ ttl = expiry_seconds if expiry_seconds is not None else ARTIFACT_URL_EXPIRY_SECONDS+ expiry = int(time.time()) + ttlpath = _ARTIFACT_CONTENT_PATH_TEMPLATE.format(artifact_id=artifact_id)canonical = _canonical_string("GET", path, expiry, kid)sig = _hmac_b64(secret_bytes, canonical)diff --git a/skyvern/forge/sdk/artifact/storage/azure.py b/skyvern/forge/sdk/artifact/storage/azure.pyindex 5604bf719..461cae955 100644--- a/skyvern/forge/sdk/artifact/storage/azure.py+++ b/skyvern/forge/sdk/artifact/storage/azure.py@@ -306,7 +306,7 @@ class AzureStorage(BaseStorage):# show completed downloads. Mirrors s3.py.artifacts = [a for a in artifacts if a.uri and not a.uri.endswith(BROWSER_DOWNLOADING_SUFFIX)]if artifacts:- return _file_infos_from_download_artifacts(artifacts)+ return await _file_infos_from_download_artifacts(artifacts)return await self._get_shared_downloaded_files_in_browser_session_via_listing(organization_id=organization_id, browser_session_id=browser_session_id@@ -534,7 +534,7 @@ class AzureStorage(BaseStorage):if run_id is not None and settings.ARTIFACT_CONTENT_HMAC_KEYRING:artifacts = await self._list_download_artifacts_safe(organization_id=organization_id, run_id=run_id)if artifacts:- return _file_infos_from_download_artifacts(artifacts)+ return await _file_infos_from_download_artifacts(artifacts)return await self._get_downloaded_files_via_blob_listing(organization_id=organization_id, run_id=run_id)diff --git a/skyvern/forge/sdk/artifact/storage/base.py b/skyvern/forge/sdk/artifact/storage/base.pyindex 16ac807c0..6c04c6425 100644--- a/skyvern/forge/sdk/artifact/storage/base.py+++ b/skyvern/forge/sdk/artifact/storage/base.py@@ -10,13 +10,21 @@ from skyvern.forge.sdk.schemas.task_v2 import TaskV2, Thoughtfrom skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock-def _file_infos_from_download_artifacts(artifacts: list[Artifact]) -> list[FileInfo]:+async def _file_infos_from_download_artifacts(artifacts: list[Artifact]) -> list[FileInfo]:"""Build the API-shaped ``FileInfo`` list from DOWNLOAD artifact rows.Filename is the URI basename (the save site writes ``{base_uri}/{file}``);checksum and modified_at come straight from the row, so retrieval needszero S3 round-trips.++ All artifacts in a single batch share the same organization (downloads are+ scoped to a run, which is scoped to an org), so the per-org URL TTL is+ resolved once and applied to every URL."""+ if not artifacts:+ return []+ organization_id = artifacts[0].organization_id+ expiry_seconds = await app.ARTIFACT_MANAGER.resolve_artifact_url_expiry_seconds(organization_id)infos: list[FileInfo] = []for artifact in artifacts:filename = artifact.uri.rsplit("/", 1)[-1] if artifact.uri else ""@@ -24,6 +32,7 @@ def _file_infos_from_download_artifacts(artifacts: list[Artifact]) -> list[FileIartifact_id=artifact.artifact_id,artifact_name=filename,artifact_type=ArtifactType.DOWNLOAD.value,+ expiry_seconds=expiry_seconds,)infos.append(FileInfo(diff --git a/skyvern/forge/sdk/artifact/storage/s3.py b/skyvern/forge/sdk/artifact/storage/s3.pyindex ebfa10c8f..485cd0395 100644--- a/skyvern/forge/sdk/artifact/storage/s3.py+++ b/skyvern/forge/sdk/artifact/storage/s3.py@@ -362,7 +362,7 @@ class S3Storage(BaseStorage):# rows so the agent can detect "still downloading" via DB query.artifacts = [a for a in artifacts if a.uri and not a.uri.endswith(BROWSER_DOWNLOADING_SUFFIX)]if artifacts:- return _file_infos_from_download_artifacts(artifacts)+ return await _file_infos_from_download_artifacts(artifacts)return await self._get_shared_downloaded_files_in_browser_session_via_listing(organization_id=organization_id, browser_session_id=browser_session_id@@ -601,7 +601,7 @@ class S3Storage(BaseStorage):if run_id is not None and settings.ARTIFACT_CONTENT_HMAC_KEYRING:artifacts = await self._list_download_artifacts_safe(organization_id=organization_id, run_id=run_id)if artifacts:- return _file_infos_from_download_artifacts(artifacts)+ return await _file_infos_from_download_artifacts(artifacts)# Legacy fallback — runs predating SKY-8861 (no artifact rows) and# OSS-default deployments without HMAC signing both arrive here.diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.pyindex 166f6b07c..f6629d0c9 100644--- a/skyvern/forge/sdk/db/models.py+++ b/skyvern/forge/sdk/db/models.py@@ -173,6 +173,7 @@ class OrganizationModel(Base):domain = Column(String, nullable=True, index=True)bw_organization_id = Column(String, nullable=True, default=None)bw_collection_ids = Column(JSON, nullable=True, default=None)+ artifact_url_expiry_seconds = Column(Integer, nullable=True)created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)modified_at = Column(DateTime,diff --git a/skyvern/forge/sdk/db/repositories/organizations.py b/skyvern/forge/sdk/db/repositories/organizations.pyindex 4691416cf..0c2e52fbd 100644--- a/skyvern/forge/sdk/db/repositories/organizations.py+++ b/skyvern/forge/sdk/db/repositories/organizations.py@@ -154,6 +154,8 @@ class OrganizationsRepository(BaseRepository):webhook_callback_url: str | None = None,max_steps_per_run: int | None = None,max_retries_per_step: int | None = None,+ artifact_url_expiry_seconds: int | None = None,+ clear_artifact_url_expiry_seconds: bool = False,) -> Organization:async with self.Session() as session:organization = (@@ -169,6 +171,13 @@ class OrganizationsRepository(BaseRepository):organization.max_steps_per_run = max_steps_per_runif max_retries_per_step:organization.max_retries_per_step = max_retries_per_step+ # ``clear_*`` decouples "don't update" (None) from "explicitly clear":+ # callers pass ``clear_artifact_url_expiry_seconds=True`` to reset+ # the value to NULL, falling back to the global default.+ if clear_artifact_url_expiry_seconds:+ organization.artifact_url_expiry_seconds = None+ elif artifact_url_expiry_seconds is not None:+ organization.artifact_url_expiry_seconds = artifact_url_expiry_secondsawait session.commit()await session.refresh(organization)return Organization.model_validate(organization)diff --git a/skyvern/forge/sdk/db/utils.py b/skyvern/forge/sdk/db/utils.pyindex 9d38810df..fe8200458 100644--- a/skyvern/forge/sdk/db/utils.py+++ b/skyvern/forge/sdk/db/utils.py@@ -315,6 +315,7 @@ def convert_to_organization(org_model: OrganizationModel) -> Organization:domain=org_model.domain,bw_organization_id=org_model.bw_organization_id,bw_collection_ids=org_model.bw_collection_ids,+ artifact_url_expiry_seconds=org_model.artifact_url_expiry_seconds,created_at=org_model.created_at,modified_at=org_model.modified_at,)diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.pyindex 46c516491..0e6109e63 100644--- a/skyvern/forge/sdk/routes/agent_protocol.py+++ b/skyvern/forge/sdk/routes/agent_protocol.py@@ -1,5 +1,6 @@import asyncioimport json+import timeimport unicodedatafrom enum import Enumfrom typing import Annotated, Any@@ -36,7 +37,13 @@ from skyvern.forge import appfrom skyvern.forge.prompts import prompt_enginefrom skyvern.forge.sdk.api.llm.exceptions import LLMProviderErrorfrom skyvern.forge.sdk.artifact.models import Artifact, ArtifactType-from skyvern.forge.sdk.artifact.signing import ARTIFACT_URL_EXPIRY_SECONDS, parse_keyring, verify_artifact_signature+from skyvern.forge.sdk.artifact.signing import (+ ARTIFACT_URL_EXPIRY_SECONDS,+ ARTIFACT_URL_EXPIRY_SECONDS_MAX,+ ARTIFACT_URL_EXPIRY_SECONDS_MIN,+ parse_keyring,+ verify_artifact_signature,+)from skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.curl_converter import curl_to_http_request_block_paramsfrom skyvern.forge.sdk.core.permissions.permission_checker_factory import PermissionCheckerFactory@@ -1547,16 +1554,34 @@ def _artifact_response_config(artifact: Artifact) -> tuple[str, str]:return media_type, "inline"-def _artifact_content_response_headers(*, disposition: str, is_signed: bool) -> dict[str, str]:+def _artifact_content_response_headers(+ *,+ disposition: str,+ is_signed: bool,+ signed_expiry_unix: int | None = None,+) -> dict[str, str]:"""Response headers for the artifact content endpoint.+ For signed URLs, ``Cache-Control: max-age`` is set to the URL's remaining+ lifetime — derived from the ``expiry`` query parameter rather than the+ global default — so per-org TTL overrides flow through to caches. Caches+ must not retain a body past the URL's own expiry.+Includes ``X-Content-Type-Options: nosniff`` as defence-in-depth forSKY-8862: even if something upstream strips the attachment disposition,the browser will not sniff the octet-stream body back into HTML/PDF."""+ if is_signed:+ if signed_expiry_unix is not None:+ remaining = max(0, signed_expiry_unix - int(time.time()))+ else:+ remaining = ARTIFACT_URL_EXPIRY_SECONDS+ cache_control = f"private, max-age={remaining}"+ else:+ cache_control = "private, no-cache"return {"Content-Disposition": disposition,- "Cache-Control": f"private, max-age={ARTIFACT_URL_EXPIRY_SECONDS}" if is_signed else "private, no-cache",+ "Cache-Control": cache_control,"X-Content-Type-Options": "nosniff",}@@ -1629,12 +1654,19 @@ async def get_artifact_content()media_type, content_disposition = _artifact_response_config(artifact)is_signed = sig is not None and expiry is not None and kid is not None+ signed_expiry_unix: int | None = None+ if is_signed and expiry is not None:+ try:+ signed_expiry_unix = int(expiry)+ except ValueError:+ signed_expiry_unix = Nonereturn Response(content=content,media_type=media_type,headers=_artifact_content_response_headers(disposition=content_disposition,is_signed=is_signed,+ signed_expiry_unix=signed_expiry_unix,),)@@ -3212,9 +3244,36 @@ async def update_organization(org_update: OrganizationUpdate,current_org: Organization = Depends(org_auth_service.get_current_org),) -> Organization:+ # Validate the per-org artifact URL expiry against the same bounds the+ # signing helper clamps to. Reject out-of-range values at the API edge so+ # users see a clear 400 instead of a silently clamped value persisting in+ # the DB. The clear flag and a non-null override are mutually exclusive —+ # the repo prefers the clear flag, but reject the ambiguity here too.+ if org_update.artifact_url_expiry_seconds is not None and not org_update.clear_artifact_url_expiry_seconds:+ if (+ org_update.artifact_url_expiry_seconds < ARTIFACT_URL_EXPIRY_SECONDS_MIN+ or org_update.artifact_url_expiry_seconds > ARTIFACT_URL_EXPIRY_SECONDS_MAX+ ):+ raise HTTPException(+ status_code=http_status.HTTP_400_BAD_REQUEST,+ detail=(+ f"artifact_url_expiry_seconds must be between "+ f"{ARTIFACT_URL_EXPIRY_SECONDS_MIN} and {ARTIFACT_URL_EXPIRY_SECONDS_MAX} seconds"+ ),+ )+ if org_update.clear_artifact_url_expiry_seconds and org_update.artifact_url_expiry_seconds is not None:+ raise HTTPException(+ status_code=http_status.HTTP_400_BAD_REQUEST,+ detail=(+ "clear_artifact_url_expiry_seconds cannot be combined with a non-null "+ "artifact_url_expiry_seconds — pick one"+ ),+ )return await app.DATABASE.organizations.update_organization(current_org.organization_id,max_steps_per_run=org_update.max_steps_per_run,+ artifact_url_expiry_seconds=org_update.artifact_url_expiry_seconds,+ clear_artifact_url_expiry_seconds=org_update.clear_artifact_url_expiry_seconds,)diff --git a/skyvern/forge/sdk/schemas/organizations.py b/skyvern/forge/sdk/schemas/organizations.pyindex f9729cd1e..8a5f6261d 100644--- a/skyvern/forge/sdk/schemas/organizations.py+++ b/skyvern/forge/sdk/schemas/organizations.py@@ -16,6 +16,15 @@ class Organization(BaseModel):domain: str | None = Nonebw_organization_id: str | None = Nonebw_collection_ids: list[str] | None = None+ artifact_url_expiry_seconds: int | None = Field(+ None,+ description=(+ "Per-org override for the lifetime of signed /v1/artifacts/{id}/content URLs, "+ "in seconds. None means use the global default (12 hours). When set, every signed "+ "URL minted for artifacts owned by this org is valid for this many seconds. "+ "Bounded between 1 hour (3600) and 7 days (604800)."+ ),+ )created_at: datetimemodified_at: datetime@@ -168,3 +177,21 @@ class GetOrganizationAPIKeysResponse(BaseModel):class OrganizationUpdate(BaseModel):max_steps_per_run: int | None = None+ artifact_url_expiry_seconds: int | None = Field(+ None,+ description=(+ "Per-org override for the lifetime of signed /v1/artifacts/{id}/content URLs, "+ "in seconds. Bounded between 1 hour (3600) and 7 days (604800). Pass null to "+ "leave the current value unchanged. To explicitly clear the override (and fall "+ "back to the global 12-hour default) set ``clear_artifact_url_expiry_seconds`` "+ "to true."+ ),+ )+ clear_artifact_url_expiry_seconds: bool = Field(+ False,+ description=(+ "When true, resets ``artifact_url_expiry_seconds`` to NULL — the org will use "+ "the global 12-hour default. Mutually exclusive with a non-null value in "+ "``artifact_url_expiry_seconds`` (the clear flag wins)."+ ),+ )diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 4f6e24f2b..21d178f98 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -535,7 +535,7 @@ class WorkflowService:# Preserve the input order so block outputs render files in save order.by_id = {a.artifact_id: a for a in artifacts}ordered = [by_id[aid] for aid in artifact_ids if aid in by_id]- return _file_infos_from_download_artifacts(ordered)+ return await _file_infos_from_download_artifacts(ordered)async def _file_infos_for_workflow_run_filtered_by_filenames(self,@@ -582,7 +582,7 @@ class WorkflowService:if basename in filenames and basename not in seen:matched.append(artifact)seen.add(basename)- return _file_infos_from_download_artifacts(matched)+ return await _file_infos_from_download_artifacts(matched)async def _refresh_output_urls(self,diff --git a/tests/unit/test_artifact_signing.py b/tests/unit/test_artifact_signing.pyindex d21a146f6..c4ba0a319 100644--- a/tests/unit/test_artifact_signing.py+++ b/tests/unit/test_artifact_signing.py@@ -15,10 +15,13 @@ import pytestfrom skyvern.forge.sdk.artifact.signing import (ARTIFACT_URL_EXPIRY_SECONDS,+ ARTIFACT_URL_EXPIRY_SECONDS_MAX,+ ARTIFACT_URL_EXPIRY_SECONDS_MIN,ArtifactHmacKeyring,HmacKeyEntry,_canonical_string,_hmac_b64,+ effective_artifact_url_expiry_seconds,parse_keyring,sign_artifact_url,verify_artifact_signature,@@ -182,6 +185,72 @@ class TestSignArtifactUrl:url = sign_artifact_url(_BASE_URL + "/", _ARTIFACT_ID, kr)assert "//" not in url.split("://", 1)[1]+ def test_custom_expiry_seconds_used(self) -> None:+ """A non-default expiry_seconds is reflected in the URL's expiry timestamp."""+ from urllib.parse import parse_qs, urlparse++ kr = _make_keyring()+ custom_ttl = 24 * 60 * 60 # 24 hours+ before = int(time.time())+ url = sign_artifact_url(_BASE_URL, _ARTIFACT_ID, kr, expiry_seconds=custom_ttl)+ after = int(time.time())++ expiry = int(parse_qs(urlparse(url).query)["expiry"][0])+ assert before + custom_ttl <= expiry <= after + custom_ttl++ def test_custom_expiry_signature_verifies(self) -> None:+ """A URL signed with a custom expiry still verifies correctly."""+ from urllib.parse import parse_qs, urlparse++ kr = _make_keyring()+ url = sign_artifact_url(_BASE_URL, _ARTIFACT_ID, kr, expiry_seconds=3600)+ qs = parse_qs(urlparse(url).query)+ assert verify_artifact_signature(+ _ARTIFACT_ID,+ qs["expiry"][0],+ qs["kid"][0],+ qs["sig"][0],+ kr,+ )++ def test_none_expiry_seconds_uses_default(self) -> None:+ """expiry_seconds=None falls back to the global 12h default."""+ from urllib.parse import parse_qs, urlparse++ kr = _make_keyring()+ before = int(time.time())+ url = sign_artifact_url(_BASE_URL, _ARTIFACT_ID, kr, expiry_seconds=None)+ after = int(time.time())+ expiry = int(parse_qs(urlparse(url).query)["expiry"][0])+ assert before + ARTIFACT_URL_EXPIRY_SECONDS <= expiry <= after + ARTIFACT_URL_EXPIRY_SECONDS+++# ---------------------------------------------------------------------------+# effective_artifact_url_expiry_seconds+# ---------------------------------------------------------------------------+++class TestEffectiveArtifactUrlExpirySeconds:+ def test_none_returns_global_default(self) -> None:+ assert effective_artifact_url_expiry_seconds(None) == ARTIFACT_URL_EXPIRY_SECONDS++ def test_value_within_bounds_passes_through(self) -> None:+ # 4 hours+ assert effective_artifact_url_expiry_seconds(4 * 3600) == 4 * 3600++ def test_below_min_clamped_up(self) -> None:+ assert effective_artifact_url_expiry_seconds(1) == ARTIFACT_URL_EXPIRY_SECONDS_MIN++ def test_above_max_clamped_down(self) -> None:+ # 30 days+ assert effective_artifact_url_expiry_seconds(30 * 24 * 3600) == ARTIFACT_URL_EXPIRY_SECONDS_MAX++ def test_exactly_min_passes(self) -> None:+ assert effective_artifact_url_expiry_seconds(ARTIFACT_URL_EXPIRY_SECONDS_MIN) == ARTIFACT_URL_EXPIRY_SECONDS_MIN++ def test_exactly_max_passes(self) -> None:+ assert effective_artifact_url_expiry_seconds(ARTIFACT_URL_EXPIRY_SECONDS_MAX) == ARTIFACT_URL_EXPIRY_SECONDS_MAX+# ---------------------------------------------------------------------------# verify_artifact_signaturediff --git a/tests/unit/test_artifact_url_expiry_org_config.py b/tests/unit/test_artifact_url_expiry_org_config.pynew file mode 100644index 000000000..ca55316a1--- /dev/null+++ b/tests/unit/test_artifact_url_expiry_org_config.py@@ -0,0 +1,279 @@+"""Tests for the per-org artifact URL expiry override (SKY-8861).++Covers:+- ArtifactManager.resolve_artifact_url_expiry_seconds+ (None org, missing org row, value within bounds, clamped, fallback)+- ArtifactManager.build_signed_content_url passes expiry_seconds to signing+- _artifact_content_response_headers Cache-Control max-age computation+"""++from datetime import datetime, timezone+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from skyvern.forge.sdk.artifact.manager import ArtifactManager+from skyvern.forge.sdk.artifact.signing import (+ ARTIFACT_URL_EXPIRY_SECONDS,+ ARTIFACT_URL_EXPIRY_SECONDS_MAX,+ ARTIFACT_URL_EXPIRY_SECONDS_MIN,+)+from skyvern.forge.sdk.routes.agent_protocol import _artifact_content_response_headers+from skyvern.forge.sdk.schemas.organizations import Organization+++def _make_org(artifact_url_expiry_seconds: int | None) -> Organization:+ now = datetime.now(timezone.utc)+ return Organization(+ organization_id="o_1",+ organization_name="acme",+ artifact_url_expiry_seconds=artifact_url_expiry_seconds,+ created_at=now,+ modified_at=now,+ )+++# ---------------------------------------------------------------------------+# resolve_artifact_url_expiry_seconds+# ---------------------------------------------------------------------------+++class TestResolveArtifactUrlExpirySeconds:+ @pytest.mark.asyncio+ async def test_none_org_id_returns_global_default(self) -> None:+ """No org in scope (e.g. system contexts) — fall straight to the global default."""+ manager = ArtifactManager()+ with patch("skyvern.forge.sdk.artifact.manager.app") as app:+ app.DATABASE.organizations.get_organization = AsyncMock()+ ttl = await manager.resolve_artifact_url_expiry_seconds(None)+ assert ttl == ARTIFACT_URL_EXPIRY_SECONDS+ app.DATABASE.organizations.get_organization.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_missing_org_row_returns_global_default(self) -> None:+ """Org row not found → fall back rather than raising — keeps URL minting resilient."""+ manager = ArtifactManager()+ with patch("skyvern.forge.sdk.artifact.manager.app") as app:+ app.DATABASE.organizations.get_organization = AsyncMock(return_value=None)+ ttl = await manager.resolve_artifact_url_expiry_seconds("o_missing")+ assert ttl == ARTIFACT_URL_EXPIRY_SECONDS++ @pytest.mark.asyncio+ async def test_org_with_no_override_returns_global_default(self) -> None:+ manager = ArtifactManager()+ org = _make_org(artifact_url_expiry_seconds=None)+ with patch("skyvern.forge.sdk.artifact.manager.app") as app:+ app.DATABASE.organizations.get_organization = AsyncMock(return_value=org)+ ttl = await manager.resolve_artifact_url_expiry_seconds("o_1")+ assert ttl == ARTIFACT_URL_EXPIRY_SECONDS++ @pytest.mark.asyncio+ async def test_org_with_override_within_bounds_returns_override(self) -> None:+ manager = ArtifactManager()+ org = _make_org(artifact_url_expiry_seconds=4 * 3600) # 4h+ with patch("skyvern.forge.sdk.artifact.manager.app") as app:+ app.DATABASE.organizations.get_organization = AsyncMock(return_value=org)+ ttl = await manager.resolve_artifact_url_expiry_seconds("o_1")+ assert ttl == 4 * 3600++ @pytest.mark.asyncio+ async def test_org_with_below_min_value_clamped_up(self) -> None:+ """Defensive clamp guards against stray DB writes (admin tool, manual SQL, etc.)."""+ manager = ArtifactManager()+ org = _make_org(artifact_url_expiry_seconds=10)+ with patch("skyvern.forge.sdk.artifact.manager.app") as app:+ app.DATABASE.organizations.get_organization = AsyncMock(return_value=org)+ ttl = await manager.resolve_artifact_url_expiry_seconds("o_1")+ assert ttl == ARTIFACT_URL_EXPIRY_SECONDS_MIN++ @pytest.mark.asyncio+ async def test_org_with_above_max_value_clamped_down(self) -> None:+ manager = ArtifactManager()+ org = _make_org(artifact_url_expiry_seconds=30 * 24 * 3600) # 30 days+ with patch("skyvern.forge.sdk.artifact.manager.app") as app:+ app.DATABASE.organizations.get_organization = AsyncMock(return_value=org)+ ttl = await manager.resolve_artifact_url_expiry_seconds("o_1")+ assert ttl == ARTIFACT_URL_EXPIRY_SECONDS_MAX+++# ---------------------------------------------------------------------------+# build_signed_content_url passes expiry through+# ---------------------------------------------------------------------------+++class TestBuildSignedContentUrl:+ def test_expiry_seconds_propagated_to_sign(self) -> None:+ manager = ArtifactManager()+ # Stub _bundle_content_url so we observe the kwargs without needing a keyring.+ with patch.object(manager, "_bundle_content_url", return_value="https://x") as bundle:+ manager.build_signed_content_url(artifact_id="a_1", expiry_seconds=3600)+ bundle.assert_called_once_with(+ artifact_id="a_1",+ artifact_name=None,+ artifact_type=None,+ expiry_seconds=3600,+ )++ def test_no_expiry_propagates_none(self) -> None:+ manager = ArtifactManager()+ with patch.object(manager, "_bundle_content_url", return_value="https://x") as bundle:+ manager.build_signed_content_url(artifact_id="a_1")+ kwargs = bundle.call_args.kwargs+ assert kwargs["expiry_seconds"] is None+++# ---------------------------------------------------------------------------+# _artifact_content_response_headers Cache-Control+# ---------------------------------------------------------------------------+++class TestArtifactContentResponseHeaders:+ def test_signed_with_expiry_uses_remaining_lifetime(self) -> None:+ """Cache-Control max-age must reflect the per-URL expiry, not the global default."""+ import time++ future = int(time.time()) + 3600 # 1h from now+ headers = _artifact_content_response_headers(+ disposition="inline",+ is_signed=True,+ signed_expiry_unix=future,+ )+ max_age = int(headers["Cache-Control"].split("max-age=")[1])+ # Allow a few seconds of clock drift between the call and the assertion.+ assert 3580 <= max_age <= 3600++ def test_signed_with_past_expiry_clamps_to_zero(self) -> None:+ """Don't emit a negative max-age — caches behave unpredictably with negative values."""+ import time++ past = int(time.time()) - 60+ headers = _artifact_content_response_headers(+ disposition="inline",+ is_signed=True,+ signed_expiry_unix=past,+ )+ assert headers["Cache-Control"] == "private, max-age=0"++ def test_signed_without_expiry_falls_back_to_global_default(self) -> None:+ """Defensive fallback when the route can't parse expiry — still emit a sane TTL."""+ headers = _artifact_content_response_headers(+ disposition="inline",+ is_signed=True,+ signed_expiry_unix=None,+ )+ assert headers["Cache-Control"] == f"private, max-age={ARTIFACT_URL_EXPIRY_SECONDS}"++ def test_unsigned_emits_no_cache(self) -> None:+ """Org-API-key path is not URL-bound, so caches must revalidate every time."""+ headers = _artifact_content_response_headers(+ disposition="inline",+ is_signed=False,+ )+ assert headers["Cache-Control"] == "private, no-cache"++ def test_nosniff_always_present(self) -> None:+ for is_signed in (True, False):+ headers = _artifact_content_response_headers(+ disposition="inline",+ is_signed=is_signed,+ signed_expiry_unix=int(__import__("time").time()) + 60 if is_signed else None,+ )+ assert headers["X-Content-Type-Options"] == "nosniff"+++# ---------------------------------------------------------------------------+# OrganizationUpdate Pydantic model+# ---------------------------------------------------------------------------+++class TestOrganizationUpdateSchema:+ def test_defaults_are_none_and_false(self) -> None:+ from skyvern.forge.sdk.schemas.organizations import OrganizationUpdate++ body = OrganizationUpdate()+ assert body.max_steps_per_run is None+ assert body.artifact_url_expiry_seconds is None+ assert body.clear_artifact_url_expiry_seconds is False++ def test_accepts_within_bounds_value(self) -> None:+ from skyvern.forge.sdk.schemas.organizations import OrganizationUpdate++ body = OrganizationUpdate(artifact_url_expiry_seconds=4 * 3600)+ assert body.artifact_url_expiry_seconds == 4 * 3600++ def test_clear_flag_can_be_set(self) -> None:+ from skyvern.forge.sdk.schemas.organizations import OrganizationUpdate++ body = OrganizationUpdate(clear_artifact_url_expiry_seconds=True)+ assert body.clear_artifact_url_expiry_seconds is True+++# ---------------------------------------------------------------------------+# get_share_links_with_bundle_support resolves once+# ---------------------------------------------------------------------------+++class TestGetShareLinksWithBundleSupport:+ @pytest.mark.asyncio+ async def test_resolves_per_org_expiry_once_for_batch(self) -> None:+ """All bundled URLs in a batch share an org → one DB lookup, not N."""+ from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType++ manager = ArtifactManager()+ now = datetime.now(timezone.utc)+ artifacts = [+ Artifact(+ artifact_id=f"a_{i}",+ artifact_type=ArtifactType.LLM_REQUEST,+ uri=f"s3://x/{i}.json",+ bundle_key=f"file_{i}.json",+ organization_id="o_1",+ created_at=now,+ modified_at=now,+ )+ for i in range(3)+ ]++ resolve = AsyncMock(return_value=2 * 3600)+ with patch.object(manager, "resolve_artifact_url_expiry_seconds", resolve):+ with patch.object(manager, "_bundle_content_url", return_value="https://x") as bundle:+ with patch("skyvern.forge.sdk.artifact.manager.app") as app:+ app.STORAGE.get_share_links = AsyncMock(return_value=[])+ result = await manager.get_share_links_with_bundle_support(artifacts)++ assert len(result) == 3+ # Resolve was called exactly once for the batch.+ assert resolve.await_count == 1+ # Every bundled URL was minted with the resolved TTL.+ assert bundle.call_count == 3+ for call in bundle.call_args_list:+ assert call.kwargs["expiry_seconds"] == 2 * 3600++ @pytest.mark.asyncio+ async def test_empty_artifact_list_returns_empty(self) -> None:+ manager = ArtifactManager()+ # Should not even attempt to resolve.+ with patch.object(+ manager,+ "resolve_artifact_url_expiry_seconds",+ AsyncMock(return_value=ARTIFACT_URL_EXPIRY_SECONDS),+ ) as resolve:+ with patch("skyvern.forge.sdk.artifact.manager.app"):+ result = await manager.get_share_links_with_bundle_support([])+ assert result == []+ # Resolve is still called (org_id=None path), and that's cheap — just don't crash.+ # We mainly want to assert no IndexError on empty list.+ _ = resolve # mark used+++__all__ = [+ "TestArtifactContentResponseHeaders",+ "TestBuildSignedContentUrl",+ "TestGetShareLinksWithBundleSupport",+ "TestOrganizationUpdateSchema",+ "TestResolveArtifactUrlExpirySeconds",+]+++# Silence unused import warnings in some lints+_ = MagicMockdiff --git a/tests/unit/test_browser_session_download_artifacts.py b/tests/unit/test_browser_session_download_artifacts.pyindex 4638cd875..a7fcb8967 100644--- a/tests/unit/test_browser_session_download_artifacts.py+++ b/tests/unit/test_browser_session_download_artifacts.py@@ -300,6 +300,7 @@ async def test_get_shared_downloaded_files_in_browser_session_uses_artifact_urlswith patch("skyvern.forge.sdk.artifact.storage.s3.app") as s3_app:s3_app.DATABASE.artifacts.list_artifacts_for_browser_session_by_type = mock_listbase_app.ARTIFACT_MANAGER.build_signed_content_url = build_url+ base_app.ARTIFACT_MANAGER.resolve_artifact_url_expiry_seconds = AsyncMock(return_value=12 * 60 * 60)result = await storage.get_shared_downloaded_files_in_browser_session(organization_id="o_1", browser_session_id="pbs_1")@@ -370,6 +371,7 @@ async def test_get_shared_downloaded_files_in_browser_session_filters_partial_ar):s3_app.DATABASE.artifacts.list_artifacts_for_browser_session_by_type = mock_listbase_app.ARTIFACT_MANAGER.build_signed_content_url = build_url+ base_app.ARTIFACT_MANAGER.resolve_artifact_url_expiry_seconds = AsyncMock(return_value=12 * 60 * 60)result = await storage.get_shared_downloaded_files_in_browser_session(organization_id="o_1", browser_session_id="pbs_1")diff --git a/tests/unit/test_downloaded_files_artifact_urls.py b/tests/unit/test_downloaded_files_artifact_urls.pyindex b169d63db..53009cc7c 100644--- a/tests/unit/test_downloaded_files_artifact_urls.py+++ b/tests/unit/test_downloaded_files_artifact_urls.py@@ -208,6 +208,7 @@ async def test_get_downloaded_files_uses_artifact_urls_when_rows_exist(keyring_cwith patch("skyvern.forge.sdk.artifact.storage.s3.app") as s3_app:s3_app.DATABASE.artifacts.list_artifacts_for_run_by_type = mock_listbase_app.ARTIFACT_MANAGER.build_signed_content_url = build_url+ base_app.ARTIFACT_MANAGER.resolve_artifact_url_expiry_seconds = AsyncMock(return_value=12 * 60 * 60)result = await storage.get_downloaded_files(organization_id="o_1", run_id="wr_1")assert len(result) == 1@@ -247,6 +248,7 @@ async def test_get_downloaded_files_preserves_artifact_row_order(keyring_configuwith patch("skyvern.forge.sdk.artifact.storage.s3.app") as s3_app:s3_app.DATABASE.artifacts.list_artifacts_for_run_by_type = mock_listbase_app.ARTIFACT_MANAGER.build_signed_content_url = build_url+ base_app.ARTIFACT_MANAGER.resolve_artifact_url_expiry_seconds = AsyncMock(return_value=12 * 60 * 60)result = await storage.get_downloaded_files(organization_id="o_1", run_id="wr_1")assert [fi.filename for fi in result] == ["first.pdf", "second.pdf"]