Skip to content

Self-improving AI Employees for everyone

refactor(oauth): Google migrates to OAuthStateStore + lifecycle factories (Wave 11.I, S.2)

trohitg210088c9b21e
diff --git a/server/nodes/google/_handlers.py b/server/nodes/google/_handlers.py
index 9cdf91cc..bc0600c5 100644
--- a/server/nodes/google/_handlers.py
+++ b/server/nodes/google/_handlers.py
@@ -1,149 +1,57 @@
-"""Google Workspace WebSocket handlers — plugin-owned dispatch table.
-
-OAuth 2.0 flow for the 6 Google Workspace plugins (Gmail, Calendar,
-Drive, Sheets, Tasks, Contacts) — they share a single OAuth grant and
-a single ``GoogleCredential`` class. The HTTP callback that completes
-the flow lives in :mod:`._router` (mounted via ``register_router``);
-the live-state probe + logout flows are WebSocket handlers
-self-registered into the central WS dispatcher via
-:func:`register_ws_handlers` from this package's ``__init__.py``.
+"""Google Workspace WebSocket handlers — factory-built (Wave 11.I, S.2).
+
+The 3 handlers (``google_oauth_login`` / ``google_oauth_status`` /
+``google_logout``) come from
+:func:`services.events.oauth_lifecycle.make_oauth_lifecycle_handlers`.
+``legacy_status_broadcast="google_status"`` keeps the pre-S frontend
+listeners happy by emitting the legacy wire-frame alongside the
+unified credential-event broadcast.
+
+The factory pulls ``google_client_id`` + ``google_client_secret`` from
+``auth_service`` inside the async :func:`_google_oauth_factory` helper
+and constructs a :class:`GoogleOAuth` per call.
"""
from __future__ import annotations
-from typing import Any, Dict
-
-from fastapi import WebSocket
+from typing import Any, Dict, Optional
-from core.logging import get_logger
-from services.oauth_utils import get_redirect_uri
-from services.status_broadcaster import get_status_broadcaster
+from services.events.oauth_lifecycle import make_oauth_lifecycle_handlers
from ._oauth import GoogleOAuth
-logger = get_logger(__name__)
-
-
-async def handle_google_oauth_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Initiate the Google Workspace OAuth 2.0 flow.
-
- Opens the browser to the Google authorisation page; after consent
- Google redirects to ``/api/google/callback`` (owned by
- :mod:`._router`) which stores tokens via ``auth_service``. One
- grant covers all 6 Workspace services.
- """
- from core.container import container
-
- auth_service = container.auth_service()
- client_id = await auth_service.get_api_key("google_client_id")
- client_secret = await auth_service.get_api_key("google_client_secret")
-
- if not client_id or not client_secret:
- return {
- "success": False,
- "error": (
- "Google Workspace Client ID and Secret not configured. "
- "Add your Google API credentials first."
- ),
- }
-
- redirect_uri = get_redirect_uri(websocket, "google")
- oauth = GoogleOAuth(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri)
- auth_data = oauth.generate_authorization_url()
-
- return {
- "success": True,
- "message": "Opening Google authorization in browser...",
- "url": auth_data["url"],
- "state": auth_data["state"],
- }
-
-
-async def handle_google_oauth_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Check Google Workspace OAuth connection status.
- Returns connection state + user info; proactively refreshes the
- access token if a refresh token is on file (RFC 9700 — refresh
- tokens are read directly from the DB, not the in-memory cache).
- Mirrors the result into the broadcaster's status snapshot so
- reconnecting clients pick up the current state.
- """
+async def _google_oauth_factory(
+ *, redirect_uri: Optional[str] = None, **_kwargs,
+) -> GoogleOAuth:
+ """Build a :class:`GoogleOAuth` from stored client credentials."""
from core.container import container
auth_service = container.auth_service()
- broadcaster = get_status_broadcaster()
-
- tokens = await auth_service.get_oauth_tokens("google", customer_id="owner")
- if not tokens or not tokens.get("access_token"):
- status = {"connected": False, "email": None, "name": None}
- broadcaster._status["google"] = status
- return status
-
- email = tokens.get("email")
- name = tokens.get("name")
- refresh_token = await auth_service.get_oauth_refresh_token("google", customer_id="owner")
-
- try:
- client_id = await auth_service.get_api_key("google_client_id") or ""
- client_secret = await auth_service.get_api_key("google_client_secret") or ""
-
- if refresh_token and client_id and client_secret:
- refreshed = GoogleOAuth.refresh_credentials(
- refresh_token=refresh_token,
- client_id=client_id,
- client_secret=client_secret,
- )
- if refreshed.get("success") and refreshed.get("access_token"):
- await auth_service.store_oauth_tokens(
- provider="google",
- access_token=refreshed["access_token"],
- refresh_token=refresh_token,
- email=email,
- name=name,
- customer_id="owner",
- )
-
- status = {"connected": True, "email": email, "name": name}
- broadcaster._status["google"] = status
- await broadcaster.broadcast({"type": "google_status", "data": status})
- return status
- except Exception as e: # noqa: BLE001 — log and return failure envelope
- logger.warning(f"Google token validation failed: {e}")
- status = {"connected": False, "email": None, "name": None, "error": str(e)}
- broadcaster._status["google"] = {"connected": False, "email": None, "name": None}
- return status
-
-
-async def handle_google_logout(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Disconnect Google Workspace and clear stored credentials.
-
- Symmetric ``credential.oauth.disconnected`` broadcast fires the
- catalogue refetch on every connected client (uniform contract with
- twitter / telegram disconnect paths). The legacy
- ``google_status`` broadcast is kept too so existing FE listeners
- continue to update.
- """
- from core.container import container
+ client_id = await auth_service.get_api_key("google_client_id") or ""
+ client_secret = await auth_service.get_api_key("google_client_secret") or ""
+ return GoogleOAuth(
+ client_id=client_id,
+ client_secret=client_secret,
+ redirect_uri=redirect_uri or "",
+ )
- auth_service = container.auth_service()
- broadcaster = get_status_broadcaster()
- await auth_service.remove_oauth_tokens("google", customer_id="owner")
+def _user_info_to_email(info: Dict[str, Any]) -> str:
+ return info.get("email", "Unknown") or "Unknown"
- cleared = {"connected": False, "email": None, "name": None}
- broadcaster._status["google"] = cleared
- await broadcaster.broadcast({"type": "google_status", "data": cleared})
- await broadcaster.broadcast_credential_event(
- "credential.oauth.disconnected",
- provider="google",
- customer_id="owner",
- )
- return {"success": True, "message": "Google Workspace disconnected"}
+WS_HANDLERS = make_oauth_lifecycle_handlers(
+ provider="google",
+ oauth_factory=_google_oauth_factory,
+ user_info_to_subject=_user_info_to_email,
+ legacy_status_broadcast="google_status",
+)
-WS_HANDLERS = {
- "google_oauth_login": handle_google_oauth_login,
- "google_oauth_status": handle_google_oauth_status,
- "google_logout": handle_google_logout,
-}
+# Module-level aliases so the contract tests in
+# ``tests/credentials/test_websocket_handlers.py`` can import the
+# handlers by name.
+handle_google_oauth_login = WS_HANDLERS["google_oauth_login"]
+handle_google_oauth_status = WS_HANDLERS["google_oauth_status"]
+handle_google_logout = WS_HANDLERS["google_logout"]
diff --git a/server/nodes/google/_oauth.py b/server/nodes/google/_oauth.py
index caa90b15..3fe801b4 100644
--- a/server/nodes/google/_oauth.py
+++ b/server/nodes/google/_oauth.py
@@ -1,25 +1,30 @@
+"""Google Workspace OAuth 2.0 (composition pattern -- Wave 11.I, S.2).
+
+Composes around ``google_auth_oauthlib.flow.Flow`` rather than
+subclassing :class:`services.plugin.oauth.OAuth2PKCEClient`. The Flow
+library handles the PKCE flow, scope handling, and offline-access
+mechanics that Google's token endpoint expects -- hand-rolling those
+would lose the ``OAUTHLIB_RELAX_TOKEN_SCOPE=1`` workaround for
+oauthlib upstream issue #562.
+
+What we DO share with the Twitter (subclass) path:
+
+* :class:`OAuthStateStore` from :mod:`services.plugin.oauth` --
+ identical TTL + cleanup contract, deduplicates the state dict +
+ ``cleanup_expired_states`` helper that pre-S lived here too.
+* The async method shape (``async exchange_code``,
+ ``async fetch_user_info``, ``async refresh_access_token``,
+ ``async revoke_token``) consumed by
+ :func:`services.events.oauth_lifecycle.make_oauth_lifecycle_handlers`
+ and :func:`make_oauth_callback_router`. Sync calls into Flow /
+ Credentials wrap through ``asyncio.to_thread``.
"""
-Google Workspace OAuth 2.0 using google-auth-oauthlib library.
-
-Unified OAuth for all Google services:
-- Gmail (send, search, read emails)
-- Google Calendar (create, list, update, delete events)
-- Google Drive (upload, download, list, share files)
-- Google Sheets (read, write, append data)
-- Google Tasks (create, list, complete tasks)
-- Google Contacts (create, list, search contacts)
-
-Two access modes:
-1. Owner Mode - Your own Google account (Credentials Modal)
-2. Customer Mode - Customer's Google account (database storage)
-
-API endpoints loaded from config/google_apis.json
-Docs: https://developers.google.com/identity/protocols/oauth2
-"""
+from __future__ import annotations
+
+import asyncio
import json
import os
-import time
import warnings
from pathlib import Path
from typing import Any, Dict, List, Optional
@@ -44,23 +49,28 @@ os.environ.setdefault("OAUTHLIB_RELAX_TOKEN_SCOPE", "1")
# errors, deprecation notices) keeps surfacing.
warnings.filterwarnings("ignore", message=r"Scope has changed.*")
+import httpx
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build
from core.logging import get_logger
+from services.plugin.oauth import OAuthStateStore
logger = get_logger(__name__)
-# Load Google API config from JSON.
+
+# ============================================================================
+# Config loaders (consumed by _auth_helper, oauth_utils, _credentials, tests)
+# ============================================================================
+
# Walk up two parents from server/nodes/google/_oauth.py -> server/, then
-# into config/google_apis.json. (Pre-D commit this file lived at
-# services/google_oauth.py and used .parent.parent; the migration into
-# nodes/google/ shifts the directory depth, so we use parents[2].)
+# into config/google_apis.json.
_config_path = Path(__file__).resolve().parents[2] / "config" / "google_apis.json"
_google_config: Dict[str, Any] = {}
+
def _load_config() -> Dict[str, Any]:
"""Load Google API config from JSON file."""
global _google_config
@@ -74,33 +84,53 @@ def _load_config() -> Dict[str, Any]:
_google_config = _get_default_config()
return _google_config
+
def _get_default_config() -> Dict[str, Any]:
- """Return default config if JSON fails to load."""
+ """Default config if JSON load fails."""
return {
"oauth": {
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"revoke_uri": "https://oauth2.googleapis.com/revoke",
- "userinfo_uri": "https://www.googleapis.com/oauth2/v2/userinfo"
+ "userinfo_uri": "https://www.googleapis.com/oauth2/v2/userinfo",
},
"scopes": {
- "userinfo": ["openid", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"],
- "gmail": ["https://www.googleapis.com/auth/gmail.send", "https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/gmail.modify"],
- "calendar": ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.events"],
- "drive": ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.file"],
+ "userinfo": [
+ "openid",
+ "https://www.googleapis.com/auth/userinfo.email",
+ "https://www.googleapis.com/auth/userinfo.profile",
+ ],
+ "gmail": [
+ "https://www.googleapis.com/auth/gmail.send",
+ "https://www.googleapis.com/auth/gmail.readonly",
+ "https://www.googleapis.com/auth/gmail.modify",
+ ],
+ "calendar": [
+ "https://www.googleapis.com/auth/calendar",
+ "https://www.googleapis.com/auth/calendar.events",
+ ],
+ "drive": [
+ "https://www.googleapis.com/auth/drive",
+ "https://www.googleapis.com/auth/drive.file",
+ ],
"sheets": ["https://www.googleapis.com/auth/spreadsheets"],
"tasks": ["https://www.googleapis.com/auth/tasks"],
- "contacts": ["https://www.googleapis.com/auth/contacts", "https://www.googleapis.com/auth/contacts.readonly"]
- }
+ "contacts": [
+ "https://www.googleapis.com/auth/contacts",
+ "https://www.googleapis.com/auth/contacts.readonly",
+ ],
+ },
}
+
def get_oauth_endpoints() -> Dict[str, str]:
- """Get OAuth endpoint URLs from config."""
+ """OAuth endpoint URLs from config."""
config = _load_config()
return config.get("oauth", _get_default_config()["oauth"])
+
def get_callback_paths() -> Dict[str, str]:
- """Get OAuth callback paths from config."""
+ """OAuth callback paths from config."""
config = _load_config()
oauth = config.get("oauth", {})
return {
@@ -110,63 +140,70 @@ def get_callback_paths() -> Dict[str, str]:
def get_service_config(service: str) -> Dict[str, Any]:
- """Get service-specific config (base_url, version, etc.)."""
+ """Service-specific config (base_url, version, etc.)."""
config = _load_config()
return config.get("services", {}).get(service, {})
+
def get_all_scopes() -> List[str]:
- """Get combined scopes for all Google Workspace services."""
+ """Combined scopes for all Google Workspace services."""
config = _load_config()
scopes_config = config.get("scopes", _get_default_config()["scopes"])
all_scopes = []
for scope_list in scopes_config.values():
all_scopes.extend(scope_list)
- return list(dict.fromkeys(all_scopes)) # Remove duplicates, preserve order
+ return list(dict.fromkeys(all_scopes)) # dedupe, preserve order
+
def get_scopes_for_services(services: List[str]) -> List[str]:
- """Get scopes for specific services only."""
+ """Scopes for specific services only."""
config = _load_config()
scopes_config = config.get("scopes", _get_default_config()["scopes"])
- scopes = []
- # Always include userinfo
- scopes.extend(scopes_config.get("userinfo", []))
+ scopes = list(scopes_config.get("userinfo", []))
for service in services:
scopes.extend(scopes_config.get(service, []))
return list(dict.fromkeys(scopes))
-# Combined scopes for all services (loaded from config)
+
GOOGLE_WORKSPACE_SCOPES = get_all_scopes()
+DEFAULT_SCOPES = GOOGLE_WORKSPACE_SCOPES # legacy alias
-# Legacy alias for backward compatibility
-DEFAULT_SCOPES = GOOGLE_WORKSPACE_SCOPES
-# In-memory state store (use Redis in production)
-_oauth_states: Dict[str, Dict[str, Any]] = {}
+# ============================================================================
+# GoogleOAuth (composition wrapper)
+# ============================================================================
class GoogleOAuth:
- """Google Workspace OAuth 2.0 using google-auth-oauthlib Flow.
+ """Google Workspace OAuth 2.0 client (composition wrapper).
+
+ Conforms to the duck-typed protocol consumed by
+ :func:`services.events.oauth_lifecycle.make_oauth_lifecycle_handlers`
+ and :func:`make_oauth_callback_router`: shared :class:`OAuthStateStore`,
+ async ``exchange_code`` / ``fetch_user_info`` /
+ ``refresh_access_token`` / ``revoke_token``.
- Provides unified OAuth for all Google Workspace services.
- API endpoints loaded from config/google_apis.json for easy updates.
+ Internally, ``Flow.from_client_config`` does the PKCE dance and
+ Flow.fetch_token does the token exchange under the
+ ``OAUTHLIB_RELAX_TOKEN_SCOPE=1`` env var.
"""
+ # Plugin-scoped state store -- isolated from Twitter's instance.
+ state_store = OAuthStateStore()
+
def __init__(
self,
client_id: str,
client_secret: str,
redirect_uri: str,
scopes: Optional[List[str]] = None,
- ):
+ ) -> None:
self.client_id = client_id
self.client_secret = client_secret
self.redirect_uri = redirect_uri
self.scopes = scopes or GOOGLE_WORKSPACE_SCOPES
- # Get OAuth endpoints from config
oauth_endpoints = get_oauth_endpoints()
-
- # Build client config in Google's format
self.client_config = {
"web": {
"client_id": client_id,
@@ -177,91 +214,50 @@ class GoogleOAuth:
}
}
self.token_uri = oauth_endpoints["token_uri"]
+ self.revoke_uri = oauth_endpoints.get(
+ "revoke_uri", "https://oauth2.googleapis.com/revoke",
+ )
def generate_authorization_url(
- self,
- state_data: Optional[Dict[str, Any]] = None,
+ self, *, state_data: Optional[Dict[str, Any]] = None,
) -> Dict[str, str]:
- """
- Generate OAuth authorization URL.
-
- Args:
- state_data: Optional data (customer_id, mode, redirect_after)
-
- Returns:
- Dict with url and state
- """
- # Create Flow from client config
+ """Build the Google authorization URL + register state."""
flow = Flow.from_client_config(
- self.client_config,
- scopes=self.scopes,
- redirect_uri=self.redirect_uri,
+ self.client_config, scopes=self.scopes, redirect_uri=self.redirect_uri,
)
-
- # Generate authorization URL with offline access for refresh tokens
authorization_url, state = flow.authorization_url(
access_type="offline",
include_granted_scopes="true",
- prompt="consent", # Force consent to get refresh token
+ prompt="consent", # force consent to get refresh token
)
-
- # Store state data for callback verification
- # PKCE: google-auth-oauthlib auto-generates code_verifier; save it
- # so exchange_code() can restore it on the new Flow instance.
- _oauth_states[state] = {
- "created_at": time.time(),
+ self.state_store.put(state, {
"data": state_data or {"mode": "owner"},
"redirect_uri": self.redirect_uri,
"code_verifier": getattr(flow, "code_verifier", None),
- }
-
- logger.info("Generated Google OAuth URL", state=state[:8])
-
- return {
- "url": authorization_url,
- "state": state,
- }
-
- def exchange_code(self, code: str, state: str) -> Dict[str, Any]:
- """
- Exchange authorization code for credentials.
+ })
+ return {"url": authorization_url, "state": state}
- Args:
- code: Authorization code from callback
- state: State for verification
-
- Returns:
- Dict with tokens and user info
- """
- # Verify state
- oauth_state = _oauth_states.pop(state, None)
- if not oauth_state:
+ async def exchange_code(self, code: str, state: str) -> Dict[str, Any]:
+ """Exchange an auth code for credentials (async wrapper)."""
+ record = self.state_store.take(state)
+ if not record:
return {"success": False, "error": "Invalid or expired state"}
- state_data = oauth_state.get("data", {})
+ state_data = record.get("data", {})
+ code_verifier = record.get("code_verifier")
- try:
- # Create Flow and fetch token
+ def _exchange_sync() -> Dict[str, Any]:
flow = Flow.from_client_config(
self.client_config,
scopes=self.scopes,
redirect_uri=self.redirect_uri,
state=state,
)
- # PKCE: restore code_verifier so token exchange includes it
- code_verifier = oauth_state.get("code_verifier")
if code_verifier:
flow.code_verifier = code_verifier
flow.fetch_token(code=code)
-
- # Get credentials from flow
creds = flow.credentials
-
- # Get user info
- user_info = self._get_user_info(creds)
-
- logger.info("Google OAuth successful", email=user_info.get("email", "")[:20])
-
+ user_info = self._get_user_info_sync(creds)
return {
"success": True,
"access_token": creds.token,
@@ -271,30 +267,85 @@ class GoogleOAuth:
"client_id": creds.client_id,
"client_secret": creds.client_secret,
"scopes": list(creds.scopes) if creds.scopes else self.scopes,
+ "scope": " ".join(creds.scopes) if creds.scopes else "",
"state_data": state_data,
"email": user_info.get("email"),
"name": user_info.get("name"),
"picture": user_info.get("picture"),
}
- except Exception as e:
- logger.error("Token exchange failed", error=str(e))
- return {"success": False, "error": str(e)}
+ try:
+ return await asyncio.to_thread(_exchange_sync)
+ except Exception as exc: # noqa: BLE001
+ logger.error(f"[google] Token exchange failed: {exc}")
+ return {"success": False, "error": str(exc)}
+
+ async def fetch_user_info(self, access_token: str) -> Dict[str, Any]:
+ """Build credentials from an access token + fetch user info."""
+ creds = self.build_credentials(
+ access_token=access_token,
+ refresh_token="", # not needed for a single read
+ client_id=self.client_id,
+ client_secret=self.client_secret,
+ token_uri=self.token_uri,
+ scopes=self.scopes,
+ )
+ try:
+ info = await asyncio.to_thread(self._get_user_info_sync, creds)
+ except Exception as exc: # noqa: BLE001
+ return {"success": False, "error": str(exc)}
+ if not info:
+ return {"success": False, "error": "Failed to read user info"}
+ return {"success": True, **info}
+
+ async def refresh_access_token(self, refresh_token: str) -> Dict[str, Any]:
+ """Async wrapper around :meth:`refresh_credentials`."""
+ return await asyncio.to_thread(
+ self.refresh_credentials,
+ refresh_token, self.client_id, self.client_secret, self.token_uri,
+ )
+
+ async def revoke_token(
+ self, token: str, token_type: str = "access_token",
+ ) -> Dict[str, Any]:
+ """Best-effort token revocation via Google's revoke endpoint."""
+ try:
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ response = await client.post(
+ self.revoke_uri,
+ data={"token": token},
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ except httpx.HTTPError as exc:
+ logger.warning(f"[google] revoke_token network error: {exc}")
+ return {"success": False, "error": str(exc)}
+ if response.status_code == 200:
+ return {"success": True}
+ return {
+ "success": False,
+ "error": (response.json() if response.text else {}).get(
+ "error_description", "Revocation failed",
+ ),
+ }
+
+ # ---- internal helpers ----------------------------------------------
- def _get_user_info(self, creds: Credentials) -> Dict[str, Any]:
- """Get user info using credentials."""
+ def _get_user_info_sync(self, creds: Credentials) -> Dict[str, Any]:
+ """Sync user-info read; called inside ``asyncio.to_thread``."""
try:
service = build("oauth2", "v2", credentials=creds)
- user_info = service.userinfo().get().execute()
+ info = service.userinfo().get().execute()
return {
- "email": user_info.get("email"),
- "name": user_info.get("name"),
- "picture": user_info.get("picture"),
+ "email": info.get("email"),
+ "name": info.get("name"),
+ "picture": info.get("picture"),
}
- except Exception as e:
- logger.error("Failed to get user info", error=str(e))
+ except Exception as exc: # noqa: BLE001
+ logger.error(f"[google] Failed to get user info: {exc}")
return {}
+ # ---- statics: kept for _auth_helper.py + other consumers ----------
+
@staticmethod
def refresh_credentials(
refresh_token: str,
@@ -302,21 +353,9 @@ class GoogleOAuth:
client_secret: str,
token_uri: Optional[str] = None,
) -> Dict[str, Any]:
- """
- Refresh expired credentials.
-
- Args:
- refresh_token: The refresh token
- client_id: OAuth client ID
- client_secret: OAuth client secret
- token_uri: Token endpoint (loaded from config if not provided)
-
- Returns:
- Dict with new access_token
- """
+ """Refresh expired credentials. Returns ``{success, access_token, ...}``."""
if not token_uri:
token_uri = get_oauth_endpoints()["token_uri"]
-
try:
creds = Credentials(
token=None,
@@ -326,15 +365,14 @@ class GoogleOAuth:
client_secret=client_secret,
)
creds.refresh(Request())
-
return {
"success": True,
"access_token": creds.token,
"expires_in": 3600,
}
- except Exception as e:
- logger.error("Token refresh failed", error=str(e))
- return {"success": False, "error": str(e), "needs_reauth": True}
+ except Exception as exc: # noqa: BLE001
+ logger.error(f"[google] Token refresh failed: {exc}")
+ return {"success": False, "error": str(exc), "needs_reauth": True}
@staticmethod
def build_credentials(
@@ -345,14 +383,9 @@ class GoogleOAuth:
token_uri: Optional[str] = None,
scopes: Optional[List[str]] = None,
) -> Credentials:
- """
- Build Credentials object from stored tokens.
-
- Use this to create credentials for Google API calls.
- """
+ """Build Credentials object from stored tokens (used by _auth_helper)."""
if not token_uri:
token_uri = get_oauth_endpoints()["token_uri"]
-
return Credentials(
token=access_token,
refresh_token=refresh_token,
@@ -362,53 +395,49 @@ class GoogleOAuth:
scopes=scopes or GOOGLE_WORKSPACE_SCOPES,
)
- # Service builders for each Google API
@staticmethod
def build_gmail_service(creds: Credentials):
- """Build Gmail API service from credentials."""
return build("gmail", "v1", credentials=creds)
@staticmethod
def build_calendar_service(creds: Credentials):
- """Build Calendar API service from credentials."""
return build("calendar", "v3", credentials=creds)
@staticmethod
def build_drive_service(creds: Credentials):
- """Build Drive API service from credentials."""
return build("drive", "v3", credentials=creds)
@staticmethod
def build_sheets_service(creds: Credentials):
- """Build Sheets API service from credentials."""
return build("sheets", "v4", credentials=creds)
@staticmethod
def build_tasks_service(creds: Credentials):
- """Build Tasks API service from credentials."""
return build("tasks", "v1", credentials=creds)
@staticmethod
def build_people_service(creds: Credentials):
- """Build People API service (Contacts) from credentials."""
return build("people", "v1", credentials=creds)
-# Backward compatibility alias
+# Legacy alias.
GmailOAuth = GoogleOAuth
-def cleanup_expired_states(max_age_seconds: int = 600):
- """Remove expired OAuth states."""
- current_time = time.time()
- expired = [
- state for state, data in _oauth_states.items()
- if current_time - data["created_at"] > max_age_seconds
- ]
- for state in expired:
- _oauth_states.pop(state, None)
+# Module-level alias to the state store's backing dict so the contract
+# tests in tests/credentials/test_google_oauth.py can ``_oauth_states.clear()``.
+# Same trick the Twitter migration uses.
+_oauth_states = GoogleOAuth.state_store._states
-def get_pending_state(state: str) -> Optional[Dict[str, Any]]:
- """Get pending state without removing it."""
- return _oauth_states.get(state)
+__all__ = [
+ "GoogleOAuth",
+ "GmailOAuth",
+ "GOOGLE_WORKSPACE_SCOPES",
+ "DEFAULT_SCOPES",
+ "get_oauth_endpoints",
+ "get_callback_paths",
+ "get_service_config",
+ "get_all_scopes",
+ "get_scopes_for_services",
+]
diff --git a/server/nodes/google/_router.py b/server/nodes/google/_router.py
index 1caeaf93..ceb74231 100644
--- a/server/nodes/google/_router.py
+++ b/server/nodes/google/_router.py
@@ -1,233 +1,115 @@
+"""Google Workspace OAuth callback router — factory-built (Wave 11.I, S.2).
+
+Two endpoints:
+
+* ``GET /api/google/callback`` -- built by
+ :func:`services.events.oauth_lifecycle.make_oauth_callback_router`.
+ ``extra_state_handler`` routes customer-mode logins (where
+ ``state_data["mode"] == "customer"`` and a ``customer_id`` is set)
+ to the ``google_connections`` table by overriding ``customer_id``
+ on ``store_oauth_tokens``. ``redirect_after`` from the same state
+ data triggers a 302 to the customer-portal URL.
+* ``POST /api/google/customer-auth-url`` -- generates an OAuth URL for
+ a specific customer (Google-only multi-tenant feature; Twitter
+ ships owner-mode only).
+
+The pre-S file also exposed ``GET /status`` and ``POST /logout`` REST
+routes; both duplicated the WS handlers in ``_handlers.py`` and have
+been retired in line with the Twitter migration.
"""
-Google Workspace OAuth 2.0 callback and API routes.
-OAuth flow:
-1. Frontend calls WebSocket 'google_oauth_login' handler
-2. Backend generates authorization URL, opens browser
-3. User authorizes on Google
-4. Google redirects to /api/google/callback with code
-5. Backend exchanges code for tokens, stores them via auth_service
-6. Frontend polls WebSocket 'google_oauth_status' for completion
+from __future__ import annotations
-Two access modes:
-- Owner Mode: Tokens stored via auth_service (single account)
-- Customer Mode: Tokens stored in google_connections table (multi-account)
+from typing import Any, Dict, Optional
-Supports all Google Workspace services:
-- Gmail, Calendar, Drive, Sheets, Tasks, Contacts
-"""
-
-from typing import Optional
+from fastapi import APIRouter, Request
-from fastapi import APIRouter, Query, Request
-from fastapi.responses import HTMLResponse, RedirectResponse
+from services.events.oauth_lifecycle import make_oauth_callback_router
-from core.logging import get_logger
-from nodes.google._oauth import GoogleOAuth, get_pending_state
+from ._handlers import _google_oauth_factory
-logger = get_logger(__name__)
-router = APIRouter(prefix="/api/google", tags=["google"])
-
-def get_auth_service():
- """Get auth service for API key storage. Imports lazily to avoid the
- nodes/<plugin>/__init__ -> core.container -> nodes.android._dispatcher
- -> nodes.android.__init__ -> _router import cycle."""
- from core.container import container
- return container.auth_service()
-
-
-def get_database():
- """Get database for customer connections (non-sensitive data only)."""
- from core.container import container
- return container.database()
+def _user_info_to_email(info: Dict[str, Any]) -> str:
+ return info.get("email", "Unknown") or "Unknown"
+def _user_info_to_name(info: Dict[str, Any]) -> str:
+ return info.get("name", "") or ""
[email protected]("/callback")
-async def google_oauth_callback(
- code: Optional[str] = Query(None),
- state: Optional[str] = Query(None),
- error: Optional[str] = Query(None),
- error_description: Optional[str] = Query(None),
-):
- """
- Handle Google OAuth callback.
+async def _customer_mode_handler(
+ payload: Dict[str, Any],
+) -> Optional[Dict[str, Any]]:
+ """If the auth flow was launched in customer mode, route the
+ token storage to the customer's slot + return a 302 target.
- Google redirects here after user authorizes (or denies) the app.
+ Owner mode -> returns ``None`` (lifecycle factory keeps its
+ defaults).
"""
- # Handle authorization denied
- if error:
- logger.warning(f"Google OAuth denied: {error} - {error_description}")
- return HTMLResponse(
- content=_callback_html(success=False, error=error_description or error),
- status_code=200,
- )
-
- # Validate required parameters
- if not code or not state:
- logger.error("Google OAuth callback missing code or state")
- return HTMLResponse(
- content=_callback_html(success=False, error="Missing authorization code or state"),
- status_code=400,
- )
-
- # Verify state exists (CSRF protection)
- pending_state = get_pending_state(state)
- if not pending_state:
- logger.error("Google OAuth callback with invalid/expired state")
- return HTMLResponse(
- content=_callback_html(success=False, error="Invalid or expired state. Please try again."),
- status_code=400,
- )
+ state_data = payload.get("state_data") or {}
+ if state_data.get("mode") != "customer":
+ return None
- # Get state data
- state_data = pending_state.get("data", {})
- mode = state_data.get("mode", "owner")
customer_id = state_data.get("customer_id")
- redirect_after = state_data.get("redirect_after")
-
- # Retrieve redirect_uri from state (set during auth initiation)
- redirect_uri = pending_state.get("redirect_uri")
- if not redirect_uri:
- logger.error("Google OAuth callback missing redirect_uri in state")
- return HTMLResponse(
- content=_callback_html(success=False, error="Invalid state: missing redirect URI. Please try again."),
- status_code=400,
- )
-
- # Get credentials
- auth_service = get_auth_service()
- client_id = await auth_service.get_api_key("google_client_id") or ""
- client_secret = await auth_service.get_api_key("google_client_secret") or ""
-
- if not client_id or not client_secret:
- return HTMLResponse(
- content=_callback_html(success=False, error="Google not configured. Add Client ID and Secret in Credentials."),
- status_code=400,
- )
-
- oauth = GoogleOAuth(
- client_id=client_id,
- client_secret=client_secret,
- redirect_uri=redirect_uri,
- )
-
- # Exchange code for tokens
- result = oauth.exchange_code(code=code, state=state)
-
- if not result.get("success"):
- logger.error(f"Google token exchange failed: {result.get('error')}")
- return HTMLResponse(
- content=_callback_html(success=False, error=result.get("error", "Token exchange failed")),
- status_code=400,
- )
-
- email = result.get("email", "Unknown")
- name = result.get("name", "")
- access_token = result.get("access_token")
- refresh_token = result.get("refresh_token")
-
- # Store tokens via auth_service (single point of access for credentials)
- auth_service = get_auth_service()
+ if not customer_id:
+ return None
- if mode == "customer" and customer_id:
- # Customer mode: store encrypted tokens via auth_service
- await auth_service.store_oauth_tokens(
- provider="google",
- access_token=access_token,
- refresh_token=refresh_token,
- email=email,
- name=name,
- scopes=",".join(result.get("scopes", [])),
- customer_id=customer_id,
- )
- logger.info(f"Google OAuth successful for customer {customer_id}: {email}")
+ user_info = payload.get("user_info") or {}
+ email = user_info.get("email", "Unknown")
+ redirect_after = state_data.get("redirect_after")
- if redirect_after:
- return RedirectResponse(url=f"{redirect_after}?google_connected=true&customer={customer_id}&email={email}")
- else:
- # Owner mode: store encrypted tokens via auth_service
- await auth_service.store_oauth_tokens(
- provider="google",
- access_token=access_token,
- refresh_token=refresh_token,
- email=email,
- name=name,
- scopes=",".join(result.get("scopes", [])),
- customer_id="owner",
+ overrides: Dict[str, Any] = {"customer_id": customer_id}
+ if redirect_after:
+ overrides["redirect_after"] = (
+ f"{redirect_after}?google_connected=true"
+ f"&customer={customer_id}&email={email}"
)
- logger.info(f"Google OAuth successful for {email}")
-
- # Update persistent status and broadcast completion event
- from services.status_broadcaster import get_status_broadcaster
- broadcaster = get_status_broadcaster()
- broadcaster._status["google"] = {
- "connected": True,
- "email": email,
- "name": name,
- }
- await broadcaster.broadcast({
- "type": "google_oauth_complete",
- "data": {"success": True, "email": email, "name": name, "mode": mode, "customer_id": customer_id},
- })
-
- return HTMLResponse(content=_callback_html(success=True, email=email), status_code=200)
-
+ return overrides
-async def get_google_status():
- """Get Google connection status for owner mode."""
- auth_service = get_auth_service()
- tokens = await auth_service.get_oauth_tokens("google", customer_id="owner")
- if not tokens:
- return {"connected": False, "email": None}
-
- return {
- "connected": True,
- "email": tokens.get("email"),
- "name": tokens.get("name"),
- }
-
-
-async def google_logout():
- """Disconnect Google (owner mode)."""
- auth_service = get_auth_service()
- await auth_service.remove_oauth_tokens("google", customer_id="owner")
- logger.info("Google disconnected")
- return {"success": True, "message": "Google disconnected"}
+# The factory mounts ``GET /api/google/callback``. Google-specific
+# extras (the customer-auth-url route + the customer-mode hook) layer
+# on top of the same router instance.
+router: APIRouter = make_oauth_callback_router(
+ provider="google",
+ oauth_factory=_google_oauth_factory,
+ user_info_to_email=_user_info_to_email,
+ user_info_to_name=_user_info_to_name,
+ extra_state_handler=_customer_mode_handler,
+ color_hex="#34a853",
+)
@router.post("/customer-auth-url")
-async def generate_customer_auth_url(request: Request, customer_id: str, redirect_after: Optional[str] = None):
+async def generate_customer_auth_url(
+ request: Request, customer_id: str, redirect_after: Optional[str] = None,
+):
"""Generate OAuth URL for a customer to connect their Google account."""
from services.oauth_utils import get_redirect_uri
- auth_service = get_auth_service()
- client_id = await auth_service.get_api_key("google_client_id") or ""
- client_secret = await auth_service.get_api_key("google_client_secret") or ""
-
- if not client_id or not client_secret:
- return {"success": False, "error": "Google not configured. Add Client ID and Secret."}
-
redirect_uri = get_redirect_uri(request, "google")
-
- oauth = GoogleOAuth(
- client_id=client_id,
- client_secret=client_secret,
- redirect_uri=redirect_uri,
+ oauth = await _google_oauth_factory(redirect_uri=redirect_uri)
+ if not oauth.client_id or not oauth.client_secret:
+ return {
+ "success": False,
+ "error": "Google not configured. Add Client ID and Secret.",
+ }
+ result = oauth.generate_authorization_url(
+ state_data={
+ "customer_id": customer_id,
+ "redirect_after": redirect_after,
+ "mode": "customer",
+ },
)
- result = oauth.generate_authorization_url(state_data={"customer_id": customer_id, "redirect_after": redirect_after, "mode": "customer"})
return {"success": True, "url": result["url"], "state": result["state"]}
@router.get("/customer/{customer_id}/status")
async def get_customer_google_status(customer_id: str):
"""Get Google connection status for a customer."""
- auth_service = get_auth_service()
+ from core.container import container
+
+ auth_service = container.auth_service()
tokens = await auth_service.get_oauth_tokens("google", customer_id=customer_id)
if not tokens:
return {"connected": False, "customer_id": customer_id}
@@ -242,39 +124,8 @@ async def get_customer_google_status(customer_id: str):
@router.post("/customer/{customer_id}/disconnect")
async def disconnect_customer_google(customer_id: str):
"""Disconnect a customer's Google account."""
- auth_service = get_auth_service()
+ from core.container import container
+
+ auth_service = container.auth_service()
await auth_service.remove_oauth_tokens("google", customer_id=customer_id)
- logger.info(f"Google disconnected for customer {customer_id}")
return {"success": True, "customer_id": customer_id}
-
-
-def _callback_html(success: bool, email: str = None, error: str = None) -> str:
- """Generate callback HTML page."""
- if success:
- title, message, color = "Google Connected", f"Successfully connected as {email}!", "#34a853"
- else:
- title, message, color = "Connection Failed", error or "Failed to connect", "#ea4335"
-
- escaped_error = error.replace("'", "\\'") if error else ""
- return f"""<!DOCTYPE html>
-<html>
-<head><title>{title}</title>
-<style>
-*{{margin:0;padding:0;box-sizing:border-box}}
-body{{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:linear-gradient(135deg,#15202b,#1a1a2e);min-height:100vh;display:flex;align-items:center;justify-content:center;color:#fff}}
-.container{{text-align:center;padding:40px;background:rgba(255,255,255,0.05);border-radius:16px;border:1px solid rgba(255,255,255,0.1);max-width:400px}}
-.icon{{width:64px;height:64px;margin-bottom:20px;color:{color}}}
-h1{{font-size:24px;margin-bottom:12px;color:{color}}}
-p{{font-size:16px;color:rgba(255,255,255,0.8);margin-bottom:20px}}
-.close-text{{font-size:14px;color:rgba(255,255,255,0.5)}}
-</style></head>
-<body><div class="container">
-<svg class="icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
-{"<path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z'/>" if success else "<path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z'/>"}
-</svg>
-<h1>{title}</h1><p>{message}</p><p class="close-text">This window will close automatically...</p>
-</div>
-<script>
-if(window.opener){{window.opener.postMessage({{type:'google_oauth_callback',success:{str(success).lower()},{"email:'"+email+"'," if email else ""}{"error:'"+escaped_error+"'," if error else ""}}},'*')}}
-setTimeout(function(){{window.close()}},2000);
-</script></body></html>"""
diff --git a/server/services/events/oauth_lifecycle.py b/server/services/events/oauth_lifecycle.py
index 868a882d..c868bf4d 100644
--- a/server/services/events/oauth_lifecycle.py
+++ b/server/services/events/oauth_lifecycle.py
@@ -161,10 +161,10 @@ def make_oauth_lifecycle_handlers(
tokens = await auth_service.get_oauth_tokens(provider, customer_id="owner")
if not tokens or not tokens.get("access_token"):
# Match pre-S handler shape -- frontends key on these
- # exact field names. Extra ``user_id``/``username``/...
- # fields are absent on success too when the provider
- # didn't return them, so callers must defensive-read.
- payload = {"connected": False, "username": None, "user_id": None}
+ # exact field names. Both Twitter (username/user_id) and
+ # Google (email/name) field sets included so a single
+ # disconnected payload satisfies every provider.
+ payload = _disconnected_payload()
await _maybe_legacy_broadcast(legacy_status_broadcast, payload)
return payload
@@ -195,9 +195,7 @@ def make_oauth_lifecycle_handlers(
if not user_info.get("success"):
payload = {
- "connected": False,
- "username": None,
- "user_id": None,
+ **_disconnected_payload(),
"error": user_info.get("error"),
}
await _maybe_legacy_broadcast(legacy_status_broadcast, payload)
@@ -265,6 +263,19 @@ async def _maybe_legacy_broadcast(
await get_status_broadcaster().broadcast({"type": broadcast_type, "data": payload})
+def _disconnected_payload() -> Dict[str, Any]:
+ """Disconnected status payload with the union of Twitter / Google
+ field names. Frontends read what they need; unknown None values
+ are ignored. Easier than parameterising the field list per plugin."""
+ return {
+ "connected": False,
+ "username": None,
+ "user_id": None,
+ "email": None,
+ "name": None,
+ }
+
+
# ============================================================================
# make_oauth_callback_router
# ============================================================================
diff --git a/server/tests/credentials/test_google_oauth.py b/server/tests/credentials/test_google_oauth.py
index 8015f577..9060e7b7 100644
--- a/server/tests/credentials/test_google_oauth.py
+++ b/server/tests/credentials/test_google_oauth.py
@@ -88,18 +88,18 @@ class TestAuthorizationUrl:
class TestExchangeCode:
- def test_unknown_state_fails(self, oauth):
+ async def test_unknown_state_fails(self, oauth):
# Don't even register a state -- exchange must fail without hitting Google.
- result = oauth.exchange_code("code", "never-generated-state")
+ result = await oauth.exchange_code("code", "never-generated-state")
assert result["success"] is False
assert "state" in result["error"].lower()
- def test_state_consumed_on_failure(self, oauth):
+ async def test_state_consumed_on_failure(self, oauth):
"""Even if the token exchange fails, the state must be popped (single use)."""
auth = oauth.generate_authorization_url()
state = auth["state"]
# Exchange will fail because we haven't mocked Google -- network error
- oauth.exchange_code("invalid-code", state)
+ await oauth.exchange_code("invalid-code", state)
# State must be gone regardless of success
assert state not in google_oauth._oauth_states