Compare commits

..
6 Commits
Author SHA1 Message Date
kiskaadee 5d2aff3f90 merge(origin/main): sync mail topology realignment into refactor/appctl-rework
Core Architecture & Invariant CI / validate (push) Successful in 33s
2026-10-13 06:53:22 -05:00
kiskaadee 6836233c95 feat(nixos): sandbox homelab-gitops service and update roadmap for Milestone P2
- Apply systemd sandboxing to homelab-gitops service: ProtectSystem=strict, ProtectHome=read-only, NoNewPrivileges=true, PrivateTmp=true, and kernel tunables protection.
- Restrict filesystem write paths to ~/Sites and ~/.local/state/homelab.
- Explicitly set DOCKER_CONFIG to isolated state directory to avoid home directory pollution.
- Prune obsolete SnappyMail tmpfiles rule and ensure gitops state directories exist.
- Mark Milestone P2 as completed in ROADMAP.md and advance Milestone P3 to current up next.
2026-10-13 06:51:27 -05:00
kiskaadee 61627cdd5d feat(gitops): implement authoritative registry, compose AST validation, and evict brain vault
- Add config/deployments.yaml as the authoritative Core repository registry enforcing strict containment within ~/Sites.
- Add validate_compose_security() AST pre-flight validator in gitops_dispatcher to reject privileged: true, Docker socket mounts, host networking, and unauthorized host bind mounts.
- Evict BRAIN_DIR constants and special-case bypasses from GitOps dispatcher; decouple knowledge vault synchronization from continuous workload deployment.
- Update tests to verify vault rejection, registry containment enforcement, and compose security AST validation.
2026-10-13 06:49:39 -05:00
kiskaadee c549ada3b4 docs(roadmap): mark Milestone P1 as completed and P2 as current up next 2026-10-13 04:02:23 -05:00
kiskaadee 10468c4afa refactor(appctl): update stalwart domain to smtp and remove deprecated portainer
- Update Stalwart CoreService domain to smtp.${HOMELAB_DOMAIN} in preparation for mail topology realignment (Milestone P1).
- Prune deprecated Portainer CoreService entry from core service inventory.
2026-10-13 03:41:02 -05:00
kiskaadee 7ae03f2176 docs(architecture): realign repository documentation with control-plane baseline and roadmap v5
- Update root README.md with Appctl Core's identity, control-plane mental model, and explicit contrast between current implementation baseline and target architecture.
- Add root ROADMAP.md as repository-facing projection of Roadmap v5 (milestones P0–P7).
- Add docs/decisions/README.md as lightweight navigation index for governing ADRs.
- Add contextual implementation scope notes to docs/architecture.md and docs/appctl.md.
2026-10-08 00:03:56 -05:00
10 changed files with 691 additions and 118 deletions

No files matched your search

+112 -43
View File
@@ -1,41 +1,104 @@
# 🌐 Homelab Core — Appliance & Platform Reference
# 🏛️ Homelab Core & Appctl Operational Control Plane
**Homelab Core** is the declarative NixOS appliance and platform foundation for the `roadtotech.me` homelab cluster.
**Homelab Core** defines the host foundation, platform infrastructure services, security boundaries, and operational control plane for the `roadtotech.me` homelab appliance.
It provides host operating system configuration, edge routing, automated wildcard TLS certificate issuance, identity and access management, mail transport, container socket isolation, workload orchestration, and continuous GitOps deployment.
This repository serves two primary roles:
1. **The Host Platform & Infrastructure Appliance**: Declarative NixOS operating system definitions, edge ingress routing, wildcard TLS certificates, identity/SSO directory services, mail routing, and Docker socket isolation.
2. **The Appctl Operational Control Plane**: The centralized engine governing workload lifecycle management, continuous GitOps deployment, source provenance tracking, and dashboard synchronization across independent application workloads in `~/Sites`.
---
## 🏛️ System Architecture & Boundaries
## 🧭 Architectural Direction & Mental Model
The homelab ecosystem separates **ownership**, **runtime architecture**, and **cross-cutting orchestration**:
Under the approved architectural baseline ([`ADR: Homelab Operational Control Plane`](docs/decisions/README.md#homelab-operational-control-plane--deployment-model-architecture) and [`ADR: 3-Tier Architecture & Provenance`](docs/decisions/README.md#homelab-3-tier-architecture--deployment-provenance-model)), `appctl` is evolving from a local procedural CLI wrapper into the **authoritative operational control plane service for Homelab Core**.
### 1. Ownership: Core vs. Sites
* **Core (`~/Core`) owns platform mechanics**: System services, host firewall, edge ingress, security barriers, deployment serialization, and secret distribution.
* **Workload Plane (`~/Sites`) owns application intent**: Workloads are self-describing via `app.yaml` and independent `docker-compose.yml` configurations. Workloads declare application intent; Core executes deployment.
### 2. Runtime Architecture
The system operates across four runtime layers:
1. **Host Foundation**: Headless NixOS Linux, disk configuration, Docker daemon, systemd daemons, firewall rules, and in-memory secret files under `/run/secrets/`.
2. **Edge Gateway**: Traefik (v3.6) reverse proxy terminating wildcard TLS (`*.roadtotech.me`) via Dynu DNS-01 Let's Encrypt validation.
3. **Core Platform Services**: Central services in `docker-compose.yml` (Authelia SSO, LLDAP directory, Stalwart mail, SnappyMail, Homepage dashboard, Dozzle, Watchtower, Diun, and socket-proxy).
4. **Workload Plane**: Independent application stacks in `~/Sites` connected to the platform over the `proxy-net` Docker network.
### 3. Cross-Cutting Orchestration
* **`appctl` CLI & Engine**: Coordinates discovery, environment injection, container lifecycle actions, and Homepage compilation across workloads and Core.
* **GitOps Webhook Dispatcher**: Listens on port 9000 (`homelab-gitops.service`), validating incoming Git push webhooks and executing declared deployment actions.
---
## 🗺️ System Topology & Network Architecture
### The Core Architectural Spine
```text
Human Operator / Automation
│
┌───────────────────┴───────────────────┐
│ │
Operations UI CLI (Local & Remote)
│ │
└───────────────────┬───────────────────┘
│
appctl Control Plane API
(One Logical API across Transports)
│
┌────────────┴────────────┐
│ │
Unix Socket HTTP Listener
(Host Clients) (Remote/LAN Clients)
│ │
└────────────┬────────────┘
│
┌───────────────────────────┼───────────────────────────┐
│ │ │
Authentication Deployment Model Operations
& Authorization Plane Execution
│ │ │
Token Validation & ┌──────┴──────┐ Docker Compose
LLDAP Directory RBAC │ │ Traefik Routing
AI Investigation Human Host Secrets
│ Approval Reconciliation
▼ │
DeploymentProposal │
│ ▼
└─────▶ DeploymentModel
│
▼ (Committed to Git)
Deployment Repository
(Git Truth)
│
▼ (appctl validates & materializes)
Deployment Definition
(Sites app.yaml + compose)
│
▼
Runtime Reconciliation
```
### Core Architectural Invariants
* **Single Operational Truth**: Exactly one implementation of every operational action (`deploy`, `restart`, `inspect`, `sync`, `validate`) exists in the platform. Clients (local CLI, remote CLI, web UI, GitOps) invoke the exact same logical API contract.
* **Host Access Does Not Confer Authority**: Entering the server via SSH is merely host access; it does not grant Appctl privileges. **Every mutating operation requires an explicit, authenticated user-scoped token**, regardless of transport. Unix socket peer credentials identify the transport context, not user authority.
* **Git is the Authoritative Source of Deployment State**: Approved workload configurations are versioned in Git. `appctl` reconciles desired Git state into running containers, preserving immutable revision history, commit provenance, peer reviews, and atomic rollbacks (`git revert`).
* **Five-Stage Model Lifecycle (Intent vs. Implementation)**:
$$\text{Repository} \xrightarrow{\text{Investigation}} \text{Application Profile} \xrightarrow{\text{Proposal}} \text{DeploymentProposal} \xrightarrow{\text{Human Selection}} \text{DeploymentModel (Git)} \xrightarrow{\text{appctl Materialize}} \text{Deployment Definition} \xrightarrow{\text{Reconcile}} \text{Containers}$$
* `DeploymentModel`: The operator-selected, implementation-agnostic representation of intent (ports, domains, volumes, dependencies, secret references). Free of Compose syntax and Traefik label boilerplate.
* `Deployment Definition`: Concrete platform descriptors (`app.yaml` + `docker-compose.yml`) materialized and enforced by `appctl`.
* **AI Authoring Boundary**: AI agents act strictly as upstream proposal generators with **zero execution or mutation authority**. The AI analyzes repositories and drafts `DeploymentProposals`. After human approval into a `DeploymentModel`, the AI is completely out of the loop.
* **Secret Reference Invariant**: Deployment definitions contain secret references (`secretKeyRef`), never secret material. References are resolved at runtime through a defined `SecretProvider` interface. Host platform secrets remain declarative in `sops-nix`.
* **Clean State Root**: Mutable application data lives strictly under `~/var/lib/homelab/<app>/`, isolated from Git deployment repositories.
---
## 🔍 Current Implementation Baseline vs. Target Architecture
To maintain clarity during development, this repository explicitly separates what is **currently implemented** from what is **planned in the roadmap**:
| Architectural Area | Current Implementation Baseline (Milestone P0) | Target Architecture (Roadmap v5) |
| :--- | :--- | :--- |
| **`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. |
| **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`. |
| **Dashboard** | `appctl sync` statically compiles `config/homepage/services.yaml`. | Homepage consumes read-only live status from `appctl`; dedicated Operations UI client for interactive management. |
---
## 🗺️ System Topology & Runtime Layers
```text
Internet
│
▼
┌───────────────────────────────┐
│ Traefik Edge Proxy (:443) │
│ Wildcard TLS (*.roadtotech.me│
│ Wildcard TLS (*.roadtotech.me)│
└───────┬───────────────┬───────┘
│ │
Public Traffic │ │ ForwardAuth Protected
@@ -71,8 +134,7 @@ The system operates across four runtime layers:
| **`socket-proxy`** | Internal (`socket-net:2375`) | Read-only Docker API gateway barrier | Internal Only |
| **`lldap`** | `users.roadtotech.me` | LDAP directory & user database | Authelia Guard |
| **`authelia`** | `auth.roadtotech.me` | Single Sign-On (SSO) & ForwardAuth middleware | Public (Bypass) |
| **`stalwart`** | `mail.roadtotech.me` | Mail Server (SMTP/IMAP/JMAP/Sieve) | Native / LLDAP |
| **`snappymail`** | `webmail.roadtotech.me` | Webmail client connected to Stalwart | Native / Stalwart |
| **`stalwart`** | `mail.roadtotech.me` | Mail Server (SMTP/IMAP/JMAP/Sieve) *(Moving to smtp in P1)* | Native / LLDAP |
| **`homepage`** | `dashboard.roadtotech.me` | Service portal & system dashboard | Authelia Guard |
| **`dozzle`** | `logs.roadtotech.me` | Container log viewer (via socket-proxy) | Authelia Guard |
| **`watchtower`** | Internal | Automated container image updater | Internal Only |
@@ -80,7 +142,7 @@ The system operates across four runtime layers:
---
## ⚡ Quick Start & Operator Workflows
## ⚡ Quick Start & Operator Workflows (Current Baseline)
### Host & System Operations
```bash
@@ -96,9 +158,9 @@ systemctl status dynu-monitor.service # Smart DDNS IP monitor
systemctl status dynu-monitor.timer # DDNS timer (every 30m)
```
### Workload Management (`appctl`)
### Workload Management (`appctl` CLI)
```bash
# List all application stacks with container health and Git tracking status
# List all application stacks with container health, Git tracking, and provenance status
appctl list
# Fetch upstream changes across all repos and inspect with SSL certificates
@@ -122,33 +184,40 @@ appctl sync
### Testing & Verification
```bash
# Run the repository test suite (linting + pytest + nix flake check)
# Run the complete test suite (Ruff linter + Pytest invariants + Nix flake check)
./scripts/test
# Run Nix sandbox flake evaluation and checks
# Run pure Nix flake evaluation and checks
nix flake check
```
---
## 📚 Repository Documentation Index
## 📚 Documentation Navigation & Ownership
| Document | Description |
| Document | Ownership & Epistemic Role |
| :--- | :--- |
| [**Architecture Guide**](docs/architecture.md) | Details system layers, component roles, network isolation, and security controls. |
| [**Operator Runbook**](docs/operations.md) | Day-to-day administration, updates, maintenance, troubleshooting, and recovery procedures. |
| [**Appctl Reference**](docs/appctl.md) | CLI command reference and consumed `app.yaml` manifest fields. |
| [**GitOps Engine**](docs/gitops.md) | Webhook admission pipeline, HMAC authentication, lock serialization, and execution boundaries. |
| [**Secrets & State**](docs/secrets-and-state.md) | SOPS encryption, runtime secret projections, user directory management, and persistent storage. |
| [**Setup & Provisioning**](docs/setup_guide.md) | Procedures for provisioning a server host and onboarding workloads. |
| [**Security Policy**](SECURITY.md) | Security controls, container isolation policies, and threat model. |
| [**`ROADMAP.md`**](ROADMAP.md) | **Implementation Trajectory**: Phased milestones (P0 through P7), active status, and deliverables based on Roadmap v5. |
| [**ADR Index**](docs/decisions/README.md) | **Architectural Decisions**: Navigation index to authoritative ADRs governing the control plane and 3-tier provenance. |
| [**Architecture Reference**](docs/architecture.md) | **Runtime Architecture**: Deep-dive into runtime layers, network segmentation, and component boundaries. |
| [**Appctl Reference**](docs/appctl.md) | **Current CLI Implementation**: Command syntax, arguments, resolution rules, and `app.yaml` fields consumed today. |
| [**GitOps Engine**](docs/gitops.md) | **Current CD Implementation**: Webhook admission pipeline, HMAC verification, and lock serialization. |
| [**Secrets & State**](docs/secrets-and-state.md) | **Current Runtime Secrets**: SOPS encryption, tmpfs projections, and persistent state roots. |
| [**Operator Runbook**](docs/operations.md) | **Operational Runbook**: Host maintenance, updates, garbage collection, and recovery procedures. |
| [**Setup & Provisioning**](docs/setup_guide.md) | **Host Provisioning**: Bare-metal NixOS installation and platform bootstrapping. |
| [**Agent Guidelines**](AGENTS.md) | **Agent Invariants**: Hard rules, trust boundaries, Core/Sites boundaries, and testing rules. |
| [**Security Policy**](SECURITY.md) | **Security Controls**: Docker socket isolation, threat models, and hardening checklists. |
---
## 🧠 Relationship to Brain Vault
## 🧠 Governance & Knowledge Architecture
* **Repository Documentation (`~/Core/docs/`)**: Describes *what exists* and *how to operate it*. It serves as the operational manual for the current repository.
* **Brain Vault (`~/Brain/projects/homelab/`)**: Captures *why it was built this way* — preserving architectural decision records (ADRs), historical trade-off discussions, active roadmaps, and deep debugging discoveries.
Durable architectural decisions, exploratory design trade-offs, and master execution roadmaps are governed in the operator's central knowledge vault under standard epistemic taxonomy:
* **Architectural Decisions**: Captured in MADR 4.0 format under `03-records/decisions/`.
* **Execution Roadmaps**: Phased engineering blueprints under `01-plans/`.
* **System Discussions**: Exploratory trade-off analyses under `02-discussions/`.
The repository documentation reflects the accepted architectural state and serves as the operational guide for the implementation.
---
+139
View File
@@ -0,0 +1,139 @@
# 🗺️ Homelab Core & Appctl Engineering Roadmap
This document serves as the repository-facing projection of the authoritative **Homelab Architecture Consolidation & Control Plane Roadmap (v5)**.
It describes the implementation trajectory and phased engineering milestones for transitioning Homelab Core into a unified platform driven by the `appctl` Operational Control Plane.
> **Authoritative Master Roadmap**: `01-plans/homelab/consolidation/architecture-consolidation-roadmap-v5.md` in the central knowledge vault.
>
> **Governing Architectural Decisions**:
> - `homelab-appctl-control-plane-architecture.md` (Operational Control Plane & Deployment Model)
> - `homelab-3tier-architecture-and-provenance.md` (3-Tier Architecture & Provenance)
---
## 🎯 Architectural Invariants Governing Execution
1. **Git is the Authoritative Source of Deployment State**: All workload configurations are versioned in Git. `appctl` reconciles desired Git state into running containers.
2. **One Logical API Across Dual Transports**: The control-plane API is a single logical command-oriented contract. Unix domain socket (`/run/homelab/appctl.sock`) on the host and HTTP for network clients are transport details.
3. **Host Access Does Not Confer Authority**: Entering via SSH does not bypass authentication. Every mutating operation requires an explicit, authenticated user-scoped token.
4. **Separation of Intent from Implementation**: `DeploymentModel` captures implementation-agnostic intent; concrete platform descriptors (`app.yaml` + Compose) are materialized and enforced by `appctl`.
5. **AI Authoring Boundary**: AI agents act strictly as proposal generators (`DeploymentProposal`). Humans approve the intent (`DeploymentModel`). The AI possesses zero execution authority.
6. **Secret Reference Invariant**: Deployment definitions store secret references (`secretKeyRef`), never plaintext material, resolved at runtime via `SecretProvider`.
7. **Clean State Root**: Mutable application runtime data resides strictly under `~/var/lib/homelab/<app>/`, isolated from Git repositories.
---
## 📊 Milestone Overview
| Milestone | Title | Focus Area | Status | Deliverables Summary |
| :--- | :--- | :--- | :--- | :--- |
| **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. |
| **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. |
---
## 🛠️ Detailed Milestones
### Milestone P0: Baseline Consolidation
**Status**: ✅ **Completed**
* Merged `refactor/appctl-rework` and `main` into a unified architectural baseline (commit `2297cd5`).
* Modernized metadata engine (`scripts/appctl_engine_v2.py`) with strongly-typed dataclasses (`SitesApp`, `CoreService`, `SourceConfig`) and Docker status inspection.
* Formalized the control-plane ADR and Roadmap v5 in the central knowledge vault; marked legacy roadmaps as superseded.
* Verified test suite (47 tests passing) and NixOS flake sandbox evaluation.
---
### Milestone P1: Mail Topology Realignment & Zero-Data-Loss Migration
**Status**: ✅ **Completed**
* **Objective**: Segregate platform mail routing from user-facing webmail while preserving all user data and settings.
* **Key Deliverables**:
1. *State Freeze & Verified Snapshot*: Generate timestamped, SHA256-verified backup archive of `Core/config/snappymail/data`.
2. *Workload Provisioning*: Scaffold `~/Sites/snappymail/` (Class B Image-Only workload) and provision persistent state root at `~/var/lib/homelab/snappymail/`.
3. *Zero-Data-Loss State Replication*: Copy data using `cp -a` and prove byte parity (`diff -r`).
4. *Stalwart Re-homing*: Update Stalwart public endpoint in `Core/docker-compose.yml` to `smtp.roadtotech.me`; remove SnappyMail from Core stack.
5. *Live Verification*: Verify webmail at `mail.roadtotech.me`, user logins, address books, IMAP/SMTP routing, and Diun SMTPS delivery on port 465.
* **Exit Criteria**: 100% of user data survives cutover; mail flow and Diun alert delivery confirmed.
---
### Milestone P2: GitOps Privilege & Authority Hardening
**Status**: ✅ **Completed**
* **Objective**: Close remaining trust boundaries in the webhook continuous deployment engine.
* **Key Deliverables**:
1. *Authoritative Core Registry*: Establish `Core/config/deployments.yaml` as the sole authority for admitted deployment repositories.
2. *Decouple Data Vault from Workload GitOps*: Evict vault special-casing (`BRAIN_DIR`) from GitOps engine; continuous deployment strictly manages Sites container workloads.
3. *Compose AST Security Validator*: Pre-flight parser rejecting `privileged: true`, Docker socket bind mounts, host networking, and host mounts outside workload root or state root.
4. *Systemd Sandboxing*: Apply `ProtectSystem=strict`, `ProtectHome=read-only`, `ReadWritePaths`, `NoNewPrivileges=true`, and private temporary directories to `homelab-gitops.service`.
* **Exit Criteria**: Path traversal rejection tests pass; Compose AST security validator rejects prohibited capabilities.
---
### Milestone P3: Manifest Contract Convergence & Provenance Engine
**Status**: 🎯 **Current / Up Next**
* **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).
2. *Two-Axis Inspection*: Local deployment checkout state (`✓ Synced`, `* Dirty`) evaluated independently of upstream software provenance (resolved via `git ls-remote` bounded by a 10s timeout during `--fetch`).
3. *Engine Promotion*: Promote `scripts/appctl_engine_v2.py` to `scripts/appctl_engine.py` with complete behavioral test coverage.
* **Exit Criteria**: Manifest validation active in CI; all provenance resolution tests passing.
---
### Milestone P4: Appctl Control Plane Daemon & Command-Oriented API
**Status**: ⏳ **Planned**
* **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.
2. *Command-Oriented Operational Router*: Strongly-typed endpoints (`POST /operations/deploy`, `POST /operations/restart`, `POST /operations/pull`, `GET /workloads`, `GET /workloads/{id}/status`, `POST /operations/sync`).
3. *Thin-Client CLI*: Re-implement `scripts/appctl` as a lightweight dispatch client communicating with the local daemon socket.
4. *Append-Only Audit Log*: Record every mutating command to `~/.local/state/homelab/appctl/audit.jsonl` with restricted `0600` permissions. Telemetry captures `principal`, `action`, `target`, `transport`, `origin`, `client`, `timestamp`, and `result`.
* **Exit Criteria**: Hermetic API test suite passing; local socket and HTTP transport tests passing; audit log correctly capturing multi-dimensional telemetry.
---
### Milestone P5: Identity, RBAC & SecretProvider Interface
**Status**: ⏳ **Planned**
* **Objective**: Implement least-privilege identity boundaries and dynamic secret projection.
* **Key Deliverables**:
1. *Authentication Gateway*: Accept trusted identity headers from Traefik/Authelia (`Remote-User`, `Remote-Groups`) for web requests; validate explicit user-scoped API tokens for all CLI requests (local and remote); validate HMAC signatures for GitOps webhooks.
2. *Role-Based Authorization Engine*: Enforce group-based access control (`homelab-admin`, `homelab-operator`, `homelab-viewer`).
3. *SecretProvider Interface*: Control plane resolves secret references (`secretKeyRef`) at container runtime, eliminating Git history pollution for workload credentials.
* **Exit Criteria**: RBAC permission matrix verified by automated tests; secret references correctly materialized into runtime environments.
---
### Milestone P6: Homelab Deployment Model & AI Authoring Workflow
**Status**: ⏳ **Planned**
* **Objective**: Enable safe, human-reviewed workload authoring from upstream repositories.
* **Key Deliverables**:
1. *Platform Capability Catalog*: Machine-readable specification of Core capabilities and security invariants.
2. *DeploymentProposal Schema*: Candidate model format produced by AI discovery workflows.
3. *DeploymentModel Git Pipeline*: Operator approves proposal into a `DeploymentModel`; the model is committed to the version-controlled deployment repository (Git).
4. *Materialization & Reconciliation*: `appctl` validates the committed model, provisions state roots, compiles platform descriptors (`app.yaml` + Compose), and reconciles running containers.
* **Exit Criteria**: Human approval gate strictly enforced; AI possesses zero execution authority; generated workloads conform to all Core invariants.
---
### Milestone P7: Operations UI & Dashboard Integration
**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.
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.
---
## 🔒 Verification & Quality Gates
Progress across milestones is governed by explicit verification criteria:
* **Behavioral Invariant Coverage**: All defined domain, authorization, deployment, and security invariants must have automated regression tests.
* **Pre-Merge Validation**: Every commit must pass `./scripts/test` (Ruff linter + Pytest suite + Nix flake check).
* **Zero Production Regressions**: Platform migrations must include verified pre-flight snapshots, state parity proofs, and documented rollback runbooks.
+53
View File
@@ -0,0 +1,53 @@
# Core Authoritative Repository Identity Registry
# Governs admitted continuous deployment targets for GitOps webhook execution.
# Owns: repository identity, canonical filesystem path, and aliases.
# Enforces: strict path containment within ~/Sites.
schemaVersion: "1.0"
repositories:
snappymail:
path: "/home/kiskaadee/Sites/snappymail"
aliases:
- "homelab-snappymail"
- "mail"
- "webmail"
gitea:
path: "/home/kiskaadee/Sites/homelab-gitea"
aliases:
- "homelab-gitea"
- "git"
jellyfin:
path: "/home/kiskaadee/Sites/homelab-jellyfin"
aliases:
- "homelab-jellyfin"
- "media"
docs:
path: "/home/kiskaadee/Sites/homelab-doc2site"
aliases:
- "doc2site"
- "homelab-doc2site"
courses:
path: "/home/kiskaadee/Sites/courses"
aliases:
- "homelab-courses"
bdinvite:
path: "/home/kiskaadee/Sites/homelab-bdinvite"
aliases:
- "homelab-bdinvite"
- "birthday"
landing:
path: "/home/kiskaadee/Sites/homelab-landing"
aliases:
- "homelab-landing"
mermaid:
path: "/home/kiskaadee/Sites/homelab-mermaid"
aliases:
- "homelab-mermaid"
excalidraw:
path: "/home/kiskaadee/Sites/homelab-excalidraw"
aliases:
- "homelab-excalidraw"
houston:
path: "/home/kiskaadee/Sites/homelab-houston"
aliases:
- "homelab-houston"
+4
View File
@@ -2,6 +2,10 @@
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.
> 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. How `appctl` Works
+5 -1
View File
@@ -2,6 +2,10 @@
This document details the architectural structure, component roles, networking models, and security controls of the **Homelab Core** platform for `roadtotech.me`.
> [!NOTE]
> **Implementation Scope**: This document details the **current runtime architecture**, edge routing, container topologies, and network isolation models of Homelab Core.
> For the overarching control-plane architecture, 5-stage deployment model lifecycle, and phased engineering milestones, see [`README.md`](../README.md), [`ROADMAP.md`](../ROADMAP.md), and the [Architecture Decision Index](decisions/README.md).
---
## 1. System Structure: Ownership vs. Runtime Layers vs. Orchestration
@@ -46,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`)**: Slices across the Host Foundation (sourcing secrets from `/run/secrets/`), Workload Plane (parsing `~/Sites/*/app.yaml` and driving Docker Compose), and Platform Services (recompiling `config/homepage/services.yaml`).
* **`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`).
* **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.
---
+61
View File
@@ -0,0 +1,61 @@
# 🏛️ Homelab Core & Appctl Architecture Decision Index
This document serves as the repository-facing index for Architectural Decision Records (ADRs) governing **Homelab Core** and the **`appctl` Operational Control Plane**.
In accordance with platform governance, authoritative ADRs are maintained in the central knowledge vault (`03-records/decisions/`) using the MADR 4.0 specification. This index provides navigation, context, and one-line summaries without duplicating architectural specifications or creating competing sources of truth.
---
## 📋 Active Architectural Decisions
| Decision Record | Status | Date | Scope & One-Line Purpose |
| :--- | :--- | :--- | :--- |
| [**Homelab Operational Control Plane & Deployment Model Architecture**](#homelab-operational-control-plane--deployment-model-architecture) | `accepted` | 2026-10-07 | Establishes `appctl` as the central operational control plane daemon, one logical API across dual transports (Unix socket and HTTP), explicit token authentication on host, Git as authoritative deployment state, the 5-stage model lifecycle, AI proposal boundaries, and append-only audit telemetry. |
| [**Homelab 3-Tier Architecture & Deployment Provenance Model**](#homelab-3-tier-architecture--deployment-provenance-model) | `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. |
---
## 🧭 Summaries of Governing Decisions
### Homelab Operational Control Plane & Deployment Model Architecture
* **Canonical Document**: `03-records/decisions/homelab-appctl-control-plane-architecture.md`
* **Status**: `accepted` (Active)
* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v5)
* **Core Commitments**:
1. **Control Plane Daemon**: `appctl` transitions from a collection of local shell scripts into the authoritative platform service (`homelab-appctl.service`).
2. **One Logical API Across Dual Transports**: Command-oriented operations exposed over a Unix domain socket (`/run/homelab/appctl.sock`) on host and an HTTP listener for network clients.
3. **Explicit Token Authentication Everywhere**: Host SSH access does not confer appctl authority; every mutating operation requires an explicit, authenticated user-scoped token.
4. **Git as Authoritative Deployment State**: Approved `DeploymentModels` are committed to Git. `appctl` acts as the reconciliation engine, validating the model, materializing platform descriptors (`app.yaml` + Compose), and reconciling running containers.
5. **Five-Stage Deployment Model Lifecycle**: Separates factual `ApplicationProfile`, candidate `DeploymentProposal`, validated `DeploymentModel` (in Git), materialized `Deployment Definition`, and runtime `Reconciliation`.
6. **AI Proposal Boundary**: AI agents act strictly as proposal generators with zero mutation or execution authority. After human approval into a `DeploymentModel`, the AI is completely out of the loop.
7. **Secret Reference Invariant**: Manifests contain secret references (`secretKeyRef`), never secret material, resolved at runtime via `SecretProvider`.
8. **Append-Only Audit Log**: Audit entries capture `principal`, `action`, `target`, `transport`, `origin`, `client`, `timestamp`, and `result`.
---
### Homelab 3-Tier Architecture & Deployment Provenance Model
* **Canonical Document**: `03-records/decisions/homelab-3tier-architecture-and-provenance.md`
* **Status**: `accepted` (Active)
* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Roadmap v5)
* **Core Commitments**:
1. **3-Tier Separation of Concerns**:
* *Tier 1 (Software Layer)*: Upstream application repositories owning code, tests, and CI. Zero Homelab infrastructure coupling.
* *Intermediate Provenance Artifact*: OCI container images produced by CI carrying commit provenance in metadata labels and content-addressed digests.
* *Tier 2 (Sites Deployment Layer)*: Declarative manifests (`app.yaml`) and Compose specs in `~/Sites`.
* *Tier 3 (Platform Core Appliance)*: NixOS host foundation, edge routing, SSO, and operational controllers.
2. **Two Workload Deployment Classes**:
* *Class A (Source-Backed)*: Declares upstream Git source and ref (`source.url`, `source.ref`); tracks upstream Git revisions against container labels.
* *Class B (Image-Only)*: Standard third-party tools; tracks container registry image tags and digests.
3. **Isolated Persistent State Root**: Mutable data lives strictly under `~/var/lib/homelab/<app>/`, isolated from Git repositories.
4. **Two Operational Inspection Axes**: Local deployment checkout state evaluated independently of upstream software provenance (resolved via `git ls-remote`).
---
## 📜 Superseded Historical Decisions & Lineage
The following historical plans and design iterations have been formally superseded by the active ADRs and Roadmap v5:
* **Roadmap v4 & v3** (`architecture-consolidation-roadmap-v4.md`): Superseded by Roadmap v5.
* **appctl-v2 Modernization Plan** (`appctl-engine-v2-refactoring.md`): Scaffolded and absorbed into Roadmap v5 Phases P0 and P3.
* **Smart Selective Deployment Pipeline Plan** (`smart-deployment-pipeline.md`): Absorbed into Roadmap v5 Phase P4 control-plane reconciliation.
* **Architecture Implementation Guide v3** (`architecture-consolidation-implementation-guide-v3.md`): Superseded by Roadmap v5.
+18 -2
View File
@@ -70,11 +70,13 @@
environment = {
GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path;
DOCKER_CONFIG = "/home/kiskaadee/.local/state/homelab/docker";
};
serviceConfig = {
Type = "simple";
User = "kiskaadee";
SupplementaryGroups = [ "docker" ];
WorkingDirectory = "/home/kiskaadee/Core";
ExecStart = "${pkgs.webhook}/bin/webhook -hooks ${pkgs.writeText "hooks.json" (builtins.toJSON [
{
@@ -91,14 +93,28 @@
])} -port 9000 -verbose";
Restart = "on-failure";
RestartSec = "5s";
# Privilege separation & Systemd sandboxing
NoNewPrivileges = true;
PrivateTmp = true;
ProtectSystem = "strict";
ProtectHome = "read-only";
ProtectKernelTunables = true;
ProtectControlGroups = true;
ReadWritePaths = [
"/home/kiskaadee/Sites"
"/home/kiskaadee/.local/state/homelab"
];
};
};
# Ensure persistent directories have proper permissions for container runtimes (e.g. Stalwart UID 2000, SnappyMail)
# Ensure persistent directories have proper permissions for container runtimes
systemd.tmpfiles.rules = [
"d /home/kiskaadee/Core/config/stalwart/data 0777 kiskaadee users -"
"d /home/kiskaadee/Core/config/stalwart/etc 0777 kiskaadee users -"
"d /home/kiskaadee/Core/config/snappymail/data 0777 kiskaadee users -"
"d /home/kiskaadee/Sites 0755 kiskaadee users -"
"d /home/kiskaadee/.local/state/homelab/gitops 0755 kiskaadee users -"
"d /home/kiskaadee/.local/state/homelab/docker 0755 kiskaadee users -"
];
# Open ports in the firewall for Traefik, Gitea SSH, GitOps Webhook Receiver, and Mail (SMTP, Submission, SMTPS, IMAPS, ManageSieve)
+1 -9
View File
@@ -308,21 +308,13 @@ def get_core_services(core_dir: str | None = None) -> list[CoreService]:
),
CoreService(
name="stalwart",
domain=f"mail.{HOMELAB_DOMAIN}",
domain=f"smtp.{HOMELAB_DOMAIN}",
container="stalwart",
description="All-in-one Mail Server",
icon="email.png",
weight=26,
),
CoreService(
name="portainer",
domain=f"portainer.{HOMELAB_DOMAIN}",
container="portainer",
description="Container Management GUI",
icon="portainer.png",
weight=30,
),
CoreService(
name="dozzle",
domain=f"logs.{HOMELAB_DOMAIN}",
+153 -56
View File
@@ -20,9 +20,15 @@ import subprocess
import sys
from pathlib import Path
try:
import yaml
except ImportError:
yaml = None
SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites")))
BRAIN_DIR = Path(os.environ.get("BRAIN_DIR", os.path.expanduser("~/Brain")))
CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent))
CONFIG_DIR = Path(os.environ.get("HOMELAB_CONFIG_DIR", os.path.expanduser("~/.config/homelab")))
DEPLOYMENTS_FILE = Path(os.environ.get("HOMELAB_DEPLOYMENTS_FILE", CORE_DIR / "config" / "deployments.yaml"))
DEFAULT_SECRET_PATH = Path(os.environ.get("GITOPS_SECRET_FILE", "/run/secrets/gitops/webhook_secret"))
STATE_DIR = Path(os.environ.get("GITOPS_STATE_DIR", Path.home() / ".local/state/homelab/gitops"))
@@ -150,16 +156,41 @@ def get_trusted_repository_mapping() -> dict[str, Path]:
"""
Build authoritative mapping of logical repository identities to local paths.
Webhook payloads can only select repositories defined in this mapping.
Prioritizes Core Authoritative Registry (deployments.yaml) over dynamic discovery.
"""
mapping: dict[str, Path] = {}
# 1. Authoritative Data Vaults
if BRAIN_DIR.is_dir():
brain_canonical = BRAIN_DIR.resolve()
for alias in ["second-brain", "Brain", "brain"]:
mapping[alias] = brain_canonical
# 1. Authoritative Core Repository Registry (deployments.yaml)
registry_file = DEPLOYMENTS_FILE if DEPLOYMENTS_FILE.is_file() else (CONFIG_DIR / "deployments.yaml")
if registry_file.is_file():
try:
content = registry_file.read_text(encoding="utf-8")
registry = (yaml.safe_load(content) if yaml else parse_yaml_simple(content)) or {}
repo_entries = registry.get("repositories", registry) if isinstance(registry, dict) else {}
if isinstance(repo_entries, dict):
for reg_name, entry in repo_entries.items():
if not isinstance(entry, dict):
continue
raw_path = entry.get("path")
if not raw_path:
continue
p = Path(raw_path).expanduser().resolve()
# Enforce strict containment strictly inside SITES_DIR
if SITES_DIR.is_dir() and p.is_relative_to(SITES_DIR.resolve()):
mapping[reg_name] = p
raw_aliases = entry.get("aliases", [])
if isinstance(raw_aliases, str):
raw_aliases = [raw_aliases]
if isinstance(raw_aliases, list):
for alias in raw_aliases:
if isinstance(alias, str) and alias.strip():
mapping[alias.strip()] = p
else:
logger.warning(f"Rejecting out-of-bounds path in deployments.yaml for '{reg_name}': {p}")
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
logger.warning(f"Failed to parse authoritative registry {registry_file}: {e}")
# 2. Workload Plane Applications in SITES_DIR
# 2. Dynamic Discovery in SITES_DIR (for workloads not explicitly registered)
if SITES_DIR.is_dir():
sites_canonical = SITES_DIR.resolve()
for entry in SITES_DIR.iterdir():
@@ -176,55 +207,36 @@ def get_trusted_repository_mapping() -> dict[str, Path]:
if not manifest_file.is_file():
continue
# Register entry directory name
# Register entry directory name if not already mapped
dir_name = entry.name
if dir_name not in mapping:
mapping[dir_name] = resolved_entry
# Parse app.yaml for canonical name and aliases
manifest = {}
try:
manifest = parse_yaml_simple(manifest_file.read_text(encoding="utf-8"))
manifest_text = manifest_file.read_text(encoding="utf-8")
manifest = (yaml.safe_load(manifest_text) if yaml else parse_yaml_simple(manifest_text)) or {}
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
logger.warning(f"Failed to parse {manifest_file}: {e}")
canonical_name = manifest.get("name")
if canonical_name and isinstance(canonical_name, str):
canonical_name = canonical_name.strip()
if canonical_name not in mapping:
mapping[canonical_name] = resolved_entry
if not canonical_name.startswith("homelab-"):
mapping[f"homelab-{canonical_name}"] = resolved_entry
else:
mapping[canonical_name.replace("homelab-", "", 1)] = resolved_entry
alias_with_prefix = f"homelab-{canonical_name}" if not canonical_name.startswith("homelab-") else canonical_name.replace("homelab-", "", 1)
if alias_with_prefix not in mapping:
mapping[alias_with_prefix] = resolved_entry
aliases = manifest.get("aliases", [])
if isinstance(aliases, str):
aliases = [aliases]
if isinstance(aliases, list):
for alias in aliases:
if isinstance(alias, str) and alias.strip():
if isinstance(alias, str) and alias.strip() and alias.strip() not in mapping:
mapping[alias.strip()] = resolved_entry
# 3. Optional local override registry with strict containment
registry_file = CONFIG_DIR / "deployments.yaml"
if registry_file.is_file():
try:
registry = parse_yaml_simple(registry_file.read_text(encoding="utf-8"))
for reg_name, entry in registry.items():
if not isinstance(entry, dict):
continue
raw_path = entry.get("path")
if not raw_path:
continue
p = Path(raw_path).resolve()
# Must be strictly relative to SITES_DIR or BRAIN_DIR
if (SITES_DIR.is_dir() and p.is_relative_to(SITES_DIR.resolve())) or \
(BRAIN_DIR.is_dir() and p.is_relative_to(BRAIN_DIR.resolve())):
mapping[reg_name] = p
else:
logger.warning(f"Rejecting out-of-bounds path in deployments.yaml for '{reg_name}': {p}")
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
logger.warning(f"Failed to parse custom registry {registry_file}: {e}")
return mapping
@@ -262,13 +274,9 @@ def resolve_repository(repo_name: str) -> Path | None:
logger.warning(f"Trusted repository target '{canonical_target}' does not exist or is not a directory.")
return None
# Defense-in-depth: check allowed root containment
allowed = False
if SITES_DIR.is_dir() and canonical_target.is_relative_to(SITES_DIR.resolve()) or BRAIN_DIR.is_dir() and canonical_target.is_relative_to(BRAIN_DIR.resolve()):
allowed = True
if not allowed:
logger.warning(f"Resolved path '{canonical_target}' escapes allowed roots for repository '{cleaned_name}'.")
# Defense-in-depth: check allowed root containment strictly within SITES_DIR
if not (SITES_DIR.is_dir() and canonical_target.is_relative_to(SITES_DIR.resolve())):
logger.warning(f"Resolved path '{canonical_target}' escapes allowed SITES_DIR root for repository '{cleaned_name}'.")
return None
return canonical_target
@@ -283,18 +291,12 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]:
if not target_dir:
return None, {}
# Data vault default deployment config
if BRAIN_DIR.is_dir() and target_dir == BRAIN_DIR.resolve():
return target_dir, {
"branch": "main",
"actions": ["git_pull"]
}
manifest_file = target_dir / "app.yaml"
manifest = {}
if manifest_file.is_file():
try:
manifest = parse_yaml_simple(manifest_file.read_text(encoding="utf-8"))
manifest_text = manifest_file.read_text(encoding="utf-8")
manifest = (yaml.safe_load(manifest_text) if yaml else parse_yaml_simple(manifest_text)) or {}
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
logger.warning(f"Failed to parse {manifest_file}: {e}")
@@ -312,6 +314,85 @@ ALLOWED_ACTIONS = {"git_pull", "compose_up", "compose_build", "compose_restart"}
ALLOWED_STRATEGIES = {"compose"}
def validate_compose_security(compose_file: Path, allowed_root: Path) -> tuple[bool, str | None]:
"""
Pre-flight AST inspection of workload docker-compose.yml to reject security violations:
1. privileged: true
2. /var/run/docker.sock bind mounts
3. network_mode: host
4. host root bind mounts outside allowed state root or workload directory
"""
if not compose_file.is_file():
return True, None
try:
content = compose_file.read_text(encoding="utf-8")
except OSError as e:
return False, f"Failed to read compose file {compose_file}: {e}"
if yaml is not None:
try:
data = yaml.safe_load(content) or {}
except yaml.YAMLError as e:
return False, f"Failed to parse compose YAML {compose_file}: {e}"
else:
# Fallback regex inspection if yaml module is not present
if re.search(r"^\s*privileged:\s*true\b", content, re.MULTILINE | re.IGNORECASE):
return False, "Privileged mode is prohibited in workload compose files."
if "/var/run/docker.sock" in content:
return False, "Docker socket mounts are prohibited in workload compose files."
if re.search(r"^\s*network_mode:\s*[\"']?host[\"']?", content, re.MULTILINE | re.IGNORECASE):
return False, "Host networking (network_mode: host) is prohibited in workload compose files."
return True, None
if not isinstance(data, dict):
return False, f"Invalid compose root in {compose_file}: expected mapping"
services = data.get("services")
if not isinstance(services, dict):
return True, None
state_root = Path(os.environ.get("HOMELAB_STATE_ROOT", Path.home() / "var/lib/homelab")).resolve()
for svc_name, svc in services.items():
if not isinstance(svc, dict):
continue
if svc.get("privileged") is True:
return False, f"Service '{svc_name}' specifies prohibited 'privileged: true'."
net_mode = str(svc.get("network_mode", "")).strip().lower()
if net_mode == "host":
return False, f"Service '{svc_name}' specifies prohibited 'network_mode: host'."
volumes = svc.get("volumes", [])
if isinstance(volumes, list):
for vol in volumes:
host_path = ""
if isinstance(vol, str):
if "/var/run/docker.sock" in vol:
return False, f"Service '{svc_name}' directly mounts Docker socket: {vol}."
if ":" in vol:
host_path = vol.split(":")[0].strip()
elif isinstance(vol, dict):
src = str(vol.get("source", ""))
if "/var/run/docker.sock" in src:
return False, f"Service '{svc_name}' directly mounts Docker socket: {src}."
if vol.get("type") == "bind":
host_path = src
# Evaluate host_path escapes
if host_path and host_path.startswith(("/", "~")):
expanded = Path(host_path).expanduser().resolve()
# Allowed if inside the workload directory or inside the state root
is_in_workload = allowed_root.is_dir() and expanded.is_relative_to(allowed_root.resolve())
is_in_state = state_root.is_dir() and expanded.is_relative_to(state_root)
if not (is_in_workload or is_in_state):
return False, f"Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'."
return True, None
def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]:
"""
Validate deployment policy inside app.yaml.
@@ -370,11 +451,11 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
# Revision-consistent manifest validation:
# The working tree has now advanced to the deployed revision.
# Re-read and re-validate app.yaml from the exact deployed revision.
if not (BRAIN_DIR.is_dir() and target_dir == BRAIN_DIR.resolve()):
manifest_file = target_dir / "app.yaml"
if manifest_file.is_file():
try:
fresh_manifest = parse_yaml_simple(manifest_file.read_text(encoding="utf-8"))
manifest_text = manifest_file.read_text(encoding="utf-8")
fresh_manifest = (yaml.safe_load(manifest_text) if yaml else parse_yaml_simple(manifest_text)) or {}
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
logger.error(f"❌ Post-pull manifest parse failure in {manifest_file}: {e}")
return False
@@ -400,7 +481,13 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
continue
elif action == "compose_up":
compose_file = target_dir / "docker-compose.yml"
if not compose_file.is_file():
compose_file = target_dir / "docker-compose.yaml"
if compose_file.is_file():
valid_sec, sec_err = validate_compose_security(compose_file, target_dir)
if not valid_sec:
logger.error(f"❌ Compose security validation failed for '{target_dir.name}': {sec_err}")
return False
logger.info(" ↳ [compose_up] Recreating containers (docker compose up -d)...")
subprocess.run(
["docker", "compose", "-f", str(compose_file), "up", "-d", "--remove-orphans"],
@@ -408,7 +495,13 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
)
elif action == "compose_build":
compose_file = target_dir / "docker-compose.yml"
if not compose_file.is_file():
compose_file = target_dir / "docker-compose.yaml"
if compose_file.is_file():
valid_sec, sec_err = validate_compose_security(compose_file, target_dir)
if not valid_sec:
logger.error(f"❌ Compose security validation failed for '{target_dir.name}': {sec_err}")
return False
logger.info(" ↳ [compose_build] Building & recreating containers...")
subprocess.run(
["docker", "compose", "-f", str(compose_file), "build"],
@@ -420,7 +513,13 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
)
elif action == "compose_restart":
compose_file = target_dir / "docker-compose.yml"
if not compose_file.is_file():
compose_file = target_dir / "docker-compose.yaml"
if compose_file.is_file():
valid_sec, sec_err = validate_compose_security(compose_file, target_dir)
if not valid_sec:
logger.error(f"❌ Compose security validation failed for '{target_dir.name}': {sec_err}")
return False
logger.info(" ↳ [compose_restart] Restarting containers...")
subprocess.run(
["docker", "compose", "-f", str(compose_file), "restart"],
@@ -493,14 +592,12 @@ def admit_deployment(
return False, None, {}, pushed_branch, f"Repository '{repo_name}' is not recognized in trusted registry."
# 4. Manifest & Strategy Validation
if BRAIN_DIR.is_dir() and target_dir == BRAIN_DIR.resolve():
deployment_config = {"branch": "main", "actions": ["git_pull"]}
else:
manifest_file = target_dir / "app.yaml"
manifest = {}
if manifest_file.is_file():
try:
manifest = parse_yaml_simple(manifest_file.read_text(encoding="utf-8"))
manifest_text = manifest_file.read_text(encoding="utf-8")
manifest = (yaml.safe_load(manifest_text) if yaml else parse_yaml_simple(manifest_text)) or {}
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
return False, None, {}, pushed_branch, f"Failed to parse manifest {manifest_file}: {e}"
+145 -7
View File
@@ -131,16 +131,52 @@ def test_resolve_repository_resolves_valid_manifest(tmp_path: Path, monkeypatch)
assert gitops_dispatcher.resolve_repository("notes") == canonical
def test_resolve_repository_resolves_vault(tmp_path: Path, monkeypatch):
"""Ensure authoritative data vault identities resolve strictly to BRAIN_DIR."""
def test_resolve_repository_rejects_vault(tmp_path: Path, monkeypatch):
"""Ensure data vault identities (Brain / second-brain) are not recognized by GitOps."""
sites_dir = tmp_path / "Sites"
sites_dir.mkdir()
brain_dir = tmp_path / "Brain"
brain_dir.mkdir()
monkeypatch.setattr(gitops_dispatcher, "BRAIN_DIR", brain_dir)
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
canonical = brain_dir.resolve()
assert gitops_dispatcher.resolve_repository("second-brain") == canonical
assert gitops_dispatcher.resolve_repository("Brain") == canonical
assert gitops_dispatcher.resolve_repository("brain") == canonical
assert gitops_dispatcher.resolve_repository("second-brain") is None
assert gitops_dispatcher.resolve_repository("Brain") is None
assert gitops_dispatcher.resolve_repository("brain") is None
def test_get_trusted_repository_mapping_from_registry(tmp_path: Path, monkeypatch):
"""Ensure authoritative Core registry (deployments.yaml) is loaded with containment checks."""
sites_dir = tmp_path / "Sites"
sites_dir.mkdir()
app_dir = sites_dir / "my-app"
app_dir.mkdir()
outside_dir = tmp_path / "outside"
outside_dir.mkdir()
deployments_content = f"""
schemaVersion: "1.0"
repositories:
my-app:
path: "{app_dir}"
aliases:
- "app-alias"
escaped-app:
path: "{outside_dir}"
"""
deployments_file = tmp_path / "deployments.yaml"
deployments_file.write_text(deployments_content, encoding="utf-8")
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", deployments_file)
mapping = gitops_dispatcher.get_trusted_repository_mapping()
assert "my-app" in mapping
assert mapping["my-app"] == app_dir.resolve()
assert "app-alias" in mapping
assert mapping["app-alias"] == app_dir.resolve()
# Out-of-bounds path must be rejected
assert "escaped-app" not in mapping
def test_webhook_verification_valid_signature():
@@ -565,6 +601,108 @@ def test_worker_records_status_file(tmp_path: Path, monkeypatch):
assert "timestamp" in status
def test_validate_compose_security_rejects_privileged(tmp_path: Path):
"""Ensure docker-compose with privileged: true fails pre-flight validation."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text("""
services:
app:
image: alpine:latest
privileged: true
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
assert valid is False
assert err is not None and "privileged: true" in err
def test_validate_compose_security_rejects_docker_socket_mount(tmp_path: Path):
"""Ensure docker-compose with /var/run/docker.sock mount fails validation."""
# Test string syntax
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text("""
services:
app:
image: alpine:latest
volumes:
- /var/run/docker.sock:/var/run/docker.sock
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
assert valid is False
assert err is not None and "Docker socket" in err
# Test dict / long syntax
compose_file.write_text("""
services:
app:
image: alpine:latest
volumes:
- type: bind
source: /var/run/docker.sock
target: /var/run/docker.sock
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
assert valid is False
assert err is not None and "Docker socket" in err
def test_validate_compose_security_rejects_host_network(tmp_path: Path):
"""Ensure docker-compose with network_mode: host fails pre-flight validation."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text("""
services:
app:
image: alpine:latest
network_mode: host
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
assert valid is False
assert err is not None and "network_mode: host" in err
def test_validate_compose_security_rejects_out_of_bounds_host_bind(tmp_path: Path):
"""Ensure host bind mounts outside workload directory or state root are rejected."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text("""
services:
app:
image: alpine:latest
volumes:
- /etc/shadow:/etc/shadow:ro
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
assert valid is False
assert err is not None and "prohibited host bind mount" in err
def test_validate_compose_security_allows_safe_compose(tmp_path: Path):
"""Ensure safe compose definitions with relative binds and named volumes pass validation."""
data_dir = tmp_path / "data"
data_dir.mkdir()
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(f"""
services:
app:
image: alpine:latest
volumes:
- {data_dir}:/data
- named_vol:/var/log
volumes:
named_vol:
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
assert valid is True
assert err is None
def test_validate_compose_security_nonexistent_file(tmp_path: Path):
"""Ensure validation passes when compose file is absent."""
compose_file = tmp_path / "nonexistent.yml"
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path)
assert valid is True
assert err is None