# ๐ŸŒ Traefik Homelab Core Welcome to the **Traefik Homelab Core Control Plane** โ€” the central orchestrator, security perimeter, and edge gateway 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`. --- ## ๐Ÿ—๏ธ Architectural Overview & Component Roles The infrastructure is strictly divided into two operational tiers: ``` Internet (roadtotech.me) โ”‚ โ–ผ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Traefik Edge Proxy (:443) โ”‚ โ”‚ (Wildcard Let's Encrypt TLS) โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ Public Traffic โ”‚ โ”‚ Auth Guarded โ–ผ โ–ผ [ Landing / Public ] [ Authelia SSO / 2FA ] โ”‚ โ”‚ โ”‚ โ–ผ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ [ Data Plane Apps ] (Sites: jellyfin, docs, etc.) ``` ### 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. --- ## ๐Ÿ”’ Security Model & Secrets Architecture 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..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: ```bash # List all application stacks with runtime container health and Git sync status appctl list # Fetch upstream git changes across all repositories before rendering status appctl list --fetch # List all applications AND core control plane services appctl list --core # Display comprehensive metadata, routing, environment, and Git diagnostics appctl info docs appctl info jellyfin # Start, stop, or restart an application stack appctl up docs appctl down jellyfin appctl restart dash # Full atomic stack upgrade (clean check -> git pull --ff-only -> docker compose pull -> docker compose up -d -> appctl 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 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 Validation ] โ”€โ”€โ–บ (app.yaml validated; pushed branch must match declared policy) โ”‚ โ–ผ [ 5. Asynchronous Queue & Worker ] โ”€โ”€โ–บ (Atomic queueing + immediate HTTP 200 return; per-repo flock worker) โ”‚ โ–ผ [ 6. Closed Execution Engine ] โ”€โ”€โ–บ (Strictly allowlisted actions without shell=True) ``` ### 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. * **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). --- ## ๐Ÿงช 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: ```bash # Run the complete test and invariant suite locally ./scripts/test # Run pure Nix sandbox verification (runs ruff and pytest in an isolated Nix derivation) 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 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 [`homelab-dashboard/config/services.yaml`](file:///home/kiskaadee/Sites/homelab-dashboard/config/services.yaml). --- ## โ„๏ธ Declarative NixOS Appliance 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 ``` --- ## ๐Ÿ“„ License This repository is released into the public domain under [The Unlicense](UNLICENSE).