Skip to content

System Architecture

Canonical architecture narrative for FastAPI RBAC. AI harness files and agent guides should link here instead of duplicating this content.

Related:

High-level architecture

┌───────────────────┐      ┌───────────────────┐      ┌───────────────────┐
│  React Frontend   │◄────►│  FastAPI Backend  │◄────►│  PostgreSQL       │
└───────────────────┘      └─────────┬─────────┘      └───────────────────┘
                                     │
                                     ▼
                           ┌───────────────────┐
                           │  Redis            │
                           │  (token allowlist │
                           │   + Celery broker)│
                           └───────────────────┘

The project is a user-management microservice: authentication and authorization for other services.

Layer Stack
Backend FastAPI, SQLAlchemy/SQLModel, Redis, Celery
Frontend React, TypeScript, Redux Toolkit, ShadCN UI
Data PostgreSQL (persistent), Redis (sessions / cache / broker)

Backend layers

API layer

  • Route handlers: backend/app/api/v1/endpoints/
  • Shared dependencies: backend/app/api/deps.py
  • Request/response validation: Pydantic schemas in backend/app/schemas/
  • Versioned under /api/v1

Persistence and domain

  • Models: backend/app/models/ (SQLModel)
  • CRUD: backend/app/crud/
  • Migrations: backend/alembic/
  • Resource-specific deps: backend/app/deps/

Security and infrastructure

  • JWT + password helpers: backend/app/core/security.py (PyJWT)
  • Settings: backend/app/core/config.py
  • Session lifecycle (open, refresh, accept, end): backend/app/utils/sessions.py
  • Redis session allowlist storage, imported only by the session module: backend/app/utils/allowlist.py
  • Celery: backend/app/celery_app.py, workers, beat schedule

Frontend layers

  • Feature modules: react-frontend/src/features/ (auth, users, roles, permissions, …)
  • Shared UI: react-frontend/src/components/ (auth, layout, ShadCN ui/)
  • API clients: react-frontend/src/services/
  • Redux store: react-frontend/src/store/
  • Types: react-frontend/src/models/
  • Hooks: react-frontend/src/hooks/ (useAuth, usePermissions, …)

See Frontend — React architecture for patterns.

Key directory layout

High-level trees only. Prefer the repo (or graphify) over copying leaf-level trees into harness files.

Backend

backend/
├── alembic/                 # Migrations
├── app/
│   ├── api/                 # deps + v1 endpoints
│   ├── core/                # config, security, celery config
│   ├── crud/                # DB operations
│   ├── db/                  # session, init
│   ├── deps/                # resource dependencies
│   ├── models/              # SQLModel entities
│   ├── schemas/             # Pydantic API schemas
│   ├── utils/               # token allowlist, email, audit, …
│   ├── main.py              # FastAPI entry
│   └── …                    # celery, email templates, startup
└── test/                    # unit + integration suite

Frontend

react-frontend/
├── src/
│   ├── components/          # auth, layout, ui
│   ├── features/            # domain feature modules
│   ├── hooks/
│   ├── lib/
│   ├── models/              # TypeScript interfaces
│   ├── pages/
│   ├── services/            # Axios API layer
│   └── store/               # Redux Toolkit
├── package.json
└── vite.config.ts

Domain model

Core RBAC terms (see domain docs): user, role, permission, role group, permission group.

Concept Backend model Notes
User user_model.py Credentials, profile, lockout / verification fields; roles via UserRole
Role role_model.py Named roles; permissions via RolePermission; optional role group
Permission permission_model.py Granular actions (user.create, …); belongs to a permission group
Role group role_group_model.py Hierarchical grouping via RoleGroupMap
Permission group permission_group_model.py Logical grouping of permissions
Password history password_history_model.py Reuse prevention / audit
Audit log audit_log_model.py Security / activity events

Mapping tables: UserRole, RolePermission, RoleGroupMap.

Deleting a user is decided per reference, not by a blanket cascade: password history goes with the user, assigned roles are refused with 409, audit actor_id is kept without a foreign key, and created_by_id on RBAC artifacts is set null. See ADR 0013.

Frontend mirrors these in react-frontend/src/models/ (user.ts, role.ts, permission.ts, roleGroup.ts, auth.ts, …).

Authentication flow

Session invalidation uses a Redis allowlist (user:{id}:{token_type} sorted sets in app/utils/allowlist.py, scored by each member's expiry), not a JWT jti blacklist. Live membership ignores expired entries. Every route that opens, refreshes, checks or ends a session goes through app/utils/sessions.py; no handler or dependency mints a token or touches the allowlist itself. A login that would exceed CONCURRENT_SESSION_LIMIT evicts the oldest session (a refresh token plus the access tokens derived from it, or the lone access token of an OAuth2 form login, which counts as a session too); a limit of 0 or less disables that cap. See ADR 0001, ADR 0006, and ADR 0011. To watch these flows run across the browser, API, Redis and Postgres, open the session lifecycle explainer.

  1. Login — POST /api/v1/auth/login validates credentials, returns the access token in JSON, sets the refresh token as an HttpOnly cookie, and records both on the Redis allowlist. Every failure that does not prove the password (unknown address, wrong password, locked account) gets one 422 body and the same response-time floor; see ADR 0015.
  2. Authenticated requests — client sends Authorization: Bearer <access_token> (and cookies via credentials); backend verifies signature/expiry and that the token remains allowlisted.
  3. Refresh — on 401, frontend calls POST /api/v1/auth/new_access_token with CSRF; backend reads the HttpOnly refresh cookie (optional JSON body fallback for non-browser clients), validates the allowlist, and returns a new access token. Failed refresh → logout. When VALIDATE_TOKEN_IP is on, the presenting client address is also compared with the one the session was established from, at IPv4 /24 or IPv6 /64: a different network revokes that one session and emits a refresh_origin_network_mismatch security event, answering with the ordinary refresh failure. Access tokens are never checked this way and the user's other sessions survive. (Refresh rotation is not implemented; see session-security follow-ups.)
  4. Logout — POST /api/v1/auth/logout ends the calling session (that refresh token and the access tokens that share its session id) and clears the refresh cookie; other sessions on the account stay usable. Session identity comes from the refresh cookie when present, otherwise from the access token's allowlist metadata. POST /api/v1/auth/logout/all revokes every session. The first-party SPA posts POST /logout from Sign out and POST /logout/all from Sign out everywhere (after confirmation), both in the header user menu. Frontend clears the in-memory access token and session hint.

Temporary password — admin create and admin set mark the user needs_to_change_password. Login still succeeds, but get_current_user then refuses every route with 403 password_change_required, superusers included, except the four that opt in with allow_pending_password_change=True: change password, logout, logout all and GET /users/me. The check reads the user row, not a token claim. The SPA sends a flagged user to /change-password-required. See ADR 0014. An expired password restricts the same way: it expires REQUIRE_PASSWORD_CHANGE_DAYS (default 90, 0 or less turns expiry off) after last_changed_password_date, computed on read with no stored column, and user responses report needs_to_change_password as true for it. See ADR 0016.

Pending accounts — a registration whose email is never verified leaves a pending user row. Celery Beat sweeps those hourly (app.worker.cleanup_unverified_users_task → app/utils/unverified_cleanup.py), deleting active, non-superuser, unverified rows created longer ago than UNVERIFIED_ACCOUNT_CLEANUP_HOURS (default 72). The delete repeats the predicate, so a user who verifies while the sweep runs is kept. The sweep reads its work from the database rather than holding a timer, so a worker restart costs one tick rather than every pending row. Beat and the workers both boot from app.celery_app, which imports the task and schedule modules; see ADR 0009.

Frontend storage strategy:

  • Access token: memory (Redux) only
  • Refresh token: HttpOnly cookie (not readable by JavaScript)

Security architecture (summary)

  • JWT access/refresh with Redis allowlist invalidation
  • bcrypt passwords, history, lockout
  • RBAC via roles and permissions on protected routes
  • CSRF, rate limiting, input sanitization, security headers
  • Client address resolved once at the edge (app/utils/client_address.py), from forwarded headers only when the peer is a TRUSTED_PROXIES member — rate limiting, security events and origin-network detection all read that one answer (ADR 0011 decision 8)

Details: Security Features. Deep session analysis lives under docs/SESSION_SECURITY_*.md (historical / design notes; prefer this page + ADR for current behavior).

Deployment sketch

Docker Compose for local and environment-scoped production layouts; Alembic for schema; Celery workers for email and background work. See Deployment.