# Authelia API - Development Guide This directory contains the source code for the Authelia API. For production deployment, use the ready-to-use binary in the root directory and follow the installation instructions in the main [README.md](../README.md). A Go-based REST API and management layer that sits alongside an Authelia LXC on Proxmox. Provides a "Source of Truth" in SQLite, handles bulk user onboarding via JSON, and automates synchronization of the Authelia `users_database.yml` file. ## Features - **Sovereign Bootstrap**: Automatically imports existing Authelia users on first run - **Bulk User Management**: Create multiple users via JSON API with automatic password generation - **Real-time Sync**: SQLite changes automatically sync to Authelia's YAML configuration - **SMTP Onboarding**: Send welcome emails using Authelia's SMTP configuration - **Secure API**: Bearer token authentication with bcrypt hashing - **Drop-in Deployment**: Runs alongside existing Authelia installation ## Prerequisites - Authelia v4.38+ installed and configured - Go 1.22+ (for building from source) - SQLite 3 (embedded via pure Go driver) - Systemd (for service management) ## Quick Start 1. **Clone or copy the API to your Authelia directory:** ```bash cd /opt/authelia git clone api ``` 2. **Build the binary:** ```bash cd api go build -o authelia-api ./cmd/server ``` 3. **Run the bootstrap (first time only):** ```bash ./authelia-api --bootstrap ``` 4. **Start the API server:** ```bash ./authelia-api --config /opt/authelia/configuration.yml ``` ## Configuration The API reads Authelia's `configuration.yml` automatically. It looks for: - `session.secret` for initial admin token - `notifier.smtp` for email sending - `authentication_backend.file.path` for user database location ### Environment Variables | Variable | Default | Description | |----------|---------|-------------| | `AUTHELIA_API_DB_PATH` | `./authelia-api.db` | SQLite database path | | `AUTHELIA_API_LISTEN_ADDR` | `127.0.0.1:8080` | API listen address | | `AUTHELIA_API_LOG_LEVEL` | `info` | Log level (debug, info, warn, error) | ## API Reference All endpoints require Bearer token authentication. ### Authentication Get your initial token from the bootstrap process: ```bash # The initial token is the hashed session.secret from Authelia config curl -H "Authorization: Bearer " http://localhost:8080/api/health ``` ### Endpoints #### `POST /api/users/bulk` Create multiple users with generated placeholder passwords. **Request:** ```json [ { "username": "john.doe", "display_name": "John Doe", "email": "john@example.com", "groups": ["users", "developers"] } ] ``` **Response:** ```json { "success": true, "created": 1, "users": [ { "username": "john.doe", "placeholder_password": "random-generated-password", "status": "created" } ] } ``` #### `GET /api/users` List all users with pagination. **Query Parameters:** - `page` (default: 1) - `pageSize` (default: 50) #### `DELETE /api/users/{username}` Remove a user from Authelia. #### `POST /api/admins` Add a new API admin. **Request:** ```json { "name": "admin_name", "token": "raw_bearer_token" } ``` ## How It Works ### Phase 1: Sovereign Bootstrap On first run, the API: 1. Locates Authelia's `configuration.yml` 2. Extracts `session.secret` and hashes it for initial admin token 3. Reads existing `users_database.yml` and imports all users to SQLite 4. Creates the SQLite database as the "Source of Truth" ### Phase 2: Core API - All changes go through the SQLite database first - Password hashing uses `authelia crypto hash generate` for compatibility - Bearer tokens validated against `api_admins` table ### Phase 3: Synchronization Engine - Every SQLite change triggers YAML regeneration - If `watch: true` is disabled in Authelia config, restarts the service - Atomic writes (temp file → rename) prevent corruption ### Phase 4: SMTP Onboarding - Parses SMTP configuration from Authelia config - Sends welcome emails with password reset instructions - Uses Authelia's own SMTP credentials ## Database Schema ### `users` table - `username` TEXT PRIMARY KEY - `displayname` TEXT - `email` TEXT - `password_hash` TEXT (raw Argon2id hash) - `groups` TEXT (JSON array) - `created_at` DATETIME - `updated_at` DATETIME ### `api_admins` table - `id` INTEGER PRIMARY KEY - `name` TEXT UNIQUE - `token_hash` TEXT (bcrypt) - `created_at` DATETIME ### `sync_logs` table - `id` INTEGER PRIMARY KEY - `operation` TEXT - `username` TEXT - `success` BOOLEAN - `error` TEXT - `timestamp` DATETIME ## Deployment ### Systemd Service Create `/etc/systemd/system/authelia-api.service`: ```ini [Unit] Description=Authelia API After=authelia.service Requires=authelia.service [Service] Type=simple User=authelia Group=authelia WorkingDirectory=/opt/authelia ExecStart=/opt/authelia/api/authelia-api --config /opt/authelia/configuration.yml Restart=on-failure RestartSec=5 [Install] WantedBy=multi-user.target ``` Enable and start: ```bash systemctl daemon-reload systemctl enable --now authelia-api ``` ### Backup Considerations The SQLite database (`authelia-api.db`) should be included in your Authelia backups since it's the "Source of Truth". It's created in the same directory as Authelia's configuration by default. ## Security - API only listens on `127.0.0.1` by default (configurable) - Bearer tokens hashed with bcrypt - Input validation on all endpoints - No sensitive data in error responses - SQLite transactions with `IMMEDIATE` mode for concurrency ## Troubleshooting ### "authelia binary not found" Ensure `authelia` is in `$PATH` or set the full path via environment variable. ### "Cannot parse configuration.yml" Check file permissions and YAML syntax. The API needs read access to Authelia's config. ### "SMTP email failing" Verify SMTP credentials in Authelia config and test connectivity. ### "YAML not syncing" Check if `watch: true` is set in Authelia config. If not, the API needs permission to restart the service. ## Development ### Building from Source ```bash cd api go mod download go build -o authelia-api ./cmd/server ``` ### Installing Development Build After building, install with development mode enabled to use the local binary: ```bash # Move binary to root directory (if building in src/) mv authelia-api ../ # Install with development mode cd .. AUTHELIA_API_DEVELOPMENT_MODE=true sudo ./install-authelia-api.sh ``` ### Testing ```bash go test ./... ``` ### Architecture ``` api/ ├── cmd/server/ # Main entry point ├── internal/ # Private packages │ ├── bootstrap/ # Phase 1: Startup logic │ ├── api/ # Phase 2: REST endpoints │ ├── sync/ # Phase 3: YAML synchronization │ ├── smtp/ # Phase 4: Email onboarding │ └── auth/ # Bearer token middleware ├── pkg/ # Public packages │ ├── config/ # Configuration parsing │ ├── database/ # SQLite operations │ └── authelia/ # Authelia binary integration └── migrations/ # Database schema ``` ## License MIT License - See LICENSE file for details. ## Contributing Contributions welcome! Please open issues or pull requests on GitHub.