Skip to content
Merged
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
7 changes: 7 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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=*
Expand Down
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,16 @@ 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,
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
```
Expand All @@ -30,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)
Expand Down
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -29,6 +32,16 @@ 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).
- `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
Expand All @@ -38,6 +51,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
Expand Down
9 changes: 9 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,15 @@ 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.

**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 <jwt>`. See [Authentication](authentication.md) for the
error tables common to all protected routes.
Expand Down
18 changes: 9 additions & 9 deletions docs/known_issues.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
19 changes: 19 additions & 0 deletions docs/setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/` |
Expand All @@ -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 <proxy-ip>`, 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
Expand Down
13 changes: 7 additions & 6 deletions src/basic_api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import logging
import uuid
from datetime import timedelta
from typing import Optional

import bcrypt
from fastapi import HTTPException, status
Expand Down Expand Up @@ -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.

Expand All @@ -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`.

Expand All @@ -182,7 +181,9 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -
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:
Expand All @@ -203,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
Expand Down Expand Up @@ -265,7 +266,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.

Expand Down
52 changes: 49 additions & 3 deletions src/basic_api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@
`name` in pyproject.toml.
"""

import logging
import os
import sys
from importlib.metadata import PackageNotFoundError, version

from dotenv import load_dotenv
from pydantic import SecretStr

load_dotenv()

Expand Down Expand Up @@ -71,11 +73,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."""
Expand Down Expand Up @@ -131,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.
Expand Down Expand Up @@ -171,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; "
Expand Down
12 changes: 10 additions & 2 deletions src/basic_api/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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)
Expand Down Expand Up @@ -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)]
7 changes: 6 additions & 1 deletion src/basic_api/limiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
Loading
Loading