Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Serve the browser a scoped session token instead of the organization API key (SKY-13084) (#8074)
Trevor Cheungfa4319e5de8f
diff --git a/entrypoint-skyvernui.sh b/entrypoint-skyvernui.shindex 2a49b6524..7fa9d64b9 100644--- a/entrypoint-skyvernui.sh+++ b/entrypoint-skyvernui.sh@@ -22,63 +22,83 @@ VITE_ARTIFACT_API_BASE_URL="${VITE_ARTIFACT_API_BASE_URL:-http://localhost:9090}VITE_BROWSER_STREAMING_MODE="${VITE_BROWSER_STREAMING_MODE:-vnc}"VITE_ENABLE_LOG_ARTIFACTS="${VITE_ENABLE_LOG_ARTIFACTS:-false}"VITE_ENABLE_CODE_BLOCK="${VITE_ENABLE_CODE_BLOCK:-false}"+VITE_ENVIRONMENT="${VITE_ENVIRONMENT:-local}"+VITE_API_PATH_PREFIX="${VITE_API_PATH_PREFIX:-}"VITE_ENABLE_2FA_NOTIFICATIONS="${VITE_ENABLE_2FA_NOTIFICATIONS:-false}"+VITE_CLERK_PUBLISHABLE_KEY="${VITE_CLERK_PUBLISHABLE_KEY:-}"+VITE_PUBLIC_POSTHOG_HOST="${VITE_PUBLIC_POSTHOG_HOST:-}"+VITE_PUBLIC_POSTHOG_KEY="${VITE_PUBLIC_POSTHOG_KEY:-}"-# Priority for VITE_SKYVERN_API_KEY:-# 1. Environment variable (from .env file or docker-compose environment),-# but only if it's not a placeholder/sentinel value. Both the Dockerfile-# default (__SKYVERN_API_KEY_PLACEHOLDER__) and the .env.example default-# (YOUR_API_KEY) can leak through if users skip configuration. Keep these-# sentinels aligned with the frontend's placeholder check in-# skyvern-frontend/src/util/env.ts (which matches the Docker sentinel by-# its _PLACEHOLDER__ suffix — the sed below rewrites every occurrence of-# the full sentinel in the bundle, so the frontend must never spell it out).-# 2. Generated credentials file from the backend first-run setup-# (volume-mounted at /app/.skyvern/credentials.toml in docker-compose)+# Priority for the server-side organization key:+# 1. SKYVERN_API_KEY environment variable+# 2. VITE_SKYVERN_API_KEY environment variable+# 3. Generated credentials file mounted by the open-source deployment+# 4. Fallback to .streamlit/secrets.toml (only available in self-hosted+# docker-compose deployments where the file is volume-mounted; not+# present in K8s deployments)+SKYVERN_API_KEY="${SKYVERN_API_KEY:-}"VITE_SKYVERN_API_KEY="${VITE_SKYVERN_API_KEY:-}"SKYVERN_CREDENTIALS_FILE="${SKYVERN_CREDENTIALS_FILE:-/app/.skyvern/credentials.toml}"-GENERATED_KEY=$(sed -n 's/.*cred\s*=\s*"\([^"]*\)".*/\1/p' "$SKYVERN_CREDENTIALS_FILE" 2>/dev/null || echo "")-if [ -n "$VITE_SKYVERN_API_KEY" ] \- && [ "$VITE_SKYVERN_API_KEY" != "__SKYVERN_API_KEY_PLACEHOLDER__" ] \- && [ "$VITE_SKYVERN_API_KEY" != "YOUR_API_KEY" ]; then+if [ -n "$SKYVERN_API_KEY" ]; then+ SKYVERN_API_KEY="${SKYVERN_API_KEY#"${SKYVERN_API_KEY%%[![:space:]]*}"}"+ SKYVERN_API_KEY="${SKYVERN_API_KEY%"${SKYVERN_API_KEY##*[![:space:]]}"}"+ echo "Using SKYVERN_API_KEY from environment variable"+elif [ -n "$VITE_SKYVERN_API_KEY" ]; thenVITE_SKYVERN_API_KEY="${VITE_SKYVERN_API_KEY#"${VITE_SKYVERN_API_KEY%%[![:space:]]*}"}"VITE_SKYVERN_API_KEY="${VITE_SKYVERN_API_KEY%"${VITE_SKYVERN_API_KEY##*[![:space:]]}"}"+ SKYVERN_API_KEY="$VITE_SKYVERN_API_KEY"echo "Using VITE_SKYVERN_API_KEY from environment variable"-elif [ -n "$GENERATED_KEY" ]; then- VITE_SKYVERN_API_KEY="$GENERATED_KEY"- echo "Using VITE_SKYVERN_API_KEY from $SKYVERN_CREDENTIALS_FILE"else- echo "WARNING: No VITE_SKYVERN_API_KEY found in environment or $SKYVERN_CREDENTIALS_FILE"- VITE_SKYVERN_API_KEY=""+ SKYVERN_API_KEY=$(sed -n 's/.*cred[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' "$SKYVERN_CREDENTIALS_FILE" 2>/dev/null || echo "")+ if [ -n "$SKYVERN_API_KEY" ]; then+ echo "Using SKYVERN_API_KEY from $SKYVERN_CREDENTIALS_FILE"+ else+ SKYVERN_API_KEY=$(sed -n 's/.*cred[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' .streamlit/secrets.toml 2>/dev/null || echo "")+ if [ -n "$SKYVERN_API_KEY" ]; then+ echo "Using SKYVERN_API_KEY from .streamlit/secrets.toml"+ else+ echo "WARNING: No organization key found in environment, $SKYVERN_CREDENTIALS_FILE, or .streamlit/secrets.toml"+ fi+ fifi+export SKYVERN_API_KEY+export VITE_API_BASE_URLecho "Injecting runtime environment variables into pre-built assets..."-# Rebuild from the pristine template each start so sed sees fresh placeholders-# and `docker restart` re-applies current env values (e.g. rotated API key).-rm -rf /app/dist-cp -r /app/dist.template /app/dist+if [ -d /app/dist.template ]; then+ rm -rf /app/dist+ cp -r /app/dist.template /app/dist+fi# Escape all values for safe use in sed replacement patternsESC_API_BASE_URL=$(escape_sed "$VITE_API_BASE_URL")ESC_WSS_BASE_URL=$(escape_sed "$VITE_WSS_BASE_URL")ESC_ARTIFACT_API_BASE_URL=$(escape_sed "$VITE_ARTIFACT_API_BASE_URL")-ESC_SKYVERN_API_KEY=$(escape_sed "$VITE_SKYVERN_API_KEY")ESC_BROWSER_STREAMING_MODE=$(escape_sed "$VITE_BROWSER_STREAMING_MODE")ESC_ENABLE_LOG_ARTIFACTS=$(escape_sed "$VITE_ENABLE_LOG_ARTIFACTS")ESC_ENABLE_CODE_BLOCK=$(escape_sed "$VITE_ENABLE_CODE_BLOCK")+ESC_ENVIRONMENT=$(escape_sed "$VITE_ENVIRONMENT")+ESC_API_PATH_PREFIX=$(escape_sed "$VITE_API_PATH_PREFIX")ESC_ENABLE_2FA_NOTIFICATIONS=$(escape_sed "$VITE_ENABLE_2FA_NOTIFICATIONS")+ESC_CLERK_PUBLISHABLE_KEY=$(escape_sed "$VITE_CLERK_PUBLISHABLE_KEY")+ESC_PUBLIC_POSTHOG_HOST=$(escape_sed "$VITE_PUBLIC_POSTHOG_HOST")+ESC_PUBLIC_POSTHOG_KEY=$(escape_sed "$VITE_PUBLIC_POSTHOG_KEY")# Replace placeholder strings in pre-built JS and HTML files with actual runtime valuesfind /app/dist \( -name "*.js" -o -name "*.html" \) -exec sed -i \-e "s|__VITE_API_BASE_URL_PLACEHOLDER__|${ESC_API_BASE_URL}|g" \-e "s|__VITE_WSS_BASE_URL_PLACEHOLDER__|${ESC_WSS_BASE_URL}|g" \-e "s|__VITE_ARTIFACT_API_BASE_URL_PLACEHOLDER__|${ESC_ARTIFACT_API_BASE_URL}|g" \- -e "s|__SKYVERN_API_KEY_PLACEHOLDER__|${ESC_SKYVERN_API_KEY}|g" \-e "s|__VITE_BROWSER_STREAMING_MODE_PLACEHOLDER__|${ESC_BROWSER_STREAMING_MODE}|g" \-e "s|__VITE_ENABLE_LOG_ARTIFACTS_PLACEHOLDER__|${ESC_ENABLE_LOG_ARTIFACTS}|g" \-e "s|__VITE_ENABLE_CODE_BLOCK_PLACEHOLDER__|${ESC_ENABLE_CODE_BLOCK}|g" \+ -e "s|__VITE_ENVIRONMENT_PLACEHOLDER__|${ESC_ENVIRONMENT}|g" \+ -e "s|__VITE_API_PATH_PREFIX_PLACEHOLDER__|${ESC_API_PATH_PREFIX}|g" \-e "s|__VITE_ENABLE_2FA_NOTIFICATIONS_PLACEHOLDER__|${ESC_ENABLE_2FA_NOTIFICATIONS}|g" \+ -e "s|__VITE_CLERK_PUBLISHABLE_KEY_PLACEHOLDER__|${ESC_CLERK_PUBLISHABLE_KEY}|g" \+ -e "s|__VITE_PUBLIC_POSTHOG_HOST_PLACEHOLDER__|${ESC_PUBLIC_POSTHOG_HOST}|g" \+ -e "s|__VITE_PUBLIC_POSTHOG_KEY_PLACEHOLDER__|${ESC_PUBLIC_POSTHOG_KEY}|g" \{} +# Sanity check: ensure ALL placeholders were actually replaced.@@ -87,10 +107,10 @@ find /app/dist \( -name "*.js" -o -name "*.html" \) -exec sed -i \# Scoped to *.js and *.html (the files sed modifies above) so unmodified# sourcemaps don't trigger false positives.if grep -rqE --include='*.js' --include='*.html' \- '__VITE_[A-Z0-9_]+_PLACEHOLDER__|__SKYVERN_API_KEY_PLACEHOLDER__' /app/dist/; then+ '__VITE_[A-Z0-9_]+_PLACEHOLDER__' /app/dist/; thenecho "ERROR: Placeholder replacement incomplete in dist/. Unreplaced placeholders:" >&2grep -rhoE --include='*.js' --include='*.html' \- '__VITE_[A-Z0-9_]+_PLACEHOLDER__|__SKYVERN_API_KEY_PLACEHOLDER__' /app/dist/ \+ '__VITE_[A-Z0-9_]+_PLACEHOLDER__' /app/dist/ \| sort -u | sed 's/^/ /' >&2exit 1fidiff --git a/run_ui.sh b/run_ui.shindex d4942cea8..c65abe66f 100755--- a/run_ui.sh+++ b/run_ui.sh@@ -9,7 +9,7 @@ cd skyvern-frontend || exit 1if [ ! -f .env ]; thencp .env.example .env- echo "[ERROR] Please add your api keys to the skyvern-frontend/.env file."+ echo "[ERROR] Set SKYVERN_API_KEY in skyvern-frontend/.env."finpm install --silentdiff --git a/skyvern-frontend/localServer.js b/skyvern-frontend/localServer.jsindex c195d58cb..b1d37e5f2 100644--- a/skyvern-frontend/localServer.js+++ b/skyvern-frontend/localServer.js@@ -1,43 +1,397 @@+import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";+import { existsSync, readFileSync } from "node:fs";import { createServer } from "http";+import { fileURLToPath, pathToFileURL } from "node:url";+import { parseEnv } from "node:util";import handler from "serve-handler";import open from "open";-const port = 8080;-const url = `http://localhost:${port}`;--const server = createServer((request, response) => {- const start = Date.now();-- // Hook into response finish to log status- response.on("finish", () => {- const duration = Date.now() - start;- const timestamp = new Date().toISOString();- console.log(- "[%s] %s %s %d %dms",- timestamp,- request.method,- request.url,- response.statusCode,- duration,+const DEFAULT_API_BASE_URL = "http://localhost:8000/api/v1";+const COMPOSE_API_BASE_URL = "http://skyvern:8000/api/v1";+const UI_SESSION_REQUEST_TIMEOUT_MS = 10_000;+const UI_SESSION_CACHE_EXPIRY_BUFFER_MS = 30_000;+const UI_SESSION_NONCE_COOKIE = "skyvern_ui_session_nonce";+const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);++function resolveOrganizationApiKey(env = process.env) {+ const key = env.SKYVERN_API_KEY?.trim() || env.VITE_SKYVERN_API_KEY?.trim();+ return key || null;+}++function isLoopbackUrl(value) {+ try {+ return LOOPBACK_HOSTNAMES.has(new URL(value).hostname);+ } catch {+ return false;+ }+}++function formatApiBaseUrlForLogging(value) {+ try {+ const url = new URL(value);+ url.username = "";+ url.password = "";+ url.search = "";+ url.hash = "";+ return url.toString();+ } catch {+ return "<invalid upstream URL>";+ }+}++function resolveServerApiBaseUrl(+ env = process.env,+ { isContainerized = existsSync("/.dockerenv") } = {},+) {+ const serverApiBaseUrl = env.SKYVERN_API_BASE_URL?.trim();+ if (serverApiBaseUrl) {+ return serverApiBaseUrl;+ }++ const browserApiBaseUrl =+ env.VITE_API_BASE_URL?.trim() || DEFAULT_API_BASE_URL;+ if (isContainerized && isLoopbackUrl(browserApiBaseUrl)) {+ return COMPOSE_API_BASE_URL;+ }+ return browserApiBaseUrl;+}++function loadEnvironmentFile(env, envFilePath) {+ let contents;+ try {+ contents = readFileSync(envFilePath, "utf8");+ } catch (error) {+ if (error?.code === "ENOENT") {+ return;+ }+ throw error;+ }++ for (const [key, value] of Object.entries(parseEnv(contents))) {+ if (!Object.hasOwn(env, key)) {+ env[key] = value;+ }+ }+}++function resolveLocalServerConfiguration({+ env = process.env,+ envFilePath = fileURLToPath(new URL(".env", import.meta.url)),+} = {}) {+ loadEnvironmentFile(env, envFilePath);+ return {+ apiBaseUrl: resolveServerApiBaseUrl(env),+ organizationApiKey: resolveOrganizationApiKey(env),+ };+}++function sendJson(response, statusCode, payload) {+ const body = JSON.stringify(payload);+ response.writeHead(statusCode, {+ "cache-control": "no-store",+ "content-length": Buffer.byteLength(body),+ "content-type": "application/json; charset=utf-8",+ });+ response.end(body);+}++// Distinct label so the nonce key is a one-way derivation and never doubles as the organization key.+const UI_SESSION_NONCE_KEY_LABEL = "skyvern.ui-session.nonce.v1";++function createUiSessionNonceManager(secret) {+ // Every replica must derive the same key: the nonce is issued by whichever pod served the HTML and+ // validated by whichever pod handles the mint, and the Service has no session affinity. A+ // per-process random key 403s that legitimate cross-pod pair, including during a rolling update.+ const signingKey = secret+ ? createHmac("sha256", String(secret))+ .update(UI_SESSION_NONCE_KEY_LABEL)+ .digest()+ : randomBytes(32);++ return {+ issue() {+ const nonce = randomBytes(32).toString("base64url");+ const signature = createHmac("sha256", signingKey)+ .update(nonce)+ .digest("base64url");+ return `${nonce}.${signature}`;+ },+ validate(value) {+ if (typeof value !== "string") {+ return false;+ }+ const separator = value.indexOf(".");+ if (separator < 1) {+ return false;+ }+ const nonce = value.slice(0, separator);+ const signature = Buffer.from(value.slice(separator + 1), "base64url");+ const expected = createHmac("sha256", signingKey).update(nonce).digest();+ return (+ signature.length === expected.length &&+ timingSafeEqual(signature, expected)+ );+ },+ };+}++function issueUiSessionNonceCookie(request, response, nonceManager) {+ if (+ request.method !== "GET" ||+ !request.headers.accept+ ?.split(",")+ .some((value) => value.trim().toLowerCase().startsWith("text/html"))+ ) {+ return;+ }+ response.setHeader(+ "set-cookie",+ `${UI_SESSION_NONCE_COOKIE}=${nonceManager.issue()}; Path=/ui-session; HttpOnly; SameSite=Strict`,+ );+}++function getCookie(request, name) {+ for (const part of request.headers.cookie?.split(";") ?? []) {+ const separator = part.indexOf("=");+ if (separator > 0 && part.slice(0, separator).trim() === name) {+ return part.slice(separator + 1).trim();+ }+ }+ return null;+}++function getRequestOrigin(request) {+ const forwardedProtocol = request.headers["x-forwarded-proto"]+ ?.split(",", 1)[0]+ ?.trim();+ const protocol =+ forwardedProtocol || (request.socket.encrypted ? "https" : "http");+ const host = request.headers.host;+ if (!host) {+ return null;+ }+ try {+ return new URL(`${protocol}://${host}`).origin;+ } catch {+ return null;+ }+}++function hasCrossOriginSignal(request) {+ const requestOrigin = getRequestOrigin(request);+ for (const header of [request.headers.origin, request.headers.referer]) {+ if (!header) {+ continue;+ }+ try {+ if (!requestOrigin || new URL(header).origin !== requestOrigin) {+ return true;+ }+ } catch {+ return true;+ }+ }+ return false;+}++function isUiSessionResponse(value) {+ return (+ value !== null &&+ typeof value === "object" &&+ typeof value.token === "string" &&+ value.token.length > 0 &&+ typeof value.expires_at === "number" &&+ Number.isFinite(value.expires_at) &&+ value.expires_at * 1000 > Date.now()+ );+}++function createUiSessionHandler({+ apiBaseUrl,+ organizationApiKey,+ fetchImpl = fetch,+ logger = console,+ requestTimeoutMs = UI_SESSION_REQUEST_TIMEOUT_MS,+ nonceManager = createUiSessionNonceManager(organizationApiKey),+} = {}) {+ let cachedUiSession = null;+ let mintFailureLogged = false;+ let mintInFlight = null;++ const logMintFailureOnce = () => {+ if (!mintFailureLogged) {+ const loggableApiBaseUrl = formatApiBaseUrlForLogging(apiBaseUrl);+ logger.error(+ `UI session minting failed against ${loggableApiBaseUrl}: upstream request failed. Set SKYVERN_API_BASE_URL to override the upstream.`,+ );+ mintFailureLogged = true;+ }+ };++ const mintUiSession = async () => {+ const abortController = new AbortController();+ const timeoutId = setTimeout(+ () => abortController.abort(),+ requestTimeoutMs,);+ try {+ const upstream = await fetchImpl(+ `${apiBaseUrl.replace(/\/+$/, "")}/ui-session`,+ {+ method: "POST",+ headers: {+ accept: "application/json",+ "x-api-key": organizationApiKey,+ },+ signal: abortController.signal,+ },+ );+ if (!upstream.ok) {+ throw new Error(`backend returned HTTP ${upstream.status}`);+ }+ const payload = await upstream.json();+ if (!isUiSessionResponse(payload)) {+ throw new Error("backend returned an invalid response");+ }+ return {+ token: payload.token,+ expires_at: payload.expires_at,+ };+ } finally {+ clearTimeout(timeoutId);+ }+ };++ const getUiSession = async (bypassCache) => {+ if (+ !bypassCache &&+ cachedUiSession &&+ cachedUiSession.expires_at * 1000 - Date.now() >+ UI_SESSION_CACHE_EXPIRY_BUFFER_MS+ ) {+ return cachedUiSession;+ }+ if (!mintInFlight) {+ mintInFlight = mintUiSession()+ .then((payload) => {+ cachedUiSession = payload;+ return payload;+ })+ .finally(() => {+ mintInFlight = null;+ });+ }+ return await mintInFlight;+ };++ return async (request, response) => {+ if (request.method !== "GET") {+ sendJson(response, 405, { detail: "Method not allowed" });+ return;+ }+ const secFetchSite = request.headers["sec-fetch-site"];+ const nonce = getCookie(request, UI_SESSION_NONCE_COOKIE);+ if (+ (secFetchSite && secFetchSite !== "same-origin") ||+ hasCrossOriginSignal(request) ||+ !nonceManager.validate(nonce)+ ) {+ sendJson(response, 403, {+ detail: "Cross-site requests are not allowed",+ });+ return;+ }+ const bypassCache =+ request.headers["x-skyvern-ui-session-refresh"] === "auth-failure";+ if (!organizationApiKey) {+ sendJson(response, 503, {+ detail: "UI session minting is not configured",+ });+ return;+ }++ try {+ sendJson(response, 200, await getUiSession(bypassCache));+ } catch {+ logMintFailureOnce();+ sendJson(response, 502, {+ detail: "Unable to mint a UI session token",+ });+ }+ };+}++function createLocalServer({+ env = process.env,+ apiBaseUrl = resolveServerApiBaseUrl(env),+ organizationApiKey = resolveOrganizationApiKey(env),+ fetchImpl = fetch,+ logger = console,+ requestTimeoutMs = UI_SESSION_REQUEST_TIMEOUT_MS,+} = {}) {+ const nonceManager = createUiSessionNonceManager(organizationApiKey);+ const serveUiSession = createUiSessionHandler({+ apiBaseUrl,+ organizationApiKey,+ fetchImpl,+ logger,+ requestTimeoutMs,+ nonceManager,});- // You pass two more arguments for config and middleware- // More details here: https://github.com/vercel/serve-handler#options- return handler(request, response, {- public: "dist",- rewrites: [- {- source: "**",- destination: "/index.html",- },- ],+ return createServer(async (request, response) => {+ const requestUrl = new URL(request.url || "/", "http://localhost");+ if (requestUrl.pathname === "/ui-session") {+ await serveUiSession(request, response);+ return;+ }++ issueUiSessionNonceCookie(request, response, nonceManager);+ await handler(request, response, {+ public: "dist",+ rewrites: [+ {+ source: "**",+ destination: "/index.html",+ },+ ],+ });});-});+}-server.listen(8080, async () => {- console.log(- `[${new Date().toISOString()}] Frontend server running at ${url}`,- );- await open(url);-});+function startLocalServer() {+ const { apiBaseUrl, organizationApiKey } = resolveLocalServerConfiguration();+ if (organizationApiKey) {+ console.log("UI session minting is configured");+ } else {+ console.error("UI session minting is disabled: no organization key found");+ }+ const server = createLocalServer({ apiBaseUrl, organizationApiKey });+ server.listen(8080, async () => {+ console.log("Running at http://localhost:8080");+ try {+ await open("http://localhost:8080");+ } catch {+ // Expected to fail in Docker containers where no browser is available+ }+ });+}++const isMainModule =+ process.argv[1] !== undefined &&+ import.meta.url === pathToFileURL(process.argv[1]).href;++if (isMainModule) {+ startLocalServer();+}++export {+ createLocalServer,+ createUiSessionHandler,+ createUiSessionNonceManager,+ issueUiSessionNonceCookie,+ resolveLocalServerConfiguration,+ resolveOrganizationApiKey,+ resolveServerApiBaseUrl,+ startLocalServer,+};diff --git a/skyvern-frontend/scripts/app-version.mjs b/skyvern-frontend/scripts/app-version.mjsnew file mode 100644index 000000000..38a886c86--- /dev/null+++ b/skyvern-frontend/scripts/app-version.mjs@@ -0,0 +1,14 @@+import { execSync } from "child_process";++// Single source for the build version: the `__APP_VERSION__` define (SDK+// `version`) and the Datadog upload's `--release-version` must derive from this.+export function resolveAppVersion(env = process.env) {+ if (env.VERCEL_GIT_COMMIT_SHA) {+ return env.VERCEL_GIT_COMMIT_SHA;+ }+ try {+ return execSync("git rev-parse HEAD").toString().trim();+ } catch {+ return "development";+ }+}diff --git a/skyvern-frontend/src/api/AxiosClient.test.ts b/skyvern-frontend/src/api/AxiosClient.test.tsnew file mode 100644index 000000000..73568bbff--- /dev/null+++ b/skyvern-frontend/src/api/AxiosClient.test.ts@@ -0,0 +1,501 @@+import { AxiosError, type AxiosAdapter, type AxiosResponse } from "axios";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const API_KEY_STORAGE_KEY = "skyvern.apiKey";+const API_KEY_EXPIRES_AT_STORAGE_KEY = "skyvern.apiKeyExpiresAt";++function createAuthRetryAdapter() {+ const adapter = vi.fn<AxiosAdapter>(async (config) => {+ const response: AxiosResponse = {+ data: { ok: true },+ status: 200,+ statusText: "OK",+ headers: {},+ config,+ };+ if (adapter.mock.calls.length === 1) {+ throw new AxiosError(+ "Request failed",+ AxiosError.ERR_BAD_REQUEST,+ config,+ undefined,+ {+ ...response,+ data: { detail: "Invalid credentials" },+ status: 401,+ statusText: "Unauthorized",+ },+ );+ }+ return response;+ });+ return adapter;+}++describe("UI session refresh", () => {+ beforeEach(() => {+ vi.resetModules();+ vi.useFakeTimers({ now: new Date("2030-01-01T00:00:00Z") });+ window.sessionStorage.clear();+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+ window.sessionStorage.clear();+ });++ function htmlCatchAll() {+ // What an SPA catch-all or a proxy mid-rollout returns for a path that does exist.+ return new Response("<!doctype html>", {+ status: 200,+ headers: { "content-type": "text/html" },+ });+ }++ function mintedSession() {+ return new Response(+ JSON.stringify({+ token: "recovered-session-canary",+ expires_at: Math.floor(Date.now() / 1000) + 3600,+ }),+ { status: 200, headers: { "content-type": "application/json" } },+ );+ }++ it("still mints after a single non-JSON response from an endpoint that exists", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(htmlCatchAll())+ .mockResolvedValue(mintedSession());+ vi.stubGlobal("fetch", fetchMock);++ const { initializeUiSession } = await import("./AxiosClient");+ await initializeUiSession();+ await initializeUiSession();++ // The old latch disabled refresh permanently on that first response, so no token was ever stored.+ expect(window.sessionStorage.getItem(API_KEY_STORAGE_KEY)).toBe(+ "recovered-session-canary",+ );+ });++ it("gives up probing an endpoint that is genuinely absent", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValue(new Response("not found", { status: 404 }));+ vi.stubGlobal("fetch", fetchMock);++ const { initializeUiSession } = await import("./AxiosClient");+ for (let attempt = 0; attempt < 4; attempt += 1) {+ await initializeUiSession();+ }+ const afterLatch = fetchMock.mock.calls.length;+ await initializeUiSession();+ await initializeUiSession();++ expect(window.sessionStorage.getItem(API_KEY_STORAGE_KEY)).toBeNull();+ expect(fetchMock.mock.calls.length).toBe(afterLatch);+ });++ it("schedules a refresh for a persisted unexpired UI session", async () => {+ const now = Math.floor(Date.now() / 1000);+ window.sessionStorage.setItem(+ API_KEY_STORAGE_KEY,+ "persisted-ui-session-canary",+ );+ window.sessionStorage.setItem(+ API_KEY_EXPIRES_AT_STORAGE_KEY,+ String(now + 120),+ );+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ token: "scheduled-refresh-canary",+ expires_at: now + 240,+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const { initializeUiSession } = await import("./AxiosClient");+ await initializeUiSession();++ expect(fetchMock).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(59_999);+ expect(fetchMock).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it.each([+ ["missing", null],+ ["expired", -1],+ ])(+ "mints on initialization when the persisted expiry is %s",+ async (_state, expiryOffset) => {+ const now = Math.floor(Date.now() / 1000);+ window.sessionStorage.setItem(+ API_KEY_STORAGE_KEY,+ "stale-ui-session-canary",+ );+ if (expiryOffset !== null) {+ window.sessionStorage.setItem(+ API_KEY_EXPIRES_AT_STORAGE_KEY,+ String(now + expiryOffset),+ );+ }+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ token: "replacement-ui-session-canary",+ expires_at: now + 120,+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const { initializeUiSession } = await import("./AxiosClient");+ await initializeUiSession();++ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(window.sessionStorage.getItem(API_KEY_STORAGE_KEY)).toBe(+ "replacement-ui-session-canary",+ );+ expect(+ window.sessionStorage.getItem(API_KEY_EXPIRES_AT_STORAGE_KEY),+ ).toBe(String(now + 120));+ },+ );++ it("mints on initialization when no token is persisted", async () => {+ const now = Math.floor(Date.now() / 1000);+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ token: "initial-ui-session-canary",+ expires_at: now + 120,+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const { initializeUiSession } = await import("./AxiosClient");+ await initializeUiSession();++ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(window.sessionStorage.getItem(API_KEY_STORAGE_KEY)).toBe(+ "initial-ui-session-canary",+ );+ expect(window.sessionStorage.getItem(API_KEY_EXPIRES_AT_STORAGE_KEY)).toBe(+ String(now + 120),+ );+ });++ it("aborts a hung session request and completes initialization", async () => {+ const fetchMock = vi.fn((_input: RequestInfo | URL, init?: RequestInit) => {+ return new Promise<Response>((_resolve, reject) => {+ init?.signal?.addEventListener(+ "abort",+ () => reject(init.signal?.reason),+ { once: true },+ );+ });+ });+ vi.stubGlobal("fetch", fetchMock);++ const { initializeUiSession } = await import("./AxiosClient");+ let initialized = false;+ const initialization = initializeUiSession().then(() => {+ initialized = true;+ });++ await vi.advanceTimersByTimeAsync(9_999);+ expect(initialized).toBe(false);++ await vi.advanceTimersByTimeAsync(1);+ await expect(initialization).resolves.toBeUndefined();+ expect(fetchMock.mock.calls[0]?.[1]?.signal?.aborted).toBe(true);+ });++ it("retries minting after a transient UI session failure", async () => {+ const now = Math.floor(Date.now() / 1000);+ const recoveredToken = "recovered-ui-session-canary";+ const fetchMock = vi+ .fn()+ .mockRejectedValueOnce(new TypeError("Network unavailable"))+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ token: recoveredToken,+ expires_at: now + 120,+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const { getClient, initializeUiSession } = await import("./AxiosClient");+ await initializeUiSession();+ const client = await getClient(null);+ const adapter = createAuthRetryAdapter();+ client.defaults.adapter = adapter;++ await expect(client.get("/protected")).resolves.toMatchObject({+ data: { ok: true },+ });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(adapter).toHaveBeenCalledTimes(2);+ expect(adapter.mock.calls[1]?.[0].headers.get("X-API-Key")).toBe(+ recoveredToken,+ );+ expect(window.sessionStorage.getItem(API_KEY_STORAGE_KEY)).toBe(+ recoveredToken,+ );+ });++ it("retries initialization after a transient UI session failure", async () => {+ const now = Math.floor(Date.now() / 1000);+ const recoveredToken = "reinitialized-ui-session-canary";+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(+ new Response(JSON.stringify({ detail: "Temporarily unavailable" }), {+ status: 502,+ headers: { "content-type": "application/json" },+ }),+ )+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ token: recoveredToken,+ expires_at: now + 120,+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const { initializeUiSession } = await import("./AxiosClient");+ await initializeUiSession();+ await initializeUiSession();++ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(window.sessionStorage.getItem(API_KEY_STORAGE_KEY)).toBe(+ recoveredToken,+ );+ });++ it.each([+ [+ "404 response",+ () =>+ new Response(JSON.stringify({ detail: "Not found" }), {+ status: 404,+ headers: { "content-type": "application/json" },+ }),+ ],+ [+ "non-JSON response",+ () =>+ new Response("<html>Not found</html>", {+ status: 200,+ headers: { "content-type": "text/html" },+ }),+ ],+ ])(+ "disables minting when the UI session endpoint returns a %s",+ async (_responseType, createResponse) => {+ const fetchMock = vi.fn().mockResolvedValue(createResponse());+ vi.stubGlobal("fetch", fetchMock);++ const { getClient, initializeUiSession } = await import("./AxiosClient");+ // One such response is ambiguous — a proxy mid-rollout produces it for an endpoint that+ // exists — so the latch needs a run of them before concluding the endpoint is absent.+ for (let attempt = 0; attempt < 4; attempt += 1) {+ await initializeUiSession();+ }+ const mintsBeforeAuthFailure = fetchMock.mock.calls.length;++ const client = await getClient(null);+ const adapter = createAuthRetryAdapter();+ client.defaults.adapter = adapter;++ await expect(client.get("/protected")).rejects.toMatchObject({+ response: { status: 401 },+ });+ // A 401 buys exactly one re-probe, because it is evidence the deployment does want a token.+ const mintsAfterAuthFailure = fetchMock.mock.calls.length;+ expect(mintsAfterAuthFailure).toBe(mintsBeforeAuthFailure + 1);+ expect(adapter).toHaveBeenCalledTimes(1);++ // Every later failure is silent: no unbounded probing of an absent endpoint.+ const secondAdapter = createAuthRetryAdapter();+ client.defaults.adapter = secondAdapter;+ await expect(client.get("/protected")).rejects.toMatchObject({+ response: { status: 401 },+ });+ expect(fetchMock.mock.calls.length).toBe(mintsAfterAuthFailure);+ },+ );++ it("treats a valid persisted UI session as endpoint confirmation", async () => {+ const now = Math.floor(Date.now() / 1000);+ const recoveredToken = "persisted-recovery-ui-session-canary";+ window.sessionStorage.setItem(+ API_KEY_STORAGE_KEY,+ "persisted-ui-session-canary",+ );+ window.sessionStorage.setItem(+ API_KEY_EXPIRES_AT_STORAGE_KEY,+ String(now + 120),+ );+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(+ new Response(JSON.stringify({ detail: "Not found" }), {+ status: 404,+ headers: { "content-type": "application/json" },+ }),+ )+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ token: recoveredToken,+ expires_at: now + 240,+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const { getClient, initializeUiSession } = await import("./AxiosClient");+ await initializeUiSession();+ expect(fetchMock).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(60_000);+ expect(fetchMock).toHaveBeenCalledTimes(1);++ const client = await getClient(null);+ const adapter = createAuthRetryAdapter();+ client.defaults.adapter = adapter;++ await expect(client.get("/protected")).resolves.toMatchObject({+ data: { ok: true },+ });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(adapter).toHaveBeenCalledTimes(2);+ expect(window.sessionStorage.getItem(API_KEY_STORAGE_KEY)).toBe(+ recoveredToken,+ );+ });++ it("refreshes after an auth failure, retries once, and succeeds", async () => {+ const expiredToken = "expired-ui-session-canary";+ const refreshedToken = "refreshed-ui-session-canary";+ window.sessionStorage.setItem(API_KEY_STORAGE_KEY, expiredToken);+ window.sessionStorage.setItem(+ API_KEY_EXPIRES_AT_STORAGE_KEY,+ String(Math.floor(Date.now() / 1000) + 120),+ );+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ token: refreshedToken,+ expires_at: Math.floor(Date.now() / 1000) + 120,+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const { getClient, initializeUiSession } = await import("./AxiosClient");+ await initializeUiSession();+ const client = await getClient(null);+ const adapter = createAuthRetryAdapter();+ client.defaults.adapter = adapter;++ const response = await client.get("/protected");++ expect(response.data).toEqual({ ok: true });+ expect(adapter).toHaveBeenCalledTimes(2);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(+ new Headers(fetchMock.mock.calls[0]?.[1]?.headers).get(+ "x-skyvern-ui-session-refresh",+ ),+ ).toBe("auth-failure");+ expect(adapter.mock.calls[1]?.[0].headers.get("X-API-Key")).toBe(+ refreshedToken,+ );+ expect(window.sessionStorage.getItem(API_KEY_STORAGE_KEY)).toBe(+ refreshedToken,+ );+ });+});++describe("open-source application entrypoint", () => {+ beforeEach(() => {+ vi.resetModules();+ window.sessionStorage.clear();+ });++ afterEach(() => {+ vi.doUnmock("../App.tsx");+ vi.doUnmock("react-dom/client");+ vi.unstubAllGlobals();+ window.sessionStorage.clear();+ });++ it("requests a UI session during startup", async () => {+ const render = vi.fn();+ vi.doMock("../App.tsx", () => ({ default: () => null }));+ vi.doMock("react-dom/client", () => ({+ default: {+ createRoot: () => ({ render }),+ },+ }));+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ detail: "Not configured" }), {+ status: 404,+ headers: { "content-type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ await import("../main");++ expect(fetchMock).toHaveBeenCalledWith(+ "/ui-session",+ expect.objectContaining({+ cache: "no-store",+ headers: { accept: "application/json" },+ }),+ );+ expect(render).toHaveBeenCalledTimes(1);+ });+});diff --git a/skyvern-frontend/src/api/AxiosClient.ts b/skyvern-frontend/src/api/AxiosClient.tsindex 40fad40c0..3b16d5278 100644--- a/skyvern-frontend/src/api/AxiosClient.ts+++ b/skyvern-frontend/src/api/AxiosClient.ts@@ -2,11 +2,12 @@ import {apiBaseUrl,artifactApiBaseUrl,getRuntimeApiKey,+ getRuntimeApiKeyExpiresAt,persistRuntimeApiKey,clearRuntimeApiKey,} from "@/util/env";import { useAuthIssueStore } from "@/store/AuthIssueStore";-import axios from "axios";+import axios, { type InternalAxiosRequestConfig } from "axios";type ApiVersion = "sans-api-v1" | "v1" | "v2";@@ -52,6 +53,155 @@ const artifactApiClient = axios.create({const clients = [client, v2Client, clientSansApiV1] as const;+type UISessionResponse = {+ token: string;+ expires_at: number;+};++type UISessionRetryConfig = InternalAxiosRequestConfig & {+ uiSessionRetry?: boolean;+};++const UI_SESSION_REQUEST_TIMEOUT_MS = 10_000;++let uiSessionEnabled = false;+let uiSessionEndpointConfirmed = false;+// "endpoint absent" is inferred from a 404 or a non-JSON 200, and an SPA catch-all or a proxy+// mid-rollout produces exactly that for an endpoint which does exist. Require a run of them before+// concluding the deployment has no mint endpoint, so one blip cannot disable refresh for the tab.+let uiSessionEndpointAbsentStreak = 0;+let uiSessionLatchReprobed = false;+const UI_SESSION_ENDPOINT_ABSENT_LIMIT = 3;+let uiSessionInitialization: Promise<void> | null = null;+let uiSessionRefresh: Promise<boolean> | null = null;+let uiSessionRefreshBypassesCache = false;+let uiSessionRefreshTimer: ReturnType<typeof setTimeout> | null = null;++function isUiSessionResponse(value: unknown): value is UISessionResponse {+ if (!value || typeof value !== "object") {+ return false;+ }+ const candidate = value as Partial<UISessionResponse>;+ return (+ typeof candidate.token === "string" &&+ candidate.token.length > 0 &&+ typeof candidate.expires_at === "number" &&+ Number.isFinite(candidate.expires_at) &&+ candidate.expires_at * 1000 > Date.now()+ );+}++function scheduleUiSessionRefresh(expiresAt: number) {+ if (uiSessionRefreshTimer) {+ clearTimeout(uiSessionRefreshTimer);+ }+ const remainingLifetime = expiresAt * 1000 - Date.now();+ uiSessionRefreshTimer = setTimeout(+ () => {+ void refreshUiSession();+ },+ Math.max(0, remainingLifetime / 2),+ );+}++async function requestUiSession(bypassCache = false): Promise<boolean> {+ const abortController = new AbortController();+ const timeoutId = setTimeout(+ () => abortController.abort(),+ UI_SESSION_REQUEST_TIMEOUT_MS,+ );+ try {+ const response = await fetch("/ui-session", {+ cache: "no-store",+ headers: {+ accept: "application/json",+ ...(bypassCache+ ? { "x-skyvern-ui-session-refresh": "auth-failure" }+ : {}),+ },+ signal: abortController.signal,+ });+ const contentType = response.headers.get("content-type") ?? "";+ const hasJsonContentType = contentType.includes("application/json");+ const endpointAbsent =+ response.status === 404 || (response.ok && !hasJsonContentType);+ if (!response.ok || !hasJsonContentType) {+ if (!uiSessionEndpointConfirmed && endpointAbsent) {+ uiSessionEndpointAbsentStreak += 1;+ if (uiSessionEndpointAbsentStreak >= UI_SESSION_ENDPOINT_ABSENT_LIMIT) {+ uiSessionEnabled = false;+ }+ }+ return false;+ }+ const payload: unknown = await response.json();+ if (!isUiSessionResponse(payload)) {+ return false;+ }+ uiSessionEndpointConfirmed = true;+ uiSessionEndpointAbsentStreak = 0;+ setApiKeyHeader(payload.token, payload.expires_at);+ scheduleUiSessionRefresh(payload.expires_at);+ return true;+ } catch {+ return false;+ } finally {+ clearTimeout(timeoutId);+ }+}++async function refreshUiSession(bypassCache = false): Promise<boolean> {+ if (!uiSessionEnabled) {+ // A 401/403 is evidence the deployment does want a credential, so a latch set by ambiguous+ // absent-endpoint responses may have been wrong. Probe exactly once per page load, and only+ // lift the latch if that probe actually mints — re-enabling first would let a genuinely absent+ // endpoint be polled again on every later failure.+ if (!bypassCache || uiSessionLatchReprobed) {+ return false;+ }+ uiSessionLatchReprobed = true;+ const recovered = await requestUiSession(true);+ if (recovered) {+ uiSessionEnabled = true;+ uiSessionEndpointAbsentStreak = 0;+ }+ return recovered;+ }+ if (uiSessionRefresh) {+ if (bypassCache && !uiSessionRefreshBypassesCache) {+ await uiSessionRefresh;+ return await refreshUiSession(true);+ }+ return await uiSessionRefresh;+ }+ uiSessionRefreshBypassesCache = bypassCache;+ uiSessionRefresh = requestUiSession(bypassCache).finally(() => {+ uiSessionRefresh = null;+ uiSessionRefreshBypassesCache = false;+ });+ return await uiSessionRefresh;+}++export function initializeUiSession(): Promise<void> {+ if (!uiSessionInitialization) {+ uiSessionEnabled = true;+ uiSessionInitialization = (async () => {+ const apiKey = getRuntimeApiKey();+ const expiresAt = getRuntimeApiKeyExpiresAt();+ if (apiKey && expiresAt && expiresAt * 1000 > Date.now()) {+ uiSessionEndpointConfirmed = true;+ scheduleUiSessionRefresh(expiresAt);+ } else {+ const initialized = await refreshUiSession();+ if (!initialized && uiSessionEnabled) {+ uiSessionInitialization = null;+ }+ }+ })();+ }+ return uiSessionInitialization;+}+function getResponseDetail(data: unknown): string | undefined {if (data && typeof data === "object" && "detail" in data) {const detail = (data as { detail?: unknown }).detail;@@ -63,10 +213,25 @@ function getResponseDetail(data: unknown): string | undefined {clients.forEach((instance) => {instance.interceptors.response.use((response) => response,- (error) => {+ async (error) => {if (axios.isAxiosError(error)) {const statusCode = error.response?.status;const detail = getResponseDetail(error.response?.data);+ const retryConfig = error.config as UISessionRetryConfig | undefined;+ if (+ (statusCode === 401 || statusCode === 403) &&+ retryConfig &&+ !retryConfig.uiSessionRetry+ ) {+ retryConfig.uiSessionRetry = true;+ if (await refreshUiSession(true)) {+ const apiKey = getRuntimeApiKey();+ if (apiKey) {+ retryConfig.headers.set("X-API-Key", apiKey);+ return await instance.request(retryConfig);+ }+ }+ }const isAuthFailure =statusCode === 401 ||statusCode === 403 ||@@ -109,8 +274,8 @@ export function removeAuthorizationHeader() {removeHeaderForAllClients("Authorization");}-export function setApiKeyHeader(apiKey: string) {- persistRuntimeApiKey(apiKey);+export function setApiKeyHeader(apiKey: string, expiresAt?: number) {+ persistRuntimeApiKey(apiKey, expiresAt);setHeaderForAllClients("X-API-Key", apiKey);}diff --git a/skyvern-frontend/src/components/CopyApiCommandDropdown.tsx b/skyvern-frontend/src/components/CopyApiCommandDropdown.tsxindex 6ba00c2b7..2b9799afb 100644--- a/skyvern-frontend/src/components/CopyApiCommandDropdown.tsx+++ b/skyvern-frontend/src/components/CopyApiCommandDropdown.tsx@@ -10,6 +10,7 @@ import { toast } from "@/components/ui/use-toast";import { copyText } from "@/util/copyText";import {generateApiCommands,+ describeCopiedCommand,type ApiCommandOptions,} from "@/util/apiCommands";@@ -34,8 +35,7 @@ function CopyApiCommandDropdown({ getOptions }: Props) {toast({variant: "success",title: "Copied to Clipboard",- description:- "The cURL command has been copied to your clipboard.",+ description: describeCopiedCommand("cURL"),});});}}@@ -49,8 +49,7 @@ function CopyApiCommandDropdown({ getOptions }: Props) {toast({variant: "success",title: "Copied to Clipboard",- description:- "The PowerShell command has been copied to your clipboard.",+ description: describeCopiedCommand("PowerShell"),});});}}diff --git a/skyvern-frontend/src/components/SelfHealApiKeyBanner.tsx b/skyvern-frontend/src/components/SelfHealApiKeyBanner.tsxindex d03ec2765..7f73c6279 100644--- a/skyvern-frontend/src/components/SelfHealApiKeyBanner.tsx+++ b/skyvern-frontend/src/components/SelfHealApiKeyBanner.tsx@@ -14,9 +14,9 @@ function getCopy(status: BannerStatus): { title: string; description: string } {switch (status) {case "missing_api_key":return {- title: "Frontend API key missing",+ title: "UI credential missing",description:- "The UI is not sending an x-api-key header. Authenticated requests will fail until local auth is repaired.",+ "The UI has no runtime credential. Authenticated requests will fail until the UI server can mint a session or a runtime key is stored.",};case "invalid_format":return {@@ -42,7 +42,7 @@ function getCopy(status: BannerStatus): { title: string; description: string } {return {title: "Skyvern API requests are unauthorized",description:- "The backend rejected a UI request. This usually means the frontend API key, backend API key, and local Docker database are out of sync.",+ "The backend rejected a UI request. This usually means UI session minting, the backend API key, and the local database are out of sync.",};case "error":default:@@ -86,8 +86,12 @@ function SelfHealApiKeyBanner() {{bannerStatus !== "error" ? (<><p>- {copy.description} Run <code>skyvern doctor --fix</code> in the- project directory, then restart local services if prompted.+ {copy.description} For local development, set{" "}+ <code>SKYVERN_API_KEY</code> in{" "}+ <code className="mx-1">skyvern-frontend/.env</code> and restart{" "}+ <code>npm run dev</code>. Otherwise run{" "}+ <code>skyvern doctor --fix</code> in the project directory, then+ restart local services if prompted.</p>{data?.detail ? (<p className="text-xs text-slate-300">{data.detail}</p>diff --git a/skyvern-frontend/src/main.tsx b/skyvern-frontend/src/main.tsxindex 2fb69d63a..6b07fc648 100644--- a/skyvern-frontend/src/main.tsx+++ b/skyvern-frontend/src/main.tsx@@ -1,12 +1,16 @@import React from "react";import ReactDOM from "react-dom/client";import App from "./App.tsx";+import { initializeUiSession } from "./api/AxiosClient";import "./index.css";import { installChunkLoadErrorHandler } from "./util/lazyWithReload";import { installTranslationCrashGuard } from "./util/translationCrashGuard";installTranslationCrashGuard();installChunkLoadErrorHandler();+void initializeUiSession().catch((err) =>+ console.error("[ui-session] failed to initialize:", err),+);ReactDOM.createRoot(document.getElementById("root")!).render(<React.StrictMode>diff --git a/skyvern-frontend/src/util/apiCommands.describeCopiedCommand.test.tsx b/skyvern-frontend/src/util/apiCommands.describeCopiedCommand.test.tsxnew file mode 100644index 000000000..7aa5c15ca--- /dev/null+++ b/skyvern-frontend/src/util/apiCommands.describeCopiedCommand.test.tsx@@ -0,0 +1,37 @@+// @vitest-environment jsdom++import { beforeEach, describe, expect, it, vi } from "vitest";++import { describeCopiedCommand } from "./apiCommands";++const { expiresAtMock } = vi.hoisted(() => ({ expiresAtMock: vi.fn() }));++vi.mock("@/util/env", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/util/env")>()),+ getRuntimeApiKeyExpiresAt: expiresAtMock,+}));++describe("describeCopiedCommand", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("warns that a copied command carries a short-lived session token", () => {+ // Far-future epoch seconds, so the assertion never depends on the wall clock.+ expiresAtMock.mockReturnValue(1_893_456_789);++ const description = describeCopiedCommand("cURL");++ expect(description).toMatch(/short-lived session token/i);+ expect(description).toMatch(/organization API key/i);+ expect(description).toMatch(/cURL/);+ });++ it("omits the warning when the credential is a durable key with no expiry", () => {+ expiresAtMock.mockReturnValue(null);++ expect(describeCopiedCommand("PowerShell")).toBe(+ "The PowerShell command has been copied to your clipboard.",+ );+ });+});diff --git a/skyvern-frontend/src/util/apiCommands.ts b/skyvern-frontend/src/util/apiCommands.tsindex f7e40da1f..2af18903c 100644--- a/skyvern-frontend/src/util/apiCommands.ts+++ b/skyvern-frontend/src/util/apiCommands.ts@@ -1,5 +1,7 @@import { fetchToCurl } from "fetch-to-curl";+import { getRuntimeApiKeyExpiresAt } from "@/util/env";+export interface ApiCommandOptions {method: string;url: string;@@ -60,4 +62,19 @@ function generateApiCommands(options: ApiCommandOptions): {return { curl, powershell };}-export { generateApiCommands };+// The browser holds a scoped session token rather than the organization key, so a copied command+// stops working when that token expires. Say so at copy time — the expiry is otherwise invisible.+function describeCopiedCommand(kind: string): string {+ const expiresAt = getRuntimeApiKeyExpiresAt();+ if (expiresAt === null) {+ return `The ${kind} command has been copied to your clipboard.`;+ }+ const expiry = new Date(expiresAt * 1000).toLocaleTimeString();+ return (+ `The ${kind} command has been copied to your clipboard. It embeds a short-lived session ` ++ `token that expires at ${expiry} — for scheduled or long-lived use, substitute an ` ++ `organization API key from your server configuration.`+ );+}++export { generateApiCommands, describeCopiedCommand };diff --git a/skyvern-frontend/src/util/env.test.ts b/skyvern-frontend/src/util/env.test.tsindex 0d3d9dc44..7484ab230 100644--- a/skyvern-frontend/src/util/env.test.ts+++ b/skyvern-frontend/src/util/env.test.ts@@ -1,6 +1,3 @@-import { readFile } from "node:fs/promises";-import path from "node:path";-import { afterEach, describe, expect, it, vi } from "vitest";async function loadEnv(apiKey: string | null = null, streamingMode = "") {@@ -22,10 +19,13 @@ describe("getCredentialParam", () => {afterEach(() => {vi.unstubAllEnvs();vi.resetModules();+ window.sessionStorage.clear();});it("includes the runtime API key even when a token getter returns a token", async () => {- const { getCredentialParam } = await loadEnv("local+api/key");+ const { getCredentialParam, persistRuntimeApiKey } =+ await loadEnv("ignored-build-key");+ persistRuntimeApiKey("local+api/key");const params = new URLSearchParams(await getCredentialParam(async () => "clerk token"),@@ -48,49 +48,70 @@ describe("getCredentialParam", () => {});describe("getRuntimeApiKey", () => {- // Built via join so this test file never contains the sentinel verbatim- // either — entrypoint-skyvernui.sh sed-replaces every occurrence in built- // assets, and the source guard below must stay meaningful.- const dockerSentinel = ["__SKYVERN_API_KEY", "_PLACEHOLDER__"].join("");-afterEach(() => {vi.unstubAllEnvs();vi.resetModules();window.sessionStorage.clear();});- it("returns the build-time API key", async () => {- const { getRuntimeApiKey } = await loadEnv("eyJhbGciOiJIUzI1NiJ9.real.key");+ it("ignores the build-time API key", async () => {+ const { getRuntimeApiKey } = await loadEnv("ignored-build-key-canary");- expect(getRuntimeApiKey()).toBe("eyJhbGciOiJIUzI1NiJ9.real.key");+ expect(getRuntimeApiKey()).toBe(null);+ expect(window.sessionStorage.getItem("skyvern.apiKey")).toBe(null);});- it("treats the .env.example placeholder as missing", async () => {- const { getRuntimeApiKey } = await loadEnv("YOUR_API_KEY");+ it("does not expose the server-side API key to the browser", async () => {+ vi.stubEnv("SKYVERN_API_KEY", "server-only-key-canary");+ const { getRuntimeApiKey } = await loadEnv();expect(getRuntimeApiKey()).toBe(null);+ expect(window.sessionStorage.getItem("skyvern.apiKey")).toBe(null);});- it("treats an un-replaced docker placeholder as missing", async () => {- const { getRuntimeApiKey } = await loadEnv(dockerSentinel);+ it("does not expose the build-time API key through credential params", async () => {+ const { getCredentialParam } = await loadEnv(+ "build-time-key-must-stay-server-side",+ );- expect(getRuntimeApiKey()).toBe(null);+ const params = new URLSearchParams(await getCredentialParam(null));++ expect(params.has("apikey")).toBe(false);});- // Regression guard for the v1.0.34–v1.0.40 docker auth outage:- // entrypoint-skyvernui.sh sed-replaces EVERY occurrence of the docker- // sentinel in the built bundle with the real API key. When the full- // sentinel appeared verbatim in this module (inside the placeholder- // deny-list), the real key replaced it there too, so the key became a- // member of its own deny-list and the UI sent no x-api-key header at all- // (403 "Invalid credentials" on every request).- it("never spells out the full docker placeholder sentinel in module source", async () => {- const source = await readFile(- path.join(process.cwd(), "src/util/env.ts"),- "utf-8",+ it("persists and clears a runtime API key and expiry in sessionStorage", async () => {+ const {+ clearRuntimeApiKey,+ getRuntimeApiKey,+ getRuntimeApiKeyExpiresAt,+ persistRuntimeApiKey,+ } = await loadEnv();++ persistRuntimeApiKey("runtime-key-canary", 1_893_456_789);+ expect(getRuntimeApiKey()).toBe("runtime-key-canary");+ expect(getRuntimeApiKeyExpiresAt()).toBe(1_893_456_789);+ expect(window.sessionStorage.getItem("skyvern.apiKey")).toBe(+ "runtime-key-canary",+ );+ expect(window.sessionStorage.getItem("skyvern.apiKeyExpiresAt")).toBe(+ "1893456789",);- expect(source.includes(dockerSentinel)).toBe(false);+ clearRuntimeApiKey();+ expect(getRuntimeApiKey()).toBe(null);+ expect(getRuntimeApiKeyExpiresAt()).toBe(null);+ expect(window.sessionStorage.getItem("skyvern.apiKey")).toBe(null);+ expect(window.sessionStorage.getItem("skyvern.apiKeyExpiresAt")).toBe(null);+ });++ it("clears a persisted expiry when replacing a session token without one", async () => {+ const { getRuntimeApiKeyExpiresAt, persistRuntimeApiKey } = await loadEnv();++ persistRuntimeApiKey("ui-session-canary", 1_893_456_789);+ persistRuntimeApiKey("api-key-canary");++ expect(getRuntimeApiKeyExpiresAt()).toBe(null);+ expect(window.sessionStorage.getItem("skyvern.apiKeyExpiresAt")).toBe(null);});});diff --git a/skyvern-frontend/src/util/env.ts b/skyvern-frontend/src/util/env.tsindex a76d2c5a6..7a5fe4de5 100644--- a/skyvern-frontend/src/util/env.ts+++ b/skyvern-frontend/src/util/env.ts@@ -14,11 +14,6 @@ const browserStreamingMode = ((import.meta.env.VITE_BROWSER_STREAMING_MODE as string | undefined) || "vnc").toLowerCase();-const buildTimeApiKey: string | null =- typeof import.meta.env.VITE_SKYVERN_API_KEY === "string"- ? import.meta.env.VITE_SKYVERN_API_KEY- : null;-const artifactApiBaseUrl = import.meta.env.VITE_ARTIFACT_API_BASE_URL;if (!artifactApiBaseUrl) {@@ -28,10 +23,12 @@ if (!artifactApiBaseUrl) {const apiPathPrefix = import.meta.env.VITE_API_PATH_PREFIX ?? "";const API_KEY_STORAGE_KEY = "skyvern.apiKey";+const API_KEY_EXPIRES_AT_STORAGE_KEY = "skyvern.apiKeyExpiresAt";const lsKeys = {browserSessionId: "skyvern.browserSessionId",apiKey: API_KEY_STORAGE_KEY,+ apiKeyExpiresAt: API_KEY_EXPIRES_AT_STORAGE_KEY,};const wssBaseUrl = import.meta.env.VITE_WSS_BASE_URL;@@ -75,25 +72,33 @@ function getRuntimeApiKey(): string | null {return runtimeApiKey;}- const persisted = readPersistedApiKey();- const candidate = persisted ?? buildTimeApiKey;-- // Treat placeholder / example values as missing so they are never sent- // as real credentials (e.g. from .env.example or an un-replaced Docker placeholder).- // The Docker sentinel is matched by its suffix on purpose: the prebuilt-image- // entrypoint sed-replaces every occurrence of the full sentinel in the bundle- // with the real API key, so spelling it out here would put the real key in its- // own deny-list and strip the x-api-key header from every request.- const isPlaceholder =- candidate === "YOUR_API_KEY" || candidate?.endsWith("_PLACEHOLDER__");- runtimeApiKey = candidate && isPlaceholder ? null : candidate;+ runtimeApiKey = readPersistedApiKey();return runtimeApiKey;}-function persistRuntimeApiKey(value: string): void {+function getRuntimeApiKeyExpiresAt(): number | null {+ if (typeof window === "undefined") {+ return null;+ }++ const expiresAt = Number(+ window.sessionStorage.getItem(API_KEY_EXPIRES_AT_STORAGE_KEY),+ );+ return Number.isFinite(expiresAt) && expiresAt > 0 ? expiresAt : null;+}++function persistRuntimeApiKey(value: string, expiresAt?: number): void {runtimeApiKey = value;if (typeof window !== "undefined") {window.sessionStorage.setItem(API_KEY_STORAGE_KEY, value);+ if (expiresAt !== undefined && Number.isFinite(expiresAt)) {+ window.sessionStorage.setItem(+ API_KEY_EXPIRES_AT_STORAGE_KEY,+ String(expiresAt),+ );+ } else {+ window.sessionStorage.removeItem(API_KEY_EXPIRES_AT_STORAGE_KEY);+ }}}@@ -101,6 +106,7 @@ function clearRuntimeApiKey(): void {runtimeApiKey = null;if (typeof window !== "undefined") {window.sessionStorage.removeItem(API_KEY_STORAGE_KEY);+ window.sessionStorage.removeItem(API_KEY_EXPIRES_AT_STORAGE_KEY);}}@@ -140,6 +146,7 @@ export {newWssBaseUrl,getCredentialParam,getRuntimeApiKey,+ getRuntimeApiKeyExpiresAt,persistRuntimeApiKey,clearRuntimeApiKey,useNewRunsUrl,diff --git a/skyvern-frontend/vite.config.ts b/skyvern-frontend/vite.config.tsindex e03b29418..c7c8196b4 100644--- a/skyvern-frontend/vite.config.ts+++ b/skyvern-frontend/vite.config.ts@@ -1,32 +1,149 @@-import { execSync } from "child_process";+import { readFileSync } from "node:fs";import path from "path";-import { defineConfig } from "vite";+import { defineConfig, loadEnv } from "vite";+import type { Connect, Plugin } from "vite";import react from "@vitejs/plugin-react-swc";+import {+ createUiSessionHandler,+ createUiSessionNonceManager,+ issueUiSessionNonceCookie,+} from "./localServer.js";+import { resolveAppVersion } from "./scripts/app-version.mjs";+// https://vitejs.dev/config/-export default defineConfig({- plugins: [react()],- server: {- port: 8080,- },- preview: {- port: 8080,- },- resolve: {- alias: {- "@": path.resolve(__dirname, "./src"),+const devPort = process.env.VITE_DEV_PORT+ ? parseInt(process.env.VITE_DEV_PORT, 10)+ : 8080;++const UI_SESSION_DEFAULT_API_BASE_URL = "http://localhost:8000/api/v1";+const UI_SESSION_REQUEST_TIMEOUT_MS = 10_000;++type UiSessionEnvironment = Record<string, string | undefined>;++type UiSessionDevPluginOptions = {+ env: UiSessionEnvironment;+ fetchImpl?: typeof fetch;+ logger?: Pick<Console, "error">;+ requestTimeoutMs?: number;+};++function resolveOrganizationApiKey(env: UiSessionEnvironment): string | null {+ const key = env.SKYVERN_API_KEY?.trim() || env.VITE_SKYVERN_API_KEY?.trim();+ return key || null;+}++function resolveServerApiBaseUrl(env: UiSessionEnvironment): string {+ return (+ env.SKYVERN_API_BASE_URL?.trim() ||+ env.VITE_API_BASE_URL?.trim() ||+ UI_SESSION_DEFAULT_API_BASE_URL+ );+}++export function createUiSessionDevPlugin({+ env,+ fetchImpl = fetch,+ logger = console,+ requestTimeoutMs = UI_SESSION_REQUEST_TIMEOUT_MS,+}: UiSessionDevPluginOptions): Plugin {+ const apiBaseUrl = resolveServerApiBaseUrl(env);+ const organizationApiKey = resolveOrganizationApiKey(env);+ const nonceManager = createUiSessionNonceManager();+ const serveUiSession = createUiSessionHandler({+ apiBaseUrl,+ organizationApiKey,+ fetchImpl,+ logger,+ requestTimeoutMs,+ nonceManager,+ });++ const middleware: Connect.NextHandleFunction = async (request, response) => {+ await serveUiSession(request, response);+ };++ return {+ name: "ui-session-dev",+ apply: "serve",+ configureServer(server) {+ server.middlewares.use((request, response, next) => {+ issueUiSessionNonceCookie(request, response, nonceManager);+ next();+ });+ server.middlewares.use("/ui-session", middleware);+ },+ };+}++function hasSourceMapPruningStep() {+ const packageJson = JSON.parse(+ readFileSync(new URL("./package.json", import.meta.url), "utf8"),+ );+ return packageJson.scripts?.build?.includes("npm run datadog:sourcemaps");+}++async function createSentryPlugin() {+ try {+ const { sentryVitePlugin } = await import("@sentry/vite-plugin");+ return sentryVitePlugin({+ org: "skyvern",+ project: "javascript-react",+ });+ } catch (error) {+ const missingDependency =+ error instanceof Error &&+ "code" in error &&+ ["ERR_MODULE_NOT_FOUND", "MODULE_NOT_FOUND"].includes(error.code) &&+ error.message.includes("@sentry/vite-plugin");+ if (!missingDependency) {+ throw error;+ }+ return { name: "optional-sentry-noop" };+ }+}++export default defineConfig(async ({ mode }) => {+ const env = {+ ...loadEnv(mode, process.cwd(), ""),+ ...process.env,+ };++ return {+ plugins: [+ react(),+ createUiSessionDevPlugin({ env }),+ await createSentryPlugin(),+ ],++ server: {+ port: devPort,+ allowedHosts: process.env.VITE_ALLOWED_HOSTS+ ? process.env.VITE_ALLOWED_HOSTS.split(",")+ : [],+ },++ preview: {+ port: devPort,+ },++ resolve: {+ alias: {+ "@": path.resolve(__dirname, "./src"),+ "@cloud": path.resolve(__dirname, "./cloud"),+ "@eval": path.resolve(__dirname, "./eval"),+ },+ },++ define: {+ __APP_VERSION__: JSON.stringify(resolveAppVersion()),+ },++ build: {+ // "hidden" emits maps for the Datadog upload but omits the+ // sourceMappingURL comment; the upload script then prunes them from dist so+ // they are never served. See scripts/upload-datadog-sourcemaps.mjs.+ sourcemap: hasSourceMapPruningStep() ? "hidden" : false,},- },- define: {- __APP_VERSION__: JSON.stringify(- process.env.APP_VERSION ||- (() => {- try {- return execSync("git rev-parse HEAD").toString().trim();- } catch {- return "development";- }- })(),- ),- },+ };});diff --git a/skyvern/config.py b/skyvern/config.pyindex 4ac03f844..4ad34de80 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -270,6 +270,7 @@ class Settings(BaseSettings):# Algorithm used to sign the JWTSIGNATURE_ALGORITHM: str = "HS256"ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 7 # one week+ UI_SESSION_TOKEN_TTL_MINUTES: int = Field(default=60, gt=0)# Artifact storage settingsARTIFACT_STORAGE_PATH: str = f"{SKYVERN_DIR}/artifacts"diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex 65e80b586..efa3868a0 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -868,6 +868,9 @@ 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 credential_routes_accept_ui_session(self) -> bool:+ return True+def supports_sequential_credentials(self) -> bool:"""Whether this deployment can execute credentials marked run_sequentially."""return Falsediff --git a/skyvern/forge/sdk/core/security.py b/skyvern/forge/sdk/core/security.pyindex b0cd5bb91..80e5fe454 100644--- a/skyvern/forge/sdk/core/security.py+++ b/skyvern/forge/sdk/core/security.py@@ -29,14 +29,17 @@ def _normalize_json_dumps(payload: dict) -> str:def create_access_token(subject: Union[str, Any],expires_delta: timedelta | None = None,+ token_type: str | None = None,) -> str:- if expires_delta:+ if expires_delta is not None:expire = datetime.utcnow() + expires_deltaelse:expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES,)to_encode = {"exp": expire, "sub": str(subject)}+ if token_type is not None:+ to_encode["token_type"] = token_typeencoded_jwt = jwt.encode(to_encode,settings.SECRET_KEY,diff --git a/skyvern/forge/sdk/db/enums.py b/skyvern/forge/sdk/db/enums.pyindex 375c0b0d2..5badaa2ef 100644--- a/skyvern/forge/sdk/db/enums.py+++ b/skyvern/forge/sdk/db/enums.py@@ -3,6 +3,7 @@ from enum import StrEnumclass OrganizationAuthTokenType(StrEnum):api = "api"+ ui_session = "ui_session"onepassword_service_account = "onepassword_service_account"azure_client_secret_credential = "azure_client_secret_credential"custom_credential_service = "custom_credential_service"diff --git a/skyvern/forge/sdk/db/repositories/organizations.py b/skyvern/forge/sdk/db/repositories/organizations.pyindex 9cc25de6c..b476ae21b 100644--- a/skyvern/forge/sdk/db/repositories/organizations.py+++ b/skyvern/forge/sdk/db/repositories/organizations.py@@ -1,9 +1,10 @@from __future__ import annotations+from collections.abc import Sequencefrom datetime import datetime, timedelta, timezonefrom typing import Literal, overload-from sqlalchemy import select, update+from sqlalchemy import delete, select, updatefrom skyvern.forge.sdk.db._error_handling import db_operationfrom skyvern.forge.sdk.db.base_alchemy_db import read_retry@@ -324,6 +325,24 @@ class OrganizationsRepository(BaseRepository):).all()return [await convert_to_organization_auth_token(token, token_type) for token in tokens]+ @db_operation("delete_org_auth_tokens")+ async def delete_org_auth_tokens(+ self,+ organization_id: str,+ token_type: OrganizationAuthTokenType,+ token_ids: Sequence[str],+ ) -> None:+ if not token_ids:+ return+ async with self.Session() as session:+ await session.execute(+ delete(OrganizationAuthTokenModel)+ .filter_by(organization_id=organization_id)+ .filter_by(token_type=token_type)+ .where(OrganizationAuthTokenModel.id.in_(token_ids))+ )+ await session.commit()+@db_operation("get_valid_org_auth_tokens_by_type")async def get_valid_org_auth_tokens_by_type(self,diff --git a/skyvern/forge/sdk/routes/__init__.py b/skyvern/forge/sdk/routes/__init__.pyindex a5087d704..fa2c88b51 100644--- a/skyvern/forge/sdk/routes/__init__.py+++ b/skyvern/forge/sdk/routes/__init__.py@@ -16,6 +16,7 @@ from skyvern.forge.sdk.routes import scripts # noqa: F401from skyvern.forge.sdk.routes import sdk # noqa: F401from skyvern.forge.sdk.routes import self_heal # noqa: F401from skyvern.forge.sdk.routes import streaming # noqa: F401+from skyvern.forge.sdk.routes import ui_session # noqa: F401from skyvern.forge.sdk.routes import webhooks # noqa: F401from skyvern.forge.sdk.routes import workflow_schedules # noqa: F401from skyvern.forge.sdk.routes.streaming import cdp_input # noqa: F401diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.pyindex 746852eca..c19448def 100644--- a/skyvern/forge/sdk/routes/agent_protocol.py+++ b/skyvern/forge/sdk/routes/agent_protocol.py@@ -5379,7 +5379,7 @@ async def get_current_organization()async def get_api_keys(organization_id: str,- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_with_api_token),) -> GetOrganizationAPIKeysResponse:if organization_id != current_org.organization_id:raise HTTPException(status_code=403, detail="You do not have permission to access this organization")diff --git a/skyvern/forge/sdk/routes/credentials.py b/skyvern/forge/sdk/routes/credentials.pyindex ef73b0c29..6b6426084 100644--- a/skyvern/forge/sdk/routes/credentials.py+++ b/skyvern/forge/sdk/routes/credentials.py@@ -446,7 +446,7 @@ async def fetch_credential_item_background(item_id: str) -> None:)async def send_totp_code(data: TOTPCodeCreate,- curr_org: Organization = Depends(org_auth_service.get_current_org),+ curr_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> TOTPCode:totp_identifier = normalize_identifier_if_email(data.totp_identifier)redacted_totp_identifier = redact_otp_identifier_for_log(data.totp_identifier)@@ -568,7 +568,7 @@ async def send_totp_code(include_in_schema=False,)async def get_totp_codes(- curr_org: Organization = Depends(org_auth_service.get_current_org),+ curr_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),totp_identifier: str | None = Query(None,description="Filter by TOTP identifier such as an email or phone number.",@@ -692,7 +692,7 @@ async def create_credential(],openapi_extra={"x-fern-sdk-parameter-name": "data"},),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CredentialResponse:if isinstance(data.credential, NonEmptyPasswordCredential):await _normalize_authenticator_totp_for_organization_or_raise(@@ -858,7 +858,7 @@ async def rename_credential(...,description="The credential fields to update",),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CredentialResponse:credential = await app.DATABASE.credentials.get_credential(credential_id=credential_id, organization_id=current_org.organization_id@@ -943,7 +943,7 @@ async def test_login(...,description="The login credentials and URL to test",),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),x_user_agent: Annotated[str | None, Header()] = None,) -> TestLoginResponse:"""Test a login with inline credentials without requiring a saved credential."""@@ -1155,7 +1155,7 @@ async def test_credential(...,description="Test configuration including the login URL",),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),x_user_agent: Annotated[str | None, Header()] = None,) -> TestCredentialResponse:organization_id = current_org.organization_id@@ -1386,7 +1386,7 @@ async def get_test_credential_status(description="The workflow run ID from the test initiation",examples=["wr_1234567890"],),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> TestCredentialStatusResponse:organization_id = current_org.organization_id@@ -1497,7 +1497,7 @@ async def cancel_credential_test(description="The workflow run ID to cancel",examples=["wr_1234567890"],),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CancelTestResponse:organization_id = current_org.organization_id@@ -1898,7 +1898,7 @@ async def update_credential(],openapi_extra={"x-fern-sdk-parameter-name": "data"},),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CredentialResponse:existing_credential = await app.DATABASE.credentials.get_credential(credential_id=credential_id, organization_id=current_org.organization_id@@ -2057,7 +2057,7 @@ async def delete_credential(examples=["cred_1234567890"],openapi_extra={"x-fern-sdk-parameter-name": "credential_id"},),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> None:credential = await app.DATABASE.credentials.get_credential(credential_id=credential_id, organization_id=current_org.organization_id@@ -2205,7 +2205,7 @@ async def get_credential_totp_code(description="The unique identifier of the credential",examples=["cred_1234567890"],),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CredentialTotpCodeResponse:response.headers["Cache-Control"] = "no-store"response.headers["Pragma"] = "no-cache"@@ -2310,7 +2310,7 @@ async def get_credential(examples=["cred_1234567890"],openapi_extra={"x-fern-sdk-parameter-name": "credential_id"},),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CredentialResponse:"""Return non-sensitive metadata for a single credential.@@ -2354,7 +2354,7 @@ async def get_credential(include_in_schema=False,)async def get_credentials(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),page: int = Query(1,ge=1,@@ -2434,7 +2434,7 @@ def _to_credential_folder_response(folder: CredentialFolderModel, credential_cou@base_router.post("/credential_folders/", response_model=CredentialFolder, include_in_schema=False)async def create_credential_folder(data: CredentialFolderCreate = Body(..., description="The credential folder to create"),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CredentialFolder:folder = await app.DATABASE.credential_folders.create_credential_folder(organization_id=current_org.organization_id,@@ -2460,7 +2460,7 @@ async def create_credential_folder(@base_router.get("/credential_folders/{folder_id}/", response_model=CredentialFolder, include_in_schema=False)async def get_credential_folder(folder_id: str = Path(..., description="Credential folder ID", examples=["cfld_123"]),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CredentialFolder:folder = await app.DATABASE.credential_folders.get_credential_folder(folder_id=folder_id,@@ -2493,7 +2493,7 @@ async def get_credential_folders(page: int = Query(1, ge=1, description="Page number"),page_size: int = Query(100, ge=1, le=500, description="Number of folders per page"),search: str | None = Query(None, description="Search folders by title or description"),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> list[CredentialFolder]:folders = await app.DATABASE.credential_folders.get_credential_folders(organization_id=current_org.organization_id,@@ -2531,7 +2531,7 @@ async def get_credential_folders(async def update_credential_folder(folder_id: str = Path(..., description="Credential folder ID", examples=["cfld_123"]),data: CredentialFolderUpdate = Body(...),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CredentialFolder:folder = await app.DATABASE.credential_folders.update_credential_folder(folder_id=folder_id,@@ -2564,7 +2564,7 @@ async def update_credential_folder(@base_router.delete("/credential_folders/{folder_id}/", include_in_schema=False)async def delete_credential_folder(folder_id: str = Path(..., description="Credential folder ID", examples=["cfld_123"]),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> dict:success = await app.DATABASE.credential_folders.soft_delete_credential_folder(folder_id=folder_id,@@ -2594,7 +2594,7 @@ async def delete_credential_folder(async def update_credential_folder_assignment(credential_id: str = Path(..., description="The ID of the credential.", examples=["cred_1234567890"]),data: UpdateCredentialFolderRequest = Body(...),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CredentialResponse:try:credential = await app.DATABASE.credential_folders.set_credential_folder(@@ -2624,7 +2624,7 @@ async def update_credential_folder_assignment(include_in_schema=False,)async def get_onepassword_token(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CreateOnePasswordTokenResponse:"""Get the current OnePassword service account token for the organization.@@ -2670,7 +2670,7 @@ async def get_onepassword_token(include_in_schema=False,)async def list_onepassword_items(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> OnePasswordItemsResponse:org_auth_token = await app.DATABASE.organizations.get_valid_org_auth_token(current_org.organization_id,@@ -2805,7 +2805,7 @@ async def list_onepassword_items(include_in_schema=False,)async def list_bitwarden_items(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> BitwardenItemsResponse:org_auth_token = await app.DATABASE.organizations.get_valid_org_auth_token(current_org.organization_id,@@ -2850,7 +2850,7 @@ async def list_bitwarden_items()async def update_onepassword_token(data: CreateOnePasswordTokenRequest,- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CreateOnePasswordTokenResponse:"""Create or update a OnePassword service account token for the current organization.@@ -2907,7 +2907,7 @@ async def update_onepassword_token()async def clear_org_auth_credential(credential_provider: str = Path(..., description="The organization auth credential provider to clear."),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> ClearOrganizationAuthTokenResponse:"""Clear the current organization auth credential for the organization.@@ -2961,7 +2961,7 @@ def _to_safe_bitwarden_response(auth_token: BitwardenOrganizationAuthToken) -> Binclude_in_schema=False,)async def get_bitwarden_credential(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> BitwardenCredentialResponse:"""Get the current Bitwarden credential for the organization.@@ -3008,7 +3008,7 @@ async def get_bitwarden_credential()async def update_bitwarden_credential(request: CreateBitwardenCredentialRequest,- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> BitwardenCredentialResponse:"""Create or update a Bitwarden credential for the current organization.@@ -3060,7 +3060,7 @@ async def update_bitwarden_credential(include_in_schema=False,)async def get_azure_client_secret_credential(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> AzureClientSecretCredentialResponse:"""Get the current Azure Client Secret Credential for the organization.@@ -3107,7 +3107,7 @@ async def get_azure_client_secret_credential()async def update_azure_client_secret_credential(request: CreateAzureClientSecretCredentialRequest,- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> AzureClientSecretCredentialResponse:"""Create or update an Azure Client Secret Credential for the current organization.@@ -3163,7 +3163,7 @@ async def update_azure_client_secret_credential(include_in_schema=False,)async def get_custom_credential_service_config(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CustomCredentialServiceConfigResponse:"""Get the current custom credential service configuration for the organization.@@ -3210,7 +3210,7 @@ async def get_custom_credential_service_config()async def update_custom_credential_service_config(request: CreateCustomCredentialServiceConfigRequest,- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CustomCredentialServiceConfigResponse:"""Create or update a custom credential service configuration for the current organization.@@ -3268,7 +3268,7 @@ async def update_custom_credential_service_config()async def test_custom_credential_service_connection(request: CreateCustomCredentialServiceConfigRequest,- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> TestConnectionResponse:"""Test connectivity to the custom credential service API.diff --git a/skyvern/forge/sdk/routes/custom_llms.py b/skyvern/forge/sdk/routes/custom_llms.pyindex 8d5788dcf..102ce0f56 100644--- a/skyvern/forge/sdk/routes/custom_llms.py+++ b/skyvern/forge/sdk/routes/custom_llms.py@@ -71,7 +71,7 @@ async def _get_custom_llm(include_in_schema=False,)async def list_custom_llms(- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CustomLLMListResponse:tokens = await app.DATABASE.organizations.get_valid_org_auth_tokens(organization_id=current_org.organization_id,@@ -108,7 +108,7 @@ async def list_custom_llms()async def create_custom_llm(request: CustomLLMCreateRequest,- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CustomLLMResponse:await _validate_custom_llm_api_base(request.config)token = await app.DATABASE.organizations.create_org_auth_token(@@ -137,7 +137,7 @@ async def create_custom_llm(async def update_custom_llm(request: CustomLLMUpdateRequest,custom_llm_id: str = Path(..., description="The custom LLM id."),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> CustomLLMResponse:try:existing_custom_llm = await _get_custom_llm(current_org.organization_id, custom_llm_id)@@ -172,7 +172,7 @@ async def update_custom_llm()async def delete_custom_llm(custom_llm_id: str = Path(..., description="The custom LLM id."),- current_org: Organization = Depends(org_auth_service.get_current_org),+ current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),) -> ClearOrganizationAuthTokenResponse:try:await app.DATABASE.organizations.invalidate_org_auth_token(diff --git a/skyvern/forge/sdk/routes/google_oauth.py b/skyvern/forge/sdk/routes/google_oauth.pyindex 4d663c61f..bb76020ca 100644--- a/skyvern/forge/sdk/routes/google_oauth.py+++ b/skyvern/forge/sdk/routes/google_oauth.py@@ -128,7 +128,7 @@ def _require_scopes_from_token(token_data: dict) -> list[str]:@google_oauth_router.post("/oauth/authorize")async def google_oauth_authorize(request: CreateGoogleOAuthAuthorizeRequest,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org_for_credential_routes)],current_user_id: Annotated[str | None, Depends(org_auth_service.get_current_user_id_or_none)],) -> GoogleOAuthAuthorizeResponse:"""Kick off the Google OAuth 2.0 authorization flow."""@@ -163,7 +163,7 @@ async def google_oauth_authorize(@google_oauth_router.post("/oauth/callback")async def google_oauth_callback(request: CreateGoogleOAuthCallbackRequest,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org_for_credential_routes)],current_user_id: Annotated[str | None, Depends(org_auth_service.get_current_user_id_or_none)],) -> GoogleOAuthCredentialResponse:"""Handle the Google OAuth 2.0 authorization callback."""@@ -277,7 +277,7 @@ async def google_oauth_callback(@google_oauth_router.get("/oauth/config")async def get_google_oauth_client_config(- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org_for_credential_routes)],) -> GoogleOAuthClientConfigResponse:"""Return the effective Google OAuth client configuration without the client secret."""_require_organization_client_config_enabled()@@ -291,7 +291,7 @@ async def get_google_oauth_client_config(@google_oauth_router.put("/oauth/config")async def update_google_oauth_client_config(request: UpdateGoogleOAuthClientConfigRequest,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org_for_credential_routes)],) -> GoogleOAuthClientConfigResponse:"""Store an organization-level Google OAuth client configuration."""_require_organization_client_config_enabled()@@ -328,7 +328,7 @@ async def update_google_oauth_client_config(@google_oauth_router.delete("/oauth/config")async def delete_google_oauth_client_config(- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org_for_credential_routes)],) -> dict[str, bool]:"""Clear the organization-level Google OAuth client config and fall back to environment config."""_require_organization_client_config_enabled()@@ -341,7 +341,7 @@ async def delete_google_oauth_client_config(@google_oauth_router.get("/oauth/credentials")async def list_google_oauth_credentials(- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org_for_credential_routes)],include_email: bool = False,) -> GoogleOAuthCredentialListResponse:"""Fetch a list of Google OAuth credentials associated with an organization."""@@ -366,7 +366,7 @@ async def list_google_oauth_credentials(async def rename_google_oauth_credential(credential_id: str,request: UpdateGoogleOAuthCredentialRequest,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org_for_credential_routes)],) -> GoogleOAuthCredentialResponse:"""Renames an existing Google OAuth credential for the specified organization"""updated = await google_oauth_service.rename_credential(@@ -384,7 +384,7 @@ async def rename_google_oauth_credential()async def delete_google_oauth_credential(credential_id: str,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org_for_credential_routes)],) -> dict[str, bool]:"""Deletes a specific Google OAuth credential associated with an organization"""revoked = await google_oauth_service.revoke_credential(diff --git a/skyvern/forge/sdk/routes/internal_auth.py b/skyvern/forge/sdk/routes/internal_auth.pyindex ababecdf5..0239a8c31 100644--- a/skyvern/forge/sdk/routes/internal_auth.py+++ b/skyvern/forge/sdk/routes/internal_auth.py@@ -8,7 +8,7 @@ from fastapi import APIRouter, HTTPException, Request, statusfrom skyvern.config import settingsfrom skyvern.forge import appfrom skyvern.forge.sdk.services.local_org_auth_token_service import fingerprint_token-from skyvern.forge.sdk.services.org_auth_service import resolve_org_from_api_key+from skyvern.forge.sdk.services.org_auth_service import credential_route_token_types, resolve_org_from_api_keyrouter = APIRouter(prefix="/internal/auth", tags=["internal"])LOG = structlog.get_logger()@@ -73,7 +73,11 @@ async def _evaluate_local_api_key(token: str) -> DiagnosticsResult:)try:- validation = await resolve_org_from_api_key(token_candidate, app.DATABASE)+ validation = await resolve_org_from_api_key(+ token_candidate,+ app.DATABASE,+ token_types=credential_route_token_types(),+ )except HTTPException as exc:if exc.status_code == status.HTTP_404_NOT_FOUND:return DiagnosticsResult(status=AuthStatus.not_found, detail=None, token=None, validation=None)diff --git a/skyvern/forge/sdk/routes/microsoft_oauth.py b/skyvern/forge/sdk/routes/microsoft_oauth.pyindex accd05311..25179f5ec 100644--- a/skyvern/forge/sdk/routes/microsoft_oauth.py+++ b/skyvern/forge/sdk/routes/microsoft_oauth.py@@ -108,7 +108,7 @@ def _require_scopes_from_token(token_data: dict) -> list[str]:@microsoft_oauth_router.post("/oauth/authorize")async def microsoft_oauth_authorize(request: CreateMicrosoftOAuthAuthorizeRequest,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org_for_credential_routes)],current_user_id: Annotated[str | None, Depends(org_auth_service.get_current_user_id_or_none)],) -> MicrosoftOAuthAuthorizeResponse:try:@@ -137,7 +137,7 @@ async def microsoft_oauth_authorize(@microsoft_oauth_router.post("/oauth/callback")async def microsoft_oauth_callback(request: CreateMicrosoftOAuthCallbackRequest,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org_for_credential_routes)],current_user_id: Annotated[str | None, Depends(org_auth_service.get_current_user_id_or_none)],) -> MicrosoftOAuthCredentialResponse:context = await microsoft_oauth_service.load_pending_consent_context(@@ -251,7 +251,7 @@ async def microsoft_oauth_callback(@microsoft_oauth_router.get("/oauth/credentials")async def list_microsoft_oauth_credentials(- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org_for_credential_routes)],include_email: bool = False,) -> MicrosoftOAuthCredentialListResponse:credentials = await microsoft_oauth_service.get_credentials_for_org(@@ -275,7 +275,7 @@ async def list_microsoft_oauth_credentials(async def rename_microsoft_oauth_credential(credential_id: str,request: UpdateMicrosoftOAuthCredentialRequest,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org_for_credential_routes)],) -> MicrosoftOAuthCredentialResponse:updated = await microsoft_oauth_service.rename_credential(organization_id=current_org.organization_id,@@ -293,7 +293,7 @@ async def rename_microsoft_oauth_credential()async def delete_microsoft_oauth_credential(credential_id: str,- current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org_for_credential_routes)],) -> None:revoked = await microsoft_oauth_service.revoke_credential(organization_id=current_org.organization_id,diff --git a/skyvern/forge/sdk/routes/ui_session.py b/skyvern/forge/sdk/routes/ui_session.pynew file mode 100644index 000000000..60a1b3d64--- /dev/null+++ b/skyvern/forge/sdk/routes/ui_session.py@@ -0,0 +1,39 @@+from typing import Annotated++from fastapi import Header, Response+from pydantic import BaseModel++from skyvern.forge import app+from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType+from skyvern.forge.sdk.routes.routers import base_router, legacy_base_router+from skyvern.forge.sdk.services.org_auth_service import resolve_org_from_api_key+from skyvern.forge.sdk.services.org_auth_token_service import create_org_ui_session_token+++class UISessionTokenResponse(BaseModel):+ token: str+ expires_at: int+++@legacy_base_router.post(+ "/ui-session",+ response_model=UISessionTokenResponse,+ include_in_schema=False,+)+@base_router.post(+ "/ui-session",+ response_model=UISessionTokenResponse,+ include_in_schema=False,+)+async def create_ui_session_token(+ response: Response,+ x_api_key: Annotated[str, Header()],+) -> UISessionTokenResponse:+ validation = await resolve_org_from_api_key(+ x_api_key,+ app.DATABASE,+ token_types=(OrganizationAuthTokenType.api,),+ )+ auth_token, expires_at = await create_org_ui_session_token(validation.organization.organization_id)+ response.headers["Cache-Control"] = "no-store"+ return UISessionTokenResponse(token=auth_token.token, expires_at=expires_at)diff --git a/skyvern/forge/sdk/services/org_auth_service.py b/skyvern/forge/sdk/services/org_auth_service.pyindex 97d2d3235..6e7b3266a 100644--- a/skyvern/forge/sdk/services/org_auth_service.py+++ b/skyvern/forge/sdk/services/org_auth_service.py@@ -213,6 +213,79 @@ async def get_current_org_with_api_key(return await get_current_org_cached(x_api_key, app.DATABASE)+def credential_route_token_types() -> tuple[OrganizationAuthTokenType, ...]:+ token_types: tuple[OrganizationAuthTokenType, ...] = (OrganizationAuthTokenType.api,)+ if app.AGENT_FUNCTION.credential_routes_accept_ui_session():+ token_types += (OrganizationAuthTokenType.ui_session,)+ return token_types+++async def _get_current_org_for_token_types(+ x_api_key: str | None,+ authorization: str | None,+ token_types: Sequence[OrganizationAuthTokenType],+) -> Organization:+ if authorization:+ try:+ return await authenticate_helper(authorization)+ except HTTPException:+ if not x_api_key:+ raise+ if not x_api_key:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="Invalid credentials",+ )+ validation = await resolve_org_from_api_key(+ x_api_key,+ app.DATABASE,+ token_types=token_types,+ )+ apply_request_org_context(validation.organization)+ return validation.organization+++async def get_current_org_for_credential_routes(+ # Header declaration must match get_current_org exactly: these dependencies are swapped on+ # published routes, and any difference rewrites the committed OpenAPI document.+ x_api_key: Annotated[+ str | None,+ Header(+ description="Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."+ ),+ ] = None,+ authorization: Annotated[str | None, Header(include_in_schema=False)] = None,+) -> Organization:+ """Credential-bearing routes: a full API token or an interactive session in cloud.++ Prefers ``authorization`` — unlike get_current_org, which prefers x-api-key — because the+ cloud dashboard sends both and its x-api-key is the ui_session token being excluded there.+ """+ return await _get_current_org_for_token_types(+ x_api_key,+ authorization,+ credential_route_token_types(),+ )+++async def get_current_org_with_api_token(+ organization_id: str,+ x_api_key: Annotated[str | None, Header()] = None,+ authorization: Annotated[str | None, Header(include_in_schema=False)] = None,+) -> Organization:+ current_org = await _get_current_org_for_token_types(+ x_api_key,+ authorization,+ (OrganizationAuthTokenType.api,),+ )+ if organization_id != current_org.organization_id:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="You do not have permission to access this organization",+ )+ return current_org++async def get_current_org_with_authentication(authorization: Annotated[str | None, Header()] = None,) -> Organization:@@ -342,6 +415,37 @@ async def authenticate_user_helper(authorization: str) -> str:return user_id+def _validate_token_expiry(token_payload: TokenPayload) -> None:+ if token_payload.exp <= time.time():+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="Auth token is expired",+ )+++def _decode_token_before_cache(x_api_key: str) -> dict[str, object] | None:+ try:+ return jwt.decode(+ x_api_key,+ settings.SECRET_KEY,+ algorithms=[ALGORITHM],+ options={"verify_exp": False},+ )+ except PyJWTError:+ return None+++def _validate_token_expiry_before_cache(payload: dict[str, object] | None) -> None:+ if payload is None:+ return+ try:+ token_payload = TokenPayload(**payload)+ except ValidationError:+ return++ _validate_token_expiry(token_payload)++async def resolve_org_from_api_key(x_api_key: str,db: AgentDB,@@ -380,15 +484,9 @@ async def resolve_org_from_api_key(status_code=status.HTTP_403_FORBIDDEN,detail="Could not validate credentials",)- if api_key_data.exp < time.time():- raise HTTPException(- status_code=status.HTTP_403_FORBIDDEN,- detail="Auth token is expired",- )-organization = await db.organizations.get_organization(organization_id=api_key_data.sub)if not organization:- LOG.warning("Organization not found", organization_id=api_key_data.sub, **payload)+ LOG.warning("Organization not found", organization_id=api_key_data.sub)raise HTTPException(status_code=404, detail="Organization not found")api_key_db_obj: OrganizationAuthToken | None = None@@ -409,7 +507,22 @@ async def resolve_org_from_api_key(detail="Invalid credentials",)+ if (+ api_key_db_obj.token_type == OrganizationAuthTokenType.ui_session+ and payload.get("token_type") != OrganizationAuthTokenType.ui_session.value+ ):+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="Invalid credentials",+ )+ _validate_token_expiry(api_key_data)+if api_key_db_obj.valid is False:+ if api_key_db_obj.token_type == OrganizationAuthTokenType.ui_session:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="Invalid credentials",+ )raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,detail="Your API key has expired. Please retrieve the latest one from https://app.skyvern.com/settings",@@ -426,9 +539,16 @@ _current_org_cache: TTLCache = TTLCache(maxsize=CACHE_SIZE, ttl=AUTHENTICATION_T@cached(cache=_current_org_cache)-async def get_current_org_cached(x_api_key: str, db: AgentDB) -> Organization:+async def _get_current_org_cached(x_api_key: str, db: AgentDB) -> Organization:"""Authentication is cached for one hour."""- validation = await resolve_org_from_api_key(x_api_key, db)+ validation = await resolve_org_from_api_key(+ x_api_key,+ db,+ token_types=(+ OrganizationAuthTokenType.api,+ OrganizationAuthTokenType.ui_session,+ ),+ )# set organization_id in skyvern context and log contextcontext = skyvern_context.current()@@ -438,6 +558,27 @@ async def get_current_org_cached(x_api_key: str, db: AgentDB) -> Organization:return validation.organization+def _claims_ui_session(payload: dict[str, object] | None) -> bool:+ return payload is not None and payload.get("token_type") == OrganizationAuthTokenType.ui_session.value+++async def get_current_org_cached(x_api_key: str, db: AgentDB) -> Organization:+ payload = _decode_token_before_cache(x_api_key)+ _validate_token_expiry_before_cache(payload)+ if _claims_ui_session(payload):+ validation = await resolve_org_from_api_key(+ x_api_key,+ db,+ token_types=(OrganizationAuthTokenType.ui_session,),+ )+ context = skyvern_context.current()+ if context:+ context.organization_id = validation.organization.organization_id+ context.organization_name = validation.organization.organization_name+ return validation.organization+ return await _get_current_org_cached(x_api_key, db)++def invalidate_cached_org(organization_id: str) -> None:"""Drop every cached ``Organization`` entry whose id matches.diff --git a/skyvern/forge/sdk/services/org_auth_token_service.py b/skyvern/forge/sdk/services/org_auth_token_service.pyindex 3883d85ae..268fe6951 100644--- a/skyvern/forge/sdk/services/org_auth_token_service.py+++ b/skyvern/forge/sdk/services/org_auth_token_service.py@@ -1,7 +1,12 @@-from datetime import timedelta+import math+from datetime import UTC, datetime, timedelta+import jwtimport structlog+from fastapi import HTTPException, status+from jwt.exceptions import PyJWTError+from skyvern.config import settingsfrom skyvern.forge import appfrom skyvern.forge.sdk.core import securityfrom skyvern.forge.sdk.schemas.organizations import OrganizationAuthToken, OrganizationAuthTokenType@@ -10,6 +15,28 @@ LOG = structlog.get_logger()API_KEY_LIFETIME = timedelta(weeks=5200)+def _ui_session_expiration(token: OrganizationAuthToken, org_id: str) -> int | None:+ try:+ payload = jwt.decode(+ token.token,+ settings.SECRET_KEY,+ algorithms=[settings.SIGNATURE_ALGORITHM],+ options={"verify_exp": False},+ )+ except PyJWTError:+ return None+ expires_at = payload.get("exp")+ if (+ payload.get("sub") != org_id+ or payload.get("token_type") != OrganizationAuthTokenType.ui_session.value+ or isinstance(expires_at, bool)+ or not isinstance(expires_at, (int, float))+ or (isinstance(expires_at, float) and not math.isfinite(expires_at))+ ):+ return None+ return int(expires_at)++async def create_org_api_token(org_id: str) -> OrganizationAuthToken:"""Creates an API token for the specified org_id.@@ -37,3 +64,46 @@ async def create_org_api_token(org_id: str) -> OrganizationAuthToken:)LOG.info("Created API token for organization", organization_id=org_id)return org_auth_token+++async def create_org_ui_session_token(org_id: str) -> tuple[OrganizationAuthToken, int]:+ organization = await app.DATABASE.organizations.get_organization(org_id)+ if not organization:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Organization not found")++ expires_delta = timedelta(minutes=settings.UI_SESSION_TOKEN_TTL_MINUTES)+ now = datetime.now(UTC)+ now_timestamp = now.timestamp()+ reusable_token: tuple[OrganizationAuthToken, int] | None = None+ expired_token_ids: list[str] = []+ for existing_token in await app.DATABASE.organizations.get_valid_org_auth_tokens(+ organization_id=org_id,+ token_type=OrganizationAuthTokenType.ui_session,+ ):+ existing_expiration = _ui_session_expiration(existing_token, org_id)+ if existing_expiration is None or existing_expiration <= now_timestamp:+ expired_token_ids.append(existing_token.id)+ elif reusable_token is None and existing_expiration - now_timestamp > expires_delta.total_seconds() / 2:+ reusable_token = existing_token, existing_expiration++ await app.DATABASE.organizations.delete_org_auth_tokens(+ organization_id=org_id,+ token_type=OrganizationAuthTokenType.ui_session,+ token_ids=expired_token_ids,+ )+ if reusable_token is not None:+ return reusable_token++ expires_at = int((now + expires_delta).timestamp())+ token = security.create_access_token(+ org_id,+ expires_delta=expires_delta,+ token_type=OrganizationAuthTokenType.ui_session.value,+ )+ org_auth_token = await app.DATABASE.organizations.create_org_auth_token(+ organization_id=org_id,+ token=token,+ token_type=OrganizationAuthTokenType.ui_session,+ )+ LOG.info("Created UI session token")+ return org_auth_token, expires_atdiff --git a/tests/unit/test_credential_test_trigger_type.py b/tests/unit/test_credential_test_trigger_type.pyindex d09edc46a..9153e236e 100644--- a/tests/unit/test_credential_test_trigger_type.py+++ b/tests/unit/test_credential_test_trigger_type.py@@ -243,6 +243,7 @@ def test_test_credential_endpoint_wires_user_agent_header(app = FastAPI()app.add_api_route("/credentials/{credential_id}/test", credentials.test_credential, methods=["POST"])app.dependency_overrides[org_auth_service.get_current_org] = _auth_override+ app.dependency_overrides[org_auth_service.get_current_org_for_credential_routes] = _auth_overrideresp = TestClient(app).post("/credentials/cred_test/test",@@ -281,6 +282,7 @@ def test_test_login_endpoint_wires_user_agent_header(app = FastAPI()app.add_api_route("/credentials/test-login", credentials.test_login, methods=["POST"])app.dependency_overrides[org_auth_service.get_current_org] = _auth_override+ app.dependency_overrides[org_auth_service.get_current_org_for_credential_routes] = _auth_overrideresp = TestClient(app).post("/credentials/test-login",diff --git a/tests/unit/test_internal_auth.py b/tests/unit/test_internal_auth.pyindex e200bce84..c81cb9065 100644--- a/tests/unit/test_internal_auth.py+++ b/tests/unit/test_internal_auth.py@@ -5,7 +5,9 @@ import pytestfrom fastapi import FastAPI, HTTPException, Request, statusfrom fastapi.testclient import TestClient+from skyvern.forge.agent_functions import AgentFunctionfrom skyvern.forge.sdk.routes import internal_auth+from skyvern.forge.sdk.schemas.organizations import OrganizationAuthTokenTypedef _request(client_host: str = "127.0.0.1") -> Request:@@ -21,6 +23,12 @@ def _request(client_host: str = "127.0.0.1") -> Request:)+def _request_with_api_key() -> Request:+ request = _request()+ request.scope["headers"] = [(b"x-api-key", b"local-ui-session-canary")]+ return request++def test_is_local_request_returns_false_for_public_ip() -> None:assert internal_auth._is_local_request(_request(client_host="8.8.8.8")) is False@@ -62,6 +70,34 @@ async def test_auth_status_rejects_private_non_loopback_address(monkeypatch: pytevaluate_local_api_key.assert_not_awaited()+async def test_auth_status_accepts_local_ui_session_without_authorization(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(internal_auth, "settings", SimpleNamespace(ENV="local"))+ monkeypatch.setattr(internal_auth.app, "AGENT_FUNCTION", AgentFunction())+ monkeypatch.setattr(internal_auth.app, "DATABASE", object())++ async def resolve_ui_session(+ token: str,+ _db: object,+ token_types: tuple[OrganizationAuthTokenType, ...],+ ) -> object:+ assert token == "local-ui-session-canary"+ assert token_types == (+ OrganizationAuthTokenType.api,+ OrganizationAuthTokenType.ui_session,+ )+ return SimpleNamespace(+ organization=SimpleNamespace(organization_id="org-local"),+ payload=SimpleNamespace(exp=4102444800),+ )++ monkeypatch.setattr(internal_auth, "resolve_org_from_api_key", resolve_ui_session)++ payload = await internal_auth.auth_status(_request_with_api_key())++ assert payload == {"status": "ok"}++def test_diagnostics_body_discloses_only_the_status() -> None:result = internal_auth.DiagnosticsResult(status=internal_auth.AuthStatus.ok,diff --git a/tests/unit/test_org_auth_service.py b/tests/unit/test_org_auth_service.pyindex 583c61206..1a6194178 100644--- a/tests/unit/test_org_auth_service.py+++ b/tests/unit/test_org_auth_service.py@@ -1,14 +1,21 @@-from datetime import datetime+from collections.abc import Iterator+from datetime import datetime, timedelta+from time import time as current_timefrom types import SimpleNamespaceimport jwtimport pytest-from fastapi import HTTPException+from fastapi import FastAPI, HTTPException+from fastapi.testclient import TestClient+from freezegun import freeze_timefrom skyvern.config import settings+from skyvern.forge.agent_functions import AgentFunctionfrom skyvern.forge.sdk.core.security import create_access_token-from skyvern.forge.sdk.schemas.organizations import Organization-from skyvern.forge.sdk.services import org_auth_service+from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType+from skyvern.forge.sdk.routes.routers import legacy_base_router+from skyvern.forge.sdk.schemas.organizations import Organization, OrganizationAuthToken+from skyvern.forge.sdk.services import org_auth_service, org_auth_token_servicefrom skyvern.forge.sdk.services.org_auth_service import (_get_api_key_debug_fields,_normalize_api_key_with_flags,@@ -224,3 +231,550 @@ def test_invalidate_cached_org_handles_empty_cache() -> None:# Should not raise.org_auth_service.invalidate_cached_org("anything")+++class _FakeOrganizationsRepository:+ def __init__(self, organization: Organization) -> None:+ self.organization = organization+ self.tokens: dict[tuple[OrganizationAuthTokenType, str], OrganizationAuthToken] = {}+ self.rows: dict[str, OrganizationAuthToken] = {}+ self.create_calls = 0+ self.validation_calls = 0+ self.validation_token_types: list[OrganizationAuthTokenType] = []++ async def get_organization(self, organization_id: str) -> Organization | None:+ if organization_id == self.organization.organization_id:+ return self.organization+ return None++ async def create_org_auth_token(+ self,+ organization_id: str,+ token_type: OrganizationAuthTokenType,+ token: str,+ ) -> OrganizationAuthToken:+ now = datetime.utcnow()+ self.create_calls += 1+ auth_token = OrganizationAuthToken(+ id=f"test-token-id-{self.create_calls}",+ organization_id=organization_id,+ token_type=token_type,+ token=token,+ valid=True,+ created_at=now,+ modified_at=now,+ )+ self.tokens[(token_type, token)] = auth_token+ self.rows[auth_token.id] = auth_token+ return auth_token++ async def get_valid_org_auth_token(+ self,+ organization_id: str,+ token_type: str,+ ) -> OrganizationAuthToken | None:+ return next(+ (+ token+ for token in self.rows.values()+ if token.organization_id == organization_id and token.token_type.value == token_type and token.valid+ ),+ None,+ )++ async def get_valid_org_auth_tokens(+ self,+ organization_id: str,+ token_type: OrganizationAuthTokenType,+ ) -> list[OrganizationAuthToken]:+ return sorted(+ (+ token+ for token in self.rows.values()+ if token.organization_id == organization_id and token.token_type == token_type and token.valid+ ),+ key=lambda token: token.created_at,+ reverse=True,+ )++ async def delete_org_auth_tokens(+ self,+ organization_id: str,+ token_type: OrganizationAuthTokenType,+ token_ids: list[str],+ ) -> None:+ for token_id in token_ids:+ token = self.rows.get(token_id)+ if token is None or token.organization_id != organization_id or token.token_type != token_type:+ continue+ self.rows.pop(token_id)+ if self.tokens.get((token_type, token.token)) is token:+ self.tokens.pop((token_type, token.token))++ async def validate_org_auth_token(+ self,+ organization_id: str,+ token_type: OrganizationAuthTokenType,+ token: str,+ valid: bool | None = None,+ ) -> OrganizationAuthToken | None:+ self.validation_calls += 1+ self.validation_token_types.append(token_type)+ auth_token = self.tokens.get((token_type, token))+ if auth_token is None or auth_token.organization_id != organization_id:+ return None+ if valid is not None and auth_token.valid is not valid:+ return None+ return auth_token+++class _FakeAgentDB:+ def __init__(self, organizations: _FakeOrganizationsRepository) -> None:+ self.organizations = organizations++[email protected](autouse=True)+def _clear_current_org_cache() -> Iterator[None]:+ org_auth_service._current_org_cache.clear()+ yield+ org_auth_service._current_org_cache.clear()+++async def _mint_ui_session_token(+ monkeypatch: pytest.MonkeyPatch,+ *,+ valid: bool = True,+) -> tuple[str, _FakeAgentDB, _FakeOrganizationsRepository]:+ monkeypatch.setattr(settings, "SECRET_KEY", "unit-test-ui-session-secret-canary-value")+ monkeypatch.setattr(settings, "UI_SESSION_TOKEN_TTL_MINUTES", 2)+ monkeypatch.setattr(org_auth_service.app, "AGENT_FUNCTION", AgentFunction())+ organization = _make_org("org-ui-session")+ repository = _FakeOrganizationsRepository(organization)+ db = _FakeAgentDB(repository)+ monkeypatch.setattr(org_auth_token_service.app, "DATABASE", db)++ auth_token, _ = await org_auth_token_service.create_org_ui_session_token(organization.organization_id)+ auth_token.valid = valid+ return auth_token.token, db, repository+++async def _mint_api_token(+ monkeypatch: pytest.MonkeyPatch,+) -> tuple[str, _FakeAgentDB, _FakeOrganizationsRepository]:+ monkeypatch.setattr(settings, "SECRET_KEY", "unit-test-api-route-secret-canary")+ monkeypatch.setattr(org_auth_service.app, "AGENT_FUNCTION", AgentFunction())+ organization = _make_org("org-api-route")+ repository = _FakeOrganizationsRepository(organization)+ db = _FakeAgentDB(repository)+ token = create_access_token(organization.organization_id, expires_delta=timedelta(hours=1))+ await repository.create_org_auth_token(+ organization_id=organization.organization_id,+ token_type=OrganizationAuthTokenType.api,+ token=token,+ )+ monkeypatch.setattr(org_auth_service.app, "DATABASE", db)+ return token, db, repository+++def _organization_routes_client() -> TestClient:+ fastapi_app = FastAPI()+ fastapi_app.include_router(legacy_base_router, prefix="/api/v1")+ return TestClient(fastapi_app)+++async def test_freshly_minted_ui_session_token_authenticates(monkeypatch: pytest.MonkeyPatch) -> None:+ issued_after = current_time()++ token, db, repository = await _mint_ui_session_token(monkeypatch)+ payload = jwt.decode(+ token,+ settings.SECRET_KEY,+ algorithms=[settings.SIGNATURE_ALGORITHM],+ options={"verify_exp": False},+ )++ assert payload["token_type"] == OrganizationAuthTokenType.ui_session.value+ assert payload["exp"] == pytest.approx(issued_after + 120, abs=2)+ assert repository.tokens[(OrganizationAuthTokenType.ui_session, token)].valid is True++ organization = await org_auth_service.get_current_org_cached(token, db)++ assert organization.organization_id == "org-ui-session"+ assert repository.validation_token_types == [OrganizationAuthTokenType.ui_session]+++async def test_expired_ui_session_token_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:+ token, db, repository = await _mint_ui_session_token(monkeypatch)+ payload = jwt.decode(+ token,+ settings.SECRET_KEY,+ algorithms=[settings.SIGNATURE_ALGORITHM],+ options={"verify_exp": False},+ )+ monkeypatch.setattr(org_auth_service.time, "time", lambda: payload["exp"] + 1)++ with pytest.raises(HTTPException) as exc_info:+ await org_auth_service.get_current_org_cached(token, db)++ assert exc_info.value.status_code == 403+ assert exc_info.value.detail == "Auth token is expired"+ assert repository.validation_calls == 0+++async def test_ui_session_expiry_is_checked_before_cached_authentication(monkeypatch: pytest.MonkeyPatch) -> None:+ token, db, repository = await _mint_ui_session_token(monkeypatch)+ payload = jwt.decode(+ token,+ settings.SECRET_KEY,+ algorithms=[settings.SIGNATURE_ALGORITHM],+ options={"verify_exp": False},+ )++ organization = await org_auth_service.get_current_org_cached(token, db)+ validation_calls = repository.validation_calls+ assert organization.organization_id == "org-ui-session"++ monkeypatch.setattr(org_auth_service.time, "time", lambda: payload["exp"] + 1)+ with pytest.raises(HTTPException) as exc_info:+ await org_auth_service.get_current_org_cached(token, db)++ assert exc_info.value.status_code == 403+ assert exc_info.value.detail == "Auth token is expired"+ assert repository.validation_calls == validation_calls+++async def test_expired_api_token_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "SECRET_KEY", "unit-test-api-token-secret-canary-value")+ organization = _make_org("org-api-token")+ repository = _FakeOrganizationsRepository(organization)+ db = _FakeAgentDB(repository)+ token = create_access_token(organization.organization_id, expires_delta=timedelta(seconds=-1))+ await repository.create_org_auth_token(+ organization_id=organization.organization_id,+ token_type=OrganizationAuthTokenType.api,+ token=token,+ )++ with pytest.raises(HTTPException) as excinfo:+ await org_auth_service.get_current_org_cached(token, db)++ assert excinfo.value.status_code == 403+++async def test_unexpired_api_token_authenticates(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "SECRET_KEY", "unit-test-api-token-secret-canary-value")+ organization = _make_org("org-api-token-valid")+ repository = _FakeOrganizationsRepository(organization)+ db = _FakeAgentDB(repository)+ token = create_access_token(organization.organization_id, expires_delta=timedelta(hours=1))+ await repository.create_org_auth_token(+ organization_id=organization.organization_id,+ token_type=OrganizationAuthTokenType.api,+ token=token,+ )++ resolved_organization = await org_auth_service.get_current_org_cached(token, db)++ assert resolved_organization.organization_id == organization.organization_id+++async def test_cached_api_authentication_decodes_once_before_cache(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "SECRET_KEY", "unit-test-cached-api-secret-canary-value")+ organization = _make_org("org-api-token-cached")+ repository = _FakeOrganizationsRepository(organization)+ db = _FakeAgentDB(repository)+ token = create_access_token(organization.organization_id, expires_delta=timedelta(hours=1))+ await repository.create_org_auth_token(+ organization_id=organization.organization_id,+ token_type=OrganizationAuthTokenType.api,+ token=token,+ )+ await org_auth_service.get_current_org_cached(token, db)++ decode = org_auth_service.jwt.decode+ decode_calls = 0++ def count_decode(*args: object, **kwargs: object) -> dict:+ nonlocal decode_calls+ decode_calls += 1+ return decode(*args, **kwargs)++ monkeypatch.setattr(org_auth_service.jwt, "decode", count_decode)++ resolved_organization = await org_auth_service.get_current_org_cached(token, db)++ assert resolved_organization.organization_id == organization.organization_id+ assert decode_calls == 1+++async def test_repeated_ui_session_mints_keep_token_rows_bounded(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "SECRET_KEY", "unit-test-bounded-ui-session-secret-canary")+ monkeypatch.setattr(settings, "UI_SESSION_TOKEN_TTL_MINUTES", 2)+ organization = _make_org("org-ui-session-bounded")+ repository = _FakeOrganizationsRepository(organization)+ db = _FakeAgentDB(repository)+ monkeypatch.setattr(org_auth_token_service.app, "DATABASE", db)++ with freeze_time("2030-01-01T00:00:00Z") as frozen_time:+ first_token, _ = await org_auth_token_service.create_org_ui_session_token(organization.organization_id)+ for _ in range(5):+ reused_token, _ = await org_auth_token_service.create_org_ui_session_token(organization.organization_id)+ assert reused_token.token == first_token.token+ assert repository.create_calls == 1++ for _ in range(6):+ frozen_time.tick(delta=timedelta(seconds=61))+ await org_auth_token_service.create_org_ui_session_token(organization.organization_id)++ assert len(repository.rows) <= 2+++async def test_revoking_a_ui_session_token_takes_effect_despite_the_auth_cache(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ token, db, repository = await _mint_ui_session_token(monkeypatch)++ # Authenticate once so a cached entry would exist for this token.+ organization = await org_auth_service.get_current_org_cached(token, db)+ assert organization.organization_id == "org-ui-session"++ for auth_token in repository.tokens.values():+ auth_token.valid = False++ with pytest.raises(HTTPException) as exc_info:+ await org_auth_service.get_current_org_cached(token, db)++ assert exc_info.value.status_code == 403+++async def test_revoked_ui_session_token_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:+ token, db, _ = await _mint_ui_session_token(monkeypatch, valid=False)++ with pytest.raises(HTTPException) as exc_info:+ await org_auth_service.get_current_org_cached(token, db)++ assert exc_info.value.status_code == 403+ assert exc_info.value.detail == "Invalid credentials"+++async def test_ui_session_token_is_not_accepted_by_api_only_resolver(monkeypatch: pytest.MonkeyPatch) -> None:+ token, db, _ = await _mint_ui_session_token(monkeypatch)++ with pytest.raises(HTTPException) as exc_info:+ await org_auth_service.resolve_org_from_api_key(token, db)++ assert exc_info.value.status_code == 403+ assert exc_info.value.detail == "Invalid credentials"++[email protected]("suffix", ["", "/"])+async def test_self_hosted_api_key_route_rejects_ui_session_token(+ monkeypatch: pytest.MonkeyPatch,+ suffix: str,+) -> None:+ token, _, _ = await _mint_ui_session_token(monkeypatch)++ with _organization_routes_client() as client:+ response = client.get(+ f"/api/v1/organizations/org-ui-session/apikeys{suffix}",+ headers={"x-api-key": token},+ )++ assert response.status_code == 403++[email protected]("suffix", ["", "/"])+async def test_api_key_route_accepts_api_token(+ monkeypatch: pytest.MonkeyPatch,+ suffix: str,+) -> None:+ token, _, _ = await _mint_api_token(monkeypatch)++ with _organization_routes_client() as client:+ response = client.get(+ f"/api/v1/organizations/org-api-route/apikeys{suffix}",+ headers={"x-api-key": token},+ )++ assert response.status_code == 200+ assert len(response.json()["api_keys"]) == 1+++async def test_self_hosted_credential_gate_accepts_ui_session_token(monkeypatch: pytest.MonkeyPatch) -> None:+ token, db, _ = await _mint_ui_session_token(monkeypatch)+ monkeypatch.setattr(org_auth_service.app, "AGENT_FUNCTION", AgentFunction())+ monkeypatch.setattr(org_auth_service.app, "DATABASE", db)++ organization = await org_auth_service.get_current_org_for_credential_routes(x_api_key=token)++ assert organization.organization_id == "org-ui-session"+++async def test_ordinary_organization_route_accepts_ui_session_token(monkeypatch: pytest.MonkeyPatch) -> None:+ token, _, _ = await _mint_ui_session_token(monkeypatch)++ with _organization_routes_client() as client:+ response = client.get(+ "/api/v1/organizations/me",+ headers={"x-api-key": token},+ )++ assert response.status_code == 200+ assert response.json()["organization_id"] == "org-ui-session"++[email protected]("expires_at", [float("nan"), float("inf"), float("-inf")])+def test_ui_session_expiration_rejects_non_finite_values(+ monkeypatch: pytest.MonkeyPatch,+ expires_at: float,+) -> None:+ monkeypatch.setattr(+ org_auth_token_service.jwt,+ "decode",+ lambda *_args, **_kwargs: {+ "sub": "org-ui-session",+ "token_type": OrganizationAuthTokenType.ui_session.value,+ "exp": expires_at,+ },+ )++ result = org_auth_token_service._ui_session_expiration(+ SimpleNamespace(token="non-finite-exp-token-canary"),+ "org-ui-session",+ )++ assert result is None+++def test_ui_session_expiration_accepts_large_integer(monkeypatch: pytest.MonkeyPatch) -> None:+ expires_at = 10**1000+ monkeypatch.setattr(+ org_auth_token_service.jwt,+ "decode",+ lambda *_args, **_kwargs: {+ "sub": "org-ui-session",+ "token_type": OrganizationAuthTokenType.ui_session.value,+ "exp": expires_at,+ },+ )++ result = org_auth_token_service._ui_session_expiration(+ SimpleNamespace(token="large-exp-token-canary"),+ "org-ui-session",+ )++ assert result == expires_at+++async def test_ui_session_row_without_signed_type_claim_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "SECRET_KEY", "unit-test-missing-claim-secret-canary")+ organization = _make_org("org-ui-session")+ repository = _FakeOrganizationsRepository(organization)+ db = _FakeAgentDB(repository)+ token = create_access_token(organization.organization_id, expires_delta=timedelta(minutes=2))+ await repository.create_org_auth_token(+ organization_id=organization.organization_id,+ token_type=OrganizationAuthTokenType.ui_session,+ token=token,+ )++ with pytest.raises(HTTPException) as exc_info:+ await org_auth_service.get_current_org_cached(token, db)++ assert exc_info.value.status_code == 403+ assert exc_info.value.detail == "Invalid credentials"+++def test_credential_bearing_routes_use_the_deployment_aware_gate() -> None:+ import inspect+ from typing import Annotated, get_args, get_origin++ from skyvern.forge.sdk.routes import agent_protocol+ from skyvern.forge.sdk.routes import credentials as credentials_routes+ from skyvern.forge.sdk.routes import custom_llms, google_oauth, microsoft_oauth++ # Every module holding credential- or credential-config-bearing routes. Enumerated from the+ # modules rather than listed by name, so a newly added route fails this test instead of silently+ # defaulting to the permissive dependency. Intentional exemptions must be named with a reason.+ # cloud/ modules are covered by tests/cloud/; this file syncs to the OSS repo where they do+ # not exist.+ CREDENTIAL_ROUTE_MODULES = (+ credentials_routes,+ custom_llms,+ google_oauth,+ microsoft_oauth,+ )+ EXEMPT_FROM_CREDENTIAL_GATE: dict[str, str] = {}++ def route_dependencies(handler: object) -> set[object]:+ # Both declaration styles count: `x = Depends(dep)` and `Annotated[T, Depends(dep)]`. Reading+ # only defaults makes every Annotated route invisible, which is how the OAuth modules stayed+ # ungated while this test reported green.+ dependencies: set[object] = set()+ for parameter in inspect.signature(handler).parameters.values():+ if parameter.default is not inspect.Parameter.empty:+ dependencies.add(getattr(parameter.default, "dependency", None))+ if get_origin(parameter.annotation) is Annotated:+ for metadata in get_args(parameter.annotation)[1:]:+ dependencies.add(getattr(metadata, "dependency", None))+ return dependencies++ def is_org_authed_route(handler: object, module: object) -> bool:+ if not callable(handler) or getattr(handler, "__module__", None) != module.__name__:+ return False+ return bool(+ route_dependencies(handler)+ & {+ org_auth_service.get_current_org,+ org_auth_service.get_current_org_for_credential_routes,+ }+ )++ credential_route_handlers = {+ f"{module.__name__}.{name}": handler+ for module in CREDENTIAL_ROUTE_MODULES+ for name, handler in vars(module).items()+ if is_org_authed_route(handler, module)+ }+ assert credential_route_handlers, "found no credential routes to check — the enumeration broke"++ for name, handler in sorted(credential_route_handlers.items()):+ if name in EXEMPT_FROM_CREDENTIAL_GATE:+ continue+ dependencies = route_dependencies(handler)+ assert org_auth_service.get_current_org_for_credential_routes in dependencies, (+ f"{name} must use the deployment-aware credential gate"+ )+ assert org_auth_service.get_current_org not in dependencies, (+ f"{name} still accepts a ui_session token via the ungated dependency"+ )++ api_key_route_dependencies = {+ getattr(parameter.default, "dependency", None)+ for parameter in inspect.signature(agent_protocol.get_api_keys).parameters.values()+ if parameter.default is not inspect.Parameter.empty+ }+ assert org_auth_service.get_current_org_with_api_token in api_key_route_dependencies+ assert org_auth_service.get_current_org_for_credential_routes not in api_key_route_dependencies++ api_key_resolver_dependencies = {+ getattr(parameter.default, "dependency", None)+ for parameter in inspect.signature(org_auth_service.get_current_org_with_api_token).parameters.values()+ if parameter.default is not inspect.Parameter.empty+ }+ assert org_auth_service.get_current_org_for_credential_routes not in api_key_resolver_dependenciesdiff --git a/tests/unit/test_ui_session_route.py b/tests/unit/test_ui_session_route.pynew file mode 100644index 000000000..4d0461b39--- /dev/null+++ b/tests/unit/test_ui_session_route.py@@ -0,0 +1,97 @@+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from fastapi import FastAPI, HTTPException, status+from fastapi.testclient import TestClient++from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType+from skyvern.forge.sdk.routes import ui_session+from skyvern.forge.sdk.routes.routers import base_router, legacy_base_router+++def client() -> TestClient:+ fastapi_app = FastAPI()+ fastapi_app.include_router(base_router, prefix="/v1")+ fastapi_app.include_router(legacy_base_router, prefix="/api/v1")+ return TestClient(fastapi_app)++[email protected]("prefix", ["/v1", "/api/v1"])+def test_ui_session_route_mints_from_api_key_only(+ client: TestClient,+ monkeypatch: pytest.MonkeyPatch,+ prefix: str,+) -> None:+ caller_key = "caller-api-key-canary"+ organization_id = "org-ui-session-route"+ minted_token = "minted-ui-session-canary"+ expires_at = 1_893_456_789++ async def resolve_org(api_key: str, _db: object, token_types: tuple[OrganizationAuthTokenType, ...]) -> object:+ assert api_key == caller_key+ assert token_types == (OrganizationAuthTokenType.api,)+ return SimpleNamespace(organization=SimpleNamespace(organization_id=organization_id))++ mint_token = AsyncMock(return_value=(SimpleNamespace(token=minted_token), expires_at))+ monkeypatch.setattr(ui_session, "resolve_org_from_api_key", resolve_org)+ monkeypatch.setattr(ui_session, "create_org_ui_session_token", mint_token)++ response = client.post(f"{prefix}/ui-session", headers={"x-api-key": caller_key})++ assert response.status_code == status.HTTP_200_OK+ assert response.headers["cache-control"] == "no-store"+ assert set(response.json()) == {"token", "expires_at"}+ assert response.json()["token"] == minted_token+ assert response.json()["expires_at"] == expires_at+ mint_token.assert_awaited_once_with(organization_id)+++def test_ui_session_route_returns_not_found_when_org_disappears(+ client: TestClient,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ caller_key = "caller-api-key-canary"+ organization_id = "missing-org-id"+ organizations = SimpleNamespace(get_organization=AsyncMock(return_value=None))+ database = SimpleNamespace(organizations=organizations)++ async def resolve_org(api_key: str, _db: object, token_types: tuple[OrganizationAuthTokenType, ...]) -> object:+ assert api_key == caller_key+ assert token_types == (OrganizationAuthTokenType.api,)+ return SimpleNamespace(organization=SimpleNamespace(organization_id=organization_id))++ monkeypatch.setattr(ui_session.app, "DATABASE", database)+ monkeypatch.setattr(ui_session, "resolve_org_from_api_key", resolve_org)++ response = client.post("/v1/ui-session", headers={"x-api-key": caller_key})++ assert response.status_code == status.HTTP_404_NOT_FOUND+ assert response.json() == {"detail": "Organization not found"}+ organizations.get_organization.assert_awaited_once_with(organization_id)+++def test_ui_session_route_rejects_ui_session_credential(+ client: TestClient,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_credential = "ui-session-credential-canary"++ async def reject_session(+ api_key: str,+ _db: object,+ token_types: tuple[OrganizationAuthTokenType, ...],+ ) -> object:+ assert api_key == session_credential+ assert token_types == (OrganizationAuthTokenType.api,)+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid credentials")++ mint_token = AsyncMock()+ monkeypatch.setattr(ui_session, "resolve_org_from_api_key", reject_session)+ monkeypatch.setattr(ui_session, "create_org_ui_session_token", mint_token)++ response = client.post("/v1/ui-session", headers={"x-api-key": session_credential})++ assert response.status_code == status.HTTP_403_FORBIDDEN+ mint_token.assert_not_awaited()