agnes-the-ai-analyst/app/auth/providers/google.py
Petr Simecek c25fd41bf7
feat(auth): Google Workspace groups on /profile + tag-triggered Keboola deploy workflow (#56)
* feat(auth): display Google Workspace groups on /profile

- Request cloud-identity.groups.readonly scope in Google OAuth
- Fetch groups via Cloud Identity API after callback; tolerate 4xx
  (non-Workspace tenants) and network errors — never break login
- Store result in Starlette session as google_groups
- Replace /profile redirect with a real profile page rendering
  account details (email, name, role) and the group list; show a
  friendly empty state when no groups are available
- Tests: helper parsing + 403 + exception paths; profile page
  smoke test; updated the old redirect test

* test: remove stale /profile redirect tests

Cherry-pick of Zdeněk's 4f7e4cd ("display Google Workspace groups on
/profile") replaces the /profile redirect with a real profile page —
but only updated one of three tests that expected the old behaviour.

These two tests in test_admin_tokens_ui.py and test_pat.py were left
asserting `/profile → 302 /tokens`, which now returns
`/profile → 302 /login?next=%2Fprofile` for unauth users (the standard
auth guard) or `/profile → 200 HTML` for authenticated users.

Removed both rather than patched — coverage for the new behaviour
already exists in tests/test_auth_providers.py (added by the same
commit). The /tokens render assertions in the deleted test_pat.py case
are redundant with test_admin_tokens_ui.py's own /tokens UI tests.

* fix(auth): Google groups search query needs parent + labels predicates

Cloud Identity Groups Search API returns 400 INVALID_ARGUMENT when the
CEL query lacks the required `parent == 'customers/<id>'` predicate AND
a `'<label>' in labels` membership predicate. Zdeněk's original 4f7e4cd
query had only `member_key_id == '<email>'` — every fetch silently
returned [] and the /profile groups list was always empty.

Fix: build the query with all three required pieces:
  parent == 'customers/my_customer'   (alias = caller's own Workspace
                                       org; no need to look up customer ID)
  member_key_id == '<email>'           (filter to this user's memberships)
  'cloudidentity.googleapis.com/groups.discussion_forum' in labels
                                       (Workspace mailing-list groups —
                                       the common case; security-group
                                       coverage is a follow-up)

Also: log the full error body (not truncated to 200 chars) and the
query string so the next time Google rejects something we can diagnose
in one log line instead of a re-deploy.

Caught when first agnes-dev login completed normally (HTTP 302) but app
log showed `Google groups fetch returned 400 for petr@keboola.com:
{"error":{"code":400,"message":"Request contains an invalid argument."}}`
on the same VM (kids-ai-data-analysis / agnes-dev.keboola.com).

Reference: https://cloud.google.com/identity/docs/reference/rest/v1/groups/search

* feat(web): add Profile link to user dropdown menu

The /profile page (Zdeněk's 4f7e4cd cherry-pick) renders a real profile
view including Google Workspace groups, but had no entry point in the
UI — users could only reach it by typing the URL manually. Add a
"Profile" menu item between the user header (email + role) and
"My tokens" so the page is discoverable.

Side effect: cleaned up the leftover `or _path.startswith('/profile')`
condition on the "My tokens" active class, which dated from the old
/profile → /tokens redirect (removed in c789617). Now each menu item
owns its own active state.

* fix: profile-link tests + .env quoting for CADDY_TLS

Two issues caught by Keboola's first agnes-dev deploy + agnes-auto-upgrade
cron run:

1. tests/test_web_ui.py — two negative assertions ("href=/profile" NOT in
   body) date from when /profile was a redirect-only stub. Now /profile
   is a real page (groups display) AND has a dropdown menu link, so the
   negative assertions flip to positive. Same for ">Profile<" text in
   the non-admin nav test.

2. startup-script.sh.tpl — CADDY_TLS line must be QUOTED in .env, because
   agnes-auto-upgrade.sh sources .env via `set -a; . .env; set +a` and
   bash treats `KEY=value with spaces` as `KEY=value` followed by `with`
   and `spaces` exec attempts. Symptom: cron log spam
   `/opt/agnes/.env: line 14: petr@keboola.com: command not found`,
   the cron exits non-zero, and no auto-upgrade ever happens. Caddy
   itself reads the value fine because docker-compose env_file=.env
   parses key=value properly without shell-evaluating the rest.

   Fix: emit `CADDY_TLS="tls <email>"` instead of `CADDY_TLS=tls <email>`.
   Both the cron source and docker-compose env_file accept the quoted
   form; cron stops failing.

* fix(auth): use searchTransitiveGroups + security label for non-admin user

Three bugs in the original cherry-pick + my prior fix attempt, all caught
by a stdlib probe script (scripts/debug/probe_google_groups.py) run
locally with a Playground-issued OAuth token:

1. Wrong endpoint. `groups:search` is the admin "find groups in org"
   endpoint and 400s for non-admin users regardless of query. Switched
   to `groups/-/memberships:searchTransitiveGroups` which is the
   user-perspective "what groups am I in" endpoint.

2. Wrong label. Querying with `cloudidentity.googleapis.com/groups.discussion_forum`
   returns 403 "Insufficient permissions to retrieve memberships" even
   on the new endpoint — Workspace policy denies non-admin reads of
   discussion-forum groups. Switching to `groups.security` returns 200
   with the actual membership list. Empirically every Workspace group
   at Keboola carries BOTH labels, so the security filter sees the full
   set anyway. Confirmed with the probe script.

3. Wrong response shape. `searchTransitiveGroups` returns
   {"memberships": [...]}, not {"groups": [...]}. Parser updated
   accordingly.

Also adds scripts/debug/probe_google_groups.py — stdlib-only standalone
probe that hits 6 candidate endpoints with a user OAuth token. Saved a
deploy cycle (~10 min) per query iteration; future API-syntax debugging
should start there.

Verified end-to-end: petr@keboola.com login on agnes-dev returns 5
groups (LIC-1PASSWORD, ROLE_ATLASSIAN_*, etc.) via the probe; once
deployed, the same will populate session["google_groups"] and render
on /profile.

* test(auth): update Google groups parser fixture to match searchTransitiveGroups shape

Mock payload was `{"groups": [...]}` (the shape `groups:search` returns).
After switching to `groups/-/memberships:searchTransitiveGroups` in the
prior commit, the actual response is `{"memberships": [...]}` and the
parser iterates that key. Test now mirrors the real shape.

The per-item structure (groupKey.id + displayName) is unchanged, so the
expected output dict stays the same: [{"id": "...", "name": "..."}].

* docs(auth): add docs/auth-groups.md — Google Workspace groups runbook

Captures the non-obvious bits: the GCP-side setup checklist (Cloud
Identity API + scope on consent screen + Internal user type), the
`security` vs `discussion_forum` label trap (the latter 403s for
non-admins, the former 200s — one of those is a 4-iteration debug
session and shouldn't have to be repeated), where groups are stored
(session, not DB) and how to refresh (re-login), plus how to use the
probe script for future API-syntax issues.

Deliberately stops short of explaining "what is Cloud Identity" or
"what is OAuth scope" — those belong in Google's own docs, not ours.

* docs(claude): document release workflows + module versioning + recreate trick

New "Release & deploy workflows" section in CLAUDE.md covers what didn't
exist anywhere in the repo before:

- Distinction between release.yml (auto-build per push) vs the new
  keboola-deploy.yml (tag-triggered, explicit deploy only) — plus when
  to use which (per-developer convenience vs shared dev VM safety)
- Module versioning (infra-vX.Y.Z) and the bump-after-merge dance
- The lifecycle.ignore_changes [metadata_startup_script] gotcha and how
  to force a recreate via workflow_dispatch's recreate_targets input

All generic — no customer hostnames, project IDs, IPs. Customer-specific
deploy steps belong in the consuming infra repo's README.

Also: cross-reference docs/auth-groups.md from the Authentication
section so future Claude sessions find the Workspace-groups runbook
without grepping.

---------

Co-authored-by: ZdenekSrotyr <zdenek.srotyr@keboola.com>
2026-04-26 00:56:44 +02:00

219 lines
8.5 KiB
Python

"""Google OAuth provider for FastAPI."""
import os
import logging
import httpx
from authlib.integrations.starlette_client import OAuth
from fastapi import APIRouter, Request
from fastapi.responses import RedirectResponse
from starlette.config import Config as StarletteConfig
from app.auth.jwt import create_access_token
from app.auth._common import safe_next_path
from app.instance_config import get_allowed_domains
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/auth/google", tags=["auth"])
oauth = OAuth()
GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID", "")
GOOGLE_CLIENT_SECRET = os.environ.get("GOOGLE_CLIENT_SECRET", "")
# Cloud Identity Groups API — requires the cloud-identity.groups.readonly scope
# AND an admin-enabled Cloud Identity / Google Workspace tenant.
#
# We use `groups/-/memberships:searchTransitiveGroups` (the "what groups does
# THIS USER belong to" endpoint), NOT `groups:search` (admin "find groups in
# org" endpoint, which requires Groups Reader admin role + 400s otherwise).
# The `-` in the path is a wildcard meaning "search across all groups in the
# caller's organization". Returns transitive memberships (incl. nested groups).
# Reference: https://cloud.google.com/identity/docs/reference/rest/v1/groups.memberships/searchTransitiveGroups
GROUPS_SEARCH_URL = (
"https://cloudidentity.googleapis.com/v1/groups/-/memberships:searchTransitiveGroups"
)
def is_available() -> bool:
return bool(GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET)
def _setup_oauth():
if not is_available():
return
oauth.register(
name="google",
client_id=GOOGLE_CLIENT_ID,
client_secret=GOOGLE_CLIENT_SECRET,
server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
client_kwargs={
"scope": (
"openid email profile "
"https://www.googleapis.com/auth/cloud-identity.groups.readonly"
),
},
)
async def _fetch_google_groups(access_token: str, email: str) -> list[dict]:
"""Fetch Google Workspace groups the user belongs to.
Best-effort: returns [] on any failure (403 non-Workspace tenant, 401 expired
token, network error, etc.). Must never raise — callers rely on this to keep
the login flow working even when Cloud Identity is unavailable.
searchTransitiveGroups query syntax (CEL) requires:
- a `labels` membership predicate scoping the group type
- `member_key_id == '<email>'` for the user
Without `labels` Google returns 400 INVALID_ARGUMENT (silently — error
body just says "invalid argument").
Reference: https://cloud.google.com/identity/docs/reference/rest/v1/groups.memberships/searchTransitiveGroups
Why `security` label and not `discussion_forum`:
Empirically Keboola's Workspace lets a non-admin user read their own
group memberships ONLY for groups labelled as security groups
(`cloudidentity.googleapis.com/groups.security`). The same query with
`groups.discussion_forum` returns 403 "Insufficient permissions to
retrieve memberships" — the discussion_forum API needs admin scope.
In practice every Workspace group at Keboola carries BOTH labels, so
filtering on `security` returns the full membership list anyway.
Confirmed via scripts/debug/probe_google_groups.py.
"""
query = (
f"member_key_id == '{email}' "
f"&& 'cloudidentity.googleapis.com/groups.security' in labels"
)
params = {"query": query}
headers = {"Authorization": f"Bearer {access_token}"}
try:
async with httpx.AsyncClient(timeout=5.0) as client:
resp = await client.get(GROUPS_SEARCH_URL, params=params, headers=headers)
if resp.status_code >= 400:
# Log full body (not truncated) so future query-syntax / scope /
# tenant issues are diagnosable from one log line.
logger.warning(
"Google groups fetch returned %s for %s — query=%r — body=%s",
resp.status_code, email, query, resp.text,
)
return []
data = resp.json()
except Exception as e:
logger.warning("Google groups fetch failed for %s: %s", email, e)
return []
# searchTransitiveGroups returns `memberships`, not `groups`. Each membership
# carries the group identity in groupKey.id (email-shaped) + displayName.
groups = []
for m in data.get("memberships", []) or []:
group_key = (m.get("groupKey") or {}).get("id", "")
if not group_key:
continue
groups.append({
"id": group_key,
"name": m.get("displayName") or group_key,
})
return groups
_setup_oauth()
@router.get("/login")
async def google_login(request: Request):
"""Redirect to Google OAuth.
Honors `?next=<path>` by stashing the sanitized value in the session so the
callback can redirect there instead of the default /dashboard. The session
is the right stash — OAuth flow is stateful and the `state` param is
managed by Authlib.
"""
if not is_available():
return RedirectResponse(url="/login?error=google_not_configured")
next_path = safe_next_path(request.query_params.get("next"), default="")
if next_path:
request.session["login_next"] = next_path
else:
# Clear any stale value from an earlier aborted attempt.
request.session.pop("login_next", None)
redirect_uri = str(request.url_for("google_callback"))
return await oauth.google.authorize_redirect(request, redirect_uri)
@router.get("/callback")
async def google_callback(request: Request):
"""Handle Google OAuth callback."""
if not is_available():
return RedirectResponse(url="/login?error=google_not_configured")
try:
token = await oauth.google.authorize_access_token(request)
user_info = token.get("userinfo", {})
email = user_info.get("email", "")
name = user_info.get("name", "")
if not email:
return RedirectResponse(url="/login?error=no_email")
# Domain check
allowed = get_allowed_domains()
if allowed:
domain = email.split("@")[-1]
if domain not in allowed:
return RedirectResponse(url="/login?error=domain_not_allowed")
# Find or create user
from src.db import get_system_db
from src.repositories.users import UserRepository
import uuid
conn = get_system_db()
try:
repo = UserRepository(conn)
user = repo.get_by_email(email)
if not user:
user_id = str(uuid.uuid4())
repo.create(id=user_id, email=email, name=name, role="analyst")
user = repo.get_by_email(email)
if not bool(user.get("active", True)):
return RedirectResponse(url="/login?error=deactivated")
finally:
conn.close()
# Fetch Google Workspace groups (best-effort — must not break login).
access_token = token.get("access_token", "")
if access_token:
try:
groups = await _fetch_google_groups(access_token, email)
request.session["google_groups"] = groups
except Exception as e:
logger.warning("Failed to store google_groups in session: %s", e)
request.session["google_groups"] = []
else:
request.session["google_groups"] = []
# Issue JWT
jwt_token = create_access_token(user["id"], user["email"], user["role"])
# Redirect to the post-login target. Prefer the value stashed by
# google_login() — re-sanitize defensively in case of session tampering.
target = safe_next_path(
request.session.pop("login_next", None), default="/dashboard"
)
# Redirect to target with token in cookie. Match password/email providers:
# Secure only when DOMAIN is set (production with TLS), so the cookie is
# actually sent over plain HTTP in dev.
use_secure = os.environ.get("DOMAIN", "") != ""
response = RedirectResponse(url=target, status_code=302)
response.set_cookie(
key="access_token", value=jwt_token,
httponly=True, max_age=86400, samesite="lax",
secure=use_secure,
)
return response
except Exception as e:
logger.error(f"Google OAuth error: {e}")
return RedirectResponse(url="/login?error=oauth_failed")