- Declare project.requires-python = ">=3.13" in pyproject.toml
- Lock dependencies and virtual package in uv.lock
- Update datetime.timezone.utc usages to datetime.UTC across scripts
@@ -30,9 +30,9 @@ It describes the implementation trajectory and phased engineering milestones for
| :--- | :--- | :--- | :--- | :--- |
| :--- | :--- | :--- | :--- | :--- |
| **P0** | **Baseline Consolidation** | Git & Architecture | ✅ **Completed** | Synchronized `refactor/appctl-rework` with `main`, recorded control plane ADR, scaffolded v2 metadata engine. |
| **P0** | **Baseline Consolidation** | Git & Architecture | ✅ **Completed** | Synchronized `refactor/appctl-rework` with `main`, recorded control plane ADR, scaffolded v2 metadata engine. |
| **P1** | **Mail Topology Realignment** | Topology & State | ✅ **Completed** | Move Stalwart to `smtp.roadtotech.me`; migrate SnappyMail to `~/Sites/snappymail` with zero data loss. |
| **P1** | **Mail Topology Realignment** | Topology & State | ✅ **Completed** | Move Stalwart to `smtp.roadtotech.me`; migrate SnappyMail to `~/Sites/snappymail` with zero data loss. |
Before initiating code implementation for `homelab-appctl.service`, this readiness plan formalizes the operational contracts, execution boundaries, and security invariants that P4 depends upon.
Milestones P0–P3 established the core foundation:
- **P0**: Baseline consolidation & Pytest/Nix test harness.
- **P1**: Zero-data-loss mail realignment & state isolation (`~/var/lib/homelab/snappymail`).
This plan resolves the six architectural prerequisites necessary to implement P4 as a secure, fail-closed operational control plane rather than discovering boundaries ad-hoc during coding.
---
## 📑 Sequence of Deliverables
| Deliverable | Phase | Focus | Status |
| :--- | :--- | :--- | :--- |
| **1. Implementation Inventory** | P0 Verification | Baseline truth, callers, dependencies, and migration state | ✅ **Completed** |
- [`tests/unit/test_appctl_engine.py`](../../tests/unit/test_appctl_engine.py): 12 unit tests exercising `resolve_app`, `get_docker_status`, `check_ssl_cert`, and `cmd_sync_homepage`.
- [`tests/unit/test_core_manifest.py`](../../tests/unit/test_core_manifest.py): 19 unit tests covering schema validation and ref classification.
- [`tests/unit/test_provenance.py`](../../tests/unit/test_provenance.py): 10 unit tests covering two-axis status inspection and timeout handling.
- [`tests/structural/test_repository_structure.py`](../../tests/structural/test_repository_structure.py): Asserts executability and paths of `scripts/appctl` and `scripts/appctl_engine.py`.
### D. Architectural Findings & Migration Deductions
1.**V1 Engine is Fully Superseded**: `scripts/appctl_engine.py` is now identical to the modern dataclass implementation. `scripts/appctl_engine_v2.py` is merely an alias and can be deprecated/retired once the daemon is active.
2.**Duplicated Operational Logic in GitOps**: `scripts/gitops_dispatcher.py` and `scripts/appctl` maintain **separate, duplicate implementations** of `git pull` and `docker compose up`. This violates Invariant #1 (*Single Operational Truth*). In P4, GitOps webhook handlers must delegate execution to the control-plane daemon via its internal client.
3.**Environment Injection Vulnerability in Bash**: The current Bash CLI constructs shell exports dynamically using `eval "$(python3 ...)"`. The daemon replaces this subprocess string interpolation with in-process, typed dictionary manipulation.
---
## 2. Command and Error Contract (P4 Prerequisite)
### A. Canonical Domain Operations
Every client (local CLI, remote CLI, GitOps dispatcher, and future Operations UI) invokes one of these domain operations across either transport:
| **Authentication Error** | `401 Unauthorized` | `ERR_AUTH_REQUIRED` | Missing, expired, or malformed API token / HMAC signature. |
| **Authorization Error** | `403 Forbidden` | `ERR_PERMISSION_DENIED` | Authenticated principal lacks necessary role (`homelab-admin` vs. `homelab-viewer`) for the target operation. |
| **Target Not Found** | `404 Not Found` | `ERR_TARGET_NOT_FOUND` | Workload target does not exist under `~/Sites` or Core services registry. |
| **State Conflict** | `409 Conflict` | `ERR_CONCURRENT_MUTATION` | Another mutating operation on the target workload is currently holding the operation lock. |
### A. The Core Principle: Host Access Does Not Confer Authority
Entering the host via SSH establishes Unix access, but **zero operational control plane privileges**. Every mutating request to `homelab-appctl.service` must present authenticated credentials.
### B. Principal Identity & Role Mapping
The platform defines three hierarchical authorization tiers:
| Role | Permitted Operations | Typical Principals |
- Authenticated via HMAC-SHA256 signature (`X-Gitea-Signature` / `X-Hub-Signature-256`) against `/run/secrets/gitops/webhook_secret`.
- Evaluated as an internal caller with `homelab-operator` role, constrained strictly to the target repository declared in [`config/deployments.yaml`](../../config/deployments.yaml).
1.**Daemon Isolation**: The control plane daemon does **not** ingest master decryption keys (`key.txt`) or decrypt raw SOPS archives.
2.**Ephemeral Secret Projection**: The daemon only accesses runtime projections mounted by NixOS/sops-nix under `/run/secrets/`:
-`/run/secrets/appctl/tokens.json`: Hashed token store for API authentication (mode `0400`, owned by daemon user).
-`/run/secrets/gitops/webhook_secret`: Shared HMAC secret for webhook verification (mode `0400`).
-`/run/secrets/rendered/traefik-deployments.env`: Projected workload secrets referenced during container startup.
3.**No Secret Material in Logs or Audit**: All environment injection is filtered: any environment variable or argument matching `*_KEY`, `*_SECRET`, `*_PASSWORD`, `*_TOKEN`, or `*_HASH` is redacted before logging.
### C. Systemd Unit Sandboxing (`homelab-appctl.service`)
Following the pattern established in Milestone P2 for `homelab-gitops.service`, the daemon runs with systemd sandboxing:
-`ProtectSystem = "strict"`: Host filesystem is read-only.
-`ProtectHome = "read-only"`: User home is read-only by default.
"message":"Workload updated and reconciled successfully"
}
}
```
### B. Event Lifecycle States
| Phase | Description |
| :--- | :--- |
| `DISPATCHED` | Emitted immediately after authentication and validation pass, before invoking Docker/Git. |
| `COMPLETED` | Emitted when operation terminates cleanly with exit code 0. |
| `FAILED` | Emitted when validation, Docker, or Git execution raises a non-zero exit or exception. |
| `DENIED` | Emitted when authentication fails (`401`) or authorization check fails (`403`). |
### C. Failure Handling & Audit Guarantees
1.**Pre-Execution Write**: Mutating actions log a `DISPATCHED` record before calling external binaries. If the daemon crashes or the host loses power mid-operation, the pending operation is permanently preserved in the audit log.
2.**Fail-Closed Disk Guard**: If writing to `audit.jsonl` fails (e.g. out of disk space, permission error), the daemon **immediately aborts the requested mutation and returns `ERR_EXECUTION_FAILED`**. Unaudited mutations are strictly prohibited.
3.**Audit Log Location & Service Ownership**:
- Primary: `/var/log/homelab/appctl/audit.jsonl` (systemd service root) or `~/.local/state/homelab/appctl/audit.jsonl`.
- Permissions: Mode `0600` owned by `homelab-appctl` service user.
---
## 6. P4 Definition of Done & Acceptance Test Matrix
Before marking Milestone P4 complete, the following automated regression suite must pass:
### Test Suite Matrix
| Test Suite / Area | Assertion / Invariant Verified | Failure Action |
| :--- | :--- | :--- |
| **Transport Parity** | `test_transport_dual_equivalence`: Compare outputs of `appctl list` via Unix socket vs HTTP `GET /workloads`. Assert 100% semantic and data parity. | Reject PR |
| **Unauthenticated Rejection** | `test_auth_missing_token_fails_closed`: `POST /operations/deploy` without `Authorization` header returns `401 Unauthorized` and executes zero subprocesses. | Block Release |
| **RBAC Authorization Enforcement**| `test_rbac_viewer_mutation_denied`: Present valid token with `homelab-viewer` role against `POST /operations/restart`. Assert `403 Forbidden` and zero container restarts. | Block Release |
| **Path Traversal Containment** | `test_path_traversal_rejection`: Submit target `../../etc` or `/var/run`. Assert `ERR_VALIDATION_FAILED` (400) and zero filesystem escape. | Block Release |
| **Truthful Error Reporting** | `test_execution_failure_audit`: Mock failing Docker compose run (exit 1). Assert daemon returns `ERR_EXECUTION_FAILED` (500) and records `phase: FAILED` in audit log. | Reject PR |
| **Daemon Crash Recovery** | `test_daemon_restart_preserves_state`: Kill and restart `homelab-appctl.service`. Assert running container stacks are undisturbed and desired Git state remains intact. | Reject PR |
| **Existing Invariant Regression** | Run `./scripts/test`: All 84 existing unit, security, and nix flake tests pass with 0 regressions. | Block Merge |
@@ -5,3 +5,9 @@ x 2026-10-13 (B) Implement bounded git ls-remote provenance resolver with 10s ti
x 2026-10-13 (B) Add unit tests for provenance resolution and timeout handling with mocked network fixtures in tests/unit/test_provenance.py +test @appctl
x 2026-10-13 (B) Add unit tests for provenance resolution and timeout handling with mocked network fixtures in tests/unit/test_provenance.py +test @appctl
x 2026-10-13 (C) Promote scripts/appctl_engine_v2.py to authoritative scripts/appctl_engine.py +engine @appctl
x 2026-10-13 (C) Promote scripts/appctl_engine_v2.py to authoritative scripts/appctl_engine.py +engine @appctl
x 2026-10-13 (C) Verify full test suite and update CLI wrappers for appctl v2 engine promotion +test @appctl
x 2026-10-13 (C) Verify full test suite and update CLI wrappers for appctl v2 engine promotion +test @appctl
x 2026-10-13 (A) Reconcile appctl implementation inventory and document caller/dependency map in docs/plans/p4-readiness-plan.md +inventory @p4-gate
x 2026-10-13 (A) Define canonical command and error contract across dual transports in docs/plans/p4-readiness-plan.md +contract @p4-gate
x 2026-10-13 (A) Close authorization design enforcing token-everywhere policy in docs/plans/p4-readiness-plan.md +auth @p4-gate
x 2026-10-13 (B) Specify daemon execution and privilege boundaries for Docker, subprocesses, and filesystem roots in docs/plans/p4-readiness-plan.md +security @p4-gate
x 2026-10-13 (B) Define append-only audit telemetry schema, lifecycle, and failure handling semantics in docs/plans/p4-readiness-plan.md +audit @p4-gate
x 2026-10-13 (C) Establish P4 acceptance test matrix and definition of done before daemon implementation in docs/plans/p4-readiness-plan.md +test @p4-gate
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.