feat(P42): stub implementation — SoD, HITL gates, attestation matrix, Wiz, Kyverno
---ci--- project: acdl phase: 42 milestone: v1.9 status: execute ---/ci--- Phase 42 — stub-implementation (REQ-107..111, D-084): route_halt_artifact (REQ-107): - core/separation_of_duties.py: real SNS publish (ACDL_SOD_HALT_TOPIC_ARN) + outbox fallback (SEPARATION_OF_DUTIES_VIOLATION event via outbox_writer) + stderr emission. No silent print-only stub. - terraform/platform/main.tf: aws_sns_topic.acdl-sod-halt + output. HITL attestation gates (REQ-108): - core/hitl_gates.py: attest(contract_id, env, approver, evidence, outbox_client) records approver_qa/approver_prod/approver_dr to outbox, runs SoD check on prod, invokes attestation matrix, returns (ok, reason). Dev skips (autonomous). approver_from_env() reads GITHUB_ACTOR/GITEA_ACTOR. - scripts/run_platform.sh: Step 7b HITL gate before apply for qa/prod/dr. 8-concern attestation matrix (REQ-109, D-084): - core/attestation_matrix.py: check(env, evidence) runs the 8 concerns from hitl_matrix_design.md §10.4. Offline-testable (contract_nfrs, schema_validity, policy_pass) run for real. Operator-supplied accept signed artifacts validated for freshness (FRESHNESS_DAYS table) + schema. Signature skip when ACDL_ATTESTATION_SIGNING_KEY_ID unset (D-089). Fail loud if missing/expired for prod/dr. Wiz real client (REQ-110): - adapters/wiz/wiz_adapter.py: WizClient (GraphQL API, Bearer auth, pagination via pageInfo.hasNextPage + endCursor). fetch_and_adapt translates issues → PolicyCheckResult; graceful degrade when WIZ_API_TOKEN/WIZ_API_URL unset. Kyverno fleshed out (REQ-111): - adapters/kyverno/kyverno_adapter.py: full PolicyReport → PolicyCheckResult mapping (pass/fail/skip/warn + severity + skip-with- reason + resource ref construction from kind/name/namespace). adapt_inactive() emits KYVERNO_INACTIVE_TF_STACK guard. --kube-version stub parsed for future GitOps. Tests: +47 (test_route_halt_artifact.py, test_hitl_gates.py, test_attestation_matrix.py, test_wiz_adapter_real_client.py, expanded test_kyverno_adapter.py). Existing wiz_adapter tests updated for the real client's control.name ruleId. 493 passed; run_ci.sh green; run_platform.sh --check-only green.
This commit is contained in:
@@ -0,0 +1,136 @@
|
||||
"""REQ-109: 8-concern attestation matrix."""
|
||||
import datetime
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from core.attestation_matrix import check, _is_fresh, _verify_signature, FRESHNESS_DAYS
|
||||
|
||||
|
||||
def _fresh_artifact(concern, days_ago=0):
|
||||
ts = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=days_ago)
|
||||
return {"timestamp": ts.isoformat(), "type": concern, "payload": {}, "signature": "sig"}
|
||||
|
||||
|
||||
def test_dev_passes_autonomous():
|
||||
ok, reason = check("dev", {})
|
||||
assert ok is True
|
||||
assert "autonomous" in reason
|
||||
|
||||
|
||||
def test_qa_offline_concerns_pass_with_valid_evidence():
|
||||
"""qa concerns: functional_correctness, performance_baseline, security_posture, contract_nfrs.
|
||||
The offline-testable contract_nfrs passes by default; the operator-supplied
|
||||
ones require artifacts."""
|
||||
evidence = {
|
||||
"functional_correctness": _fresh_artifact("functional_correctness"),
|
||||
"performance_baseline": _fresh_artifact("performance_baseline"),
|
||||
"security_posture": _fresh_artifact("security_posture"),
|
||||
"contract_nfrs": {"valid": True},
|
||||
}
|
||||
ok, reason = check("qa", evidence)
|
||||
assert ok is True
|
||||
|
||||
|
||||
def test_qa_blocks_on_missing_operator_concern():
|
||||
"""A missing operator-supplied concern blocks qa."""
|
||||
evidence = {
|
||||
"performance_baseline": _fresh_artifact("performance_baseline"),
|
||||
"security_posture": _fresh_artifact("security_posture"),
|
||||
"contract_nfrs": {"valid": True},
|
||||
# functional_correctness missing
|
||||
}
|
||||
ok, reason = check("qa", evidence)
|
||||
assert ok is False
|
||||
assert "functional_correctness" in reason
|
||||
|
||||
|
||||
def test_prod_blocks_on_missing_evidence():
|
||||
ok, reason = check("prod", {})
|
||||
assert ok is False
|
||||
assert "missing" in reason or "expired" in reason
|
||||
|
||||
|
||||
def test_prod_passes_with_all_evidence():
|
||||
evidence = {
|
||||
"operational_readiness": _fresh_artifact("operational_readiness"),
|
||||
"incident_response": _fresh_artifact("incident_response"),
|
||||
"capacity_cost": _fresh_artifact("capacity_cost"),
|
||||
"resilience_dr_drill": _fresh_artifact("resilience_dr_drill"),
|
||||
"resilience_chaos": _fresh_artifact("resilience_chaos"),
|
||||
"resilience_backup": _fresh_artifact("resilience_backup"),
|
||||
"contract_nfrs": {"valid": True},
|
||||
}
|
||||
ok, reason = check("prod", evidence)
|
||||
assert ok is True
|
||||
|
||||
|
||||
def test_expired_artifact_blocks():
|
||||
"""An artifact older than its freshness window blocks."""
|
||||
evidence = {
|
||||
"operational_readiness": _fresh_artifact("operational_readiness", days_ago=31),
|
||||
"incident_response": _fresh_artifact("incident_response"),
|
||||
"capacity_cost": _fresh_artifact("capacity_cost"),
|
||||
"resilience_dr_drill": _fresh_artifact("resilience_dr_drill"),
|
||||
"resilience_chaos": _fresh_artifact("resilience_chaos"),
|
||||
"resilience_backup": _fresh_artifact("resilience_backup"),
|
||||
"contract_nfrs": {"valid": True},
|
||||
}
|
||||
ok, reason = check("prod", evidence)
|
||||
assert ok is False
|
||||
assert "operational_readiness" in reason
|
||||
|
||||
|
||||
def test_dr_passes_with_evidence():
|
||||
evidence = {
|
||||
"dr_region_deploy": _fresh_artifact("dr_region_deploy"),
|
||||
"contract_nfrs": {"valid": True},
|
||||
}
|
||||
ok, reason = check("dr", evidence)
|
||||
assert ok is True
|
||||
|
||||
|
||||
def test_dr_blocks_on_missing_dr_drill():
|
||||
ok, reason = check("dr", {"contract_nfrs": {"valid": True}})
|
||||
assert ok is False
|
||||
assert "dr_region_deploy" in reason
|
||||
|
||||
|
||||
def test_signature_skip_when_key_unset(monkeypatch, capsys):
|
||||
"""D-089: signature verification is skipped when the signing key is unset."""
|
||||
monkeypatch.delenv("ACDL_ATTESTATION_SIGNING_KEY_ID", raising=False)
|
||||
artifact = {"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
"type": "x", "payload": {}, "signature": "sig"}
|
||||
assert _verify_signature(artifact) is True
|
||||
captured = capsys.readouterr()
|
||||
assert "skipped" in captured.err
|
||||
|
||||
|
||||
def test_signature_required_when_key_set(monkeypatch):
|
||||
"""When the signing key is set, a missing signature fails."""
|
||||
monkeypatch.setenv("ACDL_ATTESTATION_SIGNING_KEY_ID", "kms-key-id")
|
||||
artifact = {"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
"type": "x", "payload": {}} # no signature
|
||||
assert _verify_signature(artifact) is False
|
||||
|
||||
|
||||
def test_freshness_within_window():
|
||||
artifact = _fresh_artifact("functional_correctness", days_ago=0)
|
||||
assert _is_fresh(artifact, "functional_correctness") is True
|
||||
|
||||
|
||||
def test_freshness_outside_window():
|
||||
artifact = _fresh_artifact("functional_correctness", days_ago=2)
|
||||
assert _is_fresh(artifact, "functional_correctness") is False
|
||||
|
||||
|
||||
def test_freshness_days_table_has_all_concerns():
|
||||
"""The freshness table covers all operator-supplied concerns."""
|
||||
for concern in ["functional_correctness", "performance_baseline", "security_posture",
|
||||
"operational_readiness", "incident_response", "capacity_cost",
|
||||
"resilience_dr_drill", "dr_region_deploy"]:
|
||||
assert concern in FRESHNESS_DAYS
|
||||
@@ -0,0 +1,126 @@
|
||||
"""REQ-108: HITL qa/prod/dr attestation gates."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from core.hitl_gates import attest, approver_from_env
|
||||
from core.attestation_matrix import FRESHNESS_DAYS, ENV_CONCERNS
|
||||
import datetime
|
||||
|
||||
|
||||
def _fresh_evidence_for(env):
|
||||
"""Build a valid evidence bundle with fresh artifacts for every concern in env."""
|
||||
evidence = {"contract_nfrs": {"valid": True}}
|
||||
for concern in ENV_CONCERNS.get(env, []):
|
||||
if concern != "contract_nfrs":
|
||||
ts = datetime.datetime.now(datetime.timezone.utc)
|
||||
evidence[concern] = {"timestamp": ts.isoformat(), "type": concern,
|
||||
"payload": {}, "signature": "sig"}
|
||||
return evidence
|
||||
|
||||
|
||||
class FakeOutbox:
|
||||
"""Minimal outbox client for tests: stores approver attrs per contract."""
|
||||
def __init__(self):
|
||||
self.records = {}
|
||||
|
||||
def put_approver(self, contract_id, attr, value):
|
||||
self.records.setdefault(contract_id, {})[attr] = value
|
||||
|
||||
def get(self, contract_id):
|
||||
return self.records.get(contract_id)
|
||||
|
||||
|
||||
def test_dev_skips_gate():
|
||||
ok, reason = attest("c1", "dev", "alice")
|
||||
assert ok is True
|
||||
assert "autonomous" in reason
|
||||
|
||||
|
||||
def test_qa_records_approver():
|
||||
outbox = FakeOutbox()
|
||||
ok, reason = attest("c2", "qa", "bob", evidence=_fresh_evidence_for("qa"),
|
||||
outbox_client=outbox)
|
||||
assert ok is True
|
||||
assert outbox.records["c2"]["approver_qa"] == "bob"
|
||||
|
||||
|
||||
def test_prod_records_approver():
|
||||
outbox = FakeOutbox()
|
||||
ok, reason = attest("c3", "prod", "carol", evidence=_fresh_evidence_for("prod"),
|
||||
outbox_client=outbox)
|
||||
assert ok is True
|
||||
assert outbox.records["c3"]["approver_prod"] == "carol"
|
||||
|
||||
|
||||
def test_dr_records_approver():
|
||||
outbox = FakeOutbox()
|
||||
ok, reason = attest("c4", "dr", "dave", evidence=_fresh_evidence_for("dr"),
|
||||
outbox_client=outbox)
|
||||
assert ok is True
|
||||
assert outbox.records["c4"]["approver_dr"] == "dave"
|
||||
|
||||
|
||||
def test_prod_sod_blocks_on_identity_equality():
|
||||
"""When approver_qa == approver_prod, prod promotion is blocked."""
|
||||
outbox = FakeOutbox()
|
||||
outbox.put_approver("c5", "approver_qa", "eve")
|
||||
with mock.patch("core.separation_of_duties.route_halt_artifact"):
|
||||
ok, reason = attest("c5", "prod", "eve", outbox_client=outbox)
|
||||
assert ok is False
|
||||
assert "SEPARATION_OF_DUTIES_VIOLATION" in reason
|
||||
|
||||
|
||||
def test_prod_sod_passes_when_approvers_differ():
|
||||
outbox = FakeOutbox()
|
||||
outbox.put_approver("c6", "approver_qa", "alice")
|
||||
ok, reason = attest("c6", "prod", "bob", evidence=_fresh_evidence_for("prod"),
|
||||
outbox_client=outbox)
|
||||
assert ok is True
|
||||
|
||||
|
||||
def test_no_approver_blocks_non_dev():
|
||||
ok, reason = attest("c7", "qa", "", outbox_client=FakeOutbox())
|
||||
assert ok is False
|
||||
assert "no approver" in reason
|
||||
|
||||
|
||||
def test_unknown_env_blocks():
|
||||
ok, reason = attest("c8", "staging", "alice")
|
||||
assert ok is False
|
||||
assert "unknown environment" in reason
|
||||
|
||||
|
||||
def test_approver_from_env_github(monkeypatch):
|
||||
monkeypatch.setenv("GITHUB_ACTOR", "gh-user")
|
||||
monkeypatch.delenv("GITEA_ACTOR", raising=False)
|
||||
assert approver_from_env() == "gh-user"
|
||||
|
||||
|
||||
def test_approver_from_env_gitea(monkeypatch):
|
||||
monkeypatch.delenv("GITHUB_ACTOR", raising=False)
|
||||
monkeypatch.setenv("GITEA_ACTOR", "gitea-user")
|
||||
assert approver_from_env() == "gitea-user"
|
||||
|
||||
|
||||
def test_attest_invokes_attestation_matrix_for_prod():
|
||||
"""attest calls the attestation matrix for prod."""
|
||||
outbox = FakeOutbox()
|
||||
outbox.put_approver("c9", "approver_qa", "alice")
|
||||
with mock.patch("core.attestation_matrix.check", return_value=(False, "missing evidence")) as m:
|
||||
ok, reason = attest("c9", "prod", "bob", outbox_client=outbox)
|
||||
m.assert_called_once()
|
||||
assert ok is False
|
||||
assert "missing evidence" in reason
|
||||
|
||||
|
||||
def test_run_platform_sh_has_hitl_gate_step():
|
||||
text = (ROOT / "scripts" / "run_platform.sh").read_text()
|
||||
assert "HITL attestation gate" in text
|
||||
assert "hitl_gates" in text
|
||||
assert "RESOLVED_ENV" in text
|
||||
@@ -103,19 +103,23 @@ class TestAdapt:
|
||||
f = tmp_path / "empty.json"
|
||||
f.write_text(json.dumps({"results": []}))
|
||||
results = adapt(str(f), "11111111-1111-1111-1111-111111111111")
|
||||
assert results == []
|
||||
# Empty results emit the inactive-for-TF guard record (REQ-111).
|
||||
assert len(results) == 1
|
||||
assert results[0]["ruleId"] == "KYVERNO_INACTIVE_TF_STACK"
|
||||
|
||||
def test_missing_results_key(self, tmp_path):
|
||||
f = tmp_path / "noresults.json"
|
||||
f.write_text(json.dumps({"apiVersion": "x", "kind": "PolicyReport"}))
|
||||
results = adapt(str(f), "11111111-1111-1111-1111-111111111111")
|
||||
assert results == []
|
||||
assert len(results) == 1
|
||||
assert results[0]["ruleId"] == "KYVERNO_INACTIVE_TF_STACK"
|
||||
|
||||
def test_non_list_results_treated_as_empty(self, tmp_path):
|
||||
f = tmp_path / "bad.json"
|
||||
f.write_text(json.dumps({"results": "not-a-list"}))
|
||||
results = adapt(str(f), "11111111-1111-1111-1111-111111111111")
|
||||
assert results == []
|
||||
assert len(results) == 1
|
||||
assert results[0]["ruleId"] == "KYVERNO_INACTIVE_TF_STACK"
|
||||
|
||||
def test_missing_fields_in_entry(self, tmp_path, policy_check_result_schema):
|
||||
f = tmp_path / "sparse.json"
|
||||
@@ -138,4 +142,80 @@ class TestAdapt:
|
||||
]}))
|
||||
results = adapt(str(f), "11111111-1111-1111-1111-111111111111")
|
||||
assert results[0]["result"] == "error"
|
||||
jsonschema.validate(results[0], policy_check_result_schema)
|
||||
jsonschema.validate(results[0], policy_check_result_schema)
|
||||
|
||||
# --- v1.9 REQ-111: fleshed-out translator tests ---
|
||||
|
||||
class TestFleshedOutTranslator:
|
||||
def test_pass_result_emits_pass(self, tmp_path):
|
||||
f = tmp_path / "pass.json"
|
||||
f.write_text(json.dumps({"results": [
|
||||
{"policy": "require-labels", "rule": "check-app-label", "severity": "medium",
|
||||
"result": "pass", "resource": "pod/x", "message": "label present"},
|
||||
]}))
|
||||
results = adapt(str(f), "c1")
|
||||
assert results[0]["result"] == "pass"
|
||||
assert results[0]["ruleId"] == "require-labels/check-app-label"
|
||||
|
||||
def test_fail_result_with_severity(self, tmp_path):
|
||||
f = tmp_path / "fail.json"
|
||||
f.write_text(json.dumps({"results": [
|
||||
{"policy": "disallow-privileged", "rule": "no-priv", "severity": "critical",
|
||||
"result": "fail", "resource": "pod/y", "message": "privileged container"},
|
||||
]}))
|
||||
results = adapt(str(f), "c2")
|
||||
assert results[0]["result"] == "fail"
|
||||
assert results[0]["severity"] == "critical"
|
||||
assert results[0]["ruleId"] == "disallow-privileged/no-priv"
|
||||
|
||||
def test_skip_with_reason(self, tmp_path):
|
||||
f = tmp_path / "skip.json"
|
||||
f.write_text(json.dumps({"results": [
|
||||
{"policy": "require-image-digests", "rule": "digest", "severity": "low",
|
||||
"result": "skip", "resource": "pod/z", "skipReason": "no image"},
|
||||
]}))
|
||||
results = adapt(str(f), "c3")
|
||||
assert results[0]["result"] == "skipped"
|
||||
assert "no image" in results[0]["message"]
|
||||
|
||||
def test_warn_result_maps_to_skipped(self, tmp_path):
|
||||
f = tmp_path / "warn.json"
|
||||
f.write_text(json.dumps({"results": [
|
||||
{"policy": "p", "rule": "r", "severity": "info", "result": "warn", "resource": "x"},
|
||||
]}))
|
||||
results = adapt(str(f), "c4")
|
||||
assert results[0]["result"] == "skipped"
|
||||
|
||||
def test_informational_severity_maps_to_info(self, tmp_path):
|
||||
f = tmp_path / "info.json"
|
||||
f.write_text(json.dumps({"results": [
|
||||
{"policy": "p", "rule": "r", "severity": "informational", "result": "pass", "resource": "x"},
|
||||
]}))
|
||||
results = adapt(str(f), "c5")
|
||||
assert results[0]["severity"] == "info"
|
||||
|
||||
def test_resource_ref_constructed_from_kind_name(self, tmp_path):
|
||||
f = tmp_path / "res.json"
|
||||
f.write_text(json.dumps({"results": [
|
||||
{"policy": "p", "rule": "r", "severity": "low", "result": "fail",
|
||||
"kind": "Pod", "namespace": "default", "name": "my-pod"},
|
||||
]}))
|
||||
results = adapt(str(f), "c6")
|
||||
assert "my-pod" in results[0]["resourceRef"]
|
||||
|
||||
def test_inactive_guard_directly(self):
|
||||
from adapters.kyverno.kyverno_adapter import adapt_inactive
|
||||
pcrs = adapt_inactive("c7")
|
||||
assert len(pcrs) == 1
|
||||
assert pcrs[0]["ruleId"] == "KYVERNO_INACTIVE_TF_STACK"
|
||||
assert pcrs[0]["result"] == "skipped"
|
||||
assert "Terraform" in pcrs[0]["message"]
|
||||
|
||||
def test_kube_version_parsed(self, tmp_path):
|
||||
"""--kube-version is parsed but not yet used (future GitOps)."""
|
||||
f = tmp_path / "k.json"
|
||||
f.write_text(json.dumps({"results": [
|
||||
{"policy": "p", "rule": "r", "severity": "low", "result": "pass", "resource": "x"},
|
||||
]}))
|
||||
results = adapt(str(f), "c8", kube_version="1.28")
|
||||
assert len(results) == 1
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""REQ-107: route_halt_artifact is a real implementation (SNS + outbox fallback)."""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from core.separation_of_duties import route_halt_artifact
|
||||
|
||||
|
||||
def test_route_halt_publishes_to_sns_when_arn_set(monkeypatch):
|
||||
"""With ACDL_SOD_HALT_TOPIC_ARN set, the SNS client receives the publish."""
|
||||
monkeypatch.setenv("ACDL_SOD_HALT_TOPIC_ARN", "arn:aws:sns:us-east-1:000000000000:acdl-sod-halt")
|
||||
sns_client = mock.MagicMock()
|
||||
route_halt_artifact("contract-123", "SEPARATION_OF_DUTIES_VIOLATION: x==y",
|
||||
oncall_client=sns_client)
|
||||
sns_client.publish.assert_called_once()
|
||||
call = sns_client.publish.call_args
|
||||
assert call.kwargs["TopicArn"] == "arn:aws:sns:us-east-1:000000000000:acdl-sod-halt"
|
||||
assert "contract-123" in call.kwargs["Message"]
|
||||
assert "SEPARATION_OF_DUTIES_VIOLATION" in call.kwargs["Message"]
|
||||
assert call.kwargs["Subject"] == "ACDL SoD halt"
|
||||
|
||||
|
||||
def test_route_halt_falls_back_to_stderr_when_arn_unset(monkeypatch, capsys):
|
||||
"""Without ACDL_SOD_HALT_TOPIC_ARN, a stderr emission occurs."""
|
||||
monkeypatch.delenv("ACDL_SOD_HALT_TOPIC_ARN", raising=False)
|
||||
# Mock outbox_writer.write_event to avoid AWS calls.
|
||||
with mock.patch("core.outbox_writer.write_event", return_value=None):
|
||||
route_halt_artifact("contract-456", "violation", oncall_client=None)
|
||||
captured = capsys.readouterr()
|
||||
assert "contract-456" in captured.err
|
||||
assert "violation" in captured.err
|
||||
|
||||
|
||||
def test_route_halt_outbox_fallback_writes_event(monkeypatch):
|
||||
"""Without the SNS ARN, the outbox fallback writes a SEPARATION_OF_DUTIES_VIOLATION event."""
|
||||
monkeypatch.delenv("ACDL_SOD_HALT_TOPIC_ARN", raising=False)
|
||||
with mock.patch("core.outbox_writer.write_event") as mock_write:
|
||||
route_halt_artifact("contract-789", "sod violation", oncall_client=None)
|
||||
mock_write.assert_called_once()
|
||||
event = mock_write.call_args[0][0]
|
||||
assert event["contractId"] == "contract-789"
|
||||
assert event["eventType"] == "SEPARATION_OF_DUTIES_VIOLATION"
|
||||
assert "sod violation" in event["reason"]
|
||||
|
||||
|
||||
def test_route_halt_sns_failure_falls_back_to_outbox(monkeypatch):
|
||||
"""If SNS publish raises, the outbox fallback is used."""
|
||||
monkeypatch.setenv("ACDL_SOD_HALT_TOPIC_ARN", "arn:aws:sns:us-east-1:000000000000:acdl-sod-halt")
|
||||
sns_client = mock.MagicMock()
|
||||
sns_client.publish.side_effect = Exception("SNS down")
|
||||
with mock.patch("core.outbox_writer.write_event") as mock_write:
|
||||
route_halt_artifact("contract-fail", "violation", oncall_client=sns_client)
|
||||
mock_write.assert_called_once()
|
||||
|
||||
|
||||
def test_sns_topic_defined_in_terraform():
|
||||
"""terraform/platform/main.tf defines the acdl-sod-halt SNS topic."""
|
||||
tf = (ROOT / "terraform" / "platform" / "main.tf").read_text()
|
||||
assert "aws_sns_topic" in tf
|
||||
assert "acdl-sod-halt" in tf
|
||||
assert "acdl_sod_halt_topic_arn" in tf
|
||||
@@ -92,18 +92,18 @@ class TestAdapt:
|
||||
results = adapt(str(f), "11111111-1111-1111-1111-111111111111")
|
||||
assert len(results) == 3
|
||||
|
||||
# issue 1: OPEN critical -> fail/critical
|
||||
assert results[0]["ruleId"] == "wiz-issue-001"
|
||||
# issue 1: OPEN critical -> fail/critical; ruleId = control.name (v1.9 real client)
|
||||
assert results[0]["ruleId"] == "Public S3 bucket exposure"
|
||||
assert results[0]["severity"] == "critical"
|
||||
assert results[0]["result"] == "fail"
|
||||
|
||||
# issue 2: RESOLVED high -> pass/high
|
||||
assert results[1]["ruleId"] == "wiz-issue-002"
|
||||
assert results[1]["ruleId"] == "Overly broad IAM role"
|
||||
assert results[1]["severity"] == "high"
|
||||
assert results[1]["result"] == "pass"
|
||||
|
||||
# issue 3: IN_PROGRESS medium -> skipped/medium
|
||||
assert results[2]["ruleId"] == "wiz-issue-003"
|
||||
assert results[2]["ruleId"] == "SSH open to the world"
|
||||
assert results[2]["severity"] == "medium"
|
||||
assert results[2]["result"] == "skipped"
|
||||
|
||||
@@ -138,4 +138,5 @@ class TestIsConfigured:
|
||||
|
||||
def test_configured_when_env_set(self, monkeypatch):
|
||||
monkeypatch.setenv("WIZ_API_TOKEN", "token-abc")
|
||||
monkeypatch.setenv("WIZ_API_URL", "https://api.wiz.io")
|
||||
assert is_configured() is True
|
||||
@@ -0,0 +1,137 @@
|
||||
"""REQ-110: Wiz adapter real API client + graceful degrade."""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from adapters.wiz.wiz_adapter import (
|
||||
WizClient, fetch_and_adapt, adapt, is_configured,
|
||||
_to_pcr, _emit_not_configured,
|
||||
)
|
||||
|
||||
|
||||
# A recorded Wiz GraphQL fixture (response shape).
|
||||
WIZ_FIXTURE = {
|
||||
"data": {
|
||||
"issues": {
|
||||
"nodes": [
|
||||
{
|
||||
"id": "issue-1",
|
||||
"severity": "CRITICAL",
|
||||
"title": "Public S3 bucket",
|
||||
"status": "OPEN",
|
||||
"entity": {"id": "arn:aws:s3:::x", "name": "x", "type": "S3_BUCKET", "cloudPlatform": "AWS"},
|
||||
"control": {"id": "c1", "name": "no-public-buckets"},
|
||||
"createdAt": "2026-07-20T00:00:00Z",
|
||||
},
|
||||
{
|
||||
"id": "issue-2",
|
||||
"severity": "HIGH",
|
||||
"title": "Missing encryption",
|
||||
"status": "OPEN",
|
||||
"entity": {"id": "arn:aws:s3:::y", "name": "y", "type": "S3_BUCKET", "cloudPlatform": "AWS"},
|
||||
"control": {"id": "c2", "name": "require-encryption"},
|
||||
"createdAt": "2026-07-21T00:00:00Z",
|
||||
},
|
||||
],
|
||||
"pageInfo": {"hasNextPage": False, "endCursor": None},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def test_wiz_client_requires_token_and_url(monkeypatch):
|
||||
monkeypatch.delenv("WIZ_API_TOKEN", raising=False)
|
||||
monkeypatch.delenv("WIZ_API_URL", raising=False)
|
||||
with pytest.raises(RuntimeError):
|
||||
WizClient()
|
||||
|
||||
|
||||
def test_fetch_and_adapt_with_mock_client():
|
||||
"""fetch_and_adapt translates Wiz issues to PolicyCheckResult via the real client."""
|
||||
client = mock.MagicMock(spec=WizClient)
|
||||
client.fetch_issues.return_value = WIZ_FIXTURE["data"]["issues"]["nodes"]
|
||||
pcrs = fetch_and_adapt("contract-1", client=client)
|
||||
assert len(pcrs) == 2
|
||||
assert pcrs[0]["engine"] == "wiz"
|
||||
assert pcrs[0]["ruleId"] == "no-public-buckets"
|
||||
assert pcrs[0]["severity"] == "critical"
|
||||
assert pcrs[0]["result"] == "fail"
|
||||
assert pcrs[1]["ruleId"] == "require-encryption"
|
||||
assert pcrs[1]["severity"] == "high"
|
||||
|
||||
|
||||
def test_fetch_and_adapt_graceful_degrade_when_unconfigured(monkeypatch):
|
||||
monkeypatch.delenv("WIZ_API_TOKEN", raising=False)
|
||||
monkeypatch.delenv("WIZ_API_URL", raising=False)
|
||||
pcrs = fetch_and_adapt("contract-2")
|
||||
assert len(pcrs) == 1
|
||||
assert pcrs[0]["ruleId"] == "WIZ_NOT_CONFIGURED"
|
||||
assert pcrs[0]["result"] == "skipped"
|
||||
|
||||
|
||||
def test_wiz_client_pagination(monkeypatch):
|
||||
"""Pagination follows pageInfo.hasNextPage + endCursor."""
|
||||
monkeypatch.setenv("WIZ_API_TOKEN", "tok")
|
||||
monkeypatch.setenv("WIZ_API_URL", "https://api.wiz.io")
|
||||
client = WizClient()
|
||||
page1 = {
|
||||
"data": {"issues": {"nodes": [{"id": "i1", "severity": "HIGH", "title": "t1",
|
||||
"status": "OPEN", "entity": {}, "control": {}}],
|
||||
"pageInfo": {"hasNextPage": True, "endCursor": "cursor1"}}}
|
||||
}
|
||||
page2 = {
|
||||
"data": {"issues": {"nodes": [{"id": "i2", "severity": "LOW", "title": "t2",
|
||||
"status": "OPEN", "entity": {}, "control": {}}],
|
||||
"pageInfo": {"hasNextPage": False, "endCursor": None}}}
|
||||
}
|
||||
with mock.patch.object(client, "_post", side_effect=[page1, page2]):
|
||||
issues = client.fetch_issues()
|
||||
assert len(issues) == 2
|
||||
|
||||
|
||||
def test_adapt_accepts_graphql_response_shape(tmp_path):
|
||||
"""adapt() accepts a full GraphQL response shape ({data:{issues:{nodes:[...]}}})."""
|
||||
fixture = tmp_path / "wiz.json"
|
||||
fixture.write_text(json.dumps(WIZ_FIXTURE))
|
||||
pcrs = adapt(str(fixture), "contract-3")
|
||||
assert len(pcrs) == 2
|
||||
assert pcrs[0]["engine"] == "wiz"
|
||||
|
||||
|
||||
def test_adapt_accepts_bare_list(tmp_path):
|
||||
fixture = tmp_path / "wiz.json"
|
||||
fixture.write_text(json.dumps(WIZ_FIXTURE["data"]["issues"]["nodes"]))
|
||||
pcrs = adapt(str(fixture), "contract-4")
|
||||
assert len(pcrs) == 2
|
||||
|
||||
|
||||
def test_adapt_empty_issues_emits_not_configured(tmp_path):
|
||||
fixture = tmp_path / "wiz.json"
|
||||
fixture.write_text(json.dumps({"data": {"issues": {"nodes": []}}}))
|
||||
pcrs = adapt(str(fixture), "contract-5")
|
||||
assert len(pcrs) == 1
|
||||
assert pcrs[0]["ruleId"] == "WIZ_NOT_CONFIGURED"
|
||||
|
||||
|
||||
def test_to_pcr_maps_severity_and_result():
|
||||
issue = {"id": "x", "severity": "INFORMATIONAL", "status": "RESOLVED",
|
||||
"title": "t", "entity": {"id": "r"}, "control": {"name": "rule"}}
|
||||
pcr = _to_pcr(issue, "c")
|
||||
assert pcr["severity"] == "info"
|
||||
assert pcr["result"] == "pass"
|
||||
assert pcr["ruleId"] == "rule"
|
||||
|
||||
|
||||
def test_is_configured(monkeypatch):
|
||||
monkeypatch.setenv("WIZ_API_TOKEN", "tok")
|
||||
monkeypatch.setenv("WIZ_API_URL", "https://api.wiz.io")
|
||||
assert is_configured() is True
|
||||
monkeypatch.delenv("WIZ_API_URL", raising=False)
|
||||
assert is_configured() is False
|
||||
Reference in New Issue
Block a user