8000 feat: policy engine and result verification by dominicusin · Pull Request #5 · dominicusin/uaw · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8000
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ jobs:
- name: Run state durability tests
run: |
cd "${GITHUB_WORKSPACE%/*}"
python -m pytest uaw/tests/test_state_durability.py uaw/tests/test_idempotency.py -q
python -m pytest uaw/tests/test_state_durability.py uaw/tests/test_idempotency.py uaw/tests/test_policy_verification.py -q
70 changes: 70 additions & 0 deletions core/policy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""L0-L4 policy engine with approvals and side-effect-free dry runs."""
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Callable, Dict, List, Optional


class RiskLevel(Enum):
L0_READ_ONLY = 0
L1_PREPARE = 1
L2_SUPERVISED = 2
L3_AUTOMATION = 3
L4_CRITICAL = 4


DANGEROUS_KINDS = {"delete", "send", "publish", "financial"}


@dataclass
class Operation:
id: str
kind: str
level: RiskLevel = RiskLevel.L1_PREPARE
payload: Dict[str, Any] = field(default_factory=dict)

@property
def dangerous(self) -> bool:
return self.kind in DANGEROUS_KINDS or self.level == RiskLevel.L4_CRITICAL


@dataclass
class Decision:
allowed: bool
reason: str
approvals: List[str] = field(default_factory=list)


class ApprovalMissing(RuntimeError):
pass


class PolicyEngine:
"""Deny dangerous operations without an explicit approval token."""

def __init__(self, max_autonomous_level: RiskLevel = RiskLevel.L2_SUPERVISED):
self.max_autonomous_level = max_autonomous_level

def authorize(self, op: Operation, approvals: Optional[List[str]] = None) -> Decision:
approvals = list(approvals or [])
if op.level == RiskLevel.L0_READ_ONLY:
return Decision(True, "read-only", approvals)
if op.dangerous:
if op.id not in approvals:
raise ApprovalMissing(f"approval required for {op.id} ({op.kind})")
return Decision(True, "approved", approvals)
if op.level.value > self.max_autonomous_level.value:
return Decision(False, f"level {op.level.name} exceeds autonomy ceiling", approvals)
return Decision(True, "within autonomy ceiling", approvals)

def dry_run(self, steps: List[Operation], approvals: Optional[List[str]] = None) -> List[Decision]:
"""Evaluate every step without invoking any of them."""
return [self.authorize(step, approvals) for step in steps]


def execute(engine: PolicyEngine, op: Operation, action: Callable[[], Any],
approvals: Optional[List[str]] = None) -> Any:
"""Run an action only after policy authorization."""
decision = engine.authorize(op, approvals)
if not decision.allowed:
raise PermissionError(decision.reason)
return action()
38 changes: 38 additions & 0 deletions core/verification.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""Verify operation results instead of trusting successful calls."""
from dataclasses import dataclass
from typing import Any, Callable, Dict, Optional


@dataclass
class VerificationResult:
ok: bool
expected: Any
actual: Any
reason: str = ""


class VerificationFailed(RuntimeError):
def __init__(self, result: VerificationResult):
super().__init__(result.reason)
self.result = result


def verify(expected: Dict[str, Any], actual: Optional[Dict[str, Any]]) -> VerificationResult:
"""A call can succeed while its result is wrong; compare explicitly."""
if actual is None:
return VerificationResult(False, expected, actual, "no result returned")
mismatches = [k for k, v in expected.items() if actual.get(k) != v]
if mismatches:
return VerificationResult(False, expected, actual,
"mismatched fields: " + ", ".join(mismatches))
return VerificationResult(True, expected, actual, "verified")


def execute_and_verify(action: Callable[[], Optional[Dict[str, Any]]],
expected: Dict[str, Any]) -> VerificationResult:
"""Mark the operation failed when verification fails, even if action returned."""
actual = action()
result = verify(expected, actual)
if not result.ok:
raise VerificationFailed(result)
return result
79 changes: 79 additions & 0 deletions tests/test_policy_verification.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""Policy (UAW-005) and result-verification (UAW-006) tests."""
import tempfile
import unittest

from uaw.core.policy import (
ApprovalMissing, Decision, Operation, PolicyEngine, RiskLevel, execute,
)
from uaw.core.verification import VerificationFailed, execute_and_verify, verify


class TestPolicyEngine(unittest.TestCase):
def setUp(self):
self.engine = PolicyEngine()

def test_read_only_is_allowed(self):
decision = self.engine.authorize(Operation("r1", "read", RiskLevel.L0_READ_ONLY))
self.assertTrue(decision.allowed)

def test_destructive_operation_requires_approval(self):
op = Operation("del1", "delete", RiskLevel.L3_AUTOMATION)
with self.assertRaises(ApprovalMissing):
self.engine.authorize(op)
self.assertTrue(self.engine.authorize(op, ["del1"]).allowed)

def test_publish_and_financial_require_approval(self):
for kind in ("publish", "financial", "send"):
with self.assertRaises(ApprovalMissing):
self.engine.authorize(Operation(kind + ":1", kind))
self.assertTrue(self.engine.authorize(Operation(kind + ":1", kind), [kind + ":1"]).allowed)

def test_autonomy_ceiling_is_enforced(self):
strict = PolicyEngine(max_autonomous_level=RiskLevel.L0_READ_ONLY)
decision = strict.authorize(Operation("prepare", "prepare", RiskLevel.L1_PREPARE))
self.assertFalse(decision.allowed)
self.assertIn("ceiling", decision.reason)

def test_critical_requires_approval(self):
op = Operation("crit", "deploy", RiskLevel.L4_CRITICAL)
with self.assertRaises(ApprovalMissing):
self.engine.authorize(op)

def test_dry_run_has_no_side_effects(self):
calls = []
steps = [Operation("a", "read", RiskLevel.L0_READ_ONLY),
Operation("b", "delete", RiskLevel.L2_SUPERVISED)]
decisions = self.engine.dry_run(steps, approvals=["b"])
self.assertEqual(len(decisions), 2)
self.assertEqual(calls, [])

def test_execute_refuses_unapproved_action(self):
calls = []
op = Operation("pub", "publish")
with self.assertRaises(ApprovalMissing):
execute(self.engine, op, lambda: calls.append(1))
self.assertEqual(calls, [])
execute(self.engine, op, lambda: calls.append(1), approvals=["pub"])
self.assertEqual(calls, [1])


class TestResultVerification(unittest.TestCase):
def test_successful_call_with_wrong_result_is_failed(self):
def action():
return {"status": "ok", "count": 0}
with self.assertRaises(VerificationFailed) as ctx:
execute_and_verify(action, {"status": "ok", "count": 2})
self.assertFalse(ctx.exception.result.ok)
self.assertIn("count", ctx.exception.result.reason)

def test_no_result_is_failure(self):
self.assertFalse(verify({"id": 1}, None).ok)

def test_matching_result_is_verified(self):
result = execute_and_verify(lambda: {"id": 1, "state": "done"},
{"id": 1, "state": "done"})
self.assertTrue(result.ok)


if __name__ == "__main__":
unittest.main()
Loading
0