Compare commits

...
9 Commits
Author SHA1 Message Date
kiskaadee c8a12345b8 diff --git a/scripts/appctl b/scripts/appctl
index 0d5b2e6..071c3b9 100755
--- a/scripts/appctl
+++ b/scripts/appctl
@@ -8,6 +8,7 @@ set -e

 SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
 ENGINE="$SCRIPT_DIR/appctl_engine.py"
+PYTHON_BIN="${PYTHON_BIN:-python3}"
 ENV_FILE="/run/secrets/rendered/traefik-deployments.env"
 if [ ! -f "$ENV_FILE" ] && [ -f "/run/secrets/traefik-deployments.env" ]; then
   ENV_FILE="/run/secrets/traefik-deployments.env"
@@ -64,7 +65,7 @@ show_help() {
 setup_app_env() {
   local query="$1"
   local resolved_json
-  resolved_json=$(python3 "$ENGINE" resolve "$query" 2>/dev/null || true)
+  resolved_json=$("$PYTHON_BIN" "$ENGINE" resolve "$query" || true)

   if [ -z "$resolved_json" ]; then
     echo "❌ Error: Service '$query' not found under $SITES_DIR or Core"
@@ -72,10 +73,10 @@ setup_app_env() {
   fi

   # Extract fields via python json
-  TARGET_TYPE=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('type', 'app'))" "$resolved_json")
-  APP_DIR=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d['dir_path'])" "$resolved_json")
-  CANONICAL_NAME=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d['name'])" "$resolved_json")
-  TARGET_CONTAINER=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('container', ''))" "$resolved_json")
+  TARGET_TYPE=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('type', 'app'))" "$resolved_json")
+  APP_DIR=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['dir_path'])" "$resolved_json")
+  CANONICAL_NAME=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['name'])" "$resolved_json")
+  TARGET_CONTAINER=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('container', ''))" "$resolved_json")

   if [ "$TARGET_TYPE" = "core" ] || [ "$TARGET_TYPE" = "core_service" ]; then
     if [ ! -d "$CORE_DIR" ]; then
@@ -93,7 +94,7 @@ setup_app_env() {
     return
   fi

-  RESOLVED_DOMAIN=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d['domain'])" "$resolved_json")
+  RESOLVED_DOMAIN=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['domain'])" "$resolved_json")

   # 1. Base infrastructure defaults
   export PROXY_NETWORK="${PROXY_NETWORK:-proxy-net}"
@@ -110,7 +111,7 @@ setup_app_env() {
   # 3. Dynamic environment variables from app.yaml (e.g. PROJECT_PATH, MEDIA_PATH, etc.)
   while IFS= read -r -d '' k && IFS= read -r -d '' v; do
     export "$k=$v"
-  done < <(python3 -c "
+  done < <("$PYTHON_BIN" -c "
 import json, re, sys
 RESERVED = {'PATH', 'LD_PRELOAD', 'IFS', 'SHELL', 'USER', 'CORE_DIR', 'SITES_DIR', 'ENV_FILE', 'HOMESERVER_ENV'}
 d = json.loads(sys.argv[1])
@@ -151,23 +152,23 @@ APP=$2

 case "$COMMAND" in
   list|status)
-    python3 "$ENGINE" list "${@:2}"
+    "$PYTHON_BIN" "$ENGINE" list "${@:2}"
     ;;
   ssl)
-    python3 "$ENGINE" ssl "${@:2}"
+    "$PYTHON_BIN" "$ENGINE" ssl "${@:2}"
     ;;
   info)
     if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
-    python3 "$ENGINE" info "${@:2}"
+    "$PYTHON_BIN" "$ENGINE" info "${@:2}"
     ;;
   sync)
-    python3 "$ENGINE" sync "${@:2}"
+    "$PYTHON_BIN" "$ENGINE" sync "${@:2}"
     ;;
   complete)
-    python3 "$ENGINE" complete "${@:2}"
+    "$PYTHON_BIN" "$ENGINE" complete "${@:2}"
     ;;
   resolve)
-    python3 "$ENGINE" resolve "${@:2}"
+    "$PYTHON_BIN" "$ENGINE" resolve "${@:2}"
     ;;
   completion)
     cat <<'EOF'
fix(scripts): support PYTHON_BIN in appctl and unmask resolve stderr

- Introduce configurable PYTHON_BIN="${PYTHON_BIN:-python3}" in scripts/appctl.
- Remove blind '2>/dev/null' on engine resolve in setup_app_env to prevent
  masking manifest validation failures and runtime exceptions.
- Propagate active Python interpreter and PYTHONPATH in security invariant
  injection test to prevent Nix wrapper bare-python PATH shadowing.
2026-10-15 18:25:43 -05:00
kiskaadee 6997da3a58 chore(engine): retire appctl_engine_v2.py backward-compatibility shim
- Remove unused 16-line re-export shim scripts/appctl_engine_v2.py
- Update implementation inventory in docs/plans/p4-readiness-plan.md
- Confirm zero active callers across scripts, tests, and configuration
2026-10-15 16:41:32 -05:00
kiskaadee 1d196cbdd5 fix(engine): resolve pyright type narrowing issues and align pyproject.toml
- Add explicit None checks in SitesApp.to_dict() to eliminate reportOptionalMemberAccess
- Type-narrow app to SitesApp in cmd_info() eliminating reportAttributeAccessIssue
- Defensively parse X.509 peer cert RDN tuples in check_ssl_cert() resolving reportCallIssue
- Configure venvPath and venv in pyproject.toml [tool.pyright] and remove appctl_engine exclude
- Clean up Manifest type assertion in test_core_manifest.py
2026-10-15 15:17:30 -05:00
kiskaadee fe4111a628 feat(manifest): migrate core_manifest.py to Pydantic v2 and record ADR 0003
- Author MADR 4.0 ADR 0003 committing to centralized runtime validation and serialization via Pydantic v2
- Migrate SourceConfig, DeploymentConfig, HomepageConfig, and Manifest to Pydantic v2 models with ConfigDict(extra="forbid")
- Enforce fail-closed validation, strict typing, and secret-safe ManifestValidationError error transformation
- Update SitesApp.to_dict() in appctl_engine.py to recursively serialize nested Pydantic models
- Add unit tests verifying extra field rejection and model serialization in test_core_manifest.py
- Synchronize todo.txt marking manifest migration deliverable complete
2026-10-15 06:13:59 -05:00
kiskaadee fae36700b7 docs(p4): clarify pydantic target architecture and domain precedence in readiness plan
- Clarify Pydantic v2 as the target architecture for Milestone P4 implementation rather than existing code
- Detail strict type validation vs extra="forbid" rules, forbidding type coercion on operations, targets, flags, and tokens
- Specify error response transformation and information disclosure prevention (omitting raw secret values)
- Formalize domain configuration precedence (HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN -> fail closed) and RFC 2606 placeholders
- Synchronize todo.txt with completed pre-P4 tasks and schedule follow-up repository-wide domain scrub
2026-10-15 05:25:57 -05:00
kiskaadee 4786bbe1ca test(security): execute scripts/appctl directly in env injection resilience test
- De-tautologize test_appctl_env_injection_resilience by replacing copy-pasted inline bash loop with direct execution of scripts/appctl config
- Mount a mock docker binary in PATH to capture resolved environment variables without requiring a running Docker daemon
- Verify end-to-end that command substitution payloads ($(touch ...)) remain unexpanded literals and reserved environment keys cannot be overridden
- Ensure compatibility across standard environments and Nix sandbox flake checks using resolved bash interpreter
2026-10-15 05:15:41 -05:00
kiskaadee fbfbe9375f feat(core): enforce platform genericism invariant and scrub hardcoded domains
- Remove hardcoded roadtotech.me domain defaults in scripts/appctl and scripts/appctl_engine.py
- Enforce domain environment variable precedence (HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN)
- Replace personal domains and operator usernames across test fixtures with RFC 2606 placeholders (example.com, example.org, example.test)
- Add automated CI invariant test verifying zero personal domain/operator literals in scripts and tests
2026-10-15 03:45:22 -05:00
kiskaadee ea0ce0b1d6 fix(gitops): wire app_name and harden compose validator for env_file and volumes
- Pass app_name=canonical_app_name to validate_compose_security in execute_deployment
- Block env_file path escapes outside workload root to prevent secret exfiltration
- Normalize string security_opt directives before capability validation
- Reject ambiguous volume paths not declared in top-level volumes
- Add unit tests verifying env_file containment, string security_opt, and volume safety
2026-10-15 03:40:11 -05:00
kiskaadee 66c5e4280a feat(nixos): add pydantic to host runtime environment and constrain dependency range
- Add pydantic to environment.systemPackages in nixos/configuration.nix

- Add pydantic to homelab-gitops.service path in nixos/modules/homeserver.nix

- Constrain pydantic dependency to >=2.0,<3.0 in pyproject.toml
2026-10-15 03:38:08 -05:00
19 changed files with 662 additions and 286 deletions

No files matched your search

+1 -1
View File
@@ -106,7 +106,7 @@ Core platform code, templates, and documentation must remain strictly instance-a
- Instance-specific domains (e.g. personal domain names), operator usernames, and deployment topologies must never be hardcoded into Core platform definitions.
- All routing and service identities must be injected declaratively at runtime via environment variables (`HOMELAB_DOMAIN`, `DOMAIN_SUFFIX`) and local configuration overlays.
- Example manifests, tests, and documentation must use RFC-compliant generic placeholders (e.g. `example.com`, `example.org`, `testdomain.local`).
- Example manifests, tests, and documentation must use RFC-compliant generic placeholders (e.g. `example.com`, `example.org`, `example.test`).
### 9. License
@@ -0,0 +1,96 @@
---
type: decision
status: accepted
project: homelab-core
date: 2026-10-15
tags: [architecture, appctl, validation, pydantic, security, api]
---
# ADR 0003: Centralized Runtime Validation & Serialization via Pydantic v2
## Context and Problem Statement
As Homelab Core transitions from decoupled CLI scripts into an authoritative operational control plane (`homelab-appctl.service`, Milestone P4), the system must process untrusted inputs across two distinct ingestion boundaries:
1. Declarative workload manifests (`app.yaml`) authored in `~/Sites` by independent workloads or external repository webhooks.
2. Command-oriented API requests sent across dual transports (host Unix Domain Socket `/run/homelab/appctl.sock` and network HTTP listener).
Previously, manifest parsing relied on Python standard library dataclasses combined with manual regex checking and dictionary traversals in `scripts/core_manifest.py`. While functional for basic validation, manual ad-hoc validation created subtle security and maintainability risks:
- Input parsing logic was duplicated across `core_manifest.py`, `appctl_engine.py`, and `gitops_dispatcher.py`.
- Validation errors varied in structure and could inadvertently reflect unvalidated raw payloads (potentially leaking secrets or host paths).
- Future daemon API endpoints would require writing independent request/response serialization, type-checking, and error-handling routines for every operation.
The central architectural question is: **How should the control plane enforce strict, fail-closed type safety and consistent serialization across workload manifests and daemon API endpoints without duplicating validation logic or leaking secrets?**
## Decision Drivers
* **Fail-Closed Type Safety**: Unrecognized fields, unexpected types, or invalid operations must be rejected immediately at the transport boundary before reaching the operational router.
* **Unified Contract Enforcement**: Workload manifests (`app.yaml`) and control plane API payloads must share a common, declarative schema definition rather than separate parser implementations.
* **Prevention of Information Disclosure**: Error payloads returned to clients or logged to audit streams must describe schema violations without echoing raw input values, environment variables, or credentials.
* **Dual-Transport Parity**: The same validated contract must govern both local Unix Domain Socket calls (CLI) and remote HTTP calls (GitOps dispatcher, Web UI).
* **Maintainability & Performance**: Minimizing bespoke parsing code while maintaining fast validation overhead suitable for daemon and CLI operations.
## Considered Options
* **Option 1: Standard Library Dataclasses with Custom Manual Validators**: Continue relying solely on Python `dataclasses` and manual validation functions (`isinstance`, regexes).
* **Option 2: JSON Schema (`jsonschema`) with Manual Object Deserialization**: Use JSON Schema definitions to validate raw dicts, then manually map validated dicts to dataclasses.
* **Option 3: Pydantic v2 with Strict Mode & Fail-Closed Configuration (Adopted)**: Introduce Pydantic v2 as the authoritative validation and serialization engine across manifests and API models.
## Decision Outcome
Chosen option: **Option 3: Pydantic v2 with Strict Mode & Fail-Closed Configuration**, because:
> *"We opted for centralizing runtime validation and serialization across workload manifest and daemon API around Pydantic models to enforce fail-closed type safety, strict schema-based contract boundaries and consistent serialization and error handling without leaking secrets."*
### Summary of Architectural Commitments
1. **Single Schema & Validation Layer**:
All domain entities—including workload manifest configurations (`SourceConfig`, `DeploymentConfig`, `HomepageConfig`, `Manifest`) and control plane API command payloads (requests, responses, errors)—are defined exclusively as Pydantic v2 models inheriting from `pydantic.BaseModel`.
2. **Fail-Closed Schema Boundaries (`extra="forbid"`)**:
Every model enforces `ConfigDict(extra="forbid")`. Any payload containing unexpected, undocumented, or extraneous fields is rejected at the transport boundary with zero execution.
3. **Strict Typing Policy (`strict=True`)**:
To prevent unexpected coercion bugs (e.g. string `"false"` coercing to boolean `True`, or floats coercing to ints), API operations, target identifiers, flags (`recreate`, `remove_orphans`, `visible`, `auth`), and tokens enforce strict types. Explicit field validators handle string trimming/normalization where intentional.
4. **Information Disclosure Prevention**:
Transport adapters intercept `pydantic.ValidationError` and map it into structured `ERR_VALIDATION_FAILED` (HTTP 400) responses. Error messages report violating field names and failure rules, but strictly sanitize and redact raw input values to prevent leaking secrets, credentials, or filesystem paths.
5. **Dual-Transport Parity**:
The identical Pydantic request and response models govern both Unix domain socket messages and HTTP API endpoints. Neither transport performs custom validation outside the shared Pydantic models.
6. **Host Runtime Alignment**:
Pydantic is packaged into the NixOS system environment (`nixos/configuration.nix`), systemd unit paths (`nixos/modules/homeserver.nix`), Nix flake development shells, and repository test dependencies (`pyproject.toml`) constrained to major version range `>=2.0,<3.0`.
## Pros and Cons of the Options
### Option 1: Standard Library Dataclasses with Custom Manual Validators
* Good, because it requires zero external dependencies and uses Python standard library modules.
* Bad, because validation code must be manually implemented for every field, nested structure, and API payload.
* Bad, because it is error-prone and historically led to parser duplication across `core_manifest.py`, `appctl_engine.py`, and `gitops_dispatcher.py`.
* Bad, because serialization and deserialization (e.g. JSON to model and back) require bespoke helper methods.
### Option 2: JSON Schema (`jsonschema`) with Manual Object Deserialization
* Good, because JSON Schema is a standardized language-agnostic specification.
* Bad, because it requires maintaining two separate artifacts for every entity: a JSON Schema document and a corresponding Python dataclass or class.
* Bad, because mapping validated JSON Schema dicts to Python typed objects adds runtime boilerplate and cognitive overhead.
* Bad, because error messages from `jsonschema` can be difficult to sanitize and format into uniform domain error structures.
### Option 3: Pydantic v2 with Strict Mode & Fail-Closed Configuration (Adopted)
* Good, because it provides declarative, unified model definitions that handle validation, type-checking, and JSON serialization in a single class.
* Good, because Pydantic v2's Rust core (`pydantic-core`) delivers high-performance validation with minimal latency impact on the daemon.
* Good, because built-in `ValidationError` metadata makes structured error mapping straightforward and consistent.
* Good, because `model_dump(mode="json")` and `model_validate_json()` provide deterministic, standardized serialization across dual transports.
* Bad, because it introduces a third-party dependency into the Core platform that must be maintained across NixOS packages, development shells, and CI pipelines (mitigated by locking `>=2.0,<3.0` in `pyproject.toml` and Nix flake checks).
## Consequences
### Positive Consequences
* Eliminates fragmented parsing code: all callers (`appctl_engine.py`, `gitops_dispatcher.py`, `homelab-appctl.service`) validate against the same authoritative schemas in `core_manifest.py`.
* Pre-P4 security posture is substantially hardened: unvalidated fields and type confusion attacks are blocked at ingestion.
* Clean separation of concerns: transport adapters focus on wire protocol handling while Pydantic guarantees valid domain objects for the operational router.
* Client error payloads are structured, actionable, and safe from secret leakage.
### Negative Consequences & Accepted Trade-offs
* Core depends on `pydantic` in host NixOS environment; all host Python environments executing `appctl` or `homelab-gitops` must have `python3Packages.pydantic` available.
* Schema evolution requires strict versioning: since `extra="forbid"` is enforced, extending manifests or API payloads with new fields requires coordinated model updates.
## More Information
* **Governing Readiness Plan**: [`docs/plans/p4-readiness-plan.md`](../plans/p4-readiness-plan.md) (Section 2.B)
* **Governing Roadmap**: [`ROADMAP.md`](../../ROADMAP.md) (Milestone P4)
* **Platform Security Invariants**: [`AGENTS.md`](../../AGENTS.md) (Invariants #1, #2, #3)
+14
View File
@@ -10,14 +10,28 @@ In accordance with platform governance, authoritative ADRs are maintained in the
| Decision Record | Status | Date | Scope & One-Line Purpose |
| :--- | :--- | :--- | :--- |
| [**Centralized Runtime Validation & Serialization via Pydantic v2**](0003-pydantic-v2-runtime-validation.md) | `accepted` | 2026-10-15 | Adopts Pydantic v2 as the single runtime schema and validation authority across workload manifests and daemon API to enforce fail-closed type safety, strict schema-based boundaries, and secret-safe serialization. |
| [**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
### Centralized Runtime Validation & Serialization via Pydantic v2
* **Canonical Document**: [`0003-pydantic-v2-runtime-validation.md`](0003-pydantic-v2-runtime-validation.md)
* **Status**: `accepted` (Active)
* **Governing Implementation Plan**: [ROADMAP.md](../../ROADMAP.md) (Milestone P4)
* **Core Commitments**:
1. **Single Schema & Validation Layer**: Workload manifests (`core_manifest.py`) and API command models inherit from `pydantic.BaseModel`.
2. **Fail-Closed Extra Fields (`extra="forbid"`)**: Immediate rejection of unexpected or undocumented payload properties.
3. **Strict Typing Policy (`strict=True`)**: Coercion forbidden on operations, targets, identifiers, and flags.
4. **Secret-Safe Error Transformation**: Transport-level conversion of `ValidationError` into standard `ERR_VALIDATION_FAILED` (400) with raw input values redacted.
5. **Dual-Transport Parity**: Identical validated models across Unix domain socket and HTTP transports.
### 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)
+22 -9
View File
@@ -46,8 +46,8 @@ This plan resolves the six architectural prerequisites necessary to implement P4
| :--- | :--- | :--- | :--- |
| [`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. |
@@ -84,7 +84,8 @@ This plan resolves the six architectural prerequisites necessary to implement P4
### 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.
1. **V1 Engine is Fully Superseded & V2 Shim Retired**: `scripts/appctl_engine.py` is the single authoritative metadata engine. The `scripts/appctl_engine_v2.py` compatibility shim has been retired.
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.
@@ -117,11 +118,17 @@ Every client (local CLI, remote CLI, GitOps dispatcher, and future Operations UI
• platform.health
```
### B. Typed Request and Response Models (Pydantic v2 Validation Pipeline)
### B. Typed Request and Response Models (Target Architecture: Pydantic v2 Pipeline)
All control plane API requests, responses, error payloads, and workload manifest schemas are defined and validated through **Pydantic v2** (`pydantic.BaseModel`, `pydantic.Field`, `ConfigDict(extra="forbid")`):
- **Runtime Validation**: Incoming payloads over both Unix Domain Socket and HTTP endpoints are validated at the transport boundary before reaching the operational router.
- **Fail-Closed Type Safety**: Unrecognized fields, malformed types, or invalid operations immediately fail validation with structured `ERR_VALIDATION_FAILED` (400) payloads.
All control plane API requests, responses, error payloads, and workload manifest schemas will be defined and validated through **Pydantic v2** (`pydantic.BaseModel`, `pydantic.Field`, `ConfigDict(extra="forbid", strict=True)`). While the dependency has been integrated into runtime environments, the schema migration and model definitions are the first implementation deliverables of Milestone P4:
- **Runtime Validation Boundary**: Incoming payloads over both Unix Domain Socket and HTTP endpoints are validated at the transport boundary before reaching the operational router.
- **Fail-Closed Extra Fields (`extra="forbid"`)**: Rejects any undeclared or unknown fields immediately.
- **Strict Typing vs. Coercion Rules**:
- *Strict Validation*: Operations (`operation`), target identifiers (`target`), boolean flags (`recreate`, `remove_orphans`, `visible`, `auth`), and authentication tokens require strict types (`strict=True` or `StrictStr`, `StrictBool`). Coercion (e.g. converting `"true"` or `1` to `True`, or floats to ints) is strictly forbidden for control plane commands to prevent ambiguous execution.
- *Permitted Coercion / Sanitization*: Only explicitly defined string stripping/normalization (e.g. whitespace trimming) is permitted via field validators.
- **Structured Error Transformation**: Transport handlers intercept `pydantic.ValidationError` and map it to canonical `ERR_VALIDATION_FAILED` (`400 Bad Request`) responses.
- **Information Disclosure Prevention**: Error details must include field names and validation issue descriptions, but must strictly redact and omit raw input values to prevent leaking secrets, credentials, or host filesystem paths.
- **Contract Enforcement**: Manifest definitions in `core_manifest.py` migrate to Pydantic v2 models, guaranteeing uniform schema enforcement across the CLI, daemon, and GitOps engines.
All requests and responses use strict JSON payloads with explicit schema versioning (`version: "1.0"`):
@@ -248,8 +255,13 @@ Following the pattern established in Milestone P2 for `homelab-gitops.service`,
### C. Platform Genericism & Domain Decoupling
Per Invariant #8 in `AGENTS.md`, the control plane and all platform components must remain strictly instance-agnostic:
- **No Hardcoded Domains**: Personal domain names (e.g. `roadtotech.me`) must never appear hardcoded in Python modules, NixOS definitions, or default configurations.
- **Dynamic Resolution**: Domains must resolve exclusively through `HOMELAB_DOMAIN`, `DOMAIN_SUFFIX`, or `DOMAIN` environment variables.
- **Generic Fallbacks & Tests**: Test fixtures, documentation examples, and schema defaults must use RFC-reserved generic domains (`example.com`, `example.org`, `testdomain.local`).
- **Canonical Precedence & Dynamic Resolution**: All domain resolutions follow strict, fail-closed precedence:
1. `HOMELAB_DOMAIN` (Primary platform apex domain)
2. `DOMAIN_SUFFIX` (Secondary routing suffix fallback)
3. `DOMAIN` (Legacy environment fallback)
If none are set, the platform fails closed rather than defaulting to hardcoded values.
- **Generic Placeholders & Test Fixtures**: Test fixtures, documentation examples, and schema defaults must use RFC 2606 reserved domains (`example.com`, `example.org`, `example.test`).
---
@@ -325,4 +337,5 @@ Before marking Milestone P4 complete, the following automated regression suite m
| **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 86 existing unit, security, and nix flake tests pass with 0 regressions. | Block Merge |
| **Existing Invariant Regression** | Run `./scripts/test`: All 121 existing unit, security, structural, and Nix flake sandbox tests pass with 0 regressions. | Block Merge |
+2 -1
View File
@@ -127,9 +127,10 @@
# Secrets tooling (required for sops-nix secret decryption and manual re-encryption)
sops
age
# Python runtime (hard requirement for appctl and gitops_dispatcher.py)
# Python runtime (hard requirement for appctl, core_manifest, and gitops_dispatcher.py)
(python3.withPackages (ps: with ps; [
pyyaml
pydantic
]))
# Modern shell utilities
eza # ls replacement
+9 -1
View File
@@ -66,7 +66,15 @@
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
path = with pkgs; [ git docker docker-compose python3 coreutils bash openssh ];
path = with pkgs; [
git
docker
docker-compose
(python3.withPackages (ps: with ps; [ pyyaml pydantic ]))
coreutils
bash
openssh
];
environment = {
GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path;
+5 -4
View File
@@ -5,11 +5,12 @@ description = "Homelab Core platform and orchestration"
requires-python = ">=3.13"
dependencies = [
"pyyaml>=6.0",
"pydantic>=2.0",
"pydantic>=2.0,<3.0",
]
[tool.pyright]
include = ["scripts"]
extraPaths = ["scripts"]
exclude = [
"scripts/appctl_engine.py",
]
venvPath = "."
venv = ".venv"
+21 -19
View File
@@ -8,6 +8,7 @@ set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENGINE="$SCRIPT_DIR/appctl_engine.py"
PYTHON_BIN="${PYTHON_BIN:-python3}"
ENV_FILE="/run/secrets/rendered/traefik-deployments.env"
if [ ! -f "$ENV_FILE" ] && [ -f "/run/secrets/traefik-deployments.env" ]; then
ENV_FILE="/run/secrets/traefik-deployments.env"
@@ -36,7 +37,8 @@ if [ -f "$ENV_FILE" ]; then
fi
# Lock the homelab root domain before setup_app_env can mutate $DOMAIN
export HOMELAB_DOMAIN="${HOMELAB_DOMAIN:-${DOMAIN_SUFFIX:-${DOMAIN:-roadtotech.me}}}"
# Canonical precedence: HOMELAB_DOMAIN -> DOMAIN_SUFFIX -> DOMAIN
export HOMELAB_DOMAIN="${HOMELAB_DOMAIN:-${DOMAIN_SUFFIX:-${DOMAIN:-}}}"
# Show help usage
show_help() {
@@ -63,7 +65,7 @@ show_help() {
setup_app_env() {
local query="$1"
local resolved_json
resolved_json=$(python3 "$ENGINE" resolve "$query" 2>/dev/null || true)
resolved_json=$("$PYTHON_BIN" "$ENGINE" resolve "$query" || true)
if [ -z "$resolved_json" ]; then
echo "❌ Error: Service '$query' not found under $SITES_DIR or Core"
@@ -71,10 +73,10 @@ setup_app_env() {
fi
# Extract fields via python json
TARGET_TYPE=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('type', 'app'))" "$resolved_json")
APP_DIR=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d['dir_path'])" "$resolved_json")
CANONICAL_NAME=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d['name'])" "$resolved_json")
TARGET_CONTAINER=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('container', ''))" "$resolved_json")
TARGET_TYPE=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('type', 'app'))" "$resolved_json")
APP_DIR=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['dir_path'])" "$resolved_json")
CANONICAL_NAME=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['name'])" "$resolved_json")
TARGET_CONTAINER=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d.get('container', ''))" "$resolved_json")
if [ "$TARGET_TYPE" = "core" ] || [ "$TARGET_TYPE" = "core_service" ]; then
if [ ! -d "$CORE_DIR" ]; then
@@ -92,13 +94,13 @@ setup_app_env() {
return
fi
RESOLVED_DOMAIN=$(python3 -c "import json, sys; d=json.loads(sys.argv[1]); print(d['domain'])" "$resolved_json")
RESOLVED_DOMAIN=$("$PYTHON_BIN" -c "import json, sys; d=json.loads(sys.argv[1]); print(d['domain'])" "$resolved_json")
# 1. Base infrastructure defaults
export PROXY_NETWORK="${PROXY_NETWORK:-proxy-net}"
export NETWORK_NAME="${NETWORK_NAME:-$PROXY_NETWORK}"
export CERT_RESOLVER="${CERT_RESOLVER:-myresolver}"
export DOMAIN_SUFFIX="${DOMAIN_SUFFIX:-roadtotech.me}"
export DOMAIN_SUFFIX="${DOMAIN_SUFFIX:-$HOMELAB_DOMAIN}"
# 2. Canonical application identity
export SERVICE_NAME="$CANONICAL_NAME"
@@ -109,7 +111,7 @@ setup_app_env() {
# 3. Dynamic environment variables from app.yaml (e.g. PROJECT_PATH, MEDIA_PATH, etc.)
while IFS= read -r -d '' k && IFS= read -r -d '' v; do
export "$k=$v"
done < <(python3 -c "
done < <("$PYTHON_BIN" -c "
import json, re, sys
RESERVED = {'PATH', 'LD_PRELOAD', 'IFS', 'SHELL', 'USER', 'CORE_DIR', 'SITES_DIR', 'ENV_FILE', 'HOMESERVER_ENV'}
d = json.loads(sys.argv[1])
@@ -150,23 +152,23 @@ APP=$2
case "$COMMAND" in
list|status)
python3 "$ENGINE" list "${@:2}"
"$PYTHON_BIN" "$ENGINE" list "${@:2}"
;;
ssl)
python3 "$ENGINE" ssl "${@:2}"
"$PYTHON_BIN" "$ENGINE" ssl "${@:2}"
;;
info)
if [ -z "$APP" ]; then echo "❌ Error: Service name required"; exit 1; fi
python3 "$ENGINE" info "${@:2}"
"$PYTHON_BIN" "$ENGINE" info "${@:2}"
;;
sync)
python3 "$ENGINE" sync "${@:2}"
"$PYTHON_BIN" "$ENGINE" sync "${@:2}"
;;
complete)
python3 "$ENGINE" complete "${@:2}"
"$PYTHON_BIN" "$ENGINE" complete "${@:2}"
;;
resolve)
python3 "$ENGINE" resolve "${@:2}"
"$PYTHON_BIN" "$ENGINE" resolve "${@:2}"
;;
completion)
cat <<'EOF'
@@ -241,7 +243,7 @@ EOF
else
echo "🚀 Starting $CANONICAL_NAME ($APP_DIR)..."
cd "$APP_DIR" && docker compose up -d --remove-orphans "${@:3}"
python3 "$ENGINE" sync >/dev/null 2>&1 || true
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
fi
;;
down)
@@ -256,7 +258,7 @@ EOF
else
echo "🛑 Stopping $CANONICAL_NAME ($APP_DIR)..."
cd "$APP_DIR" && docker compose down "${@:3}"
python3 "$ENGINE" sync >/dev/null 2>&1 || true
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
fi
;;
restart)
@@ -276,7 +278,7 @@ EOF
else
echo "🔄 Restarting $CANONICAL_NAME ($APP_DIR)..."
cd "$APP_DIR" && docker compose down && docker compose up -d "${@:3}"
python3 "$ENGINE" sync >/dev/null 2>&1 || true
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
fi
;;
update)
@@ -317,7 +319,7 @@ EOF
echo "🚀 Recreating container stack..."
cd "$APP_DIR" && docker compose up -d --remove-orphans "${@:3}"
python3 "$ENGINE" sync >/dev/null 2>&1 || true
"$PYTHON_BIN" "$ENGINE" sync >/dev/null 2>&1 || true
echo "✨ $CANONICAL_NAME successfully updated!"
;;
pull)
+32 -8
View File
@@ -56,8 +56,8 @@ def validate_environment() -> None:
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."
"• Missing 'HOMELAB_DOMAIN' (or 'DOMAIN_SUFFIX' / 'DOMAIN') environment variable.\n"
" Please export it (e.g. export HOMELAB_DOMAIN='example.com') or set it in your environment file."
)
if not os.path.isdir(CORE_DIR):
@@ -77,7 +77,7 @@ ManifestError = ManifestValidationError
class App:
name: str # Canonical identifier (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".
domain: str = "" # Routing FQDN (e.g., "auth.example.com") or "internal".
dir_path: str = "" # Filesystem directory (CORE_DIR for Core, or ~/Sites/<app> for Sites).
@property
@@ -120,10 +120,16 @@ class SitesApp(App):
"""Serialize for JSON consumption by scripts/appctl"""
data = asdict(self)
data.pop("manifest_obj", None)
if self.source is not None:
data["source"] = self.source.to_dict() if hasattr(self.source, "to_dict") else self.source.model_dump()
if self.homepage is not None:
data["homepage"] = self.homepage.to_dict() if hasattr(self.homepage, "to_dict") else self.homepage.model_dump()
data["type"] = getattr(self, "app_type", "app")
return data
def sites_app_from_manifest(
app_dir: str,
manifest: Manifest | dict[str, Any] | None = None,
@@ -479,7 +485,8 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
socket.create_connection((domain, port), timeout=timeout) as sock,
ctx.wrap_socket(sock, server_hostname=domain) as ssock,
):
cert = ssock.getpeercert() or {}
raw_cert = ssock.getpeercert()
cert = raw_cert if isinstance(raw_cert, dict) else {}
not_after_str = str(cert.get("notAfter", ""))
days_remaining = None
@@ -492,14 +499,27 @@ def check_ssl_cert(domain: str, port: int = 443, timeout: float = 3.0) -> dict[s
days_remaining = (expiry_dt - now_dt).days
formatted_expiry = expiry_dt.strftime("%Y-%m-%d")
issuer_raw = cert.get("issuer", ())
issuer_dict = dict(x[0] for x in issuer_raw) if issuer_raw else {}
issuer_dict: dict[str, str] = {}
issuer_raw = cert.get("issuer")
if isinstance(issuer_raw, (list, tuple)):
for rdn in issuer_raw:
if isinstance(rdn, (list, tuple)) and rdn:
entry = rdn[0]
if isinstance(entry, (list, tuple)) and len(entry) >= 2:
issuer_dict[str(entry[0])] = str(entry[1])
issuer = str(issuer_dict.get("organizationName") or issuer_dict.get("commonName") or "Unknown")
subject_raw = cert.get("subject", ())
subject_dict = dict(x[0] for x in subject_raw) if subject_raw else {}
subject_dict: dict[str, str] = {}
subject_raw = cert.get("subject")
if isinstance(subject_raw, (list, tuple)):
for rdn in subject_raw:
if isinstance(rdn, (list, tuple)) and rdn:
entry = rdn[0]
if isinstance(entry, (list, tuple)) and len(entry) >= 2:
subject_dict[str(entry[0])] = str(entry[1])
subject = str(subject_dict.get("commonName") or domain)
if days_remaining is not None:
if days_remaining < 0:
status = f"🔴 Expired ({abs(days_remaining)}d ago)"
@@ -759,8 +779,12 @@ def cmd_info(args: list[str]) -> None:
print(f"Description: {app.description}")
return
if not isinstance(app, SitesApp):
return
# SitesApp
print(f"ℹ️ Workload Overview: {app.name}")
print("-" * 50)
print(f"Directory: {app.dir_path}")
print(f"Domain: {app.domain}")
-16
View File
@@ -1,16 +0,0 @@
#!/usr/bin/env python3
"""
appctl_engine_v2.py - Backward-compatibility shim pointing to appctl_engine.py.
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from appctl_engine import *
from appctl_engine import main
if __name__ == "__main__":
main()
+175 -152
View File
@@ -2,21 +2,30 @@
core_manifest.py — Authoritative Workload Manifest Schema (v1.0) & Parser Library
Governs the contract for all ~/Sites workloads:
- Strongly-typed dataclass representations (Manifest, SourceConfig, DeploymentConfig, HomepageConfig)
- Strongly-typed Pydantic v2 representations (Manifest, SourceConfig, DeploymentConfig, HomepageConfig)
- Strict source transport scheme validation (https://, ssh://, git@)
- Explicit ref classification (moving branches vs. pinned tags vs. commit SHAs)
- Workload classification: Class A (Source-Backed) vs. Class B (Image-Only)
- Fail-closed schema enforcement with ConfigDict(extra="forbid")
"""
from __future__ import annotations
import re
from dataclasses import asdict, dataclass, field
from enum import Enum
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
from pydantic import (
BaseModel,
ConfigDict,
Field,
ValidationError,
field_validator,
model_validator,
)
try:
import yaml
except ImportError:
@@ -142,15 +151,41 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]:
return RefType.BRANCH, ref
@dataclass
class SourceConfig:
class SourceConfig(BaseModel):
"""Upstream source provenance descriptor."""
model_config = ConfigDict(extra="forbid")
url: str
ref: str = "main"
type: str = "git"
ref_type: RefType = RefType.BRANCH
transport: TransportScheme = TransportScheme.HTTPS
@model_validator(mode="before")
@classmethod
def validate_source(cls, data: Any) -> Any:
if isinstance(data, dict):
src_type = str(data.get("type", "git")).strip().lower()
if src_type != "git":
raise ManifestValidationError(f"Unsupported source type '{src_type}'. Only 'git' is supported.")
data["type"] = src_type
raw_url = data.get("url")
if raw_url is not None:
transport, validated_url = validate_transport(str(raw_url))
data["url"] = validated_url
if "transport" not in data or data["transport"] is None:
data["transport"] = transport
raw_ref = data.get("ref", "main")
if raw_ref is not None:
ref_type, clean_ref = classify_ref(str(raw_ref))
data["ref"] = clean_ref
if "ref_type" not in data or data["ref_type"] is None:
data["ref_type"] = ref_type
return data
def to_dict(self) -> dict[str, Any]:
return {
"type": self.type,
@@ -161,49 +196,156 @@ class SourceConfig:
}
@dataclass
class DeploymentConfig:
class DeploymentConfig(BaseModel):
"""Continuous deployment strategy and action policy."""
model_config = ConfigDict(extra="forbid")
strategy: str = "compose"
branch: str = "main"
actions: list[str] = field(default_factory=lambda: ["git_pull", "compose_up"])
actions: list[str] = Field(default_factory=lambda: ["git_pull", "compose_up"])
@field_validator("strategy", mode="before")
@classmethod
def validate_strategy(cls, v: Any) -> str:
clean = str(v).strip().lower()
if clean not in ALLOWED_STRATEGIES:
raise ManifestValidationError(
f"Unsupported deployment strategy '{clean}'. Allowed: {sorted(ALLOWED_STRATEGIES)}"
)
return clean
@field_validator("actions", mode="before")
@classmethod
def validate_actions(cls, v: Any) -> list[str]:
if isinstance(v, list):
actions: list[str] = []
for act in v:
act_str = str(act).strip().lower()
if act_str not in ALLOWED_ACTIONS:
raise ManifestValidationError(
f"Prohibited deployment action '{act_str}'. Allowed: {sorted(ALLOWED_ACTIONS)}"
)
actions.append(act_str)
if not actions:
return ["compose_up"]
return actions
return ["compose_up"]
def to_dict(self) -> dict[str, Any]:
return asdict(self)
return self.model_dump(mode="python")
@dataclass
class HomepageConfig:
class HomepageConfig(BaseModel):
"""Dashboard card metadata for Homepage."""
model_config = ConfigDict(extra="forbid")
title: str
group: str = "Applications"
icon: str = "default.png"
container: str = ""
weight: int = 50
@field_validator("weight", mode="before")
@classmethod
def normalize_weight(cls, v: Any) -> int:
try:
return int(v)
except (ValueError, TypeError):
return 50
def to_dict(self) -> dict[str, Any]:
return asdict(self)
return self.model_dump(mode="python")
@dataclass
class Manifest:
class Manifest(BaseModel):
"""
Authoritative Workload Manifest Model (Schema v1.0).
Represents the full contract declared in a workload's app.yaml.
"""
model_config = ConfigDict(extra="forbid", populate_by_name=True)
name: str
schema_version: str = "1.0"
schema_version: str = Field(default="1.0", alias="schemaVersion")
domain: str = ""
description: str = ""
aliases: list[str] = field(default_factory=list)
aliases: list[str] = Field(default_factory=list)
visible: bool = True
auth: bool = True
networks: list[str] = field(default_factory=lambda: ["proxy-net"])
env: dict[str, Any] = field(default_factory=dict)
deployment: DeploymentConfig = field(default_factory=DeploymentConfig)
networks: list[str] = Field(default_factory=lambda: ["proxy-net"])
env: dict[str, str] = Field(default_factory=dict)
deployment: DeploymentConfig = Field(default_factory=DeploymentConfig)
source: SourceConfig | None = None
homepage: HomepageConfig | None = None
@model_validator(mode="before")
@classmethod
def prepare_manifest(cls, data: Any) -> Any:
if isinstance(data, dict):
raw_name = data.get("name")
if raw_name is None or not isinstance(raw_name, str) or not raw_name.strip():
raise ManifestValidationError("Manifest is missing mandatory string field 'name'.")
clean_name = raw_name.strip()
if not NAME_RE.match(clean_name):
raise ManifestValidationError(
f"Invalid workload name '{clean_name}'. Must be alphanumeric with optional '.' '_' '-', starting with alphanumeric."
)
data["name"] = clean_name
# Source: treat empty dict or missing url as None
src = data.get("source")
if isinstance(src, dict) and not src.get("url"):
data["source"] = None
# Homepage default propagation
hp = data.get("homepage")
if isinstance(hp, dict):
hp.setdefault("title", clean_name)
hp.setdefault("container", clean_name)
return data
@field_validator("visible", "auth", mode="before")
@classmethod
def cast_bool(cls, v: Any) -> bool:
if v is None:
return True
return bool(v)
@field_validator("aliases", mode="before")
@classmethod
def normalize_aliases(cls, v: Any) -> list[str]:
if isinstance(v, str):
return [v.strip()] if v.strip() else []
if isinstance(v, list):
return [str(a).strip() for a in v if isinstance(a, str) and str(a).strip()]
return []
@field_validator("networks", mode="before")
@classmethod
def normalize_networks(cls, v: Any) -> list[str]:
if isinstance(v, list):
clean = [str(n).strip() for n in v if str(n).strip()]
if clean:
return clean
return ["proxy-net"]
@field_validator("env", mode="before")
@classmethod
def validate_env(cls, v: Any) -> dict[str, str]:
if not isinstance(v, dict):
return {}
env: dict[str, str] = {}
for raw_k, raw_v in v.items():
k_str = str(raw_k).strip()
if not ENV_KEY_RE.match(k_str) or k_str in RESERVED_ENV_KEYS:
raise ManifestValidationError(
f"Invalid or reserved environment variable key '{k_str}'. "
f"Keys must match ^[a-zA-Z_][a-zA-Z0-9_]*$ and cannot be reserved."
)
env[k_str] = str(raw_v) if raw_v is not None else ""
return env
@property
def is_class_a(self) -> bool:
"""Class A: Source-backed workload requiring upstream repository checkout & build."""
@@ -277,141 +419,22 @@ def parse_manifest(raw_input: str | Path | dict[str, Any]) -> Manifest:
if not isinstance(data, dict):
raise ManifestValidationError("Manifest root must be a YAML dictionary mapping.")
# 1. Name validation
raw_name = data.get("name")
if not raw_name or not isinstance(raw_name, str):
raise ManifestValidationError("Manifest is missing mandatory string field 'name'.")
name = raw_name.strip()
if not NAME_RE.match(name):
raise ManifestValidationError(
f"Invalid workload name '{name}'. Must be alphanumeric with optional '.' '_' '-', starting with alphanumeric."
)
# 2. Schema Version
schema_version = str(data.get("schemaVersion", "1.0")).strip()
# 3. Domain & Description
domain = str(data.get("domain", "")).strip()
description = str(data.get("description", "")).strip()
# 4. Aliases
aliases_raw = data.get("aliases", [])
aliases: list[str] = []
if isinstance(aliases_raw, str):
aliases = [aliases_raw.strip()]
elif isinstance(aliases_raw, list):
for a in aliases_raw:
if isinstance(a, str) and a.strip():
aliases.append(a.strip())
# 5. Flags (visible, auth)
visible = bool(data.get("visible", True))
auth = bool(data.get("auth", True))
# 6. Networks
networks_raw = data.get("networks", ["proxy-net"])
networks: list[str] = []
if isinstance(networks_raw, list):
networks = [str(n).strip() for n in networks_raw if str(n).strip()]
if not networks:
networks = ["proxy-net"]
# 7. Environment overrides
env_raw = data.get("env", {})
env: dict[str, str] = {}
if isinstance(env_raw, dict):
for raw_k, raw_v in env_raw.items():
k_str = str(raw_k).strip()
if not ENV_KEY_RE.match(k_str) or k_str in RESERVED_ENV_KEYS:
raise ManifestValidationError(
f"Invalid or reserved environment variable key '{k_str}'. "
f"Keys must match ^[a-zA-Z_][a-zA-Z0-9_]*$ and cannot be reserved."
)
env[k_str] = str(raw_v) if raw_v is not None else ""
# 8. Deployment Policy
deployment_raw = data.get("deployment")
deployment = DeploymentConfig()
if isinstance(deployment_raw, dict):
strategy = str(deployment_raw.get("strategy", "compose")).strip().lower()
if strategy not in ALLOWED_STRATEGIES:
raise ManifestValidationError(
f"Unsupported deployment strategy '{strategy}'. Allowed: {sorted(ALLOWED_STRATEGIES)}"
)
branch = str(deployment_raw.get("branch", "main")).strip()
actions_raw = deployment_raw.get("actions", ["compose_up"])
actions: list[str] = []
if isinstance(actions_raw, list):
for act in actions_raw:
act_str = str(act).strip().lower()
if act_str not in ALLOWED_ACTIONS:
raise ManifestValidationError(
f"Prohibited deployment action '{act_str}'. Allowed: {sorted(ALLOWED_ACTIONS)}"
)
actions.append(act_str)
if not actions:
actions = ["compose_up"]
deployment = DeploymentConfig(strategy=strategy, branch=branch, actions=actions)
# 9. Source Provenance (Class A vs Class B)
source_raw = data.get("source")
source: SourceConfig | None = None
if isinstance(source_raw, dict) and source_raw.get("url"):
raw_url = str(source_raw.get("url", "")).strip()
transport, validated_url = validate_transport(raw_url)
raw_ref = str(source_raw.get("ref", "main")).strip()
ref_type, clean_ref = classify_ref(raw_ref)
src_type = str(source_raw.get("type", "git")).strip().lower()
if src_type != "git":
raise ManifestValidationError(f"Unsupported source type '{src_type}'. Only 'git' is supported.")
source = SourceConfig(
url=validated_url,
ref=clean_ref,
type=src_type,
ref_type=ref_type,
transport=transport,
)
# 10. Homepage configuration
homepage_raw = data.get("homepage")
homepage: HomepageConfig | None = None
if isinstance(homepage_raw, dict):
title = str(homepage_raw.get("title", name)).strip()
group = str(homepage_raw.get("group", "Applications")).strip()
icon = str(homepage_raw.get("icon", "default.png")).strip()
container = str(homepage_raw.get("container", name)).strip()
try:
weight = int(homepage_raw.get("weight", 50))
except (ValueError, TypeError):
weight = 50
homepage = HomepageConfig(
title=title,
group=group,
icon=icon,
container=container,
weight=weight,
)
return Manifest(
name=name,
schema_version=schema_version,
domain=domain,
description=description,
aliases=aliases,
visible=visible,
auth=auth,
networks=networks,
env=env,
deployment=deployment,
source=source,
homepage=homepage,
)
return Manifest.model_validate(data)
except ValidationError as e:
for err in e.errors():
ctx = err.get("ctx", {})
orig_err = ctx.get("error")
if isinstance(orig_err, ManifestValidationError):
raise orig_err from e
first_error = e.errors()[0]
msg = first_error.get("msg", str(e))
if msg.startswith("Value error, "):
msg = msg.removeprefix("Value error, ")
loc = ".".join(str(p) for p in first_error.get("loc", []))
if loc and first_error.get("type") == "extra_forbidden":
raise ManifestValidationError(f"Manifest contains unrecognized or forbidden field '{loc}'.") from e
raise ManifestValidationError(msg) from e
def _parse_yaml_basic(content: str) -> dict[str, Any]:
+48 -3
View File
@@ -370,11 +370,41 @@ def validate_compose_security(
return False, f"Service '{svc_name}' specifies prohibited host device mount: {devices}."
sec_opts = svc.get("security_opt", [])
if isinstance(sec_opts, str):
sec_opts = [sec_opts]
if isinstance(sec_opts, list):
for opt in sec_opts:
if any(bad in str(opt).lower() for bad in ("unconfined", "disable")):
return False, f"Service '{svc_name}' specifies prohibited security_opt: {opt}."
raw_env_files = svc.get("env_file")
if raw_env_files:
env_file_list: list[str] = []
if isinstance(raw_env_files, str):
env_file_list = [raw_env_files]
elif isinstance(raw_env_files, list):
for item in raw_env_files:
if isinstance(item, str):
env_file_list.append(item)
elif isinstance(item, dict) and "path" in item:
env_file_list.append(str(item["path"]))
elif isinstance(raw_env_files, dict) and "path" in raw_env_files:
env_file_list = [str(raw_env_files["path"])]
for env_path in env_file_list:
clean_env = env_path.strip()
if not clean_env:
continue
if clean_env.startswith("~"):
resolved_env = Path(clean_env).expanduser().resolve()
elif Path(clean_env).is_absolute():
resolved_env = Path(clean_env).resolve()
else:
resolved_env = (allowed_root / clean_env).resolve()
if not (allowed_root.is_dir() and resolved_env.is_relative_to(canonical_allowed_root)):
return False, f"Service '{svc_name}' specifies prohibited env_file escaping workload root: '{clean_env}'."
for ns_key in ("network_mode", "pid", "ipc", "uts", "userns_mode"):
val = str(svc.get(ns_key, "")).strip().lower()
if val in PROHIBITED_HOST_NAMESPACES:
@@ -403,6 +433,10 @@ def validate_compose_security(
if host_path in top_volumes and not (host_path.startswith((".", "/", "~")) or "/" in host_path or "\\" in host_path):
continue
# Undeclared named volumes or bare identifiers not starting with ., /, ~ or containing / are prohibited
if not (host_path.startswith((".", "/", "~")) or "/" in host_path or "\\" in host_path):
return False, f"Service '{svc_name}' specifies undeclared named volume or ambiguous path: '{host_path}'."
# Host bind mount evaluation
if host_path.startswith("~"):
expanded = Path(host_path).expanduser().resolve()
@@ -465,6 +499,14 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
logger.info(f"Skipping deployment: pushed branch '{branch}' != target branch '{expected_branch}'")
return True
canonical_app_name = target_dir.name.removeprefix("homelab-")
manifest_file = target_dir / "app.yaml"
if manifest_file.is_file():
with contextlib.suppress(Exception):
pre_manifest = (yaml.safe_load(manifest_file.read_text(encoding="utf-8")) if yaml else parse_yaml_simple(manifest_file.read_text(encoding="utf-8"))) or {}
if isinstance(pre_manifest, dict) and pre_manifest.get("name"):
canonical_app_name = str(pre_manifest["name"]).strip()
logger.info(f"🚀 Deploying '{target_dir.name}' at {target_dir} (branch: {expected_branch})...")
actions = deployment_config.get("actions", ["git_pull"])
@@ -495,6 +537,9 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
logger.error(f"❌ Post-pull manifest validation failed for '{target_dir.name}': {err_msg}")
return False
if isinstance(fresh_manifest, dict) and fresh_manifest.get("name"):
canonical_app_name = str(fresh_manifest["name"]).strip()
fresh_config = fresh_manifest.get("deployment")
if isinstance(fresh_config, dict):
fresh_branch = fresh_config.get("branch", "main")
@@ -514,7 +559,7 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
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)
valid_sec, sec_err = validate_compose_security(compose_file, target_dir, app_name=canonical_app_name)
if not valid_sec:
logger.error(f"❌ Compose security validation failed for '{target_dir.name}': {sec_err}")
return False
@@ -528,7 +573,7 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
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)
valid_sec, sec_err = validate_compose_security(compose_file, target_dir, app_name=canonical_app_name)
if not valid_sec:
logger.error(f"❌ Compose security validation failed for '{target_dir.name}': {sec_err}")
return False
@@ -546,7 +591,7 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
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)
valid_sec, sec_err = validate_compose_security(compose_file, target_dir, app_name=canonical_app_name)
if not valid_sec:
logger.error(f"❌ Compose security validation failed for '{target_dir.name}': {sec_err}")
return False
+73
View File
@@ -896,6 +896,79 @@ def test_validate_compose_security_rejects_symlink_escape(tmp_path: Path):
assert err is not None and "symlink" in err.lower()
def test_validate_compose_security_rejects_escaping_env_file(tmp_path: Path):
"""Ensure services cannot use env_file to read secrets outside the workload root."""
app_dir = tmp_path / "my-app"
app_dir.mkdir(parents=True)
(app_dir / "valid.env").write_text("A=1\n", encoding="utf-8")
# 1. Escaping absolute path
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text("""
services:
app:
image: alpine
env_file: /run/secrets/homeserver.env
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
assert valid is False
assert err is not None and "env_file" in err.lower()
# 2. Escaping relative path in list
compose_file.write_text("""
services:
app:
image: alpine
env_file:
- valid.env
- ../../Core/.env
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
assert valid is False
assert err is not None and "env_file" in err.lower()
# 3. Valid local env_file
compose_file.write_text("""
services:
app:
image: alpine
env_file: valid.env
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir, app_name="my-app")
assert valid is True
assert err is None
def test_validate_compose_security_rejects_undeclared_named_volumes(tmp_path: Path):
"""Ensure ambiguous volume paths not declared in top-level volumes are rejected."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text("""
services:
app:
image: alpine
volumes:
- rogue_named_volume:/data
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="my-app")
assert valid is False
assert err is not None and "undeclared" in err.lower()
def test_validate_compose_security_handles_string_security_opt(tmp_path: Path):
"""Ensure security_opt specified as string instead of list is strictly checked."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text("""
services:
app:
image: alpine
security_opt: "apparmor:unconfined"
""", encoding="utf-8")
valid, err = gitops_dispatcher.validate_compose_security(compose_file, tmp_path, app_name="my-app")
assert valid is False
assert err is not None and "security_opt" in err.lower()
+84 -40
View File
@@ -2,6 +2,10 @@
Security invariant tests for Docker Compose and container isolation.
"""
import os
import shutil
import subprocess
import sys
from pathlib import Path
import yaml
@@ -10,6 +14,7 @@ CORE_ROOT = Path(__file__).resolve().parent.parent.parent
def test_socket_proxy_is_strictly_read_only():
"""Ensure socket-proxy container blocks state-modifying requests (POST=0, DELETE=0)."""
compose_path = CORE_ROOT / "docker-compose.yml"
with open(compose_path, encoding="utf-8") as f:
@@ -87,58 +92,97 @@ def test_no_eval_in_appctl_script():
def test_appctl_env_injection_resilience(tmp_path: Path):
"""Ensure environment values from app.yaml cannot execute shell commands via command substitution."""
"""Ensure environment values from app.yaml cannot execute shell commands via command substitution
in scripts/appctl during environment setup. Executes scripts/appctl directly with a mock docker binary.
"""
canary = tmp_path / "pwned.txt"
payload = f"$(touch {canary})"
import json
import subprocess
# 1. Setup mock Sites directory with vulnerable app.yaml and docker-compose.yml
sites_dir = tmp_path / "Sites"
app_dir = sites_dir / "vuln-app"
app_dir.mkdir(parents=True)
appctl_path = CORE_ROOT / "scripts" / "appctl"
appctl_content = appctl_path.read_text(encoding="utf-8")
assert "eval " not in appctl_content
assert "while IFS= read -r -d '' k && IFS= read -r -d '' v; do" in appctl_content
resolved_json = json.dumps({
"name": "test-app",
"domain": "test.roadtotech.me",
"dir_path": str(tmp_path),
"env": {"INJECTION_TEST": payload, "NORMAL_VAR": "safe_value"},
})
bash_code = f"""
set -euo pipefail
resolved_json='{resolved_json}'
while IFS= read -r -d '' k && IFS= read -r -d '' v; do
export "$k=$v"
done < <(python3 -c "
import json, re, sys
RESERVED = {{'PATH', 'LD_PRELOAD', 'IFS', 'SHELL', 'USER', 'CORE_DIR', 'SITES_DIR', 'ENV_FILE', 'HOMESERVER_ENV'}}
d = json.loads(sys.argv[1])
env_dict = d.get('env', {{}})
if isinstance(env_dict, dict):
for k, v in env_dict.items():
k_str = str(k).strip()
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', k_str) or k_str in RESERVED:
continue
if v is not None and v != '':
sys.stdout.buffer.write(k_str.encode('utf-8') + b'\\0' + str(v).encode('utf-8') + b'\\0')
" "$resolved_json")
echo "INJECTION_TEST=$INJECTION_TEST"
echo "NORMAL_VAR=$NORMAL_VAR"
app_yaml = f"""
name: vuln-app
domain: vuln.example.test
env:
INJECTION_TEST: '{payload}'
NORMAL_VAR: 'safe_value'
"""
(app_dir / "app.yaml").write_text(app_yaml.strip(), encoding="utf-8")
(app_dir / "docker-compose.yml").write_text("services:\n web:\n image: nginx\n", encoding="utf-8")
# 2. Setup mock docker binary to capture environment without requiring a running Docker daemon
mock_bin = tmp_path / "bin"
mock_bin.mkdir()
mock_docker = mock_bin / "docker"
bash_bin = shutil.which("bash") or "bash"
mock_docker_script = f"""#!{bash_bin}
if [ "$1" = "compose" ] && [ "$2" = "config" ]; then
echo "MOCK_DOCKER_COMPOSE_CONFIG"
echo "CAPTURED_INJECTION=$INJECTION_TEST"
echo "CAPTURED_NORMAL=$NORMAL_VAR"
exit 0
fi
exit 0
"""
mock_docker.write_text(mock_docker_script, encoding="utf-8")
mock_docker.chmod(0o755)
# 3. Execute scripts/appctl config vuln-app directly
appctl_path = CORE_ROOT / "scripts" / "appctl"
env = os.environ.copy()
if "NIX_PYTHONPATH" in env and "PYTHONPATH" not in env:
env["PYTHONPATH"] = env["NIX_PYTHONPATH"]
env["PATH"] = f"{mock_bin}:{Path(sys.executable).parent}:{env['PATH']}"
env["PYTHON_BIN"] = sys.executable
env["SITES_DIR"] = str(sites_dir)
env["HOMELAB_DOMAIN"] = "example.test"
env["CORE_DIR"] = str(CORE_ROOT)
res = subprocess.run(
["bash", "-c", bash_code],
[bash_bin, str(appctl_path), "config", "vuln-app"],
env=env,
capture_output=True,
text=True,
check=False,
)
# 4. Assertions: command substitution was not executed, script ran, and mock docker received literal value
assert not canary.exists(), "Command substitution was executed on the host during environment setup!"
assert res.returncode == 0, f"Extraction failed: {res.stderr}"
assert f"INJECTION_TEST={payload}" in res.stdout
assert "NORMAL_VAR=safe_value" in res.stdout
assert res.returncode == 0, f"appctl config failed: {res.stderr}\nStdout: {res.stdout}"
assert "MOCK_DOCKER_COMPOSE_CONFIG" in res.stdout
assert f"CAPTURED_INJECTION={payload}" in res.stdout
assert "CAPTURED_NORMAL=safe_value" in res.stdout
assert "/dangerous/override" not in res.stdout
def test_platform_genericism_no_hardcoded_personal_domains_in_scripts_and_tests():
"""Ensure personal domains and operator usernames are absent from scripts and test files."""
forbidden = ["roadtotech.me", "kiskaadee"]
root_dirs = [CORE_ROOT / "scripts", CORE_ROOT / "tests"]
violations = []
for root_dir in root_dirs:
for file_path in root_dir.rglob("*"):
if (
file_path.is_file()
and file_path.suffix in (".py", ".sh", ".bash", ".yml", ".yaml", "")
and file_path.name != "test_security_invariants.py"
):
content = file_path.read_text(encoding="utf-8", errors="ignore")
for term in forbidden:
if term in content:
violations.append(f"{file_path.relative_to(CORE_ROOT)}: contains prohibited literal '{term}'")
assert not violations, "Platform genericism violations detected:\n" + "\n".join(violations)
+11 -11
View File
@@ -101,7 +101,7 @@ def test_sites_app_normalization(app_factory: AppFactory):
dir_name="homelab-custom",
manifest_yaml="""
name: testapp
# Missing domain - should fallback to <name>.roadtotech.me
# Missing domain - should fallback to <name>.<HOMELAB_DOMAIN>
aliases: single-string-alias # should become a list[str]
auth: "False" # should evaluate based on boolean casting
homepage:
@@ -129,7 +129,7 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
name: bitetrack
source:
type: git
url: https://git.roadtotech.me/kiskaadee/bitetrack.git
url: https://git.example.com/operator/bitetrack.git
ref: v1.2.0
"""
)
@@ -139,7 +139,7 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
manifest_yaml="""
name: doc2site
source:
url: https://git.roadtotech.me/kiskaadee/doc2site.git
url: https://git.example.com/operator/doc2site.git
"""
)
# 3. Image-only app (no source block)
@@ -156,7 +156,7 @@ def test_sites_app_source_provenance_normalization(app_factory: AppFactory):
assert bitetrack is not None
assert bitetrack.source is not None
assert bitetrack.source.type == "git"
assert bitetrack.source.url == "https://git.roadtotech.me/kiskaadee/bitetrack.git"
assert bitetrack.source.url == "https://git.example.com/operator/bitetrack.git"
assert bitetrack.source.ref == "v1.2.0"
assert bitetrack.to_dict()["source"]["ref"] == "v1.2.0"
@@ -349,8 +349,8 @@ def test_homepage_sync_core_services_domain_isolation(
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")
monkeypatch.setattr(engine, "HOMELAB_DOMAIN", "example.com")
monkeypatch.setenv("DOMAIN", "mermaid.example.com")
engine.cmd_sync_homepage(["--homepage-dir=" + str(hp_config_dir)])
@@ -358,10 +358,10 @@ def test_homepage_sync_core_services_domain_isolation(
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
assert "https://dashboard.example.com" in content
assert "https://traefik.example.com" in content
assert "https://auth.example.com" in content
assert "mermaid.example.com" not in content
def test_resolve_core_stack_type():
@@ -433,7 +433,7 @@ def test_unification_uses_core_manifest_dataclasses(app_factory: AppFactory):
manifest_yaml="""
name: unified
source:
url: https://git.roadtotech.me/kiskaadee/unified.git
url: https://git.example.com/operator/unified.git
ref: v1.0.0
homepage:
title: Unified App
+57 -13
View File
@@ -12,6 +12,7 @@ CORE_ROOT = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(CORE_ROOT / "scripts"))
from core_manifest import (
Manifest,
ManifestValidationError,
RefType,
TransportScheme,
@@ -22,25 +23,26 @@ from core_manifest import (
def test_validate_transport_https():
scheme, url = validate_transport("https://gitea.roadtotech.me/kiskaadee/homelab-snappymail.git")
scheme, url = validate_transport("https://git.example.com/operator/homelab-snappymail.git")
assert scheme == TransportScheme.HTTPS
assert url == "https://gitea.roadtotech.me/kiskaadee/homelab-snappymail.git"
assert url == "https://git.example.com/operator/homelab-snappymail.git"
def test_validate_transport_ssh():
scheme, url = validate_transport("ssh://git@gitea.roadtotech.me:2223/kiskaadee/homelab-docs.git")
scheme, url = validate_transport("ssh://git@git.example.com:2223/operator/homelab-docs.git")
assert scheme == TransportScheme.SSH
assert url == "ssh://git@gitea.roadtotech.me:2223/kiskaadee/homelab-docs.git"
assert url == "ssh://git@git.example.com:2223/operator/homelab-docs.git"
def test_validate_transport_git_scp():
scheme, url = validate_transport("git@github.com:kiskaadee/custom-workload.git")
scheme, url = validate_transport("git@github.com:operator/custom-workload.git")
assert scheme == TransportScheme.GIT_SCP
assert url == "git@github.com:kiskaadee/custom-workload.git"
assert url == "git@github.com:operator/custom-workload.git"
@pytest.mark.parametrize("insecure_url", [
"http://insecure.roadtotech.me/repo.git",
"http://insecure.example.com/repo.git",
"http://github.com/repo.git",
])
def test_validate_transport_rejects_http(insecure_url: str):
@@ -50,7 +52,7 @@ def test_validate_transport_rejects_http(insecure_url: str):
@pytest.mark.parametrize("traversal_url", [
"../../etc/shadow",
"/home/kiskaadee/secret",
"/home/operator/secret",
"~/vault",
"file:///etc/passwd",
])
@@ -83,7 +85,7 @@ schemaVersion: "1.0"
name: "bitetrack"
aliases:
- "bt"
domain: "bitetrack.roadtotech.me"
domain: "bitetrack.example.com"
description: "Nutrition and macro tracking application"
visible: true
auth: true
@@ -93,7 +95,7 @@ env:
PORT: 8080
source:
type: git
url: "https://git.roadtotech.me/kiskaadee/bitetrack.git"
url: "https://git.example.com/operator/bitetrack.git"
ref: "v1.2.0"
deployment:
strategy: compose
@@ -116,7 +118,7 @@ homepage:
assert manifest.is_class_b is False
assert manifest.is_internal is False
assert manifest.source is not None
assert manifest.source.url == "https://git.roadtotech.me/kiskaadee/bitetrack.git"
assert manifest.source.url == "https://git.example.com/operator/bitetrack.git"
assert manifest.source.ref == "v1.2.0"
assert manifest.source.ref_type == RefType.TAG
assert manifest.source.transport == TransportScheme.HTTPS
@@ -128,7 +130,7 @@ homepage:
def test_parse_manifest_class_b_image_only():
raw_yaml = """
name: "snappymail"
domain: "mail.roadtotech.me"
domain: "mail.example.com"
description: "Webmail Client"
deployment:
actions:
@@ -144,7 +146,7 @@ deployment:
def test_parse_manifest_rejects_missing_name():
with pytest.raises(ManifestValidationError, match="missing mandatory string field 'name'"):
parse_manifest("domain: test.roadtotech.me\n")
parse_manifest("domain: test.example.com\n")
def test_parse_manifest_rejects_invalid_name():
@@ -217,3 +219,45 @@ env:
assert manifest.env["CUSTOM_PORT_1"] == "8080"
assert manifest.env["_INTERNAL_FLAG"] == "true"
def test_parse_manifest_rejects_extra_fields():
"""Ensure extra='forbid' rejects unrecognized top-level manifest keys."""
raw_yaml = """
name: "app"
unrecognized_field: "should_fail"
"""
with pytest.raises(ManifestValidationError, match="unrecognized or forbidden field"):
parse_manifest(raw_yaml)
def test_parse_manifest_rejects_extra_fields_in_nested_blocks():
"""Ensure extra='forbid' rejects unrecognized keys in nested configuration blocks."""
raw_yaml = """
name: "app"
deployment:
strategy: compose
unknown_deploy_option: "forbidden"
"""
with pytest.raises(ManifestValidationError):
parse_manifest(raw_yaml)
def test_manifest_pydantic_serialization():
"""Ensure Manifest operates as a Pydantic v2 model with correct serialization."""
from pydantic import BaseModel
raw_yaml = """
name: "serialized-app"
domain: "app.example.test"
description: "Pydantic serialization test"
"""
manifest = parse_manifest(raw_yaml)
assert isinstance(manifest, Manifest)
assert isinstance(manifest, BaseModel)
dumped = manifest.model_dump(by_alias=True)
assert dumped["name"] == "serialized-app"
assert dumped["schemaVersion"] == "1.0"
assert manifest.to_dict()["name"] == "serialized-app"
+3 -3
View File
@@ -85,7 +85,7 @@ def test_resolve_upstream_provenance_image_only():
def test_resolve_upstream_provenance_synced():
source = SourceConfig(
url="https://git.roadtotech.me/kiskaadee/app.git",
url="https://git.example.com/operator/app.git",
ref="main",
ref_type=RefType.BRANCH,
transport=TransportScheme.HTTPS,
@@ -106,7 +106,7 @@ def test_resolve_upstream_provenance_synced():
def test_resolve_upstream_provenance_update_available():
source = SourceConfig(
url="https://git.roadtotech.me/kiskaadee/app.git",
url="https://git.example.com/operator/app.git",
ref="main",
ref_type=RefType.BRANCH,
transport=TransportScheme.HTTPS,
@@ -157,7 +157,7 @@ def test_resolve_upstream_provenance_unreachable():
def test_resolve_upstream_provenance_pinned_commit():
sha = "1234567890abcdef1234567890abcdef12345678"
source = SourceConfig(
url="https://git.roadtotech.me/app.git",
url="https://git.example.com/app.git",
ref=sha,
ref_type=RefType.COMMIT,
transport=TransportScheme.HTTPS,
+8 -4
View File
@@ -13,17 +13,21 @@ x 2026-10-13 (B) Define append-only audit telemetry schema, lifecycle, and failu
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
x 2026-10-14 (A) Eliminate eval in scripts/appctl and enforce strict env key validation in scripts/core_manifest.py +security @appctl
x 2026-10-15 (A) Enforce deployments.yaml as sole registry and remove dynamic discovery fallback in scripts/gitops_dispatcher.py +registry @gitops
x 2026-10-15 (A) Harden validate_compose_security in scripts/gitops_dispatcher.py blocking relative traversal, cross-tenant mounts, and privilege escalation +compose @gitops
x 2026-10-15 (A) Unify manifest parsing on core_manifest.py and eliminate duplicate parsers in scripts/appctl_engine.py +manifest @engine
x 2026-10-15 (A) Codify Platform Genericism invariant in AGENTS.md and add Pydantic to flake.nix, pyproject.toml, and scripts/test +invariant @core
(A) Migrate core_manifest.py to Pydantic v2 models for strict type validation and serialization +manifest @schema
x 2026-10-15 (A) Add pydantic to host NixOS runtime and constrain dependency range in flake.nix and nixos/configuration.nix +nixos @core
x 2026-10-15 (A) Wire app_name and harden compose validator for env_file and undeclared volumes in scripts/gitops_dispatcher.py +compose @gitops
x 2026-10-15 (B) Scrub hardcoded domain defaults across scripts and tests enforcing instance-agnostic parameterization +generic @core
x 2026-10-15 (A) De-tautologize appctl env injection test to execute scripts/appctl directly with mock docker in tests/security/test_security_invariants.py +test @security
x 2026-10-15 (A) Clarify Pydantic v2 target architecture, strict typing rules, and domain precedence in docs/plans/p4-readiness-plan.md +docs @p4-gate
x 2026-10-15 (A) Migrate core_manifest.py to Pydantic v2 models for strict type validation and serialization +manifest @schema
(A) Scaffold asyncio daemon server with Pydantic request/response models supporting dual transports in scripts/appctl_daemon.py +daemon @p4
(A) Implement unit and integration tests for dual-transport requests and error handling in tests/unit/test_appctl_daemon.py +test @p4
(B) Implement command-oriented operational router wiring domain actions to in-process appctl_engine.py methods and fixed subprocess executions +router @p4
(B) Scrub hardcoded domain defaults across scripts and tests enforcing instance-agnostic parameterization +generic @core
(B) Implement token authentication middleware validating user-scoped Bearer tokens for mutating requests +auth @p4
(B) Implement append-only audit logger writing structured RFC JSONL records with fail-closed disk guard +audit @p4
(B) Scrub remaining hardcoded domain references across NixOS modules, Compose stack, and repository documentation +generic @core
(C) Re-implement scripts/appctl as a thin client dispatching JSON requests to the daemon Unix domain socket +cli @p4
(C) Create NixOS systemd unit module for homelab-appctl.service with strict sandboxing and socket management +nixos @p4
Generated
+1 -1
View File
@@ -22,7 +22,7 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "pydantic", specifier = ">=2.0" },
{ name = "pydantic", specifier = ">=2.0,<3.0" },
{ name = "pyyaml", specifier = ">=6.0" },
]