diff --git a/scripts/appctl b/scripts/appctl index 0d726c4..a9b045c 100755 --- a/scripts/appctl +++ b/scripts/appctl @@ -107,14 +107,21 @@ setup_app_env() { export DOMAIN="$RESOLVED_DOMAIN" # 3. Dynamic environment variables from app.yaml (e.g. PROJECT_PATH, MEDIA_PATH, etc.) - eval "$(python3 -c " -import json, sys + 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', {}) -for k, v in env_dict.items(): - if v != '' and v is not None: - print(f'export {k}=\"{v}\"') -" "$resolved_json")" +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") # 4. Source local .env if present if [ -f "$APP_DIR/.env" ]; then diff --git a/scripts/core_manifest.py b/scripts/core_manifest.py index 2ce4dc0..fba8a3d 100644 --- a/scripts/core_manifest.py +++ b/scripts/core_manifest.py @@ -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}$") 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)?$") +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_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 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 deployment_raw = data.get("deployment") diff --git a/tests/security/test_security_invariants.py b/tests/security/test_security_invariants.py index 530da3c..1c9cd79 100644 --- a/tests/security/test_security_invariants.py +++ b/tests/security/test_security_invariants.py @@ -77,3 +77,68 @@ def test_portainer_is_deprecated_and_absent(): volumes = compose.get("volumes", {}) or {} 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 + + + diff --git a/tests/unit/test_core_manifest.py b/tests/unit/test_core_manifest.py index 34aa9fa..4b6f5dd 100644 --- a/tests/unit/test_core_manifest.py +++ b/tests/unit/test_core_manifest.py @@ -181,3 +181,39 @@ def test_parse_manifest_from_path(tmp_path: Path): manifest = parse_manifest(manifest_file) assert manifest.name == "file-app" 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" + diff --git a/todo.txt b/todo.txt index 31bb108..4d2d4bf 100644 --- a/todo.txt +++ b/todo.txt @@ -11,3 +11,14 @@ 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) 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-14 (A) Eliminate eval in scripts/appctl and enforce strict env key validation in scripts/core_manifest.py +security @appctl +(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