Compare commits
7
Commits
c86faa8397
...
caa8140cd3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
caa8140cd3 | ||
|
|
eb02543fa6 | ||
|
|
24508f8d92 | ||
|
|
8ad48a49db | ||
|
|
f631d5627c | ||
|
|
021c01171b | ||
|
|
7c1b9b75c5 |
No files matched your search
@@ -6,6 +6,7 @@ backup.zip
|
||||
.envrc
|
||||
.direnv
|
||||
.venv
|
||||
nixos/instance.nix
|
||||
|
||||
# SSL / ACME Certificates & Keys
|
||||
config/letsencrypt/*
|
||||
@@ -52,3 +53,4 @@ mutants/
|
||||
# Local Bootstrap & Operational Scripts
|
||||
scripts/bootstrap_lldap_users.py
|
||||
scripts/bootstrap_*.py
|
||||
!scripts/bootstrap_token.py
|
||||
+6
-6
@@ -15,8 +15,8 @@ It describes the implementation trajectory and phased engineering milestones for
|
||||
3. **Host Access Does Not Confer Mutation Authority (`DEC-02`)**: Entering via SSH does not bypass authentication. Every mutating operation and sensitive read (`workload.config`, `workload.logs`) requires an explicit Bearer token; tokenless local UDS calls fall back via `SO_PEERCRED` strictly to `homelab-viewer` read-only inspection.
|
||||
4. **Dedicated Service Identity & Fail-Closed Audit Guard (`DEC-03`)**: `homelab-appctl.service` executes as isolated user `homelab-appctl:homelab-operators` with mode `0600` append-only `/var/log/homelab/appctl/audit.jsonl`. Mutating operations abort immediately (`500 ERR_EXECUTION_FAILED`) if the pre-execution `DISPATCHED` audit write fails.
|
||||
5. **Unified Execution, Pre-Flight & Pure-Python Environment (`DEC-04`, `DEC-05`)**: Both CLI and GitOps worker paths execute through the daemon, enforcing Pydantic v2 manifest validation, `validate_compose_security()` AST checks, and inert pure-Python `.env` assembly (no shell `source` or `eval`).
|
||||
6. **Separation of Intent from Implementation**: `DeploymentModel` captures implementation-agnostic intent; concrete platform descriptors (`app.yaml` + Compose) are materialized and enforced by `appctl`.
|
||||
7. **AI Authoring Boundary**: AI agents act strictly as proposal generators (`DeploymentProposal`). Humans approve the intent (`DeploymentModel`). The AI possesses zero execution authority.
|
||||
6. **Separation of Intent from Implementation**: Declarative manifests (`app.yaml` + Compose) versioned in Git capture workload intent and platform descriptors, materialized and enforced deterministically by `appctl`.
|
||||
7. **AI Authoring Boundary & External MCP Gateway**: AI agents operate externally as proposal generators via client-side Model Context Protocol (MCP) tool integrations. Humans approve intent before any mutation is applied in Git. The server appliance hosts zero autonomous agent loops or on-server compilers.
|
||||
8. **Secret Reference Invariant**: Deployment definitions store secret references (`secretKeyRef`), never plaintext material, resolved at runtime via `SecretProvider`.
|
||||
9. **Clean State Root**: Mutable application runtime data resides strictly under `~/var/lib/homelab/<app>/`, isolated from Git repositories.
|
||||
|
||||
@@ -28,9 +28,9 @@ It describes the implementation trajectory and phased engineering milestones for
|
||||
| :--- | :--- | :--- |
|
||||
| **`appctl` Architecture** | Dedicated daemon service (`homelab-appctl.service`, user `homelab-appctl`) exposing `POST /v1/operations` over Unix socket and loopback HTTP, with thin-client CLI (`scripts/appctl_cli.py`). | Expand with Operations UI and external ForwardAuth integration (P5–P7). |
|
||||
| **Operational Auth** | Mandatory SHA-256 Bearer token + 3-role RBAC + UDS `SO_PEERCRED` viewer fallback (`/run/secrets/appctl/tokens.json`). | LLDAP directory RBAC & Authelia ForwardAuth (P5). |
|
||||
| **Metadata & Schema Engine** | Control-plane daemon validates requests via Pydantic v2 (`scripts/appctl_contracts.py`) and invokes `core_manifest.py` / `appctl_engine.py`. | Unified across `DeploymentModel` materialization (P6). |
|
||||
| **Deployment Model** | Direct authoring of `app.yaml` and `docker-compose.yml` in `~/Sites/<app>/`. | 5-stage lifecycle (planned in P6): `DeploymentProposal` $\to$ operator-approved `DeploymentModel` in Git $\to$ `appctl` materialization. |
|
||||
| **GitOps Engine** | Ingress/queue in `gitops_dispatcher.py`; worker delegates `workload.update` to daemon over `/run/homelab/appctl.sock`. | Integrated with `DeploymentModel` reconciliation (P6). |
|
||||
| **Metadata & Schema Engine** | Control-plane daemon validates requests via Pydantic v2 (`scripts/appctl_contracts.py`) and invokes `core_manifest.py` / `appctl_engine.py`. | Standardized JSON-RPC Model Context Protocol tools over Pydantic v2 schemas (P6). |
|
||||
| **Deployment Model** | Direct authoring of `app.yaml` and `docker-compose.yml` in `~/Sites/<app>/`. | Authoritative declarative Git state (`app.yaml` + Compose) managed via CLI, GitOps, or client-gated MCP tools (P6). |
|
||||
| **GitOps Engine** | Ingress/queue in `gitops_dispatcher.py`; worker delegates `workload.update` to daemon over `/run/homelab/appctl.sock`. | Unified continuous deployment worker driven by Git webhooks delegating to control plane daemon (P4 baseline consolidated). |
|
||||
| **Secret Distribution** | Age-encrypted `nixos/secrets.yaml` decrypted by `sops-nix` to tmpfs `/run/secrets/`. | Host secrets remain in `sops-nix`; workload secrets referenced by key and projected via `SecretProvider` (planned in P5). |
|
||||
| **Dashboard** | `appctl sync` compiles `config/homepage/services.yaml` from `app.yaml` manifests under `_homepage_sync.lock`. | Homepage consumes read-only live status from `appctl`; dedicated Operations UI client for management (planned in P7). |
|
||||
|
||||
@@ -138,7 +138,7 @@ It describes the implementation trajectory and phased engineering milestones for
|
||||
**Status**: ⏳ **Planned**
|
||||
* **Objective**: Deliver a unified web-based management experience without coupling the control plane to specific frontend engines.
|
||||
* **Key Deliverables**:
|
||||
1. *Operations UI Client*: Dedicated lightweight web client consuming the `appctl` API for proposal review, approval, real-time log streaming, and API token management.
|
||||
1. *Operations UI Client*: Dedicated lightweight web client consuming the `appctl` API for workload inspection, deployment management, real-time log streaming, and API token management.
|
||||
2. *Homepage Status Integration*: Homepage consumes live status widgets from `appctl` live endpoints or compiled service maps.
|
||||
* **Exit Criteria**: End-to-end browser and CLI deployment verification; Homepage accurately reflecting live container health.
|
||||
|
||||
|
||||
+108
-6
@@ -47,6 +47,98 @@ Under Milestone P4, `appctl` operates as a centralized operational control plane
|
||||
└────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Operator Admin Token Bootstrapping & Rotation
|
||||
|
||||
`appctl` implements zero-trust authorization across three roles: `homelab-admin`, `homelab-operator`, and `homelab-viewer`. Local Unix domain socket (`/run/homelab/appctl.sock`) callers without a token are granted `homelab-viewer` privileges via `SO_PEERCRED` for non-sensitive read-only commands (e.g., `appctl list`, `appctl status`, `appctl ssl`).
|
||||
|
||||
Sensitive inspection (e.g., `appctl config <workload>` which renders secrets in Compose definitions) and all mutating operations (e.g., `appctl up`, `appctl restart`, `appctl update`) require an authenticated Bearer token.
|
||||
|
||||
#### Role of `~/.config/homelab/token`
|
||||
The thin CLI client resolves Bearer tokens in the following order of precedence:
|
||||
1. Direct CLI flag: `--token <secret>`
|
||||
2. Environment variable: `APPCTL_TOKEN`
|
||||
3. Local operator token file: `~/.config/homelab/token` (mode `0600`)
|
||||
4. System service token file: `/run/secrets/appctl/token`
|
||||
|
||||
The standard operator setup stores a 256-bit hex Bearer token with mode `0600` in `~/.config/homelab/token`.
|
||||
|
||||
#### Generating a Token (`scripts/bootstrap_token.py`)
|
||||
To generate an operator token and its matching SHA-256 descriptor:
|
||||
|
||||
```bash
|
||||
python3 scripts/bootstrap_token.py
|
||||
```
|
||||
|
||||
This utility:
|
||||
1. Generates a cryptographically secure 256-bit token (`secrets.token_hex(32)`).
|
||||
2. Computes the SHA-256 digest: `hashlib.sha256(raw_token.encode("utf-8")).hexdigest()`.
|
||||
3. Ensures `~/.config/homelab` exists with mode `0700`.
|
||||
4. Writes the raw Bearer token to `~/.config/homelab/token` with mode `0600`.
|
||||
5. Outputs the JSON descriptor matching `TokenDescriptor` in `scripts/appctl_auth.py`:
|
||||
|
||||
```json
|
||||
{
|
||||
"token_id": "operator-admin",
|
||||
"identity": "operator",
|
||||
"role": "homelab-admin",
|
||||
"sha256": "4a12...<64-hex-sha256>"
|
||||
}
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> The raw secret is **never** printed to stdout or stderr. Only the descriptor snippet (containing the SHA-256 digest) is output. To print only the JSON snippet for automation or piping, pass `--print-json`.
|
||||
|
||||
#### Registering the Descriptor in SOPS
|
||||
Insert the generated JSON descriptor into your encrypted SOPS secrets store (`nixos/secrets.yaml`):
|
||||
|
||||
```bash
|
||||
sops nixos/secrets.yaml
|
||||
```
|
||||
|
||||
Under `appctl.tokens_json`, add the entry to the JSON list:
|
||||
```yaml
|
||||
appctl:
|
||||
tokens_json: |
|
||||
[
|
||||
{
|
||||
"token_id": "operator-admin",
|
||||
"identity": "operator",
|
||||
"role": "homelab-admin",
|
||||
"sha256": "<64-hex-sha256>"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
Save and exit your editor (SOPS will re-encrypt the file), then project the updated secrets:
|
||||
```bash
|
||||
sudo nixos-rebuild switch --flake ~/Core#server
|
||||
```
|
||||
This updates `/run/secrets/appctl/tokens.json` (owned by `homelab-appctl:homelab-operators`, mode `0400`), which `homelab-appctl.service` consumes.
|
||||
|
||||
#### Verifying Token Authentication
|
||||
Verify permissions using both unauthenticated and authenticated queries:
|
||||
|
||||
1. **Viewer Inspection** (succeeds without token via `SO_PEERCRED`):
|
||||
```bash
|
||||
appctl health
|
||||
# Output: OK (homelab-appctl.service operational)
|
||||
```
|
||||
|
||||
2. **Admin-Gated Operation** (requires `homelab-admin` Bearer token):
|
||||
```bash
|
||||
appctl config docs
|
||||
# Renders the resolved Compose YAML with injected secrets
|
||||
```
|
||||
If the token is missing or mismatched, `appctl` returns `401 Unauthorized` or `403 Forbidden` with `ERR_PERMISSION_DENIED`.
|
||||
|
||||
#### Token Rotation Workflow
|
||||
To rotate an operator token:
|
||||
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.
|
||||
3. Run `sudo nixos-rebuild switch --flake ~/Core#server` to apply the updated token store.
|
||||
4. Verify CLI operations (`appctl config docs`).
|
||||
5. Remove the deprecated token descriptor from `nixos/secrets.yaml` and re-run `nixos-rebuild switch`.
|
||||
|
||||
---
|
||||
|
||||
## 2. CLI Command Reference
|
||||
@@ -101,11 +193,13 @@ appctl info docs --ssl
|
||||
|
||||
### Lifecycle Management
|
||||
|
||||
#### `appctl up <service|core>`
|
||||
#### `appctl up <service|core> [--build] [--no-cache]`
|
||||
Starts the specified service stack in detached mode (`--remove-orphans`).
|
||||
* For a workload in `~/Sites`: starts containers and triggers `appctl sync`.
|
||||
* For `core`: starts the entire Core Compose stack using `/run/secrets/homeserver.env`.
|
||||
* For an individual Core service (e.g., `appctl up traefik`): starts that specific container.
|
||||
* When `--build` is passed: invokes `docker compose build --pull` prior to deployment. The `--pull` flag guarantees base images in Dockerfile `FROM` lines are refreshed from remote registries.
|
||||
* When `--no-cache` is passed: `--build` is implied (`build: True`) and `docker compose build --pull --no-cache` is executed, forcing a clean rebuild without cached layers.
|
||||
|
||||
#### `appctl down <service|core>`
|
||||
Stops and removes containers defined in the target's Compose file (or stops the targeted Core container).
|
||||
@@ -116,14 +210,22 @@ Restarts the target stack or individual container:
|
||||
* `appctl restart core`: Restarts all Core Compose services.
|
||||
* `appctl restart traefik`: Restarts only the Traefik container.
|
||||
|
||||
#### `appctl update <service>`
|
||||
Performs a sequential update workflow for a Sites workload stack:
|
||||
#### `appctl update <service> [--branch <branch>] [--build] [--no-cache]`
|
||||
Performs a sequential, revision-consistent update workflow for a Sites workload stack:
|
||||
1. Verifies that the local Git working tree is clean (aborts if uncommitted changes exist).
|
||||
2. Runs `git pull --ff-only` to fast-forward the current branch.
|
||||
3. Runs `docker compose pull` to fetch updated container images.
|
||||
4. Runs `docker compose up -d --remove-orphans` to recreate containers.
|
||||
2. Runs `git pull --ff-only [origin <expected_branch>]` to fast-forward the current branch.
|
||||
3. Re-validates `app.yaml`, expected branch declaration, and Compose security rules against the newly pulled working tree.
|
||||
4. Executes declared actions in `app.yaml` (`actions: [git_pull, compose_pull, compose_build, compose_up, compose_restart]`):
|
||||
* `compose_pull`: Runs `docker compose pull` to fetch updated container images.
|
||||
* `compose_build`: Runs `docker compose build --pull` (and `--no-cache` if requested).
|
||||
* `compose_up`: Runs `docker compose up -d --remove-orphans` to recreate containers.
|
||||
* When `--build` is passed via CLI, `compose_build` is automatically executed prior to `compose_up`, even if omitted from manifest actions.
|
||||
* When `--no-cache` is passed, build is implied and executes with `--no-cache`.
|
||||
5. Runs `appctl sync` to update the Homepage dashboard.
|
||||
|
||||
> [!NOTE]
|
||||
> **Source-Built Workload Policy**: For workloads built directly from local source Dockerfiles rather than pre-built registry images, declare `compose_build` in `app.yaml` `deployment.actions` (`actions: [git_pull, compose_build, compose_up]`). Both manual `appctl update` and automated GitOps dispatcher runs will execute `docker compose build --pull` before recreating containers, ensuring reproducible builds with current upstream base layers.
|
||||
|
||||
> [!NOTE]
|
||||
> Core platform updates are managed via version-controlled NixOS generations (`git pull` followed by `nixos-rebuild switch`), not through `appctl update core` (as Core is mounted read-only for `homelab-appctl.service`).
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using
|
||||
| Decision Record | Status | Date | Scope & One-Line Purpose |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| [**ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2**](0003-pydantic-v2-runtime-validation.md) | `accepted` | 2026-10-15 | Adopts Pydantic v2 as the single runtime schema and validation authority across workload manifests and daemon API to enforce fail-closed type safety, strict schema-based boundaries, and secret-safe serialization. |
|
||||
| [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](0002-appctl-control-plane-architecture.md) | `accepted` | 2026-10-07 | Establishes `homelab-appctl.service` as the central operational control plane daemon, one logical command API (`POST /v1/operations`) across dual transports (UDS and HTTP), mandatory token auth with UDS `SO_PEERCRED` viewer fallback, dedicated service isolation, fail-closed audit logging, GitOps worker unification, and the 5-stage `DeploymentModel` lifecycle. |
|
||||
| [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](0002-appctl-control-plane-architecture.md) | `accepted` | 2026-10-07 | Establishes `homelab-appctl.service` as the central operational control plane daemon, one logical command API (`POST /v1/operations`) across dual transports (UDS and HTTP), mandatory token auth with UDS `SO_PEERCRED` viewer fallback, dedicated service isolation, fail-closed audit logging, GitOps worker unification, and deterministic Git-backed declarative deployment state. |
|
||||
| [**ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model**](0001-3tier-architecture-and-provenance.md) | `accepted` | 2026-09-28 | Establishes 3-tier separation (Software, OCI Artifact, Sites Deployment, Core Platform), two workload classes (Source-Backed vs. Image-Only), isolated state root (`~/var/lib/homelab/<app>/`), and two operational inspection axes. |
|
||||
|
||||
---
|
||||
|
||||
+191
-1
@@ -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.
|
||||
@@ -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
|
||||
@@ -59,11 +70,11 @@ This plan establishes the concrete implementation work packages to resolve these
|
||||
- [x] **Task 1.5**: Update `systemd.tmpfiles.rules` in `nixos/modules/homeserver.nix` from `a+` to recursive `A+` on `sitesDir`.
|
||||
|
||||
### Phase 2: CLI Hardening & Status Parity
|
||||
- [ ] **Task 2.1**: Update `scripts/appctl` to fail closed when `[ ! -S "$SOCKET_PATH" ]`, removing the silent fallback to legacy Bash.
|
||||
- [ ] **Task 2.2**: Update `_op_workload_list` in `scripts/appctl_router.py` to query live container health (`get_docker_status()`).
|
||||
- [ ] **Task 2.3**: Update `_format_workload_table` in `scripts/appctl_cli.py` to render the `STATUS` column (`🟢 Running (1)` / `🔴 Stopped`).
|
||||
- [ ] **Task 2.4**: Bootstrap operator admin token documentation and setup instructions in `docs/appctl.md` and `docs/secrets-and-state.md`.
|
||||
- [ ] **Task 2.5**: Wire `--build` and `--no-cache` in `scripts/appctl_cli.py`, pass `--pull` during `compose_build` in `scripts/appctl_router.py`, and document source-built action policy in `docs/appctl.md`.
|
||||
- [x] **Task 2.1**: Update `scripts/appctl` to fail closed when `[ ! -S "$SOCKET_PATH" ]`, removing the silent fallback to legacy Bash.
|
||||
- [x] **Task 2.2**: Update `_op_workload_list` in `scripts/appctl_router.py` to query live container health (`get_docker_status()`).
|
||||
- [x] **Task 2.3**: Update `_format_workload_table` in `scripts/appctl_cli.py` to render the `STATUS` column (`🟢 Running (1)` / `🔴 Stopped`).
|
||||
- [x] **Task 2.4**: Bootstrap operator admin token documentation and setup instructions in `docs/appctl.md` and `docs/secrets-and-state.md`.
|
||||
- [x] **Task 2.5**: Wire `--build` and `--no-cache` in `scripts/appctl_cli.py`, pass `--pull` during `compose_build` in `scripts/appctl_router.py`, and document source-built action policy in `docs/appctl.md`.
|
||||
|
||||
### Phase 3: Architectural Records & Roadmap Synchronization
|
||||
- [x] **Task 3.1**: Update `ROADMAP.md` (P6 redefined as Homelab MCP Gateway; on-server AI compiler deprecated).
|
||||
@@ -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
|
||||
|
||||
@@ -64,9 +64,9 @@ Generated by `nixos/modules/traefik-deployments.nix`. Projects shared infrastruc
|
||||
|
||||
### C. Control Plane Token Store (`/run/secrets/appctl/tokens.json` & `/run/secrets/gitops/appctl_token`)
|
||||
Provisioned from `nixos/secrets.yaml` (`appctl/tokens_json` and `gitops/appctl_token`):
|
||||
* `/run/secrets/appctl/tokens.json`: Owned by `homelab-appctl:homelab-operators` with strict mode `0400` (enforced fail-closed by `TokenStore._verify_permissions()`). Stores SHA-256 hex digests of Bearer secrets mapped to `token_id`, `identity`, and `role` (`homelab-admin`, `homelab-operator`, `homelab-viewer`).
|
||||
* `/run/secrets/appctl/tokens.json`: Owned by `homelab-appctl:homelab-operators` with strict mode `0400` (enforced fail-closed by `TokenStore._verify_permissions()`, rejecting any write bit or group/world readability). Stores a JSON array of SHA-256 token descriptors (`token_id`, `identity`, `role`, and 64-hex `sha256`) defined under `appctl/tokens_json` in `nixos/secrets.yaml`.
|
||||
* `/run/secrets/gitops/appctl_token`: Owned by `config.homelab.operatorUser` (mode `0400`). Supplies the `homelab-operator` Bearer secret to `homelab-gitops.service` when delegating `workload.update` to `homelab-appctl.service`.
|
||||
* `~/.config/homelab/token`: Local operator Bearer token (mode `0600`) read by `appctl_cli.py` for interactive CLI mutations.
|
||||
* `~/.config/homelab/token`: Local operator Bearer token written with strict mode `0600` (in a mode `0700` directory) by `scripts/bootstrap_token.py`. Automatically discovered and resolved by `appctl_cli.py` for authenticated operator interactions without needing `--token` flags or environment variables.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+47
-7
@@ -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.
|
||||
|
||||
@@ -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";
|
||||
|
||||
+34
-304
@@ -1,189 +1,26 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# appctl - Unified, Manifest-Driven Container Orchestrator
|
||||
# Discovers individual application repositories located in ~/Sites/*/
|
||||
# Injects global homelab secrets, per-app metadata from app.yaml, and monitors Git sync
|
||||
# Thin CLI wrapper delegating operational commands to homelab-appctl.service over UDS
|
||||
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ENGINE="$SCRIPT_DIR/appctl_engine.py"
|
||||
PYTHON_BIN="${PYTHON_BIN:-python3}"
|
||||
if [ -z "$PYTHON_BIN" ]; then
|
||||
if [ -x "$SCRIPT_DIR/../.venv/bin/python3" ]; then
|
||||
PYTHON_BIN="$SCRIPT_DIR/../.venv/bin/python3"
|
||||
else
|
||||
PYTHON_BIN="python3"
|
||||
fi
|
||||
fi
|
||||
SOCKET_PATH="${APPCTL_SOCKET_PATH:-/run/homelab/appctl.sock}"
|
||||
CLI_CLIENT="$SCRIPT_DIR/appctl_cli.py"
|
||||
|
||||
# If daemon Unix domain socket exists, delegate operational commands directly to thin client
|
||||
# (fast-path local completion and resolution helpers through appctl_engine.py)
|
||||
# Fast-path local shell completion helpers
|
||||
case "${1:-}" in
|
||||
complete|completion|resolve)
|
||||
;;
|
||||
*)
|
||||
if [ -S "$SOCKET_PATH" ] && [ -f "$CLI_CLIENT" ]; then
|
||||
exec "$PYTHON_BIN" "$CLI_CLIENT" "$@"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
ENV_FILE="/run/secrets/rendered/traefik-deployments.env"
|
||||
if [ ! -f "$ENV_FILE" ] && [ -f "/run/secrets/traefik-deployments.env" ]; then
|
||||
ENV_FILE="/run/secrets/traefik-deployments.env"
|
||||
fi
|
||||
export SITES_DIR="${SITES_DIR:-$HOME/Sites}"
|
||||
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
|
||||
source "$ENV_FILE"
|
||||
set +a
|
||||
fi
|
||||
|
||||
# Lock the homelab root domain before setup_app_env can mutate $DOMAIN
|
||||
# Canonical precedence: HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN
|
||||
export HOMELAB_DOMAIN="${HOMELAB_DOMAIN:-${DOMAIN_SUFFIX:-${DOMAIN:-}}}"
|
||||
|
||||
# Show help usage
|
||||
show_help() {
|
||||
echo "🚀 appctl - Homelab Container Orchestrator"
|
||||
echo ""
|
||||
echo "Usage: appctl <command> [service] [options...]"
|
||||
echo ""
|
||||
echo "Commands:"
|
||||
echo " list, status [--fetch] [--core] [--ssl] List all applications with Git sync & container status"
|
||||
echo " ssl [service] Inspect SSL/TLS certificates across homelab domains"
|
||||
echo " info <service> [--ssl] Display comprehensive application & Git diagnostics"
|
||||
echo " up <service|core> Start/build a service stack or Core component"
|
||||
echo " down <service|core> Stop and remove a service stack or Core component"
|
||||
echo " restart <service|core> Restart a service stack, Core component, or entire Core"
|
||||
echo " update <service> Full stack update (git pull -> compose pull -> recreate)"
|
||||
echo " pull <service|core> Pull latest images and recreate service or Core component"
|
||||
echo " logs <service|core> Stream service or Core component logs"
|
||||
echo " config <service|core> Validate and view resolved compose configuration"
|
||||
echo " sync Synchronize Homepage dashboard services.yaml from app.yaml"
|
||||
echo " completion [bash] Output shell autocompletion script"
|
||||
}
|
||||
|
||||
# Setup application environment based on resolved metadata
|
||||
setup_app_env() {
|
||||
local query="$1"
|
||||
local resolved_json
|
||||
resolved_json=$("$PYTHON_BIN" "$ENGINE" resolve "$query" || true)
|
||||
|
||||
if [ -z "$resolved_json" ]; then
|
||||
echo "❌ Error: Service '$query' not found under $SITES_DIR or Core"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Extract fields via python json
|
||||
TARGET_TYPE=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('type', 'app'))" "$resolved_json")
|
||||
APP_DIR=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['dir_path'])" "$resolved_json")
|
||||
CANONICAL_NAME=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['name'])" "$resolved_json")
|
||||
TARGET_CONTAINER=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('container', ''))" "$resolved_json")
|
||||
|
||||
if [ "$TARGET_TYPE" = "core" ] || [ "$TARGET_TYPE" = "core_service" ]; then
|
||||
if [ ! -d "$CORE_DIR" ]; then
|
||||
echo "❌ Error: Core directory not found at $CORE_DIR"
|
||||
exit 1
|
||||
fi
|
||||
CORE_ENV_FILE="/run/secrets/rendered/homeserver.env"
|
||||
if [ ! -f "$CORE_ENV_FILE" ] && [ -f "/run/secrets/homeserver.env" ]; then
|
||||
CORE_ENV_FILE="/run/secrets/homeserver.env"
|
||||
fi
|
||||
COMPOSE_ENV_ARG=()
|
||||
if [ -f "$CORE_ENV_FILE" ]; then
|
||||
COMPOSE_ENV_ARG=(--env-file "$CORE_ENV_FILE")
|
||||
fi
|
||||
return
|
||||
fi
|
||||
|
||||
RESOLVED_DOMAIN=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['domain'])" "$resolved_json")
|
||||
|
||||
# 1. Base infrastructure defaults
|
||||
export PROXY_NETWORK="${PROXY_NETWORK:-proxy-net}"
|
||||
export NETWORK_NAME="${NETWORK_NAME:-$PROXY_NETWORK}"
|
||||
export CERT_RESOLVER="${CERT_RESOLVER:-myresolver}"
|
||||
export DOMAIN_SUFFIX="${DOMAIN_SUFFIX:-$HOMELAB_DOMAIN}"
|
||||
|
||||
# 2. Canonical application identity
|
||||
export SERVICE_NAME="$CANONICAL_NAME"
|
||||
export CONTAINER_NAME="$CANONICAL_NAME"
|
||||
export SERVICE_DOMAIN="$RESOLVED_DOMAIN"
|
||||
export DOMAIN="$RESOLVED_DOMAIN"
|
||||
|
||||
# 3. Dynamic environment variables from app.yaml (e.g. PROJECT_PATH, MEDIA_PATH, etc.)
|
||||
while IFS= read -r -d '' k && IFS= read -r -d '' v; do
|
||||
export "$k=$v"
|
||||
done < <("$PYTHON_BIN" -c "
|
||||
import json, re, sys
|
||||
RESERVED = {'PATH', 'LD_PRELOAD', 'IFS', 'SHELL', 'USER', 'CORE_DIR', 'SITES_DIR', 'ENV_FILE', 'HOMESERVER_ENV'}
|
||||
d = json.loads(sys.argv[1])
|
||||
env_dict = d.get('env', {})
|
||||
if isinstance(env_dict, dict):
|
||||
for k, v in env_dict.items():
|
||||
k_str = str(k).strip()
|
||||
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', k_str) or k_str in RESERVED:
|
||||
continue
|
||||
if v is not None and v != '':
|
||||
sys.stdout.buffer.write(k_str.encode('utf-8') + b'\0' + str(v).encode('utf-8') + b'\0')
|
||||
" "$resolved_json")
|
||||
|
||||
# 4. Source local .env if present
|
||||
if [ -f "$APP_DIR/.env" ]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1090
|
||||
source "$APP_DIR/.env"
|
||||
set +a
|
||||
fi
|
||||
|
||||
# 5. Source local app.env if present
|
||||
if [ -f "$APP_DIR/app.env" ]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1090
|
||||
source "$APP_DIR/app.env"
|
||||
set +a
|
||||
fi
|
||||
}
|
||||
|
||||
if [ $# -lt 1 ]; then
|
||||
show_help
|
||||
exit 1
|
||||
fi
|
||||
|
||||
COMMAND=$1
|
||||
APP=$2
|
||||
|
||||
case "$COMMAND" in
|
||||
list|status)
|
||||
"$PYTHON_BIN" "$ENGINE" list "${@:2}"
|
||||
;;
|
||||
ssl)
|
||||
"$PYTHON_BIN" "$ENGINE" ssl "${@:2}"
|
||||
;;
|
||||
info)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
"$PYTHON_BIN" "$ENGINE" info "${@:2}"
|
||||
;;
|
||||
sync)
|
||||
"$PYTHON_BIN" "$ENGINE" sync "${@:2}"
|
||||
;;
|
||||
complete)
|
||||
"$PYTHON_BIN" "$ENGINE" complete "${@:2}"
|
||||
;;
|
||||
resolve)
|
||||
"$PYTHON_BIN" "$ENGINE" resolve "${@:2}"
|
||||
exec "$PYTHON_BIN" "$ENGINE" complete "${@:2}"
|
||||
;;
|
||||
completion)
|
||||
cat <<'EOF'
|
||||
@@ -199,7 +36,7 @@ _appctl_completions() {
|
||||
cword=$COMP_CWORD
|
||||
fi
|
||||
|
||||
local commands="list status ssl info up down restart update pull logs config sync completion"
|
||||
local commands="list status ssl info up down restart update pull logs config sync health resolve completion"
|
||||
|
||||
if [ "$cword" -eq 1 ]; then
|
||||
COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
|
||||
@@ -233,7 +70,25 @@ _appctl_completions() {
|
||||
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
|
||||
fi
|
||||
;;
|
||||
up|down|restart|update|pull|logs|config)
|
||||
up|deploy)
|
||||
if [[ "$cur" == -* ]]; then
|
||||
COMPREPLY=( $(compgen -W "--build --no-cache" -- "$cur") )
|
||||
else
|
||||
local services
|
||||
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
|
||||
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
|
||||
fi
|
||||
;;
|
||||
update)
|
||||
if [[ "$cur" == -* ]]; then
|
||||
COMPREPLY=( $(compgen -W "--branch --build --no-cache" -- "$cur") )
|
||||
else
|
||||
local services
|
||||
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
|
||||
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
|
||||
fi
|
||||
;;
|
||||
down|restart|pull|logs|config)
|
||||
local services
|
||||
services=$("$appctl_cmd" complete services 2>/dev/null || appctl complete services 2>/dev/null || true)
|
||||
COMPREPLY=( $(compgen -W "$services" -- "$cur") )
|
||||
@@ -245,138 +100,13 @@ _appctl_completions() {
|
||||
}
|
||||
complete -F _appctl_completions appctl
|
||||
EOF
|
||||
;;
|
||||
up)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
if [ "$TARGET_TYPE" = "core" ]; then
|
||||
echo "🚀 Starting Core stack ($CORE_DIR)..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" up -d --remove-orphans "${@:3}"
|
||||
elif [ "$TARGET_TYPE" = "core_service" ]; then
|
||||
echo "🚀 Starting Core service: $TARGET_CONTAINER ($CORE_DIR)..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" up -d --remove-orphans "$TARGET_CONTAINER" "${@:3}"
|
||||
else
|
||||
echo "🚀 Starting $CANONICAL_NAME ($APP_DIR)..."
|
||||
cd "$APP_DIR" && docker compose up -d --remove-orphans "${@:3}"
|
||||
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
|
||||
fi
|
||||
;;
|
||||
down)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
if [ "$TARGET_TYPE" = "core" ]; then
|
||||
echo "🛑 Stopping Core stack ($CORE_DIR)..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" down "${@:3}"
|
||||
elif [ "$TARGET_TYPE" = "core_service" ]; then
|
||||
echo "🛑 Stopping Core service: $TARGET_CONTAINER ($CORE_DIR)..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" stop "$TARGET_CONTAINER" "${@:3}"
|
||||
else
|
||||
echo "🛑 Stopping $CANONICAL_NAME ($APP_DIR)..."
|
||||
cd "$APP_DIR" && docker compose down "${@:3}"
|
||||
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
|
||||
fi
|
||||
;;
|
||||
restart)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
if [ "$TARGET_TYPE" = "core" ]; then
|
||||
if [ -n "$3" ] && [[ "$3" != -* ]]; then
|
||||
echo "🔄 Restarting Core service: $3 ($CORE_DIR)..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" restart "$3" "${@:4}"
|
||||
else
|
||||
echo "🔄 Restarting Core stack ($CORE_DIR)..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" restart "${@:3}"
|
||||
fi
|
||||
elif [ "$TARGET_TYPE" = "core_service" ]; then
|
||||
echo "🔄 Restarting Core service: $TARGET_CONTAINER ($CORE_DIR)..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" restart "$TARGET_CONTAINER" "${@:3}"
|
||||
else
|
||||
echo "🔄 Restarting $CANONICAL_NAME ($APP_DIR)..."
|
||||
cd "$APP_DIR" && docker compose down && docker compose up -d "${@:3}"
|
||||
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
|
||||
fi
|
||||
;;
|
||||
update)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
if [ "$TARGET_TYPE" = "core" ]; then
|
||||
echo "🔄 Updating Core stack ($CORE_DIR)..."
|
||||
if [ -d "$CORE_DIR/.git" ]; then
|
||||
if [ -n "$(git -C "$CORE_DIR" status --porcelain)" ]; then
|
||||
echo "❌ Error: Cannot update. Working tree in $CORE_DIR has uncommitted changes."
|
||||
exit 1
|
||||
fi
|
||||
echo "📥 Pulling latest git changes for Core..."
|
||||
git -C "$CORE_DIR" pull --ff-only
|
||||
fi
|
||||
echo "🐳 Pulling latest Core container images..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" pull
|
||||
echo "🚀 Recreating Core container stack..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" up -d --remove-orphans "${@:3}"
|
||||
echo "✨ Core successfully updated!"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "🔄 Updating $CANONICAL_NAME ($APP_DIR)..."
|
||||
if [ -d "$APP_DIR/.git" ]; then
|
||||
if [ -n "$(git -C "$APP_DIR" status --porcelain)" ]; then
|
||||
echo "❌ Error: Cannot update. Working tree in $APP_DIR has uncommitted changes."
|
||||
echo "Commit or stash your changes before updating."
|
||||
exit 1
|
||||
fi
|
||||
echo "📥 Pulling latest git changes..."
|
||||
git -C "$APP_DIR" pull --ff-only
|
||||
fi
|
||||
|
||||
echo "🐳 Pulling latest container images..."
|
||||
cd "$APP_DIR" && docker compose pull
|
||||
|
||||
echo "🚀 Recreating container stack..."
|
||||
cd "$APP_DIR" && docker compose up -d --remove-orphans "${@:3}"
|
||||
|
||||
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
|
||||
echo "✨ $CANONICAL_NAME successfully updated!"
|
||||
;;
|
||||
pull)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
if [ "$TARGET_TYPE" = "core" ]; then
|
||||
echo "📥 Pulling latest images for Core stack..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" pull "${@:3}"
|
||||
elif [ "$TARGET_TYPE" = "core_service" ]; then
|
||||
echo "📥 Pulling latest image for Core service: $TARGET_CONTAINER..."
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" pull "$TARGET_CONTAINER" "${@:3}"
|
||||
else
|
||||
echo "📥 Pulling latest images for $CANONICAL_NAME..."
|
||||
cd "$APP_DIR" && docker compose pull && docker compose up -d --remove-orphans "${@:3}"
|
||||
fi
|
||||
;;
|
||||
logs)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
if [ "$TARGET_TYPE" = "core" ]; then
|
||||
if [ -n "$3" ] && [[ "$3" != -* ]]; then
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" logs -f "$3" "${@:4}"
|
||||
else
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" logs -f "${@:3}"
|
||||
fi
|
||||
elif [ "$TARGET_TYPE" = "core_service" ]; then
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" logs -f "$TARGET_CONTAINER" "${@:3}"
|
||||
else
|
||||
cd "$APP_DIR" && docker compose logs -f "${@:3}"
|
||||
fi
|
||||
;;
|
||||
config)
|
||||
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
|
||||
setup_app_env "$APP"
|
||||
if [ "$TARGET_TYPE" = "core" ] || [ "$TARGET_TYPE" = "core_service" ]; then
|
||||
cd "$CORE_DIR" && docker compose "${COMPOSE_ENV_ARG[@]}" config "${@:3}"
|
||||
else
|
||||
cd "$APP_DIR" && docker compose config "${@:3}"
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
show_help
|
||||
if [ ! -S "$SOCKET_PATH" ]; then
|
||||
echo "❌ Error: appctl daemon socket not found at $SOCKET_PATH. Ensure homelab-appctl.service is running." >&2
|
||||
exit 1
|
||||
fi
|
||||
exec "$PYTHON_BIN" "$CLI_CLIENT" "$@"
|
||||
;;
|
||||
esac
|
||||
+35
-14
@@ -58,28 +58,33 @@ def _format_workload_table(workloads: list[dict[str, Any]]) -> str:
|
||||
|
||||
if has_ssl:
|
||||
lines.append(
|
||||
f"{'SERVICE':<18} {'TYPE':<14} {'DOMAIN':<30} {'CERT':<24} {'DESCRIPTION'}"
|
||||
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}"
|
||||
)
|
||||
lines.append(
|
||||
f"{'-------':<18} {'----':<14} {'------':<30} {'----':<24} {'-----------'}"
|
||||
f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}"
|
||||
)
|
||||
else:
|
||||
lines.append(
|
||||
f"{'SERVICE':<18} {'TYPE':<14} {'DOMAIN':<30} {'DESCRIPTION'}"
|
||||
f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN'}"
|
||||
)
|
||||
lines.append(
|
||||
f"{'-------':<18} {'----':<14} {'------':<30} {'-----------'}"
|
||||
f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------'}"
|
||||
)
|
||||
|
||||
for w in workloads:
|
||||
name = str(w.get("name", "-"))
|
||||
w_type = str(w.get("type", w.get("app_type", "app")))
|
||||
domain = str(w.get("domain", "-"))
|
||||
desc = str(w.get("description", ""))
|
||||
name = str(w.get("name") or "-")
|
||||
domain = str(w.get("domain") or "-")
|
||||
status = str(w.get("status") or "-")
|
||||
|
||||
if w.get("manifest_error"):
|
||||
desc = f"⚠️ {w['manifest_error']}"
|
||||
elif w.get("deployment_status"):
|
||||
desc = f"{w['deployment_status']} ({w.get('provenance_status', '-')})"
|
||||
dep = "⚠️ Manifest Error"
|
||||
prov = "⚠️ Invalid Manifest"
|
||||
elif "deployment_status" in w:
|
||||
dep = str(w["deployment_status"])
|
||||
prov = str(w.get("provenance_status") or "-")
|
||||
else:
|
||||
dep = "-"
|
||||
prov = str(w.get("provenance_status") or "-")
|
||||
|
||||
if has_ssl:
|
||||
ssl_info = w.get("ssl")
|
||||
@@ -89,10 +94,12 @@ def _format_workload_table(workloads: list[dict[str, Any]]) -> str:
|
||||
else "-"
|
||||
)
|
||||
lines.append(
|
||||
f"{name:<18} {w_type:<14} {domain:<30} {cert_status:<24} {desc}"
|
||||
f"{name:<16} {dep:<22} {prov:<22} {status:<15} {domain:<28} {cert_status}"
|
||||
)
|
||||
else:
|
||||
lines.append(f"{name:<18} {w_type:<14} {domain:<30} {desc}")
|
||||
lines.append(
|
||||
f"{name:<16} {dep:<22} {prov:<24} {status:<15} {domain}"
|
||||
)
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
@@ -247,6 +254,7 @@ def run_cli(argv: list[str] | None = None) -> int:
|
||||
up_p = subparsers.add_parser("up", aliases=["deploy"], parents=[common_parser], help="Deploy workload")
|
||||
up_p.add_argument("target", help="Workload or core target")
|
||||
up_p.add_argument("--build", action="store_true", help="Rebuild container images")
|
||||
up_p.add_argument("--no-cache", action="store_true", help="Rebuild container images without cache")
|
||||
|
||||
# down / stop
|
||||
down_p = subparsers.add_parser("down", aliases=["stop"], parents=[common_parser], help="Stop workload")
|
||||
@@ -260,6 +268,8 @@ def run_cli(argv: list[str] | None = None) -> int:
|
||||
update_p = subparsers.add_parser("update", parents=[common_parser], help="Update workload revision")
|
||||
update_p.add_argument("target", help="Workload target")
|
||||
update_p.add_argument("--branch", default=None, help="Expected git branch")
|
||||
update_p.add_argument("--build", action="store_true", help="Rebuild container images")
|
||||
update_p.add_argument("--no-cache", action="store_true", help="Rebuild container images without cache")
|
||||
|
||||
# pull
|
||||
pull_p = subparsers.add_parser("pull", parents=[common_parser], help="Pull workload images")
|
||||
@@ -316,10 +326,15 @@ def run_cli(argv: list[str] | None = None) -> int:
|
||||
elif cmd == "health":
|
||||
op_req = OperationRequest(operation=OperationType.PLATFORM_HEALTH)
|
||||
elif cmd in ("up", "deploy"):
|
||||
build_flag = getattr(parsed, "build", False)
|
||||
no_cache_flag = getattr(parsed, "no_cache", False)
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_DEPLOY,
|
||||
target=parsed.target,
|
||||
parameters={"build": getattr(parsed, "build", False)},
|
||||
parameters={
|
||||
"build": build_flag or no_cache_flag,
|
||||
"no_cache": no_cache_flag,
|
||||
},
|
||||
)
|
||||
elif cmd in ("down", "stop"):
|
||||
op_req = OperationRequest(
|
||||
@@ -335,6 +350,12 @@ def run_cli(argv: list[str] | None = None) -> int:
|
||||
params = {}
|
||||
if getattr(parsed, "branch", None):
|
||||
params["expected_branch"] = parsed.branch
|
||||
build_flag = getattr(parsed, "build", False)
|
||||
no_cache_flag = getattr(parsed, "no_cache", False)
|
||||
if build_flag or no_cache_flag:
|
||||
params["build"] = True
|
||||
if no_cache_flag:
|
||||
params["no_cache"] = True
|
||||
op_req = OperationRequest(
|
||||
operation=OperationType.WORKLOAD_UPDATE,
|
||||
target=parsed.target,
|
||||
|
||||
@@ -161,6 +161,13 @@ class DeployParams(StrictModel):
|
||||
recreate: StrictBool = True
|
||||
remove_orphans: StrictBool = True
|
||||
build: StrictBool = False
|
||||
no_cache: StrictBool = False
|
||||
|
||||
@model_validator(mode="after")
|
||||
def imply_build_from_no_cache(self) -> DeployParams:
|
||||
if self.no_cache:
|
||||
self.build = True
|
||||
return self
|
||||
|
||||
|
||||
class UpdateParams(StrictModel):
|
||||
@@ -168,6 +175,13 @@ class UpdateParams(StrictModel):
|
||||
|
||||
expected_branch: Annotated[StrictStr, Field(min_length=1)] | None = None
|
||||
build: StrictBool = False
|
||||
no_cache: StrictBool = False
|
||||
|
||||
@model_validator(mode="after")
|
||||
def imply_build_from_no_cache(self) -> UpdateParams:
|
||||
if self.no_cache:
|
||||
self.build = True
|
||||
return self
|
||||
|
||||
|
||||
class LogsParams(StrictModel):
|
||||
|
||||
@@ -108,6 +108,10 @@ class CoreService(App):
|
||||
app_type: str = "core_service"
|
||||
dir_path: str = CORE_DIR
|
||||
|
||||
@property
|
||||
def container_name(self) -> str:
|
||||
return self.container
|
||||
|
||||
|
||||
@dataclass
|
||||
class SitesApp(App):
|
||||
@@ -411,6 +415,11 @@ def get_docker_status(
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if inspect_res.returncode != 0:
|
||||
err = (inspect_res.stderr or "").lower()
|
||||
if "no such object" in err or "no such container" in err:
|
||||
return "🔴 Stopped"
|
||||
return "❓ Unknown"
|
||||
state = inspect_res.stdout.strip()
|
||||
if state.lower() == "true":
|
||||
return "🟢 Running (1)"
|
||||
@@ -431,6 +440,9 @@ def get_docker_status(
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if res.returncode != 0:
|
||||
return "❓ Unknown"
|
||||
|
||||
container_ids = [c for c in res.stdout.strip().splitlines() if c]
|
||||
if not container_ids:
|
||||
return "🔴 Stopped"
|
||||
@@ -441,6 +453,9 @@ def get_docker_status(
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if inspect_res.returncode != 0:
|
||||
return "❓ Unknown"
|
||||
|
||||
running_states = inspect_res.stdout.strip().splitlines()
|
||||
running_count = sum(1 for s in running_states if s.lower() == "true")
|
||||
total_count = len(container_ids)
|
||||
|
||||
@@ -63,6 +63,7 @@ from appctl_engine import (
|
||||
check_ssl_cert,
|
||||
cmd_sync_homepage,
|
||||
get_core_services,
|
||||
get_docker_status,
|
||||
get_sites_apps,
|
||||
resolve_app,
|
||||
)
|
||||
@@ -74,7 +75,7 @@ from core_manifest import (
|
||||
parse_manifest,
|
||||
)
|
||||
from gitops_dispatcher import validate_compose_security
|
||||
from provenance import inspect_workload_two_axis
|
||||
from provenance import get_local_checkout_status, inspect_workload_two_axis
|
||||
|
||||
MAX_OUTPUT_BYTES = 256 * 1024 # 256 KiB cap per invocation
|
||||
|
||||
@@ -667,24 +668,39 @@ class OperationalRouter:
|
||||
for app in apps:
|
||||
item = app.to_dict()
|
||||
app_path = Path(app.dir_path)
|
||||
if params.fetch:
|
||||
docker_status = get_docker_status(dir_path=app_path)
|
||||
item["status"] = docker_status
|
||||
|
||||
if app.manifest_error:
|
||||
item["deployment_status"] = "⚠️ Manifest Error"
|
||||
item["provenance_status"] = "⚠️ Invalid Manifest"
|
||||
else:
|
||||
manifest_obj = app.manifest_obj or Manifest(
|
||||
name=app.name, domain=app.domain
|
||||
)
|
||||
two_axis = inspect_workload_two_axis(
|
||||
app_dir=app_path,
|
||||
manifest=manifest_obj,
|
||||
fetch_upstream=True,
|
||||
fetch_upstream=params.fetch,
|
||||
docker_status=docker_status,
|
||||
)
|
||||
item["deployment_status"] = two_axis.checkout.status_label
|
||||
item["provenance_status"] = two_axis.provenance.status.value
|
||||
|
||||
if params.ssl and not app.is_internal:
|
||||
item["ssl"] = check_ssl_cert(app.domain)
|
||||
apps_data.append(item)
|
||||
|
||||
if params.core:
|
||||
for svc in get_core_services(core_dir=str(self.core_dir)):
|
||||
core_checkout = get_local_checkout_status(self.core_dir)
|
||||
for i, svc in enumerate(get_core_services(core_dir=str(self.core_dir))):
|
||||
svc_dict = svc.to_dict()
|
||||
svc_dict["status"] = get_docker_status(
|
||||
dir_path=self.core_dir,
|
||||
container_name=svc.container_name,
|
||||
)
|
||||
svc_dict["deployment_status"] = core_checkout.status_label if i == 0 else ""
|
||||
svc_dict["provenance_status"] = "— Core Platform"
|
||||
if params.ssl and not svc.is_internal:
|
||||
svc_dict["ssl"] = check_ssl_cert(svc.domain)
|
||||
apps_data.append(svc_dict)
|
||||
@@ -769,7 +785,9 @@ class OperationalRouter:
|
||||
|
||||
# Optional build
|
||||
if params.build:
|
||||
build_cmd = ["docker", "compose", "-f", str(compose_file), "build"]
|
||||
build_cmd = ["docker", "compose", "-f", str(compose_file), "build", "--pull"]
|
||||
if params.no_cache:
|
||||
build_cmd.append("--no-cache")
|
||||
if container:
|
||||
build_cmd.append(container)
|
||||
code, out, err = run_bounded_subprocess(build_cmd, cwd=app_dir, env=env, timeout=300.0)
|
||||
@@ -912,13 +930,23 @@ class OperationalRouter:
|
||||
env = assemble_workload_env(app_dir, manifest, app.name)
|
||||
output_log = [f"git: {pull_out.strip()}"]
|
||||
|
||||
for action in declared_actions:
|
||||
actions = list(declared_actions)
|
||||
if params.build and "compose_build" not in actions:
|
||||
if "compose_up" in actions:
|
||||
idx = actions.index("compose_up")
|
||||
actions.insert(idx, "compose_build")
|
||||
else:
|
||||
actions.append("compose_build")
|
||||
|
||||
for action in actions:
|
||||
if action == "git_pull":
|
||||
continue # already executed in step 2
|
||||
elif action == "compose_pull":
|
||||
cmd = ["docker", "compose", "-f", str(compose_file), "pull"]
|
||||
elif action == "compose_build" or (params.build and action == "compose_up"):
|
||||
cmd = ["docker", "compose", "-f", str(compose_file), "build"]
|
||||
elif action == "compose_build":
|
||||
cmd = ["docker", "compose", "-f", str(compose_file), "build", "--pull"]
|
||||
if params.no_cache:
|
||||
cmd.append("--no-cache")
|
||||
elif action == "compose_up":
|
||||
cmd = ["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"]
|
||||
elif action == "compose_restart":
|
||||
|
||||
Executable
+173
@@ -0,0 +1,173 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
bootstrap_token.py — Operator Admin Token Bootstrap & Rotation Helper (WP4)
|
||||
|
||||
Generates a 256-bit cryptographically secure Bearer token, saves it locally
|
||||
with strict mode 0600 permissions (~/.config/homelab/token), and prints the
|
||||
corresponding JSON descriptor for insertion into the SOPS tokens store
|
||||
(nixos/secrets.yaml -> appctl/tokens_json).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import stat
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
# Ensure scripts directory is in sys.path when executed directly
|
||||
_scripts_dir = Path(__file__).resolve().parent
|
||||
if str(_scripts_dir) not in sys.path:
|
||||
sys.path.insert(0, str(_scripts_dir))
|
||||
|
||||
from appctl_auth import Role, TokenDescriptor
|
||||
|
||||
DEFAULT_TOKEN_PATH = Path.home() / ".config/homelab/token"
|
||||
DEFAULT_TOKEN_ID = "operator-admin"
|
||||
DEFAULT_IDENTITY = "operator"
|
||||
DEFAULT_ROLE = Role.ADMIN.value
|
||||
|
||||
|
||||
def generate_token() -> tuple[str, str]:
|
||||
"""Generate a 256-bit cryptographically secure Bearer token and its SHA-256 digest."""
|
||||
raw_token = secrets.token_hex(32)
|
||||
digest = hashlib.sha256(raw_token.encode()).hexdigest()
|
||||
return raw_token, digest
|
||||
|
||||
|
||||
def write_token_file(path: Path, raw_token: str, force: bool = False) -> None:
|
||||
"""
|
||||
Write raw Bearer token to path with mode 0600.
|
||||
Ensures parent directory exists with mode 0700.
|
||||
Fails closed if the destination exists and force is False.
|
||||
"""
|
||||
path = path.expanduser().resolve()
|
||||
if path.exists() and not force:
|
||||
raise FileExistsError(
|
||||
f"Token file '{path}' already exists. Use --force / -f to overwrite."
|
||||
)
|
||||
|
||||
parent = path.parent
|
||||
if not parent.exists():
|
||||
parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
try:
|
||||
parent.chmod(0o700)
|
||||
except OSError:
|
||||
pass
|
||||
elif stat.S_IMODE(parent.stat().st_mode) != 0o700:
|
||||
try:
|
||||
parent.chmod(0o700)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
fd = os.open(str(path), os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o600)
|
||||
try:
|
||||
content = f"{raw_token}\n".encode()
|
||||
os.write(fd, content)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
path.chmod(0o600)
|
||||
|
||||
|
||||
def bootstrap_token(
|
||||
output_path: Path | str = DEFAULT_TOKEN_PATH,
|
||||
token_id: str = DEFAULT_TOKEN_ID,
|
||||
identity: str = DEFAULT_IDENTITY,
|
||||
role: str = DEFAULT_ROLE,
|
||||
force: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Generate Bearer token, persist to file with strict permissions,
|
||||
and return the validated TokenDescriptor dictionary.
|
||||
"""
|
||||
path = Path(output_path).expanduser().resolve()
|
||||
raw_token, digest = generate_token()
|
||||
|
||||
write_token_file(path, raw_token, force=force)
|
||||
|
||||
# Validate against TokenDescriptor model
|
||||
validated = TokenDescriptor(
|
||||
token_id=token_id,
|
||||
identity=identity,
|
||||
role=Role(role),
|
||||
sha256=digest,
|
||||
)
|
||||
return validated.model_dump(mode="json")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Bootstrap or rotate an operator Bearer token for appctl."
|
||||
)
|
||||
parser.add_argument(
|
||||
"-o",
|
||||
"--output",
|
||||
default=str(DEFAULT_TOKEN_PATH),
|
||||
help=f"Destination token file path (default: {DEFAULT_TOKEN_PATH})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--token-id",
|
||||
default=DEFAULT_TOKEN_ID,
|
||||
help=f"Token descriptor ID (default: {DEFAULT_TOKEN_ID})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--identity",
|
||||
default=DEFAULT_IDENTITY,
|
||||
help=f"Caller identity (default: {DEFAULT_IDENTITY})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--role",
|
||||
default=DEFAULT_ROLE,
|
||||
choices=[r.value for r in Role],
|
||||
help=f"Role assignment (default: {DEFAULT_ROLE})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-f",
|
||||
"--force",
|
||||
action="store_true",
|
||||
help="Overwrite existing token file if present",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--print-json",
|
||||
action="store_true",
|
||||
help="Output only the JSON descriptor snippet for piping/automation",
|
||||
)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
try:
|
||||
descriptor = bootstrap_token(
|
||||
output_path=args.output,
|
||||
token_id=args.token_id,
|
||||
identity=args.identity,
|
||||
role=args.role,
|
||||
force=args.force,
|
||||
)
|
||||
except FileExistsError as err:
|
||||
sys.stderr.write(f"Error: {err}\n")
|
||||
return 1
|
||||
|
||||
json_snippet = json.dumps(descriptor, indent=2)
|
||||
|
||||
if args.print_json:
|
||||
sys.stdout.write(f"{json_snippet}\n")
|
||||
else:
|
||||
sys.stdout.write(
|
||||
f"Generated Bearer token and saved to {args.output} (mode 0600).\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"After updating nixos/secrets.yaml with `sops nixos/secrets.yaml`, apply changes with:\n"
|
||||
f" sudo nixos-rebuild switch --flake ~/Core#server\n"
|
||||
)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -5,10 +5,14 @@ Security invariant tests for Docker Compose and container isolation.
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
from appctl_audit import AuditLogger, TargetLockManager
|
||||
from appctl_auth import Principal, Role
|
||||
from appctl_contracts import OperationRequest
|
||||
from appctl_router import OperationalRouter, assemble_workload_env
|
||||
from core_manifest import parse_manifest
|
||||
|
||||
# Comment-out reason: testing pyproject-level pythonpath definition
|
||||
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
@@ -101,10 +105,9 @@ def test_no_eval_in_appctl_script():
|
||||
assert "eval " not in content, "Dangerous 'eval' detected in scripts/appctl!"
|
||||
|
||||
|
||||
def test_appctl_env_injection_resilience(tmp_path: Path):
|
||||
def test_appctl_env_injection_resilience(tmp_path: Path, monkeypatch):
|
||||
"""Ensure environment values from app.yaml cannot execute shell commands via command substitution
|
||||
|
||||
in scripts/appctl during environment setup. Executes scripts/appctl directly with a mock docker binary.
|
||||
during P4 production environment assembly and router dispatch. Executes OperationalRouter with a mock docker binary.
|
||||
"""
|
||||
canary = tmp_path / "pwned.txt"
|
||||
payload = f"$(touch {canary})"
|
||||
@@ -127,14 +130,22 @@ env:
|
||||
"services:\n web:\n image: nginx\n", encoding="utf-8"
|
||||
)
|
||||
|
||||
# 2. Setup mock docker binary to capture environment without requiring a running Docker daemon
|
||||
# 2. Verify unit-level pure Python environment assembly
|
||||
monkeypatch.setenv("HOMELAB_DOMAIN", "example.test")
|
||||
manifest = parse_manifest(app_dir / "app.yaml")
|
||||
assembled_env = assemble_workload_env(app_dir, manifest, "vuln-app")
|
||||
assert not canary.exists(), "Command substitution executed during assemble_workload_env!"
|
||||
assert assembled_env["INJECTION_TEST"] == payload
|
||||
assert assembled_env["NORMAL_VAR"] == "safe_value"
|
||||
|
||||
# 3. Setup mock docker binary to capture environment without requiring a running Docker daemon
|
||||
mock_bin = tmp_path / "bin"
|
||||
mock_bin.mkdir()
|
||||
mock_docker = mock_bin / "docker"
|
||||
bash_bin = shutil.which("bash") or "bash"
|
||||
|
||||
mock_docker_script = f"""#!{bash_bin}
|
||||
if [ "$1" = "compose" ] && [ "$2" = "config" ]; then
|
||||
if [ "$1" = "compose" ] && [ "$4" = "config" ]; then
|
||||
echo "MOCK_DOCKER_COMPOSE_CONFIG"
|
||||
echo "CAPTURED_INJECTION=$INJECTION_TEST"
|
||||
echo "CAPTURED_NORMAL=$NORMAL_VAR"
|
||||
@@ -145,36 +156,39 @@ exit 0
|
||||
mock_docker.write_text(mock_docker_script, encoding="utf-8")
|
||||
mock_docker.chmod(0o755)
|
||||
|
||||
# 3. Execute scripts/appctl config vuln-app directly
|
||||
appctl_path = CORE_ROOT / "scripts" / "appctl"
|
||||
env = os.environ.copy()
|
||||
if "NIX_PYTHONPATH" in env and "PYTHONPATH" not in env:
|
||||
env["PYTHONPATH"] = env["NIX_PYTHONPATH"]
|
||||
env["PATH"] = f"{mock_bin}:{Path(sys.executable).parent}:{env['PATH']}"
|
||||
env["PYTHON_BIN"] = sys.executable
|
||||
env["SITES_DIR"] = str(sites_dir)
|
||||
env["HOMELAB_DOMAIN"] = "example.test"
|
||||
env["CORE_DIR"] = str(CORE_ROOT)
|
||||
|
||||
res = subprocess.run(
|
||||
[bash_bin, str(appctl_path), "config", "vuln-app"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
# 4. Dispatch workload.config through OperationalRouter
|
||||
monkeypatch.setenv("PATH", f"{mock_bin}:{os.environ.get('PATH', '')}")
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=sites_dir,
|
||||
core_dir=CORE_ROOT,
|
||||
)
|
||||
req = OperationRequest.model_validate({
|
||||
"operation": "workload.config",
|
||||
"target": "vuln-app",
|
||||
})
|
||||
admin_principal = Principal(
|
||||
identity="operator",
|
||||
role=Role.ADMIN,
|
||||
token_id="tok_admin",
|
||||
auth_method="bearer_token",
|
||||
)
|
||||
|
||||
# 4. Assertions: command substitution was not executed, script ran, and mock docker received literal value
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
|
||||
# 5. Assertions: command substitution was not executed, router succeeded, mock docker received literal value
|
||||
assert not canary.exists(), (
|
||||
"Command substitution was executed on the host during environment setup!"
|
||||
)
|
||||
assert res.returncode == 0, (
|
||||
f"appctl config failed: {res.stderr}\nStdout: {res.stdout}"
|
||||
assert resp.success is True, (
|
||||
f"OperationalRouter dispatch failed: {resp.error}"
|
||||
)
|
||||
assert "MOCK_DOCKER_COMPOSE_CONFIG" in res.stdout
|
||||
assert f"CAPTURED_INJECTION={payload}" in res.stdout
|
||||
assert "CAPTURED_NORMAL=safe_value" in res.stdout
|
||||
assert "/dangerous/override" not in res.stdout
|
||||
assert resp.result is not None
|
||||
output = resp.result.get("output", "")
|
||||
assert "MOCK_DOCKER_COMPOSE_CONFIG" in output
|
||||
assert f"CAPTURED_INJECTION={payload}" in output
|
||||
assert "CAPTURED_NORMAL=safe_value" in output
|
||||
|
||||
|
||||
def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests():
|
||||
@@ -276,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"
|
||||
)
|
||||
|
||||
|
||||
@@ -107,6 +107,81 @@ def test_cli_dispatches_mutation_command():
|
||||
assert "Workload deployed" in mock_stdout.getvalue()
|
||||
|
||||
|
||||
def test_cli_up_and_deploy_build_and_no_cache_flags():
|
||||
"""Ensure appctl up/deploy with --build and --no-cache flags dispatches correct parameters."""
|
||||
mock_resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_build_01",
|
||||
operation=OperationType.WORKLOAD_DEPLOY,
|
||||
target="jellyfin",
|
||||
result={"action": "deployed", "message": "Workload deployed"},
|
||||
)
|
||||
|
||||
# 1. up with --build
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["up", "jellyfin", "--build", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req: OperationRequest = mock_send.call_args[1]["operation_request"]
|
||||
assert req.operation == OperationType.WORKLOAD_DEPLOY
|
||||
assert req.parameters.get("build") is True
|
||||
assert req.parameters.get("no_cache") is False
|
||||
|
||||
# 2. up with --no-cache implies build=True
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["up", "jellyfin", "--no-cache", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req = mock_send.call_args[1]["operation_request"]
|
||||
assert req.parameters.get("no_cache") is True
|
||||
assert req.parameters.get("build") is True
|
||||
|
||||
# 3. deploy alias with --no-cache
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["deploy", "jellyfin", "--no-cache", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req = mock_send.call_args[1]["operation_request"]
|
||||
assert req.parameters.get("no_cache") is True
|
||||
assert req.parameters.get("build") is True
|
||||
|
||||
|
||||
def test_cli_update_build_and_no_cache_flags():
|
||||
"""Ensure appctl update with --build and --no-cache flags dispatches correct parameters."""
|
||||
mock_resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_upd_01",
|
||||
operation=OperationType.WORKLOAD_UPDATE,
|
||||
target="jellyfin",
|
||||
result={"action": "updated", "message": "Workload updated"},
|
||||
)
|
||||
|
||||
# 1. update with --build
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["update", "jellyfin", "--build", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req: OperationRequest = mock_send.call_args[1]["operation_request"]
|
||||
assert req.operation == OperationType.WORKLOAD_UPDATE
|
||||
assert req.parameters.get("build") is True
|
||||
assert req.parameters.get("no_cache", False) is False
|
||||
|
||||
# 2. update with --no-cache implies build=True
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["update", "jellyfin", "--no-cache", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req = mock_send.call_args[1]["operation_request"]
|
||||
assert req.parameters.get("no_cache") is True
|
||||
assert req.parameters.get("build") is True
|
||||
|
||||
# 3. update with --branch and --no-cache
|
||||
with patch("appctl_cli.send_daemon_request", return_value=mock_resp) as mock_send, patch("sys.stdout", new_callable=io.StringIO):
|
||||
ret = run_cli(["update", "jellyfin", "--branch", "main", "--no-cache", "--token", "tok_secret"])
|
||||
assert ret == 0
|
||||
req = mock_send.call_args[1]["operation_request"]
|
||||
assert req.parameters.get("expected_branch") == "main"
|
||||
assert req.parameters.get("no_cache") is True
|
||||
assert req.parameters.get("build") is True
|
||||
|
||||
|
||||
def test_cli_handles_missing_socket():
|
||||
"""Ensure friendly stderr message when socket is absent."""
|
||||
with patch("appctl_cli.send_daemon_request", side_effect=FileNotFoundError), patch("sys.stderr", new_callable=io.StringIO) as mock_stderr:
|
||||
@@ -116,7 +191,7 @@ def test_cli_handles_missing_socket():
|
||||
|
||||
|
||||
def test_cli_format_response_renders_workload_list_table():
|
||||
"""Ensure workload.list renders a human-readable table instead of suppressing it behind result['message']."""
|
||||
"""Ensure workload.list renders the canonical 5-column layout matching docs/appctl.md."""
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
@@ -129,13 +204,17 @@ def test_cli_format_response_renders_workload_list_table():
|
||||
"name": "snappymail",
|
||||
"type": "app",
|
||||
"domain": "mail.example.test",
|
||||
"description": "Webmail client",
|
||||
"deployment_status": "✓ Synced (main)",
|
||||
"provenance_status": "✓ Synced",
|
||||
"status": "🟢 Running (1)",
|
||||
},
|
||||
{
|
||||
"name": "traefik",
|
||||
"type": "core_service",
|
||||
"domain": "traefik.example.test",
|
||||
"description": "Edge Reverse Proxy",
|
||||
"deployment_status": "",
|
||||
"provenance_status": "— Core Platform",
|
||||
"status": "🟢 Running (1)",
|
||||
},
|
||||
],
|
||||
"message": "Found 2 workloads",
|
||||
@@ -143,15 +222,89 @@ def test_cli_format_response_renders_workload_list_table():
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
assert "SERVICE" in rendered
|
||||
assert "DOMAIN" in rendered
|
||||
assert "snappymail" in rendered
|
||||
assert "mail.example.test" in rendered
|
||||
assert "traefik" in rendered
|
||||
assert "Edge Reverse Proxy" in rendered
|
||||
lines = rendered.splitlines()
|
||||
assert len(lines) >= 4
|
||||
assert lines[0] == "SERVICE DEPLOYMENT PROVENANCE STATUS DOMAIN"
|
||||
assert lines[1] == "------- ---------- ---------- ------ ------"
|
||||
assert "snappymail" in lines[2]
|
||||
assert "✓ Synced (main)" in lines[2]
|
||||
assert "✓ Synced" in lines[2]
|
||||
assert "🟢 Running (1)" in lines[2]
|
||||
assert "mail.example.test" in lines[2]
|
||||
|
||||
assert "traefik" in lines[3]
|
||||
assert "— Core Platform" in lines[3]
|
||||
assert "🟢 Running (1)" in lines[3]
|
||||
assert "traefik.example.test" in lines[3]
|
||||
assert "✨ Found 2 workloads" not in rendered
|
||||
|
||||
|
||||
def test_cli_format_response_renders_workload_list_table_with_ssl():
|
||||
"""Ensure workload.list with SSL renders the canonical 6-column layout with CERT."""
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_list_ssl_01",
|
||||
operation=OperationType.WORKLOAD_LIST,
|
||||
result={
|
||||
"total": 1,
|
||||
"workloads": [
|
||||
{
|
||||
"name": "snappymail",
|
||||
"type": "app",
|
||||
"domain": "mail.example.test",
|
||||
"deployment_status": "✓ Synced (main)",
|
||||
"provenance_status": "✓ Synced",
|
||||
"status": "🟢 Running (1)",
|
||||
"ssl": {"status": "🟢 80d remaining"},
|
||||
},
|
||||
],
|
||||
"message": "Found 1 workloads",
|
||||
},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
lines = rendered.splitlines()
|
||||
assert len(lines) >= 3
|
||||
assert lines[0] == "SERVICE DEPLOYMENT PROVENANCE STATUS DOMAIN CERT"
|
||||
assert lines[1] == "------- ---------- ---------- ------ ------ ----"
|
||||
assert "snappymail" in lines[2]
|
||||
assert "🟢 80d remaining" in lines[2]
|
||||
|
||||
|
||||
def test_cli_format_response_renders_workload_list_table_with_manifest_error():
|
||||
"""Ensure workload.list renders ⚠️ Manifest Error and ⚠️ Invalid Manifest, and status=None renders as '-'."""
|
||||
resp = OperationResponse(
|
||||
version="1.0",
|
||||
success=True,
|
||||
operation_id="op_list_err",
|
||||
operation=OperationType.WORKLOAD_LIST,
|
||||
result={
|
||||
"total": 1,
|
||||
"workloads": [
|
||||
{
|
||||
"name": "broken-app",
|
||||
"type": "app",
|
||||
"domain": "broken.example.test",
|
||||
"manifest_error": "Syntax error in app.yaml",
|
||||
"status": None,
|
||||
},
|
||||
],
|
||||
"message": "Found 1 workloads",
|
||||
},
|
||||
output="",
|
||||
)
|
||||
rendered = format_response(resp, raw_json=False)
|
||||
lines = rendered.splitlines()
|
||||
assert len(lines) >= 3
|
||||
assert "broken-app" in lines[2]
|
||||
assert "⚠️ Manifest Error" in lines[2]
|
||||
assert "⚠️ Invalid Manifest" in lines[2]
|
||||
# Ensure status is '-' and NOT 'None'
|
||||
assert " None " not in lines[2]
|
||||
assert " - " in lines[2]
|
||||
|
||||
|
||||
def test_cli_format_response_renders_workload_get_info():
|
||||
"""Ensure workload.get (appctl info) renders structured workload metadata."""
|
||||
resp = OperationResponse(
|
||||
@@ -360,3 +513,81 @@ def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path,
|
||||
finally:
|
||||
srv.close()
|
||||
|
||||
|
||||
def test_appctl_wrapper_fails_closed_when_socket_is_missing(tmp_path: Path):
|
||||
"""Ensure scripts/appctl fails closed with exit code 1 and diagnostic stderr when socket is missing."""
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
bash_bin = shutil.which("bash") or "bash"
|
||||
non_existent_sock = tmp_path / "missing_appctl.sock"
|
||||
appctl_script = Path(__file__).resolve().parent.parent.parent / "scripts" / "appctl"
|
||||
|
||||
env = {
|
||||
"PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"),
|
||||
"PYTHON_BIN": sys.executable,
|
||||
"HOMELAB_DOMAIN": "example.test",
|
||||
"APPCTL_SOCKET_PATH": str(non_existent_sock),
|
||||
"SITES_DIR": str(tmp_path),
|
||||
}
|
||||
if "PYTHONPATH" in os.environ:
|
||||
env["PYTHONPATH"] = os.environ["PYTHONPATH"]
|
||||
|
||||
res = subprocess.run(
|
||||
[bash_bin, str(appctl_script), "status"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert res.returncode == 1
|
||||
assert "daemon socket not found" in res.stderr
|
||||
|
||||
|
||||
def test_appctl_wrapper_fast_paths_completion_without_socket(tmp_path: Path):
|
||||
"""Ensure scripts/appctl completes offline via appctl_engine.py even when socket is missing."""
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
bash_bin = shutil.which("bash") or "bash"
|
||||
non_existent_sock = tmp_path / "missing_appctl.sock"
|
||||
appctl_script = Path(__file__).resolve().parent.parent.parent / "scripts" / "appctl"
|
||||
|
||||
env = {
|
||||
"PATH": os.environ.get("PATH", "/run/current-system/sw/bin:/usr/bin:/bin"),
|
||||
"PYTHON_BIN": sys.executable,
|
||||
"HOMELAB_DOMAIN": "example.test",
|
||||
"APPCTL_SOCKET_PATH": str(non_existent_sock),
|
||||
"SITES_DIR": str(tmp_path),
|
||||
}
|
||||
if "PYTHONPATH" in os.environ:
|
||||
env["PYTHONPATH"] = os.environ["PYTHONPATH"]
|
||||
|
||||
res_comp = subprocess.run(
|
||||
[bash_bin, str(appctl_script), "completion", "bash"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert res_comp.returncode == 0
|
||||
assert "_appctl_completions()" in res_comp.stdout
|
||||
assert "up|deploy)" in res_comp.stdout
|
||||
assert "--build --no-cache" in res_comp.stdout
|
||||
|
||||
res_words = subprocess.run(
|
||||
[bash_bin, str(appctl_script), "complete", "services"],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert res_words.returncode == 0
|
||||
assert "traefik" in res_words.stdout
|
||||
assert "core" in res_words.stdout
|
||||
|
||||
|
||||
@@ -210,12 +210,24 @@ def test_deploy_params_defaults_and_explicit_bounds():
|
||||
assert p_default.recreate is True
|
||||
assert p_default.remove_orphans is True
|
||||
assert p_default.build is False
|
||||
assert p_default.no_cache is False
|
||||
|
||||
# Explicit
|
||||
p_custom = DeployParams(recreate=False, remove_orphans=False, build=True)
|
||||
p_custom = DeployParams(recreate=False, remove_orphans=False, build=True, no_cache=False)
|
||||
assert p_custom.recreate is False
|
||||
assert p_custom.remove_orphans is False
|
||||
assert p_custom.build is True
|
||||
assert p_custom.no_cache is False
|
||||
|
||||
# no_cache implies build=True
|
||||
p_no_cache = DeployParams(no_cache=True)
|
||||
assert p_no_cache.no_cache is True
|
||||
assert p_no_cache.build is True
|
||||
|
||||
# no_cache overrides explicit build=False
|
||||
p_override = DeployParams(build=False, no_cache=True)
|
||||
assert p_override.no_cache is True
|
||||
assert p_override.build is True
|
||||
|
||||
|
||||
def test_deploy_params_rejects_non_strict_types():
|
||||
@@ -226,6 +238,8 @@ def test_deploy_params_rejects_non_strict_types():
|
||||
DeployParams(remove_orphans=bad_bool) # type: ignore[arg-type]
|
||||
with pytest.raises(ValidationError):
|
||||
DeployParams(build=bad_bool) # type: ignore[arg-type]
|
||||
with pytest.raises(ValidationError):
|
||||
DeployParams(no_cache=bad_bool) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_deploy_params_rejects_extra_fields():
|
||||
@@ -238,23 +252,38 @@ def test_update_params_defaults_and_explicit():
|
||||
p_default = UpdateParams()
|
||||
assert p_default.expected_branch is None
|
||||
assert p_default.build is False
|
||||
assert p_default.no_cache is False
|
||||
|
||||
# Explicit
|
||||
p_custom = UpdateParams(expected_branch="main", build=True)
|
||||
p_custom = UpdateParams(expected_branch="main", build=True, no_cache=False)
|
||||
assert p_custom.expected_branch == "main"
|
||||
assert p_custom.build is True
|
||||
assert p_custom.no_cache is False
|
||||
|
||||
# no_cache implies build=True
|
||||
p_no_cache = UpdateParams(no_cache=True)
|
||||
assert p_no_cache.no_cache is True
|
||||
assert p_no_cache.build is True
|
||||
|
||||
# no_cache overrides explicit build=False
|
||||
p_override = UpdateParams(build=False, no_cache=True)
|
||||
assert p_override.no_cache is True
|
||||
assert p_override.build is True
|
||||
|
||||
|
||||
def test_update_params_rejects_empty_branch_and_non_strict_types():
|
||||
for bad_bool in ["true", "false", 1, 0, None, [True]]:
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams(build=bad_bool) # type: ignore[arg-type]
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams(no_cache=bad_bool) # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams(expected_branch="") # min_length=1
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams(expected_branch=123) # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams(build="true") # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
UpdateParams.model_validate({"build": False, "extra": "prohibited"})
|
||||
|
||||
|
||||
@@ -200,6 +200,7 @@ def test_docker_status_parser_running(monkeypatch):
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
mock.returncode = 0
|
||||
if "ps" in args:
|
||||
mock.stdout = "container123\n"
|
||||
if "inspect" in args:
|
||||
@@ -217,6 +218,7 @@ def test_docker_status_parser_stopped(monkeypatch):
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
mock.returncode = 0
|
||||
if "ps" in args:
|
||||
mock.stdout = ""
|
||||
return mock
|
||||
@@ -232,6 +234,7 @@ def test_docker_status_parser_degraded(monkeypatch):
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
mock.returncode = 0
|
||||
if "ps" in args:
|
||||
mock.stdout = "c1\nc2\n"
|
||||
if "inspect" in args:
|
||||
@@ -256,6 +259,7 @@ def test_docker_status_single_container(monkeypatch):
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
mock = MagicMock()
|
||||
mock.returncode = 0
|
||||
if "authelia" in args:
|
||||
mock.stdout = "true\n"
|
||||
else:
|
||||
@@ -268,6 +272,72 @@ def test_docker_status_single_container(monkeypatch):
|
||||
assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped"
|
||||
|
||||
|
||||
def test_docker_status_compose_ps_daemon_error(monkeypatch):
|
||||
"""Ensure get_docker_status returns '❓ Unknown' when docker compose ps fails (e.g. daemon unreachable)."""
|
||||
import subprocess
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
return subprocess.CompletedProcess(
|
||||
args=args,
|
||||
returncode=1,
|
||||
stdout="",
|
||||
stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
|
||||
)
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
assert engine.get_docker_status("/fake/dir") == "❓ Unknown"
|
||||
|
||||
|
||||
def test_docker_status_compose_inspect_error(monkeypatch):
|
||||
"""Ensure get_docker_status returns '❓ Unknown' when docker inspect fails for compose containers."""
|
||||
import subprocess
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
if "ps" in args:
|
||||
return subprocess.CompletedProcess(args=args, returncode=0, stdout="c1\n", stderr="")
|
||||
return subprocess.CompletedProcess(
|
||||
args=args,
|
||||
returncode=1,
|
||||
stdout="",
|
||||
stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
|
||||
)
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
assert engine.get_docker_status("/fake/dir") == "❓ Unknown"
|
||||
|
||||
|
||||
def test_docker_status_single_container_daemon_error(monkeypatch):
|
||||
"""Ensure get_docker_status returns '❓ Unknown' when inspecting single container fails due to daemon error."""
|
||||
import subprocess
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
return subprocess.CompletedProcess(
|
||||
args=args,
|
||||
returncode=1,
|
||||
stdout="",
|
||||
stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
|
||||
)
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
assert engine.get_docker_status("", container_name="traefik") == "❓ Unknown"
|
||||
|
||||
|
||||
def test_docker_status_single_container_no_such_object(monkeypatch):
|
||||
"""Ensure get_docker_status returns '🔴 Stopped' when container does not exist."""
|
||||
import subprocess
|
||||
|
||||
def mock_run(args, **kwargs):
|
||||
return subprocess.CompletedProcess(
|
||||
args=args,
|
||||
returncode=1,
|
||||
stdout="",
|
||||
stderr="Error: No such object: traefik",
|
||||
)
|
||||
|
||||
monkeypatch.setattr("subprocess.run", mock_run)
|
||||
assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped"
|
||||
|
||||
|
||||
def test_docker_status_error_handling(monkeypatch):
|
||||
"""Ensure get_docker_status handles subprocess failures gracefully."""
|
||||
|
||||
|
||||
@@ -411,6 +411,65 @@ def test_operational_router_dispatches_workload_deploy(
|
||||
assert "up" in mock_run.call_args[0][0]
|
||||
|
||||
|
||||
def test_operational_router_workload_deploy_build_flags(
|
||||
tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path
|
||||
):
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_workload_dir.parent,
|
||||
)
|
||||
mock_app = MagicMock()
|
||||
mock_app.name = "snappymail"
|
||||
mock_app.dir_path = str(mock_workload_dir)
|
||||
|
||||
# 1. Deploy with build=True passes --pull
|
||||
req_build = OperationRequest.model_validate({
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
"parameters": {"build": True},
|
||||
})
|
||||
executed_commands: list[list[str]] = []
|
||||
|
||||
def mock_subproc(cmd: list[str], **kwargs):
|
||||
executed_commands.append(cmd)
|
||||
return 0, "ok", ""
|
||||
|
||||
with (
|
||||
patch("appctl_router.resolve_app", return_value=mock_app),
|
||||
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
|
||||
patch("appctl_router.cmd_sync_homepage"),
|
||||
):
|
||||
resp = router.dispatch(req_build, admin_principal)
|
||||
assert resp.success is True
|
||||
build_calls = [c for c in executed_commands if "build" in c]
|
||||
assert len(build_calls) == 1
|
||||
assert build_calls[0] == [
|
||||
"docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull"
|
||||
]
|
||||
|
||||
# 2. Deploy with no_cache=True passes --pull and --no-cache
|
||||
req_no_cache = OperationRequest.model_validate({
|
||||
"operation": "workload.deploy",
|
||||
"target": "snappymail",
|
||||
"parameters": {"no_cache": True},
|
||||
})
|
||||
executed_commands.clear()
|
||||
|
||||
with (
|
||||
patch("appctl_router.resolve_app", return_value=mock_app),
|
||||
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
|
||||
patch("appctl_router.cmd_sync_homepage"),
|
||||
):
|
||||
resp = router.dispatch(req_no_cache, admin_principal)
|
||||
assert resp.success is True
|
||||
build_calls = [c for c in executed_commands if "build" in c]
|
||||
assert len(build_calls) == 1
|
||||
assert build_calls[0] == [
|
||||
"docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull", "--no-cache"
|
||||
]
|
||||
|
||||
|
||||
def test_operational_router_workload_update_rejects_dirty_git_tree(
|
||||
tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path
|
||||
):
|
||||
@@ -527,6 +586,138 @@ def test_operational_router_workload_update_succeeds_on_clean_tree(
|
||||
assert len(pull_calls) == 2 # git pull and docker compose pull
|
||||
|
||||
|
||||
def test_operational_router_workload_update_build_and_no_cache_flags(
|
||||
tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path
|
||||
):
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_workload_dir.parent,
|
||||
)
|
||||
mock_app = MagicMock()
|
||||
mock_app.name = "snappymail"
|
||||
mock_app.dir_path = str(mock_workload_dir)
|
||||
|
||||
executed_commands: list[list[str]] = []
|
||||
|
||||
def mock_subproc(cmd: list[str], **kwargs):
|
||||
executed_commands.append(cmd)
|
||||
if "status" in cmd:
|
||||
return 0, "", ""
|
||||
if "pull" in cmd and "git" in cmd:
|
||||
return 0, "Updating 1111..2222\nFast-forward", ""
|
||||
if "rev-parse" in cmd:
|
||||
return 0, "a1b2c3d", ""
|
||||
return 0, "success", ""
|
||||
|
||||
# 1. Update with build=True
|
||||
req_build = OperationRequest.model_validate({
|
||||
"operation": "workload.update",
|
||||
"target": "snappymail",
|
||||
"parameters": {"build": True},
|
||||
})
|
||||
|
||||
with (
|
||||
patch("appctl_router.resolve_app", return_value=mock_app),
|
||||
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
|
||||
patch("appctl_router.cmd_sync_homepage"),
|
||||
):
|
||||
resp = router.dispatch(req_build, admin_principal)
|
||||
assert resp.success is True
|
||||
build_calls = [c for c in executed_commands if "build" in c]
|
||||
assert len(build_calls) == 1
|
||||
assert build_calls[0] == [
|
||||
"docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull"
|
||||
]
|
||||
# Also ensure compose_up was executed
|
||||
up_calls = [c for c in executed_commands if "up" in c]
|
||||
assert len(up_calls) == 1
|
||||
|
||||
# 2. Update with no_cache=True implies build=True and appends --no-cache
|
||||
req_no_cache = OperationRequest.model_validate({
|
||||
"operation": "workload.update",
|
||||
"target": "snappymail",
|
||||
"parameters": {"no_cache": True},
|
||||
})
|
||||
executed_commands.clear()
|
||||
|
||||
with (
|
||||
patch("appctl_router.resolve_app", return_value=mock_app),
|
||||
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
|
||||
patch("appctl_router.cmd_sync_homepage"),
|
||||
):
|
||||
resp = router.dispatch(req_no_cache, admin_principal)
|
||||
assert resp.success is True
|
||||
build_calls = [c for c in executed_commands if "build" in c]
|
||||
assert len(build_calls) == 1
|
||||
assert build_calls[0] == [
|
||||
"docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull", "--no-cache"
|
||||
]
|
||||
up_calls = [c for c in executed_commands if "up" in c]
|
||||
assert len(up_calls) == 1
|
||||
|
||||
|
||||
def test_operational_router_workload_update_declared_compose_build(
|
||||
tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path
|
||||
):
|
||||
# Rewrite app.yaml with declared compose_build action
|
||||
manifest_content = """
|
||||
schema_version: "1.0"
|
||||
name: "snappymail"
|
||||
source:
|
||||
type: "git"
|
||||
url: "https://github.com/example/snappymail.git"
|
||||
ref: "main"
|
||||
deployment:
|
||||
strategy: "compose"
|
||||
actions:
|
||||
- "git_pull"
|
||||
- "compose_build"
|
||||
- "compose_up"
|
||||
"""
|
||||
(mock_workload_dir / "app.yaml").write_text(manifest_content.strip(), encoding="utf-8")
|
||||
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_workload_dir.parent,
|
||||
)
|
||||
mock_app = MagicMock()
|
||||
mock_app.name = "snappymail"
|
||||
mock_app.dir_path = str(mock_workload_dir)
|
||||
|
||||
executed_commands: list[list[str]] = []
|
||||
|
||||
def mock_subproc(cmd: list[str], **kwargs):
|
||||
executed_commands.append(cmd)
|
||||
if "status" in cmd:
|
||||
return 0, "", ""
|
||||
if "pull" in cmd and "git" in cmd:
|
||||
return 0, "Updating 1111..2222\nFast-forward", ""
|
||||
if "rev-parse" in cmd:
|
||||
return 0, "a1b2c3d", ""
|
||||
return 0, "success", ""
|
||||
|
||||
# Update with declared compose_build invokes build --pull
|
||||
req = OperationRequest.model_validate({
|
||||
"operation": "workload.update",
|
||||
"target": "snappymail",
|
||||
})
|
||||
|
||||
with (
|
||||
patch("appctl_router.resolve_app", return_value=mock_app),
|
||||
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
|
||||
patch("appctl_router.cmd_sync_homepage"),
|
||||
):
|
||||
resp = router.dispatch(req, admin_principal)
|
||||
assert resp.success is True
|
||||
build_calls = [c for c in executed_commands if "build" in c]
|
||||
assert len(build_calls) == 1
|
||||
assert build_calls[0] == [
|
||||
"docker", "compose", "-f", str(mock_workload_dir / "docker-compose.yml"), "build", "--pull"
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Core Platform Stack & Core Service Dispatch (Issue #2)
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -829,3 +1020,132 @@ def test_operational_router_workload_list_honors_filter_params(
|
||||
assert mock_ssl.call_count >= 1
|
||||
|
||||
|
||||
def test_operational_router_workload_list_includes_live_docker_and_two_axis_status(
|
||||
tmp_path: Path,
|
||||
viewer_principal: Principal,
|
||||
mock_workload_dir: Path,
|
||||
mock_core_dir: Path,
|
||||
):
|
||||
"""Ensure workload.list always inspects docker status and computes two-axis status for apps and core."""
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_workload_dir.parent,
|
||||
core_dir=mock_core_dir,
|
||||
)
|
||||
|
||||
with patch("appctl_router.get_docker_status", return_value="🟢 Running (1)") as mock_docker:
|
||||
# 1. Sites workload offline (fetch=False)
|
||||
resp = router.dispatch(
|
||||
OperationRequest.model_validate({
|
||||
"operation": "workload.list",
|
||||
"parameters": {"core": False, "fetch": False, "ssl": False},
|
||||
}),
|
||||
viewer_principal,
|
||||
)
|
||||
assert resp.success is True
|
||||
assert resp.result is not None
|
||||
workload = resp.result["workloads"][0]
|
||||
assert workload["name"] == "snappymail"
|
||||
assert workload["status"] == "🟢 Running (1)"
|
||||
assert "deployment_status" in workload
|
||||
assert "provenance_status" in workload
|
||||
assert workload["provenance_status"] == "— Not Checked"
|
||||
mock_docker.assert_called_with(dir_path=mock_workload_dir)
|
||||
|
||||
# 2. Core services included (core=True)
|
||||
resp_core = router.dispatch(
|
||||
OperationRequest.model_validate({
|
||||
"operation": "workload.list",
|
||||
"parameters": {"core": True, "fetch": False, "ssl": False},
|
||||
}),
|
||||
viewer_principal,
|
||||
)
|
||||
assert resp_core.success is True
|
||||
assert resp_core.result is not None
|
||||
core_workloads = {w["name"]: w for w in resp_core.result["workloads"]}
|
||||
assert "traefik" in core_workloads
|
||||
traefik = core_workloads["traefik"]
|
||||
assert traefik["status"] == "🟢 Running (1)"
|
||||
assert traefik["provenance_status"] == "— Core Platform"
|
||||
assert "deployment_status" in traefik
|
||||
|
||||
|
||||
def test_operational_router_workload_list_fetch_passes_fetch_upstream(
|
||||
tmp_path: Path,
|
||||
viewer_principal: Principal,
|
||||
mock_workload_dir: Path,
|
||||
mock_core_dir: Path,
|
||||
):
|
||||
"""Ensure workload.list with fetch=True calls inspect_workload_two_axis with fetch_upstream=True."""
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_workload_dir.parent,
|
||||
core_dir=mock_core_dir,
|
||||
)
|
||||
|
||||
with (
|
||||
patch("appctl_router.get_docker_status", return_value="🟢 Running (1)"),
|
||||
patch("appctl_router.inspect_workload_two_axis") as mock_inspect,
|
||||
):
|
||||
mock_two_axis = MagicMock()
|
||||
mock_two_axis.checkout.status_label = "✓ Synced (main)"
|
||||
mock_two_axis.provenance.status.value = "✓ Synced"
|
||||
mock_inspect.return_value = mock_two_axis
|
||||
|
||||
resp_fetch = router.dispatch(
|
||||
OperationRequest.model_validate({
|
||||
"operation": "workload.list",
|
||||
"parameters": {"core": False, "fetch": True, "ssl": False},
|
||||
}),
|
||||
viewer_principal,
|
||||
)
|
||||
assert resp_fetch.success is True
|
||||
assert resp_fetch.result is not None
|
||||
mock_inspect.assert_called_once()
|
||||
_, kwargs = mock_inspect.call_args
|
||||
assert kwargs.get("fetch_upstream") is True
|
||||
w = resp_fetch.result["workloads"][0]
|
||||
assert w["deployment_status"] == "✓ Synced (main)"
|
||||
assert w["provenance_status"] == "✓ Synced"
|
||||
|
||||
|
||||
def test_operational_router_workload_list_handles_manifest_error(
|
||||
tmp_path: Path,
|
||||
viewer_principal: Principal,
|
||||
mock_sites_dir: Path,
|
||||
mock_core_dir: Path,
|
||||
):
|
||||
"""Ensure workload.list sets deployment_status and provenance_status correctly for apps with manifest errors."""
|
||||
broken_app_dir = mock_sites_dir / "broken-app"
|
||||
broken_app_dir.mkdir(parents=True, exist_ok=True)
|
||||
(broken_app_dir / "app.yaml").write_text("invalid_yaml: [unclosed list", encoding="utf-8")
|
||||
|
||||
router = OperationalRouter(
|
||||
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
|
||||
lock_manager=TargetLockManager(tmp_path / "locks"),
|
||||
sites_dir=mock_sites_dir,
|
||||
core_dir=mock_core_dir,
|
||||
)
|
||||
|
||||
with patch("appctl_router.get_docker_status", return_value="🔴 Stopped"):
|
||||
resp = router.dispatch(
|
||||
OperationRequest.model_validate({
|
||||
"operation": "workload.list",
|
||||
"parameters": {"core": False, "fetch": False, "ssl": False},
|
||||
}),
|
||||
viewer_principal,
|
||||
)
|
||||
assert resp.success is True
|
||||
assert resp.result is not None
|
||||
apps = {w["name"]: w for w in resp.result["workloads"]}
|
||||
assert "broken-app" in apps
|
||||
broken = apps["broken-app"]
|
||||
assert broken["manifest_error"] is not None
|
||||
assert broken["deployment_status"] == "⚠️ Manifest Error"
|
||||
assert broken["provenance_status"] == "⚠️ Invalid Manifest"
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
"""
|
||||
tests/unit/test_bootstrap_token.py — Unit Tests for Operator Admin Token Bootstrap Helper (WP4)
|
||||
|
||||
Verifies:
|
||||
- 256-bit secure token generation (64 hex characters) and matching SHA-256 digest
|
||||
- Strict 0600 file mode and 0700 parent directory creation
|
||||
- TokenDescriptor Pydantic validation (scripts/appctl_auth.py)
|
||||
- Refusal to overwrite existing token file without --force
|
||||
- Overwriting existing token file when --force is supplied
|
||||
- Secrets leakage prevention: raw Bearer token never appears in stdout/stderr
|
||||
- Machine-readable JSON output via --print-json
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import stat
|
||||
import string
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from appctl_auth import Role, TokenDescriptor
|
||||
from bootstrap_token import (
|
||||
bootstrap_token,
|
||||
generate_token,
|
||||
main,
|
||||
write_token_file,
|
||||
)
|
||||
|
||||
|
||||
def test_generate_token_produces_64_hex_token_and_valid_sha256() -> None:
|
||||
raw_token, digest = generate_token()
|
||||
assert len(raw_token) == 64
|
||||
assert all(c in string.hexdigits for c in raw_token)
|
||||
assert len(digest) == 64
|
||||
assert all(c in string.hexdigits for c in digest)
|
||||
expected_digest = hashlib.sha256(raw_token.encode("utf-8")).hexdigest()
|
||||
assert digest == expected_digest
|
||||
|
||||
|
||||
def test_write_token_file_creates_file_and_enforces_0600(tmp_path: Path) -> None:
|
||||
token_file = tmp_path / "subdir" / "token"
|
||||
write_token_file(token_file, "secret-token-12345")
|
||||
assert token_file.is_file()
|
||||
assert stat.S_IMODE(token_file.stat().st_mode) == 0o600
|
||||
assert stat.S_IMODE(token_file.parent.stat().st_mode) == 0o700
|
||||
assert token_file.read_text(encoding="utf-8") == "secret-token-12345\n"
|
||||
|
||||
|
||||
def test_bootstrap_token_generates_file_with_strict_mode_0600(tmp_path: Path) -> None:
|
||||
nested_dir = tmp_path / "nested" / "homelab"
|
||||
token_file = nested_dir / "token"
|
||||
|
||||
descriptor = bootstrap_token(output_path=token_file)
|
||||
|
||||
assert token_file.is_file()
|
||||
# Check parent directory mode is 0700
|
||||
parent_mode = stat.S_IMODE(nested_dir.stat().st_mode)
|
||||
assert parent_mode == 0o700, f"Expected parent mode 0700, got {oct(parent_mode)}"
|
||||
|
||||
# Check token file mode is 0600
|
||||
file_mode = stat.S_IMODE(token_file.stat().st_mode)
|
||||
assert file_mode == 0o600, f"Expected file mode 0600, got {oct(file_mode)}"
|
||||
|
||||
raw_token = token_file.read_text(encoding="utf-8").strip()
|
||||
assert len(raw_token) == 64
|
||||
assert hashlib.sha256(raw_token.encode("utf-8")).hexdigest() == descriptor["sha256"]
|
||||
|
||||
|
||||
def test_bootstrap_token_descriptor_validates_against_token_descriptor(tmp_path: Path) -> None:
|
||||
token_file = tmp_path / "custom_token"
|
||||
descriptor = bootstrap_token(
|
||||
output_path=token_file,
|
||||
token_id="custom-admin",
|
||||
identity="operator",
|
||||
role="homelab-admin",
|
||||
)
|
||||
|
||||
validated = TokenDescriptor.model_validate(descriptor)
|
||||
assert validated.token_id == "custom-admin"
|
||||
assert validated.identity == "operator"
|
||||
assert validated.role == Role.ADMIN
|
||||
assert len(validated.sha256) == 64
|
||||
|
||||
|
||||
def test_bootstrap_token_refuses_overwrite_without_force(tmp_path: Path) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
bootstrap_token(output_path=token_file)
|
||||
original_token = token_file.read_text(encoding="utf-8")
|
||||
|
||||
with pytest.raises(FileExistsError, match="already exists"):
|
||||
bootstrap_token(output_path=token_file, force=False)
|
||||
|
||||
assert token_file.read_text(encoding="utf-8") == original_token
|
||||
|
||||
|
||||
def test_bootstrap_token_overwrites_with_force(tmp_path: Path) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
descriptor1 = bootstrap_token(output_path=token_file)
|
||||
first_token = token_file.read_text(encoding="utf-8").strip()
|
||||
|
||||
descriptor2 = bootstrap_token(output_path=token_file, force=True)
|
||||
second_token = token_file.read_text(encoding="utf-8").strip()
|
||||
|
||||
assert first_token != second_token
|
||||
assert descriptor1["sha256"] != descriptor2["sha256"]
|
||||
assert descriptor2["sha256"] == hashlib.sha256(second_token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def test_bootstrap_cli_never_prints_raw_secret_to_stdout_or_stderr(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
ret = main(["--output", str(token_file)])
|
||||
assert ret == 0
|
||||
|
||||
raw_token = token_file.read_text(encoding="utf-8").strip()
|
||||
captured = capsys.readouterr()
|
||||
|
||||
# RAW SECRET MUST NEVER APPEAR IN STDOUT OR STDERR
|
||||
assert raw_token not in captured.out, "Leak: raw token found in stdout!"
|
||||
assert raw_token not in captured.err, "Leak: raw token found in stderr!"
|
||||
|
||||
# Ensure stdout provides helpful human guidance
|
||||
assert "operator-admin" in captured.out
|
||||
assert "sops nixos/secrets.yaml" in captured.out
|
||||
|
||||
|
||||
def test_bootstrap_cli_print_json_outputs_valid_json_descriptor(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
ret = main(["--output", str(token_file), "--print-json"])
|
||||
assert ret == 0
|
||||
|
||||
raw_token = token_file.read_text(encoding="utf-8").strip()
|
||||
captured = capsys.readouterr()
|
||||
|
||||
assert raw_token not in captured.out
|
||||
assert captured.err == ""
|
||||
|
||||
# Must be cleanly parseable as pure JSON
|
||||
data: dict[str, Any] = json.loads(captured.out.strip())
|
||||
validated = TokenDescriptor.model_validate(data)
|
||||
assert validated.token_id == "operator-admin"
|
||||
assert validated.identity == "operator"
|
||||
assert validated.role == Role.ADMIN
|
||||
assert validated.sha256 == hashlib.sha256(raw_token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def test_bootstrap_cli_refuses_overwrite_and_exits_nonzero(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
assert main(["--output", str(token_file)]) == 0
|
||||
|
||||
ret = main(["--output", str(token_file)])
|
||||
assert ret != 0
|
||||
captured = capsys.readouterr()
|
||||
assert "already exists" in captured.err
|
||||
|
||||
|
||||
def test_bootstrap_cli_force_overwrites(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
token_file = tmp_path / "token"
|
||||
assert main(["--output", str(token_file)]) == 0
|
||||
tok1 = token_file.read_text(encoding="utf-8").strip()
|
||||
|
||||
assert main(["--output", str(token_file), "--force"]) == 0
|
||||
tok2 = token_file.read_text(encoding="utf-8").strip()
|
||||
|
||||
assert tok1 != tok2
|
||||
@@ -39,8 +39,9 @@ x 2026-10-23 (A) Migrate operator user from kiskaadee to operator in nixos/confi
|
||||
x 2026-10-23 (A) Derive LLDAP_LDAP_BASE_DN dynamically from homelab.domain in nixos/modules/homeserver.nix and docker-compose.yml +nixos @auth
|
||||
x 2026-10-23 (A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites and homepage in nixos/modules/homeserver.nix +nixos @perms
|
||||
x 2026-10-23 (A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git
|
||||
(B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security
|
||||
(B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux
|
||||
(B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth
|
||||
(B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4
|
||||
(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 (B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security
|
||||
x 2026-10-30 (B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux
|
||||
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
|
||||
Reference in new issue
Block a user