ContextUnity Security Modelπ
This document describes the design, architecture, and configuration of the ContextUnity security model, including per-project isolation, HMAC vs Shield signing, Shield secret access, and prompt integrity.
Runtime posture: Local/Production and Shield disabled/enabled form four explicit postures with the same RPC shapes and different admitted authorities. See ADR-0017.
- INV-SECURITY-FAIL-CLOSED-AUTH: Every protected service RPC verifies the caller β via
ServicePermissionInterceptoron standard gRPC surfaces, or handler-owned authentication on protected Shield PKI/policy RPCs (excluding unauthenticated public-key lookupGetProjectPublicKey) and RouterRegisterManifestβ and enforces the operation's required permission plus its operation-specific authority check: request tenant scope (can_access_tenant) on domain RPCs, signed project binding (resolve_verified_project_binding) on token-bound infrastructure boundaries under ADR-0017, or project-admin bearer verification against the stored credential hash and requested project match on Shield policy administration (SyncProjectPolicy).
Key symbols and inputs/outputsπ
| Symbol | Role | Inputs / Outputs |
|---|---|---|
ServicePermissionInterceptor | Unified gRPC authz interceptor | gRPC metadata + rpc_permission_map -> verified token context or UNAUTHENTICATED/PERMISSION_DENIED (protected bypassed Shield PKI/policy RPCs authenticate inside PKIHandler; GetProjectPublicKey returns public verifier material without caller auth) |
resolve_auth_runtime_posture | Deployment x Shield posture matrix | (local_mode, shield_enabled) -> AuthRuntimePosture |
resolve_verified_project_binding | Post-signature project binding check | (token, authority, verifier_project_id, allow_legacy_project) -> bound project identity |
build_verifier_backend | Token kid verifier factory | Raw token string + Shield config -> HMAC/Ed25519 verifier backend or None when rejected/unresolvable |
TokenBuilder | Root/attenuated token builder | Principal, tenant, permissions -> ContextToken object; signed wire serialization is owned by serialize_token |
can_access_tenant | Request tenant scope guard | (tenant_id) -> bool enforced by service handlers on domain RPCs (e.g., Brain QueryCells / SearchCells) |
Authentication Postures (Always On)π
Security is always enforced across the ecosystem. There is no toggle to disable authentication or verification.
| Posture | Authority | Isolation claim |
|---|---|---|
| Local, no Shield | CU_PLATFORM_SECRET HMAC | One shared local trust domain |
| Local with Shield | Platform HMAC on explicit local operator surfaces; Shield sessions for project runtime | Shield isolates project runtime |
| Production, no Shield | CU_PLATFORM_SECRET HMAC | One operator-owned trust domain; no isolation between root holders |
| Production with Shield | CU_PROJECT_SECRET bootstrap β Ed25519 Shield session | Project keys and policy isolate project runtime |
Autonomous Worker jobs use the same Shield bootstrap as Router registration: project identity from CU_MANIFEST_PATH and an HMAC bootstrap proof are exchanged through IssueSessionToken for a policy-bounded Ed25519 session. Per-call attenuation and refresh then use that parent Shield session. Missing manifest, bootstrap secret, Shield URL, tenant scope, policy, or Shield availability fails closed. Shield selection never comes from a parallel env mode flag.
For the Compose stack, Shield authority data is stored at /data/shield/shield.db beside the persisted master key. Run administrative commands through bash infrastructure/docker/shield-cli.sh ...; the wrapper loads the same master key inside the container, so CLI and server cannot open the authority database with different encryption contexts.
Provisioning the No-Shield HMAC Rootπ
contextunity config init generates and preserves CU_PLATFORM_SECRET for a local installation. Production no-Shield deployments provision an independent random value through their normal secret manager:
CU_PLATFORM_SECRET=<generated>
CU_ROUTER_GRPC_URL=localhost:50050Token Minting (Where It Lives)π
ContextUnity distinguishes three auth paths. Do not conflate them.
| Path | Mechanism | Allowed in |
|---|---|---|
| Bootstrap project auth | AuthBackend.get_auth_metadata and TokenBuilder.mint_root | SDK clients that bootstrap before making service calls |
| Verified caller token | extract_and_verify_token_from_http_request or extract_and_verify_token_from_grpc_metadata | Authenticated HTTP and gRPC handlers |
| Platform service identity | get_brain_service_token applies the service permission map | Router, Worker, and Commerce calls to Brain |
Token minting boundariesπ
Extensions and Commerce use SDK bootstrap or the verified token attached to an authenticated request. Forge forwards the operator bearer from its authenticated CLI flow. Router and Commerce Brain clients use their tenant-scoped service-token helpers; callers must not construct a less-scoped replacement token.
Architecture: Defense in Depthπ
ContextUnity implements security at multiple independent layers:
Layer 6: ROUTER ββββββ Manifest-Driven Capability Stripping (Token Attenuation per-node)
Layer 5: DATABASE βββββ PostgreSQL RLS (app.current_tenant per-query)
Layer 4: STORAGE ββββββ tenant_connection() context manager (fail-closed)
Layer 3: TOOL ββββββββ SecureTool.bound_tenant + required_permission
Layer 2: SERVICE ββββββ ServicePermissionInterceptor (gRPC boundary)
Layer 1: REGISTRATION β Three-Layer project ownership (token + granular perm + Redis)- Manifest-Driven Capability Stripping: Inside ContextRouter's LangGraph, every node execution is wrapped. Before invoking the LLM, the router automatically attenuates the in-memory token to grant only the scopes declared for that specific node in
contextunity.project.yaml(e.g.,shield:secrets:read:<tenant>/api_keys/SPECIFIC_KEY), dropping all other privileges. This limits the blast radius of any prompt injection attack. - Fail-Closed Principle: Each layer operates independently. Bypassing one does NOT bypass the others.
Token Basics & Canonical Permissionsπ
ContextToken carries caller identity, authorized tenants, and permissions. TokenBuilder and the SDK bootstrap path mint tokens; authenticated handlers use extract_and_verify_token_from_http_request or extract_and_verify_token_from_grpc_metadata to verify the caller. Service callers use their tenant-scoped service-token helpers. The current Router and Worker execution permissions are Permissions.ROUTER_EXECUTE and Permissions.WORKER_EXECUTE.
See Project and tenant registration for the registration and tenant-scope rules.
Revocation vs Key Resolutionπ
Redis-backed revocation and signing-key resolution intentionally have different failure semantics:
- Revocation checks fail closed. Once either check below is needed, Redis must be reachable; missing Redis, missing
redis[async], timeouts, and transport errors all treat the token as revoked. The only exception is explicitlocal_modewithout Redis, where revocation is skipped for local development. - Two independent revocation checks use the same Redis client session (
contextunity.core.security.backend_resolver.is_token_revoked):- Explicit per-token revocation β if a token has a
revocation_id, its denylist entry (contextunity:revoked:{revocation_id}) is checked. - Per-project epoch (revoke-all) β Shield session tokens carry precise
iatissue time and a session-shapedtoken_id(session:{project_id}:{unix_ts}) that identifies the project; a token is revoked iftoken.iatis before that project'scontextunity:epoch:{project_id}watermark. This gives an O(1) "revoke all outstanding session tokens for this project" without enumerating tokens or rotating keys. Bumped via therevoke_allaction onSyncProjectPolicy(see Shield policy sync). When both checks apply, the code awaits separateEXISTSandGETcommands. Tokens with neither arevocation_idnor a sessiontoken_id+iatpair are non-revocable by this mechanism and skip Redis entirely (no per-request cost).
- Explicit per-token revocation β if a token has a
- No-Shield RegisterManifest and prompt integrity use
CU_PLATFORM_SECRETHMAC. These tokens are typically not session tokens and are non-revocable unless they also carry arevocation_id. - Shield session tokens resolve Ed25519 public keys through Shield on verification/key-refresh paths.
- In production, configure Redis/Shield revocation and key lookup explicitly so token validation does not depend on local-only fallback behavior.
- Revoking a token or bumping a project's epoch does not stop a leaked HMAC bootstrap secret from minting new session tokens β always pair revocation with
reset_hmacon the project during incident response.
Canonical Permissions Tableπ
| Permission | Who uses it | Grants |
|---|---|---|
router:execute | Project β Router | Execute an authorized Router request |
tools:register:{project_id} | Project β Router startup | Register tools for THIS project |
tool:{name} or tool:{name}:{scope} | Project tool token | Grant access to one named tool, optionally with a scope |
tool:* | β οΈ Avoid in prod | All tools (logs warning) |
brain:read | Any service reading Brain | Read knowledge/traces |
trace:read / trace:write | Trace readers / writers | Read or write tenant-scoped Execution Trace records |
Prompt Source & Integrityπ
Prompt handling has two explicit modes. Both compute prompt_version from prompt text and record prompt:{llm_name}:{version} in execution traces.
No-Shield Modeπ
- SDK Bootstrap (
sign_prompt_integrityinsdk/bootstrap/manifest.py): afterprompt_refresolution, each prompt text is hashed (prompt_version) and HMAC-signed (prompt_signature) withCU_PLATFORM_SECRET. - RegisterManifest sends resolved prompt text plus signature to Router.
- SecureNode verifies
prompt_signatureagainst the runtime prompt text before LLM invocation. Mismatch raisesTamperDetectedErrorβgrpc.StatusCode.ABORTED.
Shield Modeπ
- A project enables Shield explicitly with
services.shield.enabled: trueandCU_SHIELD_GRPC_URL. - SDK bootstrap publishes canonical node prompts to Shield at
{project_id}/prompts/{node_name}for everyallowed_tenantsentry, using only coarseshield:secrets:write. - SDK strips resolved prompt text from the Router registration bundle and keeps
prompt_ref+prompt_version. - Router attenuates execution tokens per node to the effective tenant set, project-qualified
agent_id=node:{project_id}:{node_name}, and coarseshield:secrets:read. - Router fetches the prompt from Shield using the explicitly active request tenant. If no tenant is selected, the effective scope must contain exactly one tenant; empty, ambiguous, or out-of-scope resolution fails closed.
- Shield permits prompt reads only when tenant scope matches, verified token
project_idowns the prompt path, andagent_idmatches the owning node. No prompt-specific read permission is required. - Router verifies the fetched prompt hash against
prompt_versionbefore invoking the LLM.
API-key reads remain stricter than prompt reads: Shield requires shield:secrets:read:{tenant}/api_keys/{suffix} for API-key paths. Bootstrap writes remain coarse (shield:secrets:write) so Shield project policy does not need per-path write permissions.
Key Modulesπ
contextunity.core.signingowns signing backend protocols and implementations.contextunity.core.tokensdefinesContextToken,TokenBuilder, and service token helpers.contextunity.core.permissionsdefines permission constants, scope checks, and service permission maps.contextunity.core.token_utilsexposes HTTP and gRPC token extraction and verification helpers.contextunity.core.securityowns the shared service permission interceptor.contextunity.core.sdk.bootstrapowns project registration and session bootstrap.contextunity.core.sdk.prompt_integrityowns prompt version and signature helpers.contextunity.router.cortex.prompt_sourceresolves Shield-backed prompts and checksprompt_version.contextunity.router.cortex.secure_nodeattenuates node tokens and verifies prompt integrity.contextunity.shield.service.handlers.secretsenforces Shield secret path and tenant access.