feat(appctl): implement Bearer token authenticator, UDS peercred fallback, and 3-role RBAC gate
This commit is contained in:
1 parent
8ce74ff520
commit
d092ca17b8
3 files changed
+687
-1
No files matched your search
@@ -0,0 +1,360 @@
|
||||
"""
|
||||
appctl_auth.py — Authentication & 3-Role RBAC Policy Enforcement (P4 Slice 3)
|
||||
|
||||
Implements the zero-trust authorization pipeline for homelab-appctl.service:
|
||||
- SOPS-managed SHA-256 Bearer token store loader (mode 0400 check, constant-time compare)
|
||||
- Unix domain socket SO_PEERCRED fallback to homelab-viewer for zero-friction local reads
|
||||
- Mandatory Bearer tokens for all network (HTTP) operations and all mutations / sensitive reads
|
||||
- 3-role RBAC enforcement (homelab-admin, homelab-operator, homelab-viewer)
|
||||
- Workload scope gating against config/deployments.yaml for homelab-operator
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
from enum import StrEnum
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from appctl_contracts import (
|
||||
ErrorCode,
|
||||
OperationType,
|
||||
StrictModel,
|
||||
)
|
||||
from pydantic import BeforeValidator, ConfigDict, Field, StrictStr
|
||||
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
yaml = None # type: ignore[assignment]
|
||||
|
||||
DEFAULT_TOKENS_FILE = Path("/run/secrets/appctl/tokens.json")
|
||||
DEFAULT_DEPLOYMENTS_FILE = Path(__file__).resolve().parent.parent / "config" / "deployments.yaml"
|
||||
|
||||
CORE_TARGETS: frozenset[str] = frozenset({
|
||||
"core",
|
||||
"traefik",
|
||||
"authelia",
|
||||
"lldap",
|
||||
"stalwart",
|
||||
"dozzle",
|
||||
"socket-proxy",
|
||||
"homepage",
|
||||
"diun",
|
||||
"watchtower",
|
||||
})
|
||||
|
||||
SENSITIVE_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
OperationType.WORKLOAD_CONFIG,
|
||||
OperationType.WORKLOAD_LOGS,
|
||||
})
|
||||
|
||||
MUTATING_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
OperationType.WORKLOAD_STOP,
|
||||
OperationType.WORKLOAD_RESTART,
|
||||
OperationType.WORKLOAD_UPDATE,
|
||||
OperationType.WORKLOAD_PULL,
|
||||
OperationType.PLATFORM_SYNC_HOMEPAGE,
|
||||
})
|
||||
|
||||
READ_ONLY_OPERATIONS: frozenset[OperationType] = frozenset({
|
||||
OperationType.WORKLOAD_LIST,
|
||||
OperationType.WORKLOAD_GET,
|
||||
OperationType.WORKLOAD_RESOLVE,
|
||||
OperationType.PLATFORM_SSL,
|
||||
OperationType.PLATFORM_HEALTH,
|
||||
})
|
||||
|
||||
|
||||
class Role(StrEnum):
|
||||
"""Hierarchical authorization roles for homelab-appctl.service."""
|
||||
|
||||
ADMIN = "homelab-admin"
|
||||
OPERATOR = "homelab-operator"
|
||||
VIEWER = "homelab-viewer"
|
||||
|
||||
|
||||
def _coerce_role(v: Any) -> Any:
|
||||
if isinstance(v, str):
|
||||
try:
|
||||
return Role(v)
|
||||
except ValueError:
|
||||
return v
|
||||
return v
|
||||
|
||||
|
||||
FlexibleRole = Annotated[
|
||||
Role,
|
||||
BeforeValidator(_coerce_role),
|
||||
]
|
||||
|
||||
|
||||
class Principal(StrictModel):
|
||||
"""Authenticated caller identity and operational role."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
identity: StrictStr
|
||||
role: FlexibleRole
|
||||
token_id: StrictStr | None = None
|
||||
auth_method: Literal["bearer_token", "unix_peercred"]
|
||||
|
||||
|
||||
class TokenDescriptor(StrictModel):
|
||||
"""Internal model for token entries in SOPS tokens.json store."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
token_id: StrictStr
|
||||
identity: StrictStr
|
||||
role: FlexibleRole
|
||||
sha256: Annotated[StrictStr, Field(pattern=r"^[0-9a-fA-F]{64}$")]
|
||||
|
||||
|
||||
class AuthenticationError(Exception):
|
||||
"""Raised when authentication fails (401 Unauthorized)."""
|
||||
|
||||
def __init__(self, message: str = "Authentication required", code: ErrorCode = ErrorCode.ERR_AUTH_REQUIRED) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.http_status = 401
|
||||
|
||||
|
||||
class AuthorizationError(Exception):
|
||||
"""Raised when an authenticated principal lacks required role or scope (403 Forbidden)."""
|
||||
|
||||
def __init__(self, message: str = "Permission denied", code: ErrorCode = ErrorCode.ERR_PERMISSION_DENIED) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.http_status = 403
|
||||
|
||||
|
||||
class TokenStore:
|
||||
"""Loads and validates SHA-256 Bearer tokens from a mode 0400 store."""
|
||||
|
||||
def __init__(self, tokens_path: Path | str | None = None) -> None:
|
||||
if tokens_path is not None:
|
||||
self.tokens_path = Path(tokens_path)
|
||||
elif "APPCTL_TOKENS_FILE" in os.environ:
|
||||
self.tokens_path = Path(os.environ["APPCTL_TOKENS_FILE"])
|
||||
else:
|
||||
self.tokens_path = DEFAULT_TOKENS_FILE
|
||||
|
||||
def _verify_permissions(self) -> None:
|
||||
"""Enforce strict 0400 file mode: readable only by owner, no write/exec, no group/world."""
|
||||
if not self.tokens_path.is_file():
|
||||
raise AuthenticationError(
|
||||
f"Token store '{self.tokens_path}' not found",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
# Check permissions: reject if group/world readable or writable (must be 0400)
|
||||
mode = stat.S_IMODE(self.tokens_path.stat().st_mode)
|
||||
if (mode & 0o077) != 0 or (mode & 0o200) != 0:
|
||||
raise AuthenticationError(
|
||||
f"Token store '{self.tokens_path}' has insecure mode {oct(mode)}; mode 0400 required",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
|
||||
def load_tokens(self) -> list[TokenDescriptor]:
|
||||
"""Load and parse token descriptors from the token store."""
|
||||
self._verify_permissions()
|
||||
try:
|
||||
content = self.tokens_path.read_text(encoding="utf-8")
|
||||
data = json.loads(content)
|
||||
if not isinstance(data, list):
|
||||
raise TypeError("Tokens payload must be an array of token descriptors")
|
||||
return [TokenDescriptor.model_validate(item) for item in data]
|
||||
except (OSError, json.JSONDecodeError, ValueError, TypeError) as err:
|
||||
raise AuthenticationError(
|
||||
f"Failed to load token store '{self.tokens_path}': {err}",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
) from err
|
||||
|
||||
def authenticate_bearer(self, secret: str) -> Principal:
|
||||
"""
|
||||
Hash secret with SHA-256 and look up against stored token descriptors using
|
||||
constant-time hmac.compare_digest.
|
||||
"""
|
||||
if not secret:
|
||||
raise AuthenticationError("Empty Bearer token provided", code=ErrorCode.ERR_AUTH_REQUIRED)
|
||||
|
||||
secret_hash = hashlib.sha256(secret.encode("utf-8")).hexdigest()
|
||||
tokens = self.load_tokens()
|
||||
|
||||
for token in tokens:
|
||||
if hmac.compare_digest(secret_hash, token.sha256):
|
||||
return Principal(
|
||||
identity=token.identity,
|
||||
role=token.role,
|
||||
token_id=token.token_id,
|
||||
auth_method="bearer_token",
|
||||
)
|
||||
|
||||
raise AuthenticationError("Invalid or unknown Bearer token", code=ErrorCode.ERR_AUTH_REQUIRED)
|
||||
|
||||
|
||||
def load_admitted_workloads(deployments_path: Path | str | None = None) -> set[str]:
|
||||
"""
|
||||
Load admitted repository names and aliases from config/deployments.yaml.
|
||||
Fails closed (empty set) if registry is missing or malformed.
|
||||
"""
|
||||
if deployments_path is not None:
|
||||
reg_file = Path(deployments_path)
|
||||
elif "HOMELAB_DEPLOYMENTS_FILE" in os.environ:
|
||||
reg_file = Path(os.environ["HOMELAB_DEPLOYMENTS_FILE"])
|
||||
else:
|
||||
reg_file = DEFAULT_DEPLOYMENTS_FILE
|
||||
|
||||
if not reg_file.is_file():
|
||||
return set()
|
||||
|
||||
yaml_errors = (yaml.YAMLError,) if yaml is not None else ()
|
||||
try:
|
||||
content = reg_file.read_text(encoding="utf-8")
|
||||
if yaml is not None:
|
||||
data = yaml.safe_load(content)
|
||||
else:
|
||||
data = json.loads(content)
|
||||
if not isinstance(data, dict):
|
||||
return set()
|
||||
|
||||
admitted: set[str] = set()
|
||||
repos = data.get("repositories", {})
|
||||
if isinstance(repos, dict):
|
||||
for name, entry in repos.items():
|
||||
admitted.add(name)
|
||||
if isinstance(entry, dict):
|
||||
aliases = entry.get("aliases", [])
|
||||
if isinstance(aliases, list):
|
||||
for alias in aliases:
|
||||
if isinstance(alias, str) and alias.strip():
|
||||
admitted.add(alias.strip())
|
||||
return admitted
|
||||
except (OSError, UnicodeDecodeError, ValueError, json.JSONDecodeError, *yaml_errors):
|
||||
return set()
|
||||
|
||||
|
||||
def authenticate_request(
|
||||
transport: Literal["unix_socket", "http"],
|
||||
auth_header: str | None,
|
||||
peer_uid: int | None = None,
|
||||
token_store: TokenStore | None = None,
|
||||
) -> Principal:
|
||||
"""
|
||||
Authenticate an incoming request across transports:
|
||||
- If Authorization header present: parses Bearer secret and verifies against TokenStore.
|
||||
- If Authorization header missing over HTTP: fails closed with 401 ERR_AUTH_REQUIRED.
|
||||
- If Authorization header missing over Unix socket: falls back to homelab-viewer with peer_uid.
|
||||
"""
|
||||
store = token_store or TokenStore()
|
||||
|
||||
if auth_header is not None:
|
||||
header_val = auth_header.strip()
|
||||
if not header_val.startswith("Bearer "):
|
||||
raise AuthenticationError(
|
||||
"Malformed Authorization header: must start with 'Bearer '",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
secret = header_val[7:].strip()
|
||||
if not secret:
|
||||
raise AuthenticationError(
|
||||
"Missing token secret in Authorization header",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
return store.authenticate_bearer(secret)
|
||||
|
||||
# Missing Authorization header
|
||||
if transport == "unix_socket":
|
||||
if peer_uid is not None:
|
||||
return Principal(
|
||||
identity=f"unix_uid_{peer_uid}",
|
||||
role=Role.VIEWER,
|
||||
token_id=None,
|
||||
auth_method="unix_peercred",
|
||||
)
|
||||
raise AuthenticationError(
|
||||
"Missing peer credentials over Unix socket",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
|
||||
# HTTP transport requires Bearer token strictly
|
||||
raise AuthenticationError(
|
||||
"Bearer token required over network transport",
|
||||
code=ErrorCode.ERR_AUTH_REQUIRED,
|
||||
)
|
||||
|
||||
|
||||
def enforce_rbac(
|
||||
principal: Principal,
|
||||
operation: OperationType,
|
||||
target: str | None = None,
|
||||
admitted_workloads: set[str] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Enforce 3-role RBAC policy (homelab-admin, homelab-operator, homelab-viewer).
|
||||
Raises AuthorizationError (403) on violation.
|
||||
"""
|
||||
# 1. homelab-admin has unrestricted access across all operations and targets
|
||||
if principal.role == Role.ADMIN:
|
||||
return
|
||||
|
||||
# 2. homelab-operator:
|
||||
if principal.role == Role.OPERATOR:
|
||||
# Platform homepage sync allowed
|
||||
if operation == OperationType.PLATFORM_SYNC_HOMEPAGE:
|
||||
return
|
||||
|
||||
# Target checks for operations targeting infrastructure
|
||||
if target is not None and (target in CORE_TARGETS or target == "core"):
|
||||
raise AuthorizationError(
|
||||
f"Role 'homelab-operator' is not permitted to target core service '{target}'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
|
||||
# Non-sensitive reads are permitted
|
||||
if operation in READ_ONLY_OPERATIONS:
|
||||
return
|
||||
|
||||
# Sensitive reads and mutations must target an admitted workload from deployments.yaml
|
||||
if operation in SENSITIVE_OPERATIONS or operation in MUTATING_OPERATIONS:
|
||||
if not target:
|
||||
raise AuthorizationError(
|
||||
f"Operation '{operation.value}' requires an explicit workload target",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
registry = (
|
||||
admitted_workloads
|
||||
if admitted_workloads is not None
|
||||
else load_admitted_workloads()
|
||||
)
|
||||
if target not in registry:
|
||||
raise AuthorizationError(
|
||||
f"Target '{target}' is not registered in deployments.yaml for role 'homelab-operator'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
return
|
||||
|
||||
# 3. homelab-viewer:
|
||||
if principal.role == Role.VIEWER:
|
||||
if operation in MUTATING_OPERATIONS:
|
||||
raise AuthorizationError(
|
||||
f"Role 'homelab-viewer' is not permitted to execute mutating operation '{operation.value}'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
if operation in SENSITIVE_OPERATIONS:
|
||||
raise AuthorizationError(
|
||||
f"Role 'homelab-viewer' is not permitted to access sensitive operation '{operation.value}'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
if operation in READ_ONLY_OPERATIONS:
|
||||
return
|
||||
|
||||
raise AuthorizationError(
|
||||
f"Operation '{operation.value}' denied for role '{principal.role.value}'",
|
||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||
)
|
||||
@@ -0,0 +1,326 @@
|
||||
"""
|
||||
tests/unit/test_appctl_auth.py — Unit Tests for Authentication & 3-Role RBAC (P4 Slice 3)
|
||||
|
||||
Behavior-driven test naming convention:
|
||||
test_<subject>_<accepts|rejects|enforces>_<condition>
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from appctl_auth import (
|
||||
AuthenticationError,
|
||||
AuthorizationError,
|
||||
Principal,
|
||||
Role,
|
||||
TokenStore,
|
||||
authenticate_request,
|
||||
enforce_rbac,
|
||||
load_admitted_workloads,
|
||||
)
|
||||
from appctl_contracts import ErrorCode, OperationType
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def secret_tokens() -> dict[str, str]:
|
||||
return {
|
||||
"admin_secret": "sec_admin_9876543210abcdef",
|
||||
"operator_secret": "sec_operator_1234567890abcdef",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_tokens_file(tmp_path: Path, secret_tokens: dict[str, str]) -> Path:
|
||||
tokens_path = tmp_path / "tokens.json"
|
||||
admin_hash = hashlib.sha256(secret_tokens["admin_secret"].encode("utf-8")).hexdigest()
|
||||
op_hash = hashlib.sha256(secret_tokens["operator_secret"].encode("utf-8")).hexdigest()
|
||||
|
||||
data = [
|
||||
{
|
||||
"token_id": "tok_admin_01",
|
||||
"identity": "operator",
|
||||
"role": "homelab-admin",
|
||||
"sha256": admin_hash,
|
||||
},
|
||||
{
|
||||
"token_id": "tok_gitops_01",
|
||||
"identity": "gitops-dispatcher",
|
||||
"role": "homelab-operator",
|
||||
"sha256": op_hash,
|
||||
},
|
||||
]
|
||||
tokens_path.write_text(json.dumps(data), encoding="utf-8")
|
||||
os.chmod(tokens_path, 0o400)
|
||||
return tokens_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admitted_workloads() -> set[str]:
|
||||
return {"snappymail", "mail", "webmail", "jellyfin", "media", "docs"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TokenStore & Strict Permissions (0400)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_token_store_accepts_valid_0400_store(temp_tokens_file: Path):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
tokens = store.load_tokens()
|
||||
assert len(tokens) == 2
|
||||
assert tokens[0].role == Role.ADMIN
|
||||
assert tokens[1].role == Role.OPERATOR
|
||||
|
||||
|
||||
def test_token_store_rejects_insecure_file_permissions(tmp_path: Path):
|
||||
bad_tokens_file = tmp_path / "insecure_tokens.json"
|
||||
bad_tokens_file.write_text("[]", encoding="utf-8")
|
||||
|
||||
# Insecure modes: 0644, 0600, 0777
|
||||
for insecure_mode in [0o644, 0o600, 0o777, 0o444]:
|
||||
os.chmod(bad_tokens_file, insecure_mode)
|
||||
store = TokenStore(bad_tokens_file)
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
store.load_tokens()
|
||||
assert "mode 0400 required" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_AUTH_REQUIRED
|
||||
|
||||
|
||||
def test_token_store_rejects_missing_file(tmp_path: Path):
|
||||
missing_file = tmp_path / "nonexistent.json"
|
||||
store = TokenStore(missing_file)
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
store.load_tokens()
|
||||
assert "not found" in str(exc_info.value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Bearer Token Authentication
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_token_store_authenticates_valid_bearer_secrets(
|
||||
temp_tokens_file: Path, secret_tokens: dict[str, str]
|
||||
):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
p_admin = store.authenticate_bearer(secret_tokens["admin_secret"])
|
||||
assert p_admin.identity == "operator"
|
||||
assert p_admin.role == Role.ADMIN
|
||||
assert p_admin.token_id == "tok_admin_01"
|
||||
assert p_admin.auth_method == "bearer_token"
|
||||
|
||||
p_op = store.authenticate_bearer(secret_tokens["operator_secret"])
|
||||
assert p_op.identity == "gitops-dispatcher"
|
||||
assert p_op.role == Role.OPERATOR
|
||||
assert p_op.token_id == "tok_gitops_01"
|
||||
|
||||
|
||||
def test_token_store_rejects_invalid_bearer_secret(temp_tokens_file: Path):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
store.authenticate_bearer("wrong_secret_token_123")
|
||||
assert "Invalid or unknown Bearer token" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_AUTH_REQUIRED
|
||||
|
||||
|
||||
def test_token_store_rejects_empty_bearer_secret(temp_tokens_file: Path):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
store.authenticate_bearer("")
|
||||
assert "Empty Bearer token provided" in str(exc_info.value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Transport Authentication Rules (HTTP vs. Unix Domain Socket)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_authenticate_request_over_http_requires_valid_bearer(
|
||||
temp_tokens_file: Path, secret_tokens: dict[str, str]
|
||||
):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
# Valid Bearer token
|
||||
auth_header = f"Bearer {secret_tokens['admin_secret']}"
|
||||
p = authenticate_request("http", auth_header, token_store=store)
|
||||
assert p.role == Role.ADMIN
|
||||
|
||||
# Missing Authorization header -> 401
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
authenticate_request("http", None, token_store=store)
|
||||
assert "Bearer token required over network transport" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_AUTH_REQUIRED
|
||||
|
||||
# Malformed Authorization header -> 401
|
||||
with pytest.raises(AuthenticationError):
|
||||
authenticate_request("http", "Basic dXNlcjpwYXNz", token_store=store)
|
||||
|
||||
|
||||
def test_authenticate_request_over_uds_falls_back_to_viewer(
|
||||
temp_tokens_file: Path, secret_tokens: dict[str, str]
|
||||
):
|
||||
store = TokenStore(temp_tokens_file)
|
||||
|
||||
# Missing Authorization header over UDS with peer_uid=1000
|
||||
p = authenticate_request("unix_socket", None, peer_uid=1000, token_store=store)
|
||||
assert p.identity == "unix_uid_1000"
|
||||
assert p.role == Role.VIEWER
|
||||
assert p.token_id is None
|
||||
assert p.auth_method == "unix_peercred"
|
||||
|
||||
# Explicit Bearer token over UDS confers full privileges
|
||||
auth_header = f"Bearer {secret_tokens['admin_secret']}"
|
||||
p_admin = authenticate_request("unix_socket", auth_header, peer_uid=1000, token_store=store)
|
||||
assert p_admin.role == Role.ADMIN
|
||||
assert p_admin.auth_method == "bearer_token"
|
||||
|
||||
|
||||
def test_authenticate_request_over_uds_rejects_missing_peer_uid():
|
||||
with pytest.raises(AuthenticationError) as exc_info:
|
||||
authenticate_request("unix_socket", None, peer_uid=None)
|
||||
assert "Missing peer credentials" in str(exc_info.value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Deployments Registry Scope Loader
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_load_admitted_workloads_parses_names_and_aliases(tmp_path: Path):
|
||||
deploy_file = tmp_path / "deployments.yaml"
|
||||
deploy_file.write_text("""
|
||||
schemaVersion: "1.0"
|
||||
repositories:
|
||||
snappymail:
|
||||
path: "/home/operator/Sites/snappymail"
|
||||
aliases:
|
||||
- "mail"
|
||||
- "webmail"
|
||||
jellyfin:
|
||||
path: "/home/operator/Sites/homelab-jellyfin"
|
||||
aliases:
|
||||
- "media"
|
||||
""", encoding="utf-8")
|
||||
|
||||
admitted = load_admitted_workloads(deploy_file)
|
||||
assert "snappymail" in admitted
|
||||
assert "mail" in admitted
|
||||
assert "webmail" in admitted
|
||||
assert "jellyfin" in admitted
|
||||
assert "media" in admitted
|
||||
assert "unknown_app" not in admitted
|
||||
|
||||
|
||||
def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path):
|
||||
admitted = load_admitted_workloads(tmp_path / "missing.yaml")
|
||||
assert admitted == set()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# RBAC Policy Matrix Enforcement
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_rbac_admin_permitted_across_all_operations_and_targets(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
admin = Principal(identity="admin_user", role=Role.ADMIN, auth_method="bearer_token")
|
||||
|
||||
# Mutations across Core and Sites
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "traefik", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_DEPLOY, "unregistered_site", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_CONFIG, "core", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_LOGS, "traefik", admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads)
|
||||
enforce_rbac(admin, OperationType.WORKLOAD_LIST, None, admitted_workloads)
|
||||
|
||||
|
||||
def test_rbac_operator_permitted_on_admitted_workloads(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||
|
||||
# Permitted on admitted workload
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "snappymail", admitted_workloads)
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_UPDATE, "mail", admitted_workloads)
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_CONFIG, "jellyfin", admitted_workloads)
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_LOGS, "docs", admitted_workloads)
|
||||
enforce_rbac(operator, OperationType.PLATFORM_SYNC_HOMEPAGE, None, admitted_workloads)
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_LIST, None, admitted_workloads)
|
||||
|
||||
|
||||
def test_rbac_operator_denied_on_core_targets(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||
|
||||
# Targeting "core" stack
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "core", admitted_workloads)
|
||||
assert "not permitted to target core service 'core'" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
# Targeting core services (traefik, stalwart, etc.)
|
||||
for core_svc in ["traefik", "authelia", "stalwart", "socket-proxy"]:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_RESTART, core_svc, admitted_workloads)
|
||||
assert f"not permitted to target core service '{core_svc}'" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_rbac_operator_denied_on_unregistered_workload(
|
||||
admitted_workloads: set[str],
|
||||
):
|
||||
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "unregistered_app", admitted_workloads)
|
||||
assert "not registered in deployments.yaml" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_rbac_viewer_permitted_only_on_non_sensitive_reads():
|
||||
viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
|
||||
|
||||
# Permitted reads
|
||||
enforce_rbac(viewer, OperationType.WORKLOAD_LIST, None)
|
||||
enforce_rbac(viewer, OperationType.WORKLOAD_GET, "snappymail")
|
||||
enforce_rbac(viewer, OperationType.WORKLOAD_RESOLVE, "snappymail")
|
||||
enforce_rbac(viewer, OperationType.PLATFORM_SSL, "snappymail")
|
||||
enforce_rbac(viewer, OperationType.PLATFORM_HEALTH, None)
|
||||
|
||||
|
||||
def test_rbac_viewer_denied_on_mutations():
|
||||
viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
|
||||
|
||||
mutations = [
|
||||
OperationType.WORKLOAD_DEPLOY,
|
||||
OperationType.WORKLOAD_STOP,
|
||||
OperationType.WORKLOAD_RESTART,
|
||||
OperationType.WORKLOAD_UPDATE,
|
||||
OperationType.WORKLOAD_PULL,
|
||||
OperationType.PLATFORM_SYNC_HOMEPAGE,
|
||||
]
|
||||
for mut in mutations:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(viewer, mut, "snappymail")
|
||||
assert "not permitted to execute mutating operation" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
|
||||
|
||||
def test_rbac_viewer_denied_on_sensitive_reads():
|
||||
viewer = Principal(identity="unix_uid_1000", role=Role.VIEWER, auth_method="unix_peercred")
|
||||
|
||||
for sens_op in [OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]:
|
||||
with pytest.raises(AuthorizationError) as exc_info:
|
||||
enforce_rbac(viewer, sens_op, "snappymail")
|
||||
assert "not permitted to access sensitive operation" in str(exc_info.value)
|
||||
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||
@@ -24,7 +24,7 @@ x 2026-10-15 (A) Clarify Pydantic v2 target architecture, strict typing rules, a
|
||||
x 2026-10-15 (A) Migrate core_manifest.py to Pydantic v2 models for strict type validation and serialization +manifest @schema
|
||||
x 2026-10-19 (A) Implement strict Pydantic v2 API contracts, error sanitizer, and compose_pull action in scripts/appctl_contracts.py and scripts/core_manifest.py +contracts @p4
|
||||
x 2026-10-19 (A) Implement append-only audit logger with fail-closed disk guard and per-target flock manager in scripts/appctl_audit.py +audit @p4
|
||||
(A) Implement SOPS SHA-256 Bearer token authenticator, UDS SO_PEERCRED viewer fallback, and 3-role RBAC policy in scripts/appctl_auth.py +auth @p4
|
||||
x 2026-10-19 (A) Implement SOPS SHA-256 Bearer token authenticator, UDS SO_PEERCRED viewer fallback, and 3-role RBAC policy in scripts/appctl_auth.py +auth @p4
|
||||
(B) Implement operational router, pure-Python dotenv loader, Compose AST pre-flight, and revision-consistent workload.update in scripts/appctl_router.py +router @p4
|
||||
(B) Implement dual-transport HTTP/1.1 daemon (UDS + loopback TCP) and wire gitops_dispatcher.py worker to daemon in scripts/appctl_daemon.py +daemon @p4
|
||||
(B) Add comprehensive unit and security test suite for P4 contracts, RBAC, audit guard, concurrency, and dual-transport parity in tests/unit/test_appctl_daemon.py +test @p4
|
||||
|
||||
Reference in new issue
Block a user