Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Re-authenticate an expired integration connection in place (SKY-12572) (#7680)
Aaron Perezb6af2773e3da
diff --git a/skyvern-frontend/src/api/types.ts b/skyvern-frontend/src/api/types.tsindex 18b493bdc..f2d8d66ab 100644--- a/skyvern-frontend/src/api/types.ts+++ b/skyvern-frontend/src/api/types.ts@@ -406,6 +406,9 @@ export interface CreateGoogleOAuthAuthorizeRequest {credential_name?: string;scope_profile?: string;app_origin?: string;+ // Existing credential to re-authenticate in place, preserving its id so+ // workflows referencing it keep working without edits.+ credential_id?: string;}export interface GoogleOAuthAuthorizeResponse {diff --git a/skyvern-frontend/src/routes/integrations/Integrations.test.tsx b/skyvern-frontend/src/routes/integrations/Integrations.test.tsxnew file mode 100644index 000000000..160c8a0b8--- /dev/null+++ b/skyvern-frontend/src/routes/integrations/Integrations.test.tsx@@ -0,0 +1,105 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { GoogleOAuthCredential } from "@/api/types";+import { Integrations } from "./Integrations";++const mocks = vi.hoisted(() => ({+ useGoogleOAuthCredentials: vi.fn(),+ startAuthorize: vi.fn(),+ assign: vi.fn(),+}));++vi.mock("@/hooks/useGoogleOAuthCredentials", async (importActual) => {+ const actual =+ await importActual<typeof import("@/hooks/useGoogleOAuthCredentials")>();+ return {+ ...actual,+ useGoogleOAuthCredentials: mocks.useGoogleOAuthCredentials,+ };+});++// The client-config form issues its own network calls; it is irrelevant here.+vi.mock("@/components/GoogleOAuthClientConfigForm", () => ({+ GoogleOAuthClientConfigForm: () => null,+}));++function credential(+ id: string,+ name: string,+ state: string,+): GoogleOAuthCredential {+ return {+ id,+ organization_id: "o_1",+ credential_name: name,+ state,+ scopes_granted: ["https://www.googleapis.com/auth/spreadsheets"],+ scopes_requested: ["https://www.googleapis.com/auth/spreadsheets"],+ created_at: "2026-07-20T00:00:00Z",+ modified_at: "2026-07-20T00:00:00Z",+ };+}++function installHook(credentials: GoogleOAuthCredential[]) {+ mocks.startAuthorize.mockResolvedValue({+ authorize_url: "https://accounts.google.com/o/oauth2/v2/auth?x=1",+ state: "st",+ });+ mocks.useGoogleOAuthCredentials.mockReturnValue({+ credentials,+ isFetching: false,+ startAuthorize: mocks.startAuthorize,+ isStartingAuthorize: false,+ deleteCredential: vi.fn(),+ isDeletingCredential: false,+ });+}++beforeEach(() => {+ vi.clearAllMocks();+ Object.defineProperty(window, "location", {+ value: { origin: "https://app.example.com", assign: mocks.assign },+ writable: true,+ });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe("Integrations reconnect", () => {+ it("shows the needs-reconnect state for an expired connection", () => {+ installHook([credential("goac_expired", "Sheets Bot", "error")]);+ render(<Integrations />);++ expect(screen.getByText("Needs reconnect")).toBeTruthy();+ expect(screen.getByRole("button", { name: /reconnect/i })).toBeTruthy();+ });++ it("re-authenticates in place, preserving the credential id", async () => {+ installHook([credential("goac_expired", "Sheets Bot", "error")]);+ render(<Integrations />);++ fireEvent.click(screen.getByRole("button", { name: /reconnect/i }));++ await waitFor(() => expect(mocks.startAuthorize).toHaveBeenCalledTimes(1));+ // The existing id is forwarded so the reconnected connection keeps its identity.+ expect(mocks.startAuthorize).toHaveBeenCalledWith(+ expect.objectContaining({ credential_id: "goac_expired" }),+ );+ await waitFor(() =>+ expect(mocks.assign).toHaveBeenCalledWith(+ "https://accounts.google.com/o/oauth2/v2/auth?x=1",+ ),+ );+ });++ it("offers reconnect on an active connection too", () => {+ installHook([credential("goac_active", "Sheets Bot", "active")]);+ render(<Integrations />);++ expect(screen.getByText("Active")).toBeTruthy();+ expect(screen.getByRole("button", { name: /reconnect/i })).toBeTruthy();+ });+});diff --git a/skyvern-frontend/src/routes/integrations/Integrations.tsx b/skyvern-frontend/src/routes/integrations/Integrations.tsxindex adf04cb37..787168273 100644--- a/skyvern-frontend/src/routes/integrations/Integrations.tsx+++ b/skyvern-frontend/src/routes/integrations/Integrations.tsx@@ -1,5 +1,11 @@import { useState } from "react";-import { ExternalLinkIcon, ReloadIcon, TrashIcon } from "@radix-ui/react-icons";+import {+ ExternalLinkIcon,+ ReloadIcon,+ TrashIcon,+ UpdateIcon,+} from "@radix-ui/react-icons";+import { GoogleOAuthCredential } from "@/api/types";import { GoogleOAuthClientConfigForm } from "@/components/GoogleOAuthClientConfigForm";import { Button } from "@/components/ui/button";import {@@ -60,6 +66,7 @@ const integrations = [function Integrations() {const [connectingId, setConnectingId] = useState<string | null>(null);+ const [reconnectingId, setReconnectingId] = useState<string | null>(null);const {credentials,isFetching,@@ -85,6 +92,23 @@ function Integrations() {}};+ // Re-authenticate an existing connection in place. Passing credential_id keeps+ // the connection's identity so workflows referencing it keep working — the+ // backend re-requests the scopes originally granted to this credential.+ const reconnect = async (credential: GoogleOAuthCredential) => {+ setReconnectingId(credential.id);+ try {+ const response = await startAuthorize({+ redirect_uri: buildGoogleOAuthRedirectUri(),+ app_origin: getGoogleOAuthAppOrigin(),+ credential_id: credential.id,+ });+ window.location.assign(response.authorize_url);+ } finally {+ setReconnectingId(null);+ }+ };+return (<div className="mx-auto flex max-w-5xl flex-col gap-6 p-6"><Card>@@ -155,68 +179,93 @@ function Integrations() {</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"}+ {credentials.map((credential) => {+ const isActive = isGoogleOAuthCredentialActive(credential);+ const isReconnecting = reconnectingId === credential.id;+ return (+ <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={+ isActive+ ? "text-xs text-muted-foreground"+ : "text-xs font-medium text-amber-600 dark:text-amber-400"+ }+ >+ {isActive ? "Active" : "Needs reconnect"}+ </div></div>- </div>- <Dialog>- <DialogTrigger asChild>+ <div className="flex items-center gap-2"><Buttontype="button"- variant="outline"+ variant={isActive ? "outline" : "default"}size="sm"className="gap-2"- disabled={isDeletingCredential}+ disabled={isReconnecting || isStartingAuthorize}+ onClick={() => void reconnect(credential)}>- <TrashIcon className="h-4 w-4" />- Disconnect+ {isReconnecting ? (+ <ReloadIcon className="h-4 w-4 animate-spin" />+ ) : (+ <UpdateIcon className="h-4 w-4" />+ )}+ Reconnect</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>+ <Dialog>+ <DialogTrigger asChild><Buttontype="button"- variant="secondary"+ variant="outline"+ size="sm"+ className="gap-2"disabled={isDeletingCredential}>- Cancel- </Button>- </DialogClose>- <DialogClose asChild>- <Button- type="button"- variant="destructive"- disabled={isDeletingCredential}- onClick={() => deleteCredential(credential.id)}- >+ <TrashIcon className="h-4 w-4" />Disconnect</Button>- </DialogClose>- </DialogFooter>- </DialogContent>- </Dialog>- </div>- ))}+ </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>+ );+ })}</div>)}</CardContent>diff --git a/skyvern-frontend/src/routes/workflows/WorkflowActions.tsx b/skyvern-frontend/src/routes/workflows/WorkflowActions.tsxindex 145d3c2d7..6803436f5 100644--- a/skyvern-frontend/src/routes/workflows/WorkflowActions.tsx+++ b/skyvern-frontend/src/routes/workflows/WorkflowActions.tsx@@ -89,7 +89,7 @@ function WorkflowActions({) : null}<DropdownMenuItem onSelect={() => clone()} className="p-2"><CopyIcon className="mr-2 h-4 w-4" />- Clone Agent+ Duplicate Agent</DropdownMenuItem><DropdownMenuItemonSelect={() => toggleTemplate()}diff --git a/skyvern-frontend/src/routes/workflows/components/BulkActionBar.tsx b/skyvern-frontend/src/routes/workflows/components/BulkActionBar.tsxindex b1f0def91..de6591813 100644--- a/skyvern-frontend/src/routes/workflows/components/BulkActionBar.tsx+++ b/skyvern-frontend/src/routes/workflows/components/BulkActionBar.tsx@@ -112,10 +112,11 @@ function BulkActionBar({succeeded,total: count,results,- successTitle: (n) => `Cloned ${n} agent${n !== 1 ? "s" : ""}.`,- failureTitle: (n) => `Failed to clone ${n} agent${n !== 1 ? "s" : ""}.`,+ successTitle: (n) => `Duplicated ${n} agent${n !== 1 ? "s" : ""}.`,+ failureTitle: (n) =>+ `Failed to duplicate ${n} agent${n !== 1 ? "s" : ""}.`,partialTitle: (successCount, failedCount) =>- `Cloned ${successCount} agent${successCount !== 1 ? "s" : ""}. ${failedCount} failed.`,+ `Duplicated ${successCount} agent${successCount !== 1 ? "s" : ""}. ${failedCount} failed.`,});if (succeeded === count) {onClearSelection();@@ -314,7 +315,7 @@ function BulkActionBar({<DropdownMenuSeparator /><DropdownMenuItem onSelect={() => void handleBulkClone()}><CopyIcon className="mr-2 h-4 w-4" />- Clone {count}+ Duplicate ({count})</DropdownMenuItem><DropdownMenuSub><DropdownMenuSubTrigger>diff --git a/skyvern-frontend/src/routes/workflows/components/GoogleOAuthCredentialSelector.tsx b/skyvern-frontend/src/routes/workflows/components/GoogleOAuthCredentialSelector.tsxindex 2d37701b3..8684889a0 100644--- a/skyvern-frontend/src/routes/workflows/components/GoogleOAuthCredentialSelector.tsx+++ b/skyvern-frontend/src/routes/workflows/components/GoogleOAuthCredentialSelector.tsx@@ -56,6 +56,15 @@ function GoogleOAuthCredentialSelector({const hasCredentials = credentials.length > 0;const isKnownCredential = credentials.some((c) => c.id === value);+ // The saved id may point at a connection that still exists but is expired+ // ("needs reconnect"). Re-auth-in-place keeps the same id, so the block keeps+ // working once the account is reconnected — no need to repoint.+ const savedCredentialNeedsReconnect =+ !!value &&+ !isKnownCredential &&+ allCredentials.some(+ (c) => c.id === value && !isGoogleOAuthCredentialActive(c),+ );const firstValidId = getDefaultGoogleOAuthCredentialId(credentials);const needsAutoFill = !value;@@ -120,7 +129,20 @@ function GoogleOAuthCredentialSelector({</>) : (<>- {value && hasCredentials && !isKnownCredential ? (+ {savedCredentialNeedsReconnect ? (+ <p className="rounded-md border border-amber-300 bg-amber-100 px-2 py-1 text-[0.7rem] text-amber-700 dark:border-amber-600/40 dark:bg-amber-900/20 dark:text-amber-200">+ Saved Google account needs to be reconnected. Reconnect it on the{" "}+ <a+ href="/integrations"+ target="_blank"+ rel="noreferrer"+ className="underline"+ >+ Integrations+ </a>{" "}+ page to keep this block working.+ </p>+ ) : value && hasCredentials && !isKnownCredential ? (<p className="rounded-md border border-amber-300 bg-amber-100 px-2 py-1 text-[0.7rem] text-amber-700 dark:border-amber-600/40 dark:bg-amber-900/20 dark:text-amber-200">Saved Google account is no longer connected. Pick another below.</p>diff --git a/skyvern-frontend/src/routes/workflows/components/WorkflowRowContextMenu.tsx b/skyvern-frontend/src/routes/workflows/components/WorkflowRowContextMenu.tsxindex 207f03fa9..4a73ddb76 100644--- a/skyvern-frontend/src/routes/workflows/components/WorkflowRowContextMenu.tsx+++ b/skyvern-frontend/src/routes/workflows/components/WorkflowRowContextMenu.tsx@@ -257,7 +257,7 @@ function WorkflowRowContextMenu({<ContextMenuSeparator /><ContextMenuItem onSelect={() => clone()} disabled={isMultiSelect}><CopyIcon className="mr-2 h-4 w-4" />- Clone+ Duplicate Agent</ContextMenuItem><ContextMenuItemonSelect={() => toggleTemplate()}diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex d087cfeae..e364bc643 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -1299,6 +1299,13 @@ class AgentFunction:credential_id=credential_id,)return None+ except google_oauth_service.ExpiredRefreshTokenError:+ await google_oauth_service.mark_credential_expired(+ organization_id,+ credential_id,+ expected_version=secrets.credential_version,+ )+ return Noneexcept Exception:LOG.exception("Failed to get Google Sheets credentials",@@ -1371,6 +1378,13 @@ class AgentFunction:credential_id=credential_id,)return None+ except google_oauth_service.ExpiredRefreshTokenError:+ await google_oauth_service.mark_credential_expired(+ organization_id,+ credential_id,+ expected_version=secrets.credential_version,+ )+ return Noneexcept Exception:LOG.exception("Failed to get Google Workspace credentials",diff --git a/skyvern/forge/sdk/db/repositories/google_oauth.py b/skyvern/forge/sdk/db/repositories/google_oauth.pyindex b5843240d..dbd006da2 100644--- a/skyvern/forge/sdk/db/repositories/google_oauth.py+++ b/skyvern/forge/sdk/db/repositories/google_oauth.py@@ -48,6 +48,7 @@ class ActiveCredentialCiphertext:encrypted_method: EncryptMethodscopes_granted: list[str]client_id: str | None = None+ credential_version: datetime.datetime | None = None@dataclass(frozen=True)@@ -108,6 +109,10 @@ class GoogleOAuthRepository(BaseRepository):# stale nonce, but only after the code has already been consumed.cutoff = now if now is not None else datetime.datetime.now(datetime.UTC).replace(tzinfo=None)async with self.Session() as session:+ # A consent nonce lives on a fresh ``pending_consent`` row (first connect) or on an+ # existing ``active``/``error`` row that is being re-authorized in place. The nonce is+ # globally unique while set, so matching nonce + org + unexpired identifies the row in+ # either case; a successful promotion (or revoke) nulls the nonce afterward.stmt = select(GoogleOAuthCredentialModel.id,GoogleOAuthCredentialModel.consent_redirect_uri,@@ -117,7 +122,7 @@ class GoogleOAuthRepository(BaseRepository):).where(GoogleOAuthCredentialModel.consent_nonce == nonce,GoogleOAuthCredentialModel.organization_id == organization_id,- GoogleOAuthCredentialModel.state == STATE_PENDING_CONSENT,+ GoogleOAuthCredentialModel.state.in_([STATE_PENDING_CONSENT, STATE_ACTIVE, STATE_ERROR]),GoogleOAuthCredentialModel.consent_expires_at >= cutoff,)row = (await session.execute(stmt)).one_or_none()@@ -131,6 +136,88 @@ class GoogleOAuthRepository(BaseRepository):client_id=row[4],)+ @db_operation("begin_reauthorization")+ async def begin_reauthorization(+ self,+ credential_id: str,+ organization_id: str,+ consent_nonce: str,+ consent_redirect_uri: str,+ consent_expires_at: datetime.datetime,+ consent_code_verifier: str,+ now: datetime.datetime,+ consent_app_origin: str | None = None,+ client_id: str | None = None,+ requested_scopes: list[str] | None = None,+ fallback_scopes: list[str] | None = None,+ ) -> GoogleOAuthCredentialBase | None:+ """Stamp a fresh consent challenge onto an existing connectable row so re-auth+ preserves the credential id.++ The row's live ``encrypted_refresh_token`` and ``state`` are left untouched, so any+ workflow referencing this credential keeps working until the callback promotes it with+ the new token. Only ``active``/``error`` rows are re-authorizable; returns None otherwise.+ """+ async with self.Session() as session:+ stmt = (+ select(GoogleOAuthCredentialModel)+ .where(+ GoogleOAuthCredentialModel.id == credential_id,+ GoogleOAuthCredentialModel.organization_id == organization_id,+ GoogleOAuthCredentialModel.state.in_([STATE_ACTIVE, STATE_ERROR]),+ )+ .with_for_update()+ )+ row = (await session.execute(stmt)).scalar_one_or_none()+ if row is None:+ return None+ row.scopes_requested = list(+ requested_scopes+ if requested_scopes is not None+ else row.scopes_requested or row.scopes_granted or fallback_scopes or []+ )+ row.consent_nonce = consent_nonce+ row.consent_redirect_uri = consent_redirect_uri+ row.consent_expires_at = consent_expires_at+ row.consent_code_verifier = consent_code_verifier+ row.consent_app_origin = consent_app_origin+ row.client_id = client_id+ row.modified_at = now+ await session.flush()+ result = GoogleOAuthCredentialBase.model_validate(row, from_attributes=True)+ await session.commit()+ return result++ @db_operation("mark_needs_reconnect")+ async def mark_needs_reconnect(+ self,+ organization_id: str,+ credential_id: str,+ now: datetime.datetime,+ expected_version: datetime.datetime | None = None,+ ) -> str | None:+ """Flip an active credential to ``error`` after its refresh token is rejected upstream.++ No-op when the row is no longer active or changed after the failing refresh loaded it.+ """+ async with self.Session() as session:+ filters = [+ GoogleOAuthCredentialModel.id == credential_id,+ GoogleOAuthCredentialModel.organization_id == organization_id,+ GoogleOAuthCredentialModel.state == STATE_ACTIVE,+ ]+ if expected_version is not None:+ filters.append(GoogleOAuthCredentialModel.modified_at == expected_version)+ stmt = (+ update(GoogleOAuthCredentialModel)+ .where(*filters)+ .values(state=STATE_ERROR, modified_at=now)+ .returning(GoogleOAuthCredentialModel.id)+ )+ flipped = (await session.execute(stmt)).scalar_one_or_none()+ await session.commit()+ return flipped+@db_operation("mark_active_mismatched_client_as_error")async def mark_active_mismatched_client_as_error(self,@@ -169,12 +256,16 @@ class GoogleOAuthRepository(BaseRepository):now: datetime.datetime,) -> GoogleOAuthCredentialBase:async with self.Session() as session:+ # Promotes both a first-connect row (``pending_consent``) and an in-place re-auth of an+ # existing ``active``/``error`` row: whichever row currently holds this nonce receives the+ # new refresh token and is (re)set to ``active``, preserving the credential id so workflows+ # keep referencing the same connection.stmt = (update(GoogleOAuthCredentialModel).where(GoogleOAuthCredentialModel.consent_nonce == nonce,GoogleOAuthCredentialModel.organization_id == organization_id,- GoogleOAuthCredentialModel.state == STATE_PENDING_CONSENT,+ GoogleOAuthCredentialModel.state.in_([STATE_PENDING_CONSENT, STATE_ACTIVE, STATE_ERROR]),GoogleOAuthCredentialModel.consent_expires_at >= now,).values(@@ -201,12 +292,11 @@ class GoogleOAuthRepository(BaseRepository):))).scalar_one_or_none()+ # A successful promotion (or revoke) nulls the nonce, so a missing row means the+ # nonce is unknown or already consumed. A row that still holds the nonce but failed+ # the UPDATE only failed the expiry guard.if fallback is None:- raise InvalidConsentNonceError("Unknown OAuth consent nonce")- if fallback.state == STATE_ERROR:- raise InvalidConsentNonceError("OAuth consent row is in error state")- if fallback.state != STATE_PENDING_CONSENT:- raise InvalidConsentNonceError("OAuth consent nonce already consumed")+ raise InvalidConsentNonceError("Unknown or already consumed OAuth consent nonce")raise InvalidConsentNonceError("OAuth consent nonce expired")result = GoogleOAuthCredentialBase.model_validate(promoted, from_attributes=True)await session.commit()@@ -257,6 +347,7 @@ class GoogleOAuthRepository(BaseRepository):GoogleOAuthCredentialModel.encrypted_method,GoogleOAuthCredentialModel.scopes_granted,GoogleOAuthCredentialModel.client_id,+ GoogleOAuthCredentialModel.modified_at,).where(GoogleOAuthCredentialModel.id == credential_id,GoogleOAuthCredentialModel.organization_id == organization_id,@@ -265,7 +356,7 @@ class GoogleOAuthRepository(BaseRepository):row = (await session.execute(stmt)).one_or_none()if row is None:return None- ciphertext, method, scopes, client_id = row+ ciphertext, method, scopes, client_id, credential_version = rowif not ciphertext or not method:return Nonereturn ActiveCredentialCiphertext(@@ -273,6 +364,7 @@ class GoogleOAuthRepository(BaseRepository):encrypted_method=EncryptMethod(method),scopes_granted=list(scopes or []),client_id=client_id,+ credential_version=credential_version,)@db_operation("load_ciphertext_for_revoke")@@ -316,7 +408,7 @@ class GoogleOAuthRepository(BaseRepository):.where(GoogleOAuthCredentialModel.id == credential_id,GoogleOAuthCredentialModel.organization_id == organization_id,- GoogleOAuthCredentialModel.state == STATE_ACTIVE,+ GoogleOAuthCredentialModel.state.in_([STATE_ACTIVE, STATE_ERROR]),).values(credential_name=credential_name, modified_at=now).returning(GoogleOAuthCredentialModel)diff --git a/skyvern/forge/sdk/routes/google_oauth.py b/skyvern/forge/sdk/routes/google_oauth.pyindex f2068f36a..f1e426781 100644--- a/skyvern/forge/sdk/routes/google_oauth.py+++ b/skyvern/forge/sdk/routes/google_oauth.py@@ -71,7 +71,10 @@ async def google_oauth_authorize(credential_name=request.credential_name,scope_profile=request.scope_profile,app_origin=request.app_origin,+ credential_id=request.credential_id,)+ except google_oauth_service.CredentialNotReauthorizableError as exc:+ raise HTTPException(status_code=404, detail=str(exc))except InvalidAppOriginError as exc:raise HTTPException(status_code=400, detail=str(exc))except google_oauth_service.UnsupportedScopeProfileError as exc:diff --git a/skyvern/forge/sdk/routes/google_sheets.py b/skyvern/forge/sdk/routes/google_sheets.pyindex 024541366..c14b9de8f 100644--- a/skyvern/forge/sdk/routes/google_sheets.py+++ b/skyvern/forge/sdk/routes/google_sheets.py@@ -52,6 +52,21 @@ async def _mint_access_token(organization_id: str, credential_id: str) -> str:)try:return await google_oauth_service.access_token_from_secrets(secrets, organization_id=organization_id)+ except google_oauth_service.ExpiredRefreshTokenError as exc:+ # Google rejected the refresh token as revoked/expired; record the needs-reconnect state so+ # the integrations UI reflects it, then route the caller to the reconnect flow.+ await google_oauth_service.mark_credential_expired(+ organization_id,+ credential_id,+ expected_version=secrets.credential_version,+ )+ raise HTTPException(+ status_code=409,+ detail={+ "code": "reconnect_required",+ "message": str(exc),+ },+ )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.pyindex e83d62587..5eb36055a 100644--- a/skyvern/forge/sdk/schemas/google_oauth.py+++ b/skyvern/forge/sdk/schemas/google_oauth.py@@ -103,6 +103,11 @@ class CreateGoogleOAuthAuthorizeRequest(BaseModel):description="Origin the callback should bounce back to (e.g. a Vercel preview URL). ""Must be on the GOOGLE_OAUTH_APP_ORIGINS allowlist.",)+ credential_id: str | None = Field(+ default=None,+ description="Existing credential to re-authenticate in place. When set, the connection keeps "+ "its identity so workflows referencing it continue to work without edits.",+ )class GoogleOAuthAuthorizeResponse(BaseModel):diff --git a/skyvern/forge/sdk/services/google_oauth_service.py b/skyvern/forge/sdk/services/google_oauth_service.pyindex e68d3bc6c..aee2efc3f 100644--- a/skyvern/forge/sdk/services/google_oauth_service.py+++ b/skyvern/forge/sdk/services/google_oauth_service.py@@ -12,18 +12,20 @@ from __future__ import annotationsimport asyncioimport datetimeimport secrets+from collections.abc import Mappingfrom dataclasses import dataclass, fieldfrom urllib.parse import urlparseimport httpximport structlog-from google.auth.exceptions import GoogleAuthError+from google.auth.exceptions import GoogleAuthError, RefreshErrorfrom google.auth.transport.requests import Request as GoogleAuthRequestfrom google.oauth2.credentials import Credentialsfrom google_auth_oauthlib.flow import Flowfrom skyvern.config import settingsfrom skyvern.forge import app+from skyvern.forge.sdk.cache.base import AsyncLock, NoopLockfrom skyvern.forge.sdk.db.enums import OrganizationAuthTokenTypefrom skyvern.forge.sdk.db.id import generate_google_oauth_credential_id@@ -78,12 +80,39 @@ GOOGLE_OAUTH_SCOPE_PROFILES: dict[str, tuple[str, ...]] = {}CONSENT_TTL_SECONDS = 600+GOOGLE_ACCESS_TOKEN_CACHE_LOCK_TIMEOUT_SECONDS = 120+GOOGLE_ACCESS_TOKEN_CACHE_LOCK_BLOCKING_TIMEOUT_SECONDS = 125def google_access_token_cache_key(organization_id: str, credential_id: str) -> str:return f"google:access_token:{organization_id}:{credential_id}"+def google_access_token_cache_lock_key(organization_id: str, credential_id: str) -> str:+ return f"{google_access_token_cache_key(organization_id, credential_id)}:lock"+++def google_access_token_cache_lock(organization_id: str, credential_id: str) -> AsyncLock:+ get_lock = getattr(app.CACHE, "get_lock", None)+ lock_name = google_access_token_cache_lock_key(organization_id, credential_id)+ if get_lock is None:+ return NoopLock(lock_name)+ return get_lock(+ lock_name,+ blocking_timeout=GOOGLE_ACCESS_TOKEN_CACHE_LOCK_BLOCKING_TIMEOUT_SECONDS,+ timeout=GOOGLE_ACCESS_TOKEN_CACHE_LOCK_TIMEOUT_SECONDS,+ )+++async def invalidate_google_access_token_cache(organization_id: str, credential_id: str) -> None:+ async with google_access_token_cache_lock(organization_id, credential_id):+ await app.CACHE.set(+ google_access_token_cache_key(organization_id, credential_id),+ "",+ ex=datetime.timedelta(seconds=30),+ )++class EncryptionNotConfiguredError(RuntimeError):"""Raised when Google credentials cannot be stored because AES encryption is disabled."""@@ -92,6 +121,18 @@ class MissingAccessTokenError(RuntimeError):"""Raised when Google returns a 2xx token response without an access_token."""+class ExpiredRefreshTokenError(MissingAccessTokenError):+ """Raised when Google rejects the stored refresh token (invalid_grant) because it was revoked+ or expired. Subclasses ``MissingAccessTokenError`` so existing reconnect handling still catches+ it, while letting callers flip the credential to a "needs reconnect" state on this signal alone+ (as opposed to a transient transport error)."""+++class CredentialNotReauthorizableError(ValueError):+ """Raised when an in-place re-auth targets a credential that does not exist for the org or is+ not in a re-authorizable (active/error) state."""++class InvalidRedirectURIError(ValueError):"""Raised when the supplied OAuth redirect_uri host is not on the allowlist."""@@ -116,6 +157,13 @@ class OrganizationClientConfigUnavailableError(RuntimeError):"""Raised when a stored org OAuth client config exists (or cannot be ruled out) but cannot be loaded."""+def _is_invalid_grant(exc: RefreshError) -> bool:+ for detail in exc.args:+ if isinstance(detail, Mapping):+ return detail.get("error") == "invalid_grant"+ return bool(exc.args and isinstance(exc.args[0], str) and exc.args[0].split(":", 1)[0] == "invalid_grant")++@dataclass(frozen=True)class GoogleCredentialSecrets:"""Decrypted credential material needed to mint an access token."""@@ -123,6 +171,7 @@ class GoogleCredentialSecrets:refresh_token: strscopes: list[str] = field(default_factory=list)client_id: str | None = None+ credential_version: datetime.datetime | None = None@dataclass(frozen=True)@@ -459,8 +508,15 @@ async def start_authorization(scopes_requested: str | list[str] | tuple[str, ...] | None = None,scope_profile: str | None = None,app_origin: str | None = None,+ credential_id: str | None = None,) -> GoogleAuthorizationStart:- """Insert a pending consent row, build the authorize URL, persist the PKCE verifier."""+ """Start the consent flow, build the authorize URL, and persist the PKCE verifier.++ When ``credential_id`` is provided, re-authorize that existing connection in place: the fresh+ consent challenge is stamped onto the same row (keeping its live token working) and the callback+ promotes it back to active, so the credential id — and every workflow referencing it — is+ preserved. Otherwise a new pending credential is created.+ """_require_encryption()resolved_config = await resolve_client_config(organization_id)if resolved_config.config is None:@@ -469,29 +525,56 @@ async def start_authorization(if app_origin is not None:_validate_app_origin(app_origin, resolved_config.config)- credential_id = generate_google_oauth_credential_id()nonce = secrets.token_urlsafe(32)# Pre-generate the PKCE verifier so the pending row lands with the verifier# populated in a single DB write — a crash mid-flow can no longer leave a# pending row that the callback would see as missing the verifier.code_verifier = secrets.token_urlsafe(64)now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)- requested_scopes = (- scopes_for_profile(scope_profile) if scopes_requested is None else _coerce_scopes(scopes_requested)- )-- await app.DATABASE.google_oauth.insert_pending_credential(- credential_id=credential_id,- organization_id=organization_id,- credential_name=credential_name,- scopes_requested=requested_scopes,- consent_nonce=nonce,- consent_redirect_uri=redirect_uri,- consent_expires_at=now + datetime.timedelta(seconds=CONSENT_TTL_SECONDS),- consent_app_origin=app_origin,- consent_code_verifier=code_verifier,- client_id=resolved_config.config.client_id,- )+ consent_expires_at = now + datetime.timedelta(seconds=CONSENT_TTL_SECONDS)++ if credential_id is not None:+ # Re-request the scopes originally granted to this connection unless the caller overrides,+ # so the reconnected credential stays usable by the same workflow blocks.+ if scope_profile is not None:+ requested_scopes_override = scopes_for_profile(scope_profile)+ elif scopes_requested is not None:+ requested_scopes_override = _coerce_scopes(scopes_requested)+ else:+ requested_scopes_override = None+ reauth = await app.DATABASE.google_oauth.begin_reauthorization(+ credential_id=credential_id,+ organization_id=organization_id,+ consent_nonce=nonce,+ consent_redirect_uri=redirect_uri,+ consent_expires_at=consent_expires_at,+ consent_code_verifier=code_verifier,+ now=now,+ consent_app_origin=app_origin,+ client_id=resolved_config.config.client_id,+ requested_scopes=requested_scopes_override,+ fallback_scopes=list(GOOGLE_SHEETS_SCOPES),+ )+ if reauth is None:+ raise CredentialNotReauthorizableError("Google OAuth credential not found or not in a reconnectable state")+ requested_scopes = _coerce_scopes(reauth.scopes_requested or reauth.scopes_granted)+ else:+ credential_id = generate_google_oauth_credential_id()+ requested_scopes = (+ scopes_for_profile(scope_profile) if scopes_requested is None else _coerce_scopes(scopes_requested)+ )+ await app.DATABASE.google_oauth.insert_pending_credential(+ credential_id=credential_id,+ organization_id=organization_id,+ credential_name=credential_name,+ scopes_requested=requested_scopes,+ consent_nonce=nonce,+ consent_redirect_uri=redirect_uri,+ consent_expires_at=consent_expires_at,+ consent_app_origin=app_origin,+ consent_code_verifier=code_verifier,+ client_id=resolved_config.config.client_id,+ )authorize_url, _ = build_authorize_url(redirect_uri=redirect_uri,@@ -514,7 +597,7 @@ async def promote_pending_credential(_require_encryption()encrypted_token = await encryptor.encrypt(refresh_token, EncryptMethod.AES)now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)- return await app.DATABASE.google_oauth.promote_pending_to_active(+ credential = await app.DATABASE.google_oauth.promote_pending_to_active(organization_id=organization_id,nonce=nonce,encrypted_refresh_token=encrypted_token,@@ -522,6 +605,58 @@ async def promote_pending_credential(scopes_granted=_coerce_scopes(scopes_granted),now=now,)+ # On a re-auth the credential id is reused, so serialize invalidation with token refreshes before+ # dropping the cached token. The next call then mints from the freshly stored refresh token.+ try:+ await invalidate_google_access_token_cache(organization_id, credential.id)+ except Exception:+ LOG.warning(+ "Failed to invalidate access-token cache after promotion",+ credential_id=credential.id,+ exc_info=True,+ )+ return credential+++async def mark_credential_expired(+ organization_id: str,+ credential_id: str,+ expected_version: datetime.datetime | None = None,+) -> None:+ """Flip an active credential to the "needs reconnect" (``error``) state after its refresh token+ is rejected upstream, and invalidate any cached access token. Best-effort: never raises, so the+ token-minting path stays ``token | None``.+ """+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)+ try:+ flipped = await app.DATABASE.google_oauth.mark_needs_reconnect(+ organization_id=organization_id,+ credential_id=credential_id,+ now=now,+ expected_version=expected_version,+ )+ except Exception:+ LOG.warning(+ "Failed to mark Google OAuth credential as needing reconnect",+ credential_id=credential_id,+ exc_info=True,+ )+ return+ if flipped is None:+ return+ LOG.info(+ "Marked Google OAuth credential as needing reconnect after refresh token was rejected",+ credential_id=credential_id,+ organization_id=organization_id,+ )+ try:+ await invalidate_google_access_token_cache(organization_id, credential_id)+ except Exception:+ LOG.warning(+ "Failed to invalidate access-token cache after marking credential expired",+ credential_id=credential_id,+ exc_info=True,+ )async def load_pending_consent_context(organization_id: str, nonce: str) -> PendingConsentContext | None:@@ -594,6 +729,10 @@ async def refresh_access_token()try:await asyncio.to_thread(creds.refresh, GoogleAuthRequest())+ except RefreshError as exc:+ if _is_invalid_grant(exc):+ raise ExpiredRefreshTokenError(f"Google rejected the refresh token: {exc}") from exc+ raise MissingAccessTokenError(f"Google token refresh failed: {exc}") from excexcept GoogleAuthError as exc:raise MissingAccessTokenError(f"Google token refresh failed: {exc}") from excreturn {@@ -618,6 +757,7 @@ async def load_credential_secrets(refresh_token=refresh_token,scopes=payload.scopes_granted,client_id=payload.client_id,+ credential_version=payload.credential_version,)@@ -672,6 +812,10 @@ async def credentials_from_secrets()try:await asyncio.to_thread(creds.refresh, GoogleAuthRequest())+ except RefreshError as exc:+ if _is_invalid_grant(exc):+ raise ExpiredRefreshTokenError(f"Google rejected the refresh token: {exc}") from exc+ raise MissingAccessTokenError(f"Google token refresh failed: {exc}") from excexcept GoogleAuthError as exc:raise MissingAccessTokenError(f"Google token refresh failed: {exc}") from excif not creds.token:@@ -714,7 +858,7 @@ async def rename_credential(credential_id: str,credential_name: str,) -> GoogleOAuthCredentialBase | None:- """Rename an active Google OAuth credential. Returns None for not-found / wrong-state / wrong-org."""+ """Rename a visible Google OAuth credential. Returns None for not-found / wrong-state / wrong-org."""now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)return await app.DATABASE.google_oauth.rename_active(organization_id=organization_id,@@ -756,8 +900,7 @@ async def revoke_credential(organization_id: str, credential_id: str) -> bool:if revoked_id is not None:try:# 30s tombstone outlives any in-flight token refresh that beat the revoke commit.- cache_key = google_access_token_cache_key(organization_id, credential_id)- await app.CACHE.set(cache_key, "", ex=datetime.timedelta(seconds=30))+ await invalidate_google_access_token_cache(organization_id, credential_id)except Exception:LOG.warning("Failed to invalidate access-token cache on revoke",diff --git a/tests/unit/google/test_agent_function_google_credentials.py b/tests/unit/google/test_agent_function_google_credentials.pyindex 7d3655a96..5cd09d82b 100644--- a/tests/unit/google/test_agent_function_google_credentials.py+++ b/tests/unit/google/test_agent_function_google_credentials.py@@ -6,6 +6,7 @@ failure-modes (missing encryption, missing credential, refresh failure)so a regression doesn't silently break Sheets blocks in OSS."""+import datetimefrom types import SimpleNamespacefrom unittest.mock import AsyncMock@@ -99,6 +100,64 @@ async def test_get_google_sheets_credentials_returns_none_on_refresh_failure(assert result is None+async def test_get_google_sheets_credentials_marks_expired_on_dead_refresh_token(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A rejected refresh token flips the credential to needs-reconnect so the UI reflects it."""+ credential_version = datetime.datetime(2026, 4, 20)+ secrets = google_oauth_service.GoogleCredentialSecrets(+ refresh_token="rt",+ scopes=[],+ credential_version=credential_version,+ )+ monkeypatch.setattr(+ google_oauth_service,+ "load_credential_secrets",+ AsyncMock(return_value=secrets),+ )++ async def raise_expired(*_args, **_kwargs):+ raise google_oauth_service.ExpiredRefreshTokenError("Google rejected the refresh token")++ monkeypatch.setattr(google_oauth_service, "access_token_from_secrets", raise_expired)+ mark_mock = AsyncMock()+ monkeypatch.setattr(google_oauth_service, "mark_credential_expired", mark_mock)++ result = await AgentFunction().get_google_sheets_credentials(+ organization_id="org_1",+ credential_id="goac_1",+ )+ assert result is None+ mark_mock.assert_awaited_once_with("org_1", "goac_1", expected_version=credential_version)+++async def test_get_google_workspace_credentials_marks_expired_on_dead_refresh_token(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ secrets = google_oauth_service.GoogleCredentialSecrets(refresh_token="rt", scopes=[])+ monkeypatch.setattr(+ google_oauth_service,+ "load_credential_secrets",+ AsyncMock(return_value=secrets),+ )++ async def raise_expired(*_args, **_kwargs):+ raise google_oauth_service.ExpiredRefreshTokenError("Google rejected the refresh token")++ monkeypatch.setattr(google_oauth_service, "credentials_from_secrets", raise_expired)+ mark_mock = AsyncMock()+ monkeypatch.setattr(google_oauth_service, "mark_credential_expired", mark_mock)++ result = await AgentFunction().get_google_workspace_credentials(+ organization_id="org_1",+ credential_id="goac_1",+ )+ assert result is None+ mark_mock.assert_awaited_once_with("org_1", "goac_1", expected_version=None)++@pytest.mark.asyncioasync def test_get_google_workspace_credentials_returns_credentials_on_success(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/google/test_google_oauth.py b/tests/unit/google/test_google_oauth.pyindex 8f071550f..39069f88b 100644--- a/tests/unit/google/test_google_oauth.py+++ b/tests/unit/google/test_google_oauth.py@@ -2,7 +2,7 @@ import asyncioimport datetimefrom types import SimpleNamespacefrom typing import Any, Awaitable, Callable-from unittest.mock import AsyncMock, call+from unittest.mock import AsyncMock, MagicMock, callfrom urllib.parse import parse_qs, urlparseimport httpx@@ -2026,6 +2026,42 @@ async def test_config_route_handlers_return_404_when_org_config_disabled(monkeypassert delete_exc_info.value.status_code == 404+async def test_authorize_route_forwards_credential_id_for_reconnect(monkeypatch: pytest.MonkeyPatch) -> None:+ start_mock = AsyncMock(+ return_value=google_oauth_service.GoogleAuthorizationStart(authorize_url="https://auth", state="st")+ )+ monkeypatch.setattr(google_oauth_routes.google_oauth_service, "start_authorization", start_mock)++ request = CreateGoogleOAuthAuthorizeRequest(redirect_uri="https://x/cb", credential_id="goac_existing")+ response = await google_oauth_routes.google_oauth_authorize(+ request=request,+ current_org=SimpleNamespace(organization_id="org_1"),+ )++ assert response.authorize_url == "https://auth"+ assert start_mock.await_args.kwargs["credential_id"] == "goac_existing"+++async def test_authorize_route_returns_404_when_credential_not_reauthorizable(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ google_oauth_routes.google_oauth_service,+ "start_authorization",+ AsyncMock(side_effect=google_oauth_service.CredentialNotReauthorizableError("nope")),+ )++ request = CreateGoogleOAuthAuthorizeRequest(redirect_uri="https://x/cb", credential_id="goac_missing")+ with pytest.raises(HTTPException) as exc_info:+ await google_oauth_routes.google_oauth_authorize(+ request=request,+ current_org=SimpleNamespace(organization_id="org_1"),+ )+ assert 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)@@ -2189,6 +2225,186 @@ async def test_start_authorization_refuses_without_encryption(monkeypatch: pytesfake_repo.insert_pending_credential.assert_not_awaited()+async def test_start_authorization_reconnect_reauthorizes_in_place(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(google_oauth_service.settings, "ENABLE_ENCRYPTION", True, raising=False)+ 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),+ )+ id_mock = MagicMock(return_value="goac_should_not_be_used")+ monkeypatch.setattr(google_oauth_service, "generate_google_oauth_credential_id", id_mock)++ reauth_scopes = ["https://www.googleapis.com/auth/spreadsheets"]+ reauth_mock = AsyncMock(+ return_value=SimpleNamespace(id="goac_existing", scopes_requested=reauth_scopes),+ )+ insert_mock = AsyncMock()+ fake_repo = SimpleNamespace(begin_reauthorization=reauth_mock, insert_pending_credential=insert_mock)+ 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",+ redirect_uri="https://x/cb",+ credential_id="goac_existing",+ )++ assert result.authorize_url.startswith(google_oauth_service.GOOGLE_AUTHORIZE_ENDPOINT)+ # Re-auth reuses the existing row; it must not mint a new id or insert a new pending row.+ insert_mock.assert_not_awaited()+ id_mock.assert_not_called()+ reauth_mock.assert_awaited_once()+ kwargs = reauth_mock.await_args.kwargs+ assert kwargs["credential_id"] == "goac_existing"+ assert kwargs["consent_nonce"] == result.state+ assert kwargs["client_id"] == "cid"+ # The originally granted scopes are re-requested so the reconnected credential stays usable.+ assert "scope=" in result.authorize_url+++async def test_start_authorization_reconnect_falls_back_to_legacy_granted_scopes(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(google_oauth_service.settings, "ENABLE_ENCRYPTION", True, raising=False)+ 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),+ )+ gmail_scope = "https://www.googleapis.com/auth/gmail.readonly"+ reauth_mock = AsyncMock(+ return_value=SimpleNamespace(+ id="goac_existing",+ scopes_requested=[],+ scopes_granted=[gmail_scope],+ ),+ )+ organizations = SimpleNamespace(get_valid_org_auth_token=AsyncMock(return_value=None))+ monkeypatch.setattr(+ google_oauth_service.app,+ "DATABASE",+ SimpleNamespace(+ google_oauth=SimpleNamespace(begin_reauthorization=reauth_mock),+ organizations=organizations,+ ),+ raising=False,+ )++ result = await google_oauth_service.start_authorization(+ organization_id="org_1",+ redirect_uri="https://x/cb",+ credential_id="goac_existing",+ )++ assert parse_qs(urlparse(result.authorize_url).query)["scope"] == [gmail_scope]+ assert reauth_mock.await_args.kwargs["fallback_scopes"] == list(google_oauth_service.GOOGLE_SHEETS_SCOPES)+++async def test_start_authorization_reconnect_raises_when_not_reauthorizable(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(google_oauth_service.settings, "ENABLE_ENCRYPTION", True, raising=False)+ 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),+ )+ fake_repo = SimpleNamespace(begin_reauthorization=AsyncMock(return_value=None))+ 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.CredentialNotReauthorizableError):+ await google_oauth_service.start_authorization(+ organization_id="org_1",+ redirect_uri="https://x/cb",+ credential_id="goac_missing",+ )+++async def test_refresh_access_token_wraps_transient_google_auth_error(monkeypatch: pytest.MonkeyPatch) -> None:+ from google.auth.exceptions import TransportError++ monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_ID", "cid", raising=False)+ monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_SECRET", "secret", raising=False)++ class _FakeCreds:+ def __init__(self, **_kwargs) -> None:+ self.token = None+ self.expiry = None++ def refresh(self, _request) -> None:+ raise TransportError("connection reset")++ monkeypatch.setattr(google_oauth_service, "Credentials", _FakeCreds)++ # A transient transport error is NOT an expired token — it must stay a plain+ # MissingAccessTokenError so callers don't wrongly flip the credential to needs-reconnect.+ with pytest.raises(google_oauth_service.MissingAccessTokenError, match="refresh failed") as excinfo:+ await google_oauth_service.refresh_access_token("rt-1")+ assert not isinstance(excinfo.value, google_oauth_service.ExpiredRefreshTokenError)+++async def test_mark_credential_expired_flips_and_invalidates_cache(monkeypatch: pytest.MonkeyPatch) -> None:+ mark_mock = AsyncMock(return_value="goac_1")+ fake_repo = SimpleNamespace(mark_needs_reconnect=mark_mock)+ monkeypatch.setattr(google_oauth_service.app, "DATABASE", SimpleNamespace(google_oauth=fake_repo), raising=False)+ fake_cache = SimpleNamespace(set=AsyncMock())+ monkeypatch.setattr(google_oauth_service.app, "CACHE", fake_cache, raising=False)++ credential_version = datetime.datetime(2026, 4, 20)+ await google_oauth_service.mark_credential_expired(+ "org_1",+ "goac_1",+ expected_version=credential_version,+ )++ mark_mock.assert_awaited_once()+ assert mark_mock.await_args.kwargs["credential_id"] == "goac_1"+ assert mark_mock.await_args.kwargs["expected_version"] == credential_version+ fake_cache.set.assert_awaited_once()+ assert fake_cache.set.await_args.args[0] == google_oauth_service.google_access_token_cache_key("org_1", "goac_1")+++async def test_mark_credential_expired_noop_when_not_active(monkeypatch: pytest.MonkeyPatch) -> None:+ mark_mock = AsyncMock(return_value=None)+ fake_repo = SimpleNamespace(mark_needs_reconnect=mark_mock)+ monkeypatch.setattr(google_oauth_service.app, "DATABASE", SimpleNamespace(google_oauth=fake_repo), raising=False)+ fake_cache = SimpleNamespace(set=AsyncMock())+ monkeypatch.setattr(google_oauth_service.app, "CACHE", fake_cache, raising=False)++ await google_oauth_service.mark_credential_expired("org_1", "goac_1")++ mark_mock.assert_awaited_once()+ # Nothing flipped ⇒ no cache churn.+ fake_cache.set.assert_not_awaited()++@pytest.mark.asyncioasync def test_promote_pending_credential_encrypts_and_calls_repo(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(google_oauth_service.settings, "ENABLE_ENCRYPTION", True, raising=False)@@ -2199,6 +2415,8 @@ async def test_promote_pending_credential_encrypts_and_calls_repo(monkeypatch: ppromote_mock = AsyncMock(return_value=promoted_schema)fake_repo = SimpleNamespace(promote_pending_to_active=promote_mock)monkeypatch.setattr(google_oauth_service.app, "DATABASE", SimpleNamespace(google_oauth=fake_repo), raising=False)+ fake_cache = SimpleNamespace(set=AsyncMock())+ monkeypatch.setattr(google_oauth_service.app, "CACHE", fake_cache, raising=False)result = await google_oauth_service.promote_pending_credential(organization_id="org_1",@@ -2216,6 +2434,10 @@ async def test_promote_pending_credential_encrypts_and_calls_repo(monkeypatch: passert kwargs["encrypted_refresh_token"] == "ENC::rt"assert kwargs["encrypted_method"] == EncryptMethod.AESassert kwargs["scopes_granted"] == ["https://a", "https://b"]+ # A re-auth reuses the credential id, so a token cached before rotation must be dropped.+ fake_cache.set.assert_awaited_once()+ cache_key = fake_cache.set.await_args.args[0]+ assert cache_key == google_oauth_service.google_access_token_cache_key("org_1", "goac_1")@pytest.mark.asyncio@@ -2495,11 +2717,13 @@ async def test_revoke_google_endpoint_swallows_errors(monkeypatch: pytest.Monkeyasync def test_load_credential_secrets_decrypts_repo_payload(monkeypatch: pytest.MonkeyPatch) -> None:from skyvern.forge.sdk.db.repositories.google_oauth import ActiveCredentialCiphertext+ credential_version = datetime.datetime(2026, 4, 20)payload = ActiveCredentialCiphertext(encrypted_refresh_token="ENC::rt",encrypted_method=EncryptMethod.AES,scopes_granted=["https://a", "https://b"],client_id="client-1",+ credential_version=credential_version,)fake_repo = SimpleNamespace(load_active_ciphertext=AsyncMock(return_value=payload))monkeypatch.setattr(google_oauth_service.app, "DATABASE", SimpleNamespace(google_oauth=fake_repo), raising=False)@@ -2515,6 +2739,7 @@ async def test_load_credential_secrets_decrypts_repo_payload(monkeypatch: pytestassert secrets.refresh_token == "refresh-123"assert secrets.scopes == ["https://a", "https://b"]assert secrets.client_id == "client-1"+ assert secrets.credential_version == credential_versiondecrypt_mock.assert_awaited_once_with("ENC::rt", EncryptMethod.AES)@@ -2835,10 +3060,36 @@ async def test_refresh_access_token_wraps_google_auth_error(monkeypatch: pytest.monkeypatch.setattr(google_oauth_service, "Credentials", _FakeCreds)- with pytest.raises(google_oauth_service.MissingAccessTokenError, match="refresh failed"):+ # invalid_grant surfaces as a RefreshError; classify it as an expired refresh token so callers+ # can flip the credential to "needs reconnect" rather than treat it as a transient failure.+ with pytest.raises(google_oauth_service.ExpiredRefreshTokenError, match="rejected the refresh token"):await google_oauth_service.refresh_access_token("rt-bad")+async def test_refresh_access_token_does_not_expire_credential_for_invalid_client(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from google.auth.exceptions import RefreshError++ monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_ID", "cid", raising=False)+ monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_SECRET", "secret", raising=False)++ class _FakeCreds:+ def __init__(self, **_kwargs) -> None:+ self.token = None+ self.expiry = None++ def refresh(self, _request) -> None:+ raise RefreshError("invalid_client: client authentication failed", {"error": "invalid_client"})++ monkeypatch.setattr(google_oauth_service, "Credentials", _FakeCreds)++ with pytest.raises(google_oauth_service.MissingAccessTokenError, match="refresh failed") as excinfo:+ await google_oauth_service.refresh_access_token("rt-valid")+ assert not isinstance(excinfo.value, google_oauth_service.ExpiredRefreshTokenError)++@pytest.mark.asyncioasync def test_credentials_from_secrets_wraps_google_auth_error(monkeypatch: pytest.MonkeyPatch) -> None:from google.auth.exceptions import RefreshError@@ -2851,12 +3102,15 @@ async def test_credentials_from_secrets_wraps_google_auth_error(monkeypatch: pytself.token = Nonedef refresh(self, _request) -> None:- raise RefreshError("token revoked")+ raise RefreshError(+ "invalid_grant: Token has been expired or revoked.",+ {"error": "invalid_grant"},+ )monkeypatch.setattr(google_oauth_service, "Credentials", _FakeCreds)secrets = google_oauth_service.GoogleCredentialSecrets(refresh_token="rt-1", scopes=["https://a"])- with pytest.raises(google_oauth_service.MissingAccessTokenError, match="refresh failed"):+ with pytest.raises(google_oauth_service.ExpiredRefreshTokenError, match="rejected the refresh token"):await google_oauth_service.credentials_from_secrets(secrets)diff --git a/tests/unit/google/test_google_oauth_repository.py b/tests/unit/google/test_google_oauth_repository.pyindex 745f0e51f..77a94ea26 100644--- a/tests/unit/google/test_google_oauth_repository.py+++ b/tests/unit/google/test_google_oauth_repository.py@@ -206,6 +206,22 @@ async def test_rename_active_returns_schema_without_greenlet_error(assert renamed.credential_name == "New Name"assert renamed.state == "active"+ await repo.mark_needs_reconnect(+ organization_id="o_test",+ credential_id="gcred_rename",+ now=datetime.datetime.utcnow(),+ )+ renamed_while_expired = await repo.rename_active(+ organization_id="o_test",+ credential_id="gcred_rename",+ credential_name="Reconnect Me",+ now=datetime.datetime.utcnow(),+ )++ assert renamed_while_expired is not None+ assert renamed_while_expired.credential_name == "Reconnect Me"+ assert renamed_while_expired.state == STATE_ERROR+@pytest.mark.asyncioasync def test_consent_app_origin_round_trips_through_load_pending_by_nonce(@@ -376,6 +392,263 @@ async def test_load_pending_by_nonce_filters_expired_rows(assert ctx is None+async def _seed_active_credential(+ repo: GoogleOAuthRepository,+ credential_id: str,+ nonce: str,+ *,+ client_id: str | None = None,+ scopes: list[str] | None = None,+) -> None:+ expires_at = datetime.datetime.utcnow() + datetime.timedelta(minutes=10)+ await repo.insert_pending_credential(+ credential_id=credential_id,+ organization_id="o_test",+ credential_name="Default",+ scopes_requested=scopes or ["https://www.googleapis.com/auth/spreadsheets"],+ consent_nonce=nonce,+ consent_redirect_uri="https://app/callback",+ consent_expires_at=expires_at,+ consent_code_verifier=f"ver-{credential_id}",+ client_id=client_id,+ )+ await repo.promote_pending_to_active(+ organization_id="o_test",+ nonce=nonce,+ encrypted_refresh_token=f"cipher-{credential_id}",+ encrypted_method=EncryptMethod.AES,+ scopes_granted=scopes or ["https://www.googleapis.com/auth/spreadsheets"],+ now=datetime.datetime.utcnow(),+ )+++async def test_begin_reauthorization_stamps_consent_without_disturbing_live_token(+ repo: GoogleOAuthRepository,+) -> None:+ await _seed_active_credential(repo, "gcred_reauth", "nonce-initial", client_id="client-old")+ reauth_at = datetime.datetime.utcnow()++ result = await repo.begin_reauthorization(+ credential_id="gcred_reauth",+ organization_id="o_test",+ consent_nonce="nonce-reauth",+ consent_redirect_uri="https://app/callback",+ consent_expires_at=reauth_at + datetime.timedelta(minutes=10),+ consent_code_verifier="ver-reauth",+ now=reauth_at,+ consent_app_origin="https://app",+ client_id="client-new",+ )++ assert result is not None+ assert result.id == "gcred_reauth"+ # State is untouched and the live token still resolves, so referencing workflows keep working.+ assert result.state == STATE_ACTIVE+ payload = await repo.load_active_ciphertext(organization_id="o_test", credential_id="gcred_reauth")+ assert payload is not None+ assert payload.encrypted_refresh_token == "cipher-gcred_reauth"+ # The new consent challenge is now loadable by its nonce for the callback.+ ctx = await repo.load_pending_by_nonce(organization_id="o_test", nonce="nonce-reauth")+ assert ctx is not None+ assert ctx.credential_id == "gcred_reauth"+ assert ctx.consent_code_verifier == "ver-reauth"+ assert ctx.client_id == "client-new"+++async def test_begin_reauthorization_persists_granted_scopes_for_legacy_credential(+ repo: GoogleOAuthRepository,+) -> None:+ gmail_scopes = ["https://www.googleapis.com/auth/gmail.readonly"]+ expires_at = datetime.datetime.utcnow() + datetime.timedelta(minutes=10)+ await repo.insert_pending_credential(+ credential_id="gcred_legacy_scopes",+ organization_id="o_test",+ credential_name="Default",+ scopes_requested=[],+ consent_nonce="nonce-initial",+ consent_redirect_uri="https://app/callback",+ consent_expires_at=expires_at,+ consent_code_verifier="ver-initial",+ )+ await repo.promote_pending_to_active(+ organization_id="o_test",+ nonce="nonce-initial",+ encrypted_refresh_token="cipher-legacy",+ encrypted_method=EncryptMethod.AES,+ scopes_granted=gmail_scopes,+ now=datetime.datetime.utcnow(),+ )++ result = await repo.begin_reauthorization(+ credential_id="gcred_legacy_scopes",+ organization_id="o_test",+ consent_nonce="nonce-reauth",+ consent_redirect_uri="https://app/callback",+ consent_expires_at=expires_at,+ consent_code_verifier="ver-reauth",+ now=datetime.datetime.utcnow(),+ requested_scopes=None,+ fallback_scopes=["https://www.googleapis.com/auth/spreadsheets"],+ )++ assert result is not None+ assert result.scopes_requested == gmail_scopes+++async def test_begin_reauthorization_promotes_in_place_preserving_id(+ repo: GoogleOAuthRepository,+) -> None:+ await _seed_active_credential(repo, "gcred_inplace", "nonce-initial")+ await repo.mark_needs_reconnect(+ organization_id="o_test",+ credential_id="gcred_inplace",+ now=datetime.datetime.utcnow(),+ )+ reauth_at = datetime.datetime.utcnow()+ await repo.begin_reauthorization(+ credential_id="gcred_inplace",+ organization_id="o_test",+ consent_nonce="nonce-reauth",+ consent_redirect_uri="https://app/callback",+ consent_expires_at=reauth_at + datetime.timedelta(minutes=10),+ consent_code_verifier="ver-reauth",+ now=reauth_at,+ )++ promoted = await repo.promote_pending_to_active(+ organization_id="o_test",+ nonce="nonce-reauth",+ encrypted_refresh_token="cipher-rotated",+ encrypted_method=EncryptMethod.AES,+ scopes_granted=["https://www.googleapis.com/auth/spreadsheets"],+ now=datetime.datetime.utcnow(),+ )++ assert promoted.id == "gcred_inplace"+ assert promoted.state == STATE_ACTIVE+ payload = await repo.load_active_ciphertext(organization_id="o_test", credential_id="gcred_inplace")+ assert payload is not None+ assert payload.encrypted_refresh_token == "cipher-rotated"+++async def test_begin_reauthorization_returns_none_for_non_reauthorizable_rows(+ repo: GoogleOAuthRepository,+) -> None:+ await _seed_active_credential(repo, "gcred_ok", "nonce-ok")+ await repo.mark_revoked_and_scrub(+ organization_id="o_test",+ credential_id="gcred_ok",+ now=datetime.datetime.utcnow(),+ )+ now = datetime.datetime.utcnow()+ common = dict(+ organization_id="o_test",+ consent_nonce="nonce-x",+ consent_redirect_uri="https://app/callback",+ consent_expires_at=now + datetime.timedelta(minutes=10),+ consent_code_verifier="ver-x",+ now=now,+ )++ revoked = await repo.begin_reauthorization(credential_id="gcred_ok", **common)+ missing = await repo.begin_reauthorization(credential_id="gcred_missing", **common)++ assert revoked is None+ assert missing is None+++async def test_mark_needs_reconnect_flips_active_only(+ repo: GoogleOAuthRepository,+ engine: AsyncEngine,+) -> None:+ await _seed_active_credential(repo, "gcred_active", "nonce-active")+ await _seed_active_credential(repo, "gcred_revoked", "nonce-revoked")+ await repo.mark_revoked_and_scrub(+ organization_id="o_test",+ credential_id="gcred_revoked",+ now=datetime.datetime.utcnow(),+ )++ flipped = await repo.mark_needs_reconnect(+ organization_id="o_test",+ credential_id="gcred_active",+ now=datetime.datetime.utcnow(),+ )+ # Second call is a no-op: the row is already error, not active.+ flipped_again = await repo.mark_needs_reconnect(+ organization_id="o_test",+ credential_id="gcred_active",+ now=datetime.datetime.utcnow(),+ )+ revoked_noop = await repo.mark_needs_reconnect(+ organization_id="o_test",+ credential_id="gcred_revoked",+ now=datetime.datetime.utcnow(),+ )++ assert flipped == "gcred_active"+ assert flipped_again is None+ assert revoked_noop is None+ async with engine.connect() as conn:+ states = dict(+ (+ await conn.execute(+ select(GoogleOAuthCredentialModel.id, GoogleOAuthCredentialModel.state).where(+ GoogleOAuthCredentialModel.id.in_(["gcred_active", "gcred_revoked"])+ )+ )+ ).all()+ )+ assert states == {"gcred_active": STATE_ERROR, "gcred_revoked": STATE_REVOKED}+++async def test_stale_refresh_cannot_expire_reauthorized_credential(+ repo: GoogleOAuthRepository,+) -> None:+ await _seed_active_credential(repo, "gcred_race", "nonce-initial")+ stale_payload = await repo.load_active_ciphertext(+ organization_id="o_test",+ credential_id="gcred_race",+ )+ assert stale_payload is not None++ reauth_at = stale_payload.credential_version + datetime.timedelta(seconds=1)+ await repo.begin_reauthorization(+ credential_id="gcred_race",+ organization_id="o_test",+ consent_nonce="nonce-reauth",+ consent_redirect_uri="https://app/callback",+ consent_expires_at=reauth_at + datetime.timedelta(minutes=10),+ consent_code_verifier="ver-reauth",+ now=reauth_at,+ )+ await repo.promote_pending_to_active(+ organization_id="o_test",+ nonce="nonce-reauth",+ encrypted_refresh_token="cipher-new",+ encrypted_method=EncryptMethod.AES,+ scopes_granted=["https://www.googleapis.com/auth/spreadsheets"],+ now=reauth_at + datetime.timedelta(seconds=1),+ )++ flipped = await repo.mark_needs_reconnect(+ organization_id="o_test",+ credential_id="gcred_race",+ now=reauth_at + datetime.timedelta(seconds=2),+ expected_version=stale_payload.credential_version,+ )++ assert flipped is None+ visible = await repo.list_visible_for_org("o_test")+ assert visible[0].state == STATE_ACTIVE++@pytest.mark.asyncioasync def test_mark_active_mismatched_client_as_error_flips_only_mismatched_bound_active_rows(repo: GoogleOAuthRepository,