Compare commits

...
4 Commits
Author SHA1 Message Date
kiskaadee 03c8fdcf8e docs(core): reconcile README and SECURITY with Milestone P4 control plane daemon architecture
Core Architecture & Invariant CI / validate (pull_request) Failing after 1m1s
- Update README.md to describe homelab-appctl.service operational control plane daemon architecture over UDS and loopback HTTP
- Update Repository Structure table to include bootstrap_token.py and appctl_*.py daemon modules
- Update Host System Management rebuild commands across docs to use path:$HOME/Core#server --impure
- Document control plane transport isolation, SO_PEERCRED viewer auth, SHA-256 tokens, 3-tier RBAC, per-target flocking, and fail-closed audit logging in SECURITY.md
2026-10-30 13:46:22 -05:00
kiskaadee 3ba8e2b51d docs(operations): include var/lib/homelab state and workload quiescence in operator cutover runbook
- Add explicit guidance to maintain active legacy SSH/terminal session throughout migration to prevent lockout
- Document fallback operator user provisioning if coexistence account is not yet active
- Add /home/<legacy-operator>/var/lib/homelab and ~/.local/state/homelab to initial and final rsync stages to prevent workload state stranding
- Quiesce active workload containers alongside core platform services before final rsync delta to guarantee database consistency
- Extend ownership fixup to /home/operator/var and /home/operator/.local
2026-10-30 13:42:34 -05:00
kiskaadee 4f1a63160b fix(provenance): report non-zero git status exits and update bootstrap rebuild hint
- Update get_local_checkout_status in scripts/provenance.py to surface non-zero git status exit codes as '⚠️ Git Error (exit <code>)' rather than masking them as '✓ Clean'
- Update scripts/bootstrap_token.py rebuild instruction to use path:$HOME/Core#server --impure, ensuring instance.nix evaluation is respected
- Add unit test coverage for non-zero git exit handling and bootstrap rebuild guidance
2026-10-30 13:40:22 -05:00
kiskaadee e2dbc97b0e fix(nixos): add Core to git safe.directory and update nix-switch to path flake scheme
- Update nixos/configuration.nix to include /home/${operatorUser}/Core in programs.git.config.safe.directory, preventing dubious ownership errors when homelab-appctl runs read-only status checks
- Update nix-switch alias in nixos/modules/shell.nix to use path:$HOME/Core#server --impure, ensuring gitignored instance.nix domain injection evaluates reliably
- Add security invariant tests asserting safe.directory configuration and nix-switch alias format
2026-10-30 13:37:10 -05:00
12 changed files with 182 additions and 37 deletions

No files matched your search

+26 -11
View File
@@ -9,7 +9,7 @@ It is designed around a strict two-tier boundary:
All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_DOMAIN`) and secrets (`/run/secrets/`) are injected declaratively at runtime. All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_DOMAIN`) and secrets (`/run/secrets/`) are injected declaratively at runtime.
> [!NOTE] > [!NOTE]
> **Current Implementation Baseline vs. Target Architecture**: This README documents the **currently implemented CLI and runtime baseline (Milestone P3)**. Under [Milestone P4 in `ROADMAP.md`](ROADMAP.md), `appctl` is transitioning from a host CLI orchestrator into a dedicated daemon service (`homelab-appctl.service`) exposing a unified logical API across local Unix socket and HTTP transports. See [`ROADMAP.md`](ROADMAP.md) for the full baseline-to-target matrix. > **Milestone P4 Control Plane Architecture**: Under [Milestone P4 in `ROADMAP.md`](ROADMAP.md), `appctl` operates as an operational control plane daemon service (`homelab-appctl.service`) exposing a unified logical API across a local Unix Domain Socket (`/run/homelab/appctl.sock`) and loopback HTTP (`127.0.0.1:9876`). The thin `appctl` CLI delegates commands to this daemon with automatic `SO_PEERCRED` identity inspection and token-based RBAC. See [`docs/appctl.md`](docs/appctl.md) and [`ROADMAP.md`](ROADMAP.md) for details.
--- ---
@@ -49,8 +49,10 @@ All platform definitions are strictly instance-agnostic; domain names (`HOMELAB_
▲ ▲
│ (Host Orchestration & CD) │ (Host Orchestration & CD)
┌───────────────┴───────────────┐ ┌───────────────┴───────────────┐
│ Host Control Plane Baseline │ │ Host Control Plane (P4) │
│ • appctl CLI + Engine │ │ • thin appctl CLI │
│ • homelab-appctl.service │
│ (UDS / HTTP daemon) │
│ • homelab-gitops.service │ │ • homelab-gitops.service │
└───────────────────────────────┘ └───────────────────────────────┘
``` ```
@@ -82,10 +84,17 @@ For detailed runtime layers, network segmentation, and the P4 control-plane tran
├── nixos/ # Declarative NixOS modules, systemd units, and SOPS secret wiring ├── nixos/ # Declarative NixOS modules, systemd units, and SOPS secret wiring
├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml) ├── config/ # Service configurations (Traefik, Authelia, Homepage, deployments.yaml)
├── scripts/ ├── scripts/
│ ├── appctl # Operational CLI entrypoint and Compose environment orchestrator │ ├── appctl # Thin operational CLI delegating to control plane daemon
│ ├── appctl_engine.py # Discovery, two-axis provenance, TLS inspection, and Homepage sync engine │ ├── appctl_daemon.py # Async HTTP/UDS daemon server (homelab-appctl.service)
│ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for workload app.yaml │ ├── appctl_router.py # Operational router, locking, RBAC & dispatch
│ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST security validation │ ├── appctl_auth.py # SO_PEERCRED & Bearer token RBAC authentication
│ ├── appctl_audit.py # Append-only fail-closed structured audit logger
│ ├── appctl_contracts.py # Pydantic v2 schemas for daemon RPC requests & responses
│ ├── appctl_cli.py # Unified CLI client with dual transport fallbacks
│ ├── appctl_engine.py # Discovery, two-axis provenance, TLS inspection, and Homepage sync
│ ├── bootstrap_token.py # Operator Bearer token provisioning helper
│ ├── core_manifest.py # Authoritative Pydantic v2 schema v1.0 parser for app.yaml
│ ├── gitops_dispatcher.py # Authenticated webhook CD engine with Compose AST validation
│ └── test # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks) │ └── test # Automated verification gate (Ruff, Pyright, Pytest, Nix flake checks)
├── tests/ # Unit, structural, and security invariant test suites ├── tests/ # Unit, structural, and security invariant test suites
└── docs/ # Architecture references, operational runbooks, and MADR decisions └── docs/ # Architecture references, operational runbooks, and MADR decisions
@@ -93,7 +102,7 @@ For detailed runtime layers, network segmentation, and the P4 control-plane tran
--- ---
## Quickstart & Operations (Current CLI Baseline) ## Quickstart & Operations (Control Plane Daemon & CLI)
### Development & Verification ### Development & Verification
@@ -111,7 +120,12 @@ pyright
### Workload Management (`appctl` CLI) ### Workload Management (`appctl` CLI)
The thin `appctl` CLI connects directly to `homelab-appctl.service` via Unix Domain Socket (`/run/homelab/appctl.sock`) or loopback HTTP (`127.0.0.1:9876`). Local operators in `homelab-operators` or `wheel` receive read-only viewer access via kernel `SO_PEERCRED` without tokens, while mutating actions consume Bearer tokens from `~/.config/homelab/token`:
```bash ```bash
# Check daemon health status
appctl health
# List all workloads with container health and local Git checkout status # List all workloads with container health and local Git checkout status
appctl list appctl list
@@ -121,7 +135,7 @@ appctl list --fetch --ssl --core
# Inspect detailed manifest, provenance, and container diagnostics for a workload # Inspect detailed manifest, provenance, and container diagnostics for a workload
appctl info <service> appctl info <service>
# Manage workload or Core service lifecycle (executes docker compose locally in the current baseline) # Manage workload or Core service lifecycle (dispatched via homelab-appctl daemon)
appctl up <service|core> appctl up <service|core>
appctl down <service|core> appctl down <service|core>
appctl restart <service|core> appctl restart <service|core>
@@ -136,11 +150,12 @@ appctl sync
### Host System Management ### Host System Management
```bash ```bash
# Rebuild and activate the NixOS host configuration # Rebuild and activate the NixOS host configuration (or use the 'nix-switch' alias)
sudo nixos-rebuild switch --flake .#server sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
# Inspect platform systemd units # Inspect platform systemd units
systemctl status homeserver-core.service systemctl status homeserver-core.service
systemctl status homelab-appctl.service
systemctl status homelab-gitops.service systemctl status homelab-gitops.service
systemctl status dynu-monitor.service systemctl status dynu-monitor.service
``` ```
+12
View File
@@ -31,6 +31,15 @@ This document outlines the security controls, container isolation rules, and ope
* Secrets are stored encrypted in `nixos/secrets.yaml` using Age keys derived from the host SSH key (`/etc/ssh/ssh_host_ed25519_key`). * Secrets are stored encrypted in `nixos/secrets.yaml` using Age keys derived from the host SSH key (`/etc/ssh/ssh_host_ed25519_key`).
* Decrypted secrets reside in RAM-backed ephemeral filesystems (`/run/secrets/`, `/run/credentials/`) and are not committed to unencrypted persistent files. * Decrypted secrets reside in RAM-backed ephemeral filesystems (`/run/secrets/`, `/run/credentials/`) and are not committed to unencrypted persistent files.
### F. Operational Control Plane Security (`homelab-appctl.service`)
* **Transport Isolation**: Daemon listens on a restricted Unix Domain Socket (`/run/homelab/appctl.sock`, mode `0660`, group `homelab-operators`) and loopback HTTP (`127.0.0.1:9876`). It never binds to public interfaces.
* **Authentication & RBAC**:
- **UDS Peer Credential Identification**: Local connections inspect kernel peer credentials (`SO_PEERCRED`). Callers in `homelab-operators` or `wheel` receive read-only viewer privileges automatically without requiring secrets on disk.
- **Cryptographic Bearer Tokens**: Mutating actions require Bearer tokens defined in SOPS (`/run/secrets/appctl/tokens.json`). Tokens are validated using `hmac.compare_digest` against SHA-256 digests.
- **Three-Tier RBAC**: Granular role enforcement distinguishes read-only inspectors (`viewer`), workload managers (`operator`), and core platform administrators (`admin`).
* **Per-Target Concurrency Control (`flock`)**: Non-blocking file locks (`/run/lock/homelab/<target>.lock`) serialize mutating actions per workload, returning HTTP 409 Conflict if an operation is already in flight.
* **Fail-Closed Structured Audit Logging**: Every operational command is appended synchronously to a tamper-evident audit log (`/var/log/homelab/appctl/audit.jsonl`, mode `0600`). If disk writing fails, the daemon fails closed and rejects the request.
--- ---
## 2. Threat Model & Operational Considerations ## 2. Threat Model & Operational Considerations
@@ -57,3 +66,6 @@ This document outlines the security controls, container isolation rules, and ope
- [x] Invariant test runner (`./scripts/test`) passing on changes. - [x] Invariant test runner (`./scripts/test`) passing on changes.
- [x] `config/letsencrypt/acme.json` permissions set to `0600`. - [x] `config/letsencrypt/acme.json` permissions set to `0600`.
- [x] Host firewall ports restricted to declared services in `nixos/modules/homeserver.nix`. - [x] Host firewall ports restricted to declared services in `nixos/modules/homeserver.nix`.
- [x] Control plane daemon (`homelab-appctl.service`) isolated to UDS (`0660`) and loopback HTTP.
- [x] Operational audit log (`/var/log/homelab/appctl/audit.jsonl`) append-only with strict `0600` permissions.
- [x] Control plane mutation endpoints enforce per-target `flock` and SHA-256 Bearer tokens.
+2 -2
View File
@@ -111,7 +111,7 @@ appctl:
Save and exit your editor (SOPS will re-encrypt the file), then project the updated secrets: Save and exit your editor (SOPS will re-encrypt the file), then project the updated secrets:
```bash ```bash
sudo nixos-rebuild switch --flake ~/Core#server sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
``` ```
This updates `/run/secrets/appctl/tokens.json` (owned by `homelab-appctl:homelab-operators`, mode `0400`), which `homelab-appctl.service` consumes. This updates `/run/secrets/appctl/tokens.json` (owned by `homelab-appctl:homelab-operators`, mode `0400`), which `homelab-appctl.service` consumes.
@@ -135,7 +135,7 @@ Verify permissions using both unauthenticated and authenticated queries:
To rotate an operator token: To rotate an operator token:
1. Run `python3 scripts/bootstrap_token.py --force --token-id "operator-admin-$(date +%Y%m%d)"`. 1. Run `python3 scripts/bootstrap_token.py --force --token-id "operator-admin-$(date +%Y%m%d)"`.
2. Open `sops nixos/secrets.yaml` and add the new descriptor to `appctl.tokens_json`. Keep the old entry temporarily if multiple sessions share it, or replace it immediately. 2. Open `sops nixos/secrets.yaml` and add the new descriptor to `appctl.tokens_json`. Keep the old entry temporarily if multiple sessions share it, or replace it immediately.
3. Run `sudo nixos-rebuild switch --flake ~/Core#server` to apply the updated token store. 3. Run `sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure` to apply the updated token store.
4. Verify CLI operations (`appctl config docs`). 4. Verify CLI operations (`appctl config docs`).
5. Remove the deprecated token descriptor from `nixos/secrets.yaml` and re-run `nixos-rebuild switch`. 5. Remove the deprecated token descriptor from `nixos/secrets.yaml` and re-run `nixos-rebuild switch`.
+58 -18
View File
@@ -296,20 +296,29 @@ To bring up a replacement host from version control:
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. 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 ### Stage 1: Pre-Flight Checks & Session Preservation
Before initiating data synchronization or service cutover, verify the target `operator` account environment:
1. **Verify `operator` account existence and home directory**: > [!IMPORTANT]
> **Maintain Active Legacy Shell Session**:
> Do not terminate your active SSH or terminal session as `<legacy-operator>`. Keep at least one authenticated shell open throughout the entire cutover process to prevent lockout in case of SSH key, user profile, or PAM misconfiguration.
1. **Verify or provision `operator` account**:
Check if the `operator` user exists in the running environment:
```bash ```bash
id operator id operator
# Expected output must include membership in: wheel, docker, homelab-operators ```
ls -ld /home/operator If `operator` does not exist yet (as `homelab.operatorUser` has not been switched in the active NixOS generation), provision the initial coexistence user before proceeding:
```bash
sudo useradd -m -s /run/current-system/sw/bin/bash -G wheel,docker,homelab-operators operator
``` ```
2. **Verify SSH key provisioning**: 2. **Verify SSH key provisioning & permissions**:
Ensure the operator's authorized keys are installed with strict permissions: Ensure the operator's authorized keys are installed with strict permissions (copying from `<legacy-operator>` if needed):
```bash ```bash
sudo ls -la /home/operator/.ssh/authorized_keys sudo mkdir -p /home/operator/.ssh
if [ ! -f /home/operator/.ssh/authorized_keys ] && [ -f /home/<legacy-operator>/.ssh/authorized_keys ]; then
sudo cp /home/<legacy-operator>/.ssh/authorized_keys /home/operator/.ssh/authorized_keys
fi
sudo chmod 700 /home/operator/.ssh sudo chmod 700 /home/operator/.ssh
sudo chmod 600 /home/operator/.ssh/authorized_keys sudo chmod 600 /home/operator/.ssh/authorized_keys
sudo chown -R operator:users /home/operator/.ssh sudo chown -R operator:users /home/operator/.ssh
@@ -321,20 +330,20 @@ Before initiating data synchronization or service cutover, verify the target `op
sudo -u operator sudo -n true || echo "Passwordless or password sudo required for operator" sudo -u operator sudo -n true || echo "Passwordless or password sudo required for operator"
``` ```
4. **Verify persistent directories**: 4. **Prepare persistent directories**:
Ensure `/home/operator/Sites` and `/home/operator/Core` target parent paths are ready: Ensure `/home/operator/Sites`, `/home/operator/Core`, `/home/operator/var/lib/homelab`, and state parent paths are ready:
```bash ```bash
sudo mkdir -p /home/operator/{Core,Sites,.config/homelab} sudo mkdir -p /home/operator/{Core,Sites,.config/homelab,var/lib/homelab,.local/state/homelab}
sudo chown -R operator:homelab-operators /home/operator/{Core,Sites,.config} sudo chown -R operator:homelab-operators /home/operator/{Core,Sites,.config,var,.local}
``` ```
--- ---
### Stage 2: State and Repository Synchronization ### 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): Synchronize repository checkouts, workload persistent data, 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**: 1. **Initial background synchronization**:
Seed the file trees for Core and Sites while services continue running: Seed the file trees for Core, Sites, workload databases, and configurations while services continue running:
```bash ```bash
sudo rsync -aHAX --info=progress2 \ sudo rsync -aHAX --info=progress2 \
--exclude=".venv" \ --exclude=".venv" \
@@ -344,6 +353,16 @@ Synchronize repository checkouts, environment definitions, and runtime state fro
sudo rsync -aHAX --info=progress2 \ sudo rsync -aHAX --info=progress2 \
/home/<legacy-operator>/Sites/ /home/operator/Sites/ /home/<legacy-operator>/Sites/ /home/operator/Sites/
if [ -d "/home/<legacy-operator>/var/lib/homelab" ]; then
sudo rsync -aHAX --info=progress2 \
/home/<legacy-operator>/var/lib/homelab/ /home/operator/var/lib/homelab/
fi
if [ -d "/home/<legacy-operator>/.local/state/homelab" ]; then
sudo rsync -aHAX --info=progress2 \
/home/<legacy-operator>/.local/state/homelab/ /home/operator/.local/state/homelab/
fi
if [ -d "/home/<legacy-operator>/.config/homelab" ]; then if [ -d "/home/<legacy-operator>/.config/homelab" ]; then
sudo rsync -aHAX --info=progress2 \ sudo rsync -aHAX --info=progress2 \
/home/<legacy-operator>/.config/homelab/ /home/operator/.config/homelab/ /home/<legacy-operator>/.config/homelab/ /home/operator/.config/homelab/
@@ -351,9 +370,15 @@ Synchronize repository checkouts, environment definitions, and runtime state fro
``` ```
2. **Quiesce active database writers**: 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: Stop running workload containers and the Core platform stack to guarantee point-in-time consistency across SQLite databases (e.g. LLDAP `users.db`, Authelia `db.sqlite3`, Stalwart storage, and workload app volumes in `~/var/lib/homelab/`) before the final sync:
```bash ```bash
# Stop running workload containers
appctl down --all 2>/dev/null || docker stop $(docker ps -q) 2>/dev/null || true
# Stop platform core services
sudo systemctl stop homeserver-core sudo systemctl stop homeserver-core
sudo systemctl stop homelab-appctl
sudo systemctl stop homelab-gitops
``` ```
3. **Final delta synchronization (`--delete`)**: 3. **Final delta synchronization (`--delete`)**:
@@ -366,13 +391,28 @@ Synchronize repository checkouts, environment definitions, and runtime state fro
sudo rsync -aHAX --delete --info=progress2 \ sudo rsync -aHAX --delete --info=progress2 \
/home/<legacy-operator>/Sites/ /home/operator/Sites/ /home/<legacy-operator>/Sites/ /home/operator/Sites/
if [ -d "/home/<legacy-operator>/var/lib/homelab" ]; then
sudo rsync -aHAX --delete --info=progress2 \
/home/<legacy-operator>/var/lib/homelab/ /home/operator/var/lib/homelab/
fi
if [ -d "/home/<legacy-operator>/.local/state/homelab" ]; then
sudo rsync -aHAX --delete --info=progress2 \
/home/<legacy-operator>/.local/state/homelab/ /home/operator/.local/state/homelab/
fi
``` ```
4. **Fix ownership and permissions**: 4. **Fix ownership and permissions**:
Set primary ownership to `operator` and group to `homelab-operators`: Set primary ownership to `operator` and group to `homelab-operators` across all migrated trees:
```bash ```bash
sudo chown -R operator:homelab-operators /home/operator/Core /home/operator/Sites /home/operator/.config sudo chown -R operator:homelab-operators \
sudo chmod -R u+rwX,g+rX /home/operator/Core /home/operator/Sites /home/operator/Core \
/home/operator/Sites \
/home/operator/.config \
/home/operator/.local \
/home/operator/var
sudo chmod -R u+rwX,g+rX /home/operator/Core /home/operator/Sites /home/operator/var
# ACME certificate security invariant: Traefik strictly requires 0600 on acme.json; # ACME certificate security invariant: Traefik strictly requires 0600 on acme.json;
# recursive group read permissions will cause Traefik to refuse to start. # recursive group read permissions will cause Traefik to refuse to start.
+1 -1
View File
@@ -103,7 +103,7 @@ brevo:
### 3. Save and Apply Changes ### 3. Save and Apply Changes
Saving the file in your editor automatically re-encrypts it with Age. Apply the updated templates to running services: Saving the file in your editor automatically re-encrypts it with Age. Apply the updated templates to running services:
```bash ```bash
sudo nixos-rebuild switch --flake ~/Core#server sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure
``` ```
--- ---
+1
View File
@@ -22,6 +22,7 @@
programs.git = { programs.git = {
enable = true; enable = true;
config.safe.directory = [ config.safe.directory = [
"/home/${config.homelab.operatorUser}/Core"
"/home/${config.homelab.operatorUser}/Sites/*" "/home/${config.homelab.operatorUser}/Sites/*"
]; ];
}; };
+2 -2
View File
@@ -62,8 +62,8 @@
reload = "exec bash"; reload = "exec bash";
pgoog = "ping google.com -c 3"; pgoog = "ping google.com -c 3";
wifi = "nmtui"; wifi = "nmtui";
# NixOS rebuild targeting this flake # NixOS rebuild targeting this flake (path scheme + impure required for instance.nix)
nix-switch = "sudo nixos-rebuild switch --flake ~/Core#server"; nix-switch = "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure";
}; };
interactiveShellInit = '' interactiveShellInit = ''
+1 -1
View File
@@ -163,7 +163,7 @@ def main(argv: list[str] | None = None) -> int:
f"Add the following descriptor to your SOPS tokens store (nixos/secrets.yaml -> appctl/tokens_json):\n\n" f"Add the following descriptor to your SOPS tokens store (nixos/secrets.yaml -> appctl/tokens_json):\n\n"
f"{json_snippet}\n\n" f"{json_snippet}\n\n"
f"After updating nixos/secrets.yaml with `sops nixos/secrets.yaml`, apply changes with:\n" f"After updating nixos/secrets.yaml with `sops nixos/secrets.yaml`, apply changes with:\n"
f" sudo nixos-rebuild switch --flake ~/Core#server\n" f" sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure\n"
) )
return 0 return 0
+10 -2
View File
@@ -109,6 +109,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
# 1. Check cleanliness # 1. Check cleanliness
is_dirty = False is_dirty = False
git_error: str | None = None
try: try:
status_res = subprocess.run( status_res = subprocess.run(
["git", "-C", str(path), "status", "--porcelain"], ["git", "-C", str(path), "status", "--porcelain"],
@@ -118,10 +119,14 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
timeout=5.0, timeout=5.0,
env=git_env, env=git_env,
) )
if status_res.returncode == 0 and status_res.stdout.strip(): if status_res.returncode == 0:
if status_res.stdout.strip():
is_dirty = True is_dirty = True
except (subprocess.SubprocessError, OSError): else:
git_error = f"⚠️ Git Error (exit {status_res.returncode})"
except (subprocess.SubprocessError, OSError) as exc:
is_dirty = False is_dirty = False
git_error = f"⚠️ Git Error ({exc.__class__.__name__})"
# 2. Get active branch # 2. Get active branch
branch = "" branch = ""
@@ -168,6 +173,9 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
commit_sha = "" commit_sha = ""
# 4. Format status label # 4. Format status label
if git_error:
status_label = git_error
else:
state_symbol = "* Dirty" if is_dirty else "✓ Clean" state_symbol = "* Dirty" if is_dirty else "✓ Clean"
ref_desc = f"{branch}@{commit_sha}" if commit_sha else branch ref_desc = f"{branch}@{commit_sha}" if commit_sha else branch
status_label = f"{state_symbol} ({ref_desc})" if ref_desc else state_symbol status_label = f"{state_symbol} ({ref_desc})" if ref_desc else state_symbol
@@ -419,3 +419,55 @@ def test_gitignore_includes_instance_nix():
) )
def test_nixos_switch_alias_uses_path_and_impure():
"""Ensure nix-switch alias in nixos/modules/shell.nix uses path: and --impure to prevent silent fail-open."""
shell_nix = CORE_ROOT / "nixos" / "modules" / "shell.nix"
content = shell_nix.read_text(encoding="utf-8")
assert 'nix-switch = "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure";' in content, (
"nixos/modules/shell.nix must configure nix-switch alias with path:$HOME/Core#server --impure"
)
def test_nixos_safe_directory_includes_core_and_sites():
"""Ensure programs.git.config.safe.directory includes Core and Sites to prevent dubious ownership errors."""
config_nix = CORE_ROOT / "nixos" / "configuration.nix"
content = config_nix.read_text(encoding="utf-8")
assert '"/home/${config.homelab.operatorUser}/Core"' in content, (
"nixos/configuration.nix must include Core in git safe.directory"
)
assert '"/home/${config.homelab.operatorUser}/Sites/*"' in content, (
"nixos/configuration.nix must include Sites/* in git safe.directory"
)
nix_bin = shutil.which("nix")
if nix_bin and not os.environ.get("NIX_BUILD_TOP"):
cmd = [
nix_bin,
"eval",
".#nixosConfigurations.server.config.programs.git.config",
"--json",
]
res = subprocess.run(
cmd, cwd=CORE_ROOT, capture_output=True, text=True, check=True
)
import json
configs = json.loads(res.stdout)
safe_dirs = []
for cfg in configs:
if isinstance(cfg, dict) and "safe" in cfg and "directory" in cfg["safe"]:
dirs = cfg["safe"]["directory"]
if isinstance(dirs, list):
safe_dirs.extend(dirs)
else:
safe_dirs.append(dirs)
assert "/home/operator/Core" in safe_dirs, (
f"Expected '/home/operator/Core' in git safe.directory, got {safe_dirs}"
)
assert "/home/operator/Sites/*" in safe_dirs, (
f"Expected '/home/operator/Sites/*' in git safe.directory, got {safe_dirs}"
)
+1
View File
@@ -126,6 +126,7 @@ def test_bootstrap_cli_never_prints_raw_secret_to_stdout_or_stderr(
# Ensure stdout provides helpful human guidance # Ensure stdout provides helpful human guidance
assert "operator-admin" in captured.out assert "operator-admin" in captured.out
assert "sops nixos/secrets.yaml" in captured.out assert "sops nixos/secrets.yaml" in captured.out
assert "sudo nixos-rebuild switch --flake path:$HOME/Core#server --impure" in captured.out
def test_bootstrap_cli_print_json_outputs_valid_json_descriptor( def test_bootstrap_cli_print_json_outputs_valid_json_descriptor(
+16
View File
@@ -250,3 +250,19 @@ def test_resolve_upstream_provenance_class_b_and_default_timeout():
prov = resolve_upstream_provenance(source, local_commit="abc1234") prov = resolve_upstream_provenance(source, local_commit="abc1234")
assert prov.status == ProvenanceStatus.SYNCED assert prov.status == ProvenanceStatus.SYNCED
assert mock_run.call_args[1]["timeout"] == 10.0 assert mock_run.call_args[1]["timeout"] == 10.0
def test_get_local_checkout_status_git_error(tmp_path: Path):
app_dir = tmp_path / "git_error_app"
app_dir.mkdir()
(app_dir / ".git").mkdir()
with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(
returncode=128, stdout="", stderr="fatal: dubious ownership"
)
status = get_local_checkout_status(app_dir)
assert status.is_git is True
assert status.is_dirty is False
assert status.status_label == "⚠️ Git Error (exit 128)"