Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3230e08bf9 | ||
|
|
b6ec909bb6 |
No files matched your search
@@ -46,6 +46,8 @@ __pycache__/
|
|||||||
*.pyc
|
*.pyc
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
.ruff_cache/
|
.ruff_cache/
|
||||||
|
mutants/
|
||||||
|
.mutmut-cache/
|
||||||
|
|
||||||
# Local Bootstrap & Operational Scripts
|
# Local Bootstrap & Operational Scripts
|
||||||
scripts/bootstrap_lldap_users.py
|
scripts/bootstrap_lldap_users.py
|
||||||
|
|||||||
@@ -20,3 +20,5 @@ pythonpath = [
|
|||||||
".",
|
".",
|
||||||
"scripts"
|
"scripts"
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -310,7 +310,7 @@ def enforce_rbac(
|
|||||||
return
|
return
|
||||||
|
|
||||||
# Target checks for operations targeting infrastructure
|
# Target checks for operations targeting infrastructure
|
||||||
if target is not None and (target in CORE_TARGETS or target == "core"):
|
if target is not None and target in CORE_TARGETS:
|
||||||
raise AuthorizationError(
|
raise AuthorizationError(
|
||||||
f"Role 'homelab-operator' is not permitted to target core service '{target}'",
|
f"Role 'homelab-operator' is not permitted to target core service '{target}'",
|
||||||
code=ErrorCode.ERR_PERMISSION_DENIED,
|
code=ErrorCode.ERR_PERMISSION_DENIED,
|
||||||
|
|||||||
@@ -33,7 +33,8 @@ from pydantic import (
|
|||||||
class StrictModel(BaseModel):
|
class StrictModel(BaseModel):
|
||||||
"""Base model propagating strict validation across all control plane models — ADR-0003."""
|
"""Base model propagating strict validation across all control plane models — ADR-0003."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="forbid", strict=True)
|
model_config = ConfigDict(extra="forbid", strict=True, ignored_types=(dict,))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class OperationType(StrEnum):
|
class OperationType(StrEnum):
|
||||||
@@ -241,7 +242,13 @@ def sanitize_validation_error(exc: ValidationError) -> OperationError:
|
|||||||
class OperationRequest(StrictModel):
|
class OperationRequest(StrictModel):
|
||||||
"""Defines the body requirements of an HTTP/1.1 operation request."""
|
"""Defines the body requirements of an HTTP/1.1 operation request."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="forbid", strict=True, populate_by_name=True)
|
model_config = ConfigDict(
|
||||||
|
extra="forbid",
|
||||||
|
strict=True,
|
||||||
|
populate_by_name=True,
|
||||||
|
ignored_types=(dict,),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
version: Literal["1.0"] = "1.0"
|
version: Literal["1.0"] = "1.0"
|
||||||
operation: FlexibleOperationType = Field(
|
operation: FlexibleOperationType = Field(
|
||||||
@@ -272,16 +279,17 @@ class OperationRequest(StrictModel):
|
|||||||
def validate_request(self) -> OperationRequest:
|
def validate_request(self) -> OperationRequest:
|
||||||
if self.operation in TARGET_REQUIRED_OPERATIONS and not self.target:
|
if self.operation in TARGET_REQUIRED_OPERATIONS and not self.target:
|
||||||
raise ValueError(f"Operation '{self.operation.value}' requires a non-empty target")
|
raise ValueError(f"Operation '{self.operation.value}' requires a non-empty target")
|
||||||
param_model = OPERATION_PARAMS_MAP.get(self.operation, EmptyParams)
|
param_model = OPERATION_PARAMS_MAP[self.operation]
|
||||||
param_model.model_validate(self.parameters)
|
param_model.model_validate(self.parameters)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def parse_parameters(self) -> StrictModel:
|
def parse_parameters(self) -> StrictModel:
|
||||||
"""Parse and return the typed parameter model for this operation."""
|
"""Parse and return the typed parameter model for this operation."""
|
||||||
param_model = OPERATION_PARAMS_MAP.get(self.operation, EmptyParams)
|
param_model = OPERATION_PARAMS_MAP[self.operation]
|
||||||
return param_model.model_validate(self.parameters)
|
return param_model.model_validate(self.parameters)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class OperationResponse(StrictModel):
|
class OperationResponse(StrictModel):
|
||||||
"""Defines the standard response payload for control plane operations."""
|
"""Defines the standard response payload for control plane operations."""
|
||||||
|
|
||||||
|
|||||||
@@ -244,11 +244,10 @@ def get_sites_apps(sites_dir: str | None = None) -> list[SitesApp]:
|
|||||||
KeyError,
|
KeyError,
|
||||||
) as err:
|
) as err:
|
||||||
raw_data = None
|
raw_data = None
|
||||||
with (
|
with contextlib.suppress(Exception), open(manifest_path, "r", encoding="utf-8") as f:
|
||||||
contextlib.suppress(Exception),
|
|
||||||
open(manifest_path, "r", encoding="utf-8") as f,
|
|
||||||
):
|
|
||||||
raw_data = yaml.safe_load(f)
|
raw_data = yaml.safe_load(f)
|
||||||
|
|
||||||
|
|
||||||
app_dict = raw_data if isinstance(raw_data, dict) else {}
|
app_dict = raw_data if isinstance(raw_data, dict) else {}
|
||||||
apps.append(
|
apps.append(
|
||||||
sites_app_from_manifest(
|
sites_app_from_manifest(
|
||||||
@@ -516,12 +515,10 @@ def check_ssl_cert(
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
ctx = ssl.create_default_context()
|
ctx = ssl.create_default_context()
|
||||||
with (
|
with socket.create_connection((domain, port), timeout=timeout) as sock: # noqa: SIM117
|
||||||
socket.create_connection((domain, port), timeout=timeout) as sock,
|
with ctx.wrap_socket(sock, server_hostname=domain) as ssock:
|
||||||
ctx.wrap_socket(sock, server_hostname=domain) as ssock,
|
raw_cert = ssock.getpeercert()
|
||||||
):
|
cert = raw_cert if isinstance(raw_cert, dict) else {}
|
||||||
raw_cert = ssock.getpeercert()
|
|
||||||
cert = raw_cert if isinstance(raw_cert, dict) else {}
|
|
||||||
|
|
||||||
not_after_str = str(cert.get("notAfter", ""))
|
not_after_str = str(cert.get("notAfter", ""))
|
||||||
days_remaining = None
|
days_remaining = None
|
||||||
|
|||||||
+14
-21
@@ -164,30 +164,16 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]:
|
|||||||
if SEMVER_TAG_RE.match(ref):
|
if SEMVER_TAG_RE.match(ref):
|
||||||
return RefType.TAG, ref
|
return RefType.TAG, ref
|
||||||
|
|
||||||
# Standard branch naming patterns
|
# Non-versioned arbitrary string treated as branch
|
||||||
if ref in {
|
|
||||||
"main",
|
|
||||||
"master",
|
|
||||||
"develop",
|
|
||||||
"dev",
|
|
||||||
"trunk",
|
|
||||||
"staging",
|
|
||||||
"prod",
|
|
||||||
"production",
|
|
||||||
}:
|
|
||||||
return RefType.BRANCH, ref
|
|
||||||
|
|
||||||
if ref.startswith(("feat/", "fix/", "release/", "chore/", "refactor/")):
|
|
||||||
return RefType.BRANCH, ref
|
|
||||||
|
|
||||||
# Fallback default: non-versioned arbitrary string treated as branch
|
|
||||||
return RefType.BRANCH, ref
|
return RefType.BRANCH, ref
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class SourceConfig(BaseModel):
|
class SourceConfig(BaseModel):
|
||||||
"""Upstream source provenance descriptor."""
|
"""Upstream source provenance descriptor."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="forbid")
|
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
|
||||||
|
|
||||||
|
|
||||||
url: str
|
url: str
|
||||||
ref: str = "main"
|
ref: str = "main"
|
||||||
@@ -235,7 +221,8 @@ class SourceConfig(BaseModel):
|
|||||||
class DeploymentConfig(BaseModel):
|
class DeploymentConfig(BaseModel):
|
||||||
"""Continuous deployment strategy and action policy."""
|
"""Continuous deployment strategy and action policy."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="forbid")
|
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
|
||||||
|
|
||||||
|
|
||||||
strategy: str = "compose"
|
strategy: str = "compose"
|
||||||
branch: str = "main"
|
branch: str = "main"
|
||||||
@@ -275,7 +262,8 @@ class DeploymentConfig(BaseModel):
|
|||||||
class HomepageConfig(BaseModel):
|
class HomepageConfig(BaseModel):
|
||||||
"""Dashboard card metadata for Homepage."""
|
"""Dashboard card metadata for Homepage."""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="forbid")
|
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
|
||||||
|
|
||||||
|
|
||||||
title: str
|
title: str
|
||||||
group: str = "Applications"
|
group: str = "Applications"
|
||||||
@@ -301,7 +289,12 @@ class Manifest(BaseModel):
|
|||||||
Represents the full contract declared in a workload's app.yaml.
|
Represents the full contract declared in a workload's app.yaml.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
model_config = ConfigDict(extra="forbid", populate_by_name=True)
|
model_config = ConfigDict(
|
||||||
|
extra="forbid",
|
||||||
|
populate_by_name=True,
|
||||||
|
ignored_types=(dict,),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
name: str
|
name: str
|
||||||
schema_version: str = Field(default="1.0", alias="schemaVersion")
|
schema_version: str = Field(default="1.0", alias="schemaVersion")
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
[mutmut]
|
||||||
|
also_copy=
|
||||||
|
pyproject.toml
|
||||||
|
docker-compose.yml
|
||||||
|
config
|
||||||
|
scripts
|
||||||
@@ -112,9 +112,13 @@ def test_audit_logger_writes_valid_jsonl_lifecycle(
|
|||||||
message="Workload updated and reconciled successfully",
|
message="Workload updated and reconciled successfully",
|
||||||
)
|
)
|
||||||
assert evt_comp.phase == AuditPhase.COMPLETED
|
assert evt_comp.phase == AuditPhase.COMPLETED
|
||||||
|
assert evt_comp.target == "jellyfin"
|
||||||
|
assert evt_comp.parameters == {"expected_branch": "main", "build": False}
|
||||||
assert evt_comp.result is not None
|
assert evt_comp.result is not None
|
||||||
assert evt_comp.result.status == "SUCCESS"
|
assert evt_comp.result.status == "SUCCESS"
|
||||||
assert evt_comp.result.exit_code == 0
|
assert evt_comp.result.exit_code == 0
|
||||||
|
assert evt_comp.result.duration_ms == 1450
|
||||||
|
assert evt_comp.result.message == "Workload updated and reconciled successfully"
|
||||||
assert evt_comp.result.commit_sha == "a1b2c3d"
|
assert evt_comp.result.commit_sha == "a1b2c3d"
|
||||||
|
|
||||||
# Read and validate JSONL file contents
|
# Read and validate JSONL file contents
|
||||||
@@ -153,10 +157,14 @@ def test_audit_logger_writes_failed_event(
|
|||||||
assert len(lines) == 1
|
assert len(lines) == 1
|
||||||
event = AuditEvent.model_validate(json.loads(lines[0]))
|
event = AuditEvent.model_validate(json.loads(lines[0]))
|
||||||
assert event.phase == AuditPhase.FAILED
|
assert event.phase == AuditPhase.FAILED
|
||||||
|
assert event.target == "jellyfin"
|
||||||
|
assert event.parameters == {"recreate": True}
|
||||||
assert event.result is not None
|
assert event.result is not None
|
||||||
assert event.result.status == "FAILED"
|
assert event.result.status == "FAILED"
|
||||||
assert event.result.exit_code == 1
|
assert event.result.exit_code == 1
|
||||||
assert event.result.error_code == "ERR_EXECUTION_FAILED"
|
assert event.result.error_code == "ERR_EXECUTION_FAILED"
|
||||||
|
assert event.result.duration_ms == 320
|
||||||
|
assert event.result.message == "Docker compose failed with exit code 1"
|
||||||
|
|
||||||
|
|
||||||
def test_audit_logger_writes_denied_event(
|
def test_audit_logger_writes_denied_event(
|
||||||
@@ -334,3 +342,16 @@ def test_homepage_sync_lock_acquires_designated_file(temp_lock_dir: Path):
|
|||||||
|
|
||||||
assert lock.lock_path.name == "_homepage_sync.lock"
|
assert lock.lock_path.name == "_homepage_sync.lock"
|
||||||
assert exc_info.value.target == "_homepage_sync"
|
assert exc_info.value.target == "_homepage_sync"
|
||||||
|
|
||||||
|
|
||||||
|
def test_target_lock_manager_sanitizes_special_characters_and_supports_env(
|
||||||
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
|
):
|
||||||
|
custom_lock_dir = tmp_path / "custom_locks"
|
||||||
|
monkeypatch.setenv("APPCTL_LOCK_DIR", str(custom_lock_dir))
|
||||||
|
manager = TargetLockManager()
|
||||||
|
assert manager.lock_dir == custom_lock_dir
|
||||||
|
|
||||||
|
with manager.lock_target("special/tenant:workload@v1!#$") as lock:
|
||||||
|
assert lock.lock_path.name == "special_tenant_workload_v1___.lock"
|
||||||
|
assert lock.lock_path.exists()
|
||||||
@@ -219,10 +219,36 @@ repositories:
|
|||||||
assert "unknown_app" not in admitted
|
assert "unknown_app" not in admitted
|
||||||
|
|
||||||
|
|
||||||
def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path):
|
def test_load_admitted_workloads_handles_aliases_edge_cases_and_json(tmp_path: Path):
|
||||||
|
deploy_file = tmp_path / "deployments.json"
|
||||||
|
deploy_file.write_text(json.dumps({
|
||||||
|
"repositories": {
|
||||||
|
"app1": {
|
||||||
|
"path": "/home/operator/Sites/app1",
|
||||||
|
"aliases": [123, None, " ", "valid_alias"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}), encoding="utf-8")
|
||||||
|
|
||||||
|
admitted = load_admitted_workloads(deploy_file)
|
||||||
|
assert "app1" in admitted
|
||||||
|
assert "valid_alias" in admitted
|
||||||
|
assert 123 not in admitted
|
||||||
|
assert None not in admitted
|
||||||
|
assert "" not in admitted
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_admitted_workloads_fails_closed_on_missing_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
|
||||||
admitted = load_admitted_workloads(tmp_path / "missing.yaml")
|
admitted = load_admitted_workloads(tmp_path / "missing.yaml")
|
||||||
assert admitted == set()
|
assert admitted == set()
|
||||||
|
|
||||||
|
# Test HOMELAB_DEPLOYMENTS_FILE fallback
|
||||||
|
deploy_file = tmp_path / "env_deploy.yaml"
|
||||||
|
deploy_file.write_text("repositories:\n env_app:\n path: /sites/env_app\n", encoding="utf-8")
|
||||||
|
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deploy_file))
|
||||||
|
admitted_env = load_admitted_workloads(None)
|
||||||
|
assert "env_app" in admitted_env
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# RBAC Policy Matrix Enforcement
|
# RBAC Policy Matrix Enforcement
|
||||||
@@ -274,6 +300,37 @@ def test_rbac_operator_denied_on_core_targets(
|
|||||||
with pytest.raises(AuthorizationError) as exc_info:
|
with pytest.raises(AuthorizationError) as exc_info:
|
||||||
enforce_rbac(operator, OperationType.WORKLOAD_RESTART, core_svc, admitted_workloads)
|
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)
|
assert f"not permitted to target core service '{core_svc}'" in str(exc_info.value)
|
||||||
|
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||||
|
|
||||||
|
|
||||||
|
def test_rbac_operator_denied_without_target_on_mutating_or_sensitive_ops(
|
||||||
|
admitted_workloads: set[str],
|
||||||
|
):
|
||||||
|
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||||
|
|
||||||
|
for op in [OperationType.WORKLOAD_DEPLOY, OperationType.WORKLOAD_UPDATE, OperationType.WORKLOAD_CONFIG, OperationType.WORKLOAD_LOGS]:
|
||||||
|
with pytest.raises(AuthorizationError) as exc_info:
|
||||||
|
enforce_rbac(operator, op, None, admitted_workloads)
|
||||||
|
assert f"Operation '{op.value}' requires an explicit workload target" in str(exc_info.value)
|
||||||
|
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||||
|
|
||||||
|
with pytest.raises(AuthorizationError) as exc_info:
|
||||||
|
enforce_rbac(operator, op, "", admitted_workloads)
|
||||||
|
assert f"Operation '{op.value}' requires an explicit workload target" in str(exc_info.value)
|
||||||
|
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||||
|
|
||||||
|
|
||||||
|
def test_rbac_operator_with_default_admitted_workloads(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
|
||||||
|
deployments_file = tmp_path / "deployments.yaml"
|
||||||
|
deployments_file.write_text("repositories:\n customapp:\n path: ~/Sites/customapp\n", encoding="utf-8")
|
||||||
|
monkeypatch.setenv("HOMELAB_DEPLOYMENTS_FILE", str(deployments_file))
|
||||||
|
|
||||||
|
operator = Principal(identity="gitops_bot", role=Role.OPERATOR, auth_method="bearer_token")
|
||||||
|
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "customapp", admitted_workloads=None)
|
||||||
|
|
||||||
|
with pytest.raises(AuthorizationError) as exc_info:
|
||||||
|
enforce_rbac(operator, OperationType.WORKLOAD_DEPLOY, "unknownapp", admitted_workloads=None)
|
||||||
|
assert exc_info.value.code == ErrorCode.ERR_PERMISSION_DENIED
|
||||||
|
|
||||||
|
|
||||||
def test_rbac_operator_denied_on_unregistered_workload(
|
def test_rbac_operator_denied_on_unregistered_workload(
|
||||||
|
|||||||
@@ -184,6 +184,135 @@ def test_cli_format_response_renders_workload_get_info():
|
|||||||
assert "✨ Retrieved metadata" not in rendered
|
assert "✨ Retrieved metadata" not in rendered
|
||||||
|
|
||||||
|
|
||||||
|
def test_cli_format_response_renders_empty_workload_list():
|
||||||
|
resp = OperationResponse(
|
||||||
|
version="1.0",
|
||||||
|
success=True,
|
||||||
|
operation_id="op_list_empty",
|
||||||
|
operation=OperationType.WORKLOAD_LIST,
|
||||||
|
result={"total": 0, "workloads": []},
|
||||||
|
output="",
|
||||||
|
)
|
||||||
|
rendered = format_response(resp, raw_json=False)
|
||||||
|
assert rendered == "ℹ️ No workloads found."
|
||||||
|
|
||||||
|
|
||||||
|
def test_cli_format_response_renders_core_service_and_rich_metadata():
|
||||||
|
resp = OperationResponse(
|
||||||
|
version="1.0",
|
||||||
|
success=True,
|
||||||
|
operation_id="op_get_core",
|
||||||
|
operation=OperationType.WORKLOAD_GET,
|
||||||
|
target="traefik",
|
||||||
|
result={
|
||||||
|
"workload": {
|
||||||
|
"name": "traefik",
|
||||||
|
"type": "core_service",
|
||||||
|
"dir_path": "/home/operator/Core",
|
||||||
|
"domain": "traefik.example.test",
|
||||||
|
"container": "traefik-proxy",
|
||||||
|
"description": "Edge Ingress",
|
||||||
|
"aliases": ["edge"],
|
||||||
|
"networks": ["proxy-net", "internal"],
|
||||||
|
"auth": False,
|
||||||
|
"visible": False,
|
||||||
|
"source": {
|
||||||
|
"url": "https://git.example.com/repo.git",
|
||||||
|
"ref": "main",
|
||||||
|
},
|
||||||
|
"manifest_error": "Syntax error in app.yaml",
|
||||||
|
"ssl": {
|
||||||
|
"status": "valid",
|
||||||
|
"issuer": "Let's Encrypt",
|
||||||
|
"formatted_expiry": "2027-01-01",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
output="",
|
||||||
|
)
|
||||||
|
rendered = format_response(resp, raw_json=False)
|
||||||
|
assert "ℹ️ Core Infrastructure Service: traefik" in rendered
|
||||||
|
assert "Container: traefik-proxy" in rendered
|
||||||
|
assert "Aliases: edge" in rendered
|
||||||
|
assert "Networks: proxy-net, internal" in rendered
|
||||||
|
assert "Auth Protected: False" in rendered
|
||||||
|
assert "Dashboard: Hidden" in rendered
|
||||||
|
assert "Source URL: https://git.example.com/repo.git" in rendered
|
||||||
|
assert "Target Ref: main" in rendered
|
||||||
|
assert "⚠️ Manifest Validation Error:" in rendered
|
||||||
|
assert "Syntax error in app.yaml" in rendered
|
||||||
|
assert "🔒 SSL/TLS Certificate:" in rendered
|
||||||
|
assert "Status: valid" in rendered
|
||||||
|
|
||||||
|
|
||||||
|
def test_cli_format_response_renders_ssl_info():
|
||||||
|
resp = OperationResponse(
|
||||||
|
version="1.0",
|
||||||
|
success=True,
|
||||||
|
operation_id="op_ssl_01",
|
||||||
|
operation=OperationType.PLATFORM_SSL,
|
||||||
|
result={
|
||||||
|
"ssl": {
|
||||||
|
"domain": "app.example.test",
|
||||||
|
"status": "valid",
|
||||||
|
"issuer": "Let's Encrypt Authority X3",
|
||||||
|
"subject": "CN=app.example.test",
|
||||||
|
"not_after": "2027-01-01 00:00:00 GMT",
|
||||||
|
"days_remaining": 75,
|
||||||
|
"formatted_expiry": "in 75 days",
|
||||||
|
"error": "Near expiration warning",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
output="",
|
||||||
|
)
|
||||||
|
rendered = format_response(resp, raw_json=False)
|
||||||
|
assert "🔒 SSL/TLS Certificate: app.example.test" in rendered
|
||||||
|
assert "Domain: app.example.test" in rendered
|
||||||
|
assert "Status: valid" in rendered
|
||||||
|
assert "Issuer: Let's Encrypt Authority X3" in rendered
|
||||||
|
assert "Subject: CN=app.example.test" in rendered
|
||||||
|
assert "Expiration: 2027-01-01 00:00:00 GMT" in rendered
|
||||||
|
assert "Days Remaining: 75 days (in 75 days)" in rendered
|
||||||
|
assert "Details/Error: Near expiration warning" in rendered
|
||||||
|
|
||||||
|
|
||||||
|
def test_cli_format_response_renders_workload_resolve_json():
|
||||||
|
import json
|
||||||
|
workload_data = {"name": "app1", "dir": "/sites/app1"}
|
||||||
|
resp = OperationResponse(
|
||||||
|
version="1.0",
|
||||||
|
success=True,
|
||||||
|
operation_id="op_resolve_01",
|
||||||
|
operation=OperationType.WORKLOAD_RESOLVE,
|
||||||
|
result={"workload": workload_data},
|
||||||
|
output="",
|
||||||
|
)
|
||||||
|
rendered = format_response(resp, raw_json=False)
|
||||||
|
assert json.loads(rendered) == workload_data
|
||||||
|
|
||||||
|
|
||||||
|
def test_cli_format_response_error_without_error_payload():
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
resp = MagicMock(spec=OperationResponse)
|
||||||
|
resp.success = False
|
||||||
|
resp.error = None
|
||||||
|
rendered = format_response(resp, raw_json=False)
|
||||||
|
assert rendered == "❌ Error: Unknown error"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_cli_format_response_default_success_message():
|
||||||
|
resp = OperationResponse(
|
||||||
|
version="1.0",
|
||||||
|
success=True,
|
||||||
|
operation_id="op_succ",
|
||||||
|
operation=OperationType.PLATFORM_HEALTH,
|
||||||
|
)
|
||||||
|
rendered = format_response(resp, raw_json=False)
|
||||||
|
assert rendered == "✨ Operation 'platform.health' succeeded."
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path, monkeypatch):
|
def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path, monkeypatch):
|
||||||
"""Ensure scripts/appctl executes `complete` and `completion` via appctl_engine.py even when socket exists."""
|
"""Ensure scripts/appctl executes `complete` and `completion` via appctl_engine.py even when socket exists."""
|
||||||
import os
|
import os
|
||||||
@@ -205,6 +334,9 @@ def test_appctl_wrapper_fast_paths_completion_when_socket_exists(tmp_path: Path,
|
|||||||
"APPCTL_SOCKET_PATH": str(sock_path),
|
"APPCTL_SOCKET_PATH": str(sock_path),
|
||||||
"SITES_DIR": str(tmp_path),
|
"SITES_DIR": str(tmp_path),
|
||||||
}
|
}
|
||||||
|
if "PYTHONPATH" in os.environ:
|
||||||
|
env["PYTHONPATH"] = os.environ["PYTHONPATH"]
|
||||||
|
|
||||||
res_comp = subprocess.run(
|
res_comp = subprocess.run(
|
||||||
[bash_bin, str(appctl_script), "completion", "bash"],
|
[bash_bin, str(appctl_script), "completion", "bash"],
|
||||||
env=env,
|
env=env,
|
||||||
|
|||||||
@@ -493,16 +493,23 @@ def test_sanitize_validation_error_strips_input_and_url():
|
|||||||
assert op_err.code == ErrorCode.ERR_VALIDATION_FAILED
|
assert op_err.code == ErrorCode.ERR_VALIDATION_FAILED
|
||||||
assert op_err.message == "Request payload validation failed"
|
assert op_err.message == "Request payload validation failed"
|
||||||
assert op_err.details is not None
|
assert op_err.details is not None
|
||||||
assert len(op_err.details) > 0
|
assert len(op_err.details) == 1
|
||||||
|
detail = op_err.details[0]
|
||||||
|
|
||||||
# Ensure neither input nor url appears in any details dictionary
|
# Ensure neither input nor url appears in any details dictionary
|
||||||
for detail in op_err.details:
|
assert "input" not in detail
|
||||||
assert "input" not in detail
|
assert "url" not in detail
|
||||||
assert "url" not in detail
|
assert "SUPER_SECRET_TOKEN_DO_NOT_LEAK" not in str(detail)
|
||||||
assert "SUPER_SECRET_TOKEN_DO_NOT_LEAK" not in str(detail)
|
assert detail["loc"] == ["tail"]
|
||||||
assert "loc" in detail
|
assert detail["type"] == "int_type"
|
||||||
assert "msg" in detail
|
assert "Input should be a valid integer" in detail["msg"]
|
||||||
assert "type" in detail
|
|
||||||
|
# Verify defense-in-depth: exc.errors called with include_input=False and include_url=False
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
mock_exc = MagicMock(spec=ValidationError)
|
||||||
|
mock_exc.errors.return_value = [{"loc": ("field",), "type": "value_error", "msg": "Invalid"}]
|
||||||
|
sanitize_validation_error(mock_exc)
|
||||||
|
mock_exc.errors.assert_called_once_with(include_input=False, include_url=False)
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -171,6 +171,22 @@ def test_resolve_canonical_domain_precedence(monkeypatch: pytest.MonkeyPatch):
|
|||||||
monkeypatch.delenv("DOMAIN_SUFFIX")
|
monkeypatch.delenv("DOMAIN_SUFFIX")
|
||||||
assert resolve_canonical_domain() == "domain-c.test"
|
assert resolve_canonical_domain() == "domain-c.test"
|
||||||
|
|
||||||
|
# Fails closed when domain is unset
|
||||||
|
monkeypatch.delenv("DOMAIN")
|
||||||
|
monkeypatch.setattr("appctl_router.ENGINE_HOMELAB_DOMAIN", "")
|
||||||
|
with pytest.raises(RouterValidationError, match="Canonical domain is unset"):
|
||||||
|
resolve_canonical_domain()
|
||||||
|
|
||||||
|
# Fails closed when domain is whitespace only
|
||||||
|
monkeypatch.setenv("HOMELAB_DOMAIN", " ")
|
||||||
|
with pytest.raises(RouterValidationError, match="Canonical domain is unset"):
|
||||||
|
resolve_canonical_domain()
|
||||||
|
|
||||||
|
# Strips leading and trailing whitespace
|
||||||
|
monkeypatch.setenv("HOMELAB_DOMAIN", " stripped.example.test ")
|
||||||
|
assert resolve_canonical_domain() == "stripped.example.test"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_assemble_workload_env_constructs_6_layer_environment(
|
def test_assemble_workload_env_constructs_6_layer_environment(
|
||||||
mock_workload_dir: Path, monkeypatch: pytest.MonkeyPatch
|
mock_workload_dir: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
|
|||||||
@@ -57,20 +57,73 @@ def test_validate_transport_rejects_http(insecure_url: str):
|
|||||||
validate_transport(insecure_url)
|
validate_transport(insecure_url)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"empty_or_invalid_url",
|
||||||
|
[
|
||||||
|
"",
|
||||||
|
" ",
|
||||||
|
None,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_validate_transport_rejects_empty_or_non_string(empty_or_invalid_url):
|
||||||
|
with pytest.raises(ManifestValidationError, match=r"^Source URL cannot be empty\.$"):
|
||||||
|
validate_transport(empty_or_invalid_url) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("root_path_url", "scheme"),
|
||||||
|
[
|
||||||
|
("https://git.example.com/", "HTTPS"),
|
||||||
|
("ssh://git.example.com/", "SSH"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_validate_transport_rejects_root_repository_path(root_path_url: str, scheme: str):
|
||||||
|
with pytest.raises(
|
||||||
|
ManifestValidationError,
|
||||||
|
match=rf"^Malformed {scheme} source URL \(missing repository path\)",
|
||||||
|
):
|
||||||
|
validate_transport(root_path_url)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"traversal_url",
|
"traversal_url",
|
||||||
[
|
[
|
||||||
"../../etc/shadow",
|
"../../etc/shadow",
|
||||||
"/home/operator/secret",
|
"/home/operator/secret",
|
||||||
"~/vault",
|
"~/vault",
|
||||||
"file:///etc/passwd",
|
r"repo\windows\payload",
|
||||||
|
r"..\traversal",
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_validate_transport_rejects_paths_and_traversal(traversal_url: str):
|
def test_validate_transport_rejects_paths_and_traversal(traversal_url: str):
|
||||||
with pytest.raises(ManifestValidationError):
|
with pytest.raises(
|
||||||
|
ManifestValidationError,
|
||||||
|
match="Prohibited filesystem path or traversal in source URL",
|
||||||
|
):
|
||||||
validate_transport(traversal_url)
|
validate_transport(traversal_url)
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_transport_rejects_file_scheme():
|
||||||
|
with pytest.raises(
|
||||||
|
ManifestValidationError,
|
||||||
|
match="Invalid source.url scheme: 'file:///etc/passwd'",
|
||||||
|
):
|
||||||
|
validate_transport("file:///etc/passwd")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"empty_ref",
|
||||||
|
[
|
||||||
|
"",
|
||||||
|
" ",
|
||||||
|
None,
|
||||||
|
12345,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_classify_ref_empty_or_invalid_defaults_to_main(empty_ref):
|
||||||
|
assert classify_ref(empty_ref) == (RefType.BRANCH, "main") # type: ignore[arg-type]
|
||||||
|
|
||||||
|
|
||||||
def test_classify_ref_branches():
|
def test_classify_ref_branches():
|
||||||
assert classify_ref("main") == (RefType.BRANCH, "main")
|
assert classify_ref("main") == (RefType.BRANCH, "main")
|
||||||
assert classify_ref("refs/heads/develop") == (RefType.BRANCH, "develop")
|
assert classify_ref("refs/heads/develop") == (RefType.BRANCH, "develop")
|
||||||
@@ -79,6 +132,8 @@ def test_classify_ref_branches():
|
|||||||
"feat/manifest-engine",
|
"feat/manifest-engine",
|
||||||
)
|
)
|
||||||
assert classify_ref("release/v1.0") == (RefType.BRANCH, "release/v1.0")
|
assert classify_ref("release/v1.0") == (RefType.BRANCH, "release/v1.0")
|
||||||
|
assert classify_ref("custom-adhoc-branch") == (RefType.BRANCH, "custom-adhoc-branch")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_classify_ref_tags():
|
def test_classify_ref_tags():
|
||||||
|
|||||||
@@ -230,3 +230,23 @@ def test_inspect_workload_two_axis(tmp_path: Path):
|
|||||||
)
|
)
|
||||||
assert status_fetch.provenance.status == ProvenanceStatus.SYNCED
|
assert status_fetch.provenance.status == ProvenanceStatus.SYNCED
|
||||||
mock_resolve.assert_called_once()
|
mock_resolve.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_upstream_provenance_class_b_and_default_timeout():
|
||||||
|
# 1. Class B workload (source is None)
|
||||||
|
prov_class_b = resolve_upstream_provenance(None)
|
||||||
|
assert prov_class_b.status == ProvenanceStatus.IMAGE_ONLY
|
||||||
|
assert prov_class_b.message == "Class B workload deploys prebuilt container images directly"
|
||||||
|
|
||||||
|
# 2. Default timeout (10.0s) verification
|
||||||
|
source = SourceConfig(
|
||||||
|
url="https://git.example.com/operator/app.git",
|
||||||
|
ref="main",
|
||||||
|
ref_type=RefType.BRANCH,
|
||||||
|
transport=TransportScheme.HTTPS,
|
||||||
|
)
|
||||||
|
with patch("subprocess.run") as mock_run:
|
||||||
|
mock_run.return_value = MagicMock(returncode=0, stdout="abc1234567890abcdef1234567890abcdef12345\trefs/heads/main\n")
|
||||||
|
prov = resolve_upstream_provenance(source, local_commit="abc1234")
|
||||||
|
assert prov.status == ProvenanceStatus.SYNCED
|
||||||
|
assert mock_run.call_args[1]["timeout"] == 10.0
|
||||||
Reference in new issue
Block a user