agnes-the-ai-analyst/tests/test_v2_catalog.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

135 lines
5.2 KiB
Python

import importlib
import pytest
@pytest.fixture
def reload_db(tmp_path, monkeypatch):
monkeypatch.setenv("DATA_DIR", str(tmp_path))
import src.db as db_module
importlib.reload(db_module)
yield db_module
def _seed_two_tables(conn):
from src.repositories.table_registry import TableRegistryRepository
repo = TableRegistryRepository(conn)
repo.register(
id="orders", name="orders", source_type="keboola",
bucket="sales", source_table="orders", query_mode="local",
)
repo.register(
id="bq_view", name="bq_view", source_type="bigquery",
bucket="ds", source_table="bq_view", query_mode="remote",
)
def _make_admin(conn) -> dict:
"""Create an admin user + grant Admin-group membership; return user dict."""
import uuid
from src.db import SYSTEM_ADMIN_GROUP
from src.repositories.user_group_members import UserGroupMembersRepository
from src.repositories.users import UserRepository
uid = "u-" + uuid.uuid4().hex[:8]
UserRepository(conn).create(id=uid, email=f"{uid}@x.com", name="A")
admin_gid = conn.execute(
"SELECT id FROM user_groups WHERE name = ?", [SYSTEM_ADMIN_GROUP]
).fetchone()[0]
UserGroupMembersRepository(conn).add_member(uid, admin_gid, source="system_seed")
return {"id": uid, "email": f"{uid}@x.com"}
class TestCatalogShape:
def test_admin_sees_both_tables(self, reload_db):
from app.api.v2_catalog import build_catalog
conn = reload_db.get_system_db()
try:
_seed_two_tables(conn)
admin = _make_admin(conn)
data = build_catalog(conn, admin)
ids = {t["id"] for t in data["tables"]}
assert {"orders", "bq_view"} <= ids
finally:
conn.close()
def test_local_table_has_duckdb_flavor(self, reload_db):
from app.api.v2_catalog import build_catalog
conn = reload_db.get_system_db()
try:
_seed_two_tables(conn)
admin = _make_admin(conn)
data = build_catalog(conn, admin)
row = next(t for t in data["tables"] if t["id"] == "orders")
assert row["sql_flavor"] == "duckdb"
assert row["query_mode"] == "local"
finally:
conn.close()
def test_bq_table_has_bigquery_flavor(self, reload_db):
from app.api.v2_catalog import build_catalog
conn = reload_db.get_system_db()
try:
_seed_two_tables(conn)
admin = _make_admin(conn)
data = build_catalog(conn, admin)
row = next(t for t in data["tables"] if t["id"] == "bq_view")
assert row["sql_flavor"] == "bigquery"
assert row["query_mode"] == "remote"
assert "where_examples" in row
assert "fetch_via" in row
finally:
conn.close()
class TestCatalogCacheRbac:
"""Regression: the per-user payload cache used to leave revoked users
seeing tables for up to TTL. Cache the underlying rows globally; enforce
RBAC fresh per request. Same pattern as v2_schema.py / v2_sample.py."""
def test_rbac_decision_is_fresh_per_call_not_cached(self, reload_db, monkeypatch):
from app.api import v2_catalog
conn = reload_db.get_system_db()
try:
_seed_two_tables(conn)
# Use a real (non-admin) user id; the stub can_access_table below
# decides what they actually see, but build_catalog still needs a
# real id for the is_user_admin lookup it does internally.
import uuid
from src.repositories.users import UserRepository
uid = "u-" + uuid.uuid4().hex[:8]
UserRepository(conn).create(id=uid, email=f"{uid}@x.com", name="A")
user = {"id": uid, "email": f"{uid}@x.com"}
# First call: a fake can_access_table that grants both tables.
calls = []
def grant_all(_user, table_id, _conn):
calls.append(("grant", table_id))
return True
monkeypatch.setattr(v2_catalog, "can_access_table", grant_all)
data1 = v2_catalog.build_catalog(conn, user)
ids1 = {t["id"] for t in data1["tables"]}
assert {"orders", "bq_view"} <= ids1
# Second call (cache HIT on raw rows): can_access_table now denies
# `orders`. The user must NOT see it any more — RBAC re-evaluates.
def deny_orders(_user, table_id, _conn):
calls.append(("eval", table_id))
return table_id != "orders"
monkeypatch.setattr(v2_catalog, "can_access_table", deny_orders)
data2 = v2_catalog.build_catalog(conn, user)
ids2 = {t["id"] for t in data2["tables"]}
assert "orders" not in ids2, \
f"revoked table 'orders' still visible — cache leaked stale RBAC: {ids2}"
assert "bq_view" in ids2
# And RBAC ran on the second call (the eval calls are present).
assert any(kind == "eval" for kind, _ in calls), \
"RBAC was not re-evaluated on cached call"
finally:
conn.close()
v2_catalog._table_rows_cache.clear() if hasattr(
v2_catalog._table_rows_cache, "clear"
) else None