Compare commits
9
Commits
945e80206f
...
534ea9ed11
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
534ea9ed11 | ||
|
|
33514663a3 | ||
|
|
f4b676be33 | ||
|
|
142697a19c | ||
|
|
5aae4ef0d6 | ||
|
|
c265c3e8f6 | ||
|
|
fa8054aad5 | ||
|
|
01acdb4f75 | ||
|
|
29dd186eb8 |
No files matched your search
@@ -0,0 +1,21 @@
|
|||||||
|
name: Core Architecture & Invariant CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ main ]
|
||||||
|
pull_request:
|
||||||
|
branches: [ main ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
validate:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Check out repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Install Nix
|
||||||
|
uses: DeterminateSystems/nix-installer-action@main
|
||||||
|
|
||||||
|
- name: Run Architecture & Security Invariant Checks
|
||||||
|
run: |
|
||||||
|
nix flake check
|
||||||
@@ -29,3 +29,10 @@ config/homepage/logs/
|
|||||||
Thumbs.db
|
Thumbs.db
|
||||||
.vscode/
|
.vscode/
|
||||||
.idea/
|
.idea/
|
||||||
|
|
||||||
|
# Python & Testing Caches
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
.pytest_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
|
||||||
@@ -100,6 +100,66 @@ appctl sync
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## ⚡ Hardened GitOps Continuous Deployment
|
||||||
|
|
||||||
|
Automated deployments are driven by the hardened webhook engine [`scripts/gitops_dispatcher.py`](scripts/gitops_dispatcher.py) managed via the declarative `homelab-gitops.service` systemd unit on port 9000.
|
||||||
|
|
||||||
|
```
|
||||||
|
Webhook Request (:9000)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[ 1. Cryptographic HMAC Verification ] ──► (X-Gitea-Signature checked via constant-time compare against SOPS secret)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[ 2. Event & Ref Admission ] ──► (Only 'push' to 'refs/heads/*' admitted; PRs/tags rejected)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[ 3. Canonical Repository Resolution ] ──► (Logical names resolved against trusted ~/Sites mapping; traversal blocked)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[ 4. Manifest & Branch Validation ] ──► (app.yaml validated; pushed branch must match declared policy)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[ 5. Asynchronous Queue & Worker ] ──► (Atomic queueing + immediate HTTP 200 return; per-repo flock worker)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[ 6. Closed Execution Engine ] ──► (Strictly allowlisted actions without shell=True)
|
||||||
|
```
|
||||||
|
|
||||||
|
### GitOps Security Properties:
|
||||||
|
* **Zero Arbitrary Shell Execution**: The `custom:` command path and `shell=True` invocations are abolished. Only closed, allowlisted actions (`git_pull`, `compose_up`, `compose_build`, `compose_restart`) are executable.
|
||||||
|
* **Cryptographic Admission**: Every incoming webhook must provide an `X-Gitea-Signature` matching the SOPS-managed secret projected to `/run/secrets/gitops/webhook_secret`. Missing, malformed, or mismatching signatures fail closed.
|
||||||
|
* **Trusted Identity Resolution**: Webhooks identify target applications by logical identity (`docs`, `homelab-docs`), never by filesystem path. Paths are canonicalized with strict path traversal and symlink escape defenses.
|
||||||
|
* **Serialized Asynchronous Execution**: Webhook admissions write atomic pending requests and return HTTP 200 immediately. Detached per-repo workers serialize deployments via non-blocking `flock` and automatically supersede intermediate commits (A deploys, B arrives, C replaces B -> A finishes, then C deploys).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🧪 Automated Invariant Tests & Continuous Integration
|
||||||
|
|
||||||
|
Architectural boundaries and security invariants are enforced continuously by a machine-executable test suite in [`tests/`](tests/):
|
||||||
|
|
||||||
|
### Test Structure:
|
||||||
|
* **`tests/security/test_gitops_security.py`**: Webhook HMAC signatures, traversal prevention, admission gates, and race condition superseding.
|
||||||
|
* **`tests/security/test_security_invariants.py`**: Docker socket-proxy policies (`POST=0`, `DELETE=0`), container socket isolation, and absence of `privileged: true`.
|
||||||
|
* **`tests/structural/test_repository_structure.py`**: Repository tree integrity, absence of deprecated structures, and public domain license preservation.
|
||||||
|
|
||||||
|
### Running Tests:
|
||||||
|
```bash
|
||||||
|
# Run the complete test and invariant suite locally
|
||||||
|
./scripts/test
|
||||||
|
|
||||||
|
# Run pure Nix sandbox verification (runs ruff and pytest in an isolated Nix derivation)
|
||||||
|
nix flake check
|
||||||
|
|
||||||
|
# Enter a development shell with pytest, pyyaml, and ruff preconfigured
|
||||||
|
nix develop
|
||||||
|
```
|
||||||
|
|
||||||
|
### Continuous Integration:
|
||||||
|
Every pull request and push to `main` triggers [`.gitea/workflows/ci.yaml`](.gitea/workflows/ci.yaml), executing `nix flake check` to prevent architectural regressions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 📦 Adding a New Application Stack
|
## 📦 Adding a New Application Stack
|
||||||
|
|
||||||
Adding a new application to the homelab is completely decentralized:
|
Adding a new application to the homelab is completely decentralized:
|
||||||
@@ -210,4 +270,4 @@ nixos-install --flake ~/Core#server
|
|||||||
---
|
---
|
||||||
|
|
||||||
## 📄 License
|
## 📄 License
|
||||||
This repository is released into the public domain under the [Unlicense](LICENSE).
|
This repository is released into the public domain under [The Unlicense](UNLICENSE).
|
||||||
+12
-3
@@ -22,6 +22,13 @@ The most critical security feature. No container (including Traefik or Portainer
|
|||||||
### 4. Automated Maintenance
|
### 4. Automated Maintenance
|
||||||
- **Watchtower**: Automatically updates containers when new security patches are released for their images.
|
- **Watchtower**: Automatically updates containers when new security patches are released for their images.
|
||||||
|
|
||||||
|
### 5. GitOps Admission & Trust Boundary Hardening
|
||||||
|
The webhook deployment engine (`scripts/gitops_dispatcher.py`) implements a zero-trust admission model:
|
||||||
|
- **Cryptographic Authentication**: Every request must carry an HMAC-SHA256 signature (`X-Gitea-Signature`) validated in constant-time against a SOPS-managed secret.
|
||||||
|
- **Trusted Repository Resolution**: Payloads cannot specify filesystem paths. Logical repository identities are mapped to local directories with strict regex validation, path traversal defense (`../`), and symlink escape checks.
|
||||||
|
- **Zero Arbitrary Shell Execution**: The `custom:` execution handler and `shell=True` have been eliminated. Only closed, allowlisted actions (`git_pull`, `compose_up`, `compose_build`, `compose_restart`) are executable.
|
||||||
|
- **Serialized Asynchronous Worker**: Admissions write atomic pending states and return HTTP 200 immediately. Non-blocking `flock` workers serialize deployments and supersede obsolete intermediate commits.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## ⚠️ Potential Attack Vectors & Concerns
|
## ⚠️ Potential Attack Vectors & Concerns
|
||||||
@@ -47,7 +54,9 @@ Home connections are vulnerable to bandwidth saturation.
|
|||||||
---
|
---
|
||||||
|
|
||||||
## 🛠️ Security Checklist for Production
|
## 🛠️ Security Checklist for Production
|
||||||
- [ ] Replace all placeholder secrets in `infra/authelia/.env`.
|
- [ ] Manage all production secrets declaratively in `nixos/secrets.yaml` encrypted with Age / SOPS.
|
||||||
- [ ] Hash your user passwords in `infra/authelia/config/users.yml` using `docker run --rm authelia/authelia authelia crypto hash generate pbkdf2 --password "your_password_here"`.
|
- [ ] Maintain user password hashes in `nixos/secrets.yaml` (`authelia/users/<user>/password_hash`).
|
||||||
|
- [ ] Verify `X-Gitea-Signature` webhook secret is populated in `nixos/secrets.yaml` (`gitops/webhook_secret`).
|
||||||
|
- [ ] Run `./scripts/test` and `nix flake check` before applying changes to verify structural and security invariants.
|
||||||
- [ ] Disable Traefik/Authelia access from the public internet if only local use is needed (via Firewall/IP Whitelisting).
|
- [ ] Disable Traefik/Authelia access from the public internet if only local use is needed (via Firewall/IP Whitelisting).
|
||||||
- [ ] Ensure `acme.json` is backed up securely but kept private.
|
- [ ] Ensure `config/letsencrypt/acme.json` is backed up securely but kept private (chmod 600).
|
||||||
@@ -10,14 +10,46 @@
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
outputs = { self, nixpkgs, sops-nix, ... }@inputs: {
|
outputs = { self, nixpkgs, sops-nix, ... }@inputs:
|
||||||
nixosConfigurations.server = nixpkgs.lib.nixosSystem {
|
let
|
||||||
system = "x86_64-linux";
|
system = "x86_64-linux";
|
||||||
|
pkgs = nixpkgs.legacyPackages.${system};
|
||||||
|
in
|
||||||
|
{
|
||||||
|
nixosConfigurations.server = nixpkgs.lib.nixosSystem {
|
||||||
|
inherit system;
|
||||||
specialArgs = { inherit inputs; };
|
specialArgs = { inherit inputs; };
|
||||||
modules = [
|
modules = [
|
||||||
./nixos/configuration.nix
|
./nixos/configuration.nix
|
||||||
sops-nix.nixosModules.sops
|
sops-nix.nixosModules.sops
|
||||||
];
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
devShells.${system}.default = pkgs.mkShell {
|
||||||
|
buildInputs = with pkgs; [
|
||||||
|
python3
|
||||||
|
python3Packages.pytest
|
||||||
|
python3Packages.pyyaml
|
||||||
|
ruff
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|
||||||
|
checks.${system} = {
|
||||||
|
test-suite = pkgs.runCommand "core-tests" {
|
||||||
|
nativeBuildInputs = with pkgs; [
|
||||||
|
python3
|
||||||
|
python3Packages.pytest
|
||||||
|
python3Packages.pyyaml
|
||||||
|
ruff
|
||||||
|
];
|
||||||
|
} ''
|
||||||
|
mkdir -p $out
|
||||||
|
cp -r ${self} source
|
||||||
|
chmod -R u+w source
|
||||||
|
cd source
|
||||||
|
HOME=/tmp ruff check --no-cache .
|
||||||
|
HOME=/tmp pytest -o cache_dir=/tmp/.pytest_cache tests/
|
||||||
|
'';
|
||||||
|
};
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -46,6 +46,7 @@ in
|
|||||||
"authelia/users/kiskaadee/password_hash"
|
"authelia/users/kiskaadee/password_hash"
|
||||||
"authelia/users/misa/password_hash"
|
"authelia/users/misa/password_hash"
|
||||||
"authelia/users/valenvg/password_hash"
|
"authelia/users/valenvg/password_hash"
|
||||||
|
"gitops/webhook_secret"
|
||||||
] (name: { owner = "kiskaadee"; });
|
] (name: { owner = "kiskaadee"; });
|
||||||
|
|
||||||
# Generate the unified environment file at runtime in /run/secrets/homeserver.env
|
# Generate the unified environment file at runtime in /run/secrets/homeserver.env
|
||||||
@@ -93,6 +94,10 @@ in
|
|||||||
|
|
||||||
path = with pkgs; [ git docker docker-compose python3 coreutils bash openssh ];
|
path = with pkgs; [ git docker docker-compose python3 coreutils bash openssh ];
|
||||||
|
|
||||||
|
environment = {
|
||||||
|
GITOPS_SECRET_FILE = config.sops.secrets."gitops/webhook_secret".path;
|
||||||
|
};
|
||||||
|
|
||||||
serviceConfig = {
|
serviceConfig = {
|
||||||
Type = "simple";
|
Type = "simple";
|
||||||
User = "kiskaadee";
|
User = "kiskaadee";
|
||||||
@@ -103,6 +108,8 @@ in
|
|||||||
execute-command = "/home/kiskaadee/Core/scripts/gitops_dispatcher.py";
|
execute-command = "/home/kiskaadee/Core/scripts/gitops_dispatcher.py";
|
||||||
pass-arguments-to-command = [
|
pass-arguments-to-command = [
|
||||||
{ source = "entire-payload"; }
|
{ source = "entire-payload"; }
|
||||||
|
{ source = "header"; name = "X-Gitea-Signature"; }
|
||||||
|
{ source = "header"; name = "X-Gitea-Event"; }
|
||||||
];
|
];
|
||||||
command-working-directory = "/home/kiskaadee/Core";
|
command-working-directory = "/home/kiskaadee/Core";
|
||||||
response-message = "Deployment payload dispatched successfully.";
|
response-message = "Deployment payload dispatched successfully.";
|
||||||
|
|||||||
+4
-2
@@ -33,6 +33,8 @@ learning:
|
|||||||
system:
|
system:
|
||||||
gh_repo_token: ENC[AES256_GCM,data:QAsmG5iQQJ4TUhtrIbkq3wlw4JWbj2tFX6u2BbdB4werXfWyak8sdw==,iv:orGtlDW71QHDRSTED1xNfdOggF61hHsbGztWOUSdY+Y=,tag:4xe1I+hNjxWLc16BW4yTLA==,type:str]
|
gh_repo_token: ENC[AES256_GCM,data:QAsmG5iQQJ4TUhtrIbkq3wlw4JWbj2tFX6u2BbdB4werXfWyak8sdw==,iv:orGtlDW71QHDRSTED1xNfdOggF61hHsbGztWOUSdY+Y=,tag:4xe1I+hNjxWLc16BW4yTLA==,type:str]
|
||||||
pdf_decrypt_password: ENC[AES256_GCM,data:n3XTANd+PbejUw==,iv:y2VIabyv/DfTgztbjS6M/xIfRNKOL+U+r3eXsal32OQ=,tag:oFpXg2E9dDM5dwkjSZkLgw==,type:str]
|
pdf_decrypt_password: ENC[AES256_GCM,data:n3XTANd+PbejUw==,iv:y2VIabyv/DfTgztbjS6M/xIfRNKOL+U+r3eXsal32OQ=,tag:oFpXg2E9dDM5dwkjSZkLgw==,type:str]
|
||||||
|
gitops:
|
||||||
|
webhook_secret: ENC[AES256_GCM,data:Kj3d0Repa3OOvjCkW6+kakQEfsCdpdVJQd71Am6zQHBt7QkLtxlnovUmmS+zJ+jChQBbCc9/7LunFvFT2pL36w==,iv:qh1pEIVtvB/fxbMv+a9pworhbXsIpfF5gKWS22Zn0GU=,tag:D4RNXkWhg9l3BJFp7MMloA==,type:str]
|
||||||
sops:
|
sops:
|
||||||
age:
|
age:
|
||||||
- enc: |
|
- enc: |
|
||||||
@@ -53,7 +55,7 @@ sops:
|
|||||||
yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A==
|
yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A==
|
||||||
-----END AGE ENCRYPTED FILE-----
|
-----END AGE ENCRYPTED FILE-----
|
||||||
recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg
|
recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg
|
||||||
lastmodified: "2026-09-11T19:59:23Z"
|
lastmodified: "2026-09-13T08:09:29Z"
|
||||||
mac: ENC[AES256_GCM,data:BcBncbSLf5CdYQxLn5THA6aMyxqipHpTwTgPOSZXf4B8PwO7yH4J7mL/sKEZ08448nAUaOABOrgFHoLlvVzGrUVJegRC/G9OgFQT8A4v1Dkq0yx0VSplMtf2q4ylyTjLHQb5bd4r4OzfBNFjmruyrZHS3ydxn8gfbgOft50w2vM=,iv:dTzR9j4crCaaG/wjMRxiGjVZMyBNOCN+qKlSN34m0m8=,tag:D8go58ulc1nu5biQWq1TpA==,type:str]
|
mac: ENC[AES256_GCM,data:aP+BwlAIFXxg4gBvgzPOJyqz2AMJjUpMPZhs3sZc6vSmcRU2ARoHNZ4tEaIdGNumtPd++5Xi7a2CVj5rwI9Y/dpouXkdw8p7xNlbmt2d9BbKlXNH8XfDDiDXlKHHdFyI2diX3G62k87CC684oWjIQgf/w3+kuJ+N/ZkbV8N69ZM=,iv:RJaNa76TkY8aIYXRzrqebJiHu6hBow3RYNSo6QP/Zy8=,tag:bAwWKXrH6aQVbkPNMZqgnQ==,type:str]
|
||||||
unencrypted_suffix: _unencrypted
|
unencrypted_suffix: _unencrypted
|
||||||
version: 3.13.3
|
version: 3.13.3
|
||||||
+471
-54
@@ -7,9 +7,15 @@ in ~/Sites (via app.yaml) or data vaults (like ~/Brain), and executes the declar
|
|||||||
deployment actions with zero Core restarts.
|
deployment actions with zero Core restarts.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import datetime
|
||||||
|
import fcntl
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -17,6 +23,8 @@ from pathlib import Path
|
|||||||
SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites")))
|
SITES_DIR = Path(os.environ.get("SITES_DIR", os.path.expanduser("~/Sites")))
|
||||||
BRAIN_DIR = Path(os.environ.get("BRAIN_DIR", os.path.expanduser("~/Brain")))
|
BRAIN_DIR = Path(os.environ.get("BRAIN_DIR", os.path.expanduser("~/Brain")))
|
||||||
CONFIG_DIR = Path(os.environ.get("HOMELAB_CONFIG_DIR", os.path.expanduser("~/.config/homelab")))
|
CONFIG_DIR = Path(os.environ.get("HOMELAB_CONFIG_DIR", os.path.expanduser("~/.config/homelab")))
|
||||||
|
DEFAULT_SECRET_PATH = Path(os.environ.get("GITOPS_SECRET_FILE", "/run/secrets/gitops/webhook_secret"))
|
||||||
|
STATE_DIR = Path(os.environ.get("GITOPS_STATE_DIR", Path.home() / ".local/state/homelab/gitops"))
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
level=logging.INFO,
|
level=logging.INFO,
|
||||||
@@ -26,10 +34,60 @@ logging.basicConfig(
|
|||||||
logger = logging.getLogger("gitops_dispatcher")
|
logger = logging.getLogger("gitops_dispatcher")
|
||||||
|
|
||||||
|
|
||||||
|
def load_webhook_secret(secret_file: Path | None = None) -> bytes:
|
||||||
|
"""
|
||||||
|
Load webhook shared secret from projected secret file or environment.
|
||||||
|
Never hardcoded in code or repository manifests.
|
||||||
|
"""
|
||||||
|
path = secret_file or Path(os.environ.get("GITOPS_SECRET_FILE", DEFAULT_SECRET_PATH))
|
||||||
|
if path.is_file():
|
||||||
|
try:
|
||||||
|
return path.read_bytes().strip()
|
||||||
|
except OSError as e:
|
||||||
|
logger.error(f"Failed to read webhook secret from {path}: {e}")
|
||||||
|
return b""
|
||||||
|
|
||||||
|
env_secret = os.environ.get("GITOPS_WEBHOOK_SECRET")
|
||||||
|
if env_secret:
|
||||||
|
return env_secret.strip().encode("utf-8")
|
||||||
|
|
||||||
|
return b""
|
||||||
|
|
||||||
|
|
||||||
|
def verify_signature(raw_body: bytes, signature: str | None, secret: bytes) -> bool:
|
||||||
|
"""
|
||||||
|
Verify incoming webhook HMAC-SHA256 signature using constant-time comparison.
|
||||||
|
Fail-closed: missing signature, malformed signature, empty secret, or mismatch returns False.
|
||||||
|
"""
|
||||||
|
if not secret:
|
||||||
|
logger.error("Authentication failed: Webhook shared secret is empty or missing.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
if not signature or not isinstance(signature, str):
|
||||||
|
logger.error("Authentication failed: Missing signature header.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
cleaned_signature = signature.strip()
|
||||||
|
cleaned_signature = cleaned_signature.removeprefix("sha256=")
|
||||||
|
|
||||||
|
# SHA256 hex digest is exactly 64 hexadecimal characters
|
||||||
|
if len(cleaned_signature) != 64 or not all(c in "0123456789abcdefABCDEF" for c in cleaned_signature):
|
||||||
|
logger.error("Authentication failed: Malformed signature format.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
expected_mac = hmac.new(secret, raw_body, hashlib.sha256).hexdigest()
|
||||||
|
if not hmac.compare_digest(expected_mac.lower(), cleaned_signature.lower()):
|
||||||
|
logger.error("Authentication failed: Signature mismatch.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
def parse_yaml_simple(text: str) -> dict:
|
def parse_yaml_simple(text: str) -> dict:
|
||||||
"""Lightweight, zero-dependency YAML parser tailored for app.yaml manifests."""
|
"""Lightweight, zero-dependency YAML parser tailored for app.yaml manifests."""
|
||||||
data = {}
|
data = {}
|
||||||
current_section = None
|
current_section = None
|
||||||
|
current_subsection = None
|
||||||
lines = text.splitlines()
|
lines = text.splitlines()
|
||||||
|
|
||||||
for line in lines:
|
for line in lines:
|
||||||
@@ -42,6 +100,11 @@ def parse_yaml_simple(text: str) -> dict:
|
|||||||
if stripped.startswith("- "):
|
if stripped.startswith("- "):
|
||||||
item = stripped[2:].strip().strip("\"'")
|
item = stripped[2:].strip().strip("\"'")
|
||||||
if current_section:
|
if current_section:
|
||||||
|
if current_subsection and isinstance(data.get(current_section), dict):
|
||||||
|
if not isinstance(data[current_section].get(current_subsection), list):
|
||||||
|
data[current_section][current_subsection] = []
|
||||||
|
data[current_section][current_subsection].append(item)
|
||||||
|
else:
|
||||||
if not isinstance(data.get(current_section), list):
|
if not isinstance(data.get(current_section), list):
|
||||||
data[current_section] = []
|
data[current_section] = []
|
||||||
data[current_section].append(item)
|
data[current_section].append(item)
|
||||||
@@ -61,6 +124,7 @@ def parse_yaml_simple(text: str) -> dict:
|
|||||||
|
|
||||||
if indent == 0:
|
if indent == 0:
|
||||||
current_section = k
|
current_section = k
|
||||||
|
current_subsection = None
|
||||||
if v == "":
|
if v == "":
|
||||||
data[k] = {}
|
data[k] = {}
|
||||||
else:
|
else:
|
||||||
@@ -68,68 +132,178 @@ def parse_yaml_simple(text: str) -> dict:
|
|||||||
elif indent > 0 and current_section:
|
elif indent > 0 and current_section:
|
||||||
if not isinstance(data.get(current_section), dict):
|
if not isinstance(data.get(current_section), dict):
|
||||||
data[current_section] = {}
|
data[current_section] = {}
|
||||||
|
current_subsection = k
|
||||||
|
if v == "":
|
||||||
|
data[current_section][k] = []
|
||||||
|
else:
|
||||||
data[current_section][k] = v
|
data[current_section][k] = v
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
REPO_NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]*$")
|
||||||
|
|
||||||
|
|
||||||
|
def get_trusted_repository_mapping() -> dict[str, Path]:
|
||||||
|
"""
|
||||||
|
Build authoritative mapping of logical repository identities to local paths.
|
||||||
|
Webhook payloads can only select repositories defined in this mapping.
|
||||||
|
"""
|
||||||
|
mapping: dict[str, Path] = {}
|
||||||
|
|
||||||
|
# 1. Authoritative Data Vaults
|
||||||
|
if BRAIN_DIR.is_dir():
|
||||||
|
brain_canonical = BRAIN_DIR.resolve()
|
||||||
|
for alias in ["second-brain", "Brain", "brain"]:
|
||||||
|
mapping[alias] = brain_canonical
|
||||||
|
|
||||||
|
# 2. Workload Plane Applications in SITES_DIR
|
||||||
|
if SITES_DIR.is_dir():
|
||||||
|
sites_canonical = SITES_DIR.resolve()
|
||||||
|
for entry in SITES_DIR.iterdir():
|
||||||
|
if not entry.is_dir():
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Defense-in-depth: resolve symlinks and ensure target is strictly inside SITES_DIR
|
||||||
|
resolved_entry = entry.resolve()
|
||||||
|
if not resolved_entry.is_relative_to(sites_canonical):
|
||||||
|
logger.warning(f"Rejecting repository symlink escape: {entry} -> {resolved_entry}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
manifest_file = resolved_entry / "app.yaml"
|
||||||
|
if not manifest_file.is_file():
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Register entry directory name
|
||||||
|
dir_name = entry.name
|
||||||
|
mapping[dir_name] = resolved_entry
|
||||||
|
|
||||||
|
# Parse app.yaml for canonical name and aliases
|
||||||
|
manifest = {}
|
||||||
|
try:
|
||||||
|
manifest = parse_yaml_simple(manifest_file.read_text(encoding="utf-8"))
|
||||||
|
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
||||||
|
logger.warning(f"Failed to parse {manifest_file}: {e}")
|
||||||
|
|
||||||
|
canonical_name = manifest.get("name")
|
||||||
|
if canonical_name and isinstance(canonical_name, str):
|
||||||
|
canonical_name = canonical_name.strip()
|
||||||
|
mapping[canonical_name] = resolved_entry
|
||||||
|
if not canonical_name.startswith("homelab-"):
|
||||||
|
mapping[f"homelab-{canonical_name}"] = resolved_entry
|
||||||
|
else:
|
||||||
|
mapping[canonical_name.replace("homelab-", "", 1)] = resolved_entry
|
||||||
|
|
||||||
|
aliases = manifest.get("aliases", [])
|
||||||
|
if isinstance(aliases, str):
|
||||||
|
aliases = [aliases]
|
||||||
|
if isinstance(aliases, list):
|
||||||
|
for alias in aliases:
|
||||||
|
if isinstance(alias, str) and alias.strip():
|
||||||
|
mapping[alias.strip()] = resolved_entry
|
||||||
|
|
||||||
|
# 3. Optional local override registry with strict containment
|
||||||
|
registry_file = CONFIG_DIR / "deployments.yaml"
|
||||||
|
if registry_file.is_file():
|
||||||
|
try:
|
||||||
|
registry = parse_yaml_simple(registry_file.read_text(encoding="utf-8"))
|
||||||
|
for reg_name, entry in registry.items():
|
||||||
|
if not isinstance(entry, dict):
|
||||||
|
continue
|
||||||
|
raw_path = entry.get("path")
|
||||||
|
if not raw_path:
|
||||||
|
continue
|
||||||
|
p = Path(raw_path).resolve()
|
||||||
|
# Must be strictly relative to SITES_DIR or BRAIN_DIR
|
||||||
|
if (SITES_DIR.is_dir() and p.is_relative_to(SITES_DIR.resolve())) or \
|
||||||
|
(BRAIN_DIR.is_dir() and p.is_relative_to(BRAIN_DIR.resolve())):
|
||||||
|
mapping[reg_name] = p
|
||||||
|
else:
|
||||||
|
logger.warning(f"Rejecting out-of-bounds path in deployments.yaml for '{reg_name}': {p}")
|
||||||
|
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
||||||
|
logger.warning(f"Failed to parse custom registry {registry_file}: {e}")
|
||||||
|
|
||||||
|
return mapping
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_repository(repo_name: str) -> Path | None:
|
||||||
|
"""
|
||||||
|
Resolve a logical repository identity to a trusted local directory.
|
||||||
|
Rejects directory traversal, unknown repositories, and path escapes.
|
||||||
|
"""
|
||||||
|
if not repo_name or not isinstance(repo_name, str):
|
||||||
|
return None
|
||||||
|
|
||||||
|
cleaned_name = repo_name.strip()
|
||||||
|
if not REPO_NAME_RE.match(cleaned_name):
|
||||||
|
logger.warning(f"Invalid repository name format rejected: '{repo_name}'")
|
||||||
|
return None
|
||||||
|
|
||||||
|
if ".." in cleaned_name or "/" in cleaned_name or "\\" in cleaned_name:
|
||||||
|
logger.warning(f"Path traversal characters detected in repository name: '{repo_name}'")
|
||||||
|
return None
|
||||||
|
|
||||||
|
trusted_mapping = get_trusted_repository_mapping()
|
||||||
|
target = trusted_mapping.get(cleaned_name)
|
||||||
|
|
||||||
|
if not target:
|
||||||
|
logger.warning(f"Repository '{cleaned_name}' is not in trusted repository registry.")
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
canonical_target = target.resolve()
|
||||||
|
except (OSError, RuntimeError) as e:
|
||||||
|
logger.warning(f"Failed to resolve target path for '{cleaned_name}': {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
if not canonical_target.is_dir():
|
||||||
|
logger.warning(f"Trusted repository target '{canonical_target}' does not exist or is not a directory.")
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Defense-in-depth: check allowed root containment
|
||||||
|
allowed = False
|
||||||
|
if SITES_DIR.is_dir() and canonical_target.is_relative_to(SITES_DIR.resolve()) or BRAIN_DIR.is_dir() and canonical_target.is_relative_to(BRAIN_DIR.resolve()):
|
||||||
|
allowed = True
|
||||||
|
|
||||||
|
if not allowed:
|
||||||
|
logger.warning(f"Resolved path '{canonical_target}' escapes allowed roots for repository '{cleaned_name}'.")
|
||||||
|
return None
|
||||||
|
|
||||||
|
return canonical_target
|
||||||
|
|
||||||
|
|
||||||
def resolve_target(repo_name: str) -> tuple[Path | None, dict]:
|
def resolve_target(repo_name: str) -> tuple[Path | None, dict]:
|
||||||
"""
|
"""
|
||||||
Dynamically resolve target directory and deployment configuration.
|
Dynamically resolve target directory and deployment configuration.
|
||||||
1. Check ~/Sites/<repo_name> or ~/Sites/homelab-<repo_name>
|
Uses resolve_repository() as the single authoritative resolver.
|
||||||
2. Check Data Vaults (second-brain -> ~/Brain)
|
|
||||||
3. Check ~/.config/homelab/deployments.yaml fallback
|
|
||||||
"""
|
"""
|
||||||
normalized_name = repo_name.strip()
|
target_dir = resolve_repository(repo_name)
|
||||||
short_name = normalized_name.replace("homelab-", "")
|
if not target_dir:
|
||||||
|
return None, {}
|
||||||
|
|
||||||
# 1. Check Data Vaults
|
# Data vault default deployment config
|
||||||
if normalized_name in ["second-brain", "Brain", "brain"]:
|
if BRAIN_DIR.is_dir() and target_dir == BRAIN_DIR.resolve():
|
||||||
return BRAIN_DIR, {
|
return target_dir, {
|
||||||
"branch": "main",
|
"branch": "main",
|
||||||
"actions": ["git_pull"]
|
"actions": ["git_pull"]
|
||||||
}
|
}
|
||||||
|
|
||||||
# 2. Check ~/Sites directories
|
manifest_file = target_dir / "app.yaml"
|
||||||
candidates = [
|
|
||||||
SITES_DIR / normalized_name,
|
|
||||||
SITES_DIR / f"homelab-{short_name}",
|
|
||||||
SITES_DIR / short_name,
|
|
||||||
]
|
|
||||||
|
|
||||||
for candidate in candidates:
|
|
||||||
if candidate.is_dir():
|
|
||||||
manifest_file = candidate / "app.yaml"
|
|
||||||
manifest = {}
|
manifest = {}
|
||||||
if manifest_file.is_file():
|
if manifest_file.is_file():
|
||||||
try:
|
try:
|
||||||
manifest = parse_yaml_simple(manifest_file.read_text())
|
manifest = parse_yaml_simple(manifest_file.read_text(encoding="utf-8"))
|
||||||
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
||||||
logger.warning(f"Failed to parse {manifest_file}: {e}")
|
logger.warning(f"Failed to parse {manifest_file}: {e}")
|
||||||
|
|
||||||
deployment_config = manifest.get("deployment")
|
deployment_config = manifest.get("deployment")
|
||||||
if not isinstance(deployment_config, dict):
|
if not isinstance(deployment_config, dict):
|
||||||
# Default application deployment strategy
|
|
||||||
deployment_config = {
|
deployment_config = {
|
||||||
"branch": "main",
|
"branch": "main",
|
||||||
"actions": ["git_pull", "compose_up"]
|
"actions": ["git_pull", "compose_up"]
|
||||||
}
|
}
|
||||||
return candidate, deployment_config
|
|
||||||
|
|
||||||
# 3. Check custom override registry in ~/.config/homelab/deployments.yaml
|
return target_dir, deployment_config
|
||||||
registry_file = CONFIG_DIR / "deployments.yaml"
|
|
||||||
if registry_file.is_file():
|
|
||||||
try:
|
|
||||||
registry = parse_yaml_simple(registry_file.read_text())
|
|
||||||
if normalized_name in registry:
|
|
||||||
entry = registry[normalized_name]
|
|
||||||
target_path = Path(entry.get("path", ""))
|
|
||||||
if target_path.is_dir():
|
|
||||||
return target_path, entry.get("deployment", {"branch": "main", "actions": ["git_pull"]})
|
|
||||||
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
|
||||||
logger.warning(f"Failed to parse custom registry {registry_file}: {e}")
|
|
||||||
|
|
||||||
return None, {}
|
|
||||||
|
|
||||||
|
|
||||||
def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -> bool:
|
def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -> bool:
|
||||||
@@ -178,12 +352,9 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
|||||||
["docker", "compose", "-f", str(compose_file), "restart"],
|
["docker", "compose", "-f", str(compose_file), "restart"],
|
||||||
check=True
|
check=True
|
||||||
)
|
)
|
||||||
elif isinstance(action, dict) and "custom" in action:
|
|
||||||
cmd = action["custom"]
|
|
||||||
logger.info(f" ↳ [custom] Executing: {cmd}")
|
|
||||||
subprocess.run(cmd, shell=True, cwd=str(target_dir), check=True)
|
|
||||||
else:
|
else:
|
||||||
logger.warning(f" ↳ Unknown action '{action}'; skipping.")
|
logger.error(f"❌ Unsupported or rejected deployment action '{action}'. Aborting deployment.")
|
||||||
|
return False
|
||||||
|
|
||||||
logger.info(f"✨ Deployment of '{target_dir.name}' completed successfully.")
|
logger.info(f"✨ Deployment of '{target_dir.name}' completed successfully.")
|
||||||
return True
|
return True
|
||||||
@@ -195,10 +366,248 @@ def execute_deployment(target_dir: Path, deployment_config: dict, branch: str) -
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
ALLOWED_ACTIONS = {"git_pull", "compose_up", "compose_build", "compose_restart"}
|
||||||
|
ALLOWED_STRATEGIES = {"compose"}
|
||||||
|
|
||||||
|
|
||||||
|
def validate_manifest_deployment(manifest: dict) -> tuple[bool, str]:
|
||||||
|
"""
|
||||||
|
Validate deployment policy inside app.yaml.
|
||||||
|
Rejects unsupported deployment strategies or unknown actions.
|
||||||
|
"""
|
||||||
|
deployment = manifest.get("deployment")
|
||||||
|
if deployment is None:
|
||||||
|
return True, ""
|
||||||
|
|
||||||
|
if not isinstance(deployment, dict):
|
||||||
|
return False, "Field 'deployment' must be a mapping/dictionary."
|
||||||
|
|
||||||
|
# Validate strategy if specified
|
||||||
|
strategy = deployment.get("strategy")
|
||||||
|
if strategy is not None and strategy not in ALLOWED_STRATEGIES:
|
||||||
|
return False, f"Unsupported deployment strategy '{strategy}'. Allowed strategies: {sorted(ALLOWED_STRATEGIES)}"
|
||||||
|
|
||||||
|
# Validate actions if specified
|
||||||
|
actions = deployment.get("actions")
|
||||||
|
if actions is not None:
|
||||||
|
if not isinstance(actions, list):
|
||||||
|
return False, "Field 'deployment.actions' must be a list of strings."
|
||||||
|
for action in actions:
|
||||||
|
if not isinstance(action, str) or action not in ALLOWED_ACTIONS:
|
||||||
|
return False, f"Unsupported deployment action '{action}'. Allowed actions: {sorted(ALLOWED_ACTIONS)}"
|
||||||
|
|
||||||
|
return True, ""
|
||||||
|
|
||||||
|
|
||||||
|
def admit_deployment(
|
||||||
|
payload: dict,
|
||||||
|
event_type: str | None = None
|
||||||
|
) -> tuple[bool, Path | None, dict, str, str]:
|
||||||
|
"""
|
||||||
|
Evaluate webhook deployment admission against strict policy gates:
|
||||||
|
1. Event Admission (must be a push event, rejects PRs, tags, releases)
|
||||||
|
2. Ref Format (must be 'refs/heads/<branch>')
|
||||||
|
3. Repository Admission (must resolve against trusted mapping)
|
||||||
|
4. Manifest & Strategy Validation (app.yaml must be valid)
|
||||||
|
5. Branch Policy Admission (pushed branch must match declared deployment branch)
|
||||||
|
|
||||||
|
Returns: (admitted: bool, target_dir: Path | None, deployment_config: dict, branch: str, reason: str)
|
||||||
|
"""
|
||||||
|
# 1. Event Admission
|
||||||
|
if event_type and event_type.strip().lower() != "push":
|
||||||
|
return False, None, {}, "", 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, None, {}, "", "Payload represents non-push event (pull_request/issue/release). Rejected."
|
||||||
|
|
||||||
|
# 2. Ref Admission
|
||||||
|
ref = payload.get("ref", "")
|
||||||
|
if not isinstance(ref, str) or not ref:
|
||||||
|
return False, None, {}, "", "Missing or invalid 'ref' in payload."
|
||||||
|
|
||||||
|
if ref.startswith("refs/tags/"):
|
||||||
|
return False, None, {}, "", f"Tag push '{ref}' is not deployable."
|
||||||
|
|
||||||
|
if not ref.startswith("refs/heads/"):
|
||||||
|
return False, None, {}, "", 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, None, {}, "", "Empty branch name extracted from ref."
|
||||||
|
|
||||||
|
# 3. Repository Admission
|
||||||
|
repo_field = payload.get("repository")
|
||||||
|
if not isinstance(repo_field, dict):
|
||||||
|
return False, None, {}, pushed_branch, "Missing or invalid 'repository' object in payload."
|
||||||
|
|
||||||
|
repo_name = repo_field.get("name")
|
||||||
|
if not isinstance(repo_name, str) or not repo_name.strip():
|
||||||
|
return False, None, {}, pushed_branch, "Missing or empty repository name in payload."
|
||||||
|
|
||||||
|
repo_name = repo_name.strip()
|
||||||
|
target_dir = resolve_repository(repo_name)
|
||||||
|
if not target_dir:
|
||||||
|
return False, None, {}, pushed_branch, f"Repository '{repo_name}' is not recognized in trusted registry."
|
||||||
|
|
||||||
|
# 4. Manifest & Strategy Validation
|
||||||
|
if BRAIN_DIR.is_dir() and target_dir == BRAIN_DIR.resolve():
|
||||||
|
deployment_config = {"branch": "main", "actions": ["git_pull"]}
|
||||||
|
else:
|
||||||
|
manifest_file = target_dir / "app.yaml"
|
||||||
|
manifest = {}
|
||||||
|
if manifest_file.is_file():
|
||||||
|
try:
|
||||||
|
manifest = parse_yaml_simple(manifest_file.read_text(encoding="utf-8"))
|
||||||
|
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
||||||
|
return False, None, {}, pushed_branch, f"Failed to parse manifest {manifest_file}: {e}"
|
||||||
|
|
||||||
|
valid, err_msg = validate_manifest_deployment(manifest)
|
||||||
|
if not valid:
|
||||||
|
return False, None, {}, pushed_branch, f"Manifest validation error: {err_msg}"
|
||||||
|
|
||||||
|
deployment_config = manifest.get("deployment")
|
||||||
|
if not isinstance(deployment_config, dict):
|
||||||
|
deployment_config = {
|
||||||
|
"branch": "main",
|
||||||
|
"actions": ["git_pull", "compose_up"]
|
||||||
|
}
|
||||||
|
|
||||||
|
# 5. Branch Policy Admission
|
||||||
|
expected_branch = deployment_config.get("branch", "main")
|
||||||
|
if pushed_branch != expected_branch:
|
||||||
|
return False, target_dir, deployment_config, pushed_branch, (
|
||||||
|
f"Branch mismatch: pushed branch '{pushed_branch}' does not match "
|
||||||
|
f"declared target branch '{expected_branch}'."
|
||||||
|
)
|
||||||
|
|
||||||
|
return True, target_dir, deployment_config, pushed_branch, f"Admitted for deployment on branch '{pushed_branch}'."
|
||||||
|
|
||||||
|
|
||||||
|
def get_target_lock(target_name: str) -> Path:
|
||||||
|
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
return STATE_DIR / f"{target_name}.lock"
|
||||||
|
|
||||||
|
|
||||||
|
def get_pending_file(target_name: str) -> Path:
|
||||||
|
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
return STATE_DIR / f"{target_name}.pending.json"
|
||||||
|
|
||||||
|
|
||||||
|
def enqueue_deployment(target_dir: Path, deployment_config: dict, branch: str) -> Path:
|
||||||
|
"""
|
||||||
|
Atomically enqueue a deployment request.
|
||||||
|
Supersedes any existing pending request for this target.
|
||||||
|
"""
|
||||||
|
target_name = target_dir.name
|
||||||
|
pending_file = get_pending_file(target_name)
|
||||||
|
temp_file = STATE_DIR / f"{target_name}.pending.tmp.{os.getpid()}"
|
||||||
|
|
||||||
|
data = {
|
||||||
|
"target_dir": str(target_dir),
|
||||||
|
"deployment_config": deployment_config,
|
||||||
|
"branch": branch,
|
||||||
|
"queued_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||||
|
}
|
||||||
|
|
||||||
|
temp_file.write_text(json.dumps(data), encoding="utf-8")
|
||||||
|
temp_file.replace(pending_file)
|
||||||
|
logger.info(f"📥 Enqueued deployment for '{target_name}' (branch: {branch}, superseding previous pending).")
|
||||||
|
return pending_file
|
||||||
|
|
||||||
|
|
||||||
|
def run_target_worker(target_name: str) -> bool:
|
||||||
|
"""
|
||||||
|
Serialized worker for a specific repository.
|
||||||
|
Acquires exclusive flock and processes pending deployments until queue is empty.
|
||||||
|
"""
|
||||||
|
lock_file_path = get_target_lock(target_name)
|
||||||
|
pending_file_path = get_pending_file(target_name)
|
||||||
|
|
||||||
|
with open(lock_file_path, "w", encoding="utf-8") as lock_fd:
|
||||||
|
try:
|
||||||
|
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
except (BlockingIOError, OSError):
|
||||||
|
logger.info(f"Deployment worker for '{target_name}' is already active. Pending update will be picked up.")
|
||||||
|
return True
|
||||||
|
|
||||||
|
overall_success = True
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
if not pending_file_path.is_file():
|
||||||
|
break
|
||||||
|
|
||||||
|
try:
|
||||||
|
content = pending_file_path.read_text(encoding="utf-8")
|
||||||
|
pending_file_path.unlink(missing_ok=True)
|
||||||
|
item = json.loads(content)
|
||||||
|
except (OSError, json.JSONDecodeError) as e:
|
||||||
|
logger.error(f"Failed to read pending deployment file: {e}")
|
||||||
|
break
|
||||||
|
|
||||||
|
target_dir = Path(item["target_dir"])
|
||||||
|
deployment_config = item["deployment_config"]
|
||||||
|
branch = item["branch"]
|
||||||
|
|
||||||
|
success = execute_deployment(target_dir, deployment_config, branch)
|
||||||
|
if not success:
|
||||||
|
overall_success = False
|
||||||
|
|
||||||
|
return overall_success
|
||||||
|
finally:
|
||||||
|
with contextlib.suppress(OSError):
|
||||||
|
fcntl.flock(lock_fd, fcntl.LOCK_UN)
|
||||||
|
|
||||||
|
|
||||||
|
def spawn_worker_async(target_name: str):
|
||||||
|
"""Spawn a detached worker process to execute deployments asynchronously."""
|
||||||
|
dispatcher_script = Path(__file__).resolve()
|
||||||
|
cmd = [sys.executable, str(dispatcher_script), "--worker", target_name]
|
||||||
|
subprocess.Popen(
|
||||||
|
cmd,
|
||||||
|
stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
start_new_session=True
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
payload_raw = ""
|
payload_raw = ""
|
||||||
repo_name = ""
|
repo_name = ""
|
||||||
branch = "main"
|
branch = "main"
|
||||||
|
signature = None
|
||||||
|
event_type = None
|
||||||
|
|
||||||
|
if "--worker" in sys.argv:
|
||||||
|
w_idx = sys.argv.index("--worker")
|
||||||
|
if w_idx + 1 < len(sys.argv):
|
||||||
|
worker_target = sys.argv[w_idx + 1]
|
||||||
|
success = run_target_worker(worker_target)
|
||||||
|
sys.exit(0 if success else 1)
|
||||||
|
else:
|
||||||
|
logger.error("--worker requires a repository/target name.")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
if "--signature" in sys.argv:
|
||||||
|
sig_idx = sys.argv.index("--signature")
|
||||||
|
if sig_idx + 1 < len(sys.argv):
|
||||||
|
signature = sys.argv[sig_idx + 1]
|
||||||
|
elif len(sys.argv) > 2 and not sys.argv[2].startswith("-"):
|
||||||
|
signature = sys.argv[2]
|
||||||
|
elif os.environ.get("HTTP_X_GITEA_SIGNATURE"):
|
||||||
|
signature = os.environ.get("HTTP_X_GITEA_SIGNATURE")
|
||||||
|
elif os.environ.get("X_GITEA_SIGNATURE"):
|
||||||
|
signature = os.environ.get("X_GITEA_SIGNATURE")
|
||||||
|
|
||||||
|
if "--event" in sys.argv:
|
||||||
|
ev_idx = sys.argv.index("--event")
|
||||||
|
if ev_idx + 1 < len(sys.argv):
|
||||||
|
event_type = sys.argv[ev_idx + 1]
|
||||||
|
elif len(sys.argv) > 3 and not sys.argv[3].startswith("-"):
|
||||||
|
event_type = sys.argv[3]
|
||||||
|
elif os.environ.get("HTTP_X_GITEA_EVENT"):
|
||||||
|
event_type = os.environ.get("HTTP_X_GITEA_EVENT")
|
||||||
|
elif os.environ.get("X_GITEA_EVENT"):
|
||||||
|
event_type = os.environ.get("X_GITEA_EVENT")
|
||||||
|
|
||||||
# Support CLI arguments for manual trigger: --repo <name> [--branch <branch>]
|
# Support CLI arguments for manual trigger: --repo <name> [--branch <branch>]
|
||||||
if "--repo" in sys.argv:
|
if "--repo" in sys.argv:
|
||||||
@@ -209,6 +618,13 @@ def main():
|
|||||||
b_idx = sys.argv.index("--branch")
|
b_idx = sys.argv.index("--branch")
|
||||||
if b_idx + 1 < len(sys.argv):
|
if b_idx + 1 < len(sys.argv):
|
||||||
branch = sys.argv[b_idx + 1].replace("refs/heads/", "")
|
branch = sys.argv[b_idx + 1].replace("refs/heads/", "")
|
||||||
|
logger.info(f"Local manual trigger: repository='{repo_name}', branch='{branch}'")
|
||||||
|
target_dir, deployment_config = resolve_target(repo_name)
|
||||||
|
if not target_dir or not target_dir.is_dir():
|
||||||
|
logger.error(f"Target repository '{repo_name}' could not be resolved.")
|
||||||
|
sys.exit(1)
|
||||||
|
success = execute_deployment(target_dir, deployment_config, branch)
|
||||||
|
sys.exit(0 if success else 1)
|
||||||
else:
|
else:
|
||||||
# 1. Check if first argument is a raw JSON payload string
|
# 1. Check if first argument is a raw JSON payload string
|
||||||
if len(sys.argv) > 1 and sys.argv[1].strip().startswith("{"):
|
if len(sys.argv) > 1 and sys.argv[1].strip().startswith("{"):
|
||||||
@@ -221,29 +637,30 @@ def main():
|
|||||||
logger.error("No webhook payload provided (checked sys.argv and stdin).")
|
logger.error("No webhook payload provided (checked sys.argv and stdin).")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
|
raw_body = payload_raw.encode("utf-8")
|
||||||
|
secret = load_webhook_secret()
|
||||||
|
if not verify_signature(raw_body, signature, secret):
|
||||||
|
logger.error("❌ Webhook authentication failed. Rejecting request.")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
payload = json.loads(payload_raw)
|
payload = json.loads(payload_raw)
|
||||||
repo_name = payload.get("repository", {}).get("name", "")
|
|
||||||
ref = payload.get("ref", "refs/heads/main")
|
|
||||||
branch = ref.replace("refs/heads/", "")
|
|
||||||
except json.JSONDecodeError as e:
|
except json.JSONDecodeError as e:
|
||||||
logger.error(f"Invalid JSON payload: {e}")
|
logger.error(f"Invalid JSON payload: {e}")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
if not repo_name:
|
admitted, target_dir, deployment_config, branch, reason = admit_deployment(payload, event_type)
|
||||||
logger.error("No repository name found in payload.")
|
if not admitted:
|
||||||
sys.exit(1)
|
logger.warning(f"🚫 Webhook admission rejected: {reason}")
|
||||||
|
# Branch mismatch on valid push is benign skip; other violations fail closed
|
||||||
|
sys.exit(0 if "Branch mismatch" in reason else 1)
|
||||||
|
|
||||||
logger.info(f"Incoming webhook event: repository='{repo_name}', branch='{branch}'")
|
logger.info(f"✅ Webhook admission passed: {reason}")
|
||||||
target_dir, deployment_config = resolve_target(repo_name)
|
enqueue_deployment(target_dir, deployment_config, branch)
|
||||||
|
spawn_worker_async(target_dir.name)
|
||||||
if not target_dir or not target_dir.is_dir():
|
logger.info(f"🚀 Asynchronous deployment scheduled for '{target_dir.name}'. Returning HTTP 200.")
|
||||||
logger.warning(f"No valid deployment target directory found on host for '{repo_name}'. Ignoring.")
|
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
success = execute_deployment(target_dir, deployment_config, branch)
|
|
||||||
sys.exit(0 if success else 1)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
Executable
+24
@@ -0,0 +1,24 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# scripts/test - Automated test & invariant verification runner for Homelab Core
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
echo "🔍 Running code linters (ruff)..."
|
||||||
|
if command -v ruff &>/dev/null; then
|
||||||
|
ruff check .
|
||||||
|
else
|
||||||
|
nix-shell -p ruff --run "ruff check ."
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "🧪 Running architecture & security test suite (pytest)..."
|
||||||
|
if command -v pytest &>/dev/null; then
|
||||||
|
pytest tests/
|
||||||
|
else
|
||||||
|
nix-shell -p python3Packages.pytest python3Packages.pyyaml --run "pytest tests/"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "❄️ Verifying NixOS flake & sandbox checks..."
|
||||||
|
nix flake check
|
||||||
|
|
||||||
|
echo "✨ All tests and architectural invariants passed successfully!"
|
||||||
@@ -0,0 +1,444 @@
|
|||||||
|
"""
|
||||||
|
Security invariant tests for homelab GitOps execution and admission.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
# Add Core to path so scripts can be imported
|
||||||
|
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||||
|
sys.path.insert(0, str(CORE_ROOT / "scripts"))
|
||||||
|
|
||||||
|
import gitops_dispatcher
|
||||||
|
|
||||||
|
|
||||||
|
def test_custom_shell_action_is_rejected_without_execution(tmp_path: Path):
|
||||||
|
"""Ensure that arbitrary 'custom' actions fail closed and never invoke a shell."""
|
||||||
|
deployment_config = {
|
||||||
|
"branch": "main",
|
||||||
|
"actions": [
|
||||||
|
{"custom": "touch /tmp/pwned"}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
with patch("subprocess.run") as mock_run:
|
||||||
|
success = gitops_dispatcher.execute_deployment(tmp_path, deployment_config, branch="main")
|
||||||
|
|
||||||
|
assert success is False, "execute_deployment must fail closed on 'custom' action"
|
||||||
|
mock_run.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_action_is_rejected(tmp_path: Path):
|
||||||
|
"""Ensure that unknown action strings fail closed and abort deployment."""
|
||||||
|
deployment_config = {
|
||||||
|
"branch": "main",
|
||||||
|
"actions": ["malicious_or_unknown_action"]
|
||||||
|
}
|
||||||
|
|
||||||
|
with patch("subprocess.run") as mock_run:
|
||||||
|
success = gitops_dispatcher.execute_deployment(tmp_path, deployment_config, branch="main")
|
||||||
|
|
||||||
|
assert success is False, "execute_deployment must reject unknown actions"
|
||||||
|
mock_run.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_allowed_actions_use_safe_argument_lists(tmp_path: Path):
|
||||||
|
"""Ensure that allowed actions execute safely via argument lists without shell=True."""
|
||||||
|
deployment_config = {
|
||||||
|
"branch": "main",
|
||||||
|
"actions": ["git_pull"]
|
||||||
|
}
|
||||||
|
|
||||||
|
with patch("subprocess.run") as mock_run:
|
||||||
|
mock_run.return_value = MagicMock(returncode=0)
|
||||||
|
success = gitops_dispatcher.execute_deployment(tmp_path, deployment_config, branch="main")
|
||||||
|
|
||||||
|
assert success is True
|
||||||
|
mock_run.assert_called_once()
|
||||||
|
args, kwargs = mock_run.call_args
|
||||||
|
assert isinstance(args[0], list), "Command must be passed as an argument list"
|
||||||
|
assert kwargs.get("shell") is not True, "shell=True must never be set"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_repository_rejects_path_traversal(tmp_path: Path, monkeypatch):
|
||||||
|
"""Ensure that path traversal payloads are strictly rejected before filesystem lookup."""
|
||||||
|
sites_dir = tmp_path / "Sites"
|
||||||
|
sites_dir.mkdir()
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
|
||||||
|
traversal_payloads = [
|
||||||
|
"../../foo",
|
||||||
|
"../",
|
||||||
|
"../../../etc/passwd",
|
||||||
|
"/etc",
|
||||||
|
"/home/foo",
|
||||||
|
"foo/bar",
|
||||||
|
"foo\\bar",
|
||||||
|
"app/../../secret",
|
||||||
|
]
|
||||||
|
|
||||||
|
for payload in traversal_payloads:
|
||||||
|
assert gitops_dispatcher.resolve_repository(payload) is None, f"Expected {payload} to be rejected"
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_repository_rejects_unknown_repositories(tmp_path: Path, monkeypatch):
|
||||||
|
"""Ensure that unknown repositories cannot be resolved."""
|
||||||
|
sites_dir = tmp_path / "Sites"
|
||||||
|
sites_dir.mkdir()
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
|
||||||
|
assert gitops_dispatcher.resolve_repository("unregistered-repo") is None
|
||||||
|
assert gitops_dispatcher.resolve_repository("evil-service") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_repository_rejects_symlink_escapes(tmp_path: Path, monkeypatch):
|
||||||
|
"""Ensure that symlinks inside Sites pointing outside are rejected as escapes."""
|
||||||
|
sites_dir = tmp_path / "Sites"
|
||||||
|
sites_dir.mkdir()
|
||||||
|
secret_dir = tmp_path / "outside_root" / "sneaky-app"
|
||||||
|
secret_dir.mkdir(parents=True)
|
||||||
|
(secret_dir / "app.yaml").write_text("name: sneaky\n", encoding="utf-8")
|
||||||
|
|
||||||
|
# Create a symlink inside Sites pointing outside Sites
|
||||||
|
escape_link = sites_dir / "sneaky-link"
|
||||||
|
escape_link.symlink_to(secret_dir)
|
||||||
|
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
|
||||||
|
# Resolution should catch the escape and refuse to resolve
|
||||||
|
assert gitops_dispatcher.resolve_repository("sneaky") is None
|
||||||
|
assert gitops_dispatcher.resolve_repository("sneaky-link") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_repository_resolves_valid_manifest(tmp_path: Path, monkeypatch):
|
||||||
|
"""Ensure valid registered apps resolve by folder name, manifest name, and aliases."""
|
||||||
|
sites_dir = tmp_path / "Sites"
|
||||||
|
app_dir = sites_dir / "homelab-docs"
|
||||||
|
app_dir.mkdir(parents=True)
|
||||||
|
(app_dir / "app.yaml").write_text(
|
||||||
|
"name: docs\naliases:\n - doc2site\n - notes\n",
|
||||||
|
encoding="utf-8"
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
|
||||||
|
canonical = app_dir.resolve()
|
||||||
|
assert gitops_dispatcher.resolve_repository("homelab-docs") == canonical
|
||||||
|
assert gitops_dispatcher.resolve_repository("docs") == canonical
|
||||||
|
assert gitops_dispatcher.resolve_repository("doc2site") == canonical
|
||||||
|
assert gitops_dispatcher.resolve_repository("notes") == canonical
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_repository_resolves_vault(tmp_path: Path, monkeypatch):
|
||||||
|
"""Ensure authoritative data vault identities resolve strictly to BRAIN_DIR."""
|
||||||
|
brain_dir = tmp_path / "Brain"
|
||||||
|
brain_dir.mkdir()
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "BRAIN_DIR", brain_dir)
|
||||||
|
|
||||||
|
canonical = brain_dir.resolve()
|
||||||
|
assert gitops_dispatcher.resolve_repository("second-brain") == canonical
|
||||||
|
assert gitops_dispatcher.resolve_repository("Brain") == canonical
|
||||||
|
assert gitops_dispatcher.resolve_repository("brain") == canonical
|
||||||
|
|
||||||
|
|
||||||
|
def test_webhook_verification_valid_signature():
|
||||||
|
"""Ensure valid HMAC-SHA256 signature passes verification."""
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
|
||||||
|
secret = b"supersecrettoken123"
|
||||||
|
body = b'{"repository": {"name": "docs"}, "ref": "refs/heads/main"}'
|
||||||
|
expected_hex = hmac.new(secret, body, hashlib.sha256).hexdigest()
|
||||||
|
|
||||||
|
assert gitops_dispatcher.verify_signature(body, expected_hex, secret) is True
|
||||||
|
# Support sha256= prefix as well
|
||||||
|
assert gitops_dispatcher.verify_signature(body, f"sha256={expected_hex}", secret) is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_webhook_verification_invalid_signature():
|
||||||
|
"""Ensure incorrect signature is rejected."""
|
||||||
|
secret = b"supersecrettoken123"
|
||||||
|
body = b'{"repository": {"name": "docs"}}'
|
||||||
|
bad_sig = "a" * 64
|
||||||
|
|
||||||
|
assert gitops_dispatcher.verify_signature(body, bad_sig, secret) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_webhook_verification_missing_signature():
|
||||||
|
"""Ensure missing signature header is rejected."""
|
||||||
|
secret = b"supersecrettoken123"
|
||||||
|
body = b'{"repository": {"name": "docs"}}'
|
||||||
|
|
||||||
|
assert gitops_dispatcher.verify_signature(body, None, secret) is False
|
||||||
|
assert gitops_dispatcher.verify_signature(body, "", secret) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_webhook_verification_modified_body():
|
||||||
|
"""Ensure signature mismatch from tampered body fails verification."""
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
|
||||||
|
secret = b"supersecrettoken123"
|
||||||
|
body_original = b'{"repository": {"name": "docs"}}'
|
||||||
|
sig = hmac.new(secret, body_original, hashlib.sha256).hexdigest()
|
||||||
|
|
||||||
|
body_tampered = b'{"repository": {"name": "evil-app"}}'
|
||||||
|
assert gitops_dispatcher.verify_signature(body_tampered, sig, secret) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_webhook_verification_modified_signature():
|
||||||
|
"""Ensure single-character flip in signature fails verification."""
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
|
||||||
|
secret = b"supersecrettoken123"
|
||||||
|
body = b'{"repository": {"name": "docs"}}'
|
||||||
|
sig = list(hmac.new(secret, body, hashlib.sha256).hexdigest())
|
||||||
|
sig[0] = "0" if sig[0] != "0" else "1"
|
||||||
|
flipped_sig = "".join(sig)
|
||||||
|
|
||||||
|
assert gitops_dispatcher.verify_signature(body, flipped_sig, secret) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_webhook_verification_empty_secret_fails_closed():
|
||||||
|
"""Ensure empty or missing shared secret fails closed."""
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
|
||||||
|
secret = b""
|
||||||
|
body = b'{"repository": {"name": "docs"}}'
|
||||||
|
sig = hmac.new(b"somekey", body, hashlib.sha256).hexdigest()
|
||||||
|
|
||||||
|
assert gitops_dispatcher.verify_signature(body, sig, secret) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_webhook_verification_malformed_signature():
|
||||||
|
"""Ensure non-hex or invalid length signatures fail closed."""
|
||||||
|
secret = b"supersecrettoken123"
|
||||||
|
body = b'{"repository": {"name": "docs"}}'
|
||||||
|
|
||||||
|
assert gitops_dispatcher.verify_signature(body, "not-a-valid-hex-digest", secret) is False
|
||||||
|
assert gitops_dispatcher.verify_signature(body, "deadbeef", secret) is False
|
||||||
|
assert gitops_dispatcher.verify_signature(body, "z" * 64, secret) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_admission_rejects_non_push_events(tmp_path: Path):
|
||||||
|
"""Ensure non-push events such as pull_request or release are rejected."""
|
||||||
|
payload_pr = {
|
||||||
|
"ref": "refs/heads/main",
|
||||||
|
"repository": {"name": "docs"},
|
||||||
|
"pull_request": {"id": 1}
|
||||||
|
}
|
||||||
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload_pr, event_type="push")
|
||||||
|
assert admitted is False
|
||||||
|
assert "non-push event" in reason
|
||||||
|
|
||||||
|
payload_normal = {
|
||||||
|
"ref": "refs/heads/main",
|
||||||
|
"repository": {"name": "docs"}
|
||||||
|
}
|
||||||
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload_normal, event_type="pull_request")
|
||||||
|
assert admitted is False
|
||||||
|
assert "Only 'push' is allowed" in reason
|
||||||
|
|
||||||
|
|
||||||
|
def test_admission_rejects_tags_and_invalid_refs():
|
||||||
|
"""Ensure tags or invalid ref structures are rejected from deployment."""
|
||||||
|
tag_payload = {
|
||||||
|
"ref": "refs/tags/v1.0.0",
|
||||||
|
"repository": {"name": "docs"}
|
||||||
|
}
|
||||||
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(tag_payload, event_type="push")
|
||||||
|
assert admitted is False
|
||||||
|
assert "Tag push" in reason
|
||||||
|
|
||||||
|
non_head_payload = {
|
||||||
|
"ref": "refs/pull/42/head",
|
||||||
|
"repository": {"name": "docs"}
|
||||||
|
}
|
||||||
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(non_head_payload, event_type="push")
|
||||||
|
assert admitted is False
|
||||||
|
assert "not a head branch" in reason
|
||||||
|
|
||||||
|
|
||||||
|
def test_admission_rejects_unknown_repository(tmp_path: Path, monkeypatch):
|
||||||
|
"""Ensure unknown repositories cannot be admitted."""
|
||||||
|
sites_dir = tmp_path / "Sites"
|
||||||
|
sites_dir.mkdir()
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"ref": "refs/heads/main",
|
||||||
|
"repository": {"name": "unregistered-app"}
|
||||||
|
}
|
||||||
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
||||||
|
assert admitted is False
|
||||||
|
assert "not recognized" in reason
|
||||||
|
|
||||||
|
|
||||||
|
def test_admission_rejects_branch_mismatch(tmp_path: Path, monkeypatch):
|
||||||
|
"""Ensure push to branch different from declared deployment branch is rejected."""
|
||||||
|
sites_dir = tmp_path / "Sites"
|
||||||
|
app_dir = sites_dir / "homelab-docs"
|
||||||
|
app_dir.mkdir(parents=True)
|
||||||
|
(app_dir / "app.yaml").write_text(
|
||||||
|
"name: docs\ndeployment:\n branch: production\n",
|
||||||
|
encoding="utf-8"
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"ref": "refs/heads/staging",
|
||||||
|
"repository": {"name": "docs"}
|
||||||
|
}
|
||||||
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
||||||
|
assert admitted is False
|
||||||
|
assert "Branch mismatch" in reason
|
||||||
|
|
||||||
|
|
||||||
|
def test_admission_rejects_unsupported_strategy(tmp_path: Path, monkeypatch):
|
||||||
|
"""Ensure unsupported deployment strategy in app.yaml is rejected."""
|
||||||
|
sites_dir = tmp_path / "Sites"
|
||||||
|
app_dir = sites_dir / "homelab-docs"
|
||||||
|
app_dir.mkdir(parents=True)
|
||||||
|
(app_dir / "app.yaml").write_text(
|
||||||
|
"name: docs\ndeployment:\n branch: main\n strategy: kubernetes\n",
|
||||||
|
encoding="utf-8"
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"ref": "refs/heads/main",
|
||||||
|
"repository": {"name": "docs"}
|
||||||
|
}
|
||||||
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
||||||
|
assert admitted is False
|
||||||
|
assert "Unsupported deployment strategy" in reason
|
||||||
|
|
||||||
|
|
||||||
|
def test_admission_rejects_unsupported_actions(tmp_path: Path, monkeypatch):
|
||||||
|
"""Ensure unsupported deployment action in app.yaml is rejected."""
|
||||||
|
sites_dir = tmp_path / "Sites"
|
||||||
|
app_dir = sites_dir / "homelab-docs"
|
||||||
|
app_dir.mkdir(parents=True)
|
||||||
|
(app_dir / "app.yaml").write_text(
|
||||||
|
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n",
|
||||||
|
encoding="utf-8"
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"ref": "refs/heads/main",
|
||||||
|
"repository": {"name": "docs"}
|
||||||
|
}
|
||||||
|
admitted, _, _, _, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
||||||
|
assert admitted is False
|
||||||
|
assert "Unsupported deployment action" in reason
|
||||||
|
|
||||||
|
|
||||||
|
def test_admission_admits_valid_push(tmp_path: Path, monkeypatch):
|
||||||
|
"""Ensure valid push to declared branch on registered repo passes admission."""
|
||||||
|
sites_dir = tmp_path / "Sites"
|
||||||
|
app_dir = sites_dir / "homelab-docs"
|
||||||
|
app_dir.mkdir(parents=True)
|
||||||
|
(app_dir / "app.yaml").write_text(
|
||||||
|
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n",
|
||||||
|
encoding="utf-8"
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"ref": "refs/heads/main",
|
||||||
|
"repository": {"name": "docs"}
|
||||||
|
}
|
||||||
|
admitted, target_dir, config, branch, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
||||||
|
assert admitted is True
|
||||||
|
assert "Admitted" in reason
|
||||||
|
assert target_dir == app_dir.resolve()
|
||||||
|
assert branch == "main"
|
||||||
|
assert config["actions"] == ["git_pull", "compose_up"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_enqueue_supersedes_pending_revision(tmp_path: Path, monkeypatch):
|
||||||
|
"""Ensure newer pending deployment overwrites older pending deployment."""
|
||||||
|
state_dir = tmp_path / "state"
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "STATE_DIR", state_dir)
|
||||||
|
|
||||||
|
target_dir = tmp_path / "app"
|
||||||
|
target_dir.mkdir()
|
||||||
|
|
||||||
|
# Enqueue revision A
|
||||||
|
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "A"}, "main")
|
||||||
|
pending_file = gitops_dispatcher.get_pending_file("app")
|
||||||
|
assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "A"
|
||||||
|
|
||||||
|
# Enqueue revision B (supersedes A)
|
||||||
|
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "B"}, "main")
|
||||||
|
assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "B"
|
||||||
|
|
||||||
|
# Enqueue revision C (supersedes B)
|
||||||
|
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "C"}, "main")
|
||||||
|
assert json.loads(pending_file.read_text())["deployment_config"]["rev"] == "C"
|
||||||
|
|
||||||
|
|
||||||
|
def test_serialized_worker_race_superseding(tmp_path: Path, monkeypatch):
|
||||||
|
"""
|
||||||
|
Simulate race condition:
|
||||||
|
A starts
|
||||||
|
B arrives (enqueued)
|
||||||
|
C arrives (supersedes B)
|
||||||
|
A finishes
|
||||||
|
Verify: B is skipped, C is deployed.
|
||||||
|
"""
|
||||||
|
import threading
|
||||||
|
|
||||||
|
state_dir = tmp_path / "state"
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "STATE_DIR", state_dir)
|
||||||
|
|
||||||
|
target_dir = tmp_path / "app"
|
||||||
|
target_dir.mkdir()
|
||||||
|
|
||||||
|
executed_revisions = []
|
||||||
|
a_started_event = threading.Event()
|
||||||
|
b_and_c_enqueued_event = threading.Event()
|
||||||
|
|
||||||
|
def mock_execute(target, config, branch):
|
||||||
|
rev = config.get("rev", "unknown")
|
||||||
|
executed_revisions.append(rev)
|
||||||
|
if rev == "A":
|
||||||
|
a_started_event.set()
|
||||||
|
# Wait until B and C are enqueued
|
||||||
|
b_and_c_enqueued_event.wait(timeout=2.0)
|
||||||
|
return True
|
||||||
|
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "execute_deployment", mock_execute)
|
||||||
|
|
||||||
|
# 1. Enqueue A
|
||||||
|
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "A"}, "main")
|
||||||
|
|
||||||
|
# Start worker in thread (takes A)
|
||||||
|
worker_thread = threading.Thread(target=gitops_dispatcher.run_target_worker, args=("app",))
|
||||||
|
worker_thread.start()
|
||||||
|
|
||||||
|
# Wait for A to start executing
|
||||||
|
assert a_started_event.wait(timeout=2.0) is True
|
||||||
|
|
||||||
|
# 2. B arrives while A is running
|
||||||
|
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "B"}, "main")
|
||||||
|
|
||||||
|
# 3. C arrives while A is running (supersedes B)
|
||||||
|
gitops_dispatcher.enqueue_deployment(target_dir, {"branch": "main", "rev": "C"}, "main")
|
||||||
|
|
||||||
|
# Let A complete
|
||||||
|
b_and_c_enqueued_event.set()
|
||||||
|
|
||||||
|
worker_thread.join(timeout=3.0)
|
||||||
|
|
||||||
|
# Verification: A was executed, B was superseded/skipped, C was executed!
|
||||||
|
assert executed_revisions == ["A", "C"], f"Expected ['A', 'C'] but got {executed_revisions}"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
"""
|
||||||
|
Security invariant tests for Docker Compose and container isolation.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
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:
|
||||||
|
compose = yaml.safe_load(f)
|
||||||
|
|
||||||
|
services = compose.get("services", {})
|
||||||
|
assert "socket-proxy" in services, "socket-proxy service must exist"
|
||||||
|
|
||||||
|
env = services["socket-proxy"].get("environment", [])
|
||||||
|
env_dict = {}
|
||||||
|
for item in env:
|
||||||
|
if "=" in item:
|
||||||
|
k, v = item.split("=", 1)
|
||||||
|
env_dict[k.strip()] = v.strip()
|
||||||
|
|
||||||
|
assert env_dict.get("POST") == "0", "socket-proxy must strictly enforce POST=0"
|
||||||
|
assert env_dict.get("DELETE") == "0", "socket-proxy must strictly enforce DELETE=0"
|
||||||
|
assert env_dict.get("BUILD") == "0", "socket-proxy must strictly enforce BUILD=0"
|
||||||
|
assert env_dict.get("EXEC") == "0", "socket-proxy must strictly enforce EXEC=0"
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_direct_docker_sock_mounts_except_socket_proxy():
|
||||||
|
"""Ensure no application or control service mounts /var/run/docker.sock except socket-proxy:ro."""
|
||||||
|
compose_path = CORE_ROOT / "docker-compose.yml"
|
||||||
|
with open(compose_path, encoding="utf-8") as f:
|
||||||
|
compose = yaml.safe_load(f)
|
||||||
|
|
||||||
|
services = compose.get("services", {})
|
||||||
|
for name, svc in services.items():
|
||||||
|
volumes = svc.get("volumes", [])
|
||||||
|
for vol in volumes:
|
||||||
|
if isinstance(vol, str) and "/var/run/docker.sock" in vol:
|
||||||
|
assert name == "socket-proxy", f"Service '{name}' directly mounts docker.sock!"
|
||||||
|
assert vol.endswith(":ro"), "socket-proxy docker.sock mount must be read-only (:ro)"
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_privileged_containers():
|
||||||
|
"""Ensure no service in core docker-compose runs with privileged: true."""
|
||||||
|
compose_path = CORE_ROOT / "docker-compose.yml"
|
||||||
|
with open(compose_path, encoding="utf-8") as f:
|
||||||
|
compose = yaml.safe_load(f)
|
||||||
|
|
||||||
|
services = compose.get("services", {})
|
||||||
|
for name, svc in services.items():
|
||||||
|
privileged = svc.get("privileged", False)
|
||||||
|
assert privileged is not True, f"Service '{name}' is configured as privileged: true!"
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_shell_true_in_core_scripts():
|
||||||
|
"""Ensure shell=True is completely absent from gitops execution engines."""
|
||||||
|
scripts_dir = CORE_ROOT / "scripts"
|
||||||
|
for py_file in scripts_dir.glob("*.py"):
|
||||||
|
content = py_file.read_text(encoding="utf-8")
|
||||||
|
assert "shell=True" not in content, f"shell=True detected in {py_file.name}!"
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"""
|
||||||
|
Structural invariant tests for Homelab Core repository layout.
|
||||||
|
Ensures required architectural components exist and deprecated paths do not return.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
CORE_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||||
|
|
||||||
|
|
||||||
|
def test_required_architectural_paths_exist():
|
||||||
|
"""Ensure core architectural files and directories exist."""
|
||||||
|
required_paths = [
|
||||||
|
"docker-compose.yml",
|
||||||
|
"flake.nix",
|
||||||
|
"UNLICENSE",
|
||||||
|
"AGENTS.md",
|
||||||
|
"README.md",
|
||||||
|
"SECURITY.md",
|
||||||
|
"nixos",
|
||||||
|
"nixos/configuration.nix",
|
||||||
|
"nixos/modules/homeserver.nix",
|
||||||
|
"nixos/secrets.yaml",
|
||||||
|
"scripts/gitops_dispatcher.py",
|
||||||
|
"scripts/appctl",
|
||||||
|
"scripts/appctl_engine.py",
|
||||||
|
"tests",
|
||||||
|
]
|
||||||
|
|
||||||
|
for p in required_paths:
|
||||||
|
target = CORE_ROOT / p
|
||||||
|
assert target.exists(), f"Required architectural path missing: {p}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_deprecated_legacy_structures_are_absent():
|
||||||
|
"""Ensure deprecated files and legacy layouts are not reintroduced."""
|
||||||
|
prohibited_paths = [
|
||||||
|
"infra/core",
|
||||||
|
"up.sh",
|
||||||
|
"down.sh",
|
||||||
|
"scripts/check-ssl.sh",
|
||||||
|
"scripts/purge-dynu.sh",
|
||||||
|
"scripts/ip-monitor.sh",
|
||||||
|
]
|
||||||
|
|
||||||
|
for p in prohibited_paths:
|
||||||
|
target = CORE_ROOT / p
|
||||||
|
assert not target.exists(), f"Prohibited deprecated path detected: {p}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_unlicense_preserved():
|
||||||
|
"""Ensure The Unlicense (public domain invariant) is maintained."""
|
||||||
|
unlicense = CORE_ROOT / "UNLICENSE"
|
||||||
|
assert unlicense.is_file(), "UNLICENSE file must be present"
|
||||||
|
content = unlicense.read_text(encoding="utf-8")
|
||||||
|
assert "This is free and unencumbered software released into the public domain." in content
|
||||||
Reference in new issue
Block a user