feat(nixos): add dual-path instance domain injection and operator cutover runbook
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m0s

- Implement dual-path optional imports in nixos/configuration.nix for instance domain
- Add nixos/instance.nix to .gitignore preserving platform genericism
- Add invariant tests for default domain evaluation and dynamic LDAP base DN derivation
- Document appliance domain injection and path: flake scheme in docs/setup_guide.md
- Document 4-stage staged coexistence cutover runbook and rollback plan in docs/operations.md
- Mark live host execution as BLOCKED pending authorized maintenance window
- Update todo.txt and p4-refactor-and-decoupling-plan.md

Closes #7
Refs #8
This commit is contained in:
kiskaadee committed 2026-10-30 12:13:11 -05:00
1 parent eb02543fa6
commit caa8140cd3
7 files changed
+393 -12

No files matched your search

+1
View File
@@ -6,6 +6,7 @@ backup.zip
.envrc
.direnv
.venv
nixos/instance.nix
# SSL / ACME Certificates & Keys
config/letsencrypt/*
+191 -1
View File
@@ -16,9 +16,15 @@ After modifying any file in `nixos/` (including `configuration.nix`, `hardware-c
nix-switch
# Or using the explicit command:
sudo nixos-rebuild switch --flake ~/Core#server
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
```
> [!NOTE]
> **Flake Fetcher Scheme for Untracked Files**:
> When importing the gitignored `nixos/instance.nix`, Nix's default Git fetcher filters it out unless the `path:` scheme is used (`path:/home/operator/Core#server` or `path:~/Core#server`). The `path:` scheme instructs Nix to evaluate directly from the filesystem without filtering by the Git index.
> If using `/etc/nixos/homelab-instance.nix`, a standard `--flake ~/Core#server --impure` works directly since `/etc/nixos` is outside the repository.
### Dry Build Validation & Rollback
```bash
# Validate build without activating (catches evaluation and syntax errors)
@@ -279,3 +285,187 @@ To bring up a replacement host from version control:
```bash
sudo systemctl start homeserver-core
```
---
## 7. Operator Account Migration Runbook (Decision D2: Staged Coexistence Cutover)
> [!CAUTION]
> **MAINTENANCE WINDOW REQUIRED — EXECUTION ON LIVE HOST CURRENTLY BLOCKED**
> Live execution of this runbook against production hosts is strictly blocked until an authorized platform maintenance window is scheduled. This runbook is codified for procedural readiness and dry-run verification only.
This runbook defines the 4-stage staged coexistence cutover procedure to migrate host operation from a legacy personal operator account (`<legacy-operator>`) to the platform standard `operator` user (`uid = 1000`, `extraGroups = [ "wheel" "docker" "homelab-operators" "networkmanager" ]`), fulfilling Decision D2 and eliminating personal identity coupling.
### Stage 1: Pre-Flight Checks
Before initiating data synchronization or service cutover, verify the target `operator` account environment:
1. **Verify `operator` account existence and home directory**:
```bash
id operator
# Expected output must include membership in: wheel, docker, homelab-operators
ls -ld /home/operator
```
2. **Verify SSH key provisioning**:
Ensure the operator's authorized keys are installed with strict permissions:
```bash
sudo ls -la /home/operator/.ssh/authorized_keys
sudo chmod 700 /home/operator/.ssh
sudo chmod 600 /home/operator/.ssh/authorized_keys
sudo chown -R operator:users /home/operator/.ssh
```
3. **Verify administrative (`sudo`) access**:
Test that `operator` can authenticate and execute privileged commands without failure:
```bash
sudo -u operator sudo -n true || echo "Passwordless or password sudo required for operator"
```
4. **Verify persistent directories**:
Ensure `/home/operator/Sites` and `/home/operator/Core` target parent paths are ready:
```bash
sudo mkdir -p /home/operator/{Core,Sites,.config/homelab}
sudo chown -R operator:homelab-operators /home/operator/{Core,Sites,.config}
```
---
### Stage 2: State and Repository Synchronization
Synchronize repository checkouts, environment definitions, and runtime state from the legacy user account to `/home/operator/` using non-destructive archive flags (`-aHAX` preserves hard links, attributes, and extended ACLs):
1. **Initial background synchronization**:
Seed the file trees for Core and Sites while services continue running:
```bash
sudo rsync -aHAX --info=progress2 \
--exclude=".venv" \
--exclude=".pytest_cache" \
/home/<legacy-operator>/Core/ /home/operator/Core/
sudo rsync -aHAX --info=progress2 \
/home/<legacy-operator>/Sites/ /home/operator/Sites/
if [ -d "/home/<legacy-operator>/.config/homelab" ]; then
sudo rsync -aHAX --info=progress2 \
/home/<legacy-operator>/.config/homelab/ /home/operator/.config/homelab/
fi
```
2. **Quiesce active database writers**:
Stop the platform stack to guarantee point-in-time consistency across SQLite databases (e.g. LLDAP `users.db`, Authelia `db.sqlite3`, Stalwart storage) before the cutover sync:
```bash
sudo systemctl stop homeserver-core
```
3. **Final delta synchronization (`--delete`)**:
Perform a rapid final delta synchronization with `--delete` to capture the quiesced database state and prune removed files:
```bash
sudo rsync -aHAX --delete --info=progress2 \
--exclude=".venv" \
--exclude=".pytest_cache" \
/home/<legacy-operator>/Core/ /home/operator/Core/
sudo rsync -aHAX --delete --info=progress2 \
/home/<legacy-operator>/Sites/ /home/operator/Sites/
```
4. **Fix ownership and permissions**:
Set primary ownership to `operator` and group to `homelab-operators`:
```bash
sudo chown -R operator:homelab-operators /home/operator/Core /home/operator/Sites /home/operator/.config
sudo chmod -R u+rwX,g+rX /home/operator/Core /home/operator/Sites
# ACME certificate security invariant: Traefik strictly requires 0600 on acme.json;
# recursive group read permissions will cause Traefik to refuse to start.
if [ -f /home/operator/Core/config/letsencrypt/acme.json ]; then
sudo chmod 600 /home/operator/Core/config/letsencrypt/acme.json
fi
```
---
### Stage 3: Service Rebuild & Environment Cutover
Activate the declarative configuration under the `operator` profile:
1. **Configure instance domain injection (Decision D1)**:
Ensure `nixos/instance.nix` (or `/etc/nixos/homelab-instance.nix`) is in place with the host's production domain:
```bash
cat << 'EOF' | sudo -u operator tee /home/operator/Core/nixos/instance.nix > /dev/null
{
homelab.domain = "example.com";
}
EOF
chmod 600 /home/operator/Core/nixos/instance.nix
```
2. **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
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
```
> [!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).
3. **Restart platform services**:
Restart the Core Compose stack and control plane services to consume updated paths:
```bash
sudo systemctl restart homeserver-core
sudo systemctl restart homelab-appctl
sudo systemctl restart homelab-gitops
```
---
### Stage 4: Post-Flight Verification
Validate system health and operational readiness under the `operator` identity:
1. **Verify Git safe directory**:
Ensure Git does not complain about dubious ownership when invoked by `operator` or `homelab-appctl`:
```bash
sudo -u operator git -C /home/operator/Core status
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:
```bash
sudo ls -l /run/secrets/appctl/tokens.json
```
4. **Verify container reachability & proxy routing**:
Check that external endpoints and internal reverse proxies resolve:
```bash
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
curl -s -k https://127.0.0.1 -H "Host: dashboard.example.com" | head -n 5
```
---
### Rollback Procedure
If unexpected service degradation occurs during the cutover:
1. **Revert NixOS system generation**:
```bash
sudo nixos-rebuild switch --rollback
```
2. **Restart legacy Core services**:
```bash
sudo systemctl restart homeserver-core
sudo systemctl restart homelab-appctl
sudo systemctl restart homelab-gitops
```
3. **Log rollback reason**:
Record the diagnostic failure logs in `journalctl -xe` and investigate before attempting another cutover window.
+21 -3
View File
@@ -29,9 +29,20 @@ This plan establishes the concrete implementation work packages to resolve these
- NixOS declares user `operator` (`uid = 1000` or standard user, `extraGroups = [ "wheel" "docker" "homelab-operators" "networkmanager" ]`).
- Eliminates hardcoded personal usernames from the Core platform foundation.
### B. Platform Genericism & Instance Profile
- Core modules in `nixos/modules/` remain strictly generic, defaulting to RFC 2606 placeholders (`example.test`).
- `nixos/configuration.nix` serves as the appliance instance profile where `homelab.domain` and `homelab.operatorUser` are explicitly set (e.g., using the host's configured production domain).
### B. Platform Genericism & Instance Profile (Decision D1)
- Core modules in `nixos/modules/` remain strictly generic, defaulting to RFC 2606 placeholders (`example.test` and `operator`).
- **Decision D1: Dual-Path Instance Domain Injection**: Rather than committing host-specific production domains to tracked Git files, `nixos/configuration.nix` implements an optional dual-path import mechanism:
```nix
imports = [
./hardware-configuration.nix
./modules/homeserver.nix
./modules/traefik-deployments.nix
./modules/dynu.nix
./modules/shell.nix
] ++ lib.optional (builtins.pathExists ./instance.nix) ./instance.nix
++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix;
```
- `nixos/instance.nix` is git-ignored, allowing host-specific overrides (like `homelab.domain = "example.com";`) without dirtying version control. Alternatively, `/etc/nixos/homelab-instance.nix` provides a persistent host-level configuration path outside the repository checkout.
- `LLDAP_LDAP_BASE_DN` is computed dynamically in Nix from `config.homelab.domain` (`domain: example.test` $\implies$ `dc=example,dc=test`), eliminating hardcoded domain strings across templates and Compose files.
### C. Control Plane Security & POSIX Permissions
@@ -72,6 +83,13 @@ This plan establishes the concrete implementation work packages to resolve these
- [x] **Task 3.4**: Update `docs/appctl.md` (clarifying bounded log snapshots and Core update workflow).
- [x] **Task 3.5**: Synchronize `todo.txt` with active implementation tasks.
### Phase 4: Work Package 6 (WP6: Instance Decoupling & Operator Cutover Runbook)
- [x] **Task 4.1**: Update `nixos/configuration.nix` with optional dual-path imports for `./instance.nix` and `/etc/nixos/homelab-instance.nix` (Decision D1).
- [x] **Task 4.2**: Add `nixos/instance.nix` to `.gitignore` to preserve 100% repository genericism.
- [x] **Task 4.3**: Implement automated invariant tests in `tests/security/test_security_invariants.py` (default domain evaluation, dynamic LDAP base DN, instance override, platform genericism).
- [x] **Task 4.4**: Document instance domain injection procedure in `docs/setup_guide.md`.
- [x] **Task 4.5**: Codify the 4-stage Staged Coexistence Cutover Runbook (Decision D2) in `docs/operations.md` with explicit notice blocking live host execution pending maintenance window.
---
## 4. Verification & Quality Gates
+47 -7
View File
@@ -32,24 +32,64 @@ sudo ls -l /etc/ssh/ssh_host_ed25519_key
sudo chmod 600 /etc/ssh/ssh_host_ed25519_key
```
### Step 2: Apply Declarative NixOS Configuration
### Step 2: Configure Appliance Instance Domain (Decision D1)
To preserve strict platform genericism, the repository files tracked in Git never contain production domains or personal operator identities, defaulting to RFC 2606 placeholders (`example.test` and `operator`).
An appliance host supplies its production domain and local configuration overrides via one of two untracked dual-path files:
1. **Repository-local instance profile (`nixos/instance.nix`)**:
Create an untracked, git-ignored file in `nixos/instance.nix`:
```nix
{
homelab.domain = "example.com";
}
```
When rebuilding via `sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure` (or `path:~/Core#server --impure`), Nix automatically imports `nixos/instance.nix` if present.
> [!NOTE]
> **Flake Fetcher Scheme for Untracked Files**:
> Because `nixos/instance.nix` is gitignored, Nix's default Git fetcher filters it out when evaluating standard Git flake references (e.g. `--flake ~/Core#server`). Prefixing the path with the `path:` scheme (e.g. `path:/home/operator/Core#server` or `path:~/Core#server`) instructs Nix to evaluate directly from the filesystem without filtering by the Git index.
> If using the host-level `/etc/nixos/homelab-instance.nix` instead, a bare `--flake .#server --impure` works directly because `/etc/nixos` resides outside the Git repository tree.
2. **Host-level instance profile (`/etc/nixos/homelab-instance.nix`)**:
Alternatively, create a host-level file outside the Git checkout:
```nix
{
homelab.domain = "example.com";
}
```
This persists configuration across fresh repository clones or ephemeral branches.
Both paths are declared optionally in `nixos/configuration.nix`:
```nix
imports = [
./hardware-configuration.nix
./modules/homeserver.nix
./modules/traefik-deployments.nix
./modules/dynu.nix
./modules/shell.nix
] ++ lib.optional (builtins.pathExists ./instance.nix) ./instance.nix
++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix;
```
When present, `homelab.domain` overrides the default (`example.test`), and all generated templates (`homeserver.env`, Traefik routing rules, and the dynamic `LLDAP_LDAP_BASE_DN`) automatically reflect the production domain without altering any tracked Git files.
### Step 3: Apply Declarative NixOS Configuration
```bash
cd ~/Core
sudo nixos-rebuild switch --flake ~/Core#server
sudo nixos-rebuild switch --flake path:/home/operator/Core#server --impure
```
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`).
* Systemd service units (`homeserver-core`, `homelab-appctl`, `homelab-gitops`, `dynu-monitor`).
### Step 3: Create External Docker Networks
### Step 4: 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
### Step 5: Start Platform Services
```bash
sudo systemctl start homeserver-core
```
@@ -58,7 +98,7 @@ Check running containers:
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
```
### Step 5: Verify DNS & Certificates
### Step 6: Verify DNS & Certificates
1. Trigger an immediate DDNS update:
```bash
sudo systemctl start dynu-monitor
@@ -68,7 +108,7 @@ docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
appctl ssl traefik
```
### Step 6: Initialize LLDAP Directory
### Step 7: Initialize LLDAP Directory
1. Navigate to `https://users.${HOMELAB_DOMAIN}` (e.g., `https://users.example.com`).
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.
+2 -1
View File
@@ -12,7 +12,8 @@
./modules/traefik-deployments.nix # Traefik deployment secrets and env templates
./modules/dynu.nix # Dynu DDNS smart IP monitor service
./modules/shell.nix # Declarative bash environment for the server
];
] ++ lib.optional (builtins.pathExists ./instance.nix) ./instance.nix
++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix;
# ── Homelab platform settings ────────────────────────────────────────────────
homelab.operatorUser = "operator";
+130
View File
@@ -4,6 +4,7 @@ Security invariant tests for Docker Compose and container isolation.
import os
import shutil
import subprocess
from pathlib import Path
import yaml
@@ -289,3 +290,132 @@ def test_nixos_tmpfiles_rules_use_recursive_acls():
"tmpfiles.rules must use uppercase 'A+' for recursive ACL inheritance on homepage config"
)
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"
content = homeserver_nix.read_text(encoding="utf-8")
assert 'default = "example.test";' in content, (
"homeserver.nix must set default homelab.domain to 'example.test'"
)
nix_bin = shutil.which("nix")
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
cmd = [
nix_bin,
"eval",
".#nixosConfigurations.server.config.homelab.domain",
"--raw",
]
res = subprocess.run(
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
)
assert res.stdout.strip() == "example.test", (
f"Default homelab.domain must be 'example.test', got '{res.stdout.strip()}'"
)
def test_dynamic_lldap_base_dn_splits_domain_components():
"""Assert dynamic LLDAP_LDAP_BASE_DN splits domain into dc=... components for any domain."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
assert "LLDAP_LDAP_BASE_DN = ldapBaseDn;" in content, (
"homeserver.nix must bind LLDAP_LDAP_BASE_DN to ldapBaseDn in homeserver.env template"
)
assert 'domainParts = lib.splitString "." config.homelab.domain;' in content, (
"homeserver.nix must split homelab.domain by '.'"
)
assert 'ldapBaseDn = lib.concatStringsSep "," (map (part: "dc=${part}") domainParts);' in content, (
"homeserver.nix must map domain components into dc=${part}"
)
nix_bin = shutil.which("nix")
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
cases = [
("example.test", "dc=example,dc=test"),
("my.homelab.internal", "dc=my,dc=homelab,dc=internal"),
("local", "dc=local"),
]
for domain, expected_dn in cases:
expr = (
f'let flake = builtins.getFlake (toString ./.); lib = flake.inputs.nixpkgs.lib; '
f'domainParts = lib.splitString "." "{domain}"; '
f'in lib.concatStringsSep "," (map (part: "dc=${{part}}") domainParts)'
)
cmd = [
nix_bin,
"eval",
"--impure",
"--expr",
expr,
"--raw",
]
res = subprocess.run(
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
)
assert res.stdout.strip() == expected_dn, (
f"Expected {expected_dn} for domain {domain}, got {res.stdout.strip()}"
)
# Also assert rendered sops template in default configuration contains correct LLDAP_LDAP_BASE_DN
cmd_tpl = [
nix_bin,
"eval",
'.#nixosConfigurations.server.config.sops.templates."homeserver.env".content',
"--raw",
]
res_tpl = subprocess.run(
cmd_tpl, cwd=CORE_ROOT, capture_output=True, text=True, check=True
)
assert "LLDAP_LDAP_BASE_DN=dc=example,dc=test" in res_tpl.stdout
def test_dual_path_import_overrides_homelab_domain():
"""Assert dual-path import overrides homelab.domain when ./nixos/instance.nix is present."""
nix_bin = shutil.which("nix")
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
instance_nix = CORE_ROOT / "nixos" / "instance.nix"
try:
instance_nix.write_text(
'{ homelab.domain = "custom.internal"; }\n', encoding="utf-8"
)
cmd = [
nix_bin,
"eval",
"--impure",
"path:.#nixosConfigurations.server.config.homelab.domain",
"--raw",
]
res = subprocess.run(
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
)
assert res.stdout.strip() == "custom.internal", (
f"Expected homelab.domain to be overridden to 'custom.internal', got '{res.stdout.strip()}'"
)
finally:
if instance_nix.exists():
instance_nix.unlink()
def test_nixos_configuration_declares_dual_path_instance_imports():
"""Ensure nixos/configuration.nix includes optional dual-path instance imports."""
config_nix = CORE_ROOT / "nixos" / "configuration.nix"
content = config_nix.read_text(encoding="utf-8")
assert "builtins.pathExists ./instance.nix" in content, (
"nixos/configuration.nix must check for ./instance.nix via builtins.pathExists"
)
assert "builtins.pathExists /etc/nixos/homelab-instance.nix" in content, (
"nixos/configuration.nix must check for /etc/nixos/homelab-instance.nix via builtins.pathExists"
)
def test_gitignore_includes_instance_nix():
"""Ensure nixos/instance.nix is ignored in .gitignore to preserve platform genericism."""
gitignore = CORE_ROOT / ".gitignore"
content = gitignore.read_text(encoding="utf-8")
lines = [line.strip() for line in content.splitlines()]
assert "nixos/instance.nix" in lines, (
"nixos/instance.nix must be explicitly ignored in .gitignore"
)
+1
View File
@@ -44,3 +44,4 @@ x 2026-10-30 (B) Restore live container status inspection in workload.list and f
x 2026-10-30 (B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth
x 2026-10-30 (B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4
x 2026-10-30 (C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap
x 2026-10-30 (A) Implement instance domain injection dual-path import and operator cutover runbook in nixos/configuration.nix and docs/ +generic @nixos