Skip to content

Automate browser based workflows with AI

feat(SKY-12026): open-source Google integrations + org-level OAuth client config (#7283)

Suchintan1e0afae8a022
diff --git a/docs/developers/self-hosted/google-integrations.mdx b/docs/developers/self-hosted/google-integrations.mdx
new file mode 100644
index 000000000..98d7610d8
--- /dev/null
+++ b/docs/developers/self-hosted/google-integrations.mdx
@@ -0,0 +1,118 @@
+---
+title: Google Integrations
+subtitle: Connect Google accounts to Google Sheets, Gmail, and Google Drive on a self-hosted deployment
+description: Configure Google OAuth on self-hosted Skyvern so users can connect Google accounts for Sheets, Gmail, and Drive from the Settings or Integrations page. Covers creating the OAuth client, required scopes, settings-page configuration, and the GOOGLE_OAUTH_* environment variables.
+slug: developers/self-hosted/google-integrations
+keywords:
+ - Google Sheets
+ - Gmail
+ - Google Drive
+ - Google OAuth
+ - integrations
+ - Settings
+ - GOOGLE_OAUTH_CLIENT_ID
+ - GOOGLE_OAUTH_CLIENT_SECRET
+ - GOOGLE_OAUTH_REDIRECT_HOSTS
+ - GOOGLE_OAUTH_APP_ORIGINS
+ - scopes
+---
+
+The Google Sheets, Gmail, and Google Drive integrations connect to a Google account through OAuth. On self-hosted Skyvern this is off by default. Once you configure a Google OAuth client, users can connect their accounts from the **Integrations** page and the OAuth callback completes in your own UI.
+
+## 1. Create a Google OAuth client
+
+1. In the [Google Cloud Console](https://console.cloud.google.com/), select or create a project.
+2. Enable the **Google Sheets API**, **Google Drive API**, and **Gmail API** for the project (APIs & Services → Library).
+3. Configure the **OAuth consent screen**. External apps must add each user as a test user (or publish the app) before they can connect.
+4. Create an **OAuth client ID** of type **Web application** (APIs & Services → Credentials → Create credentials).
+5. Add your Skyvern UI's callback URL to **Authorized redirect URIs**. The path is always `/integrations/google/callback`:
+ - Local: `http://localhost:8080/integrations/google/callback`
+ - Production: `https://skyvern.your-company.com/integrations/google/callback`
+6. Copy the generated **Client ID** and **Client secret**.
+
+## 2. Required scopes
+
+Skyvern requests a scope profile for the integration the user connects.
+
+### Google Sheets
+
+| Scope | Purpose |
+|-------|---------|
+| `https://www.googleapis.com/auth/spreadsheets` | Read and write spreadsheet contents |
+| `https://www.googleapis.com/auth/drive.file` | Access files the app creates or the user opens |
+| `https://www.googleapis.com/auth/drive.metadata.readonly` | List and look up spreadsheets by name |
+
+### Gmail
+
+| Scope | Purpose |
+|-------|---------|
+| `https://www.googleapis.com/auth/gmail.readonly` | Read messages for verification codes and magic links |
+
+### Google Drive
+
+| Scope | Purpose |
+|-------|---------|
+| `https://www.googleapis.com/auth/drive` | Upload files to Drive, including existing folders selected by ID or URL |
+
+You don't set these manually — Skyvern requests the appropriate profile automatically. If your consent screen restricts scopes, add the scopes above so users can grant them.
+
+## 3. Configure the OAuth client in Skyvern (recommended)
+
+First, enable encryption on the **backend** (`.env` or your deployment's environment), then restart Skyvern:
+
+```bash .env
+ENABLE_ENCRYPTION=true
+ENCRYPTOR_AES_SECRET_KEY=<32-byte base64 key>
+```
+
+Then configure the client for your organization:
+
+1. Open **Settings → Google OAuth**, or use the **Google OAuth** form at the top of **Integrations**.
+2. Confirm that the read-only **Callback URL** matches the redirect URI you registered with Google.
+3. Paste the **Client ID** and **Client Secret** from step 1.
+4. Set **Redirect Hosts** to the hostname allowed for the OAuth redirect (hostname only, without a scheme or path).
+5. Set **App Origins** to the origin allowed to finish the flow (scheme, host, and port when applicable).
+6. Click **Save Configuration**.
+
+Skyvern stores the OAuth client configuration AES-encrypted per organization. The client secret is never displayed again after you save it; leave the field blank when updating the other values to keep the existing secret.
+
+## 4. Environment variables (alternative)
+
+Operators who prefer environment configuration can set these values on the **backend** (`.env` or your deployment's environment), then restart Skyvern. An organization-level configuration saved in **Settings** takes precedence over these environment values.
+
+```bash .env
+# Enable encryption — OAuth refresh tokens are never stored in plaintext.
+ENABLE_ENCRYPTION=true
+ENCRYPTOR_AES_SECRET_KEY=<32-byte base64 key>
+
+# Google OAuth client from step 1.
+GOOGLE_OAUTH_CLIENT_ID=<your-client-id>.apps.googleusercontent.com
+GOOGLE_OAUTH_CLIENT_SECRET=<your-client-secret>
+
+# Hostname(s) allowed as the OAuth redirect_uri (host only, no scheme or path).
+# Must match the host of the redirect URI you registered with Google.
+GOOGLE_OAUTH_REDIRECT_HOSTS=skyvern.your-company.com
+
+# App origin(s) allowed to receive the connected credential after callback
+# (scheme + host + port). This is the origin your UI is served from.
+GOOGLE_OAUTH_APP_ORIGINS=https://skyvern.your-company.com
+```
+
+| Variable | Required | Description |
+|----------|----------|-------------|
+| `GOOGLE_OAUTH_CLIENT_ID` | Yes | Web-application client ID from Google Cloud. |
+| `GOOGLE_OAUTH_CLIENT_SECRET` | Yes | Client secret paired with the client ID. |
+| `GOOGLE_OAUTH_REDIRECT_HOSTS` | Yes | Comma-separated hostnames permitted as the `redirect_uri`. Non-loopback hosts must use HTTPS. |
+| `GOOGLE_OAUTH_APP_ORIGINS` | Yes | Comma-separated origins (`scheme://host[:port]`) permitted to finish the flow. Empty rejects every connect attempt. |
+| `ENABLE_ENCRYPTION` | Yes | Must be `true`; credentials are refused if encryption is off. |
+
+For local development, `localhost` is treated as a loopback host, so `http://localhost:8080` works for both `GOOGLE_OAUTH_REDIRECT_HOSTS` (`localhost`) and `GOOGLE_OAUTH_APP_ORIGINS` (`http://localhost:8080`).
+
+## 5. Verify
+
+1. Restart the backend so the encryption or environment settings load.
+2. Open the Skyvern UI and go to **Integrations**. Confirm that the **Google Sheets**, **Gmail**, and **Google Drive** cards each show a **Connect** button.
+3. Click **Connect** on one of the cards and complete the Google consent screen. You land back on the Integrations page with the account listed under **Connected Google Accounts**.
+4. Use the connected account in the corresponding Google Sheets, Gmail, or Google Drive workflow feature.
+
+If **Connect** returns an error, double-check that the redirect URI registered with Google matches **Redirect Hosts** (or `GOOGLE_OAUTH_REDIRECT_HOSTS`), and that **App Origins** (or `GOOGLE_OAUTH_APP_ORIGINS`) contains the exact origin your UI runs on.
diff --git a/docs/docs.json b/docs/docs.json
index 337cfe016..953758b48 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -212,6 +212,7 @@
"developers/self-hosted/proxy",
"developers/self-hosted/kubernetes",
"developers/self-hosted/storage",
+ "developers/self-hosted/google-integrations",
"integrations/local-llms"
]
}
diff --git a/skyvern-frontend/src/api/types.ts b/skyvern-frontend/src/api/types.ts
index cbc97706e..9cd2ce707 100644
--- a/skyvern-frontend/src/api/types.ts
+++ b/skyvern-frontend/src/api/types.ts
@@ -378,6 +378,27 @@ export interface GoogleOAuthCredentialListResponse {
credentials: GoogleOAuthCredential[];
}
+export interface GoogleOAuthClientConfigSafe {
+ client_id: string | null;
+ redirect_hosts: string[];
+ app_origins: string[];
+ client_secret_configured: boolean;
+ configured: boolean;
+ source: string;
+ encryption_enabled: boolean;
+}
+
+export interface GoogleOAuthClientConfigResponse {
+ config: GoogleOAuthClientConfigSafe;
+}
+
+export interface UpdateGoogleOAuthClientConfigRequest {
+ client_id: string;
+ client_secret?: string | null;
+ redirect_hosts: string[];
+ app_origins: string[];
+}
+
export interface CreateGoogleOAuthAuthorizeRequest {
redirect_uri: string;
credential_name?: string;
diff --git a/skyvern-frontend/src/components/GoogleOAuthClientConfigForm.tsx b/skyvern-frontend/src/components/GoogleOAuthClientConfigForm.tsx
new file mode 100644
index 000000000..c66f43981
--- /dev/null
+++ b/skyvern-frontend/src/components/GoogleOAuthClientConfigForm.tsx
@@ -0,0 +1,261 @@
+import { type FormEvent, useEffect, useMemo, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { ExternalLinkIcon } from "@radix-ui/react-icons";
+import { getClient } from "@/api/AxiosClient";
+import {
+ GoogleOAuthClientConfigResponse,
+ UpdateGoogleOAuthClientConfigRequest,
+} from "@/api/types";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Textarea } from "@/components/ui/textarea";
+import { useToast } from "@/components/ui/use-toast";
+import { ClearCredentialDialog } from "@/components/ClearCredentialDialog";
+import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { buildGoogleOAuthRedirectUri } from "@/routes/integrations/googleOAuth";
+
+const queryKey = ["googleOAuthClientConfig"];
+
+function splitList(value: string): string[] {
+ return value
+ .split(/[\n,]+/)
+ .map((item) => item.trim())
+ .filter(Boolean);
+}
+
+function joinList(values: string[] | undefined, fallback: string): string {
+ return values && values.length > 0 ? values.join("\n") : fallback;
+}
+
+function apiErrorMessage(error: unknown, fallback: string): string {
+ return (
+ (error as { response?: { data?: { detail?: string } } })?.response?.data
+ ?.detail ||
+ (error as Error)?.message ||
+ fallback
+ );
+}
+
+type Props = {
+ onSuccess?: () => void;
+};
+
+export function GoogleOAuthClientConfigForm({ onSuccess }: Props = {}) {
+ const credentialGetter = useCredentialGetter();
+ const queryClient = useQueryClient();
+ const { toast } = useToast();
+ const callbackUrl = useMemo(() => buildGoogleOAuthRedirectUri(), []);
+ const defaultRedirectHost =
+ typeof window !== "undefined" ? window.location.hostname : "localhost";
+ const defaultAppOrigin =
+ typeof window !== "undefined" ? window.location.origin : "";
+
+ const [clientId, setClientId] = useState("");
+ const [clientSecret, setClientSecret] = useState("");
+ const [redirectHosts, setRedirectHosts] = useState(defaultRedirectHost);
+ const [appOrigins, setAppOrigins] = useState(defaultAppOrigin);
+
+ const { data, isLoading } = useQuery({
+ queryKey,
+ queryFn: async () => {
+ const client = await getClient(credentialGetter);
+ return client
+ .get("/google/oauth/config")
+ .then((response) => response.data as GoogleOAuthClientConfigResponse);
+ },
+ });
+ const config = data?.config;
+
+ useEffect(() => {
+ setClientId(config?.client_id ?? "");
+ setClientSecret("");
+ setRedirectHosts(
+ config?.configured
+ ? (config.redirect_hosts ?? []).join("\n")
+ : joinList(config?.redirect_hosts, defaultRedirectHost),
+ );
+ setAppOrigins(
+ config?.configured
+ ? (config.app_origins ?? []).join("\n")
+ : joinList(config?.app_origins, defaultAppOrigin),
+ );
+ }, [config, defaultAppOrigin, defaultRedirectHost]);
+
+ const saveMutation = useMutation({
+ mutationFn: async (request: UpdateGoogleOAuthClientConfigRequest) => {
+ const client = await getClient(credentialGetter);
+ return client
+ .put("/google/oauth/config", request)
+ .then((response) => response.data as GoogleOAuthClientConfigResponse);
+ },
+ onSuccess: () => {
+ setClientSecret("");
+ queryClient.invalidateQueries({ queryKey });
+ toast({
+ title: "Success",
+ description: "Google OAuth configuration saved",
+ });
+ onSuccess?.();
+ },
+ onError: (error) => {
+ toast({
+ title: "Error",
+ description: apiErrorMessage(
+ error,
+ "Failed to save Google OAuth configuration",
+ ),
+ variant: "destructive",
+ });
+ },
+ });
+
+ const clearMutation = useMutation({
+ mutationFn: async () => {
+ const client = await getClient(credentialGetter);
+ return client.delete("/google/oauth/config");
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey });
+ toast({
+ title: "Success",
+ description: "Google OAuth configuration cleared",
+ });
+ },
+ onError: (error) => {
+ toast({
+ title: "Error",
+ description: apiErrorMessage(
+ error,
+ "Failed to clear Google OAuth configuration",
+ ),
+ variant: "destructive",
+ });
+ },
+ });
+
+ const isMutating = saveMutation.isPending || clearMutation.isPending;
+ const encryptionEnabled = config?.encryption_enabled ?? false;
+ const canClear = config?.source === "organization";
+
+ const onSubmit = (event: FormEvent) => {
+ event.preventDefault();
+ saveMutation.mutate({
+ client_id: clientId,
+ client_secret: clientSecret || undefined,
+ redirect_hosts: splitList(redirectHosts),
+ app_origins: splitList(appOrigins),
+ });
+ };
+
+ return (
+ <form onSubmit={onSubmit} className="space-y-5">
+ <div className="space-y-2">
+ <div className="flex items-center justify-between gap-4">
+ <div>
+ <h3 className="text-lg font-medium">Google OAuth</h3>
+ <p className="text-sm text-muted-foreground">
+ Configure the OAuth client used for Google Sheets, Gmail, and
+ Drive.
+ </p>
+ </div>
+ <a
+ href="https://console.cloud.google.com/apis/credentials"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center gap-2 text-sm text-blue-600 underline"
+ >
+ Google Cloud Console
+ <ExternalLinkIcon className="h-3.5 w-3.5" />
+ </a>
+ </div>
+ {!encryptionEnabled && (
+ <div className="rounded-md border border-yellow-300 bg-yellow-50 px-3 py-2 text-sm text-yellow-900">
+ Enable AES encryption before saving or connecting Google accounts.
+ </div>
+ )}
+ <div className="rounded-md bg-muted px-3 py-2 text-sm">
+ <div className="mb-1 text-muted-foreground">Callback URL</div>
+ <Input readOnly value={callbackUrl} className="bg-background" />
+ </div>
+ </div>
+
+ <div className="grid gap-4 md:grid-cols-2">
+ <div className="space-y-2">
+ <Label htmlFor="google-client-id">Client ID</Label>
+ <Input
+ id="google-client-id"
+ value={clientId}
+ onChange={(event) => setClientId(event.target.value)}
+ disabled={isLoading || isMutating}
+ placeholder="123.apps.googleusercontent.com"
+ />
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor="google-client-secret">Client Secret</Label>
+ <Input
+ id="google-client-secret"
+ type="password"
+ value={clientSecret}
+ onChange={(event) => setClientSecret(event.target.value)}
+ disabled={isLoading || isMutating}
+ placeholder={
+ config?.client_secret_configured &&
+ config?.source === "organization"
+ ? "Leave blank to keep existing secret"
+ : "Client secret"
+ }
+ />
+ </div>
+ </div>
+
+ <div className="grid gap-4 md:grid-cols-2">
+ <div className="space-y-2">
+ <Label htmlFor="google-redirect-hosts">Redirect Hosts</Label>
+ <Textarea
+ id="google-redirect-hosts"
+ value={redirectHosts}
+ onChange={(event) => setRedirectHosts(event.target.value)}
+ disabled={isLoading || isMutating}
+ className="min-h-24"
+ />
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor="google-app-origins">App Origins</Label>
+ <Textarea
+ id="google-app-origins"
+ value={appOrigins}
+ onChange={(event) => setAppOrigins(event.target.value)}
+ disabled={isLoading || isMutating}
+ className="min-h-24"
+ />
+ </div>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-3">
+ <Button
+ type="submit"
+ disabled={isLoading || isMutating || !encryptionEnabled}
+ >
+ {saveMutation.isPending ? "Saving..." : "Save Configuration"}
+ </Button>
+ {canClear && (
+ <ClearCredentialDialog
+ label="Clear Configuration"
+ title="Clear Google OAuth configuration?"
+ description="Google OAuth will fall back to environment configuration if it is available."
+ disabled={isLoading || isMutating}
+ isPending={clearMutation.isPending}
+ onConfirm={() => clearMutation.mutate()}
+ />
+ )}
+ <span className="text-sm text-muted-foreground">
+ Status:{" "}
+ {config?.configured
+ ? `Configured via ${config.source}`
+ : "Not configured"}
+ </span>
+ </div>
+ </form>
+ );
+}
diff --git a/skyvern-frontend/src/router.tsx b/skyvern-frontend/src/router.tsx
index 1a1184c4d..297d896f9 100644
--- a/skyvern-frontend/src/router.tsx
+++ b/skyvern-frontend/src/router.tsx
@@ -38,7 +38,8 @@ import { DebugStoreProvider } from "@/store/DebugStoreContext";
import { BrowserProfileDetailPage } from "@/routes/browserProfiles/BrowserProfileDetailPage.tsx";
import { BrowserProfilesPage } from "@/routes/browserProfiles/BrowserProfilesPage.tsx";
import { CredentialsPage } from "@/routes/credentials/CredentialsPage.tsx";
-import { IntegrationsUnavailable } from "@/routes/integrations/IntegrationsUnavailable";
+import { GoogleOAuthCallback } from "@/routes/integrations/GoogleOAuthCallback";
+import { Integrations } from "@/routes/integrations/Integrations";
import { RecipeComingSoonPage } from "@/routes/recipes/RecipeComingSoonPage";
import { RecipesPage } from "@/routes/recipes/RecipesPage";
import { RunRouter } from "@/routes/runs/RunRouter";
@@ -398,7 +399,11 @@ const router = createBrowserRouter([
children: [
{
index: true,
- element: <IntegrationsUnavailable />,
+ element: <Integrations />,
+ },
+ {
+ path: "google/callback",
+ element: <GoogleOAuthCallback />,
},
],
},
diff --git a/skyvern-frontend/src/routes/integrations/GoogleOAuthCallback.tsx b/skyvern-frontend/src/routes/integrations/GoogleOAuthCallback.tsx
new file mode 100644
index 000000000..330f1a534
--- /dev/null
+++ b/skyvern-frontend/src/routes/integrations/GoogleOAuthCallback.tsx
@@ -0,0 +1,65 @@
+import { useEffect, useRef } from "react";
+import { useNavigate, useSearchParams } from "react-router-dom";
+import { useQueryClient } from "@tanstack/react-query";
+import { useGoogleOAuthCredentials } from "@/hooks/useGoogleOAuthCredentials";
+import { useToast } from "@/components/ui/use-toast";
+import { clearStoredGoogleOAuthIntegrationIdForState } from "./googleOAuth";
+
+function GoogleOAuthCallback() {
+ const [searchParams] = useSearchParams();
+ const navigate = useNavigate();
+ const queryClient = useQueryClient();
+ const { submitOAuthCallbackAsync } = useGoogleOAuthCredentials();
+ const { toast } = useToast();
+ const ranRef = useRef(false);
+
+ useEffect(() => {
+ if (ranRef.current) return;
+ ranRef.current = true;
+
+ const finish = async () => {
+ const error = searchParams.get("error");
+ const code = searchParams.get("code");
+ const state = searchParams.get("state");
+
+ if (error) {
+ toast({
+ title: "Google connection cancelled",
+ description: error,
+ variant: "destructive",
+ });
+ navigate("/integrations", { replace: true });
+ return;
+ }
+ if (!code || !state) {
+ toast({
+ title: "Missing OAuth parameters",
+ description: "The callback URL was missing a code or state value.",
+ variant: "destructive",
+ });
+ navigate("/integrations", { replace: true });
+ return;
+ }
+
+ try {
+ await submitOAuthCallbackAsync({ code, state });
+ queryClient.invalidateQueries({ queryKey: ["googleOAuthCredentials"] });
+ } finally {
+ clearStoredGoogleOAuthIntegrationIdForState(state);
+ navigate("/integrations", { replace: true });
+ }
+ };
+
+ void finish();
+ }, [searchParams, navigate, queryClient, submitOAuthCallbackAsync, toast]);
+
+ return (
+ <div className="flex min-h-[40vh] items-center justify-center">
+ <p className="text-sm text-muted-foreground">
+ Finishing Google connection...
+ </p>
+ </div>
+ );
+}
+
+export { GoogleOAuthCallback };
diff --git a/skyvern-frontend/src/routes/integrations/Integrations.tsx b/skyvern-frontend/src/routes/integrations/Integrations.tsx
new file mode 100644
index 000000000..adf04cb37
--- /dev/null
+++ b/skyvern-frontend/src/routes/integrations/Integrations.tsx
@@ -0,0 +1,228 @@
+import { useState } from "react";
+import { ExternalLinkIcon, ReloadIcon, TrashIcon } from "@radix-ui/react-icons";
+import { GoogleOAuthClientConfigForm } from "@/components/GoogleOAuthClientConfigForm";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import {
+ hasGoogleOAuthCredentialScopes,
+ isGoogleOAuthCredentialActive,
+ useGoogleOAuthCredentials,
+} from "@/hooks/useGoogleOAuthCredentials";
+import {
+ GOOGLE_DRIVE_REQUIRED_SCOPES,
+ GOOGLE_GMAIL_REQUIRED_SCOPES,
+ GOOGLE_SHEETS_REQUIRED_SCOPES,
+} from "@/util/googleScopes";
+import {
+ buildGoogleOAuthRedirectUri,
+ getGoogleOAuthAppOrigin,
+ storeGoogleOAuthIntegrationIdForState,
+} from "./googleOAuth";
+
+const integrations = [
+ {
+ id: "google_sheets",
+ title: "Google Sheets",
+ description: "Read, append, and update spreadsheet data from workflows.",
+ scopeProfile: "google_sheets",
+ requiredScopes: GOOGLE_SHEETS_REQUIRED_SCOPES,
+ },
+ {
+ id: "gmail",
+ title: "Gmail",
+ description: "Read verification emails for OTP polling.",
+ scopeProfile: "gmail",
+ requiredScopes: GOOGLE_GMAIL_REQUIRED_SCOPES,
+ },
+ {
+ id: "google_drive",
+ title: "Google Drive",
+ description: "Upload generated files to connected Drive accounts.",
+ scopeProfile: "google_drive",
+ requiredScopes: GOOGLE_DRIVE_REQUIRED_SCOPES,
+ },
+] as const;
+
+function Integrations() {
+ const [connectingId, setConnectingId] = useState<string | null>(null);
+ const {
+ credentials,
+ isFetching,
+ startAuthorize,
+ isStartingAuthorize,
+ deleteCredential,
+ isDeletingCredential,
+ } = useGoogleOAuthCredentials();
+
+ const connect = async (integration: (typeof integrations)[number]) => {
+ setConnectingId(integration.id);
+ try {
+ const response = await startAuthorize({
+ redirect_uri: buildGoogleOAuthRedirectUri(),
+ app_origin: getGoogleOAuthAppOrigin(),
+ credential_name: integration.title,
+ scope_profile: integration.scopeProfile,
+ });
+ storeGoogleOAuthIntegrationIdForState(response.state, integration.id);
+ window.location.assign(response.authorize_url);
+ } finally {
+ setConnectingId(null);
+ }
+ };
+
+ return (
+ <div className="mx-auto flex max-w-5xl flex-col gap-6 p-6">
+ <Card>
+ <CardHeader className="border-b-2">
+ <CardTitle className="text-lg">Google Integrations</CardTitle>
+ <CardDescription>
+ Connect Google accounts for Sheets, Gmail, and Drive workflows.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="p-6">
+ <GoogleOAuthClientConfigForm />
+ </CardContent>
+ </Card>
+
+ <div className="grid gap-4 md:grid-cols-3">
+ {integrations.map((integration) => {
+ const matchingCredentials = credentials.filter((credential) =>
+ hasGoogleOAuthCredentialScopes(
+ credential,
+ Array.from(integration.requiredScopes),
+ ),
+ );
+ const activeCount = matchingCredentials.filter(
+ isGoogleOAuthCredentialActive,
+ ).length;
+ return (
+ <Card key={integration.id}>
+ <CardHeader>
+ <CardTitle className="text-base">{integration.title}</CardTitle>
+ <CardDescription>{integration.description}</CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <div className="text-sm text-muted-foreground">
+ {activeCount} active connection{activeCount === 1 ? "" : "s"}
+ </div>
+ <Button
+ type="button"
+ className="w-full gap-2"
+ disabled={isStartingAuthorize}
+ onClick={() => void connect(integration)}
+ >
+ {connectingId === integration.id ? (
+ <ReloadIcon className="h-4 w-4 animate-spin" />
+ ) : (
+ <ExternalLinkIcon className="h-4 w-4" />
+ )}
+ Connect
+ </Button>
+ </CardContent>
+ </Card>
+ );
+ })}
+ </div>
+
+ <Card>
+ <CardHeader className="border-b-2">
+ <CardTitle className="text-lg">Connected Google Accounts</CardTitle>
+ <CardDescription>
+ Accounts listed here are available to Google workflow blocks.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="p-0">
+ {credentials.length === 0 ? (
+ <div className="p-6 text-sm text-muted-foreground">
+ {isFetching
+ ? "Loading connections..."
+ : "No Google accounts connected"}
+ </div>
+ ) : (
+ <div className="divide-y">
+ {credentials.map((credential) => (
+ <div
+ key={credential.id}
+ className="flex items-center justify-between gap-4 p-4"
+ >
+ <div className="min-w-0">
+ <div className="truncate text-sm font-medium">
+ {credential.credential_name}
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {isGoogleOAuthCredentialActive(credential)
+ ? "Active"
+ : "Needs reconnect"}
+ </div>
+ </div>
+ <Dialog>
+ <DialogTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="gap-2"
+ disabled={isDeletingCredential}
+ >
+ <TrashIcon className="h-4 w-4" />
+ Disconnect
+ </Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogTitle>Disconnect Google account?</DialogTitle>
+ <DialogDescription>
+ Workflows using{" "}
+ <span className="font-medium text-foreground">
+ {credential.credential_name}
+ </span>{" "}
+ will lose access to this Google account.
+ </DialogDescription>
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button
+ type="button"
+ variant="secondary"
+ disabled={isDeletingCredential}
+ >
+ Cancel
+ </Button>
+ </DialogClose>
+ <DialogClose asChild>
+ <Button
+ type="button"
+ variant="destructive"
+ disabled={isDeletingCredential}
+ onClick={() => deleteCredential(credential.id)}
+ >
+ Disconnect
+ </Button>
+ </DialogClose>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ ))}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
+
+export { Integrations };
diff --git a/skyvern-frontend/src/routes/integrations/IntegrationsUnavailable.tsx b/skyvern-frontend/src/routes/integrations/IntegrationsUnavailable.tsx
deleted file mode 100644
index 91576f50e..000000000
--- a/skyvern-frontend/src/routes/integrations/IntegrationsUnavailable.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card";
-
-function IntegrationsUnavailable() {
- return (
- <div className="mx-auto max-w-2xl p-6">
- <Card>
- <CardHeader>
- <CardTitle>Integrations</CardTitle>
- <CardDescription>
- Third-party integrations are available in Skyvern Cloud.
- </CardDescription>
- </CardHeader>
- <CardContent className="text-sm text-slate-400">
- <p>
- Connect your Google account and other providers by signing up at{" "}
- <a
- href="https://app.skyvern.com"
- target="_blank"
- rel="noopener noreferrer"
- className="text-slate-200 underline hover:text-slate-100"
- >
- app.skyvern.com
- </a>
- .
- </p>
- </CardContent>
- </Card>
- </div>
- );
-}
-
-export { IntegrationsUnavailable };
diff --git a/skyvern-frontend/src/routes/integrations/googleOAuth.ts b/skyvern-frontend/src/routes/integrations/googleOAuth.ts
new file mode 100644
index 000000000..378573615
--- /dev/null
+++ b/skyvern-frontend/src/routes/integrations/googleOAuth.ts
@@ -0,0 +1,35 @@
+export const GOOGLE_OAUTH_REDIRECT_PATH = "/integrations/google/callback";
+
+const INTEGRATION_STORAGE_PREFIX = "skyvern:google-oauth-integration:";
+
+export function buildGoogleOAuthRedirectUri(): string {
+ return `${window.location.origin}${GOOGLE_OAUTH_REDIRECT_PATH}`;
+}
+
+export function getGoogleOAuthAppOrigin(): string {
+ return window.location.origin;
+}
+
+export function storeGoogleOAuthIntegrationIdForState(
+ state: string,
+ integrationId: string,
+): void {
+ try {
+ window.sessionStorage.setItem(
+ `${INTEGRATION_STORAGE_PREFIX}${state}`,
+ integrationId,
+ );
+ } catch {
+ // Best effort; callback handling does not depend on this metadata.
+ }
+}
+
+export function clearStoredGoogleOAuthIntegrationIdForState(
+ state: string,
+): void {
+ try {
+ window.sessionStorage.removeItem(`${INTEGRATION_STORAGE_PREFIX}${state}`);
+ } catch {
+ // Best effort cleanup.
+ }
+}
diff --git a/skyvern-frontend/src/routes/settings/Settings.tsx b/skyvern-frontend/src/routes/settings/Settings.tsx
index 3a42b54a5..24815d2fd 100644
--- a/skyvern-frontend/src/routes/settings/Settings.tsx
+++ b/skyvern-frontend/src/routes/settings/Settings.tsx
@@ -21,6 +21,7 @@ import { BitwardenCredentialForm } from "@/components/BitwardenCredentialForm";
import { AzureClientSecretCredentialTokenForm } from "@/components/AzureClientSecretCredentialTokenForm";
import { CustomCredentialServiceConfigForm } from "@/components/CustomCredentialServiceConfigForm";
import { CustomLLMConfigForm } from "@/components/CustomLLMConfigForm";
+import { GoogleOAuthClientConfigForm } from "@/components/GoogleOAuthClientConfigForm";
import { useVersionQuery } from "@/hooks/useVersionQuery";
import { formatVersion, getAppVersion } from "@/util/version";
@@ -126,6 +127,17 @@ function Settings() {
<CustomCredentialServiceConfigForm />
</CardContent>
</Card>
+ <Card>
+ <CardHeader className="border-b-2">
+ <CardTitle className="text-lg">Google OAuth</CardTitle>
+ <CardDescription>
+ Configure the OAuth client used by Google integrations.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="p-8">
+ <GoogleOAuthClientConfigForm />
+ </CardContent>
+ </Card>
<Card>
<CardHeader className="border-b-2">
<CardTitle className="text-lg">Custom LLMs</CardTitle>
diff --git a/skyvern/config.py b/skyvern/config.py
index a2d4900e8..e05234200 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -724,6 +724,9 @@ class Settings(BaseSettings):
# Fails closed: an empty list rejects every app_origin, so self-hosted operators
# who want to use the bounce-back flow must populate this with at least one entry.
GOOGLE_OAUTH_APP_ORIGINS: list[str] = Field(default_factory=list)
+ # OSS/self-hosted instances can store the Google OAuth client config per org
+ # through Settings. Skyvern Cloud keeps the centrally managed OAuth client.
+ ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG: bool = True
# Google Sheets API runtime tuning
GOOGLE_SHEETS_API_TIMEOUT_SECONDS: float = 30.0
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index f493edadb..655eef175 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -6,7 +6,7 @@ import time
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any, Dict, List
import aiohttp
@@ -39,7 +39,13 @@ from skyvern.forge.sdk.db.agent_db import AgentDB
from skyvern.forge.sdk.models import Step, StepStatus
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.schemas.tasks import Task, TaskStatus
-from skyvern.forge.sdk.services import google_drive_service, google_oauth_service, sftp_service
+from skyvern.forge.sdk.services import (
+ google_drive_service,
+ google_gmail_service,
+ google_oauth_service,
+ google_sheets_service,
+ sftp_service,
+)
from skyvern.forge.sdk.services.credentials import AuthenticatorTotpParseResult
from skyvern.forge.sdk.trace import traced
from skyvern.forge.sdk.workflow.models.block import BlockTypeVar
@@ -63,6 +69,9 @@ LOG = structlog.get_logger()
# Playwright's always-on ffmpeg VP8 encoder scales CPU with pixel count; 720p is the
# legibility / CPU tradeoff point that the BROWSER_RECORDING_720P flag opts a run into.
RECORDING_VIDEO_SIZE_720P: dict[str, int] = {"width": 1280, "height": 720}
+GMAIL_OTP_CREDENTIAL_REFRESH_INTERVAL_SECONDS = 30
+GMAIL_OTP_MAX_RESULTS = 5
+GMAIL_OTP_SEARCH_INTERVAL_SECONDS = 30
_LLM_CALL_TIMEOUT_SECONDS = 30 # 30s
USELESS_SHAPE_ATTRIBUTE = [SKYVERN_ID_ATTR, "id", "aria-describedby"]
@@ -1196,7 +1205,7 @@ class AgentFunction:
organization_id=organization_id,
credential_id=credential_id,
)
- return await google_oauth_service.access_token_from_secrets(secrets)
+ return await google_oauth_service.access_token_from_secrets(secrets, organization_id=organization_id)
except google_oauth_service.EncryptionNotConfiguredError:
LOG.error(
"Google credential encryption is not configured; operators must enable ENABLE_ENCRYPTION",
@@ -1236,7 +1245,7 @@ class AgentFunction:
required_scopes=required_scopes,
)
return None
- return await google_oauth_service.credentials_from_secrets(secrets)
+ return await google_oauth_service.credentials_from_secrets(secrets, organization_id=organization_id)
except google_oauth_service.EncryptionNotConfiguredError:
LOG.error(
"Google credential encryption is not configured; operators must enable ENABLE_ENCRYPTION",
@@ -1262,7 +1271,103 @@ class AgentFunction:
created_after: datetime | None = None,
context: GmailOTPVerificationContext | None = None,
) -> "OTPValue | None":
- """Cloud-only Gmail OTP lookup hook. OSS builds do not read inboxes."""
+ """Find an OTP in connected Gmail inboxes for a single polling window."""
+ if "@" not in totp_identifier:
+ return None
+
+ from skyvern.services.otp_service import parse_otp_login
+
+ lookup_context = context or GmailOTPVerificationContext()
+ now = datetime.now(timezone.utc)
+ required_scopes = list(google_oauth_service.GOOGLE_GMAIL_SCOPES)
+ credential_cache_age = (
+ (now - lookup_context.credential_ids_loaded_at).total_seconds()
+ if lookup_context.credential_ids_loaded_at
+ else None
+ )
+ if (
+ lookup_context.credential_ids is None
+ or credential_cache_age is None
+ or credential_cache_age >= GMAIL_OTP_CREDENTIAL_REFRESH_INTERVAL_SECONDS
+ ):
+ try:
+ lookup_context.credential_ids = [
+ credential.id
+ for credential in await google_oauth_service.get_credentials_for_org(organization_id)
+ if google_oauth_service.has_required_scopes(credential.scopes_granted, required_scopes)
+ ]
+ lookup_context.credential_ids_loaded_at = now
+ except Exception:
+ LOG.warning("Failed to list Google OAuth credentials for Gmail OTP lookup", exc_info=True)
+ return None
+
+ async with httpx.AsyncClient(timeout=20.0) as gmail_client:
+ for credential_id in lookup_context.credential_ids or []:
+ last_searched_at = lookup_context.last_searched_at_by_credential.get(credential_id)
+ if last_searched_at and (now - last_searched_at).total_seconds() < GMAIL_OTP_SEARCH_INTERVAL_SECONDS:
+ continue
+ lookup_context.last_searched_at_by_credential[credential_id] = now
+ try:
+ google_credentials = await self.get_google_workspace_credentials(
+ organization_id=organization_id,
+ credential_id=credential_id,
+ required_scopes=required_scopes,
+ )
+ if not google_credentials or not google_credentials.token:
+ continue
+ candidates = await google_gmail_service.search_recent_otp_messages(
+ access_token=google_credentials.token,
+ totp_identifier=totp_identifier,
+ created_after=created_after,
+ max_results=GMAIL_OTP_MAX_RESULTS,
+ client=gmail_client,
+ )
+ except google_gmail_service.GmailAPIError as exc:
+ LOG.warning(
+ "Gmail OTP lookup failed",
+ credential_id=credential_id,
+ status=exc.status,
+ code=exc.code,
+ )
+ continue
+ except Exception:
+ LOG.warning(
+ "Unexpected Gmail OTP lookup failure",
+ credential_id=credential_id,
+ exc_info=True,
+ )
+ continue
+
+ for candidate in candidates:
+ if lookup_context.has_seen_message_id(candidate.message_id):
+ continue
+ try:
+ otp_value = await parse_otp_login(candidate.content, organization_id)
+ except Exception:
+ LOG.warning(
+ "Failed to parse Gmail OTP candidate",
+ credential_id=credential_id,
+ message_id=candidate.message_id,
+ exc_info=True,
+ )
+ continue
+ lookup_context.remember_message_id(candidate.message_id)
+ if otp_value:
+ try:
+ await app.DATABASE.otp.create_otp_code(
+ organization_id,
+ totp_identifier,
+ otp_value.value,
+ otp_value.value,
+ otp_value.get_otp_type(),
+ workflow_id=workflow_id,
+ workflow_run_id=workflow_run_id,
+ source="gmail",
+ )
+ except Exception:
+ LOG.warning("Failed to persist Gmail OTP code", credential_id=credential_id, exc_info=True)
+ return otp_value
+
return None
async def ensure_sheet_tab(
@@ -1272,14 +1377,18 @@ class AgentFunction:
spreadsheet_id: str,
title: str,
) -> int | None:
- """Ensure a sheet tab with the given title exists in the spreadsheet.
-
- Returns the sheet_id of the newly created tab, or None if the caller
- should fall back to its own lookup (e.g. a concurrent creator won the
- race). OSS base is a no-op that returns None; cloud override calls the
- Sheets v4 batchUpdate addSheet endpoint.
- """
- return None
+ """Ensure a sheet tab with the given title exists in the spreadsheet."""
+ try:
+ tab = await google_sheets_service.create_sheet_tab(
+ access_token=access_token,
+ spreadsheet_id=spreadsheet_id,
+ title=title,
+ )
+ return tab.sheet_id
+ except google_sheets_service.GoogleSheetsAPIError as exc:
+ if exc.status == 400 and exc.code in {"duplicate", "duplicateSheetTitle"}:
+ return None
+ raise
async def google_sheets_values_get(
self,
@@ -1289,8 +1398,12 @@ class AgentFunction:
ranges: str,
fields: str | None = None,
) -> dict[str, Any] | None:
- """Read ranges from a spreadsheet via spreadsheets.get. OSS no-op."""
- return None
+ return await google_sheets_service.values_get(
+ access_token=access_token,
+ spreadsheet_id=spreadsheet_id,
+ ranges=ranges,
+ fields=fields,
+ )
async def google_sheets_values_append(
self,
@@ -1300,8 +1413,12 @@ class AgentFunction:
range_: str,
values: list[list[Any]],
) -> dict[str, Any] | None:
- """Append rows via spreadsheets.values.append. OSS no-op."""
- return None
+ return await google_sheets_service.values_append(
+ access_token=access_token,
+ spreadsheet_id=spreadsheet_id,
+ range_=range_,
+ values=values,
+ )
async def google_sheets_values_update(
self,
@@ -1311,8 +1428,12 @@ class AgentFunction:
range_: str,
values: list[list[Any]],
) -> dict[str, Any] | None:
- """Update rows via spreadsheets.values.update. OSS no-op."""
- return None
+ return await google_sheets_service.values_update(
+ access_token=access_token,
+ spreadsheet_id=spreadsheet_id,
+ range_=range_,
+ values=values,
+ )
async def google_sheets_batch_update(
self,
@@ -1321,8 +1442,11 @@ class AgentFunction:
spreadsheet_id: str,
requests: list[dict[str, Any]],
) -> dict[str, Any] | None:
- """Apply a batchUpdate to a spreadsheet. OSS no-op."""
- return None
+ return await google_sheets_service.batch_update(
+ access_token=access_token,
+ spreadsheet_id=spreadsheet_id,
+ requests=requests,
+ )
async def google_sheets_get_sheet_id(
self,
@@ -1331,8 +1455,11 @@ class AgentFunction:
spreadsheet_id: str,
sheet_title: str,
) -> int | None:
- """Resolve a tab title to its numeric sheetId. OSS no-op."""
- return None
+ return await google_sheets_service.get_sheet_id_by_title(
+ access_token=access_token,
+ spreadsheet_id=spreadsheet_id,
+ sheet_title=sheet_title,
+ )
async def google_sheets_get_grid_properties(
self,
@@ -1341,8 +1468,11 @@ class AgentFunction:
spreadsheet_id: str,
sheet_title: str,
) -> Any | None:
- """Return the named tab's grid dimensions (sheet_id, column_count, row_count). OSS no-op."""
- return None
+ return await google_sheets_service.get_sheet_grid_properties(
+ access_token=access_token,
+ spreadsheet_id=spreadsheet_id,
+ sheet_title=sheet_title,
+ )
async def google_sheets_get_grid_properties_by_id(
self,
@@ -1351,8 +1481,11 @@ class AgentFunction:
spreadsheet_id: str,
sheet_id: int,
) -> Any | None:
- """Return grid dimensions for a sheet matched by numeric sheetId. OSS no-op."""
- return None
+ return await google_sheets_service.get_sheet_grid_properties_by_id(
+ access_token=access_token,
+ spreadsheet_id=spreadsheet_id,
+ sheet_id=sheet_id,
+ )
async def generate_async_operations(
self,
diff --git a/skyvern/forge/request_logging.py b/skyvern/forge/request_logging.py
index f96db6a60..f9ee1ee65 100644
--- a/skyvern/forge/request_logging.py
+++ b/skyvern/forge/request_logging.py
@@ -27,6 +27,10 @@ _SENSITIVE_ENDPOINTS = {
"POST /v1/credentials/totp",
"POST /api/v1/totp",
"GET /v1/credentials/totp",
+ "PUT /v1/google/oauth/config",
+ "PUT /api/v1/google/oauth/config",
+ "POST /v1/google/oauth/callback",
+ "POST /api/v1/google/oauth/callback",
}
_MAX_BODY_LENGTH = 1000
_READ_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
diff --git a/skyvern/forge/sdk/db/enums.py b/skyvern/forge/sdk/db/enums.py
index 40c9bc984..e332f01f7 100644
--- a/skyvern/forge/sdk/db/enums.py
+++ b/skyvern/forge/sdk/db/enums.py
@@ -8,6 +8,7 @@ class OrganizationAuthTokenType(StrEnum):
custom_credential_service = "custom_credential_service"
bitwarden_credential = "bitwarden_credential"
custom_llm = "custom_llm"
+ google_oauth_client_config = "google_oauth_client_config"
class TaskType(StrEnum):
diff --git a/skyvern/forge/sdk/db/repositories/organizations.py b/skyvern/forge/sdk/db/repositories/organizations.py
index 003a8660e..38c10c5ca 100644
--- a/skyvern/forge/sdk/db/repositories/organizations.py
+++ b/skyvern/forge/sdk/db/repositories/organizations.py
@@ -193,7 +193,13 @@ class OrganizationsRepository(BaseRepository):
async def get_valid_org_auth_token(
self,
organization_id: str,
- token_type: Literal["api", "onepassword_service_account", "custom_credential_service", "custom_llm"],
+ token_type: Literal[
+ "api",
+ "onepassword_service_account",
+ "custom_credential_service",
+ "custom_llm",
+ "google_oauth_client_config",
+ ],
) -> OrganizationAuthToken | None: ...
@overload
@@ -221,6 +227,7 @@ class OrganizationsRepository(BaseRepository):
"bitwarden_credential",
"custom_credential_service",
"custom_llm",
+ "google_oauth_client_config",
],
) -> OrganizationAuthToken | AzureOrganizationAuthToken | BitwardenOrganizationAuthToken | None:
async with self.Session() as session:
diff --git a/skyvern/forge/sdk/routes/google_oauth.py b/skyvern/forge/sdk/routes/google_oauth.py
index c987ee552..c9d37888c 100644
--- a/skyvern/forge/sdk/routes/google_oauth.py
+++ b/skyvern/forge/sdk/routes/google_oauth.py
@@ -11,19 +11,28 @@ from skyvern.forge.sdk.schemas.google_oauth import (
CreateGoogleOAuthAuthorizeRequest,
CreateGoogleOAuthCallbackRequest,
GoogleOAuthAuthorizeResponse,
+ GoogleOAuthClientConfig,
+ GoogleOAuthClientConfigResponse,
GoogleOAuthCredentialListResponse,
GoogleOAuthCredentialResponse,
+ UpdateGoogleOAuthClientConfigRequest,
UpdateGoogleOAuthCredentialRequest,
)
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.services import google_oauth_service, org_auth_service
from skyvern.forge.sdk.services.google_oauth_service import InvalidAppOriginError
+from skyvern.forge.sdk.settings_manager import SettingsManager
LOG = structlog.get_logger()
google_oauth_router = APIRouter()
+def _require_organization_client_config_enabled() -> None:
+ if not SettingsManager.get_settings().ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG:
+ raise HTTPException(status_code=404, detail="Google OAuth client config is not available")
+
+
def _require_scopes_from_token(token_data: dict) -> list[str]:
"""Extract the granted scopes from Google's token response, failing closed on empty/missing"""
raw = token_data.get("scope")
@@ -69,6 +78,8 @@ async def google_oauth_authorize(
raise HTTPException(status_code=400, detail=str(exc))
except google_oauth_service.InvalidRedirectURIError as exc:
raise HTTPException(status_code=400, detail=str(exc))
+ except google_oauth_service.OrganizationClientConfigUnavailableError as exc:
+ raise HTTPException(status_code=503, detail=str(exc))
except google_oauth_service.EncryptionNotConfiguredError as exc:
raise HTTPException(status_code=503, detail=str(exc))
except ValueError as exc:
@@ -100,7 +111,10 @@ async def google_oauth_callback(
code=request.code,
redirect_uri=context.consent_redirect_uri,
code_verifier=context.consent_code_verifier,
+ organization_id=current_org.organization_id,
)
+ except google_oauth_service.OrganizationClientConfigUnavailableError as exc:
+ raise HTTPException(status_code=503, detail=str(exc))
except ValueError as exc:
LOG.exception("Google OAuth client credentials not configured")
raise HTTPException(status_code=503, detail=str(exc))
@@ -146,6 +160,70 @@ async def google_oauth_callback(
return GoogleOAuthCredentialResponse(credential=credential, app_origin=context.consent_app_origin)
+@google_oauth_router.get("/oauth/config")
+async def get_google_oauth_client_config(
+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],
+) -> GoogleOAuthClientConfigResponse:
+ """Return the effective Google OAuth client configuration without the client secret."""
+ _require_organization_client_config_enabled()
+ try:
+ resolved = await google_oauth_service.resolve_client_config(current_org.organization_id)
+ except google_oauth_service.OrganizationClientConfigUnavailableError as exc:
+ raise HTTPException(status_code=503, detail=str(exc))
+ return GoogleOAuthClientConfigResponse(config=resolved.safe())
+
+
+@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)],
+) -> GoogleOAuthClientConfigResponse:
+ """Store an organization-level Google OAuth client configuration."""
+ _require_organization_client_config_enabled()
+ try:
+ resolved = await google_oauth_service.resolve_client_config(current_org.organization_id)
+ except google_oauth_service.OrganizationClientConfigUnavailableError:
+ resolved = None
+ client_secret = request.client_secret
+ if (
+ client_secret is None
+ and resolved
+ and resolved.source == "organization"
+ and resolved.config
+ and resolved.config.client_id == request.client_id
+ ):
+ client_secret = resolved.config.client_secret
+ if not client_secret:
+ raise HTTPException(status_code=400, detail="Google OAuth client secret is required")
+
+ config = GoogleOAuthClientConfig(
+ client_id=request.client_id,
+ client_secret=client_secret,
+ redirect_hosts=request.redirect_hosts,
+ app_origins=request.app_origins,
+ )
+ try:
+ saved = await google_oauth_service.save_client_config(current_org.organization_id, config)
+ except google_oauth_service.OrganizationGoogleOAuthConfigDisabledError as exc:
+ raise HTTPException(status_code=404, detail=str(exc))
+ except google_oauth_service.EncryptionNotConfiguredError as exc:
+ raise HTTPException(status_code=503, detail=str(exc))
+ return GoogleOAuthClientConfigResponse(config=saved.safe())
+
+
+@google_oauth_router.delete("/oauth/config")
+async def delete_google_oauth_client_config(
+ current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],
+) -> dict[str, bool]:
+ """Clear the organization-level Google OAuth client config and fall back to environment config."""
+ _require_organization_client_config_enabled()
+ try:
+ await google_oauth_service.delete_client_config(current_org.organization_id)
+ except google_oauth_service.OrganizationGoogleOAuthConfigDisabledError as exc:
+ raise HTTPException(status_code=404, detail=str(exc))
+ return {"success": True}
+
+
@google_oauth_router.get("/oauth/credentials")
async def list_google_oauth_credentials(
current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],
diff --git a/skyvern/forge/sdk/routes/google_sheets.py b/skyvern/forge/sdk/routes/google_sheets.py
index d9eed97f0..024541366 100644
--- a/skyvern/forge/sdk/routes/google_sheets.py
+++ b/skyvern/forge/sdk/routes/google_sheets.py
@@ -51,7 +51,7 @@ async def _mint_access_token(organization_id: str, credential_id: str) -> str:
},
)
try:
- return await google_oauth_service.access_token_from_secrets(secrets)
+ return await google_oauth_service.access_token_from_secrets(secrets, organization_id=organization_id)
except google_oauth_service.MissingAccessTokenError as exc:
# Google rejected the refresh token (invalid_grant after revoke/expiry);
# only a fresh consent round can recover, so route to the reconnect flow.
diff --git a/skyvern/forge/sdk/schemas/google_oauth.py b/skyvern/forge/sdk/schemas/google_oauth.py
index 94a86cb41..e83d62587 100644
--- a/skyvern/forge/sdk/schemas/google_oauth.py
+++ b/skyvern/forge/sdk/schemas/google_oauth.py
@@ -4,6 +4,71 @@ from typing import Literal
from pydantic import BaseModel, Field, field_validator
+class GoogleOAuthClientConfig(BaseModel):
+ client_id: str = Field(..., min_length=1)
+ client_secret: str = Field(..., min_length=1)
+ redirect_hosts: list[str] = Field(default_factory=list)
+ app_origins: list[str] = Field(default_factory=list)
+
+ @field_validator("client_id", "client_secret")
+ @classmethod
+ def _strip_required_string(cls, value: str) -> str:
+ stripped = value.strip()
+ if not stripped:
+ raise ValueError("value must not be blank")
+ return stripped
+
+ @field_validator("redirect_hosts", "app_origins")
+ @classmethod
+ def _strip_list_values(cls, values: list[str]) -> list[str]:
+ return [item.strip() for item in values if item and item.strip()]
+
+
+class GoogleOAuthClientConfigSafe(BaseModel):
+ client_id: str | None = None
+ redirect_hosts: list[str] = Field(default_factory=list)
+ app_origins: list[str] = Field(default_factory=list)
+ client_secret_configured: bool = False
+ configured: bool = False
+ source: str = "missing"
+ encryption_enabled: bool = False
+
+
+class GoogleOAuthClientConfigResponse(BaseModel):
+ config: GoogleOAuthClientConfigSafe
+
+
+class UpdateGoogleOAuthClientConfigRequest(BaseModel):
+ client_id: str = Field(..., min_length=1)
+ client_secret: str | None = Field(
+ default=None,
+ description="Google OAuth client secret. Omit or leave blank to preserve the current organization-level secret.",
+ )
+ redirect_hosts: list[str] = Field(default_factory=list)
+ app_origins: list[str] = Field(default_factory=list)
+
+ @field_validator("client_id")
+ @classmethod
+ def _strip_client_id(cls, value: str) -> str:
+ stripped = value.strip()
+ if not stripped:
+ raise ValueError("client_id must not be blank")
+ return stripped
+
+ @field_validator("client_secret")
+ @classmethod
+ def _strip_optional_secret(cls, value: str | None) -> str | None:
+ if value is None:
+ return None
+ stripped = value.strip()
+ return stripped or None
+
+ @field_validator("redirect_hosts", "app_origins")
+ @classmethod
+ def _strip_update_list_values(cls, values: list[str]) -> list[str]:
+ return [item.strip() for item in values if item and item.strip()]
+
+
class GoogleOAuthCredentialBase(BaseModel):
id: str
organization_id: str
diff --git a/skyvern/forge/sdk/services/google_oauth_service.py b/skyvern/forge/sdk/services/google_oauth_service.py
index 8fb8402b9..2e817c3c8 100644
--- a/skyvern/forge/sdk/services/google_oauth_service.py
+++ b/skyvern/forge/sdk/services/google_oauth_service.py
@@ -24,6 +24,7 @@ from google_auth_oauthlib.flow import Flow
from skyvern.config import settings
from skyvern.forge import app
+from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType
from skyvern.forge.sdk.db.id import generate_google_oauth_credential_id
# Lifecycle constants and InvalidConsentNonceError live on the repository (the DB owns
@@ -39,7 +40,12 @@ from skyvern.forge.sdk.db.repositories.google_oauth import ( # noqa: F401
)
from skyvern.forge.sdk.encrypt import encryptor
from skyvern.forge.sdk.encrypt.base import EncryptMethod
-from skyvern.forge.sdk.schemas.google_oauth import GoogleOAuthCredentialBase
+from skyvern.forge.sdk.schemas.google_oauth import (
+ GoogleOAuthClientConfig,
+ GoogleOAuthClientConfigSafe,
+ GoogleOAuthCredentialBase,
+)
+from skyvern.forge.sdk.settings_manager import SettingsManager
LOG = structlog.get_logger()
@@ -98,6 +104,14 @@ class UnsupportedScopeProfileError(ValueError):
"""Raised when a caller asks for an unsupported Google OAuth scope profile."""
+class OrganizationGoogleOAuthConfigDisabledError(RuntimeError):
+ """Raised when org-level Google OAuth client config is disabled for this deployment."""
+
+
+class OrganizationClientConfigUnavailableError(RuntimeError):
+ """Raised when a stored org OAuth client config exists (or cannot be ruled out) but cannot be loaded."""
+
+
@dataclass(frozen=True)
class GoogleCredentialSecrets:
"""Decrypted credential material needed to mint an access token."""
@@ -106,6 +120,23 @@ class GoogleCredentialSecrets:
scopes: list[str] = field(default_factory=list)
+@dataclass(frozen=True)
+class GoogleOAuthClientConfigResolution:
+ config: GoogleOAuthClientConfig | None
+ source: str
+
+ def safe(self) -> GoogleOAuthClientConfigSafe:
+ return GoogleOAuthClientConfigSafe(
+ client_id=self.config.client_id if self.config else None,
+ redirect_hosts=list(self.config.redirect_hosts) if self.config else [],
+ app_origins=list(self.config.app_origins) if self.config else [],
+ client_secret_configured=bool(self.config and self.config.client_secret),
+ configured=self.config is not None,
+ source=self.source,
+ encryption_enabled=settings.ENABLE_ENCRYPTION,
+ )
+
+
def _require_encryption() -> None:
"""Google credentials must be encrypted at rest; refuse to write them in plaintext."""
if not settings.ENABLE_ENCRYPTION:
@@ -115,9 +146,103 @@ def _require_encryption() -> None:
)
-def _require_client_credentials() -> tuple[str, str]:
- client_id = settings.GOOGLE_OAUTH_CLIENT_ID
- client_secret = settings.GOOGLE_OAUTH_CLIENT_SECRET
+def _settings_client_config() -> GoogleOAuthClientConfig | None:
+ if not settings.GOOGLE_OAUTH_CLIENT_ID or not settings.GOOGLE_OAUTH_CLIENT_SECRET:
+ return None
+ return GoogleOAuthClientConfig(
+ client_id=settings.GOOGLE_OAUTH_CLIENT_ID,
+ client_secret=settings.GOOGLE_OAUTH_CLIENT_SECRET,
+ redirect_hosts=list(settings.GOOGLE_OAUTH_REDIRECT_HOSTS),
+ app_origins=list(settings.GOOGLE_OAUTH_APP_ORIGINS),
+ )
+
+
+def _organization_client_config_enabled() -> bool:
+ return SettingsManager.get_settings().ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG
+
+
+def _require_organization_client_config_enabled() -> None:
+ if not _organization_client_config_enabled():
+ raise OrganizationGoogleOAuthConfigDisabledError("Organization Google OAuth client config is disabled")
+
+
+async def resolve_client_config(
+ organization_id: str | None = None,
+ *,
+ strict: bool = True,
+) -> GoogleOAuthClientConfigResolution:
+ if organization_id and _organization_client_config_enabled():
+ try:
+ token = await app.DATABASE.organizations.get_valid_org_auth_token(
+ organization_id=organization_id,
+ token_type=OrganizationAuthTokenType.google_oauth_client_config.value,
+ )
+ except Exception:
+ if strict:
+ LOG.warning("Failed to load organization Google OAuth client config", organization_id=organization_id)
+ raise OrganizationClientConfigUnavailableError(
+ "Failed to load the organization Google OAuth client config"
+ ) from None
+ LOG.warning(
+ "Failed to load organization Google OAuth client config; falling back to environment for token refresh",
+ organization_id=organization_id,
+ )
+ token = None
+ if token is not None:
+ if not token.token:
+ LOG.warning(
+ "Stored organization Google OAuth client config is empty",
+ organization_id=organization_id,
+ )
+ raise OrganizationClientConfigUnavailableError(
+ "Stored organization Google OAuth client config is invalid"
+ )
+ try:
+ return GoogleOAuthClientConfigResolution(
+ config=GoogleOAuthClientConfig.model_validate_json(token.token),
+ source="organization",
+ )
+ except Exception:
+ LOG.warning(
+ "Stored organization Google OAuth client config is invalid",
+ organization_id=organization_id,
+ )
+ raise OrganizationClientConfigUnavailableError(
+ "Stored organization Google OAuth client config is invalid"
+ ) from None
+
+ env_config = _settings_client_config()
+ return GoogleOAuthClientConfigResolution(config=env_config, source="environment" if env_config else "missing")
+
+
+async def save_client_config(
+ organization_id: str,
+ config: GoogleOAuthClientConfig,
+) -> GoogleOAuthClientConfigResolution:
+ _require_organization_client_config_enabled()
+ _require_encryption()
+ token_payload = config.model_dump_json()
+ await app.DATABASE.organizations.replace_org_auth_token(
+ organization_id=organization_id,
+ token_type=OrganizationAuthTokenType.google_oauth_client_config,
+ token=token_payload,
+ encrypted_method=EncryptMethod.AES,
+ )
+ return GoogleOAuthClientConfigResolution(config=config, source="organization")
+
+
+async def delete_client_config(organization_id: str) -> None:
+ _require_organization_client_config_enabled()
+ await app.DATABASE.organizations.invalidate_org_auth_tokens(
+ organization_id=organization_id,
+ token_type=OrganizationAuthTokenType.google_oauth_client_config,
+ )
+
+
+def _require_client_credentials(client_config: GoogleOAuthClientConfig | None = None) -> tuple[str, str]:
+ config = client_config or _settings_client_config()
+ client_id = config.client_id if config else None
+ client_secret = config.client_secret if config else None
if not client_id or not client_secret:
raise ValueError("Google OAuth client credentials are not configured")
return client_id, client_secret
@@ -153,20 +278,21 @@ def has_required_scopes(
_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
-def _validate_redirect_uri(redirect_uri: str) -> None:
+def _validate_redirect_uri(redirect_uri: str, client_config: GoogleOAuthClientConfig | None = None) -> None:
"""Validate redirect_uri against the allowlist; defense-in-depth alongside Google's check.
Beyond the host allowlist, we enforce scheme=https for non-loopback hosts so
an attacker who controls ``http://allowed-host.com`` can't satisfy a
hostname-only allowlist intended for ``https://allowed-host.com``.
"""
- allowlist = settings.GOOGLE_OAUTH_REDIRECT_HOSTS
+ allowlist = client_config.redirect_hosts if client_config else settings.GOOGLE_OAUTH_REDIRECT_HOSTS
if not allowlist:
# Empty allowlist + no client_id = OAuth not configured at all → silent
# pass-through (the consent flow itself will fail later in
# ``_require_client_credentials``). Empty allowlist + client_id = misconfig
# we must catch up-front so we don't leak a redirect_uri to Google unchecked.
- if settings.GOOGLE_OAUTH_CLIENT_ID:
+ configured_client_id = client_config.client_id if client_config else settings.GOOGLE_OAUTH_CLIENT_ID
+ if configured_client_id:
raise InvalidRedirectURIError(
"GOOGLE_OAUTH_REDIRECT_HOSTS must be configured when GOOGLE_OAUTH_CLIENT_ID is set"
)
@@ -185,7 +311,7 @@ def _validate_redirect_uri(redirect_uri: str) -> None:
raise InvalidRedirectURIError(f"redirect_uri must use https for non-loopback host: {host}")
-def _validate_app_origin(app_origin: str) -> None:
+def _validate_app_origin(app_origin: str, client_config: GoogleOAuthClientConfig | None = None) -> None:
"""Validate app_origin against the GOOGLE_OAUTH_APP_ORIGINS allowlist.
Entries are either:
@@ -199,7 +325,7 @@ def _validate_app_origin(app_origin: str) -> None:
Fails closed: empty allowlist always raises.
"""
- allowlist = settings.GOOGLE_OAUTH_APP_ORIGINS
+ allowlist = client_config.app_origins if client_config else settings.GOOGLE_OAUTH_APP_ORIGINS
if not allowlist:
raise InvalidAppOriginError("GOOGLE_OAUTH_APP_ORIGINS is not configured; app_origin is not accepted")
@@ -243,6 +369,7 @@ def build_authorize_url(
state: str,
scopes: str | list[str] | tuple[str, ...] | None = None,
code_verifier: str | None = None,
+ client_config: GoogleOAuthClientConfig | None = None,
) -> tuple[str, str]:
"""Assemble the Google OAuth 2.0 consent URL the browser should navigate to.
@@ -256,8 +383,8 @@ def build_authorize_url(
"""
# Require both halves up-front; otherwise consent completes but /callback fails every time
# because exchange_code_for_tokens needs the secret for the code -> token roundtrip.
- client_id, client_secret = _require_client_credentials()
- _validate_redirect_uri(redirect_uri)
+ client_id, client_secret = _require_client_credentials(client_config)
+ _validate_redirect_uri(redirect_uri, client_config)
scope_list = _coerce_scopes(scopes)
flow = Flow.from_client_config(
@@ -305,9 +432,12 @@ async def start_authorization(
) -> GoogleAuthorizationStart:
"""Insert a pending consent row, build the authorize URL, persist the PKCE verifier."""
_require_encryption()
- _validate_redirect_uri(redirect_uri)
+ resolved_config = await resolve_client_config(organization_id)
+ if resolved_config.config is None:
+ raise ValueError("Google OAuth client credentials are not configured")
+ _validate_redirect_uri(redirect_uri, resolved_config.config)
if app_origin is not None:
- _validate_app_origin(app_origin)
+ _validate_app_origin(app_origin, resolved_config.config)
credential_id = generate_google_oauth_credential_id()
nonce = secrets.token_urlsafe(32)
@@ -337,6 +467,7 @@ async def start_authorization(
state=nonce,
scopes=requested_scopes,
code_verifier=code_verifier,
+ client_config=resolved_config.config,
)
return GoogleAuthorizationStart(authorize_url=authorize_url, state=nonce)
@@ -370,9 +501,15 @@ async def load_pending_consent_context(organization_id: str, nonce: str) -> Pend
)
-async def exchange_code_for_tokens(code: str, redirect_uri: str, code_verifier: str | None) -> dict:
+async def exchange_code_for_tokens(
+ code: str,
+ redirect_uri: str,
+ code_verifier: str | None,
+ organization_id: str | None = None,
+) -> dict:
"""Exchange an OAuth authorization code for access and refresh tokens."""
- client_id, client_secret = _require_client_credentials()
+ resolved_config = await resolve_client_config(organization_id)
+ client_id, client_secret = _require_client_credentials(resolved_config.config)
# ``code_verifier`` is passed to ``fetch_token`` (where the PKCE verification
# actually happens); ``Flow.from_client_config`` ignores the kwarg.
@@ -403,9 +540,10 @@ async def exchange_code_for_tokens(code: str, redirect_uri: str, code_verifier:
}
-async def refresh_access_token(refresh_token: str) -> dict:
+async def refresh_access_token(refresh_token: str, organization_id: str | None = None) -> dict:
"""Exchange a refresh token for a new access token via google-auth."""
- client_id, client_secret = _require_client_credentials()
+ resolved_config = await resolve_client_config(organization_id, strict=False)
+ client_id, client_secret = _require_client_credentials(resolved_config.config)
creds = Credentials(
token=None,
@@ -439,20 +577,30 @@ async def load_credential_secrets(
return GoogleCredentialSecrets(refresh_token=refresh_token, scopes=payload.scopes_granted)
-async def access_token_from_secrets(credential_secrets: GoogleCredentialSecrets) -> str:
+async def access_token_from_secrets(
+ credential_secrets: GoogleCredentialSecrets,
+ organization_id: str | None = None,
+) -> str:
"""Exchange loaded secrets for an access token. Network-only; no DB."""
if not credential_secrets.refresh_token:
raise ValueError("OAuth credential is missing refresh_token")
- token_data = await refresh_access_token(credential_secrets.refresh_token)
+ if organization_id is None:
+ token_data = await refresh_access_token(credential_secrets.refresh_token)
+ else:
+ token_data = await refresh_access_token(credential_secrets.refresh_token, organization_id=organization_id)
access_token = token_data.get("access_token")
if not access_token:
raise MissingAccessTokenError("Google token response did not include access_token")
return access_token
-async def credentials_from_secrets(credential_secrets: GoogleCredentialSecrets) -> Credentials:
+async def credentials_from_secrets(
+ credential_secrets: GoogleCredentialSecrets,
+ organization_id: str | None = None,
+) -> Credentials:
"""Build a refreshed ``Credentials`` from already-decrypted secrets. Network-only; no DB."""
- client_id, client_secret = _require_client_credentials()
+ resolved_config = await resolve_client_config(organization_id, strict=False)
+ client_id, client_secret = _require_client_credentials(resolved_config.config)
creds = Credentials(
token=None,
refresh_token=credential_secrets.refresh_token,
diff --git a/tests/unit/google/test_google_oauth.py b/tests/unit/google/test_google_oauth.py
index 6fdad817d..05f2282a7 100644
--- a/tests/unit/google/test_google_oauth.py
+++ b/tests/unit/google/test_google_oauth.py
@@ -5,11 +5,18 @@ from urllib.parse import parse_qs, urlparse
import httpx
import pytest
+from fastapi import HTTPException
from pydantic import ValidationError
from sqlalchemy.sql.elements import BindParameter
+from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType
from skyvern.forge.sdk.encrypt.base import EncryptMethod
-from skyvern.forge.sdk.schemas.google_oauth import CreateGoogleOAuthAuthorizeRequest, UpdateGoogleOAuthCredentialRequest
+from skyvern.forge.sdk.routes import google_oauth as google_oauth_routes
+from skyvern.forge.sdk.schemas.google_oauth import (
+ CreateGoogleOAuthAuthorizeRequest,
+ UpdateGoogleOAuthClientConfigRequest,
+ UpdateGoogleOAuthCredentialRequest,
+)
from skyvern.forge.sdk.services import google_drive_service, google_oauth_service
@@ -279,6 +286,591 @@ def test_sheets_api_runtime_defaults_match_previous_hardcoded_values() -> None:
assert fresh.GOOGLE_DRIVE_API_MAX_RETRIES == 3
+async def test_resolve_client_config_prefers_org_token(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ config = google_oauth_service.GoogleOAuthClientConfig(
+ client_id="org-client",
+ client_secret="org-secret",
+ redirect_hosts=["oss.example.com"],
+ app_origins=["https://oss.example.com"],
+ )
+ organizations = SimpleNamespace(
+ get_valid_org_auth_token=AsyncMock(return_value=SimpleNamespace(token=config.model_dump_json()))
+ )
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(organizations=organizations),
+ raising=False,
+ )
+
+ resolved = await google_oauth_service.resolve_client_config("org_1")
+
+ assert resolved.source == "organization"
+ assert resolved.config == config
+ organizations.get_valid_org_auth_token.assert_awaited_once()
+
+
+async def test_resolve_client_config_ignores_org_token_when_disabled(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_ID", "env-client", raising=False)
+ monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_SECRET", "env-secret", raising=False)
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=False),
+ )
+ organizations = SimpleNamespace(get_valid_org_auth_token=AsyncMock())
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(organizations=organizations),
+ raising=False,
+ )
+
+ resolved = await google_oauth_service.resolve_client_config("org_1")
+
+ assert resolved.source == "environment"
+ assert resolved.config is not None
+ assert resolved.config.client_id == "env-client"
+ organizations.get_valid_org_auth_token.assert_not_awaited()
+
+
+async def test_resolve_client_config_returns_missing_without_org_token_or_env_credentials(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_ID", "", raising=False)
+ monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_SECRET", "", raising=False)
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ organizations = SimpleNamespace(get_valid_org_auth_token=AsyncMock(return_value=None))
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(organizations=organizations),
+ raising=False,
+ )
+
+ resolved = await google_oauth_service.resolve_client_config("org_1")
+
+ assert resolved.source == "missing"
+ assert resolved.config is None
+ organizations.get_valid_org_auth_token.assert_awaited_once()
+
+
+async def test_resolve_client_config_fails_closed_for_invalid_org_token(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ monkeypatch.setattr(
+ google_oauth_service,
+ "_settings_client_config",
+ lambda: pytest.fail("environment config must not be consulted"),
+ )
+ organizations = SimpleNamespace(get_valid_org_auth_token=AsyncMock(return_value=SimpleNamespace(token="not-json")))
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(organizations=organizations),
+ raising=False,
+ )
+
+ with pytest.raises(
+ google_oauth_service.OrganizationClientConfigUnavailableError,
+ match="Stored organization Google OAuth client config is invalid",
+ ):
+ await google_oauth_service.resolve_client_config("org_1")
+
+
[email protected]("strict", [True, False])
+async def test_resolve_client_config_fails_closed_for_empty_org_token_payload(
+ monkeypatch: pytest.MonkeyPatch,
+ strict: bool,
+) -> None:
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ monkeypatch.setattr(
+ google_oauth_service,
+ "_settings_client_config",
+ lambda: pytest.fail("environment config must not be consulted"),
+ )
+ organizations = SimpleNamespace(get_valid_org_auth_token=AsyncMock(return_value=SimpleNamespace(token="")))
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(organizations=organizations),
+ raising=False,
+ )
+
+ with pytest.raises(
+ google_oauth_service.OrganizationClientConfigUnavailableError,
+ match="Stored organization Google OAuth client config is invalid",
+ ):
+ await google_oauth_service.resolve_client_config("org_1", strict=strict)
+
+
+async def test_resolve_client_config_fails_closed_when_org_token_load_raises(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ monkeypatch.setattr(
+ google_oauth_service,
+ "_settings_client_config",
+ lambda: pytest.fail("environment config must not be consulted"),
+ )
+ organizations = SimpleNamespace(
+ get_valid_org_auth_token=AsyncMock(side_effect=RuntimeError("database unavailable"))
+ )
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(organizations=organizations),
+ raising=False,
+ )
+
+ with pytest.raises(
+ google_oauth_service.OrganizationClientConfigUnavailableError,
+ match="Failed to load the organization Google OAuth client config",
+ ):
+ await google_oauth_service.resolve_client_config("org_1")
+
+
+async def test_resolve_client_config_non_strict_falls_back_to_env_when_org_token_load_raises(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_ID", "env-client", raising=False)
+ monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_SECRET", "env-secret", raising=False)
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ organizations = SimpleNamespace(
+ get_valid_org_auth_token=AsyncMock(side_effect=RuntimeError("database unavailable"))
+ )
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(organizations=organizations),
+ raising=False,
+ )
+ warning_calls: list[tuple[str, dict[str, object]]] = []
+
+ def warning(event: str, **kwargs: object) -> None:
+ warning_calls.append((event, kwargs))
+
+ monkeypatch.setattr(google_oauth_service, "LOG", SimpleNamespace(warning=warning))
+
+ resolved = await google_oauth_service.resolve_client_config("org_1", strict=False)
+
+ assert resolved.source == "environment"
+ assert resolved.config is not None
+ assert resolved.config.client_id == "env-client"
+ assert warning_calls == [
+ (
+ "Failed to load organization Google OAuth client config; falling back to environment for token refresh",
+ {"organization_id": "org_1"},
+ )
+ ]
+
+
+async def test_resolve_client_config_non_strict_fails_closed_for_invalid_org_token(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ monkeypatch.setattr(
+ google_oauth_service,
+ "_settings_client_config",
+ lambda: pytest.fail("environment config must not be consulted"),
+ )
+ organizations = SimpleNamespace(get_valid_org_auth_token=AsyncMock(return_value=SimpleNamespace(token="not-json")))
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(organizations=organizations),
+ raising=False,
+ )
+
+ with pytest.raises(
+ google_oauth_service.OrganizationClientConfigUnavailableError,
+ match="Stored organization Google OAuth client config is invalid",
+ ):
+ await google_oauth_service.resolve_client_config("org_1", strict=False)
+
+
+async def test_resolve_client_config_falls_back_to_env_without_org_token(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_ID", "env-client", raising=False)
+ monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_SECRET", "env-secret", raising=False)
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ organizations = SimpleNamespace(get_valid_org_auth_token=AsyncMock(return_value=None))
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(organizations=organizations),
+ raising=False,
+ )
+
+ resolved = await google_oauth_service.resolve_client_config("org_1")
+
+ assert resolved.source == "environment"
+ assert resolved.config is not None
+ assert resolved.config.client_id == "env-client"
+
+
+async def test_save_client_config_requires_encryption(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ monkeypatch.setattr(google_oauth_service.settings, "ENABLE_ENCRYPTION", False, raising=False)
+ organizations = SimpleNamespace(replace_org_auth_token=AsyncMock())
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(organizations=organizations),
+ raising=False,
+ )
+
+ with pytest.raises(google_oauth_service.EncryptionNotConfiguredError):
+ await google_oauth_service.save_client_config(
+ "org_1",
+ google_oauth_service.GoogleOAuthClientConfig(client_id="cid", client_secret="secret"),
+ )
+ organizations.replace_org_auth_token.assert_not_awaited()
+
+
+async def test_save_client_config_requires_org_config_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(google_oauth_service.settings, "ENABLE_ENCRYPTION", False, raising=False)
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=False),
+ )
+ organizations = SimpleNamespace(replace_org_auth_token=AsyncMock())
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(organizations=organizations),
+ raising=False,
+ )
+
+ with pytest.raises(google_oauth_service.OrganizationGoogleOAuthConfigDisabledError):
+ await google_oauth_service.save_client_config(
+ "org_1",
+ google_oauth_service.GoogleOAuthClientConfig(client_id="cid", client_secret="secret"),
+ )
+ organizations.replace_org_auth_token.assert_not_awaited()
+
+
+async def test_save_client_config_uses_aes(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ monkeypatch.setattr(google_oauth_service.settings, "ENABLE_ENCRYPTION", True, raising=False)
+ replace_mock = AsyncMock()
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(organizations=SimpleNamespace(replace_org_auth_token=replace_mock)),
+ raising=False,
+ )
+
+ config = google_oauth_service.GoogleOAuthClientConfig(client_id="cid", client_secret="secret")
+ resolved = await google_oauth_service.save_client_config("org_1", config)
+
+ assert resolved.source == "organization"
+ assert resolved.config == config
+ replace_mock.assert_awaited_once()
+ assert replace_mock.await_args.kwargs["encrypted_method"] is EncryptMethod.AES
+
+
+async def test_delete_client_config_invalidates_org_token_when_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ invalidate_mock = AsyncMock()
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(organizations=SimpleNamespace(invalidate_org_auth_tokens=invalidate_mock)),
+ raising=False,
+ )
+
+ await google_oauth_service.delete_client_config("org_1")
+
+ invalidate_mock.assert_awaited_once_with(
+ organization_id="org_1",
+ token_type=OrganizationAuthTokenType.google_oauth_client_config,
+ )
+
+
+async def test_delete_client_config_requires_org_config_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=False),
+ )
+ invalidate_mock = AsyncMock()
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(organizations=SimpleNamespace(invalidate_org_auth_tokens=invalidate_mock)),
+ raising=False,
+ )
+
+ with pytest.raises(google_oauth_service.OrganizationGoogleOAuthConfigDisabledError):
+ await google_oauth_service.delete_client_config("org_1")
+ invalidate_mock.assert_not_awaited()
+
+
+async def test_update_client_config_does_not_reuse_environment_secret(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ google_oauth_routes.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ env_config = google_oauth_service.GoogleOAuthClientConfig(
+ client_id="env-client",
+ client_secret="env-secret",
+ redirect_hosts=["env.example.com"],
+ )
+ save_mock = AsyncMock()
+ monkeypatch.setattr(
+ google_oauth_routes.google_oauth_service,
+ "resolve_client_config",
+ AsyncMock(
+ return_value=google_oauth_service.GoogleOAuthClientConfigResolution(
+ config=env_config,
+ source="environment",
+ )
+ ),
+ )
+ monkeypatch.setattr(google_oauth_routes.google_oauth_service, "save_client_config", save_mock)
+
+ with pytest.raises(HTTPException) as exc_info:
+ await google_oauth_routes.update_google_oauth_client_config(
+ UpdateGoogleOAuthClientConfigRequest(
+ client_id="org-client",
+ redirect_hosts=["org.example.com"],
+ ),
+ current_org=SimpleNamespace(organization_id="org_1"),
+ )
+
+ assert exc_info.value.status_code == 400
+ assert exc_info.value.detail == "Google OAuth client secret is required"
+ save_mock.assert_not_awaited()
+
+
+async def test_update_client_config_does_not_reuse_organization_secret_when_client_id_changes(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ google_oauth_routes.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ org_config = google_oauth_service.GoogleOAuthClientConfig(
+ client_id="old-client",
+ client_secret="old-secret",
+ redirect_hosts=["org.example.com"],
+ )
+ save_mock = AsyncMock()
+ monkeypatch.setattr(
+ google_oauth_routes.google_oauth_service,
+ "resolve_client_config",
+ AsyncMock(
+ return_value=google_oauth_service.GoogleOAuthClientConfigResolution(
+ config=org_config,
+ source="organization",
+ )
+ ),
+ )
+ monkeypatch.setattr(google_oauth_routes.google_oauth_service, "save_client_config", save_mock)
+
+ with pytest.raises(HTTPException) as exc_info:
+ await google_oauth_routes.update_google_oauth_client_config(
+ UpdateGoogleOAuthClientConfigRequest(
+ client_id="new-client",
+ redirect_hosts=["org.example.com"],
+ ),
+ current_org=SimpleNamespace(organization_id="org_1"),
+ )
+
+ assert exc_info.value.status_code == 400
+ assert exc_info.value.detail == "Google OAuth client secret is required"
+ save_mock.assert_not_awaited()
+
+
+async def test_update_client_config_allows_repair_when_stored_config_is_unavailable(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ google_oauth_routes.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ unavailable_error = google_oauth_service.OrganizationClientConfigUnavailableError(
+ "Stored organization Google OAuth client config is invalid"
+ )
+ monkeypatch.setattr(
+ google_oauth_routes.google_oauth_service,
+ "resolve_client_config",
+ AsyncMock(side_effect=unavailable_error),
+ )
+ saved_config = google_oauth_service.GoogleOAuthClientConfig(
+ client_id="replacement-client",
+ client_secret="replacement-secret",
+ redirect_hosts=["org.example.com"],
+ )
+ save_mock = AsyncMock(
+ return_value=google_oauth_service.GoogleOAuthClientConfigResolution(
+ config=saved_config,
+ source="organization",
+ )
+ )
+ monkeypatch.setattr(google_oauth_routes.google_oauth_service, "save_client_config", save_mock)
+
+ response = await google_oauth_routes.update_google_oauth_client_config(
+ UpdateGoogleOAuthClientConfigRequest(
+ client_id="replacement-client",
+ client_secret="replacement-secret",
+ redirect_hosts=["org.example.com"],
+ ),
+ current_org=SimpleNamespace(organization_id="org_1"),
+ )
+
+ assert response.config.source == "organization"
+ save_mock.assert_awaited_once_with("org_1", saved_config)
+
+
+async def test_update_client_config_requires_secret_when_stored_config_is_unavailable(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ google_oauth_routes.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ unavailable_error = google_oauth_service.OrganizationClientConfigUnavailableError(
+ "Stored organization Google OAuth client config is invalid"
+ )
+ monkeypatch.setattr(
+ google_oauth_routes.google_oauth_service,
+ "resolve_client_config",
+ AsyncMock(side_effect=unavailable_error),
+ )
+ save_mock = AsyncMock()
+ monkeypatch.setattr(google_oauth_routes.google_oauth_service, "save_client_config", save_mock)
+
+ with pytest.raises(HTTPException) as exc_info:
+ await google_oauth_routes.update_google_oauth_client_config(
+ UpdateGoogleOAuthClientConfigRequest(
+ client_id="replacement-client",
+ redirect_hosts=["org.example.com"],
+ ),
+ current_org=SimpleNamespace(organization_id="org_1"),
+ )
+
+ assert exc_info.value.status_code == 400
+ assert exc_info.value.detail == "Google OAuth client secret is required"
+ save_mock.assert_not_awaited()
+
+
+async def test_get_client_config_returns_503_when_org_config_is_unavailable(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ google_oauth_routes.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ unavailable_error = google_oauth_service.OrganizationClientConfigUnavailableError(
+ "Failed to load the organization Google OAuth client config"
+ )
+ monkeypatch.setattr(
+ google_oauth_routes.google_oauth_service,
+ "resolve_client_config",
+ AsyncMock(side_effect=unavailable_error),
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ await google_oauth_routes.get_google_oauth_client_config(current_org=SimpleNamespace(organization_id="org_1"))
+
+ assert exc_info.value.status_code == 503
+ assert exc_info.value.detail == "Failed to load the organization Google OAuth client config"
+
+
+async def test_config_route_handlers_return_404_when_org_config_disabled(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ google_oauth_routes.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=False),
+ )
+ current_org = SimpleNamespace(organization_id="org_1")
+
+ with pytest.raises(HTTPException) as get_exc_info:
+ await google_oauth_routes.get_google_oauth_client_config(current_org=current_org)
+ assert get_exc_info.value.status_code == 404
+
+ with pytest.raises(HTTPException) as delete_exc_info:
+ await google_oauth_routes.delete_google_oauth_client_config(current_org=current_org)
+ assert delete_exc_info.value.status_code == 404
+
+
def test_build_authorize_url_includes_required_params(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_ID", "cid", raising=False)
monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_SECRET", "csecret", raising=False)
@@ -390,11 +982,22 @@ async def test_start_authorization_persists_verifier_and_returns_url(monkeypatch
monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_ID", "cid", raising=False)
monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_SECRET", "csecret", raising=False)
monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_REDIRECT_HOSTS", ["x"], raising=False)
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
monkeypatch.setattr(google_oauth_service, "generate_google_oauth_credential_id", lambda: "goac_test")
insert_mock = AsyncMock(return_value=SimpleNamespace(id="goac_test", organization_id="org_1"))
fake_repo = SimpleNamespace(insert_pending_credential=insert_mock)
- monkeypatch.setattr(google_oauth_service.app, "DATABASE", SimpleNamespace(google_oauth=fake_repo), raising=False)
+ organizations = SimpleNamespace(get_valid_org_auth_token=AsyncMock(return_value=None))
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(google_oauth=fake_repo, organizations=organizations),
+ raising=False,
+ )
result = await google_oauth_service.start_authorization(
organization_id="org_1",
@@ -764,6 +1367,52 @@ async def test_access_token_from_secrets_calls_refresh(monkeypatch: pytest.Monke
refresh_mock.assert_awaited_once_with("rt-1")
+async def test_access_token_from_secrets_falls_back_to_env_when_org_config_load_raises(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_ID", "env-client", raising=False)
+ monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_SECRET", "env-secret", raising=False)
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ organizations = SimpleNamespace(
+ get_valid_org_auth_token=AsyncMock(side_effect=RuntimeError("database unavailable"))
+ )
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(organizations=organizations),
+ raising=False,
+ )
+ captured: dict[str, object] = {}
+
+ class _FakeCreds:
+ def __init__(self, **kwargs: object) -> None:
+ captured["init_kwargs"] = kwargs
+ self.token: str | None = None
+ self.expiry = None
+
+ def refresh(self, request: object) -> None:
+ captured["refresh_request"] = request
+ self.token = "at-refreshed"
+
+ monkeypatch.setattr(google_oauth_service, "Credentials", _FakeCreds)
+ secrets = google_oauth_service.GoogleCredentialSecrets(refresh_token="rt-1", scopes=["https://a"])
+
+ token = await google_oauth_service.access_token_from_secrets(secrets, organization_id="org_1")
+
+ assert token == "at-refreshed"
+ init_kwargs = captured["init_kwargs"]
+ assert isinstance(init_kwargs, dict)
+ assert init_kwargs["client_id"] == "env-client"
+ assert init_kwargs["client_secret"] == "env-secret"
+ assert "refresh_request" in captured
+ organizations.get_valid_org_auth_token.assert_awaited_once()
+
+
@pytest.mark.asyncio
async def test_access_token_from_secrets_missing_access_token_raises(monkeypatch: pytest.MonkeyPatch) -> None:
refresh_mock = AsyncMock(return_value={"scope": "foo"})
@@ -1162,11 +1811,22 @@ async def test_start_authorization_persists_app_origin(monkeypatch: pytest.Monke
google_oauth_service.settings, "GOOGLE_OAUTH_REDIRECT_HOSTS", ["app-staging.skyvern.com"], raising=False
)
monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_APP_ORIGINS", ["*.vercel.app"], raising=False)
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
monkeypatch.setattr(google_oauth_service, "generate_google_oauth_credential_id", lambda: "goac_test2")
insert_mock = AsyncMock(return_value=SimpleNamespace(id="goac_test2", organization_id="org_1"))
fake_repo = SimpleNamespace(insert_pending_credential=insert_mock)
- monkeypatch.setattr(google_oauth_service.app, "DATABASE", SimpleNamespace(google_oauth=fake_repo), raising=False)
+ organizations = SimpleNamespace(get_valid_org_auth_token=AsyncMock(return_value=None))
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(google_oauth=fake_repo, organizations=organizations),
+ raising=False,
+ )
result = await google_oauth_service.start_authorization(
organization_id="org_1",
@@ -1192,10 +1852,21 @@ async def test_start_authorization_rejects_bad_app_origin(monkeypatch: pytest.Mo
monkeypatch.setattr(
google_oauth_service.settings, "GOOGLE_OAUTH_APP_ORIGINS", ["https://app.skyvern.com"], raising=False
)
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
insert_mock = AsyncMock()
fake_repo = SimpleNamespace(insert_pending_credential=insert_mock)
- monkeypatch.setattr(google_oauth_service.app, "DATABASE", SimpleNamespace(google_oauth=fake_repo), raising=False)
+ organizations = SimpleNamespace(get_valid_org_auth_token=AsyncMock(return_value=None))
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(google_oauth=fake_repo, organizations=organizations),
+ raising=False,
+ )
with pytest.raises(google_oauth_service.InvalidAppOriginError):
await google_oauth_service.start_authorization(
diff --git a/tests/unit/google/test_otp_service_gmail.py b/tests/unit/google/test_otp_service_gmail.py
new file mode 100644
index 000000000..ce158e039
--- /dev/null
+++ b/tests/unit/google/test_otp_service_gmail.py
@@ -0,0 +1,253 @@
+from datetime import datetime, timezone
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from skyvern.forge import agent_functions
+from skyvern.forge.agent_functions import AgentFunction
+from skyvern.forge.sdk.schemas.totp_codes import OTPType
+from skyvern.forge.sdk.services import google_gmail_service, google_oauth_service
+from skyvern.services import otp_service
+from skyvern.services.otp_gmail import MAX_SEEN_GMAIL_MESSAGE_IDS, GmailOTPVerificationContext
+
+
+def test_gmail_otp_context_caps_seen_message_ids() -> None:
+ context = GmailOTPVerificationContext()
+
+ for index in range(MAX_SEEN_GMAIL_MESSAGE_IDS + 5):
+ context.remember_message_id(f"msg_{index}")
+
+ assert len(context.seen_message_ids) == MAX_SEEN_GMAIL_MESSAGE_IDS
+ assert not context.has_seen_message_id("msg_0")
+ assert context.has_seen_message_id(f"msg_{MAX_SEEN_GMAIL_MESSAGE_IDS + 4}")
+
+
+async def test_get_otp_value_from_gmail_uses_gmail_scoped_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
+ agent = AgentFunction()
+ credential = SimpleNamespace(
+ id="goac_1",
+ scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),
+ )
+ list_credentials = AsyncMock(return_value=[credential])
+ monkeypatch.setattr(agent_functions.google_oauth_service, "get_credentials_for_org", list_credentials)
+
+ get_credentials = AsyncMock(return_value=SimpleNamespace(token="AT"))
+ monkeypatch.setattr(agent, "get_google_workspace_credentials", get_credentials)
+ create_otp_code = AsyncMock()
+ monkeypatch.setattr(
+ agent_functions.app, "DATABASE", SimpleNamespace(otp=SimpleNamespace(create_otp_code=create_otp_code))
+ )
+
+ candidate = google_gmail_service.GmailMessageCandidate(
+ message_id="msg_1",
+ content="Your verification code is 123456",
+ internal_date=datetime.now(timezone.utc),
+ )
+ search_messages = AsyncMock(return_value=[candidate])
+ monkeypatch.setattr(agent_functions.google_gmail_service, "search_recent_otp_messages", search_messages)
+ parse = AsyncMock(return_value=otp_service.OTPValue(value="123456", type=OTPType.TOTP))
+ monkeypatch.setattr(otp_service, "parse_otp_login", parse)
+
+ result = await agent.get_otp_value_from_gmail(
+ organization_id="org_1",
+ totp_identifier="[email protected]",
+ workflow_id="wpid_1",
+ workflow_run_id="wr_1",
+ created_after=datetime(2025, 1, 1, tzinfo=timezone.utc),
+ )
+
+ assert result == otp_service.OTPValue(value="123456", type=OTPType.TOTP)
+ get_credentials.assert_awaited_once_with(
+ organization_id="org_1",
+ credential_id="goac_1",
+ required_scopes=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),
+ )
+ search_messages.assert_awaited_once()
+ search_messages_args = search_messages.await_args
+ assert search_messages_args is not None
+ assert search_messages_args.kwargs["max_results"] == agent_functions.GMAIL_OTP_MAX_RESULTS
+ assert search_messages_args.kwargs["client"] is not None
+ parse.assert_awaited_once_with("Your verification code is 123456", "org_1")
+ create_otp_code.assert_awaited_once_with(
+ "org_1",
+ "123456",
+ "123456",
+ OTPType.TOTP,
+ workflow_id="wpid_1",
+ workflow_run_id="wr_1",
+ source="gmail",
+ )
+
+
+async def test_get_otp_value_from_gmail_uses_first_parseable_candidate(monkeypatch: pytest.MonkeyPatch) -> None:
+ agent = AgentFunction()
+ credential = SimpleNamespace(
+ id="goac_1",
+ scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),
+ )
+ monkeypatch.setattr(
+ agent_functions.google_oauth_service,
+ "get_credentials_for_org",
+ AsyncMock(return_value=[credential]),
+ )
+ monkeypatch.setattr(agent, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT")))
+ create_otp_code = AsyncMock()
+ monkeypatch.setattr(
+ agent_functions.app, "DATABASE", SimpleNamespace(otp=SimpleNamespace(create_otp_code=create_otp_code))
+ )
+
+ candidates = [
+ google_gmail_service.GmailMessageCandidate(
+ message_id="msg_unrelated",
+ content="Security alert with no code",
+ internal_date=datetime.now(timezone.utc),
+ ),
+ google_gmail_service.GmailMessageCandidate(
+ message_id="msg_code",
+ content="Your verification code is 654321",
+ internal_date=datetime.now(timezone.utc),
+ ),
+ ]
+ monkeypatch.setattr(
+ agent_functions.google_gmail_service,
+ "search_recent_otp_messages",
+ AsyncMock(return_value=candidates),
+ )
+ parse = AsyncMock(side_effect=[None, otp_service.OTPValue(value="654321", type=OTPType.TOTP)])
+ monkeypatch.setattr(otp_service, "parse_otp_login", parse)
+
+ result = await agent.get_otp_value_from_gmail(
+ organization_id="org_1",
+ totp_identifier="[email protected]",
+ workflow_id="wpid_1",
+ workflow_run_id="wr_1",
+ )
+
+ assert result == otp_service.OTPValue(value="654321", type=OTPType.TOTP)
+ assert parse.await_count == 2
+ create_otp_code.assert_awaited_once_with(
+ "org_1",
+ "654321",
+ "654321",
+ OTPType.TOTP,
+ workflow_id="wpid_1",
+ workflow_run_id="wr_1",
+ source="gmail",
+ )
+
+
+async def test_get_otp_value_from_gmail_retries_candidate_after_parser_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ agent = AgentFunction()
+ credential = SimpleNamespace(
+ id="goac_1",
+ scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),
+ )
+ monkeypatch.setattr(
+ agent_functions.google_oauth_service,
+ "get_credentials_for_org",
+ AsyncMock(return_value=[credential]),
+ )
+ monkeypatch.setattr(agent, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT")))
+ create_otp_code = AsyncMock()
+ monkeypatch.setattr(
+ agent_functions.app, "DATABASE", SimpleNamespace(otp=SimpleNamespace(create_otp_code=create_otp_code))
+ )
+
+ candidate = google_gmail_service.GmailMessageCandidate(
+ message_id="msg_retry",
+ content="Your verification code is 112233",
+ internal_date=datetime.now(timezone.utc),
+ )
+ search_messages = AsyncMock(return_value=[candidate])
+ monkeypatch.setattr(agent_functions.google_gmail_service, "search_recent_otp_messages", search_messages)
+ parse = AsyncMock(
+ side_effect=[RuntimeError("temporary parser outage"), otp_service.OTPValue(value="112233", type=OTPType.TOTP)]
+ )
+ monkeypatch.setattr(otp_service, "parse_otp_login", parse)
+
+ context = GmailOTPVerificationContext()
+ first_result = await agent.get_otp_value_from_gmail(
+ organization_id="org_1",
+ totp_identifier="[email protected]",
+ workflow_id="wpid_1",
+ workflow_run_id="wr_1",
+ context=context,
+ )
+ context.last_searched_at_by_credential["goac_1"] = datetime(2025, 1, 1, tzinfo=timezone.utc)
+ second_result = await agent.get_otp_value_from_gmail(
+ organization_id="org_1",
+ totp_identifier="[email protected]",
+ workflow_id="wpid_1",
+ workflow_run_id="wr_1",
+ context=context,
+ )
+
+ assert first_result is None
+ assert second_result == otp_service.OTPValue(value="112233", type=OTPType.TOTP)
+ assert parse.await_count == 2
+ create_otp_code.assert_awaited_once()
+
+
+async def test_get_otp_value_from_gmail_skips_credentials_without_gmail_scope(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ agent = AgentFunction()
+ credential = SimpleNamespace(
+ id="goac_1",
+ scopes_granted=list(google_oauth_service.GOOGLE_SHEETS_SCOPES),
+ )
+ monkeypatch.setattr(
+ agent_functions.google_oauth_service,
+ "get_credentials_for_org",
+ AsyncMock(return_value=[credential]),
+ )
+ get_credentials = AsyncMock(return_value=SimpleNamespace(token="AT"))
+ monkeypatch.setattr(agent, "get_google_workspace_credentials", get_credentials)
+
+ result = await agent.get_otp_value_from_gmail(
+ organization_id="org_1",
+ totp_identifier="[email protected]",
+ )
+
+ assert result is None
+ get_credentials.assert_not_awaited()
+
+
+async def test_get_otp_value_from_gmail_throttles_credential_searches_within_polling_context(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ agent = AgentFunction()
+ credential = SimpleNamespace(
+ id="goac_1",
+ scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),
+ )
+ list_credentials = AsyncMock(return_value=[credential])
+ monkeypatch.setattr(agent_functions.google_oauth_service, "get_credentials_for_org", list_credentials)
+ get_credentials = AsyncMock(return_value=SimpleNamespace(token="AT"))
+ monkeypatch.setattr(agent, "get_google_workspace_credentials", get_credentials)
+ search_messages = AsyncMock(return_value=[])
+ monkeypatch.setattr(agent_functions.google_gmail_service, "search_recent_otp_messages", search_messages)
+
+ context = GmailOTPVerificationContext()
+
+ for _ in range(2):
+ result = await agent.get_otp_value_from_gmail(
+ organization_id="org_1",
+ totp_identifier="[email protected]",
+ context=context,
+ )
+ assert result is None
+
+ list_credentials.assert_awaited_once_with("org_1")
+ get_credentials.assert_awaited_once()
+ search_messages.assert_awaited_once()
diff --git a/tests/unit/google/test_sheets_route_helpers.py b/tests/unit/google/test_sheets_route_helpers.py
index 50f5a66f4..5616fd7ae 100644
--- a/tests/unit/google/test_sheets_route_helpers.py
+++ b/tests/unit/google/test_sheets_route_helpers.py
@@ -30,6 +30,21 @@ def _patch_session(monkeypatch: pytest.MonkeyPatch) -> None:
)
+async def test_mint_access_token_forwards_organization_id_to_refresh(monkeypatch: pytest.MonkeyPatch) -> None:
+ secrets = MagicMock()
+ load_mock = AsyncMock(return_value=secrets)
+ access_mock = AsyncMock(return_value="access-token")
+ monkeypatch.setattr(sheets_routes.google_oauth_service, "load_credential_secrets", load_mock)
+ monkeypatch.setattr(sheets_routes.google_oauth_service, "access_token_from_secrets", access_mock)
+
+ token = await sheets_routes._mint_access_token("org_1", "cred_1")
+
+ assert token == "access-token"
+ load_mock.assert_awaited_once_with(organization_id="org_1", credential_id="cred_1")
+ access_mock.assert_awaited_once_with(secrets, organization_id="org_1")
+
+
@pytest.mark.asyncio
async def test_mint_access_token_returns_503_on_database_error(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
diff --git a/tests/unit/test_request_logging.py b/tests/unit/test_request_logging.py
index 2f57bb27b..096c23083 100644
--- a/tests/unit/test_request_logging.py
+++ b/tests/unit/test_request_logging.py
@@ -328,6 +328,30 @@ class TestSanitizeBody:
result = _sanitize_body(request, b'{"password": "hunter2"}', "application/json")
assert result == _REDACTED
+ @pytest.mark.parametrize(
+ "path",
+ [
+ "/api/v1/google/oauth/config",
+ "/v1/google/oauth/config",
+ ],
+ )
+ def test_google_oauth_config_request_redacted(self, path: str) -> None:
+ request = _make_request("PUT", path)
+ result = _sanitize_body(request, b'{"client_id": "cid", "client_secret": "secret"}', "application/json")
+ assert result == _REDACTED
+
+ @pytest.mark.parametrize(
+ "path",
+ [
+ "/api/v1/google/oauth/callback",
+ "/v1/google/oauth/callback",
+ ],
+ )
+ def test_google_oauth_callback_request_redacted(self, path: str) -> None:
+ request = _make_request("POST", path)
+ result = _sanitize_body(request, b'{"code": "4/0Adeu...", "state": "nonce"}', "application/json")
+ assert result == _REDACTED
+
def test_non_sensitive_endpoint_request_preserved(self) -> None:
request = _make_request("GET", "/v1/tasks")
result = _sanitize_body(request, b'{"user": "alice"}', "application/json")