Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d9a2ce511 | ||
|
|
667f8d19b9 |
No files matched your search
+13
-6
@@ -107,14 +107,21 @@ setup_app_env() {
|
|||||||
export DOMAIN="$RESOLVED_DOMAIN"
|
export DOMAIN="$RESOLVED_DOMAIN"
|
||||||
|
|
||||||
# 3. Dynamic environment variables from app.yaml (e.g. PROJECT_PATH, MEDIA_PATH, etc.)
|
# 3. Dynamic environment variables from app.yaml (e.g. PROJECT_PATH, MEDIA_PATH, etc.)
|
||||||
eval "$(python3 -c "
|
while IFS= read -r -d '' k && IFS= read -r -d '' v; do
|
||||||
import json, sys
|
export "$k=$v"
|
||||||
|
done < <(python3 -c "
|
||||||
|
import json, re, sys
|
||||||
|
RESERVED = {'PATH', 'LD_PRELOAD', 'IFS', 'SHELL', 'USER', 'CORE_DIR', 'SITES_DIR', 'ENV_FILE', 'HOMESERVER_ENV'}
|
||||||
d = json.loads(sys.argv[1])
|
d = json.loads(sys.argv[1])
|
||||||
env_dict = d.get('env', {})
|
env_dict = d.get('env', {})
|
||||||
for k, v in env_dict.items():
|
if isinstance(env_dict, dict):
|
||||||
if v != '' and v is not None:
|
for k, v in env_dict.items():
|
||||||
print(f'export {k}=\"{v}\"')
|
k_str = str(k).strip()
|
||||||
" "$resolved_json")"
|
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', k_str) or k_str in RESERVED:
|
||||||
|
continue
|
||||||
|
if v is not None and v != '':
|
||||||
|
sys.stdout.buffer.write(k_str.encode('utf-8') + b'\0' + str(v).encode('utf-8') + b'\0')
|
||||||
|
" "$resolved_json")
|
||||||
|
|
||||||
# 4. Source local .env if present
|
# 4. Source local .env if present
|
||||||
if [ -f "$APP_DIR/.env" ]; then
|
if [ -f "$APP_DIR/.env" ]; then
|
||||||
|
|||||||
@@ -49,6 +49,11 @@ COMMIT_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$")
|
|||||||
SHORT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,12}$")
|
SHORT_SHA_RE = re.compile(r"^[0-9a-fA-F]{7,12}$")
|
||||||
SEMVER_TAG_RE = re.compile(r"^v?[0-9]+(\.[0-9]+)+([a-zA-Z0-9._-]*)$")
|
SEMVER_TAG_RE = re.compile(r"^v?[0-9]+(\.[0-9]+)+([a-zA-Z0-9._-]*)$")
|
||||||
SCP_URL_RE = re.compile(r"^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+:([0-9]+/)?([a-zA-Z0-9._-]+/)*[a-zA-Z0-9._-]+(\.git)?$")
|
SCP_URL_RE = re.compile(r"^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+:([0-9]+/)?([a-zA-Z0-9._-]+/)*[a-zA-Z0-9._-]+(\.git)?$")
|
||||||
|
ENV_KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
|
||||||
|
RESERVED_ENV_KEYS = {
|
||||||
|
"PATH", "LD_PRELOAD", "IFS", "SHELL", "USER",
|
||||||
|
"CORE_DIR", "SITES_DIR", "ENV_FILE", "HOMESERVER_ENV"
|
||||||
|
}
|
||||||
|
|
||||||
ALLOWED_STRATEGIES = {"compose"}
|
ALLOWED_STRATEGIES = {"compose"}
|
||||||
ALLOWED_ACTIONS = {"git_pull", "compose_up", "compose_build", "compose_restart"}
|
ALLOWED_ACTIONS = {"git_pull", "compose_up", "compose_build", "compose_restart"}
|
||||||
@@ -313,7 +318,16 @@ def parse_manifest(raw_input: str | Path | dict[str, Any]) -> Manifest:
|
|||||||
|
|
||||||
# 7. Environment overrides
|
# 7. Environment overrides
|
||||||
env_raw = data.get("env", {})
|
env_raw = data.get("env", {})
|
||||||
env = dict(env_raw) if isinstance(env_raw, dict) else {}
|
env: dict[str, str] = {}
|
||||||
|
if isinstance(env_raw, dict):
|
||||||
|
for raw_k, raw_v in env_raw.items():
|
||||||
|
k_str = str(raw_k).strip()
|
||||||
|
if not ENV_KEY_RE.match(k_str) or k_str in RESERVED_ENV_KEYS:
|
||||||
|
raise ManifestValidationError(
|
||||||
|
f"Invalid or reserved environment variable key '{k_str}'. "
|
||||||
|
f"Keys must match ^[a-zA-Z_][a-zA-Z0-9_]*$ and cannot be reserved."
|
||||||
|
)
|
||||||
|
env[k_str] = str(raw_v) if raw_v is not None else ""
|
||||||
|
|
||||||
# 8. Deployment Policy
|
# 8. Deployment Policy
|
||||||
deployment_raw = data.get("deployment")
|
deployment_raw = data.get("deployment")
|
||||||
|
|||||||
@@ -156,13 +156,17 @@ def get_trusted_repository_mapping() -> dict[str, Path]:
|
|||||||
"""
|
"""
|
||||||
Build authoritative mapping of logical repository identities to local paths.
|
Build authoritative mapping of logical repository identities to local paths.
|
||||||
Webhook payloads can only select repositories defined in this mapping.
|
Webhook payloads can only select repositories defined in this mapping.
|
||||||
Prioritizes Core Authoritative Registry (deployments.yaml) over dynamic discovery.
|
Core Authoritative Registry (deployments.yaml) is the sole admission authority.
|
||||||
|
Fails closed if the registry is missing, unreadable, or malformed.
|
||||||
"""
|
"""
|
||||||
mapping: dict[str, Path] = {}
|
mapping: dict[str, Path] = {}
|
||||||
|
|
||||||
# 1. Authoritative Core Repository Registry (deployments.yaml)
|
|
||||||
registry_file = DEPLOYMENTS_FILE if DEPLOYMENTS_FILE.is_file() else (CONFIG_DIR / "deployments.yaml")
|
registry_file = DEPLOYMENTS_FILE if DEPLOYMENTS_FILE.is_file() else (CONFIG_DIR / "deployments.yaml")
|
||||||
if registry_file.is_file():
|
if not registry_file.is_file():
|
||||||
|
logger.error(f"Authoritative registry {registry_file} not found. Failing closed with zero admitted repositories.")
|
||||||
|
return mapping
|
||||||
|
|
||||||
|
yaml_errors = (yaml.YAMLError,) if yaml is not None else ()
|
||||||
try:
|
try:
|
||||||
content = registry_file.read_text(encoding="utf-8")
|
content = registry_file.read_text(encoding="utf-8")
|
||||||
registry = (yaml.safe_load(content) if yaml else parse_yaml_simple(content)) or {}
|
registry = (yaml.safe_load(content) if yaml else parse_yaml_simple(content)) or {}
|
||||||
@@ -187,59 +191,19 @@ def get_trusted_repository_mapping() -> dict[str, Path]:
|
|||||||
mapping[alias.strip()] = p
|
mapping[alias.strip()] = p
|
||||||
else:
|
else:
|
||||||
logger.warning(f"Rejecting out-of-bounds path in deployments.yaml for '{reg_name}': {p}")
|
logger.warning(f"Rejecting out-of-bounds path in deployments.yaml for '{reg_name}': {p}")
|
||||||
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
else:
|
||||||
logger.warning(f"Failed to parse authoritative registry {registry_file}: {e}")
|
logger.error(f"Malformed repositories block in {registry_file}: expected dictionary mapping.")
|
||||||
|
return {}
|
||||||
|
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError, TypeError, *yaml_errors) as e:
|
||||||
|
logger.critical(f"Failed to parse authoritative registry {registry_file}: {e}. Failing closed.")
|
||||||
|
return {}
|
||||||
|
|
||||||
# 2. Dynamic Discovery in SITES_DIR (for workloads not explicitly registered)
|
|
||||||
if SITES_DIR.is_dir():
|
|
||||||
sites_canonical = SITES_DIR.resolve()
|
|
||||||
for entry in SITES_DIR.iterdir():
|
|
||||||
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 if not already mapped
|
|
||||||
dir_name = entry.name
|
|
||||||
if dir_name not in mapping:
|
|
||||||
mapping[dir_name] = resolved_entry
|
|
||||||
|
|
||||||
# Parse app.yaml for canonical name and aliases
|
|
||||||
manifest = {}
|
|
||||||
try:
|
|
||||||
manifest_text = manifest_file.read_text(encoding="utf-8")
|
|
||||||
manifest = (yaml.safe_load(manifest_text) if yaml else parse_yaml_simple(manifest_text)) or {}
|
|
||||||
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
|
||||||
logger.warning(f"Failed to parse {manifest_file}: {e}")
|
|
||||||
|
|
||||||
canonical_name = manifest.get("name")
|
|
||||||
if canonical_name and isinstance(canonical_name, str):
|
|
||||||
canonical_name = canonical_name.strip()
|
|
||||||
if canonical_name not in mapping:
|
|
||||||
mapping[canonical_name] = resolved_entry
|
|
||||||
alias_with_prefix = f"homelab-{canonical_name}" if not canonical_name.startswith("homelab-") else canonical_name.replace("homelab-", "", 1)
|
|
||||||
if alias_with_prefix not in mapping:
|
|
||||||
mapping[alias_with_prefix] = resolved_entry
|
|
||||||
|
|
||||||
aliases = manifest.get("aliases", [])
|
|
||||||
if isinstance(aliases, str):
|
|
||||||
aliases = [aliases]
|
|
||||||
if isinstance(aliases, list):
|
|
||||||
for alias in aliases:
|
|
||||||
if isinstance(alias, str) and alias.strip() and alias.strip() not in mapping:
|
|
||||||
mapping[alias.strip()] = resolved_entry
|
|
||||||
|
|
||||||
return mapping
|
return mapping
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_repository(repo_name: str) -> Path | None:
|
def resolve_repository(repo_name: str) -> Path | None:
|
||||||
"""
|
"""
|
||||||
Resolve a logical repository identity to a trusted local directory.
|
Resolve a logical repository identity to a trusted local directory.
|
||||||
|
|||||||
@@ -122,7 +122,14 @@ def test_resolve_repository_resolves_valid_manifest(tmp_path: Path, monkeypatch)
|
|||||||
encoding="utf-8"
|
encoding="utf-8"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
registry = tmp_path / "deployments.yaml"
|
||||||
|
registry.write_text(
|
||||||
|
f'schemaVersion: "1.0"\nrepositories:\n homelab-docs:\n path: "{app_dir}"\n aliases:\n - docs\n - doc2site\n - notes\n',
|
||||||
|
encoding="utf-8"
|
||||||
|
)
|
||||||
|
|
||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
canonical = app_dir.resolve()
|
canonical = app_dir.resolve()
|
||||||
assert gitops_dispatcher.resolve_repository("homelab-docs") == canonical
|
assert gitops_dispatcher.resolve_repository("homelab-docs") == canonical
|
||||||
@@ -131,6 +138,7 @@ def test_resolve_repository_resolves_valid_manifest(tmp_path: Path, monkeypatch)
|
|||||||
assert gitops_dispatcher.resolve_repository("notes") == canonical
|
assert gitops_dispatcher.resolve_repository("notes") == canonical
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_resolve_repository_rejects_vault(tmp_path: Path, monkeypatch):
|
def test_resolve_repository_rejects_vault(tmp_path: Path, monkeypatch):
|
||||||
"""Ensure data vault identities (Brain / second-brain) are not recognized by GitOps."""
|
"""Ensure data vault identities (Brain / second-brain) are not recognized by GitOps."""
|
||||||
sites_dir = tmp_path / "Sites"
|
sites_dir = tmp_path / "Sites"
|
||||||
@@ -179,6 +187,57 @@ repositories:
|
|||||||
assert "escaped-app" not in mapping
|
assert "escaped-app" not in mapping
|
||||||
|
|
||||||
|
|
||||||
|
def test_unregistered_sites_directory_rejected_when_registry_active(tmp_path: Path, monkeypatch):
|
||||||
|
"""Ensure unregistered directories in ~/Sites cannot be resolved when deployments.yaml is active."""
|
||||||
|
sites_dir = tmp_path / "Sites"
|
||||||
|
registered_dir = sites_dir / "homelab-docs"
|
||||||
|
unregistered_dir = sites_dir / "rogue-workload"
|
||||||
|
registered_dir.mkdir(parents=True)
|
||||||
|
unregistered_dir.mkdir(parents=True)
|
||||||
|
(registered_dir / "app.yaml").write_text("name: docs\n", encoding="utf-8")
|
||||||
|
(unregistered_dir / "app.yaml").write_text("name: rogue\n", encoding="utf-8")
|
||||||
|
|
||||||
|
registry = tmp_path / "deployments.yaml"
|
||||||
|
registry.write_text(
|
||||||
|
f'schemaVersion: "1.0"\nrepositories:\n docs:\n path: "{registered_dir}"\n',
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
|
assert gitops_dispatcher.resolve_repository("docs") == registered_dir.resolve()
|
||||||
|
# Unregistered workload must be rejected despite having app.yaml in Sites
|
||||||
|
assert gitops_dispatcher.resolve_repository("rogue") is None
|
||||||
|
assert gitops_dispatcher.resolve_repository("rogue-workload") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_or_corrupt_registry_fails_closed(tmp_path: Path, monkeypatch):
|
||||||
|
"""Ensure missing or corrupted deployments.yaml fails closed without falling back to directory scanning."""
|
||||||
|
sites_dir = tmp_path / "Sites"
|
||||||
|
app_dir = sites_dir / "valid-app"
|
||||||
|
app_dir.mkdir(parents=True)
|
||||||
|
(app_dir / "app.yaml").write_text("name: valid\n", encoding="utf-8")
|
||||||
|
|
||||||
|
missing_registry = tmp_path / "nonexistent-deployments.yaml"
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", missing_registry)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "CONFIG_DIR", tmp_path / "nonexistent-config")
|
||||||
|
|
||||||
|
# Missing registry must fail closed: empty mapping, no resolution
|
||||||
|
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
|
||||||
|
assert gitops_dispatcher.resolve_repository("valid") is None
|
||||||
|
|
||||||
|
# Corrupt YAML registry must also fail closed
|
||||||
|
corrupt_registry = tmp_path / "corrupt-deployments.yaml"
|
||||||
|
corrupt_registry.write_text("schemaVersion: 1.0\nrepositories: [bad list syntax", encoding="utf-8")
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", corrupt_registry)
|
||||||
|
|
||||||
|
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
|
||||||
|
assert gitops_dispatcher.resolve_repository("valid") is None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_webhook_verification_valid_signature():
|
def test_webhook_verification_valid_signature():
|
||||||
"""Ensure valid HMAC-SHA256 signature passes verification."""
|
"""Ensure valid HMAC-SHA256 signature passes verification."""
|
||||||
import hashlib
|
import hashlib
|
||||||
@@ -323,7 +382,13 @@ def test_admission_rejects_branch_mismatch(tmp_path: Path, monkeypatch):
|
|||||||
"name: docs\ndeployment:\n branch: production\n",
|
"name: docs\ndeployment:\n branch: production\n",
|
||||||
encoding="utf-8"
|
encoding="utf-8"
|
||||||
)
|
)
|
||||||
|
registry = tmp_path / "deployments.yaml"
|
||||||
|
registry.write_text(
|
||||||
|
f'schemaVersion: "1.0"\nrepositories:\n docs:\n path: "{app_dir}"\n',
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"ref": "refs/heads/staging",
|
"ref": "refs/heads/staging",
|
||||||
@@ -343,7 +408,13 @@ def test_admission_rejects_unsupported_strategy(tmp_path: Path, monkeypatch):
|
|||||||
"name: docs\ndeployment:\n branch: main\n strategy: kubernetes\n",
|
"name: docs\ndeployment:\n branch: main\n strategy: kubernetes\n",
|
||||||
encoding="utf-8"
|
encoding="utf-8"
|
||||||
)
|
)
|
||||||
|
registry = tmp_path / "deployments.yaml"
|
||||||
|
registry.write_text(
|
||||||
|
f'schemaVersion: "1.0"\nrepositories:\n docs:\n path: "{app_dir}"\n',
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"ref": "refs/heads/main",
|
"ref": "refs/heads/main",
|
||||||
@@ -363,7 +434,13 @@ def test_admission_rejects_unsupported_actions(tmp_path: Path, monkeypatch):
|
|||||||
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n",
|
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n",
|
||||||
encoding="utf-8"
|
encoding="utf-8"
|
||||||
)
|
)
|
||||||
|
registry = tmp_path / "deployments.yaml"
|
||||||
|
registry.write_text(
|
||||||
|
f'schemaVersion: "1.0"\nrepositories:\n docs:\n path: "{app_dir}"\n',
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"ref": "refs/heads/main",
|
"ref": "refs/heads/main",
|
||||||
@@ -383,7 +460,13 @@ def test_admission_admits_valid_push(tmp_path: Path, monkeypatch):
|
|||||||
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n",
|
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n",
|
||||||
encoding="utf-8"
|
encoding="utf-8"
|
||||||
)
|
)
|
||||||
|
registry = tmp_path / "deployments.yaml"
|
||||||
|
registry.write_text(
|
||||||
|
f'schemaVersion: "1.0"\nrepositories:\n docs:\n path: "{app_dir}"\n',
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"ref": "refs/heads/main",
|
"ref": "refs/heads/main",
|
||||||
@@ -391,6 +474,7 @@ def test_admission_admits_valid_push(tmp_path: Path, monkeypatch):
|
|||||||
}
|
}
|
||||||
admitted, target_dir, config, branch, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
admitted, target_dir, config, branch, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
||||||
assert admitted is True
|
assert admitted is True
|
||||||
|
|
||||||
assert "Admitted" in reason
|
assert "Admitted" in reason
|
||||||
assert target_dir == app_dir.resolve()
|
assert target_dir == app_dir.resolve()
|
||||||
assert branch == "main"
|
assert branch == "main"
|
||||||
|
|||||||
@@ -77,3 +77,68 @@ def test_portainer_is_deprecated_and_absent():
|
|||||||
|
|
||||||
volumes = compose.get("volumes", {}) or {}
|
volumes = compose.get("volumes", {}) or {}
|
||||||
assert "portainer_data" not in volumes, "Deprecated volume 'portainer_data' must not exist in docker-compose.yml"
|
assert "portainer_data" not in volumes, "Deprecated volume 'portainer_data' must not exist in docker-compose.yml"
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_eval_in_appctl_script():
|
||||||
|
"""Ensure scripts/appctl never uses eval on dynamic environment or manifest payloads."""
|
||||||
|
appctl_path = CORE_ROOT / "scripts" / "appctl"
|
||||||
|
content = appctl_path.read_text(encoding="utf-8")
|
||||||
|
assert "eval " not in content, "Dangerous 'eval' detected in scripts/appctl!"
|
||||||
|
|
||||||
|
|
||||||
|
def test_appctl_env_injection_resilience(tmp_path: Path):
|
||||||
|
"""Ensure environment values from app.yaml cannot execute shell commands via command substitution."""
|
||||||
|
canary = tmp_path / "pwned.txt"
|
||||||
|
payload = f"$(touch {canary})"
|
||||||
|
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
appctl_path = CORE_ROOT / "scripts" / "appctl"
|
||||||
|
appctl_content = appctl_path.read_text(encoding="utf-8")
|
||||||
|
assert "eval " not in appctl_content
|
||||||
|
assert "while IFS= read -r -d '' k && IFS= read -r -d '' v; do" in appctl_content
|
||||||
|
|
||||||
|
resolved_json = json.dumps({
|
||||||
|
"name": "test-app",
|
||||||
|
"domain": "test.roadtotech.me",
|
||||||
|
"dir_path": str(tmp_path),
|
||||||
|
"env": {"INJECTION_TEST": payload, "NORMAL_VAR": "safe_value"},
|
||||||
|
})
|
||||||
|
|
||||||
|
bash_code = f"""
|
||||||
|
set -euo pipefail
|
||||||
|
resolved_json='{resolved_json}'
|
||||||
|
while IFS= read -r -d '' k && IFS= read -r -d '' v; do
|
||||||
|
export "$k=$v"
|
||||||
|
done < <(python3 -c "
|
||||||
|
import json, re, sys
|
||||||
|
RESERVED = {{'PATH', 'LD_PRELOAD', 'IFS', 'SHELL', 'USER', 'CORE_DIR', 'SITES_DIR', 'ENV_FILE', 'HOMESERVER_ENV'}}
|
||||||
|
d = json.loads(sys.argv[1])
|
||||||
|
env_dict = d.get('env', {{}})
|
||||||
|
if isinstance(env_dict, dict):
|
||||||
|
for k, v in env_dict.items():
|
||||||
|
k_str = str(k).strip()
|
||||||
|
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', k_str) or k_str in RESERVED:
|
||||||
|
continue
|
||||||
|
if v is not None and v != '':
|
||||||
|
sys.stdout.buffer.write(k_str.encode('utf-8') + b'\\0' + str(v).encode('utf-8') + b'\\0')
|
||||||
|
" "$resolved_json")
|
||||||
|
|
||||||
|
echo "INJECTION_TEST=$INJECTION_TEST"
|
||||||
|
echo "NORMAL_VAR=$NORMAL_VAR"
|
||||||
|
"""
|
||||||
|
|
||||||
|
res = subprocess.run(
|
||||||
|
["bash", "-c", bash_code],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
assert not canary.exists(), "Command substitution was executed on the host during environment setup!"
|
||||||
|
assert res.returncode == 0, f"Extraction failed: {res.stderr}"
|
||||||
|
assert f"INJECTION_TEST={payload}" in res.stdout
|
||||||
|
assert "NORMAL_VAR=safe_value" in res.stdout
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -181,3 +181,39 @@ def test_parse_manifest_from_path(tmp_path: Path):
|
|||||||
manifest = parse_manifest(manifest_file)
|
manifest = parse_manifest(manifest_file)
|
||||||
assert manifest.name == "file-app"
|
assert manifest.name == "file-app"
|
||||||
assert manifest.is_internal is True
|
assert manifest.is_internal is True
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("invalid_key", [
|
||||||
|
"123_BAD",
|
||||||
|
"INVALID-KEY",
|
||||||
|
"FOO;BAR",
|
||||||
|
"KEY WITH SPACE",
|
||||||
|
"PATH",
|
||||||
|
"LD_PRELOAD",
|
||||||
|
"IFS",
|
||||||
|
"CORE_DIR",
|
||||||
|
"SITES_DIR",
|
||||||
|
])
|
||||||
|
def test_parse_manifest_rejects_invalid_or_reserved_env_keys(invalid_key: str):
|
||||||
|
raw_yaml = f"""
|
||||||
|
name: "app"
|
||||||
|
env:
|
||||||
|
"{invalid_key}": "some_value"
|
||||||
|
"""
|
||||||
|
with pytest.raises(ManifestValidationError, match="Invalid or reserved environment variable key"):
|
||||||
|
parse_manifest(raw_yaml)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_manifest_accepts_valid_env_keys():
|
||||||
|
raw_yaml = """
|
||||||
|
name: "app"
|
||||||
|
env:
|
||||||
|
PROJECT_PATH: "/mnt/data"
|
||||||
|
CUSTOM_PORT_1: "8080"
|
||||||
|
_INTERNAL_FLAG: "true"
|
||||||
|
"""
|
||||||
|
manifest = parse_manifest(raw_yaml)
|
||||||
|
assert manifest.env["PROJECT_PATH"] == "/mnt/data"
|
||||||
|
assert manifest.env["CUSTOM_PORT_1"] == "8080"
|
||||||
|
assert manifest.env["_INTERNAL_FLAG"] == "true"
|
||||||
|
|
||||||
@@ -11,3 +11,15 @@ x 2026-10-13 (A) Close authorization design enforcing token-everywhere policy in
|
|||||||
x 2026-10-13 (B) Specify daemon execution and privilege boundaries for Docker, subprocesses, and filesystem roots in docs/plans/p4-readiness-plan.md +security @p4-gate
|
x 2026-10-13 (B) Specify daemon execution and privilege boundaries for Docker, subprocesses, and filesystem roots in docs/plans/p4-readiness-plan.md +security @p4-gate
|
||||||
x 2026-10-13 (B) Define append-only audit telemetry schema, lifecycle, and failure handling semantics in docs/plans/p4-readiness-plan.md +audit @p4-gate
|
x 2026-10-13 (B) Define append-only audit telemetry schema, lifecycle, and failure handling semantics in docs/plans/p4-readiness-plan.md +audit @p4-gate
|
||||||
x 2026-10-13 (C) Establish P4 acceptance test matrix and definition of done before daemon implementation in docs/plans/p4-readiness-plan.md +test @p4-gate
|
x 2026-10-13 (C) Establish P4 acceptance test matrix and definition of done before daemon implementation in docs/plans/p4-readiness-plan.md +test @p4-gate
|
||||||
|
x 2026-10-14 (A) Eliminate eval in scripts/appctl and enforce strict env key validation in scripts/core_manifest.py +security @appctl
|
||||||
|
x 2026-10-15 (A) Enforce deployments.yaml as sole registry and remove dynamic discovery fallback in scripts/gitops_dispatcher.py +registry @gitops
|
||||||
|
|
||||||
|
(A) Harden validate_compose_security in scripts/gitops_dispatcher.py blocking relative traversal, cross-tenant mounts, and privilege escalation +compose @gitops
|
||||||
|
(A) Unify manifest parsing on core_manifest.py and eliminate duplicate parsers in scripts/appctl_engine.py +manifest @engine
|
||||||
|
(A) Scaffold asyncio daemon server supporting dual transports (Unix socket /run/homelab/appctl.sock and HTTP) in scripts/appctl_daemon.py +daemon @p4
|
||||||
|
(A) Implement unit and integration tests for dual-transport requests and error handling in tests/unit/test_appctl_daemon.py +test @p4
|
||||||
|
(B) Implement command-oriented operational router wiring domain actions to in-process appctl_engine.py methods and fixed subprocess executions +router @p4
|
||||||
|
(B) Implement token authentication middleware validating user-scoped Bearer tokens for mutating requests +auth @p4
|
||||||
|
(B) Implement append-only audit logger writing structured RFC JSONL records with fail-closed disk guard +audit @p4
|
||||||
|
(C) Re-implement scripts/appctl as a thin client dispatching JSON requests to the daemon Unix domain socket +cli @p4
|
||||||
|
(C) Create NixOS systemd unit module for homelab-appctl.service with strict sandboxing and socket management +nixos @p4
|
||||||
Reference in new issue
Block a user