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:
| Actor | Responsibility | Current / target modules |
|---|---|---|
ShieldVault | Encrypted secret custody (env, sqlite, and planned multi-instance postgres in S-001) with project/tenant/path isolation | secrets/, service/handlers/secrets.py |
ShieldCipher | Purpose-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/ |
ShieldSigner | Ed25519/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 |
ShieldSentry | Input/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:
ContextTokenattenuation: coarse per-node/per-call tenant, project, and permission envelope.Agentic Ethos(AgenticGuidanceEnvelope): Router-injected behavioral prompt guidance on classified agentic model calls only β never cited as action permission.Constitution(S-202): deterministic rule/AST classification of autonomous candidate plans, patches, and scripts before sandbox execution (allow_sandbox | require_human_review | deny).Effect Authorization(S-101): enforceable pre-provider Shield decision (EffectAuthorizationDecision+ transactionalSecurityAuditRecord) verified immediately before external side effects (S3 offload PUT, sandbox launch, tenant erasure).
- INV-SHIELD-SERVICE-ISOLATION:
ShieldServiceowns secret custody, firewall scanning, project PKI (PKIHandler), and artifact encryption (TraceArtifactProtector) without importing peer service implementations (enforced byARCH-SHIELD-ISOLATION); model confidence,AgenticGuidanceEnvelopepresence, Forge human review, or AOT compilation never substitute for a fresh intent-boundEffectAuthorizationDecisionat 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)"]| Symbol | Role | Inputs / Outputs |
|---|---|---|
ShieldService | Shield gRPC servicer | Scan, GetSecret/PutSecret/ListSecrets/RotateSecret, Encrypt/Decrypt, PKI RPCs -> ContextUnit responses |
PKIHandler | Per-project PKI & policy handler | Authenticated project/admin requests (IssueSessionToken, RotateProjectKey, SyncProjectPolicy) plus unauthenticated public verifier lookup (GetProjectPublicKey, validates project_id without caller token check) |
TraceArtifactProtector | Purpose-bound trace artifact cipher | protect(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:
| RPC | Current responsibility |
|---|---|
Scan | Scan input with the Shield firewall. |
GetStats | Return service status and project count. |
GetSecret | Read one secret value by path and tenant. |
PutSecret | Store a secret value by path and tenant. |
ListSecrets | List secret metadata for a tenant and optional path prefix. |
RotateSecret | Store a new secret version for a tenant. |
Encrypt | Protect one typed execution trace artifact. |
Decrypt | Unprotect one typed execution trace artifact. |
SyncProjectPolicy | Apply project policy through the PKI handler. |
IssueSessionToken | Authenticate a project and issue a session token. |
GetProjectPublicKey | Return a project's public signing key. |
RotateProjectKey | Rotate 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.
Invariant: Trace artifact protection requires a verified tenant and the exact project-bound token; a platform-bound token cannot authorize it.
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_KEYoutside dev mode prevents service initialization. In dev mode without a master key, trace artifact protection is unavailable and the related RPCs fail withFAILED_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:
| Variable | Default | Current use |
|---|---|---|
SHIELD_SECRET_BACKEND | env | Selects the secret backend; env and sqlite are implemented. |
SHIELD_SECRET_DSN | empty | Declared for the PostgreSQL backend, which is not implemented or selected by the current factory. |
SHIELD_DB_PATH | data/shield.db | SQLite database path for Shield data and the SQLite secret backend. |
SHIELD_MASTER_KEY | empty | Fernet key for private keys at rest and trace artifact protection; required outside dev mode. |
SHIELD_ENCRYPTION_BACKEND | fernet | Accepted by configuration and reported in startup logs; it does not select the trace artifact protector, which uses Fernet directly. |
SHIELD_ENCRYPTION_KEY | empty | Checked by compliance reporting; it does not select the trace artifact key. |
SHIELD_SECRET_ACL_PATH | empty | Accepted by configuration; the current secret access path does not load an ACL file. |
SHIELD_AUDIT_LOG_PATH | empty | Checked 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.