Skip to content

Enterprise agent platform for building, deploying, and operating AI teammates.

feat: revoke Google OAuth grants on disconnect (#3785)

Zhenghao Yind6736dc2046f
diff --git a/src/xagent/migrations/versions/20261114_oauth_revocation_fences.py b/src/xagent/migrations/versions/20261114_oauth_revocation_fences.py
new file mode 100644
index 000000000..9ba94684a
--- /dev/null
+++ b/src/xagent/migrations/versions/20261114_oauth_revocation_fences.py
@@ -0,0 +1,29 @@
+"""Fence builtin OAuth grant revocations against concurrent callbacks.
+
+Revision ID: 20261114_oauth_revocation_fences
+Revises: 20261110_rename_atlassian_to_confluence
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20261114_oauth_revocation_fences"
+down_revision = "20261110_rename_atlassian_to_confluence"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ if not sa.inspect(op.get_bind()).has_table("oauth_revocation_fences"):
+ op.create_table(
+ "oauth_revocation_fences",
+ sa.Column("provider", sa.String(50), primary_key=True, nullable=False),
+ sa.Column(
+ "provider_user_id", sa.String(), primary_key=True, nullable=False
+ ),
+ sa.Column("revoking_until", sa.DateTime(timezone=True), nullable=True),
+ )
+
+
+def downgrade() -> None:
+ op.drop_table("oauth_revocation_fences")
diff --git a/src/xagent/web/api/auth.py b/src/xagent/web/api/auth.py
index 7011b5090..36e4aa928 100644
--- a/src/xagent/web/api/auth.py
+++ b/src/xagent/web/api/auth.py
@@ -11,7 +11,9 @@ import re
import secrets
import threading
import time
+from collections.abc import Iterable
from datetime import datetime, timedelta, timezone
+from functools import partial
from typing import Annotated, Any, Dict, List, Literal, NamedTuple, Optional, cast
from urllib.parse import urlparse
@@ -128,7 +130,19 @@ from ..services.auth_email import (
send_email_changed_notice,
send_password_reset_email,
)
-from ..services.db_runtime import await_task_settlement, propagate_deferred_cancellation
+from ..services.db_runtime import (
+ await_task_settlement,
+ propagate_deferred_cancellation,
+ run_db_io_cancellation_safe,
+)
+from ..services.oauth_revocation_fences import (
+ close_oauth_revocation_fence,
+ lock_oauth_revocation_fence,
+ oauth_revocation_call_allowed,
+ oauth_revocation_fence_is_open,
+ oauth_revocation_fence_refuses,
+ open_oauth_revocation_fence,
+)
from ..services.oauth_state_claims import claim_oauth_state
from ..services.trigger_rate_limit import remote_ip_from_request
from ..services.user_oauth import (
@@ -3682,12 +3696,89 @@ def _revoke_github_oauth_grant(
)
+_GOOGLE_OAUTH_REVOKE_URL = "https://oauth2.googleapis.com/revoke"
+# OAuth providers whose grants a disconnect revokes provider-side (see
+# revoke_resolved_builtin_oauth_grant); their callbacks honor the revocation
+# fence.
+BUILTIN_OAUTH_REVOCATION_PROVIDERS = frozenset({"github", "google"})
+
+
+def _revoke_google_oauth_token(
+ token: str, *, kind: Literal["refresh_token", "access_token"]
+) -> None:
+ """Best-effort revoke of one Google OAuth grant through one of its tokens.
+
+ Google's revoke endpoint takes either token of a grant and revokes the
+ whole grant: revoking a refresh token invalidates every access token
+ issued from it, and revoking an access token also revokes its refresh
+ token. The grant is per Google account and OAuth client, not per token,
+ so this also cuts off every other token this deployment holds for the
+ same Google account -- which is why callers must clear
+ :func:`has_other_builtin_oauth_reference` first. Afterwards the next
+ authorize request shows Google's consent screen again, and the old
+ tokens are rejected by Google immediately. ``kind`` names which of the
+ grant's tokens ``token`` is, only to tell the outcomes apart in the log.
+
+ The token goes in the form body, never the query string, so it can't
+ end up in a proxy's or Google's request log. The endpoint needs no
+ client authentication.
+
+ Never raises, for the same reason and with the same exception-logging
+ shape as :func:`_revoke_github_oauth_grant`: this runs after the local
+ disconnect has already committed. Deployments that restrict outbound
+ traffic must allow oauth2.googleapis.com, which token refresh already
+ needs.
+ """
+ try:
+ response = requests.post(
+ _GOOGLE_OAUTH_REVOKE_URL,
+ data={"token": token},
+ timeout=10,
+ )
+ except Exception as exc:
+ logger.warning(
+ "Google OAuth token revocation request failed (exception_type=%s)",
+ type(exc).__name__,
+ )
+ return
+ # 200: revoked. 400 ``invalid_token`` on a refresh token: Google already
+ # considers the grant gone (revoked, or never valid) -- also a successful
+ # outcome. The same answer on an access token only says that token
+ # expired: the grant behind it may still be alive, and nothing here can
+ # revoke it, so that is logged rather than treated as done. Every other
+ # answer, including any other 400, is a genuine (still non-raising)
+ # failure.
+ if response.status_code == 200:
+ logger.info("Google OAuth grant revoked")
+ elif response.status_code == 400 and "invalid_token" in response.text:
+ if kind == "access_token":
+ logger.info(
+ "Google OAuth grant not revoked: its access token was rejected "
+ "as invalid or expired and no refresh token was stored"
+ )
+ else:
+ logger.warning(
+ "Google OAuth token revocation returned unexpected status %s",
+ response.status_code,
+ )
+
+
class BuiltinOAuthRevocation(NamedTuple):
"""Everything needed to revoke one builtin OAuth grant after its local
``UserOAuth`` row has already been deleted and committed, plus the
upstream identity (``provider_user_id``) needed to check whether another
local connection still needs that same grant alive -- see
:func:`has_other_builtin_oauth_reference`.
+
+ ``provider`` is the OAuth provider that issued the grant (``github`` or
+ ``google``), not the ``UserOAuth.provider`` key the row was stored under:
+ a Google grant is stored under its app id (``gmail``, ``google-drive``,
+ ...) or the bare ``google`` key. ``client_id``/``client_secret``
+ authenticate GitHub's grant-delete call; Google's revoke endpoint is
+ unauthenticated, so they are empty for Google. ``refresh_token`` is only
+ used for Google, where it is the token revoked whenever it is present:
+ an access token may already have expired, and Google rejects an expired
+ access token without revoking the grant behind it.
"""
provider: str
@@ -3695,40 +3786,118 @@ class BuiltinOAuthRevocation(NamedTuple):
client_id: str
client_secret: str
provider_user_id: str | None
+ refresh_token: str | None = None
def __repr__(self) -> str:
- # The default NamedTuple repr would print access_token/client_secret
+ # The default NamedTuple repr would print the tokens/client_secret
# in plain text -- a stray logger.debug(revocation) or an
# uncaught-exception traceback that includes this value as a local
- # variable must not leak either one.
+ # variable must not leak any of them.
return (
f"BuiltinOAuthRevocation(provider={self.provider!r}, "
f"access_token=<redacted>, client_id={self.client_id!r}, "
f"client_secret=<redacted>, "
- f"provider_user_id={self.provider_user_id!r})"
+ f"provider_user_id={self.provider_user_id!r}, "
+ f"refresh_token=<redacted>)"
)
+def _builtin_oauth_provider_for_key(db: Session, key: str) -> str:
+ """The OAuth provider whose client issued a ``UserOAuth.provider`` key's
+ grant.
+
+ A grant is stored under the connecting app's id (``gmail``) or, for a
+ bare provider login, the provider name itself (``google``, ``github``);
+ the catalog row of an app id names its provider. A key with no catalog
+ row is taken to be a provider name.
+ """
+ from ..models.public_mcp import PublicMCPApp
+
+ provider_name = (
+ db.query(PublicMCPApp.provider_name).filter(PublicMCPApp.app_id == key).scalar()
+ )
+ return str(provider_name or key)
+
+
+def _builtin_oauth_provider_keys(db: Session, provider: str) -> list[str]:
+ """Every ``UserOAuth.provider`` key a grant from ``provider``'s OAuth
+ client may be stored under: the bare provider name plus the id of each
+ catalog app that names it. The inverse of
+ :func:`_builtin_oauth_provider_for_key`.
+ """
+ from ..models.public_mcp import PublicMCPApp
+
+ return [
+ provider,
+ *(
+ str(app_id)
+ for (app_id,) in db.query(PublicMCPApp.app_id).filter(
+ PublicMCPApp.provider_name == provider
+ )
+ ),
+ ]
+
+
def resolve_builtin_oauth_revocation(
db: Session,
*,
provider: str,
access_token: str,
provider_user_id: str | None,
+ refresh_token: str | None = None,
+ token_type: str | None = None,
) -> BuiltinOAuthRevocation | None:
"""Resolve one deleted ``UserOAuth`` row into a network-free revocation
record, decrypting the stored client_id/secret the same way
generic_oauth_login/generic_oauth_callback already do for this row.
- Returns ``None`` when there's nothing to revoke -- an unsupported
- provider, an empty token, no configured provider row, or a missing
- secret -- so callers can skip revocation outright. Only reads the
+ ``provider`` is the row's ``UserOAuth.provider`` key; the OAuth provider
+ behind it is resolved through the catalog (see
+ :func:`_builtin_oauth_provider_for_key`), so a Gmail or Drive row
+ resolves to a Google revocation. Pass the row's ``refresh_token`` and
+ ``token_type`` too: Google revokes through the refresh token, and a
+ Composio-backed row (``token_type == COMPOSIO_TOKEN_TYPE``) holds a
+ Composio connected-account id rather than a provider token -- its grant
+ belongs to Composio's own OAuth app and is removed by deleting that
+ account (``delete_scoped_user_oauth_accounts``), never here.
+
+ A Google row with no recorded ``provider_user_id`` (legacy rows) is never
+ revoked: Google revokes the account's whole grant for this client, and
+ without the upstream identity nothing can prove that no other
+ connection -- the same user's Drive, another user's Gmail -- still
+ relies on that grant.
+
+ Returns ``None`` when there's nothing to revoke -- a Composio-backed row,
+ a provider with no revoke implementation (only GitHub and Google have
+ one), a Google row without an upstream identity, an empty token, no
+ configured provider row, or a missing secret -- so callers can skip
+ revocation outright. Only reads the
database and makes no network call, so it is safe to call while still
holding a disconnect transaction's locks; do the actual provider call
(:func:`revoke_builtin_oauth_grant_if_unreferenced`) only after that
commits.
"""
- if provider != "github" or not access_token:
+ if token_type == COMPOSIO_TOKEN_TYPE:
+ return None
+ oauth_provider = _builtin_oauth_provider_for_key(db, provider)
+ if oauth_provider == "google":
+ if not (refresh_token or access_token):
+ return None
+ if provider_user_id is None:
+ logger.info(
+ "Skipping Google OAuth grant revocation: the connection "
+ "recorded no Google account id"
+ )
+ return None
+ return BuiltinOAuthRevocation(
+ provider="google",
+ access_token=access_token,
+ client_id="",
+ client_secret="",
+ provider_user_id=provider_user_id,
+ refresh_token=refresh_token or None,
+ )
+ if oauth_provider != "github" or not access_token:
return None
from ..models.oauth_provider import OAuthProvider
@@ -3773,17 +3942,70 @@ def resolve_builtin_oauth_revocation(
)
+def snapshot_builtin_oauth_revocations(
+ db: Session, accounts: Iterable[UserOAuth]
+) -> list[BuiltinOAuthRevocation]:
+ """Resolve the revocation of every loaded ``UserOAuth`` row a disconnect
+ is about to delete (see :func:`resolve_builtin_oauth_revocation`).
+
+ Must run before the delete -- a bulk delete never loads rows, and an
+ orphan cleanup deletes rows the caller never selected -- so this is the
+ only chance to read their tokens. Only reads the database; the caller
+ revokes after its own commit through :func:`revoke_builtin_oauth_grants`.
+ """
+ resolved = []
+ for account in accounts:
+ if not account.access_token:
+ continue
+ snapshot = resolve_builtin_oauth_revocation(
+ db,
+ provider=str(account.provider),
+ access_token=str(account.access_token),
+ # is not None, not a truthy check: an empty-string
+ # provider_user_id is still a real (if unlikely) identity value,
+ # and coercing it to None here would silently disable
+ # has_other_builtin_oauth_reference's cross-user protection --
+ # only an actual NULL column means "no known identity".
+ provider_user_id=(
+ str(account.provider_user_id)
+ if account.provider_user_id is not None
+ else None
+ ),
+ refresh_token=cast(str | None, account.refresh_token),
+ token_type=cast(str | None, account.token_type),
+ )
+ if snapshot is not None:
+ resolved.append(snapshot)
+ return resolved
+
+
def has_other_builtin_oauth_reference(
db: Session, *, provider: str, provider_user_id: str | None
) -> bool:
"""True if any current ``UserOAuth`` row -- any local user, any owner
- namespace -- still points at the same upstream (provider,
- provider_user_id) identity.
-
- GitHub's grant-delete revokes every token issued to that GitHub
- account for this OAuth App, not just the one this disconnect deleted --
- a different XAgent user (or actor namespace) connected to the *same*
+ namespace, any key ``provider``'s grants are stored under -- still
+ points at the same upstream (provider, provider_user_id) identity.
+
+ ``provider`` is the OAuth provider (``BuiltinOAuthRevocation.provider``),
+ and every key its grants may be stored under counts
+ (:func:`_builtin_oauth_provider_keys`). GitHub's grant-delete revokes
+ every token issued to that GitHub account for this OAuth App, and
+ Google's revoke revokes the account's whole grant for this OAuth client,
+ not just the one token this disconnect deleted -- a different XAgent
+ user (or actor namespace), or a sibling app sharing the client (Drive
+ still connected while Gmail disconnects), connected to the *same*
upstream account would silently lose their own, still-active token.
+ Composio-backed rows don't count: they hold a Composio connected-account
+ id for a grant issued to Composio's OAuth app, which a revoke through
+ this deployment's own client never touches. For Google, every row with
+ no recorded ``provider_user_id`` (legacy rows) counts too, whichever
+ user or owner namespace holds it: it may be a connection to the very
+ Google account whose whole grant this revoke would kill -- the same
+ user's Gmail, or another xagent user's -- and nothing can prove it
+ isn't. That keeps Google revocation off while any such row survives,
+ which is the safe failure: a grant left alive, never another
+ connection cut off.
+
This must be checked with a fresh read taken as late as possible (right
before the network call, never at snapshot/pre-commit time): the row
that matters may not exist yet when the disconnect that triggered this
@@ -3814,17 +4036,40 @@ def has_other_builtin_oauth_reference(
why: a cancelled request's ``db.close()`` can otherwise race a worker
thread still mid-query on that same Session).
"""
+ return bool(
+ _builtin_oauth_references(
+ db, provider=provider, provider_user_id=provider_user_id
+ )
+ )
+
+
+def _builtin_oauth_references(
+ db: Session, *, provider: str, provider_user_id: str | None
+) -> list[UserOAuth]:
+ """The live rows :func:`has_other_builtin_oauth_reference` counts, so a
+ caller can tell *why* a revoke is blocked: rows recording the same
+ account, and -- for Google only -- rows recording no account at all."""
if not provider_user_id:
- return False
+ return []
+ same_identity = UserOAuth.provider_user_id == provider_user_id
+ if provider == "google":
+ same_identity = or_(
+ same_identity,
+ UserOAuth.provider_user_id.is_(None),
+ )
candidates = (
db.query(UserOAuth)
.filter(
- UserOAuth.provider == provider,
- UserOAuth.provider_user_id == provider_user_id,
+ UserOAuth.provider.in_(_builtin_oauth_provider_keys(db, provider)),
+ same_identity,
+ or_(
+ UserOAuth.token_type.is_(None),
+ UserOAuth.token_type != COMPOSIO_TOKEN_TYPE,
+ ),
)
.all()
)
- return any(candidate.access_token for candidate in candidates)
+ return [candidate for candidate in candidates if candidate.access_token]
def revoke_resolved_github_oauth_grant(revocation: BuiltinOAuthRevocation) -> None:
@@ -3856,8 +4101,154 @@ def revoke_resolved_github_oauth_grant(revocation: BuiltinOAuthRevocation) -> No
)
+def revoke_resolved_builtin_oauth_grant(revocation: BuiltinOAuthRevocation) -> None:
+ """Database-free provider call for one already-resolved revocation,
+ dispatched on the provider that issued it.
+
+ Google revokes through the refresh token when the row had one, else the
+ access token (see :func:`_revoke_google_oauth_token`); GitHub goes
+ through :func:`revoke_resolved_github_oauth_grant`. A provider with no
+ revoke implementation is logged and skipped -- it can only come from a
+ hand-built record, never from :func:`resolve_builtin_oauth_revocation`.
+ Same contract as that function: no Session, never raises, and the caller
+ must already have cleared :func:`has_other_builtin_oauth_reference`.
+ """
+ match revocation.provider:
+ case "google" if revocation.refresh_token:
+ _revoke_google_oauth_token(revocation.refresh_token, kind="refresh_token")
+ case "google":
+ _revoke_google_oauth_token(revocation.access_token, kind="access_token")
+ case "github":
+ revoke_resolved_github_oauth_grant(revocation)
+ case _:
+ logger.warning(
+ "Skipping OAuth grant revocation: no revoke implementation for "
+ "provider %r",
+ revocation.provider,
+ )
+
+
+class _RevocationClaim(NamedTuple):
+ """A revocation cleared to reach its provider.
+
+ ``deadline`` is the fence deadline its provider call must start well
+ before (see ``services.oauth_revocation_fences``); ``None`` for a row
+ with no recorded upstream account, which has neither a reference check
+ nor a fence to hold.
+ """
+
+ deadline: datetime | None
+
+
+def _claim_builtin_oauth_revocation(
+ db: Session, revocation: BuiltinOAuthRevocation, *, context: str
+) -> _RevocationClaim | None:
+ """Reference-check one revocation under its upstream account's fence and,
+ when nothing references the account any more, open the fence.
+
+ The fence row stays locked from before the reference check until this
+ commits, and an OAuth callback for the same account takes the same lock
+ before storing its credentials. So a callback either committed first and
+ the reference check sees its row, or it finds the opened fence and is
+ refused instead of storing tokens this revoke may kill. A revoker that
+ finds the fence already open (another revocation of the account is in
+ flight, or only just ended) skips too: that call revokes the same grant,
+ and a second holder closing the fence early could let a reconnect
+ through. Returns ``None`` when the revoke must not go ahead. Commits
+ ``db``; raises on database failure.
+
+ ``context`` names the disconnect path in the skip log lines.
+ """
+ if revocation.provider_user_id is None:
+ return _RevocationClaim(deadline=None)
+ fence = lock_oauth_revocation_fence(
+ db,
+ provider=revocation.provider,
+ provider_user_id=revocation.provider_user_id,
+ )
+ references = _builtin_oauth_references(
+ db,
+ provider=revocation.provider,
+ provider_user_id=revocation.provider_user_id,
+ )
+ if references:
+ # Decided before the commit, which expires the loaded rows.
+ only_unidentified = all(row.provider_user_id is None for row in references)
+ db.commit()
+ # Once an unidentified legacy Google row exists, every Google revoke
+ # is skipped (see has_other_builtin_oauth_reference), so say which
+ # rule fired for operators wondering why grants linger.
+ logger.info(
+ "Skipping %s OAuth grant revocation (%s): %s",
+ revocation.provider,
+ context,
+ "a legacy connection with no recorded account id may share this grant"
+ if only_unidentified
+ else "another local connection still references this account",
+ )
+ return None
+ if oauth_revocation_fence_is_open(fence):
+ db.commit()
+ logger.info(
+ "Skipping %s OAuth grant revocation (%s): another revocation of "
+ "this account is in flight",
+ revocation.provider,
+ context,
+ )
+ return None
+ deadline = open_oauth_revocation_fence(fence)
+ db.commit()
+ return _RevocationClaim(deadline=deadline)
+
+
+def _claimed_revocation_may_call(
+ revocation: BuiltinOAuthRevocation, claim: _RevocationClaim
+) -> bool:
+ """Whether the provider call can still start safely inside the fence."""
+ if claim.deadline is None or oauth_revocation_call_allowed(claim.deadline):
+ return True
+ logger.warning(
+ "Skipping %s OAuth grant revocation: it was delayed past its fence",
+ revocation.provider,
+ )
+ return False
+
+
+def _release_builtin_oauth_revocation(
+ db: Session, revocation: BuiltinOAuthRevocation, claim: _RevocationClaim
+) -> None:
+ """Close the fence once the provider call is over, so a reconnect whose
+ exchange starts from now on (past the close margin) is accepted. Commits
+ ``db``.
+
+ Never raises: it runs in ``finally`` blocks, where an exception would
+ replace a propagating cancellation. A failed release leaves the deadline
+ in place, which only delays reconnects until it lapses.
+ """
+ if claim.deadline is None or revocation.provider_user_id is None:
+ return
+ try:
+ close_oauth_revocation_fence(
+ db,
+ provider=revocation.provider,
+ provider_user_id=revocation.provider_user_id,
+ deadline=claim.deadline,
+ )
+ db.commit()
+ except Exception as exc:
+ db.rollback()
+ logger.warning(
+ "%s OAuth revocation fence release failed (exception_type=%s)",
+ revocation.provider,
+ type(exc).__name__,
+ )
+
+
def revoke_builtin_oauth_grant_if_unreferenced(
- db: Session, revocation: BuiltinOAuthRevocation
+ db: Session,
+ revocation: BuiltinOAuthRevocation,
+ *,
+ context: str = "synchronous disconnect",
) -> None:
"""Best-effort provider-side revoke of one already-resolved builtin
OAuth grant, skipped if another local connection (any owner, any user)
@@ -3865,42 +4256,38 @@ def revoke_builtin_oauth_grant_if_unreferenced(
Must run strictly after the disconnect that produced ``revocation`` has
committed: the reference check is a fresh read of current ``UserOAuth``
- rows (see :func:`has_other_builtin_oauth_reference` for exactly what
- that does and does not make safe). Never raises: unlike
- :func:`revoke_resolved_github_oauth_grant`, the reference check here
- does real database work that can fail (a dropped connection, a pool
- timeout), and this function -- not just its network-only half --
- promises never to raise, so that failure is caught here too, rolling
- the session back first so a caller that keeps using ``db`` afterward
- doesn't inherit a transaction Postgres has already poisoned.
-
- For a fully synchronous caller only (Toby's disconnect path, via
- :func:`revoke_builtin_oauth_grant`, and this module's own tests): the
- Session it does real query work on is ``db``, the caller's own, on
- whatever thread the caller itself is already running on. An async
- caller must NOT hand this whole function to ``asyncio.to_thread`` with
- its request-scoped session -- see :func:`has_other_builtin_oauth_reference`
- and :func:`revoke_resolved_github_oauth_grant` for the safe async shape.
+ rows, taken under the account's revocation fence (see
+ :func:`_claim_builtin_oauth_revocation`). Commits ``db``. Never raises:
+ unlike :func:`revoke_resolved_builtin_oauth_grant`, the fence and the
+ reference check do real database work that can fail (a dropped
+ connection, a pool timeout), and this function -- not just its
+ network-only half -- promises never to raise, so that failure is caught
+ here too, rolling the session back first so a caller that keeps using
+ ``db`` afterward doesn't inherit a transaction Postgres has already
+ poisoned. ``context`` names the disconnect path in the skip log lines.
+
+ For a fully synchronous caller only (:func:`revoke_builtin_oauth_grant`
+ and this module's own tests): the Session it does real query work on is
+ ``db``, the caller's own, on whatever thread the caller itself is
+ already running on. An async caller must NOT hand this whole function to
+ ``asyncio.to_thread`` with its request-scoped session -- see
+ :func:`revoke_builtin_oauth_grants` for the safe async shape.
"""
try:
- if has_other_builtin_oauth_reference(
- db,
- provider=revocation.provider,
- provider_user_id=revocation.provider_user_id,
- ):
- logger.info(
- "Skipping GitHub OAuth grant revocation: another local "
- "connection still references this account"
- )
- return
+ claim = _claim_builtin_oauth_revocation(db, revocation, context=context)
except Exception as exc:
db.rollback()
logger.warning(
- "GitHub OAuth grant reference check failed (exception_type=%s)",
+ "%s OAuth grant reference check failed (exception_type=%s)",
+ revocation.provider,
type(exc).__name__,
)
return
- revoke_resolved_github_oauth_grant(revocation)
+ if claim is None:
+ return
+ if _claimed_revocation_may_call(revocation, claim):
+ revoke_resolved_builtin_oauth_grant(revocation)
+ _release_builtin_oauth_revocation(db, revocation, claim)
def revoke_builtin_oauth_grant(
@@ -3909,11 +4296,14 @@ def revoke_builtin_oauth_grant(
provider: str,
access_token: str,
provider_user_id: str | None,
+ refresh_token: str | None = None,
+ token_type: str | None = None,
) -> None:
"""Best-effort provider-side revoke of one deleted ``UserOAuth`` row.
- Called after the local disconnect has committed. Only GitHub is
- implemented today (see :func:`_revoke_github_oauth_grant`); every other
+ Called after the local disconnect has committed. Only GitHub (see
+ :func:`_revoke_github_oauth_grant`) and Google (see
+ :func:`_revoke_google_oauth_token`) are implemented today; every other
provider is a deliberate no-op here -- add a branch as each provider's
own "silently reuses an existing grant" behavior needs the same fix.
Never raises. A fully synchronous convenience wrapper around
@@ -3922,13 +4312,16 @@ def revoke_builtin_oauth_grant(
already run off the event loop (e.g. inside ``anyio.to_thread.run_sync``);
an async caller should call those two directly instead, so credential
resolution can happen before its commit and the reference check plus
- network call after.
+ network call after. No production disconnect path calls it today: the
+ async endpoints use :func:`revoke_builtin_oauth_grants`.
"""
resolved = resolve_builtin_oauth_revocation(
db,
provider=provider,
access_token=access_token,
provider_user_id=provider_user_id,
+ refresh_token=refresh_token,
+ token_type=token_type,
)
if resolved is None:
return
@@ -3945,33 +4338,42 @@ async def revoke_builtin_oauth_grants(
The single shared implementation for every async disconnect endpoint
(mcp.py's ``delete_mcp_server`` and ``teardown_mcp_app_server``,
cloud_storage.py's ``delete_connected_account``) -- so the
- reference-check-then-revoke sequence, and its cancellation-safety
- shape, has exactly one place to get right instead of being copied at
- each call site. Each entry's reference check
- (:func:`has_other_builtin_oauth_reference`) runs synchronously on the
- event loop against the caller's own ``db`` -- never via
- ``asyncio.to_thread``, per that function's own docstring -- and only
- the resulting network call is offloaded. Never raises: a dead network,
- a still-live sibling reference, or a failed reference-check query must
- not turn an already-successful local disconnect into a failed request.
+ fence-check-revoke sequence, and its cancellation-safety shape, has
+ exactly one place to get right instead of being copied at each call
+ site. Each entry's fence and reference check
+ (:func:`_claim_builtin_oauth_revocation`) run synchronously on the event
+ loop against the caller's own ``db`` -- never via ``asyncio.to_thread``,
+ per :func:`has_other_builtin_oauth_reference`'s docstring -- and only
+ the resulting network call is offloaded. Commits ``db``. Never raises: a
+ dead network, a still-live sibling reference, or a failed database step
+ must not turn an already-successful local disconnect into a failed
+ request.
``context`` is folded into the warning log line so a failure can be
- traced back to which disconnect path it came from.
+ traced back to which disconnect path it came from. Identical records --
+ one row snapshotted by two cleanup steps of the same disconnect -- are
+ revoked once. A cancelled request still finishes its in-flight provider
+ call and closes its fence before the cancellation propagates.
"""
- for revocation in revocations:
+ for revocation in dict.fromkeys(revocations):
try:
- if has_other_builtin_oauth_reference(
- db,
- provider=revocation.provider,
- provider_user_id=revocation.provider_user_id,
- ):
- logger.info(
- "Skipping GitHub OAuth grant revocation (%s): another "
- "local connection still references this account",
- context,
- )
+ claim = _claim_builtin_oauth_revocation(db, revocation, context=context)
+ if claim is None:
continue
- await asyncio.to_thread(revoke_resolved_github_oauth_grant, revocation)
+ try:
+ if _claimed_revocation_may_call(revocation, claim):
+ # Drained, not abandoned, when this task is cancelled:
+ # the fence may only close once the provider call has
+ # really ended, never while its thread is still in flight.
+ await run_db_io_cancellation_safe(
+ partial(revoke_resolved_builtin_oauth_grant, revocation)
+ )
+ finally:
+ # Also on cancellation (which is no ``Exception``): the call
+ # is over by now, and a fence left open would refuse
+ # reconnects for the rest of its deadline. Synchronous and
+ # non-raising, so cancellation still propagates after it.
+ _release_builtin_oauth_revocation(db, revocation, claim)
except Exception:
db.rollback()
logger.warning("Builtin OAuth grant revocation failed (%s)", context)
@@ -5161,6 +5563,10 @@ def generic_oauth_callback(
# The client secret and code go only to the bound account host.
post_kwargs["allow_redirects"] = False
+ # Before the exchange: a grant revocation for this upstream account
+ # that may reach the provider after this point would kill the tokens
+ # the exchange is about to be issued (see the fence check below).
+ exchange_started_at = datetime.now(timezone.utc)
token_response = requests.post(
token_url,
headers=headers,
@@ -5764,6 +6170,42 @@ def generic_oauth_callback(
return HTMLResponse(
content="<h1>Error: Invalid or expired state</h1>", status_code=400
)
+ # A disconnect of the same upstream account may have revoked its
+ # whole grant after this exchange started, killing these tokens.
+ # The fence lock is held until this callback commits, so a
+ # revocation that has not opened it yet will see this
+ # credential in its reference check instead.
+ if (
+ provider.lower() in BUILTIN_OAUTH_REVOCATION_PROVIDERS
+ and provider_user_id
+ and oauth_revocation_fence_refuses(
+ lock_oauth_revocation_fence(
+ db,
+ provider=provider.lower(),
+ provider_user_id=str(provider_user_id),
+ ),
+ exchange_started_at=exchange_started_at,
+ )
+ ):
+ db.rollback()
+ rejection_reason = "grant_revoked_during_exchange"
+ _log_oauth_callback_rejection(
+ provider,
+ rejection_reason,
+ app_id=app_id,
+ actor_flow=is_actor_flow,
+ )
+ if is_actor_flow:
+ return _actor_oauth_flow_rejected_response(rejection_reason)
+ return HTMLResponse(
+ content=(
+ "<h1>Connection interrupted</h1>"
+ f"<p>This {html.escape(provider)} account was being "
+ "disconnected while you connected it. Please connect "
+ "again.</p>"
+ ),
+ status_code=409,
+ )
google_shared_scopes_claim = payload.get("google_shared_scopes")
google_shared_state = bool(
provider.lower() == "google"
diff --git a/src/xagent/web/api/cloud_storage.py b/src/xagent/web/api/cloud_storage.py
index 2de101741..190345b3f 100644
--- a/src/xagent/web/api/cloud_storage.py
+++ b/src/xagent/web/api/cloud_storage.py
@@ -921,26 +921,35 @@ async def delete_connected_account(
):
raise HTTPException(status_code=404, detail="Account not found")
- # Snapshot before the delete: it's a bulk-free single-row delete here,
- # but the same "read the token before it's gone" constraint applies as
- # in mcp.py's disconnect endpoints -- this must run before db.delete,
- # while the row (and its access_token) still exists.
- from .auth import resolve_builtin_oauth_revocation
-
- revocation = resolve_builtin_oauth_revocation(
- db,
- provider=str(account.provider),
- access_token=str(account.access_token) if account.access_token else "",
- provider_user_id=(
- str(account.provider_user_id)
- if account.provider_user_id is not None
- else None
- ),
- )
-
from ..services.google_oauth_grants import (
+ GOOGLE_SHARED_OAUTH_PROVIDER,
detach_google_shared_oauth_legacy_account,
)
+ from .auth import (
+ _builtin_oauth_provider_for_key,
+ revoke_builtin_oauth_grants,
+ snapshot_builtin_oauth_revocations,
+ )
+
+ # Snapshot before the delete, while the row (and its tokens) still
+ # exists -- the same "read the token before it's gone" constraint as in
+ # mcp.py's disconnect endpoints. Detaching a Google legacy account's last
+ # shared link also deletes the shared ``google`` credential, which this
+ # request never selected, so the user's shared credentials are
+ # snapshotted too; one that survives the detach is still there for the
+ # post-commit reference check, which then skips its revoke. Any other
+ # provider's account has no shared Google link to detach, so it skips
+ # that extra fence and reference work.
+ snapshotted = [account]
+ if _builtin_oauth_provider_for_key(db, str(account.provider)) == "google":
+ snapshotted += (
+ scoped_user_oauth_query(
+ db, user_id=cast(int, user.id), resource_owner_key=None
+ )
+ .filter(UserOAuth.provider == GOOGLE_SHARED_OAUTH_PROVIDER)
+ .all()
+ )
+ revocations = snapshot_builtin_oauth_revocations(db, snapshotted)
detach_google_shared_oauth_legacy_account(
db,
@@ -950,12 +959,9 @@ async def delete_connected_account(
db.delete(account)
db.commit()
- if revocation is not None:
- from .auth import revoke_builtin_oauth_grants
-
- await revoke_builtin_oauth_grants(
- db, [revocation], context=f"deleting connected account {account_id}"
- )
+ await revoke_builtin_oauth_grants(
+ db, revocations, context=f"deleting connected account {account_id}"
+ )
return {"success": True, "message": "Account deleted successfully"}
diff --git a/src/xagent/web/api/mcp.py b/src/xagent/web/api/mcp.py
index 04bc562dd..717d51b7b 100644
--- a/src/xagent/web/api/mcp.py
+++ b/src/xagent/web/api/mcp.py
@@ -5912,48 +5912,41 @@ def _snapshot_builtin_oauth_revocations(
``auth.has_other_builtin_oauth_reference`` (checked at that later point,
not here) confirms no other local connection still needs the grant.
"""
- from .auth import resolve_builtin_oauth_revocation
+ from .auth import snapshot_builtin_oauth_revocations
if not providers:
return []
- accounts = (
+ return snapshot_builtin_oauth_revocations(
+ db,
scoped_user_oauth_query(db, user_id=user_id, resource_owner_key=None)
.filter(UserOAuth.provider.in_(providers))
- .all()
+ .all(),
)
- resolved = []
- for account in accounts:
- if not account.access_token:
- continue
- snapshot = resolve_builtin_oauth_revocation(
- db,
- provider=str(account.provider),
- access_token=str(account.access_token),
- # is not None, not a truthy check: an empty-string
- # provider_user_id is still a real (if unlikely) identity value,
- # and coercing it to None here would silently disable
- # has_other_builtin_oauth_reference's cross-user protection --
- # only an actual NULL column means "no known identity".
- provider_user_id=(
- str(account.provider_user_id)
- if account.provider_user_id is not None
- else None
- ),
- )
- if snapshot is not None:
- resolved.append(snapshot)
- return resolved
def _detach_shared_google_grant_for_disconnect(
db: Session, *, user_id: int, provider: object, app_id: object
-) -> None:
- """Detach one ordinary Google app from any explicit shared grant."""
+) -> "list[BuiltinOAuthRevocation]":
+ """Detach one ordinary Google app from any explicit shared grant.
+
+ Detaching the last app linked to a shared grant deletes the shared
+ ``google`` credential with it, so the user's shared credentials are
+ snapshotted for revocation first. One that survives the detach (another
+ app still links it) is still there for the post-commit reference check,
+ which then skips its revoke.
+ """
if normalize_catalog_key(provider) != "google" or not isinstance(app_id, str):
- return
- from ..services.google_oauth_grants import detach_google_shared_oauth_app
+ return []
+ from ..services.google_oauth_grants import (
+ GOOGLE_SHARED_OAUTH_PROVIDER,
+ detach_google_shared_oauth_app,
+ )
+ revocations = _snapshot_builtin_oauth_revocations(
+ db, user_id=user_id, providers=[GOOGLE_SHARED_OAUTH_PROVIDER]
+ )
detach_google_shared_oauth_app(db, user_id=user_id, app_id=app_id)
+ return revocations
def _legacy_disconnect_provider_keys(
@@ -6111,8 +6104,10 @@ def _teardown_mcp_app_server_locally(
if str(server.transport or "").lower() == "oauth":
provider = expected_app.provider_name
- _detach_shared_google_grant_for_disconnect(
- db, user_id=user_id, provider=provider, app_id=app_id
+ builtin_oauth_revocations.extend(
+ _detach_shared_google_grant_for_disconnect(
+ db, user_id=user_id, provider=provider, app_id=app_id
+ )
)
providers_to_delete = restrict_to_app_scoped_oauth_grant(
expected_app, [provider, app_id]
@@ -6429,11 +6424,13 @@ async def delete_mcp_server(
if app_info:
provider = app_info.get("provider")
app_id = app_info.get("id")
- _detach_shared_google_grant_for_disconnect(
- db,
- user_id=int(user_id),
- provider=provider,
- app_id=app_id,
+ builtin_oauth_revocations.extend(
+ _detach_shared_google_grant_for_disconnect(
+ db,
+ user_id=int(user_id),
+ provider=provider,
+ app_id=app_id,
+ )
)
# Delete tokens for this specific app. For apps in
diff --git a/src/xagent/web/models/__init__.py b/src/xagent/web/models/__init__.py
index edee81ec8..036ad5189 100644
--- a/src/xagent/web/models/__init__.py
+++ b/src/xagent/web/models/__init__.py
@@ -18,6 +18,7 @@ from .mcp import MCPServer, UserMCPServer
from .mcp_oauth import MCPOAuthClient, MCPOAuthFlowState, MCPOAuthGrant
from .model import Model
from .oauth_provider import OAuthProvider
+from .oauth_revocation_fence import OAuthRevocationFence
from .oidc_consumed_token import OidcConsumedToken
from .public_mcp import PublicMCPApp, PublicMCPAppAudit
from .sandbox import DurableSandboxLifecycle, SandboxInfo, SandboxSnapshot
@@ -131,6 +132,7 @@ __all__ = [
"UserSkill",
"UserSkillFile",
"OAuthProvider",
+ "OAuthRevocationFence",
"OidcConsumedToken",
"PublicMCPApp",
"PublicMCPAppAudit",
diff --git a/src/xagent/web/models/oauth_revocation_fence.py b/src/xagent/web/models/oauth_revocation_fence.py
new file mode 100644
index 000000000..54391919e
--- /dev/null
+++ b/src/xagent/web/models/oauth_revocation_fence.py
@@ -0,0 +1,41 @@
+"""Serialize a provider-side grant revocation with OAuth callbacks."""
+
+from datetime import datetime
+
+from sqlalchemy import DateTime, String
+from sqlalchemy.orm import Mapped, mapped_column
+
+from .database import Base
+
+
+class OAuthRevocationFence(Base): # type: ignore[no-any-unimported]
+ """One row per upstream account a builtin OAuth grant has been connected for.
+
+ GitHub and Google revoke a whole grant per upstream account and OAuth
+ client, so a revoke also kills tokens a concurrent callback for the same
+ account has just been issued. The revoker and that callback both lock
+ this row (see ``services.oauth_revocation_fences``): the revoker checks
+ for live references and records ``revoking_until`` under the lock, and a
+ callback whose token exchange started before ``revoking_until`` is
+ refused instead of storing credentials the revoke may already have
+ killed.
+
+ Either side inserts the row if missing, so every Google or GitHub
+ connect that records an upstream account id creates one (with
+ ``revoking_until`` unset), whether or not that account is ever revoked.
+ Rows are never deleted -- a row is a lock target that must stay put while
+ any callback or revoker may be waiting on it -- so the table grows with
+ the number of distinct upstream accounts ever connected. Each row is two
+ short keys and a timestamp, which is why nothing prunes it.
+ """
+
+ __tablename__ = "oauth_revocation_fences"
+
+ # No FK: the fence outlives every local credential for the account.
+ provider: Mapped[str] = mapped_column(String(50), primary_key=True)
+ provider_user_id: Mapped[str] = mapped_column(String, primary_key=True)
+ # Until when a revocation may still reach the provider; ``None`` while
+ # no revocation has ever been opened for this account.
+ revoking_until: Mapped[datetime | None] = mapped_column(
+ DateTime(timezone=True), nullable=True
+ )
diff --git a/src/xagent/web/services/oauth_revocation_fences.py b/src/xagent/web/services/oauth_revocation_fences.py
new file mode 100644
index 000000000..bbd866627
--- /dev/null
+++ b/src/xagent/web/services/oauth_revocation_fences.py
@@ -0,0 +1,149 @@
+"""Fence builtin OAuth grant revocations against concurrent callbacks.
+
+GitHub and Google revoke a whole grant per upstream account and OAuth client.
+A disconnect revokes only once no local row references that account any more
+(``has_other_builtin_oauth_reference``), but a concurrent callback for the
+same account may already have exchanged its code -- its tokens belong to the
+very grant about to be revoked -- without having committed its row yet. The
+revoke would then succeed and the callback would store dead credentials and
+report success.
+
+Both sides therefore lock one ``OAuthRevocationFence`` row per (provider,
+upstream account) and hold it until their transaction commits:
+
+* the revoker locks it, runs the reference check, and -- only when the
+ revoke goes ahead -- records ``revoking_until``, a deadline by which its
+ provider call has either started or been skipped; after the call it pulls
+ the deadline back to just past the moment the call ended;
+* the callback locks it after its token exchange and refuses (asking for a
+ reconnect) when the exchange started before ``revoking_until``.
+
+Whichever commits first wins. A callback committed first is seen by the
+reference check, so nothing is revoked; a revoker committed first leaves a
+deadline every overlapping callback sees.
+
+At most one revoker holds an account's fence at a time: a revoker that finds
+the deadline still in the future skips its call, because the holder's
+provider call already revokes the whole grant (Google and GitHub both revoke
+per account, not per token). Otherwise a second revoker could close the
+fence while the first one's call is still in flight and let a reconnect
+through that the first call then kills.
+
+The exchange-start time and the deadline come from different hosts' clocks,
+so the window keeps a margin far larger than ordinary clock skew, and a
+closed fence still refuses callbacks for a short margin
+(``OAUTH_REVOCATION_CLOSE_MARGIN``) for the same reason.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+
+from sqlalchemy.orm import Session
+
+from ..models.oauth_revocation_fence import OAuthRevocationFence
+
+# How long an opened fence refuses callbacks if its revoker never closes it.
+OAUTH_REVOCATION_FENCE_WINDOW = timedelta(minutes=2)
+# The provider call must start at least this long before the fence lapses,
+# covering its own timeouts; a revoker delayed past that skips the call.
+OAUTH_REVOCATION_CALL_MARGIN = timedelta(minutes=1)
+# A closed fence keeps refusing callbacks for this long past the end of the
+# provider call: a callback host whose clock runs ahead of the revoker's
+# would otherwise record an exchange start after the close although its
+# exchange began before the call ended. Must exceed ordinary clock skew.
+OAUTH_REVOCATION_CLOSE_MARGIN = timedelta(seconds=5)
+
+
+def _utc(value: datetime) -> datetime:
+ """SQLite returns timezone-aware columns naive; they were stored as UTC."""
+ return value if value.tzinfo is not None else value.replace(tzinfo=timezone.utc)
+
+
+def lock_oauth_revocation_fence(
+ db: Session, *, provider: str, provider_user_id: str
+) -> OAuthRevocationFence:
+ """Create the account's fence row if needed and lock it until commit.
+
+ The insert happens first on both sides so the lock never depends on a
+ row that may not exist yet: PostgreSQL makes a concurrent insert of the
+ same key wait for the first one's commit, and SQLite's single writer
+ serializes the write statements outright.
+ """
+ dialect = db.get_bind().dialect.name
+ if dialect == "postgresql":
+ from sqlalchemy.dialects.postgresql import insert
+ elif dialect == "sqlite":
+ from sqlalchemy.dialects.sqlite import insert # type: ignore[assignment]
+ else:
+ raise RuntimeError("OAuth revocation fences require PostgreSQL or SQLite")
+ db.execute(
+ insert(OAuthRevocationFence)
+ .values(provider=provider, provider_user_id=provider_user_id)
+ .on_conflict_do_nothing(index_elements=["provider", "provider_user_id"])
+ )
+ fence: OAuthRevocationFence = (
+ db.query(OAuthRevocationFence)
+ .filter(
+ OAuthRevocationFence.provider == provider,
+ OAuthRevocationFence.provider_user_id == provider_user_id,
+ )
+ .with_for_update()
+ .populate_existing()
+ .one()
+ )
+ return fence
+
+
+def oauth_revocation_fence_is_open(fence: OAuthRevocationFence) -> bool:
+ """Whether a revoker's deadline (or close margin) is still in the future,
+ that is, another revocation of this account may still be in flight."""
+ return fence.revoking_until is not None and datetime.now(timezone.utc) < _utc(
+ fence.revoking_until
+ )
+
+
+def open_oauth_revocation_fence(fence: OAuthRevocationFence) -> datetime:
+ """Record that a revocation is about to reach the provider; returns its deadline.
+
+ The caller holds the fence lock and has checked that the fence is not
+ :func:`oauth_revocation_fence_is_open`, so the new deadline never
+ replaces a live one.
+ """
+ deadline = datetime.now(timezone.utc) + OAUTH_REVOCATION_FENCE_WINDOW
+ fence.revoking_until = deadline
+ return deadline
+
+
+def oauth_revocation_call_allowed(deadline: datetime) -> bool:
+ """Whether a revoker may still start its provider call before ``deadline``."""
+ return datetime.now(timezone.utc) < deadline - OAUTH_REVOCATION_CALL_MARGIN
+
+
+def close_oauth_revocation_fence(
+ db: Session, *, provider: str, provider_user_id: str, deadline: datetime
+) -> None:
+ """Pull the deadline back once this revoker's provider call is over, to
+ ``OAUTH_REVOCATION_CLOSE_MARGIN`` past now.
+
+ Only the revoker that set the current deadline may shorten it (one whose
+ deadline lapsed may find a later revoker's in its place); the caller
+ commits.
+ """
+ fence = lock_oauth_revocation_fence(
+ db, provider=provider, provider_user_id=provider_user_id
+ )
+ if fence.revoking_until is not None and _utc(fence.revoking_until) == deadline:
+ fence.revoking_until = (
+ datetime.now(timezone.utc) + OAUTH_REVOCATION_CLOSE_MARGIN
+ )
+
+
+def oauth_revocation_fence_refuses(
+ fence: OAuthRevocationFence, *, exchange_started_at: datetime
+) -> bool:
+ """Whether a revocation may have reached the provider after this exchange
+ started, killing the tokens it was issued."""
+ return fence.revoking_until is not None and exchange_started_at <= _utc(
+ fence.revoking_until
+ )
diff --git a/tests/web/api/v1/test_task_content_redaction.py b/tests/web/api/v1/test_task_content_redaction.py
index 8c63fe7ed..7b7127392 100644
--- a/tests/web/api/v1/test_task_content_redaction.py
+++ b/tests/web/api/v1/test_task_content_redaction.py
@@ -131,7 +131,14 @@ def _roots(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:
get_unscoped_file_storage.cache_clear()
register_scope_resolver(None)
set_execution_scope_snapshot_loader(load_task_execution_scope_snapshot)
- get_agent_manager()._agents.clear()
+ # The manager is process-wide and every test here reuses task id 1 on a
+ # fresh database. A run id (or generation, or build lock) another test
+ # module left behind for that id would make the cleanup fence skip the
+ # runtime as "stale", so reset the cached runtimes and all their
+ # bookkeeping, not just the agents.
+ manager = get_agent_manager()
+ for tracked in (*manager._runtime_bookkeeping_maps(), manager._agent_build_locks):
+ tracked.clear()
yield uploads
diff --git a/tests/web/test_blocking_call_inventory.py b/tests/web/test_blocking_call_inventory.py
index 68c466f73..47959f544 100644
--- a/tests/web/test_blocking_call_inventory.py
+++ b/tests/web/test_blocking_call_inventory.py
@@ -67,7 +67,7 @@ NETWORK = "Outbound network call (DNS, provider or Google API read): writes no l
ALLOWED: dict[str, tuple[int, str]] = {
# -- web/api: HTTP routes ---------------------------------------------------
"web/api/admin_users.py": (6, HTTP),
- "web/api/auth.py": (11, HTTP),
+ "web/api/auth.py": (10, HTTP),
"web/api/chat.py": (8, HTTP),
"web/api/files.py": (7, HTTP),
"web/api/kb.py": (16, HTTP),
diff --git a/tests/web/test_github_oauth.py b/tests/web/test_github_oauth.py
index e70dac1a0..8120bfa18 100644
--- a/tests/web/test_github_oauth.py
+++ b/tests/web/test_github_oauth.py
@@ -1387,25 +1387,24 @@ def test_revoke_builtin_oauth_grant_deletes_github_grant_with_decrypted_secret(
assert kwargs["json"] == {"access_token": "live-access-token"}
-def test_revoke_builtin_oauth_grant_ignores_non_github_providers(
+def test_revoke_builtin_oauth_grant_ignores_providers_without_a_revoke(
db_session, monkeypatch
):
- """Only GitHub needs this today; every other provider is a no-op and
- must not even query the database, let alone call out to it."""
+ """Only GitHub and Google have a revoke implementation; every other
+ provider is a no-op and must not call out to anything."""
db, _user = db_session
- class ExplodingQuery:
- def query(self, *args, **kwargs):
- raise AssertionError("non-github provider must not query the database")
-
delete = Mock()
+ post = Mock()
monkeypatch.setattr(auth_api.requests, "delete", delete)
+ monkeypatch.setattr(auth_api.requests, "post", post)
auth_api.revoke_builtin_oauth_grant(
- ExplodingQuery(), provider="slack", access_token="tok", provider_user_id="99"
+ db, provider="slack", access_token="tok", provider_user_id="99"
)
delete.assert_not_called()
+ post.assert_not_called()
def test_revoke_builtin_oauth_grant_swallows_network_failure(
diff --git a/tests/web/test_google_oauth_revocation.py b/tests/web/test_google_oauth_revocation.py
new file mode 100644
index 000000000..c123e4700
--- /dev/null
+++ b/tests/web/test_google_oauth_revocation.py
@@ -0,0 +1,626 @@
+"""Revoking a Google OAuth grant when a Google-backed connection is
+disconnected.
+
+Google grants are stored under the connecting app's id (``gmail``,
+``google-drive``, ...) or the bare ``google`` key, and every one of them was
+issued to the same Google OAuth client -- so the revoke resolves the
+provider through the catalog, revokes through the refresh token, and skips
+while any sibling row for the same Google account is still connected.
+"""
+
+from __future__ import annotations
+
+import logging
+from unittest.mock import Mock
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import Session
+from sqlalchemy.pool import StaticPool
+
+from xagent.web.api import auth as auth_api
+from xagent.web.models.database import Base
+from xagent.web.models.mcp import MCPServer, UserMCPServer
+from xagent.web.models.oauth_revocation_fence import OAuthRevocationFence
+from xagent.web.models.public_mcp import PublicMCPApp
+from xagent.web.models.user import User
+from xagent.web.models.user_oauth import COMPOSIO_TOKEN_TYPE, UserOAuth
+from xagent.web.services.google_oauth_grants import (
+ create_google_oauth_grant_association,
+)
+
+GOOGLE_REVOKE_URL = "https://oauth2.googleapis.com/revoke"
+
+
+class MockResponse:
+ def __init__(self, status_code: int = 200, text: str = ""):
+ self.status_code = status_code
+ self.text = text
+
+
+def db():
+ engine = create_engine(
+ "sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool
+ )
+ Base.metadata.create_all(bind=engine)
+ with Session(engine) as session:
+ for app_id in ("gmail", "google-drive"):
+ session.add(
+ PublicMCPApp(
+ app_id=app_id,
+ name=app_id,
+ transport="oauth",
+ provider_name="google",
+ launch_config={},
+ )
+ )
+ session.commit()
+ yield session
+ engine.dispose()
+
+
+def post(monkeypatch) -> Mock:
+ mock = Mock(return_value=MockResponse(200))
+ monkeypatch.setattr(auth_api.requests, "post", mock)
+ return mock
+
+
+def _user(db: Session, username: str = "alice") -> User:
+ user = User(username=username, password_hash="h", is_admin=False)
+ db.add(user)
+ db.commit()
+ db.refresh(user)
+ return user
+
+
+def _assert_revoked_with(post: Mock, token: str) -> None:
+ post.assert_called_once()
+ args, kwargs = post.call_args
+ assert args[0] == GOOGLE_REVOKE_URL
+ # In the form body, never the URL.
+ assert kwargs["data"] == {"token": token}
+
+
+def test_resolve_maps_an_app_key_to_a_google_revocation(db):
+ resolved = auth_api.resolve_builtin_oauth_revocation(
+ db,
+ provider="gmail",
+ access_token="access",
+ provider_user_id="sub-1",
+ refresh_token="refresh",
+ )
+
+ assert resolved == auth_api.BuiltinOAuthRevocation(
+ provider="google",
+ access_token="access",
+ client_id="",
+ client_secret="",
+ provider_user_id="sub-1",
+ refresh_token="refresh",
+ )
+
+
+def test_resolve_skips_a_composio_backed_row(db):
+ """Its access_token is a Composio connected-account id, and its grant
+ belongs to Composio's OAuth app; Composio account deletion handles it."""
+ assert (
+ auth_api.resolve_builtin_oauth_revocation(
+ db,
+ provider="gmail",
+ access_token="ca_composio-account",
+ provider_user_id="sub-1",
+ token_type=COMPOSIO_TOKEN_TYPE,
+ )
+ is None
+ )
+
+
+def test_revocation_repr_redacts_the_refresh_token():
+ revocation = auth_api.BuiltinOAuthRevocation(
+ provider="google",
+ access_token="the-access-token",
+ client_id="",
+ client_secret="",
+ provider_user_id="sub-1",
+ refresh_token="the-refresh-token",
+ )
+
+ assert "the-refresh-token" not in repr(revocation)
+ assert "the-access-token" not in repr(revocation)
+
+
+def test_revoke_prefers_the_refresh_token(db, post):
+ """An access token may have expired, and Google answers an expired one
+ with invalid_token without revoking the grant behind it."""
+ auth_api.revoke_builtin_oauth_grant(
+ db,
+ provider="google-drive",
+ access_token="access",
+ provider_user_id="sub-1",
+ refresh_token="refresh",
+ )
+
+ _assert_revoked_with(post, "refresh")
+
+
+def test_revoke_falls_back_to_the_access_token(db, post):
+ auth_api.revoke_builtin_oauth_grant(
+ db,
+ provider="google",
+ access_token="access",
+ provider_user_id="sub-1",
+ )
+
+ _assert_revoked_with(post, "access")
+
+
+def test_revoke_skips_while_a_sibling_google_app_is_connected(db, post):
+ """Google revokes the whole grant for the client, so disconnecting Gmail
+ must not cut off the same account's still-connected Drive."""
+ user = _user(db)
+ db.add(
+ UserOAuth(
+ user_id=int(user.id),
+ provider="google-drive",
+ provider_user_id="sub-1",
+ access_token="drive-access",
+ )
+ )
+ db.commit()
+
+ auth_api.revoke_builtin_oauth_grant(
+ db,
+ provider="gmail",
+ access_token="access",
+ provider_user_id="sub-1",
+ refresh_token="refresh",
+ )
+
+ post.assert_not_called()
+
+
+def test_a_composio_sibling_does_not_block_the_revoke(db, post):
+ user = _user(db)
+ db.add(
+ UserOAuth(
+ user_id=int(user.id),
+ provider="google-drive",
+ provider_user_id="sub-1",
+ access_token="ca_composio-account",
+ token_type=COMPOSIO_TOKEN_TYPE,
+ )
+ )
+ db.commit()
+
+ auth_api.revoke_builtin_oauth_grant(
+ db,
+ provider="gmail",
+ access_token="access",
+ provider_user_id="sub-1",
+ refresh_token="refresh",
+ )
+
+ _assert_revoked_with(post, "refresh")
+
+
+def test_a_google_row_without_an_upstream_id_is_never_revoked(db, post):
+ """Disconnecting a legacy row that recorded no Google account id can't
+ prove no other connection shares its grant, so it must not revoke."""
+ user = _user(db)
+ db.add(
+ UserOAuth(
+ user_id=int(user.id),
+ provider="google-drive",
+ provider_user_id="sub-1",
+ access_token="drive-access",
+ )
+ )
+ db.commit()
+
+ auth_api.revoke_builtin_oauth_grant(
+ db,
+ provider="gmail",
+ access_token="access",
+ provider_user_id=None,
+ refresh_token="refresh",
+ )
+
+ post.assert_not_called()
+
+
+def test_a_same_user_google_row_without_an_upstream_id_blocks_the_revoke(db, post):
+ """The legacy Gmail row may hold the very grant that disconnecting Drive
+ would revoke, so it counts as a live reference."""
+ user = _user(db)
+ db.add(
+ UserOAuth(
+ user_id=int(user.id),
+ provider="gmail",
+ provider_user_id=None,
+ access_token="legacy-gmail-access",
+ )
+ )
+ db.commit()
+
+ auth_api.revoke_builtin_oauth_grant(
+ db,
+ provider="google-drive",
+ access_token="access",
+ provider_user_id="sub-1",
+ refresh_token="refresh",
+ )
+
+ post.assert_not_called()
+
+
+def test_another_users_google_row_without_an_upstream_id_blocks_the_revoke(db, post):
+ """Bob's legacy Gmail row may be a connection to the same Google account
+ Alice is disconnecting Drive from; nothing proves it isn't, so Alice's
+ disconnect must not revoke the grant Bob may still use."""
+ _user(db)
+ other = _user(db, "bob")
+ db.add(
+ UserOAuth(
+ user_id=int(other.id),
+ provider="gmail",
+ provider_user_id=None,
+ access_token="bobs-legacy-access",
+ )
+ )
+ db.commit()
+
+ auth_api.revoke_builtin_oauth_grant(
+ db,
+ provider="google-drive",
+ access_token="access",
+ provider_user_id="sub-1",
+ refresh_token="refresh",
+ )
+
+ post.assert_not_called()
+
+
+def test_a_tokenless_or_composio_google_row_without_an_upstream_id_does_not_block(
+ db, post
+):
+ """Only a row that could still use our grant counts: a disconnected
+ tombstone holds no token, and a Composio row's grant is Composio's."""
+ user = _user(db)
+ db.add_all(
+ [
+ UserOAuth(
+ user_id=int(user.id),
+ provider="gmail",
+ provider_user_id=None,
+ access_token="",
+ ),
+ UserOAuth(
+ user_id=int(user.id),
+ provider="google",
+ provider_user_id=None,
+ access_token="ca_composio-account",
+ token_type=COMPOSIO_TOKEN_TYPE,
+ ),
+ ]
+ )
+ db.commit()
+
+ auth_api.revoke_builtin_oauth_grant(
+ db,
+ provider="google-drive",
+ access_token="access",
+ provider_user_id="sub-1",
+ refresh_token="refresh",
+ )
+
+ _assert_revoked_with(post, "refresh")
+
+
+async def test_the_skip_log_names_an_unidentified_legacy_row_and_the_context(
+ db, post, caplog
+):
+ """Once such a row exists every Google revoke is skipped, so the log must
+ tell it apart from an ordinary sibling reference and say which disconnect
+ path was skipped."""
+ user = _user(db)
+ db.add(
+ UserOAuth(
+ user_id=int(user.id),
+ provider="gmail",
+ provider_user_id=None,
+ access_token="legacy-gmail-access",
+ )
+ )
+ db.commit()
+ revocation = auth_api.BuiltinOAuthRevocation(
+ provider="google",
+ access_token="access",
+ client_id="",
+ client_secret="",
+ provider_user_id="sub-1",
+ refresh_token="refresh",
+ )
+
+ with caplog.at_level(logging.INFO, logger=auth_api.logger.name):
+ await auth_api.revoke_builtin_oauth_grants(
+ db, [revocation], context="deleting server 7"
+ )
+
+ post.assert_not_called()
+ assert "no recorded account id" in caplog.text
+ assert "deleting server 7" in caplog.text
+ assert "another local connection" not in caplog.text
+
+
+def test_the_skip_log_names_a_sibling_row_recording_the_same_account(db, post, caplog):
+ user = _user(db)
+ db.add(
+ UserOAuth(
+ user_id=int(user.id),
+ provider="google-drive",
+ provider_user_id="sub-1",
+ access_token="drive-access",
+ )
+ )
+ db.commit()
+
+ with caplog.at_level(logging.INFO, logger=auth_api.logger.name):
+ auth_api.revoke_builtin_oauth_grant(
+ db,
+ provider="gmail",
+ access_token="access",
+ provider_user_id="sub-1",
+ refresh_token="refresh",
+ )
+
+ post.assert_not_called()
+ assert "another local connection" in caplog.text
+ assert "no recorded account id" not in caplog.text
+
+
+def test_a_rejected_access_token_is_logged_as_not_revoked(monkeypatch, caplog):
+ """Google answers an expired access token with invalid_token without
+ revoking the grant behind it: that must not read as success."""
+ monkeypatch.setattr(
+ auth_api.requests,
+ "post",
+ Mock(return_value=MockResponse(400, '{"error": "invalid_token"}')),
+ )
+
+ with caplog.at_level(logging.INFO, logger=auth_api.logger.name):
+ auth_api._revoke_google_oauth_token("access", kind="access_token")
+
+ assert "not revoked" in caplog.text
+
+
+def test_an_unknown_provider_record_is_skipped_not_sent_to_github(monkeypatch, caplog):
+ delete = Mock()
+ post = Mock()
+ monkeypatch.setattr(auth_api.requests, "delete", delete)
+ monkeypatch.setattr(auth_api.requests, "post", post)
+
+ with caplog.at_level(logging.WARNING, logger=auth_api.logger.name):
+ auth_api.revoke_resolved_builtin_oauth_grant(
+ auth_api.BuiltinOAuthRevocation(
+ provider="slack",
+ access_token="tok",
+ client_id="cid",
+ client_secret="secret",
+ provider_user_id="42",
+ )
+ )
+
+ delete.assert_not_called()
+ post.assert_not_called()
+ assert "no revoke implementation" in caplog.text
+
+
+ ("response", "warned"),
+ [
+ (MockResponse(200), False),
+ # Already revoked or expired: also a successful outcome.
+ (MockResponse(400, '{"error": "invalid_token"}'), False),
+ (MockResponse(400, '{"error": "unsupported_token_type"}'), True),
+ (MockResponse(503), True),
+ ],
+)
+def test_revoke_google_token_logs_only_genuine_failures(
+ monkeypatch, caplog, response, warned
+):
+ monkeypatch.setattr(auth_api.requests, "post", Mock(return_value=response))
+
+ with caplog.at_level(logging.WARNING, logger=auth_api.logger.name):
+ auth_api._revoke_google_oauth_token("tok", kind="refresh_token")
+
+ assert bool(caplog.records) is warned
+
+
+def test_revoke_google_token_swallows_a_failure_without_leaking_it(monkeypatch, caplog):
+ monkeypatch.setattr(
+ auth_api.requests,
+ "post",
+ Mock(side_effect=RuntimeError("boom secret-refresh-token")),
+ )
+
+ with caplog.at_level(logging.WARNING, logger=auth_api.logger.name):
+ # Must not raise.
+ auth_api._revoke_google_oauth_token(
+ "secret-refresh-token", kind="refresh_token"
+ )
+
+ assert "RuntimeError" in caplog.text
+ assert "secret-refresh-token" not in caplog.text
+
+
+async def test_delete_mcp_server_revokes_the_google_grant(db, post):
+ """The disconnect endpoints snapshot the refresh token before the bulk
+ delete and revoke it after the commit."""
+ from xagent.web.api.mcp import delete_mcp_server
+
+ user = _user(db)
+ server = MCPServer(
+ name="Gmail", transport="oauth", managed=False, auth={"app_id": "gmail"}
+ )
+ db.add(server)
+ db.flush()
+ db.add(
+ UserMCPServer(
+ user_id=int(user.id), mcpserver_id=server.id, is_active=True, is_owner=True
+ )
+ )
+ db.add(
+ UserOAuth(
+ user_id=int(user.id),
+ provider="gmail",
+ provider_user_id="sub-1",
+ access_token="access",
+ refresh_token="refresh",
+ )
+ )
+ db.commit()
+
+ await delete_mcp_server(server_id=int(server.id), current_user=user, db=db)
+
+ assert db.query(UserOAuth).filter(UserOAuth.user_id == user.id).count() == 0
+ _assert_revoked_with(post, "refresh")
+
+
+def _shared_grant_with_tombstoned_last_link(db: Session, user: User) -> UserOAuth:
+ """A shared ``google`` credential whose only app link points at a legacy
+ Drive row that holds no token any more (a disconnected tombstone).
+ Detaching that link deletes the shared credential as an orphan, and the
+ tombstone itself has nothing to revoke with."""
+ shared = UserOAuth(
+ user_id=int(user.id),
+ provider="google",
+ provider_user_id="sub-1",
+ access_token="shared-access",
+ refresh_token="shared-refresh",
+ scope="openid scope.drive",
+ )
+ legacy = UserOAuth(
+ user_id=int(user.id),
+ provider="google-drive",
+ provider_user_id="sub-1",
+ access_token="shared-access",
+ refresh_token="shared-refresh",
+ scope="openid scope.drive",
+ )
+ db.add_all([shared, legacy])
+ db.flush()
+ create_google_oauth_grant_association(
+ db,
+ oauth_account=shared,
+ oauth_client_id="google-client-id",
+ app_id="google-drive",
+ legacy_oauth_account=legacy,
+ )
+ legacy.access_token = ""
+ legacy.refresh_token = None
+ db.commit()
+ return legacy
+
+
+async def test_mcp_disconnect_revokes_the_shared_grant_its_last_link_deletes(db, post):
+ from xagent.web.api.mcp import delete_mcp_server
+
+ user = _user(db)
+ _shared_grant_with_tombstoned_last_link(db, user)
+ server = MCPServer(
+ name="google-drive",
+ transport="oauth",
+ managed=False,
+ auth={"app_id": "google-drive"},
+ )
+ db.add(server)
+ db.flush()
+ db.add(
+ UserMCPServer(
+ user_id=int(user.id), mcpserver_id=server.id, is_active=True, is_owner=True
+ )
+ )
+ db.commit()
+
+ await delete_mcp_server(server_id=int(server.id), current_user=user, db=db)
+
+ assert db.query(UserOAuth).filter(UserOAuth.user_id == user.id).count() == 0
+ _assert_revoked_with(post, "shared-refresh")
+
+
+async def test_cloud_account_delete_revokes_the_shared_grant_its_last_link_deletes(
+ db, post
+):
+ from xagent.web.api.cloud_storage import delete_connected_account
+
+ user = _user(db)
+ legacy = _shared_grant_with_tombstoned_last_link(db, user)
+
+ await delete_connected_account(account_id=int(legacy.id), db=db, user=user)
+
+ assert db.query(UserOAuth).filter(UserOAuth.user_id == user.id).count() == 0
+ _assert_revoked_with(post, "shared-refresh")
+
+
+async def test_a_shared_grant_a_sibling_app_still_links_is_not_revoked(db, post):
+ """The shared credential is snapshotted before every detach, but one that
+ survives it is still there for the reference check."""
+ from xagent.web.api.cloud_storage import delete_connected_account
+
+ user = _user(db)
+ legacy = _shared_grant_with_tombstoned_last_link(db, user)
+ shared = db.query(UserOAuth).filter(UserOAuth.provider == "google").one()
+ calendar = UserOAuth(
+ user_id=int(user.id),
+ provider="google-calendar",
+ provider_user_id="sub-1",
+ access_token="shared-access",
+ refresh_token="shared-refresh",
+ )
+ db.add(calendar)
+ db.flush()
+ create_google_oauth_grant_association(
+ db,
+ oauth_account=shared,
+ oauth_client_id="google-client-id",
+ app_id="google-calendar",
+ legacy_oauth_account=calendar,
+ )
+ db.commit()
+
+ await delete_connected_account(account_id=int(legacy.id), db=db, user=user)
+
+ assert db.query(UserOAuth).filter(UserOAuth.provider == "google").count() == 1
+ post.assert_not_called()
+
+
+async def test_deleting_a_non_google_account_leaves_the_google_fences_alone(db, post):
+ """A Dropbox disconnect cannot detach a shared Google link, so it must not
+ pay for a fence insert, lock and reference query per shared Google row."""
+ from xagent.web.api.cloud_storage import delete_connected_account
+
+ user = _user(db)
+ _shared_grant_with_tombstoned_last_link(db, user)
+ dropbox = UserOAuth(
+ user_id=int(user.id),
+ provider="dropbox",
+ provider_user_id="dropbox-1",
+ access_token="dropbox-access",
+ )
+ db.add(dropbox)
+ db.commit()
+
+ await delete_connected_account(account_id=int(dropbox.id), db=db, user=user)
+
+ assert db.query(UserOAuth).filter(UserOAuth.provider == "dropbox").count() == 0
+ assert db.query(UserOAuth).filter(UserOAuth.provider == "google").count() == 1
+ assert db.query(OAuthRevocationFence).count() == 0
+ post.assert_not_called()
diff --git a/tests/web/test_oauth_revocation_fence.py b/tests/web/test_oauth_revocation_fence.py
new file mode 100644
index 000000000..2d8f9761c
--- /dev/null
+++ b/tests/web/test_oauth_revocation_fence.py
@@ -0,0 +1,343 @@
+"""The revocation fence between a Google disconnect and a concurrent callback.
+
+Google revokes a whole grant per Google account and OAuth client. When Alice
+disconnects while Bob connects the same Google account, Bob's code exchange
+may be issued tokens of the very grant Alice's revoke then kills. These tests
+interleave the two for real -- Alice's revoke runs on its own session while
+Bob's callback is inside its token exchange -- with only provider HTTP mocked.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import Session, sessionmaker
+
+from tests.shared.oauth_browser_fixture import (
+ create_access_token,
+ generic_oauth_callback,
+)
+from xagent.core.utils.encryption import encrypt_value
+from xagent.web.api import auth as auth_api
+from xagent.web.models.database import Base
+from xagent.web.models.oauth_revocation_fence import OAuthRevocationFence
+from xagent.web.models.user import User
+from xagent.web.models.user_oauth import UserOAuth
+from xagent.web.services import oauth_revocation_fences
+
+TOKEN_URL = "https://oauth2.googleapis.com/token"
+REVOKE_URL = "https://oauth2.googleapis.com/revoke"
+SUBJECT = "google-subject"
+
+
+class MockResponse:
+ def __init__(self, json_data=None, status_code: int = 200, text: str = ""):
+ self._json_data = json_data or {}
+ self.status_code = status_code
+ self.text = text
+
+ def json(self):
+ return self._json_data
+
+
+def sessions(tmp_path):
+ """Two sessions on one file database: Bob's callback and Alice's revoke."""
+ engine = create_engine(
+ f"sqlite:///{tmp_path / 'fence.db'}", connect_args={"check_same_thread": False}
+ )
+ Base.metadata.create_all(engine)
+ factory = sessionmaker(bind=engine, autoflush=False, autocommit=False)
+ bob_db, alice_db = factory(), factory()
+ yield bob_db, alice_db
+ bob_db.close()
+ alice_db.close()
+ engine.dispose()
+
+
+def _google_provider() -> SimpleNamespace:
+ return SimpleNamespace(
+ provider_name="google",
+ client_id=encrypt_value("google-client-id"),
+ client_secret=encrypt_value("google-client-secret"),
+ auth_url="https://accounts.google.com/o/oauth2/v2/auth",
+ token_url=TOKEN_URL,
+ redirect_uri="https://app.example.com/api/auth/google/callback",
+ userinfo_url="https://openidconnect.googleapis.com/v1/userinfo",
+ user_id_path="sub",
+ email_path="email",
+ default_scopes=["openid"],
+ )
+
+
+def _bob(db: Session) -> User:
+ bob = User(username="bob", password_hash="x", is_admin=False)
+ db.add(bob)
+ db.commit()
+ db.refresh(bob)
+ return bob
+
+
+def _connect_google(db: Session, user: User):
+ state = create_access_token(
+ data={
+ "type": "oauth_state",
+ "user_id": int(user.id),
+ "provider": "google",
+ "app_id": None,
+ },
+ expires_delta=timedelta(minutes=10),
+ )
+ return generic_oauth_callback(
+ "google",
+ SimpleNamespace(query_params={"code": "code", "state": state}),
+ db,
+ _google_provider(),
+ )
+
+
+def _revoke_alices_grant(db: Session) -> None:
+ """Alice's disconnect of the same Google account, after its commit."""
+ auth_api.revoke_builtin_oauth_grant(
+ db,
+ provider="google",
+ access_token="alice-access",
+ provider_user_id=SUBJECT,
+ refresh_token="alice-refresh",
+ )
+
+
+def _provider_http(monkeypatch, *, during_exchange=None) -> list[str]:
+ """Mock Google; returns the tokens sent to its revoke endpoint."""
+ revoked: list[str] = []
+
+ def post(url, **kwargs):
+ if url == REVOKE_URL:
+ revoked.append(kwargs["data"]["token"])
+ return MockResponse(status_code=200)
+ assert url == TOKEN_URL
+ if during_exchange is not None:
+ during_exchange()
+ return MockResponse(
+ {
+ "access_token": "bob-access",
+ "refresh_token": "bob-refresh",
+ "token_type": "Bearer",
+ "scope": "openid",
+ }
+ )
+
+ monkeypatch.setattr(auth_api.requests, "post", post)
+ monkeypatch.setattr(
+ auth_api.requests,
+ "get",
+ Mock(return_value=MockResponse({"sub": SUBJECT, "email": "[email protected]"})),
+ )
+ return revoked
+
+
+def test_a_callback_whose_tokens_a_revoke_may_have_killed_is_refused(
+ sessions, monkeypatch
+):
+ """Alice's revoke reaches Google while Bob's exchange is in flight: her
+ reference check cannot see Bob's uncommitted row, so Bob must not store
+ the now-dead tokens and report success."""
+ bob_db, alice_db = sessions
+ bob = _bob(bob_db)
+ revoked = _provider_http(
+ monkeypatch, during_exchange=lambda: _revoke_alices_grant(alice_db)
+ )
+
+ response = _connect_google(bob_db, bob)
+
+ assert revoked == ["alice-refresh"]
+ assert response.status_code == 409
+ assert "connect again" in response.body.decode()
+ assert bob_db.query(UserOAuth).count() == 0
+
+
+def _fence_deadline(db: Session) -> datetime:
+ """The fence's stored deadline, read fresh and tz-aware."""
+ db.expire_all()
+ fence = db.get(OAuthRevocationFence, ("google", SUBJECT))
+ assert fence is not None and fence.revoking_until is not None
+ return oauth_revocation_fences._utc(fence.revoking_until)
+
+
+def test_a_callback_that_starts_after_the_revoke_finished_is_accepted(
+ sessions, monkeypatch
+):
+ """A reconnect right after a disconnect gets a fresh grant."""
+ bob_db, alice_db = sessions
+ bob = _bob(bob_db)
+ revoked = _provider_http(monkeypatch)
+ # The close margin only absorbs clock skew between hosts; this callback
+ # starts in the same instant on the same clock.
+ monkeypatch.setattr(
+ oauth_revocation_fences, "OAUTH_REVOCATION_CLOSE_MARGIN", timedelta(0)
+ )
+ _revoke_alices_grant(alice_db)
+
+ response = _connect_google(bob_db, bob)
+
+ assert revoked == ["alice-refresh"]
+ assert response.status_code == 200
+ assert bob_db.query(UserOAuth).filter_by(provider_user_id=SUBJECT).count() == 1
+
+
+def test_a_revoke_after_the_callback_committed_is_skipped(sessions, monkeypatch):
+ bob_db, alice_db = sessions
+ bob = _bob(bob_db)
+ revoked = _provider_http(monkeypatch)
+
+ assert _connect_google(bob_db, bob).status_code == 200
+ _revoke_alices_grant(alice_db)
+
+ assert revoked == []
+
+
+def test_a_revoker_that_never_closed_its_fence_refuses_until_it_lapses(
+ sessions, monkeypatch
+):
+ """A revoker that died mid-call leaves its deadline in place; callbacks
+ are refused only until it lapses."""
+ bob_db, alice_db = sessions
+ bob = _bob(bob_db)
+ _provider_http(monkeypatch)
+ fence = oauth_revocation_fences.lock_oauth_revocation_fence(
+ alice_db, provider="google", provider_user_id=SUBJECT
+ )
+ oauth_revocation_fences.open_oauth_revocation_fence(fence)
+ alice_db.commit()
+
+ assert _connect_google(bob_db, bob).status_code == 409
+
+ stored = alice_db.get(OAuthRevocationFence, ("google", SUBJECT))
+ stored.revoking_until -= oauth_revocation_fences.OAUTH_REVOCATION_FENCE_WINDOW
+ alice_db.commit()
+
+ assert _connect_google(bob_db, bob).status_code == 200
+
+
+def test_a_revoker_delayed_past_its_fence_skips_the_call(sessions, monkeypatch):
+ _bob_db, alice_db = sessions
+ revoked = _provider_http(monkeypatch)
+ monkeypatch.setattr(
+ oauth_revocation_fences,
+ "OAUTH_REVOCATION_CALL_MARGIN",
+ oauth_revocation_fences.OAUTH_REVOCATION_FENCE_WINDOW,
+ )
+
+ _revoke_alices_grant(alice_db)
+
+ assert revoked == []
+
+
+def test_a_closed_fence_keeps_refusing_for_the_clock_skew_margin(sessions, monkeypatch):
+ """A callback host whose clock runs ahead of the revoker's records an
+ exchange start after the close although the exchange began before the
+ call ended; the close margin covers that."""
+ bob_db, alice_db = sessions
+ bob = _bob(bob_db)
+ _provider_http(monkeypatch)
+ _revoke_alices_grant(alice_db)
+
+ margin = oauth_revocation_fences.OAUTH_REVOCATION_CLOSE_MARGIN
+ assert _fence_deadline(alice_db) > datetime.now(timezone.utc)
+ assert _fence_deadline(alice_db) <= datetime.now(timezone.utc) + margin
+ assert _connect_google(bob_db, bob).status_code == 409
+
+
+def test_a_second_revoker_cannot_close_the_fence_under_one_in_flight(
+ sessions, monkeypatch
+):
+ """Two disconnects of the same account pass their reference check. While
+ the first one's provider call is in flight the second runs to the end: it
+ must neither revoke nor close the fence, or a reconnect right after it
+ would be accepted and then killed by the first call."""
+ bob_db, alice_db = sessions
+ carol_db = sessionmaker(bind=alice_db.get_bind(), autoflush=False)()
+ bob = _bob(bob_db)
+ revoked = _provider_http(monkeypatch)
+ provider_post = auth_api.requests.post
+ reconnect_status: list[int] = []
+
+ def post(url, **kwargs):
+ if url == REVOKE_URL and not reconnect_status:
+ reconnect_status.append(0) # re-entrancy guard
+ auth_api.revoke_builtin_oauth_grant(
+ carol_db,
+ provider="google",
+ access_token="carol-access",
+ provider_user_id=SUBJECT,
+ refresh_token="carol-refresh",
+ )
+ reconnect_status[0] = _connect_google(bob_db, bob).status_code
+ return provider_post(url, **kwargs)
+
+ monkeypatch.setattr(auth_api.requests, "post", post)
+
+ try:
+ _revoke_alices_grant(alice_db)
+ finally:
+ carol_db.close()
+
+ assert revoked == ["alice-refresh"]
+ assert reconnect_status == [409]
+
+
+def _alices_revocation() -> auth_api.BuiltinOAuthRevocation:
+ return auth_api.BuiltinOAuthRevocation(
+ provider="google",
+ access_token="alice-access",
+ client_id="",
+ client_secret="",
+ provider_user_id=SUBJECT,
+ refresh_token="alice-refresh",
+ )
+
+
+async def test_a_cancelled_revoke_closes_its_fence_once_the_call_ended(
+ sessions, monkeypatch
+):
+ """Cancelling the request while the provider call is in flight must not
+ leave the fence open until its deadline, nor close it while the call's
+ thread is still running."""
+ bob_db, alice_db = sessions
+ in_call, finish_call = threading.Event(), threading.Event()
+ finished: list[bool] = []
+
+ def blocked_revoke(revocation) -> None:
+ in_call.set()
+ finish_call.wait(timeout=10)
+ finished.append(True)
+
+ monkeypatch.setattr(auth_api, "revoke_resolved_builtin_oauth_grant", blocked_revoke)
+ task = asyncio.create_task(
+ auth_api.revoke_builtin_oauth_grants(
+ alice_db, [_alices_revocation()], context="test"
+ )
+ )
+ assert await asyncio.to_thread(in_call.wait, 10)
+
+ task.cancel()
+ await asyncio.sleep(0.05)
+ # Cancelled, but the call is still running: the fence stays open.
+ assert not task.done()
+ window = oauth_revocation_fences.OAUTH_REVOCATION_FENCE_WINDOW
+ assert _fence_deadline(bob_db) > datetime.now(timezone.utc) + window / 2
+
+ finish_call.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert finished == [True]
+ margin = oauth_revocation_fences.OAUTH_REVOCATION_CLOSE_MARGIN
+ assert _fence_deadline(bob_db) <= datetime.now(timezone.utc) + margin