From 96aa5cf1b69f4b58f3b653a494f77f695e0af662 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:51:56 -0700 Subject: [PATCH 1/3] Add API key usage tracking (SEL-346): /v1/api-keys/usage/daily Port of archived agentmiddleware/agent-middleware-api#840, stacked on the #841 port. Migration 051 renumbered to 046 (down_revision 045_api_key_usage_events). Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/app/routers/api_keys.py | 44 +++- gateway/docs/api-key-usage.md | 3 + gateway/docs/openapi.json | 244 ++++++++++++++++++ gateway/docs/schema-046-rollout.md | 25 ++ .../versions/046_api_key_usage_reporting.py | 21 ++ gateway/tests/test_api_key_usage_migration.py | 13 +- gateway/tests/test_api_key_usage_tracking.py | 93 +++++++ 7 files changed, 441 insertions(+), 2 deletions(-) create mode 100644 gateway/docs/schema-046-rollout.md create mode 100644 gateway/migrations/versions/046_api_key_usage_reporting.py create mode 100644 gateway/tests/test_api_key_usage_tracking.py diff --git a/gateway/app/routers/api_keys.py b/gateway/app/routers/api_keys.py index 3a5ecca86..35cf6d1e4 100644 --- a/gateway/app/routers/api_keys.py +++ b/gateway/app/routers/api_keys.py @@ -6,7 +6,7 @@ from datetime import date, datetime -from fastapi import APIRouter, Depends, Header, HTTPException, Request, status +from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request, status from pydantic import BaseModel from sqlalchemy import text @@ -76,6 +76,12 @@ async def admin_api_key_usage_daily( auth: AuthContext = Depends(get_auth_context), ) -> APIKeyUsageDailyResponse: auth.require_bootstrap_admin() + return await _read_api_key_usage_daily(key_id) + + +async def _read_api_key_usage_daily( + key_id: str | None, limit: int | None = None +) -> APIKeyUsageDailyResponse: 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" @@ -85,6 +91,9 @@ async def admin_api_key_usage_daily( query += " WHERE key_id = :key_id" parameters["key_id"] = key_id query += " ORDER BY day DESC, key_id" + if limit is not None: + query += " LIMIT :limit" + parameters["limit"] = limit async with get_session_factory()() as session: result = await session.execute(text(query), parameters) return APIKeyUsageDailyResponse( @@ -95,6 +104,39 @@ async def admin_api_key_usage_daily( ) +@router.get( + "/usage/daily", + summary="Get daily API key usage statistics", + description=( + "Get aggregated daily usage statistics for API keys. " + "Admin-only endpoint; demo keys receive 403. " + "Returns call counts, error rates, latency percentiles, and first/last call timestamps." + ), +) +async def get_daily_usage_stats( + key_id: str | None = None, + limit: int = Query(default=100, ge=1, le=1000), + auth: AuthContext = Depends(get_auth_context), +) -> list[dict]: + """Expose the existing daily view through the PR #840 route shape.""" + auth.require_bootstrap_admin() + daily = await _read_api_key_usage_daily(key_id, limit) + return [ + { + "key_id": row.key_id, + "day": row.day.isoformat(), + "calls": row.calls, + "count_4xx": row.calls_4xx, + "count_5xx": row.calls_5xx, + "p50_latency_ms": row.p50_latency_ms, + "p95_latency_ms": row.p95_latency_ms, + "first_call": row.first_call_at.isoformat(), + "last_call": row.last_call_at.isoformat(), + } + for row in daily.rows + ] + + def _not_found(error: str, message: str) -> dict: """Standardized 404 error payload.""" return {"error": error, "message": message} diff --git a/gateway/docs/api-key-usage.md b/gateway/docs/api-key-usage.md index 9bfbd9754..c3e3a5b6b 100644 --- a/gateway/docs/api-key-usage.md +++ b/gateway/docs/api-key-usage.md @@ -19,3 +19,6 @@ 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. +`GET /v1/api-keys/usage/daily` also reads the same view for bootstrap admins. +It returns a list with the archived PR #840 field names and accepts optional +`key_id` and `limit` query parameters (default 100, maximum 1000). diff --git a/gateway/docs/openapi.json b/gateway/docs/openapi.json index 6d87e43c8..4520cfc59 100644 --- a/gateway/docs/openapi.json +++ b/gateway/docs/openapi.json @@ -3629,6 +3629,103 @@ } } }, + "/v1/api-keys/usage/daily": { + "get": { + "tags": [ + "API Key Management" + ], + "summary": "Get daily API key usage statistics", + "description": "Get aggregated daily usage statistics for API keys. Admin-only endpoint; demo keys receive 403. Returns call counts, error rates, latency percentiles, and first/last call timestamps.", + "operationId": "get_daily_usage_stats_v1_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": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "maximum": 1000, + "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": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": true + }, + "title": "Response Get Daily Usage Stats V1 Api Keys Usage Daily Get" + } + } + } + }, + "401": { + "description": "Missing API key" + }, + "403": { + "description": "Insufficient permissions" + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/v1/api-keys": { "post": { "tags": [ @@ -5458,6 +5555,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" + } + } + } + } + } + } + }, "/v1/demo/keys": { "get": { "tags": [ @@ -5871,6 +6042,7 @@ "use_count": { "type": "integer", "title": "Use Count", + "description": "Bounded-key budget uses, not total calls. See api_key_usage_daily.", "default": 0 } }, @@ -5896,6 +6068,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..9d1a19433 --- /dev/null +++ b/gateway/docs/schema-046-rollout.md @@ -0,0 +1,25 @@ +# Schema 046: API key usage reporting route + +Migration `046_api_key_usage_reporting` revises `045_api_key_usage_events`. +It is a no-op migration: schema 045 already created the event table, index, +and daily view proposed by the archived PR #840. No backfill is required. +The application adds the admin-only +`GET /v1/api-keys/usage/daily?key_id=apk_...&limit=100` route using that view. +The route returns the PR #840 field names (`count_4xx`, `count_5xx`, +`first_call`, `last_call`) mapped from the existing view. It exposes no raw +request data or API key values. + +## Compatibility release + +Production boot requires the database revision to match the packaged head. +Qualify a 046-compatible image and recovery artifact against a disposable +PostgreSQL upgrade from 045. Verify both admin read routes with the intended +runtime role. Record the exact image SHA, database revision, and private parity +result. These release checks have not been run in this worktree. + +## Rollback boundary + +Downgrading 046 to 045 changes only the Alembic revision marker; it does not +drop usage events. Do not restart a 045-packaged image against a database at +046. Use a qualified 046-compatible recovery image until the database and +application revisions are aligned. diff --git a/gateway/migrations/versions/046_api_key_usage_reporting.py b/gateway/migrations/versions/046_api_key_usage_reporting.py new file mode 100644 index 000000000..b04776372 --- /dev/null +++ b/gateway/migrations/versions/046_api_key_usage_reporting.py @@ -0,0 +1,21 @@ +"""Register the additional API key usage reporting route. + +Revision ID: 046_api_key_usage_reporting +Revises: 045_api_key_usage_events + +PR #841 already created the event table and daily view. PR #840's schema +objects overlap exactly, so this revision makes no database changes. +""" + +revision: str = "046_api_key_usage_reporting" +down_revision: str = "045_api_key_usage_events" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + pass + + +def downgrade() -> None: + pass diff --git a/gateway/tests/test_api_key_usage_migration.py b/gateway/tests/test_api_key_usage_migration.py index 44609c078..ffa281a76 100644 --- a/gateway/tests/test_api_key_usage_migration.py +++ b/gateway/tests/test_api_key_usage_migration.py @@ -8,7 +8,10 @@ def test_045_revision_and_daily_view(tmp_path, monkeypatch) -> None: script = ScriptDirectory.from_config(Config("alembic.ini")) - assert script.get_heads() == ["045_api_key_usage_events"] + assert script.get_heads() == ["046_api_key_usage_reporting"] + assert script.get_revision("046_api_key_usage_reporting").down_revision == ( + "045_api_key_usage_events" + ) assert script.get_revision("045_api_key_usage_events").down_revision == ( "044_receipt_resolutions" ) @@ -110,6 +113,14 @@ def test_045_revision_and_daily_view(tmp_path, monkeypatch) -> None: ), ] + command.upgrade(config, "046_api_key_usage_reporting") + engine = create_engine(f"sqlite:///{db_path}") + assert "api_key_usage_events" in inspect(engine).get_table_names() + engine.dispose() + command.downgrade(config, "045_api_key_usage_events") + engine = create_engine(f"sqlite:///{db_path}") + assert "api_key_usage_daily" in inspect(engine).get_view_names() + engine.dispose() command.downgrade(config, "044_receipt_resolutions") engine = create_engine(f"sqlite:///{db_path}") inspector = inspect(engine) diff --git a/gateway/tests/test_api_key_usage_tracking.py b/gateway/tests/test_api_key_usage_tracking.py new file mode 100644 index 000000000..27e0be012 --- /dev/null +++ b/gateway/tests/test_api_key_usage_tracking.py @@ -0,0 +1,93 @@ +"""Archived PR #840's distinct API-key usage reporting route.""" + +import pytest +from httpx import ASGITransport, AsyncClient + +from app.core.config import get_settings +from app.main import app +from app.core.api_key_usage import record_api_key_usage_event + + +@pytest.fixture +async def client(clean_database): + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as c: + yield c + + +@pytest.fixture +def admin_key(): + settings = get_settings() + return settings.VALID_API_KEYS.split(",")[0].strip() + + +async def create_test_wallet_and_key(tenant=None): + """Use the PR #840 wallet and key fixture data.""" + from app.core.dependencies import get_agent_money + from app.services.api_key_service import get_api_key_service + + wallet = await get_agent_money().create_sponsor_wallet( + sponsor_name="Test Sponsor", + email="test@example.com", + initial_credits=1000.0, + tenant=tenant, + ) + key = await get_api_key_service().create_key( + wallet_id=wallet.wallet_id, + key_name="test_key", + tenant=tenant, + ) + return key + + +@pytest.mark.asyncio +async def test_admin_can_access(client, admin_key): + response = await client.get( + "/v1/api-keys/usage/daily", headers={"X-API-Key": admin_key} + ) + assert response.status_code == 200 + assert isinstance(response.json(), list) + + +@pytest.mark.asyncio +async def test_demo_and_non_admin_keys_forbidden(client): + assert (await client.get("/v1/api-keys/usage/daily")).status_code == 401 + demo = await create_test_wallet_and_key(tenant="demo") + normal = await create_test_wallet_and_key() + for key in (demo, normal): + response = await client.get( + "/v1/api-keys/usage/daily", headers={"X-API-Key": key["api_key"]} + ) + assert response.status_code == 403 + + +@pytest.mark.asyncio +async def test_filter_and_aggregated_fields(client, admin_key): + key = await create_test_wallet_and_key() + await record_api_key_usage_event( + key_id=key["key_id"], + tenant=None, + method="POST", + endpoint="/v1/permits", + status_code=200, + latency_ms=25, + ) + response = await client.get( + "/v1/api-keys/usage/daily", + params={"key_id": key["key_id"]}, + headers={"X-API-Key": admin_key}, + ) + assert response.status_code == 200 + rows = response.json() + assert len(rows) == 1 + assert rows[0]["key_id"] == key["key_id"] + assert rows[0]["calls"] == 1 + assert { + "day", + "count_4xx", + "count_5xx", + "p50_latency_ms", + "p95_latency_ms", + "first_call", + "last_call", + } <= rows[0].keys() From 9683909e9b3aa0e01ac3c7067e8a4d5930909896 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:18:46 -0700 Subject: [PATCH 2/3] fix(api-keys): type usage query params for mypy Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/app/routers/api_keys.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gateway/app/routers/api_keys.py b/gateway/app/routers/api_keys.py index 35cf6d1e4..bb442d0f3 100644 --- a/gateway/app/routers/api_keys.py +++ b/gateway/app/routers/api_keys.py @@ -86,7 +86,7 @@ async def _read_api_key_usage_daily( "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 = {} + parameters: dict[str, str | int] = {} if key_id is not None: query += " WHERE key_id = :key_id" parameters["key_id"] = key_id From 848bde344afa99f12e5eb000853e0c44499133a8 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:00:56 -0700 Subject: [PATCH 3/3] test(api-keys): remove fabricated usage fixture records Signed-off-by: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> --- gateway/tests/test_api_key_usage_tracking.py | 48 ++++++++------------ 1 file changed, 19 insertions(+), 29 deletions(-) diff --git a/gateway/tests/test_api_key_usage_tracking.py b/gateway/tests/test_api_key_usage_tracking.py index 27e0be012..cd1a44b83 100644 --- a/gateway/tests/test_api_key_usage_tracking.py +++ b/gateway/tests/test_api_key_usage_tracking.py @@ -1,8 +1,11 @@ """Archived PR #840's distinct API-key usage reporting route.""" +from uuid import uuid4 + import pytest from httpx import ASGITransport, AsyncClient +from app.core.auth import AuthContext, get_auth_context from app.core.config import get_settings from app.main import app from app.core.api_key_usage import record_api_key_usage_event @@ -21,25 +24,6 @@ def admin_key(): return settings.VALID_API_KEYS.split(",")[0].strip() -async def create_test_wallet_and_key(tenant=None): - """Use the PR #840 wallet and key fixture data.""" - from app.core.dependencies import get_agent_money - from app.services.api_key_service import get_api_key_service - - wallet = await get_agent_money().create_sponsor_wallet( - sponsor_name="Test Sponsor", - email="test@example.com", - initial_credits=1000.0, - tenant=tenant, - ) - key = await get_api_key_service().create_key( - wallet_id=wallet.wallet_id, - key_name="test_key", - tenant=tenant, - ) - return key - - @pytest.mark.asyncio async def test_admin_can_access(client, admin_key): response = await client.get( @@ -49,23 +33,29 @@ async def test_admin_can_access(client, admin_key): assert isinstance(response.json(), list) +@pytest.mark.parametrize("tenant", ["demo", None]) @pytest.mark.asyncio -async def test_demo_and_non_admin_keys_forbidden(client): +async def test_demo_and_non_admin_keys_forbidden(client, tenant): assert (await client.get("/v1/api-keys/usage/daily")).status_code == 401 - demo = await create_test_wallet_and_key(tenant="demo") - normal = await create_test_wallet_and_key() - for key in (demo, normal): - response = await client.get( - "/v1/api-keys/usage/daily", headers={"X-API-Key": key["api_key"]} + original = app.dependency_overrides.get(get_auth_context) + try: + app.dependency_overrides[get_auth_context] = lambda: AuthContext( + source="db", raw_key="", tenant=tenant ) + response = await client.get("/v1/api-keys/usage/daily") assert response.status_code == 403 + finally: + if original is None: + app.dependency_overrides.pop(get_auth_context, None) + else: + app.dependency_overrides[get_auth_context] = original @pytest.mark.asyncio async def test_filter_and_aggregated_fields(client, admin_key): - key = await create_test_wallet_and_key() + key_id = str(uuid4()) await record_api_key_usage_event( - key_id=key["key_id"], + key_id=key_id, tenant=None, method="POST", endpoint="/v1/permits", @@ -74,13 +64,13 @@ async def test_filter_and_aggregated_fields(client, admin_key): ) response = await client.get( "/v1/api-keys/usage/daily", - params={"key_id": key["key_id"]}, + params={"key_id": key_id}, headers={"X-API-Key": admin_key}, ) assert response.status_code == 200 rows = response.json() assert len(rows) == 1 - assert rows[0]["key_id"] == key["key_id"] + assert rows[0]["key_id"] == key_id assert rows[0]["calls"] == 1 assert { "day",