Policy Engine
The Shield Policy Engine provides declarative authorization on top of the ContextToken permission system. While ContextToken.permissions handles basic capability checks, the Policy Engine adds context-aware conditions — time windows, resource scoping, rate limits, and tenant boundaries.
Architecture
ContextToken + Request Context │ ▼ PolicyEngine.evaluate() │ ├── Rule 1: admin-all → allow (PermissionCondition) ├── Rule 2: read-only-hours → deny (TimeCondition) ├── Rule 3: brain-tenant-lock → allow (TenantCondition) └── Rule N: ... │ ▼ PolicyResult { effect, matched_rule, audit_trail }Rules are evaluated in order — the first matching rule determines the outcome. If no rule matches, the default effect is deny (fail-closed).
Usage
from contextunity.shield.policy import PolicyEngine, Policyfrom contextunity.shield.policy import PermissionCondition, TimeCondition
engine = PolicyEngine([ Policy( name="admin-all", effect="allow", conditions=[PermissionCondition("admin:*")], ), Policy( name="read-only-after-hours", effect="deny", conditions=[ OperationCondition("write"), TimeCondition(after_hour=18, before_hour=9), ], ),])
result = engine.evaluate(token, context={"resource": "brain", "action": "write"})if result.effect == "deny": raise PermissionError(f"Denied by policy: {result.matched_rule}")Condition Types
| Condition | Parameters | Description |
|---|---|---|
PermissionCondition | permission | Matches if token has the specified permission (supports * wildcards) |
TenantCondition | tenant_id | Matches if token’s allowed_tenants includes the tenant |
TimeCondition | after_hour, before_hour | Matches during specified time window |
OperationCondition | operation | Matches the requested operation (read/write/execute) |
ResourceCondition | resource | Matches the target resource |
Remote Policy Management
Operators manage policies remotely via admin tokens — no SSH to the Shield host:
# Set permissions (remote)contextshield project-policy my-project \ --admin-token "shield-admin:my-project:Abc123..." \ --set "brain:read,brain:write,router:execute"
# View current policy (remote)contextshield project-policy my-project \ --admin-token "shield-admin:my-project:Abc123..."Compliance Integration
The Policy Engine feeds into the Compliance Checker which validates that policies meet regulatory requirements:
| Standard | Requirements Checked |
|---|---|
| SOC 2 | Encryption at rest, access logging, key rotation |
| GDPR | PII detection enabled, data retention policies |
| HIPAA | Audit trail completeness, PHI access controls |
| PCI DSS | Cardholder data isolation, encryption standards |
from contextunity.shield.compliance import ComplianceChecker
checker = ComplianceChecker(standards=["gdpr", "hipaa"])report = checker.check()for finding in report.findings: print(f"{finding.severity}: {finding.description}")