Home/Docs/Core Services/ContextShield

ContextShield Service ArchitectureπŸ”—

services/shield owns the Shield gRPC service, project key operations, secret access, firewall checks, and execution trace artifact protection.

Canonical Shield actors and four control boundariesπŸ”—

ContextShield organizes its cryptographic and policy responsibilities across four canonical actors:

ActorResponsibilityCurrent / target modules
ShieldVaultEncrypted secret custody (env, sqlite, and planned multi-instance postgres in S-001) with project/tenant/path isolationsecrets/, service/handlers/secrets.py
ShieldCipherPurpose-bound payload protection (TraceArtifactProtector today; ADR-0015 envelope encryption with KEK-wrapped ephemeral per-object DEKs, O(1) wrapped_dek KEK epoch re-wrap, and emergency AtomicShadowSwap in S-101/S-201)trace_artifact_protector.py, crypto/
ShieldSignerEd25519/KMS session and artifact signing, key epochs, revocation generations, non-self-widening delegation, and platform-admin cross-tenant grants (S-002)signing/, delegation.py, revocation.py, service/handlers/pki*.py
ShieldSentryInput/output firewall scanning (Scan), deterministic Constitution candidate classification (S-202), and pre-provider Effect Authorization (S-101)firewall/, policy.py

Platform security separates four orthogonal mechanisms that never substitute for one another:

  1. ContextToken attenuation: coarse per-node/per-call tenant, project, and permission envelope.
  2. Agentic Ethos (AgenticGuidanceEnvelope): Router-injected behavioral prompt guidance on classified agentic model calls only β€” never cited as action permission.
  3. Constitution (S-202): deterministic rule/AST classification of autonomous candidate plans, patches, and scripts before sandbox execution (allow_sandbox | require_human_review | deny).
  4. Effect Authorization (S-101): enforceable pre-provider Shield decision (EffectAuthorizationDecision + transactional SecurityAuditRecord) verified immediately before external side effects (S3 offload PUT, sandbox launch, tenant erasure).
Important
  • INV-SHIELD-SERVICE-ISOLATION: ShieldService owns secret custody, firewall scanning, project PKI (PKIHandler), and artifact encryption (TraceArtifactProtector) without importing peer service implementations (enforced by ARCH-SHIELD-ISOLATION); model confidence, AgenticGuidanceEnvelope presence, Forge human review, or AOT compilation never substitute for a fresh intent-bound EffectAuthorizationDecision at an external effect boundary.

Key symbols and inputs/outputsπŸ”—

flowchart LR
  Callers["Router / Worker / CLI / SDK"] --> Interceptor["ShieldPermissionInterceptor"]
  Interceptor --> Service["ShieldService"]
  Service --> Firewall["firewall/ (Scan)"]
  Service --> Secrets["SecretsHandler (Vault)"]
  Service --> PKI["PKIHandler (Auth + Public Key Lookup)"]
  Service --> Protector["TraceArtifactProtector (Encrypt/Decrypt)"]
  PKI --> DB["ShieldDB (SQLite; Postgres planned S-001)"]
SymbolRoleInputs / Outputs
ShieldServiceShield gRPC servicerScan, GetSecret/PutSecret/ListSecrets/RotateSecret, Encrypt/Decrypt, PKI RPCs -> ContextUnit responses
PKIHandlerPer-project PKI & policy handlerAuthenticated project/admin requests (IssueSessionToken, RotateProjectKey, SyncProjectPolicy) plus unauthenticated public verifier lookup (GetProjectPublicKey, validates project_id without caller token check)
TraceArtifactProtectorPurpose-bound trace artifact cipherprotect(ProtectExecutionTraceArtifactRequest) -> ProtectedExecutionTraceArtifactEnvelope; unprotect(UnprotectExecutionTraceArtifactRequest) -> UnprotectedExecutionTraceArtifact

Entrypoint and request flowπŸ”—

contextunity.shield.__main__ starts the Typer application in contextunity.shield.cli. The serve command starts contextunity.shield.service.server.serve, which loads ShieldConfig, installs ShieldPermissionInterceptor, constructs ShieldService, and registers it with gRPC.

For RPCs covered by the permission map, the interceptor verifies the ContextToken and required permission before dispatch. The project PKI methods IssueSessionToken, RotateProjectKey, and SyncProjectPolicy bypass that interceptor and perform their own project or admin-token checks in PKIHandler; GetProjectPublicKey also bypasses the interceptor and validates project_id to return public verifier key metadata without a caller token check.

ShieldService composes the firewall, SecretsHandler, PKIHandler, ShieldDB, and an optional TraceArtifactProtector. The firewall is configured to fail closed. Outside dev mode, service initialization requires SHIELD_MASTER_KEY so project private keys are encrypted at rest.

Current gRPC surfaceπŸ”—

ShieldService in packages/core/protos/shield.proto declares these RPCs:

RPCCurrent responsibility
ScanScan input with the Shield firewall.
GetStatsReturn service status and project count.
GetSecretRead one secret value by path and tenant.
PutSecretStore a secret value by path and tenant.
ListSecretsList secret metadata for a tenant and optional path prefix.
RotateSecretStore a new secret version for a tenant.
EncryptProtect one typed execution trace artifact.
DecryptUnprotect one typed execution trace artifact.
SyncProjectPolicyApply project policy through the PKI handler.
IssueSessionTokenAuthenticate a project and issue a session token.
GetProjectPublicKeyReturn a project's public signing key.
RotateProjectKeyRotate a project's signing key.

The Encrypt and Decrypt service methods do not accept arbitrary plaintext requests. They validate ProtectExecutionTraceArtifactRequest and UnprotectExecutionTraceArtifactRequest from contextunity.core.sdk.execution_trace_artifacts.

Secret access boundaryπŸ”—

ShieldPermissionInterceptor maps secret RPCs to shield:secrets:read or shield:secrets:write. Each service handler resolves the canonical tenant from the verified token, validates the secret path, and calls require_secret_access before accessing its backend. Prompt reads also require the token's project and node identity to match the prompt path. ListSecrets returns metadata and does not return secret values.

The configured secret backend defaults to env. create_secret_backend also implements sqlite; selecting postgres or vault raises NotImplementedError. SQLite uses the configured Shield database path and master key.

Execution trace artifact protectionπŸ”—

ShieldService.Encrypt and ShieldService.Decrypt call authorize_trace_artifact_binding to resolve the tenant and require a ProjectBound token for the artifact's project. TraceArtifactProtector encrypts the typed request with Fernet and adds a keyed hmac-sha256 content digest. The envelope binds purpose, identity, artifact ID, and key epoch; decryption validates these values before returning plaintext.

Important

Invariant: Trace artifact protection requires a verified tenant and the exact project-bound token; a platform-bound token cannot authorize it.

Important

Invariant: If the trace artifact protector is unavailable, Encrypt and Decrypt fail with FAILED_PRECONDITION; Shield does not return an unprotected artifact.

Failure behaviorπŸ”—

  • Missing or invalid ContextToken fails authentication. Tenant, project, or permission mismatches fail authorization.
  • Invalid secret paths are rejected before backend access. Secret backend errors do not bypass path and tenant checks.
  • Missing SHIELD_MASTER_KEY outside dev mode prevents service initialization. In dev mode without a master key, trace artifact protection is unavailable and the related RPCs fail with FAILED_PRECONDITION.
  • Malformed or mismatched artifact envelopes fail validation and are not returned as plaintext.

Audit eventsπŸ”—

AuditTrail is an opt-in utility that records structured AuditEvent values through a logger and appends JSON Lines when constructed with a log path. Compliance reporting checks SHIELD_AUDIT_LOG_PATH.

ConfigurationπŸ”—

ShieldConfig maps the following environment variables:

VariableDefaultCurrent use
SHIELD_SECRET_BACKENDenvSelects the secret backend; env and sqlite are implemented.
SHIELD_SECRET_DSNemptyDeclared for the PostgreSQL backend, which is not implemented or selected by the current factory.
SHIELD_DB_PATHdata/shield.dbSQLite database path for Shield data and the SQLite secret backend.
SHIELD_MASTER_KEYemptyFernet key for private keys at rest and trace artifact protection; required outside dev mode.
SHIELD_ENCRYPTION_BACKENDfernetAccepted by configuration and reported in startup logs; it does not select the trace artifact protector, which uses Fernet directly.
SHIELD_ENCRYPTION_KEYemptyChecked by compliance reporting; it does not select the trace artifact key.
SHIELD_SECRET_ACL_PATHemptyAccepted by configuration; the current secret access path does not load an ACL file.
SHIELD_AUDIT_LOG_PATHemptyChecked by compliance reporting; it is not passed to AuditTrail by Shield RPC handlers.

The service defaults to gRPC port 50054. python -m contextunity.shield --help lists the CLI commands available in the active environment.