Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Mint short-lived artifact URLs on demand for recording playback (#7459)
Aaron Perez8c81c758af7f
diff --git a/skyvern-frontend/src/api/artifactUrls.test.ts b/skyvern-frontend/src/api/artifactUrls.test.tsnew file mode 100644index 000000000..2cee65694--- /dev/null+++ b/skyvern-frontend/src/api/artifactUrls.test.ts@@ -0,0 +1,73 @@+import { describe, expect, test } from "vitest";++import {+ artifactIdFromContentUrl,+ expiryFromSignedUrl,+ refreshDelayMs,+} from "./artifactUrls";++describe("artifactIdFromContentUrl", () => {+ test("extracts the artifact id from a signed content URL", () => {+ expect(+ artifactIdFromContentUrl(+ "https://api.skyvern.com/v1/artifacts/a_123/content?expiry=1800000600&kid=k1&sig=s",+ ),+ ).toBe("a_123");+ });++ test("handles trailing slash and api-prefixed paths", () => {+ expect(+ artifactIdFromContentUrl(+ "https://api.skyvern.com/api/v1/artifacts/a_456/content/?expiry=1&kid=k&sig=s",+ ),+ ).toBe("a_456");+ });++ test("returns null for storage presigned URLs", () => {+ expect(+ artifactIdFromContentUrl(+ "https://bucket.s3.amazonaws.com/recordings/foo.webm?X-Amz-Signature=abc",+ ),+ ).toBeNull();+ });++ test("returns null for null, empty, and unparseable input", () => {+ expect(artifactIdFromContentUrl(null)).toBeNull();+ expect(artifactIdFromContentUrl("")).toBeNull();+ expect(artifactIdFromContentUrl("not a url")).toBeNull();+ });+});++describe("expiryFromSignedUrl", () => {+ test("reads the expiry query param as unix seconds", () => {+ expect(+ expiryFromSignedUrl(+ "https://api.skyvern.com/v1/artifacts/a_1/content?expiry=1800000600&kid=k1&sig=s",+ ),+ ).toBe(1800000600);+ });++ test("returns null when expiry is absent or not a number", () => {+ expect(+ expiryFromSignedUrl("https://api.skyvern.com/v1/artifacts/a_1/content"),+ ).toBeNull();+ expect(+ expiryFromSignedUrl(+ "https://api.skyvern.com/v1/artifacts/a_1/content?expiry=soon",+ ),+ ).toBeNull();+ expect(expiryFromSignedUrl("not a url")).toBeNull();+ });+});++describe("refreshDelayMs", () => {+ test("schedules the refresh margin before expiry", () => {+ // expires 300s from now, margin 60s -> refresh in 240s+ expect(refreshDelayMs(1_000_300, 1_000_000_000)).toBe(240_000);+ });++ test("clamps to zero when the URL is already inside the margin", () => {+ expect(refreshDelayMs(1_000_030, 1_000_000_000)).toBe(0);+ expect(refreshDelayMs(999_000, 1_000_000_000)).toBe(0);+ });+});diff --git a/skyvern-frontend/src/api/artifactUrls.ts b/skyvern-frontend/src/api/artifactUrls.tsnew file mode 100644index 000000000..f8ab7a22f--- /dev/null+++ b/skyvern-frontend/src/api/artifactUrls.ts@@ -0,0 +1,75 @@+import { AxiosInstance } from "axios";++export type ArtifactSignedUrlApiResponse = {+ artifact_id: string;+ signed_url: string;+ expires_at: number | null;+};++const ARTIFACT_CONTENT_PATH = /\/artifacts\/([^/]+)\/content\/?$/;++/** Seconds before a signed URL's expiry at which consumers should re-mint. */+export const REFRESH_MARGIN_SECONDS = 60;++/**+ * Artifact id of a Skyvern signed content URL+ * (`.../artifacts/{id}/content?...`), or null for anything else (storage+ * presigned URLs, file:// paths) — those can't be re-minted by id.+ */+export function artifactIdFromContentUrl(+ url: string | null | undefined,+): string | null {+ if (!url) {+ return null;+ }+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ return null;+ }+ const match = ARTIFACT_CONTENT_PATH.exec(parsed.pathname);+ return match?.[1] ?? null;+}++/** Unix-seconds expiry of a signed URL, read from its `expiry` query param. */+export function expiryFromSignedUrl(+ url: string | null | undefined,+): number | null {+ if (!url) {+ return null;+ }+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ return null;+ }+ const expiry = parsed.searchParams.get("expiry");+ if (!expiry || !/^\d+$/.test(expiry)) {+ return null;+ }+ return Number(expiry);+}++/** Milliseconds until a URL expiring at `expiresAtSeconds` should be re-minted. */+export function refreshDelayMs(+ expiresAtSeconds: number,+ nowMs: number,+): number {+ return Math.max(+ 0,+ (expiresAtSeconds - REFRESH_MARGIN_SECONDS) * 1000 - nowMs,+ );+}++/** Mint a fresh short-lived content URL for the artifact (SKY-12541). */+export async function mintSignedArtifactUrl(+ client: AxiosInstance,+ artifactId: string,+): Promise<ArtifactSignedUrlApiResponse> {+ const response = await client.get<ArtifactSignedUrlApiResponse>(+ `/artifacts/${artifactId}/signed-url`,+ );+ return response.data;+}diff --git a/skyvern-frontend/src/components/ArtifactVideo.test.tsx b/skyvern-frontend/src/components/ArtifactVideo.test.tsxnew file mode 100644index 000000000..3968ef8f1--- /dev/null+++ b/skyvern-frontend/src/components/ArtifactVideo.test.tsx@@ -0,0 +1,65 @@+// @vitest-environment jsdom++import { fireEvent, render, waitFor } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++import { ArtifactVideo } from "./ArtifactVideo";++const { mintMock } = vi.hoisted(() => ({+ mintMock: vi.fn(),+}));++vi.mock("@/api/AxiosClient", () => ({+ getClient: vi.fn().mockResolvedValue({}),+}));++vi.mock("@/hooks/useCredentialGetter", () => ({+ useCredentialGetter: () => null,+}));++vi.mock("@/api/artifactUrls", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/api/artifactUrls")>()),+ mintSignedArtifactUrl: mintMock,+}));++const FAR_EXPIRY = Math.floor(Date.now() / 1000) + 12 * 3600;+const SIGNED_URL = `https://api.skyvern.com/v1/artifacts/a_rec/content?expiry=${FAR_EXPIRY}&kid=k1&sig=s`;+const MINTED_URL =+ "https://api.skyvern.com/v1/artifacts/a_rec/content?expiry=9999999999&kid=k1&sig=fresh";++describe("ArtifactVideo", () => {+ it("re-mints the URL once when playback errors", async () => {+ mintMock.mockResolvedValue({+ artifact_id: "a_rec",+ signed_url: MINTED_URL,+ expires_at: 9999999999,+ });++ const { container } = render(<ArtifactVideo src={SIGNED_URL} />);+ const video = container.querySelector("video")!;+ expect(video.getAttribute("src")).toBe(SIGNED_URL);++ fireEvent.error(video);++ await waitFor(() => {+ expect(video.getAttribute("src")).toBe(MINTED_URL);+ });+ expect(mintMock).toHaveBeenCalledWith(expect.anything(), "a_rec");++ fireEvent.error(video);+ expect(mintMock).toHaveBeenCalledTimes(1);+ });++ it("does not try to re-mint non-artifact URLs", async () => {+ mintMock.mockClear();+ const presigned =+ "https://bucket.s3.amazonaws.com/rec.webm?X-Amz-Signature=abc";+ const { container } = render(<ArtifactVideo src={presigned} />);+ const video = container.querySelector("video")!;++ fireEvent.error(video);++ expect(mintMock).not.toHaveBeenCalled();+ expect(video.getAttribute("src")).toBe(presigned);+ });+});diff --git a/skyvern-frontend/src/components/ArtifactVideo.tsx b/skyvern-frontend/src/components/ArtifactVideo.tsxnew file mode 100644index 000000000..aa4d2b996--- /dev/null+++ b/skyvern-frontend/src/components/ArtifactVideo.tsx@@ -0,0 +1,113 @@+import { useCallback, useEffect, useRef, useState } from "react";++import { getClient } from "@/api/AxiosClient";+import {+ artifactIdFromContentUrl,+ expiryFromSignedUrl,+ mintSignedArtifactUrl,+ refreshDelayMs,+} from "@/api/artifactUrls";+import { useCredentialGetter } from "@/hooks/useCredentialGetter";++type Props = Omit<React.ComponentPropsWithoutRef<"video">, "src"> & {+ src: string;+};++/**+ * Drop-in `<video>` for Skyvern recording artifacts. Signed content URLs+ * expire; long playback sessions issue Range requests past that boundary and+ * would 403 (SKY-12541). This swaps in a freshly minted URL shortly before+ * expiry — and once on error as a backstop — preserving playback position.+ * Non-Skyvern URLs (storage presigned, file://) render as a plain video.+ */+function ArtifactVideo({+ src,+ onError,+ onLoadedMetadata,+ ...videoProps+}: Props) {+ const credentialGetter = useCredentialGetter();+ const videoRef = useRef<HTMLVideoElement | null>(null);+ const resumeRef = useRef<{ time: number; playing: boolean } | null>(null);+ const retriedOnErrorRef = useRef(false);+ const [url, setUrl] = useState(src);++ useEffect(() => {+ setUrl(src);+ resumeRef.current = null;+ retriedOnErrorRef.current = false;+ }, [src]);++ const artifactId = artifactIdFromContentUrl(src);++ const refresh = useCallback(async () => {+ if (!artifactId) {+ return;+ }+ const video = videoRef.current;+ if (video) {+ resumeRef.current = {+ time: video.currentTime,+ playing: !video.paused && !video.ended,+ };+ }+ try {+ const client = await getClient(credentialGetter);+ const minted = await mintSignedArtifactUrl(client, artifactId);+ setUrl(minted.signed_url);+ } catch {+ // Leave the current URL in place; the on-error backstop (or the next+ // timer tick) retries.+ }+ }, [artifactId, credentialGetter]);++ useEffect(() => {+ const expiresAt = expiryFromSignedUrl(url);+ if (!artifactId || expiresAt === null) {+ return;+ }+ const delayMs = refreshDelayMs(expiresAt, Date.now());+ // setTimeout overflows int32 and fires immediately past ~24.8 days.+ if (delayMs > 2 ** 31 - 1) {+ return;+ }+ const timer = window.setTimeout(() => {+ void refresh();+ }, delayMs);+ return () => window.clearTimeout(timer);+ }, [artifactId, url, refresh]);++ const handleLoadedMetadata = (+ event: React.SyntheticEvent<HTMLVideoElement>,+ ) => {+ const resume = resumeRef.current;+ if (resume) {+ resumeRef.current = null;+ event.currentTarget.currentTime = resume.time;+ if (resume.playing) {+ void event.currentTarget.play().catch(() => {});+ }+ }+ onLoadedMetadata?.(event);+ };++ const handleError = (event: React.SyntheticEvent<HTMLVideoElement>) => {+ if (artifactId && !retriedOnErrorRef.current) {+ retriedOnErrorRef.current = true;+ void refresh();+ }+ onError?.(event);+ };++ return (+ <video+ ref={videoRef}+ src={url}+ onLoadedMetadata={handleLoadedMetadata}+ onError={handleError}+ {...videoProps}+ />+ );+}++export { ArtifactVideo };diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessionVideo.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSessionVideo.tsxindex 8b88e2f1d..f04a5dd0a 100644--- a/skyvern-frontend/src/routes/browserSessions/BrowserSessionVideo.tsx+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessionVideo.tsx@@ -2,6 +2,7 @@ import { useQuery } from "@tanstack/react-query";import { useParams } from "react-router-dom";import { getClient } from "@/api/AxiosClient";+import { ArtifactVideo } from "@/components/ArtifactVideo";import { useCredentialGetter } from "@/hooks/useCredentialGetter";import { type Recording } from "@/routes/workflows/types/browserSessionTypes";import { artifactApiBaseUrl } from "@/util/env";@@ -103,14 +104,14 @@ function BrowserSessionVideo() {{getRecordingUrl(recording.url) ? (<div className="w-full">- <video+ <ArtifactVideocontrolsclassName="w-full max-w-4xl rounded-lg"src={getRecordingUrl(recording.url)!}preload="metadata">Your browser does not support the video tag.- </video>+ </ArtifactVideo><div className="mt-2 text-xs text-gray-500"><ahref={getRecordingUrl(recording.url)!}diff --git a/skyvern-frontend/src/routes/tasks/detail/TaskRecording.tsx b/skyvern-frontend/src/routes/tasks/detail/TaskRecording.tsxindex e69d0e3e5..1cb90f0bc 100644--- a/skyvern-frontend/src/routes/tasks/detail/TaskRecording.tsx+++ b/skyvern-frontend/src/routes/tasks/detail/TaskRecording.tsx@@ -1,4 +1,5 @@import { getClient } from "@/api/AxiosClient";+import { ArtifactVideo } from "@/components/ArtifactVideo";import { useCredentialGetter } from "@/hooks/useCredentialGetter";import { useQuery } from "@tanstack/react-query";import { getRecordingURL } from "./artifactUtils";@@ -42,7 +43,14 @@ function TaskRecording() {}if (recordingData?.url) {- return <video width={800} height={450} src={recordingData.url} controls />;+ return (+ <ArtifactVideo+ width={800}+ height={450}+ src={recordingData.url}+ controls+ />+ );}if (recordingData?.archived) {diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/HeroRecording.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/HeroRecording.tsxindex 61dafa16b..01f6018b9 100644--- a/skyvern-frontend/src/routes/workflows/studio/runview/HeroRecording.tsx+++ b/skyvern-frontend/src/routes/workflows/studio/runview/HeroRecording.tsx@@ -1,5 +1,6 @@import { useState } from "react";+import { ArtifactVideo } from "@/components/ArtifactVideo";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";type HeroRecordingProps = {@@ -38,7 +39,7 @@ function RecordingPlayer({}return (- <video+ <ArtifactVideosrc={url}controlspreload="metadata"diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunRecording.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunRecording.tsxindex ffb934c2f..7d665f975 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunRecording.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunRecording.tsx@@ -1,4 +1,5 @@import { usePostHog } from "posthog-js/react";+import { ArtifactVideo } from "@/components/ArtifactVideo";import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWorkflowQuery";import { getRecordingUrls } from "./recordingUrls";@@ -32,10 +33,11 @@ function WorkflowRunRecording() {});}- if (recordingUrls.length === 1) {+ const singleUrl = recordingUrls.length === 1 ? recordingUrls[0] : undefined;+ if (singleUrl) {return (- <video- src={recordingUrls[0]}+ <ArtifactVideo+ src={singleUrl}controlspreload="metadata"className="w-full rounded-md"@@ -54,7 +56,7 @@ function WorkflowRunRecording() {<div className="text-sm text-muted-foreground">Recording {index + 1} of {recordingUrls.length}</div>- <video+ <ArtifactVideosrc={url}controlspreload="metadata"diff --git a/skyvern/forge/sdk/artifact/models.py b/skyvern/forge/sdk/artifact/models.pyindex f5e9309be..8b669689b 100644--- a/skyvern/forge/sdk/artifact/models.py+++ b/skyvern/forge/sdk/artifact/models.py@@ -107,6 +107,13 @@ class Artifact(BaseModel):return getattr(self, key)+class ArtifactSignedUrl(BaseModel):+ artifact_id: str+ signed_url: str+ expires_at: int | None = None+ """Unix seconds when signed_url stops working; None when the backing store controls expiry."""++class LogEntityType(StrEnum):STEP = "step"TASK = "task"diff --git a/skyvern/forge/sdk/artifact/signing.py b/skyvern/forge/sdk/artifact/signing.pyindex dcb70db0f..f9d7ea216 100644--- a/skyvern/forge/sdk/artifact/signing.py+++ b/skyvern/forge/sdk/artifact/signing.py@@ -33,6 +33,11 @@ from pydantic import BaseModel, model_validatorARTIFACT_URL_EXPIRY_SECONDS = 12 * 60 * 60 # 12 hours — global default when no per-org override.+# TTL for URLs minted at the point of use via GET /artifacts/{id}/signed-url.+# Short on purpose: the consumer asks for a fresh URL right before dereferencing+# it, so the window only needs to cover one fetch (or one video-buffering burst).+ARTIFACT_URL_ON_DEMAND_EXPIRY_SECONDS = 5 * 60+# 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 routediff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.pyindex c8ee4d057..6986e63c9 100644--- a/skyvern/forge/sdk/routes/agent_protocol.py+++ b/skyvern/forge/sdk/routes/agent_protocol.py@@ -7,7 +7,7 @@ from collections.abc import Sequencefrom datetime import datetimefrom enum import Enumfrom typing import Annotated, Any-from urllib.parse import quote+from urllib.parse import parse_qs, quote, urlparseimport structlogimport yaml@@ -44,11 +44,12 @@ from skyvern.forge import appfrom skyvern.forge.prompts import prompt_enginefrom skyvern.forge.sdk.api.llm.custom_llm_registry import load_custom_llm_configs_for_organizationfrom skyvern.forge.sdk.api.llm.exceptions import LLMProviderError-from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType+from skyvern.forge.sdk.artifact.models import Artifact, ArtifactSignedUrl, ArtifactTypefrom skyvern.forge.sdk.artifact.signing import (ARTIFACT_URL_EXPIRY_SECONDS,ARTIFACT_URL_EXPIRY_SECONDS_MAX,ARTIFACT_URL_EXPIRY_SECONDS_MIN,+ ARTIFACT_URL_ON_DEMAND_EXPIRY_SECONDS,parse_keyring,verify_artifact_signature,)@@ -3073,6 +3074,47 @@ async def get_artifact_content()+@base_router.get(+ "/artifacts/{artifact_id}/signed-url",+ tags=["Artifacts"],+ response_model=ArtifactSignedUrl,+ description="Mint a fresh short-lived URL for the artifact's content, for use at the point of consumption.",+ summary="Mint a short-lived artifact content URL",+ responses={+ 200: {"description": "Freshly minted content URL"},+ 404: {"description": "Artifact not found or content unavailable"},+ },+ # Kept out of the public OpenAPI schema until the Fern SDK deliberately adopts it.+ include_in_schema=False,+)+@base_router.get("/artifacts/{artifact_id}/signed-url/", response_model=ArtifactSignedUrl, include_in_schema=False)+async def get_artifact_signed_url(+ artifact_id: str,+ current_org: Organization = Depends(org_auth_service.get_current_org),+) -> ArtifactSignedUrl:+ artifact = await app.DATABASE.artifacts.get_artifact_by_id(+ artifact_id=artifact_id,+ organization_id=current_org.organization_id,+ )+ if not artifact:+ raise HTTPException(+ status_code=http_status.HTTP_404_NOT_FOUND,+ detail=f"Artifact not found {artifact_id}",+ )+ signed_url = await app.ARTIFACT_MANAGER.resolve_share_url(+ artifact,+ expiry_seconds=ARTIFACT_URL_ON_DEMAND_EXPIRY_SECONDS,+ )+ if not signed_url:+ raise HTTPException(+ status_code=http_status.HTTP_404_NOT_FOUND,+ detail="Artifact content not available",+ )+ expiry_values = parse_qs(urlparse(signed_url).query).get("expiry")+ expires_at = int(expiry_values[0]) if expiry_values else None+ return ArtifactSignedUrl(artifact_id=artifact_id, signed_url=signed_url, expires_at=expires_at)++@base_router.get("/runs/{run_id}/artifacts",tags=["Artifacts"],diff --git a/tests/unit/test_artifact_signed_url_endpoint.py b/tests/unit/test_artifact_signed_url_endpoint.pynew file mode 100644index 000000000..e3ef2d5a4--- /dev/null+++ b/tests/unit/test_artifact_signed_url_endpoint.py@@ -0,0 +1,233 @@+"""Tests for the on-demand artifact signed-URL endpoint (SKY-12541).++GET /v1/artifacts/{artifact_id}/signed-url mints a short-lived signed content+URL at the point of use, so consumers never depend on the long-lived URLs+embedded in earlier API responses.+"""++import json+import time+from datetime import datetime, timezone+from unittest.mock import AsyncMock, patch+from urllib.parse import parse_qs, urlparse++from fastapi import FastAPI+from fastapi.testclient import TestClient++from skyvern.config import settings+from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType+from skyvern.forge.sdk.artifact.signing import (+ ARTIFACT_URL_ON_DEMAND_EXPIRY_SECONDS,+)+from skyvern.forge.sdk.routes.routers import base_router+from skyvern.forge.sdk.schemas.organizations import Organization++_KEYRING_JSON = json.dumps({"current_kid": "k1", "keys": {"k1": {"secret": "0" * 64}}})+++def _make_artifact(artifact_id: str = "a_1", organization_id: str = "o_1") -> Artifact:+ now = datetime.now(timezone.utc)+ return Artifact(+ artifact_id=artifact_id,+ artifact_type=ArtifactType.SCREENSHOT_ACTION,+ uri=f"s3://bucket/{artifact_id}.png",+ organization_id=organization_id,+ task_id="tsk_1",+ step_id="stp_1",+ created_at=now,+ modified_at=now,+ )+++def _make_org(organization_id: str = "o_1") -> Organization:+ now = datetime.now(timezone.utc)+ return Organization(+ organization_id=organization_id,+ organization_name="org",+ created_at=now,+ modified_at=now,+ )+++def _make_client() -> TestClient:+ test_app = FastAPI()+ test_app.include_router(base_router, prefix="/v1")+ return TestClient(test_app)+++class TestGetArtifactSignedUrl:+ def test_mints_short_lived_signed_url(self) -> None:+ artifact = _make_artifact()+ with (+ patch.object(settings, "ARTIFACT_CONTENT_HMAC_KEYRING", _KEYRING_JSON),+ patch.object(settings, "SKYVERN_BASE_URL", "http://testserver"),+ patch("skyvern.forge.sdk.routes.agent_protocol.app") as app_module,+ patch(+ "skyvern.forge.sdk.services.org_auth_service.get_current_org_cached",+ new=AsyncMock(return_value=_make_org()),+ ),+ ):+ app_module.DATABASE.artifacts.get_artifact_by_id = AsyncMock(return_value=artifact)+ from skyvern.forge.sdk.artifact.manager import ArtifactManager++ app_module.ARTIFACT_MANAGER.resolve_share_url = ArtifactManager.resolve_share_url.__get__(ArtifactManager())++ before = int(time.time())+ resp = _make_client().get("/v1/artifacts/a_1/signed-url", headers={"x-api-key": "key"})+ after = int(time.time())++ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert body["artifact_id"] == "a_1"+ parsed = urlparse(body["signed_url"])+ assert parsed.path == "/v1/artifacts/a_1/content"+ qs = parse_qs(parsed.query)+ expiry = int(qs["expiry"][0])+ assert before + ARTIFACT_URL_ON_DEMAND_EXPIRY_SECONDS <= expiry <= after + ARTIFACT_URL_ON_DEMAND_EXPIRY_SECONDS+ assert body["expires_at"] == expiry++ def test_short_ttl_is_minutes_not_hours(self) -> None:+ assert 60 <= ARTIFACT_URL_ON_DEMAND_EXPIRY_SECONDS <= 15 * 60++ def test_unknown_artifact_returns_404(self) -> None:+ with (+ patch.object(settings, "ARTIFACT_CONTENT_HMAC_KEYRING", _KEYRING_JSON),+ patch("skyvern.forge.sdk.routes.agent_protocol.app") as app_module,+ patch(+ "skyvern.forge.sdk.services.org_auth_service.get_current_org_cached",+ new=AsyncMock(return_value=_make_org()),+ ),+ ):+ app_module.DATABASE.artifacts.get_artifact_by_id = AsyncMock(return_value=None)+ resp = _make_client().get("/v1/artifacts/a_missing/signed-url", headers={"x-api-key": "key"})+ assert resp.status_code == 404++ def test_requires_authentication(self) -> None:+ with patch.object(settings, "ARTIFACT_CONTENT_HMAC_KEYRING", _KEYRING_JSON):+ resp = _make_client().get("/v1/artifacts/a_1/signed-url")+ assert resp.status_code == 403++ def test_org_scoping_uses_callers_org(self) -> None:+ """The artifact lookup must be scoped to the authenticated org."""+ artifact = _make_artifact()+ with (+ patch.object(settings, "ARTIFACT_CONTENT_HMAC_KEYRING", _KEYRING_JSON),+ patch.object(settings, "SKYVERN_BASE_URL", "http://testserver"),+ patch("skyvern.forge.sdk.routes.agent_protocol.app") as app_module,+ patch(+ "skyvern.forge.sdk.services.org_auth_service.get_current_org_cached",+ new=AsyncMock(return_value=_make_org("o_2")),+ ),+ ):+ app_module.DATABASE.artifacts.get_artifact_by_id = AsyncMock(return_value=artifact)+ from skyvern.forge.sdk.artifact.manager import ArtifactManager++ app_module.ARTIFACT_MANAGER.resolve_share_url = ArtifactManager.resolve_share_url.__get__(ArtifactManager())+ resp = _make_client().get("/v1/artifacts/a_1/signed-url", headers={"x-api-key": "key"})++ assert resp.status_code == 200+ app_module.DATABASE.artifacts.get_artifact_by_id.assert_awaited_once_with(+ artifact_id="a_1", organization_id="o_2"+ )+++class TestMintedUrlAgainstContentEndpoint:+ def _mint_and_fetch(self, *, age_seconds: int, range_header: str | None = None) -> "TestClient.Response":+ """Mint a short-lived URL, then fetch content ``age_seconds`` later (patched clock)."""+ artifact = _make_artifact()+ real_time = time.time+ with (+ patch.object(settings, "ARTIFACT_CONTENT_HMAC_KEYRING", _KEYRING_JSON),+ patch.object(settings, "SKYVERN_BASE_URL", "http://testserver"),+ patch("skyvern.forge.sdk.routes.agent_protocol.app") as app_module,+ patch(+ "skyvern.forge.sdk.services.org_auth_service.get_current_org_cached",+ new=AsyncMock(return_value=_make_org()),+ ),+ ):+ app_module.DATABASE.artifacts.get_artifact_by_id = AsyncMock(return_value=artifact)+ app_module.DATABASE.artifacts.get_artifact_by_id_no_org = AsyncMock(return_value=artifact)+ app_module.ARTIFACT_MANAGER.retrieve_artifact = AsyncMock(return_value=b"0123456789")+ from skyvern.forge.sdk.artifact.manager import ArtifactManager++ app_module.ARTIFACT_MANAGER.resolve_share_url = ArtifactManager.resolve_share_url.__get__(ArtifactManager())++ client = _make_client()+ minted = client.get("/v1/artifacts/a_1/signed-url", headers={"x-api-key": "key"})+ assert minted.status_code == 200, minted.text+ signed_url = minted.json()["signed_url"].replace("http://testserver", "")++ headers = {"Range": range_header} if range_header else {}+ with patch("skyvern.forge.sdk.artifact.signing.time.time", new=lambda: real_time() + age_seconds):+ return client.get(signed_url, headers=headers)++ def test_fresh_minted_url_serves_content(self) -> None:+ resp = self._mint_and_fetch(age_seconds=0)+ assert resp.status_code == 200+ assert resp.content == b"0123456789"++ def test_expired_minted_url_is_rejected(self) -> None:+ resp = self._mint_and_fetch(age_seconds=ARTIFACT_URL_ON_DEMAND_EXPIRY_SECONDS + 5)+ assert resp.status_code == 403++ def test_fresh_minted_url_serves_range_requests(self) -> None:+ resp = self._mint_and_fetch(age_seconds=0, range_header="bytes=2-5")+ assert resp.status_code == 206+ assert resp.content == b"2345"++ def test_range_request_past_expiry_is_rejected(self) -> None:+ """Playback continuation past the TTL boundary must re-mint — the URL itself dies."""+ resp = self._mint_and_fetch(+ age_seconds=ARTIFACT_URL_ON_DEMAND_EXPIRY_SECONDS + 5,+ range_header="bytes=2-5",+ )+ assert resp.status_code == 403++ def test_tampered_artifact_id_is_rejected(self) -> None:+ """A signature minted for one artifact must not authorize another (replay/splice)."""+ artifact = _make_artifact()+ with (+ patch.object(settings, "ARTIFACT_CONTENT_HMAC_KEYRING", _KEYRING_JSON),+ patch.object(settings, "SKYVERN_BASE_URL", "http://testserver"),+ patch("skyvern.forge.sdk.routes.agent_protocol.app") as app_module,+ patch(+ "skyvern.forge.sdk.services.org_auth_service.get_current_org_cached",+ new=AsyncMock(return_value=_make_org()),+ ),+ ):+ app_module.DATABASE.artifacts.get_artifact_by_id = AsyncMock(return_value=artifact)+ app_module.DATABASE.artifacts.get_artifact_by_id_no_org = AsyncMock(return_value=artifact)+ app_module.ARTIFACT_MANAGER.retrieve_artifact = AsyncMock(return_value=b"content")+ from skyvern.forge.sdk.artifact.manager import ArtifactManager++ app_module.ARTIFACT_MANAGER.resolve_share_url = ArtifactManager.resolve_share_url.__get__(ArtifactManager())+ client = _make_client()+ minted = client.get("/v1/artifacts/a_1/signed-url", headers={"x-api-key": "key"})+ signed_url = minted.json()["signed_url"].replace("http://testserver", "")+ spliced = signed_url.replace("/artifacts/a_1/", "/artifacts/a_other/")+ resp = client.get(spliced)+ assert resp.status_code == 403+++class TestKeyringUnsetFallback:+ def test_falls_back_to_storage_presigned_url(self) -> None:+ """Self-host deployments without a keyring still get a working URL."""+ artifact = _make_artifact()+ with (+ patch.object(settings, "ARTIFACT_CONTENT_HMAC_KEYRING", None),+ patch("skyvern.forge.sdk.routes.agent_protocol.app") as app_module,+ patch(+ "skyvern.forge.sdk.services.org_auth_service.get_current_org_cached",+ new=AsyncMock(return_value=_make_org()),+ ),+ ):+ app_module.DATABASE.artifacts.get_artifact_by_id = AsyncMock(return_value=artifact)+ app_module.ARTIFACT_MANAGER.resolve_share_url = AsyncMock(+ return_value="https://bucket.s3.amazonaws.com/a_1.png?X-Amz-Signature=abc"+ )+ resp = _make_client().get("/v1/artifacts/a_1/signed-url", headers={"x-api-key": "key"})++ assert resp.status_code == 200+ body = resp.json()+ assert body["signed_url"] == "https://bucket.s3.amazonaws.com/a_1.png?X-Amz-Signature=abc"+ assert body["expires_at"] is None