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.