agnes-the-ai-analyst/app/auth/role_resolver.py
Petr Simecek 83ced81966
feat(auth): unified role management — UI + REST API + CLI + schema v9 (v0.11.4) (#73)
* feat(auth): v9 schema — unified role management foundation (WIP)

Tasks 1-5, 10 of the role-management-complete plan. Foundation only,
follow-up commits add REST API, CLI, UI, and tests.

Schema v9:
- user_role_grants table: direct user → internal_role mapping
  (complementary to group_mappings). Drives PAT/headless auth and
  persists across sessions. Source field tracks 'direct' vs auto-seed.
- internal_roles.implies (JSON): transitive role hierarchy. core.admin
  implies core.km_admin → core.analyst → core.viewer. Resolver does BFS
  expand at lookup time.
- internal_roles.is_core (BOOL): distinguishes seeded core.* hierarchy
  from module-registered roles. UI renders them differently.
- v8→v9 migration: ADD COLUMN, CREATE TABLE, _seed_core_roles +
  _backfill_users_role_to_grants, then NULL legacy users.role values.
  DuckDB FK constraint blocks DROP COLUMN — sloupec zůstává jako
  deprecated artifact (UserRepository ignoruje), fyzický drop deferred.

Resolver:
- Regex extended to allow dotted namespace (core.admin,
  context_engineering.admin), max 64 chars total.
- expand_implies(role_keys, conn): BFS over implies JSON column.
- resolve_internal_roles signature gains optional user_id parameter;
  unions group-mapping resolution with user_role_grants direct grants
  before implies expansion.

require_internal_role:
- Two-path resolution: session cache (OAuth) → DB grants (PAT/headless
  fallback). PAT clients now legitimately satisfy gates without the
  OAuth round-trip, fixing the v8 limitation where every PAT-callable
  admin endpoint needed require_role(Role.ADMIN) instead of
  require_internal_role(...).

Backward-compat:
- require_role(Role.X) and require_admin become thin wrappers over
  require_internal_role(f"core.{role}"). Implies hierarchy preserves the
  legacy "at least this level" semantics automatically — no per-level
  comparison code needed.
- src/rbac.py helpers (is_admin, has_role, get_user_role,
  set_user_role, can_access_table, get_accessible_tables) all read from
  the resolver via _get_internal_role_keys.
- UserRepository.create() and update() now mirror role changes into
  user_role_grants via _grant_core_role helper. Preserves API while
  making the new table the source of truth.
- UserRepository.delete() pre-deletes user_role_grants rows
  (FK cascade — DuckDB doesn't auto-cascade).
- count_admins() reads user_role_grants ⨝ internal_roles instead of the
  now-NULL users.role column.

First consumer:
- app/api/admin.py module-level docstring documents the v9 pattern for
  future module authors. Existing require_role(Role.ADMIN) callsites
  flow through the wrapper; no behavior change for OAuth callers, and
  PAT callers gain access via direct grants.

Tests: full suite green (1396 passed, 6 skipped). Existing tests
exercise the new pathway transparently because UserRepository.create
auto-grants. New test_pat_caller_with_direct_grant_passes pins the
PAT-aware contract.

Schema: v9 (was v8). pyproject.toml + CHANGELOG bump deferred to the
final PR-prep commit.

* feat(auth): role management complete — REST API + CLI + UI + docs (v0.11.4)

Sjednocuje legacy users.role enum s v8 internal-roles foundation pod jeden
model s implies hierarchií, dodává admin UI + REST API + CLI pro správu
group mappings i přímých user grants, a dělá require_internal_role
PAT-aware tak, aby admin endpointy fungovaly uniformly napříč OAuth
i headless callery.

REST API (app/api/role_management.py, +496 LOC):
- 8 endpointů pod /api/admin: internal-roles list, group-mappings CRUD,
  users/{id}/role-grants CRUD, users/{id}/effective-roles debug.
- Všechny gated require_internal_role("core.admin"). Audit-log na každé
  mutaci (role_mapping.created/deleted, role_grant.created/deleted).
- Last-admin protection: refuse to delete the final core.admin grant
  (mirrors users.py:count_admins protection).
- Nový UserRoleGrantsRepository v src/repositories/user_role_grants.py.

CLI (cli/commands/admin.py extension, +258 LOC):
- da admin role list / show <key>
- da admin mapping list / create <group-id> <role-key> / delete <id>
- da admin grant-role <email> <role-key>
- da admin revoke-role <email> <role-key>
- da admin effective-roles <email>
- Všechno přes typer + PAT auth, --json flag, response-shape tolerantní.

UI (admin_role_mapping.html + admin_user_detail.html + nav + user list):
- Nová stránka /admin/role-mapping: internal_roles read-only table +
  group_mappings table with create/delete forms.
- Nová stránka /admin/users/{id}: core role single-select + capabilities
  multi-checkbox + effective-roles debug (direct + group + expanded).
- Existing user list dostává "Detail" link na novou stránku.
- Nav link na /admin/role-mapping.

Tests: +85 nových testů přes 4 nové soubory:
- test_schema_v9_migration.py (8) — fresh install + v8→v9 backfill +
  legacy column NULL semantics + unknown-role fallback + invariants.
- test_api_role_management.py (33) — všech 8 endpointů, happy + error
  paths, audit-log assertions, last-admin protection.
- test_cli_admin_role.py (25 + 1 conditional) — typer subcommands,
  text + json output, PAT integration smoke.
- test_admin_role_mapping_ui.py (9) + test_admin_user_capabilities_ui.py (10)
  — page rendering, auth gating, form contracts, JS hooks.
Full suite: 1482 passed, 6 skipped (was 1396 → +86, žádné regrese).

Docs:
- docs/internal-roles.md kompletní rewrite — odstranil "no UI yet",
  přidal hierarchy diagram, dual-path resolution, dotted-namespace
  convention, admin workflow přes UI/CLI/REST, refresh semantics
  for group mappings vs direct grants, migration notes.
- CLAUDE.md schema v8 → v9.
- CHANGELOG.md [0.11.4] s BREAKING marker pro users.role NULL
  semantics + complete Added/Changed/Removed/Internal sekce.
- pyproject.toml: 0.11.3 → 0.11.4.

Sequencing: po mergi tohoto PR Pabu rebasuje pabu/local-dev (PR #72)
na main, jeho schema migrations se posouvají z v9/v10/v11 na v10/v11/v12.

Implementation breakdown:
- Sequential (já): foundation tasks — schema v9, resolver, PAT-aware
  require_internal_role, backward-compat wrappers, rbac refactor,
  UserRepository auto-grant.
- Parallel sub-agents (3 worktrees, ~10 min): REST API, CLI, UI.
- Sequential (já): integrace, docs/CHANGELOG/version, schema tests,
  fullsuite verification.

* fix(auth): address Devin review on PR #73 — three regressions

Three concrete bugs caught in Devin's PR review, all fixed in this commit.

1. **users.role hydration on read** (the big one):
   v8→v9 migration NULLs users.role for every existing user, but a long
   tail of read sites still inspect user["role"] directly:
   - app/web/templates/_app_header.html:15 — admin nav gate
   - app/web/templates/_app_header.html:36-37 — role badge in dropdown
   - app/web/router.py:319-321 — UserInfo.is_admin/is_analyst/is_privileged
   - app/web/router.py:489 — corporate memory is_km_admin
   - app/api/catalog.py:54 — admin "see all tables" bypass
   - app/api/sync.py:215 — admin "see all sync states" bypass

   Without a fix, every existing admin loses the entire admin nav (and
   API admin bypasses) immediately after upgrade — a serious regression.

   Fix: new helper _hydrate_legacy_role() in app/auth/dependencies.py
   maps the highest-level core.* grant back into user["role"] as the
   legacy enum string. Called from get_current_user() on both auth paths
   (LOCAL_DEV_MODE + JWT/PAT). Idempotent — skips when role is already
   populated. Net effect: every pre-v9 callsite keeps working transparently
   for both OAuth and PAT callers, with one extra DB round-trip per
   authenticated request (same cost as the existing PAT-aware
   require_internal_role fallback).

   3 regression tests in tests/test_schema_v9_migration.py:
   - test_hydration_recovers_role_from_user_role_grants
   - test_hydration_returns_highest_grant (multi-grant → highest wins)
   - test_hydration_falls_back_to_viewer_when_no_grants (safe fallback)

2. **CLI effective-roles TypeError**:
   API returns direct/group as List[Dict] (RoleGrantResponse-shaped),
   but the CLI did ', '.join(direct) which raises TypeError on dicts.
   Tests masked it because mocks used bare string lists. Replaced
   raw .join() with a _names() helper that extracts role_key from
   each item, falling back to str() for legacy mock shapes.

3. **UI template field-name mismatch**:
   admin_user_detail.html JS reads data.groups but the API serializes
   the field as group (singular, per EffectiveRolesResponse pydantic).
   Currently benign because the API always returns group:[], but the
   field would silently disappear once the group-derived view is wired
   up. Added data.group as the primary lookup, kept the legacy aliases
   for shape-drift tolerance.

Full suite: 1485 passed (was 1482, +3 hydration tests), 6 skipped, no
regressions.

* fix(auth): Devin review #2 + UX self-service + RBAC docs rename

Three threads landed in one commit because they share the same
auth/role surface and CHANGELOG entry.

Devin review #73 second round (2 actionable findings):

- _hydrate_legacy_role no longer short-circuits on truthy users.role.
  The role-management endpoints (POST/DELETE /api/admin/users/{id}/
  role-grants + the changeCoreRole UI flow) only mutate
  user_role_grants — they don't update the legacy column. The early
  return trusted that stale value, so a user downgraded via the new
  REST/UI kept role="admin" in their dict on subsequent requests,
  which fooled _is_admin_user_dict (src/rbac.py) and the catalog/sync
  admin-bypass short-circuits into retaining elevated table access
  even though require_internal_role correctly denied the API gates.
  Always re-resolves now, making user_role_grants the single source
  of truth on every authenticated request. Cost: one DB round-trip
  per request — same as the existing PAT-aware fallback. Pinned by
  test_hydration_ignores_stale_legacy_role_after_grant_revoke.

- Dev-bypass (app/auth/dependencies.py) and OAuth callback
  (app/auth/providers/google.py) now pass user_id to
  resolve_internal_roles so direct grants land in
  session["internal_roles"] alongside group-mapped roles. Pre-fix,
  every admin-gated request fell through to the per-request DB
  fallback inside require_internal_role and the dev-bypass log line
  read "resolved 0 internal role(s)" for an obviously-admin user.
  test_session_internal_roles_populated updated to assert union.

User-visible UX (also addresses local-test feedback):

- HTTP 500 on /admin/users post-v8→v9 migration — UserResponse.role
  is required str, but legacy users.role was NULL-ed by the
  migration. _to_response in app/api/users.py now routes every dict
  through _hydrate_legacy_role; same fix lifts the silent no-op of
  last-admin protection in update_user/delete_user (the role-equality
  short-circuits would skip the count_admins guard for migrated
  admins). Three regression tests under TestAPIUsersPostMigration.

- /profile is now a real self-service detail page for *every*
  signed-in user (not just admins). Three new server-side sections:
  Effective roles (resolver output as chip cloud), Direct grants
  (rows in user_role_grants with source label), Roles via groups
  (which Cloud Identity / dev group grants which role for the
  current user). Non-admins finally see *why* a feature is or isn't
  accessible. Admins additionally see a deep-link to
  /admin/users/{id} for editing their own grants.

- /admin/role-mapping group-id picker. New "Known groups" panel
  above the create form: clickable chips for the calling admin's
  own session.google_groups (tagged "your group") merged with
  external_group_ids already used in existing mappings (tagged
  "already mapped"). Click a chip → fills the form. Empty-state
  copy points operators at LOCAL_DEV_GROUPS / Google sign-in
  instead of leaving them to guess Cloud Identity opaque IDs from
  memory.

Operational fixes:

- Scheduler log-noise: every cron tick produced a
  POST /auth/token 401 because the auto-fetch fallback called the
  endpoint with just an email (no password) and silently fell
  through. Removed the broken path entirely. Operators set
  SCHEDULER_API_TOKEN (long-lived PAT) in production; in
  LOCAL_DEV_MODE the dev-bypass auto-authenticates the un-tokenized
  request, so jobs continue to work.

Docs:

- docs/internal-roles.md → docs/RBAC.md (git mv preserves history).
  Standard industry term, more discoverable for engineers grepping
  for RBAC in a new repo. Restructured: Quickstart-by-role
  (operator / end-user / module author), step-by-step
  Module-author workflow with code examples (register key, gate
  endpoint, declare implies, write contract test), naming pitfalls,
  refresh semantics. CLAUDE.md gets a new
  "Extensibility → RBAC" section pointing contributors at the doc
  before they add gated endpoints. Cross-refs in app/api/admin.py
  + tests/test_role_resolver.py updated.

Tests: 293 in the auth/role/scheduler/UI test set passed, 0 regressions.

* fix(auth): Devin review #3 — login flows + RBAC docs

Two new findings on commit 7d1c048, both real and addressed.

Finding 1 (BUG, HTTP 500): every auth login flow loaded users via
UserRepository.get_by_email and passed user["role"] straight to
create_access_token, Pydantic response models, and _set_login_cookie
without going through _hydrate_legacy_role. Post-v9 the legacy column
is NULL for migrated users, and TokenResponse.role is a required str —
so POST /auth/token raised ValidationError → HTTP 500 for any v8-admin
trying to log in via password. Same root cause produced non-crashing
but semantically wrong JWTs (role: null) from Google OAuth, password
web flows, and email magic-link verification.

Fix: hydrate inline in every login flow before reading user["role"]:
- app/auth/router.py — POST /auth/token (the crash site)
- app/auth/providers/google.py — OAuth callback (was just stale JWT)
- app/auth/providers/password.py — 5 flows: JSON login, web login,
  JSON setup, web reset confirm, web setup confirm
- app/auth/providers/email.py — centralized in _consume_token,
  covers both /verify endpoints

New regression class TestAuthLoginFlowsPostMigration pins both the
no-crash and the correct-role contracts for all four legacy levels
(viewer/analyst/km_admin/admin) on POST /auth/token.

Finding 2 (DOCS): docs/RBAC.md showed register_internal_role() being
called with implies=[...], but the function signature is (key, *,
display_name, description, owner_module). A module author copying the
example would TypeError at import time. The implies field on
internal_roles IS honored at runtime by expand_implies, but the
registry-side write path (register_internal_role + InternalRoleSpec +
sync_registered_roles_to_db) doesn't exist yet — implies is currently
seeded only for the core.* hierarchy via _seed_core_roles in src/db.py.

Rewrote the Implies hierarchy and Module-author workflow sections to
document what's actually supported in 0.11.4 and what a future change
would need to add. The "for cross-module hierarchies, register each
level + grant both" pattern works today.

Tests: 322 in the auth/role/scheduler/UI/password test set passed,
0 regressions.

* fix(db): _seed_core_roles actually runs on every connect (Devin review #4)

Devin flagged that the docstring on `_seed_core_roles` promised per-connect
execution as a safety net for accidental DELETEs and in-code seed changes,
but the only call sites lived inside `if current < SCHEMA_VERSION:` — so
once a DB was on v9 the function never ran again, and the docstring lied.

Picked option (b) from the review (actually call it on every startup) over
option (a) (fix the docstring) because the safety net is genuinely useful:
- recovery from accidental admin DELETE on internal_roles,
- in-code _CORE_ROLES_SEED tweaks (display_name/description/implies)
  ship without a manual SQL deploy,
- fresh installs and migrations stop needing their own seed call sites.

Tail call gated by `get_schema_version(conn) <= SCHEMA_VERSION` so the
future-version-is-noop rollback contract still holds — a v9 binary won't
touch a DB that's been upgraded past v9.

Test coverage: new TestSeedCoreRolesSafetyNet class (3 tests) pins the
three contracts — deleted row re-seeds, mutated display_name re-syncs
from in-code seed, applied_at on schema_version doesn't churn on
already-current DBs. Existing TestMigrationSafety::test_future_version_is_noop
still passes (verified against the gating logic).
2026-04-27 02:23:01 +02:00

325 lines
12 KiB
Python

"""Internal-role registry, resolver, and FastAPI dependency factory.
## Lifecycle
1. **Module import** — each Agnes module declares its internal roles via
``register_internal_role(...)``. The registry is module-level state, so
the registration happens once per process.
2. **App startup** — ``sync_registered_roles_to_db(conn)`` inserts any
newly-registered keys into ``internal_roles`` and refreshes the metadata
(display_name, description, owner_module) on existing rows. Idempotent.
3. **Sign-in** — ``resolve_internal_roles(external_groups, conn)`` joins
``session.google_groups`` against ``group_mappings`` and writes the
resulting role-key list into ``session["internal_roles"]``.
4. **Request handling** — ``require_internal_role("context_admin")`` reads
the cached list off the session; no DB hit per request.
## Refresh semantics
Resolution happens at sign-in, so a user with a stale session keeps stale
roles after an admin changes a mapping. ``Logout → sign in again`` is the
only refresh path today — the same semantics as Google's group cache and
the existing ``session.google_groups`` flow.
"""
from __future__ import annotations
import json as _json
import logging
import os
import re
import uuid
from dataclasses import dataclass
from typing import Optional
import duckdb
from fastapi import Depends, HTTPException, Request, status
from app.auth.dependencies import get_current_user
from src.repositories.group_mappings import GroupMappingsRepository
from src.repositories.internal_roles import InternalRolesRepository
logger = logging.getLogger(__name__)
# v9: dot-separated namespace convention (e.g. "core.admin",
# "context_engineering.admin"). The owner_module column is expected to match
# the prefix before the first dot; module-author validation lives in
# register_internal_role. Total length capped at 64 to keep the column
# bounded and to fit comfortably in audit-log resource strings.
_ROLE_KEY_RE = re.compile(r"^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$")
_ROLE_KEY_MAX_LEN = 64
@dataclass(frozen=True)
class InternalRoleSpec:
"""Module-side declaration of an internal role.
Mirrors the persisted shape minus ``id`` (assigned at sync time) and
timestamps. Frozen so a stray mutation can't desync registry from DB.
"""
key: str
display_name: str
description: str = ""
owner_module: Optional[str] = None
# Module-level registry. Populated by register_internal_role() at import time;
# drained by sync_registered_roles_to_db() at app startup. Kept module-level
# (not class-state) because role registration is conceptually per-process.
_REGISTRY: dict[str, InternalRoleSpec] = {}
def register_internal_role(
key: str,
*,
display_name: str,
description: str = "",
owner_module: Optional[str] = None,
) -> None:
"""Declare an internal role at module-import time.
``key`` is the immutable identifier referenced from code (e.g.
``"context_admin"``); must match ``[a-z][a-z0-9_]{0,63}``. Calling twice
with the same key + same fields is a no-op (re-import safe). Calling
twice with conflicting fields raises ``ValueError`` — that almost always
means two modules picked the same key, which would leave admins unable
to tell which capability they're granting in the mapping UI.
"""
if len(key) > _ROLE_KEY_MAX_LEN or not _ROLE_KEY_RE.match(key):
raise ValueError(
f"Invalid internal role key {key!r}: must be lower_snake_case "
f"with optional dot-separated namespace (e.g. 'core.admin' or "
f"'context_engineering.admin'), max {_ROLE_KEY_MAX_LEN} chars."
)
spec = InternalRoleSpec(
key=key,
display_name=display_name,
description=description,
owner_module=owner_module,
)
existing = _REGISTRY.get(key)
if existing is not None and existing != spec:
raise ValueError(
f"Internal role {key!r} already registered with different fields "
f"(existing={existing}, new={spec}). Pick a unique key."
)
_REGISTRY[key] = spec
def list_registered_roles() -> list[InternalRoleSpec]:
"""Snapshot of the current registry — sorted by key for stable output."""
return sorted(_REGISTRY.values(), key=lambda s: s.key)
def _clear_registry_for_tests() -> None:
"""Reset the module-level registry. Tests only — never call from app code.
Refuses to run unless ``TESTING=1`` so a stray import-path in production
can't accidentally drop the registered capabilities. Pytest sets this
via conftest / pytest.ini; production never does.
"""
if os.environ.get("TESTING", "").lower() not in ("1", "true"):
raise RuntimeError(
"_clear_registry_for_tests() called outside of TESTING — "
"this drops every registered internal role and is never safe "
"in app code. Set TESTING=1 if you really mean this.",
)
_REGISTRY.clear()
def sync_registered_roles_to_db(conn: duckdb.DuckDBPyConnection) -> None:
"""Reconcile registered roles into ``internal_roles``. Idempotent.
Inserts new keys, updates display_name/description/owner_module for
existing keys when they've changed. Never deletes — a role disappearing
from code may just mean the module was unloaded; the DB row keeps the
mappings safe until an admin explicitly removes it.
"""
repo = InternalRolesRepository(conn)
inserted = 0
updated = 0
for spec in _REGISTRY.values():
existing = repo.get_by_key(spec.key)
if existing is None:
repo.create(
id=str(uuid.uuid4()),
key=spec.key,
display_name=spec.display_name,
description=spec.description,
owner_module=spec.owner_module,
)
inserted += 1
else:
drift = (
existing.get("display_name") != spec.display_name
or (existing.get("description") or "") != spec.description
or (existing.get("owner_module") or None) != spec.owner_module
)
if drift:
repo.update(
id=existing["id"],
display_name=spec.display_name,
description=spec.description,
owner_module=spec.owner_module,
)
updated += 1
if inserted or updated:
logger.info(
"internal_roles sync: %d inserted, %d updated, %d total registered",
inserted, updated, len(_REGISTRY),
)
def expand_implies(
role_keys: list[str], conn: duckdb.DuckDBPyConnection,
) -> list[str]:
"""Transitively expand a role-key list along the ``implies`` JSON column.
Example: input ``["core.admin"]`` returns
``["core.admin", "core.km_admin", "core.analyst", "core.viewer"]`` because
``core.admin.implies = ["core.km_admin"]``, ``core.km_admin.implies =
["core.analyst"]``, etc. BFS — visits each role at most once even if the
graph contains a (mis-configured) cycle. Output is sorted + deduped.
Reads the entire ``internal_roles`` row set in a single query and walks
the graph in Python; for the expected scale (single-digit core.* + tens
of module roles) this is cheaper than recursive CTE round-trips and
keeps the JSON-as-text decode local. If the table grows past hundreds of
rows, switch to a recursive CTE in DuckDB.
"""
if not role_keys:
return []
rows = conn.execute(
"SELECT key, implies FROM internal_roles"
).fetchall()
implies_map: dict[str, list[str]] = {}
for key, implies_json in rows:
try:
implies_map[key] = list(_json.loads(implies_json or "[]"))
except (TypeError, ValueError):
implies_map[key] = []
seen: set[str] = set()
queue: list[str] = list(role_keys)
while queue:
current = queue.pop(0)
if current in seen:
continue
seen.add(current)
for implied in implies_map.get(current, []):
if implied not in seen:
queue.append(implied)
return sorted(seen)
def resolve_internal_roles(
external_groups: list[dict],
conn: duckdb.DuckDBPyConnection,
user_id: Optional[str] = None,
) -> list[str]:
"""Resolve a user's internal role keys from both auth paths.
Two complementary sources are unioned, then expanded along the implies
hierarchy:
- **External groups** — Cloud Identity / mocked dev groups joined against
``group_mappings``. Drives the OAuth-callback session cache.
- **Direct user grants** (``user_id`` supplied) — rows in
``user_role_grants``. Persists across sessions and works for PAT /
headless callers, where the session cache is unreachable.
Pure read — never mutates state. Returns a sorted, de-duplicated list of
role keys. Empty list when neither source produces any membership.
Callers in the OAuth callback pass ``external_groups`` only; PAT-aware
callers (``require_internal_role``) pass ``user_id`` only; the two paths
share the implies expansion so a user holding ``core.admin`` directly
sees the same expanded set as one resolved through a Cloud Identity
group mapping.
"""
keys: set[str] = set()
ids = [g["id"] for g in external_groups if isinstance(g, dict) and g.get("id")]
if ids:
keys.update(GroupMappingsRepository(conn).resolve_role_keys(ids))
if user_id:
rows = conn.execute(
"""SELECT r.key
FROM user_role_grants g
JOIN internal_roles r ON g.internal_role_id = r.id
WHERE g.user_id = ?""",
[user_id],
).fetchall()
keys.update(row[0] for row in rows)
if not keys:
return []
return expand_implies(sorted(keys), conn)
def require_internal_role(role_key: str):
"""FastAPI dependency factory: 403 unless the user holds ``role_key``.
Two-path resolution (v9):
1. **Session cache** (OAuth flow) — reads ``session["internal_roles"]``
populated by ``resolve_internal_roles`` at sign-in. No DB hit; the
fast path for browser users.
2. **Direct grants fallback** (PAT/headless flow) — when the session
doesn't carry the role (or no session exists), looks up
``user_role_grants`` for the authenticated user, expands implies,
and re-checks. One DB query per gated request — acceptable cost for
headless callers that lack the session cache by design.
The two-path design lets PAT clients hit endpoints gated by
``require_internal_role("core.admin")`` without surrendering session
semantics: an admin user holding ``core.admin`` via either a direct
grant or a Cloud Identity group mapping will succeed regardless of
whether they came in via OAuth cookie or Authorization: Bearer.
The ``user`` dependency runs first so we still 401 unauthenticated
requests with the standard message before checking role membership.
"""
async def _check(
request: Request,
user: dict = Depends(get_current_user),
) -> dict:
# Path 1: session cache — present for OAuth callers, absent for PAT.
roles: list[str] = []
if hasattr(request, "session"):
roles = request.session.get("internal_roles") or []
if role_key in roles:
return user
# Path 2: DB-backed direct grants. Only consulted when the session
# cache didn't grant access — typical for PAT/headless callers, but
# also a safety net for OAuth callers whose session was populated
# before the admin granted them the role (no need to log out + back
# in for direct grants to take effect, unlike group_mappings which
# are still cached on the session).
try:
from src.db import get_system_db
conn = get_system_db()
try:
granted = resolve_internal_roles(
[], conn, user_id=user.get("id"),
)
finally:
conn.close()
except Exception as e:
logger.warning(
"require_internal_role: DB grant lookup failed for %s/%s: %s",
user.get("email", "<unknown>"), role_key, e,
)
granted = []
if role_key in granted:
return user
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Requires internal role '{role_key}'",
)
return _check