From 8d4b2ce9165b5f172c311ceb8c7d589f2bbca06f Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:36:21 -0700 Subject: [PATCH 1/2] fix: AMW API: per-key usage events and daily per-key summary (SEL-346) Linear: SEL-346 Engine: codex (fleet coding engine, Grok Bot dispatch) --- app/core/api_key_usage.py | 91 +++++++++ app/core/auth.py | 16 +- app/db/api_key_usage_view.py | 58 ++++++ app/db/database.py | 27 +++ app/db/models.py | 25 ++- app/db/tenant_rls.py | 13 +- app/main.py | 7 + app/middleware/head_method.py | 1 + app/routers/api_keys.py | 56 ++++++ app/schemas/billing.py | 5 +- docs/api-key-usage.md | 20 ++ docs/railway-customer-manifest.example.json | 2 +- docs/schema-051-rollout.md | 31 ++++ docs/tenant-rls.md | 4 + .../versions/051_api_key_usage_events.py | 62 +++++++ tests/conftest.py | 1 + tests/test_api_key_usage.py | 175 ++++++++++++++++++ tests/test_api_key_usage_migration.py | 118 ++++++++++++ tests/test_demo_key_funnel.py | 2 +- tests/test_dispatch_reconcile_migration.py | 8 +- tests/test_tenant_rls.py | 46 ++++- 21 files changed, 750 insertions(+), 18 deletions(-) create mode 100644 app/core/api_key_usage.py create mode 100644 app/db/api_key_usage_view.py create mode 100644 docs/api-key-usage.md create mode 100644 docs/schema-051-rollout.md create mode 100644 migrations/versions/051_api_key_usage_events.py create mode 100644 tests/test_api_key_usage.py create mode 100644 tests/test_api_key_usage_migration.py diff --git a/app/core/api_key_usage.py b/app/core/api_key_usage.py new file mode 100644 index 00000000..c8510da3 --- /dev/null +++ b/app/core/api_key_usage.py @@ -0,0 +1,91 @@ +"""Metadata-only HTTP usage events for database-backed API keys.""" + +import logging +import time +from uuid import uuid4 + +from starlette.types import ASGIApp, Message, Receive, Scope, Send + +from .auth import CREDENTIAL_ACCEPTANCE +from ..db.database import get_session_factory +from ..db.models import APIKeyUsageEventModel +from ..db.tenant_rls import rls_admin_scope + +logger = logging.getLogger(__name__) + + +async def record_api_key_usage_event( + *, + key_id: str, + tenant: str | None, + method: str, + endpoint: str, + status_code: int, + latency_ms: int, +) -> None: + """Append one event without widening the request's database scope.""" + with rls_admin_scope("api_key_usage_event_write"): + async with get_session_factory()() as session: + session.add( + APIKeyUsageEventModel( + id=str(uuid4()), + key_id=key_id, + tenant=tenant, + method=method, + endpoint=endpoint, + status_code=status_code, + latency_ms=latency_ms, + ) + ) + await session.commit() + + +class APIKeyUsageMiddleware: + """Record the resolved key and final HTTP status once per API request.""" + + def __init__(self, app: ASGIApp) -> None: + self.app = app + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self.app(scope, receive, send) + return + + # RateLimitMiddleware sets this shared holder before entering this + # layer; auth fills its key identity in the child task after lookup. + acceptance = CREDENTIAL_ACCEPTANCE.get() + if acceptance is None: + await self.app(scope, receive, send) + return + + started = time.perf_counter() + status_code = 500 + + async def send_with_status(message: Message) -> None: + nonlocal status_code + if message["type"] == "http.response.start": + status_code = message["status"] + await send(message) + + try: + await self.app(scope, receive, send_with_status) + finally: + # route.path is the registered template. Never substitute scope's + # raw path, which could contain IDs, query values, or user text. + endpoint = getattr(scope.get("route"), "path", None) + if acceptance.key_id and endpoint: + latency_ms = max(0, int((time.perf_counter() - started) * 1000)) + try: + await record_api_key_usage_event( + key_id=acceptance.key_id, + tenant=acceptance.tenant, + method=scope.get("amw_original_method", scope["method"]), + endpoint=endpoint, + status_code=status_code, + latency_ms=latency_ms, + ) + except Exception as exc: # noqa: BLE001 - usage cannot fail API calls + logger.warning( + "api_key_usage_event_write_failed error_type=%s", + type(exc).__name__, + ) diff --git a/app/core/auth.py b/app/core/auth.py index 85e13a04..5b5c01e1 100644 --- a/app/core/auth.py +++ b/app/core/auth.py @@ -116,9 +116,11 @@ def require_bootstrap_admin(self) -> None: @dataclass class CredentialAcceptance: - """Whether ``get_auth_context`` accepted credentials during one request.""" + """Accepted credentials and any DB key resolved before route denial.""" accepted: bool = False + key_id: str | None = None + tenant: str | None = None # The converse signal, for RateLimitMiddleware's shared pre-auth bucket. A @@ -135,6 +137,14 @@ class CredentialAcceptance: ) +def _note_resolved_key(key_id: str, tenant: str | None) -> None: + """Mark a valid DB key even if route authorization later denies it.""" + acceptance = CREDENTIAL_ACCEPTANCE.get() + if acceptance is not None: + acceptance.key_id = key_id + acceptance.tenant = tenant + + async def get_auth_context( api_key: str | None = Security(api_key_header), authorization: Annotated[str | None, Header()] = None, @@ -166,6 +176,8 @@ async def get_auth_context( acceptance = CREDENTIAL_ACCEPTANCE.get() if acceptance is not None: acceptance.accepted = True + acceptance.key_id = context.key_id + acceptance.tenant = context.tenant return context @@ -310,6 +322,7 @@ async def _resolve_auth_context( "message": "The demo tenant is currently disabled.", }, ) + _note_resolved_key(db_key.key_id, tenant) if tenant == DEMO_TENANT_LABEL: current = current_demo_request() if current is None or not demo_route_allowed(*current): @@ -511,6 +524,7 @@ async def _auth_from_jwt(token: str) -> AuthContext: "message": "The demo tenant is currently disabled.", }, ) + _note_resolved_key(payload.key_id, tenant) if tenant == DEMO_TENANT_LABEL: current = current_demo_request() if current is None or not demo_route_allowed(*current): diff --git a/app/db/api_key_usage_view.py b/app/db/api_key_usage_view.py new file mode 100644 index 00000000..81a22f34 --- /dev/null +++ b/app/db/api_key_usage_view.py @@ -0,0 +1,58 @@ +"""Portable daily API-key usage view definition. + +Timestamps in this database are naive UTC. Percentiles use continuous linear +interpolation, matching PostgreSQL's percentile_cont on both supported SQL +dialects. The SQLite development schema and Alembic migration share this SQL. +""" + + +def _percentile_expression(percent: int) -> str: + return ( + "SUM(CASE " + f"WHEN latency_rank = p{percent}_floor_rank " + f"THEN latency_ms * (100 - p{percent}_remainder) / 100.0 " + f"WHEN latency_rank = p{percent}_floor_rank + 1 " + f"THEN latency_ms * p{percent}_remainder / 100.0 " + f"ELSE 0 END) AS p{percent}_latency_ms" + ) + + +CREATE_API_KEY_USAGE_DAILY_VIEW_SQL = f""" +CREATE VIEW api_key_usage_daily AS +WITH ranked AS ( + SELECT + key_id, + DATE(created_at) AS day, + status_code, + latency_ms, + created_at, + ROW_NUMBER() OVER ( + PARTITION BY key_id, DATE(created_at) + ORDER BY latency_ms, id + ) AS latency_rank, + COUNT(*) OVER ( + PARTITION BY key_id, DATE(created_at) + ) AS call_count + FROM api_key_usage_events +), positioned AS ( + SELECT + *, + ((call_count - 1) * 50) / 100 + 1 AS p50_floor_rank, + ((call_count - 1) * 50) % 100 AS p50_remainder, + ((call_count - 1) * 95) / 100 + 1 AS p95_floor_rank, + ((call_count - 1) * 95) % 100 AS p95_remainder + FROM ranked +) +SELECT + key_id, + day, + COUNT(*) AS calls, + SUM(CASE WHEN status_code BETWEEN 400 AND 499 THEN 1 ELSE 0 END) AS calls_4xx, + SUM(CASE WHEN status_code BETWEEN 500 AND 599 THEN 1 ELSE 0 END) AS calls_5xx, + {_percentile_expression(50)}, + {_percentile_expression(95)}, + MIN(created_at) AS first_call_at, + MAX(created_at) AS last_call_at +FROM positioned +GROUP BY key_id, day +""" diff --git a/app/db/database.py b/app/db/database.py index 30df07bb..f3e54dc3 100644 --- a/app/db/database.py +++ b/app/db/database.py @@ -35,6 +35,7 @@ from ..core.db_urls import as_sqlalchemy_url from ..core.time import to_naive_utc from ..core.trust_mode import is_production_like_environment +from .api_key_usage_view import CREATE_API_KEY_USAGE_DAILY_VIEW_SQL from .tenant_rls import TenantScopedSession logger = logging.getLogger(__name__) @@ -51,9 +52,22 @@ "receipts", "idempotency_records", "mcp_dispatch_attempts", + "api_key_usage_events", } ) REQUIRED_TRUST_COLUMNS = { + "api_key_usage_events": frozenset( + { + "id", + "key_id", + "tenant", + "method", + "endpoint", + "status_code", + "latency_ms", + "created_at", + } + ), "mcp_dispatch_attempts": frozenset( { "dispatch_claim_hash", @@ -292,6 +306,10 @@ def _missing_required_tables(sync_conn) -> set[str]: # noqa: ANN001 return set(REQUIRED_TRUST_TABLES) - existing +def _missing_required_views(sync_conn) -> set[str]: # noqa: ANN001 + return {"api_key_usage_daily"} - set(sa_inspect(sync_conn).get_view_names()) + + def _missing_required_columns(sync_conn) -> set[str]: # noqa: ANN001 inspector = sa_inspect(sync_conn) existing_tables = set(inspector.get_table_names()) @@ -348,6 +366,7 @@ async def verify_required_schema(engine: AsyncEngine) -> None: async with engine.connect() as conn: missing = await conn.run_sync(_missing_required_tables) missing_columns = await conn.run_sync(_missing_required_columns) + missing_views = await conn.run_sync(_missing_required_views) stale = await conn.run_sync(_stale_alembic_message) # A stamped database can be both behind head and missing tables introduced # by later revisions. Report the revision mismatch first: it is the @@ -370,6 +389,12 @@ async def verify_required_schema(engine: AsyncEngine) -> None: "the API (normally `alembic upgrade head`; review an unstamped " "legacy schema before stamping its exact existing revision)." ) + if missing_views: + raise SchemaInitError( + "Required database views missing: " + + ", ".join(sorted(missing_views)) + + ". Bring the schema to the packaged Alembic head before starting the API." + ) async def init_db() -> None: @@ -392,6 +417,8 @@ async def init_db() -> None: if allows_metadata_create_all(dialect_name=dialect, environment=environment): async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all) + if "api_key_usage_daily" in await conn.run_sync(_missing_required_views): + await conn.exec_driver_sql(CREATE_API_KEY_USAGE_DAILY_VIEW_SQL) missing_columns = await conn.run_sync(_missing_required_columns) if missing_columns: raise SchemaInitError( diff --git a/app/db/models.py b/app/db/models.py index c8d504fb..dd0f0baf 100644 --- a/app/db/models.py +++ b/app/db/models.py @@ -388,9 +388,9 @@ class APIKeyModel(SQLModel, table=True): ) expires_at: Optional[datetime] = Field(sa_type=NaiveUTCDateTime, default=None) - # Bounded-use keys: None = unlimited. use_count only advances through the - # guarded UPDATE in APIKeyService.validate_key so the cap cannot be - # overshot by concurrent requests. + # Bounded-use keys: None = unlimited. use_count tracks capped-key budget + # consumption, not total calls. api_key_usage_events is the call source + # of truth; it also includes unbounded keys and response outcomes. max_uses: Optional[int] = Field(default=None) use_count: int = Field(default=0) @@ -419,6 +419,25 @@ class APIKeyModel(SQLModel, table=True): model_config = {"arbitrary_types_allowed": True} +class APIKeyUsageEventModel(SQLModel, table=True): + """One metadata-only HTTP outcome for a resolved database API key.""" + + __tablename__ = "api_key_usage_events" + __table_args__ = ( + Index("ix_api_key_usage_events_key_created", "key_id", "created_at"), + ) + + id: str = Field(primary_key=True, max_length=36) + # Historical events survive key revocation or deletion. + key_id: str = Field(max_length=50) + tenant: Optional[str] = Field(default=None, max_length=32) + method: str = Field(max_length=16) + endpoint: str = Field(max_length=512) + status_code: int + latency_ms: int + created_at: datetime = Field(sa_type=NaiveUTCDateTime, default_factory=utc_now) + + class TelemetryEventModel(SQLModel, table=True): """ Time-series telemetry events for the Autonomous PM. diff --git a/app/db/tenant_rls.py b/app/db/tenant_rls.py index a4359fdb..6c42f51d 100644 --- a/app/db/tenant_rls.py +++ b/app/db/tenant_rls.py @@ -72,6 +72,11 @@ "refresh_tokens": ("wallet_id",), } +# No wallet owner column: only the explicit admin scope may read or append +# these cross-tenant reporting rows. Migration 051 creates its separate policy. +ADMIN_ONLY_RLS_TABLES = ("api_key_usage_events",) +RLS_POSTURE_TABLES = (*RLS_TABLES, *ADMIN_ONLY_RLS_TABLES) + def enable_rls_statements() -> list[str]: """The ALTERs that turn RLS on for a database migrated in off mode. @@ -81,7 +86,7 @@ def enable_rls_statements() -> list[str]: """ return [ f"ALTER TABLE {table} {action} ROW LEVEL SECURITY" - for table in RLS_TABLES + for table in RLS_POSTURE_TABLES for action in ("ENABLE", "FORCE") ] @@ -255,11 +260,13 @@ async def check_tenant_rls_posture(engine: AsyncEngine) -> dict[str, Any]: async with engine.connect() as conn: role = (await conn.execute(_POSTURE_SQL)).one() - rows = (await conn.execute(_TABLES_SQL, {"tables": list(RLS_TABLES)})).all() + rows = ( + await conn.execute(_TABLES_SQL, {"tables": list(RLS_POSTURE_TABLES)}) + ).all() tables = {row.relname: row for row in rows} not_forced = sorted( name - for name in RLS_TABLES + for name in RLS_POSTURE_TABLES if name not in tables or not (tables[name].relrowsecurity and tables[name].relforcerowsecurity) ) diff --git a/app/main.py b/app/main.py index 4fe666a6..4fbe17be 100644 --- a/app/main.py +++ b/app/main.py @@ -658,6 +658,12 @@ async def periodic_cleanup(): # --- Middleware Stack --- +# Run inside the rate limiter so its accepted-credential holder is shared +# with auth; this records at most one event after the routed call completes. +from .core.api_key_usage import APIKeyUsageMiddleware + +app.add_middleware(APIKeyUsageMiddleware) + # Rate limiting (enforces documented 120 req/min per API key) app.add_middleware(RateLimitMiddleware) @@ -892,6 +898,7 @@ def mount_dormant_trust_surfaces(application: FastAPI) -> None: app.include_router( demo_keys.admin_router, include_in_schema=settings.ENABLE_DEMO_TENANT ) +app.include_router(api_keys.admin_router) # Stripe webhooks answer only signed Stripe traffic; a deployment with no # Stripe key configured has nothing that could ever call them, so they are diff --git a/app/middleware/head_method.py b/app/middleware/head_method.py index 2c867b5d..07f6ff03 100644 --- a/app/middleware/head_method.py +++ b/app/middleware/head_method.py @@ -42,6 +42,7 @@ async def __call__( # Copy before mutating: the original scope belongs to the server. get_scope = dict(scope) get_scope["method"] = "GET" + get_scope["amw_original_method"] = "HEAD" async def send_without_body(message: dict[str, Any]) -> None: if message["type"] == "http.response.body": diff --git a/app/routers/api_keys.py b/app/routers/api_keys.py index fb2af1b9..741225da 100644 --- a/app/routers/api_keys.py +++ b/app/routers/api_keys.py @@ -4,11 +4,16 @@ Handles API key creation, rotation, and revocation for wallet security. """ +from datetime import date, datetime + from fastapi import APIRouter, Depends, Header, HTTPException, Request, status +from pydantic import BaseModel +from sqlalchemy import text from ..core.dependencies import get_agent_money from ..core.auth import AuthContext, get_auth_context +from ..db.database import get_session_factory from ..services.api_key_service import ( get_api_key_service, InvalidRotationRequestError, @@ -37,6 +42,57 @@ }, ) +admin_router = APIRouter( + prefix="/v1/admin/api-keys", + tags=["API Key Management"], +) + + +class APIKeyUsageDailyRow(BaseModel): + key_id: str + day: date + calls: int + calls_4xx: int + calls_5xx: int + p50_latency_ms: float + p95_latency_ms: float + first_call_at: datetime + last_call_at: datetime + + +class APIKeyUsageDailyResponse(BaseModel): + rows: list[APIKeyUsageDailyRow] + + +@admin_router.get( + "/usage/daily", + response_model=APIKeyUsageDailyResponse, + summary="Admin: daily usage by API key", + description="Read daily call counts and latency from api_key_usage_daily.", +) +async def admin_api_key_usage_daily( + key_id: str | None = None, + auth: AuthContext = Depends(get_auth_context), +) -> APIKeyUsageDailyResponse: + auth.require_bootstrap_admin() + query = ( + "SELECT key_id, day, calls, calls_4xx, calls_5xx, p50_latency_ms, " + "p95_latency_ms, first_call_at, last_call_at FROM api_key_usage_daily" + ) + parameters = {} + if key_id is not None: + query += " WHERE key_id = :key_id" + parameters["key_id"] = key_id + query += " ORDER BY day DESC, key_id" + async with get_session_factory()() as session: + result = await session.execute(text(query), parameters) + return APIKeyUsageDailyResponse( + rows=[ + APIKeyUsageDailyRow.model_validate(dict(row)) + for row in result.mappings() + ] + ) + def _not_found(error: str, message: str) -> dict: """Standardized 404 error payload.""" diff --git a/app/schemas/billing.py b/app/schemas/billing.py index 0bd7b70e..9839c036 100644 --- a/app/schemas/billing.py +++ b/app/schemas/billing.py @@ -812,7 +812,10 @@ class APIKeyResponse(BaseModel): created_at: datetime expires_at: datetime | None = None max_uses: int | None = None - use_count: int = 0 + use_count: int = Field( + default=0, + description="Bounded-key budget uses, not total calls. See api_key_usage_daily.", + ) class APIKeyWithSecret(BaseModel): diff --git a/docs/api-key-usage.md b/docs/api-key-usage.md new file mode 100644 index 00000000..8336076c --- /dev/null +++ b/docs/api-key-usage.md @@ -0,0 +1,20 @@ +# API key usage reporting + +`api_key_usage_events` is the call-count source for database-backed API keys. +Each row records the key ID, tenant label, HTTP method, registered route +template, final status, latency in milliseconds, and UTC time. It stores no +request or response body, raw URL, query, header, client address, or key value. +Bootstrap keys configured outside the database have no key ID and produce no +per-key event. Requests refused before authentication also produce no event. + +`api_keys.use_count` remains the bounded-key budget counter. It advances only +for keys with `max_uses` and must not be used as a general traffic count. +The event insert is best effort: a database write failure never changes the +API response, so a failed insert can leave a gap in reported usage. +The application only appends rows; database administrators can still alter +them. This is usage reporting, not signed audit evidence. + +The read-only `api_key_usage_daily` SQL view groups by key ID and UTC day. It +reports calls, 4xx, 5xx, continuous p50/p95 latency, and first/last call. +`GET /v1/admin/api-keys/usage/daily` reads the view; an optional `key_id` +query parameter filters one key. Only bootstrap admins can access it. diff --git a/docs/railway-customer-manifest.example.json b/docs/railway-customer-manifest.example.json index bc1e1638..1cb82279 100644 --- a/docs/railway-customer-manifest.example.json +++ b/docs/railway-customer-manifest.example.json @@ -8,5 +8,5 @@ "signing_key_id": "example-customer-production-ed25519-v1", "signing_public_key_sha256": "630dcd2966c4336691125448bbb25b4ff412a49c732db2c8abc1b8581bd710dd", "expected_commit_sha": "0000000000000000000000000000000000000000", - "expected_alembic_revision": "050_demo_key_first_used" + "expected_alembic_revision": "051_api_key_usage_events" } diff --git a/docs/schema-051-rollout.md b/docs/schema-051-rollout.md new file mode 100644 index 00000000..f389aadc --- /dev/null +++ b/docs/schema-051-rollout.md @@ -0,0 +1,31 @@ +# Schema 051: API key usage events + +Migration `051_api_key_usage_events` revises `050_demo_key_first_used`. It adds +the metadata-only `api_key_usage_events` table, an index on `(key_id, +created_at)`, and the read-only `api_key_usage_daily` view. It changes no +existing rows. Usage before 051 is not backfilled; `api_keys.use_count` is a +bounded-key budget counter, not a historical call total. + +## Compatibility release + +Production boot requires the database revision to match the packaged Alembic +head. A 050-packaged image cannot restart after 051 is applied. Before applying +051, qualify a 051-compatible image and a recovery artifact against a +disposable PostgreSQL upgrade from 050. Verify the event insert, the daily +view, the admin-only read route, and enforced RLS with the intended runtime +role. Record the exact image SHA, database revision, and private parity result. +These release checks are required and have not been run in this worktree. + +The new event writer is best effort: an insert failure leaves a reporting gap +without failing the API request. The view contains only events recorded after +the migration. The table's PostgreSQL policy allows only explicitly scoped +admin transactions when RLS is enforced; the application exposes the view +through a bootstrap-admin-only route. + +## Rollback boundary + +Do not deploy a 050-packaged image against schema 051. Use a qualified +051-compatible recovery image while retaining the database at 051. Alembic +downgrade to 050 drops the view and table, permanently discarding every usage +event recorded since 051. It is a data-loss operation, not an application +rollback; never perform it while the API serves traffic. diff --git a/docs/tenant-rls.md b/docs/tenant-rls.md index 5ce1dc49..498f9de6 100644 --- a/docs/tenant-rls.md +++ b/docs/tenant-rls.md @@ -59,6 +59,10 @@ Covered tables (`app.db.tenant_rls.RLS_TABLES`, frozen in the migration): `ledger_entries`, `mcp_dispatch_attempts`, `permit_requests`, `permits`, `policy_bundles`, `quotes`, `receipts`, `refresh_tokens`. +`api_key_usage_events` has a separate admin-only policy from migration 051. +It is included in posture checks and the manual enable/force statements; the +event writer uses an explicit admin scope for its single insert. + Not covered (deliberately, for now): `wallets` (the tenant root, read during credential resolution and parent/child provisioning), `control_plane_audit_events` and `audit_chain_heads` (carry wallet-less rows), the `insight_*` tables (own diff --git a/migrations/versions/051_api_key_usage_events.py b/migrations/versions/051_api_key_usage_events.py new file mode 100644 index 00000000..d3e7b617 --- /dev/null +++ b/migrations/versions/051_api_key_usage_events.py @@ -0,0 +1,62 @@ +"""Store per-key API call facts and expose daily aggregates. + +Revision ID: 051_api_key_usage_events +Revises: 050_demo_key_first_used + +The event rows contain route templates only, never request payloads, raw URLs, +headers, client addresses, or credentials. Timestamps are naive UTC. +""" + +from alembic import op +import sqlalchemy as sa + +from app.core.config import get_settings +from app.db.api_key_usage_view import CREATE_API_KEY_USAGE_DAILY_VIEW_SQL + +revision: str = "051_api_key_usage_events" +down_revision: str = "050_demo_key_first_used" +branch_labels = None +depends_on = None + +_RLS_POLICY = "api_key_usage_events_admin_only" +_BYPASS = "current_setting('app.rls_bypass', true) = 'on'" + + +def upgrade() -> None: + op.create_table( + "api_key_usage_events", + sa.Column("id", sa.String(length=36), primary_key=True), + sa.Column("key_id", sa.String(length=50), nullable=False), + sa.Column("tenant", sa.String(length=32), nullable=True), + sa.Column("method", sa.String(length=16), nullable=False), + sa.Column("endpoint", sa.String(length=512), nullable=False), + sa.Column("status_code", sa.Integer(), nullable=False), + sa.Column("latency_ms", sa.Integer(), nullable=False), + sa.Column("created_at", sa.DateTime(), nullable=False), + ) + op.create_index( + "ix_api_key_usage_events_key_created", + "api_key_usage_events", + ["key_id", "created_at"], + ) + + if op.get_bind().dialect.name == "postgresql": + op.execute( + f"CREATE POLICY {_RLS_POLICY} ON api_key_usage_events " + f"AS PERMISSIVE FOR ALL USING ({_BYPASS}) WITH CHECK ({_BYPASS})" + ) + if get_settings().TENANT_RLS_MODE == "enforce": + op.execute("ALTER TABLE api_key_usage_events ENABLE ROW LEVEL SECURITY") + op.execute("ALTER TABLE api_key_usage_events FORCE ROW LEVEL SECURITY") + + op.execute(CREATE_API_KEY_USAGE_DAILY_VIEW_SQL) + + +def downgrade() -> None: + op.execute("DROP VIEW IF EXISTS api_key_usage_daily") + if op.get_bind().dialect.name == "postgresql": + op.execute(f"DROP POLICY IF EXISTS {_RLS_POLICY} ON api_key_usage_events") + op.drop_index( + "ix_api_key_usage_events_key_created", table_name="api_key_usage_events" + ) + op.drop_table("api_key_usage_events") diff --git a/tests/conftest.py b/tests/conftest.py index 4cc71064..3c438e36 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -406,6 +406,7 @@ async def setup_database(): "daily_balance_snapshots", "kyc_verifications", "refresh_tokens", + "api_key_usage_events", "api_keys", "key_rotation_logs", "service_registry", diff --git a/tests/test_api_key_usage.py b/tests/test_api_key_usage.py new file mode 100644 index 00000000..07d4da26 --- /dev/null +++ b/tests/test_api_key_usage.py @@ -0,0 +1,175 @@ +"""SEL-346: per-key API usage events and operator reporting.""" + +from __future__ import annotations + +from datetime import datetime + +import pytest +from httpx import AsyncClient +from sqlalchemy import text + +from app.core import api_key_usage +from app.db.database import get_session_factory +from tests.test_demo_tenant import ( + client as _client, + demo_headers, + demo_settings as _demo_settings, + issue_demo_key, +) +from tests.test_trust_helpers import BOOTSTRAP_HEADERS, provision_agent_wallet + + +client = _client +demo_settings = _demo_settings +DAILY = "/v1/admin/api-keys/usage/daily" + + +async def _events_for(key_id: str) -> list[dict]: + async with get_session_factory()() as session: + result = await session.execute( + text( + "SELECT * FROM api_key_usage_events " + "WHERE key_id = :key_id ORDER BY created_at, id" + ), + {"key_id": key_id}, + ) + return [dict(row) for row in result.mappings()] + + +@pytest.mark.anyio +async def test_authenticated_calls_record_one_event_each_without_request_data( + client: AsyncClient, clean_database: None +) -> None: + wallet = await provision_agent_wallet(client) + private = "private-person@example.test" + response = await client.request( + "GET", + f"/v1/api-keys/{wallet['agent_wallet_id']}", + params={"email": private}, + headers={**wallet["agent_headers"], "X-Private-Note": private}, + content=private, + ) + assert response.status_code == 200, response.text + response = await client.get("/v1/me/authority", headers=wallet["agent_headers"]) + assert response.status_code == 200, response.text + + events = await _events_for(wallet["key_id"]) + assert len(events) == 2 + assert {event["endpoint"] for event in events} == { + "/v1/api-keys/{wallet_id}", + "/v1/me/authority", + } + assert all(event["method"] == "GET" for event in events) + assert all(event["status_code"] == 200 for event in events) + assert all(event["tenant"] is None for event in events) + assert all(event["latency_ms"] >= 0 for event in events) + assert all(event["created_at"] is not None for event in events) + assert all( + private not in str(value) for event in events for value in event.values() + ) + assert all( + set(event) + == { + "id", + "key_id", + "tenant", + "method", + "endpoint", + "status_code", + "latency_ms", + "created_at", + } + for event in events + ) + + +@pytest.mark.anyio +async def test_missing_and_invalid_credentials_create_no_events( + client: AsyncClient, clean_database: None +) -> None: + assert (await client.get("/v1/me/authority")).status_code == 401 + assert ( + await client.get("/v1/me/authority", headers={"X-API-Key": "not-a-real-key"}) + ).status_code == 403 + async with get_session_factory()() as session: + count = await session.scalar(text("SELECT COUNT(*) FROM api_key_usage_events")) + assert count == 0 + + +@pytest.mark.anyio +async def test_governed_route_and_head_record_original_method( + client: AsyncClient, clean_database: None +) -> None: + wallet = await provision_agent_wallet(client) + malformed = await client.post( + "/mcp/messages", + content="{private-data", + headers=wallet["agent_headers"], + ) + assert malformed.status_code == 400 + head = await client.head("/v1/me/authority", headers=wallet["agent_headers"]) + assert head.status_code == 200 + + events = await _events_for(wallet["key_id"]) + assert { + (event["method"], event["endpoint"], event["status_code"]) for event in events + } == { + ("POST", "/mcp/messages", 400), + ("HEAD", "/v1/me/authority", 200), + } + + +@pytest.mark.anyio +async def test_daily_usage_requires_bootstrap_admin_and_reports_key_calls( + client: AsyncClient, clean_database: None, demo_settings +) -> None: + wallet = await provision_agent_wallet(client) + demo = await issue_demo_key(client) + assert ( + await client.get("/v1/me/authority", headers=wallet["agent_headers"]) + ).status_code == 200 + assert ( + await client.get("/v1/me/authority", headers=demo_headers(demo)) + ).status_code == 200 + + assert (await client.get(DAILY)).status_code == 401 + assert ( + await client.get(DAILY, headers={"X-API-Key": "not-a-real-key"}) + ).status_code == 403 + assert (await client.get(DAILY, headers=wallet["agent_headers"])).status_code == 403 + assert (await client.get(DAILY, headers=demo_headers(demo))).status_code == 403 + + response = await client.get(DAILY, headers=BOOTSTRAP_HEADERS) + assert response.status_code == 200, response.text + rows = response.json()["rows"] + wallet_rows = [row for row in rows if row["key_id"] == wallet["key_id"]] + demo_rows = [row for row in rows if row["key_id"] == demo["key_id"]] + assert sum(row["calls"] for row in wallet_rows) == 2 + assert sum(row["calls_4xx"] for row in wallet_rows) == 1 + assert sum(row["calls"] for row in demo_rows) == 2 + assert sum(row["calls_4xx"] for row in demo_rows) == 1 + assert all(event["tenant"] == "demo" for event in await _events_for(demo["key_id"])) + for row in wallet_rows + demo_rows: + assert row["calls_5xx"] == 0 + assert row["p50_latency_ms"] >= 0 + assert row["p95_latency_ms"] >= 0 + assert row["first_call_at"] <= row["last_call_at"] + assert ( + datetime.fromisoformat(row["first_call_at"]).date().isoformat() + == row["day"] + ) + + +@pytest.mark.anyio +async def test_failed_usage_insert_does_not_fail_authenticated_request( + client: AsyncClient, clean_database: None, monkeypatch: pytest.MonkeyPatch +) -> None: + wallet = await provision_agent_wallet(client) + + async def fail_insert(*_args, **_kwargs) -> None: + raise RuntimeError("synthetic usage insert failure") + + monkeypatch.setattr(api_key_usage, "record_api_key_usage_event", fail_insert) + response = await client.get("/v1/me/authority", headers=wallet["agent_headers"]) + assert response.status_code == 200, response.text + assert await _events_for(wallet["key_id"]) == [] diff --git a/tests/test_api_key_usage_migration.py b/tests/test_api_key_usage_migration.py new file mode 100644 index 00000000..ec7b2c50 --- /dev/null +++ b/tests/test_api_key_usage_migration.py @@ -0,0 +1,118 @@ +"""SEL-346: API-key usage event schema and continuous daily percentiles.""" + +from alembic import command +from alembic.config import Config +from alembic.script import ScriptDirectory +from sqlalchemy import create_engine, inspect, text + + +def test_051_revision_and_daily_view(tmp_path, monkeypatch) -> None: + script = ScriptDirectory.from_config(Config("alembic.ini")) + assert script.get_revision("051_api_key_usage_events").down_revision == ( + "050_demo_key_first_used" + ) + + db_path = tmp_path / "api-key-usage-migration.db" + monkeypatch.setenv("DATABASE_URL", f"sqlite+aiosqlite:///{db_path}") + config = Config("alembic.ini") + command.upgrade(config, "050_demo_key_first_used") + command.upgrade(config, "051_api_key_usage_events") + + engine = create_engine(f"sqlite:///{db_path}") + inspector = inspect(engine) + assert "api_key_usage_events" in inspector.get_table_names() + assert "api_key_usage_daily" in inspector.get_view_names() + assert { + column["name"] for column in inspector.get_columns("api_key_usage_events") + } == { + "id", + "key_id", + "tenant", + "method", + "endpoint", + "status_code", + "latency_ms", + "created_at", + } + assert any( + index["name"] == "ix_api_key_usage_events_key_created" + and index["column_names"] == ["key_id", "created_at"] + for index in inspector.get_indexes("api_key_usage_events") + ) + + insert = text( + "INSERT INTO api_key_usage_events " + "(id, key_id, tenant, method, endpoint, status_code, latency_ms, created_at) " + "VALUES (:id, :key_id, 'demo', 'GET', '/v1/me/authority', " + ":status_code, :latency_ms, :created_at)" + ) + with engine.begin() as connection: + for event_id, key_id, status_code, latency_ms, created_at in ( + ("1", "key-a", 200, 40, "2026-10-20 23:00:00"), + ("2", "key-a", 404, 10, "2026-10-20 01:00:00"), + ("3", "key-a", 500, 30, "2026-10-20 20:00:00"), + ("4", "key-a", 400, 20, "2026-10-20 12:00:00"), + ("5", "key-a", 200, 7, "2026-10-21 00:00:00"), + ("6", "key-b", 200, 100, "2026-10-20 10:00:00"), + ): + connection.execute( + insert, + { + "id": event_id, + "key_id": key_id, + "status_code": status_code, + "latency_ms": latency_ms, + "created_at": created_at, + }, + ) + rows = connection.execute( + text( + "SELECT key_id, day, calls, calls_4xx, calls_5xx, " + "p50_latency_ms, p95_latency_ms, first_call_at, last_call_at " + "FROM api_key_usage_daily ORDER BY key_id, day" + ) + ).all() + engine.dispose() + assert [tuple(row) for row in rows] == [ + ( + "key-a", + "2026-10-20", + 4, + 2, + 1, + 25.0, + 38.5, + "2026-10-20 01:00:00", + "2026-10-20 23:00:00", + ), + ( + "key-a", + "2026-10-21", + 1, + 0, + 0, + 7.0, + 7.0, + "2026-10-21 00:00:00", + "2026-10-21 00:00:00", + ), + ( + "key-b", + "2026-10-20", + 1, + 0, + 0, + 100.0, + 100.0, + "2026-10-20 10:00:00", + "2026-10-20 10:00:00", + ), + ] + + command.downgrade(config, "050_demo_key_first_used") + engine = create_engine(f"sqlite:///{db_path}") + inspector = inspect(engine) + assert "api_key_usage_events" not in inspector.get_table_names() + assert "api_key_usage_daily" not in inspector.get_view_names() + assert "api_keys" in inspector.get_table_names() + engine.dispose() diff --git a/tests/test_demo_key_funnel.py b/tests/test_demo_key_funnel.py index 8b02d34f..f4a6194c 100644 --- a/tests/test_demo_key_funnel.py +++ b/tests/test_demo_key_funnel.py @@ -185,7 +185,7 @@ def test_050_revision_chain_and_file() -> None: script = ScriptDirectory.from_config(Config("alembic.ini")) revision = script.get_revision("050_demo_key_first_used") assert revision.down_revision == "049_demo_key_attribution" - assert script.get_heads() == ["050_demo_key_first_used"] + assert script.get_heads() == ["051_api_key_usage_events"] assert Path(revision.path).name == "050_demo_key_first_used.py" diff --git a/tests/test_dispatch_reconcile_migration.py b/tests/test_dispatch_reconcile_migration.py index e0dd5d65..cf5cf7c9 100644 --- a/tests/test_dispatch_reconcile_migration.py +++ b/tests/test_dispatch_reconcile_migration.py @@ -29,11 +29,11 @@ def test_model_and_boot_check_cover_reconcile_columns(): assert RECONCILE_COLUMNS <= REQUIRED_TRUST_COLUMNS["mcp_dispatch_attempts"] -def test_049_is_the_parent_of_the_single_head(): +def test_050_is_the_parent_of_the_single_head(): script = ScriptDirectory.from_config(Config("alembic.ini")) - assert script.get_heads() == ["050_demo_key_first_used"] - assert script.get_revision("050_demo_key_first_used").down_revision == ( - "049_demo_key_attribution" + assert script.get_heads() == ["051_api_key_usage_events"] + assert script.get_revision("051_api_key_usage_events").down_revision == ( + "050_demo_key_first_used" ) diff --git a/tests/test_tenant_rls.py b/tests/test_tenant_rls.py index 60fe3bdc..d0dc70f8 100644 --- a/tests/test_tenant_rls.py +++ b/tests/test_tenant_rls.py @@ -33,6 +33,7 @@ from app.db.models import LedgerEntryModel, PermitModel, SigningKeyModel, WalletModel from app.db.tenant_rls import ( RLS_TABLES, + RLS_POSTURE_TABLES, RlsScope, TenantRlsPostureError, TenantScopedSession, @@ -135,8 +136,8 @@ async def body(): def test_enable_rls_statements_cover_every_table(): statements = enable_rls_statements() - assert len(statements) == 2 * len(RLS_TABLES) - for table in RLS_TABLES: + assert len(statements) == 2 * len(RLS_POSTURE_TABLES) + for table in RLS_POSTURE_TABLES: assert f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY" in statements assert f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY" in statements @@ -561,6 +562,43 @@ async def test_explicit_bypass_sees_every_wallet(seeded): await engine.dispose() +@pytest.mark.anyio +async def test_api_key_usage_view_requires_admin_bypass(rls_db): + engine = _engine(rls_db["app_url"]) + try: + async with engine.begin() as conn: + await conn.execute(text("SELECT set_config('app.rls_bypass', 'on', true)")) + await conn.execute( + text( + "INSERT INTO api_key_usage_events " + "(id, key_id, tenant, method, endpoint, status_code, " + "latency_ms, created_at) VALUES " + "('rls-usage-event', 'rls-key', 'demo', 'GET', " + "'/v1/me/authority', 200, 7, '2026-10-20 12:00:00')" + ) + ) + assert ( + await conn.scalar(text("SELECT calls FROM api_key_usage_daily")) + ) == 1 + + async with engine.connect() as conn: + assert ( + await conn.scalar(text("SELECT COUNT(*) FROM api_key_usage_events")) + == 0 + ) + assert ( + await conn.scalar(text("SELECT COUNT(*) FROM api_key_usage_daily")) == 0 + ) + await conn.execute( + text("SELECT set_config('app.current_wallet_id', 'rls-wallet-a', true)") + ) + assert ( + await conn.scalar(text("SELECT COUNT(*) FROM api_key_usage_daily")) == 0 + ) + finally: + await engine.dispose() + + @pytest.mark.anyio async def test_set_local_scope_does_not_survive_commit(seeded): """A pooled connection must not carry the last request's wallet.""" @@ -655,7 +693,7 @@ async def test_off_mode_after_enforce_bypasses_once_posture_sees_rls( async with factory() as session: assert (await session.execute(count)).scalar() == 0 report = await check_tenant_rls_posture(engine) - assert report["tables_with_rls_enabled"] == sorted(RLS_TABLES) + assert report["tables_with_rls_enabled"] == sorted(RLS_POSTURE_TABLES) assert tenant_rls._off_mode_bypass_required is True async with factory() as session: assert (await session.execute(count)).scalar() == 3 @@ -684,7 +722,7 @@ async def test_posture_accepts_runtime_role_and_refuses_superuser(seeded, monkey await engine.dispose() # The owner is still bound (FORCE), so not refused, but reported. assert report["effective"] is True - assert sorted(report["owns_rls_tables"]) == sorted(RLS_TABLES) + assert sorted(report["owns_rls_tables"]) == sorted(RLS_POSTURE_TABLES) from sqlalchemy.engine import make_url From d24e3cf64ffb7233ca43fd30b4e3571c2a0395fb Mon Sep 17 00:00:00 2001 From: PetrefiedThunder <131207452+PetrefiedThunder@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:21:36 -0800 Subject: [PATCH 2/2] fix: sync per-key usage OpenAPI schema --- docs/openapi.json | 147 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) diff --git a/docs/openapi.json b/docs/openapi.json index b15996c3..cd544f8c 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -5402,6 +5402,80 @@ } } }, + "/v1/admin/api-keys/usage/daily": { + "get": { + "tags": [ + "API Key Management" + ], + "summary": "Admin: daily usage by API key", + "description": "Read daily call counts and latency from api_key_usage_daily.", + "operationId": "admin_api_key_usage_daily_v1_admin_api_keys_usage_daily_get", + "security": [ + { + "APIKeyHeader": [] + }, + { + "HTTPBearer": [] + } + ], + "parameters": [ + { + "name": "key_id", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Key Id" + } + }, + { + "name": "authorization", + "in": "header", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Authorization" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/APIKeyUsageDailyResponse" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/": { "get": { "tags": [ @@ -5655,6 +5729,7 @@ "use_count": { "type": "integer", "title": "Use Count", + "description": "Bounded-key budget uses, not total calls. See api_key_usage_daily.", "default": 0 } }, @@ -5680,6 +5755,78 @@ ], "title": "APIKeyStatus" }, + "APIKeyUsageDailyResponse": { + "properties": { + "rows": { + "items": { + "$ref": "#/components/schemas/APIKeyUsageDailyRow" + }, + "type": "array", + "title": "Rows" + } + }, + "type": "object", + "required": [ + "rows" + ], + "title": "APIKeyUsageDailyResponse" + }, + "APIKeyUsageDailyRow": { + "properties": { + "key_id": { + "type": "string", + "title": "Key Id" + }, + "day": { + "type": "string", + "format": "date", + "title": "Day" + }, + "calls": { + "type": "integer", + "title": "Calls" + }, + "calls_4xx": { + "type": "integer", + "title": "Calls 4Xx" + }, + "calls_5xx": { + "type": "integer", + "title": "Calls 5Xx" + }, + "p50_latency_ms": { + "type": "number", + "title": "P50 Latency Ms" + }, + "p95_latency_ms": { + "type": "number", + "title": "P95 Latency Ms" + }, + "first_call_at": { + "type": "string", + "format": "date-time", + "title": "First Call At" + }, + "last_call_at": { + "type": "string", + "format": "date-time", + "title": "Last Call At" + } + }, + "type": "object", + "required": [ + "key_id", + "day", + "calls", + "calls_4xx", + "calls_5xx", + "p50_latency_ms", + "p95_latency_ms", + "first_call_at", + "last_call_at" + ], + "title": "APIKeyUsageDailyRow" + }, "APIKeyWithSecret": { "properties": { "key_id": {