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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`);
Expand Down
4 changes: 2 additions & 2 deletions docs/schemas.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`).

Expand Down Expand Up @@ -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`)
Expand Down
11 changes: 6 additions & 5 deletions src/basic_api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import asyncio
import hashlib
import logging
import uuid
from datetime import timedelta
from typing import Optional

Expand Down Expand Up @@ -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".
Expand Down Expand Up @@ -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.
Expand Down
7 changes: 4 additions & 3 deletions src/basic_api/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
FastAPI dependencies for authentication.
"""

import uuid
from typing import Annotated

from fastapi import Depends, HTTPException, status
Expand All @@ -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:
Expand All @@ -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(
Expand Down
9 changes: 7 additions & 2 deletions src/basic_api/schemas/user.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import uuid
from datetime import datetime
from typing import Optional

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
3 changes: 2 additions & 1 deletion src/basic_api/services/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"""

import logging
import uuid
from typing import Optional

from sqlalchemy.exc import IntegrityError
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion tests/test_self_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion tests/test_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
15 changes: 15 additions & 0 deletions tests/test_users.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading