Skip to content

Automate browser based workflows with AI

feat(SKY-12134): bind Google OAuth credentials to their OAuth client config (#7288)

Suchintan6e384633bfe2
diff --git a/alembic/versions/2026_07_10_2309-7a729fa75d9b_bind_google_oauth_credentials_client_config.py b/alembic/versions/2026_07_10_2309-7a729fa75d9b_bind_google_oauth_credentials_client_config.py
new file mode 100644
index 000000000..6284f6969
--- /dev/null
+++ b/alembic/versions/2026_07_10_2309-7a729fa75d9b_bind_google_oauth_credentials_client_config.py
@@ -0,0 +1,27 @@
+"""bind google oauth credentials client config
+
+Revision ID: 7a729fa75d9b
+Revises: e1227914ecfe
+Create Date: 2026-07-10T23:09:58.950836+00:00
+
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "7a729fa75d9b"
+down_revision: Union[str, None] = "e1227914ecfe"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.add_column("google_oauth_credentials", sa.Column("client_id", sa.String(), nullable=True))
+
+
+def downgrade() -> None:
+ op.drop_column("google_oauth_credentials", "client_id")
diff --git a/skyvern-frontend/src/routes/workflows/components/GoogleOAuthCredentialSelector.tsx b/skyvern-frontend/src/routes/workflows/components/GoogleOAuthCredentialSelector.tsx
index 03ba3eb9a..8813357b6 100644
--- a/skyvern-frontend/src/routes/workflows/components/GoogleOAuthCredentialSelector.tsx
+++ b/skyvern-frontend/src/routes/workflows/components/GoogleOAuthCredentialSelector.tsx
@@ -13,6 +13,7 @@ import { WorkflowBlockInputTextarea } from "@/components/WorkflowBlockInputTexta
import {
getDefaultGoogleOAuthCredentialId,
hasGoogleOAuthCredentialScopes,
+ isGoogleOAuthCredentialActive,
useGoogleOAuthCredentials,
} from "@/hooks/useGoogleOAuthCredentials";
import { PlusIcon } from "@radix-ui/react-icons";
@@ -39,8 +40,10 @@ function GoogleOAuthCredentialSelector({
isFetching,
} = useGoogleOAuthCredentials();
const [showAdvanced, setShowAdvanced] = useState(false);
- const credentials = allCredentials.filter((credential) =>
- hasGoogleOAuthCredentialScopes(credential, requiredScopes),
+ const credentials = allCredentials.filter(
+ (credential) =>
+ isGoogleOAuthCredentialActive(credential) &&
+ hasGoogleOAuthCredentialScopes(credential, requiredScopes),
);
// Keep latest callback without forcing effect re-runs.
diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.py
index c37cf515a..7c5fd4721 100644
--- a/skyvern/forge/sdk/db/models.py
+++ b/skyvern/forge/sdk/db/models.py
@@ -1867,6 +1867,7 @@ class GoogleOAuthCredentialModel(Base):
consent_code_verifier = Column(String, nullable=True)
consent_app_origin = Column(String, nullable=True)
consent_expires_at = Column(DateTime, nullable=True)
+ client_id = Column(String, nullable=True)
created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)
modified_at = Column(
DateTime,
diff --git a/skyvern/forge/sdk/db/repositories/google_oauth.py b/skyvern/forge/sdk/db/repositories/google_oauth.py
index 850417610..b5843240d 100644
--- a/skyvern/forge/sdk/db/repositories/google_oauth.py
+++ b/skyvern/forge/sdk/db/repositories/google_oauth.py
@@ -39,6 +39,7 @@ class PendingConsentContext:
consent_redirect_uri: str | None
consent_code_verifier: str | None
consent_app_origin: str | None = None
+ client_id: str | None = None
@dataclass(frozen=True)
@@ -46,6 +47,7 @@ class ActiveCredentialCiphertext:
encrypted_refresh_token: str
encrypted_method: EncryptMethod
scopes_granted: list[str]
+ client_id: str | None = None
@dataclass(frozen=True)
@@ -70,6 +72,7 @@ class GoogleOAuthRepository(BaseRepository):
consent_expires_at: datetime.datetime,
consent_code_verifier: str,
consent_app_origin: str | None = None,
+ client_id: str | None = None,
) -> GoogleOAuthCredentialBase:
async with self.Session() as session:
model = GoogleOAuthCredentialModel(
@@ -85,6 +88,7 @@ class GoogleOAuthRepository(BaseRepository):
consent_expires_at=consent_expires_at,
consent_app_origin=consent_app_origin,
consent_code_verifier=consent_code_verifier,
+ client_id=client_id,
)
session.add(model)
await session.flush()
@@ -109,6 +113,7 @@ class GoogleOAuthRepository(BaseRepository):
GoogleOAuthCredentialModel.consent_redirect_uri,
GoogleOAuthCredentialModel.consent_code_verifier,
GoogleOAuthCredentialModel.consent_app_origin,
+ GoogleOAuthCredentialModel.client_id,
).where(
GoogleOAuthCredentialModel.consent_nonce == nonce,
GoogleOAuthCredentialModel.organization_id == organization_id,
@@ -123,8 +128,36 @@ class GoogleOAuthRepository(BaseRepository):
consent_redirect_uri=row[1],
consent_code_verifier=row[2],
consent_app_origin=row[3],
+ client_id=row[4],
)
+ @db_operation("mark_active_mismatched_client_as_error")
+ async def mark_active_mismatched_client_as_error(
+ self,
+ organization_id: str,
+ new_client_id: str | None,
+ now: datetime.datetime,
+ ) -> int:
+ async with self.Session() as session:
+ filters = [
+ GoogleOAuthCredentialModel.organization_id == organization_id,
+ GoogleOAuthCredentialModel.state == STATE_ACTIVE,
+ GoogleOAuthCredentialModel.client_id.is_not(None),
+ ]
+ if new_client_id is not None:
+ filters.append(GoogleOAuthCredentialModel.client_id != new_client_id)
+ stmt = (
+ update(GoogleOAuthCredentialModel)
+ .where(*filters)
+ .values(
+ state=STATE_ERROR,
+ modified_at=now,
+ )
+ )
+ result = await session.execute(stmt)
+ await session.commit()
+ return result.rowcount or 0
+
@db_operation("promote_pending_to_active")
async def promote_pending_to_active(
self,
@@ -198,6 +231,20 @@ class GoogleOAuthRepository(BaseRepository):
rows = (await session.execute(stmt)).scalars().all()
return [GoogleOAuthCredentialBase.model_validate(r, from_attributes=True) for r in rows]
+ @db_operation("list_visible_for_org")
+ async def list_visible_for_org(self, organization_id: str) -> list[GoogleOAuthCredentialBase]:
+ async with self.Session() as session:
+ stmt = (
+ select(GoogleOAuthCredentialModel)
+ .where(
+ GoogleOAuthCredentialModel.organization_id == organization_id,
+ GoogleOAuthCredentialModel.state.in_([STATE_ACTIVE, STATE_ERROR]),
+ )
+ .order_by(GoogleOAuthCredentialModel.created_at.desc())
+ )
+ rows = (await session.execute(stmt)).scalars().all()
+ return [GoogleOAuthCredentialBase.model_validate(r, from_attributes=True) for r in rows]
+
@db_operation("load_active_ciphertext")
async def load_active_ciphertext(
self,
@@ -209,6 +256,7 @@ class GoogleOAuthRepository(BaseRepository):
GoogleOAuthCredentialModel.encrypted_refresh_token,
GoogleOAuthCredentialModel.encrypted_method,
GoogleOAuthCredentialModel.scopes_granted,
+ GoogleOAuthCredentialModel.client_id,
).where(
GoogleOAuthCredentialModel.id == credential_id,
GoogleOAuthCredentialModel.organization_id == organization_id,
@@ -217,13 +265,14 @@ class GoogleOAuthRepository(BaseRepository):
row = (await session.execute(stmt)).one_or_none()
if row is None:
return None
- ciphertext, method, scopes = row
+ ciphertext, method, scopes, client_id = row
if not ciphertext or not method:
return None
return ActiveCredentialCiphertext(
encrypted_refresh_token=ciphertext,
encrypted_method=EncryptMethod(method),
scopes_granted=list(scopes or []),
+ client_id=client_id,
)
@db_operation("load_ciphertext_for_revoke")
diff --git a/skyvern/forge/sdk/routes/google_oauth.py b/skyvern/forge/sdk/routes/google_oauth.py
index c9d37888c..f2068f36a 100644
--- a/skyvern/forge/sdk/routes/google_oauth.py
+++ b/skyvern/forge/sdk/routes/google_oauth.py
@@ -105,6 +105,15 @@ async def google_oauth_callback(
status_code=400,
detail="OAuth consent row is missing the PKCE verifier; restart the consent flow",
)
+ 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))
+ if context.client_id is not None and (resolved.config is None or resolved.config.client_id != context.client_id):
+ raise HTTPException(
+ status_code=409,
+ detail="Google OAuth client configuration changed since consent started; restart the connection",
+ )
try:
token_data = await google_oauth_service.exchange_code_for_tokens(
@@ -112,6 +121,7 @@ async def google_oauth_callback(
redirect_uri=context.consent_redirect_uri,
code_verifier=context.consent_code_verifier,
organization_id=current_org.organization_id,
+ client_config=resolved.config,
)
except google_oauth_service.OrganizationClientConfigUnavailableError as exc:
raise HTTPException(status_code=503, detail=str(exc))
@@ -229,7 +239,7 @@ async def list_google_oauth_credentials(
current_org: Annotated[Organization, Depends(org_auth_service.get_current_org)],
) -> GoogleOAuthCredentialListResponse:
"""Fetch a list of Google OAuth credentials associated with an organization."""
- credentials = await google_oauth_service.get_credentials_for_org(
+ credentials = await google_oauth_service.get_visible_credentials_for_org(
organization_id=current_org.organization_id,
)
return GoogleOAuthCredentialListResponse(credentials=credentials)
diff --git a/skyvern/forge/sdk/services/google_oauth_service.py b/skyvern/forge/sdk/services/google_oauth_service.py
index 2e817c3c8..e68d3bc6c 100644
--- a/skyvern/forge/sdk/services/google_oauth_service.py
+++ b/skyvern/forge/sdk/services/google_oauth_service.py
@@ -108,6 +108,10 @@ class OrganizationGoogleOAuthConfigDisabledError(RuntimeError):
"""Raised when org-level Google OAuth client config is disabled for this deployment."""
+class ClientConfigMismatchError(ValueError):
+ """Raised when a credential's stored OAuth client no longer matches the resolved client config."""
+
+
class OrganizationClientConfigUnavailableError(RuntimeError):
"""Raised when a stored org OAuth client config exists (or cannot be ruled out) but cannot be loaded."""
@@ -118,6 +122,7 @@ class GoogleCredentialSecrets:
refresh_token: str
scopes: list[str] = field(default_factory=list)
+ client_id: str | None = None
@dataclass(frozen=True)
@@ -228,6 +233,18 @@ async def save_client_config(
token=token_payload,
encrypted_method=EncryptMethod.AES,
)
+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
+ flipped = await app.DATABASE.google_oauth.mark_active_mismatched_client_as_error(
+ organization_id=organization_id,
+ new_client_id=config.client_id,
+ now=now,
+ )
+ if flipped:
+ LOG.info(
+ "Marked Google OAuth credentials for reconnect after client config change",
+ organization_id=organization_id,
+ count=flipped,
+ )
return GoogleOAuthClientConfigResolution(config=config, source="organization")
@@ -237,6 +254,19 @@ async def delete_client_config(organization_id: str) -> None:
organization_id=organization_id,
token_type=OrganizationAuthTokenType.google_oauth_client_config,
)
+ env_config = _settings_client_config()
+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
+ flipped = await app.DATABASE.google_oauth.mark_active_mismatched_client_as_error(
+ organization_id=organization_id,
+ new_client_id=env_config.client_id if env_config else None,
+ now=now,
+ )
+ if flipped:
+ LOG.info(
+ "Marked Google OAuth credentials for reconnect after client config change",
+ organization_id=organization_id,
+ count=flipped,
+ )
def _require_client_credentials(client_config: GoogleOAuthClientConfig | None = None) -> tuple[str, str]:
@@ -460,6 +490,7 @@ async def start_authorization(
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,
)
authorize_url, _ = build_authorize_url(
@@ -506,10 +537,13 @@ async def exchange_code_for_tokens(
redirect_uri: str,
code_verifier: str | None,
organization_id: str | None = None,
+ client_config: GoogleOAuthClientConfig | None = None,
) -> dict:
"""Exchange an OAuth authorization code for access and refresh tokens."""
- resolved_config = await resolve_client_config(organization_id)
- client_id, client_secret = _require_client_credentials(resolved_config.config)
+ if client_config is None:
+ resolved_config = await resolve_client_config(organization_id)
+ client_config = resolved_config.config
+ client_id, client_secret = _require_client_credentials(client_config)
# ``code_verifier`` is passed to ``fetch_token`` (where the PKCE verification
# actually happens); ``Flow.from_client_config`` ignores the kwarg.
@@ -540,10 +574,16 @@ async def exchange_code_for_tokens(
}
-async def refresh_access_token(refresh_token: str, organization_id: str | None = None) -> dict:
+async def refresh_access_token(
+ refresh_token: str,
+ organization_id: str | None = None,
+ client_config: GoogleOAuthClientConfig | None = None,
+) -> dict:
"""Exchange a refresh token for a new access token via google-auth."""
- resolved_config = await resolve_client_config(organization_id, strict=False)
- client_id, client_secret = _require_client_credentials(resolved_config.config)
+ if client_config is None:
+ resolved_config = await resolve_client_config(organization_id, strict=False)
+ client_config = resolved_config.config
+ client_id, client_secret = _require_client_credentials(client_config)
creds = Credentials(
token=None,
@@ -574,7 +614,11 @@ async def load_credential_secrets(
if payload is None:
raise ValueError(f"No active Google OAuth credential found: {credential_id}")
refresh_token = await encryptor.decrypt(payload.encrypted_refresh_token, payload.encrypted_method)
- return GoogleCredentialSecrets(refresh_token=refresh_token, scopes=payload.scopes_granted)
+ return GoogleCredentialSecrets(
+ refresh_token=refresh_token,
+ scopes=payload.scopes_granted,
+ client_id=payload.client_id,
+ )
async def access_token_from_secrets(
@@ -587,7 +631,18 @@ async def access_token_from_secrets(
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)
+ resolved_config = await resolve_client_config(organization_id, strict=False)
+ if credential_secrets.client_id is not None and (
+ resolved_config.config is None or resolved_config.config.client_id != credential_secrets.client_id
+ ):
+ raise ClientConfigMismatchError(
+ "Google OAuth client configuration changed since this credential was connected; reconnect the account"
+ )
+ token_data = await refresh_access_token(
+ credential_secrets.refresh_token,
+ organization_id=organization_id,
+ client_config=resolved_config.config,
+ )
access_token = token_data.get("access_token")
if not access_token:
raise MissingAccessTokenError("Google token response did not include access_token")
@@ -600,6 +655,12 @@ async def credentials_from_secrets(
) -> Credentials:
"""Build a refreshed ``Credentials`` from already-decrypted secrets. Network-only; no DB."""
resolved_config = await resolve_client_config(organization_id, strict=False)
+ if credential_secrets.client_id is not None and (
+ resolved_config.config is None or resolved_config.config.client_id != credential_secrets.client_id
+ ):
+ raise ClientConfigMismatchError(
+ "Google OAuth client configuration changed since this credential was connected; reconnect the account"
+ )
client_id, client_secret = _require_client_credentials(resolved_config.config)
creds = Credentials(
token=None,
@@ -623,6 +684,10 @@ async def get_credentials_for_org(organization_id: str) -> list[GoogleOAuthCrede
return await app.DATABASE.google_oauth.list_active_for_org(organization_id=organization_id)
+async def get_visible_credentials_for_org(organization_id: str) -> list[GoogleOAuthCredentialBase]:
+ return await app.DATABASE.google_oauth.list_visible_for_org(organization_id=organization_id)
+
+
# google-auth 2.x has no first-class async revoke helper; keep the 10-line httpx POST.
async def _revoke_refresh_token_at_google(refresh_token: str) -> None:
"""Best-effort call to Google's revoke endpoint."""
diff --git a/tests/unit/google/test_google_oauth.py b/tests/unit/google/test_google_oauth.py
index 05f2282a7..0e7e8b3da 100644
--- a/tests/unit/google/test_google_oauth.py
+++ b/tests/unit/google/test_google_oauth.py
@@ -1,3 +1,4 @@
+import datetime
from types import SimpleNamespace
from typing import Any, Awaitable, Callable
from unittest.mock import AsyncMock
@@ -14,6 +15,8 @@ from skyvern.forge.sdk.encrypt.base import EncryptMethod
from skyvern.forge.sdk.routes import google_oauth as google_oauth_routes
from skyvern.forge.sdk.schemas.google_oauth import (
CreateGoogleOAuthAuthorizeRequest,
+ CreateGoogleOAuthCallbackRequest,
+ GoogleOAuthCredentialBase,
UpdateGoogleOAuthClientConfigRequest,
UpdateGoogleOAuthCredentialRequest,
)
@@ -562,10 +565,11 @@ async def test_save_client_config_requires_encryption(monkeypatch: pytest.Monkey
)
monkeypatch.setattr(google_oauth_service.settings, "ENABLE_ENCRYPTION", False, raising=False)
organizations = SimpleNamespace(replace_org_auth_token=AsyncMock())
+ google_oauth = SimpleNamespace(mark_active_mismatched_client_as_error=AsyncMock())
monkeypatch.setattr(
google_oauth_service.app,
"DATABASE",
- SimpleNamespace(organizations=organizations),
+ SimpleNamespace(organizations=organizations, google_oauth=google_oauth),
raising=False,
)
@@ -575,6 +579,7 @@ async def test_save_client_config_requires_encryption(monkeypatch: pytest.Monkey
google_oauth_service.GoogleOAuthClientConfig(client_id="cid", client_secret="secret"),
)
organizations.replace_org_auth_token.assert_not_awaited()
+ google_oauth.mark_active_mismatched_client_as_error.assert_not_awaited()
@pytest.mark.asyncio
@@ -610,10 +615,14 @@ async def test_save_client_config_uses_aes(monkeypatch: pytest.MonkeyPatch) -> N
)
monkeypatch.setattr(google_oauth_service.settings, "ENABLE_ENCRYPTION", True, raising=False)
replace_mock = AsyncMock()
+ mark_mock = AsyncMock(return_value=2)
monkeypatch.setattr(
google_oauth_service.app,
"DATABASE",
- SimpleNamespace(organizations=SimpleNamespace(replace_org_auth_token=replace_mock)),
+ SimpleNamespace(
+ organizations=SimpleNamespace(replace_org_auth_token=replace_mock),
+ google_oauth=SimpleNamespace(mark_active_mismatched_client_as_error=mark_mock),
+ ),
raising=False,
)
@@ -624,6 +633,42 @@ async def test_save_client_config_uses_aes(monkeypatch: pytest.MonkeyPatch) -> N
assert resolved.config == config
replace_mock.assert_awaited_once()
assert replace_mock.await_args.kwargs["encrypted_method"] is EncryptMethod.AES
+ mark_mock.assert_awaited_once()
+ assert mark_mock.await_args.kwargs["organization_id"] == "org_1"
+ assert mark_mock.await_args.kwargs["new_client_id"] == "cid"
+ assert isinstance(mark_mock.await_args.kwargs["now"], datetime.datetime)
+
+
+async def test_save_client_config_does_not_mark_mismatched_when_save_fails(
+ 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(side_effect=RuntimeError("save failed"))
+ mark_mock = AsyncMock()
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(
+ organizations=SimpleNamespace(replace_org_auth_token=replace_mock),
+ google_oauth=SimpleNamespace(mark_active_mismatched_client_as_error=mark_mock),
+ ),
+ raising=False,
+ )
+
+ with pytest.raises(RuntimeError, match="save failed"):
+ await google_oauth_service.save_client_config(
+ "org_1",
+ google_oauth_service.GoogleOAuthClientConfig(client_id="cid", client_secret="secret"),
+ )
+
+ replace_mock.assert_awaited_once()
+ mark_mock.assert_not_awaited()
@pytest.mark.asyncio
@@ -633,11 +678,52 @@ async def test_delete_client_config_invalidates_org_token_when_enabled(monkeypat
"get_settings",
lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
)
+ 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)
invalidate_mock = AsyncMock()
+ mark_mock = AsyncMock(return_value=1)
monkeypatch.setattr(
google_oauth_service.app,
"DATABASE",
- SimpleNamespace(organizations=SimpleNamespace(invalidate_org_auth_tokens=invalidate_mock)),
+ SimpleNamespace(
+ organizations=SimpleNamespace(invalidate_org_auth_tokens=invalidate_mock),
+ google_oauth=SimpleNamespace(mark_active_mismatched_client_as_error=mark_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,
+ )
+ mark_mock.assert_awaited_once()
+ assert mark_mock.await_args.kwargs["organization_id"] == "org_1"
+ assert mark_mock.await_args.kwargs["new_client_id"] == "env-client"
+ assert isinstance(mark_mock.await_args.kwargs["now"], datetime.datetime)
+
+
+async def test_delete_client_config_marks_mismatched_against_missing_env_config(
+ 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, "GOOGLE_OAUTH_CLIENT_ID", "", raising=False)
+ monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_SECRET", "", raising=False)
+ invalidate_mock = AsyncMock()
+ mark_mock = AsyncMock(return_value=1)
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(
+ organizations=SimpleNamespace(invalidate_org_auth_tokens=invalidate_mock),
+ google_oauth=SimpleNamespace(mark_active_mismatched_client_as_error=mark_mock),
+ ),
raising=False,
)
@@ -647,6 +733,9 @@ async def test_delete_client_config_invalidates_org_token_when_enabled(monkeypat
organization_id="org_1",
token_type=OrganizationAuthTokenType.google_oauth_client_config,
)
+ mark_mock.assert_awaited_once()
+ assert mark_mock.await_args.kwargs["organization_id"] == "org_1"
+ assert mark_mock.await_args.kwargs["new_client_id"] is None
@pytest.mark.asyncio
@@ -1013,6 +1102,7 @@ async def test_start_authorization_persists_verifier_and_returns_url(monkeypatch
assert insert_kwargs["credential_name"] == "my-cred"
assert insert_kwargs["consent_redirect_uri"] == "https://x/cb"
assert insert_kwargs["consent_nonce"] == result.state
+ assert insert_kwargs["client_id"] == "cid"
# The verifier must be in the same insert as everything else — no second
# round-trip — so a crash mid-flow can't leave a verifier-less pending row.
assert insert_kwargs["consent_code_verifier"]
@@ -1208,6 +1298,43 @@ async def test_exchange_code_for_tokens_falls_back_to_session_token_scope(monkey
assert result["scope"] == "https://a/scope"
+async def test_exchange_code_for_tokens_uses_provided_client_config_without_resolving(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ resolve_mock = AsyncMock()
+ monkeypatch.setattr(google_oauth_service, "resolve_client_config", resolve_mock)
+ config = google_oauth_service.GoogleOAuthClientConfig(
+ client_id="provided-client",
+ client_secret="provided-secret",
+ )
+ creds = SimpleNamespace(
+ token="at",
+ refresh_token="rt",
+ scopes=None,
+ granted_scopes="https://a/scope",
+ expiry=None,
+ )
+ captured = _install_fake_flow(
+ monkeypatch,
+ credentials=creds,
+ session_token={"scope": "https://a/scope", "access_token": "at"},
+ )
+
+ result = await google_oauth_service.exchange_code_for_tokens(
+ code="abc",
+ redirect_uri="https://x/cb",
+ code_verifier="v",
+ organization_id="org_1",
+ client_config=config,
+ )
+
+ assert result["access_token"] == "at"
+ assert captured["client_config"]["web"]["client_id"] == "provided-client"
+ assert captured["client_config"]["web"]["client_secret"] == "provided-secret"
+ resolve_mock.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_exchange_code_raises_without_client_creds(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_ID", None, raising=False)
@@ -1306,6 +1433,7 @@ async def test_load_credential_secrets_decrypts_repo_payload(monkeypatch: pytest
encrypted_refresh_token="ENC::rt",
encrypted_method=EncryptMethod.AES,
scopes_granted=["https://a", "https://b"],
+ client_id="client-1",
)
fake_repo = SimpleNamespace(load_active_ciphertext=AsyncMock(return_value=payload))
monkeypatch.setattr(google_oauth_service.app, "DATABASE", SimpleNamespace(google_oauth=fake_repo), raising=False)
@@ -1320,6 +1448,7 @@ async def test_load_credential_secrets_decrypts_repo_payload(monkeypatch: pytest
assert secrets.refresh_token == "refresh-123"
assert secrets.scopes == ["https://a", "https://b"]
+ assert secrets.client_id == "client-1"
decrypt_mock.assert_awaited_once_with("ENC::rt", EncryptMethod.AES)
@@ -1351,6 +1480,51 @@ async def test_get_credentials_for_org_delegates_to_repo(monkeypatch: pytest.Mon
list_mock.assert_awaited_once_with(organization_id="org_1")
+async def test_get_visible_credentials_for_org_delegates_to_repo(monkeypatch: pytest.MonkeyPatch) -> None:
+ credentials = [SimpleNamespace(id="goac_active", state="active"), SimpleNamespace(id="goac_error", state="error")]
+ list_mock = AsyncMock(return_value=credentials)
+ monkeypatch.setattr(
+ google_oauth_service.app,
+ "DATABASE",
+ SimpleNamespace(google_oauth=SimpleNamespace(list_visible_for_org=list_mock)),
+ raising=False,
+ )
+
+ result = await google_oauth_service.get_visible_credentials_for_org(organization_id="org_1")
+
+ assert result is credentials
+ list_mock.assert_awaited_once_with(organization_id="org_1")
+
+
+async def test_list_google_oauth_credentials_surfaces_error_state(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ google_oauth_routes.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
+ credential = GoogleOAuthCredentialBase(
+ id="goac_error",
+ organization_id="org_1",
+ credential_name="Needs reconnect",
+ state="error",
+ created_at=now,
+ modified_at=now,
+ )
+ list_mock = AsyncMock(return_value=[credential])
+ monkeypatch.setattr(google_oauth_routes.google_oauth_service, "get_visible_credentials_for_org", list_mock)
+
+ response = await google_oauth_routes.list_google_oauth_credentials(
+ current_org=SimpleNamespace(organization_id="org_1")
+ )
+
+ assert response.credentials == [credential]
+ assert response.credentials[0].state == "error"
+ list_mock.assert_awaited_once_with(organization_id="org_1")
+
+
@pytest.mark.asyncio
async def test_access_token_from_secrets_calls_refresh(monkeypatch: pytest.MonkeyPatch) -> None:
refresh_mock = AsyncMock(return_value={"access_token": "at-456"})
@@ -1367,6 +1541,62 @@ 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_raises_on_client_config_mismatch(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ resolve_mock = AsyncMock(
+ return_value=google_oauth_service.GoogleOAuthClientConfigResolution(
+ config=google_oauth_service.GoogleOAuthClientConfig(client_id="new", client_secret="secret"),
+ source="organization",
+ )
+ )
+ refresh_mock = AsyncMock()
+ monkeypatch.setattr(google_oauth_service, "resolve_client_config", resolve_mock)
+ monkeypatch.setattr(google_oauth_service, "refresh_access_token", refresh_mock)
+
+ secrets = google_oauth_service.GoogleCredentialSecrets(refresh_token="rt-1", client_id="old")
+
+ with pytest.raises(google_oauth_service.ClientConfigMismatchError, match="configuration changed"):
+ await google_oauth_service.access_token_from_secrets(secrets, organization_id="org_1")
+
+ resolve_mock.assert_awaited_once_with("org_1", strict=False)
+ refresh_mock.assert_not_awaited()
+
+
[email protected]("stored_client_id", ["client-1", None])
+async def test_access_token_from_secrets_passes_resolved_config_to_refresh(
+ monkeypatch: pytest.MonkeyPatch,
+ stored_client_id: str | None,
+) -> 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="client-1", client_secret="secret")
+ resolve_mock = AsyncMock(
+ return_value=google_oauth_service.GoogleOAuthClientConfigResolution(config=config, source="organization")
+ )
+ refresh_mock = AsyncMock(return_value={"access_token": "at-456"})
+ monkeypatch.setattr(google_oauth_service, "resolve_client_config", resolve_mock)
+ monkeypatch.setattr(google_oauth_service, "refresh_access_token", refresh_mock)
+
+ secrets = google_oauth_service.GoogleCredentialSecrets(refresh_token="rt-1", client_id=stored_client_id)
+
+ token = await google_oauth_service.access_token_from_secrets(secrets, organization_id="org_1")
+
+ assert token == "at-456"
+ resolve_mock.assert_awaited_once_with("org_1", strict=False)
+ refresh_mock.assert_awaited_once_with("rt-1", organization_id="org_1", client_config=config)
+
+
@pytest.mark.asyncio
async def test_access_token_from_secrets_falls_back_to_env_when_org_config_load_raises(
monkeypatch: pytest.MonkeyPatch,
@@ -1564,6 +1794,79 @@ async def test_credentials_from_secrets_wraps_google_auth_error(monkeypatch: pyt
await google_oauth_service.credentials_from_secrets(secrets)
+async def test_credentials_from_secrets_raises_on_client_config_mismatch(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ resolve_mock = AsyncMock(
+ return_value=google_oauth_service.GoogleOAuthClientConfigResolution(
+ config=google_oauth_service.GoogleOAuthClientConfig(client_id="new", client_secret="secret"),
+ source="organization",
+ )
+ )
+ monkeypatch.setattr(google_oauth_service, "resolve_client_config", resolve_mock)
+
+ class _UnexpectedCreds:
+ def __init__(self, **_kwargs) -> None:
+ raise AssertionError("Credentials should not be constructed")
+
+ monkeypatch.setattr(google_oauth_service, "Credentials", _UnexpectedCreds)
+
+ secrets = google_oauth_service.GoogleCredentialSecrets(
+ refresh_token="rt-1",
+ scopes=["https://a"],
+ client_id="old",
+ )
+ with pytest.raises(google_oauth_service.ClientConfigMismatchError, match="configuration changed"):
+ await google_oauth_service.credentials_from_secrets(secrets, organization_id="org_1")
+
+ resolve_mock.assert_awaited_once_with("org_1", strict=False)
+
+
+async def test_credentials_from_secrets_allows_matching_client_config(
+ 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="client-1", client_secret="secret")
+ resolve_mock = AsyncMock(
+ return_value=google_oauth_service.GoogleOAuthClientConfigResolution(config=config, source="organization")
+ )
+ monkeypatch.setattr(google_oauth_service, "resolve_client_config", resolve_mock)
+ captured: dict = {}
+
+ class _FakeCreds:
+ def __init__(self, **kwargs) -> None:
+ captured["init_kwargs"] = kwargs
+ self.token: str | None = None
+
+ def refresh(self, request) -> None:
+ self.token = "at-refreshed"
+
+ monkeypatch.setattr(google_oauth_service, "Credentials", _FakeCreds)
+
+ secrets = google_oauth_service.GoogleCredentialSecrets(
+ refresh_token="rt-decoded",
+ scopes=["https://a"],
+ client_id="client-1",
+ )
+ creds = await google_oauth_service.credentials_from_secrets(secrets, organization_id="org_1")
+
+ assert creds.token == "at-refreshed"
+ assert captured["init_kwargs"]["client_id"] == "client-1"
+ assert captured["init_kwargs"]["client_secret"] == "secret"
+ resolve_mock.assert_awaited_once_with("org_1", strict=False)
+
+
@pytest.mark.asyncio
async def test_credentials_from_secrets_returns_refreshed_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(google_oauth_service.settings, "GOOGLE_OAUTH_CLIENT_ID", "cid", raising=False)
@@ -1612,6 +1915,135 @@ def test_update_google_oauth_credential_request_enforces_max_length() -> None:
UpdateGoogleOAuthCredentialRequest(credential_name="x" * 129)
+async def test_google_oauth_callback_rejects_changed_client_before_exchange(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from skyvern.forge.sdk.db.repositories.google_oauth import PendingConsentContext
+
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ load_mock = AsyncMock(
+ return_value=PendingConsentContext(
+ credential_id="goac_1",
+ consent_redirect_uri="https://x/cb",
+ consent_code_verifier="verifier",
+ client_id="old-client",
+ )
+ )
+ resolve_mock = AsyncMock(
+ return_value=google_oauth_service.GoogleOAuthClientConfigResolution(
+ config=google_oauth_service.GoogleOAuthClientConfig(client_id="new-client", client_secret="secret"),
+ source="organization",
+ )
+ )
+ exchange_mock = AsyncMock()
+ monkeypatch.setattr(google_oauth_routes.google_oauth_service, "load_pending_consent_context", load_mock)
+ monkeypatch.setattr(google_oauth_routes.google_oauth_service, "resolve_client_config", resolve_mock)
+ monkeypatch.setattr(google_oauth_routes.google_oauth_service, "exchange_code_for_tokens", exchange_mock)
+
+ with pytest.raises(HTTPException) as exc_info:
+ await google_oauth_routes.google_oauth_callback(
+ CreateGoogleOAuthCallbackRequest(code="code", state="nonce"),
+ current_org=SimpleNamespace(organization_id="org_1"),
+ )
+
+ assert exc_info.value.status_code == 409
+ assert (
+ exc_info.value.detail
+ == "Google OAuth client configuration changed since consent started; restart the connection"
+ )
+ load_mock.assert_awaited_once_with(organization_id="org_1", nonce="nonce")
+ resolve_mock.assert_awaited_once_with("org_1")
+ exchange_mock.assert_not_awaited()
+
+
+ ("context_client_id", "resolved_client_id"),
+ [
+ ("old-client", "old-client"),
+ (None, None),
+ ],
+)
+async def test_google_oauth_callback_allows_matching_or_legacy_client(
+ monkeypatch: pytest.MonkeyPatch,
+ context_client_id: str | None,
+ resolved_client_id: str | None,
+) -> None:
+ from skyvern.forge.sdk.db.repositories.google_oauth import PendingConsentContext
+
+ monkeypatch.setattr(
+ google_oauth_service.SettingsManager,
+ "get_settings",
+ lambda: SimpleNamespace(ENABLE_ORGANIZATION_GOOGLE_OAUTH_CLIENT_CONFIG=True),
+ )
+ load_mock = AsyncMock(
+ return_value=PendingConsentContext(
+ credential_id="goac_1",
+ consent_redirect_uri="https://x/cb",
+ consent_code_verifier="verifier",
+ client_id=context_client_id,
+ )
+ )
+ resolved_config = (
+ google_oauth_service.GoogleOAuthClientConfig(client_id=resolved_client_id, client_secret="secret")
+ if resolved_client_id
+ else None
+ )
+ resolve_mock = AsyncMock(
+ return_value=google_oauth_service.GoogleOAuthClientConfigResolution(
+ config=resolved_config,
+ source="organization" if resolved_config else "missing",
+ )
+ )
+ exchange_mock = AsyncMock(
+ return_value={
+ "refresh_token": "refresh-token",
+ "scope": "https://www.googleapis.com/auth/spreadsheets",
+ }
+ )
+ credential = GoogleOAuthCredentialBase(
+ id="goac_1",
+ organization_id="org_1",
+ credential_name="Default",
+ provider="google",
+ state="active",
+ scopes_requested=[],
+ scopes_granted=["https://www.googleapis.com/auth/spreadsheets"],
+ created_at=datetime.datetime.utcnow(),
+ modified_at=datetime.datetime.utcnow(),
+ )
+ promote_mock = AsyncMock(return_value=credential)
+ monkeypatch.setattr(google_oauth_routes.google_oauth_service, "load_pending_consent_context", load_mock)
+ monkeypatch.setattr(google_oauth_routes.google_oauth_service, "resolve_client_config", resolve_mock)
+ monkeypatch.setattr(google_oauth_routes.google_oauth_service, "exchange_code_for_tokens", exchange_mock)
+ monkeypatch.setattr(google_oauth_routes.google_oauth_service, "promote_pending_credential", promote_mock)
+
+ response = await google_oauth_routes.google_oauth_callback(
+ CreateGoogleOAuthCallbackRequest(code="code", state="nonce"),
+ current_org=SimpleNamespace(organization_id="org_1"),
+ )
+
+ assert response.credential.id == "goac_1"
+ exchange_mock.assert_awaited_once_with(
+ code="code",
+ redirect_uri="https://x/cb",
+ code_verifier="verifier",
+ organization_id="org_1",
+ client_config=resolved_config,
+ )
+ promote_mock.assert_awaited_once_with(
+ organization_id="org_1",
+ nonce="nonce",
+ refresh_token="refresh-token",
+ scopes_granted=["https://www.googleapis.com/auth/spreadsheets"],
+ )
+
+
@pytest.mark.asyncio
async def test_rename_credential_delegates_to_repo(monkeypatch: pytest.MonkeyPatch) -> None:
renamed = SimpleNamespace(id="goac_1", credential_name="Personal Gmail")
diff --git a/tests/unit/google/test_google_oauth_repository.py b/tests/unit/google/test_google_oauth_repository.py
index fc492ee02..745f0e51f 100644
--- a/tests/unit/google/test_google_oauth_repository.py
+++ b/tests/unit/google/test_google_oauth_repository.py
@@ -3,12 +3,16 @@ from typing import AsyncGenerator
import pytest
import pytest_asyncio
+from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from skyvern.forge.sdk.db.base_alchemy_db import BaseAlchemyDB
from skyvern.forge.sdk.db.models import Base, GoogleOAuthCredentialModel # noqa: F401 - registers model on Base
from skyvern.forge.sdk.db.repositories.google_oauth import (
+ STATE_ACTIVE,
+ STATE_ERROR,
STATE_PENDING_CONSENT,
+ STATE_REVOKED,
GoogleOAuthRepository,
)
from skyvern.forge.sdk.encrypt.base import EncryptMethod
@@ -30,6 +34,83 @@ async def repo(engine: AsyncEngine) -> GoogleOAuthRepository:
return GoogleOAuthRepository(db.Session, debug_enabled=False)
+async def _seed_credentials_for_list_tests(engine: AsyncEngine) -> None:
+ now = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
+ async with engine.begin() as conn:
+ await conn.execute(
+ GoogleOAuthCredentialModel.__table__.insert(),
+ [
+ {
+ "id": "gcred_active",
+ "organization_id": "o_test",
+ "credential_name": "Active",
+ "state": STATE_ACTIVE,
+ "created_at": now,
+ "modified_at": now,
+ },
+ {
+ "id": "gcred_error",
+ "organization_id": "o_test",
+ "credential_name": "Error",
+ "state": STATE_ERROR,
+ "created_at": now,
+ "modified_at": now,
+ },
+ {
+ "id": "gcred_pending",
+ "organization_id": "o_test",
+ "credential_name": "Pending",
+ "state": STATE_PENDING_CONSENT,
+ "created_at": now,
+ "modified_at": now,
+ },
+ {
+ "id": "gcred_revoked",
+ "organization_id": "o_test",
+ "credential_name": "Revoked",
+ "state": STATE_REVOKED,
+ "created_at": now,
+ "modified_at": now,
+ },
+ {
+ "id": "gcred_other_org",
+ "organization_id": "o_other",
+ "credential_name": "Other",
+ "state": STATE_ACTIVE,
+ "created_at": now,
+ "modified_at": now,
+ },
+ ],
+ )
+
+
+async def test_list_visible_for_org_returns_active_and_error_only(
+ repo: GoogleOAuthRepository,
+ engine: AsyncEngine,
+) -> None:
+ await _seed_credentials_for_list_tests(engine)
+
+ credentials = await repo.list_visible_for_org("o_test")
+
+ assert {(credential.id, credential.state) for credential in credentials} == {
+ ("gcred_active", STATE_ACTIVE),
+ ("gcred_error", STATE_ERROR),
+ }
+
+
+async def test_list_active_for_org_excludes_error(
+ repo: GoogleOAuthRepository,
+ engine: AsyncEngine,
+) -> None:
+ await _seed_credentials_for_list_tests(engine)
+
+ credentials = await repo.list_active_for_org("o_test")
+
+ assert [(credential.id, credential.state) for credential in credentials] == [("gcred_active", STATE_ACTIVE)]
+
+
@pytest.mark.asyncio
async def test_insert_pending_credential_returns_schema_without_greenlet_error(
repo: GoogleOAuthRepository,
@@ -175,6 +256,104 @@ async def test_consent_app_origin_defaults_to_none_for_backward_compat(
assert ctx.consent_app_origin is None
+async def test_pending_client_id_round_trips_through_load_pending_by_nonce(
+ repo: GoogleOAuthRepository,
+ engine: AsyncEngine,
+) -> None:
+ expires_at = datetime.datetime.utcnow() + datetime.timedelta(minutes=10)
+ await repo.insert_pending_credential(
+ credential_id="gcred_client_id",
+ organization_id="o_test",
+ credential_name="Default",
+ scopes_requested=["https://www.googleapis.com/auth/spreadsheets"],
+ consent_nonce="nonce-client-id",
+ consent_redirect_uri="https://app-staging.skyvern.com/integrations/google/callback",
+ consent_expires_at=expires_at,
+ consent_code_verifier="ver-client-id",
+ client_id="client-old",
+ )
+ await repo.insert_pending_credential(
+ credential_id="gcred_legacy_client_id",
+ organization_id="o_test",
+ credential_name="Default",
+ scopes_requested=["https://www.googleapis.com/auth/spreadsheets"],
+ consent_nonce="nonce-legacy-client-id",
+ consent_redirect_uri="https://app-staging.skyvern.com/integrations/google/callback",
+ consent_expires_at=expires_at,
+ consent_code_verifier="ver-legacy-client-id",
+ )
+
+ async with engine.connect() as conn:
+ stored_client_id = (
+ await conn.execute(
+ select(GoogleOAuthCredentialModel.client_id).where(
+ GoogleOAuthCredentialModel.id == "gcred_client_id",
+ )
+ )
+ ).scalar_one()
+
+ bound_ctx = await repo.load_pending_by_nonce(organization_id="o_test", nonce="nonce-client-id")
+ legacy_ctx = await repo.load_pending_by_nonce(organization_id="o_test", nonce="nonce-legacy-client-id")
+
+ assert stored_client_id == "client-old"
+ assert bound_ctx is not None
+ assert bound_ctx.client_id == "client-old"
+ assert legacy_ctx is not None
+ assert legacy_ctx.client_id is None
+
+
+async def test_load_active_ciphertext_returns_stored_client_id_and_legacy_none(
+ repo: GoogleOAuthRepository,
+) -> None:
+ expires_at = datetime.datetime.utcnow() + datetime.timedelta(minutes=10)
+ await repo.insert_pending_credential(
+ credential_id="gcred_active_client_id",
+ organization_id="o_test",
+ credential_name="Default",
+ scopes_requested=["https://www.googleapis.com/auth/spreadsheets"],
+ consent_nonce="nonce-active-client-id",
+ consent_redirect_uri="https://app-staging.skyvern.com/integrations/google/callback",
+ consent_expires_at=expires_at,
+ consent_code_verifier="ver-active-client-id",
+ client_id="client-active",
+ )
+ await repo.insert_pending_credential(
+ credential_id="gcred_active_legacy",
+ organization_id="o_test",
+ credential_name="Default",
+ scopes_requested=["https://www.googleapis.com/auth/spreadsheets"],
+ consent_nonce="nonce-active-legacy",
+ consent_redirect_uri="https://app-staging.skyvern.com/integrations/google/callback",
+ consent_expires_at=expires_at,
+ consent_code_verifier="ver-active-legacy",
+ )
+ for nonce in ("nonce-active-client-id", "nonce-active-legacy"):
+ await repo.promote_pending_to_active(
+ organization_id="o_test",
+ nonce=nonce,
+ encrypted_refresh_token=f"cipher-{nonce}",
+ encrypted_method=EncryptMethod.AES,
+ scopes_granted=["https://www.googleapis.com/auth/spreadsheets"],
+ now=datetime.datetime.utcnow(),
+ )
+
+ bound_payload = await repo.load_active_ciphertext(
+ organization_id="o_test",
+ credential_id="gcred_active_client_id",
+ )
+ legacy_payload = await repo.load_active_ciphertext(
+ organization_id="o_test",
+ credential_id="gcred_active_legacy",
+ )
+
+ assert bound_payload is not None
+ assert bound_payload.client_id == "client-active"
+ assert legacy_payload is not None
+ assert legacy_payload.client_id is None
+
+
@pytest.mark.asyncio
async def test_load_pending_by_nonce_filters_expired_rows(
repo: GoogleOAuthRepository,
@@ -195,3 +374,129 @@ async def test_load_pending_by_nonce_filters_expired_rows(
ctx = await repo.load_pending_by_nonce(organization_id="o_test", nonce="nonce-expired")
assert ctx is None
+
+
+async def test_mark_active_mismatched_client_as_error_flips_only_mismatched_bound_active_rows(
+ repo: GoogleOAuthRepository,
+ engine: AsyncEngine,
+) -> None:
+ expires_at = datetime.datetime.utcnow() + datetime.timedelta(minutes=10)
+ rows = [
+ ("gcred_flip", "nonce-flip", "old"),
+ ("gcred_match", "nonce-match", "new"),
+ ("gcred_legacy", "nonce-legacy", None),
+ ("gcred_pending", "nonce-pending", "old"),
+ ("gcred_revoked", "nonce-revoked", "old"),
+ ]
+ for credential_id, nonce, client_id in rows:
+ await repo.insert_pending_credential(
+ credential_id=credential_id,
+ organization_id="o_test",
+ credential_name="Default",
+ scopes_requested=["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,
+ )
+ for nonce in ("nonce-flip", "nonce-match", "nonce-legacy", "nonce-revoked"):
+ await repo.promote_pending_to_active(
+ organization_id="o_test",
+ nonce=nonce,
+ encrypted_refresh_token="cipher-value",
+ encrypted_method=EncryptMethod.AES,
+ scopes_granted=["https://www.googleapis.com/auth/spreadsheets"],
+ now=datetime.datetime.utcnow(),
+ )
+ await repo.mark_revoked_and_scrub(
+ organization_id="o_test",
+ credential_id="gcred_revoked",
+ now=datetime.datetime.utcnow(),
+ )
+
+ changed = await repo.mark_active_mismatched_client_as_error(
+ organization_id="o_test",
+ new_client_id="new",
+ now=datetime.datetime.utcnow(),
+ )
+
+ async with engine.connect() as conn:
+ states = dict(
+ (
+ await conn.execute(
+ select(GoogleOAuthCredentialModel.id, GoogleOAuthCredentialModel.state).where(
+ GoogleOAuthCredentialModel.id.in_(
+ ["gcred_flip", "gcred_match", "gcred_legacy", "gcred_pending", "gcred_revoked"]
+ )
+ )
+ )
+ ).all()
+ )
+
+ assert changed == 1
+ assert states == {
+ "gcred_flip": STATE_ERROR,
+ "gcred_match": STATE_ACTIVE,
+ "gcred_legacy": STATE_ACTIVE,
+ "gcred_pending": STATE_PENDING_CONSENT,
+ "gcred_revoked": STATE_REVOKED,
+ }
+
+
+async def test_mark_active_mismatched_client_as_error_with_no_new_client_flips_all_bound_active_rows(
+ repo: GoogleOAuthRepository,
+ engine: AsyncEngine,
+) -> None:
+ expires_at = datetime.datetime.utcnow() + datetime.timedelta(minutes=10)
+ rows = [
+ ("gcred_bound_1", "nonce-bound-1", "old-1"),
+ ("gcred_bound_2", "nonce-bound-2", "old-2"),
+ ("gcred_unbound", "nonce-unbound", None),
+ ]
+ for credential_id, nonce, client_id in rows:
+ await repo.insert_pending_credential(
+ credential_id=credential_id,
+ organization_id="o_test",
+ credential_name="Default",
+ scopes_requested=["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="cipher-value",
+ encrypted_method=EncryptMethod.AES,
+ scopes_granted=["https://www.googleapis.com/auth/spreadsheets"],
+ now=datetime.datetime.utcnow(),
+ )
+
+ changed = await repo.mark_active_mismatched_client_as_error(
+ organization_id="o_test",
+ new_client_id=None,
+ now=datetime.datetime.utcnow(),
+ )
+
+ async with engine.connect() as conn:
+ states = dict(
+ (
+ await conn.execute(
+ select(GoogleOAuthCredentialModel.id, GoogleOAuthCredentialModel.state).where(
+ GoogleOAuthCredentialModel.id.in_(["gcred_bound_1", "gcred_bound_2", "gcred_unbound"])
+ )
+ )
+ ).all()
+ )
+
+ assert changed == 2
+ assert states == {
+ "gcred_bound_1": STATE_ERROR,
+ "gcred_bound_2": STATE_ERROR,
+ "gcred_unbound": STATE_ACTIVE,
+ }