Grok Build Leak Postmortem: The Systems Architecture Behind Agentic Data Exfiltration
A coding agent returning confidential documents across tenant lines is not an AI safety story — it is a distributed-systems story about five unenforced boundaries. Here is the architecture, the failure classes, and production-grade controls that stop agentic exfiltration cold.
AI Generated with Qwen 3.0 via CometAPIThe Incident in 90 Seconds
Public reporting describes a coding agent — Grok Build — surfacing confidential material that did not belong to the requesting user, with a portion of the exposed content attributed to SpaceX (referenced in early coverage under the shorthand SpaceXSI). Vendor postmortems were still in flight at the time of writing, and the precise trigger sequence remains unconfirmed.
That uncertainty matters less than it appears. Agentic coding tools fail in a small, well-enumerated set of ways, and every one of them is an architecture problem with a known control. This article reconstructs the plausible failure surface and then walks through the five boundaries a production coding agent must enforce — with implementations you can lift into your own stack today.
Why Coding Agents Are Structurally Riskier Than Chat Assistants
The mental model most teams carry over from chat assistants is dangerously wrong for agents. The blast radius is not a single conversation.
| Property | Chat assistant | Coding agent |
|---|---|---|
| Context scope | One user turn | Entire repo, shell history, dependency tree |
| Credentials in scope | None | Cloud roles, DB URLs, CI tokens, kubeconfig |
| Side effects | Text output | File writes, commits, deploys, package installs |
| Persistence | Session transcript | Embedding indexes, traces, eval datasets |
| Blast radius | One user | Every tenant sharing the retrieval index |
A chat assistant with a leaky prompt is embarrassing. A coding agent with a leaky retrieval layer is a cross-tenant data breach with a natural-language interface.
Six Leak Classes to Enumerate Before You Ship
- Cross-tenant retrieval collision. A shared vector index with no tenant namespace or row-level filter. Nearest-neighbour search returns the closest chunk, and the closest chunk may belong to someone else.
- Context over-collection. The agent walks
.env,~/.aws/credentials,~/.kube/config, and~/.npmrcbecause the sandbox mounted$HOME. - Telemetry retention. Full prompts and completions shipped to an observability vendor with 30-day retention and broad internal read access (CWE-532).
- Evaluation and training pipelines. Sampled production traces reused for offline evals without re-scrubbing.
- Tool-output echo. The agent redacts nothing on the way out, so a secret it read silently lands in the final answer.
- Shared prompt caching. A cache keyed on prompt prefix without tenant identity serves tenant A's cached context to tenant B.
Each class maps to exactly one boundary. Enforce the boundary and the class disappears.
Boundary 1 — Ingestion: Redact Before the Context Window, Not After
Redaction applied to model output is theatre; by then the secret is already in a vendor's logs. Redaction must run at two points: when repository content enters the context assembler, and again immediately before any bytes leave your trust boundary.
The implementation below is deterministic, detector-composable, and — critically — fail-closed. A detector that crashes must abort the request, not silently pass content through.
# redaction.py — deterministic, fail-closed secret redaction for agent context assembly
from __future__ import annotations
import hashlib
import math
import re
from collections import Counter
from dataclasses import dataclass
from enum import Enum
from typing import Iterable, Protocol
class SecretKind(str, Enum):
PRIVATE_KEY = 'private_key'
API_TOKEN = 'api_token'
CONNECTION_STRING = 'connection_string'
INTERNAL_HOST = 'internal_host'
HIGH_ENTROPY = 'high_entropy'
@dataclass(frozen=True, slots=True)
class Finding:
kind: SecretKind
start: int
end: int
digest: str
detector: str
class RedactionError(RuntimeError):
'''Raised when redaction cannot complete. Callers MUST fail closed.'''
class Detector(Protocol):
name: str
def scan(self, text: str) -> Iterable[Finding]: ...
PATTERNS: dict[SecretKind, re.Pattern[str]] = {
SecretKind.PRIVATE_KEY: re.compile(
r'-----BEGIN [A-Z ]*PRIVATE KEY-----[-\s\S]+?-----END [A-Z ]*PRIVATE KEY-----'
),
SecretKind.API_TOKEN: re.compile(
r'(?:sk|xai|ghp|gho|glpat|xox[baprs])[-_][A-Za-z0-9_]{16,}'
),
SecretKind.CONNECTION_STRING: re.compile(
r'(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis)://[^\s]+'
),
SecretKind.INTERNAL_HOST: re.compile(
r'[a-z0-9][a-z0-9-]*\.(?:internal|corp|svc\.cluster\.local)'
),
}
def _digest(value: str) -> str:
return hashlib.sha256(value.encode('utf-8', 'surrogatepass')).hexdigest()
class RegexDetector:
name = 'regex'
def scan(self, text: str) -> Iterable[Finding]:
for kind, pattern in PATTERNS.items():
for match in pattern.finditer(text):
yield Finding(kind, match.start(), match.end(), _digest(match.group(0)), self.name)
class EntropyDetector:
'''Catches opaque blobs (custom tokens, seeds) that regexes miss.'''
name = 'entropy'
THRESHOLD = 4.2
TOKEN_RE = re.compile(r'[A-Za-z0-9+/=_-]{24,}')
@staticmethod
def _shannon(s: str) -> float:
counts = Counter(s)
n = len(s)
return -sum((c / n) * math.log2(c / n) for c in counts.values())
def scan(self, text: str) -> Iterable[Finding]:
for match in self.TOKEN_RE.finditer(text):
token = match.group(0)
if self._shannon(token) >= self.THRESHOLD:
yield Finding(
SecretKind.HIGH_ENTROPY, match.start(), match.end(), _digest(token), self.name
)
class Redactor:
def __init__(self, detectors: list[Detector] | None = None) -> None:
self._detectors: list[Detector] = detectors or [RegexDetector(), EntropyDetector()]
def redact(self, text: str) -> tuple[str, list[Finding]]:
try:
findings = [f for d in self._detectors for f in d.scan(text)]
except Exception as exc:
# A crashed detector means unknown risk. Never degrade to pass-through.
raise RedactionError('detector failure') from exc
# Deterministic overlap resolution: earliest start wins, longest span breaks ties.
findings.sort(key=lambda f: (f.start, -(f.end - f.start)))
merged: list[Finding] = []
for f in findings:
if merged and f.start < merged[-1].end:
prev = merged[-1]
if f.end > prev.end:
merged[-1] = Finding(prev.kind, prev.start, f.end, prev.digest, prev.detector)
continue
merged.append(f)
out: list[str] = []
cursor = 0
for f in merged:
out.append(text[cursor:f.start])
out.append(f'[{f.kind.value}:sha256:{f.digest[:8]}]')
cursor = f.end
out.append(text[cursor:])
result = ''.join(out)
if len(result) > 4 * len(text) + 4096:
raise RedactionError('redaction output failed sanity bound')
return result, mergedDesign notes worth defending in review: the replacement carries a SHA-256 prefix, not the value, so you can correlate the same secret across transcripts without ever storing it. That single decision is what turns an incident response from archaeology into a lookup.
Boundary 2 — Retrieval: Namespace or Die
If your embedding index is shared and your filter is application-layer if statements, you have already lost. Push isolation into the datastore so that a bug in the agent — or in any future agent that shares the index — cannot bypass it.
-- Postgres: force RLS even for table owners, so no service account can opt out.
ALTER TABLE chunks ENABLE ROW LEVEL SECURITY;
ALTER TABLE chunks FORCE ROW LEVEL SECURITY;
CREATE POLICY chunks_tenant_isolation ON chunks
USING (tenant_id = current_setting('app.tenant_id', true)::uuid)
WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid);// retrieval.ts — tenant-isolated vector retrieval with defence in depth
import { Pool, PoolClient } from 'pg';
type TenantId = string & { readonly __brand: 'TenantId' };
type RepoId = string & { readonly __brand: 'RepoId' };
export interface RetrievalRequest {
readonly tenantId: TenantId;
readonly repoId: RepoId;
readonly queryEmbedding: number[];
readonly topK: number;
readonly traceId: string;
}
export interface Chunk {
readonly chunkId: string;
readonly tenantId: TenantId;
readonly repoId: RepoId;
readonly content: string;
readonly score: number;
}
export class IsolationViolation extends Error {
constructor(message: string, readonly context: Record<string, unknown>) {
super(message);
this.name = 'IsolationViolation';
}
}
const MAX_TOP_K = 50;
export class IsolatedRetriever {
constructor(private readonly pool: Pool) {}
async retrieve(req: RetrievalRequest): Promise<Chunk[]> {
if (!req.tenantId || !req.repoId) {
throw new IsolationViolation('missing tenant or repo scope', { traceId: req.traceId });
}
if (req.topK < 1 || req.topK > MAX_TOP_K) {
throw new RangeError(`topK must be within 1..${MAX_TOP_K}`);
}
const client: PoolClient = await this.pool.connect();
try {
await client.query('BEGIN READ ONLY');
// RLS reads this GUC; it is transaction-scoped and cannot leak across pool reuse.
await client.query('SET LOCAL app.tenant_id = $1', [req.tenantId]);
await client.query('SET LOCAL statement_timeout = $1', ['5000ms']);
const { rows } = await client.query<{
chunk_id: string;
tenant_id: string;
repo_id: string;
content: string;
score: string;
}>(
`SELECT chunk_id, tenant_id, repo_id, content,
1 - (embedding <=> $1::vector) AS score
FROM chunks
WHERE repo_id = $2
AND tenant_id = current_setting('app.tenant_id')::uuid
ORDER BY embedding <=> $1::vector
LIMIT $3`,
[JSON.stringify(req.queryEmbedding), req.repoId, req.topK],
);
await client.query('COMMIT');
return rows.map((r) => {
if (r.tenant_id !== req.tenantId) {
// Unreachable if RLS is enforced — which is exactly why we assert it.
throw new IsolationViolation('cross-tenant row returned', {
traceId: req.traceId,
expected: req.tenantId,
actual: r.tenant_id,
});
}
return {
chunkId: r.chunk_id,
tenantId: r.tenant_id as TenantId,
repoId: r.repo_id as RepoId,
content: r.content,
score: Number(r.score),
};
});
} catch (err) {
await client.query('ROLLBACK').catch(() => undefined);
throw err;
} finally {
client.release();
}
}
}The defensive re-check after the query is not paranoia — it converts a silent data breach into a loud, alertable exception. Add a metric counter on IsolationViolation and page on any non-zero rate.
Boundary 3 — Tool Calls: Default-Deny Capability Policy
Agents do not fail because they call tools; they fail because tool calls are evaluated late and permissively. Evaluate before execution, in a single chokepoint, with an explicit allowlist.
// policy.ts — default-deny capability evaluation for agent tool calls
export type Capability = 'fs.read' | 'fs.write' | 'net.egress' | 'proc.exec' | 'secrets.read';
export interface ToolCall {
readonly tool: string;
readonly capability: Capability;
readonly args: Readonly<Record<string, unknown>>;
readonly traceId: string;
readonly tenantId: string;
}
export type Decision =
| { readonly effect: 'allow' }
| { readonly effect: 'deny'; readonly reason: string }
| { readonly effect: 'require_approval'; readonly reason: string };
const EGRESS_ALLOWLIST = new Set(['pypi.org', 'registry.npmjs.org', 'proxy.internal']);
const SENSITIVE_SINKS = [/\.amazonaws\.com$/, /\.googleapis\.com$/, /\.openai\.com$/, /\.x\.ai$/];
export function evaluate(call: ToolCall): Decision {
switch (call.capability) {
case 'secrets.read':
return { effect: 'deny', reason: 'agents never receive raw credentials' };
case 'net.egress': {
const host = String(call.args['host'] ?? '').toLowerCase().trim();
if (host.length === 0) return { effect: 'deny', reason: 'egress without explicit host' };
if (SENSITIVE_SINKS.some((re) => re.test(host))) {
return { effect: 'require_approval', reason: `sensitive sink ${host}` };
}
if (!EGRESS_ALLOWLIST.has(host)) {
return { effect: 'deny', reason: `host ${host} not in egress allowlist` };
}
return { effect: 'allow' };
}
case 'proc.exec': {
const cmd = String(call.args['cmd'] ?? '');
if (/(^|\s)(curl|wget|nc|scp|ssh|rsync)\s/.test(cmd)) {
return { effect: 'deny', reason: 'network tooling inside sandbox' };
}
return { effect: 'allow' };
}
case 'fs.read':
case 'fs.write':
return { effect: 'allow' };
default:
return { effect: 'deny', reason: 'unknown capability' };
}
}The require_approval branch is the pragmatic middle ground: it preserves developer velocity for legitimate cross-boundary work while making every such call human-attributable in the audit log.
Boundary 4 — Execution: A Sandbox With No Ambient Authority
Most real-world agent leaks are not clever — they are a shell that had a cloud credential in its environment. Remove ambient authority entirely.
apiVersion: v1
kind: Pod
metadata:
name: agent-sandbox
spec:
automountServiceAccountToken: false
runtimeClassName: gvisor
securityContext:
runAsNonRoot: true
runAsUser: 65532
seccompProfile: { type: RuntimeDefault }
containers:
- name: runner
image: registry.internal/agent-sandbox@sha256:0000000000000000000000000000000000000000000000000000000000000000
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: { drop: [ALL] }
resources:
limits: { cpu: 2, memory: 4Gi, ephemeral-storage: 10Gi }
env:
- { name: HTTP_PROXY, value: http://egress-proxy.internal:3128 }
- { name: HTTPS_PROXY, value: http://egress-proxy.internal:3128 }
volumeMounts:
- { name: workspace, mountPath: /workspace }
- { name: tmp, mountPath: /tmp }
volumes:
- name: workspace
emptyDir: { sizeLimit: 10Gi }
- name: tmp
emptyDir: { sizeLimit: 1Gi }
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: agent-egress
spec:
podSelector:
matchLabels: { app: agent-sandbox }
policyTypes: [Egress]
egress:
- to:
- namespaceSelector:
matchLabels: { name: egress-proxy }
podSelector:
matchLabels: { app: egress-proxy }
ports:
- { protocol: TCP, port: 3128 }The runtimeClassName: gvisor line is not decoration. A user-space kernel gives you a second containment layer beneath the pod, which matters when the agent is running LLM-generated code rather than your own.
Boundary 5 — Telemetry: Hash-Chained, Provenance-Stamped Audit
You cannot investigate what you cannot verify. Every tool call, retrieval, and redaction decision should append to an append-only chain where each record commits to its predecessor.
// audit.ts — tamper-evident append-only log for agent actions
import { createHash } from 'node:crypto';
export interface AuditEvent {
readonly ts: string;
readonly traceId: string;
readonly tenantId: string;
readonly actor: string;
readonly action: string;
readonly subject: string;
readonly outcome: 'allow' | 'deny' | 'error';
readonly detail: Readonly<Record<string, string | number | boolean>>;
}
export interface SealedEvent extends AuditEvent {
readonly seq: number;
readonly prevHash: string;
readonly hash: string;
}
const GENESIS = '0'.repeat(64);
function canonicalize(e: AuditEvent & { seq: number; prevHash: string }): string {
return JSON.stringify([
e.seq,
e.prevHash,
e.ts,
e.traceId,
e.tenantId,
e.actor,
e.action,
e.subject,
e.outcome,
Object.keys(e.detail).sort().map((k) => [k, e.detail[k]]),
]);
}
export function seal(event: AuditEvent, seq: number, prevHash: string = GENESIS): SealedEvent {
const hash = createHash('sha256')
.update(canonicalize({ ...event, seq, prevHash }))
.digest('hex');
return { ...event, seq, prevHash, hash };
}
export class AuditChain {
private seq = 0;
private head = GENESIS;
constructor(private readonly sink: { append(e: SealedEvent): Promise<void> }) {}
async record(event: AuditEvent): Promise<SealedEvent> {
const sealed = seal(event, this.seq + 1, this.head);
try {
await this.sink.append(sealed);
this.seq = sealed.seq;
this.head = sealed.hash;
return sealed;
} catch (err) {
// No audit, no action. Fail the agent operation rather than lose the record.
throw new Error(`audit sink unavailable: ${(err as Error).message}`);
}
}
}Ship the head hash to WORM storage (S3 Object Lock or an append-only syslog target) on a fixed interval. If the chain ever fails verification, you have a containment event, not a logging bug.
Detection: The Signals That Should Have Fired
An exfiltration of this shape leaves fingerprints. Instrument these as first-class alerts:
- Cross-tenant retrieval counter — any
IsolationViolationabove zero is a page, not a ticket. - Entropy delta — a spike in redaction findings per request indicates the agent is reading files it should not have been able to open.
- Egress novelty — new destination host from any sandbox, or any egress volume above a per-tenant baseline.
- Tool-shape anomalies —
fs.readcalls against dotfiles,~/.aws, kubeconfig paths, or outside/workspace. - Answer-content DLP — run the redactor over the final model response and on the trace payload before persistence.
Trade-offs: The Containment Versus Productivity Curve
None of this is free, and honesty about cost is what separates an architecture article from a checklist:
- Redaction latency. Regex plus entropy scanning adds single-digit milliseconds for typical file chunks but is superlinear on giant minified bundles. Cap the scan input and stream it; never scan the entire monorepo synchronously.
- False positives. High-entropy detection flags base64 fixtures and lockfile hashes. Mitigate with path-based exemptions that are themselves audited — an exemption is a capability.
- RLS overhead. Forced row security adds a predicate to every chunk query; index on
(tenant_id, repo_id)and validate plans under realistic cardinality. - Developer friction. Strict egress allowlists break legitimate first-run installs. Prefer a transparent proxy that logs and blocks rather than a hard network drop, so developers get an error message instead of a mystery timeout.
The correct posture is containment-by-default with an audited, per-request escape hatch — not a permissive baseline with aspirational policy documents.
Production Checklist
- Vector and document retrieval enforce tenant isolation inside the datastore, not in application code.
- Redaction runs on ingestion and on egress; detectors fail closed on exception.
- No sandbox mounts
$HOME, cloud config, or a service-account token. - Tool calls pass through a single default-deny policy chokepoint before execution.
- Network egress traverses a logging proxy with an explicit host allowlist.
- Traces, evals, and replays are scrubbed with the same redactor as production traffic.
- Prompt caches are keyed on
(tenantId, repoId, promptHash). - Audit log is hash-chained and anchored to WORM storage on a schedule.
IsolationViolationand cross-tenant assertion failures page on-call.- A quarterly game-day exercises a simulated cross-tenant leak end to end.
Pitfalls to Avoid
- Redacting only the response. By then the secret is in a third-party trace store you do not control.
- Trusting a system prompt. Instructions are not a security boundary; capability checks are.
- Treating the sandbox as trusted. LLM-generated code is untrusted code, full stop.
- Shared embedding indexes with metadata filters. One missing
WHEREclause and the breach is live. - Unbounded context windows. Longer context means more retained secrets and a larger blast radius per request.
- Logging full prompts at DEBUG in production. The most common CWE-532 in AI systems is also the most preventable.
Sources & Technical References
- OWASP Top 10 for LLM Applications (2025) — LLM02: Sensitive Information Disclosure and LLM06: Excessive Agency.
- MITRE — CWE-532: Insertion of Sensitive Information into Log File.
- MITRE — CWE-200: Exposure of Sensitive Information to an Unauthorized Actor.
- NIST — AI Risk Management Framework (AI RMF 1.0).
- NIST — SP 800-53 Rev. 5, Security and Privacy Controls.
- NIST — SP 800-190, Application Container Security Guide.
- PostgreSQL Documentation — Row Security Policies.
- Kubernetes Documentation — Network Policies.
- Kubernetes Documentation — Pod Security Standards.
- gVisor Documentation — Architecture and Isolation Model.
- Firecracker — Secure and Fast microVMs for Serverless Computing (NSDI paper).
- OpenTelemetry — Semantic Conventions.
- Microsoft Presidio — Data Protection and De-identification SDK.
- SLSA — Supply-chain Levels for Software Artifacts.
- in-toto — Supply Chain Integrity Framework Specification.
- IETF — RFC 8446: The Transport Layer Security (TLS) Protocol Version 1.3.
- Model Context Protocol — Specification.
- Google SRE — Site Reliability Engineering: Monitoring Distributed Systems.
Discussion (0)
Continue Reading
More production-grade engineering deep dives and architectural guides

Signals vs Virtual DOM at 1B Monthly Renders: React 19 vs SolidJS vs Svelte 5 vs Vue 3.5 — Measured p99 Frame Time, Memory, Bundle Size, and True Cost per 1M Updates
We rebuilt the same 10,000-row update workload in React 19, SolidJS, Svelte 5, and Vue 3.5 and measured p99 frame time, retained heap, bundle weight, and a defensible cost model per million updates. The numbers show that architecture, not micro-optimization, decides whether your tail latency survives a billion renders.

Postgres Egress Cost Optimization: Cutting Network Bandwidth by 70% in High-Throughput APIs
Your Postgres bill is rarely about CPU — it is about bytes leaving the database, crossing an availability zone, and traversing a NAT gateway. Here is the systematic playbook we used to cut data transfer cost by 70% in a high-throughput API without touching query latency.

Gemini 4 Neon: A Principal Engineer's Deep Dive into the Architecture
Gemini 4 Neon is a serving-systems release disguised as a model launch: the interesting engineering lives in its control plane, cache fabric, and streaming transport, not the benchmark table. This analysis breaks down the four-plane topology, the latency budget you must own, and the production patterns that keep a Neon integration from melting down under load.