agnes-the-ai-analyst/app/marketplace_server/router.py
Vojtech Rysanek 7147bac079 feat(rbac+marketplace): schema v14 FK + AGNES_ENABLE_TABLE_GRANTS + break-glass CLI
Follow-up to the RBAC v13 + marketplace work in the parent commit. Addresses
deferred Devin findings, gemini-flagged blockers, and adds three guard rails.

== Schema v14 — FK constraints on user_group_members + resource_grants ==
Adds DuckDB foreign-key constraints so cascade deletes can no longer leave
orphaned member / grant rows pointing at a deleted group_id (which were
relying on application-level cascades up to v13). Migration is RENAME →
CREATE-with-FK → INSERT → DROP, wrapped in BEGIN TRANSACTION so a partial
failure rolls back without leaving the DB at a half-applied schema.

== AGNES_ENABLE_TABLE_GRANTS feature flag (default off) ==
ResourceType.TABLE was shipped in the parent commit as listing-only — admins
can record grants but runtime enforcement still flows through legacy
dataset_permissions. To avoid the misleading-UX surface area, the chip is
hidden from /admin/access and POST /api/admin/grants returns 422 with the
env-var name in detail until the operator opts in. Existing TABLE rows in
resource_grants stay listable + deletable so cleanup is never blocked.

Helpers: is_resource_type_enabled(rt), enabled_resource_types().

== Break-glass admin CLI ==
`da admin break-glass <user>` adds the user to the Admin user_group with
source='system_seed' regardless of RBAC state. Bypasses authentication —
relies on filesystem access to ${DATA_DIR}/state/system.duckdb implying
host-level trust. Recovery path when the operator has locked themselves
out of /admin/access.

== Devin round-2 fixes (deferred on b4ec4c4) ==
- src/repositories/user_groups.py — narrow update() guard from blocking any
  mutation on system groups to blocking name change only. Description edits
  now pass through. Endpoint pre-check stays as defense-in-depth. Prior
  behavior surfaced as a misleading 409 'Cannot rename a system group' on
  description-only PATCH.
- app/api/access.py:delete_group — wrap cascade DELETEs + repo.delete in
  BEGIN TRANSACTION / COMMIT / ROLLBACK. Prevents orphan rows if any
  DELETE fails after the user_groups row is gone.
- app/marketplace_server/{packager,router}.py — split compute_etag_for_user()
  from build_zip(); router resolves etag first and 304-shorts before any
  file read or ZIP_DEFLATED. In-process cachetools.TTLCache (default 120s,
  env-tunable via AGNES_MARKETPLACE_ETAG_TTL, set 0 to disable).
  invalidate_etag_cache() called by sync to force re-hash on content drift.

== Tests ==
- TestTableGrantsFeatureFlag (4 cases) — endpoint exclude/include, grant
  rejection/acceptance under the flag.
- test_v12_to_v13_finalize_rollback_on_failure — destructive: monkeypatches
  _seed_system_groups to raise mid-transaction, asserts schema_version stays
  at 12, legacy tables intact, new tables empty (rollback fired). Then
  restores the real function and asserts the retry succeeds.
- test_update_system_group_description_allowed,
  test_update_system_group_same_name_no_op — repo-level coverage of the
  narrowed guard.
2026-04-28 14:25:13 +02:00

59 lines
1.9 KiB
Python

"""FastAPI router for the aggregated marketplace endpoint.
Two GET routes:
- /marketplace/info → JSON summary (diagnostic / admin)
- /marketplace.zip → ZIP download with ETag / If-None-Match
Both gated by the existing `get_current_user` dependency (Bearer PAT or cookie).
The git smart-HTTP channel lives in git_router.py and is mounted separately
because it needs raw WSGI I/O that FastAPI doesn't model natively.
"""
from __future__ import annotations
import logging
import duckdb
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse, Response
from app.auth.dependencies import _get_db, get_current_user
from app.marketplace_server import packager
logger = logging.getLogger(__name__)
router = APIRouter(tags=["marketplace"])
@router.get("/marketplace/info")
async def marketplace_info(
user: dict = Depends(get_current_user),
conn: duckdb.DuckDBPyConnection = Depends(_get_db),
) -> JSONResponse:
info = packager.build_info(conn, user)
return JSONResponse(info)
@router.get("/marketplace.zip")
async def marketplace_zip(
request: Request,
user: dict = Depends(get_current_user),
conn: duckdb.DuckDBPyConnection = Depends(_get_db),
) -> Response:
if_none_match = request.headers.get("if-none-match", "").strip().strip('"')
# Resolve the etag first — this lets a 304 short-circuit before we read
# every plugin file off disk and run ZIP_DEFLATED. Hot path on every
# Claude Code SessionStart.
etag, plugins = packager.compute_etag_for_user(conn, user)
if if_none_match and if_none_match == etag:
return Response(status_code=304, headers={"ETag": f'"{etag}"'})
data, _ = packager.build_zip(conn, user, plugins=plugins, etag=etag)
return Response(
content=data,
media_type="application/zip",
headers={
"ETag": f'"{etag}"',
"Content-Disposition": 'attachment; filename="agnes-marketplace.zip"',
},
)