A production-oriented, full-stack Role-Based Access Control (RBAC) platform built with a Rust (Edition 2024 / rustc 1.100.0) + Actix Web 4 + MongoDB REST API backend and a React 19 (JavaScript ES6+) + React Router 7 + Mantine 9 + Vite 8 administration frontend.
The repository contains two independently structured projects communicating exclusively over a versioned JSON REST API (/api/v1) with short-lived EdDSA (Ed25519) JWT access tokens and rotating refresh tokens—delivered by default via HttpOnly cookies protected by double-submit CSRF validation for browsers, with an opt-in transport-bound JSON-body flow (X-Auth-Transport: body) for non-browser, desktop, and allowlisted WebView clients.
┌──────────────────────────────┐ HTTPS / JSON + Bearer JWT ┌────────────────────────────────────┐
│ React 19 + Mantine 9 UI │ ──────────────────────────────────────► │ Rust / Actix Web 4 REST API │
│ - In-memory Access Token │ + HttpOnly Refresh Cookie │ - RequestId & Security Headers │
│ - Axios Refresh Queue │ + X-CSRF-Token Header │ - Rate Limiting & Strict CORS │
│ - Auth & Permission Context │ ◄────────────────────────────────────── │ - JwtAuthMiddleware │
└──────────────────────────────┘ │ - RequirePermission Guards │
│ - Controllers → Services → Repos │
└──────────────────┬─────────────────┘
│ Official MongoDB Driver 3
▼
┌────────────────────────────────────┐
│ MongoDB (Replica Set rs0) │
│ - users, roles, permissions, │
│ organisations, refresh_tokens, │
│ audit_logs │
└────────────────────────────────────┘
- Controllers (
web/controller/*.rs): Thin HTTP adapters; extract DTOs/params, attach cookies, call services, and formatApiResponse. Never access MongoDB or embed business logic. - DTOs (
web/dto/*.rs): Strict separation between MongoDB BSON DAOs and API request/response contracts (#[serde(deny_unknown_fields)]blocks mass assignment; password hashes are never serialized). - Services (
services/*.rs): Business rules, DTO validation, defense-in-depth permission & privilege-escalation checks, structuredtracing+ persistent MongoDB audit logging (auth_backend::audit), permission-filtered dashboard analytics & aggregations, cache invalidation, and session revocation. - Repositories & DAOs (
repository/*/*_repository.rs,repository/*/dao/*.rs): Trait-based MongoDB persistence with explicit indexes, transaction support, and BSON data access objects. - Module Convention: Modern Rust 2024 directory modules — zero
mod.rsfiles exist anywhere in the project. - Safety Lints & Release Optimization:
unsafe_code = "forbid",clippy::{unwrap_used, expect_used, panic} = "deny", and an optimized[profile.release](opt-level = 3,lto = "fat",codegen-units = 1,strip = "symbols",panic = "abort").
- Pure JavaScript (ES6+) with React 19, React Router 7 (lazy-loaded route & layout chunks with
RouteFallbackandRouteErrorBoundary), Mantine UI 9, Vite 8, Yarn Berry (yarn@4.19.0), and Axios — no TypeScript and no TanStack packages. - Secure Token Lifecycle: Access tokens live exclusively in JS memory (never
localStorage), refresh tokens live inHttpOnlycookies, concurrent401responses coalesce into a single/api/v1/auth/refreshrequest, and open browser tabs coordinate token refresh & logout vianavigator.locks+BroadcastChannelto prevent multi-tab refresh-token reuse races. - RBAC UX & Security Dashboard: Navigation links, lazy-loaded routes, Organisations (
/organisations), Audit Logs (/audit-logs), profile Account Access Summary, self-service Personal & Organisation account registration, and the interactive Dashboard (KPI cards, 7-day stacked SVG security/audit activity chart, user status donut chart, top organisations, role & permission distribution bars, dismissible 24h token-reuse alert banner, recent audit feed, and quick navigation—with RBAC role/permission summaries gated toroles.read/permissions.read) are strictly guarded by user permissions both server-side and client-side; logging out clears route history state so a subsequent user never inherits a restricted redirect. - UX, Resilience & Accessibility: Automatic OS color scheme detection (
defaultColorScheme="auto") with manual toggle, offline/timeout/gateway/non-JSON API error handling (api.js+nginx.conf/api/503JSON fallback), semantic<main>landmarks across all routes, meta description, andpublic/robots.txt.
.
├── .github/
│ └── workflows/
│ ├── backend-ci.yml
│ ├── frontend-ci.yml
│ └── docker-publish.yml
├── deploy/
│ ├── README.md
│ ├── swarm-stack.yml
│ └── portainer.env.example
├── docker-compose.yml
├── mongo/
│ └── mongod.dev.conf
├── docs/
│ └── DEPLOYMENT.md
├── backend/
│ ├── README.md
│ ├── Cargo.toml
│ ├── Cargo.lock
│ ├── Dockerfile
│ ├── .dockerignore
│ ├── .env.example
│ ├── config/default.toml
│ ├── migrations/README.md
│ ├── src/
│ │ ├── main.rs, lib.rs, app.rs, routes.rs, openapi.rs
│ │ ├── config.rs + config/settings.rs
│ │ ├── common.rs + common/{errors,responses,pagination,validation}.rs
│ │ ├── database.rs + database/{mongodb,seed}.rs
│ │ ├── security.rs + security/{keys,password,jwt,csrf}.rs
│ │ ├── middleware.rs + middleware/{authentication,authorization,csrf,rate_limit,request_id}.rs
│ │ ├── web.rs
│ │ ├── web/controller.rs + web/controller/{audit,auth,users,roles,permissions,organisations,profile,dashboard,health}.rs
│ │ ├── web/dto.rs + web/dto/{audit,auth,users,roles,permissions,organisations,profile,dashboard,health}.rs
│ │ ├── services.rs + services/{audit,auth,users,roles,permissions,organisations,profile,dashboard}.rs
│ │ ├── repository.rs
│ │ ├── repository/user.rs + repository/user/{user_repository.rs, dao.rs, dao/user.rs}
│ │ ├── repository/role.rs + repository/role/{role_repository.rs, dao.rs, dao/role.rs}
│ │ ├── repository/permission.rs + repository/permission/{permission_repository.rs, dao.rs, dao/permission.rs}
│ │ ├── repository/organisation.rs + repository/organisation/{organisation_repository.rs, dao.rs, dao/organisation.rs}
│ │ ├── repository/auth.rs + repository/auth/{refresh_token_repository.rs, dao.rs, dao/refresh_token.rs}
│ │ ├── repository/audit.rs + repository/audit/{audit_log_repository.rs, dao.rs, dao/audit_log.rs}
│ │ └── test_support.rs
│ └── tests/
│ ├── audit_log_tests.rs
│ ├── auth_tests.rs
│ ├── dashboard_tests.rs
│ ├── organisation_tests.rs
│ ├── profile_tests.rs
│ ├── user_tests.rs
│ ├── role_tests.rs
│ ├── permission_tests.rs
│ └── mongodb_integration_tests.rs
└── frontend/
├── README.md
├── package.json
├── yarn.lock
├── .yarnrc.yml
├── .yarn/releases/yarn-4.19.0.cjs
├── .gitignore
├── Dockerfile
├── .dockerignore
├── nginx.conf
├── security-headers.inc
├── vite.config.js
├── postcss.config.cjs
├── eslint.config.js
├── .prettierrc
├── .env.example
├── public/robots.txt
└── src/
├── main.jsx, App.jsx, theme.js
├── config/api.js
├── contexts/{contextInstances.js,AuthContext.jsx,PermissionContext.jsx}
├── hooks/{useAuth,usePermissions}.js
├── services/{api,auditService,authService,userService,roleService,permissionService,organisationService,profileService,dashboardService}.js
├── components/{common,navigation,forms}/
├── layouts/{AuthLayout,DashboardLayout}.jsx
├── routes/{AppRoutes,ProtectedRoute}.jsx
├── features/{audit,auth,dashboard,organisations,profile,users,roles,permissions}/
├── utils/{cookies,errors,formatters,pagination,redirects}.js
└── test/
See backend/README.md and frontend/README.md for subproject-specific guides.
| Collection | Key Fields | Indexes |
|---|---|---|
users |
_id, first_name, last_name, email, password_hash, status, email_verified, roles: [ObjectId], token_version, failed_login_attempts, locked_until, profile, created_at, updated_at, last_login_at |
Unique email (email_unique), status (status_idx), roles (roles_idx), (roles, status) (roles_status_idx), created_at (created_at_desc) |
roles |
_id, name, description, permissions: [ObjectId], is_system, created_at, updated_at |
Unique name (role_name_unique), permissions (permissions_idx), is_system (is_system_idx) |
permissions |
_id, name (resource.action), resource, action, description, is_system, created_at, updated_at |
Unique name (permission_name_unique), compound unique (resource, action) (resource_action_unique), is_system (perm_is_system_idx) |
organisations |
_id, name, members: [{ user_id, role, status, joined_at }], version, created_at, updated_at |
Case-insensitive unique name (org_name_unique, en strength-2 collation), multikey members.user_id (org_members_user_id_idx), created_at (org_created_at_desc), updated_at (org_updated_at_desc) |
refresh_tokens |
_id, user_id, token_hash (SHA-256), family_id, transport (cookie|body), csrf_token_hash, token_version, expires_at, revoked_at, replaced_by_hash, user_agent, ip_address, created_at |
Unique token_hash (token_hash_unique), user_id (user_id_idx), family_id (family_id_idx), (family_id, revoked_at) (family_revoked_at_idx), TTL on expires_at (expires_at_ttl), TTL on revoked_at (revoked_at_ttl) |
revoked_access_tokens |
_id, jti, expires_at, revoked_at |
Unique jti (jti_unique), TTL on expires_at (revoked_jti_expires_at_ttl, retained past JWT leeway + 5s) |
audit_logs |
_id, action, resource_type, resource_id, resource_name, actor_id, actor_email, summary, details, created_at |
created_at (audit_created_at_desc), (created_at, _id) (audit_created_at_id_desc), TTL on created_at (audit_created_at_ttl, configurable via AUDIT_LOG_RETENTION_DAYS), (actor_email, created_at) (audit_actor_email_created_at), (action, created_at) (audit_action_created_at), (resource_type, created_at) (audit_resource_type_created_at), (actor_id, created_at) (audit_actor_id_created_at) |
- Relationships: Users reference multiple
rolesbyObjectId; roles reference multiplepermissionsbyObjectId; organisations embedmembers({ user_id, role, status, joined_at }with org-scoped rolesowner/admin/memberand statusesactive/invited/suspended). A single user can belong to multiple organisations simultaneously. Effective platform permissions are computed dynamically as the union of permissions across all assigned roles. - Seeded System Roles:
Super Administrator,Administrator,Moderator,User. - Seeded System Permissions:
users.{read,create,update,delete,assign_roles,manage_self_roles},roles.{read,create,update,delete},permissions.{read,create,update,delete},organisations.{read,create,update,delete,manage_members},audit_logs.read,profile.{read,update,delete}(newly-introduced system permissions are automatically backfilled onto existing system roles on startup).
See backend/migrations/README.md for indexing and replica-set transaction details.
- Password Security, Memory Zeroization & Account Lockout: Argon2id (
argon2 0.6,Algorithm::Argon2id,V0x13, 19 MiB, 2 iterations) executed off the Actix event loop viatokio::task::spawn_blockingwith configurable concurrency capping (ARGON2_MAX_CONCURRENCY) andzeroizememory wiping for passwords, private key PEM buffers, and bootstrap credentials. Unknown-email logins execute a dummy Argon2id verification propagating overload status (503 AUTH_OVERLOADED) identically to prevent timing- and load-based user enumeration. Consecutive failed logins trigger temporary per-account lockout (AUTH_MAX_FAILED_LOGIN_ATTEMPTS/AUTH_ACCOUNT_LOCKOUT_SECONDS, returning an anti-enumeration401 INVALID_CREDENTIALSand recordingauth.account_locked), and post-Argon2id updates (loginlast_login_atandchange_password) use atomic MongoDB$set/$incfilters onstatus: "active"so concurrent admin disables or role revocations can never be overwritten. - Access JWTs & Immediate Revocation: Asymmetric EdDSA (Ed25519) signed tokens (
jsonwebtoken 12,ed25519-dalek 3, default 15m TTL, with a startup keypair sign+verify self-check) validating signature,iss,aud,exp,nbf,token_type == "access",tv(usertoken_version, incremented immediately upon role changes, email changes, account deactivation, password changes, orPOST /api/v1/auth/logout-all), and a TTL-indexedrevoked_access_tokensjtidenylist populated on single-sessionPOST /api/v1/auth/logout(retained pastJWT_LEEWAY_SECONDS + 5s). Token revocation (tvandjti) is verified before account status so revoked JWTs always receive401 SESSION_REVOKEDrather than leaking account status. Permissions are never trusted blindly from JWT claims; they are resolved via a bounded, generation-trackedPermissionCacheexplicitly invalidated immediately upon any user role, role permission, or permission mutation. - Refresh Token Rotation, Reuse Detection & Dual Transport: Opaque 32-byte random tokens stored as SHA-256 hashes in MongoDB and bound to the user's
token_versionso concurrentlogout-all, password changes, or role updates immediately reject stale refresh tokens (401 SESSION_REVOKED). By default, tokens are transmitted viaHttpOnly; SameSite=Laxcookies (Securein production) with session-bound double-submit CSRF protection andOriginallowlist checks on cookie/login,/register,/refresh, and/logout. Non-browser clients (desktop, CLI, mobile, or allowlisted WebView apps) can opt into JSON-body refresh tokens by sendingX-Auth-Transport: bodyon/api/v1/auth/loginor/api/v1/auth/registerand passing{ "refresh_token": "..." }to/api/v1/auth/refreshand/api/v1/auth/logout. Each refresh token family is strictly transport-bound (cookievsbody) so cookie sessions can never be downgraded into JS-readable JSON responses, ambiguous cookie+body requests are rejected (400), web SPA origins (FRONTEND_URL/ALLOWED_ORIGINS) are blocked from body transport (403), and WebView JS origins can be explicitly allowlisted viaALLOWED_BODY_TOKEN_ORIGINS. Each refresh atomically rotates the token within afamily_id(using MongoDB transactions on replica sets, withWriteConflict/TransientTransactionErrorhandled cleanly as concurrent reuse) and prunes older revoked tokens in that family to at most 5 recent entries so repeated page reloads cannot grow the collection unboundedly. Presenting an already-rotated token to/auth/refreshor/auth/logouttriggers reuse detection, revoking the entire token family and bumpingtoken_versionimmediately (and the frontend coordinates multi-tab refreshes, login/register broadcasts, late-401 token reuse, and logout sync vianavigator.locks+BroadcastChannelto prevent benign cross-tab races). Revoked tokens are automatically purged by MongoDB'srevoked_atTTL index (REVOKED_TOKEN_RETENTION_SECONDS, default3600seconds;0drops the index), expired tokens are purged via theexpires_atTTL index, and normal logout or account/user deletion hard-deletes session tokens immediately. - Session-Bound CSRF Protection: Double-submit cookie pattern (
csrf_tokencookie +X-CSRF-Tokenheader verified in constant time viasubtle) bound server-side via SHA-256csrf_token_hashon each cookieRefreshTokenrecord to defeat subdomain cookie-tossing fixation attacks, alongsideOriginandSec-Fetch-Site(cross-site/same-site) validation. - Privilege Escalation Defenses (enforced in both HTTP middleware and services):
- Registration strictly assigns only the
Userrole, rejects unexpected fields (#[serde(deny_unknown_fields)]), and whenREQUIRE_EMAIL_VERIFICATION=truewithholds tokens/cookies and rejectsorganisation_name(400 ORGANISATION_REQUIRES_VERIFIED_ACCOUNT) until the account is verified. - Self-service email changes (
PUT /api/v1/profile) requirecurrent_passwordverification, clear verification status (transitioning topending_verificationwhenREQUIRE_EMAIL_VERIFICATION=true, while protecting the last activeSuper Administrator), and immediately revoke all existing sessions; profile updates apply field-granular patches (preserving omittedprofilesubfields while explicitnullor empty values clear them). Admin email changes resetemail_verified(transitioning topending_verificationwhenREQUIRE_EMAIL_VERIFICATION=trueand not explicitly re-verified) and revoke the target's active sessions. Non-Super-Administrators cannot change or self-verify their own email viaPUT /api/v1/users/{id}. - Users cannot modify their own account status, delete themselves via administration endpoints, or modify their own roles unless explicitly holding
users.manage_self_roles. Self-service profile mutations (PUT /api/v1/profile), account deletion (DELETE /api/v1/profile, requiringprofile.delete), and password change (PATCH /api/v1/profile/password) are protected by a dedicated sensitive-profile rate limiter, require current password confirmation for email/password/deletion, revoke all sessions, and protect the last activeSuper Administrator. - Non-Super-Administrators cannot assign
Super Administratoror any role containing permissions they do not personally hold, cannot edit, disable, delete, or change roles of any user account that holds permissions they do not personally hold (e.g., aModeratorcannot modify or disable anAdministrator), cannot rename a custom permission'sresourceoraction, and cannot delete a custom role whose single-roleUserfallback contains permissions they do not hold. - The last active
Super Administratorcannot be disabled, locked, demoted, or deleted. - Protected system roles and system permissions cannot be deleted or renamed, non-Super-Administrators cannot edit protected
is_systemroles, and creating custom roles with lookalike system role names is blocked.
- Registration strictly assigns only the
- Organisation Isolation & User Data Minimization:
- Users can belong to multiple organisations simultaneously with independent org-scoped roles (
owner,admin,member) and statuses (active,invited,suspended), capped at 500 members per organisation. Organisation updates and deletions use optimistic concurrency (versionfield) to prevent lost updates and stale deletes. - Any authenticated user can create a new organisation (
POST /api/v1/organisations, becoming its activeowner, capped at 10 self-service owned organisations and unable to omit themselves or attach arbitraryinitial_member_ids/initial_owner_email). Platform admins creating an organisation withinclude_creator: falsecan delegate ownership viainitial_owner_email(orinitial_member_ids) to an active user account, ensuring every organisation starts with at least one active owner. - Organisation owners/admins can invite active users strictly by their signup email address (protected by a dedicated organisation-invite rate limiter, never by raw
user_id, capped at 100 pending invitations per organisation, with non-active target accounts returning the same404 USER_NOT_FOUNDso account status is never leaked), cancel pending invitations, remove members, and rename or delete their own organisation (owner only), while remaining strictly isolated from all other organisations (403 Forbidden). - Self-service organisation invitations start in
invitedstatus and require the user to explicitly accept (POST /api/v1/organisations/{id}/accept) before becomingactive(declining viaPOST /api/v1/organisations/{id}/leaverecords a distinctorganisation.invitation_declinedaudit event). Self-service managers cannot promote non-active (invited/suspended) members toowner, cannot change the status of a pending invitation (preventing both direct activation andInvited -> Suspended -> Activebypasses) or revert active members back toinvited, and personal names (first_name/last_name) remain redacted whileinvitedfor callers without globalusers.read. Callers holding onlyorganisations.read(withoutusers.readand not managing the organisation) receive membership roles/statuses/counts without personal emails or names. - Organisations never receive access to user profiles (
phone,bio,job_title,department), global RBAC roles/permissions, login timestamps, or memberships in other organisations. Regular orgmembers cannot view other members' rosters, and the last activeowneris protected (409 LAST_ORG_OWNER_PROTECTED) across role changes, removals, leaving, and account deletion (while solo organisations with no other active members are automatically deleted via version-guardeddelete_if_versiononly when their active owner's account is deleted, preventing empty/ownerless orphan organisations).
- Users can belong to multiple organisations simultaneously with independent org-scoped roles (
Interactive OpenAPI 3.1 Swagger UI (utoipa 6 + vendored utoipa-swagger-ui 10) is enabled by default in development and disabled by default in production (ENABLE_SWAGGER_UI):
GET /swagger-ui/GET /api/v1/openapi.json
GET /health— Liveness probe (200 OK)GET /health/ready— Readiness probe (verifies MongoDB connectivity; returns200 OKor503 Service Unavailable)
| Method | Endpoint | Auth / Permission | Description |
|---|---|---|---|
POST |
/api/v1/auth/register |
Public | Register a personal User account (or an Organisation account when organisation_name is provided and REQUIRE_EMAIL_VERIFICATION=false). Optional X-Auth-Transport: body header returns refresh_token in JSON instead of setting cookies |
POST |
/api/v1/auth/login |
Public | Authenticate & issue access JWT + refresh cookie (or JSON refresh_token with X-Auth-Transport: body) |
POST |
/api/v1/auth/refresh |
Refresh cookie + CSRF, or JSON { "refresh_token" } |
Rotate refresh token & issue new access JWT (strictly bound to original transport) |
POST |
/api/v1/auth/logout |
Refresh cookie + CSRF, or JSON { "refresh_token" } (plus optional Bearer JWT) |
Delete token family, revoke presented access JWT jti immediately, and clear cookies in cookie mode |
POST |
/api/v1/auth/logout-all |
Bearer JWT | Revoke all refresh tokens across every device, bump token_version, and clear auth cookies |
GET |
/api/v1/auth/me |
Bearer JWT | Get authenticated user & effective permissions |
| Method | Endpoint | Required Permission |
|---|---|---|
GET |
/api/v1/dashboard/stats |
Authenticated (strictly filtered per permission: users.read, organisations.read, roles.read, permissions.read, audit_logs.read; always includes caller's own my_active_sessions and my_organisations) |
GET / PUT / DELETE |
/api/v1/profile |
profile.read / profile.update / profile.delete |
PATCH |
/api/v1/profile/password |
profile.update |
GET / POST |
/api/v1/users |
users.read / users.create |
GET / PUT / DELETE |
/api/v1/users/{id} |
users.read / users.update / users.delete |
PATCH |
/api/v1/users/{id}/status |
users.update |
GET / PUT |
/api/v1/users/{id}/roles |
users.read / users.assign_roles |
GET |
/api/v1/users/{id}/permissions |
users.read |
GET |
/api/v1/users/{id}/organisations |
users.read + organisations.read |
GET |
/api/v1/organisations/me |
Authenticated (caller's own organisation memberships & pending invitations) |
GET / POST |
/api/v1/organisations |
organisations.read (GET) / Authenticated (POST — self-service users become active owner, capped at 10 owned orgs) |
GET / PUT / DELETE |
/api/v1/organisations/{id} |
organisations.read or org owner/admin (GET) / organisations.update or org owner (PUT) / organisations.delete or org owner (DELETE) |
POST |
/api/v1/organisations/{id}/members |
organisations.manage_members or org owner/admin (self-service invites by signup email only) |
PATCH / DELETE |
/api/v1/organisations/{id}/members/{user_id} |
organisations.manage_members or org owner/admin |
POST |
/api/v1/organisations/{id}/accept |
Authenticated (accept pending invitation to organisation) |
POST |
/api/v1/organisations/{id}/leave |
Authenticated (decline invitation or leave organisation) |
GET / POST |
/api/v1/roles |
roles.read / roles.create |
GET / PUT / DELETE |
/api/v1/roles/{id} |
roles.read / roles.update / roles.delete |
GET / PUT |
/api/v1/roles/{id}/permissions |
roles.read / roles.update |
GET |
/api/v1/roles/{id}/users |
roles.read + users.read |
GET / POST |
/api/v1/permissions |
permissions.read / permissions.create |
GET / PUT / DELETE |
/api/v1/permissions/{id} |
permissions.read / permissions.update / permissions.delete |
GET |
/api/v1/permissions/{id}/roles |
permissions.read + roles.read |
GET |
/api/v1/audit-logs |
audit_logs.read |
GET |
/api/v1/audit-logs/{id} |
audit_logs.read |
POST /api/v1/auth/login HTTP/1.1
Content-Type: application/json
{
"email": "admin@example.com",
"password": "ChangeMe123!"
}{
"success": true,
"data": {
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJFZERTQSJ9...",
"token_type": "Bearer",
"expires_in": 900,
"expires_at": "2026-11-21T09:15:00Z",
"csrf_token": "r4nd0m_csrf_value",
"user": {
"id": "67401a...",
"first_name": "System",
"last_name": "Administrator",
"email": "admin@example.com",
"status": "active",
"roles": [{ "id": "67401a...", "name": "Super Administrator", "is_system": true }]
},
"permissions": ["permissions.create", "permissions.read", "roles.read", "users.read"]
},
"message": "Signed in successfully"
}Non-browser clients (native desktop apps, CLIs, mobile apps) and allowlisted WebView apps (e.g., Tauri, Electron, Capacitor) can opt into JSON-body refresh tokens without cookies or CSRF headers:
- Sign In: Send
X-Auth-Transport: bodyonPOST /api/v1/auth/login(or/register). The response includesaccess_token,refresh_token,refresh_expires_in, andrefresh_expires_at, omitscsrf_token, and sets no cookies. - Store Securely: Persist
refresh_tokenin the OS credential manager / keychain (never plaintext config files orlocalStorage). - Refresh: Send
POST /api/v1/auth/refreshwithContent-Type: application/jsonand{"refresh_token": "<token>"}(serialize concurrent refreshes in the client so rotated tokens are never replayed). - Logout: Send
POST /api/v1/auth/logoutwithContent-Type: application/jsonand{"refresh_token": "<token>"}. - WebView JS Origins: If calling from a WebView JS context (e.g.,
tauri://localhost,http://tauri.localhost,capacitor://localhost), add the WebView origin(s) toALLOWED_BODY_TOKEN_ORIGINS. Web browser origins inFRONTEND_URL/ALLOWED_ORIGINSremain restricted toHttpOnlycookie sessions.
POST /api/v1/auth/login HTTP/1.1
Content-Type: application/json
X-Auth-Transport: body
{
"email": "admin@example.com",
"password": "ChangeMe123!"
}POST /api/v1/auth/refresh HTTP/1.1
Content-Type: application/json
{
"refresh_token": "<opaque_refresh_token>"
}Error response example (403 Forbidden):
{
"success": false,
"error": {
"code": "INSUFFICIENT_PERMISSIONS",
"message": "You do not have permission to perform this operation"
}
}Copy backend/.env.example to backend/.env and frontend/.env.example to frontend/.env.
| Variable | Default (config/default.toml) |
Description |
|---|---|---|
APP_ENV |
development |
development or production (production requires PEM keys & COOKIE_SECURE=true) |
SERVER_HOST / SERVER_PORT |
127.0.0.1 / 8080 |
Bind host and port |
MONGODB_URI / MONGODB_URI_FILE |
mongodb://localhost:27017 |
MongoDB connection URI (standalone, replica set, or Atlas mongodb+srv://; supports Docker Secret _FILE path) |
MONGODB_DATABASE |
user_management |
Configurable target MongoDB database name (override via .env, docker-compose.yml, or Portainer stack env) |
MONGODB_MAX_POOL_SIZE / MONGODB_MIN_POOL_SIZE |
50 / 5 |
MongoDB driver connection pool bounds |
JWT_ISSUER / JWT_AUDIENCE |
user-management-api / user-management-client |
JWT iss and aud validation claims |
JWT_ACCESS_TOKEN_TTL / JWT_REFRESH_TOKEN_TTL |
900 / 604800 |
Token lifetimes in seconds (15 min / 7 days) |
REVOKED_TOKEN_RETENTION_SECONDS |
3600 |
MongoDB TTL retention in seconds for revoked refresh tokens (1 hour; 0 drops/disables revoked_at_ttl; max 2147483647); rotation also prunes to at most 5 revoked tokens per session family |
JWT_PRIVATE_KEY_PATH / JWT_PUBLIC_KEY_PATH |
(empty in dev) | Ed25519 PKCS#8/SPKI PEM key paths (both required together; mandatory in production; sign+verify checked at startup) |
FRONTEND_URL / ALLOWED_ORIGINS |
http://localhost:5173 |
Explicit CORS origin allowlist for the web UI (setting FRONTEND_URL replaces the dev default; * and null origins forbidden) |
ALLOWED_BODY_TOKEN_ORIGINS |
(empty) | Optional comma-separated WebView / desktop origins (e.g., tauri://localhost,http://tauri.localhost) permitted to use CORS + X-Auth-Transport: body JSON refresh tokens (* and null origins forbidden) |
ALLOW_BODY_REFRESH_TOKENS |
true |
Enables or disables issuing/refreshing JSON-body refresh tokens for non-browser/WebView clients (body logout remains allowed so existing sessions can revoke cleanly) |
REJECT_BROWSER_ORIGIN_FOR_BODY_TOKENS |
true |
Rejects Origin / Sec-Fetch-Site browser headers on body-token requests unless the Origin is listed in ALLOWED_BODY_TOKEN_ORIGINS (any overlap between FRONTEND_URL / ALLOWED_ORIGINS and ALLOWED_BODY_TOKEN_ORIGINS is rejected at startup) |
COOKIE_SECURE / COOKIE_SAME_SITE / COOKIE_DOMAIN |
false / Lax / (empty) |
Refresh & CSRF cookie attributes (COOKIE_SAME_SITE validated at startup; None requires COOKIE_SECURE=true) |
RATE_LIMIT_ENABLED / RATE_LIMIT_AUTH_PER_MINUTE / RATE_LIMIT_API_PER_MINUTE |
true / 30 / 300 |
Sharded cross-worker per-IP rate limiting thresholds (bounded memory; independent bucket stores for /api/v1, /api/v1/auth, sensitive /api/v1/profile mutations, and organisation invites) |
TRUST_PROXY_HEADERS / TRUST_CF_CONNECTING_IP / TRUSTED_PROXY_CIDRS |
false / false / RFC1918 + loopback |
When TRUST_PROXY_HEADERS=true and peer IP is in TRUSTED_PROXY_CIDRS, walks X-Forwarded-For right-to-left (falling back to peer IP if all hops are trusted); honors single CF-Connecting-IP only when TRUST_CF_CONNECTING_IP=true |
ARGON2_MAX_CONCURRENCY |
8 (4 in Swarm) |
Max concurrent Argon2id hashes (1–64, ~19 MiB each) to prevent OOM DoS under auth bursts |
AUTH_MAX_FAILED_LOGIN_ATTEMPTS / AUTH_ACCOUNT_LOCKOUT_SECONDS |
5 / 900 |
Per-account temporary lockout threshold (0 disables) and duration in seconds after consecutive wrong passwords |
ENABLE_SWAGGER_UI |
true (dev) / false (prod) |
Controls whether /swagger-ui/ and /api/v1/openapi.json are exposed (disabled by default in production) |
AUDIT_LOG_RETENTION_DAYS |
90 |
MongoDB TTL index retention period in days for audit_logs (0 drops/disables audit_created_at_ttl; max 24855 days) |
PERMISSION_CACHE_TTL_SECONDS |
30 |
Bounded, generation-tracked in-memory RBAC cache TTL in seconds (0 disables caching for multi-replica deployments) |
REQUIRE_EMAIL_VERIFICATION |
false |
When true, newly registered accounts start in pending_verification status without issuing session tokens/cookies |
BOOTSTRAP_SUPER_ADMIN_EMAIL / BOOTSTRAP_SUPER_ADMIN_PASSWORD (_FILE) |
admin@example.com / (empty) |
Optional initial Super Administrator bootstrap (also supports BOOTSTRAP_SUPER_ADMIN_FIRST_NAME / LAST_NAME and _FILE secret path) |
RUST_LOG |
info,auth_backend=debug,actix_web=info |
tracing-subscriber filter expression (info in production container) |
| Variable | Default | Description |
|---|---|---|
VITE_API_BASE_URL |
http://localhost:8080/api/v1 |
Base URL for the Rust REST API |
docker compose up --buildUses mongo:9 configured as a single-node replica set (rs0, bound to 127.0.0.1:27017), the optimized Rust release container, and the Nginx frontend container:
- Frontend:
http://localhost:5173 - Backend API:
http://localhost:8080/api/v1 - Swagger UI:
http://localhost:8080/swagger-ui/ - Bootstrap Super Admin (dev compose defaults):
admin@example.com/ChangeMe123!
- Start MongoDB (
docker compose up -d mongodb, or a local replica setrs0on127.0.0.1:27017;backend/.env.exampleincludesdirectConnection=trueso the host connects directly to the containerized replica set). - Configure & run the backend:
cd backend cp .env.example .env cargo run - Configure & run the frontend:
cd frontend cp .env.example .env yarn install yarn dev
Deploy pre-built GHCR images with external Ed25519 Swarm secrets and MongoDB Atlas using deploy/swarm-stack.yml and deploy/portainer.env.example. See deploy/README.md and docs/DEPLOYMENT.md for step-by-step instructions.
cd backend
cargo fmt --all -- --check
cargo clippy --locked --all-targets -- -D warnings
cargo test --locked
cargo build --release --locked
# Optional: run live MongoDB repository, index, and seeding integration test
MONGODB_TEST_URI=mongodb://localhost:27017 cargo test --locked --test mongodb_integration_tests -- --nocapturecd frontend
yarn format:check
yarn lint --max-warnings=0
yarn test
yarn buildAutomated CI runs on pushes to main and develop, and on pull requests (opened, synchronize, reopened) targeting main or develop:
- .github/workflows/backend-ci.yml: Verifies zero
mod.rsfiles, runscargo fmt --check,cargo clippy --locked --all-targets -- -D warnings, and executes the full unit, API/RBAC, and livemongo:9replica-set (rs0) integration test suite. - .github/workflows/frontend-ci.yml: Verifies JavaScript-only source and zero TanStack dependencies, installs with Yarn Berry (
--immutable), and runs Prettier, ESLint (--max-warnings=0), Vitest, and the Vite production build. - .github/workflows/docker-publish.yml: Gates releases on backend/frontend lint, tests, and
yarn npm audit --all --severity high, then builds and publishes backend and frontend container images toghcr.ioon pushes tomain,v*.*.*tags, or manual dispatch (ready for deploy/swarm-stack.yml in Portainer).
See docs/DEPLOYMENT.md for production hardening instructions.