Compare commits

...
4 Commits
Author SHA1 Message Date
kiskaadee cdd2d562c3 feat(gitops): support canopy-workloads monorepo dispatch and remote build URLs (#33)
Core Architecture & Invariant CI / validate (push) Successful in 1m15s
Core Architecture & Invariant CI / validate (pull_request) Successful in 1m10s
- Add is_monorepo_push, extract_monorepo_changed_subdirs, and dispatch_monorepo_push in gitops_dispatcher.py to pull ~/Workloads once under lock and dispatch only affected admitted deployments.yaml subdirectories
- Add build context validation in validate_compose_security() permitting remote Git/HTTP URLs (https://, http://, ssh://, git@, git://), enforcing allowed_root containment on local build contexts, and rejecting ${...} variable interpolation
- Add security tests in test_gitops_security.py for remote build URLs, unsafe build context escapes/interpolation, and monorepo webhook dispatch
2026-11-16 14:08:07 -05:00
kiskaadee 2df95648d4 feat(provenance,router): support hybrid ~/Workloads monorepo subpath inspection and git pull (#33)
- Update provenance.get_local_checkout_status to check <workload_dir>/.git first and fall back to <parent>/.git with subpath-scoped git status --porcelain -- <app>/
- Update OperationalRouter._op_workload_update via _resolve_git_context to target parent monorepo .git for status, pull --ff-only, and rev-parse when <app>/.git is absent
- Add real git init tests in test_provenance.py for monorepo subpath dirty-state isolation and standalone <app>/.git precedence
- Add router unit test in test_appctl_router.py verifying monorepo git pull and subpath status checks during workload.update
2026-11-16 14:03:59 -05:00
kiskaadee 9d7114b547 feat(nixos,core): transition ~/Sites default to ~/Workloads with WORKLOADS_DIR env support (#33)
- Update nixos/modules/homeserver.nix default homelab.sitesDir to ~/Workloads and export both WORKLOADS_DIR and SITES_DIR
- Add ~/Workloads and ~/Workloads/* to programs.git.config.safe.directory in nixos/configuration.nix while retaining ~/Sites/* for transition
- Update all workload paths in config/deployments.yaml from ~/Sites/<app> to ~/Workloads/<app>
- Update appctl_engine.py, appctl_daemon.py, and gitops_dispatcher.py to honor WORKLOADS_DIR -> SITES_DIR -> ~/Workloads and resolve both ~/Workloads/ and ~/Sites/ prefixes in deployments.yaml
- Add TDD security and unit tests covering NixOS defaults, git safe.directory, tilde prefix resolution, and WORKLOADS_DIR env precedence
2026-11-16 14:00:45 -05:00
kiskaadee 9ac44d0baa docs(adr): add ADR-0004 for unified ~/Workloads monorepo and state isolation (#33)
- Author MADR 4.0 ADR-0004 amending ADR-0001 to adopt the unified ~/Workloads Tier 2 monorepo (canopy-workloads), rename ~/Sites to ~/Workloads with WORKLOADS_DIR -> SITES_DIR fallback, and enforce ~/var/lib/homelab/<app>/ state isolation
- Register ADR-0004 in docs/decisions/README.md active decisions table and summaries
2026-11-16 13:57:54 -05:00
15 changed files with 840 additions and 35 deletions

No files matched your search

+10 -10
View File
@@ -1,48 +1,48 @@
# Core Authoritative Repository Identity Registry # Core Authoritative Repository Identity Registry
# Governs admitted continuous deployment targets for GitOps webhook execution. # Governs admitted continuous deployment targets for GitOps webhook execution.
# Owns: repository identity, canonical filesystem path, and aliases. # Owns: repository identity, canonical filesystem path, and aliases.
# Enforces: strict path containment within ~/Sites. # Enforces: strict path containment within ~/Workloads.
schemaVersion: "1.0" schemaVersion: "1.0"
repositories: repositories:
snappymail: snappymail:
path: "~/Sites/snappymail" path: "~/Workloads/snappymail"
aliases: aliases:
- "homelab-snappymail" - "homelab-snappymail"
- "mail" - "mail"
- "webmail" - "webmail"
gitea: gitea:
path: "~/Sites/homelab-gitea" path: "~/Workloads/homelab-gitea"
aliases: aliases:
- "homelab-gitea" - "homelab-gitea"
- "git" - "git"
jellyfin: jellyfin:
path: "~/Sites/homelab-jellyfin" path: "~/Workloads/homelab-jellyfin"
aliases: aliases:
- "homelab-jellyfin" - "homelab-jellyfin"
- "media" - "media"
courses: courses:
path: "~/Sites/courses" path: "~/Workloads/courses"
aliases: aliases:
- "homelab-courses" - "homelab-courses"
bdinvite: bdinvite:
path: "~/Sites/homelab-bdinvite" path: "~/Workloads/homelab-bdinvite"
aliases: aliases:
- "homelab-bdinvite" - "homelab-bdinvite"
- "birthday" - "birthday"
landing: landing:
path: "~/Sites/homelab-landing" path: "~/Workloads/homelab-landing"
aliases: aliases:
- "homelab-landing" - "homelab-landing"
mermaid: mermaid:
path: "~/Sites/homelab-mermaid" path: "~/Workloads/homelab-mermaid"
aliases: aliases:
- "homelab-mermaid" - "homelab-mermaid"
excalidraw: excalidraw:
path: "~/Sites/homelab-excalidraw" path: "~/Workloads/homelab-excalidraw"
aliases: aliases:
- "homelab-excalidraw" - "homelab-excalidraw"
houston: houston:
path: "~/Sites/homelab-houston" path: "~/Workloads/homelab-houston"
aliases: aliases:
- "homelab-houston" - "homelab-houston"
@@ -0,0 +1,91 @@
---
type: decision
status: accepted
project: homelab-core
date: 2026-11-16
tags: [architecture, workloads, monorepo, gitops, state, nixos]
amends: 0001-3tier-architecture-and-provenance.md
---
# ADR 0004: Unified ~/Workloads Monorepo & State Isolation
## Context and Problem Statement
Under [ADR-0001](0001-3tier-architecture-and-provenance.md), Tier 2 deployment descriptors (`app.yaml` and `docker-compose.yml`) were hosted in `~/Sites/<app>` as one standalone Git repository per application. In practice, operating a fleet of 9+ Tier 2 workloads (including both Class A source-backed services and Class B off-the-shelf image-only tools) revealed structural friction:
1. **Per-App Repository Sprawl**: Every third-party tool (`jellyfin`, `snappymail`, `excalidraw`, `mermaid`) required its own Gitea repository, webhook configuration, and clone lifecycle just to version 2–3 declarative files.
2. **Naming Coupling (`~/Sites`)**: The directory name `~/Sites` implied web-only sites rather than general self-hosted workloads (mail, media, diagrams, internal tools).
3. **Cross-Workload Drift & Webhook Overhead**: Coordinating shared network, label, or manifest conventions across N separate deployment repositories required N separate commits and N separate Gitea webhook registrations.
4. **State Co-location Risk**: Moving to a unified monorepo increases the blast radius if any workload stores mutable runtime state inside its deployment directory instead of the isolated host state root (`~/var/lib/homelab/<app>/`).
The central architectural question is: **How should Canopy NixOS Core organize Tier 2 deployment descriptors to eliminate per-app repository sprawl while preserving independent per-workload deployment, backward-compatible migration, and strict runtime state isolation?**
## Decision Drivers
* **Eliminate Tier 2 Repository Sprawl**: Consolidate Tier 2 deployment descriptors (`<app>/app.yaml`, `<app>/docker-compose.yml`) into a single unified `canopy-workloads` monorepo at `~/Workloads`.
* **Preserve Per-Workload Independence**: Pushing to `canopy-workloads` must selectively deploy only the workload subdirectories modified in that push, without restarting unaffected services.
* **Zero-Downtime Migration Compatibility**: Support `WORKLOADS_DIR` as the canonical configuration variable with a clean `SITES_DIR` fallback, and support hybrid per-app `.git` checkouts alongside monorepo subdirectories during transition.
* **Strict State Isolation**: Enforce `~/var/lib/homelab/<app>/` as the sole persistent runtime state root so the `~/Workloads` Git working tree remains 100% declarative and clean.
* **Preserve 3-Tier & Security Boundaries**: Keep Tier 1 application source repositories independent, keep Core platform services in `~/Core`, and maintain `deployments.yaml` allowlisting and Compose AST security validation.
## Considered Options
* **Option 1: Keep Per-App Tier 2 Repositories in `~/Sites/<app>` (Status Quo)**: Maintain one Git repository per workload under `~/Sites`.
* **Option 2: Merge Tier 2 Workloads into `~/Core`**: Place all workload `app.yaml` and `docker-compose.yml` files directly inside `canopy-homelab/nixos-core`.
* **Option 3: Unified `~/Workloads` Monorepo (`canopy-workloads`) with Isolated Host State (Adopted)**: Amend ADR-0001 to rename Tier 2 from `~/Sites` to `~/Workloads`, consolidate Tier 2 manifests into `canopy-workloads`, and enforce `~/var/lib/homelab/<app>/` state isolation.
## Decision Outcome
Chosen option: **Option 3: Unified `~/Workloads` Monorepo (`canopy-workloads`) with Isolated Host State**, because it eliminates Tier 2 repository and webhook sprawl while preserving the 3-tier boundary between Tier 1 application source, Tier 2 deployment intent, and Tier 3 NixOS Core platform infrastructure.
### Summary of Architectural Commitments
This ADR formally amends [ADR-0001](0001-3tier-architecture-and-provenance.md) with the following commitments:
1. **Tier 2 Rename (`~/Sites` $\rightarrow$ `~/Workloads`)**:
* The canonical Tier 2 deployment root is `~/Workloads` (configured via `homelab.workloadsDir` / `homelab.sitesDir` in NixOS and `WORKLOADS_DIR` in Core services).
* Core Python modules (`appctl_engine.py`, `appctl_daemon.py`, `appctl_router.py`, `gitops_dispatcher.py`) default to `~/Workloads`, honoring `WORKLOADS_DIR` first and falling back to `SITES_DIR` for backward compatibility.
2. **Unified `canopy-workloads` Monorepo**:
* Tier 2 workloads reside as subdirectories `~/Workloads/<app>/` inside the `canopy-workloads` monorepo, each owning its own `app.yaml` and `docker-compose.yml`.
* During migration, `~/Workloads/<app>` may operate either as a monorepo subdirectory (sharing `~/Workloads/.git`) or as a standalone checkout (`~/Workloads/<app>/.git`).
3. **Mandatory State Isolation (`~/var/lib/homelab/<app>/`)**:
* All mutable application data (databases, caches, uploads, dynamic configs) must reside under `~/var/lib/homelab/<app>/` (or named Docker volumes) and never inside `~/Workloads/<app>/`.
* NixOS `systemd.tmpfiles.rules` provisions `~/Workloads` and `~/var/lib/homelab` with recursive `A+` POSIX ACLs for `homelab-appctl`.
4. **Core Registry & Safe Directory Containment**:
* `config/deployments.yaml` maps admitted workload identities to canonical `~/Workloads/<app>` paths, enforced by strict containment inside `WORKLOADS_DIR`.
* Host Git `safe.directory` configuration includes `~/Workloads` and `~/Workloads/*` (alongside `~/Core`).
## Pros and Cons of the Options
### Option 1: Keep Per-App Tier 2 Repositories in `~/Sites/<app>`
* Good, because each workload has an isolated Git history and independent webhook.
* Bad, because adding or updating a simple third-party service requires creating and maintaining a full Git repository.
* Bad, because fleet-wide manifest or Compose conventions require N separate PRs and commits.
### Option 2: Merge Tier 2 Workloads into `~/Core`
* Good, because only one repository exists for Core and Workloads.
* Bad, because it violates the 3-tier boundary (ADR-0001), mixing NixOS host/platform configuration with application deployment topologies.
* Bad, because `~/Core` changes would trigger NixOS evaluation/rebuild concerns alongside routine app updates.
### Option 3: Unified `~/Workloads` Monorepo (`canopy-workloads`) with Isolated Host State (Adopted)
* Good, because Tier 2 deployment descriptors are managed in one repository with atomic cross-workload changes and a single GitOps webhook.
* Good, because Tier 1 software repositories and Tier 3 NixOS Core remain strictly decoupled.
* Good, because `WORKLOADS_DIR` $\rightarrow$ `SITES_DIR` fallback allows incremental host cutover without breaking existing environments.
* Bad, because GitOps webhook dispatch and provenance inspection must distinguish monorepo-root `.git` from per-app `.git` checkouts (addressed in follow-up slices).
* Bad, because monorepo commits touching multiple subdirectories require changed-path filtering to avoid redeploying unaffected workloads.
## Consequences
### Positive Consequences
* **Single Tier 2 Control Surface**: One `canopy-workloads` repository versions all workload manifests and Compose topologies.
* **Clean Git Working Tree**: Enforcing `~/var/lib/homelab/<app>/` ensures runtime state never dirties the monorepo checkout.
* **Smooth Cutover**: Dual `WORKLOADS_DIR` / `SITES_DIR` environment support and `homelab.sitesDir` NixOS option compatibility prevent abrupt breakage.
### Negative Consequences & Accepted Trade-offs
* **Hybrid Provenance & Subpath Dispatch Complexity**: Core tooling (`provenance.py`, `gitops_dispatcher.py`) must handle both monorepo-level `.git` and legacy per-app `.git` directories, as well as selective changed-directory deployment on monorepo pushes.
## More Information
* **Amended Decision**: [`0001-3tier-architecture-and-provenance.md`](0001-3tier-architecture-and-provenance.md)
* **Architecture Specification**: [`docs/architecture.md`](../architecture.md)
* **Secrets & State Contract**: [`docs/secrets-and-state.md`](../secrets-and-state.md)
+10
View File
@@ -10,6 +10,7 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using
| Decision Record | Status | Date | Scope & One-Line Purpose | | Decision Record | Status | Date | Scope & One-Line Purpose |
| :--- | :--- | :--- | :--- | | :--- | :--- | :--- | :--- |
| [**ADR-0004: Unified ~/Workloads Monorepo & State Isolation**](0004-unified-workloads-monorepo.md) | `accepted` | 2026-11-16 | Amends ADR-0001 to adopt the unified `~/Workloads` Tier 2 monorepo (`canopy-workloads`), rename `~/Sites` to `~/Workloads` with `WORKLOADS_DIR` fallback, and enforce `~/var/lib/homelab/<app>/` state isolation. |
| [**ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2**](0003-pydantic-v2-runtime-validation.md) | `accepted` | 2026-10-15 | Adopts Pydantic v2 as the single runtime schema and validation authority across workload manifests and daemon API to enforce fail-closed type safety, strict schema-based boundaries, and secret-safe serialization. | | [**ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2**](0003-pydantic-v2-runtime-validation.md) | `accepted` | 2026-10-15 | Adopts Pydantic v2 as the single runtime schema and validation authority across workload manifests and daemon API to enforce fail-closed type safety, strict schema-based boundaries, and secret-safe serialization. |
| [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](0002-appctl-control-plane-architecture.md) | `accepted` | 2026-10-07 | Establishes `homelab-appctl.service` as the central operational control plane daemon, one logical command API (`POST /v1/operations`) across dual transports (UDS and HTTP), mandatory token auth with UDS `SO_PEERCRED` viewer fallback, dedicated service isolation, fail-closed audit logging, GitOps worker unification, and deterministic Git-backed declarative deployment state. | | [**ADR-0002: Homelab Operational Control Plane & Deployment Model Architecture**](0002-appctl-control-plane-architecture.md) | `accepted` | 2026-10-07 | Establishes `homelab-appctl.service` as the central operational control plane daemon, one logical command API (`POST /v1/operations`) across dual transports (UDS and HTTP), mandatory token auth with UDS `SO_PEERCRED` viewer fallback, dedicated service isolation, fail-closed audit logging, GitOps worker unification, and deterministic Git-backed declarative deployment state. |
| [**ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model**](0001-3tier-architecture-and-provenance.md) | `accepted` | 2026-09-28 | Establishes 3-tier separation (Software, OCI Artifact, Sites Deployment, Core Platform), two workload classes (Source-Backed vs. Image-Only), isolated state root (`~/var/lib/homelab/<app>/`), and two operational inspection axes. | | [**ADR-0001: Homelab 3-Tier Architecture & Deployment Provenance Model**](0001-3tier-architecture-and-provenance.md) | `accepted` | 2026-09-28 | Establishes 3-tier separation (Software, OCI Artifact, Sites Deployment, Core Platform), two workload classes (Source-Backed vs. Image-Only), isolated state root (`~/var/lib/homelab/<app>/`), and two operational inspection axes. |
@@ -18,6 +19,15 @@ Repository-level architectural decisions are recorded in `docs/decisions/` using
## 🧭 Summaries of Governing Decisions ## 🧭 Summaries of Governing Decisions
### [ADR-0004: Unified ~/Workloads Monorepo & State Isolation](0004-unified-workloads-monorepo.md)
* **Canonical Document**: [`0004-unified-workloads-monorepo.md`](0004-unified-workloads-monorepo.md)
* **Status**: `accepted` (Active — Amends ADR-0001)
* **Core Commitments**:
1. **Tier 2 Rename (`~/Sites` -> `~/Workloads`)**: Canonical Tier 2 deployment root is `~/Workloads`, with `WORKLOADS_DIR` -> `SITES_DIR` environment fallback.
2. **Unified `canopy-workloads` Monorepo**: Tier 2 workload manifests (`app.yaml`, `docker-compose.yml`) consolidate under `~/Workloads/<app>/`, supporting hybrid per-app `.git` checkouts during migration.
3. **Mandatory State Isolation**: All mutable application data resides strictly under `~/var/lib/homelab/<app>/` (or named Docker volumes), never inside `~/Workloads`.
4. **Core Registry & Safe Directory Containment**: `config/deployments.yaml` resolves admitted workloads within `WORKLOADS_DIR`; NixOS `safe.directory` includes `~/Workloads` and `~/Workloads/*`.
### [ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2](0003-pydantic-v2-runtime-validation.md) ### [ADR-0003: Centralized Runtime Validation & Serialization via Pydantic v2](0003-pydantic-v2-runtime-validation.md)
* **Canonical Document**: [`0003-pydantic-v2-runtime-validation.md`](0003-pydantic-v2-runtime-validation.md) * **Canonical Document**: [`0003-pydantic-v2-runtime-validation.md`](0003-pydantic-v2-runtime-validation.md)
* **Status**: `accepted` (Active) * **Status**: `accepted` (Active)
+2
View File
@@ -23,6 +23,8 @@
enable = true; enable = true;
config.safe.directory = [ config.safe.directory = [
"/home/${config.homelab.operatorUser}/Core" "/home/${config.homelab.operatorUser}/Core"
"/home/${config.homelab.operatorUser}/Workloads"
"/home/${config.homelab.operatorUser}/Workloads/*"
"/home/${config.homelab.operatorUser}/Sites/*" "/home/${config.homelab.operatorUser}/Sites/*"
]; ];
}; };
+5 -2
View File
@@ -23,8 +23,8 @@
}; };
sitesDir = lib.mkOption { sitesDir = lib.mkOption {
type = lib.types.str; type = lib.types.str;
default = "/home/${config.homelab.operatorUser}/Sites"; default = "/home/${config.homelab.operatorUser}/Workloads";
description = "Path to Sites directory"; description = "Path to Workloads directory (legacy option name: sitesDir)";
}; };
}; };
@@ -124,6 +124,8 @@
GITOPS_APPCTL_TOKEN_FILE = config.sops.secrets."gitops/appctl_token".path; GITOPS_APPCTL_TOKEN_FILE = config.sops.secrets."gitops/appctl_token".path;
DOCKER_CONFIG = "/home/${config.homelab.operatorUser}/.local/state/homelab/docker"; DOCKER_CONFIG = "/home/${config.homelab.operatorUser}/.local/state/homelab/docker";
HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab"; HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab";
WORKLOADS_DIR = config.homelab.sitesDir;
SITES_DIR = config.homelab.sitesDir;
}; };
serviceConfig = { serviceConfig = {
@@ -198,6 +200,7 @@
APPCTL_AUDIT_LOG = "/var/log/homelab/appctl/audit.jsonl"; APPCTL_AUDIT_LOG = "/var/log/homelab/appctl/audit.jsonl";
APPCTL_LOCK_DIR = "/var/lib/homelab/appctl/locks"; APPCTL_LOCK_DIR = "/var/lib/homelab/appctl/locks";
APPCTL_TOKENS_FILE = config.sops.secrets."appctl/tokens_json".path; APPCTL_TOKENS_FILE = config.sops.secrets."appctl/tokens_json".path;
WORKLOADS_DIR = config.homelab.sitesDir;
SITES_DIR = config.homelab.sitesDir; SITES_DIR = config.homelab.sitesDir;
CORE_DIR = config.homelab.coreDir; CORE_DIR = config.homelab.coreDir;
HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab"; HOMELAB_STATE_ROOT = "/home/${config.homelab.operatorUser}/var/lib/homelab";
+6 -1
View File
@@ -57,7 +57,12 @@ from pydantic import ValidationError
logger = logging.getLogger("appctl_daemon") logger = logging.getLogger("appctl_daemon")
CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent)) CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent))
SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites"))) WORKLOADS_DIR = Path(
os.environ.get("WORKLOADS_DIR")
or os.environ.get("SITES_DIR")
or os.path.expanduser("~/Workloads")
)
SITES_DIR = WORKLOADS_DIR
DEPLOYMENTS_FILE = Path( DEPLOYMENTS_FILE = Path(
os.environ.get("HOMELAB_DEPLOYMENTS_FILE", CORE_DIR / "config" / "deployments.yaml") os.environ.get("HOMELAB_DEPLOYMENTS_FILE", CORE_DIR / "config" / "deployments.yaml")
) )
+13 -6
View File
@@ -37,12 +37,19 @@ CORE_DIR = os.environ.get(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))), os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
) )
SITES_DIR = os.environ.get( def _resolve_default_workloads_dir() -> str:
"SITES_DIR", """Resolve workloads root honoring WORKLOADS_DIR, SITES_DIR, sibling Workloads, or ~/Workloads."""
os.path.join(os.path.dirname(CORE_DIR), "Sites") env_dir = os.environ.get("WORKLOADS_DIR") or os.environ.get("SITES_DIR")
if os.path.isdir(os.path.join(os.path.dirname(CORE_DIR), "Sites")) if env_dir:
else os.path.expanduser("~/Sites"), return env_dir
) sibling_workloads = os.path.join(os.path.dirname(CORE_DIR), "Workloads")
if os.path.isdir(sibling_workloads):
return sibling_workloads
return os.path.expanduser("~/Workloads")
WORKLOADS_DIR = _resolve_default_workloads_dir()
SITES_DIR = WORKLOADS_DIR
HOMELAB_DOMAIN = ( HOMELAB_DOMAIN = (
os.environ.get("HOMELAB_DOMAIN") os.environ.get("HOMELAB_DOMAIN")
+21 -6
View File
@@ -1021,6 +1021,15 @@ class OperationalRouter:
"message": f"Workload '{app.name}' pulled and updated", "message": f"Workload '{app.name}' pulled and updated",
} }
@staticmethod
def _resolve_git_context(app_dir: Path) -> tuple[Path, str | None]:
"""Resolve (git_root, subpath) supporting standalone <app>/.git and parent monorepo .git."""
if (app_dir / ".git").exists():
return app_dir, None
if (app_dir.parent / ".git").exists():
return app_dir.parent, f"{app_dir.name}/"
return app_dir, None
def _op_workload_update( def _op_workload_update(
self, request: OperationRequest, app: Any self, request: OperationRequest, app: Any
) -> tuple[dict[str, Any], str | None]: ) -> tuple[dict[str, Any], str | None]:
@@ -1037,11 +1046,17 @@ class OperationalRouter:
app_dir = Path(app.dir_path) app_dir = Path(app.dir_path)
is_core = self._is_core_target(app) is_core = self._is_core_target(app)
container = self._target_container(app) container = self._target_container(app)
git_root, git_subpath = (
(app_dir, None) if is_core else self._resolve_git_context(app_dir)
)
# 1. Clean working tree check # 1. Clean working tree check
status_cmd = ["git", "-C", str(git_root), "status", "--porcelain"]
if git_subpath is not None:
status_cmd.extend(["--", git_subpath])
code, status_out, _ = run_bounded_subprocess( code, status_out, _ = run_bounded_subprocess(
["git", "-C", str(app_dir), "status", "--porcelain"], status_cmd,
cwd=app_dir, cwd=git_root,
timeout=5.0, timeout=5.0,
) )
if code != 0 or status_out.strip(): if code != 0 or status_out.strip():
@@ -1050,11 +1065,11 @@ class OperationalRouter:
) )
# 2. git pull --ff-only # 2. git pull --ff-only
pull_cmd = ["git", "-C", str(app_dir), "pull", "--ff-only"] pull_cmd = ["git", "-C", str(git_root), "pull", "--ff-only"]
if params.expected_branch: if params.expected_branch:
pull_cmd.extend(["origin", "--", params.expected_branch]) pull_cmd.extend(["origin", "--", params.expected_branch])
code, pull_out, pull_err = run_bounded_subprocess( code, pull_out, pull_err = run_bounded_subprocess(
pull_cmd, cwd=app_dir, timeout=60.0 pull_cmd, cwd=git_root, timeout=60.0
) )
if code != 0: if code != 0:
raise RouterExecutionError( raise RouterExecutionError(
@@ -1132,8 +1147,8 @@ class OperationalRouter:
# 5. Extract current commit SHA # 5. Extract current commit SHA
_, sha_out, _ = run_bounded_subprocess( _, sha_out, _ = run_bounded_subprocess(
["git", "-C", str(app_dir), "rev-parse", "--short", "HEAD"], ["git", "-C", str(git_root), "rev-parse", "--short", "HEAD"],
cwd=app_dir, cwd=git_root,
timeout=5.0, timeout=5.0,
) )
commit_sha = sha_out.strip() or None commit_sha = sha_out.strip() or None
+267 -2
View File
@@ -36,7 +36,12 @@ try:
except ImportError: except ImportError:
yaml = None yaml = None
SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites"))) WORKLOADS_DIR = Path(
os.environ.get("WORKLOADS_DIR")
or os.environ.get("SITES_DIR")
or os.path.expanduser("~/Workloads")
)
SITES_DIR = WORKLOADS_DIR
CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent)) CORE_DIR = Path(os.environ.get("CORE_DIR", Path(__file__).resolve().parent.parent))
CONFIG_DIR = Path( CONFIG_DIR = Path(
os.environ.get("HOMELAB_CONFIG_DIR", os.path.expanduser("~/.config/homelab")) os.environ.get("HOMELAB_CONFIG_DIR", os.path.expanduser("~/.config/homelab"))
@@ -287,7 +292,10 @@ def get_trusted_repository_mapping() -> dict[str, Path]:
raw_path = entry.get("path") raw_path = entry.get("path")
if not raw_path: if not raw_path:
continue continue
if raw_path.startswith("~/Sites/") or raw_path == "~/Sites": if raw_path.startswith("~/Workloads/") or raw_path == "~/Workloads":
sub = raw_path[len("~/Workloads") :].lstrip("/")
p = (SITES_DIR / sub).resolve() if sub else SITES_DIR.resolve()
elif raw_path.startswith("~/Sites/") or raw_path == "~/Sites":
sub = raw_path[len("~/Sites") :].lstrip("/") sub = raw_path[len("~/Sites") :].lstrip("/")
p = (SITES_DIR / sub).resolve() if sub else SITES_DIR.resolve() p = (SITES_DIR / sub).resolve() if sub else SITES_DIR.resolve()
else: else:
@@ -553,6 +561,46 @@ def validate_compose_security(
f"Service '{svc_name}' specifies prohibited security_opt: {opt}.", f"Service '{svc_name}' specifies prohibited security_opt: {opt}.",
) )
build_cfg = svc.get("build")
if build_cfg is not None:
build_context: str | None = None
if isinstance(build_cfg, str):
build_context = build_cfg.strip()
elif isinstance(build_cfg, dict):
raw_ctx = build_cfg.get("context")
if raw_ctx is not None:
build_context = str(raw_ctx).strip()
else:
return (
False,
f"Service '{svc_name}' specifies invalid 'build' configuration.",
)
if build_context:
if "${" in build_context or "}" in build_context:
return (
False,
f"Service '{svc_name}' specifies prohibited variable interpolation in build context: '{build_context}'.",
)
remote_prefixes = ("https://", "http://", "ssh://", "git@", "git://")
if not build_context.startswith(remote_prefixes):
if build_context.startswith("~"):
resolved_build = Path(build_context).expanduser().resolve()
elif Path(build_context).is_absolute():
resolved_build = Path(build_context).resolve()
else:
resolved_build = (allowed_root / build_context).resolve()
if not (
allowed_root.is_dir()
and resolved_build.is_relative_to(canonical_allowed_root)
):
return (
False,
f"Service '{svc_name}' specifies prohibited build context escaping workload root: '{build_context}'.",
)
raw_env_files = svc.get("env_file") raw_env_files = svc.get("env_file")
if raw_env_files: if raw_env_files:
env_file_list: list[str] = [] env_file_list: list[str] = []
@@ -917,6 +965,215 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
return False return False
def is_monorepo_push(payload: dict) -> bool:
"""Return True when payload targets the unified workloads monorepo (e.g. canopy-workloads)."""
if not (SITES_DIR / ".git").exists():
return False
repo_field = payload.get("repository")
if not isinstance(repo_field, dict):
return False
repo_name = repo_field.get("name")
if not isinstance(repo_name, str):
return False
cleaned = repo_name.strip()
return cleaned in ("canopy-workloads", SITES_DIR.name)
def extract_monorepo_changed_subdirs(
payload: dict, monorepo_dir: Path, git_env: dict[str, str] | None = None
) -> list[str]:
"""
Extract safe top-level workload subdirectory names touched by a monorepo push.
Combines commit payload file lists (added/modified/removed) with git diff when available.
Rejects absolute paths, '..' traversal, and root-level files.
"""
raw_paths: list[str] = []
commits = payload.get("commits")
if isinstance(commits, list):
for commit in commits:
if not isinstance(commit, dict):
continue
for key in ("added", "modified", "removed"):
items = commit.get(key)
if isinstance(items, list):
for item in items:
if isinstance(item, str) and item.strip():
raw_paths.append(item.strip())
before_sha = str(payload.get("before", "")).strip()
after_sha = str(payload.get("after", "")).strip()
zero_sha = "0" * 40
if (
before_sha
and after_sha
and before_sha != zero_sha
and after_sha != zero_sha
and REPO_NAME_RE.match(before_sha)
and REPO_NAME_RE.match(after_sha)
):
env = git_env or {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
try:
diff_res = subprocess.run(
["git", "-C", str(monorepo_dir), "diff", "--name-only", before_sha, after_sha],
capture_output=True,
text=True,
check=False,
timeout=15.0,
env=env,
)
if diff_res.returncode == 0:
for line in diff_res.stdout.splitlines():
if line.strip():
raw_paths.append(line.strip())
except (subprocess.SubprocessError, OSError):
pass
seen: set[str] = set()
subdirs: list[str] = []
for rel in raw_paths:
if rel.startswith("/") or "\\" in rel:
continue
parts = Path(rel).parts
if len(parts) < 2 or ".." in parts:
continue
top = parts[0]
if not REPO_NAME_RE.match(top):
continue
if top not in seen:
seen.add(top)
subdirs.append(top)
return subdirs
def dispatch_monorepo_push(
payload: dict, event_type: str | None = None
) -> tuple[bool, list[Path], str]:
"""
Handle a Gitea push webhook for the unified workloads monorepo:
1. Validate push event and refs/heads/<branch>.
2. Pull ~/Workloads once under an exclusive lock.
3. Determine changed top-level <app>/ subdirectories, filter strictly against
deployments.yaml, validate each affected manifest, and enqueue/spawn workers.
"""
if event_type and event_type.strip().lower() != "push":
return (
False,
[],
f"Event '{event_type}' is not eligible for deployment. Only 'push' is allowed.",
)
if "pull_request" in payload or "issue" in payload or "release" in payload:
return (
False,
[],
"Payload represents non-push event (pull_request/issue/release). Rejected.",
)
ref = payload.get("ref", "")
if not isinstance(ref, str) or not ref:
return False, [], "Missing or invalid 'ref' in payload."
if ref.startswith("refs/tags/"):
return False, [], f"Tag push '{ref}' is not deployable."
if not ref.startswith("refs/heads/"):
return False, [], f"Ref '{ref}' is not a head branch. Only 'refs/heads/*' is supported."
pushed_branch = ref.removeprefix("refs/heads/")
if not pushed_branch:
return False, [], "Empty branch name extracted from ref."
expected_monorepo_branch = os.environ.get("MONOREPO_BRANCH", "main")
if pushed_branch != expected_monorepo_branch:
return (
False,
[],
f"Branch mismatch: pushed branch '{pushed_branch}' does not match monorepo branch '{expected_monorepo_branch}'.",
)
git_env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
lock_file_path = get_target_lock("_monorepo")
with open(lock_file_path, "w", encoding="utf-8") as lock_fd:
fcntl.flock(lock_fd, fcntl.LOCK_EX)
try:
pull_res = subprocess.run(
[
"git",
"-C",
str(SITES_DIR),
"pull",
"--ff-only",
"origin",
"--",
pushed_branch,
],
capture_output=True,
text=True,
check=False,
timeout=60.0,
env=git_env,
)
if pull_res.returncode != 0:
return (
False,
[],
f"Failed to pull monorepo '{SITES_DIR}': {pull_res.stderr.strip()}",
)
finally:
with contextlib.suppress(OSError):
fcntl.flock(lock_fd, fcntl.LOCK_UN)
changed_subdirs = extract_monorepo_changed_subdirs(payload, SITES_DIR, git_env=git_env)
trusted_mapping = get_trusted_repository_mapping()
admitted_paths = {p.resolve() for p in trusted_mapping.values()}
canonical_sites = SITES_DIR.resolve()
commit_sha = str(payload.get("after", "") or "")
if not commit_sha and isinstance(payload.get("head_commit"), dict):
commit_sha = str(payload.get("head_commit", {}).get("id", "") or "")
dispatched: list[Path] = []
for subdir in changed_subdirs:
candidate = (SITES_DIR / subdir).resolve()
if not (candidate.is_relative_to(canonical_sites) and candidate in admitted_paths and candidate.is_dir()):
logger.info(
f"Ignoring unregistered or out-of-bounds monorepo subdirectory '{subdir}'."
)
continue
manifest_file = candidate / "app.yaml"
manifest: dict[str, Any] = {}
if manifest_file.is_file():
try:
parsed_manifest = parse_manifest(manifest_file)
manifest = parsed_manifest.model_dump()
except (ManifestValidationError, OSError) as e:
logger.warning(f"Skipping '{subdir}' due to manifest error: {e}")
continue
valid, err_msg = validate_manifest_deployment(manifest)
if not valid:
logger.warning(f"Skipping '{subdir}' due to deployment policy error: {err_msg}")
continue
deployment_config = manifest.get("deployment")
if not isinstance(deployment_config, dict):
deployment_config = {"branch": "main", "actions": ["git_pull", "compose_up"]}
if deployment_config.get("branch", "main") != pushed_branch:
logger.info(
f"Skipping '{subdir}': declared branch '{deployment_config.get('branch', 'main')}' != '{pushed_branch}'."
)
continue
enqueue_deployment(candidate, deployment_config, pushed_branch, commit_sha=commit_sha)
spawn_worker_async(candidate.name)
dispatched.append(candidate)
return (
True,
dispatched,
f"Monorepo push dispatched {len(dispatched)} workload(s) on branch '{pushed_branch}'.",
)
def admit_deployment( def admit_deployment(
payload: dict, event_type: str | None = None payload: dict, event_type: str | None = None
) -> tuple[bool, Path | None, dict, str, str]: ) -> tuple[bool, Path | None, dict, str, str]:
@@ -1259,6 +1516,14 @@ def main():
logger.error(f"Invalid JSON payload: {e}") logger.error(f"Invalid JSON payload: {e}")
sys.exit(1) sys.exit(1)
if is_monorepo_push(payload):
ok, dispatched, reason = dispatch_monorepo_push(payload, event_type)
if not ok:
logger.warning(f"🚫 Monorepo webhook rejected: {reason}")
sys.exit(0 if "Branch mismatch" in reason else 1)
logger.info(f"✅ {reason} ({[d.name for d in dispatched]})")
sys.exit(0)
admitted, target_dir, deployment_config, branch, reason = admit_deployment( admitted, target_dir, deployment_config, branch, reason = admit_deployment(
payload, event_type payload, event_type
) )
+17 -7
View File
@@ -92,10 +92,17 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
""" """
Inspect local git repository checkout state. Inspect local git repository checkout state.
Reports clean/dirty status, active branch/ref, and current commit SHA. Reports clean/dirty status, active branch/ref, and current commit SHA.
Supports standalone <dir_path>/.git checkouts (checked first) and
unified monorepo checkouts where <dir_path>.parent/.git exists.
""" """
path = Path(dir_path) path = Path(dir_path)
git_dir = path / ".git" subpath: str | None = None
if not git_dir.exists(): if (path / ".git").exists():
git_root = path
elif (path.parent / ".git").exists():
git_root = path.parent
subpath = f"{path.name}/"
else:
return CheckoutStatus( return CheckoutStatus(
is_git=False, is_git=False,
is_dirty=False, is_dirty=False,
@@ -107,12 +114,15 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
# Clean git environment so calls are not polluted by outer hooks # Clean git environment so calls are not polluted by outer hooks
git_env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} git_env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
# 1. Check cleanliness # 1. Check cleanliness (scoped to workload subpath in monorepo mode)
is_dirty = False is_dirty = False
git_error: str | None = None git_error: str | None = None
status_cmd = ["git", "-C", str(git_root), "status", "--porcelain"]
if subpath is not None:
status_cmd.extend(["--", subpath])
try: try:
status_res = subprocess.run( status_res = subprocess.run(
["git", "-C", str(path), "status", "--porcelain"], status_cmd,
capture_output=True, capture_output=True,
text=True, text=True,
check=False, check=False,
@@ -132,7 +142,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
branch = "" branch = ""
try: try:
branch_res = subprocess.run( branch_res = subprocess.run(
["git", "-C", str(path), "rev-parse", "--abbrev-ref", "HEAD"], ["git", "-C", str(git_root), "rev-parse", "--abbrev-ref", "HEAD"],
capture_output=True, capture_output=True,
text=True, text=True,
check=False, check=False,
@@ -144,7 +154,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
if branch == "HEAD": if branch == "HEAD":
# Detached HEAD, check describe # Detached HEAD, check describe
desc_res = subprocess.run( desc_res = subprocess.run(
["git", "-C", str(path), "describe", "--tags", "--exact-match"], ["git", "-C", str(git_root), "describe", "--tags", "--exact-match"],
capture_output=True, capture_output=True,
text=True, text=True,
check=False, check=False,
@@ -160,7 +170,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus:
commit_sha = "" commit_sha = ""
try: try:
sha_res = subprocess.run( sha_res = subprocess.run(
["git", "-C", str(path), "rev-parse", "--short", "HEAD"], ["git", "-C", str(git_root), "rev-parse", "--short", "HEAD"],
capture_output=True, capture_output=True,
text=True, text=True,
check=False, check=False,
+156
View File
@@ -228,6 +228,34 @@ def test_missing_or_corrupt_registry_fails_closed(tmp_path: Path, monkeypatch):
# Missing registry must fail closed: empty mapping, no resolution # Missing registry must fail closed: empty mapping, no resolution
assert gitops_dispatcher.get_trusted_repository_mapping() == {} assert gitops_dispatcher.get_trusted_repository_mapping() == {}
def test_registry_resolves_workloads_and_sites_tilde_prefixes(
tmp_path: Path, monkeypatch
):
"""Ensure ~/Workloads/<app> and legacy ~/Sites/<app> paths resolve cleanly inside SITES_DIR."""
workloads_dir = tmp_path / "Workloads"
app_a = workloads_dir / "snappymail"
app_b = workloads_dir / "legacy-app"
app_a.mkdir(parents=True)
app_b.mkdir(parents=True)
registry = tmp_path / "deployments.yaml"
registry.write_text(
'schemaVersion: "1.0"\n'
"repositories:\n"
" snappymail:\n"
' path: "~/Workloads/snappymail"\n'
" legacy:\n"
' path: "~/Sites/legacy-app"\n',
encoding="utf-8",
)
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", workloads_dir)
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
assert gitops_dispatcher.resolve_repository("snappymail") == app_a.resolve()
assert gitops_dispatcher.resolve_repository("legacy") == app_b.resolve()
assert gitops_dispatcher.resolve_repository("valid") is None assert gitops_dispatcher.resolve_repository("valid") is None
# Corrupt YAML registry must also fail closed # Corrupt YAML registry must also fail closed
@@ -1160,3 +1188,131 @@ services:
) )
assert valid is True assert valid is True
assert err is None assert err is None
def test_validate_compose_security_allows_remote_git_build_urls(tmp_path: Path):
"""Ensure validate_compose_security permits remote Git/HTTP build URLs (#33)."""
compose_file = tmp_path / "docker-compose.yml"
compose_file.write_text(
"""
services:
https_app:
build: https://git.example.com/operator/app.git#main
ssh_dict_app:
build:
context: ssh://git@git.example.com:2223/operator/app.git
dockerfile: Dockerfile
scp_git_app:
build: git@git.example.com:operator/app.git
local_app:
build:
context: ./docker
""",
encoding="utf-8",
)
(tmp_path / "docker").mkdir()
valid, err = gitops_dispatcher.validate_compose_security(
compose_file, tmp_path, app_name="my-app"
)
assert valid is True
assert err is None
@pytest.mark.parametrize(
"build_yaml,expected_substr",
[
("build: /etc", "escaping workload root"),
("build:\n context: ../../outside", "escaping workload root"),
('build: "${BUILD_CTX}/app"', "variable interpolation"),
('build:\n context: "${BUILD_CTX}/app"', "variable interpolation"),
],
)
def test_validate_compose_security_rejects_unsafe_build_contexts(
tmp_path: Path, build_yaml: str, expected_substr: str
):
"""Ensure validate_compose_security blocks local build host-path escapes and ${...} interpolation (#33)."""
app_dir = tmp_path / "Workloads" / "my-app"
app_dir.mkdir(parents=True)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"services:\n app:\n {build_yaml}\n",
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 expected_substr in err.lower()
def test_monorepo_webhook_dispatch_pulls_once_and_deploys_only_admitted_changed_subdirs(
tmp_path: Path, monkeypatch
):
"""Ensure canopy-workloads push pulls ~/Workloads once and dispatches only admitted changed subdirs (#33)."""
workloads_dir = tmp_path / "Workloads"
(workloads_dir / ".git").mkdir(parents=True)
snappymail_dir = workloads_dir / "snappymail"
gitea_dir = workloads_dir / "homelab-gitea"
rogue_dir = workloads_dir / "rogue-app"
for d in (snappymail_dir, gitea_dir, rogue_dir):
d.mkdir(parents=True)
(d / "app.yaml").write_text(f"name: {d.name}\n", encoding="utf-8")
registry = tmp_path / "deployments.yaml"
registry.write_text(
'schemaVersion: "1.0"\n'
"repositories:\n"
" snappymail:\n"
' path: "~/Workloads/snappymail"\n'
" gitea:\n"
' path: "~/Workloads/homelab-gitea"\n',
encoding="utf-8",
)
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", workloads_dir)
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
monkeypatch.setattr(gitops_dispatcher, "STATE_DIR", tmp_path / "state")
payload = {
"ref": "refs/heads/main",
"after": "deadbeef1234",
"repository": {"name": "canopy-workloads"},
"commits": [
{
"added": ["rogue-app/app.yaml", "README.md"],
"modified": ["snappymail/docker-compose.yml"],
"removed": ["../Core/scripts/appctl"],
}
],
}
git_calls: list[list[str]] = []
enqueued: list[Path] = []
spawned: list[str] = []
def mock_run(cmd, *args, **kwargs):
git_calls.append(cmd)
return MagicMock(returncode=0, stdout="", stderr="")
monkeypatch.setattr(gitops_dispatcher.subprocess, "run", mock_run)
monkeypatch.setattr(
gitops_dispatcher,
"enqueue_deployment",
lambda target_dir, cfg, branch, commit_sha="": enqueued.append(target_dir),
)
monkeypatch.setattr(
gitops_dispatcher,
"spawn_worker_async",
lambda target_name: spawned.append(target_name),
)
assert gitops_dispatcher.is_monorepo_push(payload) is True
ok, dispatched, _ = gitops_dispatcher.dispatch_monorepo_push(payload, "push")
assert ok is True
assert dispatched == [snappymail_dir.resolve()]
assert enqueued == [snappymail_dir.resolve()]
assert spawned == ["snappymail"]
# Pulled ~/Workloads exactly once
pull_calls = [c for c in git_calls if "pull" in c]
assert len(pull_calls) == 1
assert str(workloads_dir) in pull_calls[0]
+29 -1
View File
@@ -485,12 +485,18 @@ def test_nixos_switch_alias_uses_path_and_impure():
def test_nixos_safe_directory_includes_core_and_sites(): def test_nixos_safe_directory_includes_core_and_sites():
"""Ensure programs.git.config.safe.directory includes Core and Sites to prevent dubious ownership errors.""" """Ensure programs.git.config.safe.directory includes Core, Workloads, and Sites to prevent dubious ownership errors."""
config_nix = CORE_ROOT / "nixos" / "configuration.nix" config_nix = CORE_ROOT / "nixos" / "configuration.nix"
content = config_nix.read_text(encoding="utf-8") content = config_nix.read_text(encoding="utf-8")
assert '"/home/${config.homelab.operatorUser}/Core"' in content, ( assert '"/home/${config.homelab.operatorUser}/Core"' in content, (
"nixos/configuration.nix must include Core in git safe.directory" "nixos/configuration.nix must include Core in git safe.directory"
) )
assert '"/home/${config.homelab.operatorUser}/Workloads"' in content, (
"nixos/configuration.nix must include Workloads in git safe.directory"
)
assert '"/home/${config.homelab.operatorUser}/Workloads/*"' in content, (
"nixos/configuration.nix must include Workloads/* in git safe.directory"
)
assert '"/home/${config.homelab.operatorUser}/Sites/*"' in content, ( assert '"/home/${config.homelab.operatorUser}/Sites/*"' in content, (
"nixos/configuration.nix must include Sites/* in git safe.directory" "nixos/configuration.nix must include Sites/* in git safe.directory"
) )
@@ -521,9 +527,31 @@ def test_nixos_safe_directory_includes_core_and_sites():
assert "/home/operator/Core" in safe_dirs, ( assert "/home/operator/Core" in safe_dirs, (
f"Expected '/home/operator/Core' in git safe.directory, got {safe_dirs}" f"Expected '/home/operator/Core' in git safe.directory, got {safe_dirs}"
) )
assert "/home/operator/Workloads" in safe_dirs, (
f"Expected '/home/operator/Workloads' in git safe.directory, got {safe_dirs}"
)
assert "/home/operator/Workloads/*" in safe_dirs, (
f"Expected '/home/operator/Workloads/*' in git safe.directory, got {safe_dirs}"
)
assert "/home/operator/Sites/*" in safe_dirs, ( assert "/home/operator/Sites/*" in safe_dirs, (
f"Expected '/home/operator/Sites/*' in git safe.directory, got {safe_dirs}" f"Expected '/home/operator/Sites/*' in git safe.directory, got {safe_dirs}"
) )
def test_nixos_homeserver_defaults_to_workloads_dir():
"""Ensure homeserver.nix defaults sitesDir to ~/Workloads and exports WORKLOADS_DIR + SITES_DIR (#33)."""
homeserver_nix = CORE_ROOT / "nixos" / "modules" / "homeserver.nix"
content = homeserver_nix.read_text(encoding="utf-8")
assert 'default = "/home/${config.homelab.operatorUser}/Workloads";' in content, (
"homelab.sitesDir must default to /home/${config.homelab.operatorUser}/Workloads"
)
assert "WORKLOADS_DIR = config.homelab.sitesDir;" in content, (
"homeserver.nix must export WORKLOADS_DIR"
)
assert "SITES_DIR = config.homelab.sitesDir;" in content, (
"homeserver.nix must export SITES_DIR for backward compatibility"
)
+53
View File
@@ -554,3 +554,56 @@ def test_cmd_list_flags_manifest_error(
engine.cmd_list([]) engine.cmd_list([])
captured = capsys.readouterr() captured = capsys.readouterr()
assert "Manifest Error" in captured.out assert "Manifest Error" in captured.out
def test_workloads_dir_env_precedence_and_fallback(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
"""Ensure WORKLOADS_DIR > SITES_DIR > ~/Workloads fallback across core modules (#33)."""
import importlib
import appctl_daemon
import gitops_dispatcher
workloads_override = tmp_path / "custom-workloads"
sites_override = tmp_path / "legacy-sites"
fake_home = tmp_path / "home"
fake_core = tmp_path / "repo" / "core"
fake_core.mkdir(parents=True)
try:
# 1. WORKLOADS_DIR takes precedence over SITES_DIR
monkeypatch.setenv("CORE_DIR", str(fake_core))
monkeypatch.setenv("WORKLOADS_DIR", str(workloads_override))
monkeypatch.setenv("SITES_DIR", str(sites_override))
importlib.reload(engine)
importlib.reload(appctl_daemon)
importlib.reload(gitops_dispatcher)
assert engine.SITES_DIR == str(workloads_override)
assert appctl_daemon.SITES_DIR == workloads_override
assert gitops_dispatcher.SITES_DIR == workloads_override
# 2. SITES_DIR acts as fallback when WORKLOADS_DIR is unset
monkeypatch.delenv("WORKLOADS_DIR", raising=False)
importlib.reload(engine)
importlib.reload(appctl_daemon)
importlib.reload(gitops_dispatcher)
assert engine.SITES_DIR == str(sites_override)
assert appctl_daemon.SITES_DIR == sites_override
assert gitops_dispatcher.SITES_DIR == sites_override
# 3. Default resolves to ~/Workloads when neither env var is set
monkeypatch.delenv("SITES_DIR", raising=False)
monkeypatch.setenv("HOME", str(fake_home))
importlib.reload(engine)
importlib.reload(appctl_daemon)
importlib.reload(gitops_dispatcher)
expected_default = fake_home / "Workloads"
assert engine.SITES_DIR == str(expected_default)
assert appctl_daemon.SITES_DIR == expected_default
assert gitops_dispatcher.SITES_DIR == expected_default
finally:
monkeypatch.undo()
importlib.reload(engine)
importlib.reload(appctl_daemon)
importlib.reload(gitops_dispatcher)
+63
View File
@@ -1618,3 +1618,66 @@ def test_trigger_homepage_sync_acquires_homepage_sync_lock(tmp_path: Path, mock_
with patch("appctl_router.cmd_sync_homepage", side_effect=mock_sync): with patch("appctl_router.cmd_sync_homepage", side_effect=mock_sync):
router._trigger_homepage_sync() router._trigger_homepage_sync()
assert lock_acquired is True assert lock_acquired is True
def test_operational_router_workload_update_pulls_monorepo_when_parent_git_exists(
tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path
):
"""Ensure workload.update targets parent monorepo .git when <app>/.git is absent (#33)."""
monorepo_root = mock_workload_dir.parent
(monorepo_root / ".git").mkdir()
router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=monorepo_root,
)
req = OperationRequest.model_validate(
{
"operation": "workload.update",
"target": "snappymail",
"parameters": {"expected_branch": "main"},
}
)
mock_app = MagicMock()
mock_app.name = "snappymail"
mock_app.dir_path = str(mock_workload_dir)
executed: list[tuple[list[str], Path | None]] = []
def mock_subproc(cmd: list[str], **kwargs):
executed.append((cmd, kwargs.get("cwd")))
if "status" in cmd:
return 0, "", ""
if "pull" in cmd:
return 0, "Updating 1111..2222\nFast-forward", ""
if "rev-parse" in cmd:
return 0, "beef123", ""
return 0, "success", ""
with (
patch("appctl_router.resolve_app", return_value=mock_app),
patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc),
patch("appctl_router.cmd_sync_homepage"),
):
resp = router.dispatch(req, admin_principal)
assert resp.success is True
assert resp.result is not None
assert resp.result["commit_sha"] == "beef123"
status_calls = [c for c, _ in executed if c[0] == "git" and "status" in c]
assert status_calls == [
["git", "-C", str(monorepo_root), "status", "--porcelain", "--", "snappymail/"]
]
git_pull_calls = [(c, cwd) for c, cwd in executed if c[0] == "git" and "pull" in c]
assert git_pull_calls == [
(["git", "-C", str(monorepo_root), "pull", "--ff-only", "origin", "--", "main"], monorepo_root)
]
rev_parse_calls = [c for c, _ in executed if c[0] == "git" and "rev-parse" in c]
assert rev_parse_calls == [
["git", "-C", str(monorepo_root), "rev-parse", "--short", "HEAD"]
]
# Compose commands still run in app_dir
compose_cwds = [cwd for c, cwd in executed if c[0] == "docker"]
assert compose_cwds and all(cwd == mock_workload_dir for cwd in compose_cwds)
+97
View File
@@ -266,3 +266,100 @@ def test_get_local_checkout_status_git_error(tmp_path: Path):
assert status.is_dirty is False assert status.is_dirty is False
assert status.status_label == "⚠️ Git Error (exit 128)" assert status.status_label == "⚠️ Git Error (exit 128)"
def _init_git_repo(repo_dir: Path, branch: str = "main") -> None:
env = _clean_git_env()
subprocess.run(
["git", "-C", str(repo_dir), "init", "-b", branch],
check=True,
capture_output=True,
env=env,
)
subprocess.run(
["git", "-C", str(repo_dir), "config", "user.email", "test@example.com"],
check=True,
env=env,
)
subprocess.run(
["git", "-C", str(repo_dir), "config", "user.name", "Test"],
check=True,
env=env,
)
def test_get_local_checkout_status_monorepo_subpath_isolation(tmp_path: Path):
"""Ensure monorepo subpath inspection isolates dirty state per workload directory (#33)."""
workloads_dir = tmp_path / "Workloads"
app_a = workloads_dir / "app_a"
app_b = workloads_dir / "app_b"
app_a.mkdir(parents=True)
app_b.mkdir(parents=True)
_init_git_repo(workloads_dir, branch="main")
(app_a / "app.yaml").write_text("name: app_a\n", encoding="utf-8")
(app_b / "app.yaml").write_text("name: app_b\n", encoding="utf-8")
env = _clean_git_env()
subprocess.run(["git", "-C", str(workloads_dir), "add", "."], check=True, env=env)
subprocess.run(
["git", "-C", str(workloads_dir), "commit", "-m", "init monorepo"],
check=True,
capture_output=True,
env=env,
)
# Dirty only app_b
(app_b / "app.yaml").write_text("name: app_b_dirty\n", encoding="utf-8")
(app_b / "untracked.txt").write_text("dirty\n", encoding="utf-8")
status_a = get_local_checkout_status(app_a)
assert status_a.is_git is True
assert status_a.is_dirty is False
assert status_a.branch == "main"
assert status_a.commit_sha != ""
assert "✓ Clean" in status_a.status_label
status_b = get_local_checkout_status(app_b)
assert status_b.is_git is True
assert status_b.is_dirty is True
assert status_b.branch == "main"
assert "* Dirty" in status_b.status_label
def test_get_local_checkout_status_hybrid_precedence_standalone_over_monorepo(
tmp_path: Path,
):
"""Ensure standalone <app>/.git takes precedence over parent monorepo .git (#33)."""
workloads_dir = tmp_path / "Workloads"
app_a = workloads_dir / "app_a"
app_a.mkdir(parents=True)
_init_git_repo(workloads_dir, branch="main")
env = _clean_git_env()
(workloads_dir / "README.md").write_text("monorepo\n", encoding="utf-8")
subprocess.run(
["git", "-C", str(workloads_dir), "add", "README.md"], check=True, env=env
)
subprocess.run(
["git", "-C", str(workloads_dir), "commit", "-m", "monorepo root"],
check=True,
capture_output=True,
env=env,
)
# Nested standalone .git inside app_a on a distinct branch
_init_git_repo(app_a, branch="standalone-branch")
(app_a / "app.yaml").write_text("name: app_a\n", encoding="utf-8")
subprocess.run(["git", "-C", str(app_a), "add", "app.yaml"], check=True, env=env)
subprocess.run(
["git", "-C", str(app_a), "commit", "-m", "standalone commit"],
check=True,
capture_output=True,
env=env,
)
status_a = get_local_checkout_status(app_a)
assert status_a.is_git is True
assert status_a.is_dirty is False
assert status_a.branch == "standalone-branch"