14 Commits

Author SHA1 Message Date
7a835d3172 Feat: Rate-limit login endpoint to block brute-force attacks
After LOGIN_MAX_FAILURES consecutive failed attempts from the same source
IP within LOGIN_WINDOW_SECONDS, POST /api/v1/auth/token returns HTTP 429
with a Retry-After header for LOGIN_COOLDOWN_SECONDS. A successful login
resets the counter. Trusted upstream proxy IPs/CIDRs can be declared via
LOGIN_TRUSTED_PROXY_IPS so X-Forwarded-For is honoured correctly behind
nginx ingress or similar reverse proxies.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 21:01:37 +00:00
f3e0021ee8 Feat: Enforce PostgreSQL for integration tests; add Docker test stack
- conftest.py: pytest_configure guard rejects non-postgresql+asyncpg:// URLs
  before any test collects (per constitution §2.5/§5.2 v1.3.0)
- docker-compose.test.yml: isolated postgres-test (5433) + minio-test (9002)
  + api-test runner; one command runs the full suite against real PostgreSQL
- Makefile: test-unit and test-integration targets
- .env.test.example: documents variables needed to run tests outside Docker
- Fix pre-existing test bug: integration tests using client fixture (NoOpAuthProvider)
  for write operations (upload/delete/patch) now use authed_client with Bearer
  token — these were never caught because tests never ran against a live stack

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 19:14:12 +00:00
354c85292d Docs: Bump constitution to v1.3.0 — require PostgreSQL for integration tests
§2.5: Remove the planned PostgreSQL→SQLite refactor note; prohibit
alternative database engines in integration tests.
§5.2: Explicitly require a real PostgreSQL instance for integration
tests; ban SQLite — a GROUP BY/HAVING production bug was masked by
SQLite's permissive dialect in feature 007.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 18:47:57 +00:00
265b967f6b Fix: Use WHERE instead of HAVING for min_count filter in list_tags()
HAVING requires GROUP BY; count_subq is a correlated scalar subquery, not
an aggregate, so PostgreSQL rejects it. WHERE works correctly and the
integration tests used SQLite which is permissive about this rule.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 18:42:50 +00:00
355014f975 Feat: Add tag browser page at /tags with count-sorted tag list and library deep-link
- Extends GET /api/v1/tags with sort=count_desc and min_count query params
- New TagsComponent at /tags (public, no auth guard) shows all tags sorted by image count
- Clicking a tag navigates to /?tags=<name> for a pre-filtered library view
- LibraryComponent reads ?tags= query param on init to support deep-linking from tag browser
- Library header gains a "Browse tags" link to /tags for discoverability
- All 15 TDD tasks complete; ruff, ng lint, and ng build clean

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 18:40:06 +00:00
6092a4454e Chore: Update .gitignore 2026-05-03 16:29:57 -04:00
28df9a1261 Feat: Header title links to grid; sign-out redirects to grid
Make the app title a clickable link to / so users can return to the
image grid from any sub-page without the browser back button. Change
the sign-out destination from /login to / since the grid is publicly
accessible and avoids unnecessary friction post-logout.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 20:14:35 +00:00
9246f75fdd Feat: Polish Angular UI with cohesive design system
Introduces a shared CSS custom property token layer and applies it
across all five views (library, upload, detail, login, app shell).
Each view now has intentional loading, empty, and error states.

- styles.css: 13 design tokens on :root; shimmer skeleton animation
- Library: 150ms-debounced skeleton loading, empty state with /upload
  link, error card with retry, card hover lift, broken-image fallback
- Upload: token-styled drop-zone, Uploading… spinner, 4s success
  banner, distinct validation vs. network error messages
- Detail: image skeleton, network error card (separate from 404
  not-found card), Owner actions panel, danger tag error styling,
  broken-image fallback
- Login: vertically centred surface card, danger field/server errors,
  Signing in… disabled button
- App shell: 48px fixed header, app name left, sign-out right, no
  reflow on auth state change
- All 24 ESLint errors resolved (including pre-existing auth spec
  issues); ng build and ng lint pass clean

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 20:03:56 +00:00
5179786261 Docs: Bump constitution to v1.2.0 — reflect JWT auth completion
Phase 2 (JWT bearer) is shipped; update §2.4 phase status, add PyJWT
to §6 tech stack table, remove username/password from §8 out-of-scope.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 19:17:18 +00:00
86961d19ee Chore: Add updated files 2026-05-03 15:13:35 -04:00
5fbbc1e67f Feat: Implement JWT bearer token authentication
Protects image upload, delete, and tag-update endpoints behind
Bearer token auth. Public read endpoints remain open. Angular SPA
gains a login page, auth interceptor, and route guard for /upload.

- JWTAuthProvider (HS256, sub/iat/exp, secrets.compare_digest)
- POST /api/v1/auth/token login endpoint
- require_auth FastAPI dependency on all write routes
- AuthService, LoginComponent, authInterceptor, authGuard
- Detail page hides write controls for unauthenticated visitors
- 43 unit tests passing; integration tests require Docker stack

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 19:12:38 +00:00
d91a65abe5 Docs: Update scope boundaries in constitution
Due to the introduction of image thumbnail generation in
cd89ba5dea, the scope boundaries in §10 of
the project constitution should be updated with a clarification.
2026-05-03 14:02:51 -04:00
ec7bf591a4 Chore: Add example image to README.md 2026-05-03 13:46:16 -04:00
f953c88984 Feat: Pre-generate WebP thumbnails on upload for faster library load
- Add Pillow dependency and thumbnail.py with generate_thumbnail() — produces
  WebP ≤400px, preserves aspect ratio, never upscales, handles GIF frame 0
- Alembic migration 002 adds nullable thumbnail_key column to images table
- Upload route generates thumbnail via asyncio.to_thread (non-blocking),
  stores at {hash}-thumb; failure is tolerated and upload succeeds with null key
- New GET /api/v1/images/{id}/thumbnail endpoint: serves WebP thumbnail or
  falls back to original for pre-feature images; ETag + immutable cache headers
- Delete route cleans up thumbnail storage object alongside original
- Library grid switches from /file to /thumbnail for all image src bindings
- 59 tests passing (46 existing + 13 new across unit, upload, serving, delete)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 17:26:16 +00:00
116 changed files with 26895 additions and 275 deletions

View File

@@ -13,3 +13,17 @@ API_BASE_URL=http://localhost:8000
# Upload size limit in bytes (default 50 MiB)
MAX_UPLOAD_BYTES=52428800
# Owner credentials and JWT signing secret
JWT_SECRET_KEY=change-me-to-a-long-random-string
JWT_EXPIRY_SECONDS=86400
OWNER_USERNAME=owner
OWNER_PASSWORD=change-me
# Login brute-force protection
LOGIN_MAX_FAILURES=5
LOGIN_WINDOW_SECONDS=300
LOGIN_COOLDOWN_SECONDS=900
# Comma-separated IPs/CIDRs of trusted upstream proxies (e.g. nginx ingress pod CIDR).
# Leave empty when not behind a reverse proxy.
LOGIN_TRUSTED_PROXY_IPS=

36
.env.test.example Normal file
View File

@@ -0,0 +1,36 @@
# Integration test environment variables
# Used when running pytest directly on the host (outside Docker).
#
# Start test services first:
# docker compose -f docker-compose.test.yml up -d postgres-test minio-test minio-init-test
#
# Then source this file and run tests:
# export $(grep -v '^#' .env.test.example | xargs)
# cd api && python -m pytest tests/integration/ -v
# PostgreSQL test database (postgres-test container on host port 5433)
TEST_DATABASE_URL=postgresql+asyncpg://reactbin:reactbin@localhost:5433/reactbin_test
DATABASE_URL=postgresql+asyncpg://reactbin:reactbin@localhost:5433/reactbin_test
# MinIO test instance (minio-test container on host port 9002)
S3_ENDPOINT_URL=http://localhost:9002
S3_BUCKET_NAME=reactbin-test
S3_ACCESS_KEY_ID=minioadmin
S3_SECRET_ACCESS_KEY=minioadmin
S3_REGION=us-east-1
# Auth (test values — not for production)
JWT_SECRET_KEY=test-secret-key-for-testing-only
OWNER_USERNAME=testowner
OWNER_PASSWORD=testpassword
# API
API_BASE_URL=http://localhost:8000
MAX_UPLOAD_BYTES=52428800
# Login brute-force protection
LOGIN_MAX_FAILURES=5
LOGIN_WINDOW_SECONDS=300
LOGIN_COOLDOWN_SECONDS=900
# Comma-separated IPs/CIDRs of trusted upstream proxies; leave empty for direct connections.
LOGIN_TRUSTED_PROXY_IPS=

4
.gitignore vendored
View File

@@ -1,7 +1,11 @@
# Developer notes
notes/
# Environment
.env
.env.*
!.env.example
!.env.test.example
# Python
__pycache__/

BIN
.img/reactbin-ui.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 352 KiB

View File

@@ -1,3 +1,3 @@
{
"feature_directory": "specs/002-api-image-proxy"
"feature_directory": "specs/009-login-rate-limiting"
}

View File

@@ -1,8 +1,8 @@
<!--
SYNC IMPACT REPORT
==================
Version change: [TEMPLATE — no prior version] → 1.1.0
Ratified: 2026-05-01 | Last amended: 2026-05-02
Version change: 1.2.0 → 1.3.0
Ratified: 2026-05-01 | Last amended: 2026-05-06
Principles introduced (first population from docs/CONSTITUTION.md):
- §2 Architecture Principles (6 sub-principles)
@@ -82,22 +82,23 @@ or SDK-specific types directly — only the interface contract.
### 2.4 Auth abstraction (progressive)
Authentication is treated as a pluggable backend from day one, even though
Phase 1 ships with no auth. The API MUST route all request-identity resolution
through a single `AuthProvider` interface. The no-op provider (Phase 1) returns
a static anonymous identity. Adding username/password or OIDC in a later phase
MUST be a new provider implementation, not a rewrite of business logic.
Authentication is treated as a pluggable backend from day one. The API MUST
route all request-identity resolution through a single `AuthProvider` interface.
Each phase introduces a new provider implementation; no phase rewrites business
logic already behind the interface.
**Phase 1 implements: no-auth (localhost only).**
**Planned phases: username/password, then OIDC.**
**Phase 1 — no-auth (NoOpAuthProvider): complete.**
**Phase 2 — JWT bearer token (JWTAuthProvider, HS256, single owner): complete.**
**Phase 3 — OIDC: planned.**
The constitution acknowledges all three; the spec governs which is built.
### 2.5 Database abstraction
PostgreSQL is the Phase 1 database. All DB access MUST go through a repository
layer (one repository class per domain aggregate). Raw SQL or an ORM is
acceptable, but no query logic MAY live outside a repository. This makes the
planned PostgreSQL → SQLite refactor a repository-layer change only.
PostgreSQL is the database. All DB access MUST go through a repository layer
(one repository class per domain aggregate). Raw SQL or an ORM is acceptable,
but no query logic MAY live outside a repository. No alternative database
engine (SQLite, DuckDB, in-memory substitutes) MAY be used in integration
tests — dialect differences mask production bugs.
### 2.6 No speculative abstraction
@@ -179,8 +180,11 @@ before any implementation step.
### 5.2 Test pyramid
- **Unit tests** — pure logic, repository mocks, no I/O
- **Integration tests** — API routes tested against a real (test) database
and a real (test) S3-compatible bucket (e.g. MinIO in Docker)
- **Integration tests** — API routes tested against a real PostgreSQL instance
and a real S3-compatible bucket (e.g. MinIO in Docker). SQLite and other
in-memory database substitutes are **prohibited** — PostgreSQL-specific
behaviour (GROUP BY enforcement, JSON operators, constraint handling) MUST
be exercised by the test suite.
- **E2E tests** — Angular + API, minimal set covering the core happy paths
Unit and integration tests are required. E2E tests are best-effort in v1.
@@ -199,16 +203,17 @@ NOT be marked complete while CI is failing.
## 6. Tech Stack Constraints
| Concern | Choice | Rationale |
|---|---|---|
| API language | Python 3.12+ | Primary language, type hints required |
| API framework | FastAPI | Async, OpenAPI-native |
| ORM / query | SQLAlchemy 2.x (async) + asyncpg driver | Repository layer owns all queries |
| DB migrations | Alembic | Schema changes tracked in version control |
| Object storage | S3-compatible via `boto3` / `aiobotocore` | Swap MinIO ↔ S3 via env config |
| UI framework | Angular (latest stable) | Job-relevant, learning goal |
| UI language | TypeScript strict mode | No `any`, no implicit types |
| Containerisation | Docker + Docker Compose | Local dev must start with one command |
| Concern | Choice | Rationale |
|------------------|-------------------------------------------|-------------------------------------------|
| API language | Python 3.12+ | Primary language, type hints required |
| API framework | FastAPI | Async, OpenAPI-native |
| ORM / query | SQLAlchemy 2.x (async) + asyncpg driver | Repository layer owns all queries |
| DB migrations | Alembic | Schema changes tracked in version control |
| Object storage | S3-compatible via `boto3` / `aiobotocore` | Swap MinIO ↔ S3 via env config |
| Auth tokens | PyJWT (HS256) | Lightweight; compatible with OIDC migration path |
| UI framework | Angular (latest stable) | Job-relevant, learning goal |
| UI language | TypeScript strict mode | No `any`, no implicit types |
| Containerisation | Docker + Docker Compose | Local dev must start with one command |
---
@@ -241,10 +246,9 @@ revised:
- Multi-user support
- Public sharing or embeds
- Collections or albums beyond tag-based grouping
- Image editing or transformation
- Image editing or transformation beyond thumbnail generation
- OR/NOT tag logic
- Mobile-native app
- Username/password auth (planned Phase 2)
- OIDC auth (planned Phase 3)
---
@@ -277,12 +281,15 @@ Phase 1 design is complete.
## 10. Revision Log
| Version | Date | Change |
|---|---|---|
| 1.0.0 | 2026-05-01 | Initial constitution |
| 1.1.0 | 2026-05-01 | asyncpg driver explicit; SHA-256 deduplication added to data model; deduplication removed from out-of-scope |
| 1.1.0 | 2026-05-02 | Adopted into Spec Kit memory; fixed duplicate §4.3 → §4.4; strengthened "should" language to MUST/MUST NOT; added §9 Governance |
| Version | Date | Change |
|---------|------------|---------------------------------------------------------------------------------------------------------------------------------|
| 1.0.0 | 2026-05-01 | Initial constitution |
| 1.1.0 | 2026-05-01 | asyncpg driver explicit; SHA-256 deduplication added to data model; deduplication removed from out-of-scope |
| 1.1.0 | 2026-05-02 | Adopted into Spec Kit memory; fixed duplicate §4.3 → §4.4; strengthened "should" language to MUST/MUST NOT; added §9 Governance |
| 1.1.1 | 2026-05-03 | Clarify that the only acceptable form of image transformation or editing is thumbnail generation |
| 1.2.0 | 2026-05-03 | §2.4: Mark Phase 2 (JWT bearer auth) complete, reword phase status; §6: Add PyJWT to tech stack table; §8: Remove username/password auth from out-of-scope (now shipped) |
| 1.3.0 | 2026-05-06 | §2.5: Remove planned PostgreSQL → SQLite refactor note; prohibit alternative database engines in integration tests. §5.2: Explicitly require PostgreSQL for integration tests; prohibit SQLite — a production HAVING/GROUP BY bug was masked by SQLite's permissive dialect. |
---
**Version**: 1.1.0 | **Ratified**: 2026-05-01 | **Last Amended**: 2026-05-02
**Version**: 1.3.0 | **Ratified**: 2026-05-01 | **Last Amended**: 2026-05-06

View File

@@ -1,5 +1,5 @@
<!-- SPECKIT START -->
For additional context about technologies to be used, project structure,
shell commands, and other important information, read the current plan at
`specs/002-api-image-proxy/plan.md`.
`specs/009-login-rate-limiting/plan.md`.
<!-- SPECKIT END -->

7
Makefile Normal file
View File

@@ -0,0 +1,7 @@
.PHONY: test-unit test-integration
test-unit:
cd api && python -m pytest tests/unit/ -v
test-integration:
docker compose -f docker-compose.test.yml run --rm api-test

View File

@@ -1,2 +1,4 @@
# reactbin
Organize your reaction images.
_Organize your reaction images._
![Reactbin UI](.img/reactbin-ui.png)

View File

@@ -0,0 +1,23 @@
"""add thumbnail_key column to images
Revision ID: 002
Revises: 001
Create Date: 2026-05-03
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "002"
down_revision: Union[str, None] = "001"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.add_column("images", sa.Column("thumbnail_key", sa.String(70), nullable=True))
def downgrade() -> None:
op.drop_column("images", "thumbnail_key")

View File

@@ -0,0 +1,51 @@
import secrets
from datetime import UTC, datetime, timedelta
import jwt
from fastapi import HTTPException
from app.auth.provider import AuthProvider, Identity
_UNAUTHORIZED = HTTPException(
status_code=401, detail={"detail": "Unauthorized", "code": "unauthorized"}
)
class JWTAuthProvider(AuthProvider):
def __init__(
self,
secret_key: str,
expiry_seconds: int,
owner_username: str,
owner_password: str,
) -> None:
self._secret_key = secret_key
self._expiry_seconds = expiry_seconds
self._owner_username = owner_username
self._owner_password = owner_password
def create_token(self) -> str:
now = datetime.now(tz=UTC)
payload = {
"sub": "owner",
"iat": now,
"exp": now + timedelta(seconds=self._expiry_seconds),
}
return jwt.encode(payload, self._secret_key, algorithm="HS256")
def verify_credentials(self, username: str, password: str) -> bool:
username_ok = secrets.compare_digest(username, self._owner_username)
password_ok = secrets.compare_digest(password, self._owner_password)
return username_ok and password_ok
async def get_identity(self, authorization: str | None) -> Identity:
if not authorization or not authorization.startswith("Bearer "):
raise _UNAUTHORIZED
token = authorization.removeprefix("Bearer ")
try:
jwt.decode(token, self._secret_key, algorithms=["HS256"])
except jwt.ExpiredSignatureError:
raise _UNAUTHORIZED from None
except jwt.InvalidTokenError:
raise _UNAUTHORIZED from None
return Identity(id="owner", anonymous=False)

View File

@@ -4,5 +4,5 @@ _ANONYMOUS = Identity(id="anonymous", anonymous=True)
class NoOpAuthProvider(AuthProvider):
async def get_identity(self) -> Identity:
async def get_identity(self, authorization: str | None) -> Identity:
return _ANONYMOUS

View File

@@ -10,5 +10,5 @@ class Identity:
class AuthProvider(ABC):
@abstractmethod
async def get_identity(self) -> Identity:
"""Resolve the request identity."""
async def get_identity(self, authorization: str | None) -> Identity:
"""Resolve the request identity from the Authorization header value."""

View File

@@ -0,0 +1,91 @@
import ipaddress
import logging
import time
from dataclasses import dataclass, field
from ipaddress import IPv4Network, IPv6Network
from threading import Lock
from starlette.requests import Request
logger = logging.getLogger(__name__)
def get_client_ip(
request: Request,
trusted_networks: list[IPv4Network | IPv6Network],
) -> str:
"""Return the resolved client IP, honouring X-Forwarded-For when the
TCP peer is a trusted upstream proxy. Falls back to the TCP peer address
when no trusted networks are configured or the peer is not in the list."""
peer = request.client.host if request.client else "unknown"
if trusted_networks and peer != "unknown":
try:
peer_addr = ipaddress.ip_address(peer)
if any(peer_addr in net for net in trusted_networks):
xff = request.headers.get("X-Forwarded-For", "").split(",")[0].strip()
if xff:
return xff
real_ip = request.headers.get("X-Real-IP", "").strip()
if real_ip:
return real_ip
except ValueError:
pass
return peer
@dataclass
class _Record:
failures: int = 0
window_start: float = field(default_factory=time.time)
blocked_until: float = 0.0
class LoginRateLimiter:
def __init__(
self,
max_failures: int = 5,
window_seconds: int = 300,
cooldown_seconds: int = 900,
) -> None:
self._max = max_failures
self._window = window_seconds
self._cooldown = cooldown_seconds
self._store: dict[str, _Record] = {}
self._lock = Lock()
@property
def cooldown_seconds(self) -> int:
return self._cooldown
def is_blocked(self, ip: str) -> bool:
now = time.time()
with self._lock:
rec = self._store.get(ip)
if rec is None:
return False
if rec.blocked_until > now:
return True
if rec.blocked_until > 0:
del self._store[ip]
return False
def record_failure(self, ip: str) -> None:
now = time.time()
with self._lock:
rec = self._store.get(ip)
if rec is None:
rec = _Record(window_start=now)
self._store[ip] = rec
if now - rec.window_start > self._window:
rec.failures = 0
rec.window_start = now
rec.failures += 1
if rec.failures >= self._max:
rec.blocked_until = now + self._cooldown
logger.warning(
"Login blocked for %s after %d failures", ip, rec.failures
)
def record_success(self, ip: str) -> None:
with self._lock:
self._store.pop(ip, None)

View File

@@ -1,4 +1,5 @@
from functools import lru_cache
from pydantic_settings import BaseSettings, SettingsConfigDict
@@ -13,6 +14,14 @@ class Settings(BaseSettings):
s3_region: str = "us-east-1"
api_base_url: str = "http://localhost:8000"
max_upload_bytes: int = 52_428_800 # 50 MiB
jwt_secret_key: str
jwt_expiry_seconds: int = 86400
owner_username: str
owner_password: str
login_max_failures: int = 5
login_window_seconds: int = 300
login_cooldown_seconds: int = 900
login_trusted_proxy_ips: str = ""
@lru_cache

View File

@@ -1,4 +1,4 @@
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from app.config import get_settings

View File

@@ -1,10 +1,10 @@
from typing import AsyncGenerator
from collections.abc import AsyncGenerator
from fastapi import Depends
from fastapi import Depends, Header, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.noop import NoOpAuthProvider
from app.auth.provider import AuthProvider
from app.auth.jwt_provider import JWTAuthProvider
from app.auth.provider import AuthProvider, Identity
from app.database import get_session_factory
from app.storage.backend import StorageBackend
from app.storage.s3_backend import S3StorageBackend
@@ -23,12 +23,38 @@ def get_storage() -> StorageBackend:
def get_auth() -> AuthProvider:
global _auth
if _auth is None:
_auth = NoOpAuthProvider()
from app.config import get_settings
s = get_settings()
_auth = JWTAuthProvider(
secret_key=s.jwt_secret_key,
expiry_seconds=s.jwt_expiry_seconds,
owner_username=s.owner_username,
owner_password=s.owner_password,
)
return _auth
def get_jwt_auth() -> JWTAuthProvider:
auth = get_auth()
assert isinstance(auth, JWTAuthProvider)
return auth
async def require_auth(
authorization: str | None = Header(None, alias="Authorization"),
auth: AuthProvider = Depends(get_auth),
) -> Identity:
identity = await auth.get_identity(authorization)
if identity.anonymous:
raise HTTPException(
status_code=401,
detail={"detail": "Authentication required", "code": "unauthorized"},
)
return identity
async def get_db() -> AsyncGenerator[AsyncSession, None]:
factory = get_session_factory()
async with factory() as session:
async with session.begin():
yield session
async with factory() as session, session.begin():
yield session

View File

@@ -1,17 +1,30 @@
from contextlib import asynccontextmanager
import ipaddress
from contextlib import asynccontextmanager, suppress
from fastapi import FastAPI, Request
from fastapi.exceptions import HTTPException
from fastapi.responses import JSONResponse
from app.auth.rate_limiter import LoginRateLimiter
from app.config import get_settings
from app.database import get_engine, get_session_factory, Base
from app.database import Base, get_engine
@asynccontextmanager
async def lifespan(application: FastAPI):
settings = get_settings()
# Verify DB connection and run migrations on startup
application.state.login_rate_limiter = LoginRateLimiter(
max_failures=settings.login_max_failures,
window_seconds=settings.login_window_seconds,
cooldown_seconds=settings.login_cooldown_seconds,
)
trusted_networks = []
for part in settings.login_trusted_proxy_ips.split(","):
part = part.strip()
if part:
with suppress(ValueError):
trusted_networks.append(ipaddress.ip_network(part, strict=False))
application.state.login_trusted_networks = trusted_networks
engine = get_engine()
async with engine.begin() as conn:
# In production, Alembic handles migrations; this is a dev convenience
@@ -22,6 +35,10 @@ async def lifespan(application: FastAPI):
app = FastAPI(title="Reactbin API", version="1.0.0", lifespan=lifespan)
# Defaults so app.state is populated even when lifespan doesn't run (e.g. tests)
app.state.login_rate_limiter = LoginRateLimiter()
app.state.login_trusted_networks = []
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
@@ -36,7 +53,8 @@ async def health():
# Routers registered after all modules are defined to avoid circular imports
from app.routers import images, tags # noqa: E402
from app.routers import auth, images, tags # noqa: E402
app.include_router(auth.router, prefix="/api/v1")
app.include_router(images.router, prefix="/api/v1")
app.include_router(tags.router, prefix="/api/v1")

View File

@@ -1,7 +1,7 @@
import uuid
from datetime import datetime, timezone
from datetime import UTC, datetime
from sqlalchemy import String, Integer, BigInteger, DateTime, ForeignKey, UniqueConstraint, Index
from sqlalchemy import BigInteger, DateTime, ForeignKey, Index, Integer, String, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
@@ -9,7 +9,7 @@ from app.database import Base
def _utcnow() -> datetime:
return datetime.now(timezone.utc)
return datetime.now(UTC)
class Image(Base):
@@ -23,9 +23,14 @@ class Image(Base):
width: Mapped[int] = mapped_column(Integer, nullable=False)
height: Mapped[int] = mapped_column(Integer, nullable=False)
storage_key: Mapped[str] = mapped_column(String(64), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, nullable=False)
thumbnail_key: Mapped[str | None] = mapped_column(String(70), nullable=True, default=None)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=_utcnow, nullable=False
)
image_tags: Mapped[list["ImageTag"]] = relationship(back_populates="image", cascade="all, delete-orphan")
image_tags: Mapped[list["ImageTag"]] = relationship(
back_populates="image", cascade="all, delete-orphan"
)
@property
def tags(self) -> list[str]:
@@ -37,7 +42,9 @@ class Tag(Base):
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name: Mapped[str] = mapped_column(String(64), unique=True, nullable=False, index=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=_utcnow, nullable=False
)
image_tags: Mapped[list["ImageTag"]] = relationship(back_populates="tag")

View File

@@ -1,5 +1,4 @@
import uuid
from typing import Optional
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -12,15 +11,19 @@ class ImageRepository:
def __init__(self, session: AsyncSession) -> None:
self._session = session
async def get_by_hash(self, hash_hex: str) -> Optional[Image]:
async def get_by_hash(self, hash_hex: str) -> Image | None:
result = await self._session.execute(
select(Image).where(Image.hash == hash_hex).options(selectinload(Image.image_tags).selectinload(ImageTag.tag))
select(Image)
.where(Image.hash == hash_hex)
.options(selectinload(Image.image_tags).selectinload(ImageTag.tag))
)
return result.scalar_one_or_none()
async def get_by_id(self, image_id: uuid.UUID) -> Optional[Image]:
async def get_by_id(self, image_id: uuid.UUID) -> Image | None:
result = await self._session.execute(
select(Image).where(Image.id == image_id).options(selectinload(Image.image_tags).selectinload(ImageTag.tag))
select(Image)
.where(Image.id == image_id)
.options(selectinload(Image.image_tags).selectinload(ImageTag.tag))
)
return result.scalar_one_or_none()
@@ -34,6 +37,7 @@ class ImageRepository:
width: int,
height: int,
storage_key: str,
thumbnail_key: str | None = None,
) -> Image:
image = Image(
hash=hash_hex,
@@ -43,6 +47,7 @@ class ImageRepository:
width=width,
height=height,
storage_key=storage_key,
thumbnail_key=thumbnail_key,
)
self._session.add(image)
await self._session.flush()
@@ -55,7 +60,7 @@ class ImageRepository:
limit: int = 50,
offset: int = 0,
) -> tuple[list[Image], int]:
from sqlalchemy import func, and_
from sqlalchemy import func
base_query = select(Image).options(
selectinload(Image.image_tags).selectinload(ImageTag.tag)

View File

@@ -1,7 +1,7 @@
import re
import uuid
from sqlalchemy import select, func
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models import Image, ImageTag, Tag
@@ -76,6 +76,8 @@ class TagRepository:
prefix: str | None = None,
limit: int = 100,
offset: int = 0,
sort: str = "name",
min_count: int = 0,
) -> tuple[list[dict], int]:
count_subq = (
select(func.count(ImageTag.image_id))
@@ -87,12 +89,16 @@ class TagRepository:
query = select(Tag, count_subq.label("image_count"))
if prefix:
query = query.where(Tag.name.like(f"{prefix}%"))
if min_count > 0:
query = query.where(count_subq >= min_count)
total_query = select(func.count()).select_from(query.subquery())
total_result = await self._session.execute(total_query)
total = total_result.scalar_one()
paginated = query.order_by(Tag.name).limit(limit).offset(offset)
order = [count_subq.desc(), Tag.name.asc()] if sort == "count_desc" else [Tag.name.asc()]
paginated = query.order_by(*order).limit(limit).offset(offset)
rows = await self._session.execute(paginated)
items = [

55
api/app/routers/auth.py Normal file
View File

@@ -0,0 +1,55 @@
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from app.auth.jwt_provider import JWTAuthProvider
from app.auth.rate_limiter import LoginRateLimiter, get_client_ip
from app.dependencies import get_jwt_auth
router = APIRouter(tags=["auth"])
class LoginRequest(BaseModel):
username: str
password: str
class TokenResponse(BaseModel):
access_token: str
token_type: str = "bearer"
expires_in: int
@router.post("/auth/token", response_model=TokenResponse)
async def login(
request: Request,
body: LoginRequest,
auth: JWTAuthProvider = Depends(get_jwt_auth),
):
limiter: LoginRateLimiter = request.app.state.login_rate_limiter
ip: str = get_client_ip(request, request.app.state.login_trusted_networks)
if limiter.is_blocked(ip):
return JSONResponse(
status_code=429,
content={
"detail": "Too many failed login attempts. Please try again later.",
"code": "login_rate_limited",
},
headers={"Retry-After": str(limiter.cooldown_seconds)},
)
if not auth.verify_credentials(body.username, body.password):
limiter.record_failure(ip)
raise HTTPException(
status_code=401,
detail={"detail": "Invalid credentials", "code": "invalid_credentials"},
)
limiter.record_success(ip)
token = auth.create_token()
return TokenResponse(
access_token=token,
token_type="bearer",
expires_in=auth._expiry_seconds,
)

View File

@@ -1,3 +1,5 @@
import asyncio
import logging
import struct
import uuid
from typing import Any
@@ -5,16 +7,19 @@ from typing import Any
from fastapi import APIRouter, Depends, File, Form, HTTPException, Response, UploadFile
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.provider import AuthProvider
from app.auth.provider import Identity
from app.config import get_settings
from app.dependencies import get_auth, get_db, get_storage
from app.dependencies import get_db, get_storage, require_auth
from app.models import Image
from app.repositories.image_repo import ImageRepository
from app.repositories.tag_repo import TagRepository
from app.storage.backend import StorageBackend
from app.thumbnail import generate_thumbnail
from app.utils import compute_sha256
from app.validation import FileSizeError, MimeTypeError, validate_file_size, validate_mime_type
logger = logging.getLogger(__name__)
router = APIRouter(tags=["images"])
@@ -32,6 +37,7 @@ def _image_to_dict(image: Image, *, duplicate: bool | None = None) -> dict[str,
"width": image.width,
"height": image.height,
"storage_key": image.storage_key,
"thumbnail_key": image.thumbnail_key,
"created_at": image.created_at.isoformat(),
"tags": image.tags,
}
@@ -103,7 +109,7 @@ async def upload_image(
tags: str | None = Form(None),
db: AsyncSession = Depends(get_db),
storage: StorageBackend = Depends(get_storage),
auth: AuthProvider = Depends(get_auth),
_: Identity = Depends(require_auth),
settings=Depends(get_settings),
):
data = await file.read()
@@ -151,6 +157,16 @@ async def upload_image(
width, height = _read_image_dimensions(data, mime_type)
await storage.put(hash_hex, data, mime_type)
thumbnail_key: str | None = None
try:
thumb_bytes = await asyncio.to_thread(generate_thumbnail, data, mime_type)
await storage.put(f"{hash_hex}-thumb", thumb_bytes, "image/webp")
thumbnail_key = f"{hash_hex}-thumb"
except Exception:
logger.warning(
"Thumbnail generation failed for %s; upload will proceed without thumbnail", hash_hex
)
image = await image_repo.create(
hash_hex=hash_hex,
filename=file.filename or "upload",
@@ -159,6 +175,7 @@ async def upload_image(
width=width,
height=height,
storage_key=hash_hex,
thumbnail_key=thumbnail_key,
)
if tag_names:
@@ -233,11 +250,44 @@ async def serve_image_file(
)
@router.get("/images/{image_id}/thumbnail")
async def serve_image_thumbnail(
image_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
storage: StorageBackend = Depends(get_storage),
):
image_repo = ImageRepository(db)
image = await image_repo.get_by_id(image_id)
if not image:
raise HTTPException(
status_code=404,
detail={"detail": "Image not found", "code": "image_not_found"},
)
key = image.thumbnail_key or image.storage_key
media_type = "image/webp" if image.thumbnail_key else image.mime_type
try:
data = await storage.get(key)
except Exception:
raise HTTPException(
status_code=500,
detail={"detail": "Failed to retrieve image content", "code": "storage_error"},
) from None
return Response(
content=data,
media_type=media_type,
headers={
"ETag": f'"{image.hash}"',
"Cache-Control": "public, max-age=31536000, immutable",
},
)
@router.patch("/images/{image_id}/tags")
async def update_image_tags(
image_id: uuid.UUID,
body: dict,
db: AsyncSession = Depends(get_db),
_: Identity = Depends(require_auth),
):
image_repo = ImageRepository(db)
image = await image_repo.get_by_id(image_id)
@@ -267,6 +317,7 @@ async def delete_image(
image_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
storage: StorageBackend = Depends(get_storage),
_: Identity = Depends(require_auth),
):
image_repo = ImageRepository(db)
image = await image_repo.get_by_id(image_id)
@@ -276,6 +327,9 @@ async def delete_image(
detail={"detail": "Image not found", "code": "image_not_found"},
)
storage_key = image.storage_key
thumbnail_key = image.thumbnail_key
await image_repo.delete(image)
await storage.delete(storage_key)
if thumbnail_key:
await storage.delete(thumbnail_key)
return Response(status_code=204)

View File

@@ -12,9 +12,13 @@ async def list_tags(
q: str | None = None,
limit: int = 100,
offset: int = 0,
sort: str = "name",
min_count: int = 0,
db: AsyncSession = Depends(get_db),
):
limit = min(limit, 200)
limit = min(limit, 500)
tag_repo = TagRepository(db)
items, total = await tag_repo.list_tags(prefix=q, limit=limit, offset=offset)
items, total = await tag_repo.list_tags(
prefix=q, limit=limit, offset=offset, sort=sort, min_count=min_count
)
return {"items": items, "total": total, "limit": limit, "offset": offset}

16
api/app/thumbnail.py Normal file
View File

@@ -0,0 +1,16 @@
import contextlib
import io
from PIL import Image
def generate_thumbnail(data: bytes, mime_type: str) -> bytes:
img = Image.open(io.BytesIO(data))
with contextlib.suppress(EOFError):
img.seek(0)
if img.mode not in ("RGB", "RGBA"):
img = img.convert("RGBA" if img.mode == "P" and "transparency" in img.info else "RGB")
img.thumbnail((400, 400), Image.LANCZOS)
buf = io.BytesIO()
img.save(buf, format="WEBP", quality=80)
return buf.getvalue()

View File

@@ -15,6 +15,8 @@ dependencies = [
"aiobotocore>=2.13",
"pydantic-settings>=2.2",
"python-multipart>=0.0.9",
"pillow>=10.0",
"PyJWT>=2.8",
]
[project.optional-dependencies]
@@ -31,7 +33,10 @@ target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "SIM"]
ignore = []
ignore = [
"B008", # FastAPI Depends/File/Form in function signatures — intentional
"B904", # raise-without-from inside except — HTTPException re-raise pattern
]
[tool.pytest.ini_options]
asyncio_mode = "auto"
@@ -42,3 +47,11 @@ testpaths = ["tests"]
[tool.setuptools.packages.find]
where = ["."]
include = ["app*"]
[dependency-groups]
dev = [
"anyio>=4.13.0",
"httpx>=0.28.1",
"pytest>=9.0.3",
"pytest-asyncio>=1.3.0",
]

View File

@@ -1,19 +1,32 @@
import os
import pytest
import pytest_asyncio
from httpx import AsyncClient, ASGITransport
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.main import app
from app.config import get_settings
from app.database import Base
from app.dependencies import get_db, get_storage, get_auth
# Provide required settings for the test environment before any app imports resolve them
os.environ.setdefault("JWT_SECRET_KEY", "test-secret-key-for-testing-only")
os.environ.setdefault("OWNER_USERNAME", "testowner")
os.environ.setdefault("OWNER_PASSWORD", "testpassword")
from app.auth.jwt_provider import JWTAuthProvider # noqa: E402
from app.config import get_settings # noqa: E402
from app.database import Base # noqa: E402
from app.dependencies import get_auth, get_db, get_storage # noqa: E402
from app.main import app # noqa: E402
# Bust the LRU cache so get_settings() picks up the env vars set above
get_settings.cache_clear()
_TEST_JWT_SECRET = os.environ["JWT_SECRET_KEY"]
_TEST_OWNER_USERNAME = os.environ["OWNER_USERNAME"]
_TEST_OWNER_PASSWORD = os.environ["OWNER_PASSWORD"]
@pytest_asyncio.fixture(scope="session", loop_scope="session")
async def engine():
settings = get_settings()
# Use a separate test database URL if TEST_DATABASE_URL is set
import os
db_url = os.getenv("TEST_DATABASE_URL", settings.database_url)
eng = create_async_engine(db_url, echo=False)
async with eng.begin() as conn:
@@ -34,8 +47,8 @@ async def db_session(engine):
@pytest_asyncio.fixture
async def client(db_session):
from app.storage.s3_backend import S3StorageBackend
from app.auth.noop import NoOpAuthProvider
from app.storage.s3_backend import S3StorageBackend
storage = S3StorageBackend()
auth = NoOpAuthProvider()
@@ -57,3 +70,52 @@ async def client(db_session):
yield c
app.dependency_overrides.clear()
@pytest_asyncio.fixture
async def jwt_auth_provider() -> JWTAuthProvider:
return JWTAuthProvider(
secret_key=_TEST_JWT_SECRET,
expiry_seconds=3600,
owner_username=_TEST_OWNER_USERNAME,
owner_password=_TEST_OWNER_PASSWORD,
)
@pytest_asyncio.fixture
async def authed_client(db_session, jwt_auth_provider):
from app.storage.s3_backend import S3StorageBackend
storage = S3StorageBackend()
auth = jwt_auth_provider
async def override_db():
yield db_session
def override_storage():
return storage
def override_auth():
return auth
app.dependency_overrides[get_db] = override_db
app.dependency_overrides[get_storage] = override_storage
app.dependency_overrides[get_auth] = override_auth
valid_token = auth.create_token()
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
yield c, valid_token
app.dependency_overrides.clear()
def pytest_configure(config):
db_url = os.getenv("TEST_DATABASE_URL") or os.getenv("DATABASE_URL", "")
if not db_url.startswith("postgresql+asyncpg://"):
pytest.exit(
"Integration tests require a PostgreSQL database "
"(postgresql+asyncpg://...). "
"Set TEST_DATABASE_URL or DATABASE_URL accordingly. "
f"Got: {db_url!r}",
returncode=1,
)

View File

@@ -0,0 +1,51 @@
import pytest
_VALID_CREDS = {"username": "testowner", "password": "testpassword"}
@pytest.mark.asyncio
async def test_login_success(authed_client):
client, _ = authed_client
response = await client.post("/api/v1/auth/token", json=_VALID_CREDS)
assert response.status_code == 200
body = response.json()
assert isinstance(body.get("access_token"), str)
assert len(body["access_token"]) > 0
assert body.get("token_type") == "bearer"
assert body.get("expires_in", 0) > 0
@pytest.mark.asyncio
async def test_login_wrong_password(authed_client):
client, _ = authed_client
response = await client.post(
"/api/v1/auth/token",
json={"username": "testowner", "password": "wrongpassword"},
)
assert response.status_code == 401
assert response.json().get("code") == "invalid_credentials"
@pytest.mark.asyncio
async def test_login_wrong_username(authed_client):
client, _ = authed_client
response = await client.post(
"/api/v1/auth/token",
json={"username": "notowner", "password": "testpassword"},
)
assert response.status_code == 401
assert response.json().get("code") == "invalid_credentials"
@pytest.mark.asyncio
async def test_login_missing_password(authed_client):
client, _ = authed_client
response = await client.post("/api/v1/auth/token", json={"username": "testowner"})
assert response.status_code == 422
@pytest.mark.asyncio
async def test_login_missing_username(authed_client):
client, _ = authed_client
response = await client.post("/api/v1/auth/token", json={"password": "testpassword"})
assert response.status_code == 422

View File

@@ -5,7 +5,9 @@ T067 — DELETE of unknown ID → 404 image_not_found
"""
import io
import uuid
import pytest
from PIL import Image as PILImage
def _minimal_jpeg_v2() -> bytes:
@@ -17,15 +19,18 @@ def _minimal_jpeg_v2() -> bytes:
@pytest.mark.asyncio
async def test_delete_removes_record(client):
async def test_delete_removes_record(authed_client):
client, token = authed_client
headers = {"Authorization": f"Bearer {token}"}
data = _minimal_jpeg_v2()
upload = await client.post(
"/api/v1/images",
files={"file": ("del-test.jpg", io.BytesIO(data), "image/jpeg")},
headers=headers,
)
image_id = upload.json()["id"]
delete_resp = await client.delete(f"/api/v1/images/{image_id}")
delete_resp = await client.delete(f"/api/v1/images/{image_id}", headers=headers)
assert delete_resp.status_code == 204
get_resp = await client.get(f"/api/v1/images/{image_id}")
@@ -34,17 +39,19 @@ async def test_delete_removes_record(client):
@pytest.mark.asyncio
async def test_delete_removes_storage_object(client):
async def test_delete_removes_storage_object(authed_client):
client, token = authed_client
headers = {"Authorization": f"Bearer {token}"}
data = _minimal_jpeg_v2() + b"\x00"
upload = await client.post(
"/api/v1/images",
files={"file": ("del-storage-test.jpg", io.BytesIO(data), "image/jpeg")},
headers=headers,
)
assert upload.status_code in (200, 201)
image_id = upload.json()["id"]
storage_key = upload.json()["hash"]
delete_resp = await client.delete(f"/api/v1/images/{image_id}")
delete_resp = await client.delete(f"/api/v1/images/{image_id}", headers=headers)
assert delete_resp.status_code == 204
# Confirm storage redirect no longer works (404 since record is gone)
@@ -53,8 +60,37 @@ async def test_delete_removes_storage_object(client):
@pytest.mark.asyncio
async def test_delete_unknown_id_returns_404(client):
response = await client.delete(f"/api/v1/images/{uuid.uuid4()}")
async def test_delete_unknown_id_returns_404(authed_client):
client, token = authed_client
response = await client.delete(
f"/api/v1/images/{uuid.uuid4()}",
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code == 404
body = response.json()
assert body["code"] == "image_not_found"
@pytest.mark.asyncio
async def test_delete_removes_thumbnail(authed_client):
client, token = authed_client
headers = {"Authorization": f"Bearer {token}"}
buf = io.BytesIO()
PILImage.new("RGB", (200, 150), color=(60, 90, 120)).save(buf, format="JPEG")
data = buf.getvalue()
upload = await client.post(
"/api/v1/images",
files={"file": ("thumb-del.jpg", io.BytesIO(data), "image/jpeg")},
headers=headers,
)
assert upload.status_code == 201
image_id = upload.json()["id"]
assert upload.json()["thumbnail_key"] is not None
delete_resp = await client.delete(f"/api/v1/images/{image_id}", headers=headers)
assert delete_resp.status_code == 204
thumb_resp = await client.get(f"/api/v1/images/{image_id}/thumbnail")
assert thumb_resp.status_code == 404
assert thumb_resp.json()["code"] == "image_not_found"

View File

@@ -0,0 +1,121 @@
import os
import pytest
from httpx import AsyncClient
from app.auth.rate_limiter import LoginRateLimiter
from app.main import app
BAD_CREDS = {"username": "attacker", "password": "wrong"}
VALID_CREDS = {
"username": os.environ.get("OWNER_USERNAME", "testowner"),
"password": os.environ.get("OWNER_PASSWORD", "testpassword"),
}
def _fresh_limiter():
return LoginRateLimiter(max_failures=3, window_seconds=60, cooldown_seconds=30)
@pytest.mark.asyncio
async def test_repeated_failures_trigger_429(client: AsyncClient):
original_limiter = app.state.login_rate_limiter
original_networks = app.state.login_trusted_networks
app.state.login_rate_limiter = _fresh_limiter()
app.state.login_trusted_networks = []
try:
for _ in range(3):
await client.post("/api/v1/auth/token", json=BAD_CREDS)
resp = await client.post("/api/v1/auth/token", json=BAD_CREDS)
assert resp.status_code == 429
assert resp.json()["code"] == "login_rate_limited"
finally:
app.state.login_rate_limiter = original_limiter
app.state.login_trusted_networks = original_networks
@pytest.mark.asyncio
async def test_success_resets_counter(client: AsyncClient):
original_limiter = app.state.login_rate_limiter
original_networks = app.state.login_trusted_networks
app.state.login_rate_limiter = _fresh_limiter()
app.state.login_trusted_networks = []
try:
for _ in range(2):
await client.post("/api/v1/auth/token", json=BAD_CREDS)
await client.post("/api/v1/auth/token", json=VALID_CREDS)
for _ in range(3):
resp = await client.post("/api/v1/auth/token", json=BAD_CREDS)
assert resp.status_code == 401, "counter should have reset after success"
finally:
app.state.login_rate_limiter = original_limiter
app.state.login_trusted_networks = original_networks
@pytest.mark.asyncio
async def test_429_has_retry_after_header(client: AsyncClient):
original_limiter = app.state.login_rate_limiter
original_networks = app.state.login_trusted_networks
app.state.login_rate_limiter = _fresh_limiter()
app.state.login_trusted_networks = []
try:
for _ in range(3):
await client.post("/api/v1/auth/token", json=BAD_CREDS)
resp = await client.post("/api/v1/auth/token", json=BAD_CREDS)
assert resp.status_code == 429
assert "Retry-After" in resp.headers
assert int(resp.headers["Retry-After"]) > 0
finally:
app.state.login_rate_limiter = original_limiter
app.state.login_trusted_networks = original_networks
@pytest.mark.asyncio
async def test_429_body_shape(client: AsyncClient):
original_limiter = app.state.login_rate_limiter
original_networks = app.state.login_trusted_networks
app.state.login_rate_limiter = _fresh_limiter()
app.state.login_trusted_networks = []
try:
for _ in range(3):
await client.post("/api/v1/auth/token", json=BAD_CREDS)
resp = await client.post("/api/v1/auth/token", json=BAD_CREDS)
assert resp.status_code == 429
assert resp.json() == {
"detail": "Too many failed login attempts. Please try again later.",
"code": "login_rate_limited",
}
finally:
app.state.login_rate_limiter = original_limiter
app.state.login_trusted_networks = original_networks
@pytest.mark.asyncio
async def test_xff_header_ignored_when_no_trusted_networks(client: AsyncClient):
original_limiter = app.state.login_rate_limiter
original_networks = app.state.login_trusted_networks
app.state.login_rate_limiter = _fresh_limiter()
app.state.login_trusted_networks = []
try:
# Send 3 failures all claiming to be "1.2.3.4" via XFF
for _ in range(3):
await client.post(
"/api/v1/auth/token",
json=BAD_CREDS,
headers={"X-Forwarded-For": "1.2.3.4"},
)
# 4th request with a *different* XFF — if XFF were trusted, this
# would appear to be a fresh IP and get 401. Since XFF is ignored,
# the real peer ("testclient") is blocked and we get 429.
resp = await client.post(
"/api/v1/auth/token",
json=BAD_CREDS,
headers={"X-Forwarded-For": "9.9.9.9"},
)
assert resp.status_code == 429, (
"XFF should be ignored when no trusted networks are configured; "
"expected real peer to be blocked"
)
finally:
app.state.login_rate_limiter = original_limiter
app.state.login_trusted_networks = original_networks

View File

@@ -0,0 +1,95 @@
"""
Tests that write endpoints require authentication (US2).
These use the authed_client fixture which wires JWTAuthProvider.
"""
import io
import uuid
import pytest
def _minimal_jpeg() -> bytes:
return (
b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x02"
b"\xff\xd9"
)
@pytest.mark.asyncio
async def test_upload_without_token_returns_401(authed_client):
client, _ = authed_client
data = _minimal_jpeg()
response = await client.post(
"/api/v1/images",
files={"file": ("test.jpg", io.BytesIO(data), "image/jpeg")},
)
assert response.status_code == 401
assert response.json().get("code") == "unauthorized"
@pytest.mark.asyncio
async def test_upload_with_valid_token_succeeds(authed_client):
client, token = authed_client
data = _minimal_jpeg()
response = await client.post(
"/api/v1/images",
files={"file": ("test.jpg", io.BytesIO(data), "image/jpeg")},
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code in (200, 201)
@pytest.mark.asyncio
async def test_delete_without_token_returns_401(authed_client):
client, _ = authed_client
fake_id = uuid.uuid4()
response = await client.delete(f"/api/v1/images/{fake_id}")
assert response.status_code == 401
assert response.json().get("code") == "unauthorized"
@pytest.mark.asyncio
async def test_delete_with_valid_token_succeeds(authed_client):
client, token = authed_client
data = _minimal_jpeg()
upload = await client.post(
"/api/v1/images",
files={"file": ("del-protected.jpg", io.BytesIO(data), "image/jpeg")},
headers={"Authorization": f"Bearer {token}"},
)
image_id = upload.json()["id"]
response = await client.delete(
f"/api/v1/images/{image_id}",
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code == 204
@pytest.mark.asyncio
async def test_patch_tags_without_token_returns_401(authed_client):
client, _ = authed_client
fake_id = uuid.uuid4()
response = await client.patch(
f"/api/v1/images/{fake_id}/tags",
json={"tags": ["a"]},
)
assert response.status_code == 401
assert response.json().get("code") == "unauthorized"
@pytest.mark.asyncio
async def test_patch_tags_with_valid_token_succeeds(authed_client):
client, token = authed_client
data = _minimal_jpeg()
upload = await client.post(
"/api/v1/images",
files={"file": ("tag-protected.jpg", io.BytesIO(data), "image/jpeg")},
headers={"Authorization": f"Bearer {token}"},
)
image_id = upload.json()["id"]
response = await client.patch(
f"/api/v1/images/{image_id}/tags",
json={"tags": ["protected-tag"]},
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code == 200

View File

@@ -0,0 +1,70 @@
"""
US3 regression tests: all read endpoints must remain accessible without a token
even after require_auth is applied to write endpoints.
"""
import io
import pytest
def _minimal_jpeg() -> bytes:
return (
b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x03"
b"\xff\xd9"
)
@pytest.mark.asyncio
async def test_list_images_without_token_is_200(authed_client):
client, _ = authed_client
response = await client.get("/api/v1/images")
assert response.status_code == 200
@pytest.mark.asyncio
async def test_get_image_without_token_is_200(authed_client):
client, token = authed_client
data = _minimal_jpeg()
upload = await client.post(
"/api/v1/images",
files={"file": ("pub-test.jpg", io.BytesIO(data), "image/jpeg")},
headers={"Authorization": f"Bearer {token}"},
)
image_id = upload.json()["id"]
response = await client.get(f"/api/v1/images/{image_id}")
assert response.status_code == 200
@pytest.mark.asyncio
async def test_serve_file_without_token_is_200(authed_client):
client, token = authed_client
data = _minimal_jpeg()
upload = await client.post(
"/api/v1/images",
files={"file": ("pub-file.jpg", io.BytesIO(data), "image/jpeg")},
headers={"Authorization": f"Bearer {token}"},
)
image_id = upload.json()["id"]
response = await client.get(f"/api/v1/images/{image_id}/file")
assert response.status_code == 200
@pytest.mark.asyncio
async def test_serve_thumbnail_without_token_is_200(authed_client):
client, token = authed_client
data = _minimal_jpeg()
upload = await client.post(
"/api/v1/images",
files={"file": ("pub-thumb.jpg", io.BytesIO(data), "image/jpeg")},
headers={"Authorization": f"Bearer {token}"},
)
image_id = upload.json()["id"]
response = await client.get(f"/api/v1/images/{image_id}/thumbnail")
assert response.status_code == 200
@pytest.mark.asyncio
async def test_list_tags_without_token_is_200(authed_client):
client, _ = authed_client
response = await client.get("/api/v1/tags")
assert response.status_code == 200

View File

@@ -3,6 +3,7 @@ T041 — GET /api/v1/images?tags=cat,funny → only images with both tags
T042 — same query excludes images with only one matching tag
"""
import io
import pytest
@@ -15,7 +16,9 @@ def _minimal_gif() -> bytes:
@pytest.mark.asyncio
async def test_and_filter_returns_only_matching_images(client):
async def test_and_filter_returns_only_matching_images(authed_client):
client, token = authed_client
headers = {"Authorization": f"Bearer {token}"}
data = _minimal_gif()
# Image with both tags
@@ -23,6 +26,7 @@ async def test_and_filter_returns_only_matching_images(client):
"/api/v1/images",
files={"file": ("both.gif", io.BytesIO(data), "image/gif")},
data={"tags": "andcat,andfunny"},
headers=headers,
)
both_id = r_both.json()["id"]
@@ -31,6 +35,7 @@ async def test_and_filter_returns_only_matching_images(client):
"/api/v1/images",
files={"file": ("one.gif", io.BytesIO(data + b"\x00"), "image/gif")},
data={"tags": "andcat"},
headers=headers,
)
response = await client.get("/api/v1/images?tags=andcat,andfunny")
@@ -42,7 +47,9 @@ async def test_and_filter_returns_only_matching_images(client):
@pytest.mark.asyncio
async def test_filter_excludes_partial_tag_match(client):
async def test_filter_excludes_partial_tag_match(authed_client):
client, token = authed_client
headers = {"Authorization": f"Bearer {token}"}
data = _minimal_gif()
# Image with only "exclcat"
@@ -50,6 +57,7 @@ async def test_filter_excludes_partial_tag_match(client):
"/api/v1/images",
files={"file": ("partial.gif", io.BytesIO(data + b"\x01"), "image/gif")},
data={"tags": "exclcat"},
headers=headers,
)
# Filter requires both exclcat and exclother

View File

@@ -7,6 +7,16 @@ import io
import uuid
import pytest
from PIL import Image as PILImage
from sqlalchemy import update
from app.models import Image
def _real_jpeg() -> bytes:
buf = io.BytesIO()
PILImage.new("RGB", (200, 150), color=(120, 80, 200)).save(buf, format="JPEG")
return buf.getvalue()
def _minimal_webp() -> bytes:
@@ -19,11 +29,13 @@ def _minimal_webp() -> bytes:
@pytest.mark.asyncio
async def test_file_returns_200_with_content(client):
async def test_file_returns_200_with_content(authed_client):
client, token = authed_client
data = _minimal_webp()
upload = await client.post(
"/api/v1/images",
files={"file": ("img.webp", io.BytesIO(data), "image/webp")},
headers={"Authorization": f"Bearer {token}"},
)
assert upload.status_code in (200, 201)
upload_body = upload.json()
@@ -47,11 +59,13 @@ async def test_file_unknown_id_returns_404(client):
@pytest.mark.asyncio
async def test_file_response_exposes_no_storage_details(client):
async def test_file_response_exposes_no_storage_details(authed_client):
client, token = authed_client
data = _minimal_webp()
upload = await client.post(
"/api/v1/images",
files={"file": ("img.webp", io.BytesIO(data), "image/webp")},
headers={"Authorization": f"Bearer {token}"},
)
assert upload.status_code in (200, 201)
image_id = upload.json()["id"]
@@ -62,3 +76,57 @@ async def test_file_response_exposes_no_storage_details(client):
assert "minio" not in response.text.lower()
assert "s3://" not in response.text.lower()
assert "amazonaws.com" not in response.text.lower()
@pytest.mark.asyncio
async def test_thumbnail_returns_webp(authed_client):
client, token = authed_client
data = _real_jpeg()
upload = await client.post(
"/api/v1/images",
files={"file": ("t.jpg", io.BytesIO(data), "image/jpeg")},
headers={"Authorization": f"Bearer {token}"},
)
assert upload.status_code == 201
body = upload.json()
image_id = body["id"]
image_hash = body["hash"]
response = await client.get(f"/api/v1/images/{image_id}/thumbnail")
assert response.status_code == 200
assert response.headers["content-type"] == "image/webp"
assert response.headers["etag"] == f'"{image_hash}"'
assert "immutable" in response.headers["cache-control"]
assert len(response.content) > 0
@pytest.mark.asyncio
async def test_thumbnail_fallback_returns_original(authed_client, db_session):
client, token = authed_client
data = _real_jpeg()
upload = await client.post(
"/api/v1/images",
files={"file": ("fallback.jpg", io.BytesIO(data), "image/jpeg")},
headers={"Authorization": f"Bearer {token}"},
)
assert upload.status_code == 201
image_id = upload.json()["id"]
await db_session.execute(
update(Image).where(Image.id == uuid.UUID(image_id)).values(thumbnail_key=None)
)
await db_session.flush()
db_session.expire_all()
response = await client.get(f"/api/v1/images/{image_id}/thumbnail")
assert response.status_code == 200
assert "image/jpeg" in response.headers["content-type"]
assert len(response.content) > 0
@pytest.mark.asyncio
async def test_thumbnail_unknown_id_returns_404(client):
response = await client.get(f"/api/v1/images/{uuid.uuid4()}/thumbnail")
assert response.status_code == 404
body = response.json()
assert body["code"] == "image_not_found"

View File

@@ -5,13 +5,17 @@ T057 — PATCH replaces tags, old tags unlinked, new tags upserted
T058 — PATCH with invalid tag → 422 invalid_tag
T073 — GET /api/v1/tags returns all tags alphabetically with correct image_count
T074 — GET /api/v1/tags?q=ca returns only tags prefixed "ca"
T001 — GET /api/v1/tags?sort=count_desc returns tags ordered highest-count-first
T002 — GET /api/v1/tags?min_count=N excludes tags with image_count < N
"""
import io
import pytest
def _minimal_png() -> bytes:
import struct, zlib
import struct
import zlib
def chunk(name: bytes, data: bytes) -> bytes:
c = name + data
return struct.pack(">I", len(data)) + c + struct.pack(">I", zlib.crc32(c) & 0xFFFFFFFF)
@@ -27,12 +31,14 @@ def _minimal_png() -> bytes:
@pytest.mark.asyncio
async def test_upload_with_tags_persists_tags(client):
async def test_upload_with_tags_persists_tags(authed_client):
client, token = authed_client
data = _minimal_png()
response = await client.post(
"/api/v1/images",
files={"file": ("img.png", io.BytesIO(data), "image/png")},
data={"tags": "cat,funny"},
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code == 201
body = response.json()
@@ -40,12 +46,15 @@ async def test_upload_with_tags_persists_tags(client):
@pytest.mark.asyncio
async def test_duplicate_upload_tags_unchanged(client):
async def test_duplicate_upload_tags_unchanged(authed_client):
client, token = authed_client
headers = {"Authorization": f"Bearer {token}"}
data = _minimal_png()
r1 = await client.post(
"/api/v1/images",
files={"file": ("img.png", io.BytesIO(data), "image/png")},
data={"tags": "original-tag"},
headers=headers,
)
assert r1.status_code in (200, 201)
original_tags = set(r1.json()["tags"])
@@ -54,6 +63,7 @@ async def test_duplicate_upload_tags_unchanged(client):
"/api/v1/images",
files={"file": ("img.png", io.BytesIO(data), "image/png")},
data={"tags": "different-tag"},
headers=headers,
)
assert r2.status_code == 200
assert r2.json()["duplicate"] is True
@@ -61,18 +71,22 @@ async def test_duplicate_upload_tags_unchanged(client):
@pytest.mark.asyncio
async def test_patch_replaces_tag_set(client):
async def test_patch_replaces_tag_set(authed_client):
client, token = authed_client
headers = {"Authorization": f"Bearer {token}"}
data = _minimal_png()
r1 = await client.post(
"/api/v1/images",
files={"file": ("patch-test.png", io.BytesIO(data), "image/png")},
data={"tags": "old-tag"},
headers=headers,
)
image_id = r1.json()["id"]
patch = await client.patch(
f"/api/v1/images/{image_id}/tags",
json={"tags": ["new-tag", "another"]},
headers=headers,
)
assert patch.status_code == 200
body = patch.json()
@@ -81,17 +95,21 @@ async def test_patch_replaces_tag_set(client):
@pytest.mark.asyncio
async def test_patch_invalid_tag_returns_422(client):
async def test_patch_invalid_tag_returns_422(authed_client):
client, token = authed_client
headers = {"Authorization": f"Bearer {token}"}
data = _minimal_png()
r1 = await client.post(
"/api/v1/images",
files={"file": ("invalid-tag-test.png", io.BytesIO(data), "image/png")},
headers=headers,
)
image_id = r1.json()["id"]
patch = await client.patch(
f"/api/v1/images/{image_id}/tags",
json={"tags": ["valid", "INVALID TAG WITH SPACES!"]},
headers=headers,
)
assert patch.status_code == 422
body = patch.json()
@@ -99,12 +117,14 @@ async def test_patch_invalid_tag_returns_422(client):
@pytest.mark.asyncio
async def test_list_tags_alphabetical_with_counts(client):
async def test_list_tags_alphabetical_with_counts(authed_client):
client, token = authed_client
data = _minimal_png()
await client.post(
"/api/v1/images",
files={"file": ("tag-list-test.png", io.BytesIO(data), "image/png")},
data={"tags": "zebra,apple"},
headers={"Authorization": f"Bearer {token}"},
)
response = await client.get("/api/v1/tags")
assert response.status_code == 200
@@ -117,12 +137,14 @@ async def test_list_tags_alphabetical_with_counts(client):
@pytest.mark.asyncio
async def test_list_tags_prefix_filter(client):
async def test_list_tags_prefix_filter(authed_client):
client, token = authed_client
data = _minimal_png()
await client.post(
"/api/v1/images",
files={"file": ("prefix-test.png", io.BytesIO(data), "image/png")},
data={"tags": "cat,catfish,caterpillar,dog"},
headers={"Authorization": f"Bearer {token}"},
)
response = await client.get("/api/v1/tags?q=cat")
assert response.status_code == 200
@@ -130,3 +152,70 @@ async def test_list_tags_prefix_filter(client):
for item in body["items"]:
assert item["name"].startswith("cat")
assert not any(item["name"] == "dog" for item in body["items"])
def _unique_png(seed: int) -> bytes:
"""Generate a 1x1 PNG with a seed-determined pixel so each seed produces a distinct hash."""
import struct
import zlib
def chunk(name: bytes, data: bytes) -> bytes:
c = name + data
return struct.pack(">I", len(data)) + c + struct.pack(">I", zlib.crc32(c) & 0xFFFFFFFF)
ihdr = struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0)
r, g, b = (seed * 37) % 256, (seed * 53) % 256, (seed * 71) % 256
idat_data = zlib.compress(bytes([0, r, g, b]))
return (
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", ihdr)
+ chunk(b"IDAT", idat_data)
+ chunk(b"IEND", b"")
)
@pytest.mark.asyncio
async def test_list_tags_sort_count_desc(authed_client):
client, token = authed_client
headers = {"Authorization": f"Bearer {token}"}
# popular-sort-tag appears on 2 images, rare-sort-tag on 1 — verify count_desc ordering
for seed in (100, 101):
await client.post(
"/api/v1/images",
files={"file": (f"sort-{seed}.png", io.BytesIO(_unique_png(seed)), "image/png")},
data={"tags": "popular-sort-tag,rare-sort-tag" if seed == 100 else "popular-sort-tag"},
headers=headers,
)
response = await client.get("/api/v1/tags?sort=count_desc")
assert response.status_code == 200
items = response.json()["items"]
sort_items = [i for i in items if i["name"] in ("popular-sort-tag", "rare-sort-tag")]
assert len(sort_items) == 2
# popular-sort-tag (count=2) must come before rare-sort-tag (count=1)
names = [i["name"] for i in sort_items]
assert names.index("popular-sort-tag") < names.index("rare-sort-tag")
# Counts must be non-increasing
counts = [i["image_count"] for i in items]
assert counts == sorted(counts, reverse=True)
@pytest.mark.asyncio
async def test_list_tags_min_count_excludes_below_threshold(authed_client):
client, token = authed_client
headers = {"Authorization": f"Bearer {token}"}
# common-min-tag appears on 2 images, uncommon-min-tag on 1
for seed in (200, 201):
await client.post(
"/api/v1/images",
files={"file": (f"min-{seed}.png", io.BytesIO(_unique_png(seed)), "image/png")},
data={"tags": "common-min-tag,uncommon-min-tag" if seed == 200 else "common-min-tag"},
headers=headers,
)
# min_count=2 should exclude uncommon-min-tag (count=1) but keep common-min-tag (count=2)
response = await client.get("/api/v1/tags?min_count=2")
assert response.status_code == 200
items = response.json()["items"]
names = [i["name"] for i in items]
assert "common-min-tag" in names
assert "uncommon-min-tag" not in names
# All returned tags must have image_count >= 2
for item in items:
assert item["image_count"] >= 2

View File

@@ -6,7 +6,17 @@ T029 — file > MAX_UPLOAD_BYTES → 422 file_too_large
T079 — GET /api/v1/images/{id} 404 → error envelope shape
"""
import io
import uuid
from unittest.mock import patch
import pytest
from PIL import Image as PILImage
def _real_jpeg(color: tuple = (100, 150, 200), size: tuple = (200, 150)) -> bytes:
buf = io.BytesIO()
PILImage.new("RGB", size, color=color).save(buf, format="JPEG")
return buf.getvalue()
def _minimal_jpeg() -> bytes:
@@ -18,11 +28,13 @@ def _minimal_jpeg() -> bytes:
@pytest.mark.asyncio
async def test_upload_new_image_returns_201(client):
async def test_upload_new_image_returns_201(authed_client):
client, token = authed_client
data = _minimal_jpeg()
response = await client.post(
"/api/v1/images",
files={"file": ("test.jpg", io.BytesIO(data), "image/jpeg")},
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code == 201
body = response.json()
@@ -35,12 +47,15 @@ async def test_upload_new_image_returns_201(client):
@pytest.mark.asyncio
async def test_upload_duplicate_returns_200_with_flag(client):
async def test_upload_duplicate_returns_200_with_flag(authed_client):
client, token = authed_client
data = _minimal_jpeg()
headers = {"Authorization": f"Bearer {token}"}
# First upload
r1 = await client.post(
"/api/v1/images",
files={"file": ("test.jpg", io.BytesIO(data), "image/jpeg")},
headers=headers,
)
assert r1.status_code in (200, 201)
@@ -48,6 +63,7 @@ async def test_upload_duplicate_returns_200_with_flag(client):
r2 = await client.post(
"/api/v1/images",
files={"file": ("test.jpg", io.BytesIO(data), "image/jpeg")},
headers=headers,
)
assert r2.status_code == 200
body = r2.json()
@@ -56,10 +72,12 @@ async def test_upload_duplicate_returns_200_with_flag(client):
@pytest.mark.asyncio
async def test_upload_invalid_mime_type_returns_422(client):
async def test_upload_invalid_mime_type_returns_422(authed_client):
client, token = authed_client
response = await client.post(
"/api/v1/images",
files={"file": ("doc.pdf", io.BytesIO(b"%PDF-1.4"), "application/pdf")},
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code == 422
body = response.json()
@@ -68,10 +86,12 @@ async def test_upload_invalid_mime_type_returns_422(client):
@pytest.mark.asyncio
async def test_upload_oversized_file_returns_422(client):
async def test_upload_oversized_file_returns_422(authed_client):
import os
from app.config import get_settings
client, token = authed_client
os.environ["MAX_UPLOAD_BYTES"] = "10"
get_settings.cache_clear()
@@ -79,6 +99,7 @@ async def test_upload_oversized_file_returns_422(client):
response = await client.post(
"/api/v1/images",
files={"file": ("big.jpg", io.BytesIO(b"x" * 11), "image/jpeg")},
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code == 422
body = response.json()
@@ -90,9 +111,64 @@ async def test_upload_oversized_file_returns_422(client):
@pytest.mark.asyncio
async def test_get_unknown_image_returns_404_with_envelope(client):
import uuid
response = await client.get(f"/api/v1/images/{uuid.uuid4()}")
assert response.status_code == 404
body = response.json()
assert body["code"] == "image_not_found"
assert "detail" in body
@pytest.mark.asyncio
async def test_upload_returns_thumbnail_key(authed_client):
client, token = authed_client
data = _real_jpeg(color=(100, 150, 200))
response = await client.post(
"/api/v1/images",
files={"file": ("thumb_test.jpg", io.BytesIO(data), "image/jpeg")},
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code == 201
body = response.json()
assert "thumbnail_key" in body
assert body["thumbnail_key"] is not None
assert body["thumbnail_key"].endswith("-thumb")
@pytest.mark.asyncio
async def test_duplicate_upload_reuses_thumbnail_key(authed_client):
client, token = authed_client
headers = {"Authorization": f"Bearer {token}"}
data = _real_jpeg(color=(200, 100, 50))
r1 = await client.post(
"/api/v1/images",
files={"file": ("dup.jpg", io.BytesIO(data), "image/jpeg")},
headers=headers,
)
assert r1.status_code in (200, 201)
r2 = await client.post(
"/api/v1/images",
files={"file": ("dup.jpg", io.BytesIO(data), "image/jpeg")},
headers=headers,
)
assert r2.status_code == 200
tk1 = r1.json()["thumbnail_key"]
tk2 = r2.json()["thumbnail_key"]
assert tk1 is not None
assert tk1 == tk2
@pytest.mark.asyncio
async def test_upload_succeeds_when_thumbnail_fails(authed_client):
client, token = authed_client
data = _real_jpeg(color=(50, 200, 150))
with patch("app.routers.images.generate_thumbnail", side_effect=RuntimeError("simulated")):
response = await client.post(
"/api/v1/images",
files={"file": ("no_thumb.jpg", io.BytesIO(data), "image/jpeg")},
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code in (200, 201)
body = response.json()
assert body["thumbnail_key"] is None

View File

@@ -1,18 +1,30 @@
import os
import pytest
_BASE_ENV = {
"DATABASE_URL": "postgresql+asyncpg://u:p@localhost/db",
"S3_ENDPOINT_URL": "http://localhost:9000",
"S3_BUCKET_NAME": "test-bucket",
"S3_ACCESS_KEY_ID": "key",
"S3_SECRET_ACCESS_KEY": "secret",
"S3_REGION": "us-east-1",
"API_BASE_URL": "http://localhost:8000",
"JWT_SECRET_KEY": "test-secret",
"OWNER_USERNAME": "admin",
"OWNER_PASSWORD": "password",
}
def _apply_env(monkeypatch, extra=None):
for k, v in {**_BASE_ENV, **(extra or {})}.items():
monkeypatch.setenv(k, v)
def test_settings_load_from_env(monkeypatch):
monkeypatch.setenv("DATABASE_URL", "postgresql+asyncpg://u:p@localhost/db")
monkeypatch.setenv("S3_ENDPOINT_URL", "http://localhost:9000")
monkeypatch.setenv("S3_BUCKET_NAME", "test-bucket")
monkeypatch.setenv("S3_ACCESS_KEY_ID", "key")
monkeypatch.setenv("S3_SECRET_ACCESS_KEY", "secret")
monkeypatch.setenv("S3_REGION", "us-east-1")
monkeypatch.setenv("API_BASE_URL", "http://localhost:8000")
_apply_env(monkeypatch)
# Import inside test to pick up monkeypatched env
import importlib
import app.config as config_module
importlib.reload(config_module)
@@ -20,21 +32,30 @@ def test_settings_load_from_env(monkeypatch):
assert s.database_url == "postgresql+asyncpg://u:p@localhost/db"
assert s.s3_bucket_name == "test-bucket"
assert s.max_upload_bytes == 52428800 # default
assert s.jwt_secret_key == "test-secret"
assert s.jwt_expiry_seconds == 86400 # default
assert s.owner_username == "admin"
def test_settings_max_upload_bytes_override(monkeypatch):
monkeypatch.setenv("DATABASE_URL", "postgresql+asyncpg://u:p@localhost/db")
monkeypatch.setenv("S3_ENDPOINT_URL", "http://localhost:9000")
monkeypatch.setenv("S3_BUCKET_NAME", "test-bucket")
monkeypatch.setenv("S3_ACCESS_KEY_ID", "key")
monkeypatch.setenv("S3_SECRET_ACCESS_KEY", "secret")
monkeypatch.setenv("S3_REGION", "us-east-1")
monkeypatch.setenv("API_BASE_URL", "http://localhost:8000")
monkeypatch.setenv("MAX_UPLOAD_BYTES", "10485760")
_apply_env(monkeypatch, {"MAX_UPLOAD_BYTES": "10485760"})
import importlib
import app.config as config_module
importlib.reload(config_module)
s = config_module.Settings()
assert s.max_upload_bytes == 10485760
def test_settings_jwt_expiry_override(monkeypatch):
_apply_env(monkeypatch, {"JWT_EXPIRY_SECONDS": "3600"})
import importlib
import app.config as config_module
importlib.reload(config_module)
s = config_module.Settings()
assert s.jwt_expiry_seconds == 3600

View File

@@ -1,4 +1,5 @@
import hashlib
from app.utils import compute_sha256

View File

@@ -0,0 +1,96 @@
import jwt as pyjwt
import pytest
from fastapi import HTTPException
from app.auth.jwt_provider import JWTAuthProvider
SECRET = "test-secret-key"
USERNAME = "owner"
PASSWORD = "hunter2"
def make_provider(**kwargs) -> JWTAuthProvider:
defaults = dict(
secret_key=SECRET,
expiry_seconds=3600,
owner_username=USERNAME,
owner_password=PASSWORD,
)
return JWTAuthProvider(**{**defaults, **kwargs})
def test_create_token_is_valid_jwt():
provider = make_provider()
token = provider.create_token()
payload = pyjwt.decode(token, SECRET, algorithms=["HS256"])
assert payload["sub"] == "owner"
assert "iat" in payload
assert "exp" in payload
@pytest.mark.asyncio
async def test_get_identity_returns_owner():
provider = make_provider()
token = provider.create_token()
identity = await provider.get_identity(f"Bearer {token}")
assert identity.id == "owner"
assert identity.anonymous is False
@pytest.mark.asyncio
async def test_get_identity_raises_on_expired_token():
provider = make_provider(expiry_seconds=-1)
token = provider.create_token()
with pytest.raises(HTTPException) as exc_info:
await provider.get_identity(f"Bearer {token}")
assert exc_info.value.status_code == 401
@pytest.mark.asyncio
async def test_get_identity_raises_on_wrong_key():
provider = make_provider()
other = make_provider(secret_key="different-secret")
token = other.create_token()
with pytest.raises(HTTPException) as exc_info:
await provider.get_identity(f"Bearer {token}")
assert exc_info.value.status_code == 401
@pytest.mark.asyncio
async def test_get_identity_raises_on_garbage():
provider = make_provider()
with pytest.raises(HTTPException) as exc_info:
await provider.get_identity("Bearer not.a.real.token")
assert exc_info.value.status_code == 401
@pytest.mark.asyncio
async def test_get_identity_raises_on_missing_header():
provider = make_provider()
with pytest.raises(HTTPException) as exc_info:
await provider.get_identity(None)
assert exc_info.value.status_code == 401
@pytest.mark.asyncio
async def test_get_identity_raises_on_missing_bearer_prefix():
provider = make_provider()
token = provider.create_token()
with pytest.raises(HTTPException) as exc_info:
await provider.get_identity(token)
assert exc_info.value.status_code == 401
def test_verify_credentials_true():
provider = make_provider()
assert provider.verify_credentials(USERNAME, PASSWORD) is True
def test_verify_credentials_false_wrong_password():
provider = make_provider()
assert provider.verify_credentials(USERNAME, "wrongpassword") is False
def test_verify_credentials_false_wrong_username():
provider = make_provider()
assert provider.verify_credentials("notowner", PASSWORD) is False

View File

@@ -0,0 +1,98 @@
import ipaddress
from unittest.mock import MagicMock
from starlette.requests import Request
from app.auth.rate_limiter import LoginRateLimiter, get_client_ip
# ---------------------------------------------------------------------------
# LoginRateLimiter tests
# ---------------------------------------------------------------------------
def make_limiter():
return LoginRateLimiter(max_failures=3, window_seconds=60, cooldown_seconds=300)
def test_not_blocked_initially():
assert make_limiter().is_blocked("1.2.3.4") is False
def test_blocked_after_threshold():
limiter = make_limiter()
for _ in range(3):
limiter.record_failure("1.2.3.4")
assert limiter.is_blocked("1.2.3.4") is True
def test_success_clears_failures():
limiter = make_limiter()
limiter.record_failure("1.2.3.4")
limiter.record_failure("1.2.3.4")
limiter.record_success("1.2.3.4")
assert limiter.is_blocked("1.2.3.4") is False
def test_ips_are_isolated():
limiter = make_limiter()
for _ in range(3):
limiter.record_failure("1.1.1.1")
assert limiter.is_blocked("2.2.2.2") is False
def test_window_resets_after_expiry():
import time
limiter = LoginRateLimiter(max_failures=3, window_seconds=0, cooldown_seconds=300)
limiter.record_failure("1.2.3.4")
limiter.record_failure("1.2.3.4")
time.sleep(0.01)
limiter.record_failure("1.2.3.4")
# window expired — counter reset on third call, so failures = 1, not 3
assert limiter.is_blocked("1.2.3.4") is False
def test_log_warning_on_lockout(caplog):
import logging
limiter = make_limiter()
with caplog.at_level(logging.WARNING, logger="app.auth.rate_limiter"):
for _ in range(3):
limiter.record_failure("5.6.7.8")
assert "Login blocked" in caplog.text
assert "5.6.7.8" in caplog.text
# ---------------------------------------------------------------------------
# get_client_ip tests
# ---------------------------------------------------------------------------
def make_request(peer: str, headers: dict) -> MagicMock:
req = MagicMock(spec=Request)
req.client.host = peer
req.headers = headers
return req
def test_get_client_ip_no_trusted_networks_returns_peer():
req = make_request("203.0.113.1", {"X-Forwarded-For": "10.0.0.1"})
assert get_client_ip(req, []) == "203.0.113.1"
def test_get_client_ip_trusted_peer_uses_xff():
req = make_request("10.0.0.1", {"X-Forwarded-For": "203.0.113.5"})
nets = [ipaddress.ip_network("10.0.0.0/8")]
assert get_client_ip(req, nets) == "203.0.113.5"
def test_get_client_ip_untrusted_peer_ignores_xff():
req = make_request("8.8.8.8", {"X-Forwarded-For": "203.0.113.5"})
nets = [ipaddress.ip_network("10.0.0.0/8")]
assert get_client_ip(req, nets) == "8.8.8.8"
def test_get_client_ip_trusted_peer_falls_back_to_real_ip():
req = make_request("10.0.0.1", {"X-Real-IP": "203.0.113.9"})
nets = [ipaddress.ip_network("10.0.0.0/8")]
assert get_client_ip(req, nets) == "203.0.113.9"

View File

@@ -3,6 +3,7 @@ T037 — tag normalisation: uppercase → lowercase, whitespace stripped
T038 — tag validation: rejects names > 64 chars, invalid chars
"""
import pytest
from app.repositories.tag_repo import TagRepository

View File

@@ -0,0 +1,79 @@
"""Unit tests for thumbnail generation utility."""
import io
from PIL import Image as PILImage
from app.thumbnail import generate_thumbnail
def _make_jpeg(width: int, height: int) -> bytes:
buf = io.BytesIO()
img = PILImage.new("RGB", (width, height), color=(128, 64, 32))
img.save(buf, format="JPEG", quality=80)
return buf.getvalue()
def _make_png_rgba(width: int, height: int) -> bytes:
buf = io.BytesIO()
img = PILImage.new("RGBA", (width, height), color=(10, 20, 30, 180))
img.save(buf, format="PNG")
return buf.getvalue()
def _make_gif(width: int, height: int) -> bytes:
buf = io.BytesIO()
img = PILImage.new("P", (width, height))
img.save(buf, format="GIF")
return buf.getvalue()
def test_thumbnail_is_webp():
data = _make_jpeg(600, 400)
result = generate_thumbnail(data, "image/jpeg")
assert result[:4] == b"RIFF"
assert result[8:12] == b"WEBP"
def test_thumbnail_fits_within_400px():
data = _make_jpeg(800, 600)
result = generate_thumbnail(data, "image/jpeg")
img = PILImage.open(io.BytesIO(result))
w, h = img.size
assert w <= 400
assert h <= 400
def test_thumbnail_preserves_aspect_ratio():
original_w, original_h = 800, 300
data = _make_jpeg(original_w, original_h)
result = generate_thumbnail(data, "image/jpeg")
img = PILImage.open(io.BytesIO(result))
w, h = img.size
original_ratio = original_w / original_h
thumb_ratio = w / h
assert abs(original_ratio - thumb_ratio) / original_ratio < 0.01
def test_thumbnail_handles_gif_first_frame():
data = _make_gif(500, 500)
result = generate_thumbnail(data, "image/gif")
assert result[8:12] == b"WEBP"
img = PILImage.open(io.BytesIO(result))
assert not getattr(img, "is_animated", False)
def test_thumbnail_handles_png_with_alpha():
data = _make_png_rgba(300, 300)
result = generate_thumbnail(data, "image/png")
assert result[8:12] == b"WEBP"
img = PILImage.open(io.BytesIO(result))
assert img.format == "WEBP"
def test_thumbnail_does_not_upscale():
data = _make_jpeg(100, 100)
result = generate_thumbnail(data, "image/jpeg")
img = PILImage.open(io.BytesIO(result))
w, h = img.size
assert w <= 100
assert h <= 100

View File

@@ -1,5 +1,6 @@
import pytest
from app.validation import validate_mime_type, validate_file_size, MimeTypeError, FileSizeError
from app.validation import FileSizeError, MimeTypeError, validate_file_size, validate_mime_type
ACCEPTED_TYPES = ["image/jpeg", "image/png", "image/gif", "image/webp"]
REJECTED_TYPES = ["application/pdf", "video/mp4", "text/plain", "application/octet-stream"]

1594
api/uv.lock generated Normal file

File diff suppressed because it is too large Load Diff

67
docker-compose.test.yml Normal file
View File

@@ -0,0 +1,67 @@
services:
postgres-test:
image: postgres:16-alpine
environment:
POSTGRES_USER: reactbin
POSTGRES_PASSWORD: reactbin
POSTGRES_DB: reactbin_test
ports:
- "5433:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U reactbin"]
interval: 5s
timeout: 5s
retries: 5
minio-test:
image: minio/minio:latest
command: server /data --console-address ":9001"
environment:
MINIO_ROOT_USER: minioadmin
MINIO_ROOT_PASSWORD: minioadmin
ports:
- "9002:9000"
- "9003:9001"
healthcheck:
test: ["CMD", "mc", "ready", "local"]
interval: 5s
timeout: 5s
retries: 5
minio-init-test:
image: minio/mc:latest
depends_on:
minio-test:
condition: service_healthy
environment:
MINIO_ROOT_USER: minioadmin
MINIO_ROOT_PASSWORD: minioadmin
entrypoint: >
/bin/sh -c "
mc alias set local http://minio-test:9000 $$MINIO_ROOT_USER $$MINIO_ROOT_PASSWORD &&
mc mb --ignore-existing local/reactbin-test
"
api-test:
build:
context: ./api
environment:
TEST_DATABASE_URL: postgresql+asyncpg://reactbin:reactbin@postgres-test:5432/reactbin_test
DATABASE_URL: postgresql+asyncpg://reactbin:reactbin@postgres-test:5432/reactbin_test
S3_ENDPOINT_URL: http://minio-test:9000
S3_BUCKET_NAME: reactbin-test
S3_ACCESS_KEY_ID: minioadmin
S3_SECRET_ACCESS_KEY: minioadmin
S3_REGION: us-east-1
JWT_SECRET_KEY: test-secret-key-for-testing-only
OWNER_USERNAME: testowner
OWNER_PASSWORD: testpassword
API_BASE_URL: http://localhost:8000
MAX_UPLOAD_BYTES: "52428800"
depends_on:
postgres-test:
condition: service_healthy
minio-init-test:
condition: service_completed_successfully
command: ["python", "-m", "pytest", "tests/", "-v"]
working_dir: /app

View File

@@ -0,0 +1,34 @@
# Specification Quality Checklist: Upload Thumbnails
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2026-05-03
**Feature**: [spec.md](../spec.md)
## Content Quality
- [x] No implementation details (languages, frameworks, APIs)
- [x] Focused on user value and business needs
- [x] Written for non-technical stakeholders
- [x] All mandatory sections completed
## Requirement Completeness
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Requirements are testable and unambiguous
- [x] Success criteria are measurable
- [x] Success criteria are technology-agnostic (no implementation details)
- [x] All acceptance scenarios are defined
- [x] Edge cases are identified
- [x] Scope is clearly bounded
- [x] Dependencies and assumptions identified
## Feature Readiness
- [x] All functional requirements have clear acceptance criteria
- [x] User scenarios cover primary flows
- [x] Feature meets measurable outcomes defined in Success Criteria
- [x] No implementation details leak into specification
## Notes
All checklist items pass. Spec is ready for `/speckit-plan`.

View File

@@ -0,0 +1,90 @@
# API Contract: Upload Thumbnails
**Branch**: `003-upload-thumbnails` | **Date**: 2026-05-03
---
## New endpoint
### `GET /api/v1/images/{image_id}/thumbnail`
Returns the thumbnail content for the given image. If no thumbnail was generated
(image pre-dates the feature or generation failed), falls back to the full-size
original.
**Path parameters**
| Parameter | Type | Description |
|-----------|------|-------------|
| `image_id` | UUID | Unique identifier of the image |
**Responses**
#### `200 OK` — Thumbnail (or original fallback) content
| Header | Value | Notes |
|--------|-------|-------|
| `Content-Type` | `image/webp` | Always WebP when a thumbnail exists; original `mime_type` when falling back to the original |
| `ETag` | `"{sha256-hex}"` | Same hash as the original image — content is immutable |
| `Cache-Control` | `public, max-age=31536000, immutable` | Safe: thumbnail content never changes |
Body: raw image bytes (WebP thumbnail, or original bytes as fallback).
#### `404 Not Found` — Image not found
```json
{ "detail": "Image not found", "code": "image_not_found" }
```
#### `500 Internal Server Error` — Storage retrieval failure
```json
{ "detail": "Failed to retrieve image content", "code": "storage_error" }
```
---
## Changed endpoint: `POST /api/v1/images`
The upload response body gains one new field:
| Field | Type | Notes |
|-------|------|-------|
| `thumbnail_key` | `string \| null` | S3 key of the generated thumbnail. `null` if generation failed. |
All existing fields are unchanged.
**Example response** (new field only shown):
```json
{
"id": "...",
"thumbnail_key": "abc123…-thumb",
...
}
```
---
## Changed endpoint: `GET /api/v1/images` and `GET /api/v1/images/{id}`
Both metadata responses gain the same `thumbnail_key` field (`string | null`).
---
## UI contract
The Angular `ImageService` gains one new method:
```
getThumbnailUrl(id: string): string
→ '/api/v1/images/{id}/thumbnail'
```
The `ImageRecord` interface gains:
```
thumbnail_key: string | null;
```
The library grid component uses `getThumbnailUrl(image.id)` as the `src` for
every grid cell. The detail component continues using `getFileUrl(image.id)`.

View File

@@ -0,0 +1,79 @@
# Data Model: Upload Thumbnails
**Branch**: `003-upload-thumbnails` | **Date**: 2026-05-03
## Schema change: `images` table
One nullable column is added to the existing `images` table.
| Column | Type | Nullable | Default | Notes |
|--------|------|----------|---------|-------|
| `thumbnail_key` | `VARCHAR(70)` | YES | `NULL` | S3 object key for the WebP thumbnail. `NULL` = no thumbnail available (generation failed or pre-dates this feature). Derived value: `{image.hash}-thumb`. |
No other tables change. No new tables are added.
### Migration
**File**: `api/alembic/versions/002_add_thumbnail_key.py`
```
upgrade: ALTER TABLE images ADD COLUMN thumbnail_key VARCHAR(70);
downgrade: ALTER TABLE images DROP COLUMN thumbnail_key;
```
---
## ORM model change: `Image`
`api/app/models.py``Image` class gains one field:
```
thumbnail_key: Mapped[str | None] = mapped_column(String(70), nullable=True, default=None)
```
---
## New module: `api/app/thumbnail.py`
Contains the thumbnail generation logic. Not a model, but documented here because
it defines the thumbnail's shape:
| Aspect | Value |
|--------|-------|
| Output format | WebP |
| Max dimension (longest side) | 400 px |
| Aspect ratio | Preserved (never upscaled) |
| Source formats supported | JPEG, PNG, GIF (frame 0), WebP |
| Key signature | `async def generate_thumbnail(data: bytes, mime_type: str) -> bytes` |
---
## API response shape change
`_image_to_dict()` in `api/app/routers/images.py` adds `"thumbnail_key"` to its
output so the UI can determine whether a thumbnail is available:
```json
{
"id": "...",
"hash": "...",
"thumbnail_key": "abc123...-thumb", new (null if no thumbnail)
...
}
```
The UI uses the presence of `thumbnail_key` to decide whether to call
`/api/v1/images/{id}/thumbnail` (with thumbnail) or fall back to
`/api/v1/images/{id}/file` (without). In practice the endpoint itself
handles the fallback, so the UI can always call `/thumbnail`.
---
## Storage objects per image (after this feature)
| Object | Key | Format | Created at |
|--------|-----|--------|-----------|
| Original | `{sha256_hash}` | Original mime_type | Upload |
| Thumbnail | `{sha256_hash}-thumb` | `image/webp` | Upload (same request) |
Thumbnail object is deleted alongside original on image deletion.

View File

@@ -0,0 +1,246 @@
# Implementation Plan: Upload Thumbnails
**Branch**: `003-upload-thumbnails` | **Date**: 2026-05-03 | **Spec**: [spec.md](spec.md)
**Input**: Feature specification from `specs/003-upload-thumbnails/spec.md`
## Summary
When an image is uploaded, generate a WebP thumbnail (longest side ≤ 400 px,
aspect ratio preserved) and store it in S3 alongside the original. Add a
`GET /api/v1/images/{id}/thumbnail` endpoint that serves the thumbnail (or falls
back to the original for images that pre-date the feature). The Angular library
grid switches from `/file` to `/thumbnail`. The detail page is unchanged.
Changes span: a new Pillow dependency, a new `thumbnail.py` utility module, one
Alembic migration, the upload and delete routes, a new thumbnail serve route, and
the Angular image service and library component.
## Technical Context
**Language/Version**: Python 3.12+ (API); TypeScript strict mode (UI)
**Primary Dependencies**: FastAPI, Pillow (new — thumbnail generation), aiobotocore,
SQLAlchemy 2.x async, Alembic, Angular
**Storage**: S3-compatible object storage via `StorageBackend.put()` and `.get()`;
thumbnails stored at key `{sha256_hash}-thumb` in the same bucket
**Testing**: pytest + pytest-asyncio (API); Angular Karma/Jest + TestBed (UI)
**Target Platform**: Linux server (containerised); modern evergreen desktop browsers
**Project Type**: Web application — FastAPI API + Angular SPA
**Performance Goals**: 20-image grid transfers ≥ 80% less data than full-size;
first page of 1,000-image library loads in under 2 s
**Constraints**: Thumbnail generation is synchronous within the upload request;
thumbnail failure must not block upload success; no backfill of existing images in v1
**Scale/Scope**: Single-user personal application; upload frequency low
## Constitution Check
*GATE: Must pass before Phase 0 research. Re-checked after Phase 1 design below.*
| Principle | Check | Status |
|-----------|-------|--------|
| §2.1 Separation of concerns | `thumbnail.py` owns resize logic; router owns orchestration; UI knows nothing about S3 keys | ✅ |
| §2.2 Dependency direction | UI → API → Storage; thumbnail stored via `StorageBackend`; no upward imports | ✅ |
| §2.3 Storage abstraction | All thumbnail I/O via `StorageBackend.put()` and `.get()`; no raw S3 SDK calls in routes or `thumbnail.py` | ✅ |
| §2.4 Auth abstraction | No change to auth flow | ✅ |
| §2.5 DB abstraction | New `thumbnail_key` column accessed only through `ImageRepository`; migration added | ✅ |
| §2.6 No speculative abstraction | `thumbnail.py` is a concrete module-level function; no interface added because one implementation exists | ✅ |
| §3.1 API versioning | New route at `/api/v1/images/{id}/thumbnail` | ✅ |
| §3.3 Error shape | `image_not_found` and `storage_error` codes used consistently | ✅ |
| §4.2 Images immutable after upload | Thumbnail is generated at upload time only; never mutated | ✅ |
| §4.3 Dedup by hash | Duplicate upload returns existing record including existing `thumbnail_key`; no re-generation | ✅ |
| §5.1 TDD non-negotiable | Failing tests written before every implementation task | ✅ |
| §5.2 Test pyramid | Unit test for `thumbnail.py`; integration tests for new route + upload + delete | ✅ |
| §5.3 Test colocation | API tests in `api/tests/`; Angular spec files colocated with components | ✅ |
| §5.4 CI gate | All tests + ruff must pass before milestone is done | ✅ |
| §7.1 One-command start | No change to `docker-compose.yml` required | ✅ |
| §7.2 Env configuration | No new env vars; Pillow is a build dependency, not a runtime config | ✅ |
| §8 Scope boundaries | Backfill of existing images, multiple thumbnail sizes, animated WebP — all deferred | ✅ |
**Post-design re-check**: All gates still pass after Phase 1 design.
## Project Structure
### Documentation (this feature)
```text
specs/003-upload-thumbnails/
├── plan.md # This file
├── spec.md # Feature specification
├── research.md # Phase 0 decisions
├── data-model.md # Schema and module changes
├── contracts/
│ └── api.md # New endpoint + changed response shapes
├── checklists/
│ └── requirements.md # Spec quality checklist
└── tasks.md # Phase 2 output (/speckit-tasks — NOT created here)
```
### Files changed or created
```text
api/
├── pyproject.toml # Add Pillow dependency
├── app/
│ ├── thumbnail.py # NEW — generate_thumbnail()
│ ├── models.py # Add thumbnail_key column to Image
│ ├── repositories/
│ │ └── image_repo.py # Pass thumbnail_key on create
│ └── routers/
│ └── images.py # Upload: generate+store thumbnail
│ # Delete: remove thumbnail
│ # New route: GET /images/{id}/thumbnail
│ # _image_to_dict: add thumbnail_key field
└── alembic/
└── versions/
└── 002_add_thumbnail_key.py # NEW migration
ui/
└── src/
└── app/
├── services/
│ └── image.service.ts # Add getThumbnailUrl(); add thumbnail_key to ImageRecord
└── library/
└── library.component.ts # Use getThumbnailUrl() for grid image src
```
## Milestones
> **TDD ORDER IS MANDATORY** (constitution §5.1): For every milestone, write
> the failing test(s) first, confirm they fail, then implement until they pass.
---
### M1 — Thumbnail generation utility
**Goal**: A tested, self-contained function that produces a WebP thumbnail from
raw image bytes.
**Deliverables**:
- Add `pillow>=10.0` to `[project.dependencies]` in `api/pyproject.toml`
- Create `api/app/thumbnail.py` with `generate_thumbnail(data: bytes, mime_type: str) -> bytes`:
- Open image bytes with Pillow
- Seek to frame 0 (handles animated GIFs)
- Convert mode as needed for WebP output
- Resize to fit within 400×400 using LANCZOS resampling (never upscale)
- Encode as WebP quality 80 and return bytes
- Unit tests in `api/tests/unit/test_thumbnail.py`:
- `test_thumbnail_is_webp` — output starts with WebP magic bytes
- `test_thumbnail_fits_within_400px` — both dimensions ≤ 400
- `test_thumbnail_preserves_aspect_ratio` — ratio within 1% of original
- `test_thumbnail_handles_gif_first_frame` — GIF input produces static WebP
- `test_thumbnail_handles_png_with_alpha` — RGBA PNG produces valid WebP
- `test_thumbnail_does_not_upscale` — 100×100 image stays ≤ 100×100
**Done criterion**: All unit tests pass; `ruff check api/` passes.
---
### M2 — Database migration
**Goal**: The `images` table has a nullable `thumbnail_key` column; the ORM model
and repository reflect it.
**Deliverables**:
- `api/alembic/versions/002_add_thumbnail_key.py``upgrade` adds
`VARCHAR(70) NULLABLE` column; `downgrade` drops it
- `api/app/models.py`: add `thumbnail_key: Mapped[str | None]` mapped to
`String(70)`, `nullable=True`, `default=None`
- `api/app/repositories/image_repo.py`: add `thumbnail_key: str | None = None`
parameter to `create()`; persist it on the new `Image` instance
**Done criterion**: `alembic upgrade head` runs cleanly inside Docker; all
existing 46 integration tests still pass (new column is nullable, no existing
test breaks).
---
### M3 — Upload route: generate and store thumbnail
**Goal**: Every new upload generates a thumbnail; duplicates reuse the existing
record; failures are tolerated without blocking the upload.
**TDD first** — new tests in `api/tests/integration/test_upload.py`:
- `test_upload_returns_thumbnail_key` — upload response includes non-null
`thumbnail_key` ending in `-thumb`
- `test_duplicate_upload_reuses_thumbnail_key` — second upload of the same
file returns the same `thumbnail_key` as the first
- `test_upload_succeeds_when_thumbnail_fails` — patch `generate_thumbnail` to
raise, upload returns 200/201 with `thumbnail_key: null`
**Implementation** in `api/app/routers/images.py` `upload_image()`:
1. After `await storage.put(hash_hex, data, mime_type)`, attempt thumbnail generation
and storage in a try/except; catch any exception and leave `thumbnail_key` as `None`
2. Call `thumb_bytes = await asyncio.to_thread(generate_thumbnail, data, mime_type)`
`generate_thumbnail` is CPU-bound (Pillow); `asyncio.to_thread` runs it in the
default thread pool executor so it does not block the async event loop
3. Pass `thumbnail_key` to `image_repo.create()`
4. Add `"thumbnail_key": image.thumbnail_key` to `_image_to_dict()`
**Done criterion**: New tests pass; all 46 existing tests pass.
---
### M4 — New `GET /api/v1/images/{id}/thumbnail` endpoint
**Goal**: Clients fetch thumbnail content; falls back to original if no thumbnail exists.
**TDD first** — new tests in `api/tests/integration/test_serving.py`:
- `test_thumbnail_returns_webp` — upload image, call `/thumbnail`, assert
200, `content-type: image/webp`, ETag, `Cache-Control` with immutable
- `test_thumbnail_fallback_returns_original` — set `thumbnail_key=None` on a
record, call `/thumbnail`, assert 200 with original mime_type
- `test_thumbnail_unknown_id_returns_404` — unknown UUID → 404 `image_not_found`
**Implementation**: new route `GET /images/{image_id}/thumbnail` in
`api/app/routers/images.py` using `image.thumbnail_key or image.storage_key`
to select the key, and `"image/webp" if image.thumbnail_key else image.mime_type`
for the content type. Same `ETag` + `Cache-Control` headers as `/file`.
**Done criterion**: All new tests pass; all existing tests pass.
---
### M5 — Delete route: remove thumbnail from storage
**Goal**: Deleting an image also removes its thumbnail; no orphaned objects left.
**TDD first** — new test in `api/tests/integration/test_delete.py`:
- `test_delete_removes_thumbnail` — upload image, delete it, then verify
`GET /images/{id}/thumbnail` returns 404
**Implementation** in `api/app/routers/images.py` `delete_image()`: after
deleting the DB record and the original object, call `await storage.delete(image.thumbnail_key)`
if `image.thumbnail_key` is not None.
**Done criterion**: New test passes; all existing delete tests pass.
---
### M6 — UI: library grid uses thumbnail endpoint
**Goal**: Library grid fetches thumbnails instead of full-size originals; detail
page is unchanged.
**Deliverables**:
- `ui/src/app/services/image.service.ts`:
- Add `thumbnail_key: string | null` to `ImageRecord` interface
- Add `getThumbnailUrl(id: string): string` returning `/api/v1/images/${id}/thumbnail`
- `ui/src/app/library/library.component.ts` + template: replace
`getFileUrl(image.id)` with `getThumbnailUrl(image.id)` for grid `<img src>`
- Update Angular spec files: add `thumbnail_key: null` to all `ImageRecord`
mock objects
- Verify `ng test` passes and `ng build` succeeds
**Done criterion**: Angular build clean; all Angular tests pass; library grid
`<img>` elements reference `/thumbnail` not `/file`.
## Post-design Constitution Re-check
| Principle | Verdict |
|-----------|---------|
| §2.3 Storage abstraction | All thumbnail I/O via `StorageBackend`; `thumbnail.py` never touches S3 directly | ✅ |
| §2.5 DB abstraction | `thumbnail_key` persisted only through `ImageRepository.create()` | ✅ |
| §2.6 No speculative abstraction | One concrete function; no interface | ✅ |
| §4.2 Immutability | Thumbnail written once at upload; never mutated | ✅ |
| §5.1 TDD | Failing tests written before each milestone's implementation | ✅ |
All gates pass. Feature is ready for `/speckit-tasks`.

View File

@@ -0,0 +1,130 @@
# Research: Upload Thumbnails
**Branch**: `003-upload-thumbnails` | **Date**: 2026-05-03
## Decision 1: Image processing library
**Decision**: Add `Pillow` as a runtime dependency to the API.
**Rationale**: Pillow is the standard Python image processing library. It supports
reading JPEG, PNG, GIF (frame extraction), and WebP, and can encode output as WebP.
It handles aspect-ratio-preserving resize natively via `Image.thumbnail()`. No
other dependency is needed.
**Alternatives considered**:
- `wand` (ImageMagick binding): More powerful but much heavier; overkill for a
fixed-size resize operation.
- `opencv-python`: ML-focused, large binary; not justified for simple resize.
- Pure `aiobotocore` + external service: Adds operational complexity with no benefit
over a local library for a single-user app.
---
## Decision 2: Thumbnail dimensions and format
**Decision**: Longest side ≤ 400 px, WebP output, aspect ratio preserved. This
matches FR-003 and FR-004 exactly and the user's stated preference.
**Rationale**: WebP produces smaller files than JPEG/PNG at equivalent visual quality.
400 px covers a typical grid thumbnail at 1× and 2× display density without being
oversized. Pillow's `Image.thumbnail((400, 400))` implements this constraint directly
(it shrinks to fit within the bounding box, never upscaling).
**Alternatives considered**:
- JPEG thumbnails: Larger file sizes; no alpha channel support.
- Multiple sizes: Out of scope for v1 per spec Assumptions.
- On-demand resize: Rejected by user in favour of pre-generation.
---
## Decision 3: Thumbnail storage key convention
**Decision**: `{sha256_hash}-thumb` (e.g., the 64-char hash hex string + literal
`-thumb`, giving a 70-char key). Stored under the same S3 bucket as originals.
**Rationale**: Deterministic from the image hash — no new random state needed and the
key can always be reconstructed from the `Image.hash` field. The `-thumb` suffix
clearly distinguishes it from the original key. Fits within a `String(70)` column.
**Alternatives considered**:
- Separate bucket for thumbnails: More complex bucket policy management with no benefit
for a single-user app.
- UUID-based key: Non-deterministic; requires an extra DB round-trip to look up.
- `{hash}/thumb.webp` (path prefix): Works, but adds key parsing complexity for no gain.
---
## Decision 4: Database schema change
**Decision**: Add a nullable `thumbnail_key: String(70)` column to the `images`
table. `NULL` means no thumbnail exists (either generation failed or the image
pre-dates this feature). Add a new Alembic migration `002_add_thumbnail_key.py`.
**Rationale**: Explicitly tracking the thumbnail key in the DB makes the "does a
thumbnail exist?" question a simple `IS NOT NULL` check rather than an S3 head
request. Also allows the delete route to skip the thumbnail delete if the column
is NULL, avoiding a storage error for legacy images.
**Alternatives considered**:
- Derive key at runtime from `image.hash + "-thumb"` without a DB column: Simpler but
means no way to distinguish "thumbnail was generated" from "thumbnail was never
attempted", and delete would need a conditional S3 head request.
- Separate `thumbnails` table: Over-engineered; one thumbnail per image with no
additional attributes doesn't warrant its own table.
---
## Decision 5: Where thumbnail generation lives in the code
**Decision**: A standalone async function `generate_thumbnail(data: bytes, mime_type: str) -> bytes`
in a new module `api/app/thumbnail.py`. Called from the upload route after the original
is stored, before the Image record is created.
**Rationale**: Keeps the thumbnail logic self-contained and independently testable.
The upload route calls it but doesn't own it. Constitution §2.6 allows concrete
functions when no second implementation is needed — no abstract interface is warranted.
**Alternatives considered**:
- Method on `StorageBackend`: Wrong layer; storage knows nothing about image content.
- Inline in the upload route: Makes the route harder to test and read.
- A `ThumbnailService` class: No justification for a class when a module-level function suffices.
---
## Decision 6: Failure handling during upload
**Decision**: If `generate_thumbnail()` raises, log the exception, set `thumbnail_key`
to `NULL` on the Image record, and continue. The upload response succeeds. The
`GET /api/v1/images/{id}/thumbnail` endpoint falls back to the original when
`thumbnail_key` is NULL (FR-009).
**Rationale**: A thumbnail failure should not block the upload — the user still gets
their image in the library. The fallback in the thumbnail endpoint ensures the grid
still renders something.
---
## Decision 7: Thumbnail endpoint response
**Decision**: `GET /api/v1/images/{id}/thumbnail` follows the same pattern as
`GET /api/v1/images/{id}/file`:
- Returns `200` with binary content, `Content-Type: image/webp` (or original
`mime_type` when falling back to original), `ETag`, and
`Cache-Control: public, max-age=31536000, immutable`.
- Returns `404` with `{"detail": "...", "code": "image_not_found"}` if the image
does not exist.
- Falls back to the original when `thumbnail_key IS NULL`.
**Rationale**: Consistent with the existing `/file` endpoint pattern established in
feature 002. The UI only needs to know one URL per image for the grid.
---
## Decision 8: GIF handling
**Decision**: For GIF uploads, `generate_thumbnail()` extracts frame 0 via
`Image.seek(0)` before resizing. The output is always WebP (static, not animated).
**Rationale**: Matches spec assumption: "Animated GIF thumbnails capture only the
first frame; animation is not preserved in the thumbnail." Pillow supports this
with `im.seek(0)`.

View File

@@ -0,0 +1,180 @@
# Feature Specification: Upload Thumbnails
**Feature Branch**: `003-upload-thumbnails`
**Created**: 2026-05-03
**Status**: Draft
**Input**: User description: "When users load the UI, full size images are fetched, which may cause considerable load time when there are a lot of images -- a grid of 20 images could silently pull several hundred megabytes. We will solve this by pre-generating thumbnails on upload: when an image is uploaded, immediately produce one (or a few) fixed-size thumbnail variants and store them alongside the original. The library always fetches the thumbnail key, the detail page fetches the original key. Zero resize cost at serve time. A single fixed-size re-encoded as WebP for smaller bytes will cover the grid view."
## User Scenarios & Testing *(mandatory)*
### User Story 1 — Fast Library Load (Priority: P1)
A user opens the application or runs a tag-filtered search. The image grid
loads quickly even when the library contains many images, because each grid
cell fetches a compact thumbnail rather than the full-size original.
**Why this priority**: This is the core motivation. A grid of 20 images today
could pull hundreds of megabytes; thumbnails bring that down to a few
megabytes, making the library usable on slow or metered connections.
**Independent Test**: Upload 20 images of varying sizes (including some near
the 50 MB limit). Open the library. Measure total bytes transferred while the
grid loads. Compare against loading the same library before this feature.
Verify the grid renders fully and that each thumbnail is visually recognisable
as the correct image.
**Acceptance Scenarios**:
1. **Given** a library with multiple images, **When** the user opens the
library page, **Then** each grid cell displays a thumbnail that is visually
recognisable as its image, and the total data transferred to render the
full grid is substantially less than the sum of the original file sizes.
2. **Given** a user applies one or more tag filters, **When** the filtered
results are displayed, **Then** thumbnails are shown for all matching
images with the same reduced data footprint.
3. **Given** a library with images of mixed types (JPEG, PNG, GIF, WebP),
**When** the grid loads, **Then** thumbnails for all types display
correctly.
---
### User Story 2 — Full-Size Image on Detail Page (Priority: P1)
A user clicks an image in the library grid to open its detail page. The
full-size original is displayed, not the thumbnail. The experience is
unchanged from before this feature.
**Why this priority**: The detail page is where the user inspects or copies
an image; showing the thumbnail there would degrade the product's core value.
**Independent Test**: Open any image's detail page. Verify the image
displayed matches the original resolution and file size, not the thumbnail
dimensions.
**Acceptance Scenarios**:
1. **Given** the user clicks an image thumbnail in the library, **When** the
detail page loads, **Then** the full-size original image is displayed at
its native resolution.
2. **Given** the user navigates directly to an image's detail URL, **When**
the page loads, **Then** the full-size original is displayed.
---
### User Story 3 — Thumbnails Generated Automatically on Upload (Priority: P1)
A user uploads a new image. Without any additional action, a thumbnail is
available immediately. There is no separate step or explicit request to
generate a thumbnail.
**Why this priority**: The value of the feature depends entirely on thumbnails
being present for every image. Manual generation or lazy generation would
create inconsistencies in the grid.
**Independent Test**: Upload a new image. Immediately open the library. Verify
the new image's thumbnail appears in the grid without any extra action.
**Acceptance Scenarios**:
1. **Given** the user uploads a supported image, **When** the upload
completes, **Then** a thumbnail is available and appears correctly in
the library grid.
2. **Given** the user uploads a duplicate image (already in the library),
**When** the upload completes, **Then** no redundant thumbnail is
generated — the existing thumbnail is reused.
3. **Given** the user uploads an image at or near the maximum supported
file size (50 MB), **When** the upload completes, **Then** the thumbnail
is generated successfully and the upload response time remains acceptable.
---
### Edge Cases
- What happens when thumbnail generation fails during upload? → The upload
still succeeds and the original image is stored; a fallback to the original
is shown in the grid, or the item is hidden until the thumbnail is available
(assumption: fall back to original rather than silently drop the image).
- What happens when an image is deleted? → Both the original and its thumbnail
are removed from storage.
- What happens with existing images that were uploaded before this feature? →
Those images have no pre-generated thumbnail; the grid falls back to the
original for those entries until a backfill is performed (backfill is out of
scope for v1 of this feature).
- What happens with animated GIFs? → A static thumbnail is generated from the
first frame.
## Requirements *(mandatory)*
### Functional Requirements
- **FR-001**: The system MUST generate a thumbnail for every newly uploaded
image as part of the upload operation, before the upload response is
returned to the caller.
- **FR-002**: Thumbnails MUST be stored in the same object storage as the
original, addressable by a distinct key derived from the image.
- **FR-003**: The thumbnail MUST be encoded as WebP regardless of the original
image format.
- **FR-004**: The thumbnail MUST fit within a fixed maximum dimension on its
longest side, preserving the original aspect ratio; no dimension of the
thumbnail MAY exceed 400 pixels.
- **FR-005**: The library grid view MUST fetch and display thumbnails instead
of original images.
- **FR-006**: The image detail view MUST continue to fetch and display the
full-size original.
- **FR-007**: When a duplicate image is uploaded, the thumbnail MUST NOT be
regenerated or re-stored; the existing thumbnail is reused.
- **FR-008**: When an image is deleted, its thumbnail MUST also be deleted
from storage.
- **FR-009**: If thumbnail generation fails during upload, the upload MUST
still succeed; the system MUST fall back to serving the original image in
the grid for that entry.
- **FR-010**: The API MUST expose a way for clients to retrieve the thumbnail
content for a given image, distinct from the full-size content endpoint.
### Key Entities *(include if feature involves data)*
- **Image**: Gains a new optional attribute indicating whether a thumbnail is
available and the key under which the thumbnail is stored.
- **Thumbnail**: A derived, smaller representation of an Image. Key
attributes: storage key, dimensions (width × height), format (WebP),
relationship to its source Image.
## Success Criteria *(mandatory)*
### Measurable Outcomes
- **SC-001**: The total data transferred to render a 20-image library grid is
reduced by at least 80% compared to fetching full-size originals for the
same images.
- **SC-002**: The library grid's first page loads in under 2 seconds on a
local network connection for a library of 1,000 images, with thumbnails
visible without a second load.
- **SC-003**: Thumbnails are available immediately after upload completes —
no polling or manual refresh is required.
- **SC-004**: The detail page continues to show the full-size original; no
regression in detail-page image quality is introduced.
- **SC-005**: Deleting an image removes both the original and its thumbnail;
no orphaned thumbnail objects remain in storage after deletion.
## Assumptions
- A single thumbnail size (longest side ≤ 400 px, WebP) is sufficient for
the library grid view in v1. Additional sizes or formats are out of scope.
- Thumbnail generation happens synchronously during the upload request. Async
background processing is not required for v1.
- Existing images uploaded before this feature are not automatically
backfilled with thumbnails in v1; the grid falls back to the original for
those entries.
- Animated GIF thumbnails capture only the first frame; animation is not
preserved in the thumbnail.
- The thumbnail storage key is derived deterministically from the image's
existing content hash, so no additional database column is strictly required
to locate it — however the Image record will track thumbnail availability
for correctness.
- No change is required to tag management, duplicate detection, or any other
upload behaviour beyond adding thumbnail generation.

View File

@@ -0,0 +1,186 @@
# Tasks: Upload Thumbnails
**Input**: Design documents from `specs/003-upload-thumbnails/`
**Prerequisites**: plan.md ✅, spec.md ✅, research.md ✅, data-model.md ✅, contracts/api.md ✅
**TDD**: Tests are non-negotiable per constitution §5.1. Every test task MUST be written and confirmed failing before its implementation task runs.
**Organization**: Tasks grouped by user story to enable independent implementation and testing.
## Format: `[ID] [P?] [Story] Description`
- **[P]**: Can run in parallel (different files, no dependencies on incomplete tasks)
- **[Story]**: Which user story this task belongs to (US1, US2, US3)
---
## Phase 1: Setup
- [X] T001 Add `pillow>=10.0` to `[project.dependencies]` in `api/pyproject.toml`; rebuild the Docker API image (`docker compose build api`) so Pillow is available inside the container for all subsequent test runs
---
## Phase 2: Foundational (Blocking Prerequisites)
**Purpose**: Thumbnail generation logic and the DB schema change that all three user stories depend on.
**⚠️ CRITICAL**: All tasks in this phase must complete before any user story work begins.
### Tests for thumbnail utility (write FIRST — must FAIL before T005) ⚠️
- [X] T002 Write 6 unit tests in `api/tests/unit/test_thumbnail.py``test_thumbnail_is_webp` (output begins with WebP magic bytes `RIFF...WEBP`), `test_thumbnail_fits_within_400px` (both dimensions ≤ 400), `test_thumbnail_preserves_aspect_ratio` (ratio within 1% of original), `test_thumbnail_handles_gif_first_frame` (GIF input → static WebP, no animation), `test_thumbnail_handles_png_with_alpha` (RGBA PNG → valid WebP output), `test_thumbnail_does_not_upscale` (100×100 input stays ≤ 100×100); to confirm the TDD red state, first create an empty stub `api/app/thumbnail.py` (so pytest can collect tests), then run `pytest api/tests/unit/test_thumbnail.py` and confirm all 6 **fail** with assertion errors (not import errors)
### Thumbnail utility implementation
- [X] T003 Create `api/app/thumbnail.py` with `generate_thumbnail(data: bytes, mime_type: str) -> bytes`: open bytes with `PIL.Image.open(BytesIO(data))`, call `.seek(0)` to target frame 0 (GIF support), convert mode to RGB or RGBA as needed for WebP, call `.thumbnail((400, 400), PIL.Image.LANCZOS)` (never upscales), save to a `BytesIO` buffer as WebP quality=80, return bytes; run `pytest api/tests/unit/test_thumbnail.py` and confirm all 6 pass
### Database migration
- [X] T004 [P] Create `api/alembic/versions/002_add_thumbnail_key.py` with `upgrade()` calling `op.add_column("images", sa.Column("thumbnail_key", sa.String(70), nullable=True))` and `downgrade()` calling `op.drop_column("images", "thumbnail_key")`; set `revision="002"`, `down_revision="001"`
- [X] T005 [P] Add `thumbnail_key: Mapped[str | None] = mapped_column(String(70), nullable=True, default=None)` to the `Image` class in `api/app/models.py`
- [X] T006 Add `thumbnail_key: str | None = None` keyword argument to `ImageRepository.create()` in `api/app/repositories/image_repo.py`; include it in the `Image(...)` constructor call; run `docker compose run --rm api alembic upgrade head` inside the container and confirm migration applies cleanly; run `pytest api/` to confirm all 46 existing tests still pass
**Checkpoint**: Pillow available, thumbnail.py works, schema migrated, all existing tests green.
---
## Phase 3: User Story 3 — Thumbnails Generated Automatically on Upload (Priority: P1) 🎯
**Goal**: Every new upload triggers thumbnail generation and storage as part of the same request. No extra step required from the user.
**Independent Test**: Upload any supported image. Immediately check the upload response — it includes a non-null `thumbnail_key`. Call `GET /api/v1/images/{id}/thumbnail` — it returns 200 with `content-type: image/webp`.
### Tests for User Story 3 (write FIRST — must FAIL before T008) ⚠️
- [X] T007 [US3] Add three tests to `api/tests/integration/test_upload.py`: `test_upload_returns_thumbnail_key` (upload a JPEG/PNG/WebP, assert response JSON contains `thumbnail_key` ending in `-thumb`), `test_duplicate_upload_reuses_thumbnail_key` (upload same file twice, assert both responses have equal, non-null `thumbnail_key`), and `test_upload_succeeds_when_thumbnail_fails` (patch `generate_thumbnail` to raise an exception, upload an image, assert response is 200/201 with `thumbnail_key: null` — upload must not be blocked by thumbnail failure); run `pytest api/tests/integration/test_upload.py` and confirm all three new tests **fail**
### Implementation for User Story 3
- [X] T008 [US3] In `api/app/routers/images.py` `upload_image()`: import `asyncio` and `generate_thumbnail` from `app.thumbnail`; after `await storage.put(hash_hex, data, mime_type)`, wrap thumbnail generation in a try/except — call `thumb_bytes = await asyncio.to_thread(generate_thumbnail, data, mime_type)` (runs CPU-bound Pillow work off the async event loop), store result via `await storage.put(f"{hash_hex}-thumb", thumb_bytes, "image/webp")`, set `thumbnail_key = f"{hash_hex}-thumb"`; on any exception log a warning and leave `thumbnail_key = None`; pass `thumbnail_key=thumbnail_key` to `image_repo.create()`
- [X] T009 [US3] Add `"thumbnail_key": image.thumbnail_key` to the dict returned by `_image_to_dict()` in `api/app/routers/images.py`
- [X] T010 [US3] Run `pytest api/tests/integration/test_upload.py` to confirm both new tests pass; then run `pytest api/` to confirm no regressions
**Checkpoint**: Upload generates and stores a thumbnail. Duplicate uploads reuse the existing thumbnail. `thumbnail_key` appears in all image metadata responses.
---
## Phase 4: User Story 1 — Fast Library Load (Priority: P1)
**Goal**: The library grid fetches compact WebP thumbnails instead of full-size originals, dramatically reducing page-load bandwidth.
**Independent Test**: Open the library in a browser with DevTools network tab open. All grid `<img>` elements request `/api/v1/images/{id}/thumbnail`. Total bytes transferred for a 20-image grid is a small fraction of what the originals would cost.
### Tests for User Story 1 (write FIRST — must FAIL before T013) ⚠️
- [X] T011 [US1] Add `test_thumbnail_returns_webp` (upload image, GET `/thumbnail`, assert 200, `content-type: image/webp`, ETag header matches `f'"{image_hash}"'`, `"immutable"` in `cache-control`, non-empty content), `test_thumbnail_fallback_returns_original` (manually set `thumbnail_key=None` on a DB record via the session fixture, GET `/thumbnail`, assert 200 with original `mime_type` in content-type), and `test_thumbnail_unknown_id_returns_404` (unknown UUID, assert 404 `image_not_found`) to `api/tests/integration/test_serving.py`; run and confirm all three **fail**
- [X] T012 [P] [US1] In `ui/src/app/services/image.service.ts`: add `thumbnail_key: string | null` field to the `ImageRecord` interface; add `getThumbnailUrl(id: string): string { return \`${this.base}/images/${id}/thumbnail\`; }` method to `ImageService`
### Implementation for User Story 1
- [X] T013 [US1] Add `GET /api/v1/images/{image_id}/thumbnail` route to `api/app/routers/images.py`: look up image (404 if missing), select `key = image.thumbnail_key or image.storage_key` and `media_type = "image/webp" if image.thumbnail_key else image.mime_type`, call `await storage.get(key)` in a try/except (500 `storage_error` on failure), return `Response(content=data, media_type=media_type, headers={"ETag": f'"{image.hash}"', "Cache-Control": "public, max-age=31536000, immutable"})`
- [X] T014 [US1] In `ui/src/app/library/library.component.ts` and its HTML template: replace every use of `imageService.getFileUrl(image.id)` (or equivalent) with `imageService.getThumbnailUrl(image.id)` for grid cell `<img src>` bindings
- [X] T015 [US1] Add `thumbnail_key: null` to every `ImageRecord` mock/stub object in `ui/src/app/services/image.service.spec.ts`, `ui/src/app/library/library.component.spec.ts`, `ui/src/app/detail/detail.component.spec.ts`, and `ui/src/app/upload/upload.component.spec.ts`
- [X] T016 [US1] Run `pytest api/tests/integration/test_serving.py` to confirm all three new thumbnail tests pass and no existing serving tests regress
**Checkpoint**: `GET /api/v1/images/{id}/thumbnail` serves WebP with caching headers. Falls back to original for legacy images. Library grid `<img>` elements all use the thumbnail endpoint.
---
## Phase 5: User Story 2 — Full-Size Image on Detail Page (Priority: P1)
**Goal**: The detail page continues to display the full-size original. No regression introduced by the thumbnail work.
**Independent Test**: Navigate to any image detail page. The image displayed is full-resolution. Browser DevTools shows the detail `<img>` requests `/api/v1/images/{id}/file`, not `/thumbnail`.
### Verification for User Story 2
- [X] T017 [US2] Confirm `ui/src/app/detail/detail.component.ts` still calls `imageService.getFileUrl(image.id)` (not `getThumbnailUrl`) for its `<img src>` — no code change expected; if the file was accidentally updated in T014 or T015, revert the detail component to `getFileUrl`
- [X] T018 [US2] Run `ng test` (inside the UI container or locally) and confirm all Angular unit tests pass including the detail component spec; run `ng build` to confirm the Angular build succeeds
**Checkpoint**: Detail page verified unchanged. Angular build and tests clean.
---
## Phase 6: Polish & Cross-Cutting Concerns
**Purpose**: Delete cleanup, final test run, linting.
### Delete thumbnail on image deletion
- [X] T019 Write `test_delete_removes_thumbnail` in `api/tests/integration/test_delete.py`: upload an image, delete it, then `GET /api/v1/images/{id}/thumbnail` and assert 404; run and confirm it **fails** (currently delete does not remove the thumbnail object)
- [X] T020 In `api/app/routers/images.py` `delete_image()`: capture `thumbnail_key = image.thumbnail_key` before `image_repo.delete(image)`; after deleting the original via `await storage.delete(storage_key)`, add `if thumbnail_key: await storage.delete(thumbnail_key)`; run `pytest api/tests/integration/test_delete.py` to confirm new test and all existing delete tests pass
### Final validation
- [X] T021 [P] Run `~/.local/bin/ruff check api/app/thumbnail.py api/app/routers/images.py api/app/models.py api/app/repositories/image_repo.py api/tests/unit/test_thumbnail.py` and fix any lint issues in the changed files
- [X] T022 Run `pytest api/ -v` and confirm all tests pass; record final count (expected: 46 existing + ~10 new = ~56 total)
---
## Dependencies & Execution Order
### Phase Dependencies
- **Setup (Phase 1)**: No dependencies — start immediately
- **Foundational (Phase 2)**: Depends on Phase 1 (Pillow must be installed before tests can import it)
- **US3 (Phase 3)**: Depends on Phase 2 complete (T002T006 all done)
- **US1 (Phase 4)**: Depends on Phase 3 complete (upload must set `thumbnail_key` before the endpoint can serve one)
- **US2 (Phase 5)**: Depends on Phase 4 complete (Angular changes in T014/T015 must be done before verifying no regression)
- **Polish (Phase 6)**: Depends on Phases 3, 4, and 5 complete
### Within Each Phase
- T002 (write failing tests) MUST precede T003 (implement thumbnail.py)
- T004 and T005 can run in parallel (different files)
- T006 (repo change) depends on T005 (model must compile first)
- T007 (write failing upload tests) MUST precede T008 (implement upload change)
- T011 (write failing serving tests) and T012 (UI service) can run in parallel
- T011 MUST precede T013 (implement thumbnail route)
- T019 (write failing delete test) MUST precede T020 (implement delete cleanup)
---
## Parallel Example: Phase 2 (Foundational)
```bash
# After T003 is done, run T004 and T005 together:
Task: "Create 002_add_thumbnail_key.py migration in api/alembic/versions/"
Task: "Add thumbnail_key column to Image ORM in api/app/models.py"
```
## Parallel Example: Phase 4 (US1)
```bash
# T011 and T012 touch different layers — run together:
Task: "Write 3 failing thumbnail serving tests in api/tests/integration/test_serving.py"
Task: "Add getThumbnailUrl() and thumbnail_key field to ui/src/app/services/image.service.ts"
```
---
## Implementation Strategy
### MVP (All three user stories — tightly coupled)
All three user stories are P1 and interdependent: US3 (generation) enables US1 (grid) which proves US2 (detail unchanged) by contrast. Complete all phases in order.
1. Phase 1: T001 (Pillow setup)
2. Phase 2: T002T006 (core infrastructure)
3. Phase 3: T007T010 (upload generates thumbnail)
4. Phase 4: T011T016 (thumbnail endpoint + UI)
5. Phase 5: T017T018 (detail page verification)
6. Phase 6: T019T022 (delete cleanup + polish)
7. **STOP and VALIDATE**: Open library in browser; DevTools shows `/thumbnail` requests; bandwidth used is a fraction of original file sizes
### Total tasks: 22 (T001T022)
---
## Notes
- [P] tasks touch different files and have no mutual dependencies within their phase
- T002 must be run **before** T003 and confirmed failing — this is the TDD red step
- T007, T011, T019 are all "write failing test" steps — confirm failure before implementing
- `thumbnail_key` in the API response is informational; the UI always calls `/thumbnail` and lets the endpoint handle the fallback — no client-side conditional logic needed
- Existing images (pre-dating this feature) will have `thumbnail_key: null`; the `/thumbnail` endpoint serves their original transparently
- The backfill migration for existing images is explicitly out of scope for this feature

View File

@@ -0,0 +1,34 @@
# Specification Quality Checklist: JWT Bearer Token Authentication
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2026-05-03
**Feature**: [spec.md](../spec.md)
## Content Quality
- [x] No implementation details (languages, frameworks, APIs)
- [x] Focused on user value and business needs
- [x] Written for non-technical stakeholders
- [x] All mandatory sections completed
## Requirement Completeness
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Requirements are testable and unambiguous
- [x] Success criteria are measurable
- [x] Success criteria are technology-agnostic (no implementation details)
- [x] All acceptance scenarios are defined
- [x] Edge cases are identified
- [x] Scope is clearly bounded
- [x] Dependencies and assumptions identified
## Feature Readiness
- [x] All functional requirements have clear acceptance criteria
- [x] User scenarios cover primary flows
- [x] Feature meets measurable outcomes defined in Success Criteria
- [x] No implementation details leak into specification
## Notes
All items pass. Spec is ready for `/speckit-plan`.

View File

@@ -0,0 +1,120 @@
# API Contracts: JWT Bearer Token Authentication
**Feature**: `004-jwt-bearer-auth` | **Date**: 2026-05-03
All routes remain under `/api/v1/`. Error responses use the existing envelope:
`{ "detail": "<human message>", "code": "<machine code>" }`.
---
## New Endpoint
### `POST /api/v1/auth/token`
Issues a bearer token for the owner after verifying credentials.
**Request**
```
Content-Type: application/json
{
"username": "<string>",
"password": "<string>"
}
```
Both fields are required. A missing or empty field returns `422`.
**Success response**`200 OK`
```json
{
"access_token": "<jwt-string>",
"token_type": "bearer",
"expires_in": 86400
}
```
`expires_in` reflects the configured `JWT_EXPIRY_SECONDS` value.
**Failure responses**
| Status | Code | When |
|---|---|---|
| `401` | `invalid_credentials` | Username or password is wrong |
| `422` | (FastAPI default) | Missing or malformed request body |
---
## Changed Endpoints — Access Control
The following endpoints now require a valid bearer token. Requests without
a token, or with an invalid/expired token, receive a `401`.
| Method | Path | Was | Now |
|---|---|---|---|
| `POST` | `/api/v1/images` | Public | **Protected** |
| `DELETE` | `/api/v1/images/{id}` | Public | **Protected** |
| `PATCH` | `/api/v1/images/{id}/tags` | Public | **Protected** |
**Bearer token transmission**
The client MUST include the token in the `Authorization` header:
```
Authorization: Bearer <access_token>
```
**401 response shape** (returned by all three protected endpoints when
authentication fails):
```json
{
"detail": "Authentication required",
"code": "unauthorized"
}
```
---
## Unchanged Endpoints — Remain Public
The following endpoints require no token and must continue to accept requests
without an `Authorization` header:
| Method | Path | Description |
|---|---|---|
| `GET` | `/api/v1/images` | List / filter images |
| `GET` | `/api/v1/images/{id}` | Get image metadata |
| `GET` | `/api/v1/images/{id}/file` | Serve original image |
| `GET` | `/api/v1/images/{id}/thumbnail` | Serve image thumbnail |
| `GET` | `/api/v1/tags` | List / search tags |
| `GET` | `/api/v1/health` | Health check |
Sending a token on these endpoints is harmless (the server ignores it) but
is not required.
---
## Token Validation Rules
The API validates tokens using the following rules, in order:
1. The `Authorization` header value MUST begin with `Bearer ` (case-sensitive).
2. The token MUST be a valid HS256-signed JWT (verified against `JWT_SECRET_KEY`).
3. The `exp` claim MUST be in the future (at time of request receipt).
4. Any failure in steps 13 returns `401 unauthorized`.
---
## UI Route Contracts
These are Angular SPA routes affected by this feature.
| Route | Guard | Behaviour |
|---|---|---|
| `/login` | None | Login form; redirects to `returnUrl` or `/` on success |
| `/upload` | `authGuard` | Redirects to `/login?returnUrl=/upload` if not authenticated |
| `/images/:id` | None | Always accessible; tag-edit and delete controls visible only when authenticated |
| `/` | None | Always accessible (library) |

View File

@@ -0,0 +1,187 @@
# Data Model: JWT Bearer Token Authentication
**Feature**: `004-jwt-bearer-auth` | **Date**: 2026-05-03
---
## Database Changes
**None.** JWTs are stateless bearer tokens. The API validates them by
cryptographic signature and embedded expiry claim on each request. No token
storage, session table, or blocklist is introduced in Phase 2.
---
## Configuration Schema (new env vars)
Four new environment variables are added to `api/app/config.py` and
`.env.example`.
| Variable | Type | Required | Default | Description |
|---|---|---|---|---|
| `JWT_SECRET_KEY` | `str` | Yes | — | HMAC-SHA256 signing secret. Must be a long random string; no default (startup fails if absent). |
| `JWT_EXPIRY_SECONDS` | `int` | No | `86400` | Token lifetime in seconds (24 h). |
| `OWNER_USERNAME` | `str` | Yes | — | Login username for the single owner account. |
| `OWNER_PASSWORD` | `str` | Yes | — | Login password for the single owner account. |
These values are loaded via `pydantic-settings` (`BaseSettings`) alongside the
existing database and S3 settings. `JWT_SECRET_KEY`, `OWNER_USERNAME`, and
`OWNER_PASSWORD` have no defaults and will raise a validation error at startup
if absent, providing a clear "misconfigured" failure rather than a silent
security hole.
---
## Token Structure
A JWT issued by the login endpoint carries the following claims.
| Claim | Type | Value |
|---|---|---|
| `sub` | string | `"owner"` — fixed identifier for the single owner |
| `iat` | integer | Unix epoch seconds at time of issuance |
| `exp` | integer | `iat + JWT_EXPIRY_SECONDS` |
Algorithm: `HS256` (HMAC-SHA256). Secret: `JWT_SECRET_KEY` setting.
The token is opaque to the client. The Angular SPA stores it in
`sessionStorage` and transmits it as `Authorization: Bearer <token>` on every
request.
---
## Module and Interface Changes
### `api/app/auth/provider.py` — updated interface
The `get_identity()` method gains an `authorization` parameter — the raw value
of the `Authorization` HTTP header (or `None` if the header is absent).
```
AuthProvider (abstract)
get_identity(authorization: str | None) -> Identity
Identity (dataclass)
id: str
anonymous: bool = True
```
### `api/app/auth/noop.py` — no behavioural change
`NoOpAuthProvider.get_identity()` continues to return the static anonymous
identity regardless of the `authorization` argument. The signature is updated
to match the new interface.
### `api/app/auth/jwt_provider.py` — new module
```
JWTAuthProvider (AuthProvider)
__init__(secret_key: str, expiry_seconds: int, owner_username: str, owner_password: str)
get_identity(authorization: str | None) -> Identity
- Parses "Bearer <token>" from authorization header
- Decodes and validates the JWT (signature + exp)
- Returns Identity(id="owner", anonymous=False) on success
- Raises HTTPException 401 with code "unauthorized" on any failure
create_token() -> str
- Mints a new HS256 JWT with sub="owner", iat=now, exp=now+expiry_seconds
- Returns the encoded token string
verify_credentials(username: str, password: str) -> bool
- Compares username and password against OWNER_USERNAME / OWNER_PASSWORD
- Uses secrets.compare_digest to prevent timing attacks
- Returns True on match, False otherwise
```
### `api/app/dependencies.py` — new `require_auth` dependency
```
require_auth(
authorization: str | None = Header(None, alias="Authorization"),
auth: AuthProvider = Depends(get_auth)
) -> Identity
- Calls auth.get_identity(authorization)
- Raises HTTPException 401 if identity.anonymous is True
- Returns the Identity on success
```
Protected routes inject `identity: Identity = Depends(require_auth)` and do
not need to perform any additional auth checks — the dependency raises before
the route body executes if authentication fails.
### `api/app/routers/auth.py` — new router
```
POST /api/v1/auth/token
Request body: LoginRequest { username: str, password: str }
Success (200): TokenResponse { access_token: str, token_type: "bearer", expires_in: int }
Failure (401): { detail: "Invalid credentials", code: "invalid_credentials" }
```
---
## Angular Module Changes
### `ui/src/app/auth/auth.service.ts` — new service
```
AuthService
TOKEN_KEY = 'auth_token' (sessionStorage key)
login(username: string, password: string): Observable<void>
- POST /api/v1/auth/token
- On success: stores access_token in sessionStorage, emits completion
- On 401: propagates error for the component to handle
logout(): void
- Removes token from sessionStorage
getToken(): string | null
- Returns stored token or null
isAuthenticated(): boolean
- Returns true if getToken() is non-null
```
### `ui/src/app/auth/auth.interceptor.ts` — new functional interceptor
Attaches `Authorization: Bearer <token>` to every outbound `HttpRequest` if
`AuthService.getToken()` returns a non-null value. Requests without a token
are passed through unmodified.
### `ui/src/app/auth/auth.guard.ts` — new route guard
Functional `CanActivateFn`. If `AuthService.isAuthenticated()` is `false`,
redirects to `/login?returnUrl=<current-url>`. Otherwise allows navigation.
### `ui/src/app/login/login.component.ts` — new component
Route: `/login`
```
LoginComponent
Fields: username (required), password (required)
On submit:
- Calls AuthService.login()
- On success: navigates to returnUrl query param, or '/' if absent
- On 401: displays inline error "Invalid username or password"
- On other error: displays generic error message
Shows loading state while request is in flight
```
### `ui/src/app/detail/detail.component.ts` — updated
Injects `AuthService`. Hides tag-edit input and delete button when
`auth.isAuthenticated()` is `false`. Shows them when authenticated.
Read-only view (image display, tag chips) is always visible.
### `ui/src/app/app.routes.ts` — updated
`/upload` route gains `canActivate: [authGuard]`. `/login` route is added
(unguarded). All other routes are unchanged.
### `ui/src/app/app.config.ts` — updated
`provideHttpClient()` becomes
`provideHttpClient(withInterceptors([authInterceptor]))`.

View File

@@ -0,0 +1,355 @@
# Implementation Plan: JWT Bearer Token Authentication
**Branch**: `004-jwt-bearer-auth` | **Date**: 2026-05-03 | **Spec**: [spec.md](spec.md)
**Input**: Feature specification from `specs/004-jwt-bearer-auth/spec.md`
## Summary
Implement Phase 2 of the progressive auth plan (constitution §2.4): replace
the no-op `AuthProvider` with a `JWTAuthProvider` that issues and validates
HS256 bearer tokens. Upload, delete, and tag-update endpoints become
protected; all read endpoints stay public. The Angular SPA gains a login page,
a session-scoped token store, an HTTP interceptor, and a route guard for the
upload page.
No database migration is required — tokens are stateless. A single new PyJWT
dependency is added to the API. The `AuthProvider` interface gains a parameter
so the JWT provider can access the `Authorization` header; `NoOpAuthProvider`
is updated to match but its behaviour is unchanged.
Changes span: `api/app/config.py` (4 new settings), `api/app/auth/provider.py`
(interface update), `api/app/auth/jwt_provider.py` (new), `api/app/routers/auth.py`
(new), `api/app/dependencies.py` (new `require_auth` dependency), three route
updates in `api/app/routers/images.py`, and on the UI side: a new `AuthService`,
`AuthInterceptor`, `AuthGuard`, and `LoginComponent`, plus small updates to
`app.routes.ts`, `app.config.ts`, and `detail.component.ts`.
## Technical Context
**Language/Version**: Python 3.12+ (API); TypeScript strict mode (UI)
**Primary Dependencies**: FastAPI, PyJWT (new), pydantic-settings, Angular
**Storage**: PostgreSQL (no schema changes); S3-compatible (no changes)
**Testing**: pytest + pytest-asyncio (API); Angular Karma/Jest + TestBed (UI)
**Target Platform**: Linux server (containerised); modern evergreen desktop browsers
**Project Type**: Web application — FastAPI API + Angular SPA
**Performance Goals**: Login round-trip under 15 s on local network (well within
reach; no database lookup, only in-memory credential comparison + JWT signing)
**Constraints**: Stateless tokens — no server-side session storage; single owner
account; no token revocation in v1
**Scale/Scope**: Single-user personal application; auth is a deployment-time
configuration concern, not a runtime management concern
## Constitution Check
*GATE: Must pass before Phase 0 research. Re-checked after Phase 1 design below.*
| Principle | Check | Status |
|---|---|---|
| §2.1 Separation of concerns | JWT logic lives only in `JWTAuthProvider`; routes orchestrate; UI knows nothing about signing | ✅ |
| §2.2 Dependency direction | UI → API only; no upward imports introduced | ✅ |
| §2.3 Storage abstraction | No change to storage layer | ✅ |
| §2.4 Auth abstraction | `JWTAuthProvider` is a second `AuthProvider` implementation — exactly the pattern §2.4 designed for | ✅ |
| §2.5 DB abstraction | No DB changes; stateless JWTs require no session table | ✅ |
| §2.6 No speculative abstraction | No new interfaces; only a second concrete implementation of an already-planned interface | ✅ |
| §3.1 API versioning | New route at `/api/v1/auth/token` | ✅ |
| §3.3 Error shape | `401` uses `{"detail": "...", "code": "unauthorized"}` / `"invalid_credentials"` | ✅ |
| §5.1 TDD non-negotiable | Failing tests written before every implementation task | ✅ |
| §5.2 Test pyramid | Unit tests for JWT logic; integration tests for all changed routes | ✅ |
| §5.3 Test colocation | API tests in `api/tests/`; Angular specs colocated with components | ✅ |
| §5.4 CI gate | All tests + ruff must pass before milestone is done | ✅ |
| §7.1 One-command start | No change to `docker-compose.yml` required | ✅ |
| §7.2 Env configuration | `JWT_SECRET_KEY`, `JWT_EXPIRY_SECONDS`, `OWNER_USERNAME`, `OWNER_PASSWORD` added as env vars | ✅ |
| §8 Scope boundaries | §8 lists "Username/password auth (planned Phase 2)" as deferred. This feature IS Phase 2; the deferral is now lifted. All other §8 items remain deferred. | ✅ |
**Post-design re-check**: All gates still pass after Phase 1 design.
## Project Structure
### Documentation (this feature)
```text
specs/004-jwt-bearer-auth/
├── plan.md # This file
├── spec.md # Feature specification
├── research.md # Phase 0 decisions
├── data-model.md # Module and interface changes
├── contracts/
│ └── api.md # New endpoint + changed access control
├── checklists/
│ └── requirements.md # Spec quality checklist
└── tasks.md # Phase 2 output (/speckit-tasks — NOT created here)
```
### Files changed or created
```text
api/
├── pyproject.toml # Add PyJWT dependency
├── app/
│ ├── config.py # Add 4 new settings
│ ├── dependencies.py # Add require_auth dependency
│ ├── auth/
│ │ ├── provider.py # get_identity(authorization) signature
│ │ ├── noop.py # Updated signature, same behaviour
│ │ └── jwt_provider.py # NEW — JWTAuthProvider
│ └── routers/
│ ├── auth.py # NEW — POST /auth/token
│ └── images.py # Protect upload, delete, patch-tags
├── main.py # Register auth router
└── .env.example # Add 4 new vars
ui/
└── src/
└── app/
├── auth/
│ ├── auth.service.ts # NEW
│ ├── auth.service.spec.ts # NEW
│ ├── auth.interceptor.ts # NEW
│ ├── auth.interceptor.spec.ts # NEW
│ └── auth.guard.ts # NEW
├── login/
│ ├── login.component.ts # NEW
│ ├── login.component.html # NEW
│ └── login.component.spec.ts # NEW
├── detail/
│ └── detail.component.ts # Conditionally show edit/delete
├── app.routes.ts # Add /login; guard /upload
├── app.config.ts # Register authInterceptor
└── app.component.ts # Add logout button (visible when authenticated)
```
## Milestones
> **TDD ORDER IS MANDATORY** (constitution §5.1): For every milestone, write
> the failing test(s) first, confirm they fail, then implement until they pass.
---
### M1 — JWT provider: token signing and validation
**Goal**: A tested `JWTAuthProvider` that can mint tokens and validate bearer
tokens from an `Authorization` header. The `AuthProvider` interface is updated;
`NoOpAuthProvider` is kept compatible.
**Deliverables**:
- Add `PyJWT>=2.8` to `[project.dependencies]` in `api/pyproject.toml`
- Update `api/app/config.py`:
- `jwt_secret_key: str` (required — no default; validated by pydantic)
- `jwt_expiry_seconds: int = 86400`
- `owner_username: str` (required)
- `owner_password: str` (required)
- Update `api/app/auth/provider.py`: `get_identity(self, authorization: str | None) -> Identity`
- Update `api/app/auth/noop.py`: match new signature; behaviour unchanged
- Create `api/app/auth/jwt_provider.py` with `JWTAuthProvider`:
- `create_token() -> str` — mint HS256 JWT with `sub="owner"`, `iat`, `exp`
- `verify_credentials(username, password) -> bool``secrets.compare_digest`
- `get_identity(authorization) -> Identity` — parse `"Bearer <token>"`,
decode JWT, return `Identity(id="owner", anonymous=False)` on success, or
raise `HTTPException(401, {"detail": "...", "code": "unauthorized"})` on
any failure (missing header, invalid format, bad signature, expired)
**Unit tests** in `api/tests/unit/test_jwt_auth.py` (write first, confirm fail):
- `test_create_token_is_valid_jwt` — minted token decodes with PyJWT without error
- `test_get_identity_returns_owner` — valid token → non-anonymous Identity
- `test_get_identity_raises_on_expired_token` — token with past `exp` → 401
- `test_get_identity_raises_on_wrong_key` — token signed with different key → 401
- `test_get_identity_raises_on_garbage` — random string as token → 401
- `test_get_identity_raises_on_missing_header``authorization=None` → 401
- `test_get_identity_raises_on_missing_bearer_prefix``"token-without-prefix"` → 401
- `test_verify_credentials_true` — correct username + password → True
- `test_verify_credentials_false_wrong_password` — wrong password → False
- `test_verify_credentials_false_wrong_username` — wrong username → False
**Done criterion**: All 10 unit tests pass; `ruff check api/` passes; existing
tests unaffected.
---
### M2 — Login endpoint
**Goal**: `POST /api/v1/auth/token` issues a token for valid credentials and
rejects invalid ones.
**Deliverables**:
- Create `api/app/routers/auth.py`:
- `LoginRequest` Pydantic model: `username: str`, `password: str`
- `POST /auth/token` route: call `auth_provider.verify_credentials()`; on
success call `auth_provider.create_token()` and return `TokenResponse`
`{access_token, token_type="bearer", expires_in}`; on failure raise
`401 invalid_credentials`
- Update `api/app/dependencies.py`: instantiate `JWTAuthProvider` (reading
settings) instead of `NoOpAuthProvider` in `get_auth()`
- Update `api/app/main.py`: register `auth.router` under `/api/v1`
**Integration tests** in `api/tests/integration/test_auth.py` (write first):
- `test_login_success` — POST valid creds → 200, response contains
`access_token` (non-empty string), `token_type="bearer"`, `expires_in > 0`
- `test_login_wrong_password` — correct username, wrong password → 401,
code `invalid_credentials`
- `test_login_wrong_username` — wrong username → 401, code `invalid_credentials`
- `test_login_missing_password` — body `{"username": "x"}` → 422
- `test_login_missing_username` — body `{"password": "x"}` → 422
**Test infrastructure note**: The integration test `conftest.py` currently
overrides `get_auth` with `NoOpAuthProvider`. Tests for the auth endpoint
need to override with a test `JWTAuthProvider` (a real provider with test
credentials). Add a `jwt_auth_provider` fixture and an `authed_client` fixture
(with a bearer token) to `conftest.py` for use in M3.
**Done criterion**: All 5 new tests pass; all existing tests pass (the
`NoOpAuthProvider` override in `conftest.py` means existing tests are
unaffected by switching the production `get_auth()` to `JWTAuthProvider`).
---
### M3 — Protected endpoints
**Goal**: Upload, delete, and patch-tags reject unauthenticated requests.
All public endpoints remain accessible without a token.
**Deliverables**:
- Add `require_auth` to `api/app/dependencies.py`:
```python
async def require_auth(
authorization: str | None = Header(None, alias="Authorization"),
auth: AuthProvider = Depends(get_auth),
) -> Identity:
identity = await auth.get_identity(authorization)
if identity.anonymous:
raise HTTPException(
status_code=401,
detail={"detail": "Authentication required", "code": "unauthorized"},
)
return identity
```
- In `api/app/routers/images.py`:
- `upload_image()`: add `_: Identity = Depends(require_auth)` parameter
- `delete_image()`: add `_: Identity = Depends(require_auth)` parameter
- `update_image_tags()`: add `_: Identity = Depends(require_auth)` parameter
- Remove the now-redundant `auth: AuthProvider = Depends(get_auth)` from
`upload_image()` (it was injected but never called; `require_auth` subsumes it)
**Integration tests** — add to existing test files (write failing tests first):
In `api/tests/integration/test_upload.py`:
- `test_upload_without_token_returns_401` — POST without `Authorization` → 401, code `unauthorized`
- `test_upload_with_valid_token_succeeds` — POST with valid bearer token → 200/201
In `api/tests/integration/test_delete.py`:
- `test_delete_without_token_returns_401` — DELETE without token → 401
- `test_delete_with_valid_token_succeeds` — DELETE with valid token → 204
In `api/tests/integration/test_serving.py` (tag update lives here conceptually
but the route is in images; add to `test_upload.py` or a new `test_tags.py`):
- `test_patch_tags_without_token_returns_401` — PATCH without token → 401
- `test_patch_tags_with_valid_token_succeeds` — PATCH with valid token → 200
Public endpoint regression tests (confirm no 401 regression):
- `test_list_images_without_token_is_200` — GET /images → 200 (no auth)
- `test_get_image_without_token_is_200` — GET /images/{id} → 200
- `test_serve_file_without_token_is_200` — GET /images/{id}/file → 200
- `test_serve_thumbnail_without_token_is_200` — GET /images/{id}/thumbnail → 200
- `test_list_tags_without_token_is_200` — GET /tags → 200
**conftest.py update**: The `client` fixture already overrides `get_auth` with
`NoOpAuthProvider`, so all existing tests (which do not send tokens) continue
to pass without modification. The new `authed_client` fixture (from M2) uses
a `JWTAuthProvider` override and injects a valid token via the `Authorization`
header.
**Done criterion**: All new tests pass; all existing tests continue to pass.
---
### M4 — UI: `AuthService`, `AuthInterceptor`, `AuthGuard`, `LoginComponent`
**Goal**: Angular has a working login flow. The upload page is protected.
The detail page shows/hides write controls based on auth state.
**Deliverables**:
`ui/src/app/auth/auth.service.ts`:
- `TOKEN_KEY = 'auth_token'`
- `login(username, password): Observable<void>` — POST to `/api/v1/auth/token`,
store `access_token` in `sessionStorage` on success
- `logout(): void` — `sessionStorage.removeItem(TOKEN_KEY)`
- `getToken(): string | null`
- `isAuthenticated(): boolean`
`ui/src/app/auth/auth.interceptor.ts` (functional interceptor):
- If `AuthService.getToken()` returns non-null, clone request with
`Authorization: Bearer <token>` header; otherwise pass through
`ui/src/app/auth/auth.guard.ts` (`CanActivateFn`):
- If not authenticated: `router.createUrlTree(['/login'], {queryParams: {returnUrl: state.url}})`
- If authenticated: `true`
`ui/src/app/login/login.component.ts`:
- Reactive form with `username` (required) and `password` (required) controls
- `onSubmit()`: calls `AuthService.login()`; on success navigates to `returnUrl`
query param (default `/`); on error displays inline "Invalid username or password"
- Loading state while request is in flight; button disabled during loading
`ui/src/app/detail/detail.component.ts` (update):
- Inject `AuthService`
- In template: `*ngIf="auth.isAuthenticated()"` wraps the tag-edit input and
the delete button
`ui/src/app/app.routes.ts` (update):
- Add `{ path: 'login', loadComponent: () => import('./login/login.component').then(...) }`
- Add `canActivate: [authGuard]` to the `/upload` route
`ui/src/app/app.config.ts` (update):
- `provideHttpClient(withInterceptors([authInterceptor]))`
**Angular unit tests** (write first, confirm fail):
`ui/src/app/auth/auth.service.spec.ts`:
- `test_login_stores_token` — mock HTTP, verify `sessionStorage` has token after login
- `test_logout_clears_token` — store a token, logout, verify `sessionStorage` empty
- `test_isAuthenticated_true_when_token_present` — set token, assert true
- `test_isAuthenticated_false_when_no_token` — clear sessionStorage, assert false
`ui/src/app/auth/auth.interceptor.spec.ts`:
- `test_adds_auth_header_when_authenticated` — authenticated state, outbound
request has `Authorization: Bearer <token>` header
- `test_no_auth_header_when_not_authenticated` — unauthenticated, outbound
request has no `Authorization` header
`ui/src/app/login/login.component.spec.ts`:
- `test_submit_calls_auth_service_login` — spy on `AuthService.login`, submit
form, verify called with correct username/password
- `test_navigates_on_success` — mock successful login, verify router navigate called
- `test_shows_error_on_failure` — mock 401, verify error message visible
**Done criterion**: Angular build clean; all Angular tests pass.
---
### M5 — `.env.example` update and final validation
**Goal**: New env vars documented; full test suite green.
**Deliverables**:
- Update `.env.example`: add `JWT_SECRET_KEY`, `JWT_EXPIRY_SECONDS`,
`OWNER_USERNAME`, `OWNER_PASSWORD` with example values and comments
- Run `pytest api/ -v` — confirm all tests pass (expected: existing ~57 tests
+ ~20 new tests ≈ 77 total)
- Run `ruff check api/ && ruff format --check api/` — zero violations
- Run `ng test` (inside UI container) — all Angular tests pass
- Run `ng build` — Angular build succeeds
**Done criterion**: All tests pass; both linters pass; `docker compose up`
starts the full stack and the login flow works end-to-end in the browser.
## Post-design Constitution Re-check
| Principle | Verdict |
|---|---|
| §2.4 Auth abstraction | `JWTAuthProvider` is a drop-in second implementation; business logic in routes is unchanged except for the added `require_auth` dependency | ✅ |
| §2.6 No speculative abstraction | No new interfaces; `JWTAuthProvider` is concrete and implements an already-planned interface | ✅ |
| §3.3 Error shape | `401` envelope uses `code` field throughout | ✅ |
| §5.1 TDD | Failing tests precede every implementation milestone | ✅ |
| §7.2 Env config | All four new settings come from env vars; no hardcoded credentials | ✅ |
All gates pass. Feature is ready for `/speckit-tasks`.

View File

@@ -0,0 +1,185 @@
# Research: JWT Bearer Token Authentication
**Feature**: `004-jwt-bearer-auth` | **Date**: 2026-05-03
---
## Decision 1 — JWT library
**Decision**: `PyJWT>=2.8`
**Rationale**: The project needs only HS256 signing with a single symmetric
secret key — the simplest possible JWT profile. `PyJWT` is the de-facto
standard Python JWT library for this use case: no additional crypto
dependencies, actively maintained, wide community adoption. `python-jose` was
the alternative; it has broader JOSE/JWE support but has had maintenance gaps
and brings extra dependencies that we do not need.
For Phase 3 (OIDC), token issuance is replaced by the external identity
provider. The `JWTAuthProvider` will be replaced by an OIDC-aware provider;
the library choice for Phase 2 does not constrain Phase 3.
**Alternatives considered**: `python-jose[cryptography]` — wider JOSE support
but heavier dependency tree and slower maintenance cadence. Rejected.
---
## Decision 2 — Password storage for the single owner account
**Decision**: Store plaintext `OWNER_USERNAME` and `OWNER_PASSWORD` in
environment variables; compare at login time using `secrets.compare_digest`
to prevent timing attacks.
**Rationale**: This is a single-user self-hosted application accessed over a
trusted local network. The password is already known to the person deploying
the application (they set it). Bcrypt pre-hashing would require operators to
run a separate tool to generate the hash before setting the env var, adding
friction with no meaningful security benefit for this threat model. In Phase 3
the owner credentials are replaced by an external OIDC provider entirely, so
this is a temporary mechanism with limited lifetime.
`secrets.compare_digest` is used instead of `==` to prevent any theoretical
timing oracle.
**Alternatives considered**: `passlib[bcrypt]` with a pre-hashed password env
var — more "correct" in absolute terms but adds operator complexity for a
single-user local app. Rejected.
---
## Decision 3 — JWT algorithm and claims
**Decision**: HS256 (HMAC-SHA256) with claims: `sub` (fixed string `"owner"`),
`iat` (issued-at epoch seconds), `exp` (expiry epoch seconds).
**Rationale**: HS256 is symmetric — a single `JWT_SECRET_KEY` env var is used
for both signing and verification. This is appropriate for a single-server
deployment where only the API ever validates tokens. RS256 (asymmetric) would
be needed if a second service needed to verify tokens independently; that is
not the case here and would be added complexity.
The `sub` claim carries the owner identifier. `exp` enables configurable
expiry. `iat` is included for auditability.
**Alternatives considered**: RS256 — appropriate when multiple services verify
tokens. Overkill for this single-server deployment. Rejected.
---
## Decision 4 — Login endpoint request format
**Decision**: JSON body `{"username": "...", "password": "..."}` at
`POST /api/v1/auth/token`. Response: `{"access_token": "...", "token_type": "bearer", "expires_in": <seconds>}`.
**Rationale**: The OAuth2 `application/x-www-form-urlencoded` format
(`grant_type=password, username, password`) is the spec-compliant form for
the Resource Owner Password Credentials grant. However, we are not building a
full OAuth2 authorization server — this is a simplified login endpoint for a
single-user SPA. A JSON body is simpler to consume from Angular's
`HttpClient`, avoids `URLSearchParams` boilerplate, and does not mislead
consumers into thinking this is a full OAuth2 endpoint.
The response shape (`access_token`, `token_type`) follows the OAuth2 bearer
token response convention because Phase 3 (OIDC) will also produce tokens in
this shape — the Angular `AuthService` does not need to change its
token-parsing logic.
**Alternatives considered**: OAuth2 password grant form format — interoperable
but unnecessarily strict for this use case. Rejected.
---
## Decision 5 — `AuthProvider` interface evolution
**Decision**: Evolve `get_identity()` to accept a single optional string
argument: `async def get_identity(self, authorization: str | None) -> Identity`.
`NoOpAuthProvider` ignores the argument and returns the anonymous identity as
before. `JWTAuthProvider` parses `"Bearer <token>"`, validates the JWT, and
returns a non-anonymous `Identity`, or raises a `401` via `HTTPException` if
the token is invalid or expired.
A new `require_auth` dependency in `dependencies.py` calls
`auth.get_identity(authorization_header)` and raises `401` if the returned
identity is anonymous. Protected routes inject `Depends(require_auth)`.
Public routes continue to bypass auth entirely — they neither inject auth nor
call `get_identity`.
**Rationale**: Minimal interface change that preserves backward compatibility
(`NoOpAuthProvider` continues to work unchanged) while allowing the JWT
provider to access the request header cleanly through FastAPI's `Header`
dependency. An alternative would be injecting `Request` directly into the
provider, but that couples the provider to the ASGI framework; a string header
value keeps the provider framework-agnostic.
**Alternatives considered**: Pass `Request` to `get_identity()` — couples the
provider to FastAPI/ASGI. Rejected. Create a separate `validate_token(token)`
method — more interface surface, no clear benefit over the chosen approach.
Rejected.
---
## Decision 6 — Token storage in the browser
**Decision**: `sessionStorage` — tokens are discarded when the browser tab is
closed.
**Rationale**: `localStorage` persists across browser sessions and is
accessible to any JavaScript on the page, making it a wider XSS target.
`sessionStorage` is scoped to the tab and cleared on close, giving better
security for a shared or semi-public machine. For a personal app used by the
owner on their own machine, the loss of persistence across browser restarts is
a minor inconvenience that is well worth the security improvement.
`HttpOnly` cookies would be more secure still but require CSRF protection and
server-side session management, which conflicts with the stateless JWT design.
**Alternatives considered**: `localStorage` — persistent but wider XSS
exposure. Rejected. `HttpOnly` cookie — strongest XSS protection but requires
CSRF mitigation and session server state. Rejected.
---
## Decision 7 — Angular interceptor API
**Decision**: Functional HTTP interceptor registered via
`provideHttpClient(withInterceptors([authInterceptor]))` in `app.config.ts`.
The interceptor reads the token from `AuthService.getToken()` and adds
`Authorization: Bearer <token>` to every outbound request if a token is
present.
**Rationale**: Angular 17+ prefers functional interceptors over class-based
ones (`APP_INITIALIZER` / `HTTP_INTERCEPTORS` token). The functional pattern
integrates with standalone components and is the current idiomatic approach.
The interceptor attaches the token to all requests unconditionally (not just
protected endpoints) — the API ignores the header on public endpoints, so this
is safe and avoids the complexity of URL matching in the interceptor.
**Alternatives considered**: Class-based `HttpInterceptor` — legacy pattern,
not aligned with Angular 17+ standalone idiom. Rejected.
---
## Decision 8 — No database migration required
**Decision**: JWTs are stateless — no token storage or blocklist is introduced.
**Rationale**: The tokens carry their own expiry; the API validates them by
signature and expiry on each request. A token blocklist (for logout
invalidation) would require a database table and lookup on every protected
request, adding complexity disproportionate to the threat model of a
single-user local application. On logout, the Angular client discards the
token from `sessionStorage`; the token technically remains valid until its
`exp`, but since there is no other client that holds it, this is acceptable.
**Alternatives considered**: Token blocklist table — true server-side logout.
Out of scope for Phase 2; noted as a potential hardening step.
---
## Summary of new dependencies
| Package | Where | Purpose |
|---------|-------|---------|
| `PyJWT>=2.8` | `api/pyproject.toml` | JWT signing and verification |
No new UI dependencies — Angular's `HttpClient` and `Router` cover all
interceptor, guard, and HTTP needs.

View File

@@ -0,0 +1,253 @@
# Feature Specification: JWT Bearer Token Authentication
**Feature Branch**: `004-jwt-bearer-auth`
**Created**: 2026-05-03
**Status**: Draft
**Input**: User description: "Implement authentication with JWT bearer tokens. Image uploads, image deletion, and image tag updates should be protected. Non-authenticated users should still be able see images and tags, including searching for tags."
## User Scenarios & Testing *(mandatory)*
### User Story 1 — Log In and Receive a Token (Priority: P1)
The owner visits the application and logs in with their username and password.
On success, the application silently stores a credential that it will attach to
all future requests. The owner is taken to the library without needing to take
any further action.
**Why this priority**: Every protected action depends on having a valid
credential in hand. Without a working login flow, uploads, deletions, and tag
edits are all inaccessible.
**Independent Test**: Submit valid credentials via the login form. Confirm the
application navigates to the library and that subsequent protected actions
(upload, delete, tag edit) succeed without a second login prompt.
**Acceptance Scenarios**:
1. **Given** the owner is not logged in, **When** they open the application,
**Then** they are presented with a login form before they can reach any
protected action.
2. **Given** the owner submits their correct username and password, **When**
the submission is processed, **Then** they are authenticated, taken to the
library, and the credential is retained for the current session.
3. **Given** the owner submits an incorrect username or password, **When**
the submission is processed, **Then** an inline error is shown ("Invalid
credentials"), the credential is not stored, and the user remains on the
login page.
4. **Given** the owner is logged in and their session has expired, **When**
they attempt a protected action, **Then** they are redirected to the login
page and informed their session has ended.
5. **Given** the owner submits the login form with an empty username or
password field, **When** the submission is attempted, **Then** a validation
error is shown and no authentication request is made.
---
### User Story 2 — Protected Write Actions Require Authentication (Priority: P1)
An authenticated owner can upload images, delete images, and update tags as
before. An unauthenticated visitor who attempts these actions is turned away.
**Why this priority**: This is the core security requirement. Until protected
actions reliably reject unauthenticated requests, the feature has not delivered
its value.
**Independent Test**: Without logging in, attempt to upload an image via the
API or UI. Confirm the attempt is rejected with an authentication error. Log in
and repeat — confirm the upload succeeds.
**Acceptance Scenarios**:
1. **Given** an authenticated owner, **When** they upload an image, delete an
image, or update tags on an image, **Then** the action succeeds as it did
before authentication was introduced.
2. **Given** an unauthenticated visitor, **When** they attempt to upload an
image via the UI or API, **Then** the request is rejected with a clear
authentication error and no image is stored.
3. **Given** an unauthenticated visitor, **When** they attempt to delete an
image via the UI or API, **Then** the request is rejected and the image
remains in the library.
4. **Given** an unauthenticated visitor, **When** they attempt to update tags
on an image via the UI or API, **Then** the request is rejected and the
tags are unchanged.
5. **Given** a request that carries a malformed, expired, or tampered
credential, **When** it reaches a protected endpoint, **Then** it is
rejected with an authentication error, not silently ignored.
---
### User Story 3 — Public Read Access (Priority: P1)
Unauthenticated visitors can browse the image library, view individual images,
and search or filter by tags — no login required for read-only use.
**Why this priority**: The user explicitly requires this behaviour. Forcing
login for read-only access would break the browse-without-an-account use case
and is not part of the security model for this application.
**Independent Test**: Without a credential, call the list-images, get-image,
serve-image, serve-thumbnail, and list-tags endpoints. All should return
successful responses.
**Acceptance Scenarios**:
1. **Given** an unauthenticated visitor, **When** they open the library,
**Then** all images and their tags are visible without a login prompt.
2. **Given** an unauthenticated visitor, **When** they apply tag filters,
**Then** the filtered results are shown without requiring authentication.
3. **Given** an unauthenticated visitor, **When** they open an image detail
page, **Then** the full-size image and its tags are displayed without a
login prompt.
4. **Given** an unauthenticated visitor, **When** they browse the tag list
or search for tags by prefix, **Then** results are returned without
requiring authentication.
---
### User Story 4 — Log Out (Priority: P2)
The owner can end their authenticated session. After logging out, the browser
no longer retains their credential and protected actions are blocked until
they log in again.
**Why this priority**: Important for shared or public machines, but secondary
to the core login and protection flows.
**Independent Test**: Log in, then log out. Attempt a protected action and
confirm it is rejected. Refresh the page and confirm the login screen is shown.
**Acceptance Scenarios**:
1. **Given** the owner is logged in, **When** they choose to log out,
**Then** their credential is discarded, they are returned to the login page,
and subsequent protected actions are rejected.
2. **Given** the owner has logged out, **When** they navigate directly to a
protected page (e.g., the upload form), **Then** they are redirected to the
login page.
---
### Edge Cases
- What happens when the owner's credential expires mid-session? → The next
protected action fails with an authentication error; the UI redirects to
the login page.
- What happens when an attacker replays a valid but expired credential? → The
request is rejected; expired credentials are never accepted.
- What happens when the login endpoint is called many times with wrong
credentials? → The spec does not require rate limiting or lockout in v1;
this is noted as a future hardening concern.
- What happens if the owner forgets their password? → Password reset is out of
scope for v1; credentials are set via server-side configuration only.
- What happens if the login endpoint is called while already authenticated? →
A new credential is issued; the old one may be discarded by the client.
- What happens when the UI receives a 401 on a read (public) endpoint? → This
should not occur; read endpoints must never require authentication.
## Requirements *(mandatory)*
### Functional Requirements
- **FR-001**: The system MUST provide an endpoint that accepts a username and
password and, on success, returns a time-limited credential the client can
use to prove identity on subsequent requests.
- **FR-002**: The system MUST reject login attempts that supply an incorrect
username or password with a clear error; no credential is issued.
- **FR-003**: The following actions MUST be protected — they MUST reject any
request that does not carry a valid, unexpired credential:
- Upload an image
- Delete an image
- Update the tags on an image
- **FR-004**: The following actions MUST remain publicly accessible without any
credential:
- List images (with or without tag filters)
- Retrieve a single image's metadata
- Retrieve image file content
- Retrieve image thumbnail content
- List tags (with or without prefix filter)
- **FR-005**: Credentials MUST have a finite lifetime; a credential issued
before a configurable expiry window MUST be rejected.
- **FR-006**: The system MUST reject credentials that have been tampered with
or are otherwise invalid.
- **FR-007**: The UI MUST automatically attach the owner's credential to every
request that targets a protected action, without requiring the owner to
manually supply it each time.
- **FR-008**: The UI MUST redirect unauthenticated users to the login page when
they attempt to reach a protected action or page.
- **FR-009**: After a successful login, the UI MUST navigate the owner to the
library (or to the page they originally tried to reach, if redirected from
there).
- **FR-010**: The owner MUST be able to log out; after logout the credential is
discarded and protected actions are blocked until the owner logs in again.
- **FR-011**: The owner's username and password MUST be configurable without
changing application code (e.g., via environment variables or a configuration
file read at startup).
- **FR-012**: Only one set of owner credentials is required in v1; multi-user
support is explicitly out of scope.
### Key Entities
- **Credential**: A time-limited proof of identity issued to the owner after
successful login. Key attributes: subject (owner identifier), issued-at
timestamp, expiry timestamp, validity state (valid / expired / invalid).
- **Login Request**: The combination of username and password submitted by the
user to obtain a credential.
- **Protected Endpoint**: An API endpoint that MUST reject requests that lack a
valid credential.
- **Public Endpoint**: An API endpoint that MUST accept requests regardless of
whether a credential is present.
## Success Criteria *(mandatory)*
### Measurable Outcomes
- **SC-001**: An unauthenticated visitor can browse the full image library and
tag list without being prompted to log in.
- **SC-002**: An unauthenticated attempt to upload, delete, or edit tags is
rejected every time — 0% of such attempts succeed.
- **SC-003**: An authenticated owner can complete a login-to-upload round trip
in under 15 seconds on a local network connection.
- **SC-004**: An expired credential is rejected on the first use after expiry;
no grace period or retry is granted.
- **SC-005**: After logging out, 100% of subsequent protected actions are
rejected until the owner logs in again.
- **SC-006**: The library, detail, tag list, and image-serving pages all load
correctly without a credential present.
## Assumptions
- A single owner account is sufficient for v1. No user registration flow is
required; credentials are set via environment variables or configuration at
deployment time.
- The application is accessed over a trusted local network connection for v1;
HTTPS is not mandated by this spec but is assumed for any production
deployment.
- Credential lifetime is configurable but defaults to 24 hours. The exact
value is a deployment decision, not a product requirement.
- Password reset, account management, and credential revocation are out of
scope for v1.
- Rate limiting and account lockout after repeated failed login attempts are
out of scope for v1; they are noted as future hardening work.
- The UI maintains the owner's credential for the duration of the browser
session. Behaviour after the browser is closed (persist vs. discard) follows
a secure default for the credential storage mechanism chosen during
implementation.
- This is Phase 2 of a planned three-phase auth progression (no-auth →
username/password → OIDC). The implementation MUST be structured so that
replacing the credential issuance and validation mechanism in Phase 3 does
not require changes to protected business logic.
- The detail page and upload form are considered "protected pages" in the UI
sense (require login to interact with write actions), but their read content
(viewing image, viewing tags) remains publicly accessible at the API level.

View File

@@ -0,0 +1,322 @@
# Tasks: JWT Bearer Token Authentication
**Input**: Design documents from `specs/004-jwt-bearer-auth/`
**Prerequisites**: plan.md ✅, spec.md ✅, research.md ✅, data-model.md ✅, contracts/api.md ✅
**TDD**: Tests are non-negotiable per constitution §5.1. Every test task MUST be written and confirmed failing before its implementation task runs.
**Organization**: Tasks follow user story priority order (US1 P1 → US2 P1 → US3 P1 → US4 P2). API milestones run first in each story, then Angular.
## Format: `[ID] [P?] [Story] Description`
- **[P]**: Can run in parallel (different files, no dependencies on incomplete tasks)
- **[Story]**: Which user story this task belongs to (US1US4)
- Include exact file paths in descriptions
## Path Conventions
```
api/app/ API source
api/tests/unit/ API unit tests
api/tests/integration/ API integration tests
ui/src/app/ Angular source
ui/src/app/auth/ New auth module
ui/src/app/login/ New login component
```
---
## Phase 1: Setup (Shared Infrastructure)
**Purpose**: New dependency, updated config, updated interfaces, and test fixtures
that all user stories depend on. No user story work can begin until this is complete.
**⚠️ CRITICAL**: Complete all setup tasks before starting any user story phase.
- [X] T001 Add `PyJWT>=2.8` to `[project.dependencies]` in `api/pyproject.toml`; rebuild the Docker API image (`docker compose build api`) so PyJWT is available inside the container for all subsequent test runs
- [X] T002 Add four new settings to `api/app/config.py` (pydantic-settings `BaseSettings`): `jwt_secret_key: str` (required — no default, startup fails if absent), `jwt_expiry_seconds: int = 86400`, `owner_username: str` (required), `owner_password: str` (required); confirm `get_settings()` still loads from env vars via the existing `SettingsConfigDict`
- [X] T003 [P] Update `api/app/auth/provider.py`: change `get_identity(self)` to `get_identity(self, authorization: str | None) -> Identity`; this is a breaking interface change that will cause the `NoOpAuthProvider` to fail type-checking until T004 is done
- [X] T004 [P] Update `api/app/auth/noop.py`: match the new `get_identity(self, authorization: str | None) -> Identity` signature; the implementation still returns `_ANONYMOUS` and ignores `authorization`; run `pytest api/` to confirm all existing tests still pass (the conftest overrides get_auth so the interface change is invisible to running tests)
- [X] T005 Update `api/tests/integration/conftest.py`: add a `# TODO: complete after T007` comment block where the `jwt_auth_provider` and `authed_client` fixtures will live — do not add the import of `JWTAuthProvider` yet (it does not exist until T007 and would break `pytest api/` if imported now); the existing `client` fixture (with `NoOpAuthProvider`) must remain unchanged. After T007 is done, complete this task: add `jwt_auth_provider` fixture that constructs a `JWTAuthProvider` with test credentials, and `authed_client` fixture that overrides `get_auth` with that provider and yields `(client, valid_token)` where `valid_token = auth.create_token()`
**Checkpoint**: PyJWT installed, four new settings wired, interface updated, `NoOpAuthProvider` adapted, conftest ready. All existing tests still pass.
---
## Phase 2: Foundational (JWTAuthProvider — Blocks All Stories)
**Purpose**: The `JWTAuthProvider` must exist before the login endpoint (US1),
protected endpoints (US2), or public-read regression tests (US3) can be built.
**⚠️ CRITICAL**: All tasks in this phase must complete before any user story work begins.
### Tests for JWTAuthProvider (write FIRST — must FAIL before T007) ⚠️
- [X] T006 Write 10 unit tests in `api/tests/unit/test_jwt_auth.py` for the (not-yet-existing) `JWTAuthProvider`: `test_create_token_is_valid_jwt` (minted token decodes with PyJWT without error), `test_get_identity_returns_owner` (valid bearer token → non-anonymous `Identity` with `id="owner"`), `test_get_identity_raises_on_expired_token` (token with past `exp``HTTPException` 401), `test_get_identity_raises_on_wrong_key` (token signed with different secret → 401), `test_get_identity_raises_on_garbage` (random string as token value → 401), `test_get_identity_raises_on_missing_header` (`authorization=None` → 401), `test_get_identity_raises_on_missing_bearer_prefix` (`"token-without-prefix"` → 401), `test_verify_credentials_true` (matching username + password → `True`), `test_verify_credentials_false_wrong_password` (wrong password → `False`), `test_verify_credentials_false_wrong_username` (wrong username → `False`); run `pytest api/tests/unit/test_jwt_auth.py` and confirm all 10 **fail** with `ImportError` or `AttributeError` (not-yet-implemented)
### JWTAuthProvider implementation
- [X] T007 Create `api/app/auth/jwt_provider.py` with `JWTAuthProvider(AuthProvider)`: constructor takes `secret_key: str`, `expiry_seconds: int`, `owner_username: str`, `owner_password: str`; implement `create_token() -> str` using `jwt.encode({"sub": "owner", "iat": now, "exp": now + expiry_seconds}, secret_key, algorithm="HS256")`; implement `verify_credentials(username, password) -> bool` using `secrets.compare_digest`; implement `get_identity(authorization: str | None) -> Identity` — parse `"Bearer <token>"` (raise 401 `unauthorized` if missing or wrong prefix), decode with `jwt.decode()` (raise 401 on `ExpiredSignatureError`, `InvalidTokenError`, or any exception), return `Identity(id="owner", anonymous=False)` on success; run `pytest api/tests/unit/test_jwt_auth.py` and confirm all 10 pass; then run `pytest api/` to confirm no regressions
**Checkpoint**: `JWTAuthProvider` is fully implemented and tested. Login endpoint, protected-endpoint guard, and conftest fixtures can now be built.
---
## Phase 3: User Story 1 — Log In and Receive a Token (Priority: P1) 🎯 MVP
**Goal**: The owner can log in with username and password and receive a bearer
token. The Angular SPA has a working login page backed by a real API endpoint.
**Independent Test**: POST `{"username": "owner", "password": "correct"}` to
`/api/v1/auth/token`. Confirm a `200` response with a non-empty `access_token`.
Then open the browser, enter credentials in the login form, and confirm navigation
to the library. Subsequent protected requests in the browser include the token.
### Tests for User Story 1 API (write FIRST — must FAIL before T009) ⚠️
- [X] T008 [US1] Write 5 integration tests in `api/tests/integration/test_auth.py` for the (not-yet-existing) `POST /api/v1/auth/token` endpoint: `test_login_success` (POST valid creds → 200, response has `access_token` as non-empty string, `token_type="bearer"`, `expires_in > 0`), `test_login_wrong_password` (correct username, wrong password → 401, code `invalid_credentials`), `test_login_wrong_username` (wrong username → 401, code `invalid_credentials`), `test_login_missing_password` (body `{"username": "x"}` → 422), `test_login_missing_username` (body `{"password": "x"}` → 422); these tests should use a fixture with the `JWTAuthProvider` override; run `pytest api/tests/integration/test_auth.py` and confirm all 5 **fail** with `404` (route not yet registered)
### Implementation for User Story 1 (API)
- [X] T009 [US1] In `api/app/dependencies.py`, add `get_jwt_auth() -> JWTAuthProvider` — a typed dependency that returns the same `JWTAuthProvider` instance as `get_auth()` but with the concrete type, so the auth router can call `verify_credentials()` and `create_token()` without a downcast (the login endpoint is inherently tied to token issuance and is replaced wholesale in Phase 3, so it is correct for it to depend on the concrete type rather than the `AuthProvider` abstraction). Then create `api/app/routers/auth.py`: define `LoginRequest` Pydantic model (`username: str`, `password: str`), define `TokenResponse` Pydantic model (`access_token: str`, `token_type: str = "bearer"`, `expires_in: int`), add `POST /auth/token` route that injects `auth: JWTAuthProvider = Depends(get_jwt_auth)` — calls `auth.verify_credentials(username, password)`, raises `HTTPException(401, {"detail": "Invalid credentials", "code": "invalid_credentials"})` on failure, calls `auth.create_token()` and returns `TokenResponse` on success; complete T005's `conftest.py` `jwt_auth_provider` fixture import now that the module exists
- [X] T010 [US1] Update `api/app/dependencies.py`: in `get_auth()`, replace `NoOpAuthProvider()` with `JWTAuthProvider(secret_key=s.jwt_secret_key, expiry_seconds=s.jwt_expiry_seconds, owner_username=s.owner_username, owner_password=s.owner_password)` (loading settings via `get_settings()`); the existing `client` fixture in `conftest.py` still overrides `get_auth` with `NoOpAuthProvider`, so all existing tests remain unaffected
- [X] T011 [US1] Update `api/app/main.py`: import `auth` router from `app.routers.auth` and register it with `app.include_router(auth.router, prefix="/api/v1")`; run `pytest api/tests/integration/test_auth.py` and confirm all 5 tests pass; run `pytest api/` and confirm no regressions
### Tests for User Story 1 (Angular — write FIRST — must FAIL before T014) ⚠️
- [X] T012 [P] [US1] Write 3 unit tests in `ui/src/app/auth/auth.service.spec.ts` for the (not-yet-existing) `AuthService`: `test_login_stores_token` (mock `HttpClient` POST returning `{access_token: "tok"}`, verify `sessionStorage.getItem("auth_token") === "tok"` after `login()` completes), `test_isAuthenticated_true_when_token_present` (set token in sessionStorage, assert `isAuthenticated()` returns true), `test_isAuthenticated_false_when_no_token` (clear sessionStorage, assert `isAuthenticated()` returns false); run `ng test` and confirm all 3 **fail** with `Cannot find module` or similar. Note: logout tests belong to US4 and are written in T025.
- [X] T013 [P] [US1] Write 4 unit tests in `ui/src/app/login/login.component.spec.ts` for the (not-yet-existing) `LoginComponent`: `test_submit_calls_auth_service_login` (spy on `AuthService.login`, fill form, submit, verify `login` called with correct username and password), `test_navigates_to_library_on_success` (mock `AuthService.login` returning `of(void 0)`, submit, verify `Router.navigate` called with `['/']`), `test_shows_error_on_401` (mock `AuthService.login` throwing `HttpErrorResponse` with status 401, submit, verify error message element is visible in the template), `test_shows_validation_error_on_empty_fields` (disable browser-native validation via `novalidate`, leave username and password blank, click submit, verify no `HttpClient.post` call was made and a validation error element is visible in the DOM); run `ng test` and confirm all 4 **fail**
### Implementation for User Story 1 (Angular)
- [X] T014 [P] [US1] Create `ui/src/app/auth/auth.service.ts`: `TOKEN_KEY = 'auth_token'`; `login(username: string, password: string): Observable<void>` — POST `/api/v1/auth/token`, pipe `tap(res => sessionStorage.setItem(this.TOKEN_KEY, res.access_token))`, map to void; `logout(): void``sessionStorage.removeItem(this.TOKEN_KEY)`; `getToken(): string | null``sessionStorage.getItem(this.TOKEN_KEY)`; `isAuthenticated(): boolean``this.getToken() !== null`; decorate with `@Injectable({ providedIn: 'root' })`
- [X] T015 [P] [US1] Create `ui/src/app/login/login.component.ts` (standalone component, route `/login`): reactive form with `username` (required) and `password` (required) validators; `onSubmit()` calls `AuthService.login()`, sets `loading = true` while in-flight, on success reads `returnUrl` query param (default `'/'`) and calls `router.navigateByUrl(returnUrl)`, on error sets `errorMessage = 'Invalid username or password'`; template (`login.component.html`) includes a form with username input, password input, submit button (disabled while loading), and an error paragraph (`*ngIf="errorMessage"`)
- [X] T016 [US1] Update `ui/src/app/app.routes.ts`: add `{ path: 'login', loadComponent: () => import('./login/login.component').then(m => m.LoginComponent) }` before the wildcard route; run `ng test` and confirm T012 and T013 tests now pass; run `ng build` to confirm no build errors
**Checkpoint**: `POST /api/v1/auth/token` works end-to-end. Angular login form posts credentials, stores token, navigates to library. All 12 new tests (5 API + 3 Angular service + 4 Angular login) pass.
---
## Phase 4: User Story 2 — Protected Write Actions Require Authentication (Priority: P1)
**Goal**: Upload, delete, and tag-update endpoints reject unauthenticated requests
with a `401`. Angular automatically attaches the stored token to all requests.
**Independent Test**: Without logging in, attempt `POST /api/v1/images` — confirm
`401` with code `unauthorized`. Log in, then upload again — confirm `200/201`. In
the browser, verify that after login the upload form submits successfully.
### Tests for User Story 2 API (write FIRST — must FAIL before T019) ⚠️
- [X] T017 [US2] Add 6 integration tests using the `authed_client` fixture across existing test files: in `api/tests/integration/test_upload.py` add `test_upload_without_token_returns_401` (POST with no `Authorization` header → 401, code `unauthorized`) and `test_upload_with_valid_token_succeeds` (POST with `Authorization: Bearer <token>` → 200/201); in `api/tests/integration/test_delete.py` add `test_delete_without_token_returns_401` (DELETE with no token → 401) and `test_delete_with_valid_token_succeeds` (DELETE with valid token → 204); add `test_patch_tags_without_token_returns_401` (PATCH `/images/{id}/tags` with no token → 401) and `test_patch_tags_with_valid_token_succeeds` (PATCH with valid token → 200) to `api/tests/integration/test_upload.py` (or a new `test_protected.py`); run these 6 tests and confirm they all **fail** (currently return 200/204 without auth, or fixture not yet usable)
### Implementation for User Story 2 (API)
- [X] T018 [US2] Add `require_auth` async dependency to `api/app/dependencies.py`: `async def require_auth(authorization: str | None = Header(None, alias="Authorization"), auth: AuthProvider = Depends(get_auth)) -> Identity` — calls `await auth.get_identity(authorization)`, raises `HTTPException(401, {"detail": "Authentication required", "code": "unauthorized"})` if `identity.anonymous` is True, otherwise returns `Identity`
- [X] T019 [US2] In `api/app/routers/images.py`: add `_: Identity = Depends(require_auth)` parameter to `upload_image()`, `delete_image()`, and `update_image_tags()`; also remove the existing `auth: AuthProvider = Depends(get_auth)` from `upload_image()` (it was injected but never called — `require_auth` now subsumes it); add `from app.dependencies import require_auth` and `from app.auth.provider import Identity` to imports; run `pytest api/tests/integration/` and confirm all 6 new protected-endpoint tests pass and all pre-existing tests (which use the `client` fixture with `NoOpAuthProvider` override) still pass
### Tests for User Story 2 (Angular — write FIRST — must FAIL before T021) ⚠️
- [X] T020 [US2] Write 3 unit tests in `ui/src/app/auth/auth.interceptor.spec.ts` for the (not-yet-existing) `authInterceptor`: `test_adds_auth_header_when_authenticated` (configure `TestBed` with `authInterceptor`, spy `AuthService.getToken()` returning `"test-token"`, make any HTTP request via `HttpClient`, verify the outgoing request in `HttpTestingController` has header `Authorization: Bearer test-token`), `test_no_auth_header_when_not_authenticated` (spy `AuthService.getToken()` returning `null`, make HTTP request, verify `Authorization` header is absent), `test_interceptor_redirects_to_login_on_401` (spy `AuthService.getToken()` returning `"test-token"`, flush the HTTP response with status 401, spy `AuthService.logout()` and `Router.navigate`, verify `logout()` was called and `router.navigate(['/login'])` was called); run `ng test` and confirm all 3 **fail**
### Implementation for User Story 2 (Angular)
- [X] T021 [US2] Create `ui/src/app/auth/auth.interceptor.ts` as a functional interceptor that handles both outbound token injection and inbound 401 responses: `export const authInterceptor: HttpInterceptorFn = (req, next) => { const auth = inject(AuthService); const router = inject(Router); const token = auth.getToken(); if (token) { req = req.clone({ setHeaders: { Authorization: \`Bearer \${token}\` } }); } return next(req).pipe(catchError(err => { if (err instanceof HttpErrorResponse && err.status === 401) { auth.logout(); router.navigate(['/login']); } return throwError(() => err); })); }`; import `catchError`, `throwError` from `rxjs/operators` and `HttpErrorResponse` from `@angular/common/http`
- [X] T022 [US2] Update `ui/src/app/app.config.ts`: change `provideHttpClient()` to `provideHttpClient(withInterceptors([authInterceptor]))`; add the necessary imports; run `ng test` and confirm T020's 3 tests now pass; run `ng build` to confirm no build errors; run `pytest api/` to confirm all API tests still pass
**Checkpoint**: Upload, delete, and tag-update reject unauthenticated requests. The Angular interceptor attaches the token on outbound requests and redirects to `/login` on any 401 response (covering expired mid-session tokens). All 9 new tests (6 API + 3 Angular) pass.
---
## Phase 5: User Story 3 — Public Read Access (Priority: P1)
**Goal**: All read endpoints remain accessible without any credential. Verify no
401 regression was introduced by the changes in US2.
**Independent Test**: Without providing any `Authorization` header, call
`GET /api/v1/images`, `GET /api/v1/images/{id}`, `GET /api/v1/images/{id}/file`,
`GET /api/v1/images/{id}/thumbnail`, and `GET /api/v1/tags`. All must return `200`.
### Tests for User Story 3 (write FIRST — must FAIL before T024) ⚠️
- [X] T023 [US3] Add 5 regression integration tests using the `authed_client` fixture (which uses `JWTAuthProvider` but no `Authorization` header in the request) in a new `api/tests/integration/test_public_access.py`: `test_list_images_without_token_is_200` (GET `/api/v1/images` with no auth header → 200), `test_get_image_without_token_is_200` (upload image first using `authed_client` with token, then GET `/api/v1/images/{id}` with no auth header → 200), `test_serve_file_without_token_is_200` (GET `/api/v1/images/{id}/file` with no auth header → 200), `test_serve_thumbnail_without_token_is_200` (GET `/api/v1/images/{id}/thumbnail` with no auth header → 200), `test_list_tags_without_token_is_200` (GET `/api/v1/tags` with no auth header → 200); run these tests and confirm they all **fail** (they will fail until T019 is complete because the `authed_client` fixture may not yet be fully wired — or they may pass if the fixture is ready, in which case document as already-green)
### Verification for User Story 3
- [X] T024 [US3] Run `pytest api/tests/integration/test_public_access.py` and confirm all 5 pass; run `pytest api/ -v` to confirm the full API suite passes without regressions; document the passing test count
**Checkpoint**: All public read endpoints confirmed accessible without a token. No 401 regression introduced by the protected-write changes.
---
## Phase 6: User Story 4 — Log Out (Priority: P2)
**Goal**: The owner can end their session. After logout, the token is gone from
the browser and the upload page redirects to login.
**Independent Test**: Log in, verify the upload page is accessible. Click the
logout control. Verify the application navigates to `/login`. Navigate directly
to `/upload` — confirm redirect to `/login`.
### Tests for User Story 4 (write FIRST — must FAIL before T027) ⚠️
- [X] T025 [P] [US4] Add 2 unit tests to `ui/src/app/auth/auth.service.spec.ts`: `test_logout_removes_token_from_storage` (set a token in sessionStorage, call `logout()`, confirm `sessionStorage.getItem("auth_token")` is null), `test_isAuthenticated_false_after_logout` (set token, call `logout()`, confirm `isAuthenticated()` returns false); these tests cover logout behaviour which belongs to US4 and was intentionally excluded from T012; `logout()` is implemented in T014 so these tests should pass immediately — confirm they pass before proceeding
- [X] T026 [P] [US4] Write 1 unit test in a new `ui/src/app/auth/auth.guard.spec.ts` for the (not-yet-existing) `authGuard`: `test_redirects_to_login_when_not_authenticated` — configure `TestBed` with `provideRouter([])` and `provideLocationMocks()` (standalone Angular 17+ pattern; do NOT use the deprecated `RouterTestingModule`), spy `AuthService.isAuthenticated()` returning `false`, execute the guard function directly with a mock `ActivatedRouteSnapshot` and `RouterStateSnapshot` with `url = '/upload'`, assert the returned value is a `UrlTree` whose `toString()` starts with `/login`; run `ng test` and confirm it **fails**
### Implementation for User Story 4
- [X] T027 [P] [US4] Create `ui/src/app/auth/auth.guard.ts` as a functional `CanActivateFn`: inject `AuthService` and `Router`; if `auth.isAuthenticated()` return `true`; else return `router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } })`
- [X] T028 [P] [US4] Update `ui/src/app/app.routes.ts`: add `canActivate: [authGuard]` to the `/upload` route entry; add import for `authGuard`; add `CanActivateFn` guard to the route object
- [X] T029 [P] [US4] Update `ui/src/app/detail/detail.component.ts`: inject `AuthService` as `public auth: AuthService`; in the template, wrap the tag-edit input block and the delete button with `*ngIf="auth.isAuthenticated()"` so they are hidden for unauthenticated visitors; the image display and read-only tag chips remain visible to all
- [X] T030 [US4] Add a logout link/button to the application shell (`ui/src/app/app.component.ts` and its template): inject `AuthService` and `Router`; add `onLogout()` method that calls `auth.logout()` then `router.navigate(['/login'])`; render the button only when `auth.isAuthenticated()` is true; run `ng test` and confirm T025 and T026 tests pass; run `ng build` to confirm no build errors
**Checkpoint**: Logout works. Upload page is guarded. Detail page hides write controls for unauthenticated visitors. All 3 new Angular tests (2 service + 1 guard) pass.
---
## Phase 7: Polish & Cross-Cutting Concerns
**Purpose**: Environment documentation, final linting, and complete test run.
- [X] T031 [P] Update `.env.example`: add four new variables with comments:
```
# Owner credentials and JWT signing secret
JWT_SECRET_KEY=change-me-to-a-long-random-string
JWT_EXPIRY_SECONDS=86400
OWNER_USERNAME=owner
OWNER_PASSWORD=change-me
```
- [X] T032 [P] Run `~/.local/bin/ruff check api/app/auth/jwt_provider.py api/app/routers/auth.py api/app/dependencies.py api/app/config.py api/app/routers/images.py` and `ruff format --check` on the same files; fix any lint or formatting violations
- [X] T033 Run `pytest api/ -v` and confirm all tests pass; record final count (expected: ~57 existing + ~18 new ≈ 75 total)
- [X] T034 Run `ng test` inside the UI container (or locally) and confirm all Angular unit tests pass; run `ng build` and confirm the Angular build succeeds with no errors
- [X] T035 End-to-end smoke test: `docker compose up`, open the browser, verify: (a) the library loads without login, (b) navigating to `/upload` redirects to `/login`, (c) logging in navigates to the library, (d) uploading an image succeeds, (e) logging out redirects to `/login`, (f) attempting `/upload` again redirects to `/login`
---
## Dependencies & Execution Order
### Phase Dependencies
- **Setup (Phase 1)**: No dependencies — start immediately
- **Foundational (Phase 2)**: Depends on Phase 1 complete (PyJWT must be installed before tests can import `JWTAuthProvider`)
- **US1 (Phase 3)**: Depends on Phase 2 complete (`JWTAuthProvider` must exist before login endpoint tests reference it)
- **US2 (Phase 4)**: Depends on Phase 3 complete (Angular interceptor needs `AuthService`; API `require_auth` needs `JWTAuthProvider`)
- **US3 (Phase 5)**: Depends on Phase 4 complete (`require_auth` must be wired before public-access regression tests are meaningful)
- **US4 (Phase 6)**: Depends on Phase 3 complete (`AuthService.logout()` may already be implemented in T014; guard and route changes depend on login route existing from T016)
- **Polish (Phase 7)**: Depends on all feature phases complete
### Within Each Phase
- T006 (write failing tests) MUST precede T007 (implement JWTAuthProvider)
- T008 (write failing API auth tests) MUST precede T009 (implement login route)
- T012 and T013 (write failing Angular tests) MUST precede T014 and T015
- T017 (write failing 401 tests) MUST precede T018 + T019
- T020 (write failing interceptor tests) MUST precede T021
- T023 (write failing public-access tests) MUST precede T024
- T025 and T026 (write failing US4 tests) MUST precede T027T030
### Parallel Opportunities (within phases)
- T003 and T004 can run in parallel (different files in `api/app/auth/`)
- T009, T010, T011 are sequential (dependencies.py → auth.py → main.py)
- T012 and T013 can run in parallel (different spec files)
- T014 and T015 can run in parallel after T012 and T013 (different component files)
- T020 MUST precede T021 (TDD: confirm 3 tests fail before implementing interceptor)
- T025 and T026 can run in parallel (different spec files)
- T027, T028, T029 can run in parallel (different files: guard, routes, detail component)
- T031 and T032 can run in parallel
---
## Parallel Example: Phase 1 (Setup)
```bash
# T003 and T004 touch different files — run together:
Task: "Update AuthProvider interface signature in api/app/auth/provider.py"
Task: "Update NoOpAuthProvider signature in api/app/auth/noop.py"
```
## Parallel Example: Phase 3 / US1 (Angular)
```bash
# T012 and T013 touch different spec files — run together:
Task: "Write 3 failing AuthService unit tests in ui/src/app/auth/auth.service.spec.ts"
Task: "Write 4 failing LoginComponent unit tests in ui/src/app/login/login.component.spec.ts"
# T014 and T015 touch different source files — run together after T012/T013:
Task: "Create AuthService in ui/src/app/auth/auth.service.ts"
Task: "Create LoginComponent in ui/src/app/login/login.component.ts"
```
## Parallel Example: Phase 4 / US2 (Angular)
```bash
# T020 MUST precede T021 (TDD). Within US2 they are sequential.
# T020 can run in parallel with other US2 API tasks (T017, T018, T019 touch different files):
Task: "Write 3 failing interceptor tests in ui/src/app/auth/auth.interceptor.spec.ts" # T020
# (after T020 confirms failing):
Task: "Create authInterceptor in ui/src/app/auth/auth.interceptor.ts" # T021
```
## Parallel Example: Phase 6 / US4
```bash
# T027, T028, T029 touch different files — run together:
Task: "Create authGuard in ui/src/app/auth/auth.guard.ts"
Task: "Add canActivate guard to /upload route in ui/src/app/app.routes.ts"
Task: "Conditionally show write controls in ui/src/app/detail/detail.component.ts"
```
---
## Implementation Strategy
### MVP (User Stories 1 + 2 + 3 — minimum shippable auth)
All three P1 stories are interdependent: login (US1) enables write-protection
(US2), and write-protection must not break public reads (US3). Complete phases
in order:
1. Phase 1: Setup (T001T005)
2. Phase 2: Foundational JWT provider (T006T007)
3. Phase 3: US1 Login API + Angular (T008T016)
4. Phase 4: US2 Protected writes API + Angular interceptor (T017T022)
5. Phase 5: US3 Public-read regression (T023T024)
6. **STOP and VALIDATE**: Login, upload (authenticated), and public browse all work
### Incremental add-on: Logout (US4)
Once MVP is validated, add Phase 6 (T025T030) to complete the session
lifecycle. This is independently addable without revisiting previous phases.
### Total tasks: 35 (T001T035)
---
## Notes
- [P] tasks touch different files and have no mutual dependencies within their phase
- T006, T008, T012, T013, T017, T020, T023, T025, T026 are all "write failing test" steps — always confirm failure before implementing
- The `client` fixture in `conftest.py` uses `NoOpAuthProvider` and MUST NOT be changed — all existing tests depend on it passing without a token
- The `authed_client` fixture returns `(client, valid_token)` — tests choose whether to include the token, enabling both 401 and success scenarios from the same fixture
- The `authInterceptor` attaches the token unconditionally to all requests; the API silently ignores the `Authorization` header on public endpoints — no URL matching needed in the interceptor
- Logout in the UI invalidates the client-side session only; the JWT technically remains valid until its `exp` (acceptable for a single-user local app with no token revocation)

View File

@@ -0,0 +1,34 @@
# Specification Quality Checklist: UI Polish & Design System
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2026-05-03
**Feature**: [spec.md](../spec.md)
## Content Quality
- [X] No implementation details (languages, frameworks, APIs)
- [X] Focused on user value and business needs
- [X] Written for non-technical stakeholders
- [X] All mandatory sections completed
## Requirement Completeness
- [X] No [NEEDS CLARIFICATION] markers remain
- [X] Requirements are testable and unambiguous
- [X] Success criteria are measurable
- [X] Success criteria are technology-agnostic (no implementation details)
- [X] All acceptance scenarios are defined
- [X] Edge cases are identified
- [X] Scope is clearly bounded
- [X] Dependencies and assumptions identified
## Feature Readiness
- [X] All functional requirements have clear acceptance criteria
- [X] User scenarios cover primary flows
- [X] Feature meets measurable outcomes defined in Success Criteria
- [X] No implementation details leak into specification
## Notes
- All items pass. Spec is ready for `/speckit-plan`.

242
specs/005-ui-polish/plan.md Normal file
View File

@@ -0,0 +1,242 @@
# Implementation Plan: UI Polish & Design System
**Branch**: `005-ui-polish` | **Date**: 2026-05-03 | **Spec**: [spec.md](spec.md)
**Input**: Feature specification from `specs/005-ui-polish/spec.md`
## Summary
Refine the existing Angular SPA from functional-but-bare to intentional and
finished. All changes are purely front-end: a shared design-token layer
(CSS custom properties) is introduced in `styles.css`, and each of the five
views (library, upload, detail, login, app shell) is updated to use those tokens
and to handle loading, empty, and error states consistently. No new dependencies,
no new API endpoints.
---
## Technical Context
**Language/Version**: TypeScript 5 / Angular 19 (standalone components, no NgModules)
**Primary Dependencies**: Angular 19, RxJS 7 (already installed; no new deps added)
**Storage**: N/A — UI-only feature
**Testing**: Karma / Jasmine (Angular CLI default; `npm test`)
**Target Platform**: Browser SPA (desktop-primary, 375 px minimum viewport)
**Project Type**: Web application — UI layer only
**Performance Goals**: Loading indicators must not flash on sub-150 ms responses
**Constraints**: No new npm dependencies; no external icon or component library
**Scale/Scope**: Five component files + one global CSS file
---
## Constitution Check
*GATE: Must pass before Phase 0 research. Re-checked after Phase 1 design.*
| Principle | Status | Notes |
|-----------|--------|-------|
| §2.1 Strict separation of concerns — UI knows nothing about storage or DB | ✅ Pass | No API or storage changes |
| §2.2 Dependency direction — UI → API only | ✅ Pass | No new API calls introduced |
| §2.3 Storage abstraction | ✅ Pass | Not touched |
| §2.4 Auth abstraction — identity resolution via AuthProvider | ✅ Pass | Auth logic unchanged; FR-006 (hide write controls) already implemented |
| §2.6 No speculative abstraction | ✅ Pass | Tokens centralised because all five views use them; no hypothetical interfaces |
| §3.3 Error shape | ✅ Pass | UI consumes existing error envelopes; no API change |
| §5.1 TDD non-negotiable | ✅ Pass | All template and state changes will have Angular component tests written first |
| §5.2 Test pyramid | ✅ Pass | Unit tests (Karma) cover state logic; E2E visual check is the acceptance gate |
| §6 Tech stack | ✅ Pass | Angular + TypeScript; no new languages or frameworks added |
| §7.2 No hardcoded values | ✅ Pass | Colours/spacing moved to CSS custom properties, not hardcoded further |
| §7.3 Linting non-optional | ✅ Pass | ESLint + Prettier enforced; `ng build` type-check must pass |
| §8 Scope boundaries | ✅ Pass | UI-only; no multi-user, no OR/NOT tags, no OIDC |
**Constitution Check result: ALL GATES PASS**
No violations. No complexity justification table required.
---
## Project Structure
### Documentation (this feature)
```text
specs/005-ui-polish/
├── plan.md ← this file
├── research.md ← Phase 0 output (complete)
├── quickstart.md ← Phase 1 output (visual acceptance scenarios)
└── tasks.md ← Phase 2 output (/speckit-tasks — not yet created)
```
*No `data-model.md` or `contracts/` — this feature introduces no new data
entities and no API surface changes.*
### Source Code (affected files)
```text
ui/
└── src/
├── styles.css ← Add CSS custom properties (design tokens)
└── app/
├── app.component.ts ← Polish header shell
├── library/
│ └── library.component.ts ← Skeleton load, empty state, error state, card polish
├── upload/
│ └── upload.component.ts ← Drop-zone polish, in-progress state, success/error states
├── detail/
│ └── detail.component.ts ← Loading state, not-found state, section organisation
└── login/
└── login.component.ts ← Visual alignment with design system
```
---
## Milestones
### Milestone 1 — Design Token Layer (blocks all other milestones)
Extract the shared colour, spacing, and motion values already present across the
five components into CSS custom properties on `:root` in `styles.css`.
**Deliverable**: `:root` block in `styles.css` with 13 named tokens (see
research.md Decision 5). Each existing component still renders identically
(tokens match current hard-coded values exactly). `ng build` passes.
**Token set**:
```
--bg, --surface, --surface-raised, --border, --border-focus,
--text, --text-muted, --accent, --accent-text, --danger, --danger-text,
--radius, --radius-chip, --transition
```
---
### Milestone 2 — Library View (US1)
**Loading state**: Replace the current `loading = true` boolean with the
150 msdebounced spinner pattern (see research.md Decision 3). While loading,
render a grid of skeleton cards (same dimensions as real cards) using the
shimmer CSS class (see research.md Decision 2).
**Empty state**: The existing empty-state `<p>` is already functional. Polish it:
centred layout, muted icon (✦ or similar Unicode), larger text, and a prominent
"Upload your first image" link that navigates to `/upload`.
**Error state**: Add an `error: boolean` flag to the component. If the `list()`
call errors, set `error = true` and render an error card with a retry button
that calls `load()` again.
**Card polish**: Apply tokens to card background, border-radius, and tag chips.
Add a subtle `box-shadow` and `transform: translateY(-2px)` on hover (using
`--transition`). Ensure the card thumbnail `<img>` has an `(error)` fallback
(see research.md Decision 4).
**Responsive**: The existing `auto-fill minmax(200px, 1fr)` grid already handles
narrow viewports. Verify it does not overflow at 375 px; reduce min card width
to 160 px if needed.
---
### Milestone 3 — Upload View (US2)
**Drop-zone polish**: Apply token-based border and background to the existing
drag-and-drop zone. Add a dashed border accent colour (`--accent` at 40%
opacity) on active drag state.
**In-progress state**: The existing `loading` flag already disables the button.
Add a visible spinner or animated label ("Uploading…") inside the button while
in-flight so the state change is unmistakable.
**Success state**: After a successful upload, show a brief success banner
(green-tinted surface, tick character) with a "Upload another" link and a "View
in library" link. Auto-dismiss after 4 seconds or on navigation.
**Error states**: Distinct messages for validation errors (wrong type/size —
already returned by API) vs. network/server errors (generic retry). Both
displayed inline below the form, not in a modal.
**Double-submit prevention**: Already implemented (button disabled while
`loading`). Confirm the disabled style is visually clear using `--text-muted`
and reduced opacity.
---
### Milestone 4 — Detail View (US3)
**Loading state**: Add a skeleton layout while `loading = true`: a grey
rectangle at full width for the image area, and two skeleton chip rows below.
**Not-found state**: The existing `!image && !loading` condition renders a
plain text paragraph. Replace with a styled not-found card: centred layout,
muted icon, "Image not found" heading, and a "Back to library" button.
**Section organisation**: Visually separate the image area, tags section, and
write controls with consistent spacing using `--surface` panels and token-based
gaps. Write controls (tag input + delete button) should be grouped in a visually
distinct "Owner actions" area when visible.
**Tag error**: The existing `tagError` renders inline. Apply `--danger` colour
and a left border accent to make it unmistakable.
**Broken image**: Add `(error)` handler on the full-size `<img>` in the detail
view (inline SVG placeholder showing a broken-link icon).
---
### Milestone 5 — Login View (US4)
Apply the token-based design system to the login form:
- Centre the card vertically and horizontally on the page
- Wrap the form in a `--surface` card with `--radius` and a subtle border
- Use token-based input styles matching the library filter bar
- Display field-level validation errors using `--danger` colour
- The submit button uses the same `--accent` style as the library upload button
- In-progress state: button text changes to "Signing in…", button disabled
No layout changes to the existing reactive-form structure.
---
### Milestone 6 — App Shell (US5)
The existing `app.component.ts` header already conditionally renders the
sign-out button. Polish:
- Slim top bar: `--surface` background, bottom border using `--border`
- App name / logo mark on the left (text only, no image asset)
- Sign-out button aligned right using `--text-muted` colour and a simple
hover state
- Header height: `48px` fixed; does not reflow page content on state change
---
## Implementation Order
```
Milestone 1 (tokens)
Milestone 2 (library) ─┐
Milestone 3 (upload) ├─ can proceed in parallel after M1
Milestone 4 (detail) │
Milestone 5 (login) ─┘
Milestone 6 (shell) ← last (touches app.component which wraps all views)
```
M2M5 are independent of each other (different component files). M6 is last
because the app shell wraps all views and its final state is easiest to validate
once the inner views are stable.
---
## Testing Strategy
**Unit tests (Karma/Jasmine)**:
- All new state variables (`error`, `showSpinner`, skeleton visibility) are
tested via component spec files.
- Template conditionals (`*ngIf="error"`, `*ngIf="loading"`) are verified with
fixture queries.
- The `(error)` image fallback handler is tested by simulating an error event.
- Existing tests must continue to pass — no regressions.
**Visual acceptance (manual, quickstart.md)**:
- Each milestone has a corresponding scenario in quickstart.md.
- Visual checks are performed in a running `docker compose up` stack.
- 375 px viewport check: Chrome DevTools → device toolbar → iPhone SE.
**Build gate**: `ng build` must pass with zero errors after every milestone.

View File

@@ -0,0 +1,155 @@
# Quickstart: UI Polish Visual Acceptance Scenarios
Use this guide to manually verify each milestone after implementation.
Run `docker compose up` before starting. Open the browser at `http://localhost:4200`.
---
## M1 — Design Token Layer
**Goal**: Tokens exist; visual output is identical to before.
1. Open the library, upload, detail, and login pages.
2. Open browser DevTools → Elements → `<html>` or `<body>`.
3. Confirm `--bg`, `--surface`, `--accent`, `--danger` etc. are visible in
computed styles.
4. Confirm no visible change in any view compared to before M1.
---
## M2 — Library View
### Loading skeleton
1. Open DevTools → Network → set throttle to "Slow 3G".
2. Hard-refresh the library page.
3. **Expect**: A grid of grey shimmer cards appears immediately; no blank white
space; no layout jump when real images load in.
### Empty state
1. Ensure no images are uploaded (or use a fresh test database).
2. Open the library.
3. **Expect**: A centred empty-state panel with explanatory text and a prominent
"Upload your first image" link. Clicking the link navigates to `/upload`.
### Error state
1. Stop the API container (`docker compose stop api`).
2. Hard-refresh the library.
3. **Expect**: An error card with a plain-language message and a "Retry" button.
No blank grid, no raw status code.
4. Restart the API (`docker compose start api`) and click "Retry".
5. **Expect**: Images load successfully.
### Card polish
1. Hover over an image card.
2. **Expect**: Card lifts slightly (2 px translate) with a smooth transition.
### Broken image
1. Manually corrupt a storage key in the database (or unplug MinIO) and reload.
2. **Expect**: Card shows a grey placeholder graphic, not a broken-image browser icon.
### 375 px viewport
1. DevTools → Device toolbar → iPhone SE (375 × 667).
2. **Expect**: Cards stack, no horizontal scrollbar, all content readable.
---
## M3 — Upload View
### Drop-zone idle
1. Navigate to `/upload` (must be logged in).
2. **Expect**: A visually distinct drop-zone with dashed border and clear
instructions. Submit button is disabled/greyed.
### In-progress
1. Select a large image file.
2. Click upload.
3. **Expect**: Button label changes to "Uploading…" and is disabled. A spinner
or animated indicator is visible.
### Success
1. After a successful upload completes.
2. **Expect**: A green-tinted success banner with the filename, "Upload another"
link, and "View in library" link. Banner disappears after 4 seconds.
### Validation error
1. Attempt to upload a `.txt` file.
2. **Expect**: An inline error message names the problem ("Unsupported file type").
The form is still usable — no page reload required.
### Network error
1. Stop the API mid-upload (or use DevTools → block the upload request).
2. **Expect**: A generic inline error with guidance to retry. Form remains usable.
---
## M4 — Detail View
### Loading skeleton
1. Set network throttle to Slow 3G.
2. Navigate directly to an image URL (e.g., `http://localhost:4200/images/<id>`).
3. **Expect**: A grey rectangle skeleton for the image area and chip skeletons
below. No blank page.
### Not-found state
1. Navigate to `http://localhost:4200/images/00000000-0000-0000-0000-000000000000`.
2. **Expect**: A styled not-found card with "Image not found" heading and a
"Back to library" button. No blank page, no raw 404 text.
### Authenticated write controls
1. Log in and open a detail page.
2. **Expect**: Tag editing input and delete button are visible and clearly grouped.
### Unauthenticated view
1. Open the detail page in a private/incognito window (not logged in).
2. **Expect**: Image and read-only tag chips are visible. No tag input, no
delete button.
### Tag error
1. While logged in, attempt to add a tag with invalid characters (e.g., `TAG!`).
2. **Expect**: An inline error in danger colour with a left accent border.
Other tags and the image remain visible.
### Broken image
1. Open a detail page for an image whose storage object has been deleted.
2. **Expect**: A placeholder graphic replaces the image. Page layout is not broken.
---
## M5 — Login View
### Visual consistency
1. Open `/login` without being logged in.
2. **Expect**: Dark background matching the library; form centred in a surface
card; same font and spacing as other pages.
### Field validation
1. Click the Sign In button without entering any credentials.
2. **Expect**: Inline validation messages appear on the username and password
fields without a page reload.
### Invalid credentials error
1. Enter wrong credentials and submit.
2. **Expect**: A single error message below the form. Fields retain their values.
### In-progress state
1. Submit valid credentials (throttle network if needed to see the state).
2. **Expect**: Button label changes to "Signing in…" and is disabled while the
request is in flight.
---
## M6 — App Shell
### Authenticated header
1. Log in and navigate between library, upload, and an image detail page.
2. **Expect**: A consistent 48 px header is present on all pages. Sign-out
control is visible on the right. Header does not reflow content.
### Unauthenticated header
1. Open the library or detail page without logging in.
2. **Expect**: Header is present but sign-out control is absent.
### Sign out
1. Click the sign-out control in the header.
2. **Expect**: Redirected to `/login`. Header no longer shows sign-out control.
Navigating to `/upload` redirects back to `/login`.

View File

@@ -0,0 +1,137 @@
# Research: UI Polish & Design System
## Decision 1: Design token delivery mechanism
**Decision**: CSS custom properties declared on `:root` in `styles.css`.
**Rationale**: Angular's default ViewEncapsulation.Emulated scopes component
selectors with attribute hashes but does not block CSS custom property
inheritance. `:root` variables cascade into every inline component style block
without any special configuration. This is now the standard Angular 2025+ token
approach and requires zero new dependencies.
**Alternatives considered**:
- SCSS variables — require a preprocessor; project currently uses plain CSS.
- A shared `.css` import per component — works but adds per-component boilerplate
and duplicates the token surface unnecessarily.
---
## Decision 2: Skeleton loading pattern
**Decision**: Pure-CSS shimmer using `::after` pseudo-element animated gradient;
no third-party library.
**Rationale**: The spec assumption explicitly prohibits new icon/component
libraries. The standard pure-CSS skeleton pattern (placeholder divs with a
light-to-dark horizontal gradient sweeping via `@keyframes`) produces the same
visual result as library skeletons with zero added dependencies. The `::after`
approach requires no extra DOM nodes per skeleton block.
**Pattern**:
```css
@keyframes shimmer {
from { background-position: -200% 0; }
to { background-position: 200% 0; }
}
.skeleton {
background: linear-gradient(90deg, var(--surface) 25%, var(--surface-raised) 50%, var(--surface) 75%);
background-size: 200% 100%;
animation: shimmer 1.4s infinite;
border-radius: var(--radius);
}
```
**Alternatives considered**:
- `@angular/material` skeleton — adds the entire Material library as a dep.
- CSS opacity pulse — simpler but less visually informative than a shimmer.
---
## Decision 3: Loading-flash debounce
**Decision**: `timer(150).pipe(takeUntil(response$))` to gate the visibility of
loading indicators.
**Rationale**: Showing a spinner immediately causes a visible flash when the
server responds in under ~150 ms (common on localhost). The idiomatic RxJS
approach is to start a 150 ms timer alongside the real request; if the request
completes first (`takeUntil`), the timer never fires and the spinner never
appears. This avoids `race()` complexity and cleanly unsubscribes.
**Implementation sketch**:
```typescript
showSpinner = false;
load(): void {
const req$ = this.service.fetch().pipe(share());
timer(150).pipe(takeUntil(req$)).subscribe(() => { this.showSpinner = true; });
req$.subscribe(data => { this.showSpinner = false; /* handle data */ });
}
```
**Alternatives considered**:
- `race([req$, timer(150)])` — fires timer regardless of req$ speed on certain
race conditions; harder to reason about.
- CSS `animation-delay` — cannot easily tie delay to actual response time.
---
## Decision 4: Broken-image fallback
**Decision**: Inline `(error)` event binding on `<img>` elements, guarded
against recursive fallback.
**Rationale**: For a small number of distinct image elements (card thumbnail,
detail full-image), an event binding is the minimal idiomatic pattern and
avoids the complexity of a directive. Recursive fallback is prevented by
checking that the current `src` is not already the placeholder before
reassigning.
**Pattern**:
```html
<img [src]="url" (error)="onImgError($event)" />
```
```typescript
onImgError(e: Event): void {
const img = e.target as HTMLImageElement;
if (!img.src.endsWith('placeholder')) {
img.src = 'data:image/svg+xml,...'; // inline SVG placeholder
}
}
```
**Alternatives considered**:
- Custom `ImageFallbackDirective` — reusable but over-engineered for two call
sites; can be extracted later if the pattern spreads.
---
## Decision 5: Global design token set
**Decision**: Seven semantic tokens defined on `:root` in `styles.css`, derived
from colours already present in the components.
| Token | Value | Meaning |
|--------------------|-----------|----------------------------------------------|
| `--bg` | `#0f0f0f` | Page background (already in body) |
| `--surface` | `#1a1a1a` | Card / input / panel background |
| `--surface-raised` | `#252525` | Hover state, skeleton highlight |
| `--border` | `#333` | Subtle dividers, input borders |
| `--border-focus` | `#555` | Input focus ring |
| `--text` | `#e0e0e0` | Primary text (already on body) |
| `--text-muted` | `#777` | Secondary text, placeholders |
| `--accent` | `#4a9eff` | CTAs, active chips (already in upload-btn) |
| `--accent-text` | `#000` | Text on accent backgrounds |
| `--danger` | `#c0392b` | Destructive actions (already in delete-btn) |
| `--danger-text` | `#fff` | Text on danger backgrounds |
| `--radius` | `6px` | Standard border radius |
| `--radius-chip` | `12px` | Pill-shaped chips |
| `--transition` | `200ms ease` | Standard animation duration |
**Rationale**: All values are already present in the components but hard-coded
per file. Centralising them eliminates drift without introducing a new colour
palette — the visual result is identical to the current state, but consistent.
**Alternatives considered**:
- Introducing a new darker/lighter palette — unnecessary scope creep; the
existing colours are well-chosen for a dark personal tool.

180
specs/005-ui-polish/spec.md Normal file
View File

@@ -0,0 +1,180 @@
# Feature Specification: UI Polish & Design System
**Feature Branch**: `005-ui-polish`
**Created**: 2026-05-03
**Status**: Draft
**Input**: User description: "Polish the Angular UI with a cohesive visual design. The three main views — library (image grid), upload form, and image detail — should feel intentional and finished. Add proper loading states, empty states, and error states to each view. The overall aesthetic should be dark-themed and minimal, fitting a personal tool used frequently. The login page should also match the design system."
## User Scenarios & Testing *(mandatory)*
### User Story 1 — Library Feels Complete (Priority: P1)
The owner opens the app and is greeted by a polished image grid. While images
load, something visually coherent fills the space so the page doesn't feel
broken. If the library is empty, a helpful prompt explains what to do. If the
request fails, a clear error message appears with a way to retry.
**Why this priority**: The library is the landing page and the most-visited
view. Its quality sets first impressions for every session.
**Independent Test**: Open the app with no images uploaded — confirm an
intentional empty state is shown. Upload an image, return to the library —
confirm the grid renders cleanly with consistent card sizing. Throttle the
network — confirm a loading indicator appears before images arrive.
**Acceptance Scenarios**:
1. **Given** the library is loading, **When** the page first renders, **Then** a skeleton or spinner occupies the grid area so the layout does not jump or appear blank.
2. **Given** no images have been uploaded, **When** the library loads successfully, **Then** an empty-state message is shown explaining that no images exist yet, with a visible prompt to upload the first image.
3. **Given** the image fetch fails (network error), **When** the library loads, **Then** an error message is shown with a retry action; the page does not display a blank grid or a raw error code.
4. **Given** images exist, **When** the library renders, **Then** all image cards have consistent size, spacing, and visual weight; tag chips are readable and do not overflow their cards.
---
### User Story 2 — Upload Form Feels Finished (Priority: P1)
The owner navigates to the upload page and finds a form that clearly communicates
its state at every step: idle with a helpful drop-zone, active while uploading
with visible progress, and resolved with success or a plain-language error.
**Why this priority**: Upload is the primary write action. A rough upload
experience erodes confidence in the whole tool.
**Independent Test**: Upload a valid image and confirm the flow from drop-zone
through in-progress indicator to success result is smooth and clearly
communicated. Attempt an upload with an invalid file type and confirm a
plain-language validation error appears without a page reload.
**Acceptance Scenarios**:
1. **Given** the upload page is idle, **When** no file is selected, **Then** a drop-zone with clear instructions is visible; the submit button is visibly disabled.
2. **Given** a file is selected and uploading, **When** the upload is in progress, **Then** the submit button is disabled and a visible in-progress indicator is shown; the user cannot accidentally submit twice.
3. **Given** an upload succeeds, **When** the server responds, **Then** a success confirmation is shown and the owner can navigate onward without confusion.
4. **Given** an upload fails due to an invalid file type or size, **When** the server responds, **Then** a plain-language error message is shown identifying the problem; the form remains usable for another attempt.
5. **Given** an upload fails due to a network or server error, **When** the server responds, **Then** a generic error message is shown with guidance to retry.
---
### User Story 3 — Detail Page Is Well Organised (Priority: P1)
The owner opens an image's detail page and finds the image prominently displayed,
tag management clearly grouped, and write controls (edit tags, delete) visually
distinct from read content. Visitors who are not logged in see the image and
tags but no write controls. Loading and error states are handled gracefully.
**Why this priority**: The detail page is where tag curation and deletion
happen — the two most common editing actions after upload.
**Independent Test**: Open a detail page while logged in — confirm write
controls are visible and clearly grouped. Open the same page while logged out —
confirm write controls are hidden. Navigate to a non-existent image ID — confirm
a not-found state is shown rather than a blank or broken page.
**Acceptance Scenarios**:
1. **Given** the detail page is loading, **When** the route is first entered, **Then** a loading indicator is shown in place of the image and metadata.
2. **Given** the image exists and the owner is logged in, **When** the page renders, **Then** the image is the focal point; tags are displayed below; tag editing and delete controls are clearly grouped and visually differentiated from read content.
3. **Given** the image exists and the visitor is not logged in, **When** the page renders, **Then** the image and tags are visible; no tag-edit input or delete button is present.
4. **Given** a non-existent image ID is requested, **When** the page loads, **Then** a not-found state is shown with a link back to the library; no raw error code or blank area is displayed.
5. **Given** a tag update fails, **When** the owner submits a tag change, **Then** an inline error message explains the failure; the image and other tags remain visible.
---
### User Story 4 — Login Page Matches the Design (Priority: P2)
The owner lands on the login page (directly or after a redirect) and finds a
form that visually belongs to the same application as the library and detail
page. The form clearly communicates validation errors and submission state.
**Why this priority**: Login is visited infrequently. A consistent visual
treatment matters, but functional correctness (already implemented) is more
critical than aesthetic alignment.
**Independent Test**: Navigate to `/login` directly — confirm the page uses the
same colour scheme, typography, and spacing as the rest of the app. Submit with
empty fields — confirm visible validation errors appear without a page reload.
**Acceptance Scenarios**:
1. **Given** the login page loads, **When** the owner views it, **Then** the page uses the same dark background, colour palette, and typographic scale as all other views.
2. **Given** the owner submits with empty username or password, **When** the form is submitted, **Then** inline validation messages appear on the relevant fields without a page reload or server round-trip.
3. **Given** the owner submits invalid credentials, **When** the server rejects them, **Then** a single error message is shown below the form; the fields are not cleared.
4. **Given** the form is submitting, **When** the request is in-flight, **Then** the submit button is disabled and shows an in-progress label so the owner cannot submit twice.
---
### User Story 5 — App Shell Is Consistent (Priority: P2)
Every page shares a consistent outer frame: a slim header that shows the
sign-out control when logged in. The header does not compete with page content
for visual attention but is always present and usable.
**Why this priority**: A coherent shell ties the individual views together into
a single application rather than a collection of pages.
**Independent Test**: Navigate between library, detail, and upload while logged
in — confirm the header is consistent across all views. Sign out and visit a
public page — confirm the sign-out control is absent.
**Acceptance Scenarios**:
1. **Given** the owner is logged in, **When** viewing any page, **Then** a slim header is present with a sign-out control; it does not draw excessive visual attention away from the page content.
2. **Given** the visitor is not logged in, **When** viewing the library or a detail page, **Then** the header is present but contains no sign-out control.
3. **Given** the owner clicks sign out in the header, **When** the action completes, **Then** they are redirected to the login page and the header no longer shows the sign-out control.
---
### Edge Cases
- What happens if an image fails to load (broken URL or storage outage)? The card or detail view should show a placeholder, not the browser's default broken-image icon.
- What happens on a very narrow viewport (mobile browser)? Cards should stack or resize; the layout must not overflow horizontally.
- What happens if a tag is very long? Tag chips must truncate or wrap without breaking the card or detail layout.
- What happens during slow network conditions? Loading states must appear promptly and not flash on fast connections.
---
## Requirements *(mandatory)*
### Functional Requirements
- **FR-001**: Every view (library, upload, detail, login) MUST display a loading indicator while async data or actions are in progress.
- **FR-002**: The library MUST display a meaningful empty-state message with a call to action when no images exist.
- **FR-003**: All four views MUST display plain-language error messages when an operation fails; raw HTTP status codes or stack traces MUST NOT be shown to the user.
- **FR-004**: The upload form MUST disable the submit control while an upload is in progress to prevent duplicate submissions.
- **FR-005**: The detail page MUST show a not-found state (with a back link) when the requested image does not exist.
- **FR-006**: Write controls on the detail page (tag editing, delete) MUST be hidden for unauthenticated visitors and visible only to the logged-in owner.
- **FR-007**: All views MUST share a consistent set of visual tokens: background colours, text colours, spacing scale, border radii, and interactive-element styles.
- **FR-008**: The application MUST be usable on viewports as narrow as 375 px (iPhone SE width) without horizontal overflow.
- **FR-009**: Loading indicators MUST NOT flash on connections fast enough to resolve in under 150 ms; debounced or skeleton-based approaches are preferred.
- **FR-010**: Broken image assets (failed loads) MUST display a visible placeholder rather than the browser's default broken-image icon.
### Key Entities
- **Design token set**: The shared palette, spacing scale, and typographic rules that all views derive from (background, surface, border, text-primary, text-muted, accent, danger).
- **Loading state**: A visual treatment applied to any view or element while data is being fetched or an action is in progress.
- **Empty state**: A purposeful layout shown when a collection has zero items, including explanatory text and a next-action prompt.
- **Error state**: A purposeful layout shown when an operation fails, including a plain-language description and (where applicable) a retry action.
---
## Success Criteria *(mandatory)*
### Measurable Outcomes
- **SC-001**: Every view transitions from loading to content (or error/empty) without a layout shift visible to the naked eye.
- **SC-002**: All five views pass a visual consistency check: an observer can identify them as belonging to the same application by colour, typography, and spacing alone.
- **SC-003**: The library, upload, and detail views each render without horizontal scrollbars on a 375 px wide viewport.
- **SC-004**: Each error condition (network failure, validation failure, not-found) produces a user-visible message within the current view — zero conditions result in a silent failure or blank screen.
- **SC-005**: Loading indicators do not appear on responses that complete in under 150 ms in a local development environment (no flicker on fast connections).
---
## Assumptions
- The existing dark colour palette already in the components (#1a1a1a backgrounds, #e0e0e0 text, #4a9eff accent) is the correct base; the polish work refines and extends it rather than replacing it wholesale.
- No external component library or icon set is introduced; any icons needed are either inline SVG or Unicode characters to avoid new dependencies.
- The app remains a single-page application; no server-side rendering or route-level transitions are in scope.
- Mobile layout is "good enough to use" at 375 px rather than a fully optimised mobile-first redesign; a dedicated mobile redesign is out of scope.
- No new API endpoints are needed; all changes are purely front-end.
- Animations and transitions are minimal — a single standard duration applied consistently; no complex motion design.
- FR-006 (hiding write controls for unauthenticated visitors) is already implemented in the detail component; this spec confirms the behaviour is preserved and visually correct, not that it needs to be built from scratch.

View File

@@ -0,0 +1,242 @@
# Tasks: UI Polish & Design System
**Input**: Design documents from `specs/005-ui-polish/`
**Prerequisites**: plan.md ✓, spec.md ✓, research.md ✓, quickstart.md ✓
**Tests**: Component spec tests are included per §5.1 (TDD non-negotiable). Tests are written first and must fail before implementation begins. Karma/Jasmine via Angular CLI test runner.
**Organization**: Phase 2 (design token layer) blocks all user story phases. User story phases (Phase 37) are independent of each other and can proceed in parallel after Phase 2 completes.
**Milestone mapping** (cross-reference with `plan.md` and `quickstart.md`):
Phase 2 = M1 (Tokens) | Phase 3 = M2 (Library) | Phase 4 = M3 (Upload) | Phase 5 = M4 (Detail) | Phase 6 = M5 (Login) | Phase 7 = M6 (Shell)
## Format: `[ID] [P?] [Story] Description`
- **[P]**: Can run in parallel (different files, no dependencies on incomplete tasks)
- **[Story]**: Which user story this task belongs to (US1US5)
- All component files are under `ui/src/app/`
---
## Phase 1: Setup
**Purpose**: Verify baseline state before any changes are made.
- [X] T001 Confirm `ng build` passes with zero errors in `ui/` (baseline gate before any changes)
---
## Phase 2: Foundational — M1: Design Token Layer
**Purpose**: Establish the shared CSS custom property layer in `ui/src/styles.css`. This is the blocking prerequisite for all five user story phases — no component work begins until these tokens exist.
**⚠️ CRITICAL**: No user story phase can begin until T004 passes.
- [X] T002 Add 13 CSS custom property tokens to `:root` in `ui/src/styles.css`: `--bg`, `--surface`, `--surface-raised`, `--border`, `--border-focus`, `--text`, `--text-muted`, `--accent`, `--accent-text`, `--danger`, `--danger-text`, `--radius`, `--radius-chip`, `--transition` — use exact values from research.md Decision 5
- [X] T003 Add `@keyframes shimmer` animation and `.skeleton` utility class to `ui/src/styles.css` using the gradient pattern from research.md Decision 2
- [X] T004 Confirm `ng build` passes with zero errors after token additions (M1 gate — components unchanged, visual output identical)
**Checkpoint**: Design token layer complete. User story phases 37 may now start.
---
## Phase 3: User Story 1 — Library Feels Complete (Priority: P1) 🎯 MVP
**Goal**: The library view has skeleton loading, a styled empty state, an error state with retry, polished cards with hover lift, image error fallback, and responsive layout at 375 px.
**Independent Test**: Throttle network to Slow 3G and hard-refresh `/` — confirm shimmer skeleton appears. Remove all images — confirm styled empty state with "Upload your first image" link. Stop API — confirm error card with Retry button. Hover a card — confirm 2 px lift. Set viewport to 375 px — confirm no horizontal scrollbar.
### Tests for User Story 1 (TDD — write first, confirm failure before T008) ⚠️
- [X] T005 [US1] Add component tests for `showSpinner` debounce flag, `error` flag, skeleton card count, empty-state link, error card retry button, and `onImgError` handler in `ui/src/app/library/library.component.spec.ts`
### Implementation for User Story 1
- [X] T006 [P] [US1] Replace all hardcoded colour and spacing values with CSS token variables in the component styles block of `ui/src/app/library/library.component.ts`
- [X] T007 [US1] Replace `loading = true` boolean with `showSpinner = false` and add 150 ms debounce using `timer(150).pipe(takeUntil(req$))` from research.md Decision 3 in `ui/src/app/library/library.component.ts`
- [X] T008 [US1] Add skeleton loading grid: while `showSpinner` is true render 8 `<div class="skeleton card-skeleton">` placeholders at the same dimensions as real cards in `ui/src/app/library/library.component.ts`
- [X] T009 [US1] Add `error = false` flag; set it on `list()` failure; render an error card with plain-language message and "Retry" button that calls `load()` in `ui/src/app/library/library.component.ts`
- [X] T010 [US1] Replace the plain empty-state `<p>` with a centred panel: Unicode icon (✦), larger muted heading, and a `routerLink="/upload"` "Upload your first image" link in `ui/src/app/library/library.component.ts`
- [X] T011 [US1] Add card hover effect: `transform: translateY(-2px)` and `box-shadow` with `transition: var(--transition)` using `--surface-raised` in `ui/src/app/library/library.component.ts`
- [X] T012 [US1] Add `(error)="onImgError($event)"` on the card thumbnail `<img>` and implement `onImgError` with an inline SVG placeholder (guard against recursive fallback per research.md Decision 4) in `ui/src/app/library/library.component.ts`
- [X] T013 [US1] Check the `auto-fill minmax()` value in the grid at 375 px: if cards overflow horizontally, reduce min card width to `160px` and record the change; if no overflow, document "verified at 160px — no change needed" in a code comment in `ui/src/app/library/library.component.ts`
**Checkpoint**: Library view is fully functional with all loading/empty/error/responsive states.
---
## Phase 4: User Story 2 — Upload Form Feels Finished (Priority: P1)
**Goal**: The upload form has a visually distinct drop-zone, visible in-progress state ("Uploading…" + spinner), a success banner with auto-dismiss, distinct validation vs. network error messages, and a clearly disabled button style.
**Independent Test**: Navigate to `/upload` — confirm dashed drop-zone border. Select a large file and click Upload — confirm button shows "Uploading…" and is disabled. After success — confirm green banner appears then disappears after 4 s. Attempt to upload a `.txt` file — confirm "Unsupported file type" inline error.
### Tests for User Story 2 (TDD — write first, confirm failure before T016) ⚠️
- [X] T014 [US2] Add component tests for `loading` button-disabled state, "Uploading…" label, `showSuccess` banner visibility, auto-dismiss timer, validation error message, and network error message in `ui/src/app/upload/upload.component.spec.ts`
### Implementation for User Story 2
- [X] T015 [P] [US2] Replace all hardcoded colour values with CSS token variables in the component styles block of `ui/src/app/upload/upload.component.ts`
- [X] T016 [US2] Style the drop-zone with a dashed `--accent`-coloured border at 40% opacity; add an active drag state that brightens the border to full `--accent` in `ui/src/app/upload/upload.component.ts`
- [X] T017 [US2] Change submit button label to "Uploading…" and add a CSS spinner `<span>` inside the button while `loading = true` in `ui/src/app/upload/upload.component.ts`
- [X] T018 [US2] Add `showSuccess = false` and `uploadedFilename = ''`; after a successful upload set both, show a green-tinted banner with filename, "Upload another" link, and "View in library" routerLink, then auto-dismiss after 4 s using `setTimeout` in `ui/src/app/upload/upload.component.ts`
- [X] T019 [US2] Show distinct inline error messages: validation errors (wrong type/size from API) show the specific problem; network/server errors show a generic retry message — both rendered below the form without a page reload in `ui/src/app/upload/upload.component.ts`
- [X] T020 [US2] Apply `--text-muted` colour and `opacity: 0.5` to the disabled button style to make the disabled state visually unmistakable in `ui/src/app/upload/upload.component.ts`
**Checkpoint**: Upload form communicates every state clearly and prevents duplicate submission.
---
## Phase 5: User Story 3 — Detail Page Is Well Organised (Priority: P1)
**Goal**: The detail view has a loading skeleton, a network error state with retry, a styled not-found card with back link, a grouped "Owner actions" panel for write controls, danger-styled tag errors, and a broken-image fallback.
**Independent Test**: Throttle to Slow 3G and navigate to `/images/<id>` — confirm skeleton appears. Stop the API and hard-refresh a detail page — confirm error card with retry (not a blank page). Navigate to `/images/00000000-0000-0000-0000-000000000000` — confirm not-found card with "Back to library" button. Log in and open a detail page — confirm write controls are grouped. Open detail page while logged out — confirm write controls absent. Add tag with `!` character — confirm danger-coloured inline error.
### Tests for User Story 3 (TDD — write first, confirm failure before T023) ⚠️
- [X] T021 [US3] Add component tests for skeleton visibility while `loading=true`, network error card when fetch fails (non-404), not-found card when `!image && !loading && !error`, tag error `--danger` style application, and `onImgError` handler in `ui/src/app/detail/detail.component.spec.ts`
### Implementation for User Story 3
- [X] T022 [P] [US3] Replace all hardcoded colour values with CSS token variables in the component styles block of `ui/src/app/detail/detail.component.ts`
- [X] T023 [US3] Add skeleton loading layout while `loading = true`: a full-width grey `.skeleton` rectangle for the image area and two rows of `.skeleton` chip placeholders below in `ui/src/app/detail/detail.component.ts`
- [X] T024 [US3] Add `error = false` flag; set it on API fetch failure (non-404 errors); render an error card with plain-language "Failed to load image" message, "Back to library" link, and a "Retry" button that calls the fetch again — distinct from the not-found state in `ui/src/app/detail/detail.component.ts`
- [X] T025 [US3] Replace the plain `!image && !loading && !error` paragraph with a styled not-found card: centred layout, muted Unicode icon, "Image not found" `<h2>`, and a "Back to library" `routerLink="/"` button in `ui/src/app/detail/detail.component.ts`
- [X] T026 [US3] Wrap the tag-edit input and delete button in a visually distinct "Owner actions" `<section>` with a `--surface` panel, `--border` top separator, and token-based padding/gap in `ui/src/app/detail/detail.component.ts`
- [X] T027 [US3] Apply `color: var(--danger)` and `border-left: 3px solid var(--danger)` with left-padding to the `tagError` inline error element in `ui/src/app/detail/detail.component.ts`
- [X] T028 [US3] Add `(error)="onImgError($event)"` on the full-size `<img>` and implement `onImgError` with an inline SVG broken-link placeholder (guard against recursive fallback) in `ui/src/app/detail/detail.component.ts`
**Checkpoint**: Detail page handles all states (loading, error, not-found, success) gracefully and clearly separates read from write content.
---
## Phase 6: User Story 4 — Login Page Matches the Design (Priority: P2)
**Goal**: The login page uses the shared dark design system, displays field-level validation errors and server error messages in `--danger` colour without a page reload, shows a single server error below the form on bad credentials, and disables the button with "Signing in…" label while in-flight.
**Independent Test**: Navigate to `/login` — confirm dark background, surface card, same font as library. Click Sign In with empty fields — confirm field-level errors without page reload. Enter wrong credentials — confirm single error message below form in danger colour; fields retain values. Throttle network and submit valid credentials — confirm button shows "Signing in…" and is disabled.
### Tests for User Story 4 (TDD — write first, confirm failure before T031) ⚠️
- [X] T029 [US4] Add component tests for field-level validation error display on empty submit, `errorMessage` server error paragraph visibility after failed login, "Signing in…" button label while `loading=true`, and fields-not-cleared behaviour in `ui/src/app/login/login.component.spec.ts`
### Implementation for User Story 4
- [X] T030 [P] [US4] Replace all hardcoded colour values with CSS token variables in the component styles block of `ui/src/app/login/login.component.ts`
- [X] T031 [US4] Centre the login card vertically (`height: 100vh; display: flex; align-items: center; justify-content: center`) and wrap the form in a `--surface` card with `--radius` border-radius and a `1px solid var(--border)` border in `ui/src/app/login/login.component.ts`
- [X] T032 [US4] Apply `color: var(--danger)` to field-level reactive-form validation error `<span>` elements for both username and password fields, and to the `errorMessage` server error paragraph below the form in `ui/src/app/login/login.component.ts`
- [X] T033 [US4] Change submit button label to "Signing in…" and add `disabled` attribute while `loading = true`; style the button with `--accent` background and `--accent-text` foreground matching other views in `ui/src/app/login/login.component.ts`
**Checkpoint**: Login page is visually consistent with the rest of the app and communicates all form states.
---
## Phase 7: User Story 5 — App Shell Is Consistent (Priority: P2)
**Goal**: Every page shares a 48 px fixed-height header with the app name on the left and the sign-out control on the right (when authenticated). The header uses `--surface` background and `--border` bottom border and does not reflow page content on auth state change.
**Independent Test**: Log in and navigate between library, upload, and detail — confirm identical 48 px header on all pages. Log out — confirm sign-out control disappears but header height is unchanged. Visit library without logging in — confirm header is present but sign-out control absent.
### Tests for User Story 5 (TDD — write first, confirm failure before T036) ⚠️
- [X] T034 [US5] Add component tests for header 48 px height, sign-out button visibility when authenticated, sign-out button absence when unauthenticated, sign-out action redirecting to `/login`, and header height unchanged between auth states in `ui/src/app/app.component.spec.ts`
### Implementation for User Story 5
- [X] T035 [P] [US5] Replace all hardcoded colour values with CSS token variables in the component styles block of `ui/src/app/app.component.ts`
- [X] T036 [US5] Style the header `<header>` element with `height: 48px`, `background: var(--surface)`, `border-bottom: 1px solid var(--border)`, and a flex layout placing the app name text on the left and the sign-out button on the right; use `color: var(--text-muted)` and a token-based hover state for the sign-out button; ensure `height` is declared on the host element so the 48 px is preserved regardless of sign-out button visibility in `ui/src/app/app.component.ts`
**Checkpoint**: All five views share a coherent shell. Application feels like one product.
---
## Phase 8: Polish & Cross-Cutting Concerns
**Purpose**: Linting gate, build validation, responsive checks, and visual acceptance walk-through across all milestones.
- [X] T037 [P] Run `ng lint` in `ui/` and confirm zero ESLint and Prettier violations across all modified component files (§7.3 gate)
- [X] T038 [P] Run `ng build` in `ui/` and confirm zero TypeScript or template errors across all modified components
- [ ] T039 [P] Run `ng test --watch=false` in `ui/` (or equivalent build-time check) and confirm all new component spec tests pass with zero regressions
- [ ] T040 [P] Verify upload form layout at 375 px viewport (Chrome DevTools device toolbar → iPhone SE): confirm no horizontal scrollbar and all form elements are usable in `ui/src/app/upload/upload.component.ts`
- [ ] T041 [P] Verify detail page layout at 375 px viewport: confirm image, tags, and (when authenticated) owner actions are all visible without horizontal overflow in `ui/src/app/detail/detail.component.ts`
- [ ] T042 Walk through `specs/005-ui-polish/quickstart.md` scenarios M1M6 in a running `docker compose up` stack and confirm every visual acceptance criterion passes
---
## Dependencies & Execution Order
### Phase Dependencies
- **Setup (Phase 1)**: No dependencies — start immediately
- **Foundational (Phase 2)**: Depends on Phase 1 — **BLOCKS all user story phases**
- **User Stories (Phases 37)**: ALL depend on Phase 2 (T004 gate); independent of each other
- **Polish (Phase 8)**: Depends on all desired user story phases completing
### User Story Dependencies
- **US1 Library (Phase 3, P1)**: Can start after Phase 2 — no dependency on US2US5
- **US2 Upload (Phase 4, P1)**: Can start after Phase 2 — no dependency on US1, US3US5
- **US3 Detail (Phase 5, P1)**: Can start after Phase 2 — no dependency on US1US2, US4US5
- **US4 Login (Phase 6, P2)**: Can start after Phase 2 — no dependency on US1US3, US5
- **US5 App Shell (Phase 7, P2)**: Can start after Phase 2 — best done last as it wraps all views, but technically independent
### Within Each User Story Phase
1. Write component spec tests first (TDD) — they MUST fail before implementation
2. Token replacement task [P] can run alongside test writing (different files)
3. Implementation tasks follow in sequence (each new feature depends on the test that exercises it)
---
## Parallel Execution Examples
### Running US1 (Library) startup in parallel
```text
# Start simultaneously after Phase 2 completes:
Task T005: Write library component tests (spec file)
Task T006: Apply CSS tokens to library component styles
```
### Running all three P1 stories in parallel (Phase 3, 4, 5)
```text
# All can start simultaneously after T004 (Phase 2 gate):
Phase 3 (US1): T005 → T006/T007 → T008 → T009 → T010 → T011 → T012 → T013
Phase 4 (US2): T014 → T015/T016 → T017 → T018 → T019 → T020
Phase 5 (US3): T021 → T022/T023 → T024 → T025 → T026 → T027 → T028
```
---
## Implementation Strategy
### MVP First (US1 + US2 + US3 — all P1 stories)
1. Complete Phase 1: Baseline verification
2. Complete Phase 2: Design token layer (CRITICAL gate)
3. Complete Phases 3, 4, 5 in parallel or sequence (all P1)
4. **STOP and VALIDATE**: Run quickstart.md M1M4 scenarios
5. Add Phase 6 (US4 Login) and Phase 7 (US5 Shell) for complete polish
### Incremental Delivery
1. Phase 1 + Phase 2 → Token layer live (no visible change)
2. Phase 3 (US1) → Library feels complete → Demo
3. Phase 4 (US2) → Upload flow polished → Demo
4. Phase 5 (US3) → Detail page organised → Demo
5. Phase 6 (US4) + Phase 7 (US5) → Full design system applied → Final demo
6. Phase 8 → Lint clean, build clean, all tests pass, quickstart validated
---
## Notes
- `[P]` tasks have no file conflicts with other concurrent `[P]` tasks in the same phase
- TDD order is mandatory: spec tests must be written and confirmed failing before implementation tasks
- All five component files are standalone Angular components — changes are isolated
- `ng build` is the type-check gate; Karma tests require the full Docker stack for browser runner
- No new npm dependencies are introduced in any task
- Commit after each milestone (M1M6) for clean rollback points

View File

@@ -0,0 +1,34 @@
# Specification Quality Checklist: Header Navigation & Sign-Out Destination
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2026-05-03
**Feature**: [spec.md](../spec.md)
## Content Quality
- [X] No implementation details (languages, frameworks, APIs)
- [X] Focused on user value and business needs
- [X] Written for non-technical stakeholders
- [X] All mandatory sections completed
## Requirement Completeness
- [X] No [NEEDS CLARIFICATION] markers remain
- [X] Requirements are testable and unambiguous
- [X] Success criteria are measurable
- [X] Success criteria are technology-agnostic (no implementation details)
- [X] All acceptance scenarios are defined
- [X] Edge cases are identified
- [X] Scope is clearly bounded
- [X] Dependencies and assumptions identified
## Feature Readiness
- [X] All functional requirements have clear acceptance criteria
- [X] User scenarios cover primary flows
- [X] Feature meets measurable outcomes defined in Success Criteria
- [X] No implementation details leak into specification
## Notes
- All items pass. Both changes are small, independent, and clearly bounded. Spec is ready for `/speckit-plan`.

View File

@@ -0,0 +1,25 @@
# Implementation Plan: Header Navigation & Sign-Out Destination
**Branch**: `006-header-nav-signout` | **Date**: 2026-05-03 | **Spec**: [spec.md](spec.md)
## Summary
Two targeted changes to `ui/src/app/app.component.ts`:
1. Wrap the header app-name text in a router link to `/`.
2. Change the post-sign-out navigation target from `/login` to `/`.
No API changes. No new dependencies. One component file affected.
## Technical Context
**Language/Version**: TypeScript 5 / Angular 19 (standalone components)
**Affected files**: `ui/src/app/app.component.ts`, `ui/src/app/app.component.spec.ts`
**Testing**: Karma / Jasmine
## Constitution Check
| Principle | Status |
|-----------|--------|
| §2.1 Strict separation of concerns | ✅ UI-only change |
| §5.1 TDD non-negotiable | ✅ Tests written first |
| §7.3 Linting non-optional | ✅ ng lint gate in tasks |

View File

@@ -0,0 +1,69 @@
# Feature Specification: Header Navigation & Sign-Out Destination
**Feature Branch**: `006-header-nav-signout`
**Created**: 2026-05-03
**Status**: Draft
**Input**: User description: "Simple updates to the UI. Site title in the header should link to the base URL so that it's quick to get back to the main grid view from any sub-page now or in the future. When a user signs out, they should be sent back to the grid view instead of the sign in form."
## User Scenarios & Testing *(mandatory)*
### User Story 1 — Header Title Links to Grid (Priority: P1)
The owner (or any visitor) is on a sub-page — an image detail page, the upload form, or any future page — and wants to return to the main image grid. Clicking the application name in the header takes them there immediately, without needing the browser back button or a dedicated navigation link.
**Why this priority**: The header title is always visible on every page and is the most natural home-navigation affordance. Making it functional costs almost nothing and benefits every session.
**Independent Test**: Open any sub-page (e.g., an image detail page). Click the application title in the header. Confirm the image grid loads. Works identically whether logged in or not.
**Acceptance Scenarios**:
1. **Given** the user is on any page other than the grid, **When** they click the application title in the header, **Then** they are taken to the image grid view.
2. **Given** the user is already on the grid view, **When** they click the application title, **Then** the page either reloads the grid or stays on it — no error, no blank page.
3. **Given** the user is not logged in and is on a public detail page, **When** they click the application title, **Then** they are taken to the grid (which is publicly visible) without being redirected to login.
---
### User Story 2 — Sign Out Lands on Grid (Priority: P1)
The owner signs out of the application and is returned to the image grid rather than the login page. Since the grid is publicly accessible, there is no need to force a redirect to login — the owner can choose to sign back in if they wish.
**Why this priority**: Sending a signed-out user to the login page is unnecessary friction for a personal tool where the grid content is public. It also makes the sign-out flow feel punitive rather than neutral.
**Independent Test**: Log in and sign out from the header. Confirm the image grid is shown, not the login form. Confirm the grid shows images in read-only mode (no write controls).
**Acceptance Scenarios**:
1. **Given** the user is signed in, **When** they click the sign-out control, **Then** their session ends and they are taken to the image grid view.
2. **Given** the user has landed on the grid after signing out, **When** they view the page, **Then** tag-edit and delete controls are not shown (consistent with unauthenticated behaviour already in place).
3. **Given** the user signs out from a sub-page (e.g., detail page), **When** the sign-out completes, **Then** they are taken to the grid — not to the page they were on, and not to the login form.
---
### Edge Cases
- What happens if the grid is unavailable when the user clicks the title? The navigation attempt is made; any existing error-state handling on the grid covers this.
- What if a future page introduces an auth-required route? The header title links to the grid unconditionally; auth guards on specific routes handle their own redirects independently.
## Requirements *(mandatory)*
### Functional Requirements
- **FR-001**: The application title displayed in the persistent header MUST be a navigable link that takes the user to the image grid view from any page in the application.
- **FR-002**: The title link MUST be accessible to both authenticated and unauthenticated users; it MUST NOT trigger a login redirect.
- **FR-003**: After a user successfully signs out, the application MUST navigate them to the image grid view.
- **FR-004**: The sign-out destination MUST be the grid view regardless of which page the user was on when they signed out.
## Success Criteria *(mandatory)*
### Measurable Outcomes
- **SC-001**: From any page, the image grid is reachable in exactly one click via the header title — no intermediate pages or redirects.
- **SC-002**: After signing out, the user sees the image grid (not the login page) in 100% of sign-out flows.
- **SC-003**: The title link functions correctly for both authenticated and unauthenticated sessions — verified across the grid, detail, and upload pages.
## Assumptions
- The image grid at the root URL is publicly accessible without authentication (confirmed: existing behaviour shows images to unauthenticated visitors).
- The application title ("Reactbin") is already rendered as a text element in the persistent header from the UI polish work; this spec adds navigation behaviour to it, not a new visual element.
- No change is made to the login redirect behaviour for protected routes (e.g., navigating directly to `/upload` while logged out still redirects to login as before).
- The sign-out action clears the session as already implemented; only the post-sign-out destination changes.

View File

@@ -0,0 +1,15 @@
# Tasks: Header Navigation & Sign-Out Destination
## Phase 1: Tests (TDD — write first)
- [X] T001 Add component tests for header title routerLink to `/` and sign-out navigation to `/` in `ui/src/app/app.component.spec.ts`
## Phase 2: Implementation
- [X] T002 Wrap the `.app-name` span in a `routerLink="/"` anchor in `ui/src/app/app.component.ts`
- [X] T003 Change `onLogout()` navigation target from `/login` to `/` in `ui/src/app/app.component.ts`
## Phase 3: Validation
- [X] T004 Run `ng lint` in `ui/` — zero violations
- [X] T005 Run `ng build` in `ui/` — zero errors

View File

@@ -0,0 +1,34 @@
# Specification Quality Checklist: Tag Browser
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2026-05-06
**Feature**: [spec.md](../spec.md)
## Content Quality
- [X] No implementation details (languages, frameworks, APIs)
- [X] Focused on user value and business needs
- [X] Written for non-technical stakeholders
- [X] All mandatory sections completed
## Requirement Completeness
- [X] No [NEEDS CLARIFICATION] markers remain
- [X] Requirements are testable and unambiguous
- [X] Success criteria are measurable
- [X] Success criteria are technology-agnostic (no implementation details)
- [X] All acceptance scenarios are defined
- [X] Edge cases are identified
- [X] Scope is clearly bounded
- [X] Dependencies and assumptions identified
## Feature Readiness
- [X] All functional requirements have clear acceptance criteria
- [X] User scenarios cover primary flows
- [X] Feature meets measurable outcomes defined in Success Criteria
- [X] No implementation details leak into specification
## Notes
- All items pass. Feature is small and well-bounded — two P1 stories (browse + navigate) form the core MVP; P2 (discoverability link) is a natural follow-on. No clarifications needed. Ready for `/speckit-plan`.

View File

@@ -0,0 +1,58 @@
# Contract: GET /api/v1/tags (enhanced)
## Overview
Extends the existing tags list endpoint with two new optional query parameters. All existing behaviour is preserved when the new parameters are omitted.
## Request
```
GET /api/v1/tags
```
### Query Parameters
| Parameter | Type | Default | Description |
|------------|---------|----------|-------------|
| `q` | string | — | Filter tags by name prefix (existing) |
| `limit` | integer | 100 | Max items to return; capped at 200 (existing) |
| `offset` | integer | 0 | Pagination offset (existing) |
| `sort` | string | `name` | Sort order: `name` (alphabetical asc) or `count_desc` (image count descending, alphabetical secondary) |
| `min_count`| integer | 0 | Exclude tags with fewer than this many images. Use `1` to hide zero-count tags. |
### Authentication
Not required. Public endpoint.
## Response
```json
{
"items": [
{ "id": "uuid", "name": "string", "image_count": 0 }
],
"total": 0,
"limit": 100,
"offset": 0
}
```
No changes to the response shape.
## Tag Browser Usage
The tag browser component calls:
```
GET /api/v1/tags?sort=count_desc&min_count=1&limit=500
```
`limit=500` is a safe upper bound for a personal library. If `total` exceeds `limit` in the response, the component logs a warning but renders what it received (no pagination UI required at this scale).
## Library Autocomplete Usage (unchanged)
```
GET /api/v1/tags?q=<prefix>&limit=10
```
Uses neither `sort` nor `min_count` — default behaviour is unchanged.

View File

@@ -0,0 +1,23 @@
# Data Model: Tag Browser
No schema changes are required for this feature. All data needed to power the tag browser already exists.
## Derived Entity: Tag with Count
The tag browser displays a **read-only, derived view** of existing data:
| Field | Source | Notes |
|-------|--------|-------|
| `name` | `tags.name` | Lowercase, normalised string |
| `image_count` | `COUNT(image_tags.image_id) WHERE image_tags.tag_id = tags.id` | Computed at query time |
This is exactly the shape already returned by `GET /api/v1/tags` as `{"id", "name", "image_count"}`.
## What Changes
The query in `TagRepository.list_tags()` gains two optional behaviours:
1. **Sort by count descending** — adds `ORDER BY image_count DESC, name ASC` (count-desc primary, alphabetical secondary) instead of the current `ORDER BY name ASC`.
2. **Exclude zero-count tags** — adds `HAVING image_count > 0` (or equivalent `WHERE` on the subquery) when `min_count=1` is requested.
No new tables, columns, indexes, or migrations are needed.

View File

@@ -0,0 +1,96 @@
# Implementation Plan: Tag Browser
**Branch**: `007-tag-browser` | **Date**: 2026-05-06 | **Spec**: [spec.md](spec.md)
**Input**: Feature specification from `specs/007-tag-browser/spec.md`
## Summary
Add a `/tags` page that lists every tag with its image count, sorted by popularity, each linking to the filtered library view. Requires: (1) two new query parameters on the existing `/api/v1/tags` endpoint to support sort-by-count and zero-count exclusion, (2) query-parameter-driven filtering on the library route so tag browser links deep-link correctly, (3) a new `TagBrowserComponent`, and (4) a navigation entry point from the library.
## Technical Context
**Language/Version**: Python 3.12 (API), TypeScript strict / Angular 19 (UI)
**Primary Dependencies**: FastAPI, SQLAlchemy 2.x async, Angular standalone components
**Storage**: PostgreSQL (read-only for this feature — no schema changes)
**Testing**: pytest + httpx (API integration), Jasmine/Karma (Angular unit)
**Target Platform**: Web (same stack as all prior features)
**Project Type**: Web service + SPA
**Performance Goals**: Tag list page load perceived as instant (same bar as library)
**Constraints**: No schema changes; no new dependencies; counts must be accurate at page-load time
**Scale/Scope**: Personal library — tag count is bounded; no pagination UI needed for tag browser, but the API call uses existing paginated endpoint
## Constitution Check
| Principle | Status | Notes |
|-----------|--------|-------|
| §2.1 Strict separation of concerns | ✅ | UI calls API; API owns all DB logic |
| §2.5 Repository layer | ✅ | All query changes go in `TagRepository.list_tags()` |
| §2.6 No speculative abstraction | ✅ | No new interfaces; extends existing repo method |
| §3.1 API versioning `/api/v1/` | ✅ | Modifying existing versioned endpoint |
| §3.2 OpenAPI as contract | ✅ | New query params documented via FastAPI |
| §3.3 Error shape | ✅ | No new error paths |
| §3.4 Pagination | ✅ | Existing endpoint already paginates; tag browser fetches with `limit=500` (safe upper bound for a personal library) |
| §4.1 Tags lowercase normalised | ✅ | No change to tag creation/normalisation |
| §5.1 TDD non-negotiable | ✅ | Tests written before implementation in tasks |
| §5.3 Tests colocated | ✅ | API tests in `api/tests/`, Angular spec next to component |
| §6 Tech stack | ✅ | No new dependencies |
| §7.3 Linting/formatting enforced | ✅ | `ng lint` + `ruff` gates in tasks |
**Gate**: All principles pass. Phase 0 research not required — no unknowns.
## Project Structure
### Documentation (this feature)
```text
specs/007-tag-browser/
├── plan.md ← this file
├── research.md ← not required (no unknowns)
├── data-model.md ← see below (derived data, no schema changes)
├── contracts/
│ └── tags-endpoint.md ← enhanced GET /api/v1/tags contract
└── tasks.md ← generated by /speckit-tasks
```
### Source Code Changes
```text
api/
├── app/
│ ├── repositories/
│ │ └── tag_repo.py ← extend list_tags() with sort + min_count params
│ └── routers/
│ └── tags.py ← expose sort + min_count as query params
└── tests/
├── integration/
│ └── test_tags.py ← new tests: sort=count_desc, min_count=1
└── unit/
└── test_tags.py ← unit tests for repo sort/filter logic (if applicable)
ui/src/app/
├── tags/
│ ├── tags.component.ts ← new TagBrowserComponent
│ └── tags.component.spec.ts ← component tests
├── services/
│ └── tag.service.ts ← add sort param to list() method
├── library/
│ └── library.component.ts ← read ?tags= query param on init; add /tags nav link
└── app.routes.ts ← add /tags route (lazy-loaded)
```
## Design Decisions
### API: extend existing endpoint rather than add new one
The `/api/v1/tags` endpoint already returns tags with `image_count`. Two new optional query parameters make it serve the tag browser without breaking existing callers (the library autocomplete uses the endpoint unchanged):
- `sort`: `name` (default, current behaviour) | `count_desc` (tag browser use case)
- `min_count`: integer, default `0` (all tags, current behaviour) | `1` (excludes zero-count tags)
### Library: query param deep-linking
The library component currently manages `activeFilters` in memory only. Adding `?tags=cat,funny` query parameter support (read on `ngOnInit` via `ActivatedRoute`) allows the tag browser to link directly to a pre-filtered library view. The library already uses `addFilter()` / `applyFilter()` internally — reading from query params simply pre-populates `activeFilters` before the initial `load()` call. Navigation from within the library that changes filters should update the URL to keep it shareable, but that is a polish concern — minimum requirement is that arriving at `/?tags=cat` shows the cat-filtered library.
### Tag browser UI layout
A responsive chip/card grid sorted by count descending. Each item shows the tag name and count. Each item is a `routerLink` to `/?tags=<name>`. Follows the existing design token system (`--surface`, `--accent`, `--chip` styles). Empty state if no tags exist.

View File

@@ -0,0 +1,45 @@
# Quickstart: Tag Browser
## Verifying the feature end-to-end
### Prerequisites
- Docker stack running (`docker compose up`)
- At least 3 images uploaded with different tags (e.g., `cat`, `funny`, `reaction`)
- At least one image with two tags (e.g., both `cat` and `funny`)
### Scenario 1 — Tag browser shows all tags with correct counts
1. Open the app (not logged in).
2. Navigate to `/tags`.
3. **Expected**: A list of tags is shown. Each tag displays the number of images with that tag. Tags are ordered from most images to fewest.
4. Verify: Count next to `cat` matches the number of images actually tagged `cat`.
5. Verify: Tags with zero images are not shown.
### Scenario 2 — Clicking a tag navigates to the filtered library
1. On the `/tags` page, click the `cat` tag.
2. **Expected**: Navigated to the library (`/`) showing only images tagged `cat`.
3. Verify: The active filter chip shows `cat` in the library.
### Scenario 3 — Library page links to tag browser
1. Navigate to `/` (library, logged in or out).
2. **Expected**: A link or button labelled "Browse by tag" (or similar) is visible.
3. Click it.
4. **Expected**: The tag browser page loads.
### Scenario 4 — Empty state
1. If the library has no images at all, navigate to `/tags`.
2. **Expected**: An empty state message is shown rather than a blank page or error.
### API verification
```bash
# Sorted by count, zero-count tags excluded
curl http://localhost:8000/api/v1/tags?sort=count_desc&min_count=1
# Existing autocomplete behaviour unchanged
curl http://localhost:8000/api/v1/tags?q=ca&limit=10
```

View File

@@ -0,0 +1,95 @@
# Feature Specification: Tag Browser
**Feature Branch**: `007-tag-browser`
**Created**: 2026-05-06
**Status**: Draft
**Input**: User description: "A page that lists all tags with their image counts so that users don't have to guess at searches to find image categories/tags"
## User Scenarios & Testing *(mandatory)*
### User Story 1 — Browse All Tags (Priority: P1)
The owner (or any visitor) wants to know what categories of images exist in the library without having to type guesses into a search box. They navigate to the tag browser page and see every tag in the library alongside the number of images associated with it, sorted so the most-used tags appear first.
**Why this priority**: This is the entire purpose of the feature. A visitor who doesn't know what tags exist has no way to discover them otherwise — the tag filter on the library page only helps when you already know what to type.
**Independent Test**: Navigate to the tag browser page without being logged in. Confirm every tag in the library is shown with its image count, ordered from highest to lowest count.
**Acceptance Scenarios**:
1. **Given** the library contains images with various tags, **When** a visitor opens the tag browser page, **Then** every tag in the library is listed with the number of images that carry that tag.
2. **Given** the tag list is displayed, **When** the visitor looks at the ordering, **Then** tags with more images appear before tags with fewer images.
3. **Given** the visitor is not logged in, **When** they open the tag browser page, **Then** the page loads and displays tags without requiring authentication.
---
### User Story 2 — Navigate from Tag to Library (Priority: P1)
A visitor sees a tag they are interested in and wants to view the images in that category. Clicking a tag on the tag browser page takes them directly to the library filtered to that tag, without requiring them to retype it.
**Why this priority**: The tag browser page has no value as a dead end. Each tag must be a link to the filtered library view — that is the core action the page enables. Treated as P1 because the browse and navigate actions together form the minimum useful feature.
**Independent Test**: Click any tag on the tag browser page. Confirm the library view opens showing only images carrying that tag.
**Acceptance Scenarios**:
1. **Given** the tag browser is showing a list of tags, **When** the visitor clicks a tag, **Then** they are taken to the library view filtered to show only images with that tag.
2. **Given** the visitor clicks a tag with a count of one, **When** the library loads, **Then** exactly one image is shown.
---
### User Story 3 — Reach the Tag Browser from the Library (Priority: P2)
The owner is browsing the image library and wants to switch to the tag browser to explore by category. A navigation element on the library page makes the tag browser discoverable without requiring the visitor to type the URL directly.
**Why this priority**: The tag browser is only useful if visitors can find it. A direct entry point from the library is the most natural discovery path; however, the core value of browsing and navigating tags is independently deliverable without it.
**Independent Test**: Load the library page. Confirm a visible link or button leads to the tag browser and navigates correctly when clicked.
**Acceptance Scenarios**:
1. **Given** the visitor is on the library page, **When** they look for a way to browse by tag, **Then** a visible link or button leads them to the tag browser.
2. **Given** the visitor clicks that link, **When** the tag browser loads, **Then** all tags and counts are shown as expected.
---
### Edge Cases
- What if there are no tags in the library at all? The page displays an appropriate empty state message rather than a blank page or error.
- What if a tag has been removed from all images (count reaches zero)? Tags with a count of zero are not shown on the tag browser page.
- What if the library contains a very large number of distinct tags? The page renders all of them without truncation; pagination is not required at personal library scale.
- What if two tags share the same count? An alphabetical secondary sort is acceptable — no specific tie-breaking order was requested.
## Requirements *(mandatory)*
### Functional Requirements
- **FR-001**: The application MUST provide a dedicated tag browser page accessible at a stable URL.
- **FR-002**: The tag browser page MUST display every tag that exists in the library with at least one associated image, each shown with its current image count.
- **FR-003**: Tags with an image count of zero MUST NOT appear on the tag browser page.
- **FR-004**: Tags MUST be ordered from highest image count to lowest image count.
- **FR-005**: Each tag on the tag browser page MUST be a navigable link that takes the visitor to the library view filtered to that tag.
- **FR-006**: The tag browser page MUST be publicly accessible without authentication.
- **FR-007**: The library page MUST include a discoverable navigation element leading to the tag browser page.
### Key Entities
- **Tag with count**: A tag label paired with the number of images currently carrying that tag. No new stored data — counts are derived from existing imagetag relationships at read time.
## Success Criteria *(mandatory)*
### Measurable Outcomes
- **SC-001**: Every tag present in the library with at least one image appears on the tag browser page — 0% omission rate.
- **SC-002**: The image count displayed next to each tag matches the actual number of images with that tag — 100% accuracy.
- **SC-003**: Clicking any tag on the tag browser navigates to the correctly filtered library view in 100% of cases.
- **SC-004**: The tag browser page loads successfully without authentication — verified by opening it while logged out.
- **SC-005**: A visitor can go from the library page to the tag browser and on to a filtered library view in three interactions or fewer.
## Assumptions
- Tags are already a first-class concept in the library — images can have multiple tags and the data needed to derive counts already exists. No schema changes are required.
- The library page already supports filtering by tag (via the existing search/filter mechanism); the tag browser links into that existing behaviour.
- Alphabetical secondary sort for equal-count tags is acceptable.
- Pagination of the tag list is out of scope for a personal image library.
- Creating, renaming, or deleting tags from the tag browser page is out of scope; it is a read-only view.

View File

@@ -0,0 +1,152 @@
# Tasks: Tag Browser
**Input**: Design documents from `specs/007-tag-browser/`
**Prerequisites**: plan.md ✅, spec.md ✅, data-model.md ✅, contracts/ ✅, quickstart.md ✅
**Tests**: TDD is non-negotiable (§5.1). Every implementation task is preceded by a failing-test task. Test tasks MUST be written and confirmed failing before the corresponding implementation task begins.
**Organization**: Foundational API + service changes first (block all stories), then one phase per user story.
## Format: `[ID] [P?] [Story] Description`
- **[P]**: Can run in parallel with other [P] tasks in the same phase
- **[Story]**: Which user story this task belongs to
- Exact file paths included in every task description
---
## Phase 1: Setup
No new project structure required. The existing layout accommodates all changes.
---
## Phase 2: Foundational — API Enhancement & Service Update
**Purpose**: Extend `GET /api/v1/tags` with `sort` and `min_count` query parameters; update the Angular `TagService` to pass them. All three user stories depend on the API returning tags sorted by count with zero-count tags excluded.
**⚠️ CRITICAL**: No user story work can begin until this phase is complete.
- [X] T001 [P] Write failing API integration tests for `sort=count_desc` and `min_count=1` params in `api/tests/integration/test_tags.py` — assert response is ordered highest-count-first and excludes zero-count tags
- [X] T002 [P] Write failing spec for updated `TagService.list()` accepting `sort` and `minCount` params in `ui/src/app/services/tag.service.spec.ts` — final signature: `list(prefix = '', limit = 100, offset = 0, sort?: string, minCount?: number)`
- [X] T003 Extend `TagRepository.list_tags()` in `api/app/repositories/tag_repo.py` — add `sort: str = "name"` and `min_count: int = 0` params; apply `ORDER BY image_count DESC, name ASC` when `sort="count_desc"`; apply `HAVING image_count >= min_count` filter — run AFTER T001 (TDD)
- [X] T004 Expose `sort` and `min_count` as optional query params in `api/app/routers/tags.py` — pass through to `tag_repo.list_tags()` — run AFTER T003
- [X] T005 Update `TagService.list()` in `ui/src/app/services/tag.service.ts` — final signature: `list(prefix = '', limit = 100, offset = 0, sort?: string, minCount?: number)`; include `sort` and `min_count` in `HttpParams` when provided — run AFTER T002 (TDD)
**Execution order**: T001 ∥ T002 → T003 (after T001), T005 (after T002) → T004 (after T003)
**Checkpoint**: `GET /api/v1/tags?sort=count_desc&min_count=1` returns tags sorted by image count descending with zero-count tags excluded. `TagService.list()` passes the new params.
---
## Phase 3: User Story 1 — Browse All Tags (Priority: P1) 🎯 MVP
**Goal**: A `/tags` page that lists every tag (with count ≥ 1) sorted from most-used to least-used, with loading skeleton, empty state, and error state matching the existing design system.
**Independent Test**: Navigate to `/tags` while logged out. Confirm every tag with at least one image is shown with its count, ordered by count descending. Confirm the empty state appears when no tags exist.
### Tests for User Story 1
- [X] T006 [US1] Write failing spec for `TagBrowserComponent` in `ui/src/app/tags/tags.component.spec.ts` covering: (a) skeleton shown while loading, (b) tag list rendered with name and count after load, (c) tags ordered by count descending, (d) empty state shown when tag list is empty, (e) error state shown on fetch failure with retry button, (f) each rendered tag element has an `href` of `/?tags=<tagname>` (FR-005 coverage), (g) component renders when `AuthService` is not present / user is unauthenticated (FR-006 coverage)
### Implementation for User Story 1
- [X] T007 [US1] Create `TagBrowserComponent` in `ui/src/app/tags/tags.component.ts` — standalone component; on init call `tagService.list('', 500, 0, 'count_desc', 1)` (positional order matches T005 signature); display tag chips with name + count; each chip is a `routerLink="/"` with `[queryParams]="{tags: tag.name}"` so the href renders as `/?tags=<name>`; include skeleton loading state (reuse `.skeleton` class from global styles), empty state, and error state with retry; apply design tokens throughout
- [X] T008 [P] [US1] Add `/tags` lazy route to `ui/src/app/app.routes.ts` — load `TagBrowserComponent`; no auth guard (public route)
**Checkpoint**: `/tags` renders a sorted, filterable tag list visible without authentication.
---
## Phase 4: User Story 2 — Navigate from Tag to Library (Priority: P1)
**Goal**: Clicking a tag on the tag browser navigates to the library pre-filtered to that tag. Requires the library to read `?tags=<name>` from the URL on init and apply it as an active filter before the first image load.
**Independent Test**: Navigate directly to `/?tags=cat` in the browser. Confirm the library loads showing only images tagged `cat` and the `cat` chip appears in the active filter bar.
### Tests for User Story 2
- [X] T009 [US2] Write failing spec for `LibraryComponent` reading `?tags=` query param in `ui/src/app/library/library.component.spec.ts` — assert that when the component initialises with `?tags=cat` in the URL, `activeFilters` contains `['cat']` and `imageService.list` is called with `['cat']`
### Implementation for User Story 2
- [X] T010 [US2] Update `LibraryComponent` in `ui/src/app/library/library.component.ts` — inject `ActivatedRoute`; in `ngOnInit`, read `snapshot.queryParamMap.get('tags')`; if present, split by comma, set `activeFilters` before calling `load()` so the first fetch is already filtered
**Checkpoint**: Navigating to `/?tags=cat` from the tag browser shows the correctly filtered library.
---
## Phase 5: User Story 3 — Tag Browser Discoverable from Library (Priority: P2)
**Goal**: A visible "Browse tags" link in the library page header navigates to `/tags`. Makes the tag browser discoverable without requiring the user to type the URL.
**Independent Test**: Load the library page. Confirm a link to `/tags` is visible in the header and navigates correctly when clicked.
### Tests for User Story 3
- [X] T011 [US3] Write failing spec for library nav link to `/tags` in `ui/src/app/library/library.component.spec.ts` — assert a link element with `href="/tags"` is present in the rendered header
### Implementation for User Story 3
- [X] T012 [US3] Add "Browse tags" `routerLink="/tags"` link to `LibraryComponent` header in `ui/src/app/library/library.component.ts` — place alongside the existing Upload button; style consistently with the existing header button pattern
**Checkpoint**: All three user stories are independently functional.
---
## Phase 6: Polish & Cross-Cutting Concerns
- [X] T013 [P] Run `ruff check api/app/ api/tests/` and fix any violations
- [X] T014 [P] Run `ng lint` in `ui/` — zero violations required
- [X] T015 Run `ng build` in `ui/` — zero errors required
---
## Dependencies & Execution Order
### Phase Dependencies
- **Phase 2 (Foundational)**: Blocks all user story phases — must complete first
- **Phase 3 (US1)**: Depends on Phase 2 — TagBrowserComponent needs the sorted tag endpoint
- **Phase 4 (US2)**: Depends on Phase 2 — library deep-link needs no API change, but should follow US1 for coherent testing
- **Phase 5 (US3)**: Depends on Phase 3 (needs the `/tags` route to exist for the link to be meaningful)
- **Phase 6 (Polish)**: Depends on all prior phases
### Within Phase 2
- T001 ∥ T002 (different repos, both write failing tests)
- T003 after T001 (TDD: failing test must exist first)
- T005 after T002 (TDD: failing test must exist first)
- T003 ∥ T005 (different repos, after their respective tests)
- T004 after T003 (router wraps repo)
### Execution Order (Phase 2)
```
Step 1 (parallel): T001, T002
Step 2 (parallel): T003 (after T001), T005 (after T002)
Step 3: T004 (after T003)
```
### Parallel Opportunities (Phases 35)
- T007 and T008 are parallel within Phase 3
---
## Implementation Strategy
### MVP (US1 + US2 — both P1)
1. Complete Phase 2 (Foundational)
2. Complete Phase 3 (US1 — TagBrowserComponent)
3. Complete Phase 4 (US2 — library deep-link)
4. **Validate**: Navigate from tag browser → library → confirm pre-filtered results
5. Phases 56 add discoverability and polish
### Incremental Delivery
- After Phase 3: `/tags` page is live and usable (visitors can browse tags)
- After Phase 4: clicking a tag works end-to-end (browse → filtered library)
- After Phase 5: tag browser is discoverable from the library without typing the URL
- After Phase 6: lint and build clean, ready for merge

View File

@@ -0,0 +1,236 @@
# Implementation Plan: PostgreSQL Integration Test Infrastructure
**Branch**: `master` | **Date**: 2026-05-06 | **Spec**: specs/008-postgres-integration-tests/spec.md
**Input**: Feature specification from `specs/008-postgres-integration-tests/spec.md`
---
## Summary
Enforce the constitution's PostgreSQL mandate (§2.5, §5.2 v1.3.0) for integration tests. Three concrete deliverables: (1) a fast-fail guard in `conftest.py` that rejects non-PostgreSQL URLs before any test collects, (2) a `docker-compose.test.yml` that provides isolated `postgres-test` and `minio-test` services and an `api-test` runner, and (3) a `Makefile` + `.env.test.example` that document the canonical test commands.
---
## Technical Context
**Language/Version**: Python 3.12, Docker Compose v2
**Primary Dependencies**: pytest, pytest-asyncio, asyncpg, SQLAlchemy 2.x (all already in `pyproject.toml [dev]`)
**Storage**: PostgreSQL 16-alpine (test instance), MinIO (test instance)
**Testing**: pytest — this feature *is* the test infrastructure change
**Target Platform**: Developer workstation (Linux/macOS) with Docker
**Project Type**: Infrastructure / developer-experience
**Performance Goals**: Guard exits in < 2 s; full integration suite continues to run in < 60 s
**Constraints**: Must not break the existing dev compose stack; no changes to application source code
**Scale/Scope**: One guard, one compose file, one Makefile, one env example
---
## Constitution Check
| Principle | Status | Notes |
|-----------|--------|-------|
| §2.5 Database abstraction — no alternative DB in integration tests | ✅ ENFORCED | This feature implements the enforcement |
| §5.1 TDD — failing test before implementation | ✅ | Guard itself is tested by running with a bad URL before adding the guard |
| §5.2 Test pyramid — integration tests use real PostgreSQL | ✅ ENFORCED | docker-compose.test.yml provides the real instance |
| §5.4 CI must pass before task is done | ✅ | Verified by running the full suite via compose |
| §6 Tech stack — asyncpg driver, Docker Compose | ✅ | No new technologies introduced |
| §7.1 One-command local start | ✅ | `docker compose -f docker-compose.test.yml run --rm api-test` |
| §7.2 Environment config via env vars | ✅ | .env.test.example documents all vars |
| §7.3 Linting not optional | ✅ | ruff will run as part of task validation |
No violations.
---
## Project Structure
### Documentation (this feature)
```text
specs/008-postgres-integration-tests/
├── plan.md ← this file
├── research.md ← decisions made above
├── spec.md ← feature specification
└── tasks.md ← generated by /speckit-tasks
```
### Source changes
```text
# New files
docker-compose.test.yml ← isolated test services + api-test runner
.env.test.example ← documents test environment variables
Makefile ← test-unit / test-integration targets
# Modified files
api/tests/integration/conftest.py ← add postgresql+asyncpg:// dialect guard
```
No application source files (`api/app/`) are modified. No UI files are touched.
---
## Detailed Design
### 1. conftest.py — dialect guard
Add a module-level `pytest_configure` hook at the top of `api/tests/integration/conftest.py`. It resolves the database URL (same logic as the `engine` fixture: prefer `TEST_DATABASE_URL`, fall back to `settings.database_url`) and calls `pytest.exit()` if the scheme is not `postgresql+asyncpg`:
```python
def pytest_configure(config):
import os
db_url = os.getenv("TEST_DATABASE_URL") or os.getenv("DATABASE_URL", "")
if not db_url.startswith("postgresql+asyncpg://"):
pytest.exit(
"Integration tests require a PostgreSQL database "
"(postgresql+asyncpg://...). "
"Set TEST_DATABASE_URL or DATABASE_URL accordingly. "
f"Got: {db_url!r}",
returncode=1,
)
```
The hook runs before any fixture or collection, giving an immediate, unambiguous error.
**Note**: This guard goes in `api/tests/integration/conftest.py` only, not in `api/tests/conftest.py`, so that unit tests (which use no database) are unaffected.
### 2. docker-compose.test.yml
```yaml
services:
postgres-test:
image: postgres:16-alpine
environment:
POSTGRES_USER: reactbin
POSTGRES_PASSWORD: reactbin
POSTGRES_DB: reactbin_test
ports:
- "5433:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U reactbin"]
interval: 5s
timeout: 5s
retries: 5
minio-test:
image: minio/minio:latest
command: server /data --console-address ":9001"
environment:
MINIO_ROOT_USER: minioadmin
MINIO_ROOT_PASSWORD: minioadmin
ports:
- "9002:9000"
- "9003:9001"
healthcheck:
test: ["CMD", "mc", "ready", "local"]
interval: 5s
timeout: 5s
retries: 5
minio-init-test:
image: minio/mc:latest
depends_on:
minio-test:
condition: service_healthy
environment:
MINIO_ROOT_USER: minioadmin
MINIO_ROOT_PASSWORD: minioadmin
entrypoint: >
/bin/sh -c "
mc alias set local http://minio-test:9000 $$MINIO_ROOT_USER $$MINIO_ROOT_PASSWORD &&
mc mb --ignore-existing local/reactbin-test
"
api-test:
build:
context: ./api
environment:
TEST_DATABASE_URL: postgresql+asyncpg://reactbin:reactbin@postgres-test:5432/reactbin_test
DATABASE_URL: postgresql+asyncpg://reactbin:reactbin@postgres-test:5432/reactbin_test
S3_ENDPOINT_URL: http://minio-test:9000
S3_BUCKET_NAME: reactbin-test
S3_ACCESS_KEY_ID: minioadmin
S3_SECRET_ACCESS_KEY: minioadmin
S3_REGION: us-east-1
JWT_SECRET_KEY: test-secret-key-for-testing-only
OWNER_USERNAME: testowner
OWNER_PASSWORD: testpassword
API_BASE_URL: http://localhost:8000
MAX_UPLOAD_BYTES: "52428800"
depends_on:
postgres-test:
condition: service_healthy
minio-init-test:
condition: service_completed_successfully
command: ["python", "-m", "pytest", "tests/", "-v"]
working_dir: /app
```
### 3. .env.test.example
Documents the variables needed to run integration tests from the host (with postgres-test and minio-test already running via compose):
```bash
# Integration test environment — used when running pytest directly on the host
# Start test services first: docker compose -f docker-compose.test.yml up -d postgres-test minio-test minio-init-test
TEST_DATABASE_URL=postgresql+asyncpg://reactbin:reactbin@localhost:5433/reactbin_test
DATABASE_URL=postgresql+asyncpg://reactbin:reactbin@localhost:5433/reactbin_test
S3_ENDPOINT_URL=http://localhost:9002
S3_BUCKET_NAME=reactbin-test
S3_ACCESS_KEY_ID=minioadmin
S3_SECRET_ACCESS_KEY=minioadmin
S3_REGION=us-east-1
JWT_SECRET_KEY=test-secret-key-for-testing-only
OWNER_USERNAME=testowner
OWNER_PASSWORD=testpassword
API_BASE_URL=http://localhost:8000
MAX_UPLOAD_BYTES=52428800
```
### 4. Makefile
```makefile
.PHONY: test-unit test-integration
test-unit:
cd api && python -m pytest tests/unit/ -v
test-integration:
docker compose -f docker-compose.test.yml run --rm api-test
```
---
## Phase Breakdown
### Phase 1: Guard (FR-001) — US1
- Write a failing test: run `pytest api/tests/integration/` with `TEST_DATABASE_URL=sqlite+aiosqlite:///test.db` — confirm it does NOT exit early (test that the guard is absent)
- Add `pytest_configure` guard to `api/tests/integration/conftest.py`
- Verify: running with SQLite URL now exits immediately with the correct message
- Verify: running with a PostgreSQL URL proceeds normally
### Phase 2: Docker Compose test stack (FR-002, FR-003) — US2
- Write `docker-compose.test.yml` with `postgres-test`, `minio-test`, `minio-init-test`, `api-test`
- Run `docker compose -f docker-compose.test.yml run --rm api-test` — all tests pass
- Confirm dev stack (port 5432, 9000) is unaffected
### Phase 3: Documentation (FR-004, FR-005) — US3
- Write `.env.test.example`
- Write `Makefile` with `test-unit` and `test-integration`
- Verify `make test-unit` runs unit tests without Docker
- Verify `make test-integration` invokes the compose command
### Phase 4: Polish
- `ruff check api/app/ api/tests/` — zero violations
- `ng lint` is unaffected (no UI changes)
---
## No data model or API contracts
This feature touches only developer tooling. No new API endpoints, database schema changes, or UI components.

View File

@@ -0,0 +1,38 @@
# Quickstart: Integration Test Infrastructure
## Run the full integration test suite (Docker, recommended)
```bash
docker compose -f docker-compose.test.yml run --rm api-test
```
Test services start automatically. The command exits with pytest's return code.
## Run unit tests only (no Docker required)
```bash
make test-unit
# or directly:
cd api && python -m pytest tests/unit/ -v
```
## Run integration tests from the host (test services must be running)
```bash
# Start test services
docker compose -f docker-compose.test.yml up -d postgres-test minio-test minio-init-test
# Copy and source test env vars
cp .env.test.example .env.test
export $(cat .env.test | xargs)
# Run tests
cd api && python -m pytest tests/integration/ -v
```
## Validate the guard works
```bash
TEST_DATABASE_URL=sqlite+aiosqlite:///test.db python -m pytest api/tests/integration/
# Expected: exits immediately with "Integration tests require postgresql+asyncpg://"
```

View File

@@ -0,0 +1,55 @@
# Research: PostgreSQL Integration Test Infrastructure
## Decision 1: How to enforce the PostgreSQL dialect in conftest.py
**Decision**: Add a `pytest_configure` hook (or a module-level guard in `conftest.py`) that calls `pytest.exit()` if the resolved database URL does not start with `postgresql+asyncpg://`.
**Rationale**: `pytest_configure` runs before collection, giving the clearest possible failure signal. A module-level assertion would also work but produces a less readable traceback. `pytest.exit()` with a human-readable message is the idiomatic approach.
**Alternatives considered**:
- A custom pytest plugin in a separate file — unnecessary complexity for a one-liner guard.
- Raising an exception in the `engine` fixture — runs too late (after collection); developers see confusing fixture errors instead of a clear message.
---
## Decision 2: Separate docker-compose.test.yml vs profiles in docker-compose.yml
**Decision**: Use a standalone `docker-compose.test.yml` at the repo root.
**Rationale**: Docker Compose profiles require the developer to remember `--profile test` on every command. A separate file is explicit and self-contained. The test file can define its own service names and ports without touching the dev compose file at all.
**Alternatives considered**:
- `docker-compose.yml` with a `test` profile — profile discovery is non-obvious; modifying the dev file risks breaking the dev stack.
- A `docker-compose.override.yml` — override files apply automatically to `docker compose up`, which is the opposite of what we want for tests.
---
## Decision 3: Port assignments for test services
**Decision**:
- `postgres-test`: host port 5433 (standard offset from dev 5432)
- `minio-test` API: host port 9002 (offset from dev 9000)
- `minio-test` console: host port 9003 (offset from dev 9001)
**Rationale**: Predictable offsets make it easy to remember. Developers running both stacks simultaneously won't hit port conflicts.
---
## Decision 4: S3 isolation strategy for tests
**Decision**: The `api-test` service sets `S3_BUCKET_NAME=reactbin-test` pointing to the dedicated `minio-test` instance. The `minio-init-test` sidecar creates that bucket before tests run.
**Rationale**: The existing conftest already manages database isolation via `create_all` / `drop_all`. MinIO requires bucket pre-creation (same as dev). A dedicated test bucket on a dedicated test MinIO instance gives full isolation. No changes to application storage code are needed.
---
## Decision 5: Makefile vs shell scripts
**Decision**: A `Makefile` at the repo root with `test-unit` and `test-integration` targets.
**Rationale**: `make` is universally available on Linux/macOS developer machines. The targets are short wrappers that document the canonical test invocation. No build logic; just convenience aliases.
**Alternatives considered**:
- Shell scripts (`scripts/test.sh`) — no discoverability; `make help` is more ergonomic.
- `package.json` scripts — wrong tool for a Python/Docker project.
- `justfile` — not universally installed.

View File

@@ -0,0 +1,95 @@
# Feature Specification: PostgreSQL Integration Test Infrastructure
**Feature Branch**: `008-postgres-integration-tests`
**Created**: 2026-05-06
**Status**: Draft
---
## Overview
Integration tests currently permit any SQLAlchemy-compatible database URL, including SQLite. This allowed a real production bug (incorrect `HAVING` without `GROUP BY`) to ship undetected because SQLite's permissive dialect did not reject it. The project constitution (§2.5, §5.2 v1.3.0) now explicitly mandates PostgreSQL for integration tests. This feature enforces that mandate with infrastructure and guardrails.
---
## User Scenarios & Testing
### User Story 1 — Integration tests are enforced to run against PostgreSQL (Priority: P1)
A developer running `pytest` against a non-PostgreSQL database URL receives an immediate, descriptive failure before any test runs.
**Why this priority**: Directly addresses the production bug that prompted this feature. Without this, the constitution mandate has no teeth.
**Independent Test**: Set `TEST_DATABASE_URL=sqlite+aiosqlite:///test.db` and run `pytest api/tests/integration/`. Confirm pytest exits immediately with a message identifying the dialect problem and naming the required scheme.
**Acceptance Scenarios**:
1. **Given** `TEST_DATABASE_URL` is set to a SQLite URL, **When** `pytest api/tests/integration/` is invoked, **Then** pytest exits before collecting any test with an error: `Integration tests require postgresql+asyncpg://`.
2. **Given** `DATABASE_URL` is unset and `TEST_DATABASE_URL` is unset, **When** pytest is invoked, **Then** pytest exits with a clear message about the missing database URL.
3. **Given** `TEST_DATABASE_URL` is a valid `postgresql+asyncpg://` URL, **When** pytest is invoked, **Then** tests collect and run normally.
---
### User Story 2 — One-command integration test run against isolated services (Priority: P1)
A developer can run the entire integration test suite against dedicated, isolated PostgreSQL and MinIO instances with a single command.
**Why this priority**: Without this, the PostgreSQL requirement is mandated but impractical — developers have no easy way to satisfy it.
**Independent Test**: From the repo root with Docker available, run `docker compose -f docker-compose.test.yml run --rm api-test`. Confirm all integration tests pass, test containers start and stop cleanly, and dev database/bucket are untouched.
**Acceptance Scenarios**:
1. **Given** Docker is running and dev services are stopped, **When** the test command is run, **Then** isolated `postgres-test` and `minio-test` services start, all tests run against them, and the command exits with pytest's return code.
2. **Given** dev services are running on their normal ports, **When** the test command is run, **Then** test services use different ports (5433, 9002/9003) and do not interfere with the dev stack.
3. **Given** any test data is written during the run, **When** the test run completes, **Then** all test schema is dropped (conftest teardown is unchanged).
---
### User Story 3 — Test infrastructure is documented (Priority: P2)
A developer new to the project can understand how to run unit tests vs integration tests without reading the source code.
**Independent Test**: Read `.env.test.example` and `Makefile`. Confirm all required environment variables are documented and `make test-unit` / `make test-integration` targets are present.
**Acceptance Scenarios**:
1. **Given** a fresh clone, **When** the developer reads `.env.test.example`, **Then** they see every variable needed to run integration tests outside Docker, with example values.
2. **Given** the Makefile, **When** the developer runs `make test-unit`, **Then** the pytest unit suite runs without requiring Docker.
3. **Given** the Makefile, **When** the developer runs `make test-integration`, **Then** the Docker Compose test command runs.
---
### Edge Cases
- What if `TEST_DATABASE_URL` is set but malformed? — The guard should still catch a non-PostgreSQL scheme; asyncpg will raise its own error for a malformed URL.
- What if Docker is not available? — `make test-integration` fails at the Docker level with Docker's own error; the Makefile does not need to guard for this.
- What if the test PostgreSQL port (5433) is already in use? — Standard Docker port conflict error; no special handling needed.
---
## Requirements
### Functional Requirements
- **FR-001**: `conftest.py` MUST assert the resolved database URL starts with `postgresql+asyncpg://` and call `pytest.exit()` with a descriptive message before any test collects.
- **FR-002**: A `docker-compose.test.yml` MUST define isolated `postgres-test` (port 5433) and `minio-test` (ports 9002/9003) services and an `api-test` runner service.
- **FR-003**: The `api-test` service MUST set `TEST_DATABASE_URL` pointing to `postgres-test` and all S3 env vars pointing to `minio-test`.
- **FR-004**: A `.env.test.example` MUST document all environment variables required to run integration tests outside Docker.
- **FR-005**: A `Makefile` MUST provide `test-unit` and `test-integration` targets.
---
## Success Criteria
- **SC-001**: Running `pytest api/tests/integration/` with a SQLite URL exits in under 2 seconds with a clear error message — no tests run.
- **SC-002**: `docker compose -f docker-compose.test.yml run --rm api-test` completes successfully with all integration tests passing.
- **SC-003**: Dev services (postgres on 5432, minio on 9000) are unaffected when the test command runs.
---
## Assumptions
- Docker Compose v2 (`docker compose`) is available in the developer environment.
- The existing `conftest.py` `engine` fixture (session-scoped `create_all` / `drop_all`) continues to handle schema lifecycle; no per-test transaction rollback mechanism is introduced.
- CI/CD pipeline configuration is out of scope for this feature.

View File

@@ -0,0 +1,113 @@
# Tasks: PostgreSQL Integration Test Infrastructure
**Input**: Design documents from `specs/008-postgres-integration-tests/`
**Prerequisites**: plan.md ✅, spec.md ✅, research.md ✅, quickstart.md ✅
**Tests**: TDD is non-negotiable (§5.1). For infrastructure tasks the "failing test" is a verification step that confirms the thing being built is absent before building it, then confirms it works after. Every user story has an explicit TDD red step before its implementation task.
**Organization**: No foundational blocking phase — all three user stories touch independent files and can proceed in order.
## Format: `[ID] [P?] [Story] Description`
- **[P]**: Can run in parallel with other [P] tasks in the same phase
- **[Story]**: Which user story this task belongs to
- Exact file paths included in every task description
---
## Phase 1: Setup
No new project structure required. The existing layout accommodates all changes.
---
## Phase 2: User Story 1 — Dialect guard in conftest (Priority: P1) 🎯 MVP
**Goal**: `pytest api/tests/integration/` exits immediately with a clear message if the database URL is not `postgresql+asyncpg://`.
**Independent Test**: Run `TEST_DATABASE_URL=sqlite+aiosqlite:///test.db python -m pytest api/tests/integration/ -q` — command exits in < 2 s with the error message `Integration tests require postgresql+asyncpg://` and no tests are collected.
- [X] T001 [US1] Confirm guard is absent (TDD red): from `api/`, run `TEST_DATABASE_URL=sqlite+aiosqlite:///test.db python -m pytest tests/integration/ -q --co 2>&1 | head -20` — observe that tests ARE collected and note the count (guard not yet in place)
- [X] T002 [US1] Add `pytest_configure` hook to `api/tests/integration/conftest.py` — resolve URL via `os.getenv("TEST_DATABASE_URL") or os.getenv("DATABASE_URL", "")`, call `pytest.exit("Integration tests require postgresql+asyncpg://...", returncode=1)` if URL does not start with `postgresql+asyncpg://`; place hook before any imports that depend on the database URL
- [X] T003 [US1] Verify guard works (TDD green): run `TEST_DATABASE_URL=sqlite+aiosqlite:///test.db python -m pytest api/tests/integration/ -q` — confirm immediate exit with the correct error message and zero tests collected; also confirm a valid `postgresql+asyncpg://` URL does not trigger the guard
**Checkpoint**: Dialect-mismatched test runs are blocked before any test collects.
---
## Phase 3: User Story 2 — Docker Compose test stack (Priority: P1)
**Goal**: `docker compose -f docker-compose.test.yml run --rm api-test` runs the full integration suite against isolated PostgreSQL and MinIO services on different ports than the dev stack.
**Independent Test**: Run `docker compose -f docker-compose.test.yml run --rm api-test` from the repo root — all tests pass; verify `docker compose ps` shows dev services (if running) are unaffected on their original ports.
- [X] T004 [US2] Confirm compose file is absent (TDD red): run `test -f docker-compose.test.yml && echo EXISTS || echo ABSENT` — confirm output is `ABSENT`
- [X] T005 [US2] Create `docker-compose.test.yml` at the repo root with four services: `postgres-test` (image `postgres:16-alpine`, host port 5433, db `reactbin_test`), `minio-test` (image `minio/minio:latest`, host ports 9002/9003), `minio-init-test` (creates bucket `reactbin-test`, depends on `minio-test` healthy), and `api-test` (builds from `./api`, runs `python -m pytest tests/ -v`, depends on `postgres-test` healthy and `minio-init-test` completed, environment sets `TEST_DATABASE_URL=postgresql+asyncpg://reactbin:reactbin@postgres-test:5432/reactbin_test`, `DATABASE_URL` to same value, and all S3 vars pointing to `minio-test:9000` with bucket `reactbin-test`) — follow exact design in `specs/008-postgres-integration-tests/plan.md`
- [X] T006 [US2] Verify compose stack (TDD green): run `docker compose -f docker-compose.test.yml run --rm api-test` — confirm all integration tests pass; confirm no errors about missing env vars or connection failures
**Checkpoint**: Full integration suite runs against real PostgreSQL via one command.
---
## Phase 4: User Story 3 — Test documentation (Priority: P2)
**Goal**: `.env.test.example` and `Makefile` document how to run both test tiers.
**Independent Test**: Read `.env.test.example` — all variables needed for integration tests are present with example values. Run `make test-unit` — pytest unit suite runs without Docker and passes.
- [X] T007 [P] [US3] Create `.env.test.example` at the repo root documenting all variables required to run integration tests outside Docker: `TEST_DATABASE_URL`, `DATABASE_URL`, `S3_ENDPOINT_URL`, `S3_BUCKET_NAME`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `S3_REGION`, `JWT_SECRET_KEY`, `OWNER_USERNAME`, `OWNER_PASSWORD`, `API_BASE_URL`, `MAX_UPLOAD_BYTES` — with example values pointing to `localhost:5433` and `localhost:9002` (test service ports); include a comment explaining how to start test services first — follow exact design in `specs/008-postgres-integration-tests/plan.md`
- [X] T008 [P] [US3] Create `Makefile` at the repo root with `.PHONY: test-unit test-integration`, `test-unit` target running `cd api && python -m pytest tests/unit/ -v`, and `test-integration` target running `docker compose -f docker-compose.test.yml run --rm api-test`
- [X] T009 [US3] Verify `make test-unit` — unit tests pass without Docker (validates the Makefile target and confirms unit tests have no Docker dependency)
- [X] T010 Verify `make test-integration` — Docker integration suite passes end-to-end (cross-story verification: exercises the US2 compose stack via the US3 Makefile target)
**Checkpoint**: All three user stories independently functional.
---
## Phase 5: Polish & Cross-Cutting Concerns
- [X] T011 Run `ruff check api/app/ api/tests/` — zero violations (conftest change must pass ruff; fix any issues)
---
## Dependencies & Execution Order
### Phase Dependencies
- **Phase 2 (US1)**: No external dependencies — can start immediately
- **Phase 3 (US2)**: Depends on Phase 2 (guard must be in place so the compose stack run exercises it)
- **Phase 4 (US3)**: T007 and T008 are independent file writes (can run in parallel with each other after Phase 3); T009 requires T008; T010 requires T008 and T006
- **Phase 5 (Polish)**: Depends on all prior phases
### Within Phase 4
- T007 ∥ T008 (different files, no dependency)
- T009 after T008 (Makefile must exist)
- T010 after T008 and T006 (requires both Makefile and compose stack)
### Execution Order Summary
```
Step 1: T001, T002, T003 (sequential — TDD for guard)
Step 2: T004, T005, T006 (sequential — TDD for compose stack)
Step 3 (parallel): T007, T008
Step 4: T009 (after T008), T010 (after T008 + T006)
Step 5: T011
```
---
## Implementation Strategy
### MVP (US1 — the guard)
1. Complete T001T003
2. **Validate**: SQLite URL is blocked; PostgreSQL URL proceeds
3. US2 and US3 add the infrastructure to make the mandate practical
### Incremental Delivery
- After Phase 2: Dialect bugs are caught immediately — core safety net is in place
- After Phase 3: Full integration suite runs against PostgreSQL via one Docker command
- After Phase 4: Both test tiers are documented and accessible via `make`
- After Phase 5: Lint clean, ready for merge

View File

@@ -0,0 +1,34 @@
# Specification Quality Checklist: Login Brute-Force Protection
**Purpose**: Validate specification completeness and quality before proceeding to planning
**Created**: 2026-05-06
**Feature**: [spec.md](../spec.md)
## Content Quality
- [X] No implementation details (languages, frameworks, APIs)
- [X] Focused on user value and business needs
- [X] Written for non-technical stakeholders
- [X] All mandatory sections completed
## Requirement Completeness
- [X] No [NEEDS CLARIFICATION] markers remain
- [X] Requirements are testable and unambiguous
- [X] Success criteria are measurable
- [X] Success criteria are technology-agnostic (no implementation details)
- [X] All acceptance scenarios are defined
- [X] Edge cases are identified
- [X] Scope is clearly bounded
- [X] Dependencies and assumptions identified
## Feature Readiness
- [X] All functional requirements have clear acceptance criteria
- [X] User scenarios cover primary flows
- [X] Feature meets measurable outcomes defined in Success Criteria
- [X] No implementation details leak into specification
## Notes
- All items pass. Spec is ready for `/speckit-plan`.

View File

@@ -0,0 +1,85 @@
# API Contract: Authentication
## POST /api/v1/auth/token
Authenticates the owner and returns a JWT access token.
**This endpoint is modified by feature 009** to enforce brute-force protection.
All previous behaviour is preserved. One new response code (429) is added.
### Request
```
POST /api/v1/auth/token
Content-Type: application/json
```
```json
{
"username": "string",
"password": "string"
}
```
### Responses
#### 200 OK — Credentials accepted
```json
{
"access_token": "<jwt>",
"token_type": "bearer",
"expires_in": 86400
}
```
Side effect: resets the failure counter for the caller's IP address.
---
#### 401 Unauthorized — Credentials rejected
```json
{
"detail": "Invalid credentials",
"code": "invalid_credentials"
}
```
Side effect: increments the failure counter for the caller's IP address. If the
counter reaches `LOGIN_MAX_FAILURES`, subsequent requests from this IP will receive
429 until the cooldown expires.
---
#### 429 Too Many Requests — Source blocked after repeated failures
**This response is new in feature 009.**
```
HTTP/1.1 429 Too Many Requests
Retry-After: 900
Content-Type: application/json
```
```json
{
"detail": "Too many failed login attempts. Please try again later.",
"code": "login_rate_limited"
}
```
The `Retry-After` header value is the configured cooldown duration in seconds (default: 900).
It reflects the maximum possible wait, not the exact remaining lockout time.
No credentials are verified when this response is returned — the request is
rejected before authentication is attempted.
---
### Notes
- The failure counter is per source IP address (TCP peer, not forwarded headers).
- Threshold values (`LOGIN_MAX_FAILURES`, `LOGIN_WINDOW_SECONDS`, `LOGIN_COOLDOWN_SECONDS`)
are not disclosed in any response.
- Counters are in-memory and reset on process restart.

View File

@@ -0,0 +1,53 @@
# Data Model: Login Brute-Force Protection
## Overview
This feature introduces no new database tables. The only data entity is a transient,
in-memory rate-limit record that does not survive process restarts. This is intentional
(see research.md Decision 3).
---
## Entity: Rate-Limit Record (in-memory only)
| Field | Type | Description |
|----------------|---------|-----------------------------------------------------------------------------|
| `failures` | int | Count of consecutive failed login attempts in the current window |
| `window_start` | float | Unix timestamp marking when the current counting window began |
| `blocked_until`| float | Unix timestamp after which the source is no longer blocked; 0.0 if not blocked |
**Keyed by**: resolved client IP address string (e.g., `"192.168.1.1"`); see `get_client_ip()` in `rate_limiter.py` for resolution logic
**Lifecycle**:
1. Record is created on the first failed login from a source.
2. `failures` increments on each subsequent failure within the window.
3. When `failures >= LOGIN_MAX_FAILURES`, `blocked_until` is set to `now + LOGIN_COOLDOWN_SECONDS`.
4. When `blocked_until` has passed, the record is deleted on the next request from that source.
5. A successful login deletes the record immediately (failure counter reset).
6. If `now - window_start > LOGIN_WINDOW_SECONDS` without triggering lockout, the counter resets within the existing record.
**State machine**:
```
[no record]
│ first failure
[tracking] ──── failure N ≥ max ────► [blocked]
│ │
│ success / window expires │ cooldown expires
▼ ▼
[no record] ◄─────────────────────── [no record]
```
---
## Configuration Entity: Rate-Limit Settings
Stored as environment variables; loaded via `app.config.Settings`:
| Env Var | Default | Description |
|----------------------------|---------|----------------------------------------------------------|
| `LOGIN_MAX_FAILURES` | `5` | Failures within window before lockout |
| `LOGIN_WINDOW_SECONDS` | `300` | Rolling window duration in seconds (5 minutes) |
| `LOGIN_COOLDOWN_SECONDS` | `900` | Lockout duration in seconds after threshold exceeded (15 minutes) |
| `LOGIN_TRUSTED_PROXY_IPS` | `""` | Comma-separated IPs/CIDRs of trusted upstream proxies (e.g., `10.0.0.0/8`); empty = disabled |

View File

@@ -0,0 +1,388 @@
# Implementation Plan: Login Brute-Force Protection
**Branch**: `009-login-rate-limiting` | **Date**: 2026-05-06 | **Spec**: [spec.md](spec.md)
**Input**: Feature specification from `specs/009-login-rate-limiting/spec.md`
## Summary
Add failure-counting brute-force protection to the login endpoint (`POST /api/v1/auth/token`).
After a configurable number of consecutive failed attempts from the same resolved client IP,
the endpoint returns HTTP 429 with a `Retry-After` header for a configurable cooldown period.
A successful login resets the counter. All thresholds are configurable via environment variables.
When deployed behind a reverse proxy (nginx, Kubernetes ingress), a `LOGIN_TRUSTED_PROXY_IPS`
setting enables extraction of the real client IP from `X-Forwarded-For`. No new infrastructure
(no Redis, no new DB table) — counters live in process memory.
---
## Technical Context
**Language/Version**: Python 3.12+
**Primary Dependencies**: FastAPI, pydantic-settings (already in use); no new dependencies added
**Storage**: In-memory `dict` (no persistence across restarts — intentional)
**Testing**: pytest + pytest-asyncio (existing test infrastructure)
**Target Platform**: Linux server (Docker)
**Project Type**: Web service (API only — this feature has no UI surface)
**Performance Goals**: Rate limiter adds negligible overhead (dict lookup + lock acquisition; sub-millisecond)
**Constraints**: Must not add new runtime service dependencies; must not change any auth behaviour for non-blocked sources
**Scale/Scope**: Single process, single user; in-memory store is sufficient
---
## Constitution Check
| Principle | Status | Notes |
|-----------|--------|-------|
| §2.4 Auth abstraction (AuthProvider interface) | ✅ Pass | Rate limiter is a guard *before* `JWTAuthProvider.verify_credentials()`, not a bypass of the interface |
| §2.5 DB abstraction (repository layer) | ✅ Pass | No database access; in-memory only |
| §2.6 No speculative abstraction | ✅ Pass | Concrete `LoginRateLimiter` class, no interface; only one implementation planned |
| §3.3 Error envelope (`detail` + `code`) | ✅ Pass | 429 response uses `{"detail": "...", "code": "login_rate_limited"}` |
| §5.1 TDD | ✅ Required | Tasks follow red → green order |
| §5.2 Integration tests against PostgreSQL | ✅ Pass | Integration test for the login endpoint will run against the Docker PostgreSQL stack |
| §7.2 Environment configuration | ✅ Pass | `LOGIN_MAX_FAILURES`, `LOGIN_WINDOW_SECONDS`, `LOGIN_COOLDOWN_SECONDS`, `LOGIN_TRUSTED_PROXY_IPS` from env vars |
| §7.3 Linting (ruff) | ✅ Required | All new files must pass `ruff check` |
**Gate result**: No violations. Cleared to proceed.
---
## Project Structure
### Documentation (this feature)
```text
specs/009-login-rate-limiting/
├── plan.md ← this file
├── research.md ← decisions on approach
├── data-model.md ← rate-limit record entity
├── quickstart.md ← curl runbook
├── contracts/
│ └── auth.md ← updated POST /api/v1/auth/token with 429
└── tasks.md ← generated by /speckit-tasks
```
### Source Code Changes
```text
api/
├── app/
│ ├── auth/
│ │ ├── rate_limiter.py ← NEW: LoginRateLimiter class
│ │ ├── jwt_provider.py (unchanged)
│ │ ├── noop.py (unchanged)
│ │ └── provider.py (unchanged)
│ ├── config.py ← add login_max_failures, login_window_seconds, login_cooldown_seconds, login_trusted_proxy_ips
│ ├── main.py ← init LoginRateLimiter in lifespan, attach to app.state
│ └── routers/
│ └── auth.py ← check rate limit before auth, record outcome
└── tests/
├── unit/
│ └── test_rate_limiter.py ← NEW: unit tests for LoginRateLimiter logic
└── integration/
└── test_login_rate_limit.py ← NEW: integration tests for 429 behaviour via HTTP
```
---
## Implementation Detail
### `api/app/auth/rate_limiter.py`
```python
import ipaddress
import logging
import time
from dataclasses import dataclass, field
from ipaddress import IPv4Network, IPv6Network
from threading import Lock
from starlette.requests import Request
logger = logging.getLogger(__name__)
def get_client_ip(
request: Request,
trusted_networks: list[IPv4Network | IPv6Network],
) -> str:
"""Return the resolved client IP, honouring X-Forwarded-For when the
TCP peer is a trusted upstream proxy. Falls back to the TCP peer address
when no trusted networks are configured or the peer is not in the list."""
peer = request.client.host if request.client else "unknown"
if trusted_networks and peer != "unknown":
try:
peer_addr = ipaddress.ip_address(peer)
if any(peer_addr in net for net in trusted_networks):
xff = request.headers.get("X-Forwarded-For", "").split(",")[0].strip()
if xff:
return xff
real_ip = request.headers.get("X-Real-IP", "").strip()
if real_ip:
return real_ip
except ValueError:
pass
return peer
@dataclass
class _Record:
failures: int = 0
window_start: float = field(default_factory=time.time)
blocked_until: float = 0.0
class LoginRateLimiter:
def __init__(
self,
max_failures: int = 5,
window_seconds: int = 300,
cooldown_seconds: int = 900,
) -> None:
self._max = max_failures
self._window = window_seconds
self._cooldown = cooldown_seconds
self._store: dict[str, _Record] = {}
self._lock = Lock()
@property
def cooldown_seconds(self) -> int:
return self._cooldown
def is_blocked(self, ip: str) -> bool:
now = time.time()
with self._lock:
rec = self._store.get(ip)
if rec is None:
return False
if rec.blocked_until > now:
return True
if rec.blocked_until > 0:
del self._store[ip]
return False
def record_failure(self, ip: str) -> None:
now = time.time()
with self._lock:
rec = self._store.get(ip)
if rec is None:
rec = _Record(window_start=now)
self._store[ip] = rec
if now - rec.window_start > self._window:
rec.failures = 0
rec.window_start = now
rec.failures += 1
if rec.failures >= self._max:
rec.blocked_until = now + self._cooldown
logger.warning(
"Login blocked for %s after %d failures", ip, rec.failures
)
def record_success(self, ip: str) -> None:
with self._lock:
self._store.pop(ip, None)
```
### `api/app/config.py` additions
```python
login_max_failures: int = 5
login_window_seconds: int = 300
login_cooldown_seconds: int = 900
login_trusted_proxy_ips: str = "" # comma-separated IPs/CIDRs; empty = disabled
```
### `api/app/main.py` lifespan update
```python
import ipaddress
from app.auth.rate_limiter import LoginRateLimiter
@asynccontextmanager
async def lifespan(application: FastAPI):
settings = get_settings()
application.state.login_rate_limiter = LoginRateLimiter(
max_failures=settings.login_max_failures,
window_seconds=settings.login_window_seconds,
cooldown_seconds=settings.login_cooldown_seconds,
)
trusted_networks = []
for part in settings.login_trusted_proxy_ips.split(","):
part = part.strip()
if part:
try:
trusted_networks.append(ipaddress.ip_network(part, strict=False))
except ValueError:
pass # invalid entry — skip silently
application.state.login_trusted_networks = trusted_networks
# ... existing DB setup unchanged
engine = get_engine()
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
await engine.dispose()
```
### `api/app/routers/auth.py` update
```python
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from app.auth.jwt_provider import JWTAuthProvider
from app.auth.rate_limiter import LoginRateLimiter, get_client_ip
from app.dependencies import get_jwt_auth
router = APIRouter(tags=["auth"])
class LoginRequest(BaseModel):
username: str
password: str
class TokenResponse(BaseModel):
access_token: str
token_type: str = "bearer"
expires_in: int
@router.post("/auth/token", response_model=TokenResponse)
async def login(
request: Request,
body: LoginRequest,
auth: JWTAuthProvider = Depends(get_jwt_auth),
):
limiter: LoginRateLimiter = request.app.state.login_rate_limiter
ip: str = get_client_ip(request, request.app.state.login_trusted_networks)
if limiter.is_blocked(ip):
return JSONResponse(
status_code=429,
content={
"detail": "Too many failed login attempts. Please try again later.",
"code": "login_rate_limited",
},
headers={"Retry-After": str(limiter.cooldown_seconds)},
)
if not auth.verify_credentials(body.username, body.password):
limiter.record_failure(ip)
raise HTTPException(
status_code=401,
detail={"detail": "Invalid credentials", "code": "invalid_credentials"},
)
limiter.record_success(ip)
token = auth.create_token()
return TokenResponse(
access_token=token,
token_type="bearer",
expires_in=auth._expiry_seconds,
)
```
### `api/tests/unit/test_rate_limiter.py` (representative cases)
```python
import time
import pytest
from app.auth.rate_limiter import LoginRateLimiter
def test_not_blocked_initially():
limiter = LoginRateLimiter(max_failures=3, window_seconds=60, cooldown_seconds=300)
assert limiter.is_blocked("1.2.3.4") is False
def test_blocked_after_threshold():
limiter = LoginRateLimiter(max_failures=3, window_seconds=60, cooldown_seconds=300)
for _ in range(3):
limiter.record_failure("1.2.3.4")
assert limiter.is_blocked("1.2.3.4") is True
def test_success_clears_failures():
limiter = LoginRateLimiter(max_failures=3, window_seconds=60, cooldown_seconds=300)
limiter.record_failure("1.2.3.4")
limiter.record_failure("1.2.3.4")
limiter.record_success("1.2.3.4")
assert limiter.is_blocked("1.2.3.4") is False
def test_ips_are_isolated():
limiter = LoginRateLimiter(max_failures=2, window_seconds=60, cooldown_seconds=300)
limiter.record_failure("1.1.1.1")
limiter.record_failure("1.1.1.1")
assert limiter.is_blocked("2.2.2.2") is False
```
### `api/tests/integration/test_login_rate_limit.py` (representative cases)
```python
import pytest
from httpx import AsyncClient
# Uses the 'client' fixture (NoOpAuthProvider) from conftest — sufficient for this
# endpoint since we're testing the rate-limit layer, not auth correctness.
# The login endpoint instantiates its own limiter via app.state, so we need
# the full ASGI app.
BAD_CREDS = {"username": "attacker", "password": "wrong"}
@pytest.mark.asyncio
async def test_repeated_failures_trigger_429(client: AsyncClient):
# Use a custom limiter with low threshold to avoid slow tests
# (the app.state.login_rate_limiter is set in lifespan; override for test)
from app.auth.rate_limiter import LoginRateLimiter
from app.main import app
original = app.state.login_rate_limiter
app.state.login_rate_limiter = LoginRateLimiter(
max_failures=3, window_seconds=60, cooldown_seconds=30
)
try:
for _ in range(3):
await client.post("/api/v1/auth/token", json=BAD_CREDS)
resp = await client.post("/api/v1/auth/token", json=BAD_CREDS)
assert resp.status_code == 429
assert resp.json()["code"] == "login_rate_limited"
assert "Retry-After" in resp.headers
finally:
app.state.login_rate_limiter = original
```
---
## Implementation Phases
### Phase 1 (MVP — P1): Blocking after repeated failures
1. Add `login_max_failures`, `login_window_seconds`, `login_cooldown_seconds`, `login_trusted_proxy_ips` to `api/app/config.py`
2. Create `api/app/auth/rate_limiter.py` with `LoginRateLimiter` and `get_client_ip()`
3. Initialize rate limiter and parse trusted networks in `api/app/main.py` lifespan; attach both to `app.state`
4. Update `api/app/routers/auth.py` to resolve client IP via `get_client_ip()`, then check + record outcomes
5. Unit tests: `api/tests/unit/test_rate_limiter.py`
6. Integration tests: `api/tests/integration/test_login_rate_limit.py`
### Phase 2 (US2 — observability): Logging and response hints
Delivered as part of Phase 1 (the `logger.warning(...)` call and `Retry-After` header
are embedded in the same implementation). No separate phase needed.
---
## Environment Variables to Add to `.env.example`
```dotenv
# Login brute-force protection
LOGIN_MAX_FAILURES=5
LOGIN_WINDOW_SECONDS=300
LOGIN_COOLDOWN_SECONDS=900
# Comma-separated IPs/CIDRs of trusted upstream proxies (e.g. nginx ingress pod CIDR).
# Leave empty when not behind a reverse proxy.
LOGIN_TRUSTED_PROXY_IPS=
```
These are optional (have defaults) so existing `.env` files without them continue working.

View File

@@ -0,0 +1,112 @@
# Quickstart: Login Brute-Force Protection
## Prerequisites
- API running (via `docker compose up` or locally with `.env` set)
- `curl` available
---
## Scenario 1: Trigger the rate limiter
Send 6 consecutive failed login attempts (default threshold is 5):
```bash
for i in $(seq 1 6); do
echo "Attempt $i:"
curl -s -o /dev/null -w "%{http_code}\n" \
-X POST http://localhost:8000/api/v1/auth/token \
-H "Content-Type: application/json" \
-d '{"username": "wrong", "password": "wrong"}'
done
```
Expected output:
```
Attempt 1: 401
Attempt 2: 401
Attempt 3: 401
Attempt 4: 401
Attempt 5: 401
Attempt 6: 429
```
The 6th attempt returns 429. Inspect the headers:
```bash
curl -i -X POST http://localhost:8000/api/v1/auth/token \
-H "Content-Type: application/json" \
-d '{"username": "wrong", "password": "wrong"}'
```
Expected headers include:
```
HTTP/1.1 429 Too Many Requests
Retry-After: 900
```
Expected body:
```json
{"detail": "Too many failed login attempts. Please try again later.", "code": "login_rate_limited"}
```
---
## Scenario 2: Successful login resets the counter
Make some failed attempts, then log in with valid credentials:
```bash
# Fail twice
for i in 1 2; do
curl -s -o /dev/null -w "fail $i: %{http_code}\n" \
-X POST http://localhost:8000/api/v1/auth/token \
-H "Content-Type: application/json" \
-d '{"username": "wrong", "password": "wrong"}'
done
# Succeed — resets counter
curl -s -o /dev/null -w "success: %{http_code}\n" \
-X POST http://localhost:8000/api/v1/auth/token \
-H "Content-Type: application/json" \
-d '{"username": "'"$OWNER_USERNAME"'", "password": "'"$OWNER_PASSWORD"'"}'
# Now fail 5 more times — counter was reset, so no 429 yet
for i in $(seq 1 5); do
curl -s -o /dev/null -w "fail after reset $i: %{http_code}\n" \
-X POST http://localhost:8000/api/v1/auth/token \
-H "Content-Type: application/json" \
-d '{"username": "wrong", "password": "wrong"}'
done
```
Expected: all "fail after reset" lines return 401 (not 429), confirming the counter was reset.
---
## Scenario 3: Observe log output
While triggering the rate limiter (Scenario 1), watch API logs:
```bash
docker compose logs -f api
```
After the threshold is crossed you should see a line like:
```
WARNING app.auth.rate_limiter:rate_limiter.py:NN Login blocked for 172.18.0.1 after 5 failures
```
---
## Environment variable overrides
To test with a lower threshold without code changes:
```bash
LOGIN_MAX_FAILURES=2 LOGIN_WINDOW_SECONDS=60 LOGIN_COOLDOWN_SECONDS=30 \
uvicorn app.main:app --reload
```
Then only 2 failures trigger the lockout, and it clears after 30 seconds.

View File

@@ -0,0 +1,67 @@
# Research: Login Brute-Force Protection
## Decision 1: Library vs. custom implementation
**Decision**: Custom in-memory failure tracker (no new library dependency)
**Rationale**: The requirement is to count *failed* login attempts specifically and reset on success — not to rate-limit all requests regardless of outcome. Popular libraries like `slowapi` count all requests to a route, which would break FR-004 (reset on success) without significant workarounds. A purpose-built 60-line class is simpler, more auditable, and has no dependency footprint.
**Alternatives considered**:
- `slowapi` (built on `limits`): Counts all requests, not failures. Requires patching the exception handler to decrement on success — fragile and non-obvious.
- `slowapi` with a custom key function: Could be done, but the library's storage model doesn't expose a "reset this key" API in a clean way.
- Redis-backed counter: Overkill for a single-user personal app with one instance. No new infrastructure justified.
---
## Decision 2: Fixed window vs. sliding window
**Decision**: Fixed window with per-source reset on successful login
**Rationale**: Fixed window is simpler to implement correctly and sufficient for this use case. The main attack — rapid sequential guessing — is fully addressed. The known "burst at window boundary" weakness is irrelevant here because: (a) the cooldown period is separate from the counting window, and (b) a successful login resets the counter entirely.
**Alternatives considered**:
- Sliding window: More accurate, but adds complexity (requires storing timestamps of each request). The marginal security benefit doesn't justify the implementation cost for a personal single-user app.
---
## Decision 3: In-memory backing store
**Decision**: Python `dict` keyed by source IP, protected by a threading `Lock`
**Rationale**: The application runs as a single process. In-memory storage means counters reset on restart — this is acceptable and matches the "fail open" assumption in the spec. No new infrastructure (Redis, database table) is required.
**Alternatives considered**:
- Database-backed counters: Persistent across restarts, but adds a DB round-trip to every login request (including successful ones). Not justified.
- Redis: Distributed-safe and persistent, but requires a new service dependency. Out of scope for a personal single-instance app.
---
## Decision 4: Source identifier
**Decision**: `request.client.host` (the TCP peer address)
**Rationale**: The spec explicitly states not to trust `X-Forwarded-For` headers unless the app is known to be behind a trusted proxy. `request.client.host` in Starlette/FastAPI is the actual TCP peer IP — it cannot be spoofed by an attacker sending arbitrary headers.
**Alternatives considered**:
- `X-Forwarded-For` first value: Spoofable if the app is not behind a trusted proxy (attacker can set arbitrary header values).
- `X-Real-IP`: Same spoofing concern.
---
## Decision 5: 429 response and Retry-After header
**Decision**: Return HTTP 429 with `{"detail": "...", "code": "login_rate_limited"}` and a `Retry-After` header set to the configured cooldown duration in seconds
**Rationale**: HTTP 429 is the standard "Too Many Requests" status. The `Retry-After` header is explicitly mentioned in the spec (US2 acceptance scenario) and is required by RFC 6585 for rate-limit responses. Setting it to the *configured* cooldown (not the exact remaining time) satisfies FR-005: it doesn't reveal precise expiry, just the maximum wait. The response body follows §3.3 of the constitution (error envelope with `detail` and `code`).
---
## Decision 6: Default threshold values
**Decision**: `LOGIN_MAX_FAILURES=5`, `LOGIN_WINDOW_SECONDS=300` (5 min), `LOGIN_COOLDOWN_SECONDS=900` (15 min)
**Rationale**: Industry standard for web apps. 5 attempts is enough for legitimate typos but makes brute-force infeasible at human scale. A 5-minute counting window matches typical "I fat-fingered my password" retry patterns. A 15-minute cooldown is a meaningful deterrent without locking out a legitimate owner indefinitely.
**Alternatives considered**:
- 3 failures / 60 s window / 300 s cooldown: More aggressive, but too likely to lock out the legitimate owner on a bad day.
- 10 failures: Too permissive for a brute-force defense.

View File

@@ -0,0 +1,84 @@
# Feature Specification: Login Brute-Force Protection
**Feature Branch**: `009-login-rate-limiting`
**Created**: 2026-05-06
**Status**: Draft
**Input**: User description: "Login API endpoints should be rate limited or otherwise protected against brute force attacks"
## User Scenarios & Testing *(mandatory)*
### User Story 1 - Repeated failed logins are blocked (Priority: P1)
An attacker (or misconfigured client) sending many rapid login attempts with the wrong password is slowed or blocked before they can exhaustively guess credentials. After a threshold number of consecutive failures from the same source, the system refuses further attempts for a cooldown period and returns a clear, non-leaking error.
**Why this priority**: Directly prevents credential-stuffing and brute-force attacks against the sole privileged account. Without this, the owner account is exposed to automated password guessing with no friction.
**Independent Test**: Send more than the allowed number of failed login requests in quick succession and confirm that subsequent attempts are rejected with a rate-limit or lockout response — without knowing or changing the real password.
**Acceptance Scenarios**:
1. **Given** an attacker sends N+1 failed login attempts within the configured window, **When** the (N+1)th request arrives, **Then** the system returns an error response indicating the request is blocked (not the normal "invalid credentials" error) and does not process the login attempt.
2. **Given** a legitimate user has been temporarily blocked after too many failures, **When** the cooldown period elapses and they retry with the correct password, **Then** they are logged in successfully.
3. **Given** a legitimate user makes a few failed attempts and then waits beyond the cooldown window, **When** they retry within the next window, **Then** their failure counter resets and they are not blocked.
---
### User Story 2 - Operators can observe and reason about blocking activity (Priority: P2)
When the protection triggers, the system produces enough observable signal (log entries, response metadata) that an operator can confirm the feature is working, diagnose false positives, and tune thresholds — without exposing sensitive details to the client.
**Why this priority**: Invisible security controls are unmanageable. Operators need to know the system is doing what it claims, and blocked legitimate users need a clear (but not exploitable) explanation.
**Independent Test**: Trigger the rate limiter and confirm that: (a) the response body or headers communicate that the request was blocked and when the client may retry; (b) the server logs an entry identifying the blocked source and the reason.
**Acceptance Scenarios**:
1. **Given** a source is blocked, **When** they receive the rejection response, **Then** the response indicates they should wait before retrying (e.g., a `Retry-After` hint) without disclosing the exact threshold values.
2. **Given** the rate limiter fires, **When** an operator inspects server logs, **Then** there is a log entry at WARNING level or above recording the blocked source and timestamp.
---
### Edge Cases
- What happens when a distributed attacker rotates IPs to avoid per-IP limits?
- How does the system behave if the backing store for rate-limit counters is temporarily unavailable — does it fail open (allow all) or fail closed (block all)?
- Are IPv6 addresses and IPv4-mapped-IPv6 addresses treated consistently?
- Does a successful login reset the failure counter for that source?
- What happens if many legitimate users share a NAT/proxy IP (e.g., corporate network)?
- What if `TRUSTED_PROXY_IPS` is configured to include an IP that an external attacker controls? (An attacker could then spoof `X-Forwarded-For` and rotate fake source IPs to bypass the rate limiter — operators must only list genuinely trusted upstream infrastructure.)
## Requirements *(mandatory)*
### Functional Requirements
- **FR-001**: The system MUST enforce a maximum number of failed login attempts per source identifier (the resolved client IP address) within a rolling time window before blocking further attempts.
- **FR-002**: Once a source exceeds the failure threshold, the system MUST reject subsequent login requests for a configurable cooldown period, returning a distinct response (not the normal invalid-credentials response).
- **FR-003**: After the cooldown period expires, the system MUST permit the source to attempt login again, resetting its failure count.
- **FR-004**: A successful login MUST reset the failure counter for that source, preventing accumulation of old failures from blocking future legitimate access.
- **FR-005**: The rejection response MUST NOT reveal the specific threshold values or remaining lockout duration in a way that aids an attacker in timing their attempts, but MUST provide enough information (e.g., "try again later") for a legitimate user to understand the situation.
- **FR-006**: The system MUST log a structured warning event whenever a source is blocked, including the source identifier and timestamp.
- **FR-007**: Rate-limit thresholds (maximum attempts, window duration, cooldown duration) MUST be configurable without code changes.
- **FR-008**: The system MUST support a configurable list of trusted upstream proxy IP addresses and CIDR ranges. When the TCP peer address matches a trusted proxy, the resolved client IP MUST be extracted from the `X-Forwarded-For` request header (first entry) or, if absent, `X-Real-IP`. When no trusted proxies are configured, the TCP peer address MUST be used directly and forwarded-IP headers MUST be ignored.
### Key Entities
- **Rate-limit record**: Tracks the number of consecutive failures and the window start time for a given source identifier; expires automatically after the cooldown period.
- **Source identifier**: The resolved client IP address used to key rate-limit records. When `LOGIN_TRUSTED_PROXY_IPS` is empty (default), this is the TCP peer address. When one or more proxy IPs/CIDRs are configured and the TCP peer matches, the first `X-Forwarded-For` entry (or `X-Real-IP`) is used instead.
## Success Criteria *(mandatory)*
### Measurable Outcomes
- **SC-001**: An automated script sending 100 consecutive failed login requests completes with at least 90 of those requests rejected after the threshold is crossed — verified in a controlled test environment.
- **SC-002**: A legitimate user who has been temporarily blocked can successfully log in within 5 minutes of the cooldown period expiring without any manual intervention.
- **SC-003**: Zero information about threshold values or exact lockout expiry is present in blocked response bodies or headers.
- **SC-004**: Every blocking event produces a corresponding log entry; 100% of triggered blocking events are observable in logs during testing.
## Assumptions
- The application has a single login endpoint used by all clients (the owner login introduced in feature 004).
- Source identification uses the resolved client IP address. By default (when `LOGIN_TRUSTED_PROXY_IPS` is empty) this is the TCP peer address. When one or more proxy IPs/CIDRs are configured, the first entry of `X-Forwarded-For` (or `X-Real-IP`) is used instead — but only when the TCP peer is in the trusted list, preventing header spoofing by external clients.
- If the rate-limit backing store is unavailable, the system fails open (allows the attempt through) rather than blocking all logins — this preserves the owner's access, which is critical for a single-user admin application.
- No CAPTCHA or multi-factor step is in scope; protection is purely count/time-based.
- The feature targets the login endpoint only; other endpoints are out of scope.
- The single-user nature of the app means IP-based identification is sufficient — there is no need for per-username lockout, and using IP (rather than username) avoids contributing to username enumeration risk.

View File

@@ -0,0 +1,120 @@
# Tasks: Login Brute-Force Protection
**Input**: Design documents from `specs/009-login-rate-limiting/`
**Prerequisites**: plan.md ✅, spec.md ✅, research.md ✅, data-model.md ✅, contracts/auth.md ✅, quickstart.md ✅
**Tests**: TDD is non-negotiable (§5.1). Every test task appears before the implementation task it covers. For each red step, run the test and confirm it fails before proceeding to the implementation.
**Organization**: Phase 1 adds env vars; Phase 2 adds config fields (shared by both stories); Phase 3 implements the core blocking behaviour (US1 MVP); Phase 4 adds observability-specific test coverage (US2); Phase 5 is polish.
## Format: `[ID] [P?] [Story] Description`
- **[P]**: Can run in parallel with other [P] tasks in the same phase
- **[Story]**: Which user story this task belongs to
- Exact file paths included in every task description
---
## Phase 1: Setup
- [X] T001 Add a `# Login brute-force protection` comment block with `LOGIN_MAX_FAILURES=5`, `LOGIN_WINDOW_SECONDS=300`, `LOGIN_COOLDOWN_SECONDS=900`, and `LOGIN_TRUSTED_PROXY_IPS=` (empty by default, with an inline comment explaining it accepts comma-separated IPs/CIDRs) to both `.env.example` and `.env.test.example` at the repo root
---
## Phase 2: Foundational
**Purpose**: Add the three new settings fields — required before any story implementation.
- [X] T002 Add `login_max_failures: int = 5`, `login_window_seconds: int = 300`, `login_cooldown_seconds: int = 900`, `login_trusted_proxy_ips: str = ""` to the `Settings` class in `api/app/config.py` (append after `owner_password`)
**Checkpoint**: `api/app/config.py` accepts all three new env vars with defaults.
---
## Phase 3: User Story 1 — Repeated failed logins are blocked (Priority: P1) 🎯 MVP
**Goal**: After `LOGIN_MAX_FAILURES` consecutive failed login attempts from the same source IP within `LOGIN_WINDOW_SECONDS`, `POST /api/v1/auth/token` returns HTTP 429 for `LOGIN_COOLDOWN_SECONDS`. A successful login resets the counter.
**Independent Test**: `cd api && python -m pytest tests/unit/test_rate_limiter.py tests/integration/test_login_rate_limit.py::test_repeated_failures_trigger_429 tests/integration/test_login_rate_limit.py::test_success_resets_counter tests/integration/test_login_rate_limit.py::test_429_has_retry_after_header tests/integration/test_login_rate_limit.py::test_xff_header_ignored_when_no_trusted_networks -v` — all pass.
### Tests for User Story 1 (TDD red — write first, confirm failure before T005)
- [X] T003 [P] [US1] Create `api/tests/unit/test_rate_limiter.py` with ten failing unit tests — import `LoginRateLimiter` and `get_client_ip` from `app.auth.rate_limiter`; for `LoginRateLimiter` (instantiate with `max_failures=3, window_seconds=60, cooldown_seconds=300`): `test_not_blocked_initially`, `test_blocked_after_threshold`, `test_success_clears_failures`, `test_ips_are_isolated`, `test_window_resets_after_expiry`, `test_log_warning_on_lockout` (caplog at WARNING level: call `record_failure()` until threshold, assert `"Login blocked" in caplog.text` and IP in log output); for `get_client_ip` (construct a mock using `from unittest.mock import MagicMock` and `from starlette.requests import Request`: `req = MagicMock(spec=Request); req.client.host = "10.0.0.1"; req.headers = {"X-Forwarded-For": "203.0.113.5"}`): `test_get_client_ip_no_trusted_networks_returns_peer` (empty `trusted_networks=[]` → returns `req.client.host`), `test_get_client_ip_trusted_peer_uses_xff` (peer `"10.0.0.1"` in trusted CIDR `"10.0.0.0/8"` → returns `"203.0.113.5"`), `test_get_client_ip_untrusted_peer_ignores_xff` (peer `"8.8.8.8"` not in trusted CIDR `"10.0.0.0/8"` → returns `"8.8.8.8"` despite XFF), `test_get_client_ip_trusted_peer_falls_back_to_real_ip` (peer trusted, no XFF header, `X-Real-IP: "203.0.113.9"` → returns `"203.0.113.9"`); run `python -m pytest tests/unit/test_rate_limiter.py -v` and confirm `ImportError` or `ModuleNotFoundError` (red)
- [X] T004 [P] [US1] Create `api/tests/integration/test_login_rate_limit.py` with four failing integration tests; each must override both `app.state.login_rate_limiter` (fresh `LoginRateLimiter(max_failures=3, window_seconds=60, cooldown_seconds=30)`) and `app.state.login_trusted_networks` (set to `[]` for all four tests — the `ASGITransport` peer is `"testclient"`, not a valid IP, so trusted-network matching can't be exercised here; proxy extraction is fully covered by T003 unit tests) via try/finally: (1) `test_repeated_failures_trigger_429` — POST three bad-credential requests then assert fourth returns 429 with `resp.json()["code"] == "login_rate_limited"`; (2) `test_success_resets_counter` — two failures → one valid login using `{"username": os.environ["OWNER_USERNAME"], "password": os.environ["OWNER_PASSWORD"]}` (matching conftest.py defaults: `testowner`/`testpassword`) → three more failures → assert all three return 401, not 429; (3) `test_429_has_retry_after_header` — trigger lockout (three failures), then assert `"Retry-After" in resp.headers` and `int(resp.headers["Retry-After"]) > 0`; (4) `test_xff_header_ignored_when_no_trusted_networks` — send three bad-cred requests with `headers={"X-Forwarded-For": "1.2.3.4"}` then a fourth with `headers={"X-Forwarded-For": "9.9.9.9"}` — assert the fourth returns 429 (not 401), proving the limiter tracked the real peer `"testclient"` for all requests and XFF was ignored; run `python -m pytest tests/integration/test_login_rate_limit.py -v` and confirm failure (red)
### Implementation for User Story 1
- [X] T005 [US1] Create `api/app/auth/rate_limiter.py` with two exports: (1) `get_client_ip(request: Request, trusted_networks: list[IPv4Network | IPv6Network]) -> str` — imports `ipaddress`, `from ipaddress import IPv4Network, IPv6Network`, `from starlette.requests import Request`; extracts `peer = request.client.host if request.client else "unknown"`; if `trusted_networks` is non-empty and peer is parseable as an IP address and falls within any trusted network, returns first `X-Forwarded-For` entry (strip whitespace) or `X-Real-IP` value, otherwise returns `peer`; wraps `ipaddress.ip_address(peer)` in `try/except ValueError` and falls back to `peer` on error; (2) `LoginRateLimiter` class: `__init__(self, max_failures: int = 5, window_seconds: int = 300, cooldown_seconds: int = 900)` storing params as `_max`, `_window`, `_cooldown`; `_store: dict[str, _Record]` and `_lock: threading.Lock`; `@dataclass _Record` with `failures: int = 0`, `window_start: float = field(default_factory=time.time)`, `blocked_until: float = 0.0`; `is_blocked(ip: str) -> bool`, `record_failure(ip: str) -> None` (logs WARNING on lockout), `record_success(ip: str) -> None`, `cooldown_seconds` property; stdlib imports: `import ipaddress, logging, time`, `from dataclasses import dataclass, field`, `from threading import Lock`
- [X] T006 [US1] Update `api/app/main.py` lifespan: add `import ipaddress` at top; import `LoginRateLimiter` from `app.auth.rate_limiter`; inside `lifespan` before `engine = get_engine()`, consolidate to `settings = get_settings()` (remove the existing bare `get_settings()` call), then set `application.state.login_rate_limiter = LoginRateLimiter(max_failures=settings.login_max_failures, window_seconds=settings.login_window_seconds, cooldown_seconds=settings.login_cooldown_seconds)`; then parse `settings.login_trusted_proxy_ips` — split on `","`, strip each part, skip empty strings, call `ipaddress.ip_network(part, strict=False)` inside a `try/except ValueError` (skip invalid entries silently), collect results into `trusted_networks: list`; set `application.state.login_trusted_networks = trusted_networks`
- [X] T007 [US1] Update `api/app/routers/auth.py` login endpoint: add `Request` to FastAPI imports and add `from fastapi.responses import JSONResponse`; add `from app.auth.rate_limiter import LoginRateLimiter, get_client_ip`; add `request: Request` as first parameter to `login()`; extract `limiter: LoginRateLimiter = request.app.state.login_rate_limiter` and `ip: str = get_client_ip(request, request.app.state.login_trusted_networks)`; add guard block — if `limiter.is_blocked(ip)`: return `JSONResponse(status_code=429, content={"detail": "Too many failed login attempts. Please try again later.", "code": "login_rate_limited"}, headers={"Retry-After": str(limiter.cooldown_seconds)})`; after `verify_credentials` returns False: call `limiter.record_failure(ip)` before the existing `HTTPException`; after `auth.create_token()`: call `limiter.record_success(ip)` before returning `TokenResponse`
- [X] T008 [US1] Verify TDD green: run `cd api && python -m pytest tests/unit/test_rate_limiter.py -v` — all 10 pass; run `make test-integration` — all tests pass including `test_repeated_failures_trigger_429`, `test_success_resets_counter`, `test_429_has_retry_after_header`, and `test_xff_header_ignored_when_no_trusted_networks`
**Checkpoint**: Brute-force blocking is live. Automated repeated failures are stopped after threshold; the owner can still log in after cooldown; unit and integration tests pass.
---
## Phase 4: User Story 2 — Operators can observe blocking activity (Priority: P2)
**Goal**: The 429 response includes a `Retry-After` header with a positive integer; the response body `code` is `"login_rate_limited"` and contains no threshold numeric values; server logs a WARNING when blocking triggers.
**Independent Test**: Trigger the rate limiter (already works from Phase 3) and assert `Retry-After` header is present in the response and `code` field is `"login_rate_limited"`.
### Tests for User Story 2 (TDD red — extend existing file)
- [X] T009 [US2] Add one test to `api/tests/integration/test_login_rate_limit.py` targeting observability properties not yet covered: `test_429_body_shape` — override `app.state.login_rate_limiter` with a fresh `LoginRateLimiter(max_failures=3, window_seconds=60, cooldown_seconds=30)` via try/finally (same isolation pattern as T004), trigger lockout (three failures), then assert `resp.json() == {"detail": "Too many failed login attempts. Please try again later.", "code": "login_rate_limited"}` (exact match — confirms no threshold values leak and shape is correct); confirm this test is green immediately against the US1 implementation (T007 already returns this exact body)
**Checkpoint**: US2 observability properties are explicitly exercised by integration tests; a future regression in the Retry-After header or code field will be caught.
---
## Phase 5: Polish & Cross-Cutting Concerns
- [X] T010 Run `cd api && ruff check app/auth/rate_limiter.py app/routers/auth.py app/config.py app/main.py tests/unit/test_rate_limiter.py tests/integration/test_login_rate_limit.py` — fix any violations
---
## Dependencies & Execution Order
### Phase Dependencies
- **Phase 1 (Setup)**: No external dependencies — can start immediately
- **Phase 2 (Foundational)**: No external dependencies — can start immediately (parallel with Phase 1)
- **Phase 3 (US1)**: Depends on Phase 2 (T002 must exist before T006 can use `settings.login_max_failures`)
- **Phase 4 (US2)**: Depends on Phase 3 (tests verify behaviour implemented in T007)
- **Phase 5 (Polish)**: Depends on all prior phases
### Within Phase 3
- T003 ∥ T004 (different files, no dependency — write tests in parallel)
- T005 after T003, T004 (implement after tests confirm they fail)
- T006 ∥ T007 after T005 (both import from `rate_limiter.py`; write to different files — `main.py` and `auth.py`; T006 sets `app.state.login_trusted_networks` which T007's router reads)
- T008 after T005, T006, T007 (verify all pass)
### Execution Order Summary
```
Step 1: T001 ∥ T002 (setup + foundational — parallel, different files)
Step 2: T003 ∥ T004 (write failing tests — parallel)
Step 3: T005 (implement LoginRateLimiter — after red tests confirmed)
Step 4: T006 ∥ T007 (wire limiter into app — parallel, different files)
Step 5: T008 (verify green)
Step 6: T009 (US2 observability tests — verify green immediately)
Step 7: T010 (ruff clean)
```
---
## Implementation Strategy
### MVP (US1 — the blocker)
1. Complete T001T002 (config setup)
2. Complete T003T008 (core blocking)
3. **Validate**: Run `make test-integration` — all 88 existing tests still pass; 2 new rate-limit tests pass
4. US2 adds verification coverage for already-implemented observability features
### Incremental Delivery
- After Phase 3: Brute-force attacks on the login endpoint are blocked — core security net is in place
- After Phase 4: Observability properties are explicitly tested — regressions in headers/logs will be caught
- After Phase 5: Lint clean, ready for merge

4
ui/.prettierignore Normal file
View File

@@ -0,0 +1,4 @@
dist/
node_modules/
coverage/
package-lock.json

View File

@@ -4,6 +4,9 @@ const tseslint = require("typescript-eslint");
const angular = require("angular-eslint");
module.exports = tseslint.config(
{
ignores: ["dist/", "node_modules/", "coverage/", "*.min.js"],
},
{
files: ["**/*.ts"],
extends: [

16734
ui/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,25 +1,95 @@
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { provideRouter } from '@angular/router';
import { provideRouter, Router } from '@angular/router';
import { routes } from './app.routes';
import { AuthService } from './auth/auth.service';
describe('AppComponent', () => {
let authSpy: jasmine.SpyObj<AuthService>;
beforeEach(async () => {
authSpy = jasmine.createSpyObj('AuthService', ['isAuthenticated', 'logout']);
await TestBed.configureTestingModule({
imports: [AppComponent],
providers: [provideRouter(routes)],
providers: [
provideRouter(routes),
{ provide: AuthService, useValue: authSpy },
],
}).compileComponents();
});
it('should create the app', () => {
authSpy.isAuthenticated.and.returnValue(false);
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
expect(fixture.componentInstance).toBeTruthy();
});
it('should have title reactbin-ui', () => {
authSpy.isAuthenticated.and.returnValue(false);
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('reactbin-ui');
expect(fixture.componentInstance.title).toEqual('reactbin-ui');
});
it('header is present when authenticated', () => {
authSpy.isAuthenticated.and.returnValue(true);
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const header = (fixture.nativeElement as HTMLElement).querySelector('header.app-header');
expect(header).not.toBeNull();
});
it('header is present when not authenticated', () => {
authSpy.isAuthenticated.and.returnValue(false);
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const header = (fixture.nativeElement as HTMLElement).querySelector('header.app-header');
expect(header).not.toBeNull();
});
it('sign-out button is visible when authenticated', () => {
authSpy.isAuthenticated.and.returnValue(true);
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const btn = (fixture.nativeElement as HTMLElement).querySelector('.logout-btn');
expect(btn).not.toBeNull();
});
it('sign-out button is absent when not authenticated', () => {
authSpy.isAuthenticated.and.returnValue(false);
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const btn = (fixture.nativeElement as HTMLElement).querySelector('.logout-btn');
expect(btn).toBeNull();
});
it('onLogout calls auth.logout and navigates to / (grid)', () => {
authSpy.isAuthenticated.and.returnValue(true);
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const router = TestBed.inject(Router);
spyOn(router, 'navigate');
fixture.componentInstance.onLogout();
expect(authSpy.logout).toHaveBeenCalled();
expect(router.navigate).toHaveBeenCalledWith(['/']);
});
it('header app-name is a link to /', () => {
authSpy.isAuthenticated.and.returnValue(false);
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const link = (fixture.nativeElement as HTMLElement).querySelector('a.app-name') as HTMLAnchorElement;
expect(link).not.toBeNull();
expect(link.getAttribute('href')).toBe('/');
});
it('header height is 48px', () => {
authSpy.isAuthenticated.and.returnValue(true);
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const header = (fixture.nativeElement as HTMLElement).querySelector('header.app-header') as HTMLElement;
// The CSS declares height: 48px; we verify the class is applied correctly via the element presence
// (actual computed styles require a real browser/DOM environment)
expect(header.classList.contains('app-header')).toBeTrue();
});
});

View File

@@ -1,12 +1,51 @@
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { CommonModule } from '@angular/common';
import { Router, RouterLink, RouterOutlet } from '@angular/router';
import { AuthService } from './auth/auth.service';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
template: `<router-outlet />`,
imports: [CommonModule, RouterLink, RouterOutlet],
template: `
<header class="app-header">
<a routerLink="/" class="app-name">Reactbin</a>
<button *ngIf="auth.isAuthenticated()" class="logout-btn" (click)="onLogout()">Sign out</button>
</header>
<router-outlet />
`,
styles: [`
:host { display: block; }
.app-header {
height: 48px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 20px;
background: var(--surface);
border-bottom: 1px solid var(--border);
}
.app-name { font-weight: 600; font-size: 1rem; color: var(--text); letter-spacing: 0.02em; text-decoration: none; }
.logout-btn {
background: none;
border: 1px solid var(--border);
color: var(--text-muted);
padding: 4px 12px;
border-radius: var(--radius);
cursor: pointer;
font-size: 0.85rem;
transition: border-color var(--transition), color var(--transition);
}
.logout-btn:hover { border-color: var(--border-focus); color: var(--text); }
`],
})
export class AppComponent {
title = 'reactbin-ui';
constructor(public auth: AuthService, private router: Router) {}
onLogout(): void {
this.auth.logout();
this.router.navigate(['/']);
}
}

View File

@@ -1,13 +1,14 @@
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { routes } from './app.routes';
import { authInterceptor } from './auth/auth.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideHttpClient(),
provideHttpClient(withInterceptors([authInterceptor])),
],
};

View File

@@ -1,4 +1,5 @@
import { Routes } from '@angular/router';
import { authGuard } from './auth/auth.guard';
export const routes: Routes = [
{
@@ -6,11 +7,22 @@ export const routes: Routes = [
loadComponent: () =>
import('./library/library.component').then((m) => m.LibraryComponent),
},
{
path: 'login',
loadComponent: () =>
import('./login/login.component').then((m) => m.LoginComponent),
},
{
path: 'upload',
canActivate: [authGuard],
loadComponent: () =>
import('./upload/upload.component').then((m) => m.UploadComponent),
},
{
path: 'tags',
loadComponent: () =>
import('./tags/tags.component').then((m) => m.TagsComponent),
},
{
path: 'images/:id',
loadComponent: () =>

View File

@@ -0,0 +1,31 @@
import { TestBed } from '@angular/core/testing';
import { provideRouter, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { provideLocationMocks } from '@angular/common/testing';
import { authGuard } from './auth.guard';
import { AuthService } from './auth.service';
describe('authGuard', () => {
let authService: jasmine.SpyObj<AuthService>;
beforeEach(() => {
authService = jasmine.createSpyObj('AuthService', ['isAuthenticated']);
TestBed.configureTestingModule({
providers: [
provideRouter([]),
provideLocationMocks(),
{ provide: AuthService, useValue: authService },
],
});
});
it('redirects to login when not authenticated', () => {
authService.isAuthenticated.and.returnValue(false);
const route = {} as ActivatedRouteSnapshot;
const state = { url: '/upload' } as RouterStateSnapshot;
const result = TestBed.runInInjectionContext(() => authGuard(route, state));
expect(result).toBeTruthy();
const urlTree = result as ReturnType<Router['createUrlTree']>;
expect(urlTree.toString()).toContain('/login');
});
});

View File

@@ -0,0 +1,12 @@
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = (_route, state) => {
const auth = inject(AuthService);
const router = inject(Router);
if (auth.isAuthenticated()) {
return true;
}
return router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });
};

View File

@@ -0,0 +1,58 @@
import { TestBed } from '@angular/core/testing';
import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { Router } from '@angular/router';
import { authInterceptor } from './auth.interceptor';
import { AuthService } from './auth.service';
describe('authInterceptor', () => {
let http: HttpClient;
let httpMock: HttpTestingController;
let authService: jasmine.SpyObj<AuthService>;
let router: jasmine.SpyObj<Router>;
beforeEach(() => {
authService = jasmine.createSpyObj('AuthService', ['getToken', 'logout']);
router = jasmine.createSpyObj('Router', ['navigate']);
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([authInterceptor])),
provideHttpClientTesting(),
{ provide: AuthService, useValue: authService },
{ provide: Router, useValue: router },
],
});
http = TestBed.inject(HttpClient);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => httpMock.verify());
it('adds Authorization header when authenticated', () => {
authService.getToken.and.returnValue('test-token');
http.get('/api/v1/images').subscribe();
const req = httpMock.expectOne('/api/v1/images');
expect(req.request.headers.get('Authorization')).toBe('Bearer test-token');
req.flush([]);
});
it('does not add Authorization header when not authenticated', () => {
authService.getToken.and.returnValue(null);
http.get('/api/v1/images').subscribe();
const req = httpMock.expectOne('/api/v1/images');
expect(req.request.headers.has('Authorization')).toBeFalse();
req.flush([]);
});
it('redirects to login on 401 response', () => {
authService.getToken.and.returnValue('test-token');
// eslint-disable-next-line @typescript-eslint/no-empty-function
http.get('/api/v1/images').subscribe({ error: () => {} });
const req = httpMock.expectOne('/api/v1/images');
req.flush('Unauthorized', { status: 401, statusText: 'Unauthorized' });
expect(authService.logout).toHaveBeenCalled();
expect(router.navigate).toHaveBeenCalledWith(['/login']);
});
});

View File

@@ -0,0 +1,23 @@
import { inject } from '@angular/core';
import { HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import { catchError, throwError } from 'rxjs';
import { AuthService } from './auth.service';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const auth = inject(AuthService);
const router = inject(Router);
const token = auth.getToken();
if (token) {
req = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
}
return next(req).pipe(
catchError((err) => {
if (err instanceof HttpErrorResponse && err.status === 401) {
auth.logout();
router.navigate(['/login']);
}
return throwError(() => err);
}),
);
};

Some files were not shown because too many files have changed in this diff Show More