agnes-the-ai-analyst/cli/commands/auth.py
minasarustamyan d4ac84dd46
feat(rbac): drop dataset_permissions + users.role + is_public; v19 migration (#150)
* feat(rbac): drop dataset_permissions + access_requests + users.role + is_public; v19 migration

BREAKING. Sjednocení datové RBAC vrstvy do per-group resource_grants modelu.
Před PR byla legacy data RBAC vrstva (dataset_permissions + is_public bypass)
de-facto neaktivní — is_public neměl API/UI/CLI surface, default true znamenal
že can_access_table vždycky bypassl. Dnes každý non-admin přístup vyžaduje
explicitní resource_grants(group, "table", id) řádek.

Schema v18 → v19 (src/db.py:_v18_to_v19_finalize):
- DROP TABLE dataset_permissions, access_requests
- DROP COLUMN users.role (NULL artifact since v13)
- DROP COLUMN table_registry.is_public
- Drops přes table-rebuild idiom (rename → create new → INSERT … SELECT
  → drop old) kvůli DuckDB ALTER DROP COLUMN limitacím na tabulkách
  s historic FK constraints. INSERT picks intersection sloupců, takže
  test fixtures s minimal pre-v19 schemou migrate cleanly.

Runtime:
- src/rbac.py:can_access_table → deleguje na app.auth.access.can_access
- DatasetPermissionRepository, AccessRequestRepository smazány
- AGNES_ENABLE_TABLE_GRANTS env-gate v app/resource_types.py odstraněn
  (TABLE je unconditionally enabled)

API drop:
- app/api/permissions.py, app/api/access_requests.py celé soubory
- /admin/permissions web route + admin_permissions.html
- "Request Access" modal v catalog.html + locked-row UI
- ~10 if user.get("role") != "admin" checků nahrazeno (admin shortcut
  je uvnitř can_access_table)
- /api/settings: drop permissions field z GET; PUT /api/settings/dataset
  gate přepnut na can_access(user_id, "table", dataset, conn)

Auth:
- app/auth/jwt.py:create_access_token: drop role parametr (claim zmizí
  z nově vydávaných JWT; staré tokeny zůstávají valid, claim ignored)
- app/api/users.py: drop role z CreateUserRequest / UpdateUserRequest
  (admin promotion = explicit add to Admin group via memberships API)
- src/repositories/users.py: drop role z create() / update()

CLI:
- da admin set-role smazán → hard-fail s replacement command
- da admin add-user --role flag pryč
- da auth import-token --role flag pryč
- da auth whoami: drop "Role:" výpis
- cli/config.py:save_token: role parametr now optional, no longer written
  (back-compat se starými token.json soubory zachována — pole se ignoruje)

Tests:
- DELETE: test_permissions.py, test_permissions_api.py, test_access_requests_api.py
- REWRITE: test_access_control.py (resource_grants flow), test_rbac.py
  (can_access_table over resource_grants), test_journey_rbac.py
  (drop access-request flow), test_resource_types.py (drop env-gate
  tests, drop is_public from helpers), test_v2_*.py (drop role-based
  user dicts in favor of id-based + Admin group membership),
  test_settings_api.py (no permissions field, can_access gate)
- TRIVIAL: ~30 souborů — drop role="admin" arg z UserRepository.create
  a 3rd positional role z create_access_token
- NEW: test_v18_to_v19 migration test (test_db.py),
  test_can_access_table_no_implicit_public (test_rbac.py),
  test_admin_set_role_returns_hardfail (test_cli_admin.py)
- OpenAPI snapshot regenerated

Docs:
- CHANGELOG: BREAKING entry pod [Unreleased]
- CLAUDE.md: schema v18 → v19
- docs/architecture.md: schema table + RBAC sekce přepsána
- docs/auth-google-oauth.md: admin promotion přes da admin break-glass
- cli/skills/security.md: kompletně přepsáno na group-based model
- docs/TODO-rbac-data-enforcement.md: smazáno (TODO splněn)

Test results: 2363 passed, 19 failed. Zbývající failures jsou pre-existing
Windows-specific issues (fcntl, charset) nesouvisející s tímto PR —
ověřeno git stash pop.

Plan: ~/.claude/plans/floofy-coalescing-parnas.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(release): cut 0.27.0

---------

Co-authored-by: Minas Arustamyan <arustamyan.minas@gmail.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: ZdenekSrotyr <zdenek.srotyr@keboola.com>
2026-04-30 22:02:16 +02:00

201 lines
6.8 KiB
Python

"""Auth commands — da login, da logout, da whoami, da auth import-token."""
import httpx
import typer
from cli.client import api_post, api_get
from cli.config import (
save_token,
clear_token,
get_token,
get_server_url,
save_config,
load_config,
)
auth_app = typer.Typer(help="Authentication commands")
@auth_app.command()
def login(
email: str = typer.Option(..., prompt=True, help="Your email address"),
password: str = typer.Option(
"", prompt="Password (leave empty for magic-link / OAuth accounts)",
hide_input=True, help="Your password (if the account has one)",
),
server: str = typer.Option(None, help="Server URL override"),
):
"""Login and obtain a JWT token.
Password-enabled accounts: enter the password when prompted.
Magic-link / OAuth accounts: leave the password empty — the server will
respond with guidance pointing you to the correct auth provider.
"""
if server:
import os
os.environ["DA_SERVER"] = server
body = {"email": email}
if password:
body["password"] = password
try:
resp = api_post("/auth/token", json=body)
if resp.status_code == 200:
data = resp.json()
save_token(data["access_token"], data["email"])
typer.echo(f"Logged in as {data['email']}")
return
# Helpful error for accounts that cannot login via password.
try:
detail = resp.json().get("detail", resp.text)
except Exception:
detail = resp.text
if resp.status_code == 401 and "external authentication" in str(detail).lower():
typer.echo(
"This account uses a magic link / OAuth provider. "
"Sign in via the web UI, open /tokens, and create a personal "
"access token — then export it as DA_TOKEN.",
err=True,
)
else:
typer.echo(f"Login failed: {detail}", err=True)
raise typer.Exit(1)
except typer.Exit:
raise
except Exception as e:
typer.echo(f"Connection error: {e}", err=True)
raise typer.Exit(1)
@auth_app.command()
def logout():
"""Clear stored token."""
clear_token()
typer.echo("Logged out.")
@auth_app.command()
def whoami():
"""Show current user info."""
token = get_token()
if not token:
typer.echo("Not logged in. Run: da login")
raise typer.Exit(1)
import jwt
try:
payload = jwt.decode(token, options={"verify_signature": False})
typer.echo(f"Email: {payload.get('email', 'unknown')}")
typer.echo(f"Server: {get_server_url()}")
except Exception:
typer.echo("Invalid token. Run: da login")
raise typer.Exit(1)
@auth_app.command("import-token")
def import_token(
token: str = typer.Option(..., "--token", help="JWT / Personal Access Token to import"),
server: str = typer.Option(
None,
"--server",
help="Server URL (defaults to ~/.config/da/config.yaml or $DA_SERVER)",
),
email: str = typer.Option(
None,
"--email",
help="Override email (used only if the JWT lacks an 'email' claim)",
),
skip_verify: bool = typer.Option(
False,
"--skip-verify",
help="Skip the server-side verification step (offline import)",
),
):
"""Import a personal access token non-interactively.
Decodes the JWT locally to extract the email claim, verifies it
against the server, and writes it to ~/.config/da/token.json using the
canonical format so subsequent `da auth whoami` / `da sync` calls
authenticate cleanly.
Example:
da auth import-token --token "$AGNES_PAT"
da auth import-token --token "$AGNES_PAT" --server https://agnes.example.com
"""
import os
import jwt as pyjwt
# 1) Seed server URL so the verify call below uses the right base URL.
if server:
save_config({"server": server})
os.environ["DA_SERVER"] = server
else:
cfg = load_config()
if not os.environ.get("DA_SERVER") and not cfg.get("server"):
typer.echo(
"No server configured. Pass --server https://<host> or set "
"DA_SERVER, or seed ~/.config/da/config.yaml first.",
err=True,
)
raise typer.Exit(1)
# 2) Decode JWT without signature verification — we only need the claims.
resolved_email = email
try:
payload = pyjwt.decode(token, options={"verify_signature": False})
resolved_email = resolved_email or payload.get("email")
except Exception as e:
typer.echo(f"Could not decode token as JWT: {e}", err=True)
raise typer.Exit(1)
# 3) Server-side verification. The server has no dedicated /auth/me — we
# use /api/catalog/tables which is the lightest endpoint that every
# authenticated user can call and also exercises the PAT validation
# path (revocation, expiry, token_hash match).
verify_url = get_server_url()
if not skip_verify:
headers = {"Authorization": f"Bearer {token}"}
try:
with httpx.Client(base_url=verify_url, headers=headers, timeout=15.0) as client:
resp = client.get("/api/catalog/tables")
except Exception as e:
typer.echo(f"Could not reach server {verify_url}: {e}", err=True)
raise typer.Exit(1)
if resp.status_code == 401:
detail = "unauthorized"
try:
detail = resp.json().get("detail", detail)
except Exception:
pass
typer.echo(f"Token rejected by server ({verify_url}): {detail}", err=True)
raise typer.Exit(1)
if resp.status_code >= 500:
typer.echo(
f"Server error from {verify_url} during verification "
f"(HTTP {resp.status_code}). Re-run with --skip-verify to bypass.",
err=True,
)
raise typer.Exit(1)
# 4) Fallback claim lookup via a response the server might include.
# /api/catalog/tables doesn't return user info, but other JWT
# issuers might later gain an /auth/me. For now, we rely on JWT
# claims + the CLI overrides.
# 5) Refuse to write a partial record if the email claim is missing.
if not resolved_email:
typer.echo(
"Token is missing the 'email' claim. Re-issue the token "
"or pass --email explicitly.",
err=True,
)
raise typer.Exit(1)
# 6) Persist in the canonical on-disk format used by cli/config.py.
save_token(token, resolved_email)
typer.echo(f"Imported token for {resolved_email}.")
from cli.commands.tokens import token_app
auth_app.add_typer(token_app, name="token")