diff --git a/tests/unit/test_appctl_audit.py b/tests/unit/test_appctl_audit.py index ce69250..92edd18 100644 --- a/tests/unit/test_appctl_audit.py +++ b/tests/unit/test_appctl_audit.py @@ -112,9 +112,13 @@ def test_audit_logger_writes_valid_jsonl_lifecycle( message="Workload updated and reconciled successfully", ) 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.status == "SUCCESS" 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" # Read and validate JSONL file contents @@ -153,10 +157,14 @@ def test_audit_logger_writes_failed_event( assert len(lines) == 1 event = AuditEvent.model_validate(json.loads(lines[0])) assert event.phase == AuditPhase.FAILED + assert event.target == "jellyfin" + assert event.parameters == {"recreate": True} assert event.result is not None assert event.result.status == "FAILED" assert event.result.exit_code == 1 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( @@ -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 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() diff --git a/tests/unit/test_appctl_auth.py b/tests/unit/test_appctl_auth.py index da980db..07f36f4 100644 --- a/tests/unit/test_appctl_auth.py +++ b/tests/unit/test_appctl_auth.py @@ -219,10 +219,36 @@ repositories: 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") 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 @@ -274,6 +300,37 @@ def test_rbac_operator_denied_on_core_targets( 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) + 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( diff --git a/tests/unit/test_appctl_cli.py b/tests/unit/test_appctl_cli.py index 48d022d..23e6e58 100644 --- a/tests/unit/test_appctl_cli.py +++ b/tests/unit/test_appctl_cli.py @@ -184,6 +184,135 @@ def test_cli_format_response_renders_workload_get_info(): 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): """Ensure scripts/appctl executes `complete` and `completion` via appctl_engine.py even when socket exists.""" 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), "SITES_DIR": str(tmp_path), } + if "PYTHONPATH" in os.environ: + env["PYTHONPATH"] = os.environ["PYTHONPATH"] + res_comp = subprocess.run( [bash_bin, str(appctl_script), "completion", "bash"], env=env, diff --git a/tests/unit/test_appctl_contracts.py b/tests/unit/test_appctl_contracts.py index a76c79b..c04ff57 100644 --- a/tests/unit/test_appctl_contracts.py +++ b/tests/unit/test_appctl_contracts.py @@ -493,16 +493,23 @@ def test_sanitize_validation_error_strips_input_and_url(): assert op_err.code == ErrorCode.ERR_VALIDATION_FAILED assert op_err.message == "Request payload validation failed" 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 - for detail in op_err.details: - assert "input" not in detail - assert "url" not in detail - assert "SUPER_SECRET_TOKEN_DO_NOT_LEAK" not in str(detail) - assert "loc" in detail - assert "msg" in detail - assert "type" in detail + assert "input" not in detail + assert "url" not in detail + assert "SUPER_SECRET_TOKEN_DO_NOT_LEAK" not in str(detail) + assert detail["loc"] == ["tail"] + assert detail["type"] == "int_type" + assert "Input should be a valid integer" in detail["msg"] + + # 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) # --------------------------------------------------------------------------- diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index 2199243..50d0cd1 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -171,6 +171,22 @@ def test_resolve_canonical_domain_precedence(monkeypatch: pytest.MonkeyPatch): monkeypatch.delenv("DOMAIN_SUFFIX") 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( mock_workload_dir: Path, monkeypatch: pytest.MonkeyPatch diff --git a/tests/unit/test_core_manifest.py b/tests/unit/test_core_manifest.py index d16eb78..edf2f5e 100644 --- a/tests/unit/test_core_manifest.py +++ b/tests/unit/test_core_manifest.py @@ -57,20 +57,73 @@ def test_validate_transport_rejects_http(insecure_url: str): 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( "traversal_url", [ "../../etc/shadow", "/home/operator/secret", "~/vault", - "file:///etc/passwd", + r"repo\windows\payload", + r"..\traversal", ], ) 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) +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(): assert classify_ref("main") == (RefType.BRANCH, "main") assert classify_ref("refs/heads/develop") == (RefType.BRANCH, "develop") @@ -79,6 +132,8 @@ def test_classify_ref_branches(): "feat/manifest-engine", ) 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(): diff --git a/tests/unit/test_provenance.py b/tests/unit/test_provenance.py index a068658..01c5834 100644 --- a/tests/unit/test_provenance.py +++ b/tests/unit/test_provenance.py @@ -230,3 +230,23 @@ def test_inspect_workload_two_axis(tmp_path: Path): ) assert status_fetch.provenance.status == ProvenanceStatus.SYNCED 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