docs(platform): establish implementation-backed documentation baseline
Core Architecture & Invariant CI / validate (push) Successful in 9m42s
Core Architecture & Invariant CI / validate (push) Successful in 9m42s
Replace legacy documentation with a precise, implementation-derived operator manual that accurately reflects current system boundaries. - Define strict orthogonal boundaries between ownership (Core vs Sites), runtime topology, and cross-cutting orchestration - Document the precise GitOps pipeline, webhook admission gates, and flock serialization mechanics - Provide safe operational runbooks for NixOS, systemd, and appctl - Map accurate persistent state boundaries and SOPS secret projections - Remove speculative schemas and destructive operational defaults
This commit is contained in:
1 parent
3f8fb1756b
commit
abf8d8d7e0
8 files changed
+1236
-350
No files matched your search
@@ -1,278 +1,158 @@
|
||||
# 🌐 Traefik Homelab Core
|
||||
# 🌐 Homelab Core — Appliance & Platform Reference
|
||||
|
||||
Welcome to the **Traefik Homelab Core Control Plane** — the central orchestrator, security perimeter, and edge gateway for the `roadtotech.me` homelab cluster.
|
||||
**Homelab Core** is the declarative NixOS appliance and platform foundation for the `roadtotech.me` homelab cluster.
|
||||
|
||||
This repository implements a **Hardened Hub** architecture where routing, SSL termination, identity management, container isolation, and orchestration are managed centrally, while user applications live in independent repositories in `~/Sites`.
|
||||
It provides host operating system configuration, edge routing, automated wildcard TLS certificate issuance, identity and access management, mail transport, container socket isolation, workload orchestration, and continuous GitOps deployment.
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ Architectural Overview & Component Roles
|
||||
## 🏛️ System Architecture & Boundaries
|
||||
|
||||
The infrastructure is strictly divided into two operational tiers:
|
||||
The homelab ecosystem separates **ownership**, **runtime architecture**, and **cross-cutting orchestration**:
|
||||
|
||||
### 1. Ownership: Core vs. Sites
|
||||
* **Core (`~/Core`) owns platform mechanics**: System services, host firewall, edge ingress, security barriers, deployment serialization, and secret distribution.
|
||||
* **Workload Plane (`~/Sites`) owns application intent**: Workloads are self-describing via `app.yaml` and independent `docker-compose.yml` configurations. Workloads declare application intent; Core executes deployment.
|
||||
|
||||
### 2. Runtime Architecture
|
||||
The system operates across four runtime layers:
|
||||
1. **Host Foundation**: Headless NixOS Linux, disk configuration, Docker daemon, systemd daemons, firewall rules, and in-memory secret files under `/run/secrets/`.
|
||||
2. **Edge Gateway**: Traefik (v3.6) reverse proxy terminating wildcard TLS (`*.roadtotech.me`) via Dynu DNS-01 Let's Encrypt validation.
|
||||
3. **Core Platform Services**: Central services in `docker-compose.yml` (Authelia SSO, LLDAP directory, Stalwart mail, SnappyMail, Homepage dashboard, Portainer, Dozzle, Watchtower, Diun, and socket-proxy).
|
||||
4. **Workload Plane**: Independent application stacks in `~/Sites` connected to the platform over the `proxy-net` Docker network.
|
||||
|
||||
### 3. Cross-Cutting Orchestration
|
||||
* **`appctl` CLI & Engine**: Coordinates discovery, environment injection, container lifecycle actions, and Homepage compilation across workloads and Core.
|
||||
* **GitOps Webhook Dispatcher**: Listens on port 9000 (`homelab-gitops.service`), validating incoming Git push webhooks and executing declared deployment actions.
|
||||
|
||||
---
|
||||
|
||||
## 🗺️ System Topology & Network Architecture
|
||||
|
||||
```
|
||||
Internet (roadtotech.me)
|
||||
Internet
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────┐
|
||||
│ Traefik Edge Proxy (:443) │
|
||||
│ (Wildcard Let's Encrypt TLS) │
|
||||
│ Wildcard TLS (*.roadtotech.me│
|
||||
└───────┬───────────────┬───────┘
|
||||
│ │
|
||||
Public Traffic │ │ Auth Guarded
|
||||
Public Traffic │ │ ForwardAuth Protected
|
||||
(e.g., mail, landing) │ │ (authelia-auth@docker)
|
||||
▼ ▼
|
||||
[ Landing / Public ] [ Authelia SSO / 2FA ]
|
||||
[ Public Services ] [ Authelia SSO / 2FA ]
|
||||
│ │ (LDAP -> LLDAP)
|
||||
│ │
|
||||
│ ▼
|
||||
└───────► [ Data Plane Apps ]
|
||||
(Sites: jellyfin, docs, etc.)
|
||||
▼ ▼
|
||||
┌───────────────────────────────┐
|
||||
│ Docker proxy-net │
|
||||
├───────────────────────────────┤
|
||||
│ • Core Services (Homepage, │
|
||||
│ Portainer, Dozzle, etc.) │
|
||||
│ • Workload Apps (~/Sites/*) │
|
||||
└───────────────────────────────┘
|
||||
│
|
||||
(Protected API via TCP:2375)
|
||||
▼
|
||||
┌───────────────────────────────┐
|
||||
│ Docker socket-proxy │
|
||||
│ (socket-net, Read-Only) │
|
||||
└───────────────┬───────────────┘
|
||||
│ (read-only mount)
|
||||
▼
|
||||
/var/run/docker.sock
|
||||
```
|
||||
|
||||
### 1. Control Plane Components (`~/Core`)
|
||||
* **`Traefik` (v3.6):** The edge reverse proxy and SSL terminator. Automatically obtains and maintains Let's Encrypt wildcard certificates (`*.roadtotech.me`, `roadtotech.me`) using the Dynu DNS-01 challenge. Routes incoming HTTP/HTTPS traffic to internal Docker containers over `proxy-net`.
|
||||
* **`socket-proxy` (tecnativa):** Security barrier. Prevents Traefik and other containers from having direct access to `/var/run/docker.sock`, restricting access exclusively to safe container read operations via TCP (`socket-net`).
|
||||
* **`Authelia`:** Single Sign-On (SSO) and Multi-Factor Authentication (2FA) identity gateway. Provides ForwardAuth middleware (`authelia-auth@docker`) that gates administrative dashboards and sensitive applications before traffic touches them.
|
||||
* **`Portainer CE`:** Visual GUI for container inspection, stack lifecycle management, and log tracking.
|
||||
* **`Dozzle`:** Lightweight real-time log viewer for all running containers, protected by Authelia SSO.
|
||||
* **`Watchtower` & `Diun`:** Background daemons responsible for container image update notifications and automated updates.
|
||||
|
||||
### 2. Data Plane Applications (`~/Sites`)
|
||||
User and service applications (e.g. `dashboard`, `docs`, `jellyfin`, `excalidraw`, `gitea`, `mermaid`, `minecraft`, `ollama`, `pgsql`, `mongodb`) live in isolated, dedicated git repositories under `~/Sites`. They integrate with the Core control plane dynamically via the `proxy-net` Docker network and Traefik container labels.
|
||||
### Core Services (`docker-compose.yml`)
|
||||
| Service | Domain / Ingress | Function | Auth Policy |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **`traefik`** | `traefik.roadtotech.me` | Edge reverse proxy, Dynu DNS-01 ACME TLS | Authelia Guard |
|
||||
| **`socket-proxy`** | Internal (`socket-net:2375`) | Read-only Docker API gateway barrier | Internal Only |
|
||||
| **`lldap`** | `users.roadtotech.me` | LDAP directory & user database | Authelia Guard |
|
||||
| **`authelia`** | `auth.roadtotech.me` | Single Sign-On (SSO) & ForwardAuth middleware | Public (Bypass) |
|
||||
| **`stalwart`** | `mail.roadtotech.me` | Mail Server (SMTP/IMAP/JMAP/Sieve) | Native / LLDAP |
|
||||
| **`snappymail`** | `webmail.roadtotech.me` | Webmail client connected to Stalwart | Native / Stalwart |
|
||||
| **`homepage`** | `dashboard.roadtotech.me` | Service portal & system dashboard | Authelia Guard |
|
||||
| **`portainer`** | `portainer.roadtotech.me` | Container management GUI (via socket-proxy) | Authelia Guard |
|
||||
| **`dozzle`** | `logs.roadtotech.me` | Container log viewer (via socket-proxy) | Authelia Guard |
|
||||
| **`watchtower`** | Internal | Automated container image updater | Internal Only |
|
||||
| **`diun`** | Internal | Container image update notifier | Internal Only |
|
||||
|
||||
---
|
||||
|
||||
## 🔒 Security Model & Secrets Architecture
|
||||
## ⚡ Quick Start & Operator Workflows
|
||||
|
||||
The security model is built on zero hardcoded secrets and defense-in-depth:
|
||||
|
||||
```text
|
||||
[nixos/secrets.yaml] (Encrypted with SOPS + age keys)
|
||||
│
|
||||
▼ (Decrypted at boot by sops-nix using host SSH key)
|
||||
[/run/secrets/rendered/homeserver.env] & [/run/secrets/rendered/traefik-deployments.env]
|
||||
│
|
||||
▼ (Fed via --env-file and appctl)
|
||||
[Core & Sites Containers]
|
||||
```
|
||||
|
||||
1. **SOPS & sops-nix Integration:** All sensitive tokens (Dynu API key, Authelia session secrets, JWT keys, database passwords) are encrypted in `nixos/secrets.yaml` and decrypted by NixOS at runtime into in-memory `/run/secrets/` and `/run/secrets/rendered/`.
|
||||
2. **Edge TLS & HSTS:** All external traffic is forced over HTTPS using Let's Encrypt wildcard certificates with strict redirect schemes (`https-redirect@docker`).
|
||||
3. **Authelia ForwardAuth:** Applications that require authentication declare `traefik.http.routers.<name>.middlewares=authelia-auth@docker`, delegating identity verification to Authelia.
|
||||
4. **Socket Isolation:** Direct Docker daemon sockets are completely hidden behind `socket-proxy`.
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Orchestration with `appctl`
|
||||
|
||||
Applications in `~/Sites` are managed using the custom `appctl` CLI tool located in `scripts/appctl`.
|
||||
|
||||
### Key Commands:
|
||||
### Host & System Operations
|
||||
```bash
|
||||
# List all application stacks with runtime container health and Git sync status
|
||||
# Rebuild and switch NixOS configuration
|
||||
sudo nixos-rebuild switch --flake ~/Core#server
|
||||
# or use the built-in shell alias:
|
||||
nix-switch
|
||||
|
||||
# Inspect systemd platform services
|
||||
systemctl status homeserver-core.service # Core Compose stack
|
||||
systemctl status homelab-gitops.service # GitOps webhook engine
|
||||
systemctl status dynu-monitor.service # Smart DDNS IP monitor
|
||||
systemctl status dynu-monitor.timer # DDNS timer (every 30m)
|
||||
```
|
||||
|
||||
### Workload Management (`appctl`)
|
||||
```bash
|
||||
# List all application stacks with container health and Git tracking status
|
||||
appctl list
|
||||
|
||||
# Fetch upstream git changes across all repositories before rendering status
|
||||
appctl list --fetch
|
||||
# Fetch upstream changes across all repos and inspect with SSL certificates
|
||||
appctl list --fetch --ssl --core
|
||||
|
||||
# List all applications AND core control plane services
|
||||
appctl list --core
|
||||
|
||||
# Display comprehensive metadata, routing, environment, and Git diagnostics
|
||||
appctl info docs
|
||||
# Inspect full diagnostic metadata for a service
|
||||
appctl info jellyfin
|
||||
|
||||
# Start, stop, or restart an application stack
|
||||
# Start, stop, or restart an application or Core service
|
||||
appctl up docs
|
||||
appctl down jellyfin
|
||||
appctl restart dash
|
||||
appctl down mongodb
|
||||
appctl restart traefik
|
||||
|
||||
# Full atomic stack upgrade (clean check -> git pull --ff-only -> docker compose pull -> docker compose up -d -> appctl sync)
|
||||
# Sequential stack update (clean working tree check -> git pull -> compose pull -> up -> sync)
|
||||
appctl update docs
|
||||
appctl update core
|
||||
appctl update all
|
||||
|
||||
# Validate resolved docker compose configuration
|
||||
appctl config docs
|
||||
|
||||
# Synchronize Homepage dashboard services.yaml from app.yaml manifests
|
||||
# Recompile Homepage services.yaml from active app.yaml manifests
|
||||
appctl sync
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚡ Hardened GitOps Continuous Deployment
|
||||
|
||||
Automated deployments are driven by the hardened webhook engine [`scripts/gitops_dispatcher.py`](scripts/gitops_dispatcher.py) managed via the declarative `homelab-gitops.service` systemd unit on port 9000.
|
||||
|
||||
```
|
||||
Webhook Request (:9000)
|
||||
│
|
||||
▼
|
||||
[ 1. Cryptographic HMAC Verification ] ──► (X-Gitea-Signature checked via constant-time compare against SOPS secret)
|
||||
│
|
||||
▼
|
||||
[ 2. Event & Ref Admission ] ──► (Only 'push' to 'refs/heads/*' admitted; PRs/tags rejected)
|
||||
│
|
||||
▼
|
||||
[ 3. Canonical Repository Resolution ] ──► (Logical names resolved against trusted ~/Sites mapping; traversal blocked)
|
||||
│
|
||||
▼
|
||||
[ 4. Manifest & Branch Admission ] ──► (Initial policy check; pushed branch must match declared target)
|
||||
│
|
||||
▼
|
||||
[ 5. Asynchronous Queue & Dispatch ] ──► (Atomic queueing + immediate HTTP 200 return; per-repo flock worker)
|
||||
│
|
||||
▼
|
||||
[ 6. Revision-Consistent Validation ] ──► (Working tree updated to target revision; app.yaml re-validated on-tree)
|
||||
│
|
||||
▼
|
||||
[ 7. Closed Execution & Status ] ──► (Strictly allowlisted actions; persistent .status.json state tracking)
|
||||
```
|
||||
|
||||
### GitOps Security Properties:
|
||||
* **Zero Arbitrary Shell Execution**: The `custom:` command path and `shell=True` invocations are abolished. Only closed, allowlisted actions (`git_pull`, `compose_up`, `compose_build`, `compose_restart`) are executable.
|
||||
* **Cryptographic Admission**: Every incoming webhook must provide an `X-Gitea-Signature` matching the SOPS-managed secret projected to `/run/secrets/gitops/webhook_secret`. Missing, malformed, or mismatching signatures fail closed.
|
||||
* **Trusted Identity Resolution**: Webhooks identify target applications by logical identity (`docs`, `homelab-docs`), never by filesystem path. Paths are canonicalized with strict path traversal and symlink escape defenses.
|
||||
* **Revision-Consistent Manifest Validation**: Manifests and branch authorization policies are re-validated immediately post-pull directly against the target revision working tree, preventing pre-pull configuration hijacking and ensuring deployment policy is strictly derived from the revision being deployed.
|
||||
* **Serialized Asynchronous Execution**: Webhook admissions write atomic pending requests and return HTTP 200 immediately. Detached per-repo workers serialize deployments via non-blocking `flock` and automatically supersede intermediate commits (A deploys, B arrives, C replaces B -> A finishes, then C deploys).
|
||||
* **Intentional Worker State Observation**: Workers record execution status, commit SHAs, timestamps, and error states to `~/.local/state/homelab/gitops/<target>.status.json`.
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Automated Invariant Tests & Continuous Integration
|
||||
|
||||
Architectural boundaries and security invariants are enforced continuously by a machine-executable test suite in [`tests/`](tests/):
|
||||
|
||||
### Test Structure:
|
||||
* **`tests/security/test_gitops_security.py`**: Webhook HMAC signatures, traversal prevention, admission gates, and race condition superseding.
|
||||
* **`tests/security/test_security_invariants.py`**: Docker socket-proxy policies (`POST=0`, `DELETE=0`), container socket isolation, and absence of `privileged: true`.
|
||||
* **`tests/structural/test_repository_structure.py`**: Repository tree integrity, absence of deprecated structures, and public domain license preservation.
|
||||
|
||||
### Running Tests:
|
||||
### Testing & Verification
|
||||
```bash
|
||||
# Run the complete test and invariant suite locally
|
||||
# Run the repository test suite (linting + pytest + nix flake check)
|
||||
./scripts/test
|
||||
|
||||
# Run pure Nix sandbox verification (runs ruff and pytest in an isolated Nix derivation)
|
||||
# Run Nix sandbox flake evaluation and checks
|
||||
nix flake check
|
||||
|
||||
# Enter a development shell with pytest, pyyaml, and ruff preconfigured
|
||||
nix develop
|
||||
```
|
||||
|
||||
### Continuous Integration:
|
||||
Every pull request and push to `main` triggers [`.gitea/workflows/ci.yaml`](.gitea/workflows/ci.yaml), executing `nix flake check` to prevent architectural regressions.
|
||||
|
||||
---
|
||||
|
||||
## 📦 Adding a New Application Stack
|
||||
## 📚 Repository Documentation Index
|
||||
|
||||
Adding a new application to the homelab is completely decentralized:
|
||||
|
||||
### 1. Create the App Directory
|
||||
```bash
|
||||
mkdir -p ~/Sites/homelab-myapp
|
||||
cd ~/Sites/homelab-myapp
|
||||
git init
|
||||
```
|
||||
|
||||
### 2. Create `app.yaml` Manifest
|
||||
Define the application metadata:
|
||||
```yaml
|
||||
name: "myapp"
|
||||
aliases:
|
||||
- "app"
|
||||
domain: "myapp.roadtotech.me"
|
||||
description: "My Awesome New Homelab App"
|
||||
visible: true
|
||||
auth: false
|
||||
networks:
|
||||
- proxy-net
|
||||
env:
|
||||
CUSTOM_VAR: "value"
|
||||
homepage:
|
||||
title: "My App"
|
||||
group: "Knowledge & Notes"
|
||||
icon: "custom.png"
|
||||
container: "myapp"
|
||||
weight: 50
|
||||
```
|
||||
|
||||
### 3. Create `docker-compose.yml`
|
||||
```yaml
|
||||
services:
|
||||
myapp:
|
||||
image: myapp/image:latest
|
||||
container_name: ${CONTAINER_NAME:-myapp}
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- proxy-net
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
# HTTPS Router
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.rule=Host(`${SERVICE_DOMAIN}`)"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.entrypoints=websecure"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.tls=true"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.service=${CONTAINER_NAME:-myapp}-svc"
|
||||
# HTTP to HTTPS Redirect
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}-red.rule=Host(`${SERVICE_DOMAIN}`)"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}-red.entrypoints=web"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}-red.middlewares=https-redirect@docker"
|
||||
# Service Target Port
|
||||
- "traefik.http.services.${CONTAINER_NAME:-myapp}-svc.loadbalancer.server.port=8080"
|
||||
|
||||
networks:
|
||||
proxy-net:
|
||||
name: ${PROXY_NETWORK:-proxy-net}
|
||||
external: true
|
||||
```
|
||||
|
||||
### 4. Deploy and Sync
|
||||
```bash
|
||||
appctl up myapp
|
||||
```
|
||||
`appctl` will start the container, inject standard environment variables, and automatically recompile [`config/homepage/services.yaml`](config/homepage/services.yaml).
|
||||
| Document | Description |
|
||||
| :--- | :--- |
|
||||
| [**Architecture Guide**](docs/architecture.md) | Details system layers, component roles, network isolation, and security controls. |
|
||||
| [**Operator Runbook**](docs/operations.md) | Day-to-day administration, updates, maintenance, troubleshooting, and recovery procedures. |
|
||||
| [**Appctl Reference**](docs/appctl.md) | CLI command reference and consumed `app.yaml` manifest fields. |
|
||||
| [**GitOps Engine**](docs/gitops.md) | Webhook admission pipeline, HMAC authentication, lock serialization, and execution boundaries. |
|
||||
| [**Secrets & State**](docs/secrets-and-state.md) | SOPS encryption, runtime secret projections, user directory management, and persistent storage. |
|
||||
| [**Setup & Provisioning**](docs/setup_guide.md) | Procedures for provisioning a server host and onboarding workloads. |
|
||||
| [**Security Policy**](SECURITY.md) | Security controls, container isolation policies, and threat model. |
|
||||
|
||||
---
|
||||
|
||||
## ❄️ Declarative NixOS Appliance
|
||||
## 🧠 Relationship to Brain Vault
|
||||
|
||||
This repository is a self-contained NixOS appliance. It defines the operating system, Docker infrastructure, firewall rules, automated DDNS updates, and host shell environment in a single flake.
|
||||
|
||||
### Repository NixOS Layout:
|
||||
* **[`flake.nix`](flake.nix)** — Flake entrypoint defining `nixosConfigurations.server`.
|
||||
* **[`nixos/configuration.nix`](nixos/configuration.nix)** — Standalone headless host configuration (locale, SSH, Docker, packages).
|
||||
* **[`nixos/hardware-configuration.nix`](nixos/hardware-configuration.nix)** — Server hardware, disk mounts, and kernel parameters.
|
||||
* **[`nixos/secrets.yaml`](nixos/secrets.yaml)** — SOPS-encrypted secrets for the server.
|
||||
* **[`nixos/modules/homeserver.nix`](nixos/modules/homeserver.nix)** — `homeserver-core.service`, `homelab-gitops.service`, and Authelia secrets.
|
||||
* **[`nixos/modules/traefik-deployments.nix`](nixos/modules/traefik-deployments.nix)** — Traefik applications environment secrets (`traefik-deployments.env`).
|
||||
* **[`nixos/modules/dynu.nix`](nixos/modules/dynu.nix)** — Dynu DDNS smart IP monitor timer and ddclient credentials.
|
||||
* **[`nixos/modules/shell.nix`](nixos/modules/shell.nix)** — Server-tailored bash shell profile, aliases, and utilities.
|
||||
|
||||
### Common Operations:
|
||||
```bash
|
||||
# Rebuild and switch the running system
|
||||
sudo nixos-rebuild switch --flake ~/Core#server
|
||||
# (or use the built-in alias: nix-switch)
|
||||
|
||||
# Inspect core service units
|
||||
systemctl status homeserver-core
|
||||
journalctl -u homeserver-core -f
|
||||
|
||||
# Inspect GitOps webhook dispatcher
|
||||
systemctl status homelab-gitops
|
||||
|
||||
# Inspect dynamic IP monitor
|
||||
systemctl status dynu-monitor
|
||||
```
|
||||
|
||||
### Disaster Recovery:
|
||||
Any clean machine can be provisioned into this server:
|
||||
```bash
|
||||
nixos-install --flake ~/Core#server
|
||||
```
|
||||
* **Repository Documentation (`~/Core/docs/`)**: Describes *what exists* and *how to operate it*. It serves as the operational manual for the current repository.
|
||||
* **Brain Vault (`~/Brain/projects/homelab/`)**: Captures *why it was built this way* — preserving architectural decision records (ADRs), historical trade-off discussions, active roadmaps, and deep debugging discoveries.
|
||||
|
||||
---
|
||||
|
||||
## 📄 License
|
||||
|
||||
This repository is released into the public domain under [The Unlicense](UNLICENSE).
|
||||
+47
-50
@@ -1,62 +1,59 @@
|
||||
# Security Policy & Hardening Overview
|
||||
# 🛡️ Homelab Core — Security Controls & Hardening
|
||||
|
||||
This document outlines the security posture of the **Hardened Private Cloud Hub** and provides guidance on maintaining a secure environment.
|
||||
|
||||
## 🛡️ Implemented Hardening Measures
|
||||
|
||||
### 1. Docker Socket Isolation (Socket-Proxy)
|
||||
The most critical security feature. No container (including Traefik or Portainer) has direct access to the host's `/var/run/docker.sock`.
|
||||
- **Mechanism**: The `socket-proxy` container is the *only* one with access to the real socket.
|
||||
- **Filtering**: It uses HAProxy to filter API calls. Traefik can see containers and networks but cannot create/delete them. Management tools like Watchtower are granted specific POST/DELETE permissions only through this proxy.
|
||||
- **Benefit**: Even if an attacker compromises Traefik, they cannot use the Docker API to spin up a privileged container and take over the host (a common "container breakout" attack).
|
||||
|
||||
### 2. Identity & Access Management (Authelia)
|
||||
- **SSO**: All management tools (Traefik Dash, Dozzle, Portainer) and critical apps (Gitea) are behind Authelia.
|
||||
- **2FA Support**: Authelia supports TOTP (Google Authenticator, etc.) and FIDO2 (Yubikey).
|
||||
- **Forward Auth**: Traefik intercepts all requests and validates the session with Authelia before the request ever reaches the target app.
|
||||
|
||||
### 3. Network Segmentation
|
||||
- **`proxy-net`**: Shared network for Traefik to route traffic to apps.
|
||||
- **`socket-net`**: Highly restricted network for infrastructure-to-socket communication. Application containers are **not** members of this network.
|
||||
|
||||
### 4. Automated Maintenance
|
||||
- **Watchtower**: Automatically updates containers when new security patches are released for their images.
|
||||
|
||||
### 5. GitOps Admission & Trust Boundary Hardening
|
||||
The webhook deployment engine (`scripts/gitops_dispatcher.py`) implements a zero-trust admission model:
|
||||
- **Cryptographic Authentication**: Every request must carry an HMAC-SHA256 signature (`X-Gitea-Signature`) validated in constant-time against a SOPS-managed secret.
|
||||
- **Trusted Repository Resolution**: Payloads cannot specify filesystem paths. Logical repository identities are mapped to local directories with strict regex validation, path traversal defense (`../`), and symlink escape checks.
|
||||
- **Zero Arbitrary Shell Execution**: The `custom:` execution handler and `shell=True` have been eliminated. Only closed, allowlisted actions (`git_pull`, `compose_up`, `compose_build`, `compose_restart`) are executable.
|
||||
- **Serialized Asynchronous Worker**: Admissions write atomic pending states and return HTTP 200 immediately. Non-blocking `flock` workers serialize deployments and supersede obsolete intermediate commits.
|
||||
This document outlines the security controls, container isolation rules, and operational boundaries implemented in **Homelab Core**.
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Potential Attack Vectors & Concerns
|
||||
## 1. Implemented Security Controls
|
||||
|
||||
Despite the hardening, you should remain vigilant about the following:
|
||||
### A. Docker Socket Isolation (`socket-proxy`)
|
||||
* Direct container mounts of `/var/run/docker.sock` are restricted.
|
||||
* Only the dedicated `socket-proxy` container mounts `/var/run/docker.sock:ro`.
|
||||
* State-modifying and execution API endpoints are disabled in HAProxy (`POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`, `COMMIT=0`, `CONFIGS=0`, `DISTRIBUTION=0`, `NODES=0`, `PLUGINS=0`, `SECRETS=0`, `SWARM=0`, `SYSTEM=0`).
|
||||
* Traefik, Portainer, and Dozzle query Docker metrics and metadata via `tcp://socket-proxy:2375` rather than direct socket mounts.
|
||||
|
||||
### 1. Host-Level Security (The Foundation)
|
||||
If an attacker gains SSH access to your host, they have control over the system.
|
||||
- **Action**: Use SSH Keys exclusively (`PermitRootLogin = "no"` is enforced by NixOS). Keep your Nix flake inputs and system updated (`sudo nixos-rebuild switch --flake ~/Core#server`).
|
||||
### B. Identity & Access Management (`lldap` & `authelia`)
|
||||
* **Directory Service**: User accounts and group memberships are stored in LLDAP (`users.roadtotech.me`).
|
||||
* **ForwardAuth**: Traefik intercepts incoming HTTP/HTTPS requests and validates sessions with Authelia (`auth.roadtotech.me`) before routing to protected backends.
|
||||
* **MFA Support**: Supports TOTP and FIDO2 authentication.
|
||||
|
||||
### 2. Application-Specific Vulnerabilities
|
||||
A zero-day exploit in Gitea or Ollama could allow an attacker to execute code *inside* that specific container.
|
||||
- **Mitigation**: Containers run as non-root users where possible. The `socket-proxy` ensures they cannot escape to the host easily.
|
||||
### C. Network Segmentation
|
||||
* **`proxy-net`**: Bridge network connecting Traefik to backend application containers.
|
||||
* **`socket-net`**: Restricted bridge network connecting infrastructure daemons to `socket-proxy`. Workload applications in `~/Sites` are not attached to `socket-net`.
|
||||
|
||||
### 3. Let's Encrypt / ACME Exposure
|
||||
The `acme.json` file contains your private keys.
|
||||
- **Action**: This file is restricted to `chmod 600`. Never share it or commit it to version control.
|
||||
### D. Webhook Admission Controls
|
||||
* **HMAC-SHA256 Signatures**: Webhook requests are verified using `hmac.compare_digest` against `/run/secrets/gitops/webhook_secret`.
|
||||
* **Trusted Name Resolution**: Webhook payloads specify logical repository names; filesystem path traversal (`..`, `/`) and symlink escapes are rejected.
|
||||
* **Non-Shell Execution**: Deployment commands execute as fixed argument lists without `shell=True`. Custom shell commands fail validation closed.
|
||||
* **Revision-Consistent Validation**: Manifest deployment policy is re-validated directly on the deployed commit immediately post-pull.
|
||||
|
||||
### 4. Denial of Service (DDoS)
|
||||
Home connections are vulnerable to bandwidth saturation.
|
||||
- **Mitigation**: Consider using a Cloudflare Tunnel or a VPS-based "Entry Node" if you expect high traffic or targeted attacks.
|
||||
### E. Declarative Secrets Encryption (`sops-nix`)
|
||||
* Secrets are stored encrypted in `nixos/secrets.yaml` using Age keys derived from the host SSH key (`/etc/ssh/ssh_host_ed25519_key`).
|
||||
* Decrypted secrets reside in RAM-backed ephemeral filesystems (`/run/secrets/`, `/run/credentials/`) and are not committed to unencrypted persistent files.
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Security Checklist for Production
|
||||
- [ ] Manage all production secrets declaratively in `nixos/secrets.yaml` encrypted with Age / SOPS.
|
||||
- [ ] Maintain user accounts and group memberships dynamically in LLDAP (`users.roadtotech.me`).
|
||||
- [ ] Verify `X-Gitea-Signature` webhook secret is populated in `nixos/secrets.yaml` (`gitops/webhook_secret`).
|
||||
- [ ] Run `./scripts/test` and `nix flake check` before applying changes to verify structural and security invariants.
|
||||
- [ ] Disable Traefik/Authelia access from the public internet if only local use is needed (via Firewall/IP Whitelisting).
|
||||
- [ ] Ensure `config/letsencrypt/acme.json` is backed up securely but kept private (chmod 600).
|
||||
## 2. Threat Model & Operational Considerations
|
||||
|
||||
### Host Access
|
||||
* SSH root login is disabled (`PermitRootLogin = "no"`). Access is authenticated via ED25519 public keys.
|
||||
* Unneeded services (such as printing, bluetooth, sleep/suspend targets) are disabled at the NixOS configuration level.
|
||||
|
||||
### ACME Certificates
|
||||
* Let's Encrypt keys in `config/letsencrypt/acme.json` are maintained with mode `0600`.
|
||||
|
||||
### Workload Containment
|
||||
* Applications run in dedicated containers attached to `proxy-net`.
|
||||
* Application manifests cannot request arbitrary host commands through the GitOps engine.
|
||||
|
||||
---
|
||||
|
||||
## 3. Verification Checklist
|
||||
|
||||
- [x] Secrets encrypted in `nixos/secrets.yaml` via Age / SOPS.
|
||||
- [x] User identities managed in LLDAP (`users.roadtotech.me`).
|
||||
- [x] `socket-proxy` configured with `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`.
|
||||
- [x] Webhook HMAC signature verification active on port 9000.
|
||||
- [x] Invariant test runner (`./scripts/test`) passing on changes.
|
||||
- [x] `config/letsencrypt/acme.json` permissions set to `0600`.
|
||||
- [x] Host firewall ports restricted to declared services in `nixos/modules/homeserver.nix`.
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
# 📦 Workload Orchestration & `app.yaml` Reference (`appctl`)
|
||||
|
||||
The `appctl` tool is the command-line orchestrator and metadata engine for the **Homelab Core** platform. It coordinates interactions between independent workload repositories in `~/Sites` and platform services in `~/Core`.
|
||||
|
||||
---
|
||||
|
||||
## 1. How `appctl` Works
|
||||
|
||||
`appctl` consists of two cooperating scripts:
|
||||
1. **`scripts/appctl`** (Bash CLI wrapper): Handles command-line arguments, sources secret environment templates, dispatches `docker compose` commands, and provides shell autocompletions.
|
||||
2. **`scripts/appctl_engine.py`** (Python metadata engine): Scans directories in `~/Sites`, parses `app.yaml` manifests, computes Git synchronization status against remotes, queries SSL/TLS certificate validity, and compiles the Homepage dashboard configuration.
|
||||
|
||||
```
|
||||
┌───────────────────────────────┐
|
||||
│ appctl <command> │
|
||||
└───────────────┬───────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────┐
|
||||
│ setup_app_env() │
|
||||
└─────────────┬─────────────┘
|
||||
│
|
||||
┌──────────────────────────┴──────────────────────────┐
|
||||
▼ ▼
|
||||
[ appctl_engine.py resolve ] [ Source Secrets ]
|
||||
Resolves aliases, domain, /run/secrets/traefik-deployments.env
|
||||
and manifest parameters /run/secrets/homeserver.env
|
||||
│ │
|
||||
└──────────────────────────┬──────────────────────────┘
|
||||
▼
|
||||
┌─────────────────────────────┐
|
||||
│ Injected Compose Context │
|
||||
│ • PROXY_NETWORK │
|
||||
│ • SERVICE_DOMAIN / DOMAIN │
|
||||
│ • CONTAINER_NAME │
|
||||
│ • Custom manifest env │
|
||||
└──────────────┬──────────────┘
|
||||
▼
|
||||
┌─────────────────────────────┐
|
||||
│ docker compose <subcommand> │
|
||||
└─────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. CLI Command Reference
|
||||
|
||||
### Status & Inspection
|
||||
|
||||
#### `appctl list` / `appctl status`
|
||||
Lists applications discovered in `~/Sites` with container status, Git synchronization badge, routed domain, and filesystem path.
|
||||
|
||||
**Options**:
|
||||
* `--fetch` (`-f`): Runs `git fetch --quiet` across repositories before computing sync badges.
|
||||
* `--core` (`-c`): Includes Core infrastructure services (`traefik`, `authelia`, `lldap`, `stalwart`, etc.) in the output.
|
||||
* `--ssl` (`-s`): Queries SSL/TLS certificates for each domain and displays status and expiration days.
|
||||
* `--all` (`-a`): Equivalent to `--core`.
|
||||
|
||||
**Example Output**:
|
||||
```text
|
||||
SERVICE STATUS GIT SYNC DOMAIN DIRECTORY
|
||||
------- ------ -------- ------ ---------
|
||||
docs 🟢 Running (1) ✓ Synced docs.roadtotech.me ~/Sites/homelab-docs
|
||||
jellyfin 🟢 Running (1) ✓ Synced jellyfin.roadtotech.me ~/Sites/homelab-jellyfin
|
||||
gitea 🟢 Running (2) ⬇ 1 Behind gitea.roadtotech.me ~/Sites/homelab-gitea
|
||||
mongodb 🔴 Stopped ✓ Synced * mongodb.roadtotech.me ~/Sites/homelab-mongodb
|
||||
```
|
||||
|
||||
#### `appctl ssl [service]`
|
||||
Inspects SSL/TLS certificates over port 443. If a service is specified, shows detailed issuer, subject, and expiration data; otherwise, inspects all homelab domains.
|
||||
|
||||
```bash
|
||||
# Check all domains
|
||||
appctl ssl
|
||||
|
||||
# Check a specific service
|
||||
appctl ssl jellyfin
|
||||
```
|
||||
|
||||
#### `appctl info <service>`
|
||||
Displays diagnostic information for a workload or Core service:
|
||||
* Canonical name, directory, and aliases.
|
||||
* Docker container running status.
|
||||
* Primary routed domain and Authelia guard status.
|
||||
* Git tracking details: branch, upstream remote, uncommitted file count.
|
||||
* Injected environment variable defaults.
|
||||
* Homepage card configuration.
|
||||
* SSL certificate details (when `--ssl` is passed).
|
||||
|
||||
```bash
|
||||
appctl info docs --ssl
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Lifecycle Management
|
||||
|
||||
#### `appctl up <service|core>`
|
||||
Starts the specified service stack in detached mode (`--remove-orphans`).
|
||||
* For a workload in `~/Sites`: starts containers and calls `appctl sync`.
|
||||
* For `core`: starts the entire Core Compose stack using `/run/secrets/homeserver.env`.
|
||||
* For an individual Core service (e.g. `appctl up traefik`): starts that specific container.
|
||||
|
||||
#### `appctl down <service|core>`
|
||||
Stops and removes containers defined in the target's Compose file.
|
||||
|
||||
#### `appctl restart <service|core>`
|
||||
Restarts the target stack or individual container.
|
||||
* `appctl restart docs`: Restarts the docs workload.
|
||||
* `appctl restart core`: Restarts all Core Compose services.
|
||||
* `appctl restart traefik`: Restarts only the Traefik container.
|
||||
|
||||
#### `appctl update <service|core>`
|
||||
Performs a sequential update workflow:
|
||||
1. Checks that the local git working tree is clean (aborts if uncommitted changes exist).
|
||||
2. Runs `git pull --ff-only` to fast-forward the current branch.
|
||||
3. Runs `docker compose pull` to fetch updated container images.
|
||||
4. Runs `docker compose up -d --remove-orphans` to recreate containers.
|
||||
5. Runs `appctl sync` to update the Homepage dashboard.
|
||||
|
||||
#### `appctl pull <service|core>`
|
||||
Pulls latest container images and recreates the target service.
|
||||
|
||||
#### `appctl logs <service|core>`
|
||||
Streams container logs (`docker compose logs -f`).
|
||||
* Supports passing container names: `appctl logs core traefik` or `appctl logs stalwart`.
|
||||
|
||||
#### `appctl config <service|core>`
|
||||
Renders the resolved Docker Compose configuration with all injected variables.
|
||||
|
||||
#### `appctl sync`
|
||||
Scans all `~/Sites/*/app.yaml` manifests and re-generates `config/homepage/services.yaml`.
|
||||
|
||||
#### `appctl completion [bash]`
|
||||
Outputs the bash autocompletion script.
|
||||
|
||||
---
|
||||
|
||||
## 3. `app.yaml` Fields Consumed by `appctl` and GitOps
|
||||
|
||||
`app.yaml` files in `~/Sites` are read by `appctl_engine.py` and `gitops_dispatcher.py` for the following fields:
|
||||
|
||||
```yaml
|
||||
# ── Identity & Routing ────────────────────────────────────────────────────────
|
||||
name: "jellyfin" # Canonical service name (defaults to folder name minus homelab-)
|
||||
aliases: # Alternate CLI aliases
|
||||
- "media"
|
||||
- "movies"
|
||||
domain: "jellyfin.roadtotech.me" # Primary routed domain (defaults to <name>.roadtotech.me)
|
||||
description: "Media Streaming Server"
|
||||
|
||||
# ── Platform Integration ──────────────────────────────────────────────────────
|
||||
visible: true # Display on Homepage dashboard (default: true)
|
||||
auth: false # Authelia ForwardAuth protection (default: false)
|
||||
networks: # Docker networks to join (default: [proxy-net])
|
||||
- proxy-net
|
||||
|
||||
# ── Injected Environment Defaults ─────────────────────────────────────────────
|
||||
# Injected into the Compose environment when appctl commands run
|
||||
env:
|
||||
MEDIA_PATH: "/media"
|
||||
JELLYFIN_TZ: "UTC"
|
||||
JELLYFIN_PUID: "1000"
|
||||
JELLYFIN_PGID: "1000"
|
||||
|
||||
# ── GitOps Deployment Policy ──────────────────────────────────────────────────
|
||||
# Evaluated by scripts/gitops_dispatcher.py upon webhook reception
|
||||
deployment:
|
||||
branch: "main" # Target branch that triggers deployment
|
||||
strategy: "compose" # Deployment strategy (only 'compose' is permitted)
|
||||
actions: # Strictly allowlisted actions
|
||||
- git_pull
|
||||
- compose_up
|
||||
|
||||
# ── Homepage Dashboard Metadata ───────────────────────────────────────────────
|
||||
homepage:
|
||||
title: "Jellyfin" # Card title
|
||||
group: "Media & Productivity" # Group name
|
||||
icon: "jellyfin.png" # Icon name (matched against config/homepage/icons/)
|
||||
container: "jellyfin" # Container name for live status widget
|
||||
weight: 10 # Card sort weight
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Environment Injection & Resolution Precedence
|
||||
|
||||
When `appctl` executes commands against a workload, environment variables are resolved in this sequence:
|
||||
|
||||
1. **Global Secrets & Templates**: Sourced from `/run/secrets/homeserver.env` and `/run/secrets/traefik-deployments.env` (or `/run/secrets/rendered/*` fallbacks).
|
||||
2. **Infrastructure Defaults**:
|
||||
- `PROXY_NETWORK` (defaults to `proxy-net`)
|
||||
- `CERT_RESOLVER` (defaults to `myresolver`)
|
||||
- `DOMAIN_SUFFIX` (defaults to `roadtotech.me`)
|
||||
3. **Application Identity**:
|
||||
- `SERVICE_NAME` = `<canonical-name>`
|
||||
- `CONTAINER_NAME` = `<canonical-name>`
|
||||
- `SERVICE_DOMAIN` = `<resolved-domain>`
|
||||
- `DOMAIN` = `<resolved-domain>`
|
||||
4. **Manifest Variables**: Declared under the `env:` block in `app.yaml`.
|
||||
5. **Local Repository Files**: Sourced from `$APP_DIR/.env` and `$APP_DIR/app.env` if present.
|
||||
|
||||
---
|
||||
|
||||
## 5. Homepage Dashboard Compilation
|
||||
|
||||
When `appctl sync` runs:
|
||||
1. `appctl_engine.py` reads all `~/Sites/*/app.yaml` files.
|
||||
2. Core services (`traefik`, `authelia`, `lldap`, `stalwart`, `snappymail`, `portainer`, `dozzle`) are assigned to `Core Infrastructure`.
|
||||
3. Workload applications with `visible: true` are grouped by their `homepage.group` (ordered: `Core Infrastructure`, `Knowledge & Notes`, `Media & Productivity`, `Development & AI`, `Applications`).
|
||||
4. Custom icons matching files in `config/homepage/icons/` (SVG or PNG) are mapped to `/icons/<name>`.
|
||||
5. The compiled configuration is written to `config/homepage/services.yaml`.
|
||||
@@ -0,0 +1,177 @@
|
||||
# 🏛️ Homelab Core — Architecture & System Design
|
||||
|
||||
This document details the architectural structure, component roles, networking models, and security controls of the **Homelab Core** platform for `roadtotech.me`.
|
||||
|
||||
---
|
||||
|
||||
## 1. System Structure: Ownership vs. Runtime Layers vs. Orchestration
|
||||
|
||||
To understand how the system is organized, three architectural dimensions are distinguished:
|
||||
|
||||
### A. Ownership Boundary
|
||||
* **Core (`~/Core`) owns**: NixOS host configuration, shared platform services, edge ingress, identity boundaries, secrets distribution, and deployment orchestration mechanics.
|
||||
* **Workload Plane (`~/Sites`) owns**: Independent application codebases, application-specific Docker Compose files, application-specific `app.yaml` metadata, and application data/state.
|
||||
|
||||
### B. Four Runtime Layers
|
||||
The runtime environment consists of four functional layers:
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ 1. EDGE GATEWAY & INGRESS │
|
||||
│ Traefik (v3.6) · Let's Encrypt Wildcard TLS · Dynu DNS-01 Provider │
|
||||
└───────────────────────────────────┬────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ 2. CONTROL & PLATFORM SERVICES (Core Compose Stack) │
|
||||
│ Authelia SSO · LLDAP Directory · Stalwart Mail · SnappyMail │
|
||||
│ Homepage Dashboard · Portainer · Dozzle · Watchtower · Diun │
|
||||
│ socket-proxy (Read-Only Docker API Barrier) │
|
||||
└───────────────────────────────────┬────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ 3. WORKLOAD PLANE (~/Sites) │
|
||||
│ Autonomous Workload Repositories (Jellyfin, Docs, Gitea, DBs, etc.) │
|
||||
│ Declarative app.yaml Manifests & Compose Stacks │
|
||||
└───────────────────────────────────┬────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ 4. HOST FOUNDATION │
|
||||
│ NixOS Linux · sops-nix Secrets · Docker Engine · Systemd Units │
|
||||
│ Smart Dynu DDNS Monitor · Host Firewall · /run Secret Projections │
|
||||
└────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### C. Cross-Cutting Orchestration
|
||||
Orchestration coordinates operations across the runtime layers without being a runtime layer itself:
|
||||
* **`appctl` CLI & Metadata Engine (`scripts/appctl`, `scripts/appctl_engine.py`)**: Slices across the Host Foundation (sourcing secrets from `/run/secrets/`), Workload Plane (parsing `~/Sites/*/app.yaml` and driving Docker Compose), and Platform Services (recompiling `config/homepage/services.yaml`).
|
||||
* **GitOps Webhook Dispatcher (`scripts/gitops_dispatcher.py`)**: Governed by the `homelab-gitops.service` systemd unit, it receives webhooks on port 9000, enforces admission policies, and dispatches serialized deployment actions for workloads or data repositories.
|
||||
|
||||
---
|
||||
|
||||
## 2. Component Roles & Operational Boundaries
|
||||
|
||||
### A. Edge Gateway (`traefik`)
|
||||
* **Role**: Ingress proxy for incoming HTTP (80) and HTTPS (443) traffic.
|
||||
* **TLS Management**: Employs Traefik's native ACME resolver using the Dynu DNS-01 challenge provider (`myresolver`) to obtain and renew wildcard certificates for `*.roadtotech.me` and `roadtotech.me`. Certificate data is stored at `config/letsencrypt/acme.json` (mode `0600`).
|
||||
* **Redirection**: Automatically upgrades HTTP traffic to HTTPS via the `https-redirect@docker` middleware.
|
||||
* **Dynamic Routing**: Discovers routers and services dynamically by reading Docker container labels via `socket-proxy` (`tcp://socket-proxy:2375`).
|
||||
|
||||
### B. Security Barrier (`socket-proxy`)
|
||||
* **Role**: Isolates the host Docker daemon socket from direct container access.
|
||||
* **Access Rules**:
|
||||
- Mounted read-only: `/var/run/docker.sock:/var/run/docker.sock:ro`.
|
||||
- State-modifying and execution endpoints disabled: `POST=0`, `DELETE=0`, `BUILD=0`, `EXEC=0`, `COMMIT=0`, `CONFIGS=0`, `DISTRIBUTION=0`, `NODES=0`, `PLUGINS=0`, `SECRETS=0`, `SWARM=0`, `SYSTEM=0`.
|
||||
- Read-only inspection endpoints enabled: `CONTAINERS=1`, `NETWORKS=1`, `SERVICES=1`, `TASKS=1`, `IMAGES=1`, `VOLUMES=1`, `INFO=1`, `EVENTS=1`, `PING=1`, `VERSION=1`.
|
||||
* **Network**: Attached exclusively to `socket-net`. Application containers in `~/Sites` are not attached to `socket-net`.
|
||||
|
||||
### C. Identity & Directory Services (`lldap` & `authelia`)
|
||||
* **`lldap`**: Lightweight LDAP directory service storing user accounts, password hashes, and groups. Web UI exposed at `users.roadtotech.me` (protected by Authelia). SQLite database stored in `config/lldap/data/users.db`.
|
||||
* **`authelia`**: Authentication and SSO gateway (`auth.roadtotech.me`).
|
||||
- Configured with an LDAP authentication backend querying `ldap://lldap:3890`.
|
||||
- Exposes the ForwardAuth endpoint (`/api/verify?rd=https://auth.roadtotech.me/`), registered as the `authelia-auth@docker` Traefik middleware.
|
||||
- Passes user identity headers (`Remote-User`, `Remote-Groups`, `Remote-Email`, `Remote-Name`) upon successful session verification.
|
||||
|
||||
### D. Mail Subsystem (`stalwart` & `snappymail`)
|
||||
* **`stalwart`**: All-in-one mail server handling inbound SMTP (25), SMTPS (465), SMTP Submission (587), IMAPS (993), and ManageSieve (4190).
|
||||
- WebAdmin & JMAP UI accessible at `mail.roadtotech.me` via Traefik.
|
||||
- Authenticates users against the LLDAP directory.
|
||||
- Outbound mail relay configured to route through an external smart host (Brevo SMTP relay via SOPS secrets).
|
||||
* **`snappymail`**: Webmail client accessible at `webmail.roadtotech.me` routing to Stalwart.
|
||||
|
||||
### E. Portal & Observability (`homepage`, `portainer`, `dozzle`)
|
||||
* **`homepage`**: Service dashboard at `dashboard.roadtotech.me`. Synchronized from `app.yaml` manifests in `~/Sites` by `appctl sync`.
|
||||
* **`portainer`**: Container management interface at `portainer.roadtotech.me`, connecting to Docker through `socket-proxy`.
|
||||
* **`dozzle`**: Log viewing interface at `logs.roadtotech.me`, connecting through `socket-proxy`.
|
||||
|
||||
### F. Host Foundation & Daemons
|
||||
* **`homeserver-core.service`**: Systemd unit managing the Core Docker Compose stack (`/home/kiskaadee/Core/docker-compose.yml`) using secrets projected to `/run/secrets/homeserver.env`.
|
||||
* **`homelab-gitops.service`**: Systemd unit listening on port 9000 executing `scripts/gitops_dispatcher.py`.
|
||||
* **`dynu-monitor.service` & `dynu-monitor.timer`**: IP change monitor executing `nixos/scripts/monitor.py` every 30 minutes to detect WAN IP changes and update DNS via `ddclient`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Network Segmentation
|
||||
|
||||
Homelab Core configures two bridge networks:
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ HOST DOCKER ENGINE │
|
||||
├────────────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌──────────────────────────────────────────────────────────────┐ │
|
||||
│ │ proxy-net (Bridge) │ │
|
||||
│ │ │ │
|
||||
│ │ • traefik (router) • authelia (sso) │ │
|
||||
│ │ • lldap (directory) • stalwart (mail) │ │
|
||||
│ │ • snappymail (webmail) • homepage (dashboard) │ │
|
||||
│ │ • portainer (management) • dozzle (logs) │ │
|
||||
│ │ • All User Workloads (~/Sites/*) │ │
|
||||
│ └──────────────────────────────┬───────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ┌──────────────────────────────┴───────────────────────────────┐ │
|
||||
│ │ socket-net (Bridge) │ │
|
||||
│ │ │ │
|
||||
│ │ • socket-proxy (HAProxy :2375) • traefik │ │
|
||||
│ │ • portainer • dozzle │ │
|
||||
│ │ • watchtower • diun │ │
|
||||
│ │ • homepage │ │
|
||||
│ └──────────────────────────────┬───────────────────────────────┘ │
|
||||
│ │ (ro mount) │
|
||||
│ ▼ │
|
||||
│ /var/run/docker.sock │
|
||||
└────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
1. **`proxy-net`**: Ingress routing network. Traefik directs traffic to backend service containers on this network. Workload containers in `~/Sites` join `proxy-net`.
|
||||
2. **`socket-net`**: Isolated Docker socket proxy network. Only Core infrastructure components needing container metadata join this network.
|
||||
|
||||
---
|
||||
|
||||
## 4. Host Firewall & Port Exposure
|
||||
|
||||
The host firewall is configured in `nixos/modules/homeserver.nix`:
|
||||
|
||||
| Port | Protocol | Service | Description | Exposure |
|
||||
| :--- | :--- | :--- | :--- | :--- |
|
||||
| **80** | TCP | Traefik | HTTP Ingress (Redirects to 443) | Public |
|
||||
| **443** | TCP | Traefik | HTTPS Ingress (TLS Termination) | Public |
|
||||
| **22** | TCP | OpenSSH | Host SSH Access (`PermitRootLogin = "no"`) | Host Access |
|
||||
| **2223** | TCP | Gitea SSH | Git over SSH for Workloads & Gitea | Public |
|
||||
| **9000** | TCP | GitOps Webhook | GitOps Webhook Receiver | Public / Gitea |
|
||||
| **25** | TCP | Stalwart | Inbound SMTP | Public |
|
||||
| **465** | TCP | Stalwart | SMTPS (Implicit TLS) | Public |
|
||||
| **587** | TCP | Stalwart | SMTP Submission (STARTTLS) | Public |
|
||||
| **993** | TCP | Stalwart | IMAPS (Secure IMAP) | Public |
|
||||
| **4190** | TCP | Stalwart | ManageSieve (Mail Filters) | Public |
|
||||
|
||||
Application containers in `~/Sites` do not bind host ports directly; they receive traffic routed by Traefik over `proxy-net`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Workload Integration Model
|
||||
|
||||
Workloads in `~/Sites/<app>` integrate with Core through two mechanisms:
|
||||
|
||||
1. **Manifest Metadata (`app.yaml`)**: Declares identity, routed domain, environment variable defaults, homepage card layout, and deployment policy.
|
||||
2. **Compose Configuration (`docker-compose.yml`)**:
|
||||
- Attaches to the external `proxy-net` network.
|
||||
- Declares Traefik routing labels:
|
||||
```yaml
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.http.routers.${CONTAINER_NAME}.rule=Host(`${SERVICE_DOMAIN}`)"
|
||||
- "traefik.http.routers.${CONTAINER_NAME}.entrypoints=websecure"
|
||||
- "traefik.http.routers.${CONTAINER_NAME}.tls=true"
|
||||
- "traefik.http.routers.${CONTAINER_NAME}.service=${CONTAINER_NAME}-svc"
|
||||
- "traefik.http.routers.${CONTAINER_NAME}-red.rule=Host(`${SERVICE_DOMAIN}`)"
|
||||
- "traefik.http.routers.${CONTAINER_NAME}-red.entrypoints=web"
|
||||
- "traefik.http.routers.${CONTAINER_NAME}-red.middlewares=https-redirect@docker"
|
||||
- "traefik.http.services.${CONTAINER_NAME}-svc.loadbalancer.server.port=8080"
|
||||
# If auth is required:
|
||||
- "traefik.http.routers.${CONTAINER_NAME}.middlewares=authelia-auth@docker"
|
||||
```
|
||||
3. **Execution**: The `appctl` CLI and GitOps dispatcher supply environment variables (such as `SERVICE_DOMAIN`, `CONTAINER_NAME`, and projected secrets) when invoking Docker Compose.
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
# ⚡ Homelab Core — GitOps Continuous Deployment Engine
|
||||
|
||||
Homelab Core includes an automated GitOps deployment engine implemented in [`scripts/gitops_dispatcher.py`](../scripts/gitops_dispatcher.py). It processes Git push webhooks from Gitea (or external Git forges) and executes declared deployment actions for workloads in `~/Sites` or data vaults (such as `~/Brain`).
|
||||
|
||||
---
|
||||
|
||||
## 1. Architectural Model
|
||||
|
||||
The GitOps engine is invoked via the `homelab-gitops.service` systemd unit running on internal/firewall port 9000:
|
||||
|
||||
```
|
||||
Webhook Request (:9000)
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ 1. Cryptographic HMAC-SHA256 Verification │
|
||||
│ Constant-time comparison with SOPS secret │
|
||||
└───────────────────────┬───────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ 2. Event & Ref Format Admission │
|
||||
│ Admits 'push' to 'refs/heads/*' │
|
||||
│ Rejects PRs, issues, releases, and tags │
|
||||
└───────────────────────┬───────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ 3. Canonical Repository Identity Resolution │
|
||||
│ Maps logical names to trusted local paths │
|
||||
│ Rejects path traversal & symlink escapes │
|
||||
└───────────────────────┬───────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ 4. Pre-Pull Manifest & Branch Policy Check │
|
||||
│ Validates app.yaml & matches target branch │
|
||||
└───────────────────────┬───────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ 5. Atomic Enqueue & Immediate HTTP 200 │
|
||||
│ Writes pending state & spawns async worker │
|
||||
└───────────────────────┬───────────────────────┘
|
||||
│
|
||||
▼ (Detached Worker Process)
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ 6. Serialized Worker & Lock Acquisition │
|
||||
│ Non-blocking flock; supersedes stale queue │
|
||||
└───────────────────────┬───────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ 7. Revision-Consistent Validation & Execution │
|
||||
│ git pull -> re-validate manifest on-tree │
|
||||
│ Execute allowlisted actions -> write status│
|
||||
└───────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Admission & Execution Gates
|
||||
|
||||
### A. Non-Shell Subprocess Execution
|
||||
* The deployment engine contains no `shell=True` subprocess invocations.
|
||||
* Commands are executed as fixed argument lists (e.g. `["docker", "compose", "-f", ..., "up", "-d"]`).
|
||||
* Arbitrary `custom:` shell actions fail validation closed.
|
||||
|
||||
### B. Cryptographic HMAC-SHA256 Authentication
|
||||
* Incoming webhook payloads must provide a signature via `X-Gitea-Signature` or `X-Hub-Signature-256`.
|
||||
* Signatures are verified using HMAC-SHA256 with `hmac.compare_digest` against the shared secret stored in `nixos/secrets.yaml` (projected to `/run/secrets/gitops/webhook_secret`).
|
||||
* Missing, empty, or mismatched signatures are rejected.
|
||||
|
||||
### C. Trusted Repository Resolution
|
||||
* Webhook payloads identify targets by logical name (e.g. `docs`, `homelab-docs`), never by raw filesystem path.
|
||||
* The engine resolves names against a trusted mapping derived from:
|
||||
1. Authoritative Data Vaults (`~/Brain` via aliases `second-brain`, `Brain`, `brain`).
|
||||
2. Workload directories in `~/Sites` by parsing `app.yaml`.
|
||||
* **Input Validation**: Names must match `^[a-zA-Z0-9][a-zA-Z0-9._-]*$`. Slashes, backslashes, and `..` are rejected.
|
||||
* **Containment Check**: Resolved target paths must reside within `~/Sites` or `~/Brain`. Symlinks pointing outside these roots are rejected.
|
||||
|
||||
### D. Revision-Consistent Manifest Validation
|
||||
* When a webhook is admitted, an initial policy check verifies that the pushed branch matches the declared `deployment.branch`.
|
||||
* After `git pull --ff-only` runs, the working tree reflects the newly pulled commit.
|
||||
* The engine **re-reads and re-validates `app.yaml` from the newly pulled working tree** before running subsequent container actions (`compose_up`, `compose_build`, etc.).
|
||||
* If the pulled commit introduces an invalid action, unsupported strategy, or changes the target branch away from the pushed branch, deployment is aborted.
|
||||
|
||||
---
|
||||
|
||||
## 3. Asynchronous Queueing, Serialization & Superseding
|
||||
|
||||
To avoid blocking HTTP connections and handle overlapping pushes:
|
||||
|
||||
1. **Immediate HTTP 200 Return**: Upon passing admission, the dispatcher writes a pending file (`~/.local/state/homelab/gitops/<target>.pending.json`), spawns a detached worker (`--worker <target>`), and returns HTTP 200.
|
||||
2. **Per-Target `flock` Serialization**: The worker acquires an exclusive non-blocking `fcntl.flock` on `~/.local/state/homelab/gitops/<target>.lock`. If a worker is already running for this target, the second worker exits safely while the running worker continues to drain the pending file.
|
||||
3. **Commit Superseding**:
|
||||
- Commit A begins deploying.
|
||||
- Commit B arrives and is written to the pending file.
|
||||
- Commit C arrives while A is still deploying; C overwrites B in the pending file.
|
||||
- Commit A completes; the worker processes C, skipping intermediate commit B.
|
||||
|
||||
---
|
||||
|
||||
## 4. Manifest Deployment Configuration (`app.yaml`)
|
||||
|
||||
Workload repositories declare their deployment policy under the `deployment` block in `app.yaml`:
|
||||
|
||||
```yaml
|
||||
deployment:
|
||||
branch: "main" # Target branch that triggers deployment
|
||||
strategy: "compose" # Deployment strategy (only 'compose' is permitted)
|
||||
actions: # Strictly allowlisted actions
|
||||
- git_pull # Pulls latest branch revision (--ff-only)
|
||||
- compose_up # Runs docker compose up -d --remove-orphans
|
||||
```
|
||||
|
||||
### Allowlisted Deployment Actions
|
||||
* **`git_pull`**: Executes `git -C <target> pull --ff-only origin <branch>`.
|
||||
* **`compose_up`**: Executes `docker compose -f <compose_file> up -d --remove-orphans`.
|
||||
* **`compose_build`**: Executes `docker compose -f <compose_file> build` followed by `compose_up`.
|
||||
* **`compose_restart`**: Executes `docker compose -f <compose_file> restart`.
|
||||
|
||||
Any action outside this list causes manifest validation to fail closed.
|
||||
|
||||
---
|
||||
|
||||
## 5. Execution State & Monitoring
|
||||
|
||||
Each deployment records its result to a status file:
|
||||
|
||||
**Path**: `~/.local/state/homelab/gitops/<target>.status.json`
|
||||
|
||||
**Example Content**:
|
||||
```json
|
||||
{
|
||||
"target": "homelab-docs",
|
||||
"branch": "main",
|
||||
"commit_sha": "d4f8a1e2c3b5a7",
|
||||
"success": true,
|
||||
"timestamp": "2026-09-16T12:00:00+00:00"
|
||||
}
|
||||
```
|
||||
|
||||
### Diagnostics & Manual Invocations
|
||||
```bash
|
||||
# View live webhook dispatcher logs
|
||||
journalctl -u homelab-gitops -f
|
||||
|
||||
# Inspect deployment status for a service
|
||||
cat ~/.local/state/homelab/gitops/homelab-docs.status.json
|
||||
|
||||
# Trigger a local manual deployment run
|
||||
python3 ~/Core/scripts/gitops_dispatcher.py --repo docs --branch main
|
||||
```
|
||||
@@ -0,0 +1,281 @@
|
||||
# 🛠️ Homelab Core — Operator Runbook & Procedures
|
||||
|
||||
This document contains operational procedures, system maintenance workflows, diagnostic commands, and recovery runbooks for administering **Homelab Core**.
|
||||
|
||||
---
|
||||
|
||||
## 1. System Lifecycle & NixOS Administration
|
||||
|
||||
The host system runs NixOS configured declaratively via the flake in `~/Core`.
|
||||
|
||||
### Rebuilding the System Configuration
|
||||
After modifying any file in `nixos/` (including `configuration.nix`, `hardware-configuration.nix`, or any `nixos/modules/*.nix`), apply changes to the running host:
|
||||
|
||||
```bash
|
||||
# Using the built-in shell alias:
|
||||
nix-switch
|
||||
|
||||
# Or using the explicit command:
|
||||
sudo nixos-rebuild switch --flake ~/Core#server
|
||||
```
|
||||
|
||||
### Dry Build Validation & Rollback
|
||||
```bash
|
||||
# Validate build without activating (catches evaluation and syntax errors)
|
||||
nix flake check
|
||||
nix build .#nixosConfigurations.server.config.system.build.toplevel --no-link
|
||||
|
||||
# Roll back to the previous generation if needed
|
||||
sudo nixos-rebuild switch --rollback
|
||||
```
|
||||
|
||||
### System Maintenance & Disk Space Management
|
||||
```bash
|
||||
# Check disk usage across partitions
|
||||
df -h
|
||||
|
||||
# Delete older system generations (older than 7 days)
|
||||
sudo nix-env --delete-generations +7d --profile /nix/var/nix/profiles/system
|
||||
|
||||
# Prune unreachable Nix store paths
|
||||
sudo nix-collect-garbage -d
|
||||
|
||||
# Prune old Docker resources (only containers stopped for >7 days)
|
||||
docker system prune -a --volumes --filter "until=168h"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Managing Core Systemd Services
|
||||
|
||||
Homelab Core runs several platform services managed by systemd:
|
||||
|
||||
### `homeserver-core.service` (Core Compose Stack)
|
||||
Manages the lifecycle of Traefik, Authelia, LLDAP, Stalwart, SnappyMail, Homepage, Portainer, Dozzle, Watchtower, and Diun.
|
||||
|
||||
```bash
|
||||
# Check service status
|
||||
systemctl status homeserver-core
|
||||
|
||||
# View startup and runtime logs
|
||||
journalctl -u homeserver-core -f
|
||||
|
||||
# Restart the entire Core stack
|
||||
sudo systemctl restart homeserver-core
|
||||
|
||||
# Stop or Start the Core stack
|
||||
sudo systemctl stop homeserver-core
|
||||
sudo systemctl start homeserver-core
|
||||
```
|
||||
|
||||
### `homelab-gitops.service` (Dynamic GitOps Webhook)
|
||||
Listens on port 9000 for Gitea webhook requests and dispatches automated deployments.
|
||||
|
||||
```bash
|
||||
# Check status and port binding
|
||||
systemctl status homelab-gitops
|
||||
|
||||
# Stream webhook reception and deployment worker logs
|
||||
journalctl -u homelab-gitops -f -n 50
|
||||
|
||||
# Restart the webhook dispatcher daemon
|
||||
sudo systemctl restart homelab-gitops
|
||||
```
|
||||
|
||||
### `dynu-monitor.service` & `dynu-monitor.timer` (Smart DDNS)
|
||||
Runs every 30 minutes to detect WAN IP address changes and trigger `ddclient`.
|
||||
|
||||
```bash
|
||||
# Check next scheduled timer execution
|
||||
systemctl list-timers dynu-monitor.timer
|
||||
|
||||
# Check last monitor run status and output
|
||||
systemctl status dynu-monitor.service
|
||||
|
||||
# Manually trigger an immediate IP check
|
||||
sudo systemctl start dynu-monitor.service
|
||||
|
||||
# View historical WAN IP transitions log
|
||||
tail -n 20 /var/lib/dynu/ip_history.jsonl
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Workload Lifecycle Operations (`appctl`)
|
||||
|
||||
Applications in `~/Sites` are managed with the `appctl` CLI.
|
||||
|
||||
### Inspection & Status
|
||||
```bash
|
||||
# Check status of all applications and their Git tracking state
|
||||
appctl list
|
||||
|
||||
# Fetch remote changes from Git remotes before rendering status
|
||||
appctl list --fetch
|
||||
|
||||
# Check applications and Core infrastructure services together
|
||||
appctl list --core
|
||||
|
||||
# Check SSL/TLS certificate validity across all domains
|
||||
appctl list --ssl --core
|
||||
|
||||
# Inspect diagnostic details for a specific service
|
||||
appctl info docs
|
||||
appctl info jellyfin --ssl
|
||||
```
|
||||
|
||||
### Deployment & Lifecycle Actions
|
||||
```bash
|
||||
# Start a service stack
|
||||
appctl up docs
|
||||
|
||||
# Gracefully stop a service stack
|
||||
appctl down docs
|
||||
|
||||
# Restart a service stack (re-injects environment)
|
||||
appctl restart docs
|
||||
|
||||
# Restart an individual Core component without restarting the whole host
|
||||
appctl restart traefik
|
||||
appctl restart authelia
|
||||
|
||||
# Sequential stack update (clean working tree check -> git pull -> compose pull -> up -> sync)
|
||||
appctl update docs
|
||||
appctl update core
|
||||
|
||||
# Stream live container logs
|
||||
appctl logs docs
|
||||
appctl logs -f stalwart
|
||||
|
||||
# View resolved Docker Compose configuration
|
||||
appctl config docs
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. User Identity & Access Management (LLDAP & Authelia)
|
||||
|
||||
User accounts and group memberships are managed dynamically in **LLDAP** rather than static configuration files.
|
||||
|
||||
### Accessing the Directory
|
||||
1. Open `https://users.roadtotech.me` in your browser.
|
||||
2. Authenticate using your admin credentials (`admin` / password configured in `nixos/secrets.yaml`).
|
||||
3. From the LLDAP UI, you can:
|
||||
- Create and delete user accounts.
|
||||
- Reset user passwords.
|
||||
- Manage user email addresses.
|
||||
- Assign users to groups (e.g. `admin`, `users`, `media`).
|
||||
|
||||
### Authelia Session & Authentication
|
||||
* **URL**: `https://auth.roadtotech.me`
|
||||
* **Session Lifetime**: 7 days maximum session, 3 days inactivity timeout.
|
||||
* **ForwardAuth Guard**: Applications requiring authentication attach the `authelia-auth@docker` middleware.
|
||||
|
||||
---
|
||||
|
||||
## 5. Troubleshooting Common Failure Modes
|
||||
|
||||
### A. SSL/TLS Certificate Failures (Let's Encrypt / Dynu)
|
||||
* **Symptom**: Browser reports `NET::ERR_CERT_AUTHORITY_INVALID` or self-signed Traefik default certificate.
|
||||
* **Diagnosis**:
|
||||
1. Verify certificate status: `appctl ssl <service>` or `appctl list --ssl`.
|
||||
2. Inspect Traefik logs: `appctl logs traefik | grep -i acme`.
|
||||
3. Verify Dynu API key is valid and not rate-limited.
|
||||
4. Check `config/letsencrypt/acme.json` permissions (must be `0600`).
|
||||
* **Recovery**:
|
||||
```bash
|
||||
# Check acme.json permissions
|
||||
ls -la ~/Core/config/letsencrypt/acme.json
|
||||
chmod 600 ~/Core/config/letsencrypt/acme.json
|
||||
|
||||
# Restart Traefik to trigger challenge retry
|
||||
appctl restart traefik
|
||||
```
|
||||
|
||||
### B. Dynamic DNS (WAN IP) Drift
|
||||
* **Symptom**: External domain `roadtotech.me` does not resolve to the current ISP WAN address.
|
||||
* **Diagnosis**:
|
||||
```bash
|
||||
# Check current public IP vs resolved DNS IP
|
||||
curl -s https://api.ipify.org
|
||||
dig +short roadtotech.me @1.1.1.1
|
||||
|
||||
# Check dynu-monitor logs
|
||||
systemctl status dynu-monitor
|
||||
journalctl -u dynu-monitor -n 30
|
||||
```
|
||||
* **Recovery**:
|
||||
```bash
|
||||
# Trigger manual IP update run
|
||||
sudo systemctl start dynu-monitor
|
||||
```
|
||||
|
||||
### C. Docker Socket Communication Errors
|
||||
* **Symptom**: Traefik fails to discover routers, or Dozzle/Portainer shows "Cannot connect to Docker daemon".
|
||||
* **Diagnosis**:
|
||||
```bash
|
||||
# Verify socket-proxy is running and healthy
|
||||
docker ps -f name=socket-proxy
|
||||
|
||||
# Verify socket-proxy logs
|
||||
appctl logs socket-proxy
|
||||
|
||||
# Test internal socket-proxy connectivity from another container
|
||||
docker exec -it traefik wget -qO- http://socket-proxy:2375/version
|
||||
```
|
||||
* **Recovery**:
|
||||
```bash
|
||||
appctl restart socket-proxy
|
||||
appctl restart traefik
|
||||
```
|
||||
|
||||
### D. GitOps Deployment Stuck or Failed
|
||||
* **Symptom**: Pushed commit to Gitea did not deploy or container is in an inconsistent state.
|
||||
* **Diagnosis**:
|
||||
```bash
|
||||
# Check webhook daemon logs
|
||||
journalctl -u homelab-gitops -f -n 50
|
||||
|
||||
# Check execution status file for the target service
|
||||
cat ~/.local/state/homelab/gitops/<service>.status.json
|
||||
|
||||
# Check if a lock file is held
|
||||
ls -la ~/.local/state/homelab/gitops/
|
||||
```
|
||||
* **Recovery**:
|
||||
```bash
|
||||
# Manually run deployment via appctl
|
||||
appctl update <service>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Backup & Disaster Recovery
|
||||
|
||||
### Critical Persistent State Locations
|
||||
To back up the homelab, create secure snapshots of the following state directories:
|
||||
|
||||
| Component | Host Path | Description |
|
||||
| :--- | :--- | :--- |
|
||||
| **Secrets Key** | `/etc/ssh/ssh_host_ed25519_key` | Host SSH key used by sops-nix to decrypt secrets |
|
||||
| **Encrypted Secrets** | `~/Core/nixos/secrets.yaml` | Encrypted secrets source |
|
||||
| **SSL Certificates** | `~/Core/config/letsencrypt/acme.json` | Active Let's Encrypt certificates |
|
||||
| **User Directory** | `~/Core/config/lldap/data/` | LLDAP SQLite database (`users.db`) |
|
||||
| **Auth Database** | `~/Core/config/authelia/db.sqlite3` | Authelia session database |
|
||||
| **Mail Storage** | `~/Core/config/stalwart/` | Stalwart database, mailboxes, and DKIM keys |
|
||||
| **Webmail State** | `~/Core/config/snappymail/data/` | SnappyMail configuration and sessions |
|
||||
| **Dashboard State** | `~/Core/config/homepage/` | Homepage configuration and custom icons |
|
||||
|
||||
### Host Recovery Requirements
|
||||
To bring up a replacement host from version control:
|
||||
1. Boot the target system with a NixOS installation medium and configure partitions according to `nixos/hardware-configuration.nix`.
|
||||
2. **Restore the host SSH private key** to `/etc/ssh/ssh_host_ed25519_key` (mode `0600`) before running `nixos-install`, as `sops-nix` requires this key during system evaluation and activation.
|
||||
3. Install NixOS targeting the server flake:
|
||||
```bash
|
||||
nixos-install --flake /mnt/home/kiskaadee/Core#server
|
||||
reboot
|
||||
```
|
||||
4. Restore persistent data directories (`config/` backups) and start the Core stack:
|
||||
```bash
|
||||
sudo systemctl start homeserver-core
|
||||
```
|
||||
@@ -0,0 +1,120 @@
|
||||
# 🔒 Homelab Core — Secrets Management & Persistent State
|
||||
|
||||
This document explains the secrets distribution architecture, runtime projection mechanisms, user directory model, and persistent state boundaries for **Homelab Core**.
|
||||
|
||||
---
|
||||
|
||||
## 1. Secrets Management Policy
|
||||
|
||||
* **No Plaintext Secrets in Git**: All sensitive credentials, API keys, tokens, and private keys are encrypted at rest using **Mozilla SOPS** with **Age keys** derived from the server's SSH host key.
|
||||
* **In-Memory Projections**: Secret files are decrypted at boot by **`sops-nix`** into an ephemeral in-memory filesystem (`/run/secrets/` and `/run/credentials/`) and are not committed to unencrypted persistent storage.
|
||||
|
||||
---
|
||||
|
||||
## 2. Secrets Lifecycle & Projection Architecture
|
||||
|
||||
```text
|
||||
[nixos/secrets.yaml] (Encrypted with Age / SOPS)
|
||||
│
|
||||
▼ (Decrypted at boot by sops-nix using /etc/ssh/ssh_host_ed25519_key)
|
||||
┌──────┴─────────────────────────────────────────────────────────────────┐
|
||||
│ In-Memory Projections (/run/secrets/ & /run/credentials/) │
|
||||
├────────────────────────────────────────────────────────────────────────┤
|
||||
│ 1. /run/secrets/homeserver.env │
|
||||
│ -> Consumed by homeserver-core.service & Core docker-compose.yml │
|
||||
│ │
|
||||
│ 2. /run/secrets/traefik-deployments.env │
|
||||
│ -> Consumed by appctl to inject secrets into Sites workloads │
|
||||
│ │
|
||||
│ 3. /run/secrets/gitops/webhook_secret │
|
||||
│ -> Consumed by homelab-gitops.service for HMAC verification │
|
||||
│ │
|
||||
│ 4. /run/credentials/ddclient.service/ddclient.conf │
|
||||
│ -> Consumed by systemd ddclient service │
|
||||
│ │
|
||||
│ 5. /run/secrets/pdf_decrypt_password │
|
||||
│ -> Consumed by shell pdf_dc utility │
|
||||
└────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Projected Secret Templates
|
||||
|
||||
### A. Core Platform Environment (`/run/secrets/homeserver.env`)
|
||||
Generated by `nixos/modules/homeserver.nix`. Supplies credentials to the Core Compose stack:
|
||||
* `DOMAIN`: Apex domain (`roadtotech.me`).
|
||||
* `DYNU_API_KEY`: API key for Dynu DNS-01 ACME Let's Encrypt validation.
|
||||
* `ACME_EMAIL`: Account email for Let's Encrypt certificates.
|
||||
* `AUTHELIA_SESSION_SECRET`: Authelia cookie encryption secret.
|
||||
* `AUTHELIA_STORAGE_ENCRYPTION_KEY`: Database encryption key for Authelia SQLite storage.
|
||||
* `AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET`: Reset password token secret.
|
||||
* `LLDAP_JWT_SECRET` & `LLDAP_KEY_SEED`: Cryptographic tokens for LLDAP.
|
||||
* `LLDAP_LDAP_USER_PASS`: Admin password for LLDAP and Authelia LDAP binding.
|
||||
* `SMTP_SERVER`, `SMTP_PORT`, `SMTP_LOGIN`, `SMTP_KEY`: Outbound relay credentials (Brevo) for Stalwart mail transport.
|
||||
|
||||
### B. Workload Deployments Environment (`/run/secrets/traefik-deployments.env`)
|
||||
Generated by `nixos/modules/traefik-deployments.nix`. Projects shared infrastructure secrets and workload credentials that `appctl` sources when orchestrating stacks in `~/Sites` (such as database passwords, API keys, and runner tokens).
|
||||
|
||||
---
|
||||
|
||||
## 4. Secret Modification and Rotation Workflow
|
||||
|
||||
To edit or rotate secrets:
|
||||
|
||||
### 1. Open the Encrypted Secrets File
|
||||
```bash
|
||||
cd ~/Core
|
||||
sops nixos/secrets.yaml
|
||||
```
|
||||
SOPS decrypts the file using your host SSH private key and opens it in your editor.
|
||||
|
||||
### 2. Modify Secret Keys
|
||||
```yaml
|
||||
dynu:
|
||||
api_key: "..."
|
||||
authelia:
|
||||
session_secret: "..."
|
||||
jwt_secret: "..."
|
||||
lldap:
|
||||
admin_password: "..."
|
||||
gitops:
|
||||
webhook_secret: "..."
|
||||
brevo:
|
||||
smtp_login: "..."
|
||||
smtp_key: "..."
|
||||
```
|
||||
|
||||
### 3. Save and Apply Changes
|
||||
Saving the file in your editor automatically re-encrypts it with Age. Apply the updated templates to running services:
|
||||
```bash
|
||||
sudo nixos-rebuild switch --flake ~/Core#server
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. User Directory vs. Static Secrets
|
||||
|
||||
Homelab Core separates **user identity** from **static platform secrets**:
|
||||
|
||||
* **Static Secrets**: Stored in `nixos/secrets.yaml` (system API keys, JWT secrets, database passwords).
|
||||
* **Dynamic User Directory**: User accounts, credentials, and group memberships are managed live in **LLDAP** (`https://users.roadtotech.me`). User account updates do not require editing `secrets.yaml` or rebuilding NixOS.
|
||||
* **Authelia Integration**: Authelia queries LLDAP over LDAP (`ldap://lldap:3890`) at runtime using credentials projected from `/run/secrets/homeserver.env`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Persistent State Map
|
||||
|
||||
| Category | Storage Location | Stored in Git? | Description |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Declarative Config** | `~/Core/nixos/*.nix`, `docker-compose.yml` | ✅ Yes | System and container definitions |
|
||||
| **Encrypted Secrets** | `~/Core/nixos/secrets.yaml` | ✅ Yes (Encrypted) | SOPS Age-encrypted secret source |
|
||||
| **Runtime Secrets** | `/run/secrets/*` | ❌ No (RAM tmpfs) | Ephemeral decrypted environment files |
|
||||
| **SSL Certificates** | `~/Core/config/letsencrypt/acme.json` | ❌ No | Active Let's Encrypt certificates (mode 0600) |
|
||||
| **User Directory** | `~/Core/config/lldap/data/` | ❌ No | LLDAP SQLite database (`users.db`) |
|
||||
| **Auth Database** | `~/Core/config/authelia/db.sqlite3` | ❌ No | Authelia session database |
|
||||
| **Mail Data & Keys** | `~/Core/config/stalwart/` | ❌ No | Stalwart mail storage, DKIM keys, mailboxes |
|
||||
| **Webmail Storage** | `~/Core/config/snappymail/data/` | ❌ No | SnappyMail configuration and sessions |
|
||||
| **Container Volumes** | Docker volume `portainer_data` | ❌ No | Portainer internal metadata |
|
||||
| **DDNS History** | `/var/lib/dynu/ip_history.jsonl` | ❌ No | Historical WAN IP transitions log |
|
||||
| **GitOps State** | `~/.local/state/homelab/gitops/` | ❌ No | Deployment locks, pending JSONs, status logs |
|
||||
+141
-76
@@ -1,108 +1,173 @@
|
||||
# Setup & Secrets Management Guide (Traefik Homelab)
|
||||
# 🚀 Homelab Core — Setup & Provisioning Guide
|
||||
|
||||
This document provides an exhaustive operational guide for configuring, deploying, securing, and maintaining the **Traefik Homelab Core Control Plane** on NixOS.
|
||||
This document describes procedures for provisioning a host machine, bootstrapping **Homelab Core**, and onboarding new application workloads into `~/Sites`.
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ Architectural Overview
|
||||
## 1. Host Provisioning & Bootstrapping
|
||||
|
||||
The core infrastructure runs as a consolidated Docker Compose stack in [`/home/kiskaadee/Core`](file:///home/kiskaadee/Core):
|
||||
### A. Fresh Machine Provisioning via NixOS Install
|
||||
When provisioning bare-metal hardware or a virtual machine from a NixOS Minimal ISO:
|
||||
|
||||
* **[`docker-compose.yml`](file:///home/kiskaadee/Core/docker-compose.yml)**: Root compose specification defining all control plane services (`traefik`, `authelia`, `portainer`, `dozzle`, `watchtower`, `diun`, `socket-proxy`).
|
||||
* **[`config/`](file:///home/kiskaadee/Core/config/)**: Persistent state directories:
|
||||
* `config/letsencrypt/`: Contains SSL certificate storage (`acme.json`).
|
||||
* `config/authelia/`: Contains configuration (`configuration.yml`, `users.yml`) and authentication database (`db.sqlite3`).
|
||||
* `config/diun/`: Diun container update tracking database (`diun.db`).
|
||||
|
||||
---
|
||||
|
||||
## 🔒 Secrets Architecture & SOPS Flow
|
||||
|
||||
All sensitive tokens, encryption keys, and credentials are encrypted using **`sops-nix`** (Mozilla SOPS with age keys derived from the host SSH key). No plaintext secrets exist in any git repository.
|
||||
|
||||
### Secrets Lifecycle:
|
||||
|
||||
```text
|
||||
[nixos/secrets.yaml] (Encrypted with Age)
|
||||
│
|
||||
▼ (Decrypted at boot by sops-nix daemon)
|
||||
1. [/run/secrets/rendered/homeserver.env] --> Fed to Core Compose Stack
|
||||
2. [/run/secrets/rendered/traefik-deployments.env] --> Fed to appctl & App Stacks
|
||||
│
|
||||
▼
|
||||
[Active Docker Containers]
|
||||
1. Partition and format disks according to `nixos/hardware-configuration.nix` (e.g. boot EFI partition and root filesystem).
|
||||
2. Mount partitions under `/mnt`.
|
||||
3. **Restore Host Secrets Key**: Copy the host SSH private key to `/mnt/etc/ssh/ssh_host_ed25519_key` (mode `0600`). This is required because `sops-nix` decrypts `nixos/secrets.yaml` during system activation.
|
||||
4. Clone the Core repository to `/mnt/home/kiskaadee/Core`.
|
||||
5. Run the NixOS installer:
|
||||
```bash
|
||||
nixos-install --flake /mnt/home/kiskaadee/Core#server
|
||||
reboot
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔑 Modifying and Adding Secrets
|
||||
## 2. Platform Bootstrap on a Running Host
|
||||
|
||||
To update credentials (e.g. changing your Dynu API key or updating Authelia user passwords):
|
||||
When initializing the platform on an installed system:
|
||||
|
||||
1. Navigate to the core repository:
|
||||
### Step 1: Verify Host Secrets Key
|
||||
Ensure the host SSH key exists with strict permissions:
|
||||
```bash
|
||||
sudo ls -l /etc/ssh/ssh_host_ed25519_key
|
||||
sudo chmod 600 /etc/ssh/ssh_host_ed25519_key
|
||||
```
|
||||
|
||||
### Step 2: Apply Declarative NixOS Configuration
|
||||
```bash
|
||||
cd ~/Core
|
||||
```
|
||||
2. Decrypt and open the secrets file in your editor:
|
||||
```bash
|
||||
sops nixos/secrets.yaml
|
||||
```
|
||||
3. Update or append keys under the root block:
|
||||
```yaml
|
||||
dynu:
|
||||
api_key: "your_dynu_api_key"
|
||||
traefik:
|
||||
acme_email: "your_email@domain.com"
|
||||
authelia:
|
||||
session_secret: "secure_64_char_secret"
|
||||
storage_encryption_key: "secure_64_char_key"
|
||||
jwt_secret: "secure_64_char_jwt_secret"
|
||||
users:
|
||||
kiskaadee:
|
||||
password_hash: "$argon2id$v=19$m=65536..."
|
||||
```
|
||||
*To generate an Argon2 password hash securely, run:*
|
||||
```bash
|
||||
docker run --rm -it authelia/authelia:latest authelia crypto hash generate argon2
|
||||
```
|
||||
4. Save and close. SOPS will automatically encrypt the modified file before saving.
|
||||
5. Rebuild the system to apply new secret templates:
|
||||
```bash
|
||||
sudo nixos-rebuild switch --flake ~/Core#server
|
||||
```
|
||||
This configures:
|
||||
* Docker daemon, host firewall rules, and system packages.
|
||||
* Decrypted secret files in `/run/secrets/homeserver.env` and `/run/secrets/traefik-deployments.env`.
|
||||
* Systemd service units (`homeserver-core`, `homelab-gitops`, `dynu-monitor`).
|
||||
|
||||
### Step 3: Create External Docker Networks
|
||||
The Core Compose stack and workloads require the `proxy-net` and `socket-net` bridge networks:
|
||||
```bash
|
||||
docker network create proxy-net 2>/dev/null || true
|
||||
docker network create socket-net 2>/dev/null || true
|
||||
```
|
||||
|
||||
### Step 4: Start Platform Services
|
||||
```bash
|
||||
sudo systemctl start homeserver-core
|
||||
```
|
||||
Check running containers:
|
||||
```bash
|
||||
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
|
||||
```
|
||||
|
||||
### Step 5: Verify DNS & Certificates
|
||||
1. Trigger an immediate DDNS update:
|
||||
```bash
|
||||
sudo systemctl start dynu-monitor
|
||||
```
|
||||
2. Verify Let's Encrypt wildcard certificate generation:
|
||||
```bash
|
||||
appctl ssl traefik
|
||||
```
|
||||
|
||||
### Step 6: Initialize LLDAP Directory
|
||||
1. Navigate to `https://users.roadtotech.me`.
|
||||
2. Authenticate using `admin` and the password configured in `nixos/secrets.yaml` (`lldap/admin_password`).
|
||||
3. Create standard user accounts and assign them to required groups.
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ Declarative NixOS Modules
|
||||
## 3. Onboarding a New Application Workload
|
||||
|
||||
The Core stack and deployment environments are defined declaratively in `nixos/modules/`:
|
||||
Applications live in isolated repositories under `~/Sites/`. To deploy a new service:
|
||||
|
||||
### 1. Control Plane Module ([`nixos/modules/homeserver.nix`](../nixos/modules/homeserver.nix))
|
||||
Generates `/run/secrets/rendered/homeserver.env`, `/run/secrets/rendered/users.yml`, and manages the `homeserver-core.service` and `homelab-gitops.service` systemd daemons.
|
||||
### Step 1: Create Repository Directory
|
||||
```bash
|
||||
mkdir -p ~/Sites/homelab-myapp
|
||||
cd ~/Sites/homelab-myapp
|
||||
git init
|
||||
```
|
||||
|
||||
### 2. Applications Secret Module ([`nixos/modules/traefik-deployments.nix`](../nixos/modules/traefik-deployments.nix))
|
||||
Generates `/run/secrets/rendered/traefik-deployments.env` consumed by `appctl`.
|
||||
### Step 2: Create `app.yaml` Manifest
|
||||
Create `~/Sites/homelab-myapp/app.yaml`:
|
||||
```yaml
|
||||
name: "myapp"
|
||||
aliases:
|
||||
- "app"
|
||||
domain: "myapp.roadtotech.me"
|
||||
description: "My New Application Service"
|
||||
visible: true
|
||||
auth: false
|
||||
networks:
|
||||
- proxy-net
|
||||
|
||||
### 3. Dynamic DNS Module ([`nixos/modules/dynu.nix`](../nixos/modules/dynu.nix))
|
||||
Configures the smart IP monitor timer and updates ddclient when IP rotations occur.
|
||||
env:
|
||||
APP_PORT: "8080"
|
||||
|
||||
### 4. Server Shell Module ([`nixos/modules/shell.nix`](../nixos/modules/shell.nix))
|
||||
Defines interactive bash aliases, git helpers, and terminal tools via system `/etc/bashrc`.
|
||||
deployment:
|
||||
branch: "main"
|
||||
actions:
|
||||
- git_pull
|
||||
- compose_up
|
||||
|
||||
homepage:
|
||||
title: "My App"
|
||||
group: "Applications"
|
||||
icon: "default.png"
|
||||
container: "myapp"
|
||||
weight: 50
|
||||
```
|
||||
|
||||
### Step 3: Create `docker-compose.yml`
|
||||
Create `~/Sites/homelab-myapp/docker-compose.yml`:
|
||||
```yaml
|
||||
services:
|
||||
myapp:
|
||||
image: myapp/image:latest
|
||||
container_name: ${CONTAINER_NAME:-myapp}
|
||||
restart: always
|
||||
environment:
|
||||
- PORT=${APP_PORT:-8080}
|
||||
networks:
|
||||
- proxy-net
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
# HTTPS Router
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.rule=Host(`${SERVICE_DOMAIN}`)"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.entrypoints=websecure"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.tls=true"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}.service=${CONTAINER_NAME:-myapp}-svc"
|
||||
# HTTP -> HTTPS Redirect
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}-red.rule=Host(`${SERVICE_DOMAIN}`)"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}-red.entrypoints=web"
|
||||
- "traefik.http.routers.${CONTAINER_NAME:-myapp}-red.middlewares=https-redirect@docker"
|
||||
# Target Port
|
||||
- "traefik.http.services.${CONTAINER_NAME:-myapp}-svc.loadbalancer.server.port=${APP_PORT:-8080}"
|
||||
|
||||
networks:
|
||||
proxy-net:
|
||||
name: ${PROXY_NETWORK:-proxy-net}
|
||||
external: true
|
||||
```
|
||||
|
||||
### Step 4: Launch and Sync
|
||||
```bash
|
||||
# Launch application stack via appctl
|
||||
appctl up myapp
|
||||
|
||||
# Inspect application diagnostics
|
||||
appctl info myapp
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Running and Managing the Stack
|
||||
## 4. Verification
|
||||
|
||||
### Standard Systemd Operations:
|
||||
* **Start:** `sudo systemctl start homeserver-core`
|
||||
* **Stop:** `sudo systemctl stop homeserver-core`
|
||||
* **Restart:** `sudo systemctl restart homeserver-core`
|
||||
* **Status:** `systemctl status homeserver-core`
|
||||
* **Live Logs:** `journalctl -u homeserver-core -f`
|
||||
Before committing changes to Homelab Core, run the repository test runner:
|
||||
|
||||
### Dynamic Tweaks without Rebuilding NixOS:
|
||||
When making configuration adjustments to `docker-compose.yml` (e.g. tuning Traefik middlewares):
|
||||
```bash
|
||||
cd ~/Core
|
||||
docker compose --env-file /run/secrets/rendered/homeserver.env up -d --remove-orphans
|
||||
./scripts/test
|
||||
```
|
||||
This runs:
|
||||
* Code formatting and lint checks (`ruff`).
|
||||
* Security and structural invariant tests (`pytest tests/`).
|
||||
* Nix flake check (`nix flake check`).
|
||||
Reference in new issue
Block a user