agnes-the-ai-analyst/scripts/debug/probe_google_groups.py
ZdenekSrotyr 4e4d2a39e6
chore(oss): isolate customer-specific deploy bits from scripts/grpn/ (#88, wave 1) (#94)
* chore(oss): isolate customer-specific deploy bits from scripts/grpn/ (#88)

Vendor-neutralization step before public release. The directory mixed
two concerns: (1) generic ops scripts referenced from mainline OSS
infrastructure (TLS rotation, auto-upgrade cron) and (2) one operator's
hackathon manual-deploy helper with hardcoded GCP project IDs, VM names,
and admin emails. Splitting them per concern.

Moved (still in OSS, just under a vendor-neutral name):
- scripts/grpn/agnes-tls-rotate.sh   → scripts/ops/agnes-tls-rotate.sh
- scripts/grpn/agnes-auto-upgrade.sh → scripts/ops/agnes-auto-upgrade.sh

Removed (belongs in private consumer infra repos, not upstream OSS):
- scripts/grpn/Makefile (hardcoded prj-grp-foundryai-dev-7c37, foundryai-development VM name, e_zsrotyr@groupon.com bootstrap email)
- scripts/grpn/README.md (GRPN hackathon deploy walkthrough)
- docs/superpowers/plans/2026-04-22-grpn-deploy-learnings.md (org-specific deploy log)

Cross-refs updated in README.md, CLAUDE.md, docs/DEPLOYMENT.md,
docker-compose.yml. CHANGELOG entry flags BREAKING (ops) for any
consumer infra repo that installs these scripts via path-based systemd
timers.

This is the first wave of #88 — the remaining leaks (test data with
prj-grp-dataview-prod-1ff9, AIAgent.FoundryAI tags in OpenMetadata test
fixtures, docstrings in connectors/openmetadata/enricher.py) will be a
separate, smaller PR.

Refs #88.

* chore(oss): comprehensive vendor-neutralization (#88 wave 2 + review fixes)

PR #94 review found that the original wave-1 grep was scoped wrong and
many leaks survived. This commit closes wave 1 properly AND folds in all
wave-2 anonymization in a single pass — easier to review than two PRs.

Wave-1 review-fix corrections:
- Caddyfile: scripts/grpn/agnes-tls-rotate.sh → scripts/ops/ (the original
  wave-1 grep filter excluded extensionless files like Caddyfile).
- CHANGELOG bullet rewritten — original wording implied an in-repo migration
  for infra/modules/customer-instance/, which is wrong (the TF module embeds
  the script inline via heredoc, never sourced from scripts/grpn/). Now
  flags downstream consumer infra repos only.
- infra/modules/customer-instance/variables.tf: Czech docstring with `grpn`
  example → English description with `acme, example` placeholders.

Wave-2 anonymization:
- Code docstrings (connectors/openmetadata/{client,transformer,enricher}.py,
  src/catalog_export.py, scripts/duckdb_manager.py): prj-grp-… →
  my-bq-project / prj-example-1234, AIAgent.FoundryAI → AIAgent.MyAgent,
  FoundryAIDataModel → AnalyticsDataModel.
- Test fixtures (4 files): same set of replacements — 157 tests still pass.
- .github/workflows/keboola-deploy.yml: "Groupon-side dev VMs" comment →
  generic "per-developer dev VMs".
- docs/auth-groups.md + scripts/debug/probe_google_groups.py:
  kids-ai-data-analysis project name → acme-internal-prod placeholder.
- 5 planning/spec docs under docs/superpowers/{plans,specs}/2026-04-21-*:
  hardcoded IPs (34.77.94.14, 34.77.102.61) → <dev-vm-ip>/<prod-vm-ip>;
  GRPN/Groupon → Acme/another-customer; prj-grp-… → prj-example-….
- scripts/switch-dev-vm.sh deleted — hackathon-era helper hardcoded to a
  specific shared dev VM. Per-developer dev VMs are the supported pattern.

Final grep `groupon|grpn|foundryai|prj-grp|groupondev|34\.77\.(94|102)\.…|kids-ai-data`
returns zero hits (excluding CHANGELOG.md historical entries).

CHANGELOG entry expanded to document both waves under one bullet, with
the BREAKING (ops) clarification about the TF module being unaffected.

Refs review of #94, closes #88.

* fix(oss): close remaining #94 review-2 findings (Czech, padak refs, CHANGELOG)

Reviewer of PR #94 round 2 caught 4 remaining items the wave-2 pass missed:

1. infra/modules/customer-instance/variables.tf had Czech descriptions on
   8 more variables. Previous review only flagged line 19; this round
   audited the rest. Translated lines 2, 28, 42-46 (heredoc), 60, 65, 71,
   78, 84 to English. Same review concern: a Terraform module that is
   the customer-facing API surface in Czech is unfit for OSS distribution.

2. infra/modules/customer-instance/outputs.tf had Czech descriptions on
   four outputs. Same fix.

3. docs/padak-security.md referenced a private repo (padak/keboola_agent_cli#206)
   in two places. Replaced with generic 'tracked upstream in the auth-CLI repo'
   per CLAUDE.md vendor-agnostic rule (no cross-refs to private repos).

4. scripts/fetch-env-from-secrets.sh:41 had a Czech comment.
   Translated.

5. CHANGELOG cosmetic: bullet said 'AIAgent.FoundryAI -> AIAgent.MyAgent'
   but the actual code uses both MyAgent (in docstrings) and Example
   (in test fixtures). Reworded to mention both targets.

Final grep across all shipping file types (.md, .py, .yml, .yaml, .sh,
Makefile, .json, .tf, .tpl, Caddyfile, .toml) for groupon|grpn|foundryai|
prj-grp|groupondev|34.77.94.14|34.77.102.61|kids-ai-data|padak/keboola_agent_cli
returns ZERO hits (excluding CHANGELOG.md). Czech-diacritic grep across
.tf/.toml/Caddyfile/Makefile/.yml returns ZERO hits.

157/157 OpenMetadata + DuckDB tests still pass.

* fix(oss): close #94 round-3 leaks (env.template, instance.yaml.example, padak typo)

Round-3 reviewer caught two MUST-FIX leaks the round-2 grep missed
(grep was scoped to extensions that did not include .template / .example
suffixes — the audit was right, the previous grep was not paranoid enough):

1. config/instance.yaml.example:114 — '(optional - Groupon-specific)' brand
   leak in a shipping config example. Replaced with '(optional)'.

2. config/.env.template:68 — stale path 'scripts/grpn/agnes-tls-rotate.sh'
   in operator-facing env-template comment. The script lives at
   scripts/ops/ now (commit 16a85cc); this comment had been pointing
   operators at a non-existent path.

3. docs/padak-security.md:188 — phrase duplication 'tracked in tracked
   upstream' from a sloppy substitution in round-2. Trivial wording fix.

Final paranoid grep across .md/.py/.yml/.yaml/.sh/Makefile/.json/.tf/.tpl/
Caddyfile/.toml/.template/.example/.env* with the full token set
(groupon|grpn|foundryai|prj-grp|groupondev|34\.77\.94\.14|34\.77\.102\.61|
kids-ai-data|padak/keboola_agent_cli) returns ZERO hits, excluding
CHANGELOG.md historical entries.

* fix(oss): #94 round-4 — QUICKSTART.md + rename padak-security.md

Devin Review caught two findings on the latest round-3 commit:

1. docs/QUICKSTART.md:67 still pointed users at the deleted
   scripts/switch-dev-vm.sh. A Quickstart user following step-by-step
   would hit a missing-file error at the final step. Replaced with the
   inline gcloud-ssh equivalent that the Removed bullet documents.

2. docs/padak-security.md filename retains the personal identifier
   'padak'. The PR fixed the body content (replaced
   padak/keboola_agent_cli#206 references with generic wording) but
   missed the filename. Renamed to docs/security-audit-2026-04.md
   (date-anchored, vendor-neutral). Updated the historical CHANGELOG
   link to point at the new path with an inline note about the rename.

* fix(oss): redact remaining hardcoded IPs from planning docs + remove default email

Devin Review caught two more leaks:
1. scripts/fetch-env-from-secrets.sh line 16 had a hardcoded
   personal-email default (zdenek.srotyr@keboola.com). Replaced with
   ':?' bash error so SEED_ADMIN_EMAIL must be explicitly set —
   safer than carrying any specific identity.
2. Planning docs still had 35.195.96.98 and 34.62.223.189 (legacy
   prod/dev IPs) that the round-1 IP-replace pattern missed (it only
   targeted 34.77.x.x). Generic regex redaction across all five
   planning docs replaces every public IP with <redacted-ip>,
   preserving private/loopback/IAP ranges.
2026-04-27 20:24:34 +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 (the same OAuth client your Agnes
deployment 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())