All ArticlesSystem Architecture•November 15, 2026•10 min read

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.

Grok Build Leak Postmortem: The Systems Architecture Behind Agentic Data ExfiltrationAI Generated with Qwen 3.0 via CometAPI

The 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.

PropertyChat assistantCoding agent
Context scopeOne user turnEntire repo, shell history, dependency tree
Credentials in scopeNoneCloud roles, DB URLs, CI tokens, kubeconfig
Side effectsText outputFile writes, commits, deploys, package installs
PersistenceSession transcriptEmbedding indexes, traces, eval datasets
Blast radiusOne userEvery 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

  1. 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.
  2. Context over-collection. The agent walks .env, ~/.aws/credentials, ~/.kube/config, and ~/.npmrc because the sandbox mounted $HOME.
  3. Telemetry retention. Full prompts and completions shipped to an observability vendor with 30-day retention and broad internal read access (CWE-532).
  4. Evaluation and training pipelines. Sampled production traces reused for offline evals without re-scrubbing.
  5. Tool-output echo. The agent redacts nothing on the way out, so a secret it read silently lands in the final answer.
  6. 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.

python
# 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, merged

Design 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.

sql
-- 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);
ts
// 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.

ts
// 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.

yaml
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.

ts
// 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 IsolationViolation above 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.read calls 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.
  • IsolationViolation and 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 WHERE clause 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

2 views•0 comments

Discussion (0)

Join the conversation

Loading comments...

Continue Reading

More production-grade engineering deep dives and architectural guides

Explore all articles