fix(security,tests): harden compose fallback, root UID check, and split grant tests
Core Architecture & Invariant CI / validate (pull_request) Failing after 0s

- Fail closed in validate_compose_security() when PyYAML is unavailable instead of regex fallback (CR-01)

- Reject zero-padded root UIDs (e.g. 00:1000) in _validate_service_user() via int() parsing (CR-02)

- Extract _resolve_contained_host_path() and _validate_service_volumes() and add docstrings across capability helpers (CR-03, CR-04)

- Fix missing-device-node test and split multi-behavior grant tests into focused single-behavior tests (Axis 3 CR-01, CR-02)
This commit is contained in:
kiskaadee committed 2026-11-21 04:13:59 -05:00
1 parent c9f3108805
commit 1a8e3b5eae
4 files changed
+350 -242

No files matched your search

+206 -213
View File
@@ -497,6 +497,7 @@ def _validate_service_group_add(
granted_names: set[str], granted_names: set[str],
granted_gids: set[int], granted_gids: set[int],
) -> tuple[bool, str | None]: ) -> tuple[bool, str | None]:
"""Enforce default-deny and host-granted group_add membership."""
group_add = svc.get("group_add") group_add = svc.get("group_add")
if not group_add: if not group_add:
return True, None return True, None
@@ -550,6 +551,7 @@ def _validate_service_user(
granted_names: set[str], granted_names: set[str],
granted_gids: set[int], granted_gids: set[int],
) -> tuple[bool, str | None]: ) -> tuple[bool, str | None]:
"""Enforce non-root UID and granted/unprivileged primary GID containment for service user."""
raw_user = svc.get("user") raw_user = svc.get("user")
if raw_user is None: if raw_user is None:
return True, None return True, None
@@ -568,7 +570,11 @@ def _validate_service_user(
uid_part, gid_part = user_val, None uid_part, gid_part = user_val, None
uid_clean = uid_part.strip() uid_clean = uid_part.strip()
if uid_clean.lower() in ("0", "root"): try:
is_zero_uid = int(uid_clean) == 0
except ValueError:
is_zero_uid = False
if uid_clean.lower() == "root" or is_zero_uid:
return ( return (
False, False,
f"Capability not granted: Service '{svc_name}' requests root user '{user_val}'.", f"Capability not granted: Service '{svc_name}' requests root user '{user_val}'.",
@@ -628,12 +634,46 @@ def _validate_service_user(
return True, None return True, None
def _resolve_contained_host_path(
svc_name: str,
kind: str,
host_path: str,
granted_roots: list[Path],
) -> tuple[bool, str | None]:
"""Verify an absolute host path exists canonically without '..' and falls within a granted root."""
posix = PurePosixPath(host_path)
if not posix.is_absolute() or ".." in posix.parts:
return (
False,
f"Capability not granted: Service '{svc_name}' {kind} '{host_path}' must be absolute without '..'.",
)
try:
strict_host = Path(host_path).resolve(strict=True)
except OSError:
return (
False,
f"Capability not granted: Service '{svc_name}' {kind} '{host_path}' does not exist on host.",
)
if not any(
strict_host == g_res or strict_host.is_relative_to(g_res)
for g_res in granted_roots
):
return (
False,
f"Capability not granted: Service '{svc_name}' requests ungranted {kind} '{host_path}'.",
)
return True, None
def _validate_service_devices( def _validate_service_devices(
svc_name: str, svc_name: str,
svc: dict[str, Any], svc: dict[str, Any],
grant: WorkloadGrant, grant: WorkloadGrant,
resolved_env: dict[str, str] | None, resolved_env: dict[str, str] | None,
) -> tuple[bool, str | None]: ) -> tuple[bool, str | None]:
"""Validate host device mounts against granted device paths and forbid mknod ('m') permissions."""
devices = svc.get("devices") devices = svc.get("devices")
if not devices: if not devices:
return True, None return True, None
@@ -679,29 +719,160 @@ def _validate_service_devices(
f"Capability not granted: Service '{svc_name}' requests prohibited 'm' (mknod) device permission in '{dev_str}'.", f"Capability not granted: Service '{svc_name}' requests prohibited 'm' (mknod) device permission in '{dev_str}'.",
) )
posix = PurePosixPath(host_dev) ok_path, path_err = _resolve_contained_host_path(
if not posix.is_absolute() or ".." in posix.parts: svc_name, "device", host_dev, granted_resolved
return (
False,
f"Capability not granted: Service '{svc_name}' device path '{host_dev}' must be absolute without '..'.",
) )
if not ok_path:
return False, path_err
return True, None
def _validate_service_volumes(
svc_name: str,
svc: dict[str, Any],
allowed_root: Path,
canonical_allowed_root: Path,
target_state_root: Path,
top_volumes: set[str],
grant: WorkloadGrant,
resolved_env: dict[str, str] | None,
) -> tuple[bool, str | None]:
"""Validate service volume mounts against workload/state roots and granted readOnlyPaths."""
volumes = svc.get("volumes", [])
if not isinstance(volumes, list):
return True, None
granted_ro_resolved: list[Path] = []
for g_ro in grant.readOnlyPaths:
try: try:
resolved_dev = Path(host_dev).resolve(strict=True) granted_ro_resolved.append(Path(g_ro).resolve(strict=True))
except OSError: except OSError:
continue
for vol in volumes:
host_path = ""
is_short_ro = False
is_long_bind_ro = False
is_long_syntax = False
unsafe_prop: str | None = None
if isinstance(vol, str):
vol_resolved = _interpolate_compose_value(vol, resolved_env)
if "/var/run/docker.sock" in vol_resolved:
return ( return (
False, False,
f"Capability not granted: Service '{svc_name}' device '{host_dev}' does not exist on host.", f"Service '{svc_name}' directly mounts Docker socket: {vol_resolved}.",
)
if ":" in vol_resolved:
parts = vol_resolved.split(":")
host_path = parts[0].strip()
if len(parts) >= 3:
opts = [
o.strip().lower()
for o in parts[2].split(",")
if o.strip()
]
for opt in opts:
if opt in UNSAFE_BIND_PROPAGATIONS:
unsafe_prop = opt
is_short_ro = ("ro" in opts) and ("rw" not in opts)
else:
host_path = vol_resolved.strip()
elif isinstance(vol, dict):
is_long_syntax = True
src = _interpolate_compose_value(
str(vol.get("source", "")), resolved_env
)
if "/var/run/docker.sock" in src:
return (
False,
f"Service '{svc_name}' directly mounts Docker socket: {src}.",
)
vol_type = vol.get("type")
if vol_type in ("bind", "volume") or (vol_type is None and src):
host_path = src
bind_cfg = vol.get("bind")
if isinstance(bind_cfg, dict):
prop = _interpolate_compose_value(
str(bind_cfg.get("propagation", "")).strip().lower(),
resolved_env,
)
if prop in UNSAFE_BIND_PROPAGATIONS:
unsafe_prop = prop
is_long_bind_ro = (vol_type == "bind") and (
vol.get("read_only") is True
) )
if not any( if unsafe_prop is not None:
resolved_dev == g_res or resolved_dev.is_relative_to(g_res) return (
for g_res in granted_resolved False,
f"Capability not granted: Service '{svc_name}' specifies unsafe bind propagation '{unsafe_prop}'.",
)
if not host_path:
continue
if "${" in host_path or "}" in host_path:
return (
False,
f"Service '{svc_name}' specifies prohibited variable interpolation in volume host path: '{host_path}'.",
)
if host_path in top_volumes and not (
host_path.startswith((".", "/", "~"))
or "/" in host_path
or "\\" in host_path
):
continue
if not (
host_path.startswith((".", "/", "~"))
or "/" in host_path
or "\\" in host_path
): ):
return ( return (
False, False,
f"Capability not granted: Service '{svc_name}' requests ungranted device '{host_dev}'.", f"Service '{svc_name}' specifies undeclared named volume or ambiguous path: '{host_path}'.",
) )
if host_path.startswith("~"):
expanded = Path(host_path).expanduser().resolve()
elif Path(host_path).is_absolute():
expanded = Path(host_path).resolve()
else:
expanded = (allowed_root / host_path).resolve()
is_in_workload = allowed_root.is_dir() and expanded.is_relative_to(
canonical_allowed_root
)
is_in_own_state = expanded.is_relative_to(target_state_root)
if is_in_workload or is_in_own_state:
continue
if not grant.readOnlyPaths:
return (
False,
f"Capability not granted: Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'.",
)
if is_long_syntax and not is_long_bind_ro:
return (
False,
f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' must specify type=bind and read_only=true.",
)
if not is_long_syntax and not is_short_ro:
return (
False,
f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' must be read-only (:ro).",
)
ok_path, path_err = _resolve_contained_host_path(
svc_name, "external bind mount", host_path, granted_ro_resolved
)
if not ok_path:
return False, path_err
return True, None return True, None
@@ -714,15 +885,15 @@ def validate_compose_security(
group_lookup: Callable[[str | int], tuple[str, int]] | None = None, group_lookup: Callable[[str | int], tuple[str, int]] | None = None,
) -> tuple[bool, str | None]: ) -> tuple[bool, str | None]:
""" """
Pre-flight AST inspection of workload docker-compose.yml enforcing Core platform security invariants: Pre-flight AST inspection of workload docker-compose.yml enforcing Core platform security invariants
1. File Integrity: regular file, non-symlink (or strictly contained symlink). and host-granted workload capabilities (ADR-0005):
2. Privilege Containment: blocks 'privileged: true', 'cap_add', 'devices', and 'security_opt: unconfined'. 1. File Integrity & Parser: regular file, non-symlink (or strictly contained symlink); fails closed if PyYAML is unavailable.
3. Host Namespace Isolation: blocks 'pid: host', 'ipc: host', 'uts: host', 'userns_mode: host', 'network_mode: host'. 2. Privilege Containment: blocks 'privileged: true', 'cap_add', 'device_cgroup_rules', and 'security_opt: unconfined'.
4. Docker Socket Ban: blocks direct mounts of /var/run/docker.sock. 3. Host Namespace Isolation: blocks 'host', 'container:*', and 'service:*' across 'network_mode', 'pid', 'ipc', 'uts', 'userns_mode'.
5. Top-Level Inclusion Ban: blocks top-level 'include' directives. 4. Docker Socket & Include Bans: blocks direct mounts of /var/run/docker.sock and top-level 'include' directives.
6. Bind-Mount & Tenant State Isolation: resolves all relative and absolute host paths. Requires containment 5. Host-Granted Capabilities: enforces fail-closed workloadGrants for 'devices' (forbidding mknod 'm'), 'group_add',
strictly within either the workload root (allowed_root) OR the workload's dedicated state root 'user' primary GIDs, and external ':ro' 'volumes' ('readOnlyPaths', rejecting unsafe bind propagation).
(~/var/lib/homelab/<app_name>/). Cross-tenant state mounts are rejected fail-closed. 6. Bind-Mount & Tenant State Isolation: resolves all relative and absolute host paths within allowed_root or ~/var/lib/homelab/<app_name>/.
""" """
if not compose_file.exists(): if not compose_file.exists():
return True, None return True, None
@@ -745,48 +916,13 @@ def validate_compose_security(
except OSError as e: except OSError as e:
return False, f"Failed to read compose file {compose_file}: {e}" return False, f"Failed to read compose file {compose_file}: {e}"
yaml_errors = (yaml.YAMLError,) if yaml is not None else () if yaml is None:
if yaml is not None: return False, "PyYAML is required for Compose security validation."
try: try:
data = yaml.safe_load(content) or {} data = yaml.safe_load(content) or {}
except yaml_errors as e: except yaml.YAMLError as e:
return False, f"Failed to parse compose YAML {compose_file}: {e}" return False, f"Failed to parse compose YAML {compose_file}: {e}"
else:
# Fallback regex inspection if yaml module is not present
if re.search(
r"^\s*privileged:\s*true\b", content, re.MULTILINE | re.IGNORECASE
):
return False, "Privileged mode is prohibited in workload compose files."
if "/var/run/docker.sock" in content:
return (
False,
"Docker socket mounts are prohibited in workload compose files.",
)
if re.search(
r"^\s*network_mode:\s*[\"']?host[\"']?",
content,
re.MULTILINE | re.IGNORECASE,
):
return (
False,
"Host networking (network_mode: host) is prohibited in workload compose files.",
)
if re.search(r"^\s*cap_add:\s*", content, re.MULTILINE | re.IGNORECASE):
return (
False,
"Linux capabilities (cap_add) are prohibited in workload compose files.",
)
if re.search(r"^\s*devices:\s*", content, re.MULTILINE | re.IGNORECASE):
return (
False,
"Host device mounts (devices) are prohibited in workload compose files.",
)
if re.search(r"^\s*include:\s*", content, re.MULTILINE | re.IGNORECASE):
return (
False,
"Top-level include directives are prohibited in workload compose files.",
)
return True, None
if not isinstance(data, dict): if not isinstance(data, dict):
return False, f"Invalid compose root in {compose_file}: expected mapping" return False, f"Invalid compose root in {compose_file}: expected mapping"
@@ -959,161 +1095,18 @@ def validate_compose_security(
f"Service '{svc_name}' specifies prohibited host namespace '{ns_key}: {val}'.", f"Service '{svc_name}' specifies prohibited host namespace '{ns_key}: {val}'.",
) )
volumes = svc.get("volumes", []) ok_vol, vol_err = _validate_service_volumes(
if isinstance(volumes, list): svc_name,
granted_ro_resolved: list[Path] = [] svc,
for g_ro in grant.readOnlyPaths: allowed_root,
try: canonical_allowed_root,
granted_ro_resolved.append(Path(g_ro).resolve(strict=True)) target_state_root,
except OSError: top_volumes,
continue grant,
for vol in volumes:
host_path = ""
is_short_ro = False
is_long_bind_ro = False
is_long_syntax = False
unsafe_prop: str | None = None
if isinstance(vol, str):
vol_resolved = _interpolate_compose_value(vol, resolved_env)
if "/var/run/docker.sock" in vol_resolved:
return (
False,
f"Service '{svc_name}' directly mounts Docker socket: {vol_resolved}.",
)
if ":" in vol_resolved:
parts = vol_resolved.split(":")
host_path = parts[0].strip()
if len(parts) >= 3:
opts = [
o.strip().lower()
for o in parts[2].split(",")
if o.strip()
]
for opt in opts:
if opt in UNSAFE_BIND_PROPAGATIONS:
unsafe_prop = opt
is_short_ro = ("ro" in opts) and ("rw" not in opts)
else:
host_path = vol_resolved.strip()
elif isinstance(vol, dict):
is_long_syntax = True
src = _interpolate_compose_value(
str(vol.get("source", "")), resolved_env
)
if "/var/run/docker.sock" in src:
return (
False,
f"Service '{svc_name}' directly mounts Docker socket: {src}.",
)
vol_type = vol.get("type")
if vol_type in ("bind", "volume") or (vol_type is None and src):
host_path = src
bind_cfg = vol.get("bind")
if isinstance(bind_cfg, dict):
prop = _interpolate_compose_value(
str(bind_cfg.get("propagation", "")).strip().lower(),
resolved_env, resolved_env,
) )
if prop in UNSAFE_BIND_PROPAGATIONS: if not ok_vol:
unsafe_prop = prop return False, vol_err
is_long_bind_ro = (vol_type == "bind") and (
vol.get("read_only") is True
)
if unsafe_prop is not None:
return (
False,
f"Capability not granted: Service '{svc_name}' specifies unsafe bind propagation '{unsafe_prop}'.",
)
if not host_path:
continue
if "${" in host_path or "}" in host_path:
return (
False,
f"Service '{svc_name}' specifies prohibited variable interpolation in volume host path: '{host_path}'.",
)
# Declared top-level named volume without path separators
if host_path in top_volumes and not (
host_path.startswith((".", "/", "~"))
or "/" in host_path
or "\\" in host_path
):
continue
# Undeclared named volumes or bare identifiers not starting with ., /, ~ or containing / are prohibited
if not (
host_path.startswith((".", "/", "~"))
or "/" in host_path
or "\\" in host_path
):
return (
False,
f"Service '{svc_name}' specifies undeclared named volume or ambiguous path: '{host_path}'.",
)
# Host bind mount evaluation
if host_path.startswith("~"):
expanded = Path(host_path).expanduser().resolve()
elif Path(host_path).is_absolute():
expanded = Path(host_path).resolve()
else:
# Relative path resolved against workload root
expanded = (allowed_root / host_path).resolve()
# Containment check: strictly within workload directory or dedicated state root
is_in_workload = allowed_root.is_dir() and expanded.is_relative_to(
canonical_allowed_root
)
is_in_own_state = expanded.is_relative_to(target_state_root)
if is_in_workload or is_in_own_state:
continue
if not grant.readOnlyPaths:
return (
False,
f"Capability not granted: Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'.",
)
if is_long_syntax and not is_long_bind_ro:
return (
False,
f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' must specify type=bind and read_only=true.",
)
if not is_long_syntax and not is_short_ro:
return (
False,
f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' must be read-only (:ro).",
)
posix_host = PurePosixPath(host_path)
if not posix_host.is_absolute() or ".." in posix_host.parts:
return (
False,
f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' must be absolute without '..'.",
)
try:
strict_host = Path(host_path).resolve(strict=True)
except OSError:
return (
False,
f"Capability not granted: Service '{svc_name}' external bind mount '{host_path}' does not exist on host.",
)
if not any(
strict_host == g_res or strict_host.is_relative_to(g_res)
for g_res in granted_ro_resolved
):
return (
False,
f"Capability not granted: Service '{svc_name}' requests ungranted host bind mount '{host_path}'.",
)
return True, None return True, None
+86 -20
View File
@@ -1498,6 +1498,7 @@ services:
"compose_body,expected_substr", "compose_body,expected_substr",
[ [
(" user: '0:131'", "user"), (" user: '0:131'", "user"),
(" user: '00:1000'", "root"),
(" user: '1000:0'", "user"), (" user: '1000:0'", "user"),
(" user: '1000:docker'", "docker"), (" user: '1000:docker'", "docker"),
(" user: '1000:44'", "44"), (" user: '1000:44'", "44"),
@@ -1534,8 +1535,23 @@ def test_capability_grants_negative_and_bypass_cases(
assert expected_substr.lower() in err.lower() assert expected_substr.lower() in err.lower()
def test_capability_grants_device_mknod_and_missing_node_rejected(tmp_path: Path): def test_validate_compose_security_fails_closed_when_pyyaml_missing(
"""Ensure :rwm (mknod) and non-existent device nodes are rejected even with a device grant.""" tmp_path: Path, monkeypatch
):
"""Ensure validate_compose_security fails closed when PyYAML is unavailable."""
app_dir = tmp_path / "Workloads" / "app"
app_dir.mkdir(parents=True)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text("services:\n app:\n image: alpine\n", encoding="utf-8")
monkeypatch.setattr(gitops_dispatcher, "yaml", None)
ok, err = gitops_dispatcher.validate_compose_security(compose_file, app_dir)
assert ok is False
assert err is not None and "pyyaml" in err.lower()
def test_capability_grants_device_mknod_rejected(tmp_path: Path):
"""Ensure :rwm (mknod) is rejected even when the device node exists and is granted."""
app_dir = tmp_path / "Workloads" / "media" app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True) app_dir.mkdir(parents=True)
dev_dir = tmp_path / "dev" / "dri" dev_dir = tmp_path / "dev" / "dri"
@@ -1566,26 +1582,47 @@ services:
assert err is not None and "mknod" in err.lower() assert err is not None and "mknod" in err.lower()
def test_capability_grants_volumes_reject_rw_long_syntax_unsafe_propagation_and_symlink_escape( def test_capability_grants_missing_device_node_rejected(tmp_path: Path):
tmp_path: Path, """Ensure a granted device path that does not exist on the host fails closed."""
): app_dir = tmp_path / "Workloads" / "media"
"""Ensure readOnlyPaths rejects long-syntax rw, unsafe bind propagation, and symlink escapes.""" app_dir.mkdir(parents=True)
missing_node = tmp_path / "dev" / "dri" / "renderD999"
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"devices": [str(missing_node)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text(
f"""
services:
app:
image: alpine
devices:
- "{missing_node}:/dev/dri/renderD999:rw"
""",
encoding="utf-8",
)
ok, err = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name="media", grants_file=grants_file
)
assert ok is False
assert err is not None and "does not exist" in err.lower()
def test_capability_grants_volumes_reject_rw_long_syntax(tmp_path: Path):
"""Ensure readOnlyPaths rejects long-syntax bind mounts without read_only: true."""
app_dir = tmp_path / "Workloads" / "media" app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True) app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media" media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True) media_dir.mkdir(parents=True)
outside_dir = tmp_path / "etc"
outside_dir.mkdir(parents=True)
escaped_link = media_dir / "escape"
escaped_link.symlink_to(outside_dir)
grants_file = _write_grants( grants_file = _write_grants(
tmp_path / "grants.json", tmp_path / "grants.json",
{"media": {"readOnlyPaths": [str(media_dir)]}}, {"media": {"readOnlyPaths": [str(media_dir)]}},
) )
compose_file = app_dir / "docker-compose.yml" compose_file = app_dir / "docker-compose.yml"
# 1. Long syntax without read_only: true
compose_file.write_text( compose_file.write_text(
f""" f"""
services: services:
@@ -1604,7 +1641,19 @@ services:
) )
assert ok is False assert ok is False
# 2. Long syntax with unsafe bind propagation (rshared)
def test_capability_grants_volumes_reject_unsafe_propagation(tmp_path: Path):
"""Ensure readOnlyPaths rejects long-syntax bind mounts with unsafe propagation (rshared)."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text( compose_file.write_text(
f""" f"""
services: services:
@@ -1626,7 +1675,23 @@ services:
assert ok is False assert ok is False
assert err is not None and "propagation" in err.lower() assert err is not None and "propagation" in err.lower()
# 3. Symlink escape outside granted readOnlyPaths
def test_capability_grants_volumes_reject_symlink_escape(tmp_path: Path):
"""Ensure readOnlyPaths rejects symlinks resolving outside the granted directory."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
outside_dir = tmp_path / "etc"
outside_dir.mkdir(parents=True)
escaped_link = media_dir / "escape"
escaped_link.symlink_to(outside_dir)
grants_file = _write_grants(
tmp_path / "grants.json",
{"media": {"readOnlyPaths": [str(media_dir)]}},
)
compose_file = app_dir / "docker-compose.yml"
compose_file.write_text( compose_file.write_text(
f""" f"""
services: services:
@@ -1643,10 +1708,8 @@ services:
assert ok is False assert ok is False
def test_capability_grants_app_name_none_and_malformed_grants_fail_closed( def test_capability_grants_app_name_none_receives_zero_grants(tmp_path: Path):
tmp_path: Path, """Ensure app_name=None receives zero grants even when grants.json defines workloads."""
):
"""Ensure app_name=None gets zero grants and malformed grants.json fails closed."""
app_dir = tmp_path / "Workloads" / "media" app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True) app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media" media_dir = tmp_path / "mnt" / "media"
@@ -1668,13 +1731,16 @@ services:
encoding="utf-8", encoding="utf-8",
) )
# app_name=None -> zero grants
ok, _ = gitops_dispatcher.validate_compose_security( ok, _ = gitops_dispatcher.validate_compose_security(
compose_file, app_dir, app_name=None, grants_file=grants_file compose_file, app_dir, app_name=None, grants_file=grants_file
) )
assert ok is False assert ok is False
# Malformed grants.json -> fails closed even on plain compose file
def test_capability_grants_malformed_grants_fail_closed(tmp_path: Path):
"""Ensure malformed grants.json fails closed even on a plain compose file."""
app_dir = tmp_path / "Workloads" / "media"
app_dir.mkdir(parents=True)
plain_compose = app_dir / "plain.yml" plain_compose = app_dir / "plain.yml"
plain_compose.write_text("services:\n app:\n image: alpine\n", encoding="utf-8") plain_compose.write_text("services:\n app:\n image: alpine\n", encoding="utf-8")
bad_grants = tmp_path / "bad_grants.json" bad_grants = tmp_path / "bad_grants.json"
+39 -4
View File
@@ -1684,10 +1684,10 @@ def test_operational_router_workload_update_pulls_monorepo_when_parent_git_exist
assert compose_cwds and all(cwd == mock_workload_dir for cwd in compose_cwds) assert compose_cwds and all(cwd == mock_workload_dir for cwd in compose_cwds)
def test_operational_router_returns_err_capability_not_granted_and_passes_resolved_env( def test_operational_router_returns_err_capability_not_granted(
tmp_path: Path, admin_principal: Principal, monkeypatch tmp_path: Path, admin_principal: Principal, monkeypatch
): ):
"""Ensure appctl_router passes assembled env to validate_compose_security and maps denials to ERR_CAPABILITY_NOT_GRANTED.""" """Ensure appctl_router maps capability-grant denials to ERR_CAPABILITY_NOT_GRANTED."""
sites_dir = tmp_path / "Workloads" sites_dir = tmp_path / "Workloads"
app_dir = sites_dir / "media" app_dir = sites_dir / "media"
app_dir.mkdir(parents=True) app_dir.mkdir(parents=True)
@@ -1721,14 +1721,33 @@ def test_operational_router_returns_err_capability_not_granted_and_passes_resolv
{"operation": "workload.deploy", "target": "media"} {"operation": "workload.deploy", "target": "media"}
) )
# 1. Without grant -> ERR_CAPABILITY_NOT_GRANTED
with patch("appctl_router.resolve_app", return_value=mock_app): with patch("appctl_router.resolve_app", return_value=mock_app):
resp = router.dispatch(req, admin_principal) resp = router.dispatch(req, admin_principal)
assert resp.success is False assert resp.success is False
assert resp.error is not None assert resp.error is not None
assert resp.error.code == ErrorCode.ERR_CAPABILITY_NOT_GRANTED assert resp.error.code == ErrorCode.ERR_CAPABILITY_NOT_GRANTED
# 2. With grant -> resolved_env interpolates ${MEDIA_PATH} and deploy succeeds
def test_operational_router_passes_resolved_env_to_capability_validation(
tmp_path: Path, admin_principal: Principal, monkeypatch
):
"""Ensure appctl_router passes assembled 6-layer env into validate_compose_security()."""
sites_dir = tmp_path / "Workloads"
app_dir = sites_dir / "media"
app_dir.mkdir(parents=True)
media_dir = tmp_path / "mnt" / "media"
media_dir.mkdir(parents=True)
(app_dir / "app.yaml").write_text(
f"name: media\ndomain: media.example.test\nenv:\n MEDIA_PATH: '{media_dir}'\n",
encoding="utf-8",
)
(app_dir / "docker-compose.yml").write_text(
"services:\n app:\n image: alpine\n volumes:\n - \"${MEDIA_PATH}:/media:ro\"\n",
encoding="utf-8",
)
grants_file = tmp_path / "grants.json"
grants_file.write_text( grants_file.write_text(
json.dumps( json.dumps(
{ {
@@ -1738,6 +1757,22 @@ def test_operational_router_returns_err_capability_not_granted_and_passes_resolv
), ),
encoding="utf-8", encoding="utf-8",
) )
monkeypatch.setenv("HOMELAB_GRANTS_FILE", str(grants_file))
monkeypatch.setenv("HOMELAB_DOMAIN", "example.test")
mock_app = MagicMock()
mock_app.name = "media"
mock_app.dir_path = str(app_dir)
router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=sites_dir,
)
req = OperationRequest.model_validate(
{"operation": "workload.deploy", "target": "media"}
)
with ( with (
patch("appctl_router.resolve_app", return_value=mock_app), patch("appctl_router.resolve_app", return_value=mock_app),
patch("appctl_router.run_bounded_subprocess", return_value=(0, "ok", "")), patch("appctl_router.run_bounded_subprocess", return_value=(0, "ok", "")),
+19 -5
View File
@@ -72,7 +72,7 @@ def test_workload_grant_rejects_relative_and_traversal_paths(bad_path: str) -> N
WorkloadGrant(readOnlyPaths=[bad_path]) WorkloadGrant(readOnlyPaths=[bad_path])
def test_grants_registry_rejects_extra_fields_and_bad_schema_version() -> None: def test_grants_registry_rejects_extra_fields() -> None:
with pytest.raises(ValidationError): with pytest.raises(ValidationError):
GrantsRegistry.model_validate( GrantsRegistry.model_validate(
{ {
@@ -80,6 +80,9 @@ def test_grants_registry_rejects_extra_fields_and_bad_schema_version() -> None:
"workloads": {"app": {"devices": [], "extra_field": True}}, "workloads": {"app": {"devices": [], "extra_field": True}},
} }
) )
def test_grants_registry_rejects_bad_schema_version() -> None:
with pytest.raises(ValidationError): with pytest.raises(ValidationError):
GrantsRegistry.model_validate({"schemaVersion": "2.0", "workloads": {}}) GrantsRegistry.model_validate({"schemaVersion": "2.0", "workloads": {}})
@@ -115,13 +118,12 @@ def test_load_workload_grants_verify_permissions_rejects_symlink(tmp_path: Path)
load_workload_grants(link_file, verify_permissions=True) load_workload_grants(link_file, verify_permissions=True)
def test_load_workload_grants_verify_permissions_rejects_non_root_and_writable( def test_load_workload_grants_verify_permissions_rejects_non_root_owner(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None: ) -> None:
grants_path = tmp_path / "grants.json" grants_path = tmp_path / "grants.json"
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8") grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
# Non-root owner
monkeypatch.setattr( monkeypatch.setattr(
os, os,
"lstat", "lstat",
@@ -130,7 +132,13 @@ def test_load_workload_grants_verify_permissions_rejects_non_root_and_writable(
with pytest.raises(WorkloadGrantsError, match="root"): with pytest.raises(WorkloadGrantsError, match="root"):
load_workload_grants(grants_path, verify_permissions=True) load_workload_grants(grants_path, verify_permissions=True)
# Group/world writable even if root-owned
def test_load_workload_grants_verify_permissions_rejects_writable_mode(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
monkeypatch.setattr( monkeypatch.setattr(
os, os,
"lstat", "lstat",
@@ -139,7 +147,13 @@ def test_load_workload_grants_verify_permissions_rejects_non_root_and_writable(
with pytest.raises(WorkloadGrantsError, match="writable"): with pytest.raises(WorkloadGrantsError, match="writable"):
load_workload_grants(grants_path, verify_permissions=True) load_workload_grants(grants_path, verify_permissions=True)
# Valid root-owned 0640 regular file
def test_load_workload_grants_verify_permissions_accepts_root_0640(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
grants_path = tmp_path / "grants.json"
grants_path.write_text('{"schemaVersion": "1.0", "workloads": {}}', encoding="utf-8")
monkeypatch.setattr( monkeypatch.setattr(
os, os,
"lstat", "lstat",