Skip to content

Automate browser based workflows with AI

feat: add residential ISP proxy pinning (#6848)

Suchintan705c563a94f7
diff --git a/alembic/versions/2026_06_26_1926-a1cad008154a_add_proxy_pin_fields.py b/alembic/versions/2026_06_26_1926-a1cad008154a_add_proxy_pin_fields.py
new file mode 100644
index 000000000..8a2a443bb
--- /dev/null
+++ b/alembic/versions/2026_06_26_1926-a1cad008154a_add_proxy_pin_fields.py
@@ -0,0 +1,36 @@
+"""add proxy pin fields
+
+Revision ID: a1cad008154a
+Revises: 45128d67bc1a
+Create Date: 2026-06-26T19:26:11.232122+00:00
+
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "a1cad008154a"
+down_revision: Union[str, None] = "45128d67bc1a"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.add_column("credentials", sa.Column("proxy_location", sa.String(), nullable=True))
+ op.add_column("credentials", sa.Column("proxy_session_id", sa.String(), nullable=True))
+ op.add_column("browser_profiles", sa.Column("proxy_location", sa.String(), nullable=True))
+ op.add_column("browser_profiles", sa.Column("proxy_session_id", sa.String(), nullable=True))
+ op.add_column("persistent_browser_sessions", sa.Column("proxy_session_id", sa.String(), nullable=True))
+
+
+def downgrade() -> None:
+ op.drop_column("persistent_browser_sessions", "proxy_session_id")
+ op.drop_column("browser_profiles", "proxy_session_id")
+ op.drop_column("browser_profiles", "proxy_location")
+ op.drop_column("credentials", "proxy_session_id")
+ op.drop_column("credentials", "proxy_location")
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.json
index 18d998fe9..183ba19e2 100644
--- a/docs/api-reference/openapi.json
+++ b/docs/api-reference/openapi.json
@@ -8640,6 +8640,35 @@
],
"title": "Source Browser Type"
},
+ "proxy_location": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ProxyLocation"
+ },
+ {
+ "$ref": "#/components/schemas/GeoTarget"
+ },
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Proxy Location"
+ },
+ "proxy_session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Proxy Session Id"
+ },
"created_at": {
"type": "string",
"format": "date-time",
@@ -9753,6 +9782,37 @@
],
"title": "Workflow Run Id",
"description": "Workflow run whose persisted session should be captured. Omit for a blank profile."
+ },
+ "proxy_location": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ProxyLocation"
+ },
+ {
+ "$ref": "#/components/schemas/GeoTarget"
+ },
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Proxy Location",
+ "description": "Optional proxy location for this profile's pinned proxy identity."
+ },
+ "proxy_session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Proxy Session Id",
+ "description": "Explicit sticky-session id for this profile's pinned proxy identity."
}
},
"type": "object",
@@ -9797,6 +9857,18 @@
"title": "Proxy Location",
"description": "\nGeographic Proxy location to route the browser traffic through. This is only available in Skyvern Cloud.\n\nAvailable geotargeting options:\n- RESIDENTIAL: the default value. Skyvern Cloud uses a random US residential proxy.\n- RESIDENTIAL_ES: Spain\n- RESIDENTIAL_IE: Ireland\n- RESIDENTIAL_GB: United Kingdom\n- RESIDENTIAL_IN: India\n- RESIDENTIAL_JP: Japan\n- RESIDENTIAL_FR: France\n- RESIDENTIAL_DE: Germany\n- RESIDENTIAL_NZ: New Zealand\n- RESIDENTIAL_PH: Philippines\n- RESIDENTIAL_KR: South Korea\n- RESIDENTIAL_SA: Saudi Arabia\n- RESIDENTIAL_ZA: South Africa\n- RESIDENTIAL_AR: Argentina\n- RESIDENTIAL_AU: Australia\n- RESIDENTIAL_BR: Brazil\n- RESIDENTIAL_TR: Turkey\n- RESIDENTIAL_CA: Canada\n- RESIDENTIAL_MX: Mexico\n- RESIDENTIAL_IT: Italy\n- RESIDENTIAL_NL: Netherlands\n- RESIDENTIAL_ISP: ISP proxy\n- US-CA: California (deprecated, routes through RESIDENTIAL_ISP)\n- US-NY: New York (deprecated, routes through RESIDENTIAL_ISP)\n- US-TX: Texas (deprecated, routes through RESIDENTIAL_ISP)\n- US-FL: Florida (deprecated, routes through RESIDENTIAL_ISP)\n- US-WA: Washington (deprecated, routes through RESIDENTIAL_ISP)\n- NONE: No proxy\n\nFor self-hosted deployments, you can pass a custom proxy URL as a dict: {\"url\": \"http://user:[email protected]:8080\"}. This routes the browser through your own proxy server and takes precedence over any globally configured proxy pool.\n Can also be a GeoTarget object for granular city/state targeting: {\"country\": \"US\", \"subdivision\": \"CA\", \"city\": \"San Francisco\"}, or a custom proxy URL dict for self-hosted deployments: {\"url\": \"http://user:[email protected]:8080\"}"
},
+ "proxy_session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Proxy Session Id",
+ "description": "Opaque Skyvern-managed proxy sticky-session id for pinned Residential ISP sessions."
+ },
"extensions": {
"anyOf": [
{
@@ -9896,6 +9968,37 @@
"azure_vault",
"bitwarden"
]
+ },
+ "proxy_location": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ProxyLocation"
+ },
+ {
+ "$ref": "#/components/schemas/GeoTarget"
+ },
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Proxy Location",
+ "description": "Optional proxy location for this credential's pinned proxy identity."
+ },
+ "proxy_session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Proxy Session Id",
+ "description": "Optional advanced reuse key for this credential's pinned proxy identity."
}
},
"type": "object",
@@ -10240,6 +10343,37 @@
"examples": [
"cfld_1234567890"
]
+ },
+ "proxy_location": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ProxyLocation"
+ },
+ {
+ "$ref": "#/components/schemas/GeoTarget"
+ },
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Proxy Location",
+ "description": "Optional proxy location used for the credential's pinned proxy identity."
+ },
+ "proxy_session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Proxy Session Id",
+ "description": "Opaque Skyvern-managed proxy sticky-session id."
}
},
"type": "object",
@@ -21416,6 +21550,37 @@
],
"title": "Description",
"description": "New description for the browser profile"
+ },
+ "proxy_location": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ProxyLocation"
+ },
+ {
+ "$ref": "#/components/schemas/GeoTarget"
+ },
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Proxy Location",
+ "description": "Optional proxy location for this profile's pinned proxy identity."
+ },
+ "proxy_session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Proxy Session Id",
+ "description": "Opaque Skyvern-managed proxy sticky-session id."
}
},
"type": "object",
diff --git a/docs/pr-screenshots/proxy-pin-browser-profile-detail.png b/docs/pr-screenshots/proxy-pin-browser-profile-detail.png
new file mode 100644
index 000000000..694c7e058
Binary files /dev/null and b/docs/pr-screenshots/proxy-pin-browser-profile-detail.png differ
diff --git a/docs/pr-screenshots/proxy-pin-create-profile-dialog.png b/docs/pr-screenshots/proxy-pin-create-profile-dialog.png
new file mode 100644
index 000000000..472c0d38b
Binary files /dev/null and b/docs/pr-screenshots/proxy-pin-create-profile-dialog.png differ
diff --git a/docs/pr-screenshots/proxy-pin-credential-modal-rotate.png b/docs/pr-screenshots/proxy-pin-credential-modal-rotate.png
new file mode 100644
index 000000000..f887ada93
Binary files /dev/null and b/docs/pr-screenshots/proxy-pin-credential-modal-rotate.png differ
diff --git a/docs/pr-screenshots/proxy-pin-credential-modal.png b/docs/pr-screenshots/proxy-pin-credential-modal.png
new file mode 100644
index 000000000..13f0ee4d4
Binary files /dev/null and b/docs/pr-screenshots/proxy-pin-credential-modal.png differ
diff --git a/skyvern-frontend/src/api/types.ts b/skyvern-frontend/src/api/types.ts
index 9e2f2c856..9bbb85841 100644
--- a/skyvern-frontend/src/api/types.ts
+++ b/skyvern-frontend/src/api/types.ts
@@ -90,6 +90,9 @@ export type GeoTarget = {
export type ProxyLocation = LegacyProxyLocation | GeoTarget | null;
+export const PINNED_RESIDENTIAL_ISP_PROXY_LOCATION =
+ "RESIDENTIAL_ISP" satisfies LegacyProxyLocation;
+
export type ArtifactApiResponse = {
created_at: string;
modified_at: string;
@@ -794,6 +797,8 @@ export type BrowserProfileApiResponse = {
name: string;
description: string | null;
source_browser_type: string | null;
+ proxy_location?: ProxyLocation | null;
+ proxy_session_id?: string | null;
created_at: string;
modified_at: string;
deleted_at: string | null;
@@ -832,6 +837,8 @@ export type CredentialApiResponse = {
user_context?: string | null;
save_browser_session_intent?: boolean | null;
folder_id?: string | null;
+ proxy_location?: ProxyLocation | null;
+ proxy_session_id?: string | null;
};
export function isPasswordCredential(
@@ -866,6 +873,9 @@ export type CreateCredentialRequest = {
credential_type: "password" | "credit_card" | "secret";
credential: PasswordCredential | CreditCardCredential | SecretCredential;
vault_type?: "custom";
+ proxy_location?: ProxyLocation | null;
+ proxy_session_id?: string | null;
+ rotate_proxy_session_id?: boolean;
};
export type PasswordCredential = {
diff --git a/skyvern-frontend/src/routes/browserProfiles/BrowserProfileDetailPage.tsx b/skyvern-frontend/src/routes/browserProfiles/BrowserProfileDetailPage.tsx
index d62ffc2ce..067b44641 100644
--- a/skyvern-frontend/src/routes/browserProfiles/BrowserProfileDetailPage.tsx
+++ b/skyvern-frontend/src/routes/browserProfiles/BrowserProfileDetailPage.tsx
@@ -1,8 +1,16 @@
-import { useState } from "react";
-import { ChevronLeftIcon, Pencil1Icon } from "@radix-ui/react-icons";
+import { useEffect, useState } from "react";
+import {
+ ChevronLeftIcon,
+ Pencil1Icon,
+ ReloadIcon,
+} from "@radix-ui/react-icons";
import { useNavigate, useParams } from "react-router-dom";
+import { PINNED_RESIDENTIAL_ISP_PROXY_LOCATION } from "@/api/types";
+import { HelpTooltip } from "@/components/HelpTooltip";
import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import { CopyText } from "@/routes/workflows/editor/Workspace";
import { basicLocalTimeFormat, basicTimeFormat } from "@/util/timeFormat";
@@ -10,11 +18,22 @@ import { basicLocalTimeFormat, basicTimeFormat } from "@/util/timeFormat";
import { DeleteBrowserProfileButton } from "./DeleteBrowserProfileButton";
import { RenameBrowserProfileDialog } from "./RenameBrowserProfileDialog";
import { useBrowserProfileQuery } from "./hooks/useBrowserProfileQuery";
+import { useUpdateBrowserProfileMutation } from "./hooks/useBrowserProfileMutations";
+
+function formatProxyIdentity(value?: string | null) {
+ if (!value) {
+ return null;
+ }
+ return `${value.slice(0, 3)}...${value.slice(-2)}`;
+}
function BrowserProfileDetailPage() {
const navigate = useNavigate();
const { profileId } = useParams<{ profileId: string }>();
const [renameOpen, setRenameOpen] = useState(false);
+ const [pinResidentialIspProxy, setPinResidentialIspProxy] = useState(false);
+ const [rotateProxyPin, setRotateProxyPin] = useState(false);
+ const updateProfileMutation = useUpdateBrowserProfileMutation();
const {
data: profile,
@@ -22,6 +41,37 @@ function BrowserProfileDetailPage() {
isError,
} = useBrowserProfileQuery(profileId);
+ useEffect(() => {
+ if (!profile) {
+ return;
+ }
+ setPinResidentialIspProxy(Boolean(profile.proxy_session_id));
+ setRotateProxyPin(false);
+ }, [profile]);
+
+ const existingProxyPinEnabled = Boolean(profile?.proxy_session_id);
+ const existingProxyIdentity = formatProxyIdentity(profile?.proxy_session_id);
+ const proxyPinChanged = Boolean(
+ profile &&
+ (pinResidentialIspProxy !== existingProxyPinEnabled ||
+ (pinResidentialIspProxy && rotateProxyPin)),
+ );
+
+ const handleSaveProxyPin = () => {
+ if (!profile || !proxyPinChanged) {
+ return;
+ }
+ updateProfileMutation.mutate({
+ profileId: profile.browser_profile_id,
+ proxy_location: pinResidentialIspProxy
+ ? PINNED_RESIDENTIAL_ISP_PROXY_LOCATION
+ : null,
+ proxy_session_id: pinResidentialIspProxy ? undefined : null,
+ rotate_proxy_session_id:
+ pinResidentialIspProxy && rotateProxyPin ? true : undefined,
+ });
+ };
+
return (
<div className="space-y-5">
<div>
@@ -124,6 +174,91 @@ function BrowserProfileDetailPage() {
{basicLocalTimeFormat(profile.modified_at)}
</dd>
</dl>
+
+ <div className="mt-6 border-t border-slate-700 pt-4">
+ <div className="flex items-start gap-3">
+ <Checkbox
+ id="browser-profile-pin-residential-isp-proxy"
+ checked={pinResidentialIspProxy}
+ onCheckedChange={(checked) =>
+ setPinResidentialIspProxy(checked === true)
+ }
+ disabled={Boolean(profile.deleted_at)}
+ className="mt-0.5"
+ />
+ <div className="space-y-1">
+ <div className="flex items-center gap-2">
+ <Label
+ htmlFor="browser-profile-pin-residential-isp-proxy"
+ className="cursor-pointer text-sm font-medium"
+ >
+ Use a consistent IP address
+ </Label>
+ <HelpTooltip content="Routes browser sessions launched with this profile through the same residential IP to reduce account security prompts caused by changing IPs." />
+ </div>
+ <p className="text-xs leading-5 text-muted-foreground">
+ Helps profiles keep the same residential IP across launches,
+ so saved logins are less likely to be challenged.
+ </p>
+ {pinResidentialIspProxy &&
+ existingProxyIdentity &&
+ profile.proxy_session_id && (
+ <div className="space-y-2">
+ <p className="flex items-center gap-1 text-xs text-slate-300">
+ <span>
+ Consistent IP active: identity{" "}
+ {existingProxyIdentity}
+ </span>
+ <CopyText
+ className="opacity-75 hover:opacity-100"
+ text={profile.proxy_session_id}
+ />
+ </p>
+ <div className="flex flex-wrap items-center gap-2">
+ <Button
+ type="button"
+ variant="secondary"
+ size="sm"
+ onClick={() => setRotateProxyPin(true)}
+ disabled={
+ Boolean(profile.deleted_at) || rotateProxyPin
+ }
+ >
+ Rotate IP identity
+ </Button>
+ {rotateProxyPin && (
+ <span className="text-xs text-slate-300">
+ A new IP identity will be created when you save.
+ </span>
+ )}
+ </div>
+ </div>
+ )}
+ {pinResidentialIspProxy && !existingProxyIdentity && (
+ <p className="text-xs text-slate-300">
+ Skyvern will create an IP identity for this profile when
+ you save.
+ </p>
+ )}
+ </div>
+ </div>
+ <div className="mt-4 flex justify-end">
+ <Button
+ variant="secondary"
+ onClick={handleSaveProxyPin}
+ disabled={
+ !proxyPinChanged ||
+ updateProfileMutation.isPending ||
+ Boolean(profile.deleted_at)
+ }
+ >
+ {updateProfileMutation.isPending && (
+ <ReloadIcon className="mr-2 size-4 animate-spin" />
+ )}
+ Save IP Settings
+ </Button>
+ </div>
+ </div>
</div>
<RenameBrowserProfileDialog
diff --git a/skyvern-frontend/src/routes/browserProfiles/CreateBrowserProfileButton.tsx b/skyvern-frontend/src/routes/browserProfiles/CreateBrowserProfileButton.tsx
index 6a111b76e..d5851b1a6 100644
--- a/skyvern-frontend/src/routes/browserProfiles/CreateBrowserProfileButton.tsx
+++ b/skyvern-frontend/src/routes/browserProfiles/CreateBrowserProfileButton.tsx
@@ -1,6 +1,18 @@
+import { useState } from "react";
import { PlusIcon, ReloadIcon } from "@radix-ui/react-icons";
+import { PINNED_RESIDENTIAL_ISP_PROXY_LOCATION } from "@/api/types";
+import { HelpTooltip } from "@/components/HelpTooltip";
import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Label } from "@/components/ui/label";
import { useCreateBrowserSessionMutation } from "@/routes/browserSessions/hooks/useCreateBrowserSessionMutation";
import { useBrowserProfileCreateStore } from "@/store/useBrowserProfileCreateStore";
@@ -13,6 +25,8 @@ function CreateBrowserProfileButton({
size = "default",
label = "Create a Browser Profile",
}: Props) {
+ const [open, setOpen] = useState(false);
+ const [pinResidentialIspProxy, setPinResidentialIspProxy] = useState(false);
const createBrowserSessionMutation = useCreateBrowserSessionMutation();
const isBackgroundCreateInProgress = useBrowserProfileCreateStore(
(state) => state.active !== null,
@@ -21,30 +35,83 @@ function CreateBrowserProfileButton({
const disabled =
createBrowserSessionMutation.isPending || isBackgroundCreateInProgress;
+ const handleCreate = () => {
+ createBrowserSessionMutation.mutate({
+ proxyLocation: pinResidentialIspProxy
+ ? PINNED_RESIDENTIAL_ISP_PROXY_LOCATION
+ : null,
+ proxySessionId: null,
+ timeout: null,
+ generateBrowserProfile: true,
+ });
+ setOpen(false);
+ };
+
return (
- <Button
- size={size}
- disabled={disabled}
- title={
- isBackgroundCreateInProgress
- ? "A browser profile is already being created"
- : undefined
- }
- onClick={() => {
- createBrowserSessionMutation.mutate({
- proxyLocation: null,
- timeout: null,
- generateBrowserProfile: true,
- });
- }}
- >
- {createBrowserSessionMutation.isPending ? (
- <ReloadIcon className="mr-2 h-4 w-4 animate-spin" />
- ) : (
- <PlusIcon className="mr-2 h-4 w-4" />
- )}
- {label}
- </Button>
+ <>
+ <Button
+ size={size}
+ disabled={disabled}
+ title={
+ isBackgroundCreateInProgress
+ ? "A browser profile is already being created"
+ : undefined
+ }
+ onClick={() => setOpen(true)}
+ >
+ {createBrowserSessionMutation.isPending ? (
+ <ReloadIcon className="mr-2 h-4 w-4 animate-spin" />
+ ) : (
+ <PlusIcon className="mr-2 h-4 w-4" />
+ )}
+ {label}
+ </Button>
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent onCloseAutoFocus={(event) => event.preventDefault()}>
+ <DialogHeader>
+ <DialogTitle>Create Browser Profile</DialogTitle>
+ </DialogHeader>
+ <div className="space-y-3 py-2">
+ <div className="flex items-center gap-3">
+ <Checkbox
+ id="create-browser-profile-pin-residential-isp-proxy"
+ checked={pinResidentialIspProxy}
+ onCheckedChange={(checked) =>
+ setPinResidentialIspProxy(checked === true)
+ }
+ />
+ <div className="space-y-1">
+ <div className="flex items-center gap-2">
+ <Label
+ htmlFor="create-browser-profile-pin-residential-isp-proxy"
+ className="cursor-pointer text-sm font-medium"
+ >
+ Use a consistent IP address
+ </Label>
+ <HelpTooltip content="Starts the capture browser on a stable residential IP so the saved login is less likely to be challenged later." />
+ </div>
+ <p className="text-xs leading-5 text-muted-foreground">
+ Skyvern will create a residential IP identity for this
+ profile.
+ </p>
+ </div>
+ </div>
+ </div>
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={() => setOpen(false)}
+ >
+ Cancel
+ </Button>
+ <Button type="button" onClick={handleCreate}>
+ Create
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
);
}
diff --git a/skyvern-frontend/src/routes/browserProfiles/hooks/useBrowserProfileMutations.test.tsx b/skyvern-frontend/src/routes/browserProfiles/hooks/useBrowserProfileMutations.test.tsx
new file mode 100644
index 000000000..51e1b92d4
--- /dev/null
+++ b/skyvern-frontend/src/routes/browserProfiles/hooks/useBrowserProfileMutations.test.tsx
@@ -0,0 +1,103 @@
+// @vitest-environment jsdom
+
+import type { ReactNode } from "react";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { PINNED_RESIDENTIAL_ISP_PROXY_LOCATION } from "@/api/types";
+
+const { mockPatch } = vi.hoisted(() => ({ mockPatch: vi.fn() }));
+
+vi.mock("@/api/AxiosClient", () => ({
+ getClient: () => Promise.resolve({ patch: mockPatch }),
+}));
+
+vi.mock("@/hooks/useCredentialGetter", () => ({
+ useCredentialGetter: () => () => Promise.resolve("test-token"),
+}));
+
+vi.mock("@/components/ui/use-toast", () => ({ toast: vi.fn() }));
+
+import { useUpdateBrowserProfileMutation } from "./useBrowserProfileMutations";
+
+function wrapper({ children }: { children: ReactNode }) {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+}
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("useUpdateBrowserProfileMutation proxy pin payloads", () => {
+ it("omits proxy_session_id when keeping the existing consistent IP identity", async () => {
+ mockPatch.mockResolvedValue({ data: {} });
+ const { result } = renderHook(() => useUpdateBrowserProfileMutation(), {
+ wrapper,
+ });
+
+ act(() => {
+ result.current.mutate({
+ profileId: "bp_123",
+ proxy_location: PINNED_RESIDENTIAL_ISP_PROXY_LOCATION,
+ proxy_session_id: undefined,
+ });
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(mockPatch).toHaveBeenCalledWith("/browser_profiles/bp_123", {
+ proxy_location: PINNED_RESIDENTIAL_ISP_PROXY_LOCATION,
+ });
+ });
+
+ it("sends rotate_proxy_session_id when rotating the consistent IP identity", async () => {
+ mockPatch.mockResolvedValue({ data: {} });
+ const { result } = renderHook(() => useUpdateBrowserProfileMutation(), {
+ wrapper,
+ });
+
+ act(() => {
+ result.current.mutate({
+ profileId: "bp_123",
+ proxy_location: PINNED_RESIDENTIAL_ISP_PROXY_LOCATION,
+ rotate_proxy_session_id: true,
+ });
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(mockPatch).toHaveBeenCalledWith("/browser_profiles/bp_123", {
+ proxy_location: PINNED_RESIDENTIAL_ISP_PROXY_LOCATION,
+ rotate_proxy_session_id: true,
+ });
+ });
+
+ it("sends null proxy fields when disabling consistent IP", async () => {
+ mockPatch.mockResolvedValue({ data: {} });
+ const { result } = renderHook(() => useUpdateBrowserProfileMutation(), {
+ wrapper,
+ });
+
+ act(() => {
+ result.current.mutate({
+ profileId: "bp_123",
+ proxy_location: null,
+ proxy_session_id: null,
+ });
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(mockPatch).toHaveBeenCalledWith("/browser_profiles/bp_123", {
+ proxy_location: null,
+ proxy_session_id: null,
+ });
+ });
+});
diff --git a/skyvern-frontend/src/routes/browserProfiles/hooks/useBrowserProfileMutations.ts b/skyvern-frontend/src/routes/browserProfiles/hooks/useBrowserProfileMutations.ts
index f92758480..a678a0900 100644
--- a/skyvern-frontend/src/routes/browserProfiles/hooks/useBrowserProfileMutations.ts
+++ b/skyvern-frontend/src/routes/browserProfiles/hooks/useBrowserProfileMutations.ts
@@ -2,7 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { getClient } from "@/api/AxiosClient";
-import { BrowserProfileApiResponse } from "@/api/types";
+import { BrowserProfileApiResponse, ProxyLocation } from "@/api/types";
import { toast } from "@/components/ui/use-toast";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
@@ -10,6 +10,9 @@ type UpdateBrowserProfileInput = {
profileId: string;
name?: string;
description?: string | null;
+ proxy_location?: ProxyLocation | null;
+ proxy_session_id?: string | null;
+ rotate_proxy_session_id?: boolean;
};
function useUpdateBrowserProfileMutation() {
@@ -21,15 +24,28 @@ function useUpdateBrowserProfileMutation() {
profileId,
name,
description,
+ proxy_location,
+ proxy_session_id,
+ rotate_proxy_session_id,
}: UpdateBrowserProfileInput) => {
const client = await getClient(credentialGetter, "sans-api-v1");
- const payload: Record<string, string | null> = {};
+ const payload: Record<string, string | boolean | ProxyLocation | null> =
+ {};
if (name !== undefined) {
payload.name = name;
}
if (description !== undefined) {
payload.description = description;
}
+ if (proxy_location !== undefined) {
+ payload.proxy_location = proxy_location;
+ }
+ if (proxy_session_id !== undefined) {
+ payload.proxy_session_id = proxy_session_id;
+ }
+ if (rotate_proxy_session_id !== undefined) {
+ payload.rotate_proxy_session_id = rotate_proxy_session_id;
+ }
return client
.patch<BrowserProfileApiResponse>(
`/browser_profiles/${profileId}`,
diff --git a/skyvern-frontend/src/routes/browserSessions/hooks/useCreateBrowserSessionMutation.test.tsx b/skyvern-frontend/src/routes/browserSessions/hooks/useCreateBrowserSessionMutation.test.tsx
new file mode 100644
index 000000000..8c37ebc09
--- /dev/null
+++ b/skyvern-frontend/src/routes/browserSessions/hooks/useCreateBrowserSessionMutation.test.tsx
@@ -0,0 +1,87 @@
+// @vitest-environment jsdom
+
+import type { ReactNode } from "react";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { MemoryRouter } from "react-router-dom";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { PINNED_RESIDENTIAL_ISP_PROXY_LOCATION } from "@/api/types";
+
+const { mockNavigate, mockPost } = vi.hoisted(() => ({
+ mockNavigate: vi.fn(),
+ mockPost: vi.fn(),
+}));
+
+vi.mock("@/api/AxiosClient", () => ({
+ getClient: () => Promise.resolve({ post: mockPost }),
+}));
+
+vi.mock("@/hooks/useCredentialGetter", () => ({
+ useCredentialGetter: () => () => Promise.resolve("test-token"),
+}));
+
+vi.mock("@/components/ui/use-toast", () => ({ toast: vi.fn() }));
+
+vi.mock("react-router-dom", async () => {
+ const actual =
+ await vi.importActual<typeof import("react-router-dom")>(
+ "react-router-dom",
+ );
+ return {
+ ...actual,
+ useNavigate: () => mockNavigate,
+ };
+});
+
+import { useCreateBrowserSessionMutation } from "./useCreateBrowserSessionMutation";
+
+function wrapper({ children }: { children: ReactNode }) {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+
+ return (
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter>{children}</MemoryRouter>
+ </QueryClientProvider>
+ );
+}
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("useCreateBrowserSessionMutation proxy pin payloads", () => {
+ it("sends null proxy_session_id when creating a pinned profile", async () => {
+ mockPost.mockResolvedValue({
+ data: { browser_session_id: "pbs_123" },
+ });
+ const { result } = renderHook(() => useCreateBrowserSessionMutation(), {
+ wrapper,
+ });
+
+ act(() => {
+ result.current.mutate({
+ proxyLocation: PINNED_RESIDENTIAL_ISP_PROXY_LOCATION,
+ proxySessionId: null,
+ timeout: null,
+ generateBrowserProfile: true,
+ });
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(mockPost).toHaveBeenCalledWith("/browser_sessions", {
+ proxy_location: PINNED_RESIDENTIAL_ISP_PROXY_LOCATION,
+ proxy_session_id: null,
+ timeout: null,
+ extensions: [],
+ browser_type: null,
+ generate_browser_profile: true,
+ });
+ expect(mockNavigate).toHaveBeenCalledWith("/browser-session/pbs_123");
+ });
+});
diff --git a/skyvern-frontend/src/routes/browserSessions/hooks/useCreateBrowserSessionMutation.ts b/skyvern-frontend/src/routes/browserSessions/hooks/useCreateBrowserSessionMutation.ts
index dc1526ee6..5027dd985 100644
--- a/skyvern-frontend/src/routes/browserSessions/hooks/useCreateBrowserSessionMutation.ts
+++ b/skyvern-frontend/src/routes/browserSessions/hooks/useCreateBrowserSessionMutation.ts
@@ -19,12 +19,14 @@ function useCreateBrowserSessionMutation() {
return useMutation({
mutationFn: async ({
proxyLocation = null,
+ proxySessionId = null,
timeout = null,
extensions = [],
browserType = null,
generateBrowserProfile = false,
}: {
proxyLocation: ProxyLocation | null;
+ proxySessionId?: string | null;
timeout: number | null;
extensions?: BrowserSessionExtension[];
browserType?: BrowserSessionType | null;
@@ -35,6 +37,7 @@ function useCreateBrowserSessionMutation() {
"/browser_sessions",
{
proxy_location: proxyLocation,
+ proxy_session_id: proxySessionId,
timeout,
extensions,
browser_type: browserType,
diff --git a/skyvern-frontend/src/routes/credentials/CredentialsModal.tsx b/skyvern-frontend/src/routes/credentials/CredentialsModal.tsx
index 633a1cedd..0fb5c572c 100644
--- a/skyvern-frontend/src/routes/credentials/CredentialsModal.tsx
+++ b/skyvern-frontend/src/routes/credentials/CredentialsModal.tsx
@@ -24,11 +24,13 @@ import {
type CreditCardBillingAddress,
type CreditCardCredential,
type CredentialApiResponse,
+ PINNED_RESIDENTIAL_ISP_PROXY_LOCATION,
isPasswordCredential,
isCreditCardCredential,
isSecretCredential,
type TestCredentialStatusResponse,
type TestLoginResponse,
+ type ProxyLocation,
} from "@/api/types";
import { getClient } from "@/api/AxiosClient";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
@@ -191,6 +193,19 @@ type Props = {
) => void;
};
+type ProxyPinPayload = {
+ proxy_location: ProxyLocation | null;
+ proxy_session_id?: string | null;
+ rotate_proxy_session_id?: boolean;
+};
+
+function formatProxyIdentity(value?: string | null) {
+ if (!value) {
+ return null;
+ }
+ return `${value.slice(0, 3)}...${value.slice(-2)}`;
+}
+
function CredentialsModal({
onCredentialCreated,
isOpen: controlledIsOpen,
@@ -246,6 +261,11 @@ function CredentialsModal({
const [testAndSave, setTestAndSave] = useState(false);
const [testUrl, setTestUrl] = useState("");
const [userContext, setUserContext] = useState("");
+ const [pinResidentialIspProxy, setPinResidentialIspProxy] = useState(false);
+ const [rotateProxyPin, setRotateProxyPin] = useState(false);
+ const existingProxyIdentity = formatProxyIdentity(
+ editingCredential?.proxy_session_id,
+ );
const [testStatus, setTestStatus] = useState<
"idle" | "testing" | "completed" | "failed" | "profile_failed"
>("idle");
@@ -269,6 +289,30 @@ function CredentialsModal({
// Guards against in-flight poll responses updating state after cancel/close
const pollCancelledRef = useRef(false);
+ const getProxyPinPayload = useCallback((): ProxyPinPayload => {
+ if (!pinResidentialIspProxy) {
+ return {
+ proxy_location: null,
+ proxy_session_id: null,
+ };
+ }
+ return {
+ proxy_location: PINNED_RESIDENTIAL_ISP_PROXY_LOCATION,
+ ...(rotateProxyPin ? { rotate_proxy_session_id: true } : {}),
+ };
+ }, [pinResidentialIspProxy, rotateProxyPin]);
+
+ const hasProxyPinChanges = useCallback(() => {
+ if (!editingCredential) {
+ return pinResidentialIspProxy;
+ }
+ const existingPinEnabled = Boolean(editingCredential.proxy_session_id);
+ return (
+ pinResidentialIspProxy !== existingPinEnabled ||
+ (pinResidentialIspProxy && rotateProxyPin)
+ );
+ }, [editingCredential, pinResidentialIspProxy, rotateProxyPin]);
+
// Captures save intent before mutation fires — testAndSave/testUrl may be
// reset by the time onSuccess runs, so we snapshot them here.
const saveIntentRef = useRef<{
@@ -277,12 +321,18 @@ function CredentialsModal({
testUrl: string;
userContext: string;
name: string;
+ proxyLocation: ProxyLocation | null;
+ proxySessionId?: string | null;
+ proxyPinChanged: boolean;
}>({
shouldTestAfterSave: false,
saveBrowserSessionIntent: false,
testUrl: "",
userContext: "",
name: "",
+ proxyLocation: null,
+ proxySessionId: null,
+ proxyPinChanged: false,
});
// Cleanup polling on unmount
@@ -319,6 +369,8 @@ function CredentialsModal({
passwordCredentialValues.totp_type,
passwordCredentialValues.totp_identifier,
testUrl,
+ pinResidentialIspProxy,
+ rotateProxyPin,
]);
const formInitializedRef = useRef(false);
@@ -352,6 +404,8 @@ function CredentialsModal({
if (editingCredential.user_context) {
setUserContext(editingCredential.user_context);
}
+ setPinResidentialIspProxy(Boolean(editingCredential.proxy_session_id));
+ setRotateProxyPin(false);
if (isPasswordCredential(cred)) {
setPasswordCredentialValues({
name: editingCredential.name,
@@ -419,12 +473,17 @@ function CredentialsModal({
pollErrorCountRef.current = 0;
pollCancelledRef.current = false;
setUserContext("");
+ setPinResidentialIspProxy(false);
+ setRotateProxyPin(false);
saveIntentRef.current = {
shouldTestAfterSave: false,
saveBrowserSessionIntent: false,
testUrl: "",
userContext: "",
name: "",
+ proxyLocation: null,
+ proxySessionId: null,
+ proxyPinChanged: false,
};
if (pollIntervalRef.current) {
clearTimeout(pollIntervalRef.current);
@@ -561,6 +620,7 @@ function CredentialsModal({
const startTest = useCallback(async () => {
try {
const client = await getClient(credentialGetter, "sans-api-v1");
+ const proxyPinPayload = getProxyPinPayload();
const response = await client.post<TestLoginResponse>(
`/credentials/test-login`,
{
@@ -572,6 +632,7 @@ function CredentialsModal({
totp_identifier:
passwordCredentialValues.totp_identifier.trim() || null,
user_context: userContext.trim() || null,
+ ...proxyPinPayload,
},
);
const data = response.data;
@@ -619,6 +680,7 @@ function CredentialsModal({
passwordCredentialValues,
userContext,
pollTestStatus,
+ getProxyPinPayload,
]);
const createCredentialMutation = useMutation({
@@ -783,15 +845,23 @@ function CredentialsModal({
tested_url,
user_context,
save_browser_session_intent,
+ proxy_location,
+ proxy_session_id,
+ rotate_proxy_session_id,
}: {
id: string;
name: string;
tested_url?: string;
user_context?: string | null;
save_browser_session_intent?: boolean;
+ proxy_location?: ProxyLocation | null;
+ proxy_session_id?: string | null;
+ rotate_proxy_session_id?: boolean;
}) => {
const client = await getClient(credentialGetter, "sans-api-v1");
- const body: Record<string, string | boolean | null> = { name };
+ const body: Record<string, string | boolean | ProxyLocation | null> = {
+ name,
+ };
if (tested_url) {
body.tested_url = tested_url;
}
@@ -801,6 +871,15 @@ function CredentialsModal({
if (save_browser_session_intent !== undefined) {
body.save_browser_session_intent = save_browser_session_intent;
}
+ if (proxy_location !== undefined) {
+ body.proxy_location = proxy_location;
+ }
+ if (proxy_session_id !== undefined) {
+ body.proxy_session_id = proxy_session_id;
+ }
+ if (rotate_proxy_session_id !== undefined) {
+ body.rotate_proxy_session_id = rotate_proxy_session_id;
+ }
const response = await client.patch<CredentialApiResponse>(
`/credentials/${id}`,
body,
@@ -834,20 +913,6 @@ function CredentialsModal({
? updateCredentialMutation
: createCredentialMutation;
- const handleRenameOnly = (name: string) => {
- if (!editingCredential) return;
- // Skip the API call if the name hasn't actually changed
- if (name === editingCredential.name) {
- reset();
- setIsOpen(false);
- return;
- }
- renameCredentialMutation.mutate({
- id: editingCredential.credential_id,
- name,
- });
- };
-
const handleSave = () => {
const name =
type === CredentialModalTypes.PASSWORD
@@ -864,16 +929,25 @@ function CredentialsModal({
return;
}
+ const proxyPinPayload = getProxyPinPayload();
+ const proxyPinChanged = hasProxyPinChanges();
+ const credentialSaveProxyPinPayload =
+ !isEditMode || proxyPinChanged ? proxyPinPayload : {};
+
// In edit mode, use editingGroups to determine what changed (type-agnostic)
if (isEditMode && editingCredential) {
- if (!editingGroups.name && !editingGroups.values) {
+ if (!editingGroups.name && !editingGroups.values && !proxyPinChanged) {
// Nothing was edited — close silently
reset();
setIsOpen(false);
return;
}
- if (editingGroups.name && !editingGroups.values) {
- handleRenameOnly(name);
+ if (!editingGroups.values) {
+ renameCredentialMutation.mutate({
+ id: editingCredential.credential_id,
+ name,
+ ...(proxyPinChanged ? proxyPinPayload : {}),
+ });
return;
}
}
@@ -906,6 +980,7 @@ function CredentialsModal({
tested_url: url || undefined,
user_context: ctx || null,
save_browser_session_intent: true,
+ ...proxyPinPayload,
});
return;
}
@@ -928,6 +1003,9 @@ function CredentialsModal({
testUrl: testUrl.trim(),
userContext: userContext.trim(),
name,
+ proxyLocation: proxyPinPayload.proxy_location,
+ proxySessionId: proxyPinPayload.proxy_session_id,
+ proxyPinChanged,
};
activeMutation.mutate({
@@ -941,6 +1019,7 @@ function CredentialsModal({
totp_identifier: totpIdentifier === "" ? null : totpIdentifier,
},
...(vaultType === "custom" ? { vault_type: "custom" } : {}),
+ ...credentialSaveProxyPinPayload,
});
} else if (type === CredentialModalTypes.CREDIT_CARD) {
const cardNumber = creditCardCredentialValues.cardNumber.trim();
@@ -1016,11 +1095,22 @@ function CredentialsModal({
...(billingPhone ? { billing_phone: billingPhone } : {}),
...(metadata ? { metadata } : {}),
};
+ saveIntentRef.current = {
+ shouldTestAfterSave: false,
+ saveBrowserSessionIntent: false,
+ testUrl: "",
+ userContext: "",
+ name,
+ proxyLocation: proxyPinPayload.proxy_location,
+ proxySessionId: proxyPinPayload.proxy_session_id,
+ proxyPinChanged,
+ };
activeMutation.mutate({
name,
credential_type: "credit_card",
credential: credentialPayload,
...(vaultType === "custom" ? { vault_type: "custom" } : {}),
+ ...credentialSaveProxyPinPayload,
});
} else if (type === CredentialModalTypes.SECRET) {
const secretValue = secretCredentialValues.secretValue.trim();
@@ -1035,6 +1125,16 @@ function CredentialsModal({
return;
}
+ saveIntentRef.current = {
+ shouldTestAfterSave: false,
+ saveBrowserSessionIntent: false,
+ testUrl: "",
+ userContext: "",
+ name,
+ proxyLocation: proxyPinPayload.proxy_location,
+ proxySessionId: proxyPinPayload.proxy_session_id,
+ proxyPinChanged,
+ };
activeMutation.mutate({
name,
credential_type: "secret",
@@ -1043,6 +1143,7 @@ function CredentialsModal({
secret_label: secretLabel === "" ? null : secretLabel,
},
...(vaultType === "custom" ? { vault_type: "custom" } : {}),
+ ...credentialSaveProxyPinPayload,
});
}
};
@@ -1097,6 +1198,66 @@ function CredentialsModal({
? getAuthenticatorKeyError(passwordCredentialValues)
: null;
+ const proxyPinContent = (
+ <div className="space-y-3 border-t border-slate-700 pt-4">
+ <div className="flex items-start gap-3">
+ <Checkbox
+ id="pin-residential-isp-proxy"
+ checked={pinResidentialIspProxy}
+ onCheckedChange={(checked) =>
+ setPinResidentialIspProxy(checked === true)
+ }
+ disabled={isTestInProgress}
+ className="mt-0.5"
+ />
+ <div className="space-y-1">
+ <div className="flex items-center gap-2">
+ <Label
+ htmlFor="pin-residential-isp-proxy"
+ className="cursor-pointer text-sm font-medium"
+ >
+ Use a consistent IP address
+ </Label>
+ <HelpTooltip content="Routes this credential through the same residential IP each time to reduce account security prompts caused by changing IPs." />
+ </div>
+ <p className="text-xs leading-5 text-muted-foreground">
+ Helps avoid extra 2FA, captchas, or temporary locks caused by
+ signing in from a new location.
+ </p>
+ {pinResidentialIspProxy && existingProxyIdentity && (
+ <div className="space-y-2">
+ <p className="text-xs text-slate-300">
+ Consistent IP active: identity {existingProxyIdentity}
+ </p>
+ <div className="flex flex-wrap items-center gap-2">
+ <Button
+ type="button"
+ variant="secondary"
+ size="sm"
+ onClick={() => setRotateProxyPin(true)}
+ disabled={isTestInProgress || rotateProxyPin}
+ >
+ Rotate IP identity
+ </Button>
+ {rotateProxyPin && (
+ <span className="text-xs text-slate-300">
+ A new IP identity will be created when you save.
+ </span>
+ )}
+ </div>
+ </div>
+ )}
+ {pinResidentialIspProxy && !existingProxyIdentity && (
+ <p className="text-xs text-slate-300">
+ Skyvern will create an IP identity for this credential when you
+ save.
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+
const credentialContent = (() => {
if (type === CredentialModalTypes.PASSWORD) {
return (
@@ -1386,6 +1547,7 @@ function CredentialsModal({
</Alert>
)}
{credentialContent}
+ {proxyPinContent}
<DialogFooter>
<div className="flex w-full items-center justify-end gap-2">
diff --git a/skyvern/client/client.py b/skyvern/client/client.py
index e895338ae..0a6c887d8 100644
--- a/skyvern/client/client.py
+++ b/skyvern/client/client.py
@@ -1620,6 +1620,8 @@ class Skyvern:
description: typing.Optional[str] = OMIT,
browser_session_id: typing.Optional[str] = OMIT,
workflow_run_id: typing.Optional[str] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> BrowserProfile:
"""
@@ -1663,6 +1665,8 @@ class Skyvern:
description=description,
browser_session_id=browser_session_id,
workflow_run_id=workflow_run_id,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
request_options=request_options,
)
return _response.data
@@ -1738,6 +1742,9 @@ class Skyvern:
*,
name: typing.Optional[str] = OMIT,
description: typing.Optional[str] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
+ rotate_proxy_session_id: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> BrowserProfile:
"""
@@ -1754,6 +1761,9 @@ class Skyvern:
description : typing.Optional[str]
New description for the browser profile
+ rotate_proxy_session_id : typing.Optional[bool]
+ Rotate the Skyvern-managed proxy sticky-session id for this browser profile.
+
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -1774,7 +1784,13 @@ class Skyvern:
)
"""
_response = self._raw_client.update_browser_profile(
- profile_id, name=name, description=description, request_options=request_options
+ profile_id,
+ name=name,
+ description=description,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
+ rotate_proxy_session_id=rotate_proxy_session_id,
+ request_options=request_options,
)
return _response.data
@@ -1811,6 +1827,7 @@ class Skyvern:
*,
timeout: typing.Optional[int] = OMIT,
proxy_location: typing.Optional[CreateBrowserSessionRequestProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
extensions: typing.Optional[typing.Sequence[Extensions]] = OMIT,
browser_type: typing.Optional[PersistentBrowserType] = OMIT,
browser_profile_id: typing.Optional[str] = OMIT,
@@ -1861,6 +1878,9 @@ class Skyvern:
For self-hosted deployments, you can pass a custom proxy URL as a dict: {"url": "http://user:[email protected]:8080"}. This routes the browser through your own proxy server and takes precedence over any globally configured proxy pool.
Can also be a GeoTarget object for granular city/state targeting: {"country": "US", "subdivision": "CA", "city": "San Francisco"}, or a custom proxy URL dict for self-hosted deployments: {"url": "http://user:[email protected]:8080"}
+ proxy_session_id : typing.Optional[str]
+ Opaque Skyvern-managed proxy sticky-session id for pinned Residential ISP sessions.
+
extensions : typing.Optional[typing.Sequence[Extensions]]
A list of extensions to install in the browser session.
@@ -1890,6 +1910,7 @@ class Skyvern:
_response = self._raw_client.create_browser_session(
timeout=timeout,
proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
extensions=extensions,
browser_type=browser_type,
browser_profile_id=browser_profile_id,
@@ -2093,6 +2114,9 @@ class Skyvern:
credential_type: SkyvernForgeSdkSchemasCredentialsCredentialType,
credential: CreateCredentialRequestCredential,
vault_type: typing.Optional[CredentialVaultType] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
+ rotate_proxy_session_id: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> CredentialResponse:
"""
@@ -2112,6 +2136,9 @@ class Skyvern:
vault_type : typing.Optional[CredentialVaultType]
Which vault to store this credential in. If omitted, uses the instance default. Use this to mix Skyvern-hosted and custom credentials within the same organization.
+ rotate_proxy_session_id : typing.Optional[bool]
+ Rotate the Skyvern-managed proxy sticky-session id for this credential.
+
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -2141,6 +2168,9 @@ class Skyvern:
credential_type=credential_type,
credential=credential,
vault_type=vault_type,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
+ rotate_proxy_session_id=rotate_proxy_session_id,
request_options=request_options,
)
return _response.data
@@ -2153,6 +2183,9 @@ class Skyvern:
credential_type: SkyvernForgeSdkSchemasCredentialsCredentialType,
credential: CreateCredentialRequestCredential,
vault_type: typing.Optional[CredentialVaultType] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
+ rotate_proxy_session_id: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> CredentialResponse:
"""
@@ -2175,6 +2208,9 @@ class Skyvern:
vault_type : typing.Optional[CredentialVaultType]
Which vault to store this credential in. If omitted, uses the instance default. Use this to mix Skyvern-hosted and custom credentials within the same organization.
+ rotate_proxy_session_id : typing.Optional[bool]
+ Rotate the Skyvern-managed proxy sticky-session id for this credential.
+
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -2206,6 +2242,9 @@ class Skyvern:
credential_type=credential_type,
credential=credential,
vault_type=vault_type,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
+ rotate_proxy_session_id=rotate_proxy_session_id,
request_options=request_options,
)
return _response.data
@@ -4568,6 +4607,8 @@ class AsyncSkyvern:
description: typing.Optional[str] = OMIT,
browser_session_id: typing.Optional[str] = OMIT,
workflow_run_id: typing.Optional[str] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> BrowserProfile:
"""
@@ -4619,6 +4660,8 @@ class AsyncSkyvern:
description=description,
browser_session_id=browser_session_id,
workflow_run_id=workflow_run_id,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
request_options=request_options,
)
return _response.data
@@ -4710,6 +4753,9 @@ class AsyncSkyvern:
*,
name: typing.Optional[str] = OMIT,
description: typing.Optional[str] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
+ rotate_proxy_session_id: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> BrowserProfile:
"""
@@ -4726,6 +4772,9 @@ class AsyncSkyvern:
description : typing.Optional[str]
New description for the browser profile
+ rotate_proxy_session_id : typing.Optional[bool]
+ Rotate the Skyvern-managed proxy sticky-session id for this browser profile.
+
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -4754,7 +4803,13 @@ class AsyncSkyvern:
asyncio.run(main())
"""
_response = await self._raw_client.update_browser_profile(
- profile_id, name=name, description=description, request_options=request_options
+ profile_id,
+ name=name,
+ description=description,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
+ rotate_proxy_session_id=rotate_proxy_session_id,
+ request_options=request_options,
)
return _response.data
@@ -4799,6 +4854,7 @@ class AsyncSkyvern:
*,
timeout: typing.Optional[int] = OMIT,
proxy_location: typing.Optional[CreateBrowserSessionRequestProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
extensions: typing.Optional[typing.Sequence[Extensions]] = OMIT,
browser_type: typing.Optional[PersistentBrowserType] = OMIT,
browser_profile_id: typing.Optional[str] = OMIT,
@@ -4849,6 +4905,9 @@ class AsyncSkyvern:
For self-hosted deployments, you can pass a custom proxy URL as a dict: {"url": "http://user:[email protected]:8080"}. This routes the browser through your own proxy server and takes precedence over any globally configured proxy pool.
Can also be a GeoTarget object for granular city/state targeting: {"country": "US", "subdivision": "CA", "city": "San Francisco"}, or a custom proxy URL dict for self-hosted deployments: {"url": "http://user:[email protected]:8080"}
+ proxy_session_id : typing.Optional[str]
+ Opaque Skyvern-managed proxy sticky-session id for pinned Residential ISP sessions.
+
extensions : typing.Optional[typing.Sequence[Extensions]]
A list of extensions to install in the browser session.
@@ -4886,6 +4945,7 @@ class AsyncSkyvern:
_response = await self._raw_client.create_browser_session(
timeout=timeout,
proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
extensions=extensions,
browser_type=browser_type,
browser_profile_id=browser_profile_id,
@@ -5121,6 +5181,9 @@ class AsyncSkyvern:
credential_type: SkyvernForgeSdkSchemasCredentialsCredentialType,
credential: CreateCredentialRequestCredential,
vault_type: typing.Optional[CredentialVaultType] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
+ rotate_proxy_session_id: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> CredentialResponse:
"""
@@ -5140,6 +5203,9 @@ class AsyncSkyvern:
vault_type : typing.Optional[CredentialVaultType]
Which vault to store this credential in. If omitted, uses the instance default. Use this to mix Skyvern-hosted and custom credentials within the same organization.
+ rotate_proxy_session_id : typing.Optional[bool]
+ Rotate the Skyvern-managed proxy sticky-session id for this credential.
+
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -5177,6 +5243,9 @@ class AsyncSkyvern:
credential_type=credential_type,
credential=credential,
vault_type=vault_type,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
+ rotate_proxy_session_id=rotate_proxy_session_id,
request_options=request_options,
)
return _response.data
@@ -5189,6 +5258,9 @@ class AsyncSkyvern:
credential_type: SkyvernForgeSdkSchemasCredentialsCredentialType,
credential: CreateCredentialRequestCredential,
vault_type: typing.Optional[CredentialVaultType] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
+ rotate_proxy_session_id: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> CredentialResponse:
"""
@@ -5211,6 +5283,9 @@ class AsyncSkyvern:
vault_type : typing.Optional[CredentialVaultType]
Which vault to store this credential in. If omitted, uses the instance default. Use this to mix Skyvern-hosted and custom credentials within the same organization.
+ rotate_proxy_session_id : typing.Optional[bool]
+ Rotate the Skyvern-managed proxy sticky-session id for this credential.
+
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -5250,6 +5325,9 @@ class AsyncSkyvern:
credential_type=credential_type,
credential=credential,
vault_type=vault_type,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
+ rotate_proxy_session_id=rotate_proxy_session_id,
request_options=request_options,
)
return _response.data
diff --git a/skyvern/client/raw_client.py b/skyvern/client/raw_client.py
index 1b7aed09c..a60a95ed6 100644
--- a/skyvern/client/raw_client.py
+++ b/skyvern/client/raw_client.py
@@ -2181,6 +2181,8 @@ class RawSkyvern:
description: typing.Optional[str] = OMIT,
browser_session_id: typing.Optional[str] = OMIT,
workflow_run_id: typing.Optional[str] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> HttpResponse[BrowserProfile]:
"""
@@ -2200,6 +2202,12 @@ class RawSkyvern:
workflow_run_id : typing.Optional[str]
Workflow run whose persisted session should be captured. Omit for a blank profile.
+ proxy_location : typing.Optional[ProxyLocation]
+ Optional proxy location for this browser profile's pinned proxy identity.
+
+ proxy_session_id : typing.Optional[str]
+ Optional advanced reuse key for this browser profile's pinned proxy identity.
+
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -2216,6 +2224,8 @@ class RawSkyvern:
"description": description,
"browser_session_id": browser_session_id,
"workflow_run_id": workflow_run_id,
+ "proxy_location": proxy_location,
+ "proxy_session_id": proxy_session_id,
},
headers={
"content-type": "application/json",
@@ -2391,6 +2401,9 @@ class RawSkyvern:
*,
name: typing.Optional[str] = OMIT,
description: typing.Optional[str] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
+ rotate_proxy_session_id: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> HttpResponse[BrowserProfile]:
"""
@@ -2407,6 +2420,15 @@ class RawSkyvern:
description : typing.Optional[str]
New description for the browser profile
+ proxy_location : typing.Optional[ProxyLocation]
+ Optional proxy location for this browser profile's pinned proxy identity.
+
+ proxy_session_id : typing.Optional[str]
+ Optional advanced reuse key for this browser profile's pinned proxy identity.
+
+ rotate_proxy_session_id : typing.Optional[bool]
+ Rotate the Skyvern-managed proxy sticky-session id for this browser profile.
+
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -2421,6 +2443,9 @@ class RawSkyvern:
json={
"name": name,
"description": description,
+ "proxy_location": proxy_location,
+ "proxy_session_id": proxy_session_id,
+ "rotate_proxy_session_id": rotate_proxy_session_id,
},
headers={
"content-type": "application/json",
@@ -2539,6 +2564,7 @@ class RawSkyvern:
*,
timeout: typing.Optional[int] = OMIT,
proxy_location: typing.Optional[CreateBrowserSessionRequestProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
extensions: typing.Optional[typing.Sequence[Extensions]] = OMIT,
browser_type: typing.Optional[PersistentBrowserType] = OMIT,
browser_profile_id: typing.Optional[str] = OMIT,
@@ -2589,6 +2615,9 @@ class RawSkyvern:
For self-hosted deployments, you can pass a custom proxy URL as a dict: {"url": "http://user:[email protected]:8080"}. This routes the browser through your own proxy server and takes precedence over any globally configured proxy pool.
Can also be a GeoTarget object for granular city/state targeting: {"country": "US", "subdivision": "CA", "city": "San Francisco"}, or a custom proxy URL dict for self-hosted deployments: {"url": "http://user:[email protected]:8080"}
+ proxy_session_id : typing.Optional[str]
+ Opaque Skyvern-managed proxy sticky-session id for pinned Residential ISP sessions.
+
extensions : typing.Optional[typing.Sequence[Extensions]]
A list of extensions to install in the browser session.
@@ -2614,6 +2643,7 @@ class RawSkyvern:
"proxy_location": convert_and_respect_annotation_metadata(
object_=proxy_location, annotation=CreateBrowserSessionRequestProxyLocation, direction="write"
),
+ "proxy_session_id": proxy_session_id,
"extensions": extensions,
"browser_type": browser_type,
"browser_profile_id": browser_profile_id,
@@ -2975,6 +3005,9 @@ class RawSkyvern:
credential_type: SkyvernForgeSdkSchemasCredentialsCredentialType,
credential: CreateCredentialRequestCredential,
vault_type: typing.Optional[CredentialVaultType] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
+ rotate_proxy_session_id: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> HttpResponse[CredentialResponse]:
"""
@@ -2994,6 +3027,15 @@ class RawSkyvern:
vault_type : typing.Optional[CredentialVaultType]
Which vault to store this credential in. If omitted, uses the instance default. Use this to mix Skyvern-hosted and custom credentials within the same organization.
+ proxy_location : typing.Optional[ProxyLocation]
+ Optional proxy location for this credential's pinned proxy identity.
+
+ proxy_session_id : typing.Optional[str]
+ Optional advanced reuse key for this credential's pinned proxy identity.
+
+ rotate_proxy_session_id : typing.Optional[bool]
+ Rotate the Skyvern-managed proxy sticky-session id for this credential.
+
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -3012,6 +3054,9 @@ class RawSkyvern:
object_=credential, annotation=CreateCredentialRequestCredential, direction="write"
),
"vault_type": vault_type,
+ "proxy_location": proxy_location,
+ "proxy_session_id": proxy_session_id,
+ "rotate_proxy_session_id": rotate_proxy_session_id,
},
headers={
"content-type": "application/json",
@@ -3053,6 +3098,9 @@ class RawSkyvern:
credential_type: SkyvernForgeSdkSchemasCredentialsCredentialType,
credential: CreateCredentialRequestCredential,
vault_type: typing.Optional[CredentialVaultType] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
+ rotate_proxy_session_id: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> HttpResponse[CredentialResponse]:
"""
@@ -3075,6 +3123,15 @@ class RawSkyvern:
vault_type : typing.Optional[CredentialVaultType]
Which vault to store this credential in. If omitted, uses the instance default. Use this to mix Skyvern-hosted and custom credentials within the same organization.
+ proxy_location : typing.Optional[ProxyLocation]
+ Optional proxy location for this credential's pinned proxy identity.
+
+ proxy_session_id : typing.Optional[str]
+ Optional advanced reuse key for this credential's pinned proxy identity.
+
+ rotate_proxy_session_id : typing.Optional[bool]
+ Rotate the Skyvern-managed proxy sticky-session id for this credential.
+
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -3093,6 +3150,9 @@ class RawSkyvern:
object_=credential, annotation=CreateCredentialRequestCredential, direction="write"
),
"vault_type": vault_type,
+ "proxy_location": proxy_location,
+ "proxy_session_id": proxy_session_id,
+ "rotate_proxy_session_id": rotate_proxy_session_id,
},
headers={
"content-type": "application/json",
@@ -5973,6 +6033,8 @@ class AsyncRawSkyvern:
description: typing.Optional[str] = OMIT,
browser_session_id: typing.Optional[str] = OMIT,
workflow_run_id: typing.Optional[str] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> AsyncHttpResponse[BrowserProfile]:
"""
@@ -5992,6 +6054,12 @@ class AsyncRawSkyvern:
workflow_run_id : typing.Optional[str]
Workflow run whose persisted session should be captured. Omit for a blank profile.
+ proxy_location : typing.Optional[ProxyLocation]
+ Optional proxy location for this browser profile's pinned proxy identity.
+
+ proxy_session_id : typing.Optional[str]
+ Optional advanced reuse key for this browser profile's pinned proxy identity.
+
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -6008,6 +6076,8 @@ class AsyncRawSkyvern:
"description": description,
"browser_session_id": browser_session_id,
"workflow_run_id": workflow_run_id,
+ "proxy_location": proxy_location,
+ "proxy_session_id": proxy_session_id,
},
headers={
"content-type": "application/json",
@@ -6183,6 +6253,9 @@ class AsyncRawSkyvern:
*,
name: typing.Optional[str] = OMIT,
description: typing.Optional[str] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
+ rotate_proxy_session_id: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> AsyncHttpResponse[BrowserProfile]:
"""
@@ -6199,6 +6272,15 @@ class AsyncRawSkyvern:
description : typing.Optional[str]
New description for the browser profile
+ proxy_location : typing.Optional[ProxyLocation]
+ Optional proxy location for this browser profile's pinned proxy identity.
+
+ proxy_session_id : typing.Optional[str]
+ Optional advanced reuse key for this browser profile's pinned proxy identity.
+
+ rotate_proxy_session_id : typing.Optional[bool]
+ Rotate the Skyvern-managed proxy sticky-session id for this browser profile.
+
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -6213,6 +6295,9 @@ class AsyncRawSkyvern:
json={
"name": name,
"description": description,
+ "proxy_location": proxy_location,
+ "proxy_session_id": proxy_session_id,
+ "rotate_proxy_session_id": rotate_proxy_session_id,
},
headers={
"content-type": "application/json",
@@ -6331,6 +6416,7 @@ class AsyncRawSkyvern:
*,
timeout: typing.Optional[int] = OMIT,
proxy_location: typing.Optional[CreateBrowserSessionRequestProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
extensions: typing.Optional[typing.Sequence[Extensions]] = OMIT,
browser_type: typing.Optional[PersistentBrowserType] = OMIT,
browser_profile_id: typing.Optional[str] = OMIT,
@@ -6381,6 +6467,9 @@ class AsyncRawSkyvern:
For self-hosted deployments, you can pass a custom proxy URL as a dict: {"url": "http://user:[email protected]:8080"}. This routes the browser through your own proxy server and takes precedence over any globally configured proxy pool.
Can also be a GeoTarget object for granular city/state targeting: {"country": "US", "subdivision": "CA", "city": "San Francisco"}, or a custom proxy URL dict for self-hosted deployments: {"url": "http://user:[email protected]:8080"}
+ proxy_session_id : typing.Optional[str]
+ Opaque Skyvern-managed proxy sticky-session id for pinned Residential ISP sessions.
+
extensions : typing.Optional[typing.Sequence[Extensions]]
A list of extensions to install in the browser session.
@@ -6406,6 +6495,7 @@ class AsyncRawSkyvern:
"proxy_location": convert_and_respect_annotation_metadata(
object_=proxy_location, annotation=CreateBrowserSessionRequestProxyLocation, direction="write"
),
+ "proxy_session_id": proxy_session_id,
"extensions": extensions,
"browser_type": browser_type,
"browser_profile_id": browser_profile_id,
@@ -6767,6 +6857,9 @@ class AsyncRawSkyvern:
credential_type: SkyvernForgeSdkSchemasCredentialsCredentialType,
credential: CreateCredentialRequestCredential,
vault_type: typing.Optional[CredentialVaultType] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
+ rotate_proxy_session_id: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> AsyncHttpResponse[CredentialResponse]:
"""
@@ -6786,6 +6879,15 @@ class AsyncRawSkyvern:
vault_type : typing.Optional[CredentialVaultType]
Which vault to store this credential in. If omitted, uses the instance default. Use this to mix Skyvern-hosted and custom credentials within the same organization.
+ proxy_location : typing.Optional[ProxyLocation]
+ Optional proxy location for this credential's pinned proxy identity.
+
+ proxy_session_id : typing.Optional[str]
+ Optional advanced reuse key for this credential's pinned proxy identity.
+
+ rotate_proxy_session_id : typing.Optional[bool]
+ Rotate the Skyvern-managed proxy sticky-session id for this credential.
+
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -6804,6 +6906,9 @@ class AsyncRawSkyvern:
object_=credential, annotation=CreateCredentialRequestCredential, direction="write"
),
"vault_type": vault_type,
+ "proxy_location": proxy_location,
+ "proxy_session_id": proxy_session_id,
+ "rotate_proxy_session_id": rotate_proxy_session_id,
},
headers={
"content-type": "application/json",
@@ -6845,6 +6950,9 @@ class AsyncRawSkyvern:
credential_type: SkyvernForgeSdkSchemasCredentialsCredentialType,
credential: CreateCredentialRequestCredential,
vault_type: typing.Optional[CredentialVaultType] = OMIT,
+ proxy_location: typing.Optional[ProxyLocation] = OMIT,
+ proxy_session_id: typing.Optional[str] = OMIT,
+ rotate_proxy_session_id: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> AsyncHttpResponse[CredentialResponse]:
"""
@@ -6867,6 +6975,15 @@ class AsyncRawSkyvern:
vault_type : typing.Optional[CredentialVaultType]
Which vault to store this credential in. If omitted, uses the instance default. Use this to mix Skyvern-hosted and custom credentials within the same organization.
+ proxy_location : typing.Optional[ProxyLocation]
+ Optional proxy location for this credential's pinned proxy identity.
+
+ proxy_session_id : typing.Optional[str]
+ Optional advanced reuse key for this credential's pinned proxy identity.
+
+ rotate_proxy_session_id : typing.Optional[bool]
+ Rotate the Skyvern-managed proxy sticky-session id for this credential.
+
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
@@ -6885,6 +7002,9 @@ class AsyncRawSkyvern:
object_=credential, annotation=CreateCredentialRequestCredential, direction="write"
),
"vault_type": vault_type,
+ "proxy_location": proxy_location,
+ "proxy_session_id": proxy_session_id,
+ "rotate_proxy_session_id": rotate_proxy_session_id,
},
headers={
"content-type": "application/json",
diff --git a/skyvern/client/types/browser_profile.py b/skyvern/client/types/browser_profile.py
index 3e9bc7e39..f3547fa82 100644
--- a/skyvern/client/types/browser_profile.py
+++ b/skyvern/client/types/browser_profile.py
@@ -5,6 +5,7 @@ import typing
import pydantic
from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel
+from .proxy_location import ProxyLocation
class BrowserProfile(UniversalBaseModel):
@@ -13,6 +14,8 @@ class BrowserProfile(UniversalBaseModel):
name: str
description: typing.Optional[str] = None
source_browser_type: typing.Optional[str] = None
+ proxy_location: typing.Optional[ProxyLocation] = None
+ proxy_session_id: typing.Optional[str] = None
created_at: dt.datetime
modified_at: dt.datetime
deleted_at: typing.Optional[dt.datetime] = None
diff --git a/skyvern/client/types/credential_response.py b/skyvern/client/types/credential_response.py
index 5c2a836b7..16b357b46 100644
--- a/skyvern/client/types/credential_response.py
+++ b/skyvern/client/types/credential_response.py
@@ -7,6 +7,7 @@ from ..core.pydantic_utilities import IS_PYDANTIC_V2, UniversalBaseModel
from .credential_response_credential import CredentialResponseCredential
from .credential_type_output import CredentialTypeOutput
from .credential_vault_type import CredentialVaultType
+from .proxy_location import ProxyLocation
class CredentialResponse(UniversalBaseModel):
@@ -44,6 +45,16 @@ class CredentialResponse(UniversalBaseModel):
Browser profile ID linked to this credential
"""
+ proxy_location: typing.Optional[ProxyLocation] = pydantic.Field(default=None)
+ """
+ Optional proxy location for this credential's pinned proxy identity.
+ """
+
+ proxy_session_id: typing.Optional[str] = pydantic.Field(default=None)
+ """
+ Optional advanced reuse key for this credential's pinned proxy identity.
+ """
+
tested_url: typing.Optional[str] = pydantic.Field(default=None)
"""
Login page URL used during the credential test
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index e4b50ed42..977fde902 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -667,6 +667,26 @@ class AgentFunction:
workflow_schedules_use_local_scheduler: bool = settings.ENABLE_WORKFLOW_SCHEDULES
"""Whether the API process should run the built-in local scheduler loop."""
+ def build_proxy_session_extra_http_headers(self, proxy_session_id: str | None) -> dict[str, str] | None:
+ return None
+
+ def has_proxy_session_extra_http_headers(self, extra_http_headers: dict[str, str] | None) -> bool:
+ return False
+
+ def merge_proxy_session_extra_http_headers(
+ self,
+ extra_http_headers: dict[str, str] | None,
+ proxy_session_id: str | None,
+ ) -> dict[str, str] | None:
+ proxy_session_headers = self.build_proxy_session_extra_http_headers(proxy_session_id)
+ if not proxy_session_headers:
+ return extra_http_headers
+
+ headers = dict(extra_http_headers or {})
+ for key, value in proxy_session_headers.items():
+ headers.setdefault(key, value)
+ return headers
+
def get_flex_llm_key(self, llm_key: str | None) -> str | None:
"""Return a flex-tier router key for the given LLM key, or None if no flex twin exists.
diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.py
index cce3db4ef..96dfa69d3 100644
--- a/skyvern/forge/sdk/db/models.py
+++ b/skyvern/forge/sdk/db/models.py
@@ -1188,6 +1188,7 @@ class PersistentBrowserSessionModel(Base):
ip_address = Column(String, nullable=True)
ecs_task_arn = Column(String, nullable=True)
proxy_location = Column(String, nullable=True)
+ proxy_session_id = Column(String, nullable=True)
extensions = Column(JSON, nullable=True)
browser_type = Column(String, nullable=True)
browser_profile_id = Column(String, nullable=True, index=True)
@@ -1218,6 +1219,8 @@ class BrowserProfileModel(Base):
name = Column(String, nullable=False)
description = Column(String, nullable=True)
source_browser_type = Column(String, nullable=True)
+ proxy_location = Column(String, nullable=True)
+ proxy_session_id = Column(String, nullable=True)
created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)
modified_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow, nullable=False)
deleted_at = Column(DateTime, nullable=True)
@@ -1350,6 +1353,8 @@ class CredentialModel(Base):
tested_url = Column(String, nullable=True)
user_context = Column(String(1000), nullable=True)
save_browser_session_intent = Column(Boolean, nullable=True, default=False)
+ proxy_location = Column(String, nullable=True)
+ proxy_session_id = Column(String, nullable=True)
folder_id = Column(String, ForeignKey("credential_folders.folder_id", ondelete="SET NULL"), nullable=True)
created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)
diff --git a/skyvern/forge/sdk/db/repositories/browser_sessions.py b/skyvern/forge/sdk/db/repositories/browser_sessions.py
index 4cf0b77b5..9cbd729d1 100644
--- a/skyvern/forge/sdk/db/repositories/browser_sessions.py
+++ b/skyvern/forge/sdk/db/repositories/browser_sessions.py
@@ -13,10 +13,12 @@ from skyvern.forge.sdk.db.base_alchemy_db import read_retry
from skyvern.forge.sdk.db.base_repository import BaseRepository
from skyvern.forge.sdk.db.datetime_utils import naive_utc_now, to_naive_utc
from skyvern.forge.sdk.db.exceptions import NotFoundError
+from skyvern.forge.sdk.db.id import generate_browser_profile_id
from skyvern.forge.sdk.db.models import (
BrowserProfileModel,
PersistentBrowserSessionModel,
)
+from skyvern.forge.sdk.db.repositories.proxy_pin_update import apply_proxy_pin_to_model, normalize_proxy_pin_for_create
from skyvern.forge.sdk.db.utils import serialize_proxy_location
from skyvern.forge.sdk.schemas.browser_profiles import BrowserProfile
from skyvern.forge.sdk.schemas.persistent_browser_sessions import (
@@ -24,9 +26,11 @@ from skyvern.forge.sdk.schemas.persistent_browser_sessions import (
PersistentBrowserSession,
PersistentBrowserType,
)
+from skyvern.schemas.proxy_pinning import generate_proxy_session_id
from skyvern.schemas.runs import ProxyLocation, ProxyLocationInput
LOG = structlog.get_logger()
+_UNSET = object()
class BrowserSessionsRepository(BaseRepository):
@@ -39,13 +43,24 @@ class BrowserSessionsRepository(BaseRepository):
name: str,
description: str | None = None,
source_browser_type: str | None = None,
+ proxy_location: ProxyLocationInput = None,
+ proxy_session_id: str | None = None,
) -> BrowserProfile:
async with self.Session() as session:
+ browser_profile_id = generate_browser_profile_id()
+ proxy_location, proxy_session_id = normalize_proxy_pin_for_create(
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
+ entity_id=browser_profile_id,
+ )
browser_profile = BrowserProfileModel(
+ browser_profile_id=browser_profile_id,
organization_id=organization_id,
name=name,
description=description,
source_browser_type=source_browser_type,
+ proxy_location=serialize_proxy_location(proxy_location),
+ proxy_session_id=proxy_session_id,
)
session.add(browser_profile)
await session.commit()
@@ -151,6 +166,9 @@ class BrowserSessionsRepository(BaseRepository):
organization_id: str,
name: str | None = None,
description: str | None = None,
+ proxy_location: ProxyLocationInput | object = _UNSET,
+ proxy_session_id: str | None | object = _UNSET,
+ rotate_proxy_session_id: bool = False,
) -> BrowserProfile:
async with self.Session() as session:
query = (
@@ -167,6 +185,14 @@ class BrowserSessionsRepository(BaseRepository):
browser_profile.name = name
if description is not None:
browser_profile.description = description
+ apply_proxy_pin_to_model(
+ browser_profile,
+ entity_id=profile_id,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
+ unset=_UNSET,
+ rotate_proxy_session_id=rotate_proxy_session_id,
+ )
await session.commit()
await session.refresh(browser_profile)
@@ -288,28 +314,43 @@ class BrowserSessionsRepository(BaseRepository):
runnable_id: str | None = None,
timeout_minutes: int | None = None,
proxy_location: ProxyLocationInput = ProxyLocation.RESIDENTIAL,
+ proxy_session_id: str | None = None,
extensions: list[Extensions] | None = None,
browser_type: PersistentBrowserType | None = None,
browser_profile_id: str | None = None,
generate_browser_profile: bool = False,
) -> PersistentBrowserSession:
"""Create a new persistent browser session."""
+ proxy_location, proxy_session_id = normalize_proxy_pin_for_create(
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
+ )
extensions_str: list[str] | None = (
[extension.value for extension in extensions] if extensions is not None else None
)
+ serialized_proxy_location = serialize_proxy_location(proxy_location)
async with self.Session() as session:
browser_session = PersistentBrowserSessionModel(
organization_id=organization_id,
runnable_type=runnable_type,
runnable_id=runnable_id,
timeout_minutes=timeout_minutes,
- proxy_location=serialize_proxy_location(proxy_location),
+ proxy_location=serialized_proxy_location,
+ proxy_session_id=proxy_session_id,
extensions=extensions_str,
browser_type=browser_type.value if browser_type else None,
browser_profile_id=browser_profile_id,
generate_browser_profile=generate_browser_profile,
)
session.add(browser_session)
+ await session.flush()
+ if (
+ serialized_proxy_location == ProxyLocation.RESIDENTIAL_ISP.value
+ and browser_session.proxy_session_id is None
+ ):
+ browser_session.proxy_session_id = generate_proxy_session_id(
+ browser_session.persistent_browser_session_id
+ )
await session.commit()
await session.refresh(browser_session)
return PersistentBrowserSession.model_validate(browser_session)
diff --git a/skyvern/forge/sdk/db/repositories/credentials.py b/skyvern/forge/sdk/db/repositories/credentials.py
index 5d0c01c0c..5d47d4c38 100644
--- a/skyvern/forge/sdk/db/repositories/credentials.py
+++ b/skyvern/forge/sdk/db/repositories/credentials.py
@@ -8,8 +8,18 @@ from skyvern.forge.sdk.db._error_handling import db_operation
from skyvern.forge.sdk.db.base_repository import BaseRepository
from skyvern.forge.sdk.db.exceptions import NotFoundError
from skyvern.forge.sdk.db.models import CredentialModel, OrganizationBitwardenCollectionModel
-from skyvern.forge.sdk.schemas.credentials import Credential, CredentialType, CredentialVaultType
+from skyvern.forge.sdk.db.repositories.proxy_pin_update import apply_proxy_pin_to_model, normalize_proxy_pin_for_create
+from skyvern.forge.sdk.db.utils import serialize_proxy_location
+from skyvern.forge.sdk.schemas.credentials import (
+ Credential,
+ CredentialType,
+ CredentialVaultType,
+)
from skyvern.forge.sdk.schemas.organization_bitwarden_collections import OrganizationBitwardenCollection
+from skyvern.schemas.proxy_pinning import generate_proxy_session_id, should_generate_proxy_session_id
+from skyvern.schemas.runs import ProxyLocationInput
+
+_UNSET = object()
class CredentialRepository(BaseRepository):
@@ -29,7 +39,14 @@ class CredentialRepository(BaseRepository):
card_brand: str | None,
totp_identifier: str | None = None,
secret_label: str | None = None,
+ proxy_location: ProxyLocationInput = None,
+ proxy_session_id: str | None = None,
) -> Credential:
+ proxy_location, proxy_session_id = normalize_proxy_pin_for_create(
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
+ )
+ serialized_proxy_location = serialize_proxy_location(proxy_location)
async with self.Session() as session:
credential = CredentialModel(
organization_id=organization_id,
@@ -43,8 +60,13 @@ class CredentialRepository(BaseRepository):
card_last4=card_last4,
card_brand=card_brand,
secret_label=secret_label,
+ proxy_location=serialized_proxy_location,
+ proxy_session_id=proxy_session_id,
)
session.add(credential)
+ await session.flush()
+ if should_generate_proxy_session_id(proxy_location) and credential.proxy_session_id is None:
+ credential.proxy_session_id = generate_proxy_session_id(credential.credential_id)
await session.commit()
await session.refresh(credential)
return Credential.model_validate(credential)
@@ -132,6 +154,9 @@ class CredentialRepository(BaseRepository):
tested_url: str | None = None,
user_context: str | None = None,
save_browser_session_intent: bool | None = None,
+ proxy_location: ProxyLocationInput | object = _UNSET,
+ proxy_session_id: str | None | object = _UNSET,
+ rotate_proxy_session_id: bool = False,
) -> Credential:
async with self.Session() as session:
credential = (
@@ -154,6 +179,14 @@ class CredentialRepository(BaseRepository):
credential.user_context = user_context
if save_browser_session_intent is not None:
credential.save_browser_session_intent = save_browser_session_intent
+ apply_proxy_pin_to_model(
+ credential,
+ entity_id=credential_id,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
+ unset=_UNSET,
+ rotate_proxy_session_id=rotate_proxy_session_id,
+ )
await session.commit()
await session.refresh(credential)
return Credential.model_validate(credential)
@@ -172,6 +205,9 @@ class CredentialRepository(BaseRepository):
card_last4: str | None = None,
card_brand: str | None = None,
secret_label: str | None = None,
+ proxy_location: ProxyLocationInput | object = _UNSET,
+ proxy_session_id: str | None | object = _UNSET,
+ rotate_proxy_session_id: bool = False,
) -> Credential:
async with self.Session() as session:
credential = (
@@ -194,6 +230,14 @@ class CredentialRepository(BaseRepository):
credential.card_last4 = card_last4
credential.card_brand = card_brand
credential.secret_label = secret_label
+ apply_proxy_pin_to_model(
+ credential,
+ entity_id=credential_id,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
+ unset=_UNSET,
+ rotate_proxy_session_id=rotate_proxy_session_id,
+ )
await session.commit()
await session.refresh(credential)
return Credential.model_validate(credential)
diff --git a/skyvern/forge/sdk/db/repositories/proxy_pin_update.py b/skyvern/forge/sdk/db/repositories/proxy_pin_update.py
new file mode 100644
index 000000000..ae429b561
--- /dev/null
+++ b/skyvern/forge/sdk/db/repositories/proxy_pin_update.py
@@ -0,0 +1,56 @@
+from __future__ import annotations
+
+from typing import Any, cast
+
+from skyvern.forge.sdk.db.utils import serialize_proxy_location
+from skyvern.schemas.proxy_pinning import generate_proxy_session_id, should_generate_proxy_session_id
+from skyvern.schemas.runs import ProxyLocation, ProxyLocationInput
+
+
+def normalize_proxy_pin_for_create(
+ *,
+ proxy_location: ProxyLocationInput,
+ proxy_session_id: str | None,
+ entity_id: str | None = None,
+) -> tuple[ProxyLocationInput, str | None]:
+ if proxy_session_id and proxy_location is None:
+ return ProxyLocation.RESIDENTIAL_ISP, proxy_session_id
+ if proxy_location is None:
+ return None, None
+ if should_generate_proxy_session_id(proxy_location):
+ if proxy_session_id is None and entity_id is not None:
+ proxy_session_id = generate_proxy_session_id(entity_id)
+ return proxy_location, proxy_session_id
+ return proxy_location, None
+
+
+def apply_proxy_pin_to_model(
+ model: Any,
+ *,
+ entity_id: str,
+ proxy_location: ProxyLocationInput | object,
+ proxy_session_id: str | None | object,
+ unset: object,
+ rotate_proxy_session_id: bool = False,
+) -> None:
+ if proxy_location is not unset:
+ model.proxy_location = serialize_proxy_location(cast(ProxyLocationInput, proxy_location))
+ if proxy_location is None or not should_generate_proxy_session_id(proxy_location):
+ model.proxy_session_id = None
+ elif rotate_proxy_session_id or (proxy_session_id is unset and not model.proxy_session_id):
+ model.proxy_session_id = generate_proxy_session_id(entity_id)
+
+ if rotate_proxy_session_id and proxy_location is unset:
+ if not should_generate_proxy_session_id(model.proxy_location):
+ model.proxy_location = serialize_proxy_location(ProxyLocation.RESIDENTIAL_ISP)
+ model.proxy_session_id = generate_proxy_session_id(entity_id)
+
+ if proxy_session_id is not unset:
+ if proxy_session_id:
+ if proxy_location is unset:
+ model.proxy_location = serialize_proxy_location(ProxyLocation.RESIDENTIAL_ISP)
+ if proxy_location is unset or should_generate_proxy_session_id(proxy_location):
+ model.proxy_session_id = cast(str, proxy_session_id)
+ elif proxy_location is unset:
+ model.proxy_location = None
+ model.proxy_session_id = cast(str | None, proxy_session_id)
diff --git a/skyvern/forge/sdk/db/repositories/workflow_runs.py b/skyvern/forge/sdk/db/repositories/workflow_runs.py
index e33117abd..b186bb16d 100644
--- a/skyvern/forge/sdk/db/repositories/workflow_runs.py
+++ b/skyvern/forge/sdk/db/repositories/workflow_runs.py
@@ -264,6 +264,7 @@ class WorkflowRunsRepository(BaseRepository):
verification_code_identifier: str | None = None,
verification_code_polling_started_at: datetime | None = None,
browser_profile_id: str | None | object = _UNSET,
+ proxy_location: ProxyLocationInput | object = _UNSET,
browser_address: str | None = None,
extra_http_headers: dict[str, str] | None = None,
cdp_connect_headers: dict[str, str] | None = None,
@@ -327,6 +328,10 @@ class WorkflowRunsRepository(BaseRepository):
workflow_run.verification_code_polling_started_at = None
if browser_profile_id is not _UNSET:
workflow_run.browser_profile_id = browser_profile_id
+ if proxy_location is not _UNSET:
+ workflow_run.proxy_location = serialize_proxy_location(
+ typing_cast(ProxyLocationInput, proxy_location)
+ )
if failure_category is not None:
workflow_run.failure_category = failure_category
# Explicit timestamp overrides (used when resetting workflow runs)
diff --git a/skyvern/forge/sdk/routes/browser_profiles.py b/skyvern/forge/sdk/routes/browser_profiles.py
index 38e0ac1db..4dbea6500 100644
--- a/skyvern/forge/sdk/routes/browser_profiles.py
+++ b/skyvern/forge/sdk/routes/browser_profiles.py
@@ -1,7 +1,7 @@
import asyncio
import shutil
from pathlib import Path as FilePath
-from typing import NoReturn
+from typing import Any, NoReturn
import structlog
from fastapi import Depends, HTTPException, Path, Query, status
@@ -37,6 +37,9 @@ from skyvern.forge.sdk.schemas.browser_profiles import (
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.schemas.persistent_browser_sessions import export_profile_storage_id
from skyvern.forge.sdk.services import org_auth_service
+from skyvern.schemas.proxy_pinning import apply_proxy_pin_update as _apply_proxy_pin_update
+from skyvern.schemas.proxy_pinning import should_generate_proxy_session_id
+from skyvern.schemas.runs import ProxyLocation, ProxyLocationInput
LOG = structlog.get_logger()
@@ -62,6 +65,16 @@ DEFAULT_PROFILE_COPY_IGNORE = {
}
+def _normalize_proxy_pin_fields(
+ *,
+ proxy_location: ProxyLocationInput,
+ proxy_session_id: str | None,
+) -> tuple[ProxyLocationInput, str | None]:
+ if proxy_session_id:
+ return proxy_location or ProxyLocation.RESIDENTIAL_ISP, proxy_session_id
+ return proxy_location, None
+
+
def _handle_duplicate_profile_name(*, organization_id: str, name: str, exc: IntegrityError) -> NoReturn:
LOG.warning(
"Duplicate browser profile name",
@@ -117,26 +130,45 @@ async def create_browser_profile(
if request.browser_session_id is not None:
browser_session_id = request.browser_session_id
+ proxy_location, proxy_session_id = _normalize_proxy_pin_fields(
+ proxy_location=request.proxy_location,
+ proxy_session_id=request.proxy_session_id,
+ )
return await _create_profile_from_session(
organization_id=organization_id,
name=request.name,
description=request.description,
browser_session_id=browser_session_id,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
)
if request.workflow_run_id is not None:
+ workflow_run_id = request.workflow_run_id
+ proxy_location, proxy_session_id = _normalize_proxy_pin_fields(
+ proxy_location=request.proxy_location,
+ proxy_session_id=request.proxy_session_id,
+ )
return await _create_profile_from_workflow_run(
organization_id=organization_id,
name=request.name,
description=request.description,
- workflow_run_id=request.workflow_run_id,
+ workflow_run_id=workflow_run_id,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
)
await app.RATE_LIMITER.rate_limit_submit_run(organization_id)
+ proxy_location, proxy_session_id = _normalize_proxy_pin_fields(
+ proxy_location=request.proxy_location,
+ proxy_session_id=request.proxy_session_id,
+ )
return await _create_empty_profile(
organization_id=organization_id,
name=request.name,
description=request.description,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
)
@@ -316,12 +348,21 @@ async def update_browser_profile(
)
try:
- profile = await app.DATABASE.browser_sessions.update_browser_profile(
- profile_id=profile_id,
- organization_id=organization_id,
- name=request.name,
- description=request.description,
- )
+ update_kwargs: dict[str, Any] = {
+ "profile_id": profile_id,
+ "organization_id": organization_id,
+ "name": request.name,
+ "description": request.description,
+ }
+ _apply_proxy_pin_update(
+ update_kwargs,
+ proxy_location_was_set="proxy_location" in request.model_fields_set,
+ proxy_location=request.proxy_location,
+ proxy_session_id_was_set="proxy_session_id" in request.model_fields_set,
+ proxy_session_id=request.proxy_session_id,
+ rotate_proxy_session_id=request.rotate_proxy_session_id,
+ )
+ profile = await app.DATABASE.browser_sessions.update_browser_profile(**update_kwargs)
except BrowserProfileNotFound:
LOG.warning(
"Browser profile not found for update",
@@ -547,6 +588,8 @@ async def _create_empty_profile(
organization_id: str,
name: str,
description: str | None,
+ proxy_location: ProxyLocationInput = None,
+ proxy_session_id: str | None = None,
) -> BrowserProfile:
# Seed before inserting so local setup failures never reserve a profile name.
profile_dir = _create_empty_browser_profile_directory()
@@ -556,6 +599,8 @@ async def _create_empty_profile(
organization_id=organization_id,
name=name,
description=description,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
)
except IntegrityError as exc:
_handle_duplicate_profile_name(organization_id=organization_id, name=name, exc=exc)
@@ -596,6 +641,8 @@ async def _create_profile_from_session(
name: str,
description: str | None,
browser_session_id: str,
+ proxy_location: ProxyLocationInput = None,
+ proxy_session_id: str | None = None,
) -> BrowserProfile:
browser_session = await app.DATABASE.browser_sessions.get_persistent_browser_session(
browser_session_id, organization_id
@@ -669,6 +716,13 @@ async def _create_profile_from_session(
)
source_browser_type = browser_session.browser_type.value if browser_session.browser_type else None
+ if (
+ proxy_session_id is None
+ and browser_session.proxy_session_id
+ and (proxy_location is None or should_generate_proxy_session_id(proxy_location))
+ ):
+ proxy_location = browser_session.proxy_location or ProxyLocation.RESIDENTIAL_ISP
+ proxy_session_id = browser_session.proxy_session_id
try:
profile = await app.DATABASE.browser_sessions.create_browser_profile(
@@ -676,6 +730,8 @@ async def _create_profile_from_session(
name=name,
description=description,
source_browser_type=source_browser_type,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
)
except IntegrityError as exc:
_handle_duplicate_profile_name(organization_id=organization_id, name=name, exc=exc)
@@ -731,6 +787,8 @@ async def _create_profile_from_workflow_run(
name: str,
description: str | None,
workflow_run_id: str,
+ proxy_location: ProxyLocationInput = None,
+ proxy_session_id: str | None = None,
) -> BrowserProfile:
workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(workflow_run_id, organization_id=organization_id)
if not workflow_run:
@@ -802,6 +860,8 @@ async def _create_profile_from_workflow_run(
organization_id=organization_id,
name=name,
description=description,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
)
except IntegrityError as exc:
_handle_duplicate_profile_name(organization_id=organization_id, name=name, exc=exc)
diff --git a/skyvern/forge/sdk/routes/browser_sessions.py b/skyvern/forge/sdk/routes/browser_sessions.py
index 3229c6947..208b710ed 100644
--- a/skyvern/forge/sdk/routes/browser_sessions.py
+++ b/skyvern/forge/sdk/routes/browser_sessions.py
@@ -26,6 +26,8 @@ from skyvern.schemas.browser_sessions import (
ProcessBrowserSessionRecordingResponse,
UpdateBrowserSessionRequest,
)
+from skyvern.schemas.proxy_pinning import should_generate_proxy_session_id
+from skyvern.schemas.runs import ProxyLocation
from skyvern.webeye.schemas import BrowserSessionResponse
@@ -93,6 +95,8 @@ async def create_browser_session(
browser_session_request: CreateBrowserSessionRequest = CreateBrowserSessionRequest(),
current_org: Organization = Depends(org_auth_service.get_current_org),
) -> BrowserSessionResponse:
+ proxy_location = browser_session_request.proxy_location
+ proxy_session_id = browser_session_request.proxy_session_id
if browser_session_request.browser_profile_id:
profile = await app.DATABASE.browser_sessions.get_browser_profile(
browser_session_request.browser_profile_id,
@@ -103,11 +107,27 @@ async def create_browser_session(
status_code=404,
detail=f"Browser profile {browser_session_request.browser_profile_id} not found",
)
+ proxy_location_was_set = "proxy_location" in browser_session_request.model_fields_set
+ if not proxy_location_was_set:
+ proxy_location = profile.proxy_location
+ if "proxy_session_id" not in browser_session_request.model_fields_set:
+ if not proxy_location_was_set or should_generate_proxy_session_id(proxy_location):
+ proxy_session_id = profile.proxy_session_id
+ else:
+ proxy_session_id = None
+ if proxy_session_id and proxy_location is None:
+ proxy_location = ProxyLocation.RESIDENTIAL_ISP
+ if proxy_session_id and not should_generate_proxy_session_id(proxy_location):
+ raise HTTPException(
+ status_code=400,
+ detail="proxy_session_id is only supported with RESIDENTIAL_ISP proxy_location",
+ )
browser_session = await app.PERSISTENT_SESSIONS_MANAGER.create_session(
organization_id=current_org.organization_id,
timeout_minutes=browser_session_request.timeout,
- proxy_location=browser_session_request.proxy_location,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
extensions=browser_session_request.extensions,
browser_type=browser_session_request.browser_type,
browser_profile_id=browser_session_request.browser_profile_id,
diff --git a/skyvern/forge/sdk/routes/credentials.py b/skyvern/forge/sdk/routes/credentials.py
index 32f8d0cd5..3079b92d7 100644
--- a/skyvern/forge/sdk/routes/credentials.py
+++ b/skyvern/forge/sdk/routes/credentials.py
@@ -34,7 +34,7 @@ import asyncio
import json
import time
from dataclasses import dataclass
-from typing import Annotated
+from typing import Annotated, Any
import pyotp
import structlog
@@ -121,6 +121,9 @@ from skyvern.schemas.credential_folders import (
CredentialFolderUpdate,
UpdateCredentialFolderRequest,
)
+from skyvern.schemas.proxy_pinning import apply_proxy_pin_update as _apply_proxy_pin_update
+from skyvern.schemas.proxy_pinning import redact_proxy_session_id
+from skyvern.schemas.runs import ProxyLocation
from skyvern.schemas.workflows import (
BLOCK_YAML_TYPES,
LoginBlockYAML,
@@ -516,42 +519,7 @@ async def create_credential(
# Early resyncing the Bitwarden vault
background_tasks.add_task(fetch_credential_item_background, credential.item_id)
- if data.credential_type == CredentialType.PASSWORD:
- credential_response = PasswordCredentialResponse(
- username=data.credential.username,
- totp_type=data.credential.totp_type if hasattr(data.credential, "totp_type") else "none",
- totp_identifier=data.credential.totp_identifier if hasattr(data.credential, "totp_identifier") else None,
- )
- return CredentialResponse(
- credential=credential_response,
- credential_id=credential.credential_id,
- credential_type=data.credential_type,
- name=data.name,
- vault_type=credential.vault_type,
- )
- elif data.credential_type == CredentialType.CREDIT_CARD:
- credential_response = CreditCardCredentialResponse(
- last_four=data.credential.card_number[-4:],
- brand=data.credential.card_brand,
- )
- return CredentialResponse(
- credential=credential_response,
- credential_id=credential.credential_id,
- credential_type=data.credential_type,
- name=data.name,
- vault_type=credential.vault_type,
- )
- elif data.credential_type == CredentialType.SECRET:
- credential_response = SecretCredentialResponse(secret_label=data.credential.secret_label)
- return CredentialResponse(
- credential=credential_response,
- credential_id=credential.credential_id,
- credential_type=data.credential_type,
- name=data.name,
- vault_type=credential.vault_type,
- )
- else:
- raise HTTPException(status_code=400, detail=f"Unsupported credential type: {data.credential_type}")
+ return _convert_to_response(credential)
LOGIN_TEST_PROMPT = (
@@ -675,17 +643,26 @@ async def rename_credential(
if not credential:
raise HTTPException(status_code=404, detail=f"Credential not found, credential_id={credential_id}")
- update_kwargs: dict = {
+ update_kwargs: dict[str, Any] = {
"credential_id": credential_id,
"organization_id": current_org.organization_id,
- "name": data.name,
}
+ if "name" in data.model_fields_set:
+ update_kwargs["name"] = data.name
if data.tested_url is not None:
update_kwargs["tested_url"] = data.tested_url
if data.user_context is not None:
update_kwargs["user_context"] = data.user_context
if data.save_browser_session_intent is not None:
update_kwargs["save_browser_session_intent"] = data.save_browser_session_intent
+ _apply_proxy_pin_update(
+ update_kwargs,
+ proxy_location_was_set="proxy_location" in data.model_fields_set,
+ proxy_location=data.proxy_location,
+ proxy_session_id_was_set="proxy_session_id" in data.model_fields_set,
+ proxy_session_id=data.proxy_session_id,
+ rotate_proxy_session_id=data.rotate_proxy_session_id,
+ )
updated = await app.DATABASE.credentials.update_credential(**update_kwargs)
if not updated:
raise HTTPException(status_code=500, detail="Failed to update credential")
@@ -745,6 +722,19 @@ async def test_login(
background_tasks.add_task(fetch_credential_item_background, credential.item_id)
credential_id = credential.credential_id
+ if "proxy_location" in data.model_fields_set or "proxy_session_id" in data.model_fields_set:
+ update_kwargs: dict[str, Any] = {
+ "credential_id": credential_id,
+ "organization_id": organization_id,
+ }
+ _apply_proxy_pin_update(
+ update_kwargs,
+ proxy_location_was_set="proxy_location" in data.model_fields_set,
+ proxy_location=data.proxy_location,
+ proxy_session_id_was_set="proxy_session_id" in data.model_fields_set,
+ proxy_session_id=data.proxy_session_id,
+ )
+ credential = await app.DATABASE.credentials.update_credential(**update_kwargs)
LOG.info(
"Testing login with inline credentials",
@@ -798,7 +788,16 @@ async def test_login(
request=workflow_create_request,
)
- run_request = WorkflowRequestBody()
+ credential_proxy_session_id = getattr(credential, "proxy_session_id", None)
+ if credential_proxy_session_id:
+ run_request = WorkflowRequestBody(
+ proxy_location=getattr(credential, "proxy_location", None) or ProxyLocation.RESIDENTIAL_ISP,
+ extra_http_headers=app.AGENT_FUNCTION.build_proxy_session_extra_http_headers(
+ credential_proxy_session_id
+ ),
+ )
+ else:
+ run_request = WorkflowRequestBody()
workflow_run = await app.WORKFLOW_SERVICE.setup_workflow_run(
request_id=None,
@@ -984,7 +983,15 @@ async def test_credential(
# Boot fresh (don't seed the saved profile): a reused profile is loaded read-only and the
# refreshed session would never persist. A fresh login persists via the normal session path,
# which the saver then writes onto existing_browser_profile_id.
- run_request = WorkflowRequestBody()
+ if credential.proxy_session_id:
+ run_request = WorkflowRequestBody(
+ proxy_location=credential.proxy_location or ProxyLocation.RESIDENTIAL_ISP,
+ extra_http_headers=app.AGENT_FUNCTION.build_proxy_session_extra_http_headers(
+ credential.proxy_session_id
+ ),
+ )
+ else:
+ run_request = WorkflowRequestBody()
workflow_run = await app.WORKFLOW_SERVICE.setup_workflow_run(
request_id=None,
@@ -1396,7 +1403,16 @@ async def _create_browser_profile_after_workflow(
# Re-save overwrites the existing profile in place so references to its id keep
# working; a first-time save (or a since-deleted profile) creates a new one.
+ credential = await app.DATABASE.credentials.get_credential(
+ credential_id=credential_id,
+ organization_id=organization_id,
+ )
+ proxy_location = credential.proxy_location if credential else None
+ proxy_session_id = credential.proxy_session_id if credential else None
+ credential_has_proxy_pin = proxy_session_id is not None
+
target_profile_id = existing_browser_profile_id
+ existing_profile = None
reused_existing = False
if target_profile_id:
existing_profile = await app.DATABASE.browser_sessions.get_browser_profile(
@@ -1407,13 +1423,33 @@ async def _create_browser_profile_after_workflow(
if not reused_existing:
target_profile_id = None
+ should_update_existing_profile_pin = False
if not target_profile_id:
profile = await app.DATABASE.browser_sessions.create_browser_profile(
organization_id=organization_id,
name=f"Profile - {credential_name} ({credential_id})",
description=f"Browser profile from credential test for {credential_name}",
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
)
target_profile_id = profile.browser_profile_id
+ else:
+ should_update_existing_profile_pin = credential_has_proxy_pin
+ existing_profile_proxy_session_id = getattr(existing_profile, "proxy_session_id", None)
+ if (
+ existing_profile_proxy_session_id
+ and proxy_session_id
+ and existing_profile_proxy_session_id != proxy_session_id
+ ):
+ should_update_existing_profile_pin = False
+ LOG.warning(
+ "Skipping credential proxy pin mirror because linked browser profile already has a different pin",
+ credential_id=credential_id,
+ browser_profile_id=target_profile_id,
+ organization_id=organization_id,
+ credential_proxy_session_id=redact_proxy_session_id(proxy_session_id),
+ browser_profile_proxy_session_id=redact_proxy_session_id(existing_profile_proxy_session_id),
+ )
# Overwrites in place when reusing an existing id.
await app.STORAGE.store_browser_profile(
@@ -1422,6 +1458,13 @@ async def _create_browser_profile_after_workflow(
directory=session_dir,
)
if reused_existing:
+ if should_update_existing_profile_pin:
+ await app.DATABASE.browser_sessions.update_browser_profile(
+ profile_id=target_profile_id,
+ organization_id=organization_id,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
+ )
# Bump modified_at so the status poll can tell this run's re-save actually landed.
await app.DATABASE.browser_sessions.touch_browser_profile(
profile_id=target_profile_id,
@@ -2778,6 +2821,8 @@ def _convert_to_response(credential: Credential) -> CredentialResponse:
user_context=credential.user_context,
save_browser_session_intent=credential.save_browser_session_intent,
folder_id=credential.folder_id,
+ proxy_location=credential.proxy_location,
+ proxy_session_id=credential.proxy_session_id,
)
elif credential.credential_type == CredentialType.CREDIT_CARD:
credential_response = CreditCardCredentialResponse(
@@ -2795,6 +2840,8 @@ def _convert_to_response(credential: Credential) -> CredentialResponse:
user_context=credential.user_context,
save_browser_session_intent=credential.save_browser_session_intent,
folder_id=credential.folder_id,
+ proxy_location=credential.proxy_location,
+ proxy_session_id=credential.proxy_session_id,
)
elif credential.credential_type == CredentialType.SECRET:
credential_response = SecretCredentialResponse(secret_label=credential.secret_label)
@@ -2809,6 +2856,8 @@ def _convert_to_response(credential: Credential) -> CredentialResponse:
user_context=credential.user_context,
save_browser_session_intent=credential.save_browser_session_intent,
folder_id=credential.folder_id,
+ proxy_location=credential.proxy_location,
+ proxy_session_id=credential.proxy_session_id,
)
else:
raise HTTPException(status_code=400, detail="Credential type not supported")
diff --git a/skyvern/forge/sdk/schemas/browser_profiles.py b/skyvern/forge/sdk/schemas/browser_profiles.py
index 2c259de5c..cb99d3efd 100644
--- a/skyvern/forge/sdk/schemas/browser_profiles.py
+++ b/skyvern/forge/sdk/schemas/browser_profiles.py
@@ -1,6 +1,9 @@
from datetime import datetime
-from pydantic import BaseModel, ConfigDict, Field, model_validator
+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
+
+from skyvern.schemas.proxy_location import ProxyLocationInput
+from skyvern.schemas.proxy_pinning import parse_proxy_location_input, validate_proxy_session_id
class BrowserProfile(BaseModel):
@@ -11,10 +14,22 @@ class BrowserProfile(BaseModel):
name: str
description: str | None = None
source_browser_type: str | None = None
+ proxy_location: ProxyLocationInput = None
+ proxy_session_id: str | None = None
created_at: datetime
modified_at: datetime
deleted_at: datetime | None = None
+ @field_validator("proxy_location", mode="before")
+ @classmethod
+ def deserialize_proxy_location_field(cls, value: object) -> object:
+ return parse_proxy_location_input(value)
+
+ @field_validator("proxy_session_id")
+ @classmethod
+ def validate_proxy_session_id_field(cls, value: str | None) -> str | None:
+ return validate_proxy_session_id(value)
+
class CreateBrowserProfileRequest(BaseModel):
model_config = ConfigDict(str_strip_whitespace=True)
@@ -31,6 +46,14 @@ class CreateBrowserProfileRequest(BaseModel):
min_length=1,
description="Workflow run whose persisted session should be captured. Omit for a blank profile.",
)
+ proxy_location: ProxyLocationInput = Field(
+ default=None,
+ description="Optional proxy location for this profile's pinned proxy identity.",
+ )
+ proxy_session_id: str | None = Field(
+ default=None,
+ description="Explicit sticky-session id for this profile's pinned proxy identity.",
+ )
@model_validator(mode="after")
def _validate_source(self) -> "CreateBrowserProfileRequest":
@@ -38,6 +61,16 @@ class CreateBrowserProfileRequest(BaseModel):
raise ValueError("Provide only one of browser_session_id or workflow_run_id")
return self
+ @field_validator("proxy_location", mode="before")
+ @classmethod
+ def deserialize_proxy_location_field(cls, value: object) -> object:
+ return parse_proxy_location_input(value)
+
+ @field_validator("proxy_session_id")
+ @classmethod
+ def validate_proxy_session_id_field(cls, value: str | None) -> str | None:
+ return validate_proxy_session_id(value)
+
class UpdateBrowserProfileRequest(BaseModel):
# `None` for either field means "no change" — there is currently no way to
@@ -46,9 +79,31 @@ class UpdateBrowserProfileRequest(BaseModel):
name: str | None = Field(default=None, min_length=1, description="New name for the browser profile")
description: str | None = Field(default=None, description="New description for the browser profile")
+ proxy_location: ProxyLocationInput = Field(
+ default=None,
+ description="Optional proxy location for this profile's pinned proxy identity.",
+ )
+ proxy_session_id: str | None = Field(
+ default=None,
+ description="Opaque Skyvern-managed proxy sticky-session id.",
+ )
+ rotate_proxy_session_id: bool = Field(
+ default=False,
+ description="Rotate the Skyvern-managed proxy sticky-session id for this profile.",
+ )
@model_validator(mode="after")
def _require_at_least_one_field(self) -> "UpdateBrowserProfileRequest":
- if self.name is None and self.description is None:
- raise ValueError("At least one of `name` or `description` must be provided")
+ if not self.model_fields_set:
+ raise ValueError("At least one browser profile field must be provided")
return self
+
+ @field_validator("proxy_location", mode="before")
+ @classmethod
+ def deserialize_proxy_location_field(cls, value: object) -> object:
+ return parse_proxy_location_input(value)
+
+ @field_validator("proxy_session_id")
+ @classmethod
+ def validate_proxy_session_id_field(cls, value: str | None) -> str | None:
+ return validate_proxy_session_id(value)
diff --git a/skyvern/forge/sdk/schemas/credentials.py b/skyvern/forge/sdk/schemas/credentials.py
index b33348447..4b0e87807 100644
--- a/skyvern/forge/sdk/schemas/credentials.py
+++ b/skyvern/forge/sdk/schemas/credentials.py
@@ -6,6 +6,8 @@ from fastapi import status
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from skyvern.exceptions import SkyvernHTTPException
+from skyvern.schemas.proxy_location import ProxyLocationInput
+from skyvern.schemas.proxy_pinning import parse_proxy_location_input, validate_proxy_session_id
from skyvern.utils.url_validators import validate_url
@@ -220,6 +222,28 @@ class CreateCredentialRequest(BaseModel):
"Use this to mix Skyvern-hosted and custom credentials within the same organization.",
examples=["custom", "azure_vault", "bitwarden"],
)
+ proxy_location: ProxyLocationInput = Field(
+ default=None,
+ description="Optional proxy location for this credential's pinned proxy identity.",
+ )
+ proxy_session_id: str | None = Field(
+ default=None,
+ description="Optional advanced reuse key for this credential's pinned proxy identity.",
+ )
+ rotate_proxy_session_id: bool = Field(
+ default=False,
+ description="Rotate the Skyvern-managed proxy sticky-session id when updating this credential.",
+ )
+
+ @field_validator("proxy_location", mode="before")
+ @classmethod
+ def deserialize_proxy_location_field(cls, value: object) -> object:
+ return parse_proxy_location_input(value)
+
+ @field_validator("proxy_session_id")
+ @classmethod
+ def validate_proxy_session_id_field(cls, value: str | None) -> str | None:
+ return validate_proxy_session_id(value)
class CredentialResponse(BaseModel):
@@ -250,6 +274,19 @@ class CredentialResponse(BaseModel):
description="ID of the credential folder this credential belongs to, if any",
examples=["cfld_1234567890"],
)
+ proxy_location: ProxyLocationInput = Field(
+ default=None,
+ description="Optional proxy location used for the credential's pinned proxy identity.",
+ )
+ proxy_session_id: str | None = Field(
+ default=None,
+ description="Opaque Skyvern-managed proxy sticky-session id.",
+ )
+
+ @field_validator("proxy_session_id")
+ @classmethod
+ def validate_proxy_session_id_field(cls, value: str | None) -> str | None:
+ return validate_proxy_session_id(value)
class OnePasswordItemOverview(BaseModel):
@@ -331,17 +368,35 @@ class Credential(BaseModel):
default=None,
description="ID of the credential folder this credential belongs to, if any",
)
+ proxy_location: ProxyLocationInput = Field(
+ default=None,
+ description="Optional proxy location used for the credential's pinned proxy identity.",
+ )
+ proxy_session_id: str | None = Field(
+ default=None,
+ description="Opaque Skyvern-managed proxy sticky-session id.",
+ )
created_at: datetime = Field(..., description="Timestamp when the credential was created")
modified_at: datetime = Field(..., description="Timestamp when the credential was last modified")
deleted_at: datetime | None = Field(None, description="Timestamp when the credential was deleted, if applicable")
+ @field_validator("proxy_location", mode="before")
+ @classmethod
+ def deserialize_proxy_location_field(cls, value: object) -> object:
+ return parse_proxy_location_input(value)
+
+ @field_validator("proxy_session_id")
+ @classmethod
+ def validate_proxy_session_id_field(cls, value: str | None) -> str | None:
+ return validate_proxy_session_id(value)
+
class UpdateCredentialRequest(BaseModel):
"""Request model for updating credential metadata."""
- name: str = Field(
- ...,
+ name: str | None = Field(
+ default=None,
min_length=1,
description="New name for the credential",
examples=["My Updated Credential"],
@@ -360,12 +415,40 @@ class UpdateCredentialRequest(BaseModel):
default=None,
description="Whether the user intends to save a browser session, regardless of test outcome",
)
+ proxy_location: ProxyLocationInput = Field(
+ default=None,
+ description="Optional proxy location for this credential's pinned proxy identity.",
+ )
+ proxy_session_id: str | None = Field(
+ default=None,
+ description="Opaque Skyvern-managed proxy sticky-session id.",
+ )
+ rotate_proxy_session_id: bool = Field(
+ default=False,
+ description="Rotate the Skyvern-managed proxy sticky-session id for this credential.",
+ )
@field_validator("user_context", mode="before")
@classmethod
def normalize_user_context(cls, v: str | None) -> str | None:
return _normalize_optional_str(v)
+ @field_validator("proxy_location", mode="before")
+ @classmethod
+ def deserialize_proxy_location_field(cls, value: object) -> object:
+ return parse_proxy_location_input(value)
+
+ @field_validator("proxy_session_id")
+ @classmethod
+ def validate_proxy_session_id_field(cls, value: str | None) -> str | None:
+ return validate_proxy_session_id(value)
+
+ @model_validator(mode="after")
+ def _require_at_least_one_field(self) -> Self:
+ if not self.model_fields_set:
+ raise ValueError("At least one credential metadata field must be provided")
+ return self
+
def _normalize_optional_str(v: str | None) -> str | None:
"""Normalize whitespace-only strings to None."""
@@ -443,12 +526,30 @@ class TestLoginRequest(BaseModel):
max_length=1000,
description="Optional user-provided context describing the login sequence (e.g., 'click SSO button first')",
)
+ proxy_location: ProxyLocationInput = Field(
+ default=None,
+ description="Optional proxy location for this test credential's pinned proxy identity.",
+ )
+ proxy_session_id: str | None = Field(
+ default=None,
+ description="Opaque Skyvern-managed proxy sticky-session id.",
+ )
@field_validator("user_context", mode="before")
@classmethod
def normalize_user_context(cls, v: str | None) -> str | None:
return _normalize_optional_str(v)
+ @field_validator("proxy_location", mode="before")
+ @classmethod
+ def deserialize_proxy_location_field(cls, value: object) -> object:
+ return parse_proxy_location_input(value)
+
+ @field_validator("proxy_session_id")
+ @classmethod
+ def validate_proxy_session_id_field(cls, value: str | None) -> str | None:
+ return validate_proxy_session_id(value)
+
@model_validator(mode="after")
def validate_url(self) -> Self:
result = validate_url(self.url)
diff --git a/skyvern/forge/sdk/schemas/persistent_browser_sessions.py b/skyvern/forge/sdk/schemas/persistent_browser_sessions.py
index e5ab427d2..b297d7025 100644
--- a/skyvern/forge/sdk/schemas/persistent_browser_sessions.py
+++ b/skyvern/forge/sdk/schemas/persistent_browser_sessions.py
@@ -5,6 +5,7 @@ from enum import StrEnum
from pydantic import BaseModel, ConfigDict, field_validator
from skyvern.forge.sdk.db.utils import deserialize_proxy_location
+from skyvern.schemas.proxy_pinning import validate_proxy_session_id
from skyvern.schemas.runs import ProxyLocationInput
@@ -71,6 +72,7 @@ class PersistentBrowserSession(BaseModel):
status: str | None = None
timeout_minutes: int | None = None
proxy_location: ProxyLocationInput = None
+ proxy_session_id: str | None = None
instance_type: str | None = None
vcpu_millicores: int | None = None
memory_mb: int | None = None
@@ -96,6 +98,11 @@ class PersistentBrowserSession(BaseModel):
return deserialize_proxy_location(value, raise_on_invalid_geo_target=True)
return value
+ @field_validator("proxy_session_id")
+ @classmethod
+ def validate_proxy_session_id_field(cls, value: str | None) -> str | None:
+ return validate_proxy_session_id(value)
+
def should_export_profile(self) -> bool:
"""A session persists its profile at teardown only when it opted in or is reusing a saved profile.
diff --git a/skyvern/forge/sdk/services/credential/credential_vault_service.py b/skyvern/forge/sdk/services/credential/credential_vault_service.py
index 2a32e428e..a98a2a33c 100644
--- a/skyvern/forge/sdk/services/credential/credential_vault_service.py
+++ b/skyvern/forge/sdk/services/credential/credential_vault_service.py
@@ -1,4 +1,5 @@
from abc import ABC, abstractmethod
+from typing import Any
from skyvern.forge import app
from skyvern.forge.sdk.schemas.credentials import (
@@ -118,6 +119,8 @@ class CredentialVaultService(ABC):
totp_identifier=data.credential.totp_identifier,
card_last4=None,
card_brand=None,
+ proxy_location=data.proxy_location,
+ proxy_session_id=data.proxy_session_id,
)
elif data.credential_type == CredentialType.CREDIT_CARD:
return await app.DATABASE.credentials.create_credential(
@@ -131,6 +134,8 @@ class CredentialVaultService(ABC):
card_last4=data.credential.card_number[-4:],
card_brand=data.credential.card_brand,
totp_identifier=None,
+ proxy_location=data.proxy_location,
+ proxy_session_id=data.proxy_session_id,
)
elif data.credential_type == CredentialType.SECRET:
return await app.DATABASE.credentials.create_credential(
@@ -145,6 +150,8 @@ class CredentialVaultService(ABC):
card_brand=None,
totp_identifier=None,
secret_label=data.credential.secret_label,
+ proxy_location=data.proxy_location,
+ proxy_session_id=data.proxy_session_id,
)
else:
raise Exception(f"Unsupported credential type: {data.credential_type}")
@@ -155,6 +162,14 @@ class CredentialVaultService(ABC):
data: CreateCredentialRequest,
item_id: str,
) -> Credential:
+ proxy_kwargs: dict[str, Any] = {}
+ if "proxy_location" in data.model_fields_set:
+ proxy_kwargs["proxy_location"] = data.proxy_location
+ if "proxy_session_id" in data.model_fields_set:
+ proxy_kwargs["proxy_session_id"] = data.proxy_session_id
+ if data.rotate_proxy_session_id:
+ proxy_kwargs["rotate_proxy_session_id"] = True
+
if data.credential_type == CredentialType.PASSWORD:
return await app.DATABASE.credentials.update_credential_vault_data(
credential_id=credential.credential_id,
@@ -167,6 +182,7 @@ class CredentialVaultService(ABC):
totp_identifier=data.credential.totp_identifier,
card_last4=None,
card_brand=None,
+ **proxy_kwargs,
)
elif data.credential_type == CredentialType.CREDIT_CARD:
return await app.DATABASE.credentials.update_credential_vault_data(
@@ -180,6 +196,7 @@ class CredentialVaultService(ABC):
card_last4=data.credential.card_number[-4:],
card_brand=data.credential.card_brand,
totp_identifier=None,
+ **proxy_kwargs,
)
elif data.credential_type == CredentialType.SECRET:
return await app.DATABASE.credentials.update_credential_vault_data(
@@ -194,6 +211,7 @@ class CredentialVaultService(ABC):
card_brand=None,
totp_identifier=None,
secret_label=data.credential.secret_label,
+ **proxy_kwargs,
)
else:
raise Exception(f"Unsupported credential type: {data.credential_type}")
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 2c4839186..2793b8568 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -133,6 +133,7 @@ from skyvern.forge.sdk.workflow.status_mapping import (
from skyvern.forge.sdk.workflow.workflow_definition_converter import convert_workflow_definition
from skyvern.schemas.run_enums import RunEngine
from skyvern.schemas.runs import (
+ ProxyLocation,
ProxyLocationInput,
RunStatus,
RunType,
@@ -2795,6 +2796,12 @@ class WorkflowService:
)
if block.block_type == BlockType.LOGIN:
+ await self._apply_login_block_credential_proxy_pin(
+ block=block,
+ workflow_run=workflow_run,
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ )
resolved_browser_profile_id = await self._resolve_login_block_browser_profile_id(
block=block,
workflow_run_id=workflow_run_id,
@@ -3484,10 +3491,60 @@ class WorkflowService:
# so it must not reuse (and boot read-only from) the credential's saved profile.
if isinstance(block, LoginBlock) and block.skip_saved_profile:
return None
+ credential_ids = await self._resolve_login_block_credential_ids(
+ block=block,
+ workflow_run_id=workflow_run_id,
+ )
+
+ for credential_id in credential_ids:
+ if not organization_id:
+ continue
+ try:
+ db_cred = await app.DATABASE.credentials.get_credential(
+ credential_id=credential_id,
+ organization_id=organization_id,
+ )
+ if db_cred and db_cred.browser_profile_id:
+ # Verify the browser profile still exists before using it
+ profile = await app.DATABASE.browser_sessions.get_browser_profile(
+ profile_id=db_cred.browser_profile_id,
+ organization_id=organization_id,
+ )
+ if not profile:
+ LOG.warning(
+ "Credential has browser_profile_id but profile not found, ignoring",
+ credential_id=credential_id,
+ browser_profile_id=db_cred.browser_profile_id,
+ workflow_run_id=workflow_run_id,
+ )
+ continue
+ LOG.info(
+ "Resolved browser_profile_id from LoginBlock credential",
+ credential_id=credential_id,
+ browser_profile_id=db_cred.browser_profile_id,
+ workflow_run_id=workflow_run_id,
+ )
+ return db_cred.browser_profile_id
+ except Exception:
+ LOG.warning(
+ "Failed to look up credential for browser profile",
+ credential_id=credential_id,
+ workflow_run_id=workflow_run_id,
+ exc_info=True,
+ )
+ return None
+
+ async def _resolve_login_block_credential_ids(
+ self,
+ block: Block,
+ workflow_run_id: str | None,
+ ) -> list[str]:
+ """Return credential ids bound to this block, preserving parameter order."""
params = block.parameters
# Pre-fetch run parameters once (used by WorkflowParameter/CREDENTIAL_ID style).
run_param_tuples: list[tuple[Any, Any]] | None = None
+ credential_ids: list[str] = []
for param in params:
credential_id: str | None = None
@@ -3532,8 +3589,29 @@ class WorkflowService:
if not credential_id:
continue
+ credential_ids.append(credential_id)
+
+ return credential_ids
+
+ async def _apply_login_block_credential_proxy_pin(
+ self,
+ *,
+ block: Block,
+ workflow_run: WorkflowRun,
+ workflow_run_id: str,
+ organization_id: str | None,
+ ) -> None:
+ if not organization_id:
+ return
+ headers = dict(workflow_run.extra_http_headers or {})
+ if app.AGENT_FUNCTION.has_proxy_session_extra_http_headers(headers):
+ return
- # Look up the credential and check for a browser_profile_id
+ credential_ids = await self._resolve_login_block_credential_ids(
+ block=block,
+ workflow_run_id=workflow_run_id,
+ )
+ for credential_id in credential_ids:
if not organization_id:
continue
try:
@@ -3541,35 +3619,67 @@ class WorkflowService:
credential_id=credential_id,
organization_id=organization_id,
)
- if db_cred and db_cred.browser_profile_id:
- # Verify the browser profile still exists before using it
+ if not db_cred:
+ continue
+ proxy_session_id = db_cred.proxy_session_id
+ proxy_location = db_cred.proxy_location
+ browser_profile_id = getattr(db_cred, "browser_profile_id", None)
+ if browser_profile_id:
profile = await app.DATABASE.browser_sessions.get_browser_profile(
- profile_id=db_cred.browser_profile_id,
+ profile_id=browser_profile_id,
organization_id=organization_id,
)
- if not profile:
- LOG.warning(
- "Credential has browser_profile_id but profile not found, ignoring",
+ if profile:
+ if not profile.proxy_session_id:
+ LOG.info(
+ "Skipping LoginBlock credential proxy pin because linked browser profile is unpinned",
+ credential_id=credential_id,
+ browser_profile_id=browser_profile_id,
+ workflow_run_id=workflow_run_id,
+ )
+ return
+ proxy_session_id = profile.proxy_session_id
+ proxy_location = profile.proxy_location or ProxyLocation.RESIDENTIAL_ISP
+ LOG.info(
+ "Using linked browser profile proxy pin for LoginBlock",
credential_id=credential_id,
- browser_profile_id=db_cred.browser_profile_id,
+ browser_profile_id=browser_profile_id,
workflow_run_id=workflow_run_id,
)
- continue
+ if proxy_session_id:
+ updated_headers = app.AGENT_FUNCTION.merge_proxy_session_extra_http_headers(
+ headers, proxy_session_id
+ )
+ # The OSS AgentFunction stub returns the original headers; only persist when cloud injected a pin.
+ if updated_headers == headers:
+ return
+ proxy_location_update: ProxyLocationInput | None = None
+ if workflow_run.proxy_location is None:
+ proxy_location_update = proxy_location or ProxyLocation.RESIDENTIAL_ISP
+ update_kwargs: dict[str, Any] = {
+ "workflow_run_id": workflow_run_id,
+ "extra_http_headers": updated_headers,
+ }
+ if proxy_location_update is not None:
+ update_kwargs["proxy_location"] = proxy_location_update
+ await app.DATABASE.workflow_runs.update_workflow_run(**update_kwargs)
+ workflow_run.extra_http_headers = updated_headers
+ if proxy_location_update is not None:
+ workflow_run.proxy_location = proxy_location_update
LOG.info(
- "Resolved browser_profile_id from LoginBlock credential",
+ "Applied LoginBlock credential proxy pin to workflow run",
credential_id=credential_id,
- browser_profile_id=db_cred.browser_profile_id,
workflow_run_id=workflow_run_id,
+ proxy_location=str(workflow_run.proxy_location),
)
- return db_cred.browser_profile_id
+ return
except Exception:
- LOG.warning(
- "Failed to look up credential for browser profile",
+ LOG.error(
+ "Failed to apply LoginBlock credential proxy pin",
credential_id=credential_id,
workflow_run_id=workflow_run_id,
exc_info=True,
)
- return None
async def _evaluate_debug_session_profile_decision(
self,
diff --git a/skyvern/schemas/browser_sessions.py b/skyvern/schemas/browser_sessions.py
index fcee70b7d..34920c0ce 100644
--- a/skyvern/schemas/browser_sessions.py
+++ b/skyvern/schemas/browser_sessions.py
@@ -4,6 +4,7 @@ from skyvern.client.types.workflow_definition_yaml_blocks_item import WorkflowDe
from skyvern.client.types.workflow_definition_yaml_parameters_item import WorkflowDefinitionYamlParametersItem_Workflow
from skyvern.forge.sdk.schemas.persistent_browser_sessions import Extensions, PersistentBrowserType
from skyvern.schemas.docs.doc_strings import PROXY_LOCATION_DOC_STRING
+from skyvern.schemas.proxy_pinning import validate_proxy_session_id
from skyvern.schemas.runs import GeoTarget, ProxyLocationInput
from skyvern.services.browser_recording.types import RecordingDraftStep
@@ -37,6 +38,16 @@ class CreateBrowserSessionRequest(BaseModel):
return GeoTarget.model_validate(proxy_location)
return proxy_location
+ proxy_session_id: str | None = Field(
+ default=None,
+ description="Opaque Skyvern-managed proxy sticky-session id for pinned Residential ISP sessions.",
+ )
+
+ @field_validator("proxy_session_id")
+ @classmethod
+ def validate_proxy_session_id_field(cls, value: str | None) -> str | None:
+ return validate_proxy_session_id(value)
+
extensions: list[Extensions] | None = Field(
default=None,
description="A list of extensions to install in the browser session.",
diff --git a/skyvern/schemas/proxy_pinning.py b/skyvern/schemas/proxy_pinning.py
new file mode 100644
index 000000000..e1e486136
--- /dev/null
+++ b/skyvern/schemas/proxy_pinning.py
@@ -0,0 +1,96 @@
+from __future__ import annotations
+
+import json
+import secrets
+from typing import Any
+
+from skyvern.schemas.proxy_location import GeoTarget, ProxyLocation, ProxyLocationInput
+
+_LOWER_HEX = set("0123456789abcdef")
+
+
+def is_proxy_session_id(value: str) -> bool:
+ return len(value) == 10 and all(char in _LOWER_HEX for char in value)
+
+
+def normalize_proxy_session_id(value: str | None) -> str | None:
+ if value is None:
+ return None
+ raw_value = value.strip()
+ if not raw_value:
+ return None
+ return raw_value
+
+
+def generate_proxy_session_id(source_id: str) -> str:
+ if normalize_proxy_session_id(source_id) is None:
+ raise ValueError("Cannot generate proxy session id from an empty entity id")
+ proxy_session_id = secrets.token_hex(5)
+ if not is_proxy_session_id(proxy_session_id):
+ raise RuntimeError("Generated proxy session id does not match the expected format")
+ return proxy_session_id
+
+
+def redact_proxy_session_id(value: str | None) -> str | None:
+ if not value:
+ return None
+ if len(value) <= 5:
+ return "***"
+ return f"{value[:3]}...{value[-2:]}"
+
+
+def should_generate_proxy_session_id(proxy_location: object | None) -> bool:
+ return proxy_location == ProxyLocation.RESIDENTIAL_ISP or proxy_location == ProxyLocation.RESIDENTIAL_ISP.value
+
+
+def apply_proxy_pin_update(
+ update_kwargs: dict[str, Any],
+ *,
+ proxy_location_was_set: bool,
+ proxy_location: ProxyLocationInput,
+ proxy_session_id_was_set: bool,
+ proxy_session_id: str | None,
+ rotate_proxy_session_id: bool = False,
+) -> None:
+ if rotate_proxy_session_id:
+ update_kwargs["rotate_proxy_session_id"] = True
+
+ if proxy_location_was_set:
+ update_kwargs["proxy_location"] = proxy_location
+ if proxy_location is None or not should_generate_proxy_session_id(proxy_location):
+ update_kwargs["proxy_session_id"] = None
+ elif proxy_session_id_was_set and proxy_session_id is not None:
+ update_kwargs["proxy_session_id"] = proxy_session_id
+ return
+
+ if proxy_session_id_was_set:
+ if proxy_session_id:
+ update_kwargs["proxy_location"] = ProxyLocation.RESIDENTIAL_ISP
+ update_kwargs["proxy_session_id"] = proxy_session_id
+ else:
+ update_kwargs["proxy_location"] = None
+ update_kwargs["proxy_session_id"] = None
+
+
+def validate_proxy_session_id(value: str | None) -> str | None:
+ return normalize_proxy_session_id(value)
+
+
+def parse_proxy_location_input(value: object) -> object:
+ if value is None or isinstance(value, (ProxyLocation, GeoTarget)):
+ return value
+ if isinstance(value, dict):
+ if "url" in value and "country" not in value:
+ raise ValueError("Custom proxy URLs are not supported for pinned proxy identities")
+ return GeoTarget.model_validate(value)
+ if isinstance(value, str):
+ raw = value.strip()
+ if not raw:
+ return None
+ if raw.startswith("{"):
+ data = json.loads(raw)
+ if not isinstance(data, dict):
+ raise ValueError("proxy_location JSON must be an object")
+ return parse_proxy_location_input(data)
+ return ProxyLocation(raw)
+ return value
diff --git a/skyvern/webeye/default_persistent_sessions_manager.py b/skyvern/webeye/default_persistent_sessions_manager.py
index 93f4003bb..e2e2de4af 100644
--- a/skyvern/webeye/default_persistent_sessions_manager.py
+++ b/skyvern/webeye/default_persistent_sessions_manager.py
@@ -311,6 +311,7 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):
timeout_minutes: int | None = None,
extensions: list[Extensions] | None = None,
browser_type: PersistentBrowserType | None = None,
+ proxy_session_id: str | None = None,
is_high_priority: bool = False,
browser_profile_id: str | None = None,
generate_browser_profile: bool = False,
@@ -327,6 +328,7 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):
runnable_id=runnable_id,
timeout_minutes=timeout_minutes,
proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
extensions=extensions,
browser_type=browser_type,
browser_profile_id=browser_profile_id,
@@ -356,15 +358,28 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):
url: str | None = None,
) -> None:
try:
+ session = await self.get_session(session_id, organization_id)
+ if session is None or is_final_status(session.status) or session.completed_at is not None:
+ LOG.info(
+ "Session closed before browser launch, skipping browser launch",
+ browser_session_id=session_id,
+ )
+ return
+
+ launch_proxy_location = session.proxy_location if session.proxy_location is not None else proxy_location
+ extra_http_headers = app.AGENT_FUNCTION.build_proxy_session_extra_http_headers(session.proxy_session_id)
+
browser_state = await RealBrowserManager._create_browser_state(
- proxy_location=proxy_location,
+ proxy_location=launch_proxy_location,
url=url,
organization_id=organization_id,
+ extra_http_headers=extra_http_headers,
)
await browser_state.get_or_create_page(
url=url or "about:blank",
- proxy_location=proxy_location,
+ proxy_location=launch_proxy_location,
organization_id=organization_id,
+ extra_http_headers=extra_http_headers,
)
session = await self.get_session(session_id, organization_id)
diff --git a/skyvern/webeye/persistent_sessions_manager.py b/skyvern/webeye/persistent_sessions_manager.py
index dded80fba..a12676e5a 100644
--- a/skyvern/webeye/persistent_sessions_manager.py
+++ b/skyvern/webeye/persistent_sessions_manager.py
@@ -84,6 +84,7 @@ class PersistentSessionsManager(Protocol):
timeout_minutes: int | None = None,
extensions: list[Extensions] | None = None,
browser_type: PersistentBrowserType | None = None,
+ proxy_session_id: str | None = None,
is_high_priority: bool = False,
browser_profile_id: str | None = None,
generate_browser_profile: bool = False,
diff --git a/skyvern/webeye/real_browser_manager.py b/skyvern/webeye/real_browser_manager.py
index 4a7d6f1ca..c82bc424b 100644
--- a/skyvern/webeye/real_browser_manager.py
+++ b/skyvern/webeye/real_browser_manager.py
@@ -23,6 +23,15 @@ from skyvern.webeye.video_utils import finalize_webm
LOG = structlog.get_logger()
+def _merge_proxy_session_headers(
+ extra_http_headers: dict[str, str] | None,
+ proxy_session_id: str | None,
+) -> dict[str, str] | None:
+ if not proxy_session_id:
+ return extra_http_headers
+ return app.AGENT_FUNCTION.merge_proxy_session_extra_http_headers(extra_http_headers, proxy_session_id)
+
+
class RealBrowserManager(BrowserManager):
def __init__(self) -> None:
self.pages: dict[str, BrowserState] = {}
@@ -120,20 +129,23 @@ class RealBrowserManager(BrowserManager):
else:
LOG.warning("Browser state has no page", workflow_run_id=task.workflow_run_id)
+ proxy_location = task.proxy_location
+ extra_http_headers = task.extra_http_headers
if browser_state is None:
LOG.info("Creating browser state for task", task_id=task.task_id)
- proxy_location = task.proxy_location
if browser_session_id and task.organization_id:
session = await app.PERSISTENT_SESSIONS_MANAGER.get_session(browser_session_id, task.organization_id)
- if session and session.proxy_location is not None:
- proxy_location = session.proxy_location
+ if session:
+ if session.proxy_location is not None:
+ proxy_location = session.proxy_location
+ extra_http_headers = _merge_proxy_session_headers(extra_http_headers, session.proxy_session_id)
browser_state = await self._create_browser_state(
proxy_location=proxy_location,
url=task.url,
task_id=task.task_id,
workflow_permanent_id=task.workflow_permanent_id,
organization_id=task.organization_id,
- extra_http_headers=task.extra_http_headers,
+ extra_http_headers=extra_http_headers,
cdp_connect_headers=task.cdp_connect_headers,
browser_address=task.browser_address,
)
@@ -152,11 +164,11 @@ class RealBrowserManager(BrowserManager):
# This will make sure browser_state.page is not None.
await browser_state.get_or_create_page(
url=task.url,
- proxy_location=task.proxy_location,
+ proxy_location=proxy_location,
task_id=task.task_id,
workflow_permanent_id=task.workflow_permanent_id,
organization_id=task.organization_id,
- extra_http_headers=task.extra_http_headers,
+ extra_http_headers=extra_http_headers,
cdp_connect_headers=task.cdp_connect_headers,
browser_address=task.browser_address,
)
@@ -235,26 +247,29 @@ class RealBrowserManager(BrowserManager):
else:
LOG.warning("Browser state has no page", workflow_run_id=workflow_run.workflow_run_id)
+ proxy_location = workflow_run.proxy_location
+ extra_http_headers = workflow_run.extra_http_headers
if browser_state is None:
LOG.info(
"Creating browser state for workflow run",
sampling=True,
workflow_run_id=workflow_run.workflow_run_id,
)
- proxy_location = workflow_run.proxy_location
if browser_session_id and workflow_run.organization_id:
session = await app.PERSISTENT_SESSIONS_MANAGER.get_session(
browser_session_id, workflow_run.organization_id
)
- if session and session.proxy_location is not None:
- proxy_location = session.proxy_location
+ if session:
+ if session.proxy_location is not None:
+ proxy_location = session.proxy_location
+ extra_http_headers = _merge_proxy_session_headers(extra_http_headers, session.proxy_session_id)
browser_state = await self._create_browser_state(
proxy_location=proxy_location,
url=url,
workflow_run_id=workflow_run.workflow_run_id,
workflow_permanent_id=workflow_run.workflow_permanent_id,
organization_id=workflow_run.organization_id,
- extra_http_headers=workflow_run.extra_http_headers,
+ extra_http_headers=extra_http_headers,
cdp_connect_headers=workflow_run.cdp_connect_headers,
browser_address=workflow_run.browser_address,
browser_profile_id=browser_profile_id,
@@ -281,11 +296,11 @@ class RealBrowserManager(BrowserManager):
# script) performs the first goto itself, avoiding a redundant page load.
await browser_state.get_or_create_page(
url=url if navigate else None,
- proxy_location=workflow_run.proxy_location,
+ proxy_location=proxy_location,
workflow_run_id=workflow_run.workflow_run_id,
workflow_permanent_id=workflow_run.workflow_permanent_id,
organization_id=workflow_run.organization_id,
- extra_http_headers=workflow_run.extra_http_headers,
+ extra_http_headers=extra_http_headers,
cdp_connect_headers=workflow_run.cdp_connect_headers,
browser_address=workflow_run.browser_address,
browser_profile_id=browser_profile_id,
diff --git a/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py b/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py
index 52441d61f..c6ceb2b8a 100644
--- a/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py
+++ b/tests/unit/forge/sdk/test_create_browser_profile_from_session_route.py
@@ -21,6 +21,7 @@ from skyvern.forge.sdk.routes import browser_profiles as browser_profiles_route
from skyvern.forge.sdk.schemas.browser_profiles import BrowserProfile, CreateBrowserProfileRequest
from skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSession
from skyvern.forge.sdk.services import org_auth_service
+from skyvern.schemas.runs import ProxyLocation
_default_profile_template_candidates = browser_profiles_route._default_browser_profile_template_candidates
@@ -204,6 +205,8 @@ def test_create_empty_profile_stores_default_profile_seed(
organization_id="org_oss",
name="fresh profile",
description="blank",
+ proxy_location=None,
+ proxy_session_id=None,
)
mocks.store_profile.assert_awaited_once()
assert captured_directory["path"]
@@ -212,6 +215,29 @@ def test_create_empty_profile_stores_default_profile_seed(
mocks.hard_delete_db_profile.assert_not_awaited()
+def test_create_empty_profile_persists_requested_proxy_pin(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, mocks = _build_client(monkeypatch)
+
+ response = client.post(
+ "/v1/browser_profiles/",
+ json={
+ "name": "fresh profile",
+ "proxy_location": ProxyLocation.RESIDENTIAL_ISP,
+ "proxy_session_id": "abc1234567",
+ },
+ )
+
+ assert response.status_code == 200
+ mocks.create_profile.assert_awaited_once_with(
+ organization_id="org_oss",
+ name="fresh profile",
+ description=None,
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id="abc1234567",
+ )
+ mocks.store_profile.assert_awaited_once()
+
+
def test_default_profile_template_candidates_come_from_configured_directory(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
@@ -377,6 +403,8 @@ def test_create_profile_route_delegates_workflow_run_source(monkeypatch: pytest.
"name": "my profile",
"description": "from workflow",
"workflow_run_id": "wr_1",
+ "proxy_location": None,
+ "proxy_session_id": None,
}
]
mocks.rate_limit_submit_run.assert_not_awaited()
@@ -459,6 +487,48 @@ def test_promote_deletes_source_session_blob(monkeypatch: pytest.MonkeyPatch) ->
mocks.delete_profile_blob.assert_awaited_once_with(organization_id="org_oss", profile_id="pbs_1")
+def test_promote_inherits_session_proxy_pin(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, mocks = _build_client(monkeypatch)
+ mocks.get_session.return_value = _session(
+ generate_browser_profile=True,
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id="abc1234567",
+ )
+ mocks.retrieve_profile.return_value = "/tmp/session_dir"
+
+ response = client.post("/v1/browser_profiles/", json={"name": "my profile", "browser_session_id": "pbs_1"})
+
+ assert response.status_code == 200
+ assert mocks.create_profile.await_args.kwargs["proxy_location"] == ProxyLocation.RESIDENTIAL_ISP
+ assert mocks.create_profile.await_args.kwargs["proxy_session_id"] == "abc1234567"
+
+
+def test_promote_inherits_session_proxy_pin_for_blank_residential_request(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ client, mocks = _build_client(monkeypatch)
+ mocks.get_session.return_value = _session(
+ generate_browser_profile=True,
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id="abc1234567",
+ )
+ mocks.retrieve_profile.return_value = "/tmp/session_dir"
+
+ response = client.post(
+ "/v1/browser_profiles/",
+ json={
+ "name": "my profile",
+ "browser_session_id": "pbs_1",
+ "proxy_location": ProxyLocation.RESIDENTIAL_ISP,
+ "proxy_session_id": None,
+ },
+ )
+
+ assert response.status_code == 200
+ assert mocks.create_profile.await_args.kwargs["proxy_location"] == ProxyLocation.RESIDENTIAL_ISP
+ assert mocks.create_profile.await_args.kwargs["proxy_session_id"] == "abc1234567"
+
+
def test_failed_promote_does_not_delete_source_blob(monkeypatch: pytest.MonkeyPatch) -> None:
client, mocks = _build_client(monkeypatch)
mocks.get_session.return_value = _session(generate_browser_profile=True)
diff --git a/tests/unit/forge/sdk/test_update_browser_profile_route.py b/tests/unit/forge/sdk/test_update_browser_profile_route.py
index d87d0066f..2684b9466 100644
--- a/tests/unit/forge/sdk/test_update_browser_profile_route.py
+++ b/tests/unit/forge/sdk/test_update_browser_profile_route.py
@@ -16,6 +16,8 @@ from skyvern.forge import app as forge_app
from skyvern.forge.sdk.routes import routers as routers_module
from skyvern.forge.sdk.schemas.browser_profiles import BrowserProfile
from skyvern.forge.sdk.services import org_auth_service
+from skyvern.schemas.proxy_pinning import generate_proxy_session_id
+from skyvern.schemas.runs import ProxyLocation
ORG_ID = "org_oss"
PROFILE_ID = "bp_test_profile"
@@ -26,6 +28,8 @@ def _profile(
description: str | None = "A profile",
organization_id: str = ORG_ID,
profile_id: str = PROFILE_ID,
+ proxy_location: ProxyLocation | None = None,
+ proxy_session_id: str | None = None,
) -> BrowserProfile:
now = datetime.now(timezone.utc)
return BrowserProfile(
@@ -34,6 +38,8 @@ def _profile(
name=name,
description=description,
source_browser_type=None,
+ proxy_location=proxy_location,
+ proxy_session_id=proxy_session_id,
created_at=now,
modified_at=now,
deleted_at=None,
@@ -124,6 +130,132 @@ def test_update_browser_profile_name_and_description(monkeypatch: pytest.MonkeyP
)
+def test_update_browser_profile_enables_proxy_pin_with_generated_session_id(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, update_browser_profile = _build_client(monkeypatch)
+ generated_session_id = generate_proxy_session_id(PROFILE_ID)
+ update_browser_profile.return_value = _profile(
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id=generated_session_id,
+ )
+
+ response = client.patch(
+ f"/v1/browser_profiles/{PROFILE_ID}",
+ json={"proxy_location": "RESIDENTIAL_ISP", "proxy_session_id": None},
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["proxy_location"] == "RESIDENTIAL_ISP"
+ assert body["proxy_session_id"] == generated_session_id
+ update_browser_profile.assert_awaited_once_with(
+ profile_id=PROFILE_ID,
+ organization_id=ORG_ID,
+ name=None,
+ description=None,
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ )
+
+
+def test_update_browser_profile_rotates_proxy_pin(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, update_browser_profile = _build_client(monkeypatch)
+ rotated_session_id = generate_proxy_session_id(PROFILE_ID)
+ update_browser_profile.return_value = _profile(
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id=rotated_session_id,
+ )
+
+ response = client.patch(
+ f"/v1/browser_profiles/{PROFILE_ID}",
+ json={"proxy_location": "RESIDENTIAL_ISP", "rotate_proxy_session_id": True},
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["proxy_location"] == "RESIDENTIAL_ISP"
+ assert body["proxy_session_id"] == rotated_session_id
+ update_browser_profile.assert_awaited_once_with(
+ profile_id=PROFILE_ID,
+ organization_id=ORG_ID,
+ name=None,
+ description=None,
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ rotate_proxy_session_id=True,
+ )
+
+
+def test_update_browser_profile_sets_explicit_proxy_pin(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, update_browser_profile = _build_client(monkeypatch)
+ update_browser_profile.return_value = _profile(
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id="abc1234567",
+ )
+
+ response = client.patch(
+ f"/v1/browser_profiles/{PROFILE_ID}",
+ json={"proxy_location": "RESIDENTIAL_ISP", "proxy_session_id": "abc1234567"},
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["proxy_location"] == "RESIDENTIAL_ISP"
+ assert body["proxy_session_id"] == "abc1234567"
+ update_browser_profile.assert_awaited_once_with(
+ profile_id=PROFILE_ID,
+ organization_id=ORG_ID,
+ name=None,
+ description=None,
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id="abc1234567",
+ )
+
+
+def test_update_browser_profile_stores_advanced_proxy_identity_verbatim(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, update_browser_profile = _build_client(monkeypatch)
+ advanced_key = "[email protected]"
+ update_browser_profile.return_value = _profile(
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id=advanced_key,
+ )
+
+ response = client.patch(
+ f"/v1/browser_profiles/{PROFILE_ID}",
+ json={"proxy_session_id": advanced_key},
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["proxy_location"] == "RESIDENTIAL_ISP"
+ assert body["proxy_session_id"] == advanced_key
+ update_browser_profile.assert_awaited_once_with(
+ profile_id=PROFILE_ID,
+ organization_id=ORG_ID,
+ name=None,
+ description=None,
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id=advanced_key,
+ )
+
+
+def test_update_browser_profile_clears_proxy_pin(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, update_browser_profile = _build_client(monkeypatch)
+ update_browser_profile.return_value = _profile(proxy_location=None, proxy_session_id=None)
+
+ response = client.patch(
+ f"/v1/browser_profiles/{PROFILE_ID}",
+ json={"proxy_location": None},
+ )
+
+ assert response.status_code == 200
+ update_browser_profile.assert_awaited_once_with(
+ profile_id=PROFILE_ID,
+ organization_id=ORG_ID,
+ name=None,
+ description=None,
+ proxy_location=None,
+ proxy_session_id=None,
+ )
+
+
def test_update_browser_profile_not_found(monkeypatch: pytest.MonkeyPatch) -> None:
client, update_browser_profile = _build_client(monkeypatch)
update_browser_profile.side_effect = BrowserProfileNotFound(profile_id=PROFILE_ID, organization_id=ORG_ID)
diff --git a/tests/unit/test_client_proxy_pin_types.py b/tests/unit/test_client_proxy_pin_types.py
new file mode 100644
index 000000000..53a331b47
--- /dev/null
+++ b/tests/unit/test_client_proxy_pin_types.py
@@ -0,0 +1,104 @@
+import datetime as dt
+from types import SimpleNamespace
+from typing import cast
+from unittest.mock import Mock
+
+from skyvern.client.core.client_wrapper import SyncClientWrapper
+from skyvern.client.raw_client import RawSkyvern
+from skyvern.client.types.browser_profile import BrowserProfile
+from skyvern.client.types.credential_response import CredentialResponse
+from skyvern.client.types.non_empty_password_credential import NonEmptyPasswordCredential
+from skyvern.client.types.password_credential_response import PasswordCredentialResponse
+
+
+def test_client_browser_profile_exposes_proxy_pin_fields() -> None:
+ profile = BrowserProfile(
+ browser_profile_id="bprof_123",
+ organization_id="org_123",
+ name="Pinned profile",
+ proxy_location="RESIDENTIAL_ISP",
+ proxy_session_id="abc1234567",
+ created_at=dt.datetime(2026, 1, 1, tzinfo=dt.UTC),
+ modified_at=dt.datetime(2026, 1, 2, tzinfo=dt.UTC),
+ )
+
+ assert profile.proxy_location == "RESIDENTIAL_ISP"
+ assert profile.proxy_session_id == "abc1234567"
+
+
+def test_client_credential_response_exposes_proxy_pin_fields() -> None:
+ response = CredentialResponse(
+ credential_id="cred_123",
+ credential=PasswordCredentialResponse(username="[email protected]"),
+ credential_type="password",
+ name="Pinned credential",
+ proxy_location="RESIDENTIAL_ISP",
+ proxy_session_id="abc1234567",
+ )
+
+ assert response.proxy_location == "RESIDENTIAL_ISP"
+ assert response.proxy_session_id == "abc1234567"
+
+
+def _response(body: dict[str, object]) -> SimpleNamespace:
+ return SimpleNamespace(
+ status_code=200,
+ headers={},
+ text="",
+ json=lambda: body,
+ )
+
+
+def _raw_client(request: Mock) -> RawSkyvern:
+ client_wrapper = cast(SyncClientWrapper, SimpleNamespace(httpx_client=SimpleNamespace(request=request)))
+ return RawSkyvern(client_wrapper=client_wrapper)
+
+
+def test_raw_client_update_browser_profile_sends_rotate_proxy_session_id() -> None:
+ request = Mock(
+ return_value=_response(
+ {
+ "browser_profile_id": "bp_123",
+ "organization_id": "org_123",
+ "name": "Pinned profile",
+ "proxy_location": "RESIDENTIAL_ISP",
+ "proxy_session_id": "abc1234567",
+ "created_at": "2026-01-01T00:00:00Z",
+ "modified_at": "2026-01-02T00:00:00Z",
+ }
+ )
+ )
+
+ _raw_client(request).update_browser_profile(
+ "bp_123",
+ proxy_location="RESIDENTIAL_ISP",
+ rotate_proxy_session_id=True,
+ )
+
+ assert request.call_args.kwargs["json"]["rotate_proxy_session_id"] is True
+
+
+def test_raw_client_update_credential_sends_rotate_proxy_session_id() -> None:
+ request = Mock(
+ return_value=_response(
+ {
+ "credential_id": "cred_123",
+ "credential": {"username": "[email protected]"},
+ "credential_type": "password",
+ "name": "Pinned credential",
+ "proxy_location": "RESIDENTIAL_ISP",
+ "proxy_session_id": "abc1234567",
+ }
+ )
+ )
+
+ _raw_client(request).update_credential(
+ "cred_123",
+ name="Pinned credential",
+ credential_type="password",
+ credential=NonEmptyPasswordCredential(username="[email protected]", password="pw"),
+ proxy_location="RESIDENTIAL_ISP",
+ rotate_proxy_session_id=True,
+ )
+
+ assert request.call_args.kwargs["json"]["rotate_proxy_session_id"] is True
diff --git a/tests/unit/test_credential_test_trigger_type.py b/tests/unit/test_credential_test_trigger_type.py
index 5c1d4b420..3126082c3 100644
--- a/tests/unit/test_credential_test_trigger_type.py
+++ b/tests/unit/test_credential_test_trigger_type.py
@@ -12,6 +12,7 @@ from skyvern.forge.sdk.schemas.credentials import CredentialType
from skyvern.forge.sdk.schemas.credentials import TestCredentialRequest as CredentialTestRequest
from skyvern.forge.sdk.schemas.credentials import TestLoginRequest as LoginTestRequest
from skyvern.forge.sdk.services import org_auth_service
+from skyvern.schemas.runs import ProxyLocation
USER_AGENT_CASES = [
("skyvern-ui", WorkflowRunTriggerType.manual),
@@ -43,6 +44,15 @@ def _patch_executor(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(credentials.AsyncExecutorFactory, "get_executor", lambda: executor)
+def _patch_cloud_proxy_session_headers(monkeypatch: pytest.MonkeyPatch) -> None:
+ agent_function = SimpleNamespace(
+ build_proxy_session_extra_http_headers=lambda proxy_session_id: {"dedicated-ip": proxy_session_id}
+ if proxy_session_id
+ else None
+ )
+ monkeypatch.setattr(credentials.app, "AGENT_FUNCTION", agent_function)
+
+
@pytest.mark.parametrize("x_user_agent, expected", USER_AGENT_CASES)
@pytest.mark.asyncio
async def test_test_credential_trigger_type_from_user_agent(
@@ -58,11 +68,14 @@ async def test_test_credential_trigger_type_from_user_agent(
browser_profile_id=None,
totp_identifier=None,
name="Test Credential",
+ proxy_location=None,
+ proxy_session_id=None,
)
)
)
monkeypatch.setattr(credentials.app, "DATABASE", SimpleNamespace(credentials=mock_credentials))
monkeypatch.setattr(credentials.app, "WORKFLOW_SERVICE", _workflow_service(setup_mock))
+ _patch_cloud_proxy_session_headers(monkeypatch)
_patch_executor(monkeypatch)
response = await credentials.test_credential(
@@ -78,6 +91,39 @@ async def test_test_credential_trigger_type_from_user_agent(
assert response.workflow_run_id == "wr_test"
+async def test_test_credential_seeds_proxy_pin_workflow_request(monkeypatch: pytest.MonkeyPatch) -> None:
+ setup_mock = _setup_mock()
+ mock_credentials = SimpleNamespace(
+ get_credential=AsyncMock(
+ return_value=SimpleNamespace(
+ credential_type=CredentialType.PASSWORD,
+ browser_profile_id=None,
+ totp_identifier=None,
+ name="Test Credential",
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id="abc1234567",
+ )
+ )
+ )
+ monkeypatch.setattr(credentials.app, "DATABASE", SimpleNamespace(credentials=mock_credentials))
+ monkeypatch.setattr(credentials.app, "WORKFLOW_SERVICE", _workflow_service(setup_mock))
+ _patch_cloud_proxy_session_headers(monkeypatch)
+ _patch_executor(monkeypatch)
+
+ await credentials.test_credential(
+ background_tasks=BackgroundTasks(),
+ credential_id="cred_test",
+ data=CredentialTestRequest(url="https://example.com/login", save_browser_profile=False),
+ current_org=SimpleNamespace(organization_id="org_test"),
+ x_user_agent=None,
+ )
+
+ workflow_request = setup_mock.call_args.kwargs["workflow_request"]
+ assert workflow_request.proxy_location == ProxyLocation.RESIDENTIAL_ISP
+ assert workflow_request.extra_http_headers == {"dedicated-ip": "abc1234567"}
+
+
@pytest.mark.parametrize("x_user_agent, expected", USER_AGENT_CASES)
@pytest.mark.asyncio
async def test_test_login_trigger_type_from_user_agent(
@@ -111,6 +157,50 @@ async def test_test_login_trigger_type_from_user_agent(
await asyncio.sleep(0)
+async def test_test_login_seeds_proxy_pin_workflow_request(monkeypatch: pytest.MonkeyPatch) -> None:
+ setup_mock = _setup_mock()
+ vault_service = SimpleNamespace(
+ create_credential=AsyncMock(
+ return_value=SimpleNamespace(vault_type=None, credential_id="cred_test", totp_identifier=None)
+ )
+ )
+ mock_credentials = SimpleNamespace(
+ update_credential=AsyncMock(
+ return_value=SimpleNamespace(
+ vault_type=None,
+ credential_id="cred_test",
+ totp_identifier=None,
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id="abc1234567",
+ )
+ )
+ )
+ monkeypatch.setattr(credentials, "_get_credential_vault_service", AsyncMock(return_value=vault_service))
+ monkeypatch.setattr(credentials, "_create_browser_profile_after_workflow", AsyncMock())
+ monkeypatch.setattr(credentials.app, "DATABASE", SimpleNamespace(credentials=mock_credentials))
+ monkeypatch.setattr(credentials.app, "WORKFLOW_SERVICE", _workflow_service(setup_mock))
+ _patch_cloud_proxy_session_headers(monkeypatch)
+ _patch_executor(monkeypatch)
+
+ await credentials.test_login(
+ background_tasks=BackgroundTasks(),
+ data=LoginTestRequest(
+ url="https://example.com/login",
+ username="[email protected]",
+ password="pw",
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ ),
+ current_org=SimpleNamespace(organization_id="org_test"),
+ x_user_agent=None,
+ )
+
+ workflow_request = setup_mock.call_args.kwargs["workflow_request"]
+ assert workflow_request.proxy_location == ProxyLocation.RESIDENTIAL_ISP
+ assert workflow_request.extra_http_headers == {"dedicated-ip": "abc1234567"}
+ await asyncio.sleep(0)
+
+
def _auth_override() -> SimpleNamespace:
return SimpleNamespace(organization_id="org_test")
@@ -140,11 +230,14 @@ def test_test_credential_endpoint_wires_user_agent_header(
browser_profile_id=None,
totp_identifier=None,
name="Test Credential",
+ proxy_location=None,
+ proxy_session_id=None,
)
)
)
monkeypatch.setattr(credentials.app, "DATABASE", SimpleNamespace(credentials=mock_credentials))
monkeypatch.setattr(credentials.app, "WORKFLOW_SERVICE", _workflow_service(setup_mock))
+ _patch_cloud_proxy_session_headers(monkeypatch)
_patch_executor(monkeypatch)
app = FastAPI()
diff --git a/tests/unit/test_credential_update_params.py b/tests/unit/test_credential_update_params.py
index 34f769b87..10894b439 100644
--- a/tests/unit/test_credential_update_params.py
+++ b/tests/unit/test_credential_update_params.py
@@ -1,11 +1,31 @@
"""Tests that update_credential() accepts user_context and save_browser_session_intent
on CredentialRepository."""
-from unittest.mock import MagicMock, patch
+from datetime import datetime
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from fastapi import BackgroundTasks
+from skyvern.forge import app as forge_app
+from skyvern.forge.sdk.db.repositories.browser_sessions import BrowserSessionsRepository
from skyvern.forge.sdk.db.repositories.credentials import CredentialRepository
+from skyvern.forge.sdk.routes import credentials as credentials_routes
+from skyvern.forge.sdk.schemas.credentials import (
+ CreateCredentialRequest,
+ Credential,
+ CredentialType,
+ CredentialVaultType,
+)
+from skyvern.forge.sdk.services.credential.credential_vault_service import CredentialVaultService
+from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+from skyvern.schemas.proxy_pinning import apply_proxy_pin_update as _apply_proxy_pin_update
+from skyvern.schemas.proxy_pinning import (
+ generate_proxy_session_id,
+ is_proxy_session_id,
+)
+from skyvern.schemas.runs import ProxyLocation
from tests.unit.conftest import MockAsyncSessionCtx, make_mock_session
@@ -14,9 +34,108 @@ def _make_credential_repo(mock_credential: MagicMock) -> CredentialRepository:
return CredentialRepository(session_factory=lambda: MockAsyncSessionCtx(mock_session))
+def _make_browser_sessions_repo(mock_browser_profile: MagicMock) -> BrowserSessionsRepository:
+ mock_session = make_mock_session(mock_browser_profile)
+ return BrowserSessionsRepository(session_factory=lambda: MockAsyncSessionCtx(mock_session))
+
+
# --- CredentialRepository tests ---
+async def test_credential_vault_service_create_db_credential_passes_proxy_pin(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ create_credential = AsyncMock(return_value=MagicMock())
+ monkeypatch.setattr(forge_app.DATABASE.credentials, "create_credential", create_credential)
+
+ data = CreateCredentialRequest(
+ name="test",
+ credential_type=CredentialType.PASSWORD,
+ credential={"username": "[email protected]", "password": "pw"},
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ )
+
+ await CredentialVaultService._create_db_credential(
+ organization_id="org_123",
+ data=data,
+ item_id="item_123",
+ vault_type=CredentialVaultType.AZURE_VAULT,
+ )
+
+ create_credential.assert_awaited_once()
+ assert create_credential.await_args.kwargs["proxy_location"] == ProxyLocation.RESIDENTIAL_ISP
+ assert create_credential.await_args.kwargs["proxy_session_id"] is None
+
+
+async def test_create_credential_response_includes_generated_proxy_pin(monkeypatch: pytest.MonkeyPatch) -> None:
+ proxy_session_id = generate_proxy_session_id("cred_123")
+ stored_credential = Credential(
+ credential_id="cred_123",
+ organization_id="org_123",
+ name="test",
+ vault_type=CredentialVaultType.AZURE_VAULT,
+ item_id="item_123",
+ credential_type=CredentialType.PASSWORD,
+ username="[email protected]",
+ card_last4=None,
+ card_brand=None,
+ secret_label=None,
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id=proxy_session_id,
+ created_at=datetime(2026, 1, 1),
+ modified_at=datetime(2026, 1, 1),
+ )
+ vault_service = SimpleNamespace(create_credential=AsyncMock(return_value=stored_credential))
+ monkeypatch.setattr(credentials_routes, "_get_credential_vault_service", AsyncMock(return_value=vault_service))
+
+ data = CreateCredentialRequest(
+ name="test",
+ credential_type=CredentialType.PASSWORD,
+ credential={"username": "[email protected]", "password": "pw"},
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ )
+
+ response = await credentials_routes.create_credential(
+ background_tasks=BackgroundTasks(),
+ data=data,
+ current_org=SimpleNamespace(organization_id="org_123"),
+ )
+
+ assert response.proxy_location == ProxyLocation.RESIDENTIAL_ISP
+ assert response.proxy_session_id == proxy_session_id
+
+
+async def test_repo_create_credential_clears_incompatible_proxy_pin() -> None:
+ mock_session = AsyncMock()
+ mock_session.add = MagicMock()
+ mock_session.flush = AsyncMock()
+ mock_session.commit = AsyncMock()
+ mock_session.refresh = AsyncMock()
+ repo = CredentialRepository(session_factory=lambda: MockAsyncSessionCtx(mock_session))
+
+ with patch("skyvern.forge.sdk.schemas.credentials.Credential.model_validate", return_value=MagicMock()):
+ await repo.create_credential(
+ organization_id="org_123",
+ name="test",
+ vault_type=CredentialVaultType.AZURE_VAULT,
+ item_id="item_123",
+ credential_type=CredentialType.PASSWORD,
+ username="[email protected]",
+ totp_type="none",
+ card_last4=None,
+ card_brand=None,
+ proxy_location=ProxyLocation.NONE,
+ proxy_session_id="abc1234567",
+ )
+
+ stored_credential = mock_session.add.call_args.args[0]
+ assert stored_credential.proxy_location == ProxyLocation.NONE.value
+ assert stored_credential.proxy_session_id is None
+
+
@pytest.mark.asyncio
async def test_repo_update_credential_accepts_user_context() -> None:
mock_credential = MagicMock()
@@ -67,3 +186,454 @@ async def test_repo_update_credential_unset_params_not_applied() -> None:
assert mock_credential.user_context == "existing"
assert mock_credential.save_browser_session_intent is True
+
+
+async def test_repo_update_credential_generates_proxy_session_id_for_proxy_location() -> None:
+ mock_credential = MagicMock()
+ mock_credential.name = "test"
+ mock_credential.proxy_location = None
+ mock_credential.proxy_session_id = None
+ repo = _make_credential_repo(mock_credential)
+
+ with patch("skyvern.forge.sdk.schemas.credentials.Credential.model_validate", return_value=MagicMock()):
+ await repo.update_credential(
+ credential_id="cred_123",
+ organization_id="org_123",
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ )
+
+ assert mock_credential.proxy_location == ProxyLocation.RESIDENTIAL_ISP.value
+ assert mock_credential.proxy_session_id is not None
+ assert is_proxy_session_id(mock_credential.proxy_session_id)
+
+
+async def test_repo_update_credential_rotates_proxy_session_id_when_requested() -> None:
+ mock_credential = MagicMock()
+ mock_credential.name = "test"
+ mock_credential.proxy_location = ProxyLocation.RESIDENTIAL_ISP.value
+ mock_credential.proxy_session_id = "existing-pin"
+ repo = _make_credential_repo(mock_credential)
+
+ with patch("skyvern.forge.sdk.schemas.credentials.Credential.model_validate", return_value=MagicMock()):
+ await repo.update_credential(
+ credential_id="cred_123",
+ organization_id="org_123",
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ rotate_proxy_session_id=True,
+ )
+
+ assert mock_credential.proxy_location == ProxyLocation.RESIDENTIAL_ISP.value
+ assert mock_credential.proxy_session_id is not None
+ assert mock_credential.proxy_session_id != "existing-pin"
+ assert is_proxy_session_id(mock_credential.proxy_session_id)
+
+
+async def test_repo_update_credential_vault_data_persists_proxy_pin() -> None:
+ mock_credential = MagicMock()
+ mock_credential.name = "test"
+ mock_credential.proxy_location = None
+ mock_credential.proxy_session_id = None
+ repo = _make_credential_repo(mock_credential)
+
+ with patch("skyvern.forge.sdk.schemas.credentials.Credential.model_validate", return_value=MagicMock()):
+ await repo.update_credential_vault_data(
+ credential_id="cred_123",
+ organization_id="org_123",
+ item_id="item_123",
+ name="test",
+ credential_type="password",
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ )
+
+ assert mock_credential.proxy_location == ProxyLocation.RESIDENTIAL_ISP.value
+ assert mock_credential.proxy_session_id is not None
+ assert is_proxy_session_id(mock_credential.proxy_session_id)
+
+
+async def test_repo_update_credential_preserves_existing_proxy_pin_on_resave() -> None:
+ mock_credential = MagicMock()
+ mock_credential.name = "test"
+ mock_credential.proxy_location = ProxyLocation.RESIDENTIAL_ISP.value
+ mock_credential.proxy_session_id = "[email protected]"
+ repo = _make_credential_repo(mock_credential)
+
+ with patch("skyvern.forge.sdk.schemas.credentials.Credential.model_validate", return_value=MagicMock()):
+ await repo.update_credential(
+ credential_id="cred_123",
+ organization_id="org_123",
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ )
+
+ assert mock_credential.proxy_location == ProxyLocation.RESIDENTIAL_ISP.value
+ assert mock_credential.proxy_session_id == "[email protected]"
+
+
+async def test_repo_update_credential_explicit_null_session_id_clears_location() -> None:
+ mock_credential = MagicMock()
+ mock_credential.name = "test"
+ mock_credential.proxy_location = ProxyLocation.RESIDENTIAL_ISP.value
+ mock_credential.proxy_session_id = "abc1234567"
+ repo = _make_credential_repo(mock_credential)
+
+ with patch("skyvern.forge.sdk.schemas.credentials.Credential.model_validate", return_value=MagicMock()):
+ await repo.update_credential(
+ credential_id="cred_123",
+ organization_id="org_123",
+ proxy_session_id=None,
+ )
+
+ assert mock_credential.proxy_location is None
+ assert mock_credential.proxy_session_id is None
+
+
+async def test_repo_update_credential_non_isp_location_clears_stale_proxy_pin() -> None:
+ mock_credential = MagicMock()
+ mock_credential.name = "test"
+ mock_credential.proxy_location = ProxyLocation.RESIDENTIAL_ISP.value
+ mock_credential.proxy_session_id = "abc1234567"
+ repo = _make_credential_repo(mock_credential)
+
+ with patch("skyvern.forge.sdk.schemas.credentials.Credential.model_validate", return_value=MagicMock()):
+ await repo.update_credential(
+ credential_id="cred_123",
+ organization_id="org_123",
+ proxy_location=ProxyLocation.RESIDENTIAL,
+ )
+
+ assert mock_credential.proxy_location == ProxyLocation.RESIDENTIAL.value
+ assert mock_credential.proxy_session_id is None
+
+
+async def test_repo_update_browser_profile_preserves_existing_proxy_pin_on_resave() -> None:
+ mock_profile = MagicMock()
+ mock_profile.name = "Profile"
+ mock_profile.proxy_location = ProxyLocation.RESIDENTIAL_ISP.value
+ mock_profile.proxy_session_id = "[email protected]"
+ repo = _make_browser_sessions_repo(mock_profile)
+
+ with patch("skyvern.forge.sdk.schemas.browser_profiles.BrowserProfile.model_validate", return_value=MagicMock()):
+ await repo.update_browser_profile(
+ profile_id="bp_123",
+ organization_id="org_123",
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ )
+
+ assert mock_profile.proxy_location == ProxyLocation.RESIDENTIAL_ISP.value
+ assert mock_profile.proxy_session_id == "[email protected]"
+
+
+async def test_repo_update_browser_profile_rotates_proxy_session_id_when_requested() -> None:
+ mock_profile = MagicMock()
+ mock_profile.name = "Profile"
+ mock_profile.proxy_location = ProxyLocation.RESIDENTIAL_ISP.value
+ mock_profile.proxy_session_id = "existing-pin"
+ repo = _make_browser_sessions_repo(mock_profile)
+
+ with patch("skyvern.forge.sdk.schemas.browser_profiles.BrowserProfile.model_validate", return_value=MagicMock()):
+ await repo.update_browser_profile(
+ profile_id="bp_123",
+ organization_id="org_123",
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ rotate_proxy_session_id=True,
+ )
+
+ assert mock_profile.proxy_location == ProxyLocation.RESIDENTIAL_ISP.value
+ assert mock_profile.proxy_session_id is not None
+ assert mock_profile.proxy_session_id != "existing-pin"
+ assert is_proxy_session_id(mock_profile.proxy_session_id)
+
+
+async def test_repo_update_browser_profile_explicit_null_session_id_clears_location() -> None:
+ mock_profile = MagicMock()
+ mock_profile.name = "Profile"
+ mock_profile.proxy_location = ProxyLocation.RESIDENTIAL_ISP.value
+ mock_profile.proxy_session_id = "abc1234567"
+ repo = _make_browser_sessions_repo(mock_profile)
+
+ with patch("skyvern.forge.sdk.schemas.browser_profiles.BrowserProfile.model_validate", return_value=MagicMock()):
+ await repo.update_browser_profile(
+ profile_id="bp_123",
+ organization_id="org_123",
+ proxy_session_id=None,
+ )
+
+ assert mock_profile.proxy_location is None
+ assert mock_profile.proxy_session_id is None
+
+
+async def test_repo_update_browser_profile_non_isp_location_clears_stale_proxy_pin() -> None:
+ mock_profile = MagicMock()
+ mock_profile.name = "Profile"
+ mock_profile.proxy_location = ProxyLocation.RESIDENTIAL_ISP.value
+ mock_profile.proxy_session_id = "abc1234567"
+ repo = _make_browser_sessions_repo(mock_profile)
+
+ with patch("skyvern.forge.sdk.schemas.browser_profiles.BrowserProfile.model_validate", return_value=MagicMock()):
+ await repo.update_browser_profile(
+ profile_id="bp_123",
+ organization_id="org_123",
+ proxy_location=ProxyLocation.RESIDENTIAL,
+ )
+
+ assert mock_profile.proxy_location == ProxyLocation.RESIDENTIAL.value
+ assert mock_profile.proxy_session_id is None
+
+
+async def test_repo_create_browser_profile_clears_incompatible_proxy_pin() -> None:
+ mock_session = AsyncMock()
+ mock_session.add = MagicMock()
+ mock_session.commit = AsyncMock()
+ mock_session.refresh = AsyncMock()
+ repo = BrowserSessionsRepository(session_factory=lambda: MockAsyncSessionCtx(mock_session))
+
+ with patch("skyvern.forge.sdk.schemas.browser_profiles.BrowserProfile.model_validate", return_value=MagicMock()):
+ await repo.create_browser_profile(
+ organization_id="org_123",
+ name="Profile",
+ proxy_location=ProxyLocation.NONE,
+ proxy_session_id="abc1234567",
+ )
+
+ stored_profile = mock_session.add.call_args.args[0]
+ assert stored_profile.proxy_location == ProxyLocation.NONE.value
+ assert stored_profile.proxy_session_id is None
+
+
+async def test_browser_profile_resave_updates_proxy_pin_after_storage_write(monkeypatch: pytest.MonkeyPatch) -> None:
+ events: list[str] = []
+
+ async def store_browser_profile(**_kwargs: object) -> None:
+ events.append("store")
+
+ async def update_browser_profile(**_kwargs: object) -> SimpleNamespace:
+ events.append("update_profile")
+ return SimpleNamespace()
+
+ async def touch_browser_profile(**_kwargs: object) -> None:
+ events.append("touch_profile")
+
+ async def update_credential(**_kwargs: object) -> SimpleNamespace:
+ events.append("update_credential")
+ return SimpleNamespace()
+
+ monkeypatch.setattr(
+ forge_app.DATABASE.workflow_runs,
+ "get_workflow_run",
+ AsyncMock(return_value=SimpleNamespace(status=WorkflowRunStatus.completed)),
+ )
+ monkeypatch.setattr(forge_app.STORAGE, "retrieve_browser_session", AsyncMock(return_value="/tmp/session"))
+ monkeypatch.setattr(forge_app.STORAGE, "store_browser_profile", store_browser_profile)
+ monkeypatch.setattr(
+ forge_app.DATABASE.credentials,
+ "get_credential",
+ AsyncMock(
+ return_value=SimpleNamespace(
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id="abc1234567",
+ )
+ ),
+ )
+ monkeypatch.setattr(forge_app.DATABASE.credentials, "update_credential", update_credential)
+ monkeypatch.setattr(
+ forge_app.DATABASE.browser_sessions,
+ "get_browser_profile",
+ AsyncMock(return_value=SimpleNamespace(browser_profile_id="bp_existing")),
+ )
+ monkeypatch.setattr(forge_app.DATABASE.browser_sessions, "update_browser_profile", update_browser_profile)
+ monkeypatch.setattr(forge_app.DATABASE.browser_sessions, "touch_browser_profile", touch_browser_profile)
+
+ await credentials_routes._create_browser_profile_after_workflow(
+ credential_id="cred_123",
+ workflow_run_id="wr_123",
+ workflow_id="wf_123",
+ workflow_permanent_id="wp_123",
+ organization_id="org_123",
+ credential_name="test",
+ test_url="https://example.com/login",
+ existing_browser_profile_id="bp_existing",
+ )
+
+ assert events == ["store", "update_profile", "touch_profile", "update_credential"]
+
+
+async def test_browser_profile_resave_leaves_existing_profile_pin_when_credential_unpinned(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ events: list[str] = []
+
+ async def store_browser_profile(**_kwargs: object) -> None:
+ events.append("store")
+
+ async def update_browser_profile(**_kwargs: object) -> SimpleNamespace:
+ events.append("update_profile")
+ return SimpleNamespace()
+
+ async def touch_browser_profile(**_kwargs: object) -> None:
+ events.append("touch_profile")
+
+ async def update_credential(**_kwargs: object) -> SimpleNamespace:
+ events.append("update_credential")
+ return SimpleNamespace()
+
+ monkeypatch.setattr(
+ forge_app.DATABASE.workflow_runs,
+ "get_workflow_run",
+ AsyncMock(return_value=SimpleNamespace(status=WorkflowRunStatus.completed)),
+ )
+ monkeypatch.setattr(forge_app.STORAGE, "retrieve_browser_session", AsyncMock(return_value="/tmp/session"))
+ monkeypatch.setattr(forge_app.STORAGE, "store_browser_profile", store_browser_profile)
+ monkeypatch.setattr(
+ forge_app.DATABASE.credentials,
+ "get_credential",
+ AsyncMock(return_value=SimpleNamespace(proxy_location=None, proxy_session_id=None)),
+ )
+ monkeypatch.setattr(forge_app.DATABASE.credentials, "update_credential", update_credential)
+ monkeypatch.setattr(
+ forge_app.DATABASE.browser_sessions,
+ "get_browser_profile",
+ AsyncMock(return_value=SimpleNamespace(browser_profile_id="bp_existing")),
+ )
+ monkeypatch.setattr(forge_app.DATABASE.browser_sessions, "update_browser_profile", update_browser_profile)
+ monkeypatch.setattr(forge_app.DATABASE.browser_sessions, "touch_browser_profile", touch_browser_profile)
+
+ await credentials_routes._create_browser_profile_after_workflow(
+ credential_id="cred_123",
+ workflow_run_id="wr_123",
+ workflow_id="wf_123",
+ workflow_permanent_id="wp_123",
+ organization_id="org_123",
+ credential_name="test",
+ test_url="https://example.com/login",
+ existing_browser_profile_id="bp_existing",
+ )
+
+ assert events == ["store", "touch_profile", "update_credential"]
+
+
+async def test_browser_profile_resave_preserves_different_existing_profile_pin(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ events: list[str] = []
+
+ async def store_browser_profile(**_kwargs: object) -> None:
+ events.append("store")
+
+ async def update_browser_profile(**_kwargs: object) -> SimpleNamespace:
+ events.append("update_profile")
+ return SimpleNamespace()
+
+ async def touch_browser_profile(**_kwargs: object) -> None:
+ events.append("touch_profile")
+
+ async def update_credential(**_kwargs: object) -> SimpleNamespace:
+ events.append("update_credential")
+ return SimpleNamespace()
+
+ monkeypatch.setattr(
+ forge_app.DATABASE.workflow_runs,
+ "get_workflow_run",
+ AsyncMock(return_value=SimpleNamespace(status=WorkflowRunStatus.completed)),
+ )
+ monkeypatch.setattr(forge_app.STORAGE, "retrieve_browser_session", AsyncMock(return_value="/tmp/session"))
+ monkeypatch.setattr(forge_app.STORAGE, "store_browser_profile", store_browser_profile)
+ monkeypatch.setattr(
+ forge_app.DATABASE.credentials,
+ "get_credential",
+ AsyncMock(
+ return_value=SimpleNamespace(
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id="credential-pin",
+ )
+ ),
+ )
+ monkeypatch.setattr(forge_app.DATABASE.credentials, "update_credential", update_credential)
+ monkeypatch.setattr(
+ forge_app.DATABASE.browser_sessions,
+ "get_browser_profile",
+ AsyncMock(return_value=SimpleNamespace(browser_profile_id="bp_existing", proxy_session_id="profile-pin")),
+ )
+ monkeypatch.setattr(forge_app.DATABASE.browser_sessions, "update_browser_profile", update_browser_profile)
+ monkeypatch.setattr(forge_app.DATABASE.browser_sessions, "touch_browser_profile", touch_browser_profile)
+
+ await credentials_routes._create_browser_profile_after_workflow(
+ credential_id="cred_123",
+ workflow_run_id="wr_123",
+ workflow_id="wf_123",
+ workflow_permanent_id="wp_123",
+ organization_id="org_123",
+ credential_name="test",
+ test_url="https://example.com/login",
+ existing_browser_profile_id="bp_existing",
+ )
+
+ assert events == ["store", "touch_profile", "update_credential"]
+
+
+def test_credential_route_treats_null_advanced_key_as_no_explicit_identity() -> None:
+ update_kwargs: dict[str, object] = {}
+
+ _apply_proxy_pin_update(
+ update_kwargs,
+ proxy_location_was_set=True,
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id_was_set=True,
+ proxy_session_id=None,
+ )
+
+ assert update_kwargs == {"proxy_location": ProxyLocation.RESIDENTIAL_ISP}
+
+
+def test_credential_route_passes_rotate_proxy_session_id_intent() -> None:
+ update_kwargs: dict[str, object] = {}
+
+ _apply_proxy_pin_update(
+ update_kwargs,
+ proxy_location_was_set=True,
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ proxy_session_id_was_set=False,
+ proxy_session_id=None,
+ rotate_proxy_session_id=True,
+ )
+
+ assert update_kwargs == {
+ "proxy_location": ProxyLocation.RESIDENTIAL_ISP,
+ "rotate_proxy_session_id": True,
+ }
+
+
+def test_generate_proxy_session_id_rejects_empty_entity_id() -> None:
+ with pytest.raises(ValueError, match="empty entity id"):
+ generate_proxy_session_id(" ")
+
+
+async def test_repo_update_credential_clears_proxy_session_id_with_proxy_location() -> None:
+ mock_credential = MagicMock()
+ mock_credential.name = "test"
+ mock_credential.proxy_location = ProxyLocation.RESIDENTIAL_ISP.value
+ mock_credential.proxy_session_id = "abc1234567"
+ repo = _make_credential_repo(mock_credential)
+
+ with patch("skyvern.forge.sdk.schemas.credentials.Credential.model_validate", return_value=MagicMock()):
+ await repo.update_credential(
+ credential_id="cred_123",
+ organization_id="org_123",
+ proxy_location=None,
+ )
+
+ assert mock_credential.proxy_location is None
+ assert mock_credential.proxy_session_id is None
diff --git a/tests/unit/test_login_block_credential_proxy_pin.py b/tests/unit/test_login_block_credential_proxy_pin.py
new file mode 100644
index 000000000..1dc177c73
--- /dev/null
+++ b/tests/unit/test_login_block_credential_proxy_pin.py
@@ -0,0 +1,200 @@
+from datetime import datetime, timezone
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from skyvern.forge.sdk.workflow.models.parameter import CredentialParameter
+from skyvern.forge.sdk.workflow.service import WorkflowService
+from skyvern.schemas.runs import ProxyLocation
+
+
+def _credential_parameter(credential_id: str = "cred_1") -> CredentialParameter:
+ now = datetime.now(timezone.utc)
+ return CredentialParameter(
+ key="login",
+ credential_parameter_id="cp_1",
+ workflow_id="wf_1",
+ credential_id=credential_id,
+ created_at=now,
+ modified_at=now,
+ )
+
+
+def _proxy_header_hook() -> SimpleNamespace:
+ return SimpleNamespace(
+ has_proxy_session_extra_http_headers=lambda headers: bool(headers and "dedicated-ip" in headers),
+ merge_proxy_session_extra_http_headers=lambda headers, proxy_session_id: {
+ **dict(headers or {}),
+ "dedicated-ip": proxy_session_id,
+ },
+ )
+
+
+async def test_login_block_credential_proxy_pin_applies_to_workflow_run() -> None:
+ service = WorkflowService()
+ workflow_run = SimpleNamespace(extra_http_headers={"X-Test": "1"}, proxy_location=None)
+ block = SimpleNamespace(parameters=[_credential_parameter()])
+ credential = SimpleNamespace(proxy_session_id="credential-pin", proxy_location=ProxyLocation.RESIDENTIAL_ISP)
+
+ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:
+ mock_app.AGENT_FUNCTION = _proxy_header_hook()
+ mock_app.DATABASE.credentials.get_credential = AsyncMock(return_value=credential)
+ mock_app.DATABASE.workflow_runs.update_workflow_run = AsyncMock()
+
+ await service._apply_login_block_credential_proxy_pin(
+ block=block, # type: ignore[arg-type]
+ workflow_run=workflow_run, # type: ignore[arg-type]
+ workflow_run_id="wr_1",
+ organization_id="org_1",
+ )
+
+ assert workflow_run.extra_http_headers == {"X-Test": "1", "dedicated-ip": "credential-pin"}
+ assert workflow_run.proxy_location == ProxyLocation.RESIDENTIAL_ISP
+ mock_app.DATABASE.workflow_runs.update_workflow_run.assert_awaited_once_with(
+ workflow_run_id="wr_1",
+ extra_http_headers={"X-Test": "1", "dedicated-ip": "credential-pin"},
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ )
+
+
+async def test_login_block_credential_proxy_pin_respects_existing_run_header() -> None:
+ service = WorkflowService()
+ workflow_run = SimpleNamespace(extra_http_headers={"dedicated-ip": "run-pin"}, proxy_location=None)
+ block = SimpleNamespace(parameters=[_credential_parameter()])
+
+ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:
+ mock_app.AGENT_FUNCTION = _proxy_header_hook()
+ mock_app.DATABASE.credentials.get_credential = AsyncMock()
+ mock_app.DATABASE.workflow_runs.update_workflow_run = AsyncMock()
+
+ await service._apply_login_block_credential_proxy_pin(
+ block=block, # type: ignore[arg-type]
+ workflow_run=workflow_run, # type: ignore[arg-type]
+ workflow_run_id="wr_1",
+ organization_id="org_1",
+ )
+
+ mock_app.DATABASE.credentials.get_credential.assert_not_called()
+ mock_app.DATABASE.workflow_runs.update_workflow_run.assert_not_called()
+ assert workflow_run.extra_http_headers == {"dedicated-ip": "run-pin"}
+
+
+async def test_login_block_credential_proxy_pin_preserves_run_proxy_location() -> None:
+ service = WorkflowService()
+ workflow_run = SimpleNamespace(extra_http_headers=None, proxy_location=ProxyLocation.RESIDENTIAL)
+ block = SimpleNamespace(parameters=[_credential_parameter()])
+ credential = SimpleNamespace(proxy_session_id="credential-pin", proxy_location=ProxyLocation.RESIDENTIAL_ISP)
+
+ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:
+ mock_app.AGENT_FUNCTION = _proxy_header_hook()
+ mock_app.DATABASE.credentials.get_credential = AsyncMock(return_value=credential)
+ mock_app.DATABASE.workflow_runs.update_workflow_run = AsyncMock()
+
+ await service._apply_login_block_credential_proxy_pin(
+ block=block, # type: ignore[arg-type]
+ workflow_run=workflow_run, # type: ignore[arg-type]
+ workflow_run_id="wr_1",
+ organization_id="org_1",
+ )
+
+ update_kwargs: dict[str, Any] = mock_app.DATABASE.workflow_runs.update_workflow_run.await_args.kwargs
+ assert update_kwargs == {
+ "workflow_run_id": "wr_1",
+ "extra_http_headers": {"dedicated-ip": "credential-pin"},
+ }
+ assert workflow_run.proxy_location == ProxyLocation.RESIDENTIAL
+
+
+async def test_login_block_credential_proxy_pin_prefers_linked_profile_pin() -> None:
+ service = WorkflowService()
+ workflow_run = SimpleNamespace(extra_http_headers=None, proxy_location=None)
+ block = SimpleNamespace(parameters=[_credential_parameter()])
+ credential = SimpleNamespace(
+ proxy_session_id="credential-pin",
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ browser_profile_id="bp_1",
+ )
+ profile = SimpleNamespace(
+ proxy_session_id="profile-pin",
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ )
+
+ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:
+ mock_app.AGENT_FUNCTION = _proxy_header_hook()
+ mock_app.DATABASE.credentials.get_credential = AsyncMock(return_value=credential)
+ mock_app.DATABASE.browser_sessions.get_browser_profile = AsyncMock(return_value=profile)
+ mock_app.DATABASE.workflow_runs.update_workflow_run = AsyncMock()
+
+ await service._apply_login_block_credential_proxy_pin(
+ block=block, # type: ignore[arg-type]
+ workflow_run=workflow_run, # type: ignore[arg-type]
+ workflow_run_id="wr_1",
+ organization_id="org_1",
+ )
+
+ assert workflow_run.extra_http_headers == {"dedicated-ip": "profile-pin"}
+ assert workflow_run.proxy_location == ProxyLocation.RESIDENTIAL_ISP
+ mock_app.DATABASE.workflow_runs.update_workflow_run.assert_awaited_once_with(
+ workflow_run_id="wr_1",
+ extra_http_headers={"dedicated-ip": "profile-pin"},
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ )
+
+
+async def test_login_block_credential_proxy_pin_skips_when_linked_profile_is_unpinned() -> None:
+ service = WorkflowService()
+ workflow_run = SimpleNamespace(extra_http_headers=None, proxy_location=None)
+ block = SimpleNamespace(parameters=[_credential_parameter()])
+ credential = SimpleNamespace(
+ proxy_session_id="credential-pin",
+ proxy_location=ProxyLocation.RESIDENTIAL_ISP,
+ browser_profile_id="bp_1",
+ )
+ profile = SimpleNamespace(proxy_session_id=None, proxy_location=None)
+
+ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:
+ mock_app.AGENT_FUNCTION = _proxy_header_hook()
+ mock_app.DATABASE.credentials.get_credential = AsyncMock(return_value=credential)
+ mock_app.DATABASE.browser_sessions.get_browser_profile = AsyncMock(return_value=profile)
+ mock_app.DATABASE.workflow_runs.update_workflow_run = AsyncMock()
+
+ await service._apply_login_block_credential_proxy_pin(
+ block=block, # type: ignore[arg-type]
+ workflow_run=workflow_run, # type: ignore[arg-type]
+ workflow_run_id="wr_1",
+ organization_id="org_1",
+ )
+
+ assert workflow_run.extra_http_headers is None
+ assert workflow_run.proxy_location is None
+ mock_app.DATABASE.workflow_runs.update_workflow_run.assert_not_called()
+
+
+async def test_login_block_credential_proxy_pin_does_not_mutate_run_when_db_update_fails() -> None:
+ service = WorkflowService()
+ workflow_run = SimpleNamespace(extra_http_headers=None, proxy_location=None)
+ block = SimpleNamespace(parameters=[_credential_parameter()])
+ credential = SimpleNamespace(proxy_session_id="credential-pin", proxy_location=ProxyLocation.RESIDENTIAL_ISP)
+
+ with patch("skyvern.forge.sdk.workflow.service.app") as mock_app:
+ mock_app.AGENT_FUNCTION = _proxy_header_hook()
+ mock_app.DATABASE.credentials.get_credential = AsyncMock(return_value=credential)
+ mock_app.DATABASE.workflow_runs.update_workflow_run = AsyncMock(side_effect=RuntimeError("db down"))
+
+ await service._apply_login_block_credential_proxy_pin(
+ block=block, # type: ignore[arg-type]
+ workflow_run=workflow_run, # type: ignore[arg-type]
+ workflow_run_id="wr_1",
+ organization_id="org_1",
+ )
+
+ assert workflow_run.extra_http_headers is None
+ assert workflow_run.proxy_location is None
diff --git a/tests/unit/test_proxy_url_custom.py b/tests/unit/test_proxy_url_custom.py
index 50e16f8ab..51968f42c 100644
--- a/tests/unit/test_proxy_url_custom.py
+++ b/tests/unit/test_proxy_url_custom.py
@@ -1,7 +1,10 @@
import pytest
+from pydantic import ValidationError
from skyvern.config import settings
from skyvern.forge.sdk.db.utils import deserialize_proxy_location, serialize_proxy_location
+from skyvern.forge.sdk.schemas.browser_profiles import UpdateBrowserProfileRequest
+from skyvern.forge.sdk.schemas.credentials import UpdateCredentialRequest
from skyvern.schemas.runs import GeoTarget, ProxyLocation
from skyvern.webeye.browser_factory import BrowserContextFactory, _redact_proxy_url, _redact_url_query
@@ -79,6 +82,12 @@ def test_proxy_location_db_round_trip_custom_url() -> None:
assert deserialize_proxy_location(serialized) == original
[email protected]("request_model", [UpdateCredentialRequest, UpdateBrowserProfileRequest])
+def test_proxy_pin_requests_reject_custom_proxy_urls(request_model: type) -> None:
+ with pytest.raises(ValidationError, match="Custom proxy URLs are not supported"):
+ request_model(proxy_location={"url": "http://user:[email protected]:8080"})
+
+
def test_proxy_location_db_round_trip_geo_target() -> None:
original = GeoTarget(country="US", subdivision="CA", city="San Francisco")
serialized = serialize_proxy_location(original)
diff --git a/tests/unit/test_real_browser_manager.py b/tests/unit/test_real_browser_manager.py
index 21590e58f..886cb31ef 100644
--- a/tests/unit/test_real_browser_manager.py
+++ b/tests/unit/test_real_browser_manager.py
@@ -154,12 +154,22 @@ def make_task(
return task
-def make_session(proxy_location: object = None) -> MagicMock:
+def make_session(proxy_location: object = None, proxy_session_id: str | None = None) -> MagicMock:
session = MagicMock()
session.proxy_location = proxy_location
+ session.proxy_session_id = proxy_session_id
return session
+def _merge_cloud_proxy_session_headers(
+ extra_http_headers: dict[str, str] | None,
+ proxy_session_id: str,
+) -> dict[str, str]:
+ headers = dict(extra_http_headers or {})
+ headers.setdefault("dedicated-ip", proxy_session_id)
+ return headers
+
+
@pytest.mark.asyncio
async def test_task_browser_inherits_session_proxy_when_no_browser_state() -> None:
"""When a task has a browser_session_id and no in-memory browser state, the session's proxy_location is used."""
@@ -172,6 +182,7 @@ async def test_task_browser_inherits_session_proxy_when_no_browser_state() -> No
session = make_session(proxy_location=session_proxy)
with patch("skyvern.webeye.real_browser_manager.app") as mock_app:
+ mock_app.AGENT_FUNCTION.merge_proxy_session_extra_http_headers.side_effect = _merge_cloud_proxy_session_headers
mock_app.PERSISTENT_SESSIONS_MANAGER.get_browser_state = AsyncMock(return_value=None)
mock_app.PERSISTENT_SESSIONS_MANAGER.get_session = AsyncMock(return_value=session)
mock_app.PERSISTENT_SESSIONS_MANAGER.set_browser_state = AsyncMock()
@@ -186,6 +197,33 @@ async def test_task_browser_inherits_session_proxy_when_no_browser_state() -> No
assert kwargs["proxy_location"] == session_proxy
+async def test_task_browser_inherits_session_proxy_pin_when_no_browser_state() -> None:
+ manager = RealBrowserManager()
+ task = make_task("tsk_1", proxy_location="RESIDENTIAL")
+ task.extra_http_headers = {"X-Test": "1"}
+ new_browser_state = MagicMock()
+ new_browser_state.get_or_create_page = AsyncMock()
+
+ session = make_session(proxy_location="RESIDENTIAL_ISP", proxy_session_id="abc1234567")
+
+ with patch("skyvern.webeye.real_browser_manager.app") as mock_app:
+ mock_app.AGENT_FUNCTION.merge_proxy_session_extra_http_headers.side_effect = _merge_cloud_proxy_session_headers
+ mock_app.PERSISTENT_SESSIONS_MANAGER.get_browser_state = AsyncMock(return_value=None)
+ mock_app.PERSISTENT_SESSIONS_MANAGER.get_session = AsyncMock(return_value=session)
+ mock_app.PERSISTENT_SESSIONS_MANAGER.set_browser_state = AsyncMock()
+
+ with patch.object(
+ manager, "_create_browser_state", new=AsyncMock(return_value=new_browser_state)
+ ) as mock_create:
+ await manager.get_or_create_for_task(task=task, browser_session_id="pbs_123")
+
+ expected_headers = {"X-Test": "1", "dedicated-ip": "abc1234567"}
+ assert mock_create.await_args.kwargs["extra_http_headers"] == expected_headers
+ assert new_browser_state.get_or_create_page.await_args.kwargs["extra_http_headers"] == expected_headers
+ assert task.extra_http_headers == {"X-Test": "1"}
+
+
@pytest.mark.asyncio
async def test_task_browser_uses_task_proxy_when_session_has_no_proxy() -> None:
"""When the session has no proxy_location, the task's proxy_location is used."""
@@ -244,6 +282,38 @@ async def test_workflow_run_browser_inherits_session_proxy_when_no_browser_state
assert kwargs["proxy_location"] == session_proxy
+async def test_workflow_run_browser_inherits_session_proxy_pin_when_no_browser_state() -> None:
+ manager = RealBrowserManager()
+ workflow_run = make_workflow_run("wfr_1")
+ workflow_run.extra_http_headers = {"X-Test": "1"}
+
+ new_browser_state = MagicMock()
+ new_browser_state.get_or_create_page = AsyncMock()
+
+ session = make_session(proxy_location="RESIDENTIAL_ISP", proxy_session_id="abc1234567")
+
+ with patch("skyvern.webeye.real_browser_manager.app") as mock_app:
+ mock_app.AGENT_FUNCTION.merge_proxy_session_extra_http_headers.side_effect = _merge_cloud_proxy_session_headers
+ mock_app.PERSISTENT_SESSIONS_MANAGER.get_browser_state = AsyncMock(return_value=None)
+ mock_app.PERSISTENT_SESSIONS_MANAGER.get_session = AsyncMock(return_value=session)
+ mock_app.PERSISTENT_SESSIONS_MANAGER.set_browser_state = AsyncMock()
+
+ with patch.object(
+ manager, "_create_browser_state", new=AsyncMock(return_value=new_browser_state)
+ ) as mock_create:
+ await manager.get_or_create_for_workflow_run(
+ workflow_run=workflow_run,
+ url="https://example.com",
+ browser_session_id="pbs_456",
+ )
+
+ expected_headers = {"X-Test": "1", "dedicated-ip": "abc1234567"}
+ assert mock_create.await_args.kwargs["extra_http_headers"] == expected_headers
+ assert new_browser_state.get_or_create_page.await_args.kwargs["extra_http_headers"] == expected_headers
+ assert workflow_run.extra_http_headers == {"X-Test": "1"}
+
+
@pytest.mark.asyncio
async def test_workflow_run_browser_uses_workflow_proxy_when_session_has_no_proxy() -> None:
"""When the session has no proxy_location, the workflow run's proxy_location is used."""