agnes-the-ai-analyst/scripts/debug/probe_google_groups.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

184 lines
6.3 KiB
Python
Executable file

#!/usr/bin/env python3
"""Probe Google Cloud Identity / Admin Directory APIs for "list groups of THIS user".
Run locally with a fresh user OAuth access token to figure out which endpoint
+ scope combo actually works for your Workspace tenant — without a deploy cycle.
Stdlib only — no pip install needed.
Why this exists:
Zdeněk's first attempt used `cloudidentity.googleapis.com/v1/groups:search`
with `cloud-identity.groups.readonly` scope. Returns 400 INVALID_ARGUMENT
in Keboola's Workspace because that endpoint requires admin permission
despite the scope name suggesting otherwise.
How to get an access token (Easiest path):
Google's OAuth 2.0 Playground (https://developers.google.com/oauthplayground/)
1. Click the gear icon (top right) → tick "Use your own OAuth credentials"
2. Paste your Client ID + Secret (from kids-ai-data-analysis project,
same OAuth client agnes-dev uses)
3. Step 1: pick scopes. For comparison test all of:
https://www.googleapis.com/auth/cloud-identity.groups.readonly
https://www.googleapis.com/auth/cloud-identity.groups
https://www.googleapis.com/auth/admin.directory.group.readonly
openid
email
profile
4. Authorize APIs → sign in as your Workspace user
5. Step 2: Exchange authorization code for tokens
6. Copy the "Access token" string (starts with `ya29.`)
Usage:
python3 scripts/debug/probe_google_groups.py <access_token> <email>
Example:
python3 scripts/debug/probe_google_groups.py ya29.a0AfH6S... petr@keboola.com
"""
from __future__ import annotations
import json
import sys
import urllib.error
import urllib.parse
import urllib.request
def _section(title: str) -> None:
print()
print("=" * 78)
print(f" {title}")
print("=" * 78)
def _probe(name: str, url: str, params: dict | None = None,
headers: dict | None = None) -> None:
print(f"\n--- {name} ---")
full_url = url
if params:
full_url = f"{url}?{urllib.parse.urlencode(params)}"
print(f" GET {url}")
if params:
for k, v in params.items():
print(f" {k}={v}")
req = urllib.request.Request(full_url, headers=headers or {})
try:
with urllib.request.urlopen(req, timeout=10) as resp:
status = resp.status
body_bytes = resp.read()
except urllib.error.HTTPError as e:
status = e.code
body_bytes = e.read()
except Exception as e:
print(f" EXCEPTION: {type(e).__name__}: {e}")
return
print(f" HTTP {status}")
body = body_bytes.decode("utf-8", errors="replace")
try:
body = json.dumps(json.loads(body), indent=2)
except Exception:
body = body[:600]
print(" body:")
for line in body.splitlines():
print(f" {line}")
def main() -> int:
if len(sys.argv) != 3:
print(__doc__)
return 1
access_token, email = sys.argv[1], sys.argv[2]
auth = {"Authorization": f"Bearer {access_token}"}
_section("0. Token introspection — what scopes does this token actually have?")
_probe(
"tokeninfo",
"https://oauth2.googleapis.com/tokeninfo",
params={"access_token": access_token},
)
_section("1. OpenID userinfo — verify token identifies the right user")
_probe(
"userinfo",
"https://openidconnect.googleapis.com/v1/userinfo",
headers=auth,
)
_section("2. Cloud Identity — searchTransitiveGroups (user perspective)")
for label_kind in ("discussion_forum", "security"):
_probe(
f"with labels = '{label_kind}'",
"https://cloudidentity.googleapis.com/v1/groups/-/memberships:searchTransitiveGroups",
params={
"query": (
f"member_key_id == '{email}' && "
f"'cloudidentity.googleapis.com/groups.{label_kind}' in labels"
),
},
headers=auth,
)
_section("3. Cloud Identity — searchDirectGroups (no transitive)")
_probe(
"direct only with discussion_forum label",
"https://cloudidentity.googleapis.com/v1/groups/-/memberships:searchDirectGroups",
params={
"query": (
f"member_key_id == '{email}' && "
"'cloudidentity.googleapis.com/groups.discussion_forum' in labels"
),
},
headers=auth,
)
_section("4. Cloud Identity — groups:search (admin endpoint, expected to fail)")
_probe(
"admin search with parent + member_key_id",
"https://cloudidentity.googleapis.com/v1/groups:search",
params={
"query": (
"parent == 'customers/my_customer' && "
f"member_key_id == '{email}' && "
"'cloudidentity.googleapis.com/groups.discussion_forum' in labels"
),
"view": "BASIC",
},
headers=auth,
)
_section("5. Admin SDK Directory — legacy groups?userKey (admin scope required)")
_probe(
"directory list groups for user",
"https://admin.googleapis.com/admin/directory/v1/groups",
params={"userKey": email},
headers=auth,
)
print()
print("=" * 78)
print("Interpretation guide:")
print("=" * 78)
print("""
HTTP 200 + groups list → that's the working endpoint, use it in google.py
HTTP 200 + empty list → endpoint works but user has no matching groups
HTTP 400 INVALID_ARG → query syntax wrong OR permission issue Google
silently disguises as 400 (common for non-admin)
HTTP 403 PERMISSION → token lacks scope or admin role
HTTP 401 UNAUTHENTICATED→ token expired (re-fetch from playground)
HTTP 404 NOT FOUND → API not enabled, or wrong URL
If ALL Cloud Identity endpoints return 400/403 for a non-admin user, the
conclusion is: Cloud Identity Groups API requires admin permission for
user-perspective queries, regardless of OAuth scope. Switch to one of:
(a) Service Account + Domain-Wide Delegation (Vojta's v3 design)
(b) Workspace OIDC groups claim (admin enables in Workspace Console)
(c) Grant 'Groups Reader' role to every user (admin overhead)
""")
return 0
if __name__ == "__main__":
sys.exit(main())