diff --git a/gateway/app/core/api_key_usage.py b/gateway/app/core/api_key_usage.py new file mode 100644 index 000000000..48f157f17 --- /dev/null +++ b/gateway/app/core/api_key_usage.py @@ -0,0 +1,124 @@ +"""Metadata-only HTTP usage events for database-backed API keys.""" + +import asyncio +import logging +import time +from datetime import datetime, timedelta +from typing import Any, cast +from uuid import uuid4 + +from sqlalchemy import text +from starlette.types import ASGIApp, Message, Receive, Scope, Send + +from .auth import CREDENTIAL_ACCEPTANCE +from .config import get_settings +from .time import to_naive_utc, utc_now +from ..db.database import get_session_factory +from ..db.models import APIKeyUsageEventModel + +logger = logging.getLogger(__name__) +_USAGE_WRITE_TIMEOUT_SECONDS = 2.0 +_MAX_PRUNE_BATCH_SIZE = 1_000 + + +async def prune_api_key_usage_events( + *, batch_size: int = _MAX_PRUNE_BATCH_SIZE, now: datetime | None = None +) -> int: + """Delete at most one batch older than retention; never runs automatically.""" + retention_days = get_settings().API_KEY_USAGE_RETENTION_DAYS + if not retention_days: + return 0 + if not 1 <= batch_size <= _MAX_PRUNE_BATCH_SIZE: + raise ValueError(f"batch_size must be between 1 and {_MAX_PRUNE_BATCH_SIZE}") + cutoff = to_naive_utc(now) if now is not None else utc_now() + cutoff -= timedelta(days=retention_days) + async with get_session_factory()() as session: + result = await session.execute( + text( + "DELETE FROM api_key_usage_events WHERE id IN (" + "SELECT id FROM api_key_usage_events WHERE created_at < :cutoff " + "ORDER BY created_at, id LIMIT :batch_size)" + ), + {"cutoff": cutoff, "batch_size": batch_size}, + ) + await session.commit() + return cast(Any, result).rowcount + + +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 using a separate session after the response.""" + 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 asyncio.wait_for( + 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, + ), + timeout=_USAGE_WRITE_TIMEOUT_SECONDS, + ) + 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/gateway/app/core/auth.py b/gateway/app/core/auth.py index 690d6793d..a71d48948 100644 --- a/gateway/app/core/auth.py +++ b/gateway/app/core/auth.py @@ -100,7 +100,9 @@ def require_bootstrap_admin(self) -> None: ) -async def _key_tenant_for_auth(key_tenant: str | None, wallet_id: str) -> str | None: +async def _key_tenant_for_auth( + key_tenant: str | None, wallet_id: str, key_id: str | None = None +) -> str | None: """Apply demo confinement to the key and its owning wallet.""" from ..services.demo_tenant_boundary import ( DEMO_KEY_ROUTE_FORBIDDEN, @@ -112,6 +114,11 @@ async def _key_tenant_for_auth(key_tenant: str | None, wallet_id: str) -> str | ) tenant = await resolve_effective_tenant(key_tenant, wallet_id) + if key_id is not None: + acceptance = CREDENTIAL_ACCEPTANCE.get() + if acceptance is not None: + acceptance.key_id = key_id + acceptance.tenant = tenant if tenant != DEMO_TENANT_LABEL: return tenant if not get_settings().ENABLE_DEMO_TENANT: @@ -148,9 +155,11 @@ async def _key_tenant_for_auth(key_tenant: str | None, wallet_id: str) -> str | @dataclass class CredentialAcceptance: - """Whether ``get_auth_context`` accepted credentials during one request.""" + """Accepted credentials and any database key resolved for the request.""" accepted: bool = False + key_id: str | None = None + tenant: str | None = None # The converse signal, for RateLimitMiddleware's shared pre-auth bucket. A @@ -190,6 +199,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 @@ -311,7 +322,9 @@ async def _resolve_auth_context( if candidate: if _key_is_live(candidate, utc_now()): - await _key_tenant_for_auth(candidate.tenant, candidate.wallet_id) + await _key_tenant_for_auth( + candidate.tenant, candidate.wallet_id, candidate.key_id + ) try: db_key = await key_service.validate_key(stripped) except RuntimeError: @@ -322,7 +335,9 @@ async def _resolve_auth_context( if db_key: from ..services.demo_tenant_boundary import parse_allowlist - tenant = await _key_tenant_for_auth(db_key.tenant, db_key.wallet_id) + tenant = await _key_tenant_for_auth( + db_key.tenant, db_key.wallet_id, db_key.key_id + ) return AuthContext( source="db", raw_key=stripped, @@ -464,7 +479,9 @@ async def _auth_from_jwt(token: str) -> AuthContext: and candidate.wallet_id == payload.sub and _key_is_live(candidate, utc_now()) ): - await _key_tenant_for_auth(candidate.tenant, candidate.wallet_id) + await _key_tenant_for_auth( + candidate.tenant, candidate.wallet_id, candidate.key_id + ) if not await key_service.consume_derived_key_use(payload.key_id, payload.sub): raise HTTPException( @@ -507,7 +524,9 @@ async def _auth_from_jwt(token: str) -> AuthContext: ) from ..services.demo_tenant_boundary import parse_allowlist - tenant = await _key_tenant_for_auth(key_row.tenant, key_row.wallet_id) + tenant = await _key_tenant_for_auth( + key_row.tenant, key_row.wallet_id, key_row.key_id + ) return AuthContext( source="jwt", # Not a credential: a stable, non-secret handle for the API key that diff --git a/gateway/app/core/config.py b/gateway/app/core/config.py index 6f3bb4ed4..726ae8640 100644 --- a/gateway/app/core/config.py +++ b/gateway/app/core/config.py @@ -5,7 +5,7 @@ from decimal import Decimal from enum import Enum -from pydantic import SecretStr, field_validator +from pydantic import Field, SecretStr, field_validator from pydantic_settings import BaseSettings, SettingsConfigDict from functools import lru_cache @@ -64,6 +64,9 @@ class Settings(BaseSettings): DB_POOL_SIZE: int = 5 DB_MAX_OVERFLOW: int = 10 + # Opt-in only; no automatic usage-event cleanup is scheduled. + API_KEY_USAGE_RETENTION_DAYS: int | None = Field(default=None, ge=0) + # --- Authentication --- API_KEY_HEADER: str = "X-API-Key" # Comma-separated list of valid API keys (use a secrets manager in production) diff --git a/gateway/app/db/api_key_usage_view.py b/gateway/app/db/api_key_usage_view.py new file mode 100644 index 000000000..dc06377cb --- /dev/null +++ b/gateway/app/db/api_key_usage_view.py @@ -0,0 +1,74 @@ +"""Portable daily API-key usage view and bounded report query. + +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" + ) + + +def _daily_usage_select_sql(event_filter: str = "") -> str: + return f""" +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{event_filter} +), 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 +""" + + +CREATE_API_KEY_USAGE_DAILY_VIEW_SQL = ( + "CREATE VIEW api_key_usage_daily AS" + _daily_usage_select_sql() +) + + +def bounded_daily_usage_sql(*, filter_key: bool) -> str: + """Aggregate only events in the requested UTC window, then cap result rows.""" + event_filter = "\n WHERE created_at >= :start_at AND created_at < :end_at" + if filter_key: + event_filter += " AND key_id = :key_id" + return ( + _daily_usage_select_sql(event_filter) + + " ORDER BY day DESC, key_id LIMIT :limit" + ) diff --git a/gateway/app/db/database.py b/gateway/app/db/database.py index 89035cfc7..ecdcf09bc 100644 --- a/gateway/app/db/database.py +++ b/gateway/app/db/database.py @@ -36,6 +36,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 logger = logging.getLogger(__name__) @@ -62,9 +63,22 @@ "human_approvals", "receipt_resolutions", "resolution_chain_heads", + "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"}), "resolution_chain_heads": frozenset({"last_sequence", "last_hash"}), "receipt_resolutions": frozenset( @@ -362,6 +376,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()) @@ -418,6 +436,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 @@ -440,6 +459,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: @@ -462,6 +487,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/gateway/app/db/models.py b/gateway/app/db/models.py index 362577f5e..2ddc3e428 100644 --- a/gateway/app/db/models.py +++ b/gateway/app/db/models.py @@ -290,9 +290,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) @@ -314,6 +314,26 @@ 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"), + Index("ix_api_key_usage_events_created", "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/gateway/app/main.py b/gateway/app/main.py index e3b9b7fc3..75272c012 100644 --- a/gateway/app/main.py +++ b/gateway/app/main.py @@ -26,6 +26,7 @@ from fastapi.responses import HTMLResponse, JSONResponse from .core.auth import AuthContext, get_auth_context +from .core.api_key_usage import APIKeyUsageMiddleware from .core.build_metadata import get_build_commit_sha, get_build_provenance from .core.config import get_settings from .core.durable_state import ( @@ -582,6 +583,10 @@ def build_openapi_servers( # --- 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. +app.add_middleware(APIKeyUsageMiddleware) + # Rate limiting (enforces documented 120 req/min per API key) app.add_middleware(RateLimitMiddleware) @@ -800,6 +805,7 @@ def mount_dormant_trust_surfaces(application: FastAPI) -> None: else True ), ) +app.include_router(api_keys.admin_router) # Self-serve dev keys: the handler is triple-gated at runtime (its own # ENABLE_DEV_KEY_SELF_PROVISION flag answers 404, production-like environments diff --git a/gateway/app/middleware/head_method.py b/gateway/app/middleware/head_method.py index 2c867b5d0..07f6ff03b 100644 --- a/gateway/app/middleware/head_method.py +++ b/gateway/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/gateway/app/routers/api_keys.py b/gateway/app/routers/api_keys.py index 51258022f..10f6f950b 100644 --- a/gateway/app/routers/api_keys.py +++ b/gateway/app/routers/api_keys.py @@ -4,11 +4,18 @@ Handles API key creation, rotation, and revocation for wallet security. """ -from fastapi import APIRouter, Depends, Header, HTTPException, Request, status +from datetime import date, datetime, time, timedelta + +from fastapi import APIRouter, Depends, Header, HTTPException, Query, 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 ..db.api_key_usage_view import bounded_daily_usage_sql +from ..core.time import utc_now from ..core.wallet_resolution import resolve_wallet_id from ..services.api_key_service import ( get_api_key_service, @@ -38,6 +45,60 @@ }, ) +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 for a bounded UTC window.", +) +async def admin_api_key_usage_daily( + key_id: str | None = None, + days: int = Query(30, ge=1, le=90), + limit: int = Query(100, ge=1, le=200), + auth: AuthContext = Depends(get_auth_context), +) -> APIKeyUsageDailyResponse: + auth.require_bootstrap_admin() + today = utc_now().date() + parameters = { + "start_at": datetime.combine(today - timedelta(days=days - 1), time.min), + "end_at": datetime.combine(today + timedelta(days=1), time.min), + "limit": limit, + } + if key_id is not None: + parameters["key_id"] = key_id + async with get_session_factory()() as session: + result = await session.execute( + text(bounded_daily_usage_sql(filter_key=key_id is not None)), 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/gateway/app/schemas/billing.py b/gateway/app/schemas/billing.py index a8fc49258..36148310b 100644 --- a/gateway/app/schemas/billing.py +++ b/gateway/app/schemas/billing.py @@ -817,7 +817,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/gateway/docs/api-key-usage.md b/gateway/docs/api-key-usage.md new file mode 100644 index 000000000..fd080038f --- /dev/null +++ b/gateway/docs/api-key-usage.md @@ -0,0 +1,28 @@ +# 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 a database key is resolved produce no +event; a resolved key denied on route authorization still produces one. + +`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` computes the same aggregates from events +within the requested UTC day window. `days` defaults to 30 and is capped at +90; `limit` defaults to 100 rows and is capped at 200. Optional `key_id` +filters one key. Only bootstrap admins can access the report. + +`API_KEY_USAGE_RETENTION_DAYS` defaults to disabled (`None` or `0`). +`prune_api_key_usage_events()` deletes at most one batch of 1,000 rows per +explicit call, using a `created_at` cutoff; it is never scheduled or called +automatically. Pruning production data requires the owner's explicit approval. diff --git a/gateway/docs/openapi.json b/gateway/docs/openapi.json index f10162a32..029ddb6c9 100644 --- a/gateway/docs/openapi.json +++ b/gateway/docs/openapi.json @@ -5663,6 +5663,104 @@ } } }, + "/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 for a bounded UTC window.", + "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": "days", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "maximum": 90, + "minimum": 1, + "default": 30, + "title": "Days" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "maximum": 200, + "minimum": 1, + "default": 100, + "title": "Limit" + } + }, + { + "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" + } + } + } + } + } + } + }, "/v1/demo/keys": { "get": { "tags": [ @@ -6076,6 +6174,7 @@ "use_count": { "type": "integer", "title": "Use Count", + "description": "Bounded-key budget uses, not total calls. See api_key_usage_daily.", "default": 0 } }, @@ -6101,6 +6200,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": { diff --git a/gateway/docs/schema-046-rollout.md b/gateway/docs/schema-046-rollout.md new file mode 100644 index 000000000..49708b16b --- /dev/null +++ b/gateway/docs/schema-046-rollout.md @@ -0,0 +1,31 @@ +# Schema 046: API key usage events + +Migration `046_api_key_usage_events` revises `045_approval_gate_approvals`. 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 046 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 045-packaged image cannot restart after 046 is applied. Before applying +046, qualify a 046-compatible image and a recovery artifact against a +disposable PostgreSQL upgrade from 045. Verify the event insert, the daily +view, and the admin-only read route 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. This repository has no tenant RLS layer. The application exposes +the view through a bootstrap-admin-only route; database privileges are a +separate deployment boundary. + +## Rollback boundary + +Do not deploy a 045-packaged image against schema 046. Use a qualified +046-compatible recovery image while retaining the database at 046. Alembic +downgrade to 045 drops the view and table, permanently discarding every usage +event recorded since 046. It is a data-loss operation, not an application +rollback; never perform it while the API serves traffic. diff --git a/gateway/migrations/versions/046_api_key_usage_events.py b/gateway/migrations/versions/046_api_key_usage_events.py new file mode 100644 index 000000000..ac253ea08 --- /dev/null +++ b/gateway/migrations/versions/046_api_key_usage_events.py @@ -0,0 +1,89 @@ +"""Store per-key API call facts and expose daily aggregates. + +Revision ID: 046_api_key_usage_events +Revises: 045_approval_gate_approvals + +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 + +CREATE_API_KEY_USAGE_DAILY_VIEW_SQL = """ +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, + SUM(CASE WHEN latency_rank = p50_floor_rank THEN latency_ms * (100 - p50_remainder) / 100.0 WHEN latency_rank = p50_floor_rank + 1 THEN latency_ms * p50_remainder / 100.0 ELSE 0 END) AS p50_latency_ms, + SUM(CASE WHEN latency_rank = p95_floor_rank THEN latency_ms * (100 - p95_remainder) / 100.0 WHEN latency_rank = p95_floor_rank + 1 THEN latency_ms * p95_remainder / 100.0 ELSE 0 END) AS p95_latency_ms, + MIN(created_at) AS first_call_at, + MAX(created_at) AS last_call_at +FROM positioned +GROUP BY key_id, day +""" + +revision: str = "046_api_key_usage_events" +down_revision: str = "045_approval_gate_approvals" +branch_labels = None +depends_on = None + + +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"], + ) + op.create_index( + "ix_api_key_usage_events_created", "api_key_usage_events", ["created_at"] + ) + + op.execute(CREATE_API_KEY_USAGE_DAILY_VIEW_SQL) + + +def downgrade() -> None: + op.execute("DROP VIEW IF EXISTS api_key_usage_daily") + op.drop_index("ix_api_key_usage_events_created", table_name="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/gateway/tests/conftest.py b/gateway/tests/conftest.py index 6d765a80e..dfc913020 100644 --- a/gateway/tests/conftest.py +++ b/gateway/tests/conftest.py @@ -442,6 +442,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/gateway/tests/test_api_key_usage.py b/gateway/tests/test_api_key_usage.py new file mode 100644 index 000000000..6d31f17bf --- /dev/null +++ b/gateway/tests/test_api_key_usage.py @@ -0,0 +1,325 @@ +"""SEL-346: per-key API usage events and operator reporting.""" + +from __future__ import annotations + +import asyncio +from datetime import datetime, time, timedelta +from types import SimpleNamespace + +import pytest +from httpx import AsyncClient +from sqlalchemy import text + +from app.core import api_key_usage +from app.core.time import utc_now +from app.db.database import get_session_factory +from tests.test_demo_keys import ( + client as _client, + demo_enabled as _demo_enabled, + _issue, +) +from tests.test_trust_helpers import BOOTSTRAP_HEADERS, provision_agent_wallet + + +client = _client +demo_enabled = _demo_enabled +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()] + + +async def _set_event_times(key_id: str, times: list[datetime]) -> None: + events = await _events_for(key_id) + assert len(events) == len(times) + async with get_session_factory()() as session: + for event, created_at in zip(events, times, strict=True): + await session.execute( + text( + "UPDATE api_key_usage_events SET created_at = :created_at " + "WHERE id = :id" + ), + {"id": event["id"], "created_at": created_at}, + ) + await session.commit() + + +@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_enabled +) -> None: + wallet = await provision_agent_wallet(client) + demo = await _issue(client) + demo_headers = {"X-API-Key": demo["api_key"]} + assert ( + await client.get("/v1/me/authority", headers=wallet["agent_headers"]) + ).status_code == 200 + assert ( + await client.get("/v1/me/authority", headers=demo_headers) + ).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)).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"]] + filtered = await client.get( + DAILY, params={"key_id": wallet["key_id"]}, headers=BOOTSTRAP_HEADERS + ) + assert filtered.status_code == 200 + assert filtered.json()["rows"] == wallet_rows + 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_daily_usage_window_limit_and_invalid_bounds( + client: AsyncClient, clean_database: None +) -> None: + wallet = await provision_agent_wallet(client) + for _ in range(4): + response = await client.get("/v1/me/authority", headers=wallet["agent_headers"]) + assert response.status_code == 200 + + today = utc_now().date() + await _set_event_times( + wallet["key_id"], + [ + datetime.combine(today, time.min), + datetime.combine(today - timedelta(days=1), time.min), + datetime.combine(today - timedelta(days=2), time.min), + datetime.combine(today - timedelta(days=90), time.min), + ], + ) + response = await client.get( + DAILY, params={"key_id": wallet["key_id"]}, headers=BOOTSTRAP_HEADERS + ) + assert response.status_code == 200, response.text + assert [row["day"] for row in response.json()["rows"]] == [ + (today - timedelta(days=offset)).isoformat() for offset in range(3) + ] + + response = await client.get( + DAILY, + params={"key_id": wallet["key_id"], "days": 2}, + headers=BOOTSTRAP_HEADERS, + ) + assert response.status_code == 200, response.text + assert [row["day"] for row in response.json()["rows"]] == [ + today.isoformat(), + (today - timedelta(days=1)).isoformat(), + ] + + response = await client.get( + DAILY, + params={"key_id": wallet["key_id"], "days": 90, "limit": 1}, + headers=BOOTSTRAP_HEADERS, + ) + assert response.status_code == 200, response.text + assert [row["day"] for row in response.json()["rows"]] == [today.isoformat()] + + for params in ({"days": 0}, {"days": 91}, {"limit": 0}, {"limit": 201}): + response = await client.get(DAILY, params=params, headers=BOOTSTRAP_HEADERS) + assert response.status_code == 422, (params, response.text) + + +@pytest.mark.anyio +@pytest.mark.parametrize("retention_days", [None, 0]) +async def test_prune_usage_disabled_never_opens_session( + monkeypatch: pytest.MonkeyPatch, retention_days: int | None +) -> None: + monkeypatch.setattr( + api_key_usage, + "get_settings", + lambda: SimpleNamespace(API_KEY_USAGE_RETENTION_DAYS=retention_days), + ) + + def fail_session_factory(): + raise AssertionError("disabled pruning must not open a database session") + + monkeypatch.setattr(api_key_usage, "get_session_factory", fail_session_factory) + assert await api_key_usage.prune_api_key_usage_events() == 0 + + +@pytest.mark.anyio +async def test_prune_usage_cutoff_and_batch_cap( + client: AsyncClient, clean_database: None, monkeypatch: pytest.MonkeyPatch +) -> None: + wallet = await provision_agent_wallet(client) + for _ in range(4): + response = await client.get("/v1/me/authority", headers=wallet["agent_headers"]) + assert response.status_code == 200 + + now = utc_now().replace(microsecond=0) + cutoff = now - timedelta(days=2) + await _set_event_times( + wallet["key_id"], + [ + cutoff - timedelta(seconds=2), + cutoff - timedelta(seconds=1), + cutoff, + cutoff + timedelta(seconds=1), + ], + ) + monkeypatch.setattr( + api_key_usage, + "get_settings", + lambda: SimpleNamespace(API_KEY_USAGE_RETENTION_DAYS=2), + ) + with pytest.raises(ValueError, match="batch_size"): + await api_key_usage.prune_api_key_usage_events(batch_size=1_001, now=now) + assert await api_key_usage.prune_api_key_usage_events(batch_size=1, now=now) == 1 + assert await api_key_usage.prune_api_key_usage_events(batch_size=1, now=now) == 1 + assert await api_key_usage.prune_api_key_usage_events(batch_size=1, now=now) == 0 + assert [event["created_at"] for event in await _events_for(wallet["key_id"])] == [ + cutoff.isoformat(sep=" "), + (cutoff + timedelta(seconds=1)).isoformat(sep=" "), + ] + + +@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"]) == [] + + +@pytest.mark.anyio +async def test_slow_usage_insert_is_cancelled_without_failing_request( + client: AsyncClient, clean_database: None, monkeypatch: pytest.MonkeyPatch +) -> None: + wallet = await provision_agent_wallet(client) + cancelled = asyncio.Event() + + async def stalled_insert(*_args, **_kwargs) -> None: + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + cancelled.set() + raise + + monkeypatch.setattr(api_key_usage, "record_api_key_usage_event", stalled_insert) + monkeypatch.setattr(api_key_usage, "_USAGE_WRITE_TIMEOUT_SECONDS", 0.01) + response = await client.get("/v1/me/authority", headers=wallet["agent_headers"]) + assert response.status_code == 200, response.text + assert cancelled.is_set() + assert await _events_for(wallet["key_id"]) == [] diff --git a/gateway/tests/test_api_key_usage_migration.py b/gateway/tests/test_api_key_usage_migration.py new file mode 100644 index 000000000..8741c0251 --- /dev/null +++ b/gateway/tests/test_api_key_usage_migration.py @@ -0,0 +1,129 @@ +"""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 + +from app.db.database import CREATE_API_KEY_USAGE_DAILY_VIEW_SQL + + +def test_046_revision_and_daily_view(tmp_path, monkeypatch) -> None: + script = ScriptDirectory.from_config(Config("alembic.ini")) + assert script.get_heads() == ["046_api_key_usage_events"] + assert script.get_revision("046_api_key_usage_events").down_revision == ( + "045_approval_gate_approvals" + ) + + 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, "045_approval_gate_approvals") + command.upgrade(config, "046_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 inspector.get_view_definition("api_key_usage_daily").split() == ( + CREATE_API_KEY_USAGE_DAILY_VIEW_SQL.split() + ) + 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") + ) + assert any( + index["name"] == "ix_api_key_usage_events_created" + and index["column_names"] == ["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, "045_approval_gate_approvals") + 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/gateway/tests/test_core_db_qa.py b/gateway/tests/test_core_db_qa.py index 8987ef7b6..8c7c123a5 100644 --- a/gateway/tests/test_core_db_qa.py +++ b/gateway/tests/test_core_db_qa.py @@ -1187,6 +1187,7 @@ async def test_verify_required_schema_gate(): from sqlmodel import SQLModel import app.db.models # noqa: F401 (register tables) + from app.db.api_key_usage_view import CREATE_API_KEY_USAGE_DAILY_VIEW_SQL engine = create_async_engine("sqlite+aiosqlite:///:memory:") try: @@ -1194,6 +1195,10 @@ async def test_verify_required_schema_gate(): await verify_required_schema(engine) async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all) + with pytest.raises(SchemaInitError, match="Required database views missing"): + await verify_required_schema(engine) + async with engine.begin() as conn: + await conn.exec_driver_sql(CREATE_API_KEY_USAGE_DAILY_VIEW_SQL) await verify_required_schema(engine) finally: await engine.dispose()