feat(security): enforce host-granted workload capabilities in validate_compose_security
- Update validate_compose_security() in scripts/gitops_dispatcher.py to enforce fail-closed workloadGrants for devices, group_add, user primary GIDs, and readOnlyPaths
- Permanently block device_cgroup_rules and container:*/service:* namespace sharing, and reject uninterpolated ${...} after resolved_env interpolation
- Pass assembled 6-layer env into validate_compose_security() in scripts/appctl_router.py and map capability denials to ERR_CAPABILITY_NOT_GRANTED
- Add comprehensive Red->Green security and router tests for positive grants and bypass vectors
This commit is contained in:
1 parent
4f40668536
commit
c9f3108805
4 files changed
+836
-22
No files matched your search
@@ -85,12 +85,16 @@ MAX_OUTPUT_BYTES = 256 * 1024 # 256 KiB cap per invocation
|
|||||||
|
|
||||||
|
|
||||||
class RouterValidationError(Exception):
|
class RouterValidationError(Exception):
|
||||||
"""Raised when request payload or pre-flight validation fails (400 Bad Request)."""
|
"""Raised when request payload or pre-flight validation fails (400 Bad Request or 403 Capability Denied)."""
|
||||||
|
|
||||||
def __init__(self, message: str) -> None:
|
def __init__(
|
||||||
|
self,
|
||||||
|
message: str,
|
||||||
|
code: ErrorCode = ErrorCode.ERR_VALIDATION_FAILED,
|
||||||
|
) -> None:
|
||||||
super().__init__(message)
|
super().__init__(message)
|
||||||
self.code = ErrorCode.ERR_VALIDATION_FAILED
|
self.code = code
|
||||||
self.http_status = 400
|
self.http_status = code.http_status
|
||||||
|
|
||||||
|
|
||||||
class RouterExecutionError(Exception):
|
class RouterExecutionError(Exception):
|
||||||
@@ -313,14 +317,31 @@ def validate_workload_preflight(
|
|||||||
effective_name = app_name or manifest.name
|
effective_name = app_name or manifest.name
|
||||||
compose_file = _resolve_compose_file(app_dir)
|
compose_file = _resolve_compose_file(app_dir)
|
||||||
if compose_file.exists():
|
if compose_file.exists():
|
||||||
|
resolved_env = assemble_workload_env(app_dir, manifest, effective_name)
|
||||||
ok, reason = validate_compose_security(
|
ok, reason = validate_compose_security(
|
||||||
compose_file=compose_file,
|
compose_file=compose_file,
|
||||||
allowed_root=app_dir,
|
allowed_root=app_dir,
|
||||||
app_name=effective_name,
|
app_name=effective_name,
|
||||||
|
resolved_env=resolved_env,
|
||||||
)
|
)
|
||||||
if not ok:
|
if not ok:
|
||||||
|
is_cap_denial = bool(
|
||||||
|
reason
|
||||||
|
and reason.startswith(
|
||||||
|
(
|
||||||
|
"Capability not granted:",
|
||||||
|
"Capability grants integrity check failed:",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
err_code = (
|
||||||
|
ErrorCode.ERR_CAPABILITY_NOT_GRANTED
|
||||||
|
if is_cap_denial
|
||||||
|
else ErrorCode.ERR_VALIDATION_FAILED
|
||||||
|
)
|
||||||
raise RouterValidationError(
|
raise RouterValidationError(
|
||||||
f"Compose AST security validation failed for '{effective_name}': {reason}"
|
f"Compose AST security validation failed for '{effective_name}': {reason}",
|
||||||
|
code=err_code,
|
||||||
)
|
)
|
||||||
|
|
||||||
return manifest, compose_file
|
return manifest, compose_file
|
||||||
|
|||||||
+419
-17
@@ -10,6 +10,7 @@ deployment actions with zero Core restarts.
|
|||||||
import contextlib
|
import contextlib
|
||||||
import datetime
|
import datetime
|
||||||
import fcntl
|
import fcntl
|
||||||
|
import grp
|
||||||
import hashlib
|
import hashlib
|
||||||
import hmac
|
import hmac
|
||||||
import http.client
|
import http.client
|
||||||
@@ -19,7 +20,8 @@ import os
|
|||||||
import re
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from collections.abc import Callable
|
||||||
|
from pathlib import Path, PurePosixPath
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from appctl_contracts import OperationRequest, OperationType
|
from appctl_contracts import OperationRequest, OperationType
|
||||||
@@ -30,6 +32,12 @@ from core_manifest import (
|
|||||||
parse_manifest,
|
parse_manifest,
|
||||||
)
|
)
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
|
from workload_grants import (
|
||||||
|
PRIVILEGED_GROUPS,
|
||||||
|
WorkloadGrant,
|
||||||
|
WorkloadGrantsError,
|
||||||
|
load_workload_grants,
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import yaml
|
import yaml
|
||||||
@@ -415,12 +423,295 @@ def resolve_target(repo_name: str) -> tuple[Path | None, dict]:
|
|||||||
|
|
||||||
PROHIBITED_HOST_NAMESPACES = {"host"}
|
PROHIBITED_HOST_NAMESPACES = {"host"}
|
||||||
DANGEROUS_SECURITY_OPTS = {"unconfined", "apparmor:unconfined", "seccomp:unconfined"}
|
DANGEROUS_SECURITY_OPTS = {"unconfined", "apparmor:unconfined", "seccomp:unconfined"}
|
||||||
|
UNSAFE_BIND_PROPAGATIONS = {"shared", "rshared", "slave", "rslave"}
|
||||||
|
_COMPOSE_VAR_RE = re.compile(
|
||||||
|
r"\$\{([A-Za-z_][A-Za-z0-9_]*)(?:(:-|-)([^}]*))?\}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _interpolate_compose_value(
|
||||||
|
value: str, resolved_env: dict[str, str] | None
|
||||||
|
) -> str:
|
||||||
|
"""Resolve ${VAR}, ${VAR:-default}, and ${VAR-default} using resolved_env without shell evaluation."""
|
||||||
|
if resolved_env is None or "${" not in value:
|
||||||
|
return value
|
||||||
|
|
||||||
|
def _replace(match: re.Match[str]) -> str:
|
||||||
|
var_name = match.group(1)
|
||||||
|
op = match.group(2)
|
||||||
|
default = match.group(3)
|
||||||
|
if op == ":-":
|
||||||
|
val = resolved_env.get(var_name)
|
||||||
|
return val if val else (default or "")
|
||||||
|
if op == "-":
|
||||||
|
return resolved_env.get(var_name, default or "")
|
||||||
|
return resolved_env.get(var_name, match.group(0))
|
||||||
|
|
||||||
|
return _COMPOSE_VAR_RE.sub(_replace, value)
|
||||||
|
|
||||||
|
|
||||||
|
def _default_group_lookup(key: str | int) -> tuple[str, int]:
|
||||||
|
"""Resolve a group name or numeric GID against the host group database."""
|
||||||
|
if isinstance(key, int) or (isinstance(key, str) and key.isdigit()):
|
||||||
|
entry = grp.getgrgid(int(key))
|
||||||
|
else:
|
||||||
|
entry = grp.getgrnam(str(key))
|
||||||
|
return entry.gr_name, entry.gr_gid
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_granted_groups(
|
||||||
|
grant_groups: list[str],
|
||||||
|
lookup_fn: Callable[[str | int], tuple[str, int]],
|
||||||
|
) -> tuple[set[str], set[int]]:
|
||||||
|
"""Canonicalize granted groups bidirectionally between group names and integer GIDs."""
|
||||||
|
granted_names: set[str] = set()
|
||||||
|
granted_gids: set[int] = set()
|
||||||
|
for raw in grant_groups:
|
||||||
|
key: str | int = int(raw) if raw.isdigit() else raw
|
||||||
|
try:
|
||||||
|
res = lookup_fn(key)
|
||||||
|
except KeyError as exc:
|
||||||
|
raise WorkloadGrantsError(
|
||||||
|
f"Granted group '{raw}' does not exist in host group database."
|
||||||
|
) from exc
|
||||||
|
if res is None:
|
||||||
|
raise WorkloadGrantsError(
|
||||||
|
f"Granted group '{raw}' does not exist in host group database."
|
||||||
|
)
|
||||||
|
gr_name, gr_gid = res
|
||||||
|
if gr_name.lower() in PRIVILEGED_GROUPS or str(gr_gid) in PRIVILEGED_GROUPS:
|
||||||
|
raise WorkloadGrantsError(
|
||||||
|
f"Granted group '{raw}' resolves to privileged group '{gr_name}:{gr_gid}'."
|
||||||
|
)
|
||||||
|
granted_names.add(gr_name)
|
||||||
|
granted_gids.add(gr_gid)
|
||||||
|
return granted_names, granted_gids
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_service_group_add(
|
||||||
|
svc_name: str,
|
||||||
|
svc: dict[str, Any],
|
||||||
|
grant: WorkloadGrant,
|
||||||
|
resolved_env: dict[str, str] | None,
|
||||||
|
lookup_fn: Callable[[str | int], tuple[str, int]],
|
||||||
|
granted_names: set[str],
|
||||||
|
granted_gids: set[int],
|
||||||
|
) -> tuple[bool, str | None]:
|
||||||
|
group_add = svc.get("group_add")
|
||||||
|
if not group_add:
|
||||||
|
return True, None
|
||||||
|
if not isinstance(group_add, list):
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Service '{svc_name}' specifies invalid 'group_add' configuration.",
|
||||||
|
)
|
||||||
|
if not grant.groups:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' requests 'group_add' without any granted groups.",
|
||||||
|
)
|
||||||
|
|
||||||
|
for item in group_add:
|
||||||
|
val = _interpolate_compose_value(str(item).strip(), resolved_env)
|
||||||
|
if "${" in val or "}" in val:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Service '{svc_name}' specifies prohibited variable interpolation in group_add: '{val}'.",
|
||||||
|
)
|
||||||
|
key: str | int = int(val) if val.isdigit() else val
|
||||||
|
try:
|
||||||
|
res = lookup_fn(key)
|
||||||
|
except KeyError:
|
||||||
|
res = None
|
||||||
|
if res is None:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' requests unknown group_add '{val}'.",
|
||||||
|
)
|
||||||
|
req_name, req_gid = res
|
||||||
|
if req_name.lower() in PRIVILEGED_GROUPS or str(req_gid) in PRIVILEGED_GROUPS:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' requests privileged group_add '{val}'.",
|
||||||
|
)
|
||||||
|
if req_name not in granted_names and req_gid not in granted_gids:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' requests ungranted group_add '{val}' ({req_name}:{req_gid}).",
|
||||||
|
)
|
||||||
|
return True, None
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_service_user(
|
||||||
|
svc_name: str,
|
||||||
|
svc: dict[str, Any],
|
||||||
|
resolved_env: dict[str, str] | None,
|
||||||
|
lookup_fn: Callable[[str | int], tuple[str, int]],
|
||||||
|
granted_names: set[str],
|
||||||
|
granted_gids: set[int],
|
||||||
|
) -> tuple[bool, str | None]:
|
||||||
|
raw_user = svc.get("user")
|
||||||
|
if raw_user is None:
|
||||||
|
return True, None
|
||||||
|
user_val = _interpolate_compose_value(str(raw_user).strip(), resolved_env)
|
||||||
|
if "${" in user_val or "}" in user_val:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Service '{svc_name}' specifies prohibited variable interpolation in user: '{user_val}'.",
|
||||||
|
)
|
||||||
|
if not user_val:
|
||||||
|
return True, None
|
||||||
|
|
||||||
|
if ":" in user_val:
|
||||||
|
uid_part, gid_part = user_val.split(":", 1)
|
||||||
|
else:
|
||||||
|
uid_part, gid_part = user_val, None
|
||||||
|
|
||||||
|
uid_clean = uid_part.strip()
|
||||||
|
if uid_clean.lower() in ("0", "root"):
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' requests root user '{user_val}'.",
|
||||||
|
)
|
||||||
|
|
||||||
|
if gid_part is not None:
|
||||||
|
gid_clean = gid_part.strip()
|
||||||
|
if gid_clean.lower() in PRIVILEGED_GROUPS:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' requests privileged primary group '{gid_clean}' in user '{user_val}'.",
|
||||||
|
)
|
||||||
|
if gid_clean.isdigit():
|
||||||
|
gid_num = int(gid_clean)
|
||||||
|
if gid_num == 0:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' requests root GID 0 in user '{user_val}'.",
|
||||||
|
)
|
||||||
|
if gid_num in granted_gids:
|
||||||
|
return True, None
|
||||||
|
if gid_num < 1000:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' requests ungranted system GID '{gid_clean}' in user '{user_val}'.",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
res = lookup_fn(gid_num)
|
||||||
|
except KeyError:
|
||||||
|
res = None
|
||||||
|
if res is not None and res[0].lower() in PRIVILEGED_GROUPS:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' requests privileged GID '{gid_clean}' ({res[0]}).",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
res = lookup_fn(gid_clean)
|
||||||
|
except KeyError:
|
||||||
|
res = None
|
||||||
|
if res is None:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' requests unknown primary group '{gid_clean}' in user '{user_val}'.",
|
||||||
|
)
|
||||||
|
req_name, req_gid = res
|
||||||
|
if req_name.lower() in PRIVILEGED_GROUPS or req_gid == 0:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' requests privileged primary group '{gid_clean}' in user '{user_val}'.",
|
||||||
|
)
|
||||||
|
if req_name not in granted_names and req_gid not in granted_gids:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' requests ungranted primary group '{gid_clean}' in user '{user_val}'.",
|
||||||
|
)
|
||||||
|
return True, None
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_service_devices(
|
||||||
|
svc_name: str,
|
||||||
|
svc: dict[str, Any],
|
||||||
|
grant: WorkloadGrant,
|
||||||
|
resolved_env: dict[str, str] | None,
|
||||||
|
) -> tuple[bool, str | None]:
|
||||||
|
devices = svc.get("devices")
|
||||||
|
if not devices:
|
||||||
|
return True, None
|
||||||
|
if not isinstance(devices, list):
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Service '{svc_name}' specifies invalid 'devices' configuration.",
|
||||||
|
)
|
||||||
|
if not grant.devices:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' specifies prohibited host device mount: {devices}.",
|
||||||
|
)
|
||||||
|
|
||||||
|
granted_resolved: list[Path] = []
|
||||||
|
for g_dev in grant.devices:
|
||||||
|
try:
|
||||||
|
granted_resolved.append(Path(g_dev).resolve(strict=True))
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for dev_entry in devices:
|
||||||
|
dev_str = _interpolate_compose_value(str(dev_entry).strip(), resolved_env)
|
||||||
|
if "${" in dev_str or "}" in dev_str:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Service '{svc_name}' specifies prohibited variable interpolation in devices: '{dev_str}'.",
|
||||||
|
)
|
||||||
|
parts = dev_str.split(":")
|
||||||
|
if len(parts) in (1, 2):
|
||||||
|
host_dev, perms = parts[0].strip(), ""
|
||||||
|
elif len(parts) == 3:
|
||||||
|
host_dev, perms = parts[0].strip(), parts[2].strip()
|
||||||
|
else:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Service '{svc_name}' specifies malformed device entry '{dev_str}'.",
|
||||||
|
)
|
||||||
|
|
||||||
|
if "m" in perms.lower():
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' requests prohibited 'm' (mknod) device permission in '{dev_str}'.",
|
||||||
|
)
|
||||||
|
|
||||||
|
posix = PurePosixPath(host_dev)
|
||||||
|
if not posix.is_absolute() or ".." in posix.parts:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' device path '{host_dev}' must be absolute without '..'.",
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
resolved_dev = Path(host_dev).resolve(strict=True)
|
||||||
|
except OSError:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' device '{host_dev}' does not exist on host.",
|
||||||
|
)
|
||||||
|
|
||||||
|
if not any(
|
||||||
|
resolved_dev == g_res or resolved_dev.is_relative_to(g_res)
|
||||||
|
for g_res in granted_resolved
|
||||||
|
):
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' requests ungranted device '{host_dev}'.",
|
||||||
|
)
|
||||||
|
return True, None
|
||||||
|
|
||||||
|
|
||||||
def validate_compose_security(
|
def validate_compose_security(
|
||||||
compose_file: Path,
|
compose_file: Path,
|
||||||
allowed_root: Path,
|
allowed_root: Path,
|
||||||
app_name: str | None = None,
|
app_name: str | None = None,
|
||||||
|
resolved_env: dict[str, str] | None = None,
|
||||||
|
grants_file: Path | 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:
|
||||||
@@ -510,6 +801,18 @@ def validate_compose_security(
|
|||||||
if not isinstance(services, dict):
|
if not isinstance(services, dict):
|
||||||
return True, None
|
return True, None
|
||||||
|
|
||||||
|
try:
|
||||||
|
grants = load_workload_grants(grants_file)
|
||||||
|
except WorkloadGrantsError as exc:
|
||||||
|
return False, f"Capability grants integrity check failed: {exc}"
|
||||||
|
|
||||||
|
grant = grants.get(app_name, WorkloadGrant()) if app_name else WorkloadGrant()
|
||||||
|
lookup_fn = group_lookup or _default_group_lookup
|
||||||
|
try:
|
||||||
|
granted_names, granted_gids = _resolve_granted_groups(grant.groups, lookup_fn)
|
||||||
|
except WorkloadGrantsError as exc:
|
||||||
|
return False, f"Capability grants integrity check failed: {exc}"
|
||||||
|
|
||||||
state_root = Path(
|
state_root = Path(
|
||||||
os.environ.get("HOMELAB_STATE_ROOT", Path.home() / "var/lib/homelab")
|
os.environ.get("HOMELAB_STATE_ROOT", Path.home() / "var/lib/homelab")
|
||||||
).resolve()
|
).resolve()
|
||||||
@@ -539,13 +842,28 @@ def validate_compose_security(
|
|||||||
f"Service '{svc_name}' specifies prohibited 'cap_add' capabilities: {cap_add}.",
|
f"Service '{svc_name}' specifies prohibited 'cap_add' capabilities: {cap_add}.",
|
||||||
)
|
)
|
||||||
|
|
||||||
devices = svc.get("devices")
|
if svc.get("device_cgroup_rules"):
|
||||||
if devices:
|
|
||||||
return (
|
return (
|
||||||
False,
|
False,
|
||||||
f"Service '{svc_name}' specifies prohibited host device mount: {devices}.",
|
f"Service '{svc_name}' specifies prohibited 'device_cgroup_rules'.",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
ok_dev, dev_err = _validate_service_devices(svc_name, svc, grant, resolved_env)
|
||||||
|
if not ok_dev:
|
||||||
|
return False, dev_err
|
||||||
|
|
||||||
|
ok_grp, grp_err = _validate_service_group_add(
|
||||||
|
svc_name, svc, grant, resolved_env, lookup_fn, granted_names, granted_gids
|
||||||
|
)
|
||||||
|
if not ok_grp:
|
||||||
|
return False, grp_err
|
||||||
|
|
||||||
|
ok_usr, usr_err = _validate_service_user(
|
||||||
|
svc_name, svc, resolved_env, lookup_fn, granted_names, granted_gids
|
||||||
|
)
|
||||||
|
if not ok_usr:
|
||||||
|
return False, usr_err
|
||||||
|
|
||||||
sec_opts = svc.get("security_opt", [])
|
sec_opts = svc.get("security_opt", [])
|
||||||
if isinstance(sec_opts, str):
|
if isinstance(sec_opts, str):
|
||||||
sec_opts = [sec_opts]
|
sec_opts = [sec_opts]
|
||||||
@@ -616,15 +934,15 @@ def validate_compose_security(
|
|||||||
if not clean_env:
|
if not clean_env:
|
||||||
continue
|
continue
|
||||||
if clean_env.startswith("~"):
|
if clean_env.startswith("~"):
|
||||||
resolved_env = Path(clean_env).expanduser().resolve()
|
env_file_resolved = Path(clean_env).expanduser().resolve()
|
||||||
elif Path(clean_env).is_absolute():
|
elif Path(clean_env).is_absolute():
|
||||||
resolved_env = Path(clean_env).resolve()
|
env_file_resolved = Path(clean_env).resolve()
|
||||||
else:
|
else:
|
||||||
resolved_env = (allowed_root / clean_env).resolve()
|
env_file_resolved = (allowed_root / clean_env).resolve()
|
||||||
|
|
||||||
if not (
|
if not (
|
||||||
allowed_root.is_dir()
|
allowed_root.is_dir()
|
||||||
and resolved_env.is_relative_to(canonical_allowed_root)
|
and env_file_resolved.is_relative_to(canonical_allowed_root)
|
||||||
):
|
):
|
||||||
return (
|
return (
|
||||||
False,
|
False,
|
||||||
@@ -633,7 +951,9 @@ def validate_compose_security(
|
|||||||
|
|
||||||
for ns_key in ("network_mode", "pid", "ipc", "uts", "userns_mode"):
|
for ns_key in ("network_mode", "pid", "ipc", "uts", "userns_mode"):
|
||||||
val = str(svc.get(ns_key, "")).strip().lower()
|
val = str(svc.get(ns_key, "")).strip().lower()
|
||||||
if val in PROHIBITED_HOST_NAMESPACES:
|
if val in PROHIBITED_HOST_NAMESPACES or val.startswith(
|
||||||
|
("container:", "service:")
|
||||||
|
):
|
||||||
return (
|
return (
|
||||||
False,
|
False,
|
||||||
f"Service '{svc_name}' specifies prohibited host namespace '{ns_key}: {val}'.",
|
f"Service '{svc_name}' specifies prohibited host namespace '{ns_key}: {val}'.",
|
||||||
@@ -641,20 +961,47 @@ def validate_compose_security(
|
|||||||
|
|
||||||
volumes = svc.get("volumes", [])
|
volumes = svc.get("volumes", [])
|
||||||
if isinstance(volumes, list):
|
if isinstance(volumes, list):
|
||||||
|
granted_ro_resolved: list[Path] = []
|
||||||
|
for g_ro in grant.readOnlyPaths:
|
||||||
|
try:
|
||||||
|
granted_ro_resolved.append(Path(g_ro).resolve(strict=True))
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
|
||||||
for vol in volumes:
|
for vol in volumes:
|
||||||
host_path = ""
|
host_path = ""
|
||||||
|
is_short_ro = False
|
||||||
|
is_long_bind_ro = False
|
||||||
|
is_long_syntax = False
|
||||||
|
unsafe_prop: str | None = None
|
||||||
|
|
||||||
if isinstance(vol, str):
|
if isinstance(vol, str):
|
||||||
if "/var/run/docker.sock" in vol:
|
vol_resolved = _interpolate_compose_value(vol, resolved_env)
|
||||||
|
if "/var/run/docker.sock" in vol_resolved:
|
||||||
return (
|
return (
|
||||||
False,
|
False,
|
||||||
f"Service '{svc_name}' directly mounts Docker socket: {vol}.",
|
f"Service '{svc_name}' directly mounts Docker socket: {vol_resolved}.",
|
||||||
)
|
)
|
||||||
if ":" in vol:
|
if ":" in vol_resolved:
|
||||||
host_path = vol.split(":")[0].strip()
|
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:
|
else:
|
||||||
host_path = vol.strip()
|
host_path = vol_resolved.strip()
|
||||||
elif isinstance(vol, dict):
|
elif isinstance(vol, dict):
|
||||||
src = str(vol.get("source", ""))
|
is_long_syntax = True
|
||||||
|
src = _interpolate_compose_value(
|
||||||
|
str(vol.get("source", "")), resolved_env
|
||||||
|
)
|
||||||
if "/var/run/docker.sock" in src:
|
if "/var/run/docker.sock" in src:
|
||||||
return (
|
return (
|
||||||
False,
|
False,
|
||||||
@@ -663,6 +1010,23 @@ def validate_compose_security(
|
|||||||
vol_type = vol.get("type")
|
vol_type = vol.get("type")
|
||||||
if vol_type in ("bind", "volume") or (vol_type is None and src):
|
if vol_type in ("bind", "volume") or (vol_type is None and src):
|
||||||
host_path = 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 unsafe_prop is not None:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"Capability not granted: Service '{svc_name}' specifies unsafe bind propagation '{unsafe_prop}'.",
|
||||||
|
)
|
||||||
|
|
||||||
if not host_path:
|
if not host_path:
|
||||||
continue
|
continue
|
||||||
@@ -707,10 +1071,48 @@ def validate_compose_security(
|
|||||||
)
|
)
|
||||||
is_in_own_state = expanded.is_relative_to(target_state_root)
|
is_in_own_state = expanded.is_relative_to(target_state_root)
|
||||||
|
|
||||||
if not (is_in_workload or is_in_own_state):
|
if is_in_workload or is_in_own_state:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not grant.readOnlyPaths:
|
||||||
return (
|
return (
|
||||||
False,
|
False,
|
||||||
f"Service '{svc_name}' specifies prohibited host bind mount: '{host_path}'.",
|
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
|
||||||
|
|||||||
@@ -1358,3 +1358,330 @@ def test_monorepo_webhook_dispatch_pulls_once_and_deploys_only_admitted_changed_
|
|||||||
pull_calls = [c for c in git_calls if "pull" in c]
|
pull_calls = [c for c in git_calls if "pull" in c]
|
||||||
assert len(pull_calls) == 1
|
assert len(pull_calls) == 1
|
||||||
assert str(workloads_dir) in pull_calls[0]
|
assert str(workloads_dir) in pull_calls[0]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# ADR-0005 Host-Granted Workload Capabilities ("Compose Requests, Nix Grants")
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _write_grants(path: Path, workloads: dict) -> Path:
|
||||||
|
import json
|
||||||
|
|
||||||
|
path.write_text(
|
||||||
|
json.dumps({"schemaVersion": "1.0", "workloads": workloads}),
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def _fake_group_lookup(key: str | int) -> tuple[str, int]:
|
||||||
|
table = {
|
||||||
|
"render": ("render", 303),
|
||||||
|
303: ("render", 303),
|
||||||
|
"video": ("video", 44),
|
||||||
|
44: ("video", 44),
|
||||||
|
"docker": ("docker", 998),
|
||||||
|
998: ("docker", 998),
|
||||||
|
"wheel": ("wheel", 10),
|
||||||
|
10: ("wheel", 10),
|
||||||
|
"root": ("root", 0),
|
||||||
|
0: ("root", 0),
|
||||||
|
}
|
||||||
|
lookup_key = int(key) if isinstance(key, str) and key.isdigit() else key
|
||||||
|
if lookup_key in table:
|
||||||
|
return table[lookup_key]
|
||||||
|
raise KeyError(key)
|
||||||
|
|
||||||
|
|
||||||
|
def test_capability_grants_positive_device_group_and_ro_volumes(tmp_path: Path):
|
||||||
|
"""Positive ADR-0005 grants: render<->303, existing device, short & long :ro readOnlyPaths."""
|
||||||
|
app_dir = tmp_path / "Workloads" / "media"
|
||||||
|
app_dir.mkdir(parents=True)
|
||||||
|
|
||||||
|
dev_dir = tmp_path / "dev" / "dri"
|
||||||
|
dev_dir.mkdir(parents=True)
|
||||||
|
render_node = dev_dir / "renderD128"
|
||||||
|
render_node.write_text("", encoding="utf-8")
|
||||||
|
|
||||||
|
media_dir = tmp_path / "mnt" / "media"
|
||||||
|
media_sub = media_dir / "movies"
|
||||||
|
media_sub.mkdir(parents=True)
|
||||||
|
|
||||||
|
grants_file = _write_grants(
|
||||||
|
tmp_path / "grants.json",
|
||||||
|
{
|
||||||
|
"media": {
|
||||||
|
"devices": [str(render_node)],
|
||||||
|
"groups": ["render"],
|
||||||
|
"readOnlyPaths": [str(media_dir)],
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
compose_file = app_dir / "docker-compose.yml"
|
||||||
|
compose_file.write_text(
|
||||||
|
f"""
|
||||||
|
services:
|
||||||
|
jellyfin:
|
||||||
|
image: jellyfin/jellyfin:latest
|
||||||
|
user: "1000:303"
|
||||||
|
group_add:
|
||||||
|
- "303"
|
||||||
|
devices:
|
||||||
|
- "{render_node}:/dev/dri/renderD128:rw"
|
||||||
|
volumes:
|
||||||
|
- "{media_sub}:/media/movies:ro"
|
||||||
|
- type: bind
|
||||||
|
source: "{media_dir}"
|
||||||
|
target: /media/all
|
||||||
|
read_only: true
|
||||||
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
ok, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file,
|
||||||
|
app_dir,
|
||||||
|
app_name="media",
|
||||||
|
grants_file=grants_file,
|
||||||
|
group_lookup=_fake_group_lookup,
|
||||||
|
)
|
||||||
|
assert ok is True, f"Expected granted capabilities to pass, got: {err}"
|
||||||
|
assert err is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_capability_grants_evaluates_resolved_env_interpolation(tmp_path: Path):
|
||||||
|
"""Post-interpolation values from resolved_env are evaluated and permitted when granted."""
|
||||||
|
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": {"groups": ["303"], "readOnlyPaths": [str(media_dir)]}},
|
||||||
|
)
|
||||||
|
|
||||||
|
compose_file = app_dir / "docker-compose.yml"
|
||||||
|
compose_file.write_text(
|
||||||
|
"""
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
image: alpine
|
||||||
|
user: "${PUID:-1000}:${PGID:-1000}"
|
||||||
|
group_add:
|
||||||
|
- "${RENDER_GID}"
|
||||||
|
volumes:
|
||||||
|
- "${MEDIA_PATH}:/media:ro"
|
||||||
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
ok, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file,
|
||||||
|
app_dir,
|
||||||
|
app_name="media",
|
||||||
|
resolved_env={
|
||||||
|
"PUID": "1000",
|
||||||
|
"PGID": "1000",
|
||||||
|
"RENDER_GID": "render",
|
||||||
|
"MEDIA_PATH": str(media_dir),
|
||||||
|
},
|
||||||
|
grants_file=grants_file,
|
||||||
|
group_lookup=_fake_group_lookup,
|
||||||
|
)
|
||||||
|
assert ok is True, f"Expected resolved env capabilities to pass, got: {err}"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"compose_body,expected_substr",
|
||||||
|
[
|
||||||
|
(" user: '0:131'", "user"),
|
||||||
|
(" user: '1000:0'", "user"),
|
||||||
|
(" user: '1000:docker'", "docker"),
|
||||||
|
(" user: '1000:44'", "44"),
|
||||||
|
(" group_add:\n - '303'", "group_add"),
|
||||||
|
(" network_mode: 'container:traefik'", "container:traefik"),
|
||||||
|
(" network_mode: 'service:web'", "service:web"),
|
||||||
|
(" device_cgroup_rules:\n - 'c 226:* rmw'", "device_cgroup_rules"),
|
||||||
|
(" user: '${PUID}:1000'", "interpolation"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_capability_grants_negative_and_bypass_cases(
|
||||||
|
tmp_path: Path, compose_body: str, expected_substr: str
|
||||||
|
):
|
||||||
|
"""Ensure bypass vectors and ungranted capabilities fail closed."""
|
||||||
|
app_dir = tmp_path / "Workloads" / "ungranted"
|
||||||
|
app_dir.mkdir(parents=True)
|
||||||
|
grants_file = _write_grants(tmp_path / "grants.json", {})
|
||||||
|
|
||||||
|
compose_file = app_dir / "docker-compose.yml"
|
||||||
|
compose_file.write_text(
|
||||||
|
f"services:\n app:\n image: alpine\n{compose_body}\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
ok, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file,
|
||||||
|
app_dir,
|
||||||
|
app_name="ungranted",
|
||||||
|
grants_file=grants_file,
|
||||||
|
group_lookup=_fake_group_lookup,
|
||||||
|
)
|
||||||
|
assert ok is False
|
||||||
|
assert err is not None
|
||||||
|
assert expected_substr.lower() in err.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def test_capability_grants_device_mknod_and_missing_node_rejected(tmp_path: Path):
|
||||||
|
"""Ensure :rwm (mknod) and non-existent device nodes are rejected even with a device grant."""
|
||||||
|
app_dir = tmp_path / "Workloads" / "media"
|
||||||
|
app_dir.mkdir(parents=True)
|
||||||
|
dev_dir = tmp_path / "dev" / "dri"
|
||||||
|
dev_dir.mkdir(parents=True)
|
||||||
|
render_node = dev_dir / "renderD128"
|
||||||
|
render_node.write_text("", encoding="utf-8")
|
||||||
|
|
||||||
|
grants_file = _write_grants(
|
||||||
|
tmp_path / "grants.json",
|
||||||
|
{"media": {"devices": [str(render_node)]}},
|
||||||
|
)
|
||||||
|
|
||||||
|
compose_file = app_dir / "docker-compose.yml"
|
||||||
|
compose_file.write_text(
|
||||||
|
f"""
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
image: alpine
|
||||||
|
devices:
|
||||||
|
- "{render_node}:/dev/dri/renderD128:rwm"
|
||||||
|
""",
|
||||||
|
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 "mknod" in err.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def test_capability_grants_volumes_reject_rw_long_syntax_unsafe_propagation_and_symlink_escape(
|
||||||
|
tmp_path: Path,
|
||||||
|
):
|
||||||
|
"""Ensure readOnlyPaths rejects long-syntax rw, unsafe bind propagation, and symlink escapes."""
|
||||||
|
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"
|
||||||
|
|
||||||
|
# 1. Long syntax without read_only: true
|
||||||
|
compose_file.write_text(
|
||||||
|
f"""
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
image: alpine
|
||||||
|
volumes:
|
||||||
|
- type: bind
|
||||||
|
source: "{media_dir}"
|
||||||
|
target: /media
|
||||||
|
read_only: false
|
||||||
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
ok, _ = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file, app_dir, app_name="media", grants_file=grants_file
|
||||||
|
)
|
||||||
|
assert ok is False
|
||||||
|
|
||||||
|
# 2. Long syntax with unsafe bind propagation (rshared)
|
||||||
|
compose_file.write_text(
|
||||||
|
f"""
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
image: alpine
|
||||||
|
volumes:
|
||||||
|
- type: bind
|
||||||
|
source: "{media_dir}"
|
||||||
|
target: /media
|
||||||
|
read_only: true
|
||||||
|
bind:
|
||||||
|
propagation: rshared
|
||||||
|
""",
|
||||||
|
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 "propagation" in err.lower()
|
||||||
|
|
||||||
|
# 3. Symlink escape outside granted readOnlyPaths
|
||||||
|
compose_file.write_text(
|
||||||
|
f"""
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
image: alpine
|
||||||
|
volumes:
|
||||||
|
- "{escaped_link}:/media:ro"
|
||||||
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
ok, _ = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file, app_dir, app_name="media", grants_file=grants_file
|
||||||
|
)
|
||||||
|
assert ok is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_capability_grants_app_name_none_and_malformed_grants_fail_closed(
|
||||||
|
tmp_path: Path,
|
||||||
|
):
|
||||||
|
"""Ensure app_name=None gets zero grants and malformed grants.json fails closed."""
|
||||||
|
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(
|
||||||
|
f"""
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
image: alpine
|
||||||
|
volumes:
|
||||||
|
- "{media_dir}:/media:ro"
|
||||||
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
# app_name=None -> zero grants
|
||||||
|
ok, _ = gitops_dispatcher.validate_compose_security(
|
||||||
|
compose_file, app_dir, app_name=None, grants_file=grants_file
|
||||||
|
)
|
||||||
|
assert ok is False
|
||||||
|
|
||||||
|
# Malformed grants.json -> fails closed even on plain compose file
|
||||||
|
plain_compose = app_dir / "plain.yml"
|
||||||
|
plain_compose.write_text("services:\n app:\n image: alpine\n", encoding="utf-8")
|
||||||
|
bad_grants = tmp_path / "bad_grants.json"
|
||||||
|
bad_grants.write_text("{corrupt", encoding="utf-8")
|
||||||
|
ok, err = gitops_dispatcher.validate_compose_security(
|
||||||
|
plain_compose, app_dir, app_name="media", grants_file=bad_grants
|
||||||
|
)
|
||||||
|
assert ok is False
|
||||||
|
assert err is not None and "grants" in err.lower()
|
||||||
|
|
||||||
@@ -1682,3 +1682,67 @@ def test_operational_router_workload_update_pulls_monorepo_when_parent_git_exist
|
|||||||
# Compose commands still run in app_dir
|
# Compose commands still run in app_dir
|
||||||
compose_cwds = [cwd for c, cwd in executed if c[0] == "docker"]
|
compose_cwds = [cwd for c, cwd in executed if c[0] == "docker"]
|
||||||
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(
|
||||||
|
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."""
|
||||||
|
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('{"schemaVersion": "1.0", "workloads": {}}', 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"}
|
||||||
|
)
|
||||||
|
|
||||||
|
# 1. Without grant -> ERR_CAPABILITY_NOT_GRANTED
|
||||||
|
with patch("appctl_router.resolve_app", return_value=mock_app):
|
||||||
|
resp = router.dispatch(req, admin_principal)
|
||||||
|
assert resp.success is False
|
||||||
|
assert resp.error is not None
|
||||||
|
assert resp.error.code == ErrorCode.ERR_CAPABILITY_NOT_GRANTED
|
||||||
|
|
||||||
|
# 2. With grant -> resolved_env interpolates ${MEDIA_PATH} and deploy succeeds
|
||||||
|
grants_file.write_text(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"schemaVersion": "1.0",
|
||||||
|
"workloads": {"media": {"readOnlyPaths": [str(media_dir)]}},
|
||||||
|
}
|
||||||
|
),
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
with (
|
||||||
|
patch("appctl_router.resolve_app", return_value=mock_app),
|
||||||
|
patch("appctl_router.run_bounded_subprocess", return_value=(0, "ok", "")),
|
||||||
|
patch("appctl_router.cmd_sync_homepage"),
|
||||||
|
):
|
||||||
|
resp_ok = router.dispatch(req, admin_principal)
|
||||||
|
assert resp_ok.success is True
|
||||||
|
|
||||||
Reference in new issue
Block a user