Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 44 additions & 2 deletions gateway/app/routers/api_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -76,15 +76,24 @@ 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"
)
parameters = {}
parameters: dict[str, str | int] = {}
if key_id is not None:
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(
Expand All @@ -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}
Expand Down
3 changes: 3 additions & 0 deletions gateway/docs/api-key-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
97 changes: 97 additions & 0 deletions gateway/docs/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down
25 changes: 25 additions & 0 deletions gateway/docs/schema-046-rollout.md
Original file line number Diff line number Diff line change
@@ -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.
21 changes: 21 additions & 0 deletions gateway/migrations/versions/046_api_key_usage_reporting.py
Original file line number Diff line number Diff line change
@@ -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
13 changes: 12 additions & 1 deletion gateway/tests/test_api_key_usage_migration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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)
Expand Down
83 changes: 83 additions & 0 deletions gateway/tests/test_api_key_usage_tracking.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
"""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


@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()


@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.parametrize("tenant", ["demo", None])
@pytest.mark.asyncio
async def test_demo_and_non_admin_keys_forbidden(client, tenant):
assert (await client.get("/v1/api-keys/usage/daily")).status_code == 401
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_id = str(uuid4())
await record_api_key_usage_event(
key_id=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_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_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()
Loading