Skip to content

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, Policy
from 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

ConditionParametersDescription
PermissionConditionpermissionMatches if token has the specified permission (supports * wildcards)
TenantConditiontenant_idMatches if token’s allowed_tenants includes the tenant
TimeConditionafter_hour, before_hourMatches during specified time window
OperationConditionoperationMatches the requested operation (read/write/execute)
ResourceConditionresourceMatches the target resource

Remote Policy Management

Operators manage policies remotely via admin tokens — no SSH to the Shield host:

Terminal window
# 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:

StandardRequirements Checked
SOC 2Encryption at rest, access logging, key rotation
GDPRPII detection enabled, data retention policies
HIPAAAudit trail completeness, PHI access controls
PCI DSSCardholder 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}")