docs: add architecture documentation and standardize filenames
This commit is contained in:
1 parent
5c1340c9cb
commit
0010f2cfb8
1 file changed
+202
-299
+202
-299
@@ -1,444 +1,347 @@
|
|||||||
# NX9-Auth System Architecture Specification
|
# 1. System Overview
|
||||||
|
|
||||||
|
NX9-Auth is a self-hosted Identity and Access Management (IAM) server written in pure Rust. It provides centralized authentication, fine-grained Role-Based Access Control (RBAC), multi-tenancy, service account management, personal access tokens (PATs), and append-only audit logging.
|
||||||
|
|
||||||
|
The system is architected as a stateless HTTP server paired with a zero-JavaScript-framework WebAssembly (WASM) administration user interface. Executing natively on Linux operating systems without external memory caches, JavaScript runtimes, or third-party web frameworks, NX9-Auth achieves low memory consumption, high throughput, zero garbage collection pauses, and operational simplicity.
|
||||||
|
|
||||||
|
Supported deployment models include single-binary installations, systemd-managed services, containerized workloads, and reverse-proxy setups using embedded SQLite or external PostgreSQL database engines.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. System Overview & Executive Summary
|
# 2. Design Philosophy
|
||||||
|
|
||||||
**NX9-Auth** is a lightweight, high-performance, self-hosted Identity and Access Management (IAM) platform written entirely in pure Rust. It provides centralized authentication, fine-grained Role-Based Access Control (RBAC), multi-tenancy, service account management, personal access tokens (PATs), and append-only audit logging.
|
NX9-Auth adheres to seven core design tenets:
|
||||||
|
|
||||||
The system is architected as a modular, stateless HTTP server paired with a zero-JavaScript-framework WebAssembly (WASM) administration user interface. By executing natively on Linux systems without requiring external memory caches (e.g., Redis), JavaScript runtime environments (e.g., Node.js), or third-party web frameworks, NX9-Auth achieves minimal memory consumption, high throughput, zero garbage collection pauses, and operational simplicity.
|
- **Linux-First**: Native optimization for Linux operating systems, systemd process supervision, standard UNIX signal handling, and POSIX filesystem standards.
|
||||||
|
- **Privacy-First**: Zero external telemetry, phone-home calls, or third-party tracking. All identity records remain strictly under local operator control.
|
||||||
|
- **Self-Hosted**: Distributed as 100% Free and Open Source Software (FOSS) dual-licensed under Apache 2.0 and MIT.
|
||||||
|
- **Rust-Native**: End-to-end type safety, compile-time memory safety, and thread concurrency guarantees across both server and WebAssembly client binaries.
|
||||||
|
- **Security by Default**: OWASP-aligned response headers, memory-hard Argon2id key derivation, BLAKE3 token hashing at rest, non-enumerating error responses, and strict Content Security Policies.
|
||||||
|
- **Zero Node.js Runtime**: No JavaScript runtime dependencies, npm build chains, or external frontend node packages. The administrative interface is compiled from Rust directly to WebAssembly.
|
||||||
|
- **Operational Simplicity**: Single-binary deployment capability with embedded or external SQL databases. Zero mandatory external cache or message broker sidecars.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Design Philosophy
|
# 3. Architectural Principles
|
||||||
|
|
||||||
NX9-Auth adheres strictly to eight core design tenets:
|
|
||||||
|
|
||||||
1. **Linux-First**: Native optimization for Linux environments, systemd process supervision, standard UNIX signals, and POSIX filesystem standards.
|
|
||||||
2. **Privacy-First**: No external telemetry, phone-home mechanisms, or third-party tracking. All identity records remain strictly under local operator control.
|
|
||||||
3. **Self-Hosted & FOSS**: Distributed as 100% Free and Open Source Software (FOSS) dual-licensed under Apache 2.0 and MIT.
|
|
||||||
4. **Rust-Native Integrity**: End-to-end type safety, compile-time memory safety, and thread concurrency guarantees across both server and WebAssembly client binaries.
|
|
||||||
5. **Zero Node.js Runtime**: No JavaScript runtime dependencies, npm build chains, or node_modules overhead. The frontend is compiled from Rust directly to WebAssembly.
|
|
||||||
6. **Minimal Dependencies**: Strict audit of external crates to maintain a minimal attack surface, fast compile times, and long-term maintenance stability.
|
|
||||||
7. **Operational Simplicity**: Single-binary deployment capability with embedded or external SQL databases. Zero mandatory external cache or message broker sidecars.
|
|
||||||
8. **Security by Default**: OWASP-aligned response headers, memory-hard Argon2id key derivation, BLAKE3 token hashing at rest, non-enumerating error responses, and strict Content Security Policies (CSP).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Architectural Principles
|
|
||||||
|
|
||||||
The internal architecture is guided by structural design patterns:
|
The internal architecture is guided by structural design patterns:
|
||||||
|
|
||||||
- **Layer Separation**: Downward-only dependency flow (`CLI` $\rightarrow$ `Runtime` $\rightarrow$ `Application` $\rightarrow$ `HTTP Router` $\rightarrow$ `Services` $\rightarrow$ `Repositories` $\rightarrow$ `Database`).
|
- **Layer Separation**: Downward-only dependency flow from entry points to persistence drivers.
|
||||||
- **Dependency Inversion**: Service and handler layers depend on trait abstractions (`UserRepository`, `SessionRepository`) rather than concrete database drivers.
|
- **Repository Pattern**: Pluggable storage providers implementing unified async trait interfaces.
|
||||||
- **Repository Pattern**: Pluggable storage providers (SQLite, PostgreSQL) implementing unified async trait interfaces.
|
- **Dependency Inversion**: Service and handler layers depend on trait abstractions rather than concrete database drivers.
|
||||||
- **Configuration over Hardcoding**: Fail-fast configuration loading supporting configuration files, environment variable overrides, and CLI flags.
|
- **Stateless APIs**: Authentication state is encapsulated in cryptographically hashed session cookies or Bearer tokens, eliminating sticky-session server dependencies.
|
||||||
- **Stateless HTTP API**: Authentication state is encapsulated in cryptographically hashed session cookies or Bearer tokens, eliminating sticky-session server dependencies.
|
- **Explicit Errors**: Strongly typed error enumerations mapping internal failures to standard HTTP status codes without leaking sensitive stack traces.
|
||||||
- **Fail-Fast Startup**: Early validation of configuration paths, database connectivity, and encryption parameters before opening listening sockets.
|
- **Fail-Fast Startup**: Early validation of configuration paths, database connectivity, and encryption parameters before opening listening sockets.
|
||||||
- **Graceful Shutdown**: Signal-driven, multi-stage shutdown sequence ensuring background worker completion, audit log flushing, and pool draining.
|
- **Graceful Shutdown**: Signal-driven, multi-stage shutdown sequence ensuring background worker completion, audit log flushing, and pool draining.
|
||||||
- **Explicit Error Handling**: Strongly typed error enumerations (`AppError`) mapping internal failures to standard HTTP status codes without leaking sensitive stack traces.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Technology Stack
|
# 4. Technology Stack
|
||||||
|
|
||||||
| Component Layer | Technology Choice | Key Function & Architectural Role |
|
### Backend
|
||||||
| :--- | :--- | :--- |
|
- **Core Language**: Rust (2024 Edition)
|
||||||
| **Language Ecosystem** | Rust | Core system implementation across server and WebAssembly client. |
|
- **Async Runtime**: Tokio
|
||||||
| **Async Execution** | Tokio | Multi-threaded asynchronous I/O, timer management, and task scheduling. |
|
- **HTTP Routing**: Axum and Tower
|
||||||
| **HTTP Routing** | Axum & Tower | Type-safe REST API routing, request extraction, and middleware pipelines. |
|
- **Database Engine**: SQLx (supporting SQLite and PostgreSQL)
|
||||||
| **Database Abstraction** | SQLx | Asynchronous, compile-time verified database access for SQLite and PostgreSQL. |
|
|
||||||
| **Password Cryptography** | Argon2id | Memory-hard key derivation function for secure password verification. |
|
### Frontend
|
||||||
| **Token Hashing** | BLAKE3 | Fast cryptographic hashing for storing session tokens and PATs at rest. |
|
- **UI Framework**: Dioxus (WebAssembly compilation target)
|
||||||
| **Rate Limiting** | DashMap | Lock-free, high-concurrency in-memory hash map for tracking IP failure counters. |
|
- **WASM Interop**: wasm-bindgen
|
||||||
| **Frontend Framework** | Dioxus (WASM) | Declarative, signal-driven WebAssembly UI with virtual DOM reconciliation. |
|
- **HTTP Client**: Reqwest (configured for credentialed WebAssembly fetch operations)
|
||||||
| **WASM HTTP Client** | Reqwest (WASM) | WebAssembly HTTP fetch client configured for credentialed API interaction. |
|
- **Browser Storage**: gloo-storage
|
||||||
|
|
||||||
|
### Cryptography & Security
|
||||||
|
- **Password Hashing**: Argon2id
|
||||||
|
- **Token Hashing**: BLAKE3
|
||||||
|
- **Rate Limiting**: DashMap (lock-free in-memory tracking)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. Runtime Architecture
|
# 5. Runtime Architecture
|
||||||
|
|
||||||
### 5.1 Runtime Core Components
|
The server runtime isolates process lifecycle management from business domain logic.
|
||||||
|
|
||||||
The server runtime (`src/runtime/`) isolates process lifecycle management from business domain logic:
|
### Components
|
||||||
|
- **Application**: Core container holding global state, connection pools, state trackers, and worker managers.
|
||||||
- **Application**: The core container holding state, connection pools, state trackers, and worker managers.
|
- **Builder**: Assembles configuration, initializes database providers, applies database migrations, and binds the router.
|
||||||
- **ApplicationBuilder**: Assembles configuration, initializes database providers, applies database migrations, and binds the router.
|
- **Lifecycle**: Manages application state transitions from initialization to termination.
|
||||||
- **AtomicRuntimeState**: Lock-free atomic state machine enforcing valid lifecycle transitions.
|
- **State**: Lock-free atomic state machine enforcing valid lifecycle transitions.
|
||||||
- **SignalManager**: Asynchronous signal listener intercepting `SIGINT` and `SIGTERM`.
|
- **Workers**: Supervises background asynchronous tasks such as expired session pruning and audit log flushing.
|
||||||
- **ShutdownCoordinator**: Manages prioritized shutdown hooks and completion timeouts.
|
- **Signals**: Asynchronous signal listener intercepting SIGINT and SIGTERM.
|
||||||
- **WorkerManager**: Supervises background asynchronous tasks (e.g., expired session pruning, audit log flushing).
|
- **Hooks**: Maintains prioritized cleanup routines executed during graceful shutdown.
|
||||||
- **HookRegistry**: Maintains prioritized cleanup routines executed during graceful shutdown.
|
- **Metrics**: Tracks runtime uptime, active connections, and worker states.
|
||||||
- **RuntimeMetrics**: Tracks runtime uptime, active connections, and worker states.
|
- **Shutdown**: Manages prioritized shutdown hooks and completion timeouts.
|
||||||
|
|
||||||
### 5.2 Deterministic Lifecycle State Machine
|
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
stateDiagram-v2
|
stateDiagram-v2
|
||||||
[*] --> Initializing : ApplicationBuilder::build()
|
[*] --> Initializing : Build application runtime
|
||||||
Initializing --> Starting : Application::start()
|
Initializing --> Starting : Start application
|
||||||
Starting --> Running : TcpListener Bound & axum::serve Awaited
|
Starting --> Running : Bind TCP listener and serve
|
||||||
Running --> Draining : SIGINT / SIGTERM Received
|
Running --> Draining : Signal received
|
||||||
Draining --> StoppingWorkers : Background Workers Signaled
|
Draining --> StoppingWorkers : Stop background workers
|
||||||
StoppingWorkers --> ExecutingHooks : Prioritized Shutdown Hooks Executed
|
StoppingWorkers --> ExecutingHooks : Execute shutdown hooks
|
||||||
ExecutingHooks --> ClosingResources : Database Connection Pools Drained
|
ExecutingHooks --> ClosingResources : Close database pools
|
||||||
ClosingResources --> Stopped : Process Terminates Cleanly
|
ClosingResources --> Stopped : Process stopped
|
||||||
Stopped --> [*]
|
Stopped --> [*]
|
||||||
```
|
```
|
||||||
|
|
||||||
### 5.3 Prioritized Shutdown Sequence
|
|
||||||
|
|
||||||
When a termination signal is received, the runtime executes hooks sequentially by tier:
|
|
||||||
|
|
||||||
1. **ShutdownPriority::First**: Closes HTTP ingress listener and stops receiving new connections.
|
|
||||||
2. **ShutdownPriority::Normal**: Cancels active background worker loops and awaits inflight jobs.
|
|
||||||
3. **ShutdownPriority::Last**: Flushes pending audit trails and closes database pool connections.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 6. Request Lifecycle & Pipeline Architecture
|
# 6. Request Lifecycle
|
||||||
|
|
||||||
Every incoming HTTP request traverses a strict layered middleware pipeline:
|
Every incoming HTTP request traverses a structured, layered processing pipeline.
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart TD
|
flowchart TD
|
||||||
Client([Client Request]) --> TCP[Tokio TcpListener]
|
Client[Client Request] --> TCP[TCP Listener]
|
||||||
TCP --> Router[Axum HTTP Router]
|
TCP --> Router[Axum HTTP Router]
|
||||||
|
Router --> SecHeaders[Security Headers Middleware]
|
||||||
subgraph MiddlewarePipeline [" Middleware Pipeline "]
|
SecHeaders --> TracingMW[Tracing and Request ID]
|
||||||
Router --> SecHeaders[Security Headers Middleware\nCSP, Cache-Control, HSTS]
|
TracingMW --> Sanitizer[Query String Credential Sanitizer]
|
||||||
SecHeaders --> TracingMW[Tracing & Request ID Generation]
|
Sanitizer --> AuthExtractor[Authentication Extractor]
|
||||||
TracingMW --> Sanitizer[SPA Query String Credential Sanitizer]
|
AuthExtractor --> GuardCheck{Authorized}
|
||||||
end
|
GuardCheck -- No --> ErrResp[HTTP 401 or 403 Response] --> Client
|
||||||
|
GuardCheck -- Yes --> Handler[API Route Handler]
|
||||||
Sanitizer --> AuthExtractor[AuthUser Extractor\nCookie vs. Bearer Token]
|
|
||||||
AuthExtractor --> GuardCheck{Endpoint Allowed?}
|
|
||||||
|
|
||||||
GuardCheck -- Unauthorized --> ErrResp[HTTP 401 / 403 JSON Response] --> Client
|
|
||||||
GuardCheck -- Authorized --> Handler[API Route Handler]
|
|
||||||
|
|
||||||
Handler --> Service[Domain Service Layer]
|
Handler --> Service[Domain Service Layer]
|
||||||
Service --> RepoTrait[Repository Trait Interface]
|
Service --> RepoTrait[Repository Interface]
|
||||||
RepoTrait --> DBImpl[SQLite / PostgreSQL Driver]
|
RepoTrait --> DBImpl[Database Provider]
|
||||||
DBImpl --> DB[(Database Engine)]
|
DBImpl --> DB[(Database Engine)]
|
||||||
|
|
||||||
DB --> DBImpl --> RepoTrait --> Service --> Handler
|
DB --> DBImpl --> RepoTrait --> Service --> Handler
|
||||||
Handler --> Response[JSON Response / SPA Assets] --> Client
|
Handler --> Response[JSON Response or SPA Assets] --> Client
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 7. Repository & Database Architecture
|
# 7. Repository Architecture
|
||||||
|
|
||||||
### 7.1 Repository Abstraction Layer
|
NX9-Auth decouples persistence logic from domain services using trait abstractions. This ensures API handlers remain agnostic of the underlying storage backend.
|
||||||
|
|
||||||
NX9-Auth decouples persistence logic from domain services using Rust traits (`async_trait`). This guarantees that API handlers remain agnostic of the underlying database engine.
|
### Layer Hierarchy
|
||||||
|
1. **Traits**: Define high-level database access contracts.
|
||||||
|
2. **SQLite Implementation**: Embedded storage driver using Write-Ahead Logging for high concurrency.
|
||||||
|
3. **PostgreSQL Implementation**: Enterprise storage driver for external multi-node deployments.
|
||||||
|
4. **Service Layer**: Coordinates business logic, transactions, and audit trail records across repositories.
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
classDiagram
|
classDiagram
|
||||||
class UserRepository {
|
class UserRepository {
|
||||||
<<interface>>
|
+find_by_id(id)
|
||||||
+find_by_id(id) Option~User~
|
+find_by_username(username)
|
||||||
+find_by_username(name) Option~User~
|
+create(user)
|
||||||
+create(user) User
|
+update(user)
|
||||||
+update(user) User
|
+delete(id)
|
||||||
+delete(id) bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class SqliteUserRepository {
|
class SqliteUserRepository {
|
||||||
-SqlitePool pool
|
|
||||||
+find_by_id(id)
|
+find_by_id(id)
|
||||||
+create(user)
|
+create(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
class PostgresUserRepository {
|
class PostgresUserRepository {
|
||||||
-PgPool pool
|
|
||||||
+find_by_id(id)
|
+find_by_id(id)
|
||||||
+create(user)
|
+create(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
class AuthService {
|
class AuthService {
|
||||||
-DynUserRepository user_repo
|
|
||||||
-DynSessionRepository session_repo
|
|
||||||
+authenticate(credentials)
|
+authenticate(credentials)
|
||||||
}
|
}
|
||||||
|
|
||||||
UserRepository <|.. SqliteUserRepository
|
UserRepository <|.. SqliteUserRepository
|
||||||
UserRepository <|.. PostgresUserRepository
|
UserRepository <|.. PostgresUserRepository
|
||||||
AuthService --> UserRepository
|
AuthService --> UserRepository
|
||||||
```
|
```
|
||||||
|
|
||||||
### 7.2 Database Engines & Schema Migrations
|
|
||||||
|
|
||||||
- **SQLite**: Default embedded database provider using WAL (Write-Ahead Logging) mode and busy timeout management for high concurrency.
|
|
||||||
- **PostgreSQL**: Production multi-node provider for enterprise environments.
|
|
||||||
- **Migration System**: Managed via SQLx embedded migrations executed automatically during startup, guaranteeing schema consistency across upgrades.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 8. Authentication Architecture
|
# 8. Authentication
|
||||||
|
|
||||||
NX9-Auth supports dual-mode authentication, accommodating both web browser clients (via HttpOnly cookies) and API consumers / SPA applications (via Bearer tokens).
|
NX9-Auth supports dual-mode authentication, accommodating both browser environments and automated API clients.
|
||||||
|
|
||||||
|
### Authentication Credentials and Identifiers
|
||||||
|
- **Login Handler**: Accepts JSON credential payloads and validates passwords using Argon2id.
|
||||||
|
- **Password Verification**: Memory-hard verification with constant-time dummy delays on invalid usernames to neutralize timing side-channels.
|
||||||
|
- **Sessions**: Short-lived opaque session tokens issued upon login and stored as BLAKE3 hashes at rest.
|
||||||
|
- **Refresh Tokens**: Opaque refresh tokens used to obtain new session tokens without re-entering credentials.
|
||||||
|
- **Personal Access Tokens (PAT)**: Long-lived tokens generated for automated API integrations.
|
||||||
|
- **Service Accounts**: Non-human identities bound to specific tenants and permission scopes.
|
||||||
|
- **Cookies**: HttpOnly, SameSite-protected cookies holding session identifiers for browser clients.
|
||||||
|
- **Bearer Tokens**: Authorization header tokens for API consumers and WebAssembly applications.
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart TD
|
flowchart TD
|
||||||
AuthRequest([Incoming Credentials / Request]) --> RouteType{Request Path?}
|
AuthRequest[Incoming HTTP Request] --> RouteType{Request Path}
|
||||||
|
RouteType -- Login Route --> LoginHandler[Login Handler]
|
||||||
RouteType -- POST /api/v1/auth/login --> LoginHandler[Login Handler]
|
|
||||||
LoginHandler --> VerifyPassword[Verify Password via Argon2id]
|
LoginHandler --> VerifyPassword[Verify Password via Argon2id]
|
||||||
VerifyPassword -- Invalid --> TimingMitigation[Execute Dummy Argon2id Delay] --> Return401[Return HTTP 401 Unauthorized]
|
VerifyPassword -- Invalid --> TimingMitigation[Execute Dummy Hash Delay] --> Return401[Return HTTP 401]
|
||||||
VerifyPassword -- Valid --> RevokeSessions[Session Fixation Mitigation:\nRevoke Prior Sessions & Tokens]
|
VerifyPassword -- Valid --> RevokeSessions[Revoke Active User Sessions]
|
||||||
|
RevokeSessions --> GenerateTokens[Generate Opaque Tokens]
|
||||||
RevokeSessions --> GenerateTokens[Generate Opaque Tokens:\nst_... and rt_...]
|
GenerateTokens --> HashTokens[Compute BLAKE3 Hashes]
|
||||||
GenerateTokens --> HashTokens[Compute BLAKE3 Hashes for Storage]
|
|
||||||
HashTokens --> SaveDB[Store Hashes in Database]
|
HashTokens --> SaveDB[Store Hashes in Database]
|
||||||
SaveDB --> IssueAuth[Issue HttpOnly Cookie + Return Access Token JSON] --> AuthSuccess([Authenticated])
|
SaveDB --> IssueAuth[Issue HttpOnly Cookie and Bearer Token] --> AuthSuccess[Authentication Success]
|
||||||
|
RouteType -- Protected API Route --> ExtractAuth[Extract Authentication Context]
|
||||||
RouteType -- Protected API Route --> ExtractAuth[Extract AuthUser]
|
ExtractAuth --> CheckCookie{Cookie Present}
|
||||||
ExtractAuth --> CheckCookie{Cookie nx9_session\nPresent?}
|
|
||||||
CheckCookie -- Yes --> ValidateCookie[BLAKE3 Lookup in Sessions Table]
|
CheckCookie -- Yes --> ValidateCookie[BLAKE3 Lookup in Sessions Table]
|
||||||
ValidateCookie -- Valid --> ExtractUserCookie[Find Active User] --> SessionAuth([AuthMethod::Session])
|
ValidateCookie -- Valid --> ExtractUserCookie[Find Active User] --> SessionAuth[Authenticated Session]
|
||||||
|
CheckCookie -- No --> CheckHeader{Authorization Header Present}
|
||||||
CheckCookie -- No --> CheckHeader{Authorization: Bearer\nHeader Present?}
|
CheckHeader -- Yes --> TokenPrefix{Token Prefix}
|
||||||
CheckHeader -- Yes --> TokenPrefix{Token Prefix?}
|
TokenPrefix -- PAT Prefix --> ValidatePAT[BLAKE3 Lookup in PAT Table] --> ExtractUserPAT[Find Active User] --> PATAuth[Authenticated Token]
|
||||||
TokenPrefix -- pat_... --> ValidatePAT[BLAKE3 Lookup in PAT Table] --> ExtractUserPAT[Find Active User] --> PATAuth([AuthMethod::Token])
|
TokenPrefix -- Session Prefix --> ValidateSession[BLAKE3 Lookup in Sessions Table] --> ExtractUserSession[Find Active User] --> SessionAuth
|
||||||
TokenPrefix -- st_... --> ValidateSession[BLAKE3 Lookup in Sessions Table] --> ExtractUserSession[Find Active User] --> SessionAuth
|
|
||||||
|
|
||||||
CheckHeader -- No --> Return401
|
CheckHeader -- No --> Return401
|
||||||
ValidateCookie -- Invalid --> CheckHeader
|
ValidateCookie -- Invalid --> CheckHeader
|
||||||
ValidatePAT -- Invalid --> Return401
|
ValidatePAT -- Invalid --> Return401
|
||||||
ValidateSession -- Invalid --> Return401
|
ValidateSession -- Invalid --> Return401
|
||||||
```
|
```
|
||||||
|
|
||||||
### 8.1 Key Authentication Mechanisms
|
|
||||||
- **Session Tokens (`st_...`)**: Short-lived opaque session tokens returned on login and stored in HttpOnly cookies or client memory.
|
|
||||||
- **Refresh Tokens (`rt_...`)**: Opaque tokens used to issue new session tokens without re-entering primary credentials.
|
|
||||||
- **Personal Access Tokens (`pat_...`)**: Long-lived API tokens generated by users for automated integrations, hashed at rest using BLAKE3.
|
|
||||||
- **Service Accounts**: Non-human identities bound to specific tenants and limited permission scopes for automated workloads.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 9. Authorization Model (RBAC)
|
# 9. Authorization
|
||||||
|
|
||||||
NX9-Auth implements a hierarchical Role-Based Access Control (RBAC) model:
|
NX9-Auth implements a hierarchical Role-Based Access Control (RBAC) authorization model.
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart LR
|
flowchart LR
|
||||||
User[User / Service Account] --> UserRoles[Assigned Roles]
|
User[User or Service Account] --> UserRoles[Assigned Roles]
|
||||||
UserRoles --> RolePermissions[Role Permissions]
|
UserRoles --> RolePermissions[Role Permissions]
|
||||||
RolePermissions --> GlobalPermissions[Effective Permission Set]
|
RolePermissions --> GlobalPermissions[Effective Permission Set]
|
||||||
|
Request[API Endpoint Request] --> RequiredPerm[Required Permission Scope]
|
||||||
Request[API Request Endpoint] --> RequiredPerm[Required Permission Scope]
|
RequiredPerm --> AccessEvaluator{Permission Granted}
|
||||||
RequiredPerm --> AccessEvaluator{Permission In Set?}
|
|
||||||
GlobalPermissions --> AccessEvaluator
|
GlobalPermissions --> AccessEvaluator
|
||||||
|
AccessEvaluator -- Yes --> Allow[Execute Handler]
|
||||||
AccessEvaluator -- Yes --> Allow[HTTP 200 / Execute Handler]
|
|
||||||
AccessEvaluator -- No --> Deny[HTTP 403 Forbidden]
|
AccessEvaluator -- No --> Deny[HTTP 403 Forbidden]
|
||||||
```
|
```
|
||||||
|
|
||||||
### Authorization Rules
|
---
|
||||||
- **Super Admin (`*`)**: Universal access across all tenants and administrative APIs.
|
|
||||||
- **Tenant Admin**: Administrative authority scoped strictly to resources owned by their tenant.
|
# 10. Security
|
||||||
- **Viewer / Standard User**: Read-only access or limited domain operation privileges.
|
|
||||||
- **Permission Evaluation**: Resolved during the handler phase after successful `AuthUser` extraction.
|
NX9-Auth enforces a defense-in-depth security posture across all subsystems:
|
||||||
|
|
||||||
|
- **Argon2id Key Derivation**: Memory-hard password hashing parameters (m=19456 KiB, t=2, p=1).
|
||||||
|
- **BLAKE3 Cryptographic Hashing**: High-speed cryptographic hashing for storing session tokens, refresh tokens, and personal access tokens at rest.
|
||||||
|
- **Secure Cookie Attributes**: HttpOnly, SameSite=Lax, and Secure flag enforcement in production environments.
|
||||||
|
- **Content Security Policy (CSP)**: Strict header policy prohibiting inline script execution while allowing WebAssembly evaluation.
|
||||||
|
- **HTTP Strict Transport Security (HSTS)**: Transport security header enforcement when running under secure configurations.
|
||||||
|
- **Audit Logging**: Append-only, tamper-evident audit trail capturing actor, target, severity, IP address, and user agent.
|
||||||
|
- **Rate Limiting**: Lock-free in-memory IP tracking with automatic lockout penalties upon consecutive failure thresholds.
|
||||||
|
- **Credential Sanitization**: Fallback routes intercept and strip query strings containing credentials, returning HTTP 303 redirects to clean paths.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 10. Security Architecture
|
# 11. Multi-tenancy
|
||||||
|
|
||||||
NX9-Auth enforces a defense-in-depth security posture:
|
Resources are hierarchically isolated to enforce strict multi-tenant data boundaries.
|
||||||
|
|
||||||
```
|
|
||||||
┌────────────────────────────────────────────────────────────────────────┐
|
|
||||||
│ HTTP Response Layer │
|
|
||||||
│ Strict CSP (script-src 'self' 'wasm-unsafe-eval') | Cache-Control │
|
|
||||||
│ HSTS | X-Frame-Options: DENY | Referrer-Policy: no-referrer │
|
|
||||||
└────────────────────────────────────────────────────────────────────────┘
|
|
||||||
│
|
|
||||||
┌────────────────────────────────────────────────────────────────────────┐
|
|
||||||
│ Transport & Sanitization │
|
|
||||||
│ GET Query Credential Interceptor (HTTP 303 Redirect Sanitizer) │
|
|
||||||
│ In-Memory Rate Limiting (DashMap Exponential IP Lockout) │
|
|
||||||
└────────────────────────────────────────────────────────────────────────┘
|
|
||||||
│
|
|
||||||
┌────────────────────────────────────────────────────────────────────────┐
|
|
||||||
│ Cryptographic Storage Layer │
|
|
||||||
│ Argon2id (m=19456 KiB, t=2, p=1) Password Key Derivation │
|
|
||||||
│ BLAKE3 Opaque Token Hashing at Rest (Sessions, Refresh, PATs) │
|
|
||||||
└────────────────────────────────────────────────────────────────────────┘
|
|
||||||
│
|
|
||||||
┌────────────────────────────────────────────────────────────────────────┐
|
|
||||||
│ Audit & Observability │
|
|
||||||
│ Append-Only Tamper-Evident Audit Logging (actor, target, severity) │
|
|
||||||
└────────────────────────────────────────────────────────────────────────┘
|
|
||||||
```
|
|
||||||
|
|
||||||
- **Non-Enumerating Authentication Errors**: Password failures and non-existent usernames return identical HTTP 401 error payloads and invoke Argon2id execution paths to neutralize timing side-channels.
|
|
||||||
- **Query Parameter Credential Protection**: Server-side fallback handlers strip any query strings containing sensitive credentials (`username=`, `password=`) and issue immediate HTTP 303 redirects to clean paths.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 11. Multi-Tenancy & Resource Hierarchy
|
|
||||||
|
|
||||||
Resources are hierarchically structured to ensure data isolation:
|
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart TD
|
flowchart TD
|
||||||
System[NX9-Auth System] --> TenantA[Tenant A]
|
System[NX9-Auth System] --> TenantA[Tenant A]
|
||||||
System --> TenantB[Tenant B]
|
System --> TenantB[Tenant B]
|
||||||
|
TenantA --> UsersA[Users and Service Accounts]
|
||||||
TenantA --> UsersA[Users & Service Accounts]
|
|
||||||
TenantA --> GroupsA[Groups]
|
TenantA --> GroupsA[Groups]
|
||||||
TenantA --> AppsA[Applications]
|
TenantA --> AppsA[Applications]
|
||||||
|
|
||||||
GroupsA --> RolesA[Roles]
|
GroupsA --> RolesA[Roles]
|
||||||
AppsA --> ResourcesA[API Resources & Tokens]
|
AppsA --> ResourcesA[Resources and Tokens]
|
||||||
|
TenantB --> UsersB[Users and Service Accounts]
|
||||||
TenantB --> UsersB[Users & Service Accounts]
|
|
||||||
TenantB --> GroupsB[Groups]
|
TenantB --> GroupsB[Groups]
|
||||||
TenantB --> AppsB[Applications]
|
TenantB --> AppsB[Applications]
|
||||||
```
|
```
|
||||||
|
|
||||||
### Data Isolation Guarantees
|
### Data Isolation Rules
|
||||||
- Every database query for tenant-scoped entities contains explicit `WHERE tenant_id = ?` filters.
|
- Database queries for tenant-scoped entities enforce explicit tenant filters.
|
||||||
- Service accounts and applications are strictly bound to their parent tenant ID and cannot cross boundaries.
|
- Service accounts and applications are strictly bound to their parent tenant identifier.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 12. Frontend Architecture (WebAssembly SPA)
|
# 12. Frontend
|
||||||
|
|
||||||
The administration interface is implemented as a pure WebAssembly Single Page Application (SPA) using Dioxus 0.6:
|
The administrative user interface is implemented as a WebAssembly Single Page Application (SPA) built with Dioxus.
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart TD
|
flowchart TD
|
||||||
Browser[Web Browser] --> IndexHTML[index.html]
|
Browser[Web Browser] --> IndexHTML[Index HTML]
|
||||||
IndexHTML --> BootJS[assets/boot.js]
|
IndexHTML --> BootJS[Boot Script]
|
||||||
BootJS --> WASMModule[nx9_auth_ui_bg.wasm]
|
BootJS --> WASMModule[WASM Module]
|
||||||
|
WASMModule --> VDOM[Virtual DOM Engine]
|
||||||
subgraph DioxusWASM [" Dioxus WebAssembly Engine "]
|
VDOM --> SignalState[Signal State]
|
||||||
VDOM[Virtual DOM Engine]
|
SignalState --> Router[Dioxus Router]
|
||||||
SignalState[Signal State Management]
|
Router --> EventSystem[Dual Event Interceptors]
|
||||||
Router[Dioxus Router]
|
EventSystem --> FormSubmit[Form Submit Listener]
|
||||||
end
|
EventSystem --> ButtonClick[Button Click Listener]
|
||||||
|
FormSubmit --> PreventDefault[Prevent Default Event]
|
||||||
WASMModule --> DioxusWASM
|
ButtonClick --> PreventDefault
|
||||||
|
PreventDefault --> WASMFetch[Reqwest WASM Fetch]
|
||||||
subgraph EventSystem [" Dual Event Interception Protocol "]
|
WASMFetch --> BackendAPI[Axum REST API]
|
||||||
FormSubmit[Form onsubmit Listener] --> PreventDefault[evt.prevent_default()]
|
|
||||||
ButtonClick[Button onclick Listener] --> PreventDefault
|
|
||||||
PreventDefault --> WASMFetch[WASM Reqwest fetch()]
|
|
||||||
end
|
|
||||||
|
|
||||||
DioxusWASM --> EventSystem
|
|
||||||
WASMFetch -- "Content-Type: application/json\nfetch_credentials_include()" --> BackendAPI[NX9-Auth Axum REST API]
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 13. Configuration System
|
# 13. Configuration
|
||||||
|
|
||||||
NX9-Auth loads configuration using a multi-tiered fallback hierarchy:
|
NX9-Auth manages system parameters through a hierarchical configuration system.
|
||||||
|
|
||||||
```
|
### Configuration Precedence Order
|
||||||
1. Explicit CLI Flags (--config /path/to/config.toml)
|
1. Command Line Interface (CLI) Arguments
|
||||||
│
|
2. Environment Variables
|
||||||
▼
|
3. Configuration Files (TOML format)
|
||||||
2. Environment Variables (NX9_SERVER__PORT, NX9_DATABASE__URL)
|
4. Built-in Defaults
|
||||||
│
|
|
||||||
▼
|
|
||||||
3. Local Configuration Files (./config.toml, /etc/nx9-auth/config.toml)
|
|
||||||
│
|
|
||||||
▼
|
|
||||||
4. Compiled Default Fallbacks
|
|
||||||
```
|
|
||||||
|
|
||||||
### Validation & Startup Safeguards
|
Startup execution validates configuration parameters immediately. If configuration paths, database URIs, or security options fail validation, process startup halts with explicit error messages before network ports are bound.
|
||||||
- Configuration loading performs instant fail-fast validation. If database URIs are malformed or TLS configurations are invalid, process execution halts immediately with explicit error logging before binding network ports.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 14. Deployment Architecture
|
# 14. Deployment
|
||||||
|
|
||||||
NX9-Auth is deployed as a single, self-contained Linux executable:
|
NX9-Auth is deployed as a single self-contained executable on Linux systems, supervised by systemd and situated behind a reverse proxy.
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart LR
|
flowchart LR
|
||||||
Internet([Internet / Clients]) --> ReverseProxy[Reverse Proxy\nNginx / Caddy / Traefik\n(TLS Termination)]
|
Internet[Client Traffic] --> ReverseProxy[Reverse Proxy Caddy or Nginx]
|
||||||
ReverseProxy -- HTTP / Unix Socket --> AppService[NX9-Auth Binary\nSystemd Supervised Service]
|
ReverseProxy --> AppService[NX9-Auth Process Systemd Supervised]
|
||||||
AppService <--> SQLite[SQLite Database File\n(WAL Mode)]
|
AppService --> SQLite[SQLite Database Engine]
|
||||||
AppService <--> Postgres[(PostgreSQL Server)]
|
AppService --> Postgres[PostgreSQL Database Engine]
|
||||||
```
|
```
|
||||||
|
|
||||||
### Systemd Process Supervision Example (`nx9-auth.service`)
|
### Process Supervision Overview
|
||||||
```ini
|
Systemd handles process lifetime, automatic restarts, resource limits, and security sandboxing (such as restricting filesystem access and disabling privilege escalation). Standard deployment files reside in `deploy/systemd/nx9-auth.service`.
|
||||||
[Unit]
|
|
||||||
Description=NX9-Auth Identity & Access Management Server
|
|
||||||
After=network.target
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=simple
|
|
||||||
User=nx9-auth
|
|
||||||
Group=nx9-auth
|
|
||||||
ExecStart=/usr/local/bin/nx9-auth serve --config /etc/nx9-auth/config.toml
|
|
||||||
Restart=on-failure
|
|
||||||
RestartSec=5s
|
|
||||||
LimitNOFILE=65536
|
|
||||||
CapabilityBoundingSet=
|
|
||||||
NoNewPrivileges=true
|
|
||||||
ProtectSystem=strict
|
|
||||||
ProtectHome=true
|
|
||||||
ReadWritePaths=/var/lib/nx9-auth
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 15. Repository Directory Layout
|
# 15. Repository Layout
|
||||||
|
|
||||||
```text
|
```text
|
||||||
/
|
/
|
||||||
├── Cargo.toml # Primary Cargo workspace manifest
|
├── Cargo.toml # Primary Cargo workspace configuration
|
||||||
├── Cargo.lock # Dependency lockfile
|
├── Cargo.lock # Dependency version lockfile
|
||||||
├── build.rs # Build script for static asset embedding
|
├── build.rs # Static asset embedding build script
|
||||||
├── README.md # Project documentation overview
|
├── README.md # Project landing documentation
|
||||||
├── LICENSE # Dual license declaration (MIT OR Apache-2.0)
|
├── LICENSE # Dual license declaration
|
||||||
├── LICENSE-MIT # MIT License terms
|
├── LICENSE-MIT # MIT License text
|
||||||
├── LICENSE-APACHE # Apache 2.0 License terms
|
├── LICENSE-APACHE # Apache 2.0 License text
|
||||||
├── src/ # Core backend source directory
|
├── src/ # Core backend source files
|
||||||
│ ├── main.rs # Binary entry point and CLI subcommand dispatcher
|
│ ├── main.rs # Entry point and subcommand router
|
||||||
│ ├── lib.rs # Library root exporting domain modules
|
│ ├── lib.rs # Library root exporting domain modules
|
||||||
│ ├── api/ # Axum REST API handlers and routing table
|
│ ├── api/ # REST API handlers and endpoint routes
|
||||||
│ ├── audit/ # Audit trail logging service and DTOs
|
│ ├── audit/ # Audit trail service and data structures
|
||||||
│ ├── cli/ # Clap CLI subcommand implementations
|
│ ├── cli/ # CLI command parsing logic
|
||||||
│ ├── config/ # Configuration file parsing and environment loaders
|
│ ├── config/ # Configuration file parsing and environment logic
|
||||||
│ ├── db/ # SQLx database abstraction layers and migrations
|
│ ├── db/ # SQLx abstractions and migration files
|
||||||
│ ├── error/ # Strongly typed application error enumerations
|
│ ├── error/ # Application error types
|
||||||
│ ├── identity/ # User, role, group, and tenant management services
|
│ ├── identity/ # User, role, group, and tenant domain services
|
||||||
│ ├── middleware/ # Security headers, authentication, and logging middlewares
|
│ ├── middleware/ # Security header and authentication middlewares
|
||||||
│ ├── runtime/ # Application lifecycle, state machine, and signal hooks
|
│ ├── runtime/ # Lifecycle, state machine, and signal handlers
|
||||||
│ └── security/ # Argon2id, BLAKE3, and rate-limiting modules
|
│ └── security/ # Password hashing, token hashing, and rate limiting
|
||||||
├── ui/ # WebAssembly Frontend crate (Dioxus 0.6)
|
├── ui/ # WebAssembly frontend crate (Dioxus)
|
||||||
│ ├── Cargo.toml # UI package crate manifest
|
├── tests/ # Integration and security test suites
|
||||||
│ ├── index.html # SPA entry point template
|
├── scripts/ # Maintenance and build helper scripts
|
||||||
│ ├── assets/ # Static styling and JavaScript boot loader
|
├── deploy/ # Systemd service files and deployment templates
|
||||||
│ └── src/ # Dioxus components, routes, and services
|
└── docs/ # Architecture documents and technical specifications
|
||||||
├── tests/ # Integration and end-to-end security test suites
|
|
||||||
├── scripts/ # Maintenance, build, and release helper scripts
|
|
||||||
├── deploy/ # Containerization, systemd, and reverse-proxy templates
|
|
||||||
└── docs/ # Architecture guides, ADRs, and technical specifications
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 16. Architectural Roadmap & Future Capabilities
|
# 16. Future Roadmap
|
||||||
|
|
||||||
The following capabilities represent planned architectural extensions:
|
Planned future architectural extensions include:
|
||||||
|
|
||||||
- **OpenID Connect (OIDC) & OAuth2 Provider**: Expanding identity capabilities to act as a full OIDC Authorization Server and Identity Provider (IdP).
|
- **OpenID Connect (OIDC) & OAuth2 Server**: Native implementation enabling NX9-Auth to function as a full OIDC Authorization Server.
|
||||||
- **WebAuthn / FIDO2 Passkeys**: Native passwordless authentication support using browser WebAuthn APIs.
|
- **SAML 2.0 Support**: Enterprise federation support for identity provider integrations.
|
||||||
- **Multi-Factor Authentication (MFA)**: Time-based One-Time Password (TOTP) integration using standard RFC 6238 algorithms.
|
- **SCIM 2.0 Provisioning**: System for Cross-domain Identity Management interface for automated user synchronization.
|
||||||
- **SCIM 2.0 & Directory Sync**: System for Cross-domain Identity Management (SCIM) for automated user provisioning.
|
- **Directory Integration**: LDAP and Active Directory authentication capability.
|
||||||
- **Observability Exports**: OpenTelemetry metrics and tracing exporters for Prometheus and Grafana monitoring stacks.
|
- **Multi-Factor Authentication (MFA)**: TOTP (RFC 6238) and WebAuthn / FIDO2 passkey support.
|
||||||
- **High-Availability Clustering**: Distributed session cache synchronization across multi-region server nodes.
|
- **High-Availability Clustering**: Distributed session cache synchronization across multi-region server nodes.
|
||||||
|
- **Observability Exporters**: Native OpenTelemetry metrics and tracing integration for Prometheus and Grafana monitoring stacks.
|
||||||
Reference in new issue
Block a user