Secret-Aware Context Filters: Stop AI Editors From Shipping Keys

Secret-Aware Context Filters: Stop AI Editors From Shipping Keys

The fastest way to leak an AWS key is not a malicious prompt — it is an engineer who has .env open in a split pane while the coding agent “grabs context.” Secret-aware filters must run before context leaves the IDE, not after the vendor logs the request.

⚡ TL;DR: Scan buffers, selections, and @file attachments with high-precision detectors (entropy + known prefixes + PEM). Redact to stable placeholders. Never send .env, *.pem, or cloud credential files. Log redaction events locally for audit. Combine with Claude Projects vs Cursor: Context Hygiene and AI Coding in VPC.

Detect before transmit

// secret-filter.ts
const PATTERNS: { name: string; re: RegExp }[] = [
  { name: "aws_akid", re: /\bAKIA[0-9A-Z]{16}\b/g },
  { name: "aws_secret", re: /\b(?:=|:)\s*([A-Za-z0-9/+=]{40})\b/g },
  { name: "github_pat", re: /\bghp_[A-Za-z0-9]{36,}\b/g },
  { name: "slack_token", re: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g },
  { name: "pem", re: /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g },
  { name: "jwt", re: /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g },
];

const BLOCKED_PATHS = [
  /^\.env(\.|$)/,
  /\.pem$/,
  /credentials$/i,
  /^\.aws\//,
  /id_rsa$/,
];

export function filterContext(parts: { path?: string; text: string }[]) {
  const events: { name: string; path?: string }[] = [];
  const out = parts.map((p) => {
    if (p.path && BLOCKED_PATHS.some((re) => re.test(p.path!))) {
      events.push({ name: "blocked_path", path: p.path });
      return { ...p, text: `/* REDACTED: blocked path ${p.path} */` };
    }
    let text = p.text;
    for (const { name, re } of PATTERNS) {
      if (re.test(text)) {
        events.push({ name, path: p.path });
        text = text.replace(re, `{{REDACTED:${name}}}`);
        re.lastIndex = 0;
      }
    }
    return { ...p, text };
  });
  return { parts: out, events };
}

✅ Fail closed on known credential paths even if content looks “safe.”
❌ Relying only on the model vendor’s server-side filter after upload.

Wire into the agent request path

// before every model call
export async function sendToModel(raw: { path?: string; text: string }[]) {
  const { parts, events } = filterContext(raw);
  if (events.length) {
    await localAudit.append({ ts: Date.now(), events }); // never ship secrets to audit either
    ui.toast(`Redacted ${events.length} secret-like span(s) from AI context`);
  }
  return model.complete({ context: parts });
}

Editor ignore rules and notepads help — Cursor Agent Mode still needs this filter because agents read open buffers.

High-entropy secondary pass

# entropy_scan.py — catch unknown token shapes
import math, re

def shannon(s: str) -> float:
    if not s:
        return 0.0
    from collections import Counter
    c = Counter(s)
    n = len(s)
    return -sum((v / n) * math.log2(v / n) for v in c.values())

TOKENISH = re.compile(r"[A-Za-z0-9/+=_-]{24,}")

def redact_high_entropy(text: str, threshold: float = 4.5) -> str:
    def repl(m: re.Match) -> str:
        s = m.group(0)
        return "{{REDACTED:entropy}}" if shannon(s) >= threshold else s
    return TOKENISH.sub(repl, text)

Tune thresholds on internal corpora to limit false positives on hashes in lockfiles — or exclude package-lock.json / pnpm-lock.yaml from entropy scans entirely.

Debugging leaks that already happened

When a key may have left the laptop:

  1. Rotate immediately (do not “investigate first”).
  2. Search CloudTrail / IdP for first use of the canary or leaked principal.
  3. Add the pattern to the local detector pack.
  4. Review agent request logs for the session window (metadata only).

Relate to credential canaries and IAM hygiene on AWS posts already on the site; for IDE-side prevention stay ruthless.

Closing checklist

  • [ ] Pre-flight filter on buffers, selections, @file, and terminal selections
  • [ ] Path denylist for .env, PEM, .aws/credentials
  • [ ] Prefix detectors + entropy pass with lockfile exclusions
  • [ ] Local audit of redaction events without storing secret values
  • [ ] UI notification when redaction fires so engineers learn
  • [ ] Rotate-first playbook documented for suspected exfiltration

Related reading

Last updated on September 11, 2026


Discover more from CheatCoders

Subscribe to get the latest posts sent to your email.

1 Comment

Leave a Reply