Compare commits

..
3 Commits
Author SHA1 Message Date
kiskaadee 1fea9024f1 docs(operations): document token bootstrapping and core update policy in cutover runbook (#23)
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m2s
2026-10-31 21:39:30 -05:00
kiskaadee 4622392ca5 fix(nixos): add tmpfiles state dir, optional sandbox paths, and gitops service ordering (#22) 2026-10-31 21:39:30 -05:00
kiskaadee c740ed8c71 chore: add .worktrees/ to .gitignore 2026-10-31 21:39:30 -05:00
4 changed files with 161 additions and 25 deletions

No files matched your search

+1
View File
@@ -41,6 +41,7 @@ config/homepage/custom.js
Thumbs.db
.vscode/
.idea/
.worktrees/
# Python & Testing Caches
__pycache__/
+96 -18
View File
@@ -145,9 +145,8 @@ appctl restart docs
appctl restart traefik
appctl restart authelia
# Sequential stack update (clean working tree check -> git pull -> compose pull -> up -> sync)
# Sequential stack update for independent Sites workloads (clean tree check -> git pull -> compose pull -> up -> sync)
appctl update docs
appctl update core
# Stream live container logs
appctl logs docs
@@ -157,6 +156,37 @@ appctl logs -f stalwart
appctl config docs
```
### Workload vs. Core Update Policy
Homelab enforces a strict architectural boundary between independent application workloads (`~/Sites/<app>`) and Homelab Core (`~/Core`):
#### 1. Independent Sites Workloads (`~/Sites/<app>`)
- **Automated Lifecycle**: Workloads declare their lifecycle via `app.yaml` manifests and Compose definitions.
- **Update Command**: `appctl update <workload>` performs pre-flight verification, branch matching, `git pull --ff-only`, container image pull, stack reload, and dashboard synchronization.
- **GitOps Webhook Dispatch**: Workloads registered in `config/deployments.yaml` can be triggered automatically via authenticated GitOps webhooks on Gitea push events.
- **Daemon Permissions**: `homelab-appctl.service` holds read-write permissions over `~/Sites` to manage files, compose configurations, and workload state.
#### 2. Homelab Core Platform Stack (`~/Core`)
- **Host Foundation & Invariant Boundary**: Core defines NixOS host definitions, platform secrets, edge ingress, and security sandboxes.
- **No Untrusted Webhooks**: Core does **not** register for webhook dispatch in `config/deployments.yaml`. External push events can never trigger an automated deployment or rebuild of Core.
- **Read-Only Sandbox**: Under NixOS systemd sandboxing (`ProtectHome = "read-only"`), `homelab-appctl.service` has strictly read-only access to `/home/operator/Core`. The daemon cannot mutate the Core Git repository or run `git pull` on Core.
- **Operator-Driven Update Workflow**: Core updates must be executed explicitly by the operator:
1. Review and pull repository changes:
```bash
cd ~/Core && git pull --ff-only
```
2. If NixOS modules or secrets changed, evaluate and activate the new system generation:
```bash
sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
```
3. If Compose definitions changed, restart the platform stack:
```bash
docker compose up -d --remove-orphans
# or via systemd:
sudo systemctl restart homeserver-core
```
4. Individual platform services can be restarted via appctl using an authenticated admin token (`appctl restart traefik`, `appctl restart authelia`).
---
## 4. User Identity & Access Management (LLDAP & Authelia)
@@ -437,7 +467,51 @@ Activate the declarative configuration under the `operator` profile:
chmod 600 /home/operator/Core/nixos/instance.nix
```
2. **Rebuild NixOS host configuration**:
2. **Bootstrap appctl control plane tokens (CR-SO-08)**:
The `homelab-appctl.service` control plane daemon enforces 3-role RBAC (`homelab-admin`, `homelab-operator`, `homelab-viewer`) authenticated via SHA-256 Bearer tokens stored in `/run/secrets/appctl/tokens.json`.
Generate the operator administrator token and local CLI credentials:
```bash
sudo -u operator python3 /home/operator/Core/scripts/bootstrap_token.py
```
This command:
- Creates `~/.config/homelab/token` (mode `0600`) owned by `operator:homelab-operators` containing the raw Bearer token used automatically by the `appctl` CLI.
- Outputs the JSON token descriptor containing the SHA-256 digest:
```json
{
"token_id": "operator-admin",
"identity": "operator",
"role": "homelab-admin",
"sha256": "<64-character-sha256-digest>"
}
```
> [!IMPORTANT]
> **Unprovisioned Token Behavior & RBAC Fallback**:
> If tokens are not provisioned in `/run/secrets/appctl/tokens.json`, local UDS connections (`/run/homelab/appctl.sock`) fall back to Linux `SO_PEERCRED` socket credentials, granting callers in `homelab-operators` the read-only `homelab-viewer` role.
> Under `homelab-viewer`, safe queries succeed (`appctl list`, `appctl status`, `appctl health`).
> However, **all mutating and privileged operations** (`appctl up`, `appctl down`, `appctl restart`, `appctl update`, `appctl deploy`, `appctl config`, `appctl info`) **strictly require** a valid Bearer token with `homelab-operator` or `homelab-admin` role. If tokens are not enrolled in SOPS, attempting mutating actions fails with HTTP 403 `ERR_PERMISSION_DENIED`.
Enroll the token descriptor into SOPS secrets:
```bash
sops /home/operator/Core/nixos/secrets.yaml
```
Under `appctl.tokens_json`, insert the descriptor into the JSON array:
```yaml
appctl:
tokens_json: |
[
{
"token_id": "operator-admin",
"identity": "operator",
"role": "homelab-admin",
"sha256": "<paste-sha256-digest-here>"
}
]
```
*(Optional: If GitOps webhook dispatch is enabled, generate and enroll a `gitops-webhook` token with `homelab-operator` role using `python3 scripts/bootstrap_token.py --identity gitops --role homelab-operator --token-id gitops-webhook --print-json`).*
3. **Rebuild NixOS host configuration**:
Execute the rebuild from the new canonical Core path using `--impure` and the `path:` scheme to import the untracked instance profile:
```bash
cd /home/operator/Core
@@ -445,10 +519,10 @@ Activate the declarative configuration under the `operator` profile:
```
> [!NOTE]
> The `path:` scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index, ensuring untracked/gitignored `nixos/instance.nix` is evaluated. (If using `/etc/nixos/homelab-instance.nix`, bare `--flake .#server --impure` works directly).
> The `path:` scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index, ensuring untracked/gitignored `nixos/instance.nix` is evaluated. (If using `/etc/nixos/homelab-instance.nix`, bare `--flake .#server --impure` works directly). Rebuilding also decrypts and projects `/run/secrets/appctl/tokens.json` via `sops-nix`.
3. **Restart platform services**:
Restart the Core Compose stack and control plane services to consume updated paths:
4. **Restart platform services**:
Restart the Core Compose stack and control plane services to consume updated paths and secrets:
```bash
sudo systemctl restart homeserver-core
sudo systemctl restart homelab-appctl
@@ -467,22 +541,26 @@ Validate system health and operational readiness under the `operator` identity:
sudo -u operator git -C /home/operator/Sites/<any-workload> status
```
2. **Verify appctl control plane status**:
Execute CLI inspection using both UDS peercred authentication and token authentication:
```bash
# Peercred UDS inspection
sudo -u operator appctl list --core
# Workload health check
sudo -u operator appctl status
```
3. **Verify SOPS secrets and tokens**:
Ensure `/run/secrets/appctl/tokens.json` is readable by `homelab-appctl` and valid tokens exist for operator administration:
2. **Verify SOPS secrets and tokens projection**:
Ensure `/run/secrets/appctl/tokens.json` is readable by `homelab-appctl` (mode `0400`, owned by `homelab-appctl:homelab-operators`) and contains valid descriptors:
```bash
sudo ls -l /run/secrets/appctl/tokens.json
```
3. **Verify appctl control plane status & RBAC authentication**:
Execute CLI inspection using both UDS peercred authentication (read-only viewer fallback) and authenticated admin token operations:
```bash
# 1. Peercred UDS inspection (demonstrates viewer fallback for read-only actions)
sudo -u operator appctl list --core
sudo -u operator appctl status
sudo -u operator appctl health
# 2. Authenticated operator admin verification (requires homelab-admin Bearer token)
sudo -u operator appctl info docs
sudo -u operator appctl config docs
```
Confirm that `info` and `config` return resolved configuration without `ERR_PERMISSION_DENIED`, verifying that `~/.config/homelab/token` matches the provisioned SHA-256 digest in `/run/secrets/appctl/tokens.json`.
4. **Verify container reachability & proxy routing**:
Check that external endpoints and internal reverse proxies resolve:
```bash
+8 -7
View File
@@ -103,8 +103,8 @@
# Declarative Dynamic GitOps Webhook Service (Internal Port 9000)
systemd.services.homelab-gitops = {
description = "Dynamic Homelab GitOps Webhook Dispatcher";
after = [ "network-online.target" "docker.service" ];
wants = [ "network-online.target" ];
after = [ "network-online.target" "docker.service" "homelab-appctl.service" ];
wants = [ "network-online.target" "homelab-appctl.service" ];
wantedBy = [ "multi-user.target" ];
path = with pkgs; [
@@ -154,7 +154,7 @@
ReadWritePaths = [
config.homelab.sitesDir
"/home/${config.homelab.operatorUser}/.local/state/homelab"
"/run/homelab"
"-/run/homelab"
];
};
};
@@ -226,11 +226,11 @@
ProtectControlGroups = true;
ReadWritePaths = [
config.homelab.sitesDir
"/home/${config.homelab.operatorUser}/var/lib/homelab"
"${config.homelab.coreDir}/config/homepage"
"-/home/${config.homelab.operatorUser}/var/lib/homelab"
"-${config.homelab.coreDir}/config/homepage"
"/var/log/homelab/appctl"
"/var/lib/homelab/appctl"
"/run/homelab"
"-/var/lib/homelab/appctl"
"-/run/homelab"
];
};
};
@@ -242,6 +242,7 @@
"d ${config.homelab.sitesDir} 0755 ${config.homelab.operatorUser} users -"
"d /home/${config.homelab.operatorUser}/.local/state/homelab/gitops 0755 ${config.homelab.operatorUser} users -"
"d /home/${config.homelab.operatorUser}/.local/state/homelab/docker 0755 ${config.homelab.operatorUser} users -"
"d /home/${config.homelab.operatorUser}/var/lib/homelab 0755 ${config.homelab.operatorUser} users -"
# POSIX ACLs granting homelab-appctl traverse and access to operator sites & homepage config
"a+ /home/${config.homelab.operatorUser} - - - - u:homelab-appctl:x"
"a+ ${config.homelab.coreDir} - - - - u:homelab-appctl:x"
@@ -2,6 +2,7 @@
Security invariant tests for Docker Compose and container isolation.
"""
import json
import os
import shutil
import subprocess
@@ -291,6 +292,61 @@ def test_nixos_tmpfiles_rules_use_recursive_acls():
)
def test_nixos_tmpfiles_rules_creates_operator_var_lib_homelab():
"""Ensure tmpfiles.rules creates operator var/lib/homelab state dir before ACL assignment (#22)."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
expected_create = '"d /home/${config.homelab.operatorUser}/var/lib/homelab 0755 ${config.homelab.operatorUser} users -"'
expected_acl = '"A+ /home/${config.homelab.operatorUser}/var/lib/homelab - - - - d:u:homelab-appctl:rwx,u:homelab-appctl:rwx"'
assert expected_create in content, (
"tmpfiles.rules must declare creation of operator var/lib/homelab directory"
)
assert expected_acl in content, (
"tmpfiles.rules must declare ACLs for operator var/lib/homelab directory"
)
assert content.index(expected_create) < content.index(expected_acl), (
"operator var/lib/homelab directory creation must precede its ACL rule"
)
def test_nixos_appctl_readwritepaths_optional_prefixes():
"""Ensure appctl service ReadWritePaths uses '-' prefix for optional runtime paths (#22)."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
assert '"-/home/${config.homelab.operatorUser}/var/lib/homelab"' in content
assert '"-${config.homelab.coreDir}/config/homepage"' in content
assert '"-/var/lib/homelab/appctl"' in content
assert '"-/run/homelab"' in content
def test_nixos_gitops_orders_after_appctl():
"""Ensure homelab-gitops service declares after and wants dependency on homelab-appctl.service (#22)."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
assert '"homelab-appctl.service"' in content
nix_bin = shutil.which("nix")
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
for attr in ["after", "wants"]:
cmd = [
nix_bin,
"eval",
f".#nixosConfigurations.server.config.systemd.services.homelab-gitops.{attr}",
"--json",
]
res = subprocess.run(
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
)
data = json.loads(res.stdout)
assert "homelab-appctl.service" in data, (
f"homelab-gitops {attr} must include homelab-appctl.service"
)
def test_default_homelab_domain_evaluates_to_example_test():
"""Assert default homelab.domain in NixOS config evaluates to 'example.test'."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"