Skip to content

ContextShield

ContextShield is the security perimeter of ContextUnity. It provides declarative security through prompt injection detection, policy-based authorization, compliance auditing, cryptographic token management, and per-project admin PKI.

AI Firewall

Prompt injection, jailbreak, and PII leak detection with configurable YAML rule sets.

Policy Engine

Declarative ABAC policies with ContextToken integration for fine-grained access control.

Admin Tokens

Per-project admin tokens for remote policy management — no master key needed.

Delegation Chains

Cryptographic permission attenuation for multi-hop agent architectures.

Architecture

shield

Key Components

AI Firewall (firewall/)

The Shield orchestrates multiple validators:

  • InjectionValidator — detects prompt injection attempts
  • JailbreakValidator — detects jailbreak patterns
  • PIIValidator — detects PII (names, phones, IDs) via regex + Presidio ML
  • RAGContextValidator — validates retrieval context integrity

PII detection rules are loaded from firewall/rules/pii.yaml — no redeployment needed to add new rules.

Policy Engine (policy.py)

Declarative attribute-based access control:

from contextunity.shield import PolicyEngine, Policy
engine = PolicyEngine()
engine.add_policy(Policy(
name="brain_read",
conditions={"permission": "brain:read", "tenant": "my_project"},
effect="allow",
))
result = engine.evaluate(token, resource="brain", action="read")

Delegation Chains (delegation.py)

Cryptographic permission attenuation for multi-hop calls:

from contextunity.shield.delegation import DelegationChain
# Parent delegates subset of permissions to child
chain = DelegationChain(parent_token)
child_token = chain.attenuate(
permissions=("brain:read",), # Subset of parent's permissions
ttl_seconds=3600,
)

PKI & Admin Token Management

Shield manages per-project Ed25519 keypairs and HMAC secrets. Admin tokens provide a third trust tier that decouples project deployment from the Shield master key.

Trust Tiers

TierCredentialScopeHolder
MasterSHIELD_MASTER_KEYCreate/delete projects, rotate master keyShield daemon (systemd-cred)
Adminadmin_token (per-project)Set permissions, rotate HMAC, view policyProject deploy pipeline (Ansible vault)
RuntimeCU_PROJECT_SECRETRuntime authentication, session tokensProject service (.env)

Creating a Project

Terminal window
# Generates Ed25519 keypair + admin token
contextshield project-create my-project \
--services "brain,router"
# Output:
# project_id: my-project
# admin_token: shield-admin:my-project:Abc123... ← SAVE THIS
# public_key: ...
# hmac_secret: ...

Project IDs must match [a-z0-9][a-z0-9_-]{0,62} — lowercase, digits, hyphens, underscores only.

Remote Policy Management

With an admin token, operators manage their project remotely via gRPC — no SSH to the Shield host, no SHIELD_MASTER_KEY:

Terminal window
# Update permissions
contextshield project-policy my-project \
--admin-token "shield-admin:my-project:Abc123..." \
--set "brain:read,brain:write,router:execute"
# View policy
contextshield project-policy my-project \
--admin-token "shield-admin:my-project:Abc123..." \
--action view_policy
# Rotate HMAC secret
contextshield project-policy my-project \
--admin-token "shield-admin:my-project:Abc123..." \
--action reset_hmac

Rotating Admin Tokens

Terminal window
# Generate new admin token (invalidates the old one)
contextshield admin-create my-project
# Revoke token entirely
contextshield admin-delete my-project

gRPC Service (15 RPCs)

RPCDescription
ScanAI firewall scan (injection/PII detection)
EvaluatePolicyPolicy engine evaluation
CheckComplianceCompliance posture check
RecordAuditRecord audit event
MintTokenCreate signed ContextToken
VerifyTokenVerify token signature and validity
RevokeTokenAdd to revocation list
GetStatsSecurity metrics and statistics
SyncProjectPolicyAdmin-authenticated policy management
GetSecretRetrieve a secret
PutSecretStore a secret
ListSecretsList stored secrets
RotateSecretRotate a secret
EncryptEncrypt data
DecryptDecrypt data

Configuration

Environment Variables

VariableDefaultDescription
SHIELD_MASTER_KEYFernet key — encrypts private keys at rest
SHIELD_DB_PATHdata/shield.dbSQLite PKI database path
SHIELD_ENCRYPTION_KEYFernet key for PII mapping store
CU_SHIELD_GRPC_URLlocalhost:50054Shield gRPC endpoint

Systemd Credentials (Production)

Critical secrets can be provisioned via systemd-creds for production hardening. The config loader checks CREDENTIALS_DIRECTORY first, then falls back to .env. See Systemd Deployment for details.

Router Integration

Shield integrates with contextunity.router in two ways:

As LangChain Tools (Dispatcher Agent)

Tools are auto-registered when contextunity.shield is installed:

  • shield_scan — Scan for injection / jailbreak / PII
  • check_policy — Authorization against policy engine
  • check_compliance — Posture audit
  • audit_event — Log security events

Dual-mode: local package OR gRPC (set CU_SHIELD_GRPC_URL).

As Inline Firewall (gRPC)

Router invokes Shield natively via Scan RPC before any LangGraph agent executes. The end-user’s ContextToken is propagated directly to Shield (SPOT pattern). router:execute inherits shield:check via permission inheritance in contextunity.core.

CLI Reference

Terminal window
# Project management
contextshield project-create <id> [--services <svc,svc,...>]
contextshield project-list
contextshield project-rotate <id>
# Admin tokens
contextshield admin-create <id>
contextshield admin-delete <id>
# Policy management
contextshield project-policy <id> --set <perms> # local
contextshield project-policy <id> --admin-token <token> ... # remote
# Diagnostics
contextshield status