mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-30 20:26:09 +09:00
fix(continuous-learning-v2): redact tokens after JSON escapes and truncated DSNs
Dict tool I/O is JSON-encoded before scrubbing, so a newline before a bare GitHub token or AWS key id became a literal \n and the leading \b never matched. Replace it with a lookbehind that also accepts a preceding JSON escape (\b \f \n \r \t or \uXXXX). Capture truncation (5000 chars, 2000 in the parse-error fallback) can cut a DSN right before its '@', which defeated the (?=@) password lookahead. Let the password run to end of string, except a bare trailing host:port. Applied to both matcher copies. Regression tests cover structured output with tokens after escaped whitespace and DSNs cut before '@' on the string, structured input/output and fallback paths. Refresh registryDigest. Signed-off-by: Wen <jwcastillo@gmail.com>
This commit is contained in:
2 files changed
+63
-7
No files matched your search
@@ -281,10 +281,13 @@ _SECRET_RE = re.compile(
|
||||
# end of the truncated text), GitHub tokens, AWS key IDs, and DSN passwords
|
||||
# (scheme://user:PASSWORD@host keeps scheme and user). Each branch is anchored
|
||||
# on a literal prefix and uses bounded or non-overlapping classes (#2278).
|
||||
# Tokens may follow a JSON escape (\n, \t, \uXXXX) since dict I/O is encoded
|
||||
# before scrubbing; a DSN cut by truncation before its "@" ends at \Z,
|
||||
# except a bare trailing host:port such as http://localhost:3000 (#3568).
|
||||
_SECRET_VALUE_RE = re.compile(
|
||||
r"-----BEGIN[A-Z ]{0,40}PRIVATE KEY-----[\s\S]*?(?:-----END[A-Z ]{0,40}PRIVATE KEY-----|\Z)"
|
||||
r"|\b(?:gh[pousr]_[A-Za-z0-9]{20,255}|github_pat_[A-Za-z0-9_]{20,255}|(?:AKIA|ASIA)[A-Z0-9]{16})\b"
|
||||
r"""|(?<=://)([^\s:/@"\\]{1,256}:)[^\s@/"\\]{1,256}(?=@)"""
|
||||
r"|(?:(?<![A-Za-z0-9_])|(?<=\\[bfnrt])|(?<=\\u[0-9a-fA-F]{4}))(?:gh[pousr]_[A-Za-z0-9]{20,255}|github_pat_[A-Za-z0-9_]{20,255}|(?:AKIA|ASIA)[A-Z0-9]{16})\b"
|
||||
r"""|(?<=://)([^\s:/@"\\]{1,256}:)(?!\d{1,5}\Z)[^\s@/"\\]{1,256}(?=@|\Z)"""
|
||||
)
|
||||
|
||||
import signal
|
||||
@@ -362,10 +365,13 @@ _SECRET_RE = re.compile(
|
||||
# end of the truncated text), GitHub tokens, AWS key IDs, and DSN passwords
|
||||
# (scheme://user:PASSWORD@host keeps scheme and user). Each branch is anchored
|
||||
# on a literal prefix and uses bounded or non-overlapping classes (#2278).
|
||||
# Tokens may follow a JSON escape (\n, \t, \uXXXX) since dict I/O is encoded
|
||||
# before scrubbing; a DSN cut by truncation before its "@" ends at \Z,
|
||||
# except a bare trailing host:port such as http://localhost:3000 (#3568).
|
||||
_SECRET_VALUE_RE = re.compile(
|
||||
r"-----BEGIN[A-Z ]{0,40}PRIVATE KEY-----[\s\S]*?(?:-----END[A-Z ]{0,40}PRIVATE KEY-----|\Z)"
|
||||
r"|\b(?:gh[pousr]_[A-Za-z0-9]{20,255}|github_pat_[A-Za-z0-9_]{20,255}|(?:AKIA|ASIA)[A-Z0-9]{16})\b"
|
||||
r"""|(?<=://)([^\s:/@"\\]{1,256}:)[^\s@/"\\]{1,256}(?=@)"""
|
||||
r"|(?:(?<![A-Za-z0-9_])|(?<=\\[bfnrt])|(?<=\\u[0-9a-fA-F]{4}))(?:gh[pousr]_[A-Za-z0-9]{20,255}|github_pat_[A-Za-z0-9_]{20,255}|(?:AKIA|ASIA)[A-Z0-9]{16})\b"
|
||||
r"""|(?<=://)([^\s:/@"\\]{1,256}:)(?!\d{1,5}\Z)[^\s@/"\\]{1,256}(?=@|\Z)"""
|
||||
)
|
||||
|
||||
def scrub(val):
|
||||
|
||||
@@ -16,13 +16,14 @@ function test(name, fn) {
|
||||
catch (error) { console.log(` FAIL ${name}: ${error.message}`); failed += 1; }
|
||||
}
|
||||
|
||||
function capture(phase, input) {
|
||||
function capture(phase, input, expectedEvent) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-observe-redaction-'));
|
||||
try {
|
||||
const data = path.join(root, 'data');
|
||||
const result = spawnSync(process.execPath, [runner, `${phase}:observe`,
|
||||
'scripts/hooks/observe-runner.js', 'standard,strict'], {
|
||||
input: JSON.stringify({ cwd: root, session_id: 'redaction-fixture', ...input }),
|
||||
input: typeof input === 'string' ? input
|
||||
: JSON.stringify({ cwd: root, session_id: 'redaction-fixture', ...input }),
|
||||
cwd: root, encoding: 'utf8', timeout: 12000,
|
||||
env: { ...process.env, HOME: root, USERPROFILE: root,
|
||||
CLV2_HOMUNCULUS_DIR: data, CLAUDE_CODE_ENTRYPOINT: 'cli',
|
||||
@@ -33,7 +34,8 @@ function capture(phase, input) {
|
||||
assert.doesNotMatch(result.stderr, /runner failed|timed out/i);
|
||||
const records = fs.readFileSync(path.join(data, 'observations.jsonl'), 'utf8');
|
||||
assert.equal(records.trim().split('\n').length, 1);
|
||||
assert.equal(JSON.parse(records).event, phase === 'pre' ? 'tool_start' : 'tool_complete');
|
||||
assert.equal(JSON.parse(records).event,
|
||||
expectedEvent || (phase === 'pre' ? 'tool_start' : 'tool_complete'));
|
||||
return records;
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
@@ -82,6 +84,48 @@ if (process.platform === 'win32') {
|
||||
});
|
||||
}
|
||||
|
||||
// Structured output is JSON-encoded before scrubbing, so a newline before a
|
||||
// bare token reaches the matcher as a literal backslash-n (greptile, #3568).
|
||||
for (const [label, content, secret] of [
|
||||
['GitHub classic token after newline', `log line\n${'ghp_'}CANARY${'0'.repeat(30)}`,
|
||||
`CANARY${'0'.repeat(30)}`],
|
||||
['GitHub fine-grained token after tab', `col\t${'github_pat_'}CANARY_${'1'.repeat(40)}`,
|
||||
`CANARY_${'1'.repeat(40)}`],
|
||||
['AWS access key id after CRLF', `id:\r\n${'AKIA'}CANARY0EXAMPLE00`, 'CANARY0EXAMPLE00'],
|
||||
['AWS session key id after newline', `id:\n${'ASIA'}CANARY0EXAMPLE00`, 'CANARY0EXAMPLE00']
|
||||
]) {
|
||||
test(`redacts ${label} in structured tool output`, () => {
|
||||
const records = capture('post', { tool_name: 'Read',
|
||||
tool_input: { file_path: '/tmp/example.js' }, tool_response: { content } });
|
||||
assert.ok(!records.includes(secret), 'seeded credential persisted');
|
||||
assert.ok(records.includes('[REDACTED]'));
|
||||
});
|
||||
}
|
||||
|
||||
// Capture truncation (5000 chars, 2000 in the parse-error fallback) can cut a
|
||||
// DSN right before its '@'; the password must still be redacted (#3568).
|
||||
const cutSecret = 'CANARYcutPassw0rd';
|
||||
const dsnCutAt = (offset) => `${'a'.repeat(offset)} postgres://app:${cutSecret}@db.internal/app`;
|
||||
const dsnPad = (atIndex) => atIndex - ' postgres://app:'.length - cutSecret.length;
|
||||
for (const [label, phase, input, expectedEvent] of [
|
||||
['string tool output', 'post', { tool_name: 'Bash', tool_input: { command: 'env' },
|
||||
tool_response: dsnCutAt(dsnPad(5000)) }],
|
||||
// json.dumps prefixes '{"content": "' (13 chars) before the value.
|
||||
['structured tool output', 'post', { tool_name: 'Read', tool_input: { file_path: '/tmp/x' },
|
||||
tool_response: { content: dsnCutAt(dsnPad(5000 - 13)) } }],
|
||||
['structured tool input', 'pre', { tool_name: 'Write',
|
||||
tool_input: { content: dsnCutAt(dsnPad(5000 - 13)) } }],
|
||||
// A top-level array is valid JSON but not a hook payload: parse-error
|
||||
// fallback, which persists the first 2000 raw chars ('["' prefix).
|
||||
['parse-error fallback', 'post', JSON.stringify([dsnCutAt(dsnPad(2000 - 2))]), 'parse_error']
|
||||
]) {
|
||||
test(`redacts DSN password truncated before '@' in ${label}`, () => {
|
||||
const records = capture(phase, input, expectedEvent);
|
||||
assert.ok(!records.includes(cutSecret), 'truncated DSN password persisted');
|
||||
assert.ok(records.includes('postgres://app:[REDACTED]'));
|
||||
});
|
||||
}
|
||||
|
||||
// Ordinary code, URLs without credentials and SSH remotes stay readable.
|
||||
const benign = [
|
||||
'const tokenizer = new Tokenizer(config);',
|
||||
@@ -98,6 +142,12 @@ if (process.platform === 'win32') {
|
||||
for (const line of benign) assert.ok(records.includes(line), `benign text altered: ${line}`);
|
||||
assert.ok(!records.includes('[REDACTED]'));
|
||||
});
|
||||
test('keeps a trailing host:port in string output unredacted', () => {
|
||||
const records = capture('post', { tool_name: 'Bash', tool_input: { command: 'npm run dev' },
|
||||
tool_response: 'listening on http://localhost:3000' });
|
||||
assert.ok(records.includes('http://localhost:3000'));
|
||||
assert.ok(!records.includes('[REDACTED]'));
|
||||
});
|
||||
}
|
||||
console.log(`Passed: ${passed}`);
|
||||
console.log(`Failed: ${failed}`);
|
||||
|
||||
Reference in new issue
Block a user