Skip to content
Open
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
91 changes: 91 additions & 0 deletions app/core/api_key_usage.py
Original file line number Diff line number Diff line change
@@ -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__,
)
16 changes: 15 additions & 1 deletion app/core/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down
58 changes: 58 additions & 0 deletions app/db/api_key_usage_view.py
Original file line number Diff line number Diff line change
@@ -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
"""
27 changes: 27 additions & 0 deletions app/db/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
from .tenant_rls import TenantScopedSession

logger = logging.getLogger(__name__)
Expand All @@ -52,9 +53,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",
Expand Down Expand Up @@ -351,6 +365,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())
Expand Down Expand Up @@ -407,6 +425,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
Expand All @@ -429,6 +448,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:
Expand All @@ -451,6 +476,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(
Expand Down
25 changes: 22 additions & 3 deletions app/db/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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.
Expand Down
13 changes: 10 additions & 3 deletions app/db/tenant_rls.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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")
]

Expand Down Expand Up @@ -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)
)
Expand Down
7 changes: 7 additions & 0 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions app/middleware/head_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down
Loading