diff --git a/CHANGELOG.md b/CHANGELOG.md index 21e548e..53fcc86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,12 @@ 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). ### Changed +- 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 + time-ordered so the primary-key index stays append-friendly. **Breaking for an + existing database**: the `users.id` column type changes and `create_all` does + not convert columns; migrate before upgrading a deployment with data (#12). - Python 3.14: `.python-version` says `3.14`, `requires-python` is `>=3.14,<4.0`, Black targets `py314` and mypy checks against 3.14. Every dependency in the lock ships a 3.14 wheel or is pure Python, so no package is diff --git a/README.md b/README.md index 5d46d8e..d1041c0 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ configuration right. That work is done here, tested, and documented. ## Features -- OAuth2 password flow with JWT bearer tokens; the token subject is the user id, +- OAuth2 password flow with JWT bearer tokens; the token subject is the user's UUIDv7, so a deleted or disabled account loses access on the next request - Flexible login: the `username` form field accepts a username, an email address or a phone number diff --git a/docs/authentication.md b/docs/authentication.md index f711245..1a4940a 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -45,7 +45,7 @@ default) the request is capped; omitted, zero or negative gets the default. ### What is in the token -The subject (`sub`) is the **user id**, plus `iat` and `exp`. On every request +The subject (`sub`) is the **user's UUID**, plus `iat` and `exp`. On every request `get_current_user` loads the user by id and checks `is_active`, so: - a deleted account's tokens are refused on the next request (`401 User not found`); diff --git a/docs/schemas.md b/docs/schemas.md index b440ebd..66d73df 100644 --- a/docs/schemas.md +++ b/docs/schemas.md @@ -17,7 +17,7 @@ Fields shared by the table and the API schemas. ## User (table `users`) -`UserBase` plus `id` (primary key), `hashed_password` (bcrypt over a SHA-256 +`UserBase` plus `id` (UUIDv7 primary key, generated by `uuid.uuid7()`; time-ordered, reveals nothing about account counts), `hashed_password` (bcrypt over a SHA-256 pre-hash; never returned), `created_at` and `updated_at` (aware UTC, stored as `TIMESTAMP WITH TIME ZONE` and serialised with a trailing `Z`). @@ -60,7 +60,7 @@ Body of `DELETE /api/users/me`. ## UserResponseSchema -What every user-returning route sends: `UserBase` plus `id`, `created_at`, +What every user-returning route sends: `UserBase` plus `id` (a UUID string), `created_at`, `updated_at`. Never the hash. ## SuccessResponse (`schemas/response.py`) diff --git a/src/basic_api/auth.py b/src/basic_api/auth.py index eb1509e..f66de20 100644 --- a/src/basic_api/auth.py +++ b/src/basic_api/auth.py @@ -13,6 +13,7 @@ import asyncio import hashlib import logging +import uuid from datetime import timedelta from typing import Optional @@ -163,9 +164,9 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) - """ Create a signed JWT with the given claims plus `iat` and `exp`. - `data` must carry `sub`, the user's id as a string. The id rather than the - username, because a username can be released by a deletion and taken by a - new account; an id never comes back. + `data` must carry `sub`, the user's UUID as a string. The id rather than + the username, because a username can be released by a deletion and taken + by a new account; an id never comes back. Args: data: Claims to encode, including "sub". @@ -256,13 +257,13 @@ async def authenticate_user( return user -async def get_user_by_id(session: AsyncSession, user_id: int) -> Optional[User]: +async def get_user_by_id(session: AsyncSession, user_id: uuid.UUID) -> Optional[User]: """ Load a user by primary key. Args: session: Database session. - user_id: The user's id, as carried in the token subject. + user_id: The user's UUID, as carried in the token subject. Returns: The User, or None if no row has that id. diff --git a/src/basic_api/dependencies.py b/src/basic_api/dependencies.py index e693be3..33b73bf 100644 --- a/src/basic_api/dependencies.py +++ b/src/basic_api/dependencies.py @@ -2,6 +2,7 @@ FastAPI dependencies for authentication. """ +import uuid from typing import Annotated from fastapi import Depends, HTTPException, status @@ -25,7 +26,7 @@ async def get_current_user( Loading the user on every request is what makes deletion and deactivation take effect at once, instead of when the token expires. The subject claim - is the user id, so a username released by a deletion and taken by a new + is the user's UUID, so a username released by a deletion and taken by a new account can never make an old token resolve to the new user. Args: @@ -47,8 +48,8 @@ async def mine(current_user: Annotated[User, Depends(get_current_user)]): payload = decode_access_token(token) subject = payload.get("sub") try: - user_id = int(subject) if subject is not None else None - except TypeError, ValueError: + user_id = uuid.UUID(subject) if subject is not None else None + except TypeError, ValueError, AttributeError: user_id = None if user_id is None: raise HTTPException( diff --git a/src/basic_api/schemas/user.py b/src/basic_api/schemas/user.py index 017d93a..dfad6fc 100644 --- a/src/basic_api/schemas/user.py +++ b/src/basic_api/schemas/user.py @@ -1,3 +1,4 @@ +import uuid from datetime import datetime from typing import Optional @@ -80,7 +81,11 @@ class UserBase(SQLModel): class User(UserBase, table=True): __tablename__ = "users" - id: Optional[int] = Field(default=None, primary_key=True) + # UUIDv7 (Python 3.14, RFC 9562) rather than an auto-increment integer: ids + # no longer reveal how many accounts exist or in what order they were made + # to anyone who sees one, and uuid7 is time-ordered, so the primary-key + # index still appends at the end instead of scattering like uuid4 would. + 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( @@ -128,6 +133,6 @@ class UserDeleteSchema(SQLModel): # 7. User as returned by the API: never the hash. class UserResponseSchema(UserBase): - id: int + id: uuid.UUID created_at: datetime updated_at: Optional[datetime] = None diff --git a/src/basic_api/services/users.py b/src/basic_api/services/users.py index abb4e07..aa584dd 100644 --- a/src/basic_api/services/users.py +++ b/src/basic_api/services/users.py @@ -6,6 +6,7 @@ """ import logging +import uuid from typing import Optional from sqlalchemy.exc import IntegrityError @@ -37,7 +38,7 @@ async def _assert_identifiers_free( session: AsyncSession, values: dict[str, Optional[str]], - exclude_user_id: Optional[int] = None, + exclude_user_id: Optional[uuid.UUID] = None, ) -> None: """ Raise IdentifierTakenError if any given identifier belongs to another account. diff --git a/tests/test_self_service.py b/tests/test_self_service.py index 62bb8c0..d709d6a 100644 --- a/tests/test_self_service.py +++ b/tests/test_self_service.py @@ -20,7 +20,7 @@ async def test_read_me_returns_the_profile_without_the_hash( response = await client.get(ME, headers=auth_headers) assert response.status_code == 200 data = response.json()["data"] - assert data["id"] == test_user.id + assert data["id"] == str(test_user.id) assert data["username"] == "testuser" assert "hashed_password" not in data diff --git a/tests/test_smoke.py b/tests/test_smoke.py index 4dbc9b4..b64287e 100644 --- a/tests/test_smoke.py +++ b/tests/test_smoke.py @@ -59,7 +59,7 @@ async def test_auth_me_returns_the_stored_user(client, auth_headers, test_user): response = await client.get("/api/auth/me", headers=auth_headers) assert response.status_code == 200 data = response.json()["data"] - assert data["id"] == test_user.id + assert data["id"] == str(test_user.id) assert data["username"] == "testuser" assert data["email"] == "test@example.com" assert "role" not in data diff --git a/tests/test_users.py b/tests/test_users.py index 94a8f1c..d5b4ed7 100644 --- a/tests/test_users.py +++ b/tests/test_users.py @@ -68,3 +68,18 @@ async def test_the_response_has_no_legacy_fields(client): data = (await register(client)).json()["data"] for legacy in ("bluetooth_address", "wifi_mac_address", "is_deleted"): assert legacy not in data + + +async def test_ids_are_version_7_uuids_ordered_by_creation(client): + import uuid + + first = uuid.UUID((await register(client)).json()["data"]["id"]) + second = uuid.UUID( + ( + await register(client, username="later", email=None, phone_number=None) + ).json()["data"]["id"] + ) + # Version 7 is time-ordered (RFC 9562), so a later account sorts after an + # earlier one, and nothing about the value says how many accounts exist. + assert first.version == second.version == 7 + assert first != second and first < second