Initial public release v0.1.0

This commit is contained in:
thakares committed 2026-06-21 20:05:29 +05:30
commit 6c39e0bfbf
87 files changed
+10867

No files matched your search

+86
View File
@@ -0,0 +1,86 @@
# nx9-auth Database Backups & Recovery
Since `nx9-auth` uses SQLite with Write-Ahead Logging (WAL) enabled, standard file copies of `auth.db` during high-concurrency operations can result in corrupted backups. This guide details the correct procedures for backing up and restoring the database safely.
---
## 1. Online Backups (Recommended)
SQLite provides a built-in backup API that safely reads the database and locks it transactionally to capture a consistent snapshot, merging concurrent WAL journals correctly without interrupting the running service.
To perform an online backup:
```bash
# Create backups directory
mkdir -p /var/backups/nx9-auth
# Run SQLite .backup query
sqlite3 /var/lib/nx9-auth/auth.db ".backup /var/backups/nx9-auth/auth_$(date +%F_%H%M%S).db"
# Change ownership and permissions to protect secrets
chown root:root /var/backups/nx9-auth/auth_*.db
chmod 600 /var/backups/nx9-auth/auth_*.db
```
### Automation via Cron
You can automate this daily by adding a cron job to `/etc/cron.daily/nx9-auth-backup`:
```bash
#!/bin/bash
BACKUP_DIR="/var/backups/nx9-auth"
mkdir -p "$BACKUP_DIR"
sqlite3 /var/lib/nx9-auth/auth.db ".backup $BACKUP_DIR/auth_$(date +%F).db"
chmod 600 "$BACKUP_DIR"/auth_*.db
# Keep only last 30 days of backups
find "$BACKUP_DIR" -name "auth_*.db" -mtime +30 -delete
```
Make sure the cron script is executable:
```bash
chmod +x /etc/cron.daily/nx9-auth-backup
```
---
## 2. Offline Backups
If you need to copy the raw database file directly, you **must** stop the service first to ensure all transactions are fully written to the disk and the WAL log is empty:
```bash
# 1. Stop the service
sudo systemctl stop nx9-auth
# 2. Copy the database file
cp /var/lib/nx9-auth/auth.db /var/backups/nx9-auth/auth_offline_$(date +%F).db
# 3. Start the service
sudo systemctl start nx9-auth
```
---
## 3. Database Recovery
To restore the database from a backup:
```bash
# 1. Stop the running service
sudo systemctl stop nx9-auth
# 2. Backup the current corrupted/old database just in case
mv /var/lib/nx9-auth/auth.db /var/lib/nx9-auth/auth.db.bak
# 3. Copy the backup file into place
cp /var/backups/nx9-auth/auth_2026-06-21.db /var/lib/nx9-auth/auth.db
# 4. Correct ownership and permissions
chown nx9-auth:nx9-auth /var/lib/nx9-auth/auth.db
chmod 640 /var/lib/nx9-auth/auth.db
# 5. Start the service
sudo systemctl start nx9-auth
# 6. Run doctor checks to verify integrity of restored database
sudo -u nx9-auth nx9-auth doctor --config /etc/nx9-auth/config.toml
```
+50
View File
@@ -0,0 +1,50 @@
# nx9-auth Performance Benchmarks
This document records the performance profiles, throughput (QPS), and latency percentiles for critical authentication pathways in `nx9-auth`.
These benchmarks were measured using the embedded `bench` binary (`cargo run --bin bench` or `cargo run --release --bin bench`).
---
## Benchmark Results
### 1. Password Verification (Argon2id KDF)
Password verification is CPU-bound and deliberately computationally heavy to protect against offline brute-force attacks.
#### Production Configuration (64 MiB memory, 3 iterations, 1 parallelism)
- **Requests/sec**: `0.63` (highly secure)
- **P50 Latency**: `1578.48 ms`
- **P95 Latency**: `1600.56 ms`
- **P99 Latency**: `1600.56 ms`
#### Fast/Test Configuration (4 MiB memory, 1 iteration, 1 parallelism)
- **Requests/sec**: `32.07`
- **P50 Latency**: `31.15 ms`
- **P95 Latency**: `31.56 ms`
- **P99 Latency**: `31.73 ms`
---
## 2. Session and Token Validation (BLAKE3 Hashing + SQLite)
Session and PAT validation do not run the heavy Argon2id algorithm. Instead, they use BLAKE3 hashing and look up the session/token in SQLite, updating the `last_seen_at`/`last_used_at` timestamps. These paths are extremely fast.
### Session Validation (Cookie authentication)
- **Requests/sec**: `9,259.47`
- **P50 Latency**: `0.10 ms`
- **P95 Latency**: `0.16 ms`
- **P99 Latency**: `0.24 ms`
### Personal Access Token (PAT) Validation
- **Requests/sec**: `9,500.90`
- **P50 Latency**: `0.09 ms`
- **P95 Latency**: `0.16 ms`
- **P99 Latency**: `0.21 ms`
---
## Key Takeaways
1. **Security & Latency Tradeoff**: The password login pathway is computationally heavy (~1.6 seconds) to guarantee state-of-the-art protection against hardware brute-force attacks.
2. **Ultra-Fast Session/PAT Verification**: Once a user is authenticated, microservice session and PAT validation checks are extremely cheap (~0.1ms), enabling low-overhead checks on every inbound API call for consumer systems like BZOD.
+94
View File
@@ -0,0 +1,94 @@
# nx9-auth Deployment Guide
This guide describes how to deploy and upgrade `nx9-auth` on production systems.
## Prerequisites
- Debian- or Ubuntu-compatible Linux system.
- `systemd` init system.
- Root or sudo privileges.
- Pre-compiled `nx9-auth` release binary (get it from the release package `dist/nx9-auth`).
---
## 1. Fresh Installation
To install `nx9-auth` as a systemd service, run the `deploy.sh` script with root privileges:
```bash
sudo bash deploy.sh /path/to/compiled/nx9-auth
```
This script will automatically:
1. Create a dedicated system user `nx9-auth`.
2. Setup system directories:
- Config directory: `/etc/nx9-auth/`
- Data directory: `/var/lib/nx9-auth/`
- Logs directory: `/var/log/nx9-auth/`
3. Copy the binary to `/usr/local/bin/nx9-auth`.
4. Generate a default configuration file `/etc/nx9-auth/config.toml` (if not already present).
5. Install and configure a hardened systemd service file `/etc/systemd/system/nx9-auth.service`.
6. Run database migrations.
7. Start the service.
8. Execute diagnostic check (`doctor` command).
---
## 2. Configuration
Modify `/etc/nx9-auth/config.toml` to customize settings.
```toml
[server]
host = "127.0.0.1"
port = 8655
[database]
path = "/var/lib/nx9-auth/auth.db"
[security]
session_ttl_hours = 24
session_absolute_ttl_days = 30
token_ttl_days = 365
argon2_memory = 65536
argon2_iterations = 3
argon2_parallelism = 1
[audit]
enabled = true
```
After modifying the configuration, restart the service:
```bash
sudo systemctl restart nx9-auth
```
---
## 3. Initial Setup
Once the service is deployed, create your first administrative user:
```bash
sudo -u nx9-auth nx9-auth create-admin my-admin-username --config /etc/nx9-auth/config.toml
```
---
## 4. Upgrade Installation
Upgrading `nx9-auth` is safe and preserves both the configuration and the database.
1. Stop the active service:
```bash
sudo systemctl stop nx9-auth
```
2. Run the `deploy.sh` script pointing to the new binary:
```bash
sudo bash deploy.sh /path/to/new/nx9-auth
```
*Note: Since the configuration file and database already exist, the deploy script will skip creating them, safely leaving existing user accounts, sessions, and logs untouched.*
3. Verify the deployment:
```bash
sudo -u nx9-auth nx9-auth doctor --config /etc/nx9-auth/config.toml
```
+113
View File
@@ -0,0 +1,113 @@
# Running nx9-auth in Docker
This guide explains how to build, run, initialize, and manage `nx9-auth` using Docker and Docker Compose.
---
## 1. Build the Docker Image
To build the Docker image locally:
```bash
docker build -t nx9-auth:0.1.0-rc1 .
```
---
## 2. Local Development Stack (Docker Compose)
The local stack runs with isolated named volumes to store database and configurations without cluttering host folders:
```yaml
services:
nx9-auth:
build: .
container_name: nx9-auth
restart: unless-stopped
ports:
- "8655:8655"
volumes:
- nx9-auth-config:/etc/nx9-auth
- nx9-auth-db:/var/lib/nx9-auth
- nx9-auth-state:/var/log/nx9-auth
- nx9-auth-backups:/var/backups/nx9-auth
environment:
- NX9_AUTH_CONFIG=/etc/nx9-auth/config.toml
healthcheck:
test: ["CMD", "curl", "-fsS", "http://127.0.0.1:8655/health"]
interval: 30s
timeout: 5s
retries: 3
start_period: 15s
volumes:
nx9-auth-config:
nx9-auth-db:
nx9-auth-state:
nx9-auth-backups:
```
### Steps to Run
1. **Start the service in the background**:
```bash
docker compose up -d
```
2. **Initialize config and database** (interactive setup):
```bash
docker exec -it nx9-auth nx9-auth init
```
*Note: If you need to run non-interactively (e.g. in CI), run:*
```bash
docker exec -it nx9-auth nx9-auth init --non-interactive --admin-user admin --admin-password 'YourSecurePasswordHere'
```
3. **Check status**:
Verify the logs or query health check endpoints from the host:
```bash
curl http://127.0.0.1:8655/health
curl http://127.0.0.1:8655/version
```
---
## 3. CasaOS Deployment (Production)
For production deployment on CasaOS, volumes are mapped to the host `/DATA/AppData/nx9-auth` directories:
### Directory Mapping Layout
| Host Path | Container Path | Purpose |
| --- | --- | --- |
| `/DATA/AppData/nx9-auth/config` | `/etc/nx9-auth` | Contains `config.toml` |
| `/DATA/AppData/nx9-auth/db` | `/var/lib/nx9-auth` | Contains `auth.db` |
| `/DATA/AppData/nx9-auth/state` | `/var/log/nx9-auth` | Logs and session files |
| `/DATA/AppData/nx9-auth/backups` | `/var/backups/nx9-auth` | Database snapshots |
### Setup
CasaOS users can import the `compose.casaos.yml` file via the custom install option. After deployment, execute the init flow inside the container:
```bash
docker exec -it nx9-auth nx9-auth init
```
---
## 4. Backups
To trigger a transactionally consistent online SQLite database backup inside the container:
```bash
docker exec -it nx9-auth nx9-auth backup /var/backups/nx9-auth/auth-backup.db
```
The backup will be written directly to `/var/backups/nx9-auth/auth-backup.db` inside the container, which maps to the host's backups directory (e.g. `./backups/` or `/DATA/AppData/nx9-auth/backups/`).
---
## 5. Upgrade
To upgrade the container to a newer release:
```bash
docker compose pull
docker compose up -d
```
+113
View File
@@ -0,0 +1,113 @@
# BZOD Consumer Integration Guide
This guide details how BZOD consumes authentication and authorization services provided by `nx9-auth`.
---
## 1. Authentication
To authenticate a user and establish a session, send a `POST` request to `/api/v1/auth/login`.
### Request
- **Method**: `POST`
- **Path**: `/api/v1/auth/login`
- **Headers**: `Content-Type: application/json`
- **Payload**:
```json
{
"username": "admin",
"password": "super_secure_password"
}
```
### Response
- **Status**: `200 OK`
- **Headers**: `Set-Cookie: nx9_session=<session_token>; HttpOnly; Secure; SameSite=Lax; Path=/`
- **Payload**:
```json
{
"success": true
}
```
---
## 2. Session Validation
To validate an existing session cookie and get the authenticated user's profile, roles, and permissions, make a `GET` request to `/api/v1/auth/me`.
### Request
- **Method**: `GET`
- **Path**: `/api/v1/auth/me`
- **Headers**: Include the `nx9_session` cookie in the request.
### Response
- **Status**: `200 OK`
- **Payload**:
```json
{
"user": {
"id": "e4d3a2b1-5c6d-7e8f-9a0b-1c2d3e4f5a6b",
"username": "admin",
"status": "active",
"last_login_at": "2026-06-21T18:09:13Z",
"created_at": "2026-06-20T12:00:00Z"
},
"roles": ["admin"],
"permissions": ["users:create", "users:update", "users:delete", "tokens:create", "tokens:revoke"]
}
```
---
## 3. Personal Access Token (PAT) Authentication
For programmatic API access (service-to-service or CLI usage), clients can authenticate using a Personal Access Token (PAT) passed in the `Authorization` header.
### Request
- **Headers**: `Authorization: Bearer nx9_pat_<64_hex_chars>`
For example:
```bash
curl -H "Authorization: Bearer nx9_pat_29b2fd8c34f0f089..." https://auth.nx9.local/api/v1/auth/me
```
---
## 4. Permissions Mapping
The following table maps BZOD features and features to their required `nx9-auth` permissions:
| BZOD Feature / Action | Required Permission | Description |
|---|---|---|
| Create link | `links:create` | Allows creating new shortened links |
| Delete link | `links:delete` | Allows deleting existing shortened links |
| View link stats | `links:stats` | Allows viewing redirection analytics and link statistics |
| Create user accounts | `users:create` | Allows administrative user creation |
| Modify user status | `users:update` | Allows enabling, disabling, or locking users |
| Delete user accounts | `users:delete` | Allows soft-deleting/disabling users |
---
## 5. Unified Error Payload
All `nx9-auth` errors return a unified JSON payload format mapping to standard HTTP status codes:
```json
{
"error": "Reason for the error",
"code": "error_code"
}
```
### Standard Status Codes & Codes Mapping
| HTTP Status | Code | Description | Example Error |
|---|---|---|---|
| `401 Unauthorized` | `unauthorized` | Credentials are invalid, or session/token is missing/expired | `{"error": "invalid credentials", "code": "unauthorized"}` |
| `403 Forbidden` | `forbidden` | Authenticated user lacks the required permission | `{"error": "insufficient permissions", "code": "forbidden"}` |
| `404 Not Found` | `not_found` | Resource does not exist | `{"error": "resource not found", "code": "not_found"}` |
| `409 Conflict` | `conflict` | Unique constraint violation (e.g. username taken) | `{"error": "conflict: username already taken", "code": "conflict"}` |
| `422 Unprocessable` | `invalid_input` | Request body or payload format is invalid | `{"error": "invalid input: username cannot be empty", "code": "invalid_input"}` |
| `429 Too Many Requests` | `rate_limited` | Rate limit threshold exceeded | `{"error": "too many requests", "code": "rate_limited"}` |
| `500 Internal Error` | `internal_error` | Database query failure or unexpected server error | `{"error": "internal error", "code": "internal_error"}` |