Compare commits

...
8 Commits
Author SHA1 Message Date
kiskaadee 6052019f2c fix(appctl): lock HOMELAB_DOMAIN at startup to prevent application
Core Architecture & Invariant CI / validate (push) Successful in 40s
domain leaks during sync
2026-10-14 13:41:17 -05:00
kiskaadee 298ae728e1 chore(tooling): enforce python >=3.13 requirement and align uv lockfile
- 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
2026-10-14 13:41:17 -05:00
kiskaadee ecacb1cc39 docs(p4): formalize control plane readiness plan and boundary specifications
- Reconcile appctl implementation inventory and caller map
- Define canonical command and error contract with schema v1.0
- Close authorization design with strict token enforcement everywhere
- Specify daemon execution boundaries and fixed subprocess allowlist
- Formalize append-only audit telemetry schema and failure-handling semantics
- Establish P4 acceptance test matrix and definition of done
- Synchronize ROADMAP.md milestone table and todo.txt task tracking
2026-10-14 13:41:17 -05:00
kiskaadee f261b80477 chore(uv): bump python requirement to >=3.13 in uv.lock 2026-10-14 13:41:17 -05:00
kiskaadee 2c99e3e92e chore(flake): update nixpkgs and sops-nix inputs.
- bump nixpkgs to nixos-unstable 7fdd4004(2026-10-11)
- bump sops-nix to ee48786 with systemd shutdown fxi and nested JSON key
  support
2026-10-14 13:41:17 -05:00
kiskaadee 9381f3e070 feat(nixos): configure automated nix store garbage collection and deduplication
- Enable weekly garbage collection retaining generations newer than 14 days

- Enable automatic nix store hardlink deduplication
2026-10-14 13:41:17 -05:00
kiskaadee f0e0fc41a1 feat(appctl): promote engine v2 to authoritative appctl_engine and complete Milestone P3
- Promote scripts/appctl_engine_v2.py to authoritative scripts/appctl_engine.py
- Add full two-axis inspection, Homepage synchronization, and schema v1.0 support
- Convert scripts/appctl_engine_v2.py into a backward-compatibility shim
- Rename tests/unit/test_appctl_engine_v2.py to test_appctl_engine.py and remove xfail marker
- Update README.md, docs/appctl.md, and docs/architecture.md to reference appctl_engine
- Synchronize todo.txt and mark Milestone P3 as completed in ROADMAP.md
2026-10-14 13:41:17 -05:00
kiskaadee c78550abea feat(provenance): implement two-axis inspection engine and bounded upstream resolver
- Implement scripts/provenance.py evaluating local deployment checkout state independently from upstream software provenance.
- Add bounded git ls-remote provenance resolver with 10s timeout to prevent hanging on unresponsive remotes during --fetch.
- Add 10 unit tests in tests/unit/test_provenance.py covering clean/dirty detection, synced vs update-available states, timeout handling, and unreachable remotes.
- Include git in test-suite nativeBuildInputs in flake.nix for hermetic sandbox execution.
- Update todo.txt marking Tasks 3, 4, & 5 of Milestone P3 completed.
2026-10-14 13:41:17 -05:00
19 changed files with 1627 additions and 1092 deletions

No files matched your search

+1 -1
View File
@@ -82,7 +82,7 @@ To maintain clarity during development, this repository explicitly separates wha
| :--- | :--- | :--- |
| **`appctl` Architecture** | Bash CLI wrapper (`scripts/appctl`) driving local subprocesses (`docker compose`, `git`) and metadata engines. | Dedicated daemon service (`homelab-appctl.service`) exposing one logical API over Unix socket and HTTP. |
| **Operational Auth** | Sudo / Unix user permissions on the host. Sourcing secrets from `/run/secrets/`. | LLDAP directory identity. Explicit user-scoped API tokens for all mutating actions; Authelia ForwardAuth for Web. |
| **Metadata Engine** | Strongly-typed dataclass engine (`scripts/appctl_engine_v2.py`) with source provenance and Docker label inspection, operating alongside legacy engine. | Single unified engine (`core_manifest.py` / `appctl_engine.py`) embedded directly within the control plane daemon. |
| **Metadata Engine** | Authoritative dataclass engine (`scripts/appctl_engine.py`) with two-axis inspection and schema v1.0 parser (`core_manifest.py`). | Single unified engine (`core_manifest.py` / `appctl_engine.py`) embedded directly within the control plane daemon. |
| **Deployment Model** | Manual authoring of `app.yaml` and `docker-compose.yml` directly in `~/Sites/<app>/`. | 5-stage lifecycle: AI/human `DeploymentProposal` $\to$ operator-approved `DeploymentModel` committed to Git $\to$ `appctl` materialization. |
| **GitOps Engine** | Webhook dispatcher (`scripts/gitops_dispatcher.py`) listening on port 9000 with HMAC-SHA256 authentication and flock serialization. | Fully integrated into control-plane admission, calling central reconciliation endpoints. |
| **Secret Distribution** | Static 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 at runtime via `SecretProvider`. |
+5 -5
View File
@@ -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. |
| **P1** | **Mail Topology Realignment** | Topology & State | ✅ **Completed** | Move Stalwart to `smtp.roadtotech.me`; migrate SnappyMail to `~/Sites/snappymail` with zero data loss. |
| **P2** | **GitOps Hardening** | Ingress Security | 🎯 **Current / Up Next** | Authoritative Core repository registry (`deployments.yaml`), HMAC verification, systemd execution sandboxing. |
| **P3** | **Manifest Contract** | Domain Engine | ⏳ **Planned** | Schema v1.0, authoritative `core_manifest.py` library, `source.ref` semantics, two-axis status inspection. |
| **P4** | **Control Plane Daemon** | API & Dispatch | ⏳ **Planned** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), thin-client CLI, append-only audit log. |
| **P2** | **GitOps Hardening** | Ingress Security | ✅ **Completed** | Authoritative Core repository registry (`deployments.yaml`), Compose AST security validator, systemd sandboxing. |
| **P3** | **Manifest Contract** | Domain Engine | ✅ **Completed** | Schema v1.0, authoritative `core_manifest.py` library, two-axis status inspection, engine promotion. |
| **P4** | **Control Plane Daemon** | API & Dispatch | 🎯 **Current / Up Next** | `homelab-appctl.service` daemon, dual transports (socket + HTTP), thin-client CLI, append-only audit log. |
| **P5** | **Identity & Secrets** | Auth & Providers | ⏳ **Planned** | ForwardAuth header parsing, user-scoped API tokens, `SecretProvider` reference resolution. |
| **P6** | **Deployment Model & AI**| Intent Authoring | ⏳ **Planned** | Capability catalog, `DeploymentProposal` $\to$ `DeploymentModel` compiler, Git commit pipeline. |
| **P7** | **Operations UI & Portal** | Client Integration | ⏳ **Planned** | Dedicated Operations UI client, Homepage read-only status integration widgets. |
@@ -76,7 +76,7 @@ It describes the implementation trajectory and phased engineering milestones for
---
### Milestone P3: Manifest Contract Convergence & Provenance Engine
**Status**: 🎯 **Current / Up Next**
**Status**: ✅ **Completed**
* **Objective**: Establish a single authoritative manifest schema and two-axis inspection engine across the platform.
* **Key Deliverables**:
1. *Schema v1.0 & Parser Library (`core_manifest.py`)*: Strongly-typed manifest parsing, transport scheme validation (`https://`, `ssh://`, `git@`), and explicit ref semantics (moving branches vs. pinned tags vs. commit SHAs).
@@ -87,7 +87,7 @@ It describes the implementation trajectory and phased engineering milestones for
---
### Milestone P4: Appctl Control Plane Daemon & Command-Oriented API
**Status**: ⏳ **Planned**
**Status**: 🎯 **Current / Up Next**
* **Objective**: Evolve `appctl` from a collection of local shell scripts into the authoritative platform daemon.
* **Key Deliverables**:
1. *Daemon Service (`homelab-appctl.service`)*: Systemd daemon exposing one logical API across dual transports: Unix domain socket (`/run/homelab/appctl.sock`) on host and HTTP listener for network clients.
+1 -1
View File
@@ -3,7 +3,7 @@
The `appctl` tool is the command-line orchestrator and metadata engine for the **Homelab Core** platform. It coordinates interactions between independent workload repositories in `~/Sites` and platform services in `~/Core`.
> [!NOTE]
> **Implementation Reference**: This document serves as the **current implementation manual** for the `appctl` Bash CLI wrapper (`scripts/appctl`), metadata engines (`scripts/appctl_engine.py` / `scripts/appctl_engine_v2.py`), and currently consumed `app.yaml` manifest fields.
> **Implementation Reference**: This document serves as the **current implementation manual** for the `appctl` Bash CLI wrapper (`scripts/appctl`), metadata engine (`scripts/appctl_engine.py`), and currently consumed `app.yaml` manifest fields.
> For the platform's overarching control-plane architecture, 5-stage deployment model lifecycle, and phased engineering roadmap, see [`README.md`](../README.md), [`ROADMAP.md`](../ROADMAP.md), and the [Architecture Decision Index](decisions/README.md).
---
+1 -1
View File
@@ -50,7 +50,7 @@ The runtime environment consists of four functional layers:
### C. Cross-Cutting Orchestration
Orchestration coordinates operations across the runtime layers without being a runtime layer itself:
* **`appctl` CLI & Metadata Engine (`scripts/appctl`, `scripts/appctl_engine.py`, `scripts/appctl_engine_v2.py`)**: Current CLI implementation coordinating discovery, Docker status inspection, and Homepage compilation across workloads and Core. In the target architecture, this evolves into the centralized operational control plane daemon (`homelab-appctl.service`).
* **`appctl` CLI & Metadata Engine (`scripts/appctl`, `scripts/appctl_engine.py`)**: Current CLI implementation coordinating discovery, Docker status inspection, and Homepage compilation across workloads and Core. In the target architecture, this evolves into the centralized operational control plane daemon (`homelab-appctl.service`).
* **GitOps Webhook Dispatcher (`scripts/gitops_dispatcher.py`)**: Governed by the `homelab-gitops.service` systemd unit, it receives webhooks on port 9000, enforces admission policies, and dispatches serialized deployment actions for workloads or data repositories.
---
+311
View File
@@ -0,0 +1,311 @@
# 📋 Control Plane Milestone P4: Readiness Plan & Boundary Specifications
**Status**: 🛠️ **In Progress (Pre-P4 Architecture & Security Gate)**
**Target Milestone**: [Milestone P4: Appctl Control Plane Daemon & API](../../ROADMAP.md#milestone-p4-appctl-control-plane-daemon--command-oriented-api)
**Governing ADR**: [`homelab-appctl-control-plane-architecture.md`](../decisions/README.md)
---
## 🎯 Purpose & Scope
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`).
- **P2**: GitOps repository registry (`deployments.yaml`), AST security validation, and Systemd sandboxing.
- **P3**: Manifest Schema v1.0 ([`core_manifest.py`](../../scripts/core_manifest.py)), two-axis inspection ([`provenance.py`](../../scripts/provenance.py)), and promoted authoritative engine ([`appctl_engine.py`](../../scripts/appctl_engine.py)).
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** |
| **2. Command & Error Contract** | P4 Prerequisite (Blocker) | Canonical domain operations, typed schemas, and error taxonomy | 🎯 **In Review** |
| **3. Authorization Design** | Security Gate (Blocker) | Token lifecycle, RBAC matrix, and fail-closed evaluation | 🎯 **In Review** |
| **4. Execution & Privilege Boundaries** | P4 Prerequisite | Subprocess allowlist, Docker API capabilities, and filesystem roots | ⏳ Pending Gate |
| **5. Audit Telemetry Semantics** | P4 Prerequisite | RFC JSONL audit schema, persistent ownership, and lifecycle | ⏳ Pending Gate |
| **6. P4 Acceptance Test Suite** | Verification | Concrete DoD, black-box transport parity, and security regression gates | ⏳ Pending Gate |
---
## 1. Reconcile the Implementation Inventory
### A. Current File & Module Roles
| File / Component | Language | Authority Status | Functional Responsibilities |
| :--- | :--- | :--- | :--- |
| [`scripts/appctl`](../../scripts/appctl) | Bash | **Active CLI Client** | CLI entry point; secret environment sourcing (`homeserver.env`, `traefik-deployments.env`); resolves metadata via engine; directly runs `docker compose` and `git pull` subprocesses. |
| [`scripts/appctl_engine.py`](../../scripts/appctl_engine.py) | Python 3 | **Authoritative Engine** | Domain models (`SitesApp`, `CoreService`); schema v1.0 parsing (`core_manifest.py`); two-axis inspection (`provenance.py`); SSL cert inspection; Homepage compilation; metadata serialization (`resolve`). |
| [`scripts/appctl_engine_v2.py`](../../scripts/appctl_engine_v2.py) | Python 3 | **Compatibility Shim** | Thin backward-compatibility wrapper re-exporting all symbols from `appctl_engine.py`. No unique domain logic. |
| [`scripts/core_manifest.py`](../../scripts/core_manifest.py) | Python 3 | **Schema Library** | Strongly-typed Manifest dataclasses; transport validation (`https://`, `ssh://`, `git@`); ref semantics classification (`branch`, `tag`, `commit`). |
| [`scripts/provenance.py`](../../scripts/provenance.py) | Python 3 | **Provenance Library** | Two-axis status engine; local checkout inspection (`git status`, commit SHA); bounded upstream query (`git ls-remote` with 10s timeout). |
| [`scripts/gitops_dispatcher.py`](../../scripts/gitops_dispatcher.py) | Python 3 | **Independent Service** | Webhook listener (port 9000); HMAC validation; flock serialization; independent AST validation; executes its own `docker compose` and `git pull` subprocesses. |
### B. Command Inventory & Implementation Division
| Command | CLI Syntax | Handled By | Operation Type | Current Behavior |
| :--- | :--- | :--- | :--- | :--- |
| `list` / `status` | `appctl list [--fetch] [--core] [--ssl]` | `appctl_engine.py` | Read-Only | Scans `~/Sites`, evaluates two-axis checkout and upstream provenance, queries container status, prints formatted table. |
| `info` | `appctl info <service> [--ssl]` | `appctl_engine.py` | Read-Only | Prints detailed metadata, two-axis local checkout vs. upstream provenance, network memberships, and TLS certificate info. |
| `ssl` | `appctl ssl [service]` | `appctl_engine.py` | Read-Only | Connects over TLS socket (port 443), extracts peer X.509 certificate, calculates days until expiration. |
| `resolve` | `appctl resolve <query>` | `appctl_engine.py` | Read-Only | Resolves canonical name / alias; emits JSON string consumed by Bash `setup_app_env`. |
| `complete` | `appctl complete` | `appctl_engine.py` | Read-Only | Emits space-separated list of known workload names, aliases, and core services for Bash shell autocompletion. |
| `sync` | `appctl sync [--homepage-dir=PATH]` | `appctl_engine.py` | Mutating (Filesystem) | Reads all `app.yaml` manifests, groups and sorts cards by weight, writes `config/homepage/services.yaml`. |
| `up` | `appctl up <service\|core>` | `scripts/appctl` (Bash) | Mutating (Containers) | Sourced environment variables $\to$ `docker compose up -d --remove-orphans` $\to$ triggers `appctl sync`. |
| `down` | `appctl down <service\|core>` | `scripts/appctl` (Bash) | Mutating (Containers) | `docker compose down` (or `stop` for Core services) $\to$ triggers `appctl sync`. |
| `restart` | `appctl restart <service\|core>` | `scripts/appctl` (Bash) | Mutating (Containers) | Sourced environment variables $\to$ `docker compose restart` (or down/up) $\to$ triggers `appctl sync`. |
| `update` | `appctl update <service\|core>` | `scripts/appctl` (Bash) | Mutating (Git + Containers) | Verifies clean git working tree $\to$ `git pull --ff-only` $\to$ `docker compose pull` $\to$ `docker compose up -d` $\to$ triggers `appctl sync`. |
| `pull` | `appctl pull <service\|core>` | `scripts/appctl` (Bash) | Mutating (Images) | `docker compose pull` $\to$ `docker compose up -d --remove-orphans`. |
| `logs` | `appctl logs <service\|core> [-f]` | `scripts/appctl` (Bash) | Read-Only (Streaming) | Dispatches `docker compose logs -f`. |
| `config` | `appctl config <service\|core>` | `scripts/appctl` (Bash) | Read-Only | Injects environment $\to$ executes `docker compose config` to view fully evaluated compose AST. |
### C. Active Call Sites Across the Repository
1. **System Path Integration**:
- [`nixos/configuration.nix`](../../nixos/configuration.nix#L119-L122): Installs host wrapper `/run/current-system/sw/bin/appctl` calling `${CORE_DIR:-$HOME/Core}/scripts/appctl "$@"`.
2. **Internal Script Invocation**:
- `scripts/appctl` calls `python3 "$ENGINE" resolve "$query"` to set up the Compose environment.
- `scripts/appctl` calls `python3 "$ENGINE" sync` after mutating actions (`up`, `down`, `restart`, `update`).
3. **Automated Test Coverage**:
- [`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:
```
┌─────────────────────────┐
│ Client Request │
└────────────┬────────────┘
▼
┌───────────────────────────────────────────┐
│ Operation Dispatch Router │
└─────────────────────┬─────────────────────┘
│
┌───────────────────────────────┴───────────────────────────────┐
▼ ▼
[ Read-Only Operations ] [ Mutating Operations ]
• workload.list • workload.deploy
• workload.get • workload.stop
• workload.resolve • workload.restart
• workload.config • workload.update
• workload.logs • workload.pull
• platform.ssl • platform.sync_homepage
• platform.health
```
### B. Typed Request and Response Models
All requests and responses use strict JSON payloads with explicit schema versioning (`version: "1.0"`):
```json
// Example: POST /operations/deploy
// Request:
{
"version": "1.0",
"operation": "workload.deploy",
"target": "jellyfin",
"parameters": {
"recreate": true,
"remove_orphans": true
}
}
// Response (Success):
{
"version": "1.0",
"status": "success",
"operation_id": "op_01JAX71BC98E4",
"target": "jellyfin",
"timestamp": "2026-10-13T18:30:00Z",
"duration_ms": 1420,
"result": {
"action": "recreated",
"containers": ["jellyfin"],
"health": "running"
}
}
```
### C. Standardized Error Taxonomy
Failures are strongly typed and distinguished at three distinct architectural levels:
| Error Classification | HTTP Code | Error Code | Description / Fail-Closed Action |
| :--- | :--- | :--- | :--- |
| **Validation Error** | `400 Bad Request` | `ERR_VALIDATION_FAILED` | Request schema violation, invalid target name, malformed `app.yaml`, or Compose AST security violation. |
| **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. |
| **Execution Error** | `500 Internal Error`| `ERR_EXECUTION_FAILED` | Docker daemon error, subprocess non-zero exit, or persistent volume failure. |
---
## 3. Authorization Design (Security Gate)
### 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 |
| :--- | :--- | :--- |
| `homelab-admin` | All operations (including Core platform mutation, daemon reload, secret regeneration). | Break-glass admin token, human interactive operator (`kiskaadee`). |
| `homelab-operator` | Workload mutations (`deploy`, `stop`, `restart`, `update`, `pull`, `sync_homepage`). Cannot mutate Core platform infrastructure. | GitOps webhook runner token, automation scripts. |
| `homelab-viewer` | Read-only operations (`list`, `get`, `resolve`, `config`, `logs`, `ssl`, `health`). Zero mutations permitted. | Homepage dashboard status monitor, read-only diagnostic CLI. |
### C. Transport Authentication Rules
1. **Unix Domain Socket (`/run/homelab/appctl.sock`)**:
- Socket ownership: `root:homelab-operators`, file mode `0660`.
- Read-only operations allowed without token *if* the client UID belongs to `homelab-operators`.
- **All mutating operations strictly require a valid user-scoped Bearer token** passed in the request header (`Authorization: Bearer <token>`).
2. **HTTP Network Listener (Local LAN / Traefik)**:
- External Web: Traefik verifies Authelia session and forwards trusted identity headers (`Remote-User`, `Remote-Groups`). Headers are **strictly rejected** unless incoming connection originates from the trusted Docker `proxy-net` gateway.
- Remote CLI / API: Requires user-scoped Bearer token.
3. **GitOps Ingress**:
- 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).
---
## 4. Execution & Privilege Boundaries (P4 Prerequisite)
### A. Operational Capability Matrix
Each canonical operation is strictly bound to minimal execution permissions, allowable subprocesses, and filesystem boundaries:
| Domain Operation | Subprocess / Tool | Allowed Arguments / API | Required Filesystem Roots | Authority / Role Required |
| :--- | :--- | :--- | :--- | :--- |
| `workload.list` | In-process Python (`provenance.py`) | Read directory metadata; optional `git ls-remote` (10s timeout) | Read: `~/Sites/`, `Core/` | `homelab-viewer` |
| `workload.get` | In-process Python (`provenance.py`, `core_manifest.py`) | Parse `app.yaml`, inspect git status | Read: `~/Sites/<app>/` | `homelab-viewer` |
| `workload.resolve` | In-process Python (`appctl_engine.py`) | Name resolution & JSON export | Read: `~/Sites/`, `Core/` | `homelab-viewer` |
| `workload.config` | `/run/current-system/sw/bin/docker` | `compose -f <workload>/docker-compose.yml config` | Read: `~/Sites/<app>/` | `homelab-viewer` |
| `workload.logs` | `/run/current-system/sw/bin/docker` | `compose -f <workload>/docker-compose.yml logs [--tail=N] [--follow]` | Read: `~/Sites/<app>/` | `homelab-viewer` |
| `workload.deploy` | `/run/current-system/sw/bin/docker` | `compose -f <workload>/docker-compose.yml up -d --remove-orphans` | Read/Write: `~/Sites/<app>/`, `~/var/lib/homelab/<app>/` | `homelab-operator` |
| `workload.stop` | `/run/current-system/sw/bin/docker` | `compose -f <workload>/docker-compose.yml down` | Read/Write: `~/Sites/<app>/` | `homelab-operator` |
| `workload.restart`| `/run/current-system/sw/bin/docker` | `compose -f <workload>/docker-compose.yml restart` | Read/Write: `~/Sites/<app>/` | `homelab-operator` |
| `workload.pull` | `/run/current-system/sw/bin/docker` | `compose -f <workload>/docker-compose.yml pull` | Read: `~/Sites/<app>/` | `homelab-operator` |
| `workload.update` | `/run/current-system/sw/bin/git`<br>`/run/current-system/sw/bin/docker` | 1. `-C <workload> pull --ff-only`<br>2. `compose pull`<br>3. `compose up -d --remove-orphans` | Read/Write: `~/Sites/<app>/`, `~/var/lib/homelab/<app>/` | `homelab-operator` |
| `platform.sync_homepage` | In-process Python (`appctl_engine.py`) | Internal YAML AST generator | Read: `~/Sites/`<br>Write: `Core/config/homepage/services.yaml` | `homelab-operator` |
| `platform.core_restart` | `/run/current-system/sw/bin/docker` | `compose -f Core/docker-compose.yml restart [service]` | Read: `Core/` | `homelab-admin` |
### B. Secret Reference Boundary
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.
- `ReadWritePaths`: Explicitly allowlisted writable roots:
- `/home/kiskaadee/Sites` (workload definitions and Git checkouts)
- `/home/kiskaadee/var/lib/homelab` (workload persistent state roots)
- `/var/log/homelab/appctl` or `/home/kiskaadee/.local/state/homelab/appctl` (audit log directory)
- `/run/homelab` (socket runtime directory)
- `PrivateTmp = true`: Isolated temporary directories.
- `NoNewPrivileges = true`: Disallows privilege escalation.
---
## 5. Audit Telemetry Semantics (P4 Prerequisite)
### A. Field Schema (RFC-Compliant JSONL)
Every operation lifecycle event is emitted as a structured JSON object to `audit.jsonl` (mode `0600`):
```json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"audit_version": "1.0",
"event_id": "evt_01JAX73AB190",
"timestamp": "2026-10-13T18:32:05.112Z",
"phase": "COMPLETED",
"principal": {
"identity": "kiskaadee",
"role": "homelab-admin",
"token_id": "tok_99fa1b",
"auth_method": "bearer_token"
},
"action": "workload.update",
"target": "docs",
"transport": "unix_socket",
"origin": "peer_uid_1000",
"client": "appctl-cli/2.0",
"parameters": {
"recreate": true,
"remove_orphans": true
},
"result": {
"status": "SUCCESS",
"exit_code": 0,
"duration_ms": 3210,
"error_code": null,
"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 |
| **Audit Persistence Gate** | `test_audit_failure_blocks_mutation`: Mock read-only audit log. Assert mutating command fails closed with zero Docker invocations. | Block Release |
| **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 |
Generated
+7 -7
View File
@@ -2,11 +2,11 @@
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1790463110,
"narHash": "sha256-VZHcT2wKLkApBCACQ2SH4P1jVZUbbOA7jWAGi1MIViw=",
"rev": "e158d9ed9b51c98974c5e66e1ba1c9e0255fecaa",
"lastModified": 1791734076,
"narHash": "sha256-0dNcyVeoD61zhucIpt5BAQ+ytd6JzF641Z+A9bgltLo=",
"rev": "7fd4004d0511991fff3a0524856a9be09e28c5f0",
"type": "tarball",
"url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1080189.e158d9ed9b51/nixexprs.tar.zst"
"url": "https://releases.nixos.org/nixos/unstable/nixos-26.11pre1090327.7fd4004d0511/nixexprs.tar.zst"
},
"original": {
"type": "tarball",
@@ -26,11 +26,11 @@
]
},
"locked": {
"lastModified": 1790498116,
"narHash": "sha256-rs9meAYxW3zzrh43yaW7htrqCD+X9+pupDPHN86fumI=",
"lastModified": 1791710405,
"narHash": "sha256-mVD4XIc5JkqMW2K04IkFUzHgHmyJZlzw5ktfgMDCbKU=",
"owner": "Mic92",
"repo": "sops-nix",
"rev": "5efb5a6f4f5ab192817d28557dd4d650fa14d866",
"rev": "ee48786c6f9160d2c1a084aac841f68195b8420c",
"type": "github"
},
"original": {
+1
View File
@@ -43,6 +43,7 @@
checks.${system} = {
test-suite = pkgs.runCommand "core-tests" {
nativeBuildInputs = with pkgs; [
git
python3
python3Packages.pytest
python3Packages.pyyaml
+9 -1
View File
@@ -19,12 +19,20 @@
sops.defaultSopsFile = ./secrets.yaml;
sops.defaultSopsFormat = "yaml";
# ── Nix settings ─────────────────────────────────────────────────────────────
# ── Nix settings & maintenance ───────────────────────────────────────────────
nix.settings.experimental-features = [ "nix-command" "flakes" ];
# Pin nixpkgs registry to the flake input (avoids GitHub API calls from the CLI)
nix.registry.nixpkgs.flake = inputs.nixpkgs;
# Automated garbage collection and store hardlink deduplication
nix.gc = {
automatic = true;
dates = "weekly";
options = "--delete-older-than 14d";
};
nix.optimise.automatic = true;
nixpkgs.config.allowUnfree = true;
# ── Regional & locale settings ───────────────────────────────────────────────
+2 -2
View File
@@ -17,7 +17,7 @@ import subprocess
import sys
import urllib.error
import urllib.request
from datetime import datetime, timezone
from datetime import UTC, datetime
# History file location storing the transition log of public IP states.
# Defaults to a state directory managed securely by the systemd service unit.
@@ -133,7 +133,7 @@ def record_ip(ip, status, details=None):
"""
os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
entry = {
"timestamp": datetime.now(tz=timezone.utc).isoformat(),
"timestamp": datetime.now(tz=UTC).isoformat(),
"ip": ip,
"status": status
}
+7
View File
@@ -1,3 +1,10 @@
[project]
name = "homelab-core"
version = "0.1.0"
description = "Homelab Core platform and orchestration"
requires-python = ">=3.13"
dependencies = []
[tool.pyright]
extraPaths = ["scripts"]
exclude = [
+3
View File
@@ -35,6 +35,9 @@ if [ -f "$ENV_FILE" ]; then
set +a
fi
# Lock the homelab root domain before setup_app_env can mutate $DOMAIN
export HOMELAB_DOMAIN="${HOMELAB_DOMAIN:-${DOMAIN_SUFFIX:-${DOMAIN:-roadtotech.me}}}"
# Show help usage
show_help() {
echo "🚀 appctl - Homelab Container Orchestrator"
+694 -617
View File
File diff suppressed because it is too large. Load diff
Regular → Executable
+11 -445
View File
@@ -1,450 +1,16 @@
import os
import subprocess
#!/usr/bin/env python3
"""
appctl_engine_v2.py - Backward-compatibility shim pointing to appctl_engine.py.
"""
from __future__ import annotations
import sys
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any
import yaml
sys.path.insert(0, str(Path(__file__).resolve().parent))
# Dynamic Environment Paths
CORE_DIR = os.environ.get(
"CORE_DIR", os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
)
from appctl_engine import *
from appctl_engine import main
SITES_DIR = os.environ.get(
"SITES_DIR",
os.path.join(os.path.dirname(CORE_DIR), "Sites")
if os.path.isdir(os.path.join(os.path.dirname(CORE_DIR), "Sites"))
else os.path.expanduser("~/Sites"),
)
HOMELAB_DOMAIN = os.environ.get("HOMELAB_DOMAIN") or os.environ.get("DOMAIN", "")
def validate_environment() -> None:
"""Ensure mandatory environment configuration is valid before CLI execution."""
errors: list[str] = []
if not HOMELAB_DOMAIN:
errors.append(
"• Missing 'HOMELAB_DOMAIN' (or 'DOMAIN') environment variable.\n"
" Please export it (e.g. export HOMELAB_DOMAIN='roadtotech.me') or set it in your environment file."
)
if not os.path.isdir(CORE_DIR):
errors.append(f"• Core directory not found at: {CORE_DIR}")
if errors:
print("❌ Environment Validation Failed:\n", file=sys.stderr)
for err in errors:
print(f" {err}", file=sys.stderr)
sys.exit(1)
class ManifestError(Exception):
pass
@dataclass
class HomepageConfig:
title: str
group: str = "Applications"
icon: str = "default.png"
container: str = ""
weight: int = 50
@dataclass
class SourceConfig:
"""Upstream source provenance descriptor."""
type: str = "git" # "git"
url: str = "" # e.g., "https://git.roadtotech.me/kiskaadee/bitetrack.git"
ref: str = "main" # Branch (e.g. "main"), tag (e.g. "v1.0.0"), or commit SHA
@dataclass
class App:
name: str # Canonical identified (e.g., "traefik", "jellyfin")
description: str # Human-readable summary for dashboards and CLI info
domain: str # Routing FQDN (e.g., "auth.roadtotech.me") or "internal".
dir_path: str # Filesystem directory (CORE_DIR for Core, or ~/Sites/<app> for Sites).
@property
def is_internal(self) -> bool:
"""Returns True if the service does not expose a public TLS endpoint."""
return not self.domain or self.domain == "internal" or self.domain.endswith(".local") or ":" in self.domain
def to_dict(self) -> dict[str, Any]:
"""Serialize for JSON consumption by scripts/appctl"""
data = asdict(self)
data["type"] = getattr(self, "app_type", "app")
return data
@dataclass
class CoreService(App):
container: str = "" # Target container name inside Core's root docker-compose.yml (e.g., "authelia", "stalwart")
weight: int = 50 # Homepage ordering weight (optional, for dashboard synchronization)
icon: str = "default.png" # Dashboard icon filename
app_type: str = "core_service"
dir_path: str = CORE_DIR
@dataclass
class SitesApp(App):
dir_name: str = "" # directory name in ~/Sites (e.g., "homelab-vaultwarden")
source: SourceConfig | None = None # Upstream source provenance (optional; None indicates Image-Only workload)
aliases: list[str] = field(default_factory=list) # CLI resolution aliases (e.g., "vw", "vaultwarden")
visible: bool = True # Defines whether the icon is visible in the Homepage Dashboard
auth: bool = True # Authelia protection guard indicator; Defaulting to True is safer
has_compose: bool = False # Whether a docker-compose.yaml exists at ~/Sites/dir_name.
networks: list[str] = field(default_factory=lambda: ["proxy-net"]) # Docker network attachments (def ["proxy-net"])
env: dict[str, Any] = field(default_factory=dict) # Dynamic environment variable overrides
homepage: HomepageConfig | None = None # Dashboard Card Configuration
manifest_error: str | None = None # Captured syntax/loading errors if app.yaml was malformed/absent
app_type: str = "app"
def load_manifest(manifest_path: str) -> dict[str, Any]:
"""Load and parese the app manifest file
Raises:
FileNotFoundError: if the manifest file does not exist.
ValueError: if YAML object is malformed.
TypeError: If root is not a directory
"""
if not os.path.isfile(manifest_path):
raise FileNotFoundError(f"Manifest file not found at {manifest_path}")
try:
with open(manifest_path, "r", encoding="utf-8") as file:
manifest_data = yaml.safe_load(file) or {}
except (yaml.YAMLError, OSError) as err:
raise ManifestError(f"YAML parsing failed: {err}") from err
if not isinstance(manifest_data, dict):
raise ManifestError(f"Invalid manifest root: expected `dict`, got `{type(manifest_data).__name__}`")
return manifest_data
def sites_app_from_manifest(
app_dir: str,
manifest: dict[str, Any],
manifest_error: str | None = None
) -> SitesApp:
"""Construct and normalize a SitesApp domain model from raw manifest data."""
raw_dir_name = os.path.basename(app_dir)
canonical_name = str(manifest.get("name") or raw_dir_name.replace("homelab-", ""))
# Normalize aliases into list[str]
raw_aliases = manifest.get("aliases") or []
if isinstance(raw_aliases, str):
aliases = [raw_aliases]
elif isinstance(raw_aliases, list):
aliases = [str(alias) for alias in raw_aliases]
else:
aliases = []
# Homepage card normalization
homepage_config: HomepageConfig | None = None
raw_hp = manifest.get("homepage")
if isinstance(raw_hp, dict):
homepage_config = HomepageConfig(
title=str(raw_hp.get("title") or canonical_name),
group=str(raw_hp.get("group") or "Applications"),
icon=str(raw_hp.get("icon") or "default.png"),
container=str(raw_hp.get("container") or canonical_name),
weight=int(raw_hp.get("weight", 50))
)
has_compose = (
os.path.isfile(os.path.join(app_dir, "docker-compose.yaml")) or
os.path.isfile(os.path.join(app_dir, "docker-compose.yml"))
)
# Manifest Data parsing
raw_desc = manifest.get("description")
app_desc: str = str(raw_desc) if raw_desc is not None else ""
raw_dom = manifest.get("domain")
app_dom = str(raw_dom) if raw_dom is not None else f"{canonical_name}.{HOMELAB_DOMAIN}"
app_net = manifest.get("networks")
if not isinstance(app_net, list):
app_net = ["proxy-net"]
app_env = manifest.get("env")
if not isinstance(app_env, dict):
app_env = {}
def _as_bool(value: Any, default: bool) -> bool:
if isinstance(value, bool):
return value
return default
app_vis = _as_bool(manifest.get("visible"), True)
app_auth = _as_bool(manifest.get("auth"), True)
# Source provenance normalization
source_config: SourceConfig | None = None
raw_source = manifest.get("source")
if isinstance(raw_source, dict):
source_url = str(raw_source.get("url") or "")
allowed_schemes = ("https://", "ssh://", "git@")
if source_url:
if not any(source_url.startswith(s) for s in allowed_schemes):
err = f"Invalid source.url scheme: must start with {', '.join(allowed_schemes)}"
manifest_error = f"{manifest_error}; {err}" if manifest_error else err
else:
source_config = SourceConfig(
type=str(raw_source.get("type") or "git"),
url=source_url,
ref=str(raw_source.get("ref") or "main"),
)
return SitesApp(
name=canonical_name,
dir_name=raw_dir_name,
source=source_config,
description=app_desc,
domain=app_dom,
dir_path=app_dir,
has_compose=has_compose,
aliases=aliases,
visible=app_vis,
auth=app_auth,
networks=app_net,
env=app_env,
homepage=homepage_config,
manifest_error=manifest_error,
)
def get_sites_apps(sites_dir: str | None = None) -> list[SitesApp]:
"""
Scan the given sites directory (defaulting to SITES_DIR) for application.
"""
target_dir = sites_dir or SITES_DIR
apps: list[SitesApp] = []
if not os.path.isdir(target_dir):
return apps
for entry in sorted(os.listdir(target_dir)):
app_dir = os.path.join(target_dir, entry)
# skip hidden or null directories
if entry.startswith(".") or not os.path.isdir(app_dir):
continue
manifest_path = os.path.join(app_dir, "app.yaml")
manifest: dict[str, Any] = {}
manifest_error: str | None = None
if os.path.isfile(manifest_path):
try:
manifest = load_manifest(manifest_path=manifest_path)
except ManifestError as err:
manifest_error = str(err)
apps.append(sites_app_from_manifest(app_dir, manifest, manifest_error))
return apps
def resolve_app(
query: str,
apps: list[SitesApp] | None = None,
sites_dir: str | None = None
) -> SitesApp | None:
if apps is None:
apps = get_sites_apps(sites_dir= sites_dir if sites_dir is not None else SITES_DIR)
query_clean = query.strip().lower()
# 1. Extract match on canonical name
for app in apps:
if app.name.lower() == query_clean:
return app
# 2. Match on alias
for app in apps:
if any(alias.lower() == query_clean for alias in app.aliases):
return app
# 3. Match directory name
for app in apps:
if app.dir_name.lower() == query_clean:
return app
# 4. Match stripped 'homelab-' prefix
for app in apps:
if app.dir_name.lower() == f"homelab-{query_clean}":
return app
return None
def get_core_services(core_dir: str | None = None) -> list[CoreService]:
"""Return the strongly-typed registry of Core platform services."""
return [
CoreService(
name="traefik",
domain=f"traefik.{HOMELAB_DOMAIN}",
container="traefik",
description="Edge Reverse Proxy & ACME TLS",
icon="traefik.png",
weight=10,
),
CoreService(
name="authelia",
domain=f"auth.{HOMELAB_DOMAIN}",
container="authelia",
description="Identity & SSO Access Control",
icon="authelia.png",
weight=20,
),
CoreService(
name="lldap",
domain=f"users.{HOMELAB_DOMAIN}",
container="lldap",
description="Lightweight LDAP User Directory",
icon="lldap.png",
weight=25,
),
CoreService(
name="stalwart",
domain=f"smtp.{HOMELAB_DOMAIN}",
container="stalwart",
description="All-in-one Mail Server",
icon="email.png",
weight=26,
),
CoreService(
name="dozzle",
domain=f"logs.{HOMELAB_DOMAIN}",
container="dozzle",
description="Real-time Log Viewer",
icon="dozzle.png",
weight=40,
),
CoreService(
name="socket-proxy",
domain="internal",
container="socket-proxy",
description="Docker Socket Security Proxy",
),
CoreService(
name="homepage",
domain=f"dashboard.{HOMELAB_DOMAIN}",
container="homepage",
description="Application Dashboard & System Portal",
icon="homepage.png",
weight=5,
),
CoreService(
name="diun",
domain="internal",
container="diun",
description="Docker Image Update Notifier",
),
CoreService(
name="watchtower",
domain="internal",
container="watchtower",
description="Automated Container Updates",
),
]
def get_docker_status(
dir_path: str | Path,
container_name: str | None = None,
) -> str:
"""Get container running status for a docker-compose directory or single Core container."""
try:
if container_name:
inspect_res = subprocess.run(
["docker", "inspect", "-f", "{{.State.Running}}", container_name],
capture_output=True,
text=True,
check=False,
)
state = inspect_res.stdout.strip()
if state.lower() == "true":
return "🟢 Running (1)"
return "🔴 Stopped"
path = Path(dir_path)
if path.exists() and not (path / "docker-compose.yml").is_file() and not (path / "docker-compose.yaml").is_file():
return "⚪ Not Stack"
res = subprocess.run(
["docker", "compose", "ps", "-q"],
cwd=str(path),
capture_output=True,
text=True,
check=False,
)
container_ids = [c for c in res.stdout.strip().splitlines() if c]
if not container_ids:
return "🔴 Stopped"
inspect_res = subprocess.run(
["docker", "inspect", "-f", "{{.State.Running}}"] + container_ids,
capture_output=True,
text=True,
check=False,
)
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)
if running_count == total_count and total_count > 0:
return f"🟢 Running ({running_count})"
elif running_count > 0:
return f"🟡 Degraded ({running_count}/{total_count})"
else:
return "🔴 Stopped"
except (subprocess.SubprocessError, OSError):
return "❓ Unknown"
def get_docker_image_revision(
dir_path: str | Path | None = None,
container_name: str | None = None,
) -> str | None:
"""Extract `org.opencontainers.image.revision` label from running container."""
try:
target: str | None = container_name
if not target and dir_path:
res = subprocess.run(
["docker", "compose", "ps", "-q"],
cwd=str(dir_path),
capture_output=True,
text=True,
check=False,
)
ids = [c for c in res.stdout.strip().splitlines() if c]
if ids:
target = ids[0]
if not target:
return None
inspect_res = subprocess.run(
[
"docker",
"inspect",
"-f",
'{{ index .Config.Labels "org.opencontainers.image.revision" }}',
target,
],
capture_output=True,
text=True,
check=False,
)
revision = inspect_res.stdout.strip()
if revision and revision != "<no value>":
return revision
return None
except (subprocess.SubprocessError, OSError):
return None
def cmd_sync_homepage(args) -> None:
pass
if __name__ == "__main__":
main()
+2 -2
View File
@@ -652,7 +652,7 @@ def enqueue_deployment(
"deployment_config": deployment_config,
"branch": branch,
"commit_sha": commit_sha,
"queued_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"queued_at": datetime.datetime.now(datetime.UTC).isoformat(),
}
temp_file.write_text(json.dumps(data), encoding="utf-8")
@@ -706,7 +706,7 @@ def run_target_worker(target_name: str) -> bool:
"branch": branch,
"commit_sha": commit_sha,
"success": success,
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"timestamp": datetime.datetime.now(datetime.UTC).isoformat(),
}
status_file.write_text(json.dumps(status_data, indent=2), encoding="utf-8")
except OSError as e:
+330
View File
@@ -0,0 +1,330 @@
"""
provenance.py — Two-Axis Inspection & Upstream Provenance Resolver
Evaluates workload health along two independent axes:
1. Local Deployment Axis: Local checkout cleanliness (* Dirty vs. ✓ Clean), branch, commit, and container runtime state.
2. Upstream Provenance Axis: Upstream git repository state resolved via bounded `git ls-remote` (10s timeout).
"""
from __future__ import annotations
import os
import subprocess
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from core_manifest import Manifest, RefType, SourceConfig
class ProvenanceStatus(str, Enum):
"""Evaluation result of local state vs. upstream software provenance."""
SYNCED = "✓ Synced"
UPDATE_AVAILABLE = "↓ Update Available"
IMAGE_ONLY = "— Image-Only (Class B)"
DIRTY = "* Dirty"
UNREACHABLE = "⚠ Unreachable"
TIMEOUT = "⏱ Timed Out (10s)"
UNKNOWN = "— Not Checked"
NOT_CLONED = "✕ Missing Checkout"
@dataclass
class CheckoutStatus:
"""Axis 1: Local deployment checkout state."""
is_git: bool
is_dirty: bool
branch: str
commit_sha: str
status_label: str
def to_dict(self) -> dict[str, str | bool]:
return {
"is_git": self.is_git,
"is_dirty": self.is_dirty,
"branch": self.branch,
"commit_sha": self.commit_sha,
"status_label": self.status_label,
}
@dataclass
class UpstreamProvenance:
"""Axis 2: Upstream software provenance state."""
status: ProvenanceStatus
remote_sha: str = ""
target_ref: str = ""
message: str = ""
def to_dict(self) -> dict[str, str]:
return {
"status": self.status.value,
"remote_sha": self.remote_sha,
"target_ref": self.target_ref,
"message": self.message,
}
@dataclass
class TwoAxisStatus:
"""Unified inspection combining local deployment and upstream provenance."""
app_name: str
checkout: CheckoutStatus
provenance: UpstreamProvenance
docker_status: str
image_revision: str | None = None
def to_dict(self) -> dict[str, object]:
return {
"app_name": self.app_name,
"checkout": self.checkout.to_dict(),
"provenance": self.provenance.to_dict(),
"docker_status": self.docker_status,
"image_revision": self.image_revision,
}
def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
"""
Inspect local git repository checkout state.
Reports clean/dirty status, active branch/ref, and current commit SHA.
"""
path = Path(dir_path)
git_dir = path / ".git"
if not git_dir.exists():
return CheckoutStatus(
is_git=False,
is_dirty=False,
branch="",
commit_sha="",
status_label="— No Git Repo",
)
# Clean git environment so calls are not polluted by outer hooks
git_env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
# 1. Check cleanliness
is_dirty = False
try:
status_res = subprocess.run(
["git", "-C", str(path), "status", "--porcelain"],
capture_output=True,
text=True,
check=False,
timeout=5.0,
env=git_env,
)
if status_res.returncode == 0 and status_res.stdout.strip():
is_dirty = True
except (subprocess.SubprocessError, OSError):
is_dirty = False
# 2. Get active branch
branch = ""
try:
branch_res = subprocess.run(
["git", "-C", str(path), "rev-parse", "--abbrev-ref", "HEAD"],
capture_output=True,
text=True,
check=False,
timeout=5.0,
env=git_env,
)
if branch_res.returncode == 0:
branch = branch_res.stdout.strip()
if branch == "HEAD":
# Detached HEAD, check describe
desc_res = subprocess.run(
["git", "-C", str(path), "describe", "--tags", "--exact-match"],
capture_output=True,
text=True,
check=False,
timeout=5.0,
env=git_env,
)
if desc_res.returncode == 0 and desc_res.stdout.strip():
branch = desc_res.stdout.strip()
except (subprocess.SubprocessError, OSError):
branch = "unknown"
# 3. Get commit SHA
commit_sha = ""
try:
sha_res = subprocess.run(
["git", "-C", str(path), "rev-parse", "--short", "HEAD"],
capture_output=True,
text=True,
check=False,
timeout=5.0,
env=git_env,
)
if sha_res.returncode == 0:
commit_sha = sha_res.stdout.strip()
except (subprocess.SubprocessError, OSError):
commit_sha = ""
# 4. Format status label
state_symbol = "* Dirty" if is_dirty else "✓ Clean"
ref_desc = f"{branch}@{commit_sha}" if commit_sha else branch
status_label = f"{state_symbol} ({ref_desc})" if ref_desc else state_symbol
return CheckoutStatus(
is_git=True,
is_dirty=is_dirty,
branch=branch,
commit_sha=commit_sha,
status_label=status_label,
)
def resolve_upstream_provenance(
source: SourceConfig | None,
local_commit: str = "",
timeout: float = 10.0,
) -> UpstreamProvenance:
"""
Resolve upstream provenance via bounded `git ls-remote`.
Compares the declared upstream ref with the deployed local commit.
Bounded by a 10-second timeout to prevent hanging on unresponsive remotes.
"""
if source is None:
return UpstreamProvenance(
status=ProvenanceStatus.IMAGE_ONLY,
message="Class B workload deploys prebuilt container images directly",
)
target_ref = source.ref
remote_url = source.url
# Commits pinned directly in manifest cannot be checked via ls-remote ref matching
if source.ref_type == RefType.COMMIT:
is_match = (
local_commit and (
source.ref.startswith(local_commit) or local_commit.startswith(source.ref)
)
)
status = ProvenanceStatus.SYNCED if is_match else ProvenanceStatus.UPDATE_AVAILABLE
return UpstreamProvenance(
status=status,
remote_sha=source.ref,
target_ref=source.ref[:7],
message="Pinned immutable commit SHA",
)
cmd = ["git", "ls-remote", "--exit-code", remote_url, target_ref]
try:
proc = subprocess.run(
cmd,
capture_output=True,
text=True,
check=False,
timeout=timeout,
)
except subprocess.TimeoutExpired:
return UpstreamProvenance(
status=ProvenanceStatus.TIMEOUT,
target_ref=target_ref,
message=f"Upstream check timed out after {int(timeout)}s ({remote_url})",
)
except (subprocess.SubprocessError, OSError) as e:
return UpstreamProvenance(
status=ProvenanceStatus.UNREACHABLE,
target_ref=target_ref,
message=f"Network error querying upstream: {e}",
)
if proc.returncode != 0:
# Check if ref was not found on remote (exit code 2 for git ls-remote)
err_msg = proc.stderr.strip() or f"Ref '{target_ref}' not found on remote."
return UpstreamProvenance(
status=ProvenanceStatus.UNREACHABLE,
target_ref=target_ref,
message=f"Failed to query remote ({remote_url}): {err_msg}",
)
# Parse remote SHA from ls-remote output (Format: <SHA>\t<ref_name>)
remote_sha = ""
for line in proc.stdout.splitlines():
parts = line.strip().split()
if len(parts) >= 2 and (
parts[1] == target_ref or
parts[1] == f"refs/heads/{target_ref}" or
parts[1] == f"refs/tags/{target_ref}" or
parts[1] == f"refs/tags/{target_ref}^{{}}"
):
remote_sha = parts[0]
# Peaked tags (^{}) take precedence over lightweight tag refs
if parts[1].endswith("^{}"):
break
if not remote_sha and proc.stdout.strip():
# Fallback: take first match SHA
remote_sha = proc.stdout.strip().split()[0]
if not remote_sha:
return UpstreamProvenance(
status=ProvenanceStatus.UNREACHABLE,
target_ref=target_ref,
message=f"No matching ref found for '{target_ref}' at {remote_url}",
)
# Compare local commit with remote SHA
is_synced = False
if local_commit and (remote_sha.startswith(local_commit) or local_commit.startswith(remote_sha[:7])):
is_synced = True
status = ProvenanceStatus.SYNCED if is_synced else ProvenanceStatus.UPDATE_AVAILABLE
short_remote = remote_sha[:7]
msg = f"Upstream at {short_remote}" if not is_synced else "Up to date with upstream"
return UpstreamProvenance(
status=status,
remote_sha=remote_sha,
target_ref=target_ref,
message=msg,
)
def inspect_workload_two_axis(
app_dir: Path | str,
manifest: Manifest,
fetch_upstream: bool = False,
docker_status: str = "⚪ Not Stack",
image_revision: str | None = None,
timeout: float = 10.0,
) -> TwoAxisStatus:
"""
Perform two-axis status inspection of a single workload.
"""
path = Path(app_dir)
# Axis 1: Local Deployment Checkout
checkout = get_local_checkout_status(path)
# Axis 2: Upstream Provenance
if manifest.is_class_b:
provenance = UpstreamProvenance(
status=ProvenanceStatus.IMAGE_ONLY,
message="Class B (Image-Only)",
)
elif not fetch_upstream:
provenance = UpstreamProvenance(
status=ProvenanceStatus.UNKNOWN,
target_ref=manifest.source.ref if manifest.source else "",
message="Pass --fetch to query upstream repository",
)
else:
provenance = resolve_upstream_provenance(
manifest.source,
local_commit=checkout.commit_sha,
timeout=timeout,
)
return TwoAxisStatus(
app_name=manifest.name,
checkout=checkout,
provenance=provenance,
docker_status=docker_status,
image_revision=image_revision,
)
@@ -5,11 +5,11 @@ from unittest.mock import MagicMock
import pytest
# Import appctl engine v2
# Import appctl engine
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(CORE_ROOT / "scripts"))
import appctl_engine_v2 as engine
import appctl_engine as engine
@dataclass
@@ -291,7 +291,7 @@ def test_docker_image_revision_extraction(monkeypatch):
monkeypatch.setattr("subprocess.run", mock_run_empty)
assert engine.get_docker_image_revision("/fake/dir") is None
@pytest.mark.xfail(reason="TDD in progress: cmd_sync_homepage not yet implemented")
def test_homepage_sync_groups_and_sorts_correctly(
mock_core_dir: Path,
app_factory: AppFactory,
@@ -336,3 +336,29 @@ def test_homepage_sync_groups_and_sorts_correctly(
content = output_file.read_text()
assert content.find("- Group A") < content.find("- Group B") # Group A should appear before Group B
assert "App2" in content # App 2 is in the file
def test_homepage_sync_core_services_domain_isolation(
mock_core_dir: Path,
monkeypatch,
):
"""
Ensure Core Infrastructure services use HOMELAB_DOMAIN and do not leak
an application's domain if DOMAIN is overridden by appctl.
"""
hp_config_dir = mock_core_dir / "config" / "homepage"
hp_config_dir.mkdir(parents=True, exist_ok=True)
monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "roadtotech.me")
monkeypatch.setenv("DOMAIN", "mermaid.roadtotech.me")
engine.cmd_sync_homepage(["--homepage-dir=" + str(hp_config_dir)])
output_file = hp_config_dir / "services.yaml"
assert output_file.exists()
content = output_file.read_text()
assert "https://dashboard.roadtotech.me" in content
assert "https://traefik.roadtotech.me" in content
assert "https://auth.roadtotech.me" in content
assert "mermaid.roadtotech.me" not in content
+195
View File
@@ -0,0 +1,195 @@
"""
Unit test suite for scripts/provenance.py (Two-Axis Inspection & Provenance Resolver).
"""
import os
import subprocess
import sys
from pathlib import Path
from unittest.mock import MagicMock, patch
# Add scripts directory to path
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(CORE_ROOT / "scripts"))
from core_manifest import Manifest, RefType, SourceConfig, TransportScheme
from provenance import (
ProvenanceStatus,
get_local_checkout_status,
inspect_workload_two_axis,
resolve_upstream_provenance,
)
def _clean_git_env() -> dict[str, str]:
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
env["GIT_AUTHOR_NAME"] = "Test"
env["GIT_AUTHOR_EMAIL"] = "test@example.com"
env["GIT_COMMITTER_NAME"] = "Test"
env["GIT_COMMITTER_EMAIL"] = "test@example.com"
return env
def test_get_local_checkout_status_non_git(tmp_path: Path):
non_git = tmp_path / "app"
non_git.mkdir()
status = get_local_checkout_status(non_git)
assert status.is_git is False
assert status.is_dirty is False
assert "No Git Repo" in status.status_label
def test_get_local_checkout_status_clean_repo(tmp_path: Path):
app_dir = tmp_path / "git_app"
app_dir.mkdir()
env = _clean_git_env()
subprocess.run(["git", "-C", str(app_dir), "init", "-b", "main"], check=True, capture_output=True, env=env)
subprocess.run(["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], check=True, env=env)
subprocess.run(["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env)
(app_dir / "file.txt").write_text("hello", encoding="utf-8")
subprocess.run(["git", "-C", str(app_dir), "add", "file.txt"], check=True, env=env)
subprocess.run(["git", "-C", str(app_dir), "commit", "-m", "init"], check=True, capture_output=True, env=env)
status = get_local_checkout_status(app_dir)
assert status.is_git is True
assert status.is_dirty is False
assert status.branch == "main"
assert status.commit_sha != ""
assert "✓ Clean" in status.status_label
def test_get_local_checkout_status_dirty_repo(tmp_path: Path):
app_dir = tmp_path / "git_dirty_app"
app_dir.mkdir()
env = _clean_git_env()
subprocess.run(["git", "-C", str(app_dir), "init", "-b", "main"], check=True, capture_output=True, env=env)
subprocess.run(["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], check=True, env=env)
subprocess.run(["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env)
(app_dir / "file.txt").write_text("hello", encoding="utf-8")
subprocess.run(["git", "-C", str(app_dir), "add", "file.txt"], check=True, env=env)
subprocess.run(["git", "-C", str(app_dir), "commit", "-m", "init"], check=True, capture_output=True, env=env)
# Modify file to create dirty state
(app_dir / "file.txt").write_text("modified", encoding="utf-8")
status = get_local_checkout_status(app_dir)
assert status.is_git is True
assert status.is_dirty is True
assert "* Dirty" in status.status_label
def test_resolve_upstream_provenance_image_only():
prov = resolve_upstream_provenance(None)
assert prov.status == ProvenanceStatus.IMAGE_ONLY
def test_resolve_upstream_provenance_synced():
source = SourceConfig(
url="https://git.roadtotech.me/kiskaadee/app.git",
ref="main",
ref_type=RefType.BRANCH,
transport=TransportScheme.HTTPS,
)
mock_sha = "abc1234567890abcdef1234567890abcdef12345"
mock_output = f"{mock_sha}\trefs/heads/main\n"
with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=0, stdout=mock_output)
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
assert prov.status == ProvenanceStatus.SYNCED
assert prov.remote_sha == mock_sha
assert "Up to date" in prov.message
# Verify 10s timeout was passed to subprocess.run
assert mock_run.call_args[1]["timeout"] == 10.0
def test_resolve_upstream_provenance_update_available():
source = SourceConfig(
url="https://git.roadtotech.me/kiskaadee/app.git",
ref="main",
ref_type=RefType.BRANCH,
transport=TransportScheme.HTTPS,
)
mock_sha = "fff9999999990abcdef1234567890abcdef12345"
mock_output = f"{mock_sha}\trefs/heads/main\n"
with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=0, stdout=mock_output)
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
assert prov.status == ProvenanceStatus.UPDATE_AVAILABLE
assert prov.remote_sha == mock_sha
assert "Upstream at fff9999" in prov.message
def test_resolve_upstream_provenance_timeout():
source = SourceConfig(
url="https://slow-remote.test/repo.git",
ref="main",
ref_type=RefType.BRANCH,
transport=TransportScheme.HTTPS,
)
with patch("subprocess.run", side_effect=subprocess.TimeoutExpired(cmd=["git"], timeout=10.0)):
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
assert prov.status == ProvenanceStatus.TIMEOUT
assert "timed out after 10s" in prov.message
def test_resolve_upstream_provenance_unreachable():
source = SourceConfig(
url="https://bad-remote.test/repo.git",
ref="main",
ref_type=RefType.BRANCH,
transport=TransportScheme.HTTPS,
)
with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=128, stderr="fatal: remote error")
prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0)
assert prov.status == ProvenanceStatus.UNREACHABLE
assert "Failed to query remote" in prov.message
def test_resolve_upstream_provenance_pinned_commit():
sha = "1234567890abcdef1234567890abcdef12345678"
source = SourceConfig(
url="https://git.roadtotech.me/app.git",
ref=sha,
ref_type=RefType.COMMIT,
transport=TransportScheme.HTTPS,
)
# Matched local commit
prov = resolve_upstream_provenance(source, local_commit="1234567")
assert prov.status == ProvenanceStatus.SYNCED
# Differing local commit
prov_diff = resolve_upstream_provenance(source, local_commit="9999999")
assert prov_diff.status == ProvenanceStatus.UPDATE_AVAILABLE
def test_inspect_workload_two_axis(tmp_path: Path):
manifest = Manifest(
name="test-app",
source=SourceConfig(
url="https://git.test/app.git",
ref="main",
ref_type=RefType.BRANCH,
transport=TransportScheme.HTTPS,
),
)
# Without fetch_upstream: Axis 2 returns UNKNOWN
status_no_fetch = inspect_workload_two_axis(tmp_path, manifest, fetch_upstream=False)
assert status_no_fetch.provenance.status == ProvenanceStatus.UNKNOWN
assert "Pass --fetch" in status_no_fetch.provenance.message
# With fetch_upstream: Axis 2 queries remote
with patch("provenance.resolve_upstream_provenance") as mock_resolve:
mock_resolve.return_value = MagicMock(status=ProvenanceStatus.SYNCED)
status_fetch = inspect_workload_two_axis(tmp_path, manifest, fetch_upstream=True)
assert status_fetch.provenance.status == ProvenanceStatus.SYNCED
mock_resolve.assert_called_once()
+11 -5
View File
@@ -1,7 +1,13 @@
x 2026-10-13 (A) Create core_manifest.py schema and parser with strict transport validation (https, ssh, git) and ref classification in scripts/core_manifest.py +manifest @core
x 2026-10-13 (A) Implement unit tests for core_manifest.py covering valid manifests, invalid URLs, and ref types in tests/unit/test_core_manifest.py +test @core
(B) Implement two-axis inspection engine in appctl evaluating local checkout state independently from upstream provenance +provenance @appctl
(B) Implement bounded git ls-remote provenance resolver with 10s timeout for appctl status --fetch +provenance @appctl
(B) Add unit tests for provenance resolution and timeout handling with mocked network fixtures in tests/unit/test_provenance.py +test @appctl
(C) Promote scripts/appctl_engine_v2.py to authoritative scripts/appctl_engine.py +engine @appctl
(C) Verify full test suite and update CLI wrappers for appctl v2 engine promotion +test @appctl
x 2026-10-13 (B) Implement two-axis inspection engine in appctl evaluating local checkout state independently from upstream provenance +provenance @appctl
x 2026-10-13 (B) Implement bounded git ls-remote provenance resolver with 10s timeout for appctl status --fetch +provenance @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) 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
Generated
+7 -2
View File
@@ -1,3 +1,8 @@
version = 1
revision = 3
requires-python = ">=3.11"
revision = 5
requires-python = ">=3.13"
[[package]]
name = "homelab-core"
version = "0.1.0"
source = { virtual = "." }