Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Offer Skyvern 1.0 in every workflow's engine picker, and honor it on older workflows only when a person picked it (#8774)
pedrohsdbda8260c06899
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.jsonindex 83386aa7f..5002d2707 100644--- a/docs/api-reference/openapi.json+++ b/docs/api-reference/openapi.json@@ -8955,6 +8955,11 @@}]},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "default": false+ },"complete_criterion": {"anyOf": [{@@ -9276,6 +9281,12 @@}]},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "description": "Set to true only when skyvern-1.0 was explicitly chosen for this block; leave it unset otherwise.",+ "default": false+ },"navigation_goal": {"anyOf": [{@@ -14503,6 +14514,11 @@}]},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "default": false+ },"complete_criterion": {"anyOf": [{@@ -14846,6 +14862,12 @@}]},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "description": "Set to true only when skyvern-1.0 was explicitly chosen for this block; leave it unset otherwise.",+ "default": false+ },"data_schema": {"anyOf": [{@@ -15265,6 +15287,11 @@}]},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "default": false+ },"complete_criterion": {"anyOf": [{@@ -15808,6 +15835,12 @@}]},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "description": "Set to true only when skyvern-1.0 was explicitly chosen for this block; leave it unset otherwise.",+ "default": false+ },"error_code_mapping": {"anyOf": [{@@ -18703,6 +18736,11 @@],"default": "skyvern-1.0"},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "default": false+ },"complete_criterion": {"anyOf": [{@@ -19522,6 +19560,11 @@}]},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "default": false+ },"complete_criterion": {"anyOf": [{@@ -19833,6 +19876,12 @@}]},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "description": "Set to true only when skyvern-1.0 was explicitly chosen for this block; leave it unset otherwise.",+ "default": false+ },"navigation_goal": {"anyOf": [{@@ -20348,6 +20397,11 @@}]},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "default": false+ },"complete_criterion": {"anyOf": [{@@ -20652,6 +20706,12 @@}]},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "description": "Set to true only when skyvern-1.0 was explicitly chosen for this block; leave it unset otherwise.",+ "default": false+ },"error_code_mapping": {"anyOf": [{@@ -24545,6 +24605,11 @@}]},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "default": false+ },"complete_criterion": {"anyOf": [{@@ -24851,6 +24916,12 @@}]},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "description": "Set to true only when skyvern-1.0 was explicitly chosen for this block; leave it unset otherwise.",+ "default": false+ },"navigation_goal": {"anyOf": [{@@ -27535,6 +27606,11 @@],"default": "skyvern-1.0"},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "default": false+ },"complete_criterion": {"anyOf": [{@@ -27984,6 +28060,11 @@}]},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "default": false+ },"complete_criterion": {"anyOf": [{@@ -28279,6 +28360,12 @@}]},+ "engine_pinned": {+ "type": "boolean",+ "title": "Engine Pinned",+ "description": "Set to true only when skyvern-1.0 was explicitly chosen for this block; leave it unset otherwise.",+ "default": false+ },"complete_criterion": {"anyOf": [{diff --git a/skyvern-frontend/src/components/EngineSelector.test.tsx b/skyvern-frontend/src/components/EngineSelector.test.tsxindex 4ab6c50bb..c5ffa447d 100644--- a/skyvern-frontend/src/components/EngineSelector.test.tsx+++ b/skyvern-frontend/src/components/EngineSelector.test.tsx@@ -102,54 +102,32 @@ describe("RunEngineSelector", () => {expect(onChange.mock.calls).toEqual([[RunEngine.SkyvernV3], [null]]);});- test.each([null, RunEngine.SkyvernV3])(- "labels Default with no hint when the effective default is %s",- (effectiveDefaultEngine) => {- const { container } = render(- <RunEngineSelector- value={null}- onChange={() => {}}- effectiveDefaultEngine={effectiveDefaultEngine}- />,- );-- const defaultItem = screen- .getAllByRole("button")- .filter((button) => button.textContent?.includes("Default"));- expect(defaultItem.map((button) => button.textContent)).toEqual([- "Default",- "Default",- ]);- expect(container.textContent).not.toMatch(/routing|runs on/i);- },- );-- test("offers Skyvern 1.0 as Legacy only where the workflow can pin it", () => {- const { unmount } = render(+ test("labels Default with no routing hint", () => {+ const { container } = render(<RunEngineSelector value={null} onChange={() => {}} />,);- expect(screen.queryByText("Skyvern 1.0")).toBeNull();- unmount();- render(- <RunEngineSelector- value={null}- onChange={() => {}}- effectiveDefaultEngine={RunEngine.SkyvernV3}- />,- );- expect(screen.getByText("Skyvern 1.0")).toBeTruthy();+ const defaultItem = screen+ .getAllByRole("button")+ .filter((button) => button.textContent?.includes("Default"));+ expect(defaultItem.map((button) => button.textContent)).toEqual([+ "Default",+ "Default",+ ]);+ expect(container.textContent).not.toMatch(/routing|runs on/i);+ });++ test("offers Skyvern 1.0 as Legacy in every workflow, and selecting it pins skyvern-1.0", () => {+ const onChange = vi.fn();+ render(<RunEngineSelector value={null} onChange={onChange} />);+expect(screen.getByText("Legacy")).toBeTruthy();+ fireEvent.click(screen.getByText("Skyvern 1.0"));+ expect(onChange.mock.calls).toEqual([[RunEngine.SkyvernV1]]);});test("lists Skyvern 3.0 right after Default, above Skyvern 1.0", () => {- render(- <RunEngineSelector- value={null}- onChange={() => {}}- effectiveDefaultEngine={RunEngine.SkyvernV3}- />,- );+ render(<RunEngineSelector value={null} onChange={() => {}} />);const [, ...items] = screen.getAllByRole("button");expect(items.map((item) => item.textContent)).toEqual([diff --git a/skyvern-frontend/src/components/EngineSelector.tsx b/skyvern-frontend/src/components/EngineSelector.tsxindex 34f11016f..35b7ce793 100644--- a/skyvern-frontend/src/components/EngineSelector.tsx+++ b/skyvern-frontend/src/components/EngineSelector.tsx@@ -24,7 +24,6 @@ type Props = {onChange: (value: RunEngine | null) => void;className?: string;availableEngines?: Array<RunEngine>;- effectiveDefaultEngine?: RunEngine | null;};const engineOptions: Array<EngineOption & { value: RunEngine }> = [@@ -83,12 +82,8 @@ function RunEngineSelector({onChange,className,availableEngines,- effectiveDefaultEngine = null,}: Props) {- // Without a chosen-engine default, a skyvern-1.0 block is the routed Default, so it cannot be pinned.- const engines = (availableEngines ?? defaultEngines).filter(- (engine) => engine !== RunEngine.SkyvernV1 || effectiveDefaultEngine,- );+ const engines = availableEngines ?? defaultEngines;const visibleEngines =value && !engines.includes(value) ? [...engines, value] : engines;const options: Array<EngineOption> = [diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsxindex 43dfe47fa..e8c147944 100644--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx@@ -204,6 +204,7 @@ import {getWorkflowErrors,upgradeWorkflowDefinitionToVersionTwo,withGoalUndoRecordsFrom,+ workflowEffectiveDefaultEngine,} from "./workflowEditorUtils";import { replayPersistedCollapseVisibility } from "./collapse/applyDescendantCollapseVisibility";import { useNodeCollapseStore } from "./collapse/useNodeCollapseStore";@@ -1099,6 +1100,7 @@ function Workspace({savedWorkflow.workflow_definition.blocks,settings,true,+ workflowEffectiveDefaultEngine(savedWorkflow, queryClient),);updateNodes(replayPersistedCollapseVisibility(@@ -1144,7 +1146,7 @@ function Workspace({)useWorkflowHasChangesStore.setState({ hydrateSavedSettings: null });};- }, [updateNodes, updateEdges]);+ }, [updateNodes, updateEdges, queryClient]);usePendingWorkflowSaveRecovery(workflow);@@ -2089,6 +2091,7 @@ function Workspace({workflowData.workflow_definition.blocks,settings,true,+ workflowEffectiveDefaultEngine(workflowData, queryClient),);const collapsedSet = useNodeCollapseStore.getState().collapsed;@@ -2394,6 +2397,7 @@ function Workspace({response.data.workflow_definition.blocks ?? [],settings,true,+ workflowEffectiveDefaultEngine(saveData.workflow, queryClient),);const repairedBlocks = getWorkflowBlocks(repairedNodes, repairedEdges);settings.finallyBlockLabel = resolveFinallyBlockLabel(@@ -2547,6 +2551,7 @@ function Workspace({selectedVersion.workflow_definition?.blocks || [],settings,true, // editable+ workflowEffectiveDefaultEngine(selectedVersion, queryClient),);const collapsedSet = useNodeCollapseStore.getState().collapsed;diff --git a/skyvern-frontend/src/routes/workflows/editor/hooks/useEffectiveDefaultEngine.ts b/skyvern-frontend/src/routes/workflows/editor/hooks/useEffectiveDefaultEngine.tsdeleted file mode 100644index 0c28571ed..000000000--- a/skyvern-frontend/src/routes/workflows/editor/hooks/useEffectiveDefaultEngine.ts+++ /dev/null@@ -1,11 +0,0 @@-import type { RunEngine } from "@/api/types";-import { useWorkflowPermanentId } from "@/routes/workflows/WorkflowPermanentIdContext";-import { useWorkflowQuery } from "@/routes/workflows/hooks/useWorkflowQuery";--function useEffectiveDefaultEngine(): RunEngine | null {- const workflowPermanentId = useWorkflowPermanentId();- const { data: workflow } = useWorkflowQuery({ workflowPermanentId });- return workflow?.effective_default_engine ?? null;-}--export { useEffectiveDefaultEngine };diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/ActionNode/ActionEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/ActionNode/ActionEditor.tsxindex 235af6610..5473d48cc 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/ActionNode/ActionEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/ActionNode/ActionEditor.tsx@@ -8,7 +8,6 @@ import {AccordionTrigger,} from "@/components/ui/accordion";import { RunEngineSelector } from "@/components/EngineSelector";-import { useEffectiveDefaultEngine } from "../../hooks/useEffectiveDefaultEngine";import { HelpTooltip } from "@/components/HelpTooltip";import { Label } from "@/components/ui/label";import { ModelSelector } from "@/components/ModelSelector";@@ -80,7 +79,6 @@ function ActionEditorBody({];const { editable } = data;const update = useUpdate<ActionNodeData>({ id: blockId, editable });- const effectiveDefaultEngine = useEffectiveDefaultEngine();const nodes = useNodes<AppNode>();const edges = useEdges();const urlPlaceholder = isFirstBrowserTaskBlock(nodes, edges, blockId)@@ -188,7 +186,6 @@ function ActionEditorBody({<HelpTooltip content={helpTooltips["action"]["engine"]} /></div><RunEngineSelector- effectiveDefaultEngine={effectiveDefaultEngine}value={data.engine}onChange={(value) => update({ engine: value })}className="nopan w-52 text-xs"diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/ExtractionNode/ExtractionEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/ExtractionNode/ExtractionEditor.tsxindex 44cc4ad13..4524b6ffd 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/ExtractionNode/ExtractionEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/ExtractionNode/ExtractionEditor.tsx@@ -15,7 +15,6 @@ import { Textarea } from "@/components/ui/textarea";import { WorkflowBlockInputTextarea } from "@/components/WorkflowBlockInputTextarea";import { WorkflowDataSchemaInputGroup } from "@/components/DataSchemaInputGroup/WorkflowDataSchemaInputGroup";import { RunEngineSelector } from "@/components/EngineSelector";-import { useEffectiveDefaultEngine } from "../../hooks/useEffectiveDefaultEngine";import { ModelSelector } from "@/components/ModelSelector";import { AI_IMPROVE_CONFIGS } from "../../constants";@@ -97,7 +96,6 @@ function ExtractionEditorBody({];const { editable } = data;const update = useUpdate<ExtractionNodeData>({ id: blockId, editable });- const effectiveDefaultEngine = useEffectiveDefaultEngine();const nodes = useNodes<AppNode>();const edges = useEdges();const outputParameterKeys = getAvailableOutputParameterKeys(@@ -285,7 +283,6 @@ function ExtractionEditorBody({</Label></div><RunEngineSelector- effectiveDefaultEngine={effectiveDefaultEngine}value={data.engine}onChange={(value) => update({ engine: value })}className="nopan w-52 text-xs"diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/FileDownloadEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/FileDownloadEditor.tsxindex 64441f4f7..8579e9d6f 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/FileDownloadEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/FileDownloadEditor.tsx@@ -3,7 +3,6 @@ import type { ReactNode } from "react";import { BROWSER_DOWNLOAD_TIMEOUT_SECONDS } from "@/api/types";import { RunEngineSelector } from "@/components/EngineSelector";-import { useEffectiveDefaultEngine } from "../../hooks/useEffectiveDefaultEngine";import { HelpTooltip } from "@/components/HelpTooltip";import { ModelSelector } from "@/components/ModelSelector";import { WorkflowBlockInput } from "@/components/WorkflowBlockInput";@@ -149,7 +148,6 @@ function FileDownloadEditorBody({const isInsideForLoop = isNodeInsideForLoop(nodes, blockId);const parentLoopSkipsOnFail = getParentLoopSkipsOnFail(nodes, blockId);const update = useUpdate<FileDownloadNodeData>({ id: blockId, editable });- const effectiveDefaultEngine = useEffectiveDefaultEngine();const hasInteracted = useHasInteractedThisSession();const credentialTotpIdentifier = useSelectedCredentialTotpIdentifier(parameterKeys.length > 0 ? parameterKeys[0] : undefined,@@ -616,7 +614,6 @@ function FileDownloadEditorBody({</Label></div><RunEngineSelector- effectiveDefaultEngine={effectiveDefaultEngine}value={engine}onChange={(next) => update({ engine: next })}className="nopan w-52 text-xs"diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginEditor.tsxindex 64d3873af..bfc350525 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/LoginNode/LoginEditor.tsx@@ -22,7 +22,6 @@ import { Label } from "@/components/ui/label";import { Separator } from "@/components/ui/separator";import { Switch } from "@/components/ui/switch";import { RunEngineSelector } from "@/components/EngineSelector";-import { useEffectiveDefaultEngine } from "../../hooks/useEffectiveDefaultEngine";import { ModelSelector } from "@/components/ModelSelector";import { WorkflowBlockInputTextarea } from "@/components/WorkflowBlockInputTextarea";import { useWorkflowParametersStore } from "@/store/WorkflowParametersStore";@@ -89,7 +88,6 @@ function LoginEditorBody({];const { editable } = data;const update = useUpdate<LoginNodeData>({ id: blockId, editable });- const effectiveDefaultEngine = useEffectiveDefaultEngine();const nodes = useNodes<AppNode>();const edges = useEdges();const urlPlaceholder = isFirstBrowserTaskBlock(nodes, edges, blockId)@@ -381,7 +379,6 @@ function LoginEditorBody({</Label></div><RunEngineSelector- effectiveDefaultEngine={effectiveDefaultEngine}value={data.engine}onChange={(value) => update({ engine: value })}className="nopan w-52 text-xs"diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.test.tsxindex 051a46bbd..3139e42b6 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.test.tsx@@ -9,10 +9,6 @@ import { navigationNodeDefaultData, type NavigationNodeData } from "./types";let nodeData: { type: "navigation"; data: NavigationNodeData } | null = null;-vi.mock("../../hooks/useEffectiveDefaultEngine", () => ({- useEffectiveDefaultEngine: () => null,-}));-vi.mock("@xyflow/react", () => ({useNodesData: () => nodeData,useNodes: () => [],diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.tsxindex af0257517..dc28edbd1 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/NavigationNode/NavigationEditor.tsx@@ -2,7 +2,6 @@ import { useEdges, useNodes, useNodesData } from "@xyflow/react";import { RunEngine } from "@/api/types";import { RunEngineSelector } from "@/components/EngineSelector";-import { useEffectiveDefaultEngine } from "../../hooks/useEffectiveDefaultEngine";import { HelpTooltip } from "@/components/HelpTooltip";import { ModelSelector } from "@/components/ModelSelector";import { WorkflowBlockInput } from "@/components/WorkflowBlockInput";@@ -72,7 +71,6 @@ function NavigationEditorBody({}) {const { editable } = data;const update = useUpdate<NavigationNodeData>({ id: blockId, editable });- const effectiveDefaultEngine = useEffectiveDefaultEngine();const nodes = useNodes<AppNode>();const edges = useEdges();const urlPlaceholder = isFirstBrowserTaskBlock(nodes, edges, blockId)@@ -170,7 +168,6 @@ function NavigationEditorBody({<HelpTooltip content={helpTooltips["navigation"]["engine"]} /></div><RunEngineSelector- effectiveDefaultEngine={effectiveDefaultEngine}value={data.engine}onChange={handleEngineChange}className="nopan w-72 text-xs"@@ -346,7 +343,6 @@ function NavigationEditorBody({<HelpTooltip content={helpTooltips["navigation"]["engine"]} /></div><RunEngineSelector- effectiveDefaultEngine={effectiveDefaultEngine}value={data.engine}onChange={handleEngineChange}className="nopan w-72 text-xs"diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/TaskNode/TaskEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/TaskNode/TaskEditor.tsxindex d8d43b302..58bf3a548 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/TaskNode/TaskEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/TaskNode/TaskEditor.tsx@@ -16,7 +16,6 @@ import { WorkflowBlockInput } from "@/components/WorkflowBlockInput";import { WorkflowBlockInputTextarea } from "@/components/WorkflowBlockInputTextarea";import { WorkflowDataSchemaInputGroup } from "@/components/DataSchemaInputGroup/WorkflowDataSchemaInputGroup";import { RunEngineSelector } from "@/components/EngineSelector";-import { useEffectiveDefaultEngine } from "../../hooks/useEffectiveDefaultEngine";import { ModelSelector } from "@/components/ModelSelector";import { ErrorCodeMappingEditor } from "@/routes/workflows/editor/ErrorCodeMappingEditor";@@ -78,7 +77,6 @@ function TaskEditorBody({ blockId }: { blockId: string }) {const data = taskNode?.data as TaskNodeData | undefined;const editable = data?.editable ?? false;const update = useUpdate<TaskNodeData>({ id: blockId, editable });- const effectiveDefaultEngine = useEffectiveDefaultEngine();const outputParameterKeys = getAvailableOutputParameterKeys(nodes,edges,@@ -254,7 +252,6 @@ function TaskEditorBody({ blockId }: { blockId: string }) {<HelpTooltip content={helpTooltips["task"]["engine"]} /></div><RunEngineSelector- effectiveDefaultEngine={effectiveDefaultEngine}value={data.engine}onChange={(value) => update({ engine: value })}className="nopan w-52 text-xs"diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/ValidationNode/ValidationEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/ValidationNode/ValidationEditor.tsxindex 74dadcaf5..8936adb1f 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/ValidationNode/ValidationEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/ValidationNode/ValidationEditor.tsx@@ -2,7 +2,6 @@ import { useEdges, useNodes, useNodesData } from "@xyflow/react";import { RunEngine } from "@/api/types";import { RunEngineSelector } from "@/components/EngineSelector";-import { useEffectiveDefaultEngine } from "../../hooks/useEffectiveDefaultEngine";import { HelpTooltip } from "@/components/HelpTooltip";import { ModelSelector } from "@/components/ModelSelector";import {@@ -82,7 +81,6 @@ function ValidationEditorBody({const parentLoopSkipsOnFail = getParentLoopSkipsOnFail(nodes, blockId);const isFirstWorkflowBlock = useIsFirstBlockInWorkflow({ id: blockId });const update = useUpdate<ValidationNodeData>({ id: blockId, editable });- const effectiveDefaultEngine = useEffectiveDefaultEngine();return (<div data-testid="validation-block-form" className="space-y-4">@@ -146,7 +144,6 @@ function ValidationEditorBody({</Label></div><RunEngineSelector- effectiveDefaultEngine={effectiveDefaultEngine}value={engine}onChange={(next) => update({ engine: next })}className="nopan w-52 text-xs"diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/types.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/types.tsindex 5eb0672d1..ebb15d836 100644--- a/skyvern-frontend/src/routes/workflows/editor/nodes/types.ts+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/types.ts@@ -15,6 +15,8 @@ export type NodeBaseData = {nextLoopOnFailure?: boolean;editable: boolean;model: WorkflowModel | null;+ // A person picked the block's engine; only task-like blocks read it.+ enginePinned?: boolean;showCode?: boolean;review?: BlockReviewAnnotation | FoldReviewAnnotation;ignoreWorkflowSystemPrompt?: boolean;diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ActionBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ActionBlockForm.test.tsxindex c6bd9c6f4..9ae820455 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ActionBlockForm.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ActionBlockForm.test.tsx@@ -7,10 +7,6 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";// exercises, and pulling the full barrel transitively imports every block// component plus their providers, none of which are needed to verify// ActionBlockForm's contract.-vi.mock("../../hooks/useEffectiveDefaultEngine", () => ({- useEffectiveDefaultEngine: () => null,-}));-vi.mock("../../nodes", () => ({isWorkflowBlockNode: (node: { type: string }) =>node.type !== "nodeAdder" && node.type !== "start",diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/FileDownloadBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/FileDownloadBlockForm.test.tsxindex df459aeac..f4f02e688 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/FileDownloadBlockForm.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/FileDownloadBlockForm.test.tsx@@ -31,10 +31,6 @@ const mockNodes = new Map<const mockEdges: Array<{ id: string; source: string; target: string }> = [];const updateNodeData = vi.fn();-vi.mock("../../hooks/useEffectiveDefaultEngine", () => ({- useEffectiveDefaultEngine: () => null,-}));-vi.mock("@xyflow/react", async () => {const actual =await vi.importActual<typeof import("@xyflow/react")>("@xyflow/react");diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/LoginBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/LoginBlockForm.test.tsxindex e929f8c10..9ae5fba39 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/LoginBlockForm.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/LoginBlockForm.test.tsx@@ -10,10 +10,6 @@ const mockEmailCredentials = vi.hoisted(() => ({microsoft: vi.fn(),}));-vi.mock("../../hooks/useEffectiveDefaultEngine", () => ({- useEffectiveDefaultEngine: () => null,-}));-vi.mock("@/hooks/useGoogleOAuthCredentials", async (importActual) => {const actual =await importActual<typeof import("@/hooks/useGoogleOAuthCredentials")>();diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ValidationBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ValidationBlockForm.test.tsxindex 12cd9cd73..515a78fee 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ValidationBlockForm.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ValidationBlockForm.test.tsx@@ -18,10 +18,6 @@ const mockNodes = new Map<>();const updateNodeData = vi.fn();-vi.mock("../../hooks/useEffectiveDefaultEngine", () => ({- useEffectiveDefaultEngine: () => null,-}));-vi.mock("@xyflow/react", async () => {const actual =await vi.importActual<typeof import("@xyflow/react")>("@xyflow/react");diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsxindex bc465d049..8c7ebac32 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx@@ -1,3 +1,4 @@+import { queryClient } from "@/api/QueryClient";import { apiWorkflowToSettings } from "@/routes/workflows/editor/apiWorkflowToSettings";import {useCallback,@@ -31,7 +32,10 @@ import {import { WorkflowVersion } from "../../hooks/useWorkflowVersionsQuery";import { WorkflowBlock } from "../../types/workflowTypes";import { FlowRenderer } from "../FlowRenderer";-import { getElements } from "../workflowEditorUtils";+import {+ getElements,+ workflowEffectiveDefaultEngine,+} from "../workflowEditorUtils";import {PANE_FIT_DEBOUNCE_MS,revealNodeViewport,@@ -85,6 +89,7 @@ function annotatedElements(JSON.parse(JSON.stringify(blocks)),apiWorkflowToSettings(version),false,+ workflowEffectiveDefaultEngine(version, queryClient),);return {edges,diff --git a/skyvern-frontend/src/routes/workflows/editor/useUpdate.test.tsx b/skyvern-frontend/src/routes/workflows/editor/useUpdate.test.tsxindex e29e3634f..47c95dd61 100644--- a/skyvern-frontend/src/routes/workflows/editor/useUpdate.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/useUpdate.test.tsx@@ -4,6 +4,8 @@ import { renderHook } from "@testing-library/react";import type { ReactNode } from "react";import { afterEach, describe, expect, test, vi } from "vitest";+import { RunEngine } from "@/api/types";+import { WorkflowScopeContext } from "./WorkflowScopeContext";import { useUpdate } from "./useUpdate";@@ -51,6 +53,24 @@ describe("useUpdate", () => {expect(updateNodeData).not.toHaveBeenCalled();});+ test("an engine pick marks only skyvern-1.0 as a person's pin", () => {+ const { result } = renderHook(+ () =>+ useUpdate<{ engine: RunEngine | null }>({ id: "n1", editable: true }),+ { wrapper: scopeWrapper(false) },+ );++ result.current({ engine: RunEngine.SkyvernV1 });+ result.current({ engine: null });+ result.current({ engine: RunEngine.SkyvernV3 });++ expect(updateNodeData.mock.calls.map(([, data]) => data)).toEqual([+ { engine: RunEngine.SkyvernV1, enginePinned: true },+ { engine: null, enginePinned: false },+ { engine: RunEngine.SkyvernV3, enginePinned: false },+ ]);+ });+test("does not persist when the node is not editable", () => {const { result } = renderHook(() => useUpdate<{ x: string }>({ id: "n1", editable: false }),diff --git a/skyvern-frontend/src/routes/workflows/editor/useUpdate.ts b/skyvern-frontend/src/routes/workflows/editor/useUpdate.tsindex ecddf01c0..5cd47bb71 100644--- a/skyvern-frontend/src/routes/workflows/editor/useUpdate.ts+++ b/skyvern-frontend/src/routes/workflows/editor/useUpdate.ts@@ -1,3 +1,4 @@+import { RunEngine } from "@/api/types";import { useWorkflowTitleStore } from "@/store/WorkflowTitleStore";import { refuseMutationDuringYamlCommit } from "@/store/WorkflowYamlEditorStore";import { useReactFlow } from "@xyflow/react";@@ -37,7 +38,13 @@ export function useUpdate<T extends Record<string, unknown>>({return false;if (options?.source !== "workflow")useWorkflowTitleStore.getState().recordCopilotGraphEdit();- updateNodeData(id, updates);+ // Only a pick in the engine dropdown marks skyvern-1.0 as a pin; a load carries the stored marker.+ updateNodeData(+ id,+ "engine" in updates+ ? { ...updates, enginePinned: updates.engine === RunEngine.SkyvernV1 }+ : updates,+ );return true;},[id, editable, readOnlyScope, updateNodeData],diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.test.ts b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.test.tsindex 4ac379cb8..01fb6b118 100644--- a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.test.ts+++ b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.test.ts@@ -1,3 +1,4 @@+import { QueryClient } from "@tanstack/react-query";import { describe, expect, test } from "vitest";import { ProxyLocation, RunEngine } from "@/api/types";@@ -17,11 +18,14 @@ import {getWorkflowErrors,pendingGoalChangesOf,withGoalUndoRecordsFrom,+ workflowEffectiveDefaultEngine,} from "./workflowEditorUtils";import { collectKnownErrorCodes } from "./nodes/StartNode/retryPolicyUtils";import { terminateNodeDefaultData } from "./nodes/TerminateNode/types";-function minimalTaskBlock(overrides: { engine?: RunEngine } = {}) {+function minimalTaskBlock(+ overrides: { engine?: RunEngine; engine_pinned?: boolean } = {},+) {return {block_type: "task",label: "b1",@@ -353,17 +357,21 @@ describe("terminate block error code round trip", () => {});function loadAndSave(- stored: RunEngine | undefined,+ stored: { engine?: RunEngine; engine_pinned?: boolean },effectiveDefaultEngine: RunEngine | null | undefined,) {const { nodes, edges } = getElements(- [minimalTaskBlock(stored ? { engine: stored } : {})],+ [minimalTaskBlock(stored)],SETTINGS,true,effectiveDefaultEngine,);const [saved] = getWorkflowBlocks(nodes, edges);- return (saved as { engine?: RunEngine | null }).engine;+ const { engine, engine_pinned } = saved as {+ engine?: RunEngine | null;+ engine_pinned?: boolean;+ };+ return { engine, engine_pinned };}describe("block engine load and save", () => {@@ -373,28 +381,75 @@ describe("block engine load and save", () => {expect(getWorkflowBlocks([node], [])[0]).toMatchObject({ engine: null });});+ const v1 = RunEngine.SkyvernV1;test.each([- ["unset", undefined, null, null],- ["skyvern-1.0 on a routed workflow", RunEngine.SkyvernV1, null, null],+ ["unset", {}, null, { engine: null }],+ [+ "an unmarked skyvern-1.0 on a routed workflow",+ { engine: v1 },+ null,+ { engine: null },+ ],+ [+ "a marked skyvern-1.0 on a routed workflow",+ { engine: v1, engine_pinned: true },+ null,+ { engine: v1, engine_pinned: true },+ ],["skyvern-1.0 on a chosen-engine workflow",- RunEngine.SkyvernV1,+ { engine: v1 },RunEngine.SkyvernV3,- RunEngine.SkyvernV1,+ { engine: v1 },],["skyvern-1.0 when the workflow's default is unknown",- RunEngine.SkyvernV1,+ { engine: v1 },undefined,- RunEngine.SkyvernV1,+ { engine: v1 },+ ],+ [+ "skyvern-2.0",+ { engine: RunEngine.SkyvernV2 },+ null,+ { engine: RunEngine.SkyvernV2 },+ ],+ [+ "skyvern-3.0",+ { engine: RunEngine.SkyvernV3 },+ null,+ { engine: RunEngine.SkyvernV3 },],- ["skyvern-2.0", RunEngine.SkyvernV2, null, RunEngine.SkyvernV2],- ["skyvern-3.0", RunEngine.SkyvernV3, null, RunEngine.SkyvernV3],- ])("%s loads and saves as %s", (_, stored, effective, expected) => {- expect(loadAndSave(stored, effective)).toBe(expected);+ ])(+ "%s round-trips through load and save",+ (_, stored, effective, expected) => {+ expect(loadAndSave(stored, effective)).toEqual(expected);+ },+ );++ test("a save response, which omits the workflow's default engine, shows an unmarked skyvern-1.0 as Default", () => {+ const queryClient = new QueryClient();+ queryClient.setQueryData(["workflow", "wpid_old"], {+ workflow_permanent_id: "wpid_old",+ effective_default_engine: null,+ });+ const saveResponse = { workflow_permanent_id: "wpid_old" };++ expect(+ loadAndSave(+ { engine: v1 },+ workflowEffectiveDefaultEngine(saveResponse, queryClient),+ ),+ ).toEqual({ engine: null });+ expect(+ workflowEffectiveDefaultEngine(+ { ...saveResponse, effective_default_engine: RunEngine.SkyvernV3 },+ queryClient,+ ),+ ).toBe(RunEngine.SkyvernV3);});- test("a copy drops a legacy skyvern-1.0 unless the source honours chosen engines; an export keeps it", () => {+ test("a copy drops a legacy skyvern-1.0 unless the source honours chosen engines or a person marked it; an export keeps it", () => {const source = {title: "Source",description: null,@@ -409,6 +464,13 @@ describe("block engine load and save", () => {...minimalTaskBlock({ engine: RunEngine.SkyvernV3 }),label: "b2",},+ {+ ...minimalTaskBlock({+ engine: RunEngine.SkyvernV1,+ engine_pinned: true,+ }),+ label: "b3",+ },],},} as unknown as WorkflowApiResponse;@@ -417,10 +479,18 @@ describe("block engine load and save", () => {(block) => (block as { engine?: RunEngine | null }).engine,);- expect(engines(convert(source, { asNewWorkflow: true }))).toEqual([+ const copy = convert(source, { asNewWorkflow: true });+ expect(engines(copy)).toEqual([null,RunEngine.SkyvernV3,+ RunEngine.SkyvernV1,]);+ expect(copy.workflow_definition.blocks[2]).toMatchObject({+ engine_pinned: true,+ });+ expect(copy.workflow_definition.blocks[0]).not.toHaveProperty(+ "engine_pinned",+ );expect(engines(convert(@@ -428,10 +498,11 @@ describe("block engine load and save", () => {{ asNewWorkflow: true },),),- ).toEqual([RunEngine.SkyvernV1, RunEngine.SkyvernV3]);+ ).toEqual([RunEngine.SkyvernV1, RunEngine.SkyvernV3, RunEngine.SkyvernV1]);expect(engines(convert(source))).toEqual([RunEngine.SkyvernV1,RunEngine.SkyvernV3,+ RunEngine.SkyvernV1,]);});});diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.tsindex b592481bf..a26c67bca 100644--- a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts+++ b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts@@ -2,6 +2,7 @@ import { useWorkflowTitleStore } from "@/store/WorkflowTitleStore";import { buildWorkflowSaveRequest } from "./workflowYamlDocument";import { normalizeRetryPolicy } from "./nodes/StartNode/retryPolicyUtils";import Dagre from "@dagrejs/dagre";+import type { QueryClient } from "@tanstack/react-query";import {applyNodeChanges,applyEdgeChanges,@@ -697,18 +698,83 @@ function declaredSmtpParameterKey(return parameter.key;}-// A stored skyvern-1.0 is only a pin where the workflow honours chosen engines; elsewhere it is the-// routed Default. `undefined` means the workflow's semantics are unknown, so the stored engine is kept.+// A stored skyvern-1.0 is a pin where the workflow honours chosen engines or a person marked it; elsewhere+// it is the routed Default. `undefined` means the workflow's semantics are unknown, so the engine is kept.function blockEngineForWorkflow(engine: RunEngine | null | undefined,effectiveDefaultEngine: RunEngine | null | undefined,+ enginePinned: boolean = false,): RunEngine | null {- if (engine === RunEngine.SkyvernV1 && effectiveDefaultEngine === null) {+ if (+ engine === RunEngine.SkyvernV1 &&+ !enginePinned &&+ effectiveDefaultEngine === null+ ) {return null;}return engine ?? null;}+// Only the detail GET computes effective_default_engine; save responses and version listings omit it. It is a+// property of the workflow rather than the version, so the cached detail answers for any version of it.+function workflowEffectiveDefaultEngine(+ workflow: Pick<+ WorkflowApiResponse,+ "workflow_permanent_id" | "effective_default_engine"+ >,+ queryClient: QueryClient,+): RunEngine | null | undefined {+ if ("effective_default_engine" in workflow) {+ return workflow.effective_default_engine;+ }+ return queryClient.getQueryData<WorkflowApiResponse>([+ "workflow",+ workflow.workflow_permanent_id,+ ])?.effective_default_engine;+}++type EngineBearingBlock = {+ engine: RunEngine | null;+ engine_pinned?: boolean;+};++function blockEngineNodeData(+ block: EngineBearingBlock,+ effectiveDefaultEngine: RunEngine | null | undefined,+) {+ return {+ engine: blockEngineForWorkflow(+ block.engine,+ effectiveDefaultEngine,+ block.engine_pinned,+ ),+ enginePinned: block.engine_pinned ?? false,+ };+}++// The marker is written only beside skyvern-1.0, and only when set, so an unmarked block's YAML is unchanged.+function engineYAML(engine: RunEngine | null, enginePinned?: boolean) {+ return {+ engine,+ ...(enginePinned &&+ engine === RunEngine.SkyvernV1 && { engine_pinned: true }),+ };+}++function blockEngineYAML(+ block: EngineBearingBlock,+ effectiveDefaultEngine: RunEngine | null | undefined,+) {+ return engineYAML(+ blockEngineForWorkflow(+ block.engine,+ effectiveDefaultEngine,+ block.engine_pinned,+ ),+ block.engine_pinned,+ );+}+function convertToNode(identifiers: { id: string; parentId?: string },block: WorkflowBlock,@@ -781,7 +847,7 @@ function convertToNode(terminateCriterion: block.terminate_criterion ?? "",includeActionHistoryInVerification:block.include_action_history_in_verification ?? false,- engine: blockEngineForWorkflow(block.engine, effectiveDefaultEngine),+ ...blockEngineNodeData(block, effectiveDefaultEngine),},};}@@ -829,7 +895,7 @@ function convertToNode(terminateCriterion: block.terminate_criterion ?? "",parameterKeys: (block.parameters ?? []).map((p) => p.key),disableCache: block.disable_cache ?? false,- engine: blockEngineForWorkflow(block.engine, effectiveDefaultEngine),+ ...blockEngineNodeData(block, effectiveDefaultEngine),},};}@@ -850,7 +916,7 @@ function convertToNode(totpIdentifier: block.totp_identifier ?? null,totpVerificationUrl: block.totp_verification_url ?? null,disableCache: block.disable_cache ?? false,- engine: blockEngineForWorkflow(block.engine, effectiveDefaultEngine),+ ...blockEngineNodeData(block, effectiveDefaultEngine),},};}@@ -875,7 +941,7 @@ function convertToNode(maxStepsOverride: block.max_steps_per_run ?? null,completeCriterion: block.complete_criterion ?? "",terminateCriterion: block.terminate_criterion ?? "",- engine: blockEngineForWorkflow(block.engine, effectiveDefaultEngine),+ ...blockEngineNodeData(block, effectiveDefaultEngine),legacyV2Available: isV2Engine,includeActionHistoryInVerification:block.include_action_history_in_verification ?? false,@@ -925,7 +991,7 @@ function convertToNode(maxRetries: block.max_retries ?? null,maxStepsOverride: block.max_steps_per_run ?? null,disableCache: block.disable_cache ?? false,- engine: blockEngineForWorkflow(block.engine, effectiveDefaultEngine),+ ...blockEngineNodeData(block, effectiveDefaultEngine),exportEnabled: block.export_enabled ?? false,exportDataSchema:block.export_data_schema == null@@ -956,7 +1022,7 @@ function convertToNode(terminateCriterion: block.terminate_criterion ?? "",includeActionHistoryInVerification:block.include_action_history_in_verification ?? false,- engine: blockEngineForWorkflow(block.engine, effectiveDefaultEngine),+ ...blockEngineNodeData(block, effectiveDefaultEngine),},};}@@ -1000,7 +1066,7 @@ function convertToNode(totpVerificationUrl: block.totp_verification_url ?? null,disableCache: block.disable_cache ?? false,maxStepsOverride: block.max_steps_per_run ?? null,- engine: blockEngineForWorkflow(block.engine, effectiveDefaultEngine),+ ...blockEngineNodeData(block, effectiveDefaultEngine),downloadTimeout: block.download_timeout ?? null, // secondsdownloadTarget: block.download_target ?? "website",path: block.path ?? "{{ workflow_run_id }}",@@ -3183,7 +3249,7 @@ function getWorkflowBlock(disable_cache: node.data.disableCache ?? false,include_action_history_in_verification:node.data.includeActionHistoryInVerification,- engine: node.data.engine,+ ...engineYAML(node.data.engine, node.data.enginePinned),};}case "taskv2": {@@ -3209,7 +3275,7 @@ function getWorkflowBlock(string> | null,parameter_keys: node.data.parameterKeys,- engine: node.data.engine,+ ...engineYAML(node.data.engine, node.data.enginePinned),};}case "human_interaction": {@@ -3249,7 +3315,7 @@ function getWorkflowBlock(totp_identifier: node.data.totpIdentifier,totp_verification_url: node.data.totpVerificationUrl,disable_cache: node.data.disableCache ?? false,- engine: node.data.engine,+ ...engineYAML(node.data.engine, node.data.enginePinned),};}case "navigation": {@@ -3289,7 +3355,7 @@ function getWorkflowBlock(disable_cache: node.data.disableCache ?? false,complete_criterion: node.data.completeCriterion,terminate_criterion: node.data.terminateCriterion,- engine: node.data.engine,+ ...engineYAML(node.data.engine, node.data.enginePinned),include_action_history_in_verification:node.data.includeActionHistoryInVerification,};@@ -3308,7 +3374,7 @@ function getWorkflowBlock(max_steps_per_run: node.data.maxStepsOverride,parameter_keys: node.data.parameterKeys,disable_cache: node.data.disableCache ?? false,- engine: node.data.engine,+ ...engineYAML(node.data.engine, node.data.enginePinned),// export_data_schema (like export_file_name/export_records below) is// saved regardless of export_enabled -- the backend already no-ops on// all three while export is off, and gating persistence here would@@ -3342,7 +3408,7 @@ function getWorkflowBlock(terminate_criterion: node.data.terminateCriterion,include_action_history_in_verification:node.data.includeActionHistoryInVerification,- engine: node.data.engine,+ ...engineYAML(node.data.engine, node.data.enginePinned),};}case "wait": {@@ -3380,7 +3446,7 @@ function getWorkflowBlock(totp_identifier: node.data.totpIdentifier,totp_verification_url: node.data.totpVerificationUrl,disable_cache: node.data.disableCache ?? false,- engine: node.data.engine,+ ...engineYAML(node.data.engine, node.data.enginePinned),download_timeout: node.data.downloadTimeout, // seconds...(node.data.downloadTarget &&node.data.downloadTarget !== "website" && {@@ -4759,7 +4825,7 @@ function convertBlocksToBlockYAML(disable_cache: block.disable_cache ?? false,include_action_history_in_verification:block.include_action_history_in_verification,- engine: blockEngineForWorkflow(block.engine, effectiveDefaultEngine),+ ...blockEngineYAML(block, effectiveDefaultEngine),};return blockYaml;}@@ -4784,7 +4850,7 @@ function convertBlocksToBlockYAML(terminate_criterion: block.terminate_criterion,error_code_mapping: block.error_code_mapping,parameter_keys: (block.parameters ?? []).map((p) => p.key),- engine: blockEngineForWorkflow(block.engine, effectiveDefaultEngine),+ ...blockEngineYAML(block, effectiveDefaultEngine),};return blockYaml;}@@ -4836,7 +4902,7 @@ function convertBlocksToBlockYAML(totp_identifier: block.totp_identifier,totp_verification_url: block.totp_verification_url,disable_cache: block.disable_cache ?? false,- engine: blockEngineForWorkflow(block.engine, effectiveDefaultEngine),+ ...blockEngineYAML(block, effectiveDefaultEngine),};return blockYaml;}@@ -4846,7 +4912,7 @@ function convertBlocksToBlockYAML(block_type: "navigation",url: block.url,title: block.title,- engine: blockEngineForWorkflow(block.engine, effectiveDefaultEngine),+ ...blockEngineYAML(block, effectiveDefaultEngine),model: block.model,navigation_goal: block.navigation_goal,error_code_mapping: block.error_code_mapping,@@ -4877,7 +4943,7 @@ function convertBlocksToBlockYAML(max_steps_per_run: block.max_steps_per_run,parameter_keys: (block.parameters ?? []).map((p) => p.key),disable_cache: block.disable_cache ?? false,- engine: blockEngineForWorkflow(block.engine, effectiveDefaultEngine),+ ...blockEngineYAML(block, effectiveDefaultEngine),export_enabled: block.export_enabled ?? false,export_data_schema: block.export_data_schema ?? null,export_file_name: block.export_file_name ?? null,@@ -4903,7 +4969,7 @@ function convertBlocksToBlockYAML(terminate_criterion: block.terminate_criterion,include_action_history_in_verification:block.include_action_history_in_verification,- engine: blockEngineForWorkflow(block.engine, effectiveDefaultEngine),+ ...blockEngineYAML(block, effectiveDefaultEngine),};return blockYaml;}@@ -4939,7 +5005,7 @@ function convertBlocksToBlockYAML(totp_identifier: block.totp_identifier,totp_verification_url: block.totp_verification_url,disable_cache: block.disable_cache ?? false,- engine: blockEngineForWorkflow(block.engine, effectiveDefaultEngine),+ ...blockEngineYAML(block, effectiveDefaultEngine),download_timeout: null, // seconds...(block.download_target &&block.download_target !== "website" && {@@ -5957,6 +6023,7 @@ function getParentLoopSkipsOnFail(export {blockEngineForWorkflow,+ workflowEffectiveDefaultEngine,containsJinjaReference,convert,convertEchoParameters,diff --git a/skyvern-frontend/src/routes/workflows/importWorkflowYaml.test.ts b/skyvern-frontend/src/routes/workflows/importWorkflowYaml.test.tsindex c8b5edc01..0132e7f73 100644--- a/skyvern-frontend/src/routes/workflows/importWorkflowYaml.test.ts+++ b/skyvern-frontend/src/routes/workflows/importWorkflowYaml.test.ts@@ -233,6 +233,15 @@ describe("stripLegacyEngineFromYaml", () => {});});+ it("keeps a marked skyvern-1.0 pin while stripping the unmarked legacy lines around it", () => {+ const pinned =+ " - block_type: login\n label: p\n engine: skyvern-1.0\n engine_pinned: true\n";+ expect(stripLegacyEngineFromYaml(legacy + pinned)).toEqual({+ yaml: withoutLegacy.join("\n") + pinned,+ strippedLegacyEngines: true,+ });+ });+it("strips a legacy export whose validation block predates its engine key", () => {const bare = " - block_type: validation\n label: g\n";expect(stripLegacyEngineFromYaml(legacy + bare)).toEqual({diff --git a/skyvern-frontend/src/routes/workflows/importWorkflowYaml.ts b/skyvern-frontend/src/routes/workflows/importWorkflowYaml.tsindex e0c7dbfc7..6970b9d40 100644--- a/skyvern-frontend/src/routes/workflows/importWorkflowYaml.ts+++ b/skyvern-frontend/src/routes/workflows/importWorkflowYaml.ts@@ -152,6 +152,8 @@ function legacyEngineSpans(text: string, blocks: unknown): Span[] | null {return null;}const spansBefore = spans.length;+ // A marked skyvern-1.0 is a person's pick: keep it, and do not read it as new-editor evidence.+ const pinned = block.get("engine_pinned") === true;for (const [index, pair] of block.items.entries()) {const { key, value } = pair;if (@@ -159,6 +161,7 @@ function legacyEngineSpans(text: string, blocks: unknown): Span[] | null {key.value !== "engine" ||!isScalar(value) ||typeof value.value !== "string" ||+ pinned ||blockEngineForWorkflow(value.value as RunEngine, null) !== null) {continue;@@ -197,6 +200,7 @@ function legacyEngineSpans(text: string, blocks: unknown): Span[] | null {ENGINE_BLOCK_TYPES.has(blockType) &&// Validation blocks were exported without an engine key until #16538, so there an absent key is no evidence.(block.has("engine") || blockType !== "validation") &&+ !pinned &&spans.length === spansBefore) {return null;diff --git a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowTypes.tsindex 5572a3fcd..00247e1e1 100644--- a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts+++ b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts@@ -370,6 +370,7 @@ export type TaskBlock = WorkflowBlockBase & {disable_cache?: boolean;include_action_history_in_verification: boolean;engine: RunEngine | null;+ engine_pinned?: boolean;};export type Taskv2Block = WorkflowBlockBase & {@@ -502,6 +503,7 @@ export type ValidationBlock = WorkflowBlockBase & {parameters: Array<WorkflowParameter>;disable_cache?: boolean;engine: RunEngine | null;+ engine_pinned?: boolean;};export type HumanInteractionBlock = WorkflowBlockBase & {@@ -542,6 +544,7 @@ export type ActionBlock = WorkflowBlockBase & {totp_identifier?: string | null;disable_cache?: boolean;engine: RunEngine | null;+ engine_pinned?: boolean;};export type NavigationBlock = WorkflowBlockBase & {@@ -561,6 +564,7 @@ export type NavigationBlock = WorkflowBlockBase & {complete_criterion: string | null;terminate_criterion: string | null;engine: RunEngine | null;+ engine_pinned?: boolean;include_action_history_in_verification: boolean;};@@ -575,6 +579,7 @@ export type ExtractionBlock = WorkflowBlockBase & {parameters: Array<WorkflowParameter>;disable_cache?: boolean;engine: RunEngine | null;+ engine_pinned?: boolean;export_enabled?: boolean;export_data_schema?: Record<string, unknown> | null;export_file_name?: string | null;@@ -597,6 +602,7 @@ export type LoginBlock = WorkflowBlockBase & {terminate_criterion: string | null;include_action_history_in_verification: boolean;engine: RunEngine | null;+ engine_pinned?: boolean;};export type WaitBlock = WorkflowBlockBase & {@@ -624,6 +630,7 @@ export type FileDownloadBlock = WorkflowBlockBase & {totp_identifier?: string | null;disable_cache?: boolean;engine: RunEngine | null;+ engine_pinned?: boolean;download_timeout: number | null; // secondsdownload_target: "website" | "s3" | "azure" | "google_drive" | "sftp";path: string;diff --git a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.tsindex 50beb99b7..979aa5bf6 100644--- a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts+++ b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts@@ -213,6 +213,7 @@ export type TaskBlockYAML = BlockYAMLBase & {terminate_criterion: string | null;include_action_history_in_verification: boolean;engine: RunEngine | null;+ engine_pinned?: boolean;};export type Taskv2BlockYAML = BlockYAMLBase & {@@ -232,6 +233,7 @@ export type ValidationBlockYAML = BlockYAMLBase & {error_code_mapping: Record<string, string> | null;parameter_keys?: Array<string> | null;engine: RunEngine | null;+ engine_pinned?: boolean;};export type HumanInteractionBlockYAML = BlockYAMLBase & {@@ -271,6 +273,7 @@ export type ActionBlockYAML = BlockYAMLBase & {totp_identifier?: string | null;disable_cache: boolean;engine: RunEngine | null;+ engine_pinned?: boolean;};export type NavigationBlockYAML = BlockYAMLBase & {@@ -290,6 +293,7 @@ export type NavigationBlockYAML = BlockYAMLBase & {complete_criterion: string | null;terminate_criterion: string | null;engine: RunEngine | null;+ engine_pinned?: boolean;model: WorkflowModel | null;include_action_history_in_verification: boolean;};@@ -305,6 +309,7 @@ export type ExtractionBlockYAML = BlockYAMLBase & {parameter_keys?: Array<string> | null;disable_cache: boolean;engine: RunEngine | null;+ engine_pinned?: boolean;export_enabled?: boolean;export_data_schema?: Record<string, unknown> | null;export_file_name?: string | null;@@ -327,6 +332,7 @@ export type LoginBlockYAML = BlockYAMLBase & {terminate_criterion: string | null;include_action_history_in_verification: boolean;engine: RunEngine | null;+ engine_pinned?: boolean;};export type WaitBlockYAML = BlockYAMLBase & {@@ -376,6 +382,7 @@ export type FileDownloadBlockYAML = BlockYAMLBase & {totp_identifier?: string | null;disable_cache: boolean;engine: RunEngine | null;+ engine_pinned?: boolean;download_timeout?: number | null;};diff --git a/skyvern/config.py b/skyvern/config.pyindex 4089c49ed..d2467f354 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -317,6 +317,9 @@ class Settings(BaseSettings):# also permits plaintext http:// endpoints, for self-hosted deployments pointing at an# object store on their own network (e.g. MinIO).ALLOW_S3_ENDPOINT_INTERNAL_HOSTS: bool = False+ # Let SSRF-checked requests (webhooks, TOTP, downloads) use HTTP(S)_PROXY. A forward proxy resolves the host+ # itself, so this gives up DNS-rebinding protection; enable only where egress must go through a proxy.+ OUTBOUND_TRUST_ENV_PROXY: bool = False# Secret key for JWT. Please generate your own secret key in productionSECRET_KEY: str = "PLACEHOLDER"diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex 67309adfc..7a7c429c5 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -11,7 +11,6 @@ from dataclasses import dataclass, fieldfrom datetime import datetime, timedelta, timezonefrom typing import TYPE_CHECKING, Any, Callable, Literal, Protocol, TypedDict-import aiohttpimport httpximport structlogfrom cachetools import TTLCache@@ -224,7 +223,7 @@ class TOTPVerificationResponse:"""Normalized response shape for the TOTP verification seam.Decouples the seam contract from any specific HTTP client so the OSS- direct path (aiohttp) and the cloud proxy path (NATEgressProxyClient)+ direct path (pinned httpx) and the cloud proxy path (NATEgressProxyClient)can both produce a response the helper consumes the same way."""@@ -2665,15 +2664,28 @@ class AgentFunction:headers: dict[str, str],timeout_seconds: float = 30.0,organization_id: str | None = None,+ resolved_ips: tuple[str, ...] | None = None,+ method: str = "POST",) -> TOTPVerificationResponse:- async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout_seconds)) as session:- async with session.post(url, data=payload, headers=headers) as response:- body = await response.text()- return TOTPVerificationResponse(- status_code=response.status,- body=body,- headers=dict(response.headers),+ # Redirects are left to the caller, which validates and pins each hop. httpx timeouts are per+ # operation, so a slow-drip endpoint needs the outer cap to stay within the budget.+ try:+ async with asyncio.timeout(timeout_seconds), pinned_ip_client(resolved_ips) as client:+ response = await client.request(+ method,+ url,+ content=payload or None,+ headers=headers,+ timeout=httpx.Timeout(timeout_seconds),)+ except TimeoutError as e:+ raise httpx.ReadTimeout(f"TOTP verification request exceeded {timeout_seconds}s") from e+ return TOTPVerificationResponse(+ status_code=response.status_code,+ body=response.text,+ # Original casing, as the earlier aiohttp path returned; otp_service's Content-Type gate is case-sensitive.+ headers={key.decode("latin-1"): value.decode("latin-1") for key, value in response.headers.raw},+ )async def upload_file_to_customer_storage(self,diff --git a/skyvern/forge/sdk/copilot/tools/banned_blocks.py b/skyvern/forge/sdk/copilot/tools/banned_blocks.pyindex 9ac769b18..624971aaf 100644--- a/skyvern/forge/sdk/copilot/tools/banned_blocks.py+++ b/skyvern/forge/sdk/copilot/tools/banned_blocks.py@@ -23,6 +23,7 @@ from skyvern.forge.sdk.copilot.runtime import AgentContextfrom skyvern.forge.sdk.copilot.tracing_setup import copilot_spanfrom skyvern.forge.sdk.copilot.workflow_yaml import dump_workflow_yamlfrom skyvern.forge.sdk.schemas.credentials import CredentialType, TotpType+from skyvern.schemas.runs import RunEnginefrom skyvern.utils.yaml_loader import safe_load_no_datesfrom skyvern.webeye.utils.captcha_solver import MAX_IMAGE_CAPTCHA_READS@@ -664,6 +665,7 @@ def _validator_relevant_fingerprint(block: Mapping[str, object]) -> tuple[objectreturn (block_type,block.get("engine"),+ bool(block.get("engine_pinned")),block.get("complete_on_download"),block.get("loop_variable_reference"),block.get("loop_over_parameter_key"),@@ -838,25 +840,56 @@ class AuthoringValidation:workflow_yaml: str = ""-def _prior_block_engines(prior_workflow_yaml: str | None) -> dict[str, str]:- """The engine each prior label already runs on."""- engines: dict[str, str] = {}- for label, block in _walk_labelled_blocks(_parse_workflow_blocks(prior_workflow_yaml) or []):- engine = block.get("engine")- if label is not None and isinstance(engine, str) and engine:- engines[label] = engine- return engines+def _carry_engine_pins(blocks: list[Any], prior_blocks: Mapping[str, Mapping[str, object]]) -> bool:+ """Keep a person's skyvern-1.0 pin on a block re-emitted at skyvern-1.0 without the marker."""+ carried = False+ for label, block in _walk_labelled_blocks(blocks):+ prior = prior_blocks.get(label) if label is not None else None+ if (+ prior is not None+ and prior.get("engine_pinned")+ and isinstance(block, dict)+ and block.get("engine") == RunEngine.skyvern_v1.value+ and not block.get("engine_pinned")+ ):+ block["engine_pinned"] = True+ carried = True+ return carried+++def _strip_unearned_pins(blocks: list[Any], prior_blocks: Mapping[str, Mapping[str, object]]) -> bool:+ """A marker survives only where the prior block already carried it at skyvern-1.0 and the block stays there.++ The marker records a person's pick, so a model submission can keep one but never create one.+ """+ stripped = False+ for label, block in _walk_labelled_blocks(blocks):+ if not isinstance(block, dict) or "engine_pinned" not in block:+ continue+ prior = prior_blocks.get(label) if label is not None else None+ earned = (+ prior is not None+ and prior.get("engine_pinned") is True+ and prior.get("engine") == RunEngine.skyvern_v1.value+ and block.get("engine") == RunEngine.skyvern_v1.value+ and block.get("engine_pinned") is True+ )+ if not earned:+ block.pop("engine_pinned")+ stripped = True+ return strippeddef _pin_agent_block_engines(changed: list[tuple[str, Mapping[str, object]]],- prior_engines: Mapping[str, str],+ prior_blocks: Mapping[str, Mapping[str, object]],) -> bool:"""Fill the engine on every changed agent-family block that names none.- A label the workflow already had keeps the engine it already ran on: omitting the field is how a- whole-document write carries a block it did not touch, not a request to move it to another- engine. Only a label the workflow did not have is pinned to Task V3.+ A label the workflow already had keeps the engine it already ran on, and a person's skyvern-1.0+ pin with it: omitting the field is how a whole-document write carries a block it did not touch,+ and the prior is the editor's current draft, where a Default pick already has no engine. Only a+ label the workflow did not have is pinned to Task V3."""pinned = Falsefor label, block in changed:@@ -864,8 +897,16 @@ def _pin_agent_block_engines(if not isinstance(raw_type, str) or not isinstance(block, dict):continueblock_type = normalize_copilot_block_type_alias(raw_type.strip().lower())- if block_type in _AGENT_FAMILY_BLOCK_TYPES and not block.get("engine"):- block["engine"] = prior_engines.get(label, _TASK_V3_ENGINE)+ if block_type not in _AGENT_FAMILY_BLOCK_TYPES or block.get("engine"):+ continue+ prior = prior_blocks.get(label)+ if prior is None:+ block["engine"] = _TASK_V3_ENGINE+ pinned = True+ elif isinstance(prior.get("engine"), str) and prior["engine"]:+ block["engine"] = prior["engine"]+ if prior.get("engine_pinned") and prior["engine"] == RunEngine.skyvern_v1.value:+ block["engine_pinned"] = Truepinned = Truereturn pinned@@ -891,6 +932,12 @@ def reject_authoring_violations(parsed = Nonedefinition = parsed.get("workflow_definition") if isinstance(parsed, dict) else Noneblocks = definition.get("blocks") if isinstance(definition, dict) else None+ prior_blocks = {+ label: block+ for label, block in _walk_labelled_blocks(_parse_workflow_blocks(prior_yaml) or [])+ if label is not None+ }+ carried_pins = isinstance(blocks, list) and _carry_engine_pins(blocks, prior_blocks)changed = _changed_blocks_in(blocks, prior_yaml, capability) if isinstance(blocks, list) else []violations: list[AuthoringPolicyViolation] = []run_names = workflow_run_names(submitted_yaml)@@ -902,13 +949,10 @@ def reject_authoring_violations()if not violations:workflow_yaml = submitted_yaml- if isinstance(parsed, dict) and _pin_agent_block_engines(changed, _prior_block_engines(prior_yaml)):+ filled_engines = _pin_agent_block_engines(changed, prior_blocks)+ stripped_pins = isinstance(blocks, list) and _strip_unearned_pins(blocks, prior_blocks)+ if isinstance(parsed, dict) and (carried_pins or filled_engines or stripped_pins):workflow_yaml = dump_workflow_yaml(parsed)- prior_blocks = {- label: block- for label, block in _walk_labelled_blocks(_parse_workflow_blocks(prior_yaml) or [])- if label is not None- }changed_ids = {id(block) for _label, block in changed}rewritten = [(label, block)diff --git a/skyvern/forge/sdk/copilot/workflow_yaml.py b/skyvern/forge/sdk/copilot/workflow_yaml.pyindex aa4281535..f8200f779 100644--- a/skyvern/forge/sdk/copilot/workflow_yaml.py+++ b/skyvern/forge/sdk/copilot/workflow_yaml.py@@ -1386,8 +1386,21 @@ def preserve_untouched_block_configuration(fields: dict[str, Any] = {}# workflowEditorUtils.blockEngineForWorkflow omits V1 under the legacy default engine.# V2/V3 are explicit pins: clearing either selects Default and must survive the repair.- if block.get("engine") is None and prior.get("engine") == RunEngine.skyvern_v1.value:+ # The current editor exports a pin as skyvern-1.0 plus the marker, so a pinned block with no engine is a+ # Default pick and must not be re-pinned.+ if (+ block.get("engine") is None+ and prior.get("engine") == RunEngine.skyvern_v1.value+ and not prior.get("engine_pinned")+ ):fields["engine"] = prior["engine"]+ if (+ prior.get("engine_pinned")+ and prior.get("engine") == RunEngine.skyvern_v1.value+ and block.get("engine") == RunEngine.skyvern_v1.value+ and not block.get("engine_pinned")+ ):+ fields["engine_pinned"] = True# The editor writes node.data.label as a task block's title.if "title" in prior and block.get("title") == label and prior["title"] != label:fields["title"] = prior["title"]diff --git a/skyvern/forge/sdk/experimentation/workflow_block_engine.py b/skyvern/forge/sdk/experimentation/workflow_block_engine.pyindex 11f227db0..1629299b7 100644--- a/skyvern/forge/sdk/experimentation/workflow_block_engine.py+++ b/skyvern/forge/sdk/experimentation/workflow_block_engine.py@@ -51,6 +51,9 @@ class WorkflowBlockEngineRouteReason(StrEnum):# chosen and is honored as written (``chosen_engine``).new_workflow_v3_default = "new_workflow_v3_default"chosen_engine = "chosen_engine"+ # Before that cutoff, a block a person pinned to skyvern-1.0 keeps the run out of the A/B; labelled+ # apart from ``ineligible`` so reads can count and drop these runs by this value alone.+ pinned_v1_engine = "pinned_v1_engine"ineligible = "ineligible"disabled = "disabled"flag_undefined = "flag_undefined"@@ -232,6 +235,7 @@ async def resolve_workflow_block_engine_arm(trigger_type: WorkflowRunTriggerType | None,ineligibility_reason: V3AbIneligibleReason | None,takes_default_engine: bool | None,+ pinned_v1_blocks: int = 0,) -> None:"""Resolve the workflow-block engine A/B once at execution start and pin the arm on the context.@@ -259,6 +263,9 @@ async def resolve_workflow_block_engine_arm(per-call throwaways several endpoints mint and run in one request: most of those run while stillauto_generated, and the job-recipe endpoints build a published definition, so neither test alonecovers them.++ ``pinned_v1_blocks`` counts blocks a person pinned to skyvern-1.0 (see ``pinned_v1_block_count``);+ eligibility already keeps such a run out of the A/B, and this labels it ``pinned_v1_engine``."""if context.workflow_block_engine_resolved_run_id == workflow_run_id:return@@ -276,7 +283,11 @@ async def resolve_workflow_block_engine_arm(honors_chosen_engine = Falserun_is_eligible = ineligibility_reason is Nonebilling_tier: BillingTier | None = None- route_reason = WorkflowBlockEngineRouteReason.ineligible+ route_reason = (+ WorkflowBlockEngineRouteReason.pinned_v1_engine+ if pinned_v1_blocks+ else WorkflowBlockEngineRouteReason.ineligible+ )chosen_engine_candidate = (settings.TASK_V3_CHOSEN_ENGINE_CUTOFF is not Noneand takes_default_engine is not None@@ -378,6 +389,7 @@ async def resolve_workflow_block_engine_arm(# already stopped -- so the field means "the tier this run was bucketed on" and never# doubles as "nobody looked".billing_tier=engine_arm_log_value(billing_tier),+ pinned_v1_blocks=pinned_v1_blocks,)diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex 8ecb82cfb..98ec7ef38 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -1941,6 +1941,10 @@ def _engine_is_unset(engine: RunEngine | None) -> bool:return engine is None+def _engine_pin_is_unset(engine_pinned: bool) -> bool:+ return not engine_pinned++class BaseTaskBlock(Block):task_type: str = TaskType.generalurl: str | None = None@@ -1948,6 +1952,9 @@ class BaseTaskBlock(Block):# Left out of the dump when unset, so a stored definition stays readable by an image whose engine# field still rejects null (a rollout or a revert).engine: RunEngine | None = Field(default=None, exclude_if=_engine_is_unset)+ # A person chose skyvern-1.0. Before the chosen-engine cutoff a stored skyvern-1.0 without this is+ # usually the old editor's spelling of Default, so only a marked one is honored as a pin.+ engine_pinned: bool = Field(default=False, exclude_if=_engine_pin_is_unset)complete_criterion: str | None = Nonecomplete_criterion_is_untrusted: bool = Falseterminate_criterion: str | None = None@@ -2039,7 +2046,7 @@ class BaseTaskBlock(Block):the recorded engine cannot disagree with the one that ran. A block pinned to a non-defaultengine is honored as-authored, and a block the eligibility check never saw is left alone;neither is ever rerouted. An unset engine routes like skyvern_v1, except in a run that honors the- chosen engine, where an explicit skyvern_v1 is a pin too.+ chosen engine or on a block whose skyvern_v1 a person pinned."""declared = self.engine or RunEngine.skyvern_v1if (@@ -2053,7 +2060,7 @@ class BaseTaskBlock(Block):):return declaredif self.engine is not None and (- self.engine != RunEngine.skyvern_v1 or run_honors_chosen_engine(workflow_run_id)+ self.engine != RunEngine.skyvern_v1 or self.engine_pinned or run_honors_chosen_engine(workflow_run_id)):return self.enginereturn workflow_block_engine_override(workflow_run_id) or declared@@ -15995,31 +16002,26 @@ class HttpRequestBlock(Block):# Parameters for templatingparameters: list[PARAMETER_TYPE] = []- # Allowed directories for local file access (class variable, not a Pydantic field)- _allowed_dirs: ClassVar[list[str] | None] = None_confined_references: list[tuple[str, str | None, str, str]] = PrivateAttr(default_factory=list)TEMPLATABLE_FIELDS: ClassVar[frozenset[str]] = frozenset({"body", "download_filename", "files", "headers", "url"})- @classmethod- def get_allowed_dirs(cls) -> list[str]:- """Get the list of allowed directories for local file access.- Computed once and cached for performance.- """- if cls._allowed_dirs is None:- allowed_dirs: list[str] = []- if settings.ARTIFACT_STORAGE_PATH:- allowed_dirs.append(os.path.abspath(settings.ARTIFACT_STORAGE_PATH))- if settings.VIDEO_PATH:- allowed_dirs.append(os.path.abspath(settings.VIDEO_PATH))- if settings.HAR_PATH:- allowed_dirs.append(os.path.abspath(settings.HAR_PATH))- if settings.LOG_PATH:- allowed_dirs.append(os.path.abspath(settings.LOG_PATH))- if settings.DOWNLOAD_PATH:- allowed_dirs.append(os.path.abspath(settings.DOWNLOAD_PATH))- cls._allowed_dirs = allowed_dirs- return cls._allowed_dirs or []+ @staticmethod+ def get_allowed_dirs(workflow_run_id: str, organization_id: str | None) -> list[str]:+ run_download_id = resolve_run_download_id(skyvern_context.current(), fallback_run_id=workflow_run_id)+ allowed_dirs = [+ os.path.realpath(download_dir_path_for_run(run_id))+ for run_id in dict.fromkeys((workflow_run_id, run_download_id))+ if run_id+ ]+ if organization_id and settings.ARTIFACT_STORAGE_PATH:+ artifact_root = settings.ARTIFACT_STORAGE_PATH+ allowed_dirs += [+ os.path.realpath(os.path.join(artifact_root, settings.ENV, organization_id)),+ os.path.realpath(os.path.join(artifact_root, organization_id)),+ os.path.realpath(os.path.join(artifact_root, "downloads", settings.ENV, organization_id)),+ ]+ return allowed_dirsdef get_all_parameters(self,@@ -16382,7 +16384,7 @@ class HttpRequestBlock(Block):self.headers["Content-Type"] = "application/json"# Download files from HTTP URLs or S3 URIs if needed- # Also allow local files from allowed directories (ARTIFACT_STORAGE_PATH, VIDEO_PATH, HAR_PATH, LOG_PATH)+ # Local files are allowed only inside this run's download dir or the org's local artifact dirsif self.files:downloaded_files: dict[str, str] = {}for field_name, file_path in self.files.items():@@ -16413,26 +16415,17 @@ class HttpRequestBlock(Block):file_path.startswith("s3://") or file_path.startswith("gs://") or file_path.startswith("azure://"))- # Check if file is in allowed directoriesis_allowed_local_file = False- if actual_file_path:- # Convert to absolute path for comparison (handles both absolute and relative paths)- abs_file_path = os.path.abspath(actual_file_path)-- # Get allowed directory paths (using class method for cached result)- allowed_dirs = self.get_allowed_dirs()- LOG.debug("HttpRequestBlock Allowed directories", allowed_dirs=allowed_dirs)-- # Check if file is within any allowed directory- for allowed_dir in allowed_dirs:- # Use os.path.commonpath to check if file is within allowed directory+ if actual_file_path and not (is_url or is_managed_storage_uri):+ # realpath first so a symlink or ".." cannot point the containment check at another tree.+ resolved_file_path = os.path.realpath(actual_file_path)+ for allowed_dir in self.get_allowed_dirs(workflow_run_id, organization_id):try:- common_path = os.path.commonpath([abs_file_path, allowed_dir])- if common_path == allowed_dir:+ if os.path.commonpath([resolved_file_path, allowed_dir]) == allowed_dir:is_allowed_local_file = True+ actual_file_path = resolved_file_pathbreakexcept ValueError:- # Paths are on different drives (Windows) or incompatiblecontinue# If not URL, managed storage URI, or allowed local file, reject@@ -19209,7 +19202,7 @@ def v3_ab_ineligibility_reason(blocks: list[BlockTypeVar], *, is_script_run: boocontinueif block.block_type in _ENGINE_INERT_BLOCK_TYPES:continue- if block.engine not in (None, RunEngine.skyvern_v1):+ if block.engine not in (None, RunEngine.skyvern_v1) or _pins_v1(block):return V3AbIneligibleReason.pinned_engineif not _task_block_supports_v3(block):return V3AbIneligibleReason.unsupported_block@@ -19221,6 +19214,15 @@ def v3_ab_ineligibility_reason(blocks: list[BlockTypeVar], *, is_script_run: booreturn None+def _pins_v1(block: BaseTaskBlock) -> bool:+ return block.engine == RunEngine.skyvern_v1 and block.engine_pinned+++def pinned_v1_block_count(blocks: list[BlockTypeVar]) -> int:+ """How many blocks of the flattened definition carry a person's skyvern-1.0 pin."""+ return sum(1 for block in blocks if isinstance(block, BaseTaskBlock) and _pins_v1(block))++def takes_default_engine(blocks: list[BlockTypeVar]) -> bool | None:"""Whether any block of the run leaves its engine unchosen; None when the run has no engine to choose.diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex ef376c8fa..6c82e0371 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -186,11 +186,13 @@ from skyvern.forge.sdk.workflow.models.block import (SplitPdfBlock,TaskV2Block,TextPromptBlock,+ V3AbIneligibleReason,WebSearchBlock,WhileLoopBlock,WorkflowTriggerBlock,compute_conditional_scopes,get_all_blocks,+ pinned_v1_block_count,resolve_conditional_merge_edges,takes_default_engine,v3_ab_ineligibility_reason,@@ -7890,6 +7892,7 @@ class WorkflowService:# share an arm. Covers the DAG executor too, which this method delegates to.current_context = skyvern_context.current()if current_context:+ ineligibility_reason = v3_ab_ineligibility_reason(all_blocks, is_script_run=is_script_run)await resolve_workflow_block_engine_arm(current_context,workflow_run_id=workflow_run_id,@@ -7897,8 +7900,14 @@ class WorkflowService:workflow_permanent_id=workflow_run.workflow_permanent_id,workflow_status=workflow.status,trigger_type=workflow_run.trigger_type,- ineligibility_reason=v3_ab_ineligibility_reason(all_blocks, is_script_run=is_script_run),+ ineligibility_reason=ineligibility_reason,takes_default_engine=takes_default_engine(all_blocks),+ # Counted only when the pin is what left the A/B, so pinned_v1_engine never labels another reason.+ pinned_v1_blocks=(+ pinned_v1_block_count(all_blocks)+ if ineligibility_reason == V3AbIneligibleReason.pinned_engine+ else 0+ ),)else:LOG.warning(diff --git a/skyvern/forge/sdk/workflow/workflow_definition_converter.py b/skyvern/forge/sdk/workflow/workflow_definition_converter.pyindex 552fff5ca..d5734fdd2 100644--- a/skyvern/forge/sdk/workflow/workflow_definition_converter.py+++ b/skyvern/forge/sdk/workflow/workflow_definition_converter.py@@ -425,6 +425,7 @@ def block_yaml_to_block(url=block_yaml.url,title=block_yaml.title,engine=block_yaml.engine,+ engine_pinned=block_yaml.engine_pinned,parameters=task_block_parameters,navigation_goal=block_yaml.navigation_goal,data_extraction_goal=block_yaml.data_extraction_goal,@@ -692,6 +693,7 @@ def block_yaml_to_block(**base_kwargs,task_type=TaskType.validation,engine=block_yaml.engine,+ engine_pinned=block_yaml.engine_pinned,parameters=validation_block_parameters,complete_criterion=block_yaml.complete_criterion,terminate_criterion=block_yaml.terminate_criterion,@@ -712,6 +714,7 @@ def block_yaml_to_block(url=block_yaml.url,title=block_yaml.title,engine=block_yaml.engine,+ engine_pinned=block_yaml.engine_pinned,task_type=TaskType.action,parameters=action_block_parameters,navigation_goal=block_yaml.navigation_goal,@@ -737,6 +740,7 @@ def block_yaml_to_block(url=block_yaml.url,title=block_yaml.title,engine=block_yaml.engine,+ engine_pinned=block_yaml.engine_pinned,parameters=navigation_block_parameters,navigation_goal=block_yaml.navigation_goal,error_code_mapping=block_yaml.error_code_mapping,@@ -781,6 +785,7 @@ def block_yaml_to_block(url=block_yaml.url,title=block_yaml.title,engine=block_yaml.engine,+ engine_pinned=block_yaml.engine_pinned,parameters=extraction_block_parameters,data_extraction_goal=block_yaml.data_extraction_goal,data_schema=block_yaml.data_schema,@@ -808,6 +813,7 @@ def block_yaml_to_block(url=block_yaml.url,title=block_yaml.title,engine=block_yaml.engine,+ engine_pinned=block_yaml.engine_pinned,parameters=login_block_parameters,navigation_goal=login_navigation_goal,error_code_mapping=block_yaml.error_code_mapping,@@ -877,6 +883,7 @@ def block_yaml_to_block(url=block_yaml.url,title=block_yaml.title,engine=block_yaml.engine,+ engine_pinned=block_yaml.engine_pinned,parameters=file_download_block_parameters,navigation_goal=block_yaml.navigation_goal,error_code_mapping=block_yaml.error_code_mapping,diff --git a/skyvern/schemas/workflows.py b/skyvern/schemas/workflows.pyindex 958a35306..5aee67683 100644--- a/skyvern/schemas/workflows.py+++ b/skyvern/schemas/workflows.py@@ -94,6 +94,11 @@ def _get_text_prompt_model_name_by_llm_key() -> dict[str, str]:return reverse_mapping+ENGINE_PINNED_DESCRIPTION = (+ "Set to true only when skyvern-1.0 was explicitly chosen for this block; leave it unset otherwise."+)++class _LLMSelectionBlock(Protocol):label: strmodel: dict[str, Any] | None@@ -842,6 +847,7 @@ class TaskBlockYAML(BlockYAML):url: str | None = Nonetitle: str = ""engine: RunEngine | None = None+ engine_pinned: bool = Field(default=False, description=ENGINE_PINNED_DESCRIPTION)navigation_goal: str | None = Nonedata_extraction_goal: str | None = Nonedata_schema: dict[str, Any] | list | str | None = None@@ -1251,6 +1257,7 @@ class ValidationBlockYAML(BlockYAML):block_type: Literal[BlockType.VALIDATION] = BlockType.VALIDATION # type: ignoreengine: RunEngine | None = None+ engine_pinned: bool = Field(default=False, description=ENGINE_PINNED_DESCRIPTION)complete_criterion: str | None = Noneterminate_criterion: str | None = Noneerror_code_mapping: dict[str, str] | None = None@@ -1266,6 +1273,7 @@ class ActionBlockYAML(BlockYAML):url: str | None = Nonetitle: str = ""engine: RunEngine | None = None+ engine_pinned: bool = Field(default=False, description=ENGINE_PINNED_DESCRIPTION)navigation_goal: str | None = Noneselector: str | None = Noneai_fallback: AIFallbackMode = AIFallbackMode.FALLBACK@@ -1289,6 +1297,7 @@ class NavigationBlockYAML(BlockYAML):url: str | None = Nonetitle: str = ""engine: RunEngine | None = None+ engine_pinned: bool = Field(default=False, description=ENGINE_PINNED_DESCRIPTION)error_code_mapping: dict[str, str] | None = Nonemax_retries: int = 0max_steps_per_run: int | None = None@@ -1314,6 +1323,7 @@ class ExtractionBlockYAML(BlockYAML):url: str | None = Nonetitle: str = ""engine: RunEngine | None = None+ engine_pinned: bool = Field(default=False, description=ENGINE_PINNED_DESCRIPTION)data_schema: dict[str, Any] | list | str | None = Nonemax_retries: int = 0max_steps_per_run: int | None = None@@ -1334,6 +1344,7 @@ class LoginBlockYAML(BlockYAML):url: str | None = Nonetitle: str = ""engine: RunEngine | None = None+ engine_pinned: bool = Field(default=False, description=ENGINE_PINNED_DESCRIPTION)navigation_goal: str | None = Noneerror_code_mapping: dict[str, str] | None = Nonemax_retries: int = 0@@ -1441,6 +1452,7 @@ class FileDownloadBlockYAML(BlockYAML):url: str | None = Nonetitle: str = ""engine: RunEngine | None = None+ engine_pinned: bool = Field(default=False, description=ENGINE_PINNED_DESCRIPTION)error_code_mapping: dict[str, str] | None = Nonemax_retries: int = 0max_steps_per_run: int | None = Nonediff --git a/skyvern/services/otp_service.py b/skyvern/services/otp_service.pyindex 11f676062..446c237c0 100644--- a/skyvern/services/otp_service.py+++ b/skyvern/services/otp_service.py@@ -7,16 +7,24 @@ from collections import Counterfrom dataclasses import dataclass, fieldfrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Any, Iterator, Sequence+from urllib.parse import urljoin, urlsplitimport structlogfrom pydantic import BaseModel, Field, ValidationErrorif TYPE_CHECKING:+ from skyvern.forge.agent_functions import TOTPVerificationResponsefrom skyvern.forge.sdk.schemas.tasks import Taskfrom skyvern.forge.sdk.workflow.context_manager import WorkflowRunContextfrom skyvern.config import settings-from skyvern.exceptions import FailedToGetTOTPVerificationCode, NoTOTPVerificationCodeFound+from skyvern.exceptions import (+ BlockedHost,+ FailedToGetTOTPVerificationCode,+ NoTOTPVerificationCodeFound,+ SkyvernHTTPException,+ UnresolvableHost,+)from skyvern.forge import appfrom skyvern.forge.prompts import prompt_enginefrom skyvern.forge.sdk.api.llm.api_handler_factory import get_org_aware_secondary_llm_api_handler@@ -34,6 +42,11 @@ from skyvern.forge.sdk.services.credentials import (wait_for_fresh_totp_window,)from skyvern.services.otp_email import EmailOTPVerificationContext+from skyvern.utils.url_validators import (+ BLOCKED_HOST_ALLOWLIST_HINT,+ SAFE_REDIRECT_STATUS_CODES,+ validate_fetch_url_with_resolved_ips,+)LOG = structlog.get_logger()@@ -124,6 +137,7 @@ _TOTP_WEBHOOK_REQUEST_FAILED_REASON = "totp_webhook_request_failed"_SAFE_TOTP_ERROR_REASON_PREFIXES = (_TOTP_WEBHOOK_NON_JSON_RESPONSE_REASON, _TOTP_WEBHOOK_REQUEST_FAILED_REASON)_TOTP_WEBHOOK_REQUEST_MAX_ATTEMPTS = 3_TOTP_WEBHOOK_REQUEST_RETRY_TIMEOUT_SECONDS = 5+_TOTP_WEBHOOK_MAX_REDIRECTS = 3MFANavigationPayload = dict | list | str | None_TOTPWebhookPostResponse = tuple[int, dict[str, str], Any, bool]@@ -133,6 +147,10 @@ class _TOTPWebhookRequestError(Exception):pass+class TOTPWebhookRedirectRefused(Exception):+ """Carries a fixed, URL-free message, so it is safe to surface in a failure reason."""++class InsufficientCreditsForOTPParse(Exception):"""Control-flow signal indicating that paid OTP extraction was not attempted."""@@ -435,6 +453,74 @@ def _coerce_totp_response_body(body: str) -> tuple[Any, bool]:return body, False+async def _request_totp_following_redirects(+ *,+ url: str,+ payload: str,+ headers: dict[str, str],+ timeout: int,+ organization_id: str,+) -> "TOTPVerificationResponse":+ # Redirects are followed here rather than by the HTTP client so every hop is validated and pinned+ # like the first. Method rewriting matches the earlier aiohttp client: 303, and 301/302 after a+ # POST, continue as a GET without the body.+ method = "POST"+ current_url, resolved_ips = await asyncio.to_thread(validate_fetch_url_with_resolved_ips, url)+ for hop in range(_TOTP_WEBHOOK_MAX_REDIRECTS + 1):+ response = await app.AGENT_FUNCTION.post_totp_verification_request(+ url=current_url,+ payload=payload if method == "POST" else "",+ headers=headers if method == "POST" else _headers_without_body(headers),+ timeout_seconds=timeout,+ organization_id=organization_id,+ resolved_ips=resolved_ips,+ method=method,+ )+ location = _get_header_value(response.headers, "Location")+ if response.status_code not in SAFE_REDIRECT_STATUS_CODES or not location:+ return response+ if hop == _TOTP_WEBHOOK_MAX_REDIRECTS:+ raise TOTPWebhookRedirectRefused(f"more than {_TOTP_WEBHOOK_MAX_REDIRECTS} redirects")+ next_url = urljoin(current_url, location)+ if urlsplit(current_url).scheme == "https" and urlsplit(next_url).scheme != "https":+ raise TOTPWebhookRedirectRefused("redirect from https to http refused")+ if _origin(next_url) != _origin(current_url):+ # 307/308 would re-send the signed payload to the new host unchanged.+ if response.status_code in (307, 308):+ raise TOTPWebhookRedirectRefused("cross-origin 307/308 redirect refused")+ headers = _headers_without_credentials(headers)+ current_url, resolved_ips = await asyncio.to_thread(validate_fetch_url_with_resolved_ips, next_url)+ if response.status_code == 303 or (response.status_code in (301, 302) and method == "POST"):+ method = "GET"+ raise AssertionError("unreachable")+++def _request_failure_detail(error: Exception) -> str:+ # Other exception messages can carry the endpoint URL or response details, so only known-safe text is surfaced.+ if isinstance(error, TOTPWebhookRedirectRefused):+ return f" detail={error}"+ if isinstance(error, BlockedHost) and not isinstance(error, UnresolvableHost):+ return f" detail={BLOCKED_HOST_ALLOWLIST_HINT}"+ return ""+++def _origin(url: str) -> tuple[str, str]:+ parts = urlsplit(url)+ return parts.scheme.lower(), parts.netloc.lower()+++_CROSS_ORIGIN_REDIRECT_HEADERS = frozenset({"content-type", "accept", "user-agent"})+++def _headers_without_credentials(headers: dict[str, str]) -> dict[str, str]:+ # Signatures, auth and any custom headers are meant for the configured endpoint, not a host it redirects to.+ return {key: value for key, value in headers.items() if key.lower() in _CROSS_ORIGIN_REDIRECT_HEADERS}+++def _headers_without_body(headers: dict[str, str]) -> dict[str, str]:+ return {key: value for key, value in headers.items() if key.lower() not in ("content-type", "content-length")}++async def _post_totp_verification_url(*,url: str,@@ -449,11 +535,11 @@ async def _post_totp_verification_url(# (static IP), matching webhook and file-upload delivery.for attempt in range(max_attempts):try:- response = await app.AGENT_FUNCTION.post_totp_verification_request(+ response = await _request_totp_following_redirects(url=url,payload=signed_payload,headers=headers,- timeout_seconds=timeout,+ timeout=timeout,organization_id=organization_id,)# Content-Type gate: only trust an explicit non-JSON header to mean@@ -466,6 +552,11 @@ async def _post_totp_verification_url(parsed, is_json = _coerce_totp_response_body(response.body)return response.status_code, response.headers, parsed, is_jsonexcept Exception as e:+ # A refused target stays refused; a resolver failure may be transient, so it retries.+ if isinstance(e, TOTPWebhookRedirectRefused) or (+ isinstance(e, SkyvernHTTPException) and not isinstance(e, UnresolvableHost)+ ):+ raise# Avoid exc_info here because network exceptions can include the# webhook URL or response details; keep retry logs diagnostic but sanitized.LOG.debug(@@ -1057,7 +1148,7 @@ async def _get_otp_value_from_url(task_id=task_id,workflow_run_id=workflow_run_id,workflow_id=workflow_permanent_id,- reason=f"{_TOTP_WEBHOOK_REQUEST_FAILED_REASON} exception_type={type(e).__name__}",+ reason=f"{_TOTP_WEBHOOK_REQUEST_FAILED_REASON} exception_type={type(e).__name__}{_request_failure_detail(e)}",)content_type = _get_header_value(response_headers, "Content-Type")if context is not None:diff --git a/skyvern/services/webhook_delivery.py b/skyvern/services/webhook_delivery.pyindex 8f6af42df..06019fd89 100644--- a/skyvern/services/webhook_delivery.py+++ b/skyvern/services/webhook_delivery.py@@ -16,10 +16,11 @@ from urllib.parse import urlparseimport httpximport structlog-from skyvern.exceptions import InvalidUrl+from skyvern.exceptions import BlockedHost, InvalidUrl, UnresolvableHostfrom skyvern.forge import appfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatusfrom skyvern.schemas.run_enums import WebhookDeliveryStatus+from skyvern.utils.url_validators import BLOCKED_HOST_ALLOWLIST_HINT, validate_fetch_url_with_resolved_ipsLOG = structlog.get_logger()@@ -105,6 +106,8 @@ def _attribute_delivery_error(error: BaseException) -> WebhookDeliveryStatus:# ProxyError can only come from a hop in front of the target, such as the NAT egress proxy.if isinstance(error, (httpx.ProxyError, httpx.HTTPStatusError)):return WebhookDeliveryStatus.exhausted_platform+ if isinstance(error, BlockedHost) and not isinstance(error, UnresolvableHost):+ return WebhookDeliveryStatus.exhausted_customer_configchain = list(_exception_chain(error))if any(_is_local_resource_exhaustion(link) for link in chain):return WebhookDeliveryStatus.exhausted_platform@@ -152,7 +155,10 @@ def describe_delivery_error(exc: Exception) -> str:def format_no_response_failure_reason(exc: Exception) -> str:- return f"Webhook delivery failed before receiving a response: {describe_delivery_error(exc)}"+ reason = f"Webhook delivery failed before receiving a response: {describe_delivery_error(exc)}"+ if isinstance(exc, BlockedHost) and not isinstance(exc, UnresolvableHost):+ return f"{reason} {BLOCKED_HOST_ALLOWLIST_HINT}"+ return reasondef format_http_failure_reason(status_code: int, body: str) -> str:@@ -256,13 +262,15 @@ async def deliver_webhook_with_retries(if attempts is not None:attempts.count = attempt + 1try:+ validated_url, resolved_ips = await asyncio.to_thread(validate_fetch_url_with_resolved_ips, url)response = await app.AGENT_FUNCTION.deliver_webhook(- url=url,+ url=validated_url,payload=payload,headers=headers,timeout_seconds=timeout_seconds,organization_id=organization_id,run_id=run_id,+ resolved_ips=resolved_ips,)last_response = responselast_exc = None@@ -277,7 +285,13 @@ async def deliver_webhook_with_retries(last_exc = excif not is_retryable_status(exc.response.status_code):raise- except (httpx.TimeoutException, httpx.NetworkError, httpx.RemoteProtocolError, httpx.ProxyError) as exc:+ except (+ httpx.TimeoutException,+ httpx.NetworkError,+ httpx.RemoteProtocolError,+ httpx.ProxyError,+ UnresolvableHost,+ ) as exc:last_response = Nonelast_exc = excdiff --git a/skyvern/services/webhook_service.py b/skyvern/services/webhook_service.pyindex 256198cee..a61f06c1d 100644--- a/skyvern/services/webhook_service.py+++ b/skyvern/services/webhook_service.py@@ -573,6 +573,10 @@ async def _deliver_webhook(except (httpx.NetworkError, httpx.ProxyError) as exc:error = f"Could not reach URL: {exc}"LOG.warning("Webhook replay network error", url=url, error=str(exc))+ except BlockedHost:+ # The host passed validation, then resolved to a blocked address at delivery (DNS rebinding or proxy refusal).+ error = "The target host was refused by SSRF protection."+ LOG.warning("Webhook replay target refused", url=url)except Exception as exc: # pragma: no cover - defensive guarderror = f"Unexpected error: {exc}"LOG.error("Webhook replay unexpected error", url=url, error=str(exc), exc_info=True)diff --git a/skyvern/utils/pinned_transport.py b/skyvern/utils/pinned_transport.pynew file mode 100644index 000000000..5c0c943fa--- /dev/null+++ b/skyvern/utils/pinned_transport.py@@ -0,0 +1,108 @@+"""IP checks and pinning for outbound requests. Imports only stdlib, httpx and structlog, so the NAT proxy image can ship it alone."""++import ipaddress+import urllib.request+from typing import Any++import httpx+import structlog++LOG = structlog.get_logger(__name__)+_env_proxy_warning_logged = False++BLOCKED_IP_NETWORKS = tuple(+ ipaddress.ip_network(network)+ for network in (+ "127.0.0.0/8",+ "10.0.0.0/8",+ "172.16.0.0/12",+ "192.168.0.0/16",+ "169.254.0.0/16",+ "100.64.0.0/10",+ "::1/128",+ "fc00::/7",+ )+)+BLOCKED_METADATA_IPS = frozenset(+ ipaddress.ip_address(ip) for ip in ("169.254.169.254", "100.100.100.200", "fd00:ec2::254")+)+++def normalize_ip(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> ipaddress.IPv4Address | ipaddress.IPv6Address:+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ return ip.ipv4_mapped+ return ip+++def is_blocked_ip(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:+ ip = normalize_ip(ip)+ if ip in BLOCKED_METADATA_IPS:+ return True+ if any(ip.version == network.version and ip in network for network in BLOCKED_IP_NETWORKS):+ return True+ return bool(+ ip.is_private or ip.is_link_local or ip.is_loopback or ip.is_reserved or ip.is_multicast or ip.is_unspecified+ )+++def environment_proxy_for(url: httpx.URL) -> str | None:+ """The HTTP(S)_PROXY / ALL_PROXY URL that applies to ``url``, or None when unset or bypassed by NO_PROXY."""+ proxies = urllib.request.getproxies()+ proxy = proxies.get(url.scheme) or proxies.get("all")+ if not proxy or urllib.request.proxy_bypass(url.host):+ return None+ return proxy+++def _warn_env_proxy_once() -> None:+ # Transports are built per request, so warn once per process; the proxy URL can carry credentials.+ global _env_proxy_warning_logged+ if not _env_proxy_warning_logged:+ _env_proxy_warning_logged = True+ LOG.warning("Outbound requests are routed through an environment proxy without IP pinning")+++class PinnedIPTransport(httpx.AsyncHTTPTransport):+ """Connect only to already-validated IPs, keeping SNI, Host, and cert verification on the hostname.++ httpx resolves again at connect time, so a rebinding host can answer with a private+ address after validation passed. Addresses are tried in resolution order so a host+ whose first address is unreachable still behaves like an unpinned client.+ """++ def __init__(self, resolved_ips: tuple[str, ...], *, trust_env: bool = False, **kwargs: Any) -> None:+ super().__init__(**kwargs)+ self._transport_kwargs = kwargs+ self._resolved_ips = resolved_ips+ self._trust_env = trust_env+ self._proxy_transports: dict[str, httpx.AsyncHTTPTransport] = {}++ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:+ # httpx skips env proxies whenever a transport is passed. A forward proxy resolves the host+ # itself, so pinning cannot apply there; the caller has already validated the URL.+ proxy_url = environment_proxy_for(request.url) if self._trust_env else None+ if proxy_url:+ proxy_transport = self._proxy_transports.get(proxy_url)+ if proxy_transport is None:+ _warn_env_proxy_once()+ proxy_transport = self._proxy_transports[proxy_url] = httpx.AsyncHTTPTransport(+ proxy=proxy_url, **self._transport_kwargs+ )+ return await proxy_transport.handle_async_request(request)++ original_url = request.url+ request.extensions = {**request.extensions, "sni_hostname": original_url.host}+ last_index = len(self._resolved_ips) - 1+ for index, ip in enumerate(self._resolved_ips):+ request.url = original_url.copy_with(host=ip)+ try:+ return await super().handle_async_request(request)+ except (httpx.ConnectError, httpx.ConnectTimeout):+ if index == last_index:+ raise+ raise httpx.ConnectError(f"No validated address for {original_url.host} could be reached")++ async def aclose(self) -> None:+ for proxy_transport in self._proxy_transports.values():+ await proxy_transport.aclose()+ await super().aclose()diff --git a/skyvern/utils/url_validators.py b/skyvern/utils/url_validators.pyindex c7f9934bb..437f9e3b0 100644--- a/skyvern/utils/url_validators.py+++ b/skyvern/utils/url_validators.py@@ -10,8 +10,12 @@ from pydantic import AfterValidator, AnyHttpUrl, HttpUrl, ValidationError, Validfrom skyvern.config import settingsfrom skyvern.exceptions import BlockedHost, InvalidUrl, SkyvernHTTPException, UnresolvableHost+from skyvern.utils.pinned_transport import PinnedIPTransport, is_blocked_ip, normalize_ipSAFE_REDIRECT_STATUS_CODES = {301, 302, 303, 307, 308}+BLOCKED_HOST_ALLOWLIST_HINT = (+ "The host is blocked by SSRF protection. Self-hosted deployments can add the host to ALLOWED_HOSTS."+)MAX_SAFE_REDIRECTS = 10# getaddrinfo codes that mean the resolver answered "this name has no address", as opposed to@@ -24,22 +28,6 @@ _NO_SUCH_HOST_DNS_ERRNOS = frozenset(_BLOCKED_INTERNAL_HOSTNAMES = frozenset({"localhost", "metadata.google.internal", "kubernetes.default.svc"})_BLOCKED_INTERNAL_SUFFIXES = (".local", ".localhost", ".internal", ".cluster.local")_LOCAL_BROWSER_HOSTNAMES = frozenset({"localhost", "host.docker.internal"})-_BLOCKED_IP_NETWORKS = tuple(- ipaddress.ip_network(network)- for network in (- "127.0.0.0/8",- "10.0.0.0/8",- "172.16.0.0/12",- "192.168.0.0/16",- "169.254.0.0/16",- "100.64.0.0/10",- "::1/128",- "fc00::/7",- )-)-_BLOCKED_METADATA_IPS = frozenset(- ipaddress.ip_address(ip) for ip in ("169.254.169.254", "100.100.100.200", "fd00:ec2::254")-)def strip_query_params(url: str) -> str:@@ -206,23 +194,6 @@ def _normalize_host(host: str) -> str:return (host[1:-1] if host.startswith("[") and host.endswith("]") else host).strip().lower().rstrip(".")-def _normalize_ip(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> ipaddress.IPv4Address | ipaddress.IPv6Address:- if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:- return ip.ipv4_mapped- return ip---def _is_blocked_ip(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:- ip = _normalize_ip(ip)- if ip in _BLOCKED_METADATA_IPS:- return True- if any(ip.version == network.version and ip in network for network in _BLOCKED_IP_NETWORKS):- return True- return bool(- ip.is_private or ip.is_link_local or ip.is_loopback or ip.is_reserved or ip.is_multicast or ip.is_unspecified- )--def is_allowed_local_browser_host(host: str) -> bool:if settings.ENV != "local":return False@@ -242,7 +213,7 @@ def _is_allowed_host(host: str) -> bool:normalized = _normalize_host(host)ip: ipaddress.IPv4Address | ipaddress.IPv6Address | Nonetry:- ip = _normalize_ip(ipaddress.ip_address(normalized))+ ip = normalize_ip(ipaddress.ip_address(normalized))except ValueError:ip = Noneexcept Exception:@@ -286,7 +257,7 @@ def is_blocked_host(host: str, *, resolve_dns: bool = False) -> bool:return Trueif ip is not None:- return _is_blocked_ip(ip)+ return is_blocked_ip(ip)if not resolve_dns:return False@@ -322,8 +293,8 @@ def resolve_fetch_host_ips(host: str) -> tuple[str, ...]:raise BlockedHost(host=host)if ip is not None:- normalized_ip = _normalize_ip(ip)- if not allowed and _is_blocked_ip(normalized_ip):+ normalized_ip = normalize_ip(ip)+ if not allowed and is_blocked_ip(normalized_ip):raise BlockedHost(host=host)return (str(normalized_ip),)@@ -339,10 +310,10 @@ def resolve_fetch_host_ips(host: str) -> tuple[str, ...]:if not ip_str:continuetry:- resolved_ip = _normalize_ip(ipaddress.ip_address(ip_str))+ resolved_ip = normalize_ip(ipaddress.ip_address(ip_str))except ValueError:continue- if not allowed and _is_blocked_ip(resolved_ip):+ if not allowed and is_blocked_ip(resolved_ip):raise BlockedHost(host=host)resolved_ip_str = str(resolved_ip)if resolved_ip_str not in resolved_ips:@@ -516,41 +487,17 @@ def validate_redirect_url(url: str, location: str) -> str:return validate_redirect_url_with_resolved_ips(url, location)[0]-class _PinnedIPTransport(httpx.AsyncHTTPTransport):- """Connect only to already-validated IPs, keeping SNI, Host, and cert verification on the hostname.-- httpx resolves again at connect time, so a rebinding host can answer with a private- address after validation passed. Addresses are tried in resolution order so a host- whose first address is unreachable still behaves like an unpinned client.- """-- def __init__(self, resolved_ips: tuple[str, ...], **kwargs: Any) -> None:- super().__init__(**kwargs)- self._resolved_ips = resolved_ips-- async def handle_async_request(self, request: httpx.Request) -> httpx.Response:- original_url = request.url- request.extensions = {**request.extensions, "sni_hostname": original_url.host}- last_index = len(self._resolved_ips) - 1- for index, ip in enumerate(self._resolved_ips):- request.url = original_url.copy_with(host=ip)- try:- return await super().handle_async_request(request)- except (httpx.ConnectError, httpx.ConnectTimeout):- if index == last_index:- raise- raise httpx.ConnectError(f"No validated address for {original_url.host} could be reached")--def pinned_ip_client(resolved_ips: tuple[str, ...] | None, **kwargs: Any) -> httpx.AsyncClient:"""Client pinned to the IPs a caller already validated, so DNS cannot be re-answered at connect time.Pass the IPs from `validate_fetch_url_with_resolved_ips`. Without them this is a plain- client with no rebinding protection.+ client with no rebinding protection. Environment proxies are ignored unless OUTBOUND_TRUST_ENV_PROXY+ is set, because a forward proxy re-resolves the host and the pin no longer applies."""if not resolved_ips:return httpx.AsyncClient(**kwargs)- return httpx.AsyncClient(transport=_PinnedIPTransport(resolved_ips), **kwargs)+ transport = PinnedIPTransport(resolved_ips, trust_env=kwargs.get("trust_env", settings.OUTBOUND_TRUST_ENV_PROXY))+ return httpx.AsyncClient(transport=transport, **kwargs)def encode_url(url: str) -> str:diff --git a/tests/unit/conftest.py b/tests/unit/conftest.pyindex 04e205a4a..6f3d7eaf0 100644--- a/tests/unit/conftest.py+++ b/tests/unit/conftest.py@@ -45,6 +45,7 @@ from skyvern.forge.sdk.workflow.models.parameter import OutputParameterfrom skyvern.webeye.utils import page as page_modulefrom skyvern.webeye.utils.page import ScreenshotModefrom tests.unit._fingerprint_expectations import FINGERPRINT_TEST_SECRET_KEY+from tests.unit.dns_fixtures import no_env_proxy, public_dns # noqa: F401from tests.unit.force_stub_app import start_forge_stub_appfrom tests.unit.google.conftest import mock_sheets_transport # noqa: F401diff --git a/tests/unit/dns_fixtures.py b/tests/unit/dns_fixtures.pynew file mode 100644index 000000000..ebf70643e--- /dev/null+++ b/tests/unit/dns_fixtures.py@@ -0,0 +1,32 @@+import ipaddress+import socket++import pytest++PUBLIC_TEST_IP = "93.184.216.34"+++def public_dns(monkeypatch: pytest.MonkeyPatch) -> None:+ """Resolve every hostname to a public address, so code behind the SSRF validator runs without network DNS."""+ real_getaddrinfo = socket.getaddrinfo++ def _resolve(host: str, port: object = None, *args: object, **kwargs: object) -> list:+ try:+ ipaddress.ip_address(host)+ except ValueError:+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (PUBLIC_TEST_IP, port or 0))]+ return real_getaddrinfo(host, port, *args, **kwargs)++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _resolve)+++_PROXY_ENV_VARS = ("http_proxy", "https_proxy", "all_proxy", "no_proxy")+++def no_env_proxy(monkeypatch: pytest.MonkeyPatch) -> None:+ """Clear HTTP(S)_PROXY and friends, which would otherwise route pinned requests through a developer's proxy."""+ for name in _PROXY_ENV_VARS:+ monkeypatch.delenv(name, raising=False)+ monkeypatch.delenv(name.upper(), raising=False)diff --git a/tests/unit/test_copilot_banned_block_policy.py b/tests/unit/test_copilot_banned_block_policy.pyindex 532ec6cba..01e6f8457 100644--- a/tests/unit/test_copilot_banned_block_policy.py+++ b/tests/unit/test_copilot_banned_block_policy.py@@ -563,6 +563,107 @@ async def test_update_workflow_converts_the_engine_pinned_draft_when_the_engine_assert _engines_by_label(process.call_args.kwargs["workflow_yaml"]) == {"navigate": "skyvern-3.0"}+ "submitted_engine, stored",+ [+ ("skyvern-1.0", {"engine": "skyvern-1.0", "engine_pinned": True}),+ (None, {"engine": "skyvern-1.0", "engine_pinned": True}),+ ],+ ids=["re-emitted-without-marker", "engine-omitted"],+)+async def test_update_workflow_keeps_a_pinned_v1_through_a_whole_document_write(+ submitted_engine: str | None, stored: dict+) -> None:+ goal = {"block_type": "navigation", "label": "navigate", "navigation_goal": "Go"}+ prior = _yaml({**goal, "engine": "skyvern-1.0", "engine_pinned": True})+ resubmitted = {**goal, "engine": submitted_engine} if submitted_engine else goal++ with (+ patch(+ "skyvern.forge.sdk.copilot.tools.workflow_update._process_workflow_yaml",+ side_effect=RuntimeError("stop here"),+ ) as process,+ patch("skyvern.forge.sdk.copilot.tools.workflow_update.app"),+ pytest.raises(RuntimeError),+ ):+ await _update_workflow({"workflow_yaml": _yaml(resubmitted)}, _ctx(prior_yaml=prior))++ block = yaml.safe_load(process.call_args.kwargs["workflow_yaml"])["workflow_definition"]["blocks"][0]+ assert {key: block[key] for key in ("engine", "engine_pinned") if block.get(key)} == stored+++async def test_update_workflow_cannot_add_a_pin_to_an_unmarked_v1_block() -> None:+ goal = {"block_type": "navigation", "label": "navigate", "navigation_goal": "Go"}+ ctx = _ctx(prior_yaml=_yaml({**goal, "engine": "skyvern-1.0"}))++ # Engine omitted with a marker: the refill restores the prior engine and drops the model's marker.+ with (+ patch(+ "skyvern.forge.sdk.copilot.tools.workflow_update._process_workflow_yaml",+ side_effect=RuntimeError("stop here"),+ ) as process,+ patch("skyvern.forge.sdk.copilot.tools.workflow_update.app"),+ pytest.raises(RuntimeError),+ ):+ await _update_workflow({"workflow_yaml": _yaml({**goal, "engine_pinned": True})}, ctx)+ block = yaml.safe_load(process.call_args.kwargs["workflow_yaml"])["workflow_definition"]["blocks"][0]+ assert block["engine"] == "skyvern-1.0" and not block.get("engine_pinned")++ # Engine kept with a new marker: the block counts as changed and the non-v3 engine is refused.+ with patch("skyvern.forge.sdk.copilot.tools.workflow_update._process_workflow_yaml") as process:+ result = await _update_workflow(+ {"workflow_yaml": _yaml({**goal, "engine": "skyvern-1.0", "engine_pinned": True})}, ctx+ )+ assert result["ok"] is False+ assert result["data"]["violations"][0]["code"] == "engine_not_skyvern_v3"+ process.assert_not_called()+++_GOAL = {"block_type": "navigation", "label": "navigate", "navigation_goal": "Go"}++[email protected]("route", ["whole_document", "block_scoped"])+ "prior, submitted, expected",+ [+ ({"engine": "skyvern-1.0"}, {"engine_pinned": True}, {"engine": "skyvern-1.0"}),+ ({}, {"engine_pinned": True}, {}),+ ({"engine": "skyvern-3.0"}, {"engine_pinned": True}, {"engine": "skyvern-3.0"}),+ ({"engine": "skyvern-3.0", "engine_pinned": True}, {"engine_pinned": True}, {"engine": "skyvern-3.0"}),+ ({"engine": "skyvern-1.0"}, {"engine": "skyvern-3.0", "engine_pinned": True}, {"engine": "skyvern-3.0"}),+ (+ {"engine": "skyvern-1.0", "engine_pinned": True},+ {"engine": "skyvern-1.0"},+ {"engine": "skyvern-1.0", "engine_pinned": True},+ ),+ ],+ ids=[+ "omitted-engine-on-unmarked-v1",+ "no-prior-engine",+ "v3-prior",+ "marker-on-v3-prior",+ "v3-with-marker",+ "kept-pin",+ ],+)+def test_a_submitted_marker_survives_only_as_the_prior_blocks_pin(+ route: str, prior: dict, submitted: dict, expected: dict+) -> None:+ prior_yaml = _yaml({**_GOAL, **prior})+ if route == "whole_document":+ admission = reject_authoring_violations(_ctx(prior_yaml=prior_yaml), _yaml({**_GOAL, **submitted}), "test")+ else:+ admission = reject_authoring_violations(+ _ctx(), _yaml({**_GOAL, **submitted}), "test", prior_workflow_yaml=prior_yaml+ )++ assert admission.reject is None+ block = yaml.safe_load(admission.workflow_yaml)["workflow_definition"]["blocks"][0]+ assert {key: block[key] for key in ("engine", "engine_pinned") if block.get(key)} == expected++@pytest.mark.asyncioasync def test_task_v3_pure_update_preserves_submitted_v3_engine_bytes() -> None:submitted = _yaml(diff --git a/tests/unit/test_copilot_block_edit_engine_custody.py b/tests/unit/test_copilot_block_edit_engine_custody.pyindex 45bc6d31b..c117e1690 100644--- a/tests/unit/test_copilot_block_edit_engine_custody.py+++ b/tests/unit/test_copilot_block_edit_engine_custody.py@@ -12,7 +12,7 @@ from skyvern.forge.sdk.workflow.models.block import CodeBlock, ExtractionBlockfrom skyvern.forge.sdk.workflow.models.parameter import OutputParameterfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowDefinitionfrom skyvern.schemas.runs import RunEngine-from skyvern.utils.yaml_loader import safe_load_no_dates+from skyvern.utils.yaml_loader import dump_workflow_yaml, safe_load_no_datesfrom tests.unit.copilot_test_helpers import make_copilot_ctxDRAFT = """title: Repair@@ -158,6 +158,41 @@ def test_nested_untouched_producer_engine_is_preserved() -> None:assert nested["engine"] == RunEngine.skyvern_v1.value+def test_a_marker_on_a_non_v1_saved_block_does_not_pin_a_draft_v1() -> None:+ from skyvern.forge.sdk.copilot.workflow_yaml import preserve_untouched_block_configuration++ prior = _definition(RunEngine.skyvern_v3)+ prior.blocks[0].engine_pinned = True+ draft = DRAFT.replace(" label: extract_value", " label: extract_value\n engine: skyvern-1.0")+ restored = preserve_untouched_block_configuration(draft, prior, edited_label="repair")+ producer = safe_load_no_dates(restored)["workflow_definition"]["blocks"][0]+ assert not producer.get("engine_pinned")+++def test_untouched_pinned_skyvern_v1_keeps_its_pin() -> None:+ from skyvern.forge.sdk.copilot.workflow_yaml import preserve_untouched_block_configuration++ prior = _definition(RunEngine.skyvern_v1)+ prior.blocks[0].engine_pinned = True+ draft = safe_load_no_dates(DRAFT)+ draft["workflow_definition"]["blocks"][0]["engine"] = RunEngine.skyvern_v1.value+ restored = preserve_untouched_block_configuration(dump_workflow_yaml(draft), prior, edited_label="repair")+ producer = safe_load_no_dates(restored)["workflow_definition"]["blocks"][0]+ assert producer["engine"] == RunEngine.skyvern_v1.value+ assert producer["engine_pinned"] is True+++def test_default_pick_on_pinned_skyvern_v1_is_not_re_pinned() -> None:+ from skyvern.forge.sdk.copilot.workflow_yaml import preserve_untouched_block_configuration++ prior = _definition(RunEngine.skyvern_v1)+ prior.blocks[0].engine_pinned = True+ restored = preserve_untouched_block_configuration(DRAFT, prior, edited_label="repair")+ producer = safe_load_no_dates(restored)["workflow_definition"]["blocks"][0]+ assert "engine" not in producer+ assert not producer.get("engine_pinned")++@pytest.mark.parametrize("label, fields, edited_label",[diff --git a/tests/unit/test_otp_service.py b/tests/unit/test_otp_service.pyindex 22344a61c..3a6406d68 100644--- a/tests/unit/test_otp_service.py+++ b/tests/unit/test_otp_service.py@@ -359,6 +359,7 @@ def _patch_totp_url_response(monkeypatch.setattr(otp_service, "_post_totp_verification_url", post_totp_verification_url)[email protected]("public_dns")class TestGetOtpValueFromUrl:@pytest.mark.asyncioasync def test_returns_totp_from_valid_json_verification_code(self, monkeypatch: pytest.MonkeyPatch) -> None:@@ -2035,6 +2036,7 @@ class TestTryGenerateTotpFromCredential:assert try_generate_totp_from_credential("wr_test") is None[email protected]("public_dns")class TestPostTotpVerificationUrlSeam:"""`_post_totp_verification_url` must route through app.AGENT_FUNCTION so thecloud override can egress via the NAT proxy (static IP), like webhook/file-upload."""diff --git a/tests/unit/test_webhook_delivery.py b/tests/unit/test_webhook_delivery.pyindex bd6df7435..bcca56728 100644--- a/tests/unit/test_webhook_delivery.py+++ b/tests/unit/test_webhook_delivery.py@@ -27,6 +27,7 @@ async def test_scheme_less_url_rejected_before_delivery(monkeypatch: pytest.Monk@pytest.mark.asyncio[email protected]("public_dns")async def test_valid_https_url_reaches_delivery(monkeypatch: pytest.MonkeyPatch) -> None:resp = httpx.Response(200, request=httpx.Request("POST", "https://example.com/webhook"))deliver = AsyncMock(return_value=resp)diff --git a/tests/unit/test_webhook_delivery_retry.py b/tests/unit/test_webhook_delivery_retry.pyindex 349daf52a..23c24b6b1 100644--- a/tests/unit/test_webhook_delivery_retry.py+++ b/tests/unit/test_webhook_delivery_retry.py@@ -3,7 +3,6 @@from __future__ import annotationsimport asyncio-from types import SimpleNamespacefrom unittest.mock import AsyncMock, patchimport httpx@@ -18,6 +17,9 @@ from skyvern.services.webhook_delivery import (format_no_response_failure_reason,is_retryable_status,)+from tests.unit.scoped_asyncio import ScopedAsyncio++pytestmark = pytest.mark.usefixtures("public_dns")_STDLIB_ASYNCIO_SLEEP = asyncio.sleep@@ -47,7 +49,7 @@ def fake_sleep(monkeypatch: pytest.MonkeyPatch) -> list[float]:async def _sleep(delay: float) -> None:recorded.append(delay)- monkeypatch.setattr("skyvern.services.webhook_delivery.asyncio", SimpleNamespace(sleep=_sleep))+ monkeypatch.setattr("skyvern.services.webhook_delivery.asyncio", ScopedAsyncio(sleep=_sleep))return recordeddiff --git a/tests/unit/test_webhook_failure_reason.py b/tests/unit/test_webhook_failure_reason.pyindex cab7caf87..e01e2106d 100644--- a/tests/unit/test_webhook_failure_reason.py+++ b/tests/unit/test_webhook_failure_reason.py@@ -218,6 +218,7 @@ async def test_task_v2_webhook_exception_log_exposes_canonical_fields(@pytest.mark.asyncio[email protected]("public_dns")@pytest.mark.parametrize("task_version", ["v1", "v2"])async def test_task_http_failure_logs_do_not_copy_response_body(task_version: str,diff --git a/tests/unit/test_webhook_ssrf.py b/tests/unit/test_webhook_ssrf.pyindex 4c753730d..858bd423d 100644--- a/tests/unit/test_webhook_ssrf.py+++ b/tests/unit/test_webhook_ssrf.py@@ -7,21 +7,30 @@ was validated, or a rebinding host answers again with a private address at connefrom __future__ import annotations+import asyncioimport socket+import time+from collections.abc import AsyncIteratorfrom datetime import UTC, datetime, timedeltafrom unittest.mock import AsyncMock, MagicMock, patchimport httpximport pytest+import pytest_asyncio-from skyvern.exceptions import BlockedHost, SkyvernHTTPException+from skyvern.config import settings+from skyvern.exceptions import BlockedHost, FailedToGetTOTPVerificationCode, SkyvernHTTPException+from skyvern.forge.agent_functions import AgentFunctionfrom skyvern.forge.sdk.db.models import WorkflowRunAttemptModelfrom skyvern.forge.sdk.routes import webhooks as webhook_routesfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRun, WorkflowRunStatusfrom skyvern.forge.sdk.workflow.retry_policy import compute_attempt_view+from skyvern.schemas.run_enums import WebhookDeliveryStatusfrom skyvern.schemas.webhooks import TestWebhookRequest as WebhookTestPayload-from skyvern.services import webhook_service+from skyvern.services import otp_service, webhook_delivery, webhook_service+from skyvern.services.webhook_delivery import WebhookDeliveryAttemptsfrom skyvern.utils.url_validators import pinned_ip_client, resolve_fetch_host_ips+from tests.unit.scoped_asyncio import ScopedAsyncioPRIVATE_HOST_URL = "http://169.254.169.254.example.test/computeMetadata/v1/"REBINDING_HOST_URL = "https://rebinding.example.test/webhook"@@ -29,6 +38,9 @@ PUBLIC_IP = "93.184.216.34"METADATA_IP = "169.254.169.254"+pytestmark = pytest.mark.usefixtures("no_env_proxy")++@pytest.mark.asyncioasync def test_replay_of_a_running_run_without_attempt_rows_is_not_blocked(monkeypatch: pytest.MonkeyPatch) -> None:run = WorkflowRun.model_construct(@@ -253,3 +265,407 @@ async def test_replay_delivery_pins_the_validated_ips(rebinding_dns: None) -> No)assert delivered["resolved_ips"] == (PUBLIC_IP,)+++async def test_replay_reports_a_refused_target_without_an_unexpected_error() -> None:+ async def _deliver(**kwargs: object) -> httpx.Response:+ raise BlockedHost("rebinding.example.test")++ with patch("skyvern.services.webhook_service.app.AGENT_FUNCTION.deliver_webhook", _deliver):+ status_code, _latency, _body, error = await webhook_service._deliver_webhook(+ url=REBINDING_HOST_URL, payload="{}", headers={}+ )++ assert status_code is None+ assert error == "The target host was refused by SSRF protection."+++def oss_outbound_seams(monkeypatch: pytest.MonkeyPatch) -> None:+ agent_function = AgentFunction()+ monkeypatch.setattr(webhook_delivery.app.AGENT_FUNCTION, "deliver_webhook", agent_function.deliver_webhook)+ monkeypatch.setattr(+ otp_service.app.AGENT_FUNCTION,+ "post_totp_verification_request",+ agent_function.post_totp_verification_request,+ )+ monkeypatch.setattr(webhook_delivery, "asyncio", ScopedAsyncio(sleep=AsyncMock()))+ monkeypatch.setattr(otp_service, "asyncio", ScopedAsyncio(sleep=AsyncMock()))+++async def _deliver_run_webhook(url: str, attempts: WebhookDeliveryAttempts | None = None) -> httpx.Response:+ return await webhook_delivery.deliver_webhook_with_retries(+ url=url,+ payload="{}",+ headers={},+ timeout_seconds=5.0,+ organization_id="o_1",+ run_id="wr_1",+ attempts=attempts,+ )+++async def _post_totp(url: str) -> object:+ return await otp_service._post_totp_verification_url(+ url=url, signed_payload="{}", headers={}, organization_id="o_1", retry_timeout=0+ )+++async def test_run_webhook_delivery_connects_to_validated_ip_after_dns_rebind(+ rebinding_dns: None, oss_outbound_seams: None, capture_connect_target: dict[str, object]+) -> None:+ response = await _deliver_run_webhook(REBINDING_HOST_URL)++ assert response.status_code == 200+ assert capture_connect_target["connect_host"] == PUBLIC_IP+ assert capture_connect_target["sni_hostname"] == "rebinding.example.test"+++async def test_totp_verification_post_connects_to_validated_ip_after_dns_rebind(+ rebinding_dns: None, oss_outbound_seams: None, capture_connect_target: dict[str, object]+) -> None:+ status_code, *_ = await _post_totp(REBINDING_HOST_URL)++ assert status_code == 200+ assert capture_connect_target["connect_host"] == PUBLIC_IP+ assert capture_connect_target["host_header"] == "rebinding.example.test"+++def internal_name_resolves_to_rfc1918(monkeypatch: pytest.MonkeyPatch) -> None:+ def _resolve(host: str, *args: object, **kwargs: object) -> list:+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("10.0.0.5", 443))]++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _resolve)+++_REFUSED_TARGETS = [+ "http://169.254.169.254/latest/meta-data/",+ "http://127.0.0.1:8000/hook",+ "https://internal-api.example.test/hook",+]++[email protected]("url", _REFUSED_TARGETS)+async def test_run_webhook_delivery_refuses_internal_targets_without_retrying(+ url: str,+ internal_name_resolves_to_rfc1918: None,+ oss_outbound_seams: None,+ capture_connect_target: dict[str, object],+) -> None:+ attempts = WebhookDeliveryAttempts()+ with pytest.raises(BlockedHost) as exc_info:+ await _deliver_run_webhook(url, attempts)++ assert capture_connect_target == {}+ assert attempts.count == 1+ failure_reason = webhook_delivery.format_no_response_failure_reason(exc_info.value)+ assert "ALLOWED_HOSTS" in failure_reason+ assert "10.0.0.5" not in failure_reason+ assert (+ webhook_delivery.refine_exhausted_webhook_delivery(+ WebhookDeliveryStatus.exhausted_unattributed, error=exc_info.value+ )+ == WebhookDeliveryStatus.exhausted_customer_config+ )++[email protected]("url", _REFUSED_TARGETS)+async def test_totp_verification_refuses_internal_targets(+ url: str,+ internal_name_resolves_to_rfc1918: None,+ oss_outbound_seams: None,+ capture_connect_target: dict[str, object],+) -> None:+ with pytest.raises(FailedToGetTOTPVerificationCode) as exc_info:+ await otp_service._get_otp_value_from_url(organization_id="o_1", url=url, api_key="key", task_id="tsk_1")++ assert "exception_type=BlockedHost" in str(exc_info.value)+ assert "ALLOWED_HOSTS" in str(exc_info.value)+ assert "10.0.0.5" not in str(exc_info.value)+ assert capture_connect_target == {}+++@pytest_asyncio.fixture+async def forward_proxy() -> AsyncIterator[list[bytes]]:+ """A local HTTP forward proxy that answers every request itself, recording each request line."""+ request_lines: list[bytes] = []++ async def _handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:+ head = await reader.readuntil(b"\r\n\r\n")+ request_lines.append(head.split(b"\r\n", 1)[0])+ length = next(+ (+ int(line.split(b":", 1)[1])+ for line in head.split(b"\r\n")+ if line.lower().startswith(b"content-length:")+ ),+ 0,+ )+ await reader.readexactly(length)+ writer.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok")+ await writer.drain()+ writer.close()++ server = await asyncio.start_server(_handle, "127.0.0.1", 0)+ port = server.sockets[0].getsockname()[1]+ with pytest.MonkeyPatch.context() as env:+ env.setenv("http_proxy", f"http://127.0.0.1:{port}")+ yield request_lines+ server.close()+ await server.wait_closed()+++async def test_run_webhook_delivery_ignores_an_environment_proxy_by_default(+ rebinding_dns: None,+ oss_outbound_seams: None,+ forward_proxy: list[bytes],+ capture_connect_target: dict[str, object],+) -> None:+ response = await _deliver_run_webhook("http://rebinding.example.test/hook")++ assert response.status_code == 200+ assert capture_connect_target["connect_host"] == PUBLIC_IP+ assert forward_proxy == []+++async def test_run_webhook_delivery_goes_through_an_environment_proxy_when_opted_in(+ rebinding_dns: None, oss_outbound_seams: None, forward_proxy: list[bytes], monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(settings, "OUTBOUND_TRUST_ENV_PROXY", True)++ response = await _deliver_run_webhook("http://rebinding.example.test/hook")++ assert response.status_code == 200+ assert forward_proxy == [b"POST http://rebinding.example.test/hook HTTP/1.1"]+++async def test_run_webhook_delivery_bypassing_the_environment_proxy_stays_pinned(+ rebinding_dns: None,+ oss_outbound_seams: None,+ forward_proxy: list[bytes],+ capture_connect_target: dict[str, object],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("no_proxy", "rebinding.example.test")++ response = await _deliver_run_webhook("http://rebinding.example.test/hook")++ assert response.status_code == 200+ assert capture_connect_target["connect_host"] == PUBLIC_IP+ assert forward_proxy == []++[email protected]("url", _REFUSED_TARGETS)+async def test_run_webhook_delivery_through_an_environment_proxy_still_refuses_internal_targets(+ url: str, internal_name_resolves_to_rfc1918: None, oss_outbound_seams: None, forward_proxy: list[bytes]+) -> None:+ with pytest.raises(BlockedHost):+ await _deliver_run_webhook(url)++ assert forward_proxy == []+++TOTP_HOST = "totp.example.test"+REDIRECT_TARGET_IP = "93.184.216.35"+++def totp_redirect_dns(monkeypatch: pytest.MonkeyPatch) -> None:+ answers = {TOTP_HOST: PUBLIC_IP, "next.example.test": REDIRECT_TARGET_IP, "internal.example.test": "10.0.0.5"}++ def _resolve(host: str, *args: object, **kwargs: object) -> list:+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (answers[host], 443))]++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _resolve)+++def redirecting_endpoints(monkeypatch: pytest.MonkeyPatch) -> tuple[dict[str, httpx.Response], list[tuple]]:+ """Answer each request by its Host header, recording (method, connect host, Host header, body)."""+ responses: dict[str, httpx.Response] = {}+ requests: list[tuple] = []++ async def _answer(self: httpx.AsyncHTTPTransport, request: httpx.Request) -> httpx.Response:+ host_header = request.headers["host"]+ requests.append((request.method, request.url.host, host_header, await request.aread()))+ return responses[host_header]++ monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", _answer)+ return responses, requests+++def _redirect(status_code: int, location: str) -> httpx.Response:+ return httpx.Response(status_code, headers={"Location": location})++[email protected](("status_code", "next_method", "next_body"), [(303, "GET", b""), (302, "GET", b"")])+async def test_totp_redirect_to_a_public_host_is_followed_and_pinned(+ status_code: int,+ next_method: str,+ next_body: bytes,+ totp_redirect_dns: None,+ oss_outbound_seams: None,+ redirecting_endpoints: tuple[dict[str, httpx.Response], list[tuple]],+) -> None:+ responses, requests = redirecting_endpoints+ responses[TOTP_HOST] = _redirect(status_code, "https://next.example.test/code")+ responses["next.example.test"] = httpx.Response(200, json={"verification_code": "123456"})++ status, _headers, body, _is_json = await _post_totp(f"https://{TOTP_HOST}/totp")++ assert (status, body) == (200, {"verification_code": "123456"})+ assert requests == [+ ("POST", PUBLIC_IP, TOTP_HOST, b"{}"),+ (next_method, REDIRECT_TARGET_IP, "next.example.test", next_body),+ ]+++ ("location", "expected_reason"),+ [+ ("https://127.0.0.1:8000/code", "exception_type=BlockedHost"),+ ("https://internal.example.test/code", "exception_type=BlockedHost"),+ ("http://next.example.test/code", "detail=redirect from https to http refused"),+ ],+)+async def test_totp_redirect_to_a_refused_target_is_not_followed(+ location: str,+ expected_reason: str,+ totp_redirect_dns: None,+ oss_outbound_seams: None,+ redirecting_endpoints: tuple[dict[str, httpx.Response], list[tuple]],+) -> None:+ responses, requests = redirecting_endpoints+ responses[TOTP_HOST] = _redirect(302, location)++ with pytest.raises(FailedToGetTOTPVerificationCode) as exc_info:+ await otp_service._get_otp_value_from_url(+ organization_id="o_1", url=f"https://{TOTP_HOST}/totp", api_key="key", task_id="tsk_1"+ )++ assert expected_reason in str(exc_info.value)+ assert [request[2] for request in requests] == [TOTP_HOST]+++async def test_totp_redirect_loop_stops_after_three_hops(+ totp_redirect_dns: None,+ oss_outbound_seams: None,+ redirecting_endpoints: tuple[dict[str, httpx.Response], list[tuple]],+) -> None:+ responses, requests = redirecting_endpoints+ responses[TOTP_HOST] = _redirect(307, "/totp")++ with pytest.raises(FailedToGetTOTPVerificationCode) as exc_info:+ await otp_service._get_otp_value_from_url(+ organization_id="o_1", url=f"https://{TOTP_HOST}/totp", api_key="key", task_id="tsk_1"+ )++ assert "detail=more than 3 redirects" in str(exc_info.value)+ assert len(requests) == 4+++ ("status_code", "location", "signed_on_next_hop"),+ [(303, "https://next.example.test/code", False), (307, "/code", True)],+)+async def test_totp_redirect_drops_the_signature_when_the_origin_changes(+ status_code: int,+ location: str,+ signed_on_next_hop: bool,+ totp_redirect_dns: None,+ oss_outbound_seams: None,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ seen: list[tuple[str, bool]] = []+ custom_header_seen: list[bool] = []++ async def _answer(self: httpx.AsyncHTTPTransport, request: httpx.Request) -> httpx.Response:+ seen.append((request.headers["host"], "x-skyvern-signature" in request.headers))+ custom_header_seen.append("x-api-key" in request.headers)+ if len(seen) == 1:+ return _redirect(status_code, location)+ return httpx.Response(200, json={"verification_code": "123456"})++ monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", _answer)++ await otp_service._post_totp_verification_url(+ url=f"https://{TOTP_HOST}/totp",+ signed_payload="{}",+ headers={"x-skyvern-signature": "sig", "x-skyvern-timestamp": "1", "x-api-key": "secret"},+ organization_id="o_1",+ retry_timeout=0,+ )++ assert seen[0] == (TOTP_HOST, True)+ assert seen[1][1] is signed_on_next_hop+ assert custom_header_seen == [True, signed_on_next_hop]++[email protected]("status_code", [307, 308])+async def test_totp_cross_origin_redirect_that_keeps_the_body_is_refused(+ status_code: int,+ totp_redirect_dns: None,+ oss_outbound_seams: None,+ redirecting_endpoints: tuple[dict[str, httpx.Response], list[tuple]],+) -> None:+ responses, requests = redirecting_endpoints+ responses[TOTP_HOST] = _redirect(status_code, "https://next.example.test/code")++ with pytest.raises(FailedToGetTOTPVerificationCode) as exc_info:+ await otp_service._get_otp_value_from_url(+ organization_id="o_1", url=f"https://{TOTP_HOST}/totp", api_key="key", task_id="tsk_1"+ )++ assert "cross-origin 307/308 redirect refused" in str(exc_info.value)+ assert [request[2] for request in requests] == [TOTP_HOST]+++async def test_totp_redirect_to_a_refused_target_at_a_later_hop_is_not_followed(+ totp_redirect_dns: None,+ oss_outbound_seams: None,+ redirecting_endpoints: tuple[dict[str, httpx.Response], list[tuple]],+) -> None:+ responses, requests = redirecting_endpoints+ responses[TOTP_HOST] = _redirect(302, "https://next.example.test/code")+ responses["next.example.test"] = _redirect(302, "https://127.0.0.1:8000/code")++ with pytest.raises(FailedToGetTOTPVerificationCode) as exc_info:+ await otp_service._get_otp_value_from_url(+ organization_id="o_1", url=f"https://{TOTP_HOST}/totp", api_key="key", task_id="tsk_1"+ )++ assert "exception_type=BlockedHost" in str(exc_info.value)+ assert [request[2] for request in requests] == [TOTP_HOST, "next.example.test"]+++async def test_totp_request_is_capped_by_a_total_timeout(monkeypatch: pytest.MonkeyPatch) -> None:+ async def _slow_drip(self: httpx.AsyncHTTPTransport, request: httpx.Request) -> httpx.Response:+ await asyncio.sleep(5)+ return httpx.Response(200)++ monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", _slow_drip)+ started = time.monotonic()++ with pytest.raises(httpx.ReadTimeout):+ await AgentFunction().post_totp_verification_request(+ url=f"https://{TOTP_HOST}/totp", payload="{}", headers={}, timeout_seconds=0.2, resolved_ips=(PUBLIC_IP,)+ )++ assert time.monotonic() - started < 2diff --git a/tests/unit/test_workflow_block_engine.py b/tests/unit/test_workflow_block_engine.pyindex 31979fa69..c4baf7ff5 100644--- a/tests/unit/test_workflow_block_engine.py+++ b/tests/unit/test_workflow_block_engine.py@@ -58,10 +58,17 @@ from skyvern.forge.sdk.workflow.models.block import (v3_ab_ineligibility_reason,)from skyvern.forge.sdk.workflow.models.workflow import WorkflowDefinition-from skyvern.forge.sdk.workflow.service import WorkflowService+from skyvern.forge.sdk.workflow.service import WorkflowService, workflow_definitions_differ+from skyvern.forge.sdk.workflow.workflow_definition_converter import convert_workflow_definitionfrom skyvern.forge.taskv3.goal_composition import render_block_contextfrom skyvern.schemas.run_enums import RunEngine-from skyvern.schemas.workflows import BlockResult, BlockType, NavigationBlockYAML, WorkflowStatus+from skyvern.schemas.workflows import (+ BlockResult,+ BlockType,+ NavigationBlockYAML,+ WorkflowDefinitionYAML,+ WorkflowStatus,+)from skyvern.services import script_servicefrom tests.unit._workflow_block_engine_fakes import (WORKFLOW_BLOCK_ENGINE_APP_TARGET,@@ -517,6 +524,7 @@ async def _persisted_engine_from_execute_workflow_blocks(billing_tier: BillingTier = BillingTier.UNKNOWN,first_version_created_at: datetime | None = None,trigger_type: WorkflowRunTriggerType | None = WorkflowRunTriggerType.api,+ block: BaseTaskBlock | None = None,) -> RunEngine:"""Drives the real WorkflowService._execute_workflow_blocks -> _execute_single_block ->Block.execute_safe chain for a single eligible TaskBlock and returns the engine it persisted,@@ -532,7 +540,7 @@ async def _persisted_engine_from_execute_workflow_blocks(AsyncMock(return_value=first_version_created_at),)- block = _make_block(TaskBlock, label="e2e_block")+ block = block or _make_block(TaskBlock, label="e2e_block")workflow = MagicMock()workflow.workflow_definition.blocks = [block]workflow.workflow_definition.version = 1@@ -1637,3 +1645,72 @@ async def test_effective_default_engine_follows_the_chosen_engine_cutoff(# With no flag provider the resolver never applies the rule, so the editor must not claim it.mock_app.EXPERIMENTATION_PROVIDER = NoOpExperimentationProvider()assert await effective_default_engine("wpid_1", "org_1") is None+++ ("engine", "pinned", "born_at", "expected_engine", "expected_reason", "expected_pins"),+ [+ # An older workflow's unmarked skyvern-1.0 is usually the old editor's Default and stays in the A/B.+ (RunEngine.skyvern_v1, False, _BEFORE, RunEngine.skyvern_v3, _R.flag_bucket_treatment, 0),+ (RunEngine.skyvern_v1, True, _BEFORE, RunEngine.skyvern_v1, _R.pinned_v1_engine, 1),+ (None, False, _BEFORE, RunEngine.skyvern_v3, _R.flag_bucket_treatment, 0),+ (RunEngine.skyvern_v3, False, _BEFORE, RunEngine.skyvern_v3, _R.ineligible, 0),+ (RunEngine.skyvern_v1, True, _AFTER, RunEngine.skyvern_v1, _R.chosen_engine, 1),+ ],+)+async def test_only_a_pinned_skyvern_v1_leaves_the_ab_on_an_older_workflow(+ scoped_context: SkyvernContext,+ monkeypatch: pytest.MonkeyPatch,+ engine: RunEngine | None,+ pinned: bool,+ born_at: datetime,+ expected_engine: RunEngine,+ expected_reason: WorkflowBlockEngineRouteReason,+ expected_pins: int,+) -> None:+ monkeypatch.setattr(settings, "TASK_V3_CHOSEN_ENGINE_CUTOFF", CHOSEN_ENGINE_CUTOFF)+ block = _make_block(TaskBlock, label="e2e_block", engine=engine, engine_pinned=pinned)+ with patch("skyvern.forge.sdk.experimentation.workflow_block_engine.LOG") as mock_log:+ persisted = await _persisted_engine_from_execute_workflow_blocks(+ monkeypatch,+ FakeExperimentationProvider({WORKFLOW_TASK_V3_AB_FLAG: True}),+ first_version_created_at=born_at,+ block=block,+ )++ assert persisted == expected_engine+ log = mock_log.info.call_args.kwargs+ assert log["route_reason"] == expected_reason+ assert log.get("pinned_v1_blocks", 0) == expected_pins+++ "block",+ [+ {"block_type": "navigation", "navigation_goal": "Go"},+ {"block_type": "task", "navigation_goal": "Go"},+ {"block_type": "action", "navigation_goal": "Go"},+ {"block_type": "extraction", "data_extraction_goal": "Read"},+ {"block_type": "login", "navigation_goal": "Go"},+ {"block_type": "file_download", "navigation_goal": "Go"},+ {"block_type": "validation", "complete_criterion": "Done"},+ ],+ ids=lambda block: block["block_type"],+)+def test_a_pinned_skyvern_v1_survives_the_stored_definition_and_counts_as_a_change(block: dict[str, str]) -> None:+ def definition(pinned: bool) -> Any:+ nav = {**block, "label": "nav", "url": "https://example.com"}+ yaml = WorkflowDefinitionYAML.model_validate(+ {"parameters": [], "blocks": [{**nav, "engine": "skyvern-1.0", "engine_pinned": pinned}]}+ )+ return convert_workflow_definition(yaml, "w_test")++ pinned, unmarked = definition(True), definition(False)+ stored = pinned.model_dump(mode="json")["blocks"][0]++ assert stored["engine_pinned"] is True+ assert "engine_pinned" not in unmarked.model_dump(mode="json")["blocks"][0]+ assert WorkflowDefinition.model_validate(pinned.model_dump(mode="json")).blocks[0].engine_pinned is True+ # Before the cutoff an unmarked skyvern-1.0 and an unset engine compare alike; a pin must not.+ assert workflow_definitions_differ(unmarked, pinned)diff --git a/tests/unit/test_workflow_webhook_delivery.py b/tests/unit/test_workflow_webhook_delivery.pyindex e64365033..fa7bda40f 100644--- a/tests/unit/test_workflow_webhook_delivery.py+++ b/tests/unit/test_workflow_webhook_delivery.py@@ -20,6 +20,7 @@ from sqlalchemy.dialects import postgresqlfrom sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmakerfrom structlog.testing import capture_logs+from skyvern.config import settingsfrom skyvern.exceptions import InvalidUrlfrom skyvern.forge.agent_functions import AgentFunctionfrom skyvern.forge.sdk.core.security import generate_skyvern_webhook_signature@@ -51,6 +52,8 @@ from skyvern.services import webhook_delivery as webhook_delivery_modulefrom skyvern.services import webhook_service as replay_servicefrom tests.unit.scoped_asyncio import ScopedAsyncio+pytestmark = pytest.mark.usefixtures("public_dns")+class _StatusResponse:def __init__(self, extra_payload: dict | None = None) -> None:@@ -2272,20 +2275,25 @@ async def test_exhausted_webhook_attributes_real_connection_failures(resolver_error: int | None,expected: WebhookDeliveryStatus,) -> None:- # Real httpx/httpcore/anyio build the exception chain; only this test loop's resolver is faked.+ # Real httpx/httpcore/anyio build the exception chain. Delivery connects to the addresses the SSRF+ # validator resolved, so its resolver is the one faked; the allowlisted host lets loopback stand in+ # for a customer endpoint with nothing listening.svc, _build_response, update_run = webhook_service- ports = _closed_local_ports(2)+ [port] = _closed_local_ports(1)- async def resolve(*_args: Any, **_kwargs: Any) -> list[tuple[Any, ...]]:+ def resolve(*_args: Any, **_kwargs: Any) -> list[tuple[Any, ...]]:if resolver_error is not None:raise socket.gaierror(resolver_error, "synthetic resolver failure")- return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("127.0.0.1", port)) for port in ports]+ return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("127.0.0.1", 0))]- monkeypatch.setattr(asyncio.get_running_loop(), "getaddrinfo", resolve)+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", resolve)+ monkeypatch.setattr(settings, "ALLOWED_HOSTS", ["customer.example"])monkeypatch.setattr(service_module.app.AGENT_FUNCTION, "deliver_webhook", AgentFunction().deliver_webhook)monkeypatch.setattr(webhook_delivery_module, "asyncio", ScopedAsyncio(sleep=AsyncMock()))+ run = _workflow_run()+ run.webhook_callback_url = f"http://customer.example:{port}/hook"- await _assert_exhausted_outcome(svc, update_run, _workflow_run(), expected)+ await _assert_exhausted_outcome(svc, update_run, run, expected)@pytest.mark.asynciodiff --git a/tests/unit/workflow/test_http_request_block.py b/tests/unit/workflow/test_http_request_block.pyindex 0c45bec33..cdeffeb72 100644--- a/tests/unit/workflow/test_http_request_block.py+++ b/tests/unit/workflow/test_http_request_block.py@@ -1,6 +1,8 @@import json+import osimport socketfrom datetime import datetime, timezone+from pathlib import Pathfrom unittest.mock import AsyncMock, MagicMockfrom urllib.parse import urljoin@@ -1000,3 +1002,76 @@ class TestHttpRequestBlockCredentialSiteConfinement:assert result.success is Trueassert sent["data"] == {"password": "hunter2-secret"}+++class TestHttpRequestBlockLocalFileScope:+ """A local `files` path may only name this run's downloads or this organization's local artifacts."""++ @pytest.fixture+ def local_tree(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, str]:+ downloads = tmp_path / "downloads"+ artifacts = tmp_path / "artifacts"+ monkeypatch.setattr(block_module.settings, "DOWNLOAD_PATH", str(downloads))+ monkeypatch.setattr(block_module.settings, "ARTIFACT_STORAGE_PATH", str(artifacts))+ env = block_module.settings.ENV+ paths = {+ "run_file": downloads / "wr-1" / "report.pdf",+ "other_run_file": downloads / "wr-other" / "report.pdf",+ "org_artifact": artifacts / env / "o_1" / "workflow_runs" / "shot.png",+ "other_org_artifact": artifacts / env / "o_other" / "workflow_runs" / "shot.png",+ "outside": tmp_path / "outside.txt",+ }+ for path in paths.values():+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("x")+ symlink = downloads / "wr-1" / "escape.pdf"+ symlink.symlink_to(paths["outside"])+ resolved = {name: str(path) for name, path in paths.items()}+ resolved["symlink_escape"] = str(symlink)+ resolved["dotdot_escape"] = str(downloads / "wr-1" / ".." / "wr-other" / "report.pdf")+ return resolved++ async def _execute_with_file(+ self, monkeypatch: pytest.MonkeyPatch, file_value: str+ ) -> tuple[object, dict[str, object]]:+ block = _http_block(url="https://api.example.com/upload", files={"doc": file_value})+ sent: dict[str, object] = {}++ async def fake_aiohttp_request(**kwargs: object) -> tuple[int, dict[str, str], dict[str, object]]:+ sent.update(kwargs)+ return 200, {"Content-Type": "application/json"}, {"ok": True}++ monkeypatch.setattr(+ HttpRequestBlock, "get_workflow_run_context", lambda _self, _workflow_run_id: _make_context()+ )+ monkeypatch.setattr(block_module, "aiohttp_request", fake_aiohttp_request)+ monkeypatch.setattr(block_module.app, "DATABASE", AsyncMock())+ result = await block.execute(workflow_run_id="wr-1", workflow_run_block_id="wrb-1", organization_id="o_1")+ return result, sent++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("name", "as_uri"),+ [("run_file", False), ("run_file", True), ("org_artifact", False)],+ )+ async def test_file_inside_run_or_org_scope_is_sent(+ self, local_tree: dict[str, str], monkeypatch: pytest.MonkeyPatch, name: str, as_uri: bool+ ) -> None:+ path = local_tree[name]+ result, sent = await self._execute_with_file(monkeypatch, Path(path).as_uri() if as_uri else path)++ assert result.success is True+ assert sent["files"] == {"doc": os.path.realpath(path)}++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "name", ["other_run_file", "other_org_artifact", "outside", "symlink_escape", "dotdot_escape"]+ )+ async def test_file_outside_run_or_org_scope_is_refused(+ self, local_tree: dict[str, str], monkeypatch: pytest.MonkeyPatch, name: str+ ) -> None:+ result, sent = await self._execute_with_file(monkeypatch, local_tree[name])++ assert result.success is False+ assert "No permission to access local file" in (result.failure_reason or "")+ assert sent == {}