From 18888e5ed684fc3586a335c0f0c08b9c092063b7 Mon Sep 17 00:00:00 2001 From: JsNcAr Date: Fri, 9 Oct 2026 09:16:50 -0500 Subject: [PATCH 1/5] refactor: modern annotations (PEP 695, unions, Annotated dependencies) Replace the 16 Optional[X] annotations with X | None, declare the response envelope as a PEP 695 generic (class SuccessResponse[T](BaseModel), which pydantic 2.13 and mypy 2.4 handle), and move the eight default-value dependency parameters to Annotated through two aliases in dependencies.py: SessionDep and CurrentUserDep. Body(...) on the registration body is dropped; a single pydantic-model parameter is the body already. No behaviour change. The OpenAPI document before and after differs only in the envelope example's id, which was still an integer from before UUIDv7 ids. Co-Authored-By: Claude Fable 5.1 --- AGENTS.md | 3 +++ CHANGELOG.md | 5 +++++ src/basic_api/auth.py | 7 +++---- src/basic_api/dependencies.py | 12 ++++++++++-- src/basic_api/main.py | 28 ++++++++++++++-------------- src/basic_api/routers/auth.py | 13 ++++--------- src/basic_api/routers/users.py | 28 +++++++++++----------------- src/basic_api/schemas/response.py | 19 ++++++++++++------- src/basic_api/schemas/user.py | 19 +++++++++---------- src/basic_api/security.py | 5 ++++- src/basic_api/services/users.py | 5 ++--- 11 files changed, 77 insertions(+), 67 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 54752e3..8286372 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,6 +19,9 @@ Poetry-managed. in the change that fixes it. * **Style**: no emojis or em-dashes in code or docs; do not guess APIs, versions, flags or package names, verify in code or docs. +* **Typing**: `X | None`, never `Optional[X]`; generic classes use PEP 695 + (`class Envelope[T](BaseModel)`); route dependencies are `Annotated`, via + the `SessionDep` and `CurrentUserDep` aliases in `dependencies.py`. ## Project Structure ``` diff --git a/CHANGELOG.md b/CHANGELOG.md index 99a986d..10b9c91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,11 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versions follo `RequestBodyLimitMiddleware` answers 413 before any route runs (#13). ### Changed +- Annotations use the current syntax: `X | None` instead of `Optional[X]`, + `SuccessResponse` is a PEP 695 generic (`class SuccessResponse[T]`), and + every route dependency is `Annotated`, through the `SessionDep` and + `CurrentUserDep` aliases in `dependencies.py`. No behaviour change; the + OpenAPI document differs only in the envelope example's id, now a UUID (#15). - `JWT_SECRET_KEY` minimum follows the algorithm: 32 bytes for HS256, 48 for HS384, 64 for HS512 (RFC 7518 section 3.2), checked at startup by the tested `config.minimum_secret_bytes()`; `decode_access_token` also passes PyJWT's diff --git a/src/basic_api/auth.py b/src/basic_api/auth.py index 0aed09b..555088c 100644 --- a/src/basic_api/auth.py +++ b/src/basic_api/auth.py @@ -15,7 +15,6 @@ import logging import uuid from datetime import timedelta -from typing import Optional import bcrypt from fastapi import HTTPException, status @@ -136,7 +135,7 @@ async def get_password_hash_async(password: str) -> str: _DUMMY_PASSWORD_HASH: str = get_password_hash("_constant_time_sentinel_") -def access_token_lifetime(requested: Optional[timedelta] = None) -> timedelta: +def access_token_lifetime(requested: timedelta | None = None) -> timedelta: """ The lifetime a login token actually gets. @@ -160,7 +159,7 @@ def access_token_lifetime(requested: Optional[timedelta] = None) -> timedelta: return min(requested, maximum) -def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str: +def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str: """ Create a signed JWT with the given claims plus `iat` and `exp`. @@ -265,7 +264,7 @@ async def authenticate_user( return user -async def get_user_by_id(session: AsyncSession, user_id: uuid.UUID) -> Optional[User]: +async def get_user_by_id(session: AsyncSession, user_id: uuid.UUID) -> User | None: """ Load a user by primary key. diff --git a/src/basic_api/dependencies.py b/src/basic_api/dependencies.py index 33b73bf..4333230 100644 --- a/src/basic_api/dependencies.py +++ b/src/basic_api/dependencies.py @@ -16,10 +16,15 @@ # tokenUrl is where clients obtain tokens; Swagger's Authorize dialog uses it. oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") +# Dependency aliases: one token per dependency in a route signature, the style +# FastAPI's documentation recommends. CurrentUserDep is defined below +# get_current_user. +SessionDep = Annotated[AsyncSession, Depends(get_session)] + async def get_current_user( token: Annotated[str, Depends(oauth2_scheme)], - session: AsyncSession = Depends(get_session), + session: SessionDep, ) -> User: """ The user the bearer token belongs to, loaded from the database. @@ -42,7 +47,7 @@ async def get_current_user( Example: @router.get("/mine") - async def mine(current_user: Annotated[User, Depends(get_current_user)]): + async def mine(current_user: CurrentUserDep): return {"username": current_user.username} """ payload = decode_access_token(token) @@ -71,3 +76,6 @@ async def mine(current_user: Annotated[User, Depends(get_current_user)]): detail="This account is currently disabled", ) return user + + +CurrentUserDep = Annotated[User, Depends(get_current_user)] diff --git a/src/basic_api/main.py b/src/basic_api/main.py index 02c9ea7..1d75699 100644 --- a/src/basic_api/main.py +++ b/src/basic_api/main.py @@ -21,7 +21,7 @@ from contextlib import asynccontextmanager from datetime import timedelta -from typing import Annotated, Optional +from typing import Annotated from fastapi import Depends, FastAPI, Query, Request from fastapi.middleware.cors import CORSMiddleware @@ -29,7 +29,6 @@ from fastapi.security import OAuth2PasswordRequestForm from slowapi.errors import RateLimitExceeded from starlette.middleware.body_limit import RequestBodyLimitMiddleware -from sqlmodel.ext.asyncio.session import AsyncSession from .auth import access_token_lifetime, authenticate_user, create_access_token from .config import ( @@ -41,8 +40,8 @@ MAX_REQUEST_BODY_BYTES, ROOT_PATH, ) -from .database import engine, get_session, init_db, ping -from .dependencies import get_current_user +from .database import engine, init_db, ping +from .dependencies import CurrentUserDep, SessionDep from .exceptions import IdentifierTakenError, PasswordVerificationError from .limiter import RATE_LIMIT_LOGIN, limiter, rate_limit_exceeded_handler from .routers import auth, users @@ -53,7 +52,6 @@ HealthResponse, TokenResponse, ) -from .schemas.user import User from .security import verify_api_key SERVICE_NAME = "basic-api" @@ -167,15 +165,17 @@ async def health_check(): async def login( request: Request, form_data: Annotated[OAuth2PasswordRequestForm, Depends()], - expires_delta: Optional[timedelta] = Query( - default=None, - description=( - "Requested token lifetime, in seconds or as an ISO 8601 duration " - "(e.g. P1D). Capped at JWT_MAX_ACCESS_TOKEN_EXPIRE_MINUTES; omitted, " - "zero or negative gets JWT_ACCESS_TOKEN_EXPIRE_MINUTES." + session: SessionDep, + expires_delta: Annotated[ + timedelta | None, + Query( + description=( + "Requested token lifetime, in seconds or as an ISO 8601 duration " + "(e.g. P1D). Capped at JWT_MAX_ACCESS_TOKEN_EXPIRE_MINUTES; " + "omitted, zero or negative gets JWT_ACCESS_TOKEN_EXPIRE_MINUTES." + ), ), - ), - session: AsyncSession = Depends(get_session), + ] = None, ): """ OAuth2 password flow. Public: no API key needed, which also lets Swagger's @@ -224,7 +224,7 @@ async def login( responses=error_responses(401, 403), ) async def protected_example( - current_user: Annotated[User, Depends(get_current_user)], + current_user: CurrentUserDep, api_key: Annotated[str, Depends(verify_api_key)], ): """ diff --git a/src/basic_api/routers/auth.py b/src/basic_api/routers/auth.py index 30a5778..7c2e9c3 100644 --- a/src/basic_api/routers/auth.py +++ b/src/basic_api/routers/auth.py @@ -4,14 +4,11 @@ Thin /auth/* routes around the OAuth2 + JWT flow for frontend convenience. """ -from typing import Annotated +from fastapi import APIRouter -from fastapi import APIRouter, Depends - -from ..dependencies import get_current_user +from ..dependencies import CurrentUserDep from ..schemas import SuccessResponse, UserResponseSchema from ..schemas.errors import error_responses -from ..schemas.user import User router = APIRouter(prefix="/auth", tags=["Authentication"]) @@ -21,9 +18,7 @@ response_model=SuccessResponse[UserResponseSchema], responses=error_responses(403), ) -async def get_current_user_info( - current_user: Annotated[User, Depends(get_current_user)], -): +async def get_current_user_info(current_user: CurrentUserDep): """ The authenticated user, as stored. @@ -54,7 +49,7 @@ async def get_current_user_info( response_model=SuccessResponse[None], responses=error_responses(403), ) -async def logout(current_user: Annotated[User, Depends(get_current_user)]): +async def logout(current_user: CurrentUserDep): """ Confirm a logout. Tokens are stateless, so the client deletes its copy; nothing is invalidated server-side (see docs/known_issues.md). diff --git a/src/basic_api/routers/users.py b/src/basic_api/routers/users.py index 7b2e73b..82323a9 100644 --- a/src/basic_api/routers/users.py +++ b/src/basic_api/routers/users.py @@ -6,20 +6,16 @@ """ import logging -from typing import Annotated -from fastapi import APIRouter, Body, Depends, HTTPException, Request -from sqlmodel.ext.asyncio.session import AsyncSession +from fastapi import APIRouter, HTTPException, Request -from ..database import get_session -from ..dependencies import get_current_user +from ..dependencies import CurrentUserDep, SessionDep from ..exceptions import AppError from ..limiter import RATE_LIMIT_REGISTER, limiter from ..schemas import SuccessResponse from ..schemas.errors import error_responses from ..schemas.user import ( PasswordChangeSchema, - User, UserCreateSchema, UserDeleteSchema, UserResponseSchema, @@ -41,8 +37,8 @@ @limiter.limit(RATE_LIMIT_REGISTER) async def create_user( request: Request, - user_create: UserCreateSchema = Body(...), - session: AsyncSession = Depends(get_session), + user_create: UserCreateSchema, + session: SessionDep, ): """ Register a user. Rate-limited per client IP (RATE_LIMIT_REGISTER). @@ -86,9 +82,7 @@ async def create_user( response_model=SuccessResponse[UserResponseSchema], responses=error_responses(403), ) -async def read_current_user( - current_user: Annotated[User, Depends(get_current_user)], -): +async def read_current_user(current_user: CurrentUserDep): """ The authenticated user's profile. @@ -115,8 +109,8 @@ async def read_current_user( ) async def update_current_user( user_update: UserUpdateSchema, - current_user: Annotated[User, Depends(get_current_user)], - session: AsyncSession = Depends(get_session), + current_user: CurrentUserDep, + session: SessionDep, ): """ Update the authenticated user's profile. @@ -164,8 +158,8 @@ async def update_current_user( ) async def change_password( password_change: PasswordChangeSchema, - current_user: Annotated[User, Depends(get_current_user)], - session: AsyncSession = Depends(get_session), + current_user: CurrentUserDep, + session: SessionDep, ): """ Change the authenticated user's password. @@ -213,8 +207,8 @@ async def change_password( ) async def delete_current_user( body: UserDeleteSchema, - current_user: Annotated[User, Depends(get_current_user)], - session: AsyncSession = Depends(get_session), + current_user: CurrentUserDep, + session: SessionDep, ): """ Permanently delete the authenticated user's account. diff --git a/src/basic_api/schemas/response.py b/src/basic_api/schemas/response.py index e1d20a1..bbd88dd 100644 --- a/src/basic_api/schemas/response.py +++ b/src/basic_api/schemas/response.py @@ -5,25 +5,30 @@ string for an HTTPException and a list of validation errors for a 422. """ -from typing import Generic, Optional, TypeVar - from pydantic import BaseModel, ConfigDict, Field -T = TypeVar("T") +class SuccessResponse[T](BaseModel): + """ + Generic success response wrapper. -class SuccessResponse(BaseModel, Generic[T]): - """Generic success response wrapper.""" + `T` is the type of `data`; `SuccessResponse[UserResponseSchema]` as a + response_model names it in the OpenAPI document. PEP 695 syntax (3.12+): the + type parameter is declared in the class header, with no TypeVar or Generic. + """ success: bool = Field(default=True, description="Always true") data: T = Field(..., description="Response data") - message: Optional[str] = Field(default=None, description="Optional message") + message: str | None = Field(default=None, description="Optional message") model_config = ConfigDict( json_schema_extra={ "example": { "success": True, - "data": {"id": 123, "username": "example"}, + "data": { + "id": "0199c7a0-5f3e-7cc4-9a7b-4f1e2d3c5b6a", + "username": "example", + }, "message": "Operation completed successfully", } } diff --git a/src/basic_api/schemas/user.py b/src/basic_api/schemas/user.py index 2231a04..7644360 100644 --- a/src/basic_api/schemas/user.py +++ b/src/basic_api/schemas/user.py @@ -1,6 +1,5 @@ import uuid from datetime import datetime -from typing import Optional from pydantic import ( AwareDatetime, @@ -25,7 +24,7 @@ _HTTP_URL = TypeAdapter(HttpUrl) -def validate_http_url(value: Optional[str]) -> Optional[str]: +def validate_http_url(value: str | None) -> str | None: """ An http(s) URL as a string, or null. @@ -59,21 +58,21 @@ class UserBase(SQLModel): max_length=USERNAME_MAX_LENGTH, description="Unique username", ) - email: Optional[EmailStr] = Field( + email: EmailStr | None = Field( default=None, index=True, unique=True, max_length=EMAIL_MAX_LENGTH, description="Email address; also accepted as the login identifier", ) - phone_number: Optional[str] = Field( + phone_number: str | None = Field( default=None, index=True, unique=True, max_length=PHONE_NUMBER_MAX_LENGTH, description="Phone number; also accepted as the login identifier", ) - profile_picture_url: Optional[str] = Field( + profile_picture_url: str | None = Field( default=None, max_length=URL_MAX_LENGTH, description="http(s) URL of the profile picture", @@ -95,7 +94,7 @@ class User(UserBase, table=True): id: uuid.UUID = Field(default_factory=uuid.uuid7, primary_key=True) hashed_password: str = Field(description="bcrypt hash of the SHA-256 pre-hash") created_at: datetime = Field(default_factory=utc_now) - updated_at: Optional[datetime] = Field( + updated_at: datetime | None = Field( default=None, sa_column_kwargs={"onupdate": utc_now} ) @@ -114,13 +113,13 @@ class UserCreateSchema(UserBase): # not be able to flip (a self-disabled account could never re-enable itself), # and the password has its own route with its own confirmation. class UserUpdateSchema(SQLModel): - email: Optional[EmailStr] = Field( + email: EmailStr | None = Field( default=None, max_length=EMAIL_MAX_LENGTH, description="Email address" ) - phone_number: Optional[str] = Field( + phone_number: str | None = Field( default=None, max_length=PHONE_NUMBER_MAX_LENGTH, description="Phone number" ) - profile_picture_url: Optional[HttpUrl] = Field( + profile_picture_url: HttpUrl | None = Field( default=None, description="http(s) URL of the profile picture" ) @@ -144,4 +143,4 @@ class UserResponseSchema(UserBase): # AwareDatetime states the contract SQLModel's UTCDateTime fulfils: the values # carry a zone, and serialise with it. created_at: AwareDatetime - updated_at: Optional[AwareDatetime] = None + updated_at: AwareDatetime | None = None diff --git a/src/basic_api/security.py b/src/basic_api/security.py index dab2e93..b69c489 100644 --- a/src/basic_api/security.py +++ b/src/basic_api/security.py @@ -8,6 +8,7 @@ """ import secrets +from typing import Annotated from fastapi import HTTPException, Security, status from fastapi.security import APIKeyHeader @@ -22,7 +23,9 @@ ) -async def verify_api_key(x_api_key: str | None = Security(api_key_header)) -> str: +async def verify_api_key( + x_api_key: Annotated[str | None, Security(api_key_header)], +) -> str: """ Dependency for routes that require the client API key. diff --git a/src/basic_api/services/users.py b/src/basic_api/services/users.py index aa584dd..c15ef5f 100644 --- a/src/basic_api/services/users.py +++ b/src/basic_api/services/users.py @@ -7,7 +7,6 @@ import logging import uuid -from typing import Optional from sqlalchemy.exc import IntegrityError from sqlmodel import col, select @@ -37,8 +36,8 @@ async def _assert_identifiers_free( session: AsyncSession, - values: dict[str, Optional[str]], - exclude_user_id: Optional[uuid.UUID] = None, + values: dict[str, str | None], + exclude_user_id: uuid.UUID | None = None, ) -> None: """ Raise IdentifierTakenError if any given identifier belongs to another account. From 36b50473d1293bf8210c615410dba829d97bb1ba Mon Sep 17 00:00:00 2001 From: JsNcAr Date: Fri, 9 Oct 2026 09:21:40 -0500 Subject: [PATCH 2/5] feat: logging configuration and X-Request-ID Configure logging once, at startup, from the lifespan: LOG_LEVEL and LOG_FORMAT (json lines in production by default, text elsewhere) drive a dictConfig with a QueueHandler on the root logger and a QueueListener thread writing to stderr, so a slow destination never blocks the event loop. The listener runs as a context manager (Python 3.14) for the app's lifetime and drains on shutdown. uvicorn's loggers are untouched. Every response carries X-Request-ID: a supplied id is kept when it is 1 to 128 characters of [A-Za-z0-9._-], else a UUIDv7 is generated. The id lives in a context variable set by a pure ASGI middleware (outermost, so 413s and CORS preflights carry it too) and is stamped on every log record as it enters the queue, on the task that logged. Known Issues: the logging entry becomes "No metrics, tracing or error tracking", keeping only what is still missing. Co-Authored-By: Claude Fable 5.1 --- .env.example | 7 ++ AGENTS.md | 5 ++ CHANGELOG.md | 7 ++ docs/api.md | 5 ++ docs/known_issues.md | 18 ++-- docs/setup.md | 19 ++++ src/basic_api/config.py | 42 +++++++++ src/basic_api/logging_config.py | 148 ++++++++++++++++++++++++++++++++ src/basic_api/main.py | 30 +++++-- src/basic_api/request_id.py | 69 +++++++++++++++ tests/test_config.py | 21 ++++- tests/test_logging_config.py | 99 +++++++++++++++++++++ tests/test_request_id.py | 67 +++++++++++++++ 13 files changed, 521 insertions(+), 16 deletions(-) create mode 100644 src/basic_api/logging_config.py create mode 100644 src/basic_api/request_id.py create mode 100644 tests/test_logging_config.py create mode 100644 tests/test_request_id.py diff --git a/.env.example b/.env.example index 61837d7..7cf8bf0 100644 --- a/.env.example +++ b/.env.example @@ -13,6 +13,13 @@ ENVIRONMENT=development # Path prefix when served behind a reverse proxy, e.g. /api-name; unset = none. # ROOT_PATH= +# --- Logging --- +# DEBUG, INFO, WARNING, ERROR or CRITICAL +LOG_LEVEL=INFO +# json (one object per line, for collectors) or text; unset = json in +# production, text elsewhere. +# LOG_FORMAT=text + # --- CORS (comma-separated) --- # "*" suits native apps; a browser frontend should list its origins. CORS_ORIGINS=* diff --git a/AGENTS.md b/AGENTS.md index 8286372..7770377 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,6 +15,9 @@ Poetry-managed. response; log it with `logger.exception` and answer a generic message. * **Docstrings**: Google style (`Args`, `Returns`, `Raises`, `Example`); route docstrings render in Swagger, keep the curl examples current. +* **Logging**: `logging.getLogger(__name__)` in a module; only + `logging_config.py` configures logging, from the lifespan in `main.py`. + Never log a secret, a password or a token; the request id is added for you. * **Known issues**: `docs/known_issues.md` is the single list; remove an entry in the change that fixes it. * **Style**: no emojis or em-dashes in code or docs; do not guess APIs, @@ -33,6 +36,8 @@ src/basic_api/ dependencies.py # get_current_user (token -> User from the database) database.py # engine, session factory, create_all, ping limiter.py # shared rate limiter and 429 response + logging_config.py # level, JSON/text lines, queue listener, request id on lines + request_id.py # X-Request-ID middleware (contextvar for the log lines) exceptions.py # domain exceptions utils.py # utc_now routers/ # auth (/api/auth), users (/api/users) diff --git a/CHANGELOG.md b/CHANGELOG.md index 10b9c91..3c8f290 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,13 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versions follo - `cryptography` 46.0.3 to 50.0.2, closing seven published advisories (#7). ### Added +- Logging configuration (`logging_config.py`): `LOG_LEVEL`, `LOG_FORMAT` + (`json` lines in production by default, `text` elsewhere), and a + QueueHandler/QueueListener pipeline from the standard library so that + writing a line never blocks the event loop; the listener runs as a context + manager (Python 3.14) for the app's lifetime. `X-Request-ID` on every + response (`request_id.py`; a supplied id is kept when it is safe, otherwise + a UUIDv7 is generated) and on every log line of that request (#16). - Response models for `/`, `/health`, `/token` and `/protected-example`, so the OpenAPI document has a schema for every response (the token response had none) and FastAPI 0.130+ serialises them with pydantic-core; every status a diff --git a/docs/api.md b/docs/api.md index 22ada17..0042aa0 100644 --- a/docs/api.md +++ b/docs/api.md @@ -23,6 +23,11 @@ exception is `413`, which Starlette answers as plain text before the app runs. {"detail": "Not a valid request"} ``` +**Request id**: every response carries `X-Request-ID`, generated (a UUIDv7) +unless the request supplied an acceptable one (1 to 128 characters of letters, +digits, `.`, `_` or `-`). The server's log lines for that request carry the +same id; quote it when reporting a problem. + **Auth** column: `key` is the `X-API-Key` header, `token` is `Authorization: Bearer `. See [Authentication](authentication.md) for the error tables common to all protected routes. diff --git a/docs/known_issues.md b/docs/known_issues.md index 5083d9b..d5512a5 100644 --- a/docs/known_issues.md +++ b/docs/known_issues.md @@ -155,19 +155,19 @@ or every client shares one bucket. **Fix:** shared storage for the counts (slowapi supports Redis) when running more than one worker. -### No logging configuration or observability +### No metrics, tracing or error tracking **Where:** application-wide. -Modules call `logging.getLogger(__name__)` but nothing configures logging; -output and level are whatever uvicorn sets. No request ids, no structured logs, -no metrics, no error tracking. +Logging is configured (`logging_config.py`: levels, JSON or text lines, a +request id on every line and response), but there are no metrics, no traces +and no error tracker: a 500 is a log line, not an alert. -**Fix:** configure logging at startup (JSON in production), a request-id -middleware, and an error tracker. -For tracing and metrics, FastAPI 0.142's native OpenTelemetry (`FastAPI(telemetry={...})`, -with `auto_configure` reading the standard `OTEL_*` variables) is the path; it -needs `opentelemetry-sdk` and an OTLP exporter installed to emit anything. +**Fix:** for tracing and metrics, FastAPI 0.142's native OpenTelemetry +(`FastAPI(telemetry={...})`, with `auto_configure` reading the standard `OTEL_*` +variables) is the path; it needs `opentelemetry-sdk` and an OTLP exporter +installed to emit anything. An error tracker (Sentry or similar) hooks in as a +logging handler or ASGI middleware. ### CI has no coverage or secret scan diff --git a/docs/setup.md b/docs/setup.md index d460d92..43c5e77 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -42,6 +42,8 @@ with a comment; the table below is the summary. | `APP_VERSION` | | the installed package version | Reported by `GET /` and the OpenAPI document | | `ROOT_PATH` | | empty | Path prefix when served behind a reverse proxy | | `CORS_ORIGINS`, `CORS_METHODS`, `CORS_HEADERS` | | `*` | Comma-separated; a browser frontend should list its origins | +| `LOG_LEVEL` | | `INFO` | `DEBUG`, `INFO`, `WARNING`, `ERROR` or `CRITICAL` | +| `LOG_FORMAT` | | by `ENVIRONMENT` | `json` (one object per line) or `text`; `json` in production by default | | `DATABASE_ECHO` | | `false` | Log every SQL statement (development only) | | `RATE_LIMIT_LOGIN` | | `60/minute` | Per client IP on `POST /token` | | `RATE_LIMIT_REGISTER` | | `10/minute` | Per client IP on `POST /api/users/` | @@ -67,6 +69,23 @@ Behind a reverse proxy under a path prefix, set `ROOT_PATH`. uvicorn trusts `X-Forwarded-For` from `127.0.0.1` by default; if the proxy runs elsewhere, add `--forwarded-allow-ips `, or every client shares one rate-limit bucket. +## Logging + +Every log line from the application goes through one pipeline, configured in +`src/basic_api/logging_config.py` when the app starts: a queue on the root +logger, and a thread that writes to stderr, so a slow destination never stalls +a request. `LOG_LEVEL` sets the threshold; `LOG_FORMAT` picks the line format, +`text` for a terminal and `json` (one object per line, with `timestamp`, +`level`, `logger`, `message`, `request_id` and `exception` when there is one) +for a log collector. Production defaults to `json`. uvicorn's own startup and +access lines are not affected; configure those with uvicorn's `--log-config` +if needed. + +Every response carries an `X-Request-ID` header and the log lines written while +handling that request carry the same id. A gateway or client can send its own +(1 to 128 characters of letters, digits, `.`, `_` or `-`); anything else is +replaced by a generated UUIDv7, so the id is safe to put in a log. + ## Testing Database-backed tests need a PostgreSQL database the test user can create tables diff --git a/src/basic_api/config.py b/src/basic_api/config.py index a8411ea..db7d251 100644 --- a/src/basic_api/config.py +++ b/src/basic_api/config.py @@ -11,6 +11,7 @@ `name` in pyproject.toml. """ +import logging import os import sys from importlib.metadata import PackageNotFoundError, version @@ -71,11 +72,52 @@ def docs_enabled(environment: str, enable_docs: str | None) -> bool: return enable_docs.strip().lower() in ("1", "true", "yes", "on") +_LOG_FORMATS = ("json", "text") + + +def log_format(environment: str, raw: str | None) -> str: + """ + The log line format: JSON lines in production, readable text elsewhere. + + LOG_FORMAT overrides either way, so a production box can be read by eye + during an incident and a staging one can feed a collector. + + Args: + environment: Value of ENVIRONMENT, already lower-cased. + raw: Raw value of LOG_FORMAT, or None when unset. + + Returns: + "json" or "text". + + Raises: + ValueError: LOG_FORMAT is set to something else. + """ + if raw is None or raw.strip() == "": + return "json" if environment == "production" else "text" + value = raw.strip().lower() + if value not in _LOG_FORMATS: + raise ValueError(f"LOG_FORMAT={raw!r} is not one of " + ", ".join(_LOG_FORMATS)) + return value + + # --- Application ------------------------------------------------------------- ENVIRONMENT = os.getenv("ENVIRONMENT", "development").strip().lower() ENABLE_DOCS = docs_enabled(ENVIRONMENT, os.getenv("ENABLE_DOCS")) +# --- Logging ----------------------------------------------------------------- +# Applied by logging_config.py when the app starts; uvicorn's own loggers are +# not affected. +LOG_LEVEL = (os.getenv("LOG_LEVEL") or "INFO").strip().upper() +if LOG_LEVEL not in logging.getLevelNamesMapping(): + raise RuntimeError( + f"LOG_LEVEL={LOG_LEVEL!r} is not one of DEBUG, INFO, WARNING, ERROR, CRITICAL" + ) +try: + LOG_FORMAT = log_format(ENVIRONMENT, os.getenv("LOG_FORMAT")) +except ValueError as e: + raise RuntimeError(str(e)) + def _package_version() -> str: """The version in pyproject.toml, as installed; one source for every place.""" diff --git a/src/basic_api/logging_config.py b/src/basic_api/logging_config.py new file mode 100644 index 0000000..7b79fa9 --- /dev/null +++ b/src/basic_api/logging_config.py @@ -0,0 +1,148 @@ +""" +Logging: level, format and a queue so that writing a line never blocks the +event loop. + +Modules log through `logging.getLogger(__name__)` and nothing else; this module +is the only place that configures logging, and the lifespan in main.py is the +only caller. uvicorn's own loggers (`uvicorn`, `uvicorn.access`) keep their +handlers and do not propagate, so they are untouched here. + +The pipeline is the standard-library one from the logging cookbook: the root +logger has a single QueueHandler; a QueueListener thread takes records off the +queue and writes them to stderr. A blocking `write` to a slow terminal, a pipe +or a file therefore never stalls a request. `logging.config.dictConfig` builds +the handler and its listener (Python 3.12+); the listener is started and +stopped as a context manager (Python 3.14) around the application's lifetime. + +Every line carries the request id set by request_id.py, in a `request_id` +field (JSON) or in brackets (text). +""" + +import json +import logging +import logging.config +import logging.handlers +from contextvars import ContextVar +from datetime import UTC, datetime +from typing import Any + +from .config import LOG_FORMAT, LOG_LEVEL + +# The id of the request being handled on this task, or None outside a request. +# Set by RequestIdMiddleware; read when a record enters the queue. +request_id_var: ContextVar[str | None] = ContextVar("request_id", default=None) + +QUEUE_HANDLER_NAME = "queue" +TEXT_FORMAT = "%(asctime)s %(levelname)s %(name)s [%(request_id)s] %(message)s" + + +class ContextQueueHandler(logging.handlers.QueueHandler): + """ + QueueHandler that stamps the request id and queues the record as it is. + + The base `prepare` renders the message and drops `exc_info` so that the + record can be pickled for another process. The listener here runs in a + thread of the same process, so the record goes through untouched and the + formatter on the other side still sees the exception. The request id is + read here, on the task that logged, because the listener thread has no + request context. + """ + + def prepare(self, record: logging.LogRecord) -> logging.LogRecord: + record.request_id = request_id_var.get() or "" + return record + + +class JsonFormatter(logging.Formatter): + """ + One JSON object per line, for log collectors. + + Fields: `timestamp` (UTC, ISO 8601, milliseconds), `level`, `logger`, + `message`, `request_id`, plus `exception` and `stack` when the record has + them. Values that are not JSON types are rendered with `str`. + """ + + def format(self, record: logging.LogRecord) -> str: + entry: dict[str, Any] = { + "timestamp": datetime.fromtimestamp(record.created, UTC).isoformat( + timespec="milliseconds" + ), + "level": record.levelname, + "logger": record.name, + "message": record.getMessage(), + "request_id": getattr(record, "request_id", ""), + } + if record.exc_info: + entry["exception"] = self.formatException(record.exc_info) + if record.stack_info: + entry["stack"] = self.formatStack(record.stack_info) + return json.dumps(entry, default=str) + + +def build_config(level: str, fmt: str) -> dict[str, Any]: + """ + The dictConfig dictionary for the given level and format. + + Args: + level: A logging level name, e.g. "INFO" (validated in config.py). + fmt: "json" or "text" (validated in config.py). + + Returns: + A dictionary for `logging.config.dictConfig`: a `console` handler on + stderr behind a `queue` handler on the root logger. Existing loggers + are left enabled, so uvicorn's keep working. + """ + return { + "version": 1, + "disable_existing_loggers": False, + "formatters": { + "json": {"()": JsonFormatter}, + "text": {"format": TEXT_FORMAT}, + }, + "handlers": { + "console": { + "class": "logging.StreamHandler", + "stream": "ext://sys.stderr", + "formatter": fmt, + }, + QUEUE_HANDLER_NAME: { + # "class", not "()": only the class path builds the listener from + # "handlers" (dictConfig's QueueHandler special case). + "class": ContextQueueHandler, + "handlers": ["console"], + "respect_handler_level": True, + }, + }, + "root": {"level": level, "handlers": [QUEUE_HANDLER_NAME]}, + } + + +def configure_logging( + level: str = LOG_LEVEL, fmt: str = LOG_FORMAT +) -> logging.handlers.QueueListener: + """ + Apply the configuration and return the listener to run it. + + The listener is not started here: use the returned object as a context + manager (`with configure_logging(): ...`), which starts its thread on + entry and stops it, draining the queue, on exit. + + Args: + level: Logging level name; defaults to LOG_LEVEL. + fmt: "json" or "text"; defaults to LOG_FORMAT. + + Returns: + The QueueListener that dictConfig created for the queue handler. + + Example: + with configure_logging(): + logging.getLogger(__name__).info("ready") + """ + logging.config.dictConfig(build_config(level, fmt)) + handler = logging.getHandlerByName(QUEUE_HANDLER_NAME) + if ( + not isinstance(handler, logging.handlers.QueueHandler) + or handler.listener is None + ): + raise RuntimeError("logging configuration did not produce a queue listener") + return handler.listener diff --git a/src/basic_api/main.py b/src/basic_api/main.py index 1d75699..6f8580b 100644 --- a/src/basic_api/main.py +++ b/src/basic_api/main.py @@ -19,6 +19,7 @@ uvicorn basic_api.main:app --host 0.0.0.0 --port 8000 --app-dir src """ +import logging from contextlib import asynccontextmanager from datetime import timedelta from typing import Annotated @@ -37,6 +38,7 @@ CORS_METHODS, CORS_ORIGINS, ENABLE_DOCS, + ENVIRONMENT, MAX_REQUEST_BODY_BYTES, ROOT_PATH, ) @@ -44,6 +46,8 @@ from .dependencies import CurrentUserDep, SessionDep from .exceptions import IdentifierTakenError, PasswordVerificationError from .limiter import RATE_LIMIT_LOGIN, limiter, rate_limit_exceeded_handler +from .logging_config import configure_logging +from .request_id import REQUEST_ID_HEADER, RequestIdMiddleware from .routers import auth, users from .schemas.errors import error_responses from .schemas.system import ( @@ -56,14 +60,22 @@ SERVICE_NAME = "basic-api" +logger = logging.getLogger(__name__) + @asynccontextmanager async def lifespan(app: FastAPI): - await init_db() - yield - # Close pooled connections on the way out instead of letting the process - # drop them, which PostgreSQL logs as aborted connections. - await engine.dispose() + # The listener thread that writes log lines runs for exactly as long as the + # app does; leaving the block drains the queue, so the last lines are not + # lost on shutdown. + with configure_logging(): + logger.info("Starting %s %s (%s)", SERVICE_NAME, APP_VERSION, ENVIRONMENT) + await init_db() + yield + # Close pooled connections on the way out instead of letting the process + # drop them, which PostgreSQL logs as aborted connections. + await engine.dispose() + logger.info("Stopped %s", SERVICE_NAME) app = FastAPI( @@ -99,7 +111,9 @@ def handler(request: Request, exc: Exception) -> JSONResponse: # Middleware order: each add_middleware() wraps the ones before it, so the last # added runs first. The body limit goes in first so that CORS, added after it, -# is outermost and a 413 still carries CORS headers for a browser client. +# wraps it and a 413 still carries CORS headers for a browser client; the +# request id goes in last, outermost, so that every response has one, 413s and +# CORS preflights included. # Starlette's own `max_body_size` parameter is not forwarded by FastAPI(), hence # the middleware directly. app.add_middleware(RequestBodyLimitMiddleware, max_body_size=MAX_REQUEST_BODY_BYTES) @@ -109,8 +123,12 @@ def handler(request: Request, exc: Exception) -> JSONResponse: allow_origins=CORS_ORIGINS, allow_methods=CORS_METHODS, allow_headers=CORS_HEADERS, + # Let a browser client read the id off the response. + expose_headers=[REQUEST_ID_HEADER], ) +app.add_middleware(RequestIdMiddleware) + @app.get("/", response_model=BannerResponse) async def root(): diff --git a/src/basic_api/request_id.py b/src/basic_api/request_id.py new file mode 100644 index 0000000..ce34aef --- /dev/null +++ b/src/basic_api/request_id.py @@ -0,0 +1,69 @@ +""" +A request id on every response and every log line. + +The client may send its own in `X-Request-ID` (a gateway usually does); it is +kept when it is 1 to 128 characters of letters, digits, dot, underscore or +hyphen, and replaced otherwise so that a log line never carries arbitrary +input. Without one, the API generates a UUIDv7 (Python 3.14), which sorts by +time, so ids in a log are in request order. + +Pure ASGI middleware, not BaseHTTPMiddleware: it costs nothing per request, +works with streaming responses, and the context variable it sets is visible to +the route and to everything the route awaits. +""" + +import re +import uuid + +from starlette.datastructures import Headers, MutableHeaders +from starlette.types import ASGIApp, Message, Receive, Scope, Send + +from .logging_config import request_id_var + +REQUEST_ID_HEADER = "X-Request-ID" +_VALID_REQUEST_ID = re.compile(r"[A-Za-z0-9._-]{1,128}") + + +def resolve_request_id(supplied: str | None) -> str: + """ + The id a request gets: the supplied one when acceptable, else a new UUIDv7. + + Args: + supplied: Value of the incoming X-Request-ID header, or None. + + Returns: + The id to use for the request. + """ + if supplied is not None and _VALID_REQUEST_ID.fullmatch(supplied): + return supplied + return str(uuid.uuid7()) + + +class RequestIdMiddleware: + """ + Set `request_id_var` for the request and echo the id on the response. + + Args: + app: The ASGI application to wrap. + """ + + 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 + + request_id = resolve_request_id(Headers(scope=scope).get(REQUEST_ID_HEADER)) + + async def send_with_id(message: Message) -> None: + if message["type"] == "http.response.start": + MutableHeaders(scope=message).append(REQUEST_ID_HEADER, request_id) + await send(message) + + token = request_id_var.set(request_id) + try: + await self.app(scope, receive, send_with_id) + finally: + request_id_var.reset(token) diff --git a/tests/test_config.py b/tests/test_config.py index c76e30e..63457c3 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -5,7 +5,7 @@ import pytest from basic_api import config -from basic_api.config import csv_list, docs_enabled +from basic_api.config import csv_list, docs_enabled, log_format @pytest.mark.parametrize( @@ -54,3 +54,22 @@ def test_secret_minimum_is_the_hash_output_size(algorithm, minimum): def test_secret_minimum_rejects_algorithms_this_api_does_not_allow(): with pytest.raises(ValueError): config.minimum_secret_bytes("RS256") + + +@pytest.mark.parametrize( + "environment, raw, expected", + [ + ("development", None, "text"), + ("staging", "", "text"), + ("production", None, "json"), + ("production", "text", "text"), + ("development", " JSON ", "json"), + ], +) +def test_log_format_is_json_in_production_unless_overridden(environment, raw, expected): + assert log_format(environment, raw) == expected + + +def test_log_format_rejects_unknown_values(): + with pytest.raises(ValueError): + log_format("development", "xml") diff --git a/tests/test_logging_config.py b/tests/test_logging_config.py new file mode 100644 index 0000000..cb12a64 --- /dev/null +++ b/tests/test_logging_config.py @@ -0,0 +1,99 @@ +""" +Logging pipeline: formatter output, the dictConfig shape, and the listener's +lifetime. No database. +""" + +import io +import json +import logging +import logging.handlers + +from basic_api.logging_config import ( + QUEUE_HANDLER_NAME, + ContextQueueHandler, + JsonFormatter, + build_config, + configure_logging, + request_id_var, +) + + +def _record(message="hello %s", args=("world",), exc_info=None): + return logging.LogRecord( + name="basic_api.test", + level=logging.INFO, + pathname=__file__, + lineno=1, + msg=message, + args=args, + exc_info=exc_info, + ) + + +def test_json_formatter_emits_one_object_with_the_expected_fields(): + record = _record() + record.request_id = "req-1" + entry = json.loads(JsonFormatter().format(record)) + assert entry["message"] == "hello world" + assert entry["level"] == "INFO" + assert entry["logger"] == "basic_api.test" + assert entry["request_id"] == "req-1" + # Aware UTC timestamp: ends with the zone offset. + assert entry["timestamp"].endswith("+00:00") + assert "exception" not in entry + + +def test_json_formatter_includes_the_exception_text(): + try: + raise ValueError("boom") + except ValueError as e: + record = _record(exc_info=(type(e), e, e.__traceback__)) + entry = json.loads(JsonFormatter().format(record)) + assert "ValueError: boom" in entry["exception"] + + +def test_queue_handler_stamps_the_request_id_and_keeps_the_record(): + handler = ContextQueueHandler(queue=None) + record = _record() + token = request_id_var.set("req-2") + try: + prepared = handler.prepare(record) + finally: + request_id_var.reset(token) + assert prepared is record + assert record.request_id == "req-2" + assert request_id_var.get() is None + assert handler.prepare(_record()).request_id == "" + + +def test_build_config_routes_the_root_logger_through_the_queue(): + config = build_config("DEBUG", "json") + assert config["disable_existing_loggers"] is False + queue = config["handlers"][QUEUE_HANDLER_NAME] + assert queue["handlers"] == ["console"] + assert queue["respect_handler_level"] is True + assert config["root"] == {"level": "DEBUG", "handlers": [QUEUE_HANDLER_NAME]} + assert config["handlers"]["console"]["formatter"] == "json" + + +def test_listener_runs_for_the_block_and_delivers_lines_with_the_request_id(): + listener = configure_logging("INFO", "text") + assert isinstance(listener, logging.handlers.QueueListener) + captured = io.StringIO() + # The console handler is the listener's only target; point it at a buffer. + (console,) = listener.handlers + assert isinstance(console, logging.StreamHandler) + console.setStream(captured) + assert listener._thread is None + with listener: + assert listener._thread is not None + token = request_id_var.set("req-3") + try: + logging.getLogger("basic_api.test").info("inside the block") + finally: + request_id_var.reset(token) + # Stopped and drained: the line reached the stream in the listener thread. + assert listener._thread is None + assert "basic_api.test [req-3] inside the block" in captured.getvalue() + # Leave the test process with a configuration that writes nowhere exotic. + logging.getLogger().handlers.clear() diff --git a/tests/test_request_id.py b/tests/test_request_id.py new file mode 100644 index 0000000..3566cbd --- /dev/null +++ b/tests/test_request_id.py @@ -0,0 +1,67 @@ +""" +X-Request-ID on responses and in the request context. No database: GET / and +a bare ASGI app are enough. +""" + +import uuid + +import pytest +from httpx import ASGITransport, AsyncClient + +from basic_api.logging_config import request_id_var +from basic_api.main import app +from basic_api.request_id import ( + REQUEST_ID_HEADER, + RequestIdMiddleware, + resolve_request_id, +) + + +def bare_client(): + return AsyncClient(transport=ASGITransport(app=app), base_url="http://test") + + +async def test_every_response_carries_a_generated_uuid7(): + async with bare_client() as client: + response = await client.get("/") + assert response.status_code == 200 + assert uuid.UUID(response.headers[REQUEST_ID_HEADER]).version == 7 + + +async def test_an_acceptable_supplied_id_is_echoed(): + async with bare_client() as client: + response = await client.get("/", headers={REQUEST_ID_HEADER: "gw-42.a_b"}) + assert response.headers[REQUEST_ID_HEADER] == "gw-42.a_b" + + +@pytest.mark.parametrize("bad", ["", "x" * 129, "has space", "new\nline", "a;b"]) +def test_an_unacceptable_supplied_id_is_replaced(bad): + resolved = resolve_request_id(bad) + assert resolved != bad + assert uuid.UUID(resolved).version == 7 + + +def test_none_gets_a_generated_id(): + assert uuid.UUID(resolve_request_id(None)).version == 7 + + +async def test_the_context_variable_is_set_during_the_call_and_reset_after(): + seen = {} + + async def inner(scope, receive, send): + seen["id"] = request_id_var.get() + raise RuntimeError("route failed") + + middleware = RequestIdMiddleware(inner) + scope = {"type": "http", "headers": [(b"x-request-id", b"ctx-1")]} + + async def receive(): + return {"type": "http.request"} + + async def send(message): + pass + + with pytest.raises(RuntimeError): + await middleware(scope, receive, send) + assert seen["id"] == "ctx-1" + assert request_id_var.get() is None From 1fa09879b719e38e99a75270aa47eba1e1cbea38 Mon Sep 17 00:00:00 2001 From: JsNcAr Date: Fri, 9 Oct 2026 09:22:36 -0500 Subject: [PATCH 3/5] feat: X-RateLimit headers on the rate-limited routes Limiter(headers_enabled=True): POST /token and POST /api/users/ answer with X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset so a client can pace itself before the 429. slowapi writes them onto the route's `response: Response` parameter when the route returns a model, hence the parameter on both routes. The custom 429 handler and its Retry-After are unchanged. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 3 +++ docs/api.md | 4 ++++ src/basic_api/limiter.py | 7 ++++++- src/basic_api/main.py | 4 +++- src/basic_api/routers/users.py | 4 +++- tests/test_limiter.py | 36 ++++++++++++++++++++++++++++++++-- tests/test_rate_limit.py | 22 +++++++++++++++++++++ 7 files changed, 75 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c8f290..2360cf7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,9 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versions follo manager (Python 3.14) for the app's lifetime. `X-Request-ID` on every response (`request_id.py`; a supplied id is kept when it is safe, otherwise a UUIDv7 is generated) and on every log line of that request (#16). +- `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` on the + responses of the two rate-limited routes (slowapi `headers_enabled`), so a + client can pace itself before the `429` (#16). - Response models for `/`, `/health`, `/token` and `/protected-example`, so the OpenAPI document has a schema for every response (the token response had none) and FastAPI 0.130+ serialises them with pydantic-core; every status a diff --git a/docs/api.md b/docs/api.md index 0042aa0..16df81f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -28,6 +28,10 @@ unless the request supplied an acceptable one (1 to 128 characters of letters, digits, `.`, `_` or `-`). The server's log lines for that request carry the same id; quote it when reporting a problem. +**Rate limits**: `POST /token` and `POST /api/users/` answer with +`X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` (Unix +time at which the window resets); over the limit, a `429` with `Retry-After`. + **Auth** column: `key` is the `X-API-Key` header, `token` is `Authorization: Bearer `. See [Authentication](authentication.md) for the error tables common to all protected routes. diff --git a/src/basic_api/limiter.py b/src/basic_api/limiter.py index d63b357..486a941 100644 --- a/src/basic_api/limiter.py +++ b/src/basic_api/limiter.py @@ -7,6 +7,11 @@ Limits are per client IP, as uvicorn sees it (behind a reverse proxy, make sure uvicorn trusts the proxy's forwarded headers), and per process: with several workers each keeps its own count, so the effective limit is multiplied. + +A limited route answers with X-RateLimit-Limit, X-RateLimit-Remaining and +X-RateLimit-Reset (Unix time), so a client can pace itself before a 429. slowapi +writes them onto the route's `response: Response` parameter, which is why the +limited routes declare one they never touch. """ from fastapi import Request @@ -28,7 +33,7 @@ except ValueError as e: raise RuntimeError(f"{_name}={_value!r} is not a valid rate limit: {e}") -limiter = Limiter(key_func=get_remote_address) +limiter = Limiter(key_func=get_remote_address, headers_enabled=True) def rate_limit_exceeded_handler(request: Request, exc: Exception) -> JSONResponse: diff --git a/src/basic_api/main.py b/src/basic_api/main.py index 6f8580b..11fae8b 100644 --- a/src/basic_api/main.py +++ b/src/basic_api/main.py @@ -24,7 +24,7 @@ from datetime import timedelta from typing import Annotated -from fastapi import Depends, FastAPI, Query, Request +from fastapi import Depends, FastAPI, Query, Request, Response from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from fastapi.security import OAuth2PasswordRequestForm @@ -182,6 +182,7 @@ async def health_check(): @limiter.limit(RATE_LIMIT_LOGIN) async def login( request: Request, + response: Response, # slowapi writes the X-RateLimit headers onto it form_data: Annotated[OAuth2PasswordRequestForm, Depends()], session: SessionDep, expires_delta: Annotated[ @@ -203,6 +204,7 @@ async def login( Args: request: Needed by the rate limiter (injected). + response: Receives the X-RateLimit headers from the limiter (injected). form_data: OAuth2 password form with `username` and `password` fields. expires_delta: Requested token lifetime (query parameter); the server caps it, see access_token_lifetime. diff --git a/src/basic_api/routers/users.py b/src/basic_api/routers/users.py index 82323a9..2bab673 100644 --- a/src/basic_api/routers/users.py +++ b/src/basic_api/routers/users.py @@ -7,7 +7,7 @@ import logging -from fastapi import APIRouter, HTTPException, Request +from fastapi import APIRouter, HTTPException, Request, Response from ..dependencies import CurrentUserDep, SessionDep from ..exceptions import AppError @@ -37,6 +37,7 @@ @limiter.limit(RATE_LIMIT_REGISTER) async def create_user( request: Request, + response: Response, # slowapi writes the X-RateLimit headers onto it user_create: UserCreateSchema, session: SessionDep, ): @@ -45,6 +46,7 @@ async def create_user( Args: request: Needed by the rate limiter (injected). + response: Receives the X-RateLimit headers from the limiter (injected). user_create: Registration payload; `username` and `password` required. session: Database session. diff --git a/tests/test_limiter.py b/tests/test_limiter.py index 2872a91..1fd98c8 100644 --- a/tests/test_limiter.py +++ b/tests/test_limiter.py @@ -1,14 +1,16 @@ """ -The rate-limit error response. No database. +The rate-limit error response and the budget headers. No database. """ import json from types import SimpleNamespace +from fastapi import FastAPI, Request, Response +from httpx import ASGITransport, AsyncClient from limits import parse from slowapi.errors import RateLimitExceeded -from basic_api.limiter import rate_limit_exceeded_handler +from basic_api.limiter import limiter, rate_limit_exceeded_handler def test_rate_limit_response_uses_detail_and_retry_after(): @@ -25,3 +27,33 @@ def test_rate_limit_response_uses_detail_and_retry_after(): assert json.loads(response.body) == { "detail": "Too many requests. Try again in 60 seconds." } + + +async def test_a_limited_route_reports_its_budget_in_headers(): + # The same Limiter the app uses, on a throwaway app: the route returns a + # plain object, so slowapi needs the `response: Response` parameter to + # carry the headers (the reason the app's limited routes declare one). + app = FastAPI() + app.state.limiter = limiter + + @app.get("/limited") + @limiter.limit("3/minute") + async def limited(request: Request, response: Response): + return {"ok": True} + + limiter.enabled = True + limiter.reset() + try: + async with AsyncClient( + transport=ASGITransport(app=app), base_url="http://test" + ) as client: + first = await client.get("/limited") + second = await client.get("/limited") + finally: + limiter.enabled = False + limiter.reset() + + assert first.headers["X-RateLimit-Limit"] == "3" + assert first.headers["X-RateLimit-Remaining"] == "2" + assert second.headers["X-RateLimit-Remaining"] == "1" + assert int(first.headers["X-RateLimit-Reset"]) > 0 diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py index 156742d..d045ec0 100644 --- a/tests/test_rate_limit.py +++ b/tests/test_rate_limit.py @@ -26,3 +26,25 @@ async def test_registration_is_limited_per_client(client): assert statuses[10] == 429 assert last.headers["Retry-After"] == "60" assert last.json()["detail"].startswith("Too many requests") + + +async def test_limited_responses_report_the_remaining_budget(client): + """slowapi's headers: the limit, what is left of it, and when it resets.""" + limiter.enabled = True + limiter.reset() + try: + remaining = [] + for i in range(2): + response = await client.post( + "/api/users/", + json={"username": f"budget{i}", "password": "strongPassword123!"}, + ) + assert response.status_code == 201 + assert response.headers["X-RateLimit-Limit"] == "10" + assert int(response.headers["X-RateLimit-Reset"]) > 0 + remaining.append(int(response.headers["X-RateLimit-Remaining"])) + finally: + limiter.enabled = False + limiter.reset() + + assert remaining == [9, 8] From 8fa043dbb92427abf9aca2d450d6c4a72a4cbac9 Mon Sep 17 00:00:00 2001 From: JsNcAr Date: Fri, 9 Oct 2026 09:22:42 -0500 Subject: [PATCH 4/5] security: keep the two secrets as SecretStr API_KEY and JWT_SECRET_KEY are pydantic SecretStr values: their repr is '**********', so a traceback, a debugger dump or a log line that reaches a config value never shows them. The three use sites call get_secret_value(). Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 3 +++ src/basic_api/auth.py | 6 ++++-- src/basic_api/config.py | 10 +++++++--- src/basic_api/security.py | 4 +++- tests/test_config.py | 6 ++++++ 5 files changed, 23 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2360cf7..9f70a04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,9 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versions follo configuration for weekly, grouped dependency and GitHub Actions updates (#9). ### Security +- `API_KEY` and `JWT_SECRET_KEY` are pydantic `SecretStr` values in + `config.py`: their repr is `**********`, so a traceback or a log line that + reaches a config value never shows them (#16). - JWTs are signed and verified with PyJWT 2.15 instead of python-jose 3.5. `pip-audit` reported python-jose with an unfixed algorithm-confusion advisory (CVE-2026-85394; this API already restricted algorithms and was not diff --git a/src/basic_api/auth.py b/src/basic_api/auth.py index 555088c..a96e1a0 100644 --- a/src/basic_api/auth.py +++ b/src/basic_api/auth.py @@ -181,7 +181,9 @@ def create_access_token(data: dict, expires_delta: timedelta | None = None) -> s now = utc_now() lifetime = expires_delta or timedelta(minutes=JWT_ACCESS_TOKEN_EXPIRE_MINUTES) to_encode = {**data, "iat": now, "exp": now + lifetime} - return jwt.encode(to_encode, JWT_SECRET_KEY, algorithm=JWT_ALGORITHM) + return jwt.encode( + to_encode, JWT_SECRET_KEY.get_secret_value(), algorithm=JWT_ALGORITHM + ) def decode_access_token(token: str) -> dict: @@ -202,7 +204,7 @@ def decode_access_token(token: str) -> dict: try: return jwt.decode( token, - JWT_SECRET_KEY, + JWT_SECRET_KEY.get_secret_value(), algorithms=[JWT_ALGORITHM], # PyJWT's own key-length rule as an error, not a warning: a second # line behind the startup check in config.py, in case a key ever diff --git a/src/basic_api/config.py b/src/basic_api/config.py index db7d251..cba1c6b 100644 --- a/src/basic_api/config.py +++ b/src/basic_api/config.py @@ -17,6 +17,7 @@ from importlib.metadata import PackageNotFoundError, version from dotenv import load_dotenv +from pydantic import SecretStr load_dotenv() @@ -173,8 +174,11 @@ def _test_database_url() -> str: # --- Security ---------------------------------------------------------------- +# The two secrets are SecretStr: their repr is '**********', so a traceback, a +# debugger dump or a log line that reaches a config value never shows them. +# Use .get_secret_value() at the point of use. # The client API key (see security.py for what it is and is not). -API_KEY: str = _required("API_KEY") +API_KEY = SecretStr(_required("API_KEY")) # 32 bytes is the HMAC key size the HS256 family is specified for; a shorter # secret weakens every token at once. @@ -213,9 +217,9 @@ def minimum_secret_bytes(algorithm: str) -> int: + ", ".join(_ALLOWED_ALGORITHMS) ) -JWT_SECRET_KEY: str = _required("JWT_SECRET_KEY") +JWT_SECRET_KEY = SecretStr(_required("JWT_SECRET_KEY")) _minimum = minimum_secret_bytes(JWT_ALGORITHM) -if len(JWT_SECRET_KEY.encode("utf-8")) < _minimum: +if len(JWT_SECRET_KEY.get_secret_value().encode("utf-8")) < _minimum: raise RuntimeError( f"JWT_SECRET_KEY must be at least {_minimum} bytes for {JWT_ALGORITHM} " "(RFC 7518 section 3.2). Generate one with: python -c 'import secrets; " diff --git a/src/basic_api/security.py b/src/basic_api/security.py index b69c489..eee7345 100644 --- a/src/basic_api/security.py +++ b/src/basic_api/security.py @@ -45,7 +45,9 @@ async def verify_api_key( async def list_things(): ... """ # compare_digest: equal time whatever the first differing byte is. - if not x_api_key or not secrets.compare_digest(x_api_key, API_KEY): + if not x_api_key or not secrets.compare_digest( + x_api_key, API_KEY.get_secret_value() + ): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or missing API key", diff --git a/tests/test_config.py b/tests/test_config.py index 63457c3..7e2463f 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -73,3 +73,9 @@ def test_log_format_is_json_in_production_unless_overridden(environment, raw, ex def test_log_format_rejects_unknown_values(): with pytest.raises(ValueError): log_format("development", "xml") + + +def test_secrets_do_not_show_in_their_repr(): + assert "*" in repr(config.API_KEY) and "test" not in repr(config.API_KEY) + assert config.JWT_SECRET_KEY.get_secret_value() not in repr(config.JWT_SECRET_KEY) + assert str(config.JWT_SECRET_KEY) == "**********" From 756ea571669b037faab12744d95b33efa71c1a3b Mon Sep 17 00:00:00 2001 From: JsNcAr Date: Fri, 9 Oct 2026 09:23:53 -0500 Subject: [PATCH 5/5] test: parse X-RateLimit-Reset as Unix time slowapi reports the reset as a Unix timestamp with a fraction; the two new assertions parsed it as an integer and failed. Co-Authored-By: Claude Fable 5.1 --- tests/test_limiter.py | 2 +- tests/test_rate_limit.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_limiter.py b/tests/test_limiter.py index 1fd98c8..d2c1071 100644 --- a/tests/test_limiter.py +++ b/tests/test_limiter.py @@ -56,4 +56,4 @@ async def limited(request: Request, response: Response): assert first.headers["X-RateLimit-Limit"] == "3" assert first.headers["X-RateLimit-Remaining"] == "2" assert second.headers["X-RateLimit-Remaining"] == "1" - assert int(first.headers["X-RateLimit-Reset"]) > 0 + assert float(first.headers["X-RateLimit-Reset"]) > 0 # Unix time diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py index d045ec0..7acab1e 100644 --- a/tests/test_rate_limit.py +++ b/tests/test_rate_limit.py @@ -41,7 +41,7 @@ async def test_limited_responses_report_the_remaining_budget(client): ) assert response.status_code == 201 assert response.headers["X-RateLimit-Limit"] == "10" - assert int(response.headers["X-RateLimit-Reset"]) > 0 + assert float(response.headers["X-RateLimit-Reset"]) > 0 # Unix time remaining.append(int(response.headers["X-RateLimit-Remaining"])) finally: limiter.enabled = False