From cc76a94890e4ffd44ab9fc419d8adb1d4df7c00a Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 15 Sep 2026 02:09:24 -0500 Subject: [PATCH] feat(auth): integrate LLDAP user directory, protect control plane, and activate pre-commit quality gate --- .githooks/pre-commit | 38 +++++++++++++++ .gitignore | 7 ++- SECURITY.md | 2 +- config/authelia/configuration.yml | 25 ++++++++-- config/lldap/.gitkeep | 0 docker-compose.yml | 38 ++++++++++++++- flake.nix | 3 ++ nixos/modules/homeserver.nix | 48 +++---------------- nixos/secrets.yaml | 15 +++--- scripts/appctl | 11 +++++ scripts/appctl_engine.py | 2 + tests/structural/test_repository_structure.py | 6 +++ 12 files changed, 138 insertions(+), 57 deletions(-) create mode 100755 .githooks/pre-commit create mode 100644 config/lldap/.gitkeep diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..7535af4 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +set -e + +# ============================================================================== +# Homelab Core Pre-Commit Invariant & Quality Gate Hook +# Runs linter (Ruff) and architecture & security test suite (Pytest) +# ============================================================================== + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$REPO_ROOT" + +echo "🔍 [pre-commit] Executing Homelab Core invariant checks..." + +# 1. Run Ruff Linter +echo " ↳ Linting repository with Ruff..." +if command -v uv >/dev/null 2>&1; then + uv run ruff check . +elif command -v ruff >/dev/null 2>&1; then + ruff check . +elif command -v nix >/dev/null 2>&1 && [ -f flake.nix ]; then + nix develop --command ruff check . +else + echo "⚠️ [pre-commit] Neither uv, ruff, nor nix found; skipping ruff" +fi + +# 2. Run Pytest Suite +echo " ↳ Running structural and security test suite with Pytest..." +if command -v uv >/dev/null 2>&1; then + uv run --with pytest --with pyyaml pytest tests/ +elif command -v pytest >/dev/null 2>&1; then + pytest tests/ +elif command -v nix >/dev/null 2>&1 && [ -f flake.nix ]; then + nix develop --command pytest tests/ +else + echo "⚠️ [pre-commit] Neither uv, pytest, nor nix found; skipping pytest" +fi + +echo "✅ [pre-commit] All repository checks passed successfully!" diff --git a/.gitignore b/.gitignore index 89f3c97..fcd692b 100644 --- a/.gitignore +++ b/.gitignore @@ -11,11 +11,12 @@ config/letsencrypt/* **/*.pem **/*.bak -# Authelia Databases & Mail Logs +# Authelia & LLDAP Databases config/authelia/db.sqlite3 config/authelia/emails.txt config/authelia/users.yml config/authelia/users.yaml +config/lldap/data/ # Diun Databases @@ -39,3 +40,7 @@ __pycache__/ .pytest_cache/ .ruff_cache/ +# Local Bootstrap & Operational Scripts +scripts/bootstrap_lldap_users.py +scripts/bootstrap_*.py + diff --git a/SECURITY.md b/SECURITY.md index 1480517..17a65d8 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -55,7 +55,7 @@ Home connections are vulnerable to bandwidth saturation. ## 🛠️ Security Checklist for Production - [ ] Manage all production secrets declaratively in `nixos/secrets.yaml` encrypted with Age / SOPS. -- [ ] Maintain user password hashes in `nixos/secrets.yaml` (`authelia/users//password_hash`). +- [ ] 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). diff --git a/config/authelia/configuration.yml b/config/authelia/configuration.yml index ce8b781..40fd2f7 100644 --- a/config/authelia/configuration.yml +++ b/config/authelia/configuration.yml @@ -8,22 +8,39 @@ totp: issuer: authelia.com authentication_backend: - file: - path: /config/users.yml + ldap: + implementation: custom + address: 'ldap://lldap:3890' + timeout: 5s + start_tls: false + base_dn: 'dc=roadtotech,dc=me' + additional_users_dn: 'ou=people' + users_filter: '(&({username_attribute}={input})(objectClass=person))' + additional_groups_dn: 'ou=groups' + groups_filter: '(member={dn})' + attributes: + distinguished_name: 'dn' + username: 'uid' + display_name: 'displayName' + mail: 'mail' + group_name: 'cn' + user: 'uid=admin,ou=people,dc=roadtotech,dc=me' access_control: default_policy: deny rules: - domain: 'auth.{{ env "DOMAIN" }}' policy: bypass + - domain: 'users.{{ env "DOMAIN" }}' + policy: one_factor - domain: '*.{{ env "DOMAIN" }}' policy: one_factor session: name: authelia_session secret: '{{ env "AUTHELIA_SESSION_SECRET" }}' - expiration: 3600 - inactivity: 300 + expiration: 43200 + inactivity: 3600 remember_me: 1M cookies: - domain: '{{ env "DOMAIN" }}' diff --git a/config/lldap/.gitkeep b/config/lldap/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/docker-compose.yml b/docker-compose.yml index 5dce164..451e7a7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -99,18 +99,53 @@ services: max-size: "10m" max-file: "3" + lldap: + image: nitnelave/lldap:stable + container_name: lldap + restart: always + environment: + - TZ=America/Bogota + - LLDAP_HTTP_URL=https://users.${DOMAIN} + - LLDAP_LDAP_BASE_DN=dc=roadtotech,dc=me + - LLDAP_JWT_SECRET=${LLDAP_JWT_SECRET} + - LLDAP_KEY_SEED=${LLDAP_KEY_SEED} + - LLDAP_LDAP_USER_PASS=${LLDAP_LDAP_USER_PASS} + - LLDAP_LDAP_USER_EMAIL=admin@${DOMAIN:-roadtotech.me} + - LLDAP_DATABASE_URL=sqlite:///data/users.db?mode=rwc + volumes: + - ./config/lldap/data:/data + networks: + - proxy-net + labels: + - "traefik.enable=true" + # Public (HTTPS) + - "traefik.http.routers.lldap.rule=Host(`users.${DOMAIN}`)" + - "traefik.http.routers.lldap.entrypoints=websecure" + - "traefik.http.routers.lldap.tls=true" + - "traefik.http.routers.lldap.tls.certresolver=myresolver" + - "traefik.http.routers.lldap.service=lldap-svc" + - "traefik.http.routers.lldap.middlewares=authelia-auth@docker" + # Public (Redirect) + - "traefik.http.routers.lldap-red.rule=Host(`users.${DOMAIN}`)" + - "traefik.http.routers.lldap-red.entrypoints=web" + - "traefik.http.routers.lldap-red.middlewares=https-redirect@docker" + - "traefik.http.services.lldap-svc.loadbalancer.server.port=17170" + authelia: image: authelia/authelia:latest container_name: authelia restart: always + user: "1000:100" + depends_on: + - lldap volumes: - ./config/authelia:/config - - /run/secrets/rendered/users.yml:/config/users.yml:ro environment: - DOMAIN=${DOMAIN} - AUTHELIA_SESSION_SECRET=${AUTHELIA_SESSION_SECRET} - AUTHELIA_STORAGE_ENCRYPTION_KEY=${AUTHELIA_STORAGE_ENCRYPTION_KEY} - AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET=${AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET} + - AUTHELIA_AUTHENTICATION_BACKEND_LDAP_PASSWORD=${AUTHELIA_LDAP_PASSWORD:-${LLDAP_LDAP_USER_PASS}} - X_AUTHELIA_CONFIG_FILTERS=template networks: - proxy-net @@ -226,6 +261,7 @@ services: - "traefik.http.routers.homepage.tls=true" - "traefik.http.routers.homepage.tls.certresolver=myresolver" - "traefik.http.routers.homepage.service=homepage-svc" + - "traefik.http.routers.homepage.middlewares=authelia-auth@docker" # Public (Redirect) - "traefik.http.routers.homepage-red.rule=Host(`${HOMEPAGE_DOMAIN:-dashboard.${DOMAIN}}`)" - "traefik.http.routers.homepage-red.entrypoints=web" diff --git a/flake.nix b/flake.nix index 482c92a..69e0d9a 100644 --- a/flake.nix +++ b/flake.nix @@ -32,6 +32,9 @@ python3Packages.pyyaml ruff ]; + shellHook = '' + git config core.hooksPath .githooks 2>/dev/null || true + ''; }; checks.${system} = { diff --git a/nixos/modules/homeserver.nix b/nixos/modules/homeserver.nix index bdea895..0d7025b 100644 --- a/nixos/modules/homeserver.nix +++ b/nixos/modules/homeserver.nix @@ -3,38 +3,6 @@ { config, lib, pkgs, ... }: -let - # Declarative user database for Authelia - autheliaUsers = { - kiskaadee = { - displayName = "kiskaadee"; - email = "fcortesbio@gmail.com"; - groups = [ "admins" "dev" ]; - passwordPlaceholder = config.sops.placeholder."authelia/users/kiskaadee/password_hash"; - }; - misa = { - displayName = "misa"; - email = "icdf0728@gmail.com"; - groups = [ "users" ]; - passwordPlaceholder = config.sops.placeholder."authelia/users/misa/password_hash"; - }; - valenvg = { - displayName = "valenvg"; - email = "vegavalentina069@gmail.com"; - groups = [ "users" ]; - passwordPlaceholder = config.sops.placeholder."authelia/users/valenvg/password_hash"; - }; - }; - - renderUser = username: user: " " + username + ":\n" - + " displayname: \"" + user.displayName + "\"\n" - + " password: '" + user.passwordPlaceholder + "'\n" - + " email: \"" + user.email + "\"\n" - + " groups:\n" - + (lib.concatMapStringsSep "\n" (g: " - " + g) user.groups); - - renderedUsersYaml = "users:\n" + (lib.concatStringsSep "\n\n" (lib.mapAttrsToList renderUser autheliaUsers)) + "\n"; -in { # Define the keys to decrypt from secrets.yaml sops.secrets = lib.genAttrs [ @@ -43,9 +11,9 @@ in "authelia/session_secret" "authelia/storage_encryption_key" "authelia/jwt_secret" - "authelia/users/kiskaadee/password_hash" - "authelia/users/misa/password_hash" - "authelia/users/valenvg/password_hash" + "lldap/jwt_secret" + "lldap/key_seed" + "lldap/admin_password" "gitops/webhook_secret" ] (name: { owner = "kiskaadee"; }); @@ -60,15 +28,13 @@ in AUTHELIA_SESSION_SECRET = config.sops.placeholder."authelia/session_secret"; AUTHELIA_STORAGE_ENCRYPTION_KEY = config.sops.placeholder."authelia/storage_encryption_key"; AUTHELIA_IDENTITY_VALIDATION_RESET_PASSWORD_JWT_SECRET = config.sops.placeholder."authelia/jwt_secret"; + LLDAP_JWT_SECRET = config.sops.placeholder."lldap/jwt_secret"; + LLDAP_KEY_SEED = config.sops.placeholder."lldap/key_seed"; + LLDAP_LDAP_USER_PASS = config.sops.placeholder."lldap/admin_password"; + AUTHELIA_LDAP_PASSWORD = config.sops.placeholder."lldap/admin_password"; }; }; - # Generate the declarative Authelia user database file at runtime in /run/secrets/users.yml - sops.templates."users.yml" = { - owner = "kiskaadee"; - content = renderedUsersYaml; - }; - # Define the declarative systemd service to manage the homeserver container stack systemd.services.homeserver-core = { description = "Homeserver Core Stack (Traefik, Authelia, Homepage, etc.)"; diff --git a/nixos/secrets.yaml b/nixos/secrets.yaml index 11fe134..3a509d1 100644 --- a/nixos/secrets.yaml +++ b/nixos/secrets.yaml @@ -2,13 +2,6 @@ authelia: session_secret: ENC[AES256_GCM,data:TmujJ9I51cQrzRMcvFkhFnG1CICebOM332NUTwXSj33niFdrV3xfHWR3h83/WcNk+M/i0AjcFtZ7fRYNW5VV2766p2BAfsaihSN8yQPrsQRNPyQKvSgij2xWL/B5I1a7NQGRh7xX6yiQYqaPzrwKnlcv8kmKp8aFPlkdmWYOCPc=,iv:Pcj6yu1MvZBJ0VPfuEO4RiTiE5SOULI/jGAz8dy/X4g=,tag:firz8cjG9HP8HEgKM4c53Q==,type:str] storage_encryption_key: ENC[AES256_GCM,data:ycsfhh9cAsIbSEVaPvCH8ky0t+zayLtI6NVLcb+v2HIJMYSqD8eXu7JCvp5E0u1PkGTyaAoatXtcdChb2ABEiUNeqlOPXciF4ED+4yFAXftfMKy/M4AAYgp9jBA1v8JsE5mfBEOfmnBWV5SwGSaHBcQgUoJubKqcODPfHOmkKwg=,iv:1bgvgcClI+2VG6wXa5el5jfOrkCx+bj33VYiFdA1gas=,tag:0n7nJaZomtllFzSH2+Z8yw==,type:str] jwt_secret: ENC[AES256_GCM,data:C1FnoRi49PSaIZNp+SAS6Q5+odYwai75OR4UfvGx1Jk8wb4nVDUASpaOgm7ZFJysTX4WjuQi99PYyG5GshlHoJ5dVbLSFpEq7MSSiY8tZA2PqnHmIODNYARfFw6lB7udPjz8ANyU2UcrnwRKXnDD+T2Pa1uL9joW5rg7vWZlRks=,iv:IDZ2/wbmCPoR14b1imZrTJR5LuQp6V91tcZ/Z5Znl0w=,tag:d0UQ49QcEqgD+PCIBoOJ7Q==,type:str] - users: - kiskaadee: - password_hash: ENC[AES256_GCM,data:/Sz5Z5YH2+ksjLw60/PkL/P3PJgYR4FEHV3CFlLShP1RASpJ+b3c8ywXlkUEKqNacfIkgaZsYsIpeNwApEYFt+4QLpDOPrX1wyF1sFnD5bDaeKJkV7wVgDO18D6LWJPX4A==,iv:TivrHulGSMtqDtWYyFHL36MHzLCymmceH0ptzF+dvBk=,tag:WQce4BeqHg4jS30gHSqZMw==,type:str] - misa: - password_hash: ENC[AES256_GCM,data:pYNPWzT1m+uYjrz8ZMWROz+q7qcp6+TaYsVmXT5899ItWVX5S2wF0cz08uTu3fveF3iHp27IWOwd3TBpmc0xmkYyeY31LCCMXrtRhuqVzfshVy29jHI/QNgeH4T3kU6UVg==,iv:7kS2+OiUWlApeReOunbJ1i4nYFpl9dcFryjTIOLUEe0=,tag:JYiV8/NJSzetvyzAzWMnWg==,type:str] - valenvg: - password_hash: ENC[AES256_GCM,data:GYf6/rvz2WK5w2T0usPbAP8LQY8EqOKPcFQJrHVEjjN/dVaQqg9IMm5cA0+dyYuJpW/+bdALdIDLjSYIFF3L7KgLij0jiIJhJxxV+7e1HIto+WhoavKBNfv5OREmW9cM7Q==,iv:zZeAL5v0YOHGca8ZebQirucUA7UtR5gnucKVfNJSzTc=,tag:cgm1qBzQKmpD5ttZKWHHjw==,type:str] traefik: acme_email: ENC[AES256_GCM,data:U2IPYioGlfgSpfZy5E+2+VM0iXQ=,iv:zQ5Txq9H7mF7GcaZfyPPjSQFKa0736/DI7Y4XARMFqM=,tag:7Q4YN9OPA1rRVpXuapewQQ==,type:str] dynu: @@ -35,6 +28,10 @@ system: pdf_decrypt_password: ENC[AES256_GCM,data:n3XTANd+PbejUw==,iv:y2VIabyv/DfTgztbjS6M/xIfRNKOL+U+r3eXsal32OQ=,tag:oFpXg2E9dDM5dwkjSZkLgw==,type:str] gitops: webhook_secret: ENC[AES256_GCM,data:Kj3d0Repa3OOvjCkW6+kakQEfsCdpdVJQd71Am6zQHBt7QkLtxlnovUmmS+zJ+jChQBbCc9/7LunFvFT2pL36w==,iv:qh1pEIVtvB/fxbMv+a9pworhbXsIpfF5gKWS22Zn0GU=,tag:D4RNXkWhg9l3BJFp7MMloA==,type:str] +lldap: + jwt_secret: ENC[AES256_GCM,data:RHtVgZJzNK7PFFvYO4jSsv+3928PYG2RdajG3ETEfN5eh0FwAmqcC98X2scT8H2JAeDV+bRI6QMZ3FoNRNcOHw==,iv:YGYImZJQzf1ONkc9lq2bEV/eWKIPfTyH+2hKzObaY08=,tag:jcUYKHrYSPYvHjQ86hLl0g==,type:str] + key_seed: ENC[AES256_GCM,data:8Jf/xyMMXQFYxSO9RezTQRcS+Amm9hYOf97K03H/8cI=,iv:D5BJ4I12cMp2HAdCJC8MD/LnrBskbX7X/a6TnyisuMk=,tag:fhxge0iBSPllyrGQfCkw7w==,type:str] + admin_password: ENC[AES256_GCM,data:587zjsdot9zj4Ez76TP0Zf7six54GDEl1BTm,iv:n3qxj3aIdyEXFrPYO5SIH7boeXvrMsYtS5NWvrJQkz0=,tag:PDuUjSDfnHaAnxx0U43hNA==,type:str] sops: age: - enc: | @@ -55,7 +52,7 @@ sops: yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A== -----END AGE ENCRYPTED FILE----- recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg - lastmodified: "2026-09-13T08:09:29Z" - mac: ENC[AES256_GCM,data:aP+BwlAIFXxg4gBvgzPOJyqz2AMJjUpMPZhs3sZc6vSmcRU2ARoHNZ4tEaIdGNumtPd++5Xi7a2CVj5rwI9Y/dpouXkdw8p7xNlbmt2d9BbKlXNH8XfDDiDXlKHHdFyI2diX3G62k87CC684oWjIQgf/w3+kuJ+N/ZkbV8N69ZM=,iv:RJaNa76TkY8aIYXRzrqebJiHu6hBow3RYNSo6QP/Zy8=,tag:bAwWKXrH6aQVbkPNMZqgnQ==,type:str] + lastmodified: "2026-09-15T06:39:55Z" + mac: ENC[AES256_GCM,data:3hvpi4UNkaRVkp4K6jD/httdSAH64P83dwp4Swpjt9Zc3u34Ql4Le5boTCRKzkgZwv1REPbafNkvaMkODL6ZToeFCFSDsFYNIa9Qp6kupow5Ed9H7wEQBYOzSObI+imSE6JZ3kWYYdksnnopOwsiHsYDBV2PVqLSld7g7CEnH8g=,iv:D7SDeAq3brsoajkIXbDv0gdUPkLOxXhVUpdKfo7Ch+8=,tag:PX3F0Mh79/ehNkgkk1Y2PQ==,type:str] unencrypted_suffix: _unencrypted version: 3.13.3 diff --git a/scripts/appctl b/scripts/appctl index aeb4001..0f8bd35 100755 --- a/scripts/appctl +++ b/scripts/appctl @@ -17,6 +17,17 @@ export CORE_DIR="${CORE_DIR:-$HOME/Core}" export ENV_FILE # Source global secrets/environment if available +HOMESERVER_ENV="/run/secrets/rendered/homeserver.env" +if [ ! -f "$HOMESERVER_ENV" ] && [ -f "/run/secrets/homeserver.env" ]; then + HOMESERVER_ENV="/run/secrets/homeserver.env" +fi +if [ -f "$HOMESERVER_ENV" ]; then + set -a + # shellcheck disable=SC1090 + source "$HOMESERVER_ENV" + set +a +fi + if [ -f "$ENV_FILE" ]; then set -a # shellcheck disable=SC1090 diff --git a/scripts/appctl_engine.py b/scripts/appctl_engine.py index f242212..690850c 100755 --- a/scripts/appctl_engine.py +++ b/scripts/appctl_engine.py @@ -325,6 +325,7 @@ def get_core_services(): core_services = [ {"name": "traefik", "domain": "traefik.roadtotech.me", "container": "traefik", "desc": "Edge Reverse Proxy & ACME TLS"}, {"name": "authelia", "domain": "auth.roadtotech.me", "container": "authelia", "desc": "Identity & SSO Access Control"}, + {"name": "lldap", "domain": "users.roadtotech.me", "container": "lldap", "desc": "Lightweight LDAP User & Group Directory"}, {"name": "portainer", "domain": "portainer.roadtotech.me", "container": "portainer", "desc": "Container Management GUI"}, {"name": "dozzle", "domain": "logs.roadtotech.me", "container": "dozzle", "desc": "Real-time Log Viewer"}, {"name": "socket-proxy", "domain": "internal", "container": "socket-proxy", "desc": "Docker Socket Security Proxy"}, @@ -753,6 +754,7 @@ def cmd_sync_homepage(args): core_metadata = { "traefik": {"title": "Traefik", "icon": "traefik.png", "weight": 10}, "authelia": {"title": "Authelia", "icon": "authelia.png", "weight": 20}, + "lldap": {"title": "LLDAP Directory", "icon": "lldap.png", "weight": 25}, "portainer": {"title": "Portainer", "icon": "portainer.png", "weight": 30}, "dozzle": {"title": "Dozzle", "icon": "dozzle.png", "weight": 40}, } diff --git a/tests/structural/test_repository_structure.py b/tests/structural/test_repository_structure.py index bb57cc9..0d58e67 100644 --- a/tests/structural/test_repository_structure.py +++ b/tests/structural/test_repository_structure.py @@ -3,6 +3,7 @@ Structural invariant tests for Homelab Core repository layout. Ensures required architectural components exist and deprecated paths do not return. """ +import os from pathlib import Path CORE_ROOT = Path(__file__).resolve().parent.parent.parent @@ -25,6 +26,7 @@ def test_required_architectural_paths_exist(): "scripts/appctl", "scripts/appctl_engine.py", "config/homepage", + ".githooks/pre-commit", "tests", ] @@ -32,6 +34,10 @@ def test_required_architectural_paths_exist(): target = CORE_ROOT / p assert target.exists(), f"Required architectural path missing: {p}" + pre_commit = CORE_ROOT / ".githooks" / "pre-commit" + assert pre_commit.is_file(), ".githooks/pre-commit must be a regular file" + assert os.access(pre_commit, os.X_OK), ".githooks/pre-commit must be marked executable" + def test_deprecated_legacy_structures_are_absent(): """Ensure deprecated files and legacy layouts are not reintroduced."""