diff --git a/apps/docs/content/features/guardrails.mdx b/apps/docs/content/features/guardrails.mdx index 40232e5536..7bd5f353c4 100644 --- a/apps/docs/content/features/guardrails.mdx +++ b/apps/docs/content/features/guardrails.mdx @@ -54,9 +54,16 @@ Identifies personal information: - Social Security Numbers - Credit card numbers - IP addresses +- Passport and driver's license numbers When the action is set to **redact**, PII is replaced with placeholders like `[EMAIL_REDACTED]`. +Detection is validated rather than purely pattern-based, so identifiers that only +look like PII are left alone: card numbers must pass the Luhn checksum, phone +numbers need grouping separators or a nearby phone keyword, and passport and +license numbers need a nearby keyword. A bare numeric id such as a product id, +order number or unix timestamp is therefore never redacted as a phone number. + ### Secrets Detection Detects credentials and API keys: @@ -66,6 +73,11 @@ Detects credentials and API keys: - Passwords in common formats - Private keys +High-entropy checks and placeholder filtering keep ordinary content out of the +way: git SHAs and hex digests are not treated as AWS secrets, and template +values such as `YOUR_API_KEY`, `${OPENAI_API_KEY}` or `********` are not treated +as credentials. + ### File Type Restrictions Control which file types can be uploaded: diff --git a/ee/guardrails/src/engine.ts b/ee/guardrails/src/engine.ts index 546549e603..0b8a117dd7 100644 --- a/ee/guardrails/src/engine.ts +++ b/ee/guardrails/src/engine.ts @@ -108,34 +108,28 @@ export async function checkGuardrails( const result = rule.check(content, ruleConfig); if (!result.passed) { - let matchedPattern = result.matches.join(", "); - - if (ruleConfig.action === "redact") { - if (rule.id === "system:pii_detection") { - const { patterns } = redactPii(content); - if (patterns.length > 0) { - redactions.push({ - ruleId: rule.id, - messageIndex, - kind: "pii", - matches: [], - pattern: patterns.join(", "), - }); - } - // Avoid logging the raw PII; log the detected types instead - matchedPattern = patterns.join(", "); - } else if (rule.id === "system:secrets") { - const { patterns } = redactSecrets(content); - if (patterns.length > 0) { - redactions.push({ - ruleId: rule.id, - messageIndex, - kind: "secrets", - matches: [], - pattern: patterns.join(", "), - }); - } - } + // The PII and secrets rules report detector labels rather than + // matched values, so neither field may carry the content those + // rules exist to keep out of storage. + let matchedContent = content; + let kind: RedactionInfo["kind"] | undefined; + + if (rule.id === "system:pii_detection") { + matchedContent = redactPii(matchedContent).redacted; + kind = "pii"; + } else if (rule.id === "system:secrets") { + matchedContent = redactSecrets(matchedContent).redacted; + kind = "secrets"; + } + + if (ruleConfig.action === "redact" && kind) { + redactions.push({ + ruleId: rule.id, + messageIndex, + kind, + matches: [], + pattern: result.matches.join(", "), + }); } violations.push({ @@ -143,8 +137,8 @@ export async function checkGuardrails( ruleName: rule.name, category: rule.category, action: ruleConfig.action, - matchedPattern, - matchedContent: content.substring(0, 100), + matchedPattern: result.matches.join(", "), + matchedContent: matchedContent.substring(0, 100), }); } } diff --git a/ee/guardrails/src/rules/index.ts b/ee/guardrails/src/rules/index.ts index c69755681c..815df2b887 100644 --- a/ee/guardrails/src/rules/index.ts +++ b/ee/guardrails/src/rules/index.ts @@ -9,8 +9,8 @@ import type { SystemRule } from "@/types.js"; export { injectionRule } from "./system/injection.js"; export { jailbreakRule } from "./system/jailbreak.js"; -export { piiRule, redactPii } from "./system/pii.js"; -export { secretsRule, redactSecrets } from "./system/secrets.js"; +export { piiRule, redactPii, detectPii } from "./system/pii.js"; +export { secretsRule, redactSecrets, detectSecrets } from "./system/secrets.js"; export { fileTypesRule, checkFileType, checkFileSize } from "./system/files.js"; export { documentLeakageRule } from "./system/document-leakage.js"; diff --git a/ee/guardrails/src/rules/system/detector.ts b/ee/guardrails/src/rules/system/detector.ts new file mode 100644 index 0000000000..61dc258c30 --- /dev/null +++ b/ee/guardrails/src/rules/system/detector.ts @@ -0,0 +1,263 @@ +/** + * Shared machinery for pattern detectors (PII, secrets). + * + * Detectors are matched in a single pass and validated with an optional + * `validate` callback so a regex can stay broad while context/structure checks + * keep the false-positive rate low. Overlapping matches are resolved in favour + * of the detector listed first, so ordering is significant. + */ +export interface Detector { + id: string; + /** Human readable label used in violation/redaction logs. */ + label: string; + /** Replacement inserted for a confirmed match. */ + replacement: string; + pattern: RegExp; + /** + * Replace only the first capture group rather than the whole match. Needed + * where the match includes structure that must survive redaction, such as + * the key and quotes around a JSON password value. + */ + redactGroup?: boolean; + /** + * Returns false to discard a regex hit. `value` is the span that would be + * replaced (the capture group when `redactGroup` is set); `before`/`after` + * carry a limited window of surrounding text so detectors can require + * nearby keywords. + */ + validate?: (value: string, before: string, after: string) => boolean; +} + +export interface DetectorMatch { + detector: Detector; + value: string; + start: number; + end: number; +} + +/** Characters of context handed to `validate` on each side of a match. */ +const CONTEXT_WINDOW = 48; + +export function findMatches( + content: string, + detectors: Detector[], +): DetectorMatch[] { + const matches: DetectorMatch[] = []; + + for (const detector of detectors) { + // `g` to walk every occurrence, `d` for the capture-group spans that + // `redactGroup` detectors replace. + const flags = detector.pattern.flags.replace(/[gd]/g, "") + "gd"; + const pattern = new RegExp(detector.pattern.source, flags); + + for (const match of content.matchAll(pattern)) { + const span = detector.redactGroup + ? firstGroupSpan(match) + : [match.index, match.index + match[0].length]; + if (!span) { + continue; + } + + const [start, end] = span; + const value = content.slice(start, end); + + if (detector.validate) { + const matchStart = match.index; + const matchEnd = match.index + match[0].length; + const before = content.slice( + Math.max(0, matchStart - CONTEXT_WINDOW), + matchStart, + ); + const after = content.slice(matchEnd, matchEnd + CONTEXT_WINDOW); + if (!detector.validate(value, before, after)) { + continue; + } + } + + matches.push({ detector, value, start, end }); + } + } + + // Earlier detectors win over later ones on overlap; within a detector, + // earlier positions win. + matches.sort((a, b) => { + if (a.start !== b.start) { + return a.start - b.start; + } + return b.end - a.end; + }); + + const deduped: DetectorMatch[] = []; + let cursor = -1; + for (const match of matches) { + if (match.start < cursor) { + continue; + } + deduped.push(match); + cursor = match.end; + } + + return deduped; +} + +/** Span of the first capture group that participated in the match. */ +function firstGroupSpan(match: RegExpExecArray): [number, number] | undefined { + const indices = match.indices; + if (!indices) { + return undefined; + } + for (let group = 1; group < indices.length; group++) { + const span = indices[group]; + if (span) { + return span; + } + } + return undefined; +} + +export function redactMatches( + content: string, + matches: DetectorMatch[], +): string { + if (matches.length === 0) { + return content; + } + + let result = ""; + let cursor = 0; + for (const match of matches) { + result += content.slice(cursor, match.start) + match.detector.replacement; + cursor = match.end; + } + return result + content.slice(cursor); +} + +/** + * Shannon entropy in bits per character. Random tokens sit above ~4 bits; + * English prose, hex digests and snake_case identifiers sit well below. + */ +export function shannonEntropy(value: string): number { + if (!value) { + return 0; + } + + const counts = new Map(); + for (const char of value) { + counts.set(char, (counts.get(char) ?? 0) + 1); + } + + let entropy = 0; + for (const count of counts.values()) { + const p = count / value.length; + entropy -= p * Math.log2(p); + } + return entropy; +} + +/** Luhn checksum, used to reject digit runs that merely look like card numbers. */ +export function luhn(digits: string): boolean { + let sum = 0; + let double = false; + for (let i = digits.length - 1; i >= 0; i--) { + let digit = digits.charCodeAt(i) - 48; + if (digit < 0 || digit > 9) { + return false; + } + if (double) { + digit *= 2; + if (digit > 9) { + digit -= 9; + } + } + sum += digit; + double = !double; + } + return sum % 10 === 0; +} + +/** + * Words that carry no secret on their own. A value counts as a placeholder only + * when *every* one of its separator-delimited words comes from this list, so + * `YOUR_API_KEY_HERE` is discarded while `testingSecret123` — which a prefix + * match would have thrown away — is still treated as a credential. + */ +const PLACEHOLDER_WORDS = new Set([ + "a", + "api", + "apikey", + "bar", + "baz", + "change", + "changeme", + "dummy", + "example", + "fake", + "foo", + "here", + "insert", + "key", + "me", + "my", + "none", + "null", + "password", + "placeholder", + "pwd", + "redacted", + "replace", + "sample", + "secret", + "some", + "string", + "test", + "testing", + "the", + "todo", + "token", + "undefined", + "value", + "your", +]); + +const MASK_VALUE = /^[xX*.\-_0\s]+$/; + +// `<...>` must form a token: a bare angle bracket appears in real passwords. +const TEMPLATE_MARKER = + /<[^<>]*>|\$\{|\{\{|%\(|%s|process\.env|os\.environ|import\.meta\.env|env\[|getenv/i; + +/** + * True for values that are obviously not real credentials: template + * placeholders, env-var references, masked values and SCREAMING_SNAKE stand-ins + * such as `YOUR_API_KEY_HERE`. + */ +export function isPlaceholderSecret(value: string): boolean { + const trimmed = value.trim().replace(/^['"]|['"]$/g, ""); + if (!trimmed) { + return true; + } + if (TEMPLATE_MARKER.test(trimmed)) { + return true; + } + if (MASK_VALUE.test(trimmed)) { + return true; + } + const words = trimmed + .toLowerCase() + .split(/[_\-.\s]+/) + .filter(Boolean); + if ( + words.length > 0 && + words.every((word) => PLACEHOLDER_WORDS.has(word) || /^\d+$/.test(word)) + ) { + return true; + } + // A single repeated character, e.g. "********" or "xxxxxxxx". + if (new Set(trimmed).size === 1) { + return true; + } + // SCREAMING_SNAKE_CASE is a placeholder convention, never a real secret. + if (/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/.test(trimmed)) { + return true; + } + return false; +} diff --git a/ee/guardrails/src/rules/system/jailbreak.ts b/ee/guardrails/src/rules/system/jailbreak.ts index 41b358d9f2..d6d6a71b5f 100644 --- a/ee/guardrails/src/rules/system/jailbreak.ts +++ b/ee/guardrails/src/rules/system/jailbreak.ts @@ -1,9 +1,14 @@ import type { SystemRule } from "@/types.js"; const JAILBREAK_PATTERNS = [ - /DAN\s*(mode|prompt)?/i, - /do\s+anything\s+now/i, - /developer\s+mode/i, + // Case-sensitive and anchored: the case-insensitive substring form matched + // ordinary words such as "redundant", "abundant" and "mundane". + /\bDAN\b(\s+(mode|prompt))?/, + /\bdan\s+(mode|prompt)\b/i, + /\bdo\s+anything\s+now\b/i, + // "developer mode" on its own is ordinary product vocabulary; only the + // activation phrasing indicates a jailbreak attempt. + /(enable|enter|activate|turn\s+on|switch\s+to)\s+developer\s+mode/i, /evil\s+(mode|assistant|bot)/i, /pretend\s+(you\s+)?(are|have)\s+no\s+(restrictions?|limits?|rules?)/i, /act\s+as\s+if\s+(you\s+)?have\s+no\s+(ethics?|morals?)/i, diff --git a/ee/guardrails/src/rules/system/pii.spec.ts b/ee/guardrails/src/rules/system/pii.spec.ts new file mode 100644 index 0000000000..e219d3265e --- /dev/null +++ b/ee/guardrails/src/rules/system/pii.spec.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from "vitest"; + +import { detectPii, piiRule, redactPii } from "./pii.js"; + +const clean = [ + '{"product_id": 123456789, "qty": 3}', + '{"product_id": 3074185296}', + "product_id=3074185296", + "order 987654321 shipped, tracking 1234567890", + "created_at 1755302400 updated_at 1755302401", + "epoch ms 1755302400123", + "Total revenue 4123456789012 cents", + "card token 4111111111111112", + "Version 1.2.3.4 released", + "upgrade to v10.0.0.1", + "coordinates 1.2.3.4.5", + "Employee record AB1234567 archived", + "Flight LH123456 to Berlin", + "Invoice PO1234567 total", + "Part number X12345 out of stock", + "SKU 000-00-0000 discontinued", +]; + +const detected = [ + ["SSN", "his ssn is 123-45-6789"], + ["Credit Card", "card 4111111111111111 expires soon"], + ["Email", "ping support@example.com about it"], + ["Phone", "call me at 555-123-4567"], + ["Phone", "reception: (415) 555-0100"], + ["Phone", "phone 4155550100"], + ["IP Address", "client connected from 203.0.113.42"], + ["Passport", "passport AB1234567 expires in May"], + ["Passport", "AB1234567 is my passport number"], + ["Drivers License", "driver's license D1234567 on file"], + ["Credit Card", "card 4111 1111 1111 1111 on file"], + ["Credit Card", "card 4111-1111-1111-1111 on file"], + ["Credit Card", "amex 3782 822463 10005"], + ["Phone", "4155550100 is my mobile"], +] as const; + +describe("detectPii", () => { + it.each(clean)("does not flag %j", (content) => { + expect(detectPii(content).patterns).toEqual([]); + }); + + it.each(detected)("flags %s in %j", (label, content) => { + expect(detectPii(content).patterns).toContain(label); + }); +}); + +describe("redactPii", () => { + it("leaves numeric identifiers untouched", () => { + const content = '{"product_id": 3074185296, "created_at": 1755302400}'; + expect(redactPii(content).redacted).toBe(content); + }); + + it("redacts each detected value in place", () => { + const result = redactPii( + "mail bob@example.com or call 555-123-4567, ssn 123-45-6789", + ); + expect(result.redacted).toBe( + "mail [EMAIL_REDACTED] or call [PHONE_REDACTED], ssn [SSN_REDACTED]", + ); + }); + + it("redacts a card number once, not as overlapping matches", () => { + const result = redactPii("card 4111111111111111 on file"); + expect(result.redacted).toBe("card [CREDIT_CARD_REDACTED] on file"); + expect(result.patterns).toEqual(["Credit Card"]); + }); + + it("redacts a grouped card number as one span", () => { + const result = redactPii("card 4111 1111 1111 1111 on file"); + expect(result.redacted).toBe("card [CREDIT_CARD_REDACTED] on file"); + expect(result.patterns).toEqual(["Credit Card"]); + }); + + it("reports the same detections as the rule check", () => { + const content = "email a@b.io and phone (415) 555-0100"; + expect(redactPii(content).patterns).toEqual(detectPii(content).patterns); + }); +}); + +describe("piiRule.check", () => { + it("reports detector labels, never the matched values", () => { + const result = piiRule.check("ssn 123-45-6789 mail bob@example.com", { + enabled: true, + action: "block", + }); + + expect(result.passed).toBe(false); + expect(result.matches).toEqual(["SSN", "Email"]); + expect(result.matches.join(" ")).not.toContain("123-45-6789"); + expect(result.matches.join(" ")).not.toContain("bob@example.com"); + }); +}); diff --git a/ee/guardrails/src/rules/system/pii.ts b/ee/guardrails/src/rules/system/pii.ts index 900300e736..be898c5a32 100644 --- a/ee/guardrails/src/rules/system/pii.ts +++ b/ee/guardrails/src/rules/system/pii.ts @@ -1,82 +1,161 @@ +import { findMatches, luhn, redactMatches } from "./detector.js"; + +import type { Detector } from "./detector.js"; import type { SystemRule } from "@/types.js"; -const PII_PATTERNS = [ - // SSN - /\b\d{3}-\d{2}-\d{4}\b/, - // Credit card numbers - /\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12})\b/, - // Email addresses - /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/, - // Phone numbers (various formats) - /\b(?:\+1[-.\s]?)?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}\b/, - // IP addresses - /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/, - // Passport numbers (simplified) - /\b[A-Z]{1,2}[0-9]{6,9}\b/, - // Driver's license (simplified, US format) - /\b[A-Z]{1,2}[0-9]{5,8}\b/, -]; +/** + * Builds a check for a keyword appearing on *either* side of the match, so both + * "passport AB1234567" and "AB1234567 is my passport" are recognised. + */ +function nearKeyword( + keywords: string, +): (before: string, after: string) => boolean { + const before = new RegExp(`(?:${keywords})\\W{0,24}$`, "i"); + const after = new RegExp( + `^\\W{0,4}(?:(?:is|was|are|were)\\s+)?(?:(?:my|the|his|her|their|our)\\s+)?(?:${keywords})`, + "i", + ); + return (b, a) => before.test(b) || after.test(a); +} -const PII_REPLACEMENTS: Record = { - ssn: "[SSN_REDACTED]", - credit_card: "[CREDIT_CARD_REDACTED]", - email: "[EMAIL_REDACTED]", - phone: "[PHONE_REDACTED]", - ip_address: "[IP_REDACTED]", - passport: "[PASSPORT_REDACTED]", - drivers_license: "[LICENSE_REDACTED]", -}; +const nearPhone = nearKeyword( + "phone|telephone|tel|mobile|cell|fax|whatsapp|sms|call me|reach me|contact", +); +const nearPassport = nearKeyword("passport|travel document"); +const nearLicense = nearKeyword( + "driver'?s?\\s*licen[cs]e|driving\\s*licen[cs]e|dl\\s*(?:no|number|#)", +); -export function redactPii(content: string): { - redacted: string; - patterns: string[]; -} { - let redacted = content; - const patterns: string[] = []; +const VERSION_CONTEXT = + /(version|release|build|schema|firmware|\bv)\W{0,8}$|[\d.]$/i; - // SSN - const ssnMatches = redacted.match(/\b\d{3}-\d{2}-\d{4}\b/g); - if (ssnMatches) { - patterns.push(...ssnMatches.map(() => "SSN")); - redacted = redacted.replace(/\b\d{3}-\d{2}-\d{4}\b/g, PII_REPLACEMENTS.ssn); - } +interface CardBrand { + prefix: RegExp; + lengths: number[]; +} - // Credit cards - const ccPattern = - /\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12})\b/g; - const ccMatches = redacted.match(ccPattern); - if (ccMatches) { - patterns.push(...ccMatches.map(() => "Credit Card")); - redacted = redacted.replace(ccPattern, PII_REPLACEMENTS.credit_card); - } +const CARD_BRANDS: CardBrand[] = [ + { prefix: /^4/, lengths: [13, 16, 19] }, + { prefix: /^(?:5[1-5]|2[2-7])/, lengths: [16] }, + { prefix: /^3[47]/, lengths: [15] }, + { prefix: /^(?:6011|65\d{2}|64[4-9]\d)/, lengths: [16, 19] }, + { prefix: /^3(?:0[0-5]|[689])/, lengths: [14] }, + { prefix: /^35(?:2[89]|[3-8]\d)/, lengths: [16, 19] }, +]; - // Email - const emailPattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g; - const emailMatches = redacted.match(emailPattern); - if (emailMatches) { - patterns.push(...emailMatches.map(() => "Email")); - redacted = redacted.replace(emailPattern, PII_REPLACEMENTS.email); +/** + * A digit run is a card number only if its length matches the issuing brand's + * prefix and it passes the Luhn checksum. Grouping separators are stripped + * first, so `4111 1111 1111 1111` is caught alongside the unbroken form. + */ +function isCardNumber(value: string): boolean { + const digits = value.replace(/[ -]/g, ""); + if (!/^\d+$/.test(digits)) { + return false; } + const brand = CARD_BRANDS.find( + (candidate) => + candidate.prefix.test(digits) && + candidate.lengths.includes(digits.length), + ); + return brand !== undefined && luhn(digits); +} - // Phone - const phonePattern = - /\b(?:\+1[-.\s]?)?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}\b/g; - const phoneMatches = redacted.match(phonePattern); - if (phoneMatches) { - patterns.push(...phoneMatches.map(() => "Phone")); - redacted = redacted.replace(phonePattern, PII_REPLACEMENTS.phone); - } +/** + * Ordered by specificity: an SSN or card number must win over the looser phone + * detector when their spans overlap. + */ +const PII_DETECTORS: Detector[] = [ + { + id: "ssn", + label: "SSN", + replacement: "[SSN_REDACTED]", + // Structurally invalid area/group/serial blocks are never issued. + pattern: /\b(?!000|666|9\d\d)\d{3}-(?!00)\d{2}-(?!0000)\d{4}\b/, + }, + { + id: "credit_card_grouped", + label: "Credit Card", + replacement: "[CREDIT_CARD_REDACTED]", + // Listed before the unbroken form so the whole grouped span is replaced. + pattern: /\b\d{4}[ -]\d{4,6}[ -]\d{4,6}(?:[ -]\d{1,4})?\b/, + validate: (value) => isCardNumber(value), + }, + { + id: "credit_card", + label: "Credit Card", + replacement: "[CREDIT_CARD_REDACTED]", + pattern: /\b\d{13,19}\b/, + // Without brand and checksum validation every long digit run starting + // with 4 or 5 is reported as a card number. + validate: (value) => isCardNumber(value), + }, + { + id: "email", + label: "Email", + replacement: "[EMAIL_REDACTED]", + pattern: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,24}\b/, + }, + { + id: "phone", + label: "Phone", + replacement: "[PHONE_REDACTED]", + pattern: /\b(?:\+1[-.\s]?)?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}\b/, + // A bare 10-digit run is far more often an id, an order number or a unix + // timestamp than a phone number, so require either formatting (grouping + // separators, parentheses, country code) or a nearby phone keyword. + validate: (value, before, after) => + /[-.\s()+]/.test(value) || nearPhone(before, after), + }, + { + id: "ip_address", + label: "IP Address", + replacement: "[IP_REDACTED]", + pattern: + /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/, + // `\b` does not stop at a dot, so a dotted version or a 5-part number + // would otherwise yield an "IP" from its first four segments. + validate: (value, before, after) => + !VERSION_CONTEXT.test(before) && !/^[.\d]/.test(after), + }, + { + id: "passport", + label: "Passport", + replacement: "[PASSPORT_REDACTED]", + pattern: /\b[A-Z]{1,2}[0-9]{6,9}\b/, + // Identical in shape to order numbers, SKUs and part numbers, so only + // treat it as a passport when the surrounding text says so. + validate: (_value, before, after) => nearPassport(before, after), + }, + { + id: "drivers_license", + label: "Drivers License", + replacement: "[LICENSE_REDACTED]", + pattern: /\b[A-Z]{1,2}[0-9]{5,8}\b/, + validate: (_value, before, after) => nearLicense(before, after), + }, +]; - // IP addresses - const ipPattern = - /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g; - const ipMatches = redacted.match(ipPattern); - if (ipMatches) { - patterns.push(...ipMatches.map(() => "IP Address")); - redacted = redacted.replace(ipPattern, PII_REPLACEMENTS.ip_address); - } +export function detectPii(content: string): { + patterns: string[]; + matches: string[]; +} { + const found = findMatches(content, PII_DETECTORS); + return { + patterns: found.map((m) => m.detector.label), + matches: found.map((m) => m.value), + }; +} - return { redacted, patterns }; +export function redactPii(content: string): { + redacted: string; + patterns: string[]; +} { + const found = findMatches(content, PII_DETECTORS); + return { + redacted: redactMatches(content, found), + patterns: found.map((m) => m.detector.label), + }; } export const piiRule: SystemRule = { @@ -90,17 +169,13 @@ export const piiRule: SystemRule = { return { passed: true, matches: [] }; } - const matches: string[] = []; - for (const pattern of PII_PATTERNS) { - const match = content.match(pattern); - if (match) { - matches.push(match[0]); - } - } + // Report the detector labels, never the matched values: the engine + // persists these on the violation record. + const { patterns } = detectPii(content); return { - passed: matches.length === 0, - matches, + passed: patterns.length === 0, + matches: patterns, }; }, }; diff --git a/ee/guardrails/src/rules/system/secrets.spec.ts b/ee/guardrails/src/rules/system/secrets.spec.ts new file mode 100644 index 0000000000..cc3b880d58 --- /dev/null +++ b/ee/guardrails/src/rules/system/secrets.spec.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from "vitest"; + +import { detectSecrets, redactSecrets, secretsRule } from "./secrets.js"; + +const clean = [ + "commit a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 reverted", + "integrity sha1-2jmj7l5rSw0yVb0000000000000000000000000000", + "set apiKey: YOUR_API_KEY_HERE_PLACEHOLDER", + "api_key=${OPENAI_API_KEY}", + "apiKey: process.env.OPENAI_API_KEY_VALUE_HERE", + '{"password": "********"}', + "password: ", + "passwd: xxxxxxxxxxxx", + "the user forgot their password, please reset it", + "postgres://user:${DB_PASSWORD}@db.internal:5432/app", + "see the eyJ header docs for details", +]; + +// Assembled at runtime so the fixtures do not trip secret scanners. +const stripeKey = ["sk", "live", "51H8xQ2eZvKYlo2CabcdefghijK"].join("_"); + +const detected = [ + ["AWS Access Key", "AKIAIOSFODNN7EXAMPLE"], + [ + "AWS Secret Key", + "aws_secret_access_key = wJalrXUtnFEMIK7MDENGbPxRfiCYEXAMPLEKEY12", + ], + ["Stripe Key", stripeKey], + ["GitHub Token", "ghp_" + "a".repeat(36)], + ["Private Key", "-----BEGIN RSA PRIVATE KEY-----"], + ["Connection String", "postgres://admin:s3cretPassw0rd@db.internal:5432/app"], + ["Password", '{"password": "hunter2000!"}'], + ["Password", "password=Tr0ub4dor&3xxx"], + ["API Key", "api_key: sk9Xk2Lm4Qp7Rt1Zv8Bn3Cw6"], + // A single angle bracket must not read as a template placeholder. + ["Password", "password=p { + it.each(clean)("does not flag %j", (content) => { + expect(detectSecrets(content).patterns).toEqual([]); + }); + + it.each(detected)("flags %s in %j", (label, content) => { + expect(detectSecrets(content).patterns).toContain(label); + }); +}); + +describe("redactSecrets", () => { + it("leaves a git sha untouched", () => { + const content = "commit a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"; + expect(redactSecrets(content).redacted).toBe(content); + }); + + it("redacts a detected credential", () => { + expect(redactSecrets("use AKIAIOSFODNN7EXAMPLE for uploads").redacted).toBe( + "use [SECRET_REDACTED] for uploads", + ); + }); + + it("reports specific labels instead of a generic one", () => { + expect(detectSecrets("AKIAIOSFODNN7EXAMPLE").patterns).toEqual([ + "AWS Access Key", + ]); + }); + + it("keeps JSON valid by redacting only the value", () => { + expect(redactSecrets('{"password":"hunter2000!"}').redacted).toBe( + '{"password":"[SECRET_REDACTED]"}', + ); + }); + + it("redacts a quoted value containing a comma in full", () => { + expect(redactSecrets('password: "hunter,2000!"').redacted).toBe( + 'password: "[SECRET_REDACTED]"', + ); + }); + + it("redacts an unquoted value without touching the key", () => { + expect(redactSecrets("password=Tr0ub4dor3xyz").redacted).toBe( + "password=[SECRET_REDACTED]", + ); + }); +}); + +describe("secretsRule.check", () => { + it("reports detector labels, never fragments of the secret", () => { + const result = secretsRule.check("key AKIAIOSFODNN7EXAMPLE leaked", { + enabled: true, + action: "block", + }); + + expect(result.passed).toBe(false); + expect(result.matches).toEqual(["AWS Access Key"]); + expect(result.matches.join(" ")).not.toContain("AKIA"); + }); +}); diff --git a/ee/guardrails/src/rules/system/secrets.ts b/ee/guardrails/src/rules/system/secrets.ts index 824a031072..7d436d65b3 100644 --- a/ee/guardrails/src/rules/system/secrets.ts +++ b/ee/guardrails/src/rules/system/secrets.ts @@ -1,52 +1,159 @@ +import { + findMatches, + isPlaceholderSecret, + redactMatches, + shannonEntropy, +} from "./detector.js"; + +import type { Detector } from "./detector.js"; import type { SystemRule } from "@/types.js"; -const SECRET_PATTERNS = [ - // AWS keys - /\b(AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}\b/, - // AWS Secret Key - /\b[A-Za-z0-9/+=]{40}\b/, - // Generic API keys - /\b(api[_-]?key|apikey)[=:]\s*['"]?[A-Za-z0-9_-]{20,}['"]?\b/i, - // Bearer tokens - /\bBearer\s+[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/, - // JWT tokens - /\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*\b/, - // GitHub tokens - /\b(gh[pousr]_[A-Za-z0-9_]{36,}|github_pat_[A-Za-z0-9_]{22,})\b/, - // Slack tokens - /\bxox[baprs]-[0-9]{10,}-[0-9]{10,}-[a-zA-Z0-9]{24,}\b/, - // Stripe keys - /\b(sk|pk)_(test|live)_[A-Za-z0-9]{24,}\b/, - // OpenAI keys - /\bsk-[A-Za-z0-9]{48,}\b/, - // Private keys - /-----BEGIN\s+(RSA\s+)?PRIVATE\s+KEY-----/, - // Connection strings - /\b(postgres|mysql|mongodb|redis):\/\/[^\s]+:[^\s]+@[^\s]+\b/i, - // Password patterns - /\b(password|passwd|pwd)[=:]\s*['"]?[^\s'"]{8,}['"]?\b/i, +const SECRET_REPLACEMENT = "[SECRET_REDACTED]"; + +const AWS_SECRET_CONTEXT = + /(aws.{0,16}secret|secret.{0,4}access.{0,4}key|secret.{0,4}key)\W{0,8}$/i; + +/** + * Opaque 40-character blobs are the single biggest false-positive source: git + * SHAs, checksums, base64 payloads and content hashes all have that shape. + * Only report one when the surrounding text names an AWS secret, or when the + * value itself looks like a random key (mixed case + digits, high entropy, not + * a hex digest). + */ +function looksLikeAwsSecret(value: string, before: string): boolean { + if (AWS_SECRET_CONTEXT.test(before)) { + return true; + } + if (/^[0-9a-f]+$/i.test(value) || /^[0-9]+$/.test(value)) { + return false; + } + if (!/[a-z]/.test(value) || !/[A-Z]/.test(value) || !/[0-9]/.test(value)) { + return false; + } + return shannonEntropy(value) >= 4.2; +} + +/** + * `key = value` in the shapes credentials actually appear in: bare, quoted, or + * as a JSON property. Only the value is captured, so redaction replaces the + * secret and leaves the surrounding quotes and punctuation intact — replacing + * the whole match would turn `{"password":"hunter2"}` into invalid JSON. The + * quoted branches come first so a value containing a comma is captured whole. + */ +const ASSIGNED_VALUE = `["']?\\s*[=:]\\s*(?:"([^"\\n]{8,})"|'([^'\\n]{8,})'|([^\\s'",;]{8,}))`; + +const SECRET_DETECTORS: Detector[] = [ + { + id: "private_key", + label: "Private Key", + replacement: SECRET_REPLACEMENT, + pattern: + /-----BEGIN\s+(?:RSA\s+|EC\s+|OPENSSH\s+|PGP\s+)?PRIVATE\s+KEY-----/, + }, + { + id: "aws_access_key_id", + label: "AWS Access Key", + replacement: SECRET_REPLACEMENT, + pattern: /\b(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}\b/, + }, + { + id: "github_token", + label: "GitHub Token", + replacement: SECRET_REPLACEMENT, + pattern: /\b(?:gh[pousr]_[A-Za-z0-9_]{36,}|github_pat_[A-Za-z0-9_]{22,})\b/, + }, + { + id: "slack_token", + label: "Slack Token", + replacement: SECRET_REPLACEMENT, + pattern: /\bxox[baprs]-[0-9]{10,}-[0-9]{10,}-[a-zA-Z0-9]{24,}\b/, + }, + { + id: "stripe_key", + label: "Stripe Key", + replacement: SECRET_REPLACEMENT, + pattern: /\b(?:sk|pk)_(?:test|live)_[A-Za-z0-9]{24,}\b/, + }, + { + id: "openai_key", + label: "OpenAI Key", + replacement: SECRET_REPLACEMENT, + pattern: /\bsk-[A-Za-z0-9]{48,}\b/, + }, + { + id: "jwt", + label: "JWT", + replacement: SECRET_REPLACEMENT, + // Every segment must be non-empty; the previous `*` quantifiers matched + // bare words such as `eyJ..`. + pattern: /\beyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}/, + }, + { + id: "bearer_token", + label: "Bearer Token", + replacement: SECRET_REPLACEMENT, + pattern: + /\bBearer\s+[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?![A-Za-z0-9_.-])/, + }, + { + id: "connection_string", + label: "Connection String", + replacement: SECRET_REPLACEMENT, + pattern: + /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp):\/\/[^\s:@/]+:[^\s:@/]+@[^\s]+/i, + validate: (value) => !isPlaceholderSecret(value.split(":")[2] ?? ""), + }, + { + id: "aws_secret_access_key", + label: "AWS Secret Key", + replacement: SECRET_REPLACEMENT, + pattern: /\b[A-Za-z0-9/+=]{40}\b/, + validate: (value, before) => looksLikeAwsSecret(value, before), + }, + { + id: "api_key", + label: "API Key", + replacement: SECRET_REPLACEMENT, + pattern: new RegExp( + `\\b(?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token|client[_-]?secret)${ASSIGNED_VALUE}`, + "i", + ), + redactGroup: true, + validate: (value) => + !isPlaceholderSecret(value) && shannonEntropy(value) >= 3, + }, + { + id: "password", + label: "Password", + replacement: SECRET_REPLACEMENT, + // Also matches the JSON shape `"password": "hunter2"`, which the previous + // pattern missed because of the quote before the colon. + pattern: new RegExp(`\\b(?:password|passwd|pwd)${ASSIGNED_VALUE}`, "i"), + redactGroup: true, + validate: (value) => !isPlaceholderSecret(value), + }, ]; +export function detectSecrets(content: string): { + patterns: string[]; + matches: string[]; +} { + const found = findMatches(content, SECRET_DETECTORS); + return { + patterns: found.map((m) => m.detector.label), + matches: found.map((m) => m.value), + }; +} + export function redactSecrets(content: string): { redacted: string; patterns: string[]; } { - let redacted = content; - const patterns: string[] = []; - - for (const pattern of SECRET_PATTERNS) { - const globalPattern = new RegExp( - pattern.source, - pattern.global ? pattern.flags : pattern.flags + "g", - ); - const matches = redacted.match(globalPattern); - if (matches) { - patterns.push(...matches.map(() => "Secret")); - redacted = redacted.replace(globalPattern, "[SECRET_REDACTED]"); - } - } - - return { redacted, patterns }; + const found = findMatches(content, SECRET_DETECTORS); + return { + redacted: redactMatches(content, found), + patterns: found.map((m) => m.detector.label), + }; } export const secretsRule: SystemRule = { @@ -60,22 +167,14 @@ export const secretsRule: SystemRule = { return { passed: true, matches: [] }; } - const matches: string[] = []; - for (const pattern of SECRET_PATTERNS) { - const match = content.match(pattern); - if (match) { - // Truncate the match to avoid exposing the full secret - const truncated = - match[0].length > 20 - ? match[0].substring(0, 10) + "..." + match[0].slice(-5) - : match[0]; - matches.push(truncated); - } - } + // Report the detector labels, never the matched values: the engine + // persists these on the violation record, and a head/tail truncation + // still leaks 15 characters of a 40-character key. + const { patterns } = detectSecrets(content); return { - passed: matches.length === 0, - matches, + passed: patterns.length === 0, + matches: patterns, }; }, };