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.

Important
  • INV-SECURITY-FAIL-CLOSED-AUTH: Every protected service RPC verifies the caller β€” via ServicePermissionInterceptor on standard gRPC surfaces, or handler-owned authentication on protected Shield PKI/policy RPCs (excluding unauthenticated public-key lookup GetProjectPublicKey) and Router RegisterManifest β€” 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πŸ”—

SymbolRoleInputs / Outputs
ServicePermissionInterceptorUnified gRPC authz interceptorgRPC 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_postureDeployment x Shield posture matrix(local_mode, shield_enabled) -> AuthRuntimePosture
resolve_verified_project_bindingPost-signature project binding check(token, authority, verifier_project_id, allow_legacy_project) -> bound project identity
build_verifier_backendToken kid verifier factoryRaw token string + Shield config -> HMAC/Ed25519 verifier backend or None when rejected/unresolvable
TokenBuilderRoot/attenuated token builderPrincipal, tenant, permissions -> ContextToken object; signed wire serialization is owned by serialize_token
can_access_tenantRequest 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.

PostureAuthorityIsolation claim
Local, no ShieldCU_PLATFORM_SECRET HMACOne shared local trust domain
Local with ShieldPlatform HMAC on explicit local operator surfaces; Shield sessions for project runtimeShield isolates project runtime
Production, no ShieldCU_PLATFORM_SECRET HMACOne operator-owned trust domain; no isolation between root holders
Production with ShieldCU_PROJECT_SECRET bootstrap β†’ Ed25519 Shield sessionProject 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:50050

Token Minting (Where It Lives)πŸ”—

ContextUnity distinguishes three auth paths. Do not conflate them.

PathMechanismAllowed in
Bootstrap project authAuthBackend.get_auth_metadata and TokenBuilder.mint_rootSDK clients that bootstrap before making service calls
Verified caller tokenextract_and_verify_token_from_http_request or extract_and_verify_token_from_grpc_metadataAuthenticated HTTP and gRPC handlers
Platform service identityget_brain_service_token applies the service permission mapRouter, 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 explicit local_mode without 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):
    1. Explicit per-token revocation β€” if a token has a revocation_id, its denylist entry (contextunity:revoked:{revocation_id}) is checked.
    2. Per-project epoch (revoke-all) β€” Shield session tokens carry precise iat issue time and a session-shaped token_id (session:{project_id}:{unix_ts}) that identifies the project; a token is revoked if token.iat is before that project's contextunity: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 the revoke_all action on SyncProjectPolicy (see Shield policy sync). When both checks apply, the code awaits separate EXISTS and GET commands. Tokens with neither a revocation_id nor a session token_id + iat pair are non-revocable by this mechanism and skip Redis entirely (no per-request cost).
  • No-Shield RegisterManifest and prompt integrity use CU_PLATFORM_SECRET HMAC. These tokens are typically not session tokens and are non-revocable unless they also carry a revocation_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_hmac on the project during incident response.

Canonical Permissions TableπŸ”—

PermissionWho uses itGrants
router:executeProject β†’ RouterExecute an authorized Router request
tools:register:{project_id}Project β†’ Router startupRegister tools for THIS project
tool:{name} or tool:{name}:{scope}Project tool tokenGrant access to one named tool, optionally with a scope
tool:*⚠️ Avoid in prodAll tools (logs warning)
brain:readAny service reading BrainRead knowledge/traces
trace:read / trace:writeTrace readers / writersRead 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πŸ”—

  1. SDK Bootstrap (sign_prompt_integrity in sdk/bootstrap/manifest.py): after prompt_ref resolution, each prompt text is hashed (prompt_version) and HMAC-signed (prompt_signature) with CU_PLATFORM_SECRET.
  2. RegisterManifest sends resolved prompt text plus signature to Router.
  3. SecureNode verifies prompt_signature against the runtime prompt text before LLM invocation. Mismatch raises TamperDetectedError β†’ grpc.StatusCode.ABORTED.

Shield ModeπŸ”—

  1. A project enables Shield explicitly with services.shield.enabled: true and CU_SHIELD_GRPC_URL.
  2. SDK bootstrap publishes canonical node prompts to Shield at {project_id}/prompts/{node_name} for every allowed_tenants entry, using only coarse shield:secrets:write.
  3. SDK strips resolved prompt text from the Router registration bundle and keeps prompt_ref + prompt_version.
  4. Router attenuates execution tokens per node to the effective tenant set, project-qualified agent_id=node:{project_id}:{node_name}, and coarse shield:secrets:read.
  5. 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.
  6. Shield permits prompt reads only when tenant scope matches, verified token project_id owns the prompt path, and agent_id matches the owning node. No prompt-specific read permission is required.
  7. Router verifies the fetched prompt hash against prompt_version before 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.signing owns signing backend protocols and implementations.
  • contextunity.core.tokens defines ContextToken, TokenBuilder, and service token helpers.
  • contextunity.core.permissions defines permission constants, scope checks, and service permission maps.
  • contextunity.core.token_utils exposes HTTP and gRPC token extraction and verification helpers.
  • contextunity.core.security owns the shared service permission interceptor.
  • contextunity.core.sdk.bootstrap owns project registration and session bootstrap.
  • contextunity.core.sdk.prompt_integrity owns prompt version and signature helpers.
  • contextunity.router.cortex.prompt_source resolves Shield-backed prompts and checks prompt_version.
  • contextunity.router.cortex.secure_node attenuates node tokens and verifies prompt integrity.
  • contextunity.shield.service.handlers.secrets enforces Shield secret path and tenant access.