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..ac28e98 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 diff --git a/config/authelia/configuration.yml b/config/authelia/configuration.yml index ce8b781..1fca7d2 100644 --- a/config/authelia/configuration.yml +++ b/config/authelia/configuration.yml @@ -8,14 +8,32 @@ 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' + password: '{{ env "AUTHELIA_LDAP_PASSWORD" }}' access_control: default_policy: deny rules: - domain: 'auth.{{ env "DOMAIN" }}' policy: bypass + - domain: 'users.{{ env "DOMAIN" }}' + policy: bypass - domain: '*.{{ env "DOMAIN" }}' policy: one_factor 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..04cc33a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -99,18 +99,51 @@ 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=fcortesbio@gmail.com + - 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" + # 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 + 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_LDAP_PASSWORD=${AUTHELIA_LDAP_PASSWORD:-${LLDAP_LDAP_USER_PASS}} - X_AUTHELIA_CONFIG_FILTERS=template networks: - proxy-net 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..3656a49 100644 --- a/nixos/modules/homeserver.nix +++ b/nixos/modules/homeserver.nix @@ -46,6 +46,9 @@ in "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,6 +63,10 @@ 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"; }; }; diff --git a/nixos/secrets.yaml b/nixos/secrets.yaml index 11fe134..61dc71c 100644 --- a/nixos/secrets.yaml +++ b/nixos/secrets.yaml @@ -35,6 +35,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 +59,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:06:49Z" + mac: ENC[AES256_GCM,data:IeWQBILtVRdg4Ls35evY0QwhtLSXujYXTE3IYnpT57uZMa/xenRU6hRVNJiWd2yXyToVbITMHBM8oMVURrhonQ+L/vMf1RCmD7h0NsREY7UxeUwdSATy9jJHS+W2m+IuR+H2DJMa2hi4e/eRDM5wS+rfkz3GKZ502DC21DxrkbU=,iv:TM57w/JnTN16JncoG0BI9k6P0SrnXrgYWc0/4vlb5cQ=,tag:MVLYHV/KcSqY9CJRA3OM2A==,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/scripts/bootstrap_lldap_users.py b/scripts/bootstrap_lldap_users.py new file mode 100755 index 0000000..5a2bff6 --- /dev/null +++ b/scripts/bootstrap_lldap_users.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +""" +Bootstrap LLDAP directory with baseline groups and users. +Zero external dependencies (uses standard library urllib and json). +""" + +import json +import os +import sys +import urllib.error +import urllib.request + +LLDAP_URL = os.environ.get("LLDAP_URL", "http://127.0.0.1:17170") +ADMIN_USER = os.environ.get("LLDAP_ADMIN_USER", "admin") +ADMIN_PASS = os.environ.get("LLDAP_LDAP_USER_PASS") or os.environ.get("AUTHELIA_LDAP_PASSWORD", "") + +INITIAL_GROUPS = ["admins", "dev", "users"] + +INITIAL_USERS = [ + { + "id": "kiskaadee", + "email": "fcortesbio@gmail.com", + "displayName": "kiskaadee", + "groups": ["admins", "dev"], + }, + { + "id": "misa", + "email": "icdf0728@gmail.com", + "displayName": "misa", + "groups": ["users"], + }, + { + "id": "valenvg", + "email": "vegavalentina069@gmail.com", + "displayName": "valenvg", + "groups": ["users"], + }, +] + + +def post_json(url, data, token=None): + body = json.dumps(data).encode("utf-8") + headers = {"Content-Type": "application/json"} + if token: + headers["Authorization"] = f"Bearer {token}" + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=10) as resp: + return json.loads(resp.read().decode("utf-8")) + except urllib.error.HTTPError as e: + error_body = e.read().decode("utf-8") + try: + return json.loads(error_body) + except (json.JSONDecodeError, UnicodeDecodeError): + return {"error": str(e), "details": error_body} + + +def login(base_url, username, password): + url = f"{base_url}/auth/simple/login" + res = post_json(url, {"username": username, "password": password}) + if "token" in res: + return res["token"] + raise RuntimeError(f"Authentication to LLDAP failed: {res}") + + +def query_graphql(base_url, token, query_str, variables=None): + url = f"{base_url}/api/graphql" + payload = {"query": query_str} + if variables: + payload["variables"] = variables + res = post_json(url, payload, token=token) + return res + + +def bootstrap(): + if not ADMIN_PASS: + print("āŒ Error: Admin password not provided. Set LLDAP_LDAP_USER_PASS or AUTHELIA_LDAP_PASSWORD.") + sys.exit(1) + + print(f"šŸ”— Connecting to LLDAP at {LLDAP_URL}...") + try: + token = login(LLDAP_URL, ADMIN_USER, ADMIN_PASS) + print(" šŸ”‘ Successfully authenticated with LLDAP admin.") + except (urllib.error.URLError, RuntimeError, OSError) as e: + print(f"āŒ Failed to login to LLDAP: {e}") + sys.exit(1) + + # 1. Fetch existing groups + groups_res = query_graphql(LLDAP_URL, token, "{ groups { id displayName } }") + existing_groups = {g["displayName"]: g["id"] for g in groups_res.get("data", {}).get("groups", [])} + print(f" Existing groups: {list(existing_groups.keys())}") + + for group_name in INITIAL_GROUPS: + if group_name not in existing_groups: + print(f" āž• Creating group: {group_name}...") + mutation = f'mutation {{ createGroup(name: "{group_name}") {{ id displayName }} }}' + res = query_graphql(LLDAP_URL, token, mutation) + if "errors" in res: + print(f" āš ļø Warning creating group {group_name}: {res['errors']}") + else: + new_group = res.get("data", {}).get("createGroup", {}) + existing_groups[group_name] = new_group.get("id") + print(f" āœ… Group {group_name} created (ID: {new_group.get('id')})") + else: + print(f" ā„¹ļø Group {group_name} already exists.") + + # 2. Fetch existing users + users_res = query_graphql(LLDAP_URL, token, "{ users { id email displayName } }") + existing_users = {u["id"]: u for u in users_res.get("data", {}).get("users", [])} + print(f" Existing users: {list(existing_users.keys())}") + + for user in INITIAL_USERS: + uid = user["id"] + if uid not in existing_users: + print(f" āž• Creating user: {uid} ({user['email']})...") + mutation = f""" + mutation {{ + createUser(user: {{ + id: "{uid}", + email: "{user['email']}", + displayName: "{user['displayName']}" + }}) {{ + id + email + displayName + }} + }} + """ + res = query_graphql(LLDAP_URL, token, mutation) + if "errors" in res: + print(f" āš ļø Warning creating user {uid}: {res['errors']}") + else: + print(f" āœ… User {uid} created.") + else: + print(f" ā„¹ļø User {uid} already exists.") + + # Assign user to groups + for group_name in user.get("groups", []): + group_id = existing_groups.get(group_name) + if group_id is not None: + add_res = query_graphql( + LLDAP_URL, + token, + f'mutation {{ addUserToGroup(userId: "{uid}", groupId: {group_id}) {{ ok }} }}', + ) + if "errors" in add_res: + # Usually errors if user already member + pass + else: + print(f" šŸ”— Associated {uid} with group '{group_name}'") + + print("\n✨ LLDAP user directory bootstrap completed successfully!") + + +if __name__ == "__main__": + bootstrap() 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."""