From 4f406685362c4fa223305e0e14b2b74a0cb06463 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 21 Nov 2026 03:58:21 -0500 Subject: [PATCH] feat(security): add Pydantic workload grants loader, RESERVED_ENV_KEYS, and error code - Add HOMELAB_GRANTS_FILE to RESERVED_ENV_KEYS in scripts/core_manifest.py - Add ERR_CAPABILITY_NOT_GRANTED (HTTP 403) to ErrorCode in scripts/appctl_contracts.py - Implement WorkloadGrant, GrantsRegistry, and load_workload_grants in scripts/workload_grants.py with strict Pydantic v2 and fail-closed permission/integrity checks - Add unit tests for workload_grants, RESERVED_ENV_KEYS, and ErrorCode taxonomy --- scripts/appctl_contracts.py | 4 +- scripts/core_manifest.py | 1 + scripts/workload_grants.py | 149 ++++++++++++++++++++++++++++ tests/unit/test_appctl_contracts.py | 6 +- tests/unit/test_core_manifest.py | 12 +++ tests/unit/test_workload_grants.py | 148 +++++++++++++++++++++++++++ 6 files changed, 317 insertions(+), 3 deletions(-) create mode 100644 scripts/workload_grants.py create mode 100644 tests/unit/test_workload_grants.py diff --git a/scripts/appctl_contracts.py b/scripts/appctl_contracts.py index d85dbe3..96cf190 100644 --- a/scripts/appctl_contracts.py +++ b/scripts/appctl_contracts.py @@ -116,11 +116,12 @@ FlexibleWorkloadAction = FlexibleOperationType class ErrorCode(StrEnum): - """Canonical 6-code error taxonomy for homelab-appctl.service.""" + """Canonical 7-code error taxonomy for homelab-appctl.service.""" ERR_VALIDATION_FAILED = "ERR_VALIDATION_FAILED" ERR_AUTH_REQUIRED = "ERR_AUTH_REQUIRED" ERR_PERMISSION_DENIED = "ERR_PERMISSION_DENIED" + ERR_CAPABILITY_NOT_GRANTED = "ERR_CAPABILITY_NOT_GRANTED" ERR_TARGET_NOT_FOUND = "ERR_TARGET_NOT_FOUND" ERR_CONCURRENT_MUTATION = "ERR_CONCURRENT_MUTATION" ERR_EXECUTION_FAILED = "ERR_EXECUTION_FAILED" @@ -134,6 +135,7 @@ ERROR_HTTP_STATUS: dict[ErrorCode, int] = { ErrorCode.ERR_VALIDATION_FAILED: 400, ErrorCode.ERR_AUTH_REQUIRED: 401, ErrorCode.ERR_PERMISSION_DENIED: 403, + ErrorCode.ERR_CAPABILITY_NOT_GRANTED: 403, ErrorCode.ERR_TARGET_NOT_FOUND: 404, ErrorCode.ERR_CONCURRENT_MUTATION: 409, ErrorCode.ERR_EXECUTION_FAILED: 500, diff --git a/scripts/core_manifest.py b/scripts/core_manifest.py index efb4735..a194c9b 100644 --- a/scripts/core_manifest.py +++ b/scripts/core_manifest.py @@ -81,6 +81,7 @@ RESERVED_ENV_KEYS = { "SERVICE_NAME", "CONTAINER_NAME", "SERVICE_DOMAIN", + "HOMELAB_GRANTS_FILE", } ALLOWED_STRATEGIES = {"compose"} diff --git a/scripts/workload_grants.py b/scripts/workload_grants.py new file mode 100644 index 0000000..7856fb4 --- /dev/null +++ b/scripts/workload_grants.py @@ -0,0 +1,149 @@ +""" +workload_grants.py — Host-Granted Workload Capability Loader & Schema (ADR-0005) + +Loads and validates /etc/homelab/grants.json (or HOMELAB_GRANTS_FILE) using strict +Pydantic v2 models (ConfigDict(extra="forbid")). +""" + +from __future__ import annotations + +import json +import os +import stat +from pathlib import Path, PurePosixPath +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator + +DEFAULT_GRANTS_FILE = Path("/etc/homelab/grants.json") +PRIVILEGED_GROUPS: frozenset[str] = frozenset({"0", "root", "wheel", "docker"}) + + +class WorkloadGrantsError(Exception): + """Raised when the host capability grants file fails integrity or schema checks.""" + + +class WorkloadGrant(BaseModel): + """Explicit host-granted capabilities for a single workload.""" + + model_config = ConfigDict(extra="forbid") + + devices: list[str] = Field(default_factory=list) + groups: list[str] = Field(default_factory=list) + readOnlyPaths: list[str] = Field(default_factory=list) + + @field_validator("groups") + @classmethod + def _validate_groups(cls, values: list[str]) -> list[str]: + cleaned: list[str] = [] + for raw in values: + group = raw.strip() + if not group: + raise ValueError("Granted group entry cannot be empty.") + if group.lower() in PRIVILEGED_GROUPS: + raise ValueError( + f"Privileged group '{group}' cannot be granted to workloads." + ) + cleaned.append(group) + return cleaned + + @field_validator("devices", "readOnlyPaths") + @classmethod + def _validate_absolute_paths(cls, values: list[str]) -> list[str]: + cleaned: list[str] = [] + for raw in values: + path_str = raw.strip() + if not path_str: + raise ValueError("Granted path entry cannot be empty.") + posix = PurePosixPath(path_str) + if not posix.is_absolute(): + raise ValueError( + f"Granted path '{path_str}' must be an absolute path." + ) + if ".." in posix.parts: + raise ValueError( + f"Granted path '{path_str}' must not contain '..' traversal." + ) + cleaned.append(path_str) + return cleaned + + +class GrantsRegistry(BaseModel): + """Root schema for /etc/homelab/grants.json.""" + + model_config = ConfigDict(extra="forbid") + + schemaVersion: Literal["1.0"] = "1.0" + workloads: dict[str, WorkloadGrant] = Field(default_factory=dict) + + +def load_workload_grants( + grants_file: Path | None = None, + *, + verify_permissions: bool | None = None, +) -> dict[str, WorkloadGrant]: + """ + Load host-granted workload capabilities from grants_file or HOMELAB_GRANTS_FILE. + + - If the target file does not exist (and is not a symlink), returns {} (zero grants). + - If the file is present (or is a symlink) and fails permission/integrity checks, + is unreadable, or fails JSON/Pydantic validation, raises WorkloadGrantsError. + """ + if grants_file is None: + env_path = os.environ.get("HOMELAB_GRANTS_FILE", "").strip() + target_path = Path(env_path) if env_path else DEFAULT_GRANTS_FILE + else: + target_path = grants_file + + should_verify = ( + (target_path == DEFAULT_GRANTS_FILE) + if verify_permissions is None + else verify_permissions + ) + + if not target_path.exists() and not target_path.is_symlink(): + return {} + + if should_verify: + try: + st = os.lstat(target_path) + except OSError as exc: + raise WorkloadGrantsError( + f"Failed to stat grants file '{target_path}': {exc}" + ) from exc + + if stat.S_ISLNK(st.st_mode) or not stat.S_ISREG(st.st_mode): + raise WorkloadGrantsError( + f"Grants file '{target_path}' must be a regular non-symlink file." + ) + if st.st_uid != 0: + raise WorkloadGrantsError( + f"Grants file '{target_path}' must be owned by root (uid 0)." + ) + if (st.st_mode & 0o022) != 0: + raise WorkloadGrantsError( + f"Grants file '{target_path}' must not be group- or world-writable." + ) + + try: + raw_text = target_path.read_text(encoding="utf-8") + except OSError as exc: + raise WorkloadGrantsError( + f"Failed to read grants file '{target_path}': {exc}" + ) from exc + + try: + payload = json.loads(raw_text) + except json.JSONDecodeError as exc: + raise WorkloadGrantsError( + f"Malformed JSON in grants file '{target_path}': {exc}" + ) from exc + + try: + registry = GrantsRegistry.model_validate(payload) + except ValidationError as exc: + raise WorkloadGrantsError( + f"Invalid schema in grants file '{target_path}': {exc}" + ) from exc + + return registry.workloads diff --git a/tests/unit/test_appctl_contracts.py b/tests/unit/test_appctl_contracts.py index 678cca9..f38c791 100644 --- a/tests/unit/test_appctl_contracts.py +++ b/tests/unit/test_appctl_contracts.py @@ -445,12 +445,13 @@ def test_operation_request_backward_compatibility_aliases(): # --------------------------------------------------------------------------- -def test_error_code_taxonomy_contains_exactly_6_canonical_codes(): - assert len(ErrorCode) == 6 +def test_error_code_taxonomy_contains_exactly_7_canonical_codes(): + assert len(ErrorCode) == 7 expected_codes = { "ERR_VALIDATION_FAILED", "ERR_AUTH_REQUIRED", "ERR_PERMISSION_DENIED", + "ERR_CAPABILITY_NOT_GRANTED", "ERR_TARGET_NOT_FOUND", "ERR_CONCURRENT_MUTATION", "ERR_EXECUTION_FAILED", @@ -462,6 +463,7 @@ def test_error_code_http_status_mapping(): assert ErrorCode.ERR_VALIDATION_FAILED.http_status == 400 assert ErrorCode.ERR_AUTH_REQUIRED.http_status == 401 assert ErrorCode.ERR_PERMISSION_DENIED.http_status == 403 + assert ErrorCode.ERR_CAPABILITY_NOT_GRANTED.http_status == 403 assert ErrorCode.ERR_TARGET_NOT_FOUND.http_status == 404 assert ErrorCode.ERR_CONCURRENT_MUTATION.http_status == 409 assert ErrorCode.ERR_EXECUTION_FAILED.http_status == 500 diff --git a/tests/unit/test_core_manifest.py b/tests/unit/test_core_manifest.py index af9905a..943c9fe 100644 --- a/tests/unit/test_core_manifest.py +++ b/tests/unit/test_core_manifest.py @@ -355,3 +355,15 @@ description: "Pydantic serialization test" assert dumped["name"] == "serialized-app" assert dumped["schemaVersion"] == "1.0" assert manifest.to_dict()["name"] == "serialized-app" + + +def test_parse_manifest_rejects_homelab_grants_file_in_env(): + """Ensure HOMELAB_GRANTS_FILE is in RESERVED_ENV_KEYS and cannot be overridden by app.yaml.""" + raw_yaml = """ +name: "grants-override-app" +env: + HOMELAB_GRANTS_FILE: "/tmp/evil-grants.json" +""" + with pytest.raises(ManifestValidationError): + parse_manifest(raw_yaml) + diff --git a/tests/unit/test_workload_grants.py b/tests/unit/test_workload_grants.py new file mode 100644 index 0000000..3665c0b --- /dev/null +++ b/tests/unit/test_workload_grants.py @@ -0,0 +1,148 @@ +"""Unit tests for Pydantic v2 workload capability grants loader (ADR-0005).""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from types import SimpleNamespace + +import pytest +from pydantic import ValidationError +from workload_grants import ( + GrantsRegistry, + WorkloadGrant, + WorkloadGrantsError, + load_workload_grants, +) + + +def test_load_workload_grants_absent_file_returns_empty(tmp_path: Path) -> None: + missing = tmp_path / "does-not-exist.json" + assert load_workload_grants(missing) == {} + + +def test_load_workload_grants_honors_env_var_when_none( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + grants_path = tmp_path / "grants.json" + grants_path.write_text( + json.dumps( + { + "schemaVersion": "1.0", + "workloads": { + "media": { + "devices": ["/dev/dri/renderD128"], + "groups": ["render", "303"], + "readOnlyPaths": ["/mnt/media"], + } + }, + } + ), + encoding="utf-8", + ) + monkeypatch.setenv("HOMELAB_GRANTS_FILE", str(grants_path)) + loaded = load_workload_grants(verify_permissions=False) + assert "media" in loaded + assert loaded["media"].devices == ["/dev/dri/renderD128"] + assert loaded["media"].groups == ["render", "303"] + assert loaded["media"].readOnlyPaths == ["/mnt/media"] + + +@pytest.mark.parametrize("bad_group", ["0", "root", "wheel", "docker", "ROOT", " wheel "]) +def test_workload_grant_rejects_privileged_groups(bad_group: str) -> None: + with pytest.raises(ValidationError): + WorkloadGrant(groups=[bad_group]) + + +@pytest.mark.parametrize( + "bad_path", + [ + "dev/dri/renderD128", + "../etc/passwd", + "/dev/../etc/shadow", + "/mnt/media/..", + "", + ], +) +def test_workload_grant_rejects_relative_and_traversal_paths(bad_path: str) -> None: + with pytest.raises(ValidationError): + WorkloadGrant(devices=[bad_path]) + with pytest.raises(ValidationError): + WorkloadGrant(readOnlyPaths=[bad_path]) + + +def test_grants_registry_rejects_extra_fields_and_bad_schema_version() -> None: + with pytest.raises(ValidationError): + GrantsRegistry.model_validate( + { + "schemaVersion": "1.0", + "workloads": {"app": {"devices": [], "extra_field": True}}, + } + ) + with pytest.raises(ValidationError): + GrantsRegistry.model_validate({"schemaVersion": "2.0", "workloads": {}}) + + +def test_load_workload_grants_malformed_json_fails_closed(tmp_path: Path) -> None: + grants_path = tmp_path / "grants.json" + grants_path.write_text("{not valid json", encoding="utf-8") + with pytest.raises(WorkloadGrantsError): + load_workload_grants(grants_path) + + +def test_load_workload_grants_unreadable_file_fails_closed( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + grants_path = tmp_path / "grants.json" + grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8") + + def raise_perm_error(self: Path, *args: object, **kwargs: object) -> str: + raise PermissionError("Permission denied") + + monkeypatch.setattr(Path, "read_text", raise_perm_error) + with pytest.raises(WorkloadGrantsError, match="read"): + load_workload_grants(grants_path) + + +def test_load_workload_grants_verify_permissions_rejects_symlink(tmp_path: Path) -> None: + real_file = tmp_path / "real.json" + real_file.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8") + link_file = tmp_path / "grants.json" + link_file.symlink_to(real_file) + + with pytest.raises(WorkloadGrantsError, match="symlink"): + load_workload_grants(link_file, verify_permissions=True) + + +def test_load_workload_grants_verify_permissions_rejects_non_root_and_writable( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + grants_path = tmp_path / "grants.json" + grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8") + + # Non-root owner + monkeypatch.setattr( + os, + "lstat", + lambda _p: SimpleNamespace(st_mode=0o100640, st_uid=1000), + ) + with pytest.raises(WorkloadGrantsError, match="root"): + load_workload_grants(grants_path, verify_permissions=True) + + # Group/world writable even if root-owned + monkeypatch.setattr( + os, + "lstat", + lambda _p: SimpleNamespace(st_mode=0o100664, st_uid=0), + ) + with pytest.raises(WorkloadGrantsError, match="writable"): + load_workload_grants(grants_path, verify_permissions=True) + + # Valid root-owned 0640 regular file + monkeypatch.setattr( + os, + "lstat", + lambda _p: SimpleNamespace(st_mode=0o100640, st_uid=0), + ) + assert load_workload_grants(grants_path, verify_permissions=True) == {}