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
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ TEST_DB_NAME=basic_api_test_db
# Client API key, sent as X-API-Key on every /api route. It identifies your
# own clients; it is not a user credential.
API_KEY=your-secret-api-key-here
# JWT signing secret: at least 32 bytes, or the app refuses to start.
# JWT signing secret: at least 32 bytes for HS256 (48 for HS384, 64 for HS512),
# or the app refuses to start.
# Generate: python -c "import secrets; print(secrets.token_urlsafe(32))"
JWT_SECRET_KEY=replace_with_a_secure_random_value_of_32_bytes_or_more
# One of HS256, HS384, HS512
Expand Down
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,22 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versions follo
`RequestBodyLimitMiddleware` answers 413 before any route runs (#13).

### Changed
- `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
`enforce_minimum_key_length`, so the library's own check is an error, not a
warning (#14).
- Domain exceptions are mapped to status codes once, by app-level exception
handlers, instead of a try/except in every route; same codes and bodies (#14).
- `utc_now()` uses `datetime.UTC`; `UserResponseSchema` declares `created_at`
and `updated_at` as `AwareDatetime`, the contract SQLModel's `UTCDateTime`
fulfils (#14).
- Python 3.14 features evaluated for this code base and left unused, so the
question need not be reopened: template strings (no templating), deferred
annotations (no forward references to simplify), multiple interpreters and
free-threading (nothing CPU-bound), `compression.zstd`, `functools.Placeholder`.
Adopted: `uuid.uuid7()` (#12), PEP 758 `except A, B:` via Black, the asyncio
introspection commands in the setup guide (#14).
- Users are identified by UUIDv7 (`uuid.uuid7()`, new in Python 3.14) instead
of an auto-increment integer: `id` in every response and the token subject is
now a UUID string. Ids no longer reveal how many accounts exist, and uuid7 is
Expand Down
4 changes: 3 additions & 1 deletion docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ stateless and live until `exp` (see [Known Issues](known_issues.md#tokens-cannot
- **Constant-time login**: when the identifier matches no account, the password
is verified against a sentinel hash anyway, so timing does not reveal which
accounts exist, and both failures return the same body.
- **Startup validation**: a `JWT_SECRET_KEY` under 32 bytes, an algorithm
- **Startup validation**: a `JWT_SECRET_KEY` shorter than the algorithm's
minimum (32 bytes for HS256, 48 for HS384, 64 for HS512; RFC 7518 section
3.2, the same rule PyJWT enforces at decode), an algorithm
outside `HS256`/`HS384`/`HS512`, or fewer than 12 bcrypt rounds refuse to
start (`config.py`).
- **Fixed error messages**: a failed token decode answers one message; the
Expand Down
7 changes: 4 additions & 3 deletions docs/known_issues.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,10 @@ live in every deployment of the starter.

**Where:** `src/basic_api/config.py`, `src/basic_api/limiter.py`, `tests/`.

The checks that refuse to start (required variables, secret length, algorithm
allow-list, bcrypt minimum, rate-limit syntax) run at import, and no test
exercises any of them. `RATE_LIMIT_LOGIN` is applied but only the registration
The checks that refuse to start (required variables, algorithm allow-list,
bcrypt minimum, rate-limit syntax) run at import, and no test exercises them.
The one exception is the secret-length rule, which lives in the tested function
`minimum_secret_bytes()`. `RATE_LIMIT_LOGIN` is applied but only the registration
limit has a test.

**Fix:** move the checks into a `load_settings()` function that the module
Expand Down
15 changes: 14 additions & 1 deletion docs/setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ with a comment; the table below is the summary.
|---|---|---|---|
| `DATABASE_URL` | yes | | `postgresql+asyncpg://user:password@host:5432/dbname` |
| `API_KEY` | yes | | Client API key sent as `X-API-Key` on `/api` routes |
| `JWT_SECRET_KEY` | yes | | At least 32 bytes. `python -c "import secrets; print(secrets.token_urlsafe(32))"` |
| `JWT_SECRET_KEY` | yes | | At least 32 bytes for HS256, 48 for HS384, 64 for HS512. `python -c "import secrets; print(secrets.token_urlsafe(32))"` |
| `JWT_ALGORITHM` | | `HS256` | One of `HS256`, `HS384`, `HS512` |
| `JWT_ACCESS_TOKEN_EXPIRE_MINUTES` | | `30` | Default token lifetime |
| `JWT_MAX_ACCESS_TOKEN_EXPIRE_MINUTES` | | `10080` (7 days) | Longest lifetime a client may request with `?expires_delta=`; must be at least the default |
Expand Down Expand Up @@ -131,3 +131,16 @@ Everything a new project renames or changes, in one list:
`SERVICE_NAME` returned by `/health`.
5. **Configuration**: add a variable in `config.py` and `.env.example` together.
6. **Docs**: this folder and the README.

## Debugging a hung process

Python 3.14 can show what an asyncio program is waiting on, from outside the
process and without stopping it:

```bash
python -m asyncio ps <pid> # one line per task: id, name, coroutine stack
python -m asyncio pstree <pid> # the same as an await tree
```

Point it at the uvicorn worker's pid. A task stuck on a database call or a lock
shows up with its full await chain; that is usually enough to name the culprit.
10 changes: 9 additions & 1 deletion src/basic_api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,15 @@ def decode_access_token(token: str) -> dict:
caller, so it cannot be used to probe the server.
"""
try:
return jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])
return jwt.decode(
token,
JWT_SECRET_KEY,
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
# reaches here another way.
options={"enforce_minimum_key_length": True},
)
except PyJWTError as e:
logger.debug("Rejected token: %s", e)
raise HTTPException(
Expand Down
40 changes: 33 additions & 7 deletions src/basic_api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,16 +136,33 @@ def _test_database_url() -> str:

# 32 bytes is the HMAC key size the HS256 family is specified for; a shorter
# secret weakens every token at once.
_MIN_SECRET_BYTES = 32
_ALLOWED_ALGORITHMS = ("HS256", "HS384", "HS512")
# RFC 7518 section 3.2: an HMAC key should be at least as long as the hash it
# drives. PyJWT 2.15 checks the same rule at sign and verify time.
_SECRET_MINIMUM_BYTES = {"HS256": 32, "HS384": 48, "HS512": 64}
_MIN_BCRYPT_ROUNDS = 12

JWT_SECRET_KEY: str = _required("JWT_SECRET_KEY")
if len(JWT_SECRET_KEY.encode("utf-8")) < _MIN_SECRET_BYTES:
raise RuntimeError(
f"JWT_SECRET_KEY must be at least {_MIN_SECRET_BYTES} bytes. Generate one "
"with: python -c 'import secrets; print(secrets.token_urlsafe(32))'"
)

def minimum_secret_bytes(algorithm: str) -> int:
"""
The shortest JWT_SECRET_KEY the given HMAC algorithm should run with.

Args:
algorithm: One of HS256, HS384, HS512.

Returns:
The hash output size in bytes: 32, 48 or 64.

Raises:
ValueError: The algorithm is not one this API allows.
"""
try:
return _SECRET_MINIMUM_BYTES[algorithm]
except KeyError:
raise ValueError(
f"{algorithm!r} is not one of " + ", ".join(_ALLOWED_ALGORITHMS)
)


JWT_ALGORITHM = os.getenv("JWT_ALGORITHM") or "HS256"
if JWT_ALGORITHM not in _ALLOWED_ALGORITHMS:
Expand All @@ -154,6 +171,15 @@ def _test_database_url() -> str:
+ ", ".join(_ALLOWED_ALGORITHMS)
)

JWT_SECRET_KEY: str = _required("JWT_SECRET_KEY")
_minimum = minimum_secret_bytes(JWT_ALGORITHM)
if len(JWT_SECRET_KEY.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; "
f"print(secrets.token_urlsafe({_minimum}))'"
)

JWT_ACCESS_TOKEN_EXPIRE_MINUTES = _int("JWT_ACCESS_TOKEN_EXPIRE_MINUTES", 30)
# Longest lifetime a client may request at login (default 7 days).
JWT_MAX_ACCESS_TOKEN_EXPIRE_MINUTES = _int(
Expand Down
17 changes: 17 additions & 0 deletions src/basic_api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
)
from .database import engine, get_session, init_db, ping
from .dependencies import get_current_user
from .exceptions import IdentifierTakenError, PasswordVerificationError
from .limiter import RATE_LIMIT_LOGIN, limiter, rate_limit_exceeded_handler
from .routers import auth, users
from .schemas.errors import error_responses
Expand Down Expand Up @@ -82,6 +83,22 @@ async def lifespan(app: FastAPI):
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, rate_limit_exceeded_handler)


def _domain_error(status_code: int):
"""A handler that turns a domain exception into {"detail": str(exc)}."""

def handler(request: Request, exc: Exception) -> JSONResponse:
return JSONResponse(status_code=status_code, content={"detail": str(exc)})

return handler


# Domain exceptions from the services are mapped to status codes here, once,
# instead of in a try/except in every route. The services stay HTTP-free; a
# route only catches what it has to log.
app.add_exception_handler(IdentifierTakenError, _domain_error(409))
app.add_exception_handler(PasswordVerificationError, _domain_error(400))

# 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.
Expand Down
18 changes: 9 additions & 9 deletions src/basic_api/routers/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

from ..database import get_session
from ..dependencies import get_current_user
from ..exceptions import IdentifierTakenError, PasswordVerificationError
from ..exceptions import AppError
from ..limiter import RATE_LIMIT_REGISTER, limiter
from ..schemas import SuccessResponse
from ..schemas.errors import error_responses
Expand Down Expand Up @@ -70,8 +70,8 @@ async def create_user(
"""
try:
db_user = await user_service.create_user(session, user_create)
except IdentifierTakenError as e:
raise HTTPException(status_code=409, detail=str(e))
except AppError:
raise # mapped to a status code by the handlers in main.py
except Exception:
await session.rollback()
logger.exception("Failed to create user")
Expand Down Expand Up @@ -146,8 +146,8 @@ async def update_current_user(
"""
try:
db_user = await user_service.update_user(session, current_user, user_update)
except IdentifierTakenError as e:
raise HTTPException(status_code=409, detail=str(e))
except AppError:
raise # mapped to a status code by the handlers in main.py
except Exception:
await session.rollback()
logger.exception("Failed to update user")
Expand Down Expand Up @@ -195,8 +195,8 @@ async def change_password(
"""
try:
await user_service.change_user_password(session, current_user, password_change)
except PasswordVerificationError as e:
raise HTTPException(status_code=400, detail=str(e))
except AppError:
raise # mapped to a status code by the handlers in main.py
except Exception:
await session.rollback()
logger.exception("Failed to change password")
Expand Down Expand Up @@ -245,8 +245,8 @@ async def delete_current_user(
"""
try:
await user_service.delete_user(session, current_user, body.password)
except PasswordVerificationError as e:
raise HTTPException(status_code=400, detail=str(e))
except AppError:
raise # mapped to a status code by the handlers in main.py
except Exception:
await session.rollback()
logger.exception("Failed to delete user")
Expand Down
15 changes: 12 additions & 3 deletions src/basic_api/schemas/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@
from datetime import datetime
from typing import Optional

from pydantic import EmailStr, HttpUrl, TypeAdapter, ValidationError, field_validator
from pydantic import (
AwareDatetime,
EmailStr,
HttpUrl,
TypeAdapter,
ValidationError,
field_validator,
)
from sqlmodel import Field, SQLModel

from ..utils import utc_now
Expand Down Expand Up @@ -134,5 +141,7 @@ class UserDeleteSchema(SQLModel):
# 7. User as returned by the API: never the hash.
class UserResponseSchema(UserBase):
id: uuid.UUID
created_at: datetime
updated_at: Optional[datetime] = None
# 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
6 changes: 3 additions & 3 deletions src/basic_api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
General utility functions.
"""

from datetime import datetime, timezone
from datetime import UTC, datetime


def utc_now() -> datetime:
Expand All @@ -16,6 +16,6 @@ def utc_now() -> datetime:
aware, UTC. Responses carry the zone ("...Z") for the same reason.

Returns:
The current time with tzinfo set to timezone.utc.
The current time with tzinfo set to UTC (the 3.11+ alias of timezone.utc).
"""
return datetime.now(timezone.utc)
return datetime.now(UTC)
13 changes: 13 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,16 @@ def test_under_pytest_the_database_url_targets_the_test_database():

def test_app_version_is_a_version_string():
assert config.APP_VERSION and config.APP_VERSION[0].isdigit()


@pytest.mark.parametrize(
"algorithm, minimum", [("HS256", 32), ("HS384", 48), ("HS512", 64)]
)
def test_secret_minimum_is_the_hash_output_size(algorithm, minimum):
# RFC 7518 section 3.2, and the same rule PyJWT 2.15 applies.
assert config.minimum_secret_bytes(algorithm) == minimum


def test_secret_minimum_rejects_algorithms_this_api_does_not_allow():
with pytest.raises(ValueError):
config.minimum_secret_bytes("RS256")
Loading