diff --git a/.gitleaks.toml b/.gitleaks.toml index 7b3b3660e..2c64835c7 100644 --- a/.gitleaks.toml +++ b/.gitleaks.toml @@ -24,6 +24,13 @@ targetRules = ["curl-auth-user"] regexes = ['''^["']admin:quoted-user-password["']$'''] paths = ['''^tests/tier3/test_judge_contracts\.py$'''] +[[allowlists]] +description = "Synthetic JSON-escaped-quote curl credential placeholder used by judge evidence redaction tests" +condition = "AND" +targetRules = ["curl-auth-user"] +regexes = ['''^"admin:\{_QUOTED_SECRET\}"$'''] +paths = ['''^tests/tier3/test_judge_contracts\.py$'''] + [[allowlists]] description = "Synthetic NVIDIA Build token used by streaming redaction tests" condition = "AND" diff --git a/CHANGELOG.md b/CHANGELOG.md index ce9658ba1..71ddf37f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -258,6 +258,22 @@ All notable changes to SkillEvaluator are documented in this file. user-request section when it is set below 2,000, and that a check budget too small to hold the final response beside some tool history is logged as a warning rather than quietly raised — lower the final-response limit with it. +- `judge_attempts.json` now masks `Cookie` header values, credential flag values + (`--token`, `--password`, `-u user:password`, `--cookie`) and keys such as + `sk-proj-...` that start a line in JSON-escaped text, as in RAGAS prompts and + replies. A line break there is the two characters `\n`, and these values were + saved in clear after it or after an escaped tab (`\t`). That includes the + value on a line whose flag or header name was masked together with an unquoted + credential value that ends the line before and reads on through the escape + (`--password ...\n--token ...`). Only that value is masked; other copies of it + in the text stay as they were. Judge and security finding evidence also masks + a double-quoted `-u user:password`, MySQL `-p` or `.netrc` password value, and + the value in an argv list such as `["tool", "--password", "..."]`, when JSON + escapes the quotes (`\"...\"`), as in the tool-call arguments every judge + prompt holds; these were saved in clear. + A RAGAS `replied` entry for a reply with no text and no tool call, such as a + refusal or a content-filter stop, now saves the whole reply body instead of an + empty reply. - Code Risk Analysis reports Semgrep file-level parse errors as one partial-scan error that names up to 20 unparsed files, relative to the skill and with the line of the first error, instead of the first three truncated messages. The diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx index 0cc978c4c..8c59754f7 100644 --- a/docs/tier3-live-evaluation.mdx +++ b/docs/tier3-live-evaluation.mdx @@ -1379,21 +1379,27 @@ the case is judged and scored normally. truncated reply, the LLM attempts keep their own status (`rejected`, or `error` if the retry failed in transport), and an `accepted` `salvage` entry, numbered like the truncated attempt, holds the rebuilt results. - When the RAGAS goal scorer runs, each request it sends is saved as a - `ragas` entry with its messages as the prompt and the model named in the - request: `replied` with the judge's reply, which is the text or the - tool-call arguments RAGAS parses, or `error` with the HTTP status and body, - or with the reason the reply was not received. A request that fails before - any response arrives, such as a refused connection, saves no entry of its - own. A last `ragas` entry is `accepted` with the score RAGAS computed, or - `error` with the reason the prompt judge ran instead. Only that last entry - counts toward `--max-judge-calls`; the request entries do not. - Configured credentials, common key shapes, URL userinfo, `Authorization`, - API-key, token and `Cookie` header values, and credential flag values - (`--token`, `--password`, `curl -u user:password`) are masked, and long - prompts and replies are shortened. The prompts contain the task question, - expected answer, and agent evidence. Pass `--harbor-keep-jobs` to keep the - Harbor trial directories that hold this file. + When the RAGAS goal scorer runs, each request it sends is saved as a `ragas` + entry with its messages as the prompt and the model named in the request. A + `replied` entry holds the judge's reply: the text or the tool-call arguments + RAGAS parses, or the whole reply body when it has neither, such as a refusal + or a content-filter stop. An `error` entry holds the HTTP status and body, + or the reason the reply was not received. A request that fails before any + response arrives, such as a refused connection, saves no entry of its own. A + last `ragas` entry is `accepted` with the score RAGAS computed, or `error` + with the reason the prompt judge ran instead. Only that last entry counts + toward `--max-judge-calls`; the request entries do not. Configured + credentials, common key shapes, URL userinfo, `Authorization`, API-key, + token and `Cookie` header values, and credential flag values (`--token`, + `--password`, `curl -u user:password`) are masked, also at the start of a + line in JSON-escaped text such as RAGAS prompts, where a line break is the + two characters `\n`, and inside JSON-escaped quotes (`-u \"user:password\"`), + as in tool-call arguments. That includes a value whose flag or header name + was masked together with an unquoted credential value that ends the line + before (`--password ...\n--token ...`). Long prompts and replies are + shortened. The prompts contain the task question, expected answer, and agent + evidence. Pass `--harbor-keep-jobs` to keep the Harbor trial directories that + hold this file. - **Reasoning models.** GPT-5 and GPT-6 judges get no `temperature` and at least 32,768 output tokens, because reasoning tokens count against the limit; other judges get 16,384. GPT-6 judges and Claude 5.5 or later judges diff --git a/src/skillevaluator/tier3/eval_core/checks.py b/src/skillevaluator/tier3/eval_core/checks.py index fdfe623b7..fe0695f8b 100644 --- a/src/skillevaluator/tier3/eval_core/checks.py +++ b/src/skillevaluator/tier3/eval_core/checks.py @@ -3354,10 +3354,16 @@ def _security_finding( # value, although its marker holds spaces. A word never starts at a shell # operator: in "git config --get github.token | curl ..." or "gh auth login # --with-token < token.txt" the flag or key has no value on the command line. +# A double-quoted value whose quotes are JSON-escaped (\"VALUE\"), as a shell +# string reads in tool-call arguments and other JSON text, ends at the escaped +# closing quote or the end of the line. +_FINDING_EVIDENCE_ESCAPED_QUOTED_VALUE = r"\\\"(?:[^\"\\\r\n]|\\(?!\"))*(?:\\\")?" _FINDING_EVIDENCE_FLAG_VALUE = ( "(?:" + _FINDING_EVIDENCE_PRIVATE_KEY_MARKER - + r"|\\\"(?:[^\"\\\r\n]|\\(?!\"))*(?:\\\")?|\"(?:\\.|[^\"\\\r\n])*\"?|'[^'\r\n]*'?|(?![|&;<>])(?:\\.|[^\s'\"`\\])+)" + + "|" + + _FINDING_EVIDENCE_ESCAPED_QUOTED_VALUE + + r"|\"(?:\\.|[^\"\\\r\n])*\"?|'[^'\r\n]*'?|(?![|&;<>])(?:\\.|[^\s'\"`\\])+)" ) # Any long flag whose name holds a credential word ("--password", "--db-password", # "--client-secret", "--github-token", "--oauth2-bearer", "--cookie"), and the @@ -3385,14 +3391,16 @@ def _security_finding( # "://" is a URL ("pip install -U git+https://..."), whose userinfo is already # masked, one whose first colon starts a "/" path is a remote path ("rsync # -u host:/data"), and a "+" with a "%" conversion before the first colon is -# a date format ("date -u +%H:%M:%S"); "-u +admin:VALUE" is still masked. -_FINDING_EVIDENCE_DATE_FORMAT = r"[\"']?\+[^\s'\"`:]*%" +# a date format ("date -u +%H:%M:%S"); "-u +admin:VALUE" is still masked. A +# quoted value may have JSON-escaped quotes (-u \"user:password\"). +_FINDING_EVIDENCE_DATE_FORMAT = r"(?:\\?[\"'])?\+[^\s'\"`:]*%" _FINDING_EVIDENCE_DATE_FORMAT_RE = re.compile(_FINDING_EVIDENCE_DATE_FORMAT) _FINDING_EVIDENCE_USER_FLAG_RE = re.compile( r"((?]{0,128}/s?bin/)?" r"(?:mysql|mysqldump|mysqladmin|mysqlimport|mysqlshow|mysqlcheck|mariadb|mariadb-dump)(?=[ \t])" - r"[^|;&\r\n]{0,256}?[ \t]-p)(?!ath\b|erm\b|rint|rune\b)(?:\"(?:\\.|[^\"\\\r\n])*\"?|'[^'\r\n]*'?|[^\s'\"`|;&]+)" + r"[^|;&\r\n]{0,256}?[ \t]-p)(?!ath\b|erm\b|rint|rune\b)(?:" + + _FINDING_EVIDENCE_ESCAPED_QUOTED_VALUE + + r"|\"(?:\\.|[^\"\\\r\n])*\"?|'[^'\r\n]*'?|[^\s'\"`|;&]+)" ) # "aws configure set aws_secret_access_key VALUE" and a .netrc entry # ("machine HOST login USER password VALUE"). A .netrc entry may span lines, @@ -3451,7 +3461,9 @@ def _security_finding( + _FINDING_EVIDENCE_NETRC_SEPARATOR + "password" + _FINDING_EVIDENCE_NETRC_SEPARATOR - + r")(?:\"(?:\\.|[^\"\\\r\n])*\"?|'[^'\r\n]*'?|" + + r")(?:" + + _FINDING_EVIDENCE_ESCAPED_QUOTED_VALUE + + r"|\"(?:\\.|[^\"\\\r\n])*\"?|'[^'\r\n]*'?|" + _FINDING_EVIDENCE_NETRC_WORD + r"(?:[ \t]+(?!(?:machine|login|account|password|macdef|default)\b)" + _FINDING_EVIDENCE_NETRC_VALUE_WORD @@ -3470,19 +3482,52 @@ def _security_finding( # "-path", "-perm", "-print" and "-prune" are kept. An attached # "-uUSER:PASSWORD" element is masked by the -u rule below. Each element may # sit on its own line, as a formatter writes a long list, so up to 64 spaces -# and line breaks may follow the comma. +# and line breaks may follow the comma. In JSON text, such as tool-call +# arguments, the quotes are escaped (\"--password\", \"VALUE\") and a line +# break is the two characters "\n". An attached "-pVALUE" element opens at the +# start of a backslash run and closes with the same run and quote, so a bare +# \"-p\" element (mkdir -p, a prompting mysql -p) does not read the backslashes +# of its closing quote as a value. An element escaped again (\\\"-pVALUE\\\"), +# as when a RAGAS request repeats a tool call's JSON arguments as JSON, is +# masked with its escapes intact. +_FINDING_EVIDENCE_ARGV_QUOTE = r"\\?[\"']" +_FINDING_EVIDENCE_ARGV_SPACE = r"(?:\s|\\[nrt]){0,64}" _FINDING_EVIDENCE_ARGV_FLAG_RE = re.compile( - r"([\"'])(" + _FINDING_EVIDENCE_CREDENTIAL_FLAG_NAME + r"|-[pub])\1[ \t]*,\s{0,64}(?=[\"'][^-\"'])", + r"(" + + _FINDING_EVIDENCE_ARGV_QUOTE + + r")(" + + _FINDING_EVIDENCE_CREDENTIAL_FLAG_NAME + + r"|-[pub])\1[ \t]*," + + _FINDING_EVIDENCE_ARGV_SPACE + + r"(?=" + + _FINDING_EVIDENCE_ARGV_QUOTE + + r"[^-\"'])", re.IGNORECASE, ) -_FINDING_EVIDENCE_ARGV_VALUE_RE = re.compile(r"\"(?:\\.|[^\"\\\r\n])*\"?|'[^'\r\n]*'?") -_FINDING_EVIDENCE_ARGV_LOGIN_RE = re.compile(r"[\"']login[\"'][ \t]*,") -_FINDING_EVIDENCE_ARGV_SSHPASS_RE = re.compile(r"[\"'](?:[^\s'\"]{0,128}/)?sshpass[\"'][ \t]*,\s{0,64}$") +_FINDING_EVIDENCE_ARGV_VALUE_RE = re.compile( + _FINDING_EVIDENCE_ESCAPED_QUOTED_VALUE + r"|\"(?:\\.|[^\"\\\r\n])*\"?|'[^'\r\n]*'?" +) +_FINDING_EVIDENCE_ARGV_LOGIN_RE = re.compile( + _FINDING_EVIDENCE_ARGV_QUOTE + "login" + _FINDING_EVIDENCE_ARGV_QUOTE + r"[ \t]*," +) +_FINDING_EVIDENCE_ARGV_SSHPASS_RE = re.compile( + _FINDING_EVIDENCE_ARGV_QUOTE + + r"(?:[^\s'\"]{0,128}/)?sshpass" + + _FINDING_EVIDENCE_ARGV_QUOTE + + r"[ \t]*," + + _FINDING_EVIDENCE_ARGV_SPACE + + "$" +) _FINDING_EVIDENCE_ARGV_MYSQL_RE = re.compile( - r"[\"'](?:[^\s'\"]{0,128}/s?bin/)?" - r"(?:mysql|mysqldump|mysqladmin|mysqlimport|mysqlshow|mysqlcheck|mariadb|mariadb-dump)[\"'][ \t]*," + _FINDING_EVIDENCE_ARGV_QUOTE + + r"(?:[^\s'\"]{0,128}/s?bin/)?" + + r"(?:mysql|mysqldump|mysqladmin|mysqlimport|mysqlshow|mysqlcheck|mariadb|mariadb-dump)" + + _FINDING_EVIDENCE_ARGV_QUOTE + + r"[ \t]*," +) +_FINDING_EVIDENCE_ARGV_ATTACHED_PASSWORD_RE = re.compile( + r"(?"). _FINDING_EVIDENCE_AUTH_SCHEME = r"(?:(?:bearer|basic|token|digest)[ \t]+)?" diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py index 59df0d733..b3d76a5e3 100644 --- a/src/skillevaluator/tier3/harbor/templates/eval.py +++ b/src/skillevaluator/tier3/harbor/templates/eval.py @@ -2843,17 +2843,177 @@ def _judge_retry_feedback(problem): ) -def _redact_judge_evidence(text): - """Mask credentials in a judge prompt, reply, or problem before it is saved.""" +# RAGAS writes its input into the prompt as JSON, and tool-call arguments are +# JSON, so a line break or tab in that text arrives as the two characters "\n", +# "\r" or "\t". A header, flag or key that starts a line there follows the +# letter of the escape, where patterns that need a line start, a space or a +# word boundary before it do not match. So once the whole text is masked, the +# text between these escapes is masked again as lines of their own. +_JUDGE_EVIDENCE_ESCAPE_RE = re.compile(r"(\\[nrt])") + + +def _mask_judge_evidence_text(text): + """Mask credentials in *text* read as one piece.""" # Share finding credential semantics without imposing the finding scanner's # 2,000-character input budget on the longer judge prompt and reply budgets. - redacted = _shared_checks._mask_finding_evidence_credentials(str(text), preserve_header_format=True) + redacted = _shared_checks._mask_finding_evidence_credentials(text, preserve_header_format=True) redacted = _redact_configured_credentials(_redact_evidence_text(redacted)) for pattern in _SECRET_PATTERNS: redacted = pattern.sub("", redacted) return redacted +def _mask_judge_evidence_line(text): + """Mask credentials in the text between two escapes, which is not trimmed.""" + redacted = _shared_checks._mask_finding_evidence_credentials(text, preserve_header_format=True) + redacted = redact_secrets_in_log_line(redacted) + for pattern in _SECRET_PATTERNS: + redacted = pattern.sub("", redacted) + return redacted + + +# The markers the line pass writes in place of a value. The JWT pattern writes +# "jwt-" before its marker, and markers next to each other are read as one. +_JUDGE_EVIDENCE_LINE_MARKERS_RE = re.compile( + r"(?:(?:jwt-)?|" + re.escape(_shared_checks._FINDING_EVIDENCE_PRIVATE_KEY_MARKER) + r")+" +) +# An unquoted value ends at whitespace, a quote, a backtick or a shell +# operator, unless a backslash escapes it. +_JUDGE_EVIDENCE_VALUE_END_RE = re.compile(r"[\s'\"`;|&()<>]") +# The text after a marker runs to the next escape or marker. +_JUDGE_EVIDENCE_SITE_END_RE = re.compile( + _JUDGE_EVIDENCE_ESCAPE_RE.pattern + "|" + _JUDGE_EVIDENCE_LINE_MARKERS_RE.pattern +) + + +def _judge_evidence_line_value_spans(text, masked): + """Return *text* as the line pass read it, and the spans of the values it replaced there to write *masked*. + + The line pass only replaces values with markers, so the text between two + markers is found in *text* in order, and what lies between is a value. + """ + # The shared masker reads the text without its shell line continuations. + text = _shared_checks._LINE_CONTINUATION_RE.sub("", text) + kept = _JUDGE_EVIDENCE_LINE_MARKERS_RE.split(masked) + start = len(kept[0]) + end = len(text) - len(kept[-1]) + if len(kept) == 1 or start > end or not text.startswith(kept[0]) or not text.endswith(kept[-1]): + return text, [] + spans = [] + for between in kept[1:-1]: + found = text.find(between, start, end) + if found < 0: + return text, spans + spans.append((start, found)) + start = found + len(between) + spans.append((start, end)) + return text, spans + + +def _judge_evidence_value_sites(lines, mask_line): + """Map the text that each of *lines* can leave after a marker to the spans of the values to mask in it. + + When an unquoted value that ends the line before reads on into a line, + it stops at whitespace, a quote, a backtick or a shell operator. So the + text left after its marker is the rest of the line from one of those + characters, up to the next value that is masked there, or to the line end. + """ + sites = {} + for line in dict.fromkeys(lines): + masked = mask_line(line) if line else line + if masked == line: + continue + line, spans = _judge_evidence_line_value_spans(line, masked) + # A backslash that ends a value is left in place, as it is usually + # half of an escaped backslash: a line break escaped twice is "\\n", + # and the line ends before its "\n". + spans = [(start, start + len(line[start:end].rstrip("\\"))) for start, end in spans] + spans = [ + (start, end) + for start, end in spans + if end > start and "= stop] + if not following: + continue + rest = line[stop:] + if len(following) > 1: + sites.setdefault(rest[: following[1][0]], set()).add(following[0]) + sites.setdefault(rest, set()).update(following) + return sites + + +def _mask_judge_evidence_value_sites(text, sites): + """Mask the values of each text in *sites* that *text* holds between a marker and the next escape or marker.""" + spans = [] + after = None + for found in _JUDGE_EVIDENCE_SITE_END_RE.finditer(text): + if after is not None: + spans.extend((after + start, after + end) for start, end in sites.get(text[after : found.start()], ())) + after = None if found.group(1) else found.end() + if after is not None: + spans.extend((after + start, after + end) for start, end in sites.get(text[after:], ())) + if not spans: + return text + merged = [] + for start, end in sorted(spans): + if merged and start <= merged[-1][1]: + merged[-1][1] = max(merged[-1][1], end) + else: + merged.append([start, end]) + parts = [] + pos = 0 + for start, end in merged: + parts.extend((text[pos:start], "")) + pos = end + parts.append(text[pos:]) + return "".join(parts) + + +def _redact_judge_evidence(text): + """Mask credentials in a judge prompt, reply, or problem before it is saved.""" + text = str(text) + # The whole text is masked first, so a form that runs over an escape (a + # private key block, a continued or quoted value, a value that holds "\n" + # or "\u00e4") is masked whole before the text is split at the escapes. + redacted = _mask_judge_evidence_text(text) + masked_lines = {} + + def mask_line(line): + if line not in masked_lines: + masked_lines[line] = _mask_judge_evidence_line(line) + return masked_lines[line] + + parts = _JUDGE_EVIDENCE_ESCAPE_RE.split(redacted) + if len(parts) > 1: + # Text and escapes alternate. + parts[::2] = [mask_line(part) if part else part for part in parts[::2]] + redacted = "".join(parts) + lines = _JUDGE_EVIDENCE_ESCAPE_RE.split(text)[::2] + if len(lines) == 1: + return redacted + # An unquoted value at the end of a line reads on through the escape, so + # the whole pass can mask the name that starts the next line with it: + # "--password A\n--token B" becomes "--password B", where B no + # longer follows a name. The lines of the original text still hold the + # name, so a value the line pass masks on such a line is masked where the + # whole pass left it: in the rest of that line, which follows a marker. + # Other copies of the value are left as the whole pass left them. + sites = _judge_evidence_value_sites(lines[1:], mask_line) + return _mask_judge_evidence_value_sites(redacted, sites) if sites else redacted + + def _verifier_output_dir(): """Directory that receives skill_evaluator_reward.json (see write_reward_outputs).""" if ( @@ -3270,14 +3430,20 @@ def _ragas_request_text(body): def _ragas_reply_text(body): - """Return the judge's answer in one chat-completions reply: its text, or the tool-call arguments RAGAS parses.""" + """Return the judge's answer in one chat-completions reply: its text, or the tool-call arguments RAGAS parses. + + A reply with neither, such as a refusal or a content-filter stop, is + returned whole, so the refusal or the finish reason is kept. + """ try: message = json.loads(body)["choices"][0]["message"] - if message.get("content") or not message.get("tool_calls"): - return str(message.get("content") or "") - return "\n".join(str(call["function"]["arguments"]) for call in message["tool_calls"]) + if message.get("content"): + return str(message["content"]) + if message.get("tool_calls"): + return "\n".join(str(call["function"]["arguments"]) for call in message["tool_calls"]) except (ValueError, LookupError, TypeError, AttributeError): - return body.decode("utf-8", "replace") + pass + return body.decode("utf-8", "replace") def _record_ragas_exchange(response, problem=None): diff --git a/tests/tier3/test_judge_contracts.py b/tests/tier3/test_judge_contracts.py index 217f2ddb8..cbb4436ae 100644 --- a/tests/tier3/test_judge_contracts.py +++ b/tests/tier3/test_judge_contracts.py @@ -1107,6 +1107,285 @@ def test_judge_evidence_masks_json_escaped_tool_call_headers(command: str, secre assert "" in redacted +# RAGAS writes the agent's messages into its prompt as JSON, and tool-call +# arguments are JSON, so a line that starts with a credential follows an +# escaped "\n" (or "\r\n", or "\n\t") there, once or twice escaped. +@pytest.mark.parametrize( + ("line", "secret", "kept"), + [ + pytest.param( + "Authorization: Bearer bbbbbbbbbbbb", "bbbbbbbbbbbb", "Authorization: Bearer ", id="authorization" + ), + pytest.param( + 'Authorization: Digest username="u", response="dddddddddddd"', + "dddddddddddd", + "Authorization: Digest ", + id="authorization-digest", + ), + pytest.param("Cookie: session=cccccccccccc", "cccccccccccc", "Cookie: ", id="cookie"), + pytest.param("Api-Key: kkkkkkkkkkkk", "kkkkkkkkkkkk", "Api-Key: ", id="api-key"), + pytest.param("--token tttttttttttt", "tttttttttttt", "--token ", id="token-flag"), + pytest.param("--password pppppppppppp", "pppppppppppp", "--password ", id="password-flag"), + pytest.param("-token tttttttttttt", "tttttttttttt", "-token ", id="short-token-flag"), + pytest.param("-u uuuu:pppppppppppp", "pppppppppppp", "-u ", id="user-flag"), + pytest.param("--cookie session=cccccccccccc", "cccccccccccc", "--cookie ", id="cookie-flag"), + pytest.param("sk-proj-" + "a" * 24, "a" * 24, "sk-", id="openai-key"), + pytest.param("ghp_" + "g" * 36, "g" * 36, "ghp_", id="github-token"), + ], +) +@pytest.mark.parametrize("line_break", ["\n", "\r\n", "\n\t"], ids=["lf", "crlf", "lf-tab"]) +def test_judge_evidence_masks_credentials_after_json_escaped_line_breaks( + line: str, secret: str, kept: str, line_break: str +) -> None: + text = f"HTTP/1.1 200 OK{line_break}{line}{line_break}done" + assert secret not in eval_template._redact_judge_evidence(text) + + for escaped in (json.dumps({"reply": text}), json.dumps(json.dumps({"reply": text}))): + redacted = eval_template._redact_judge_evidence(escaped) + + assert secret not in redacted + assert kept in redacted + + +# json.dumps writes a tab as "\t", so in JSON a credential can follow the letter t. +@pytest.mark.parametrize( + ("text", "secret"), + [ + pytest.param("ok\tCookie: session=cccccccccccc", "cccccccccccc", id="tab-cookie"), + pytest.param("ok\t--token tttttttttttt", "tttttttttttt", id="tab-token-flag"), + pytest.param("ok\t-u uuuu:pppppppppppp", "pppppppppppp", id="tab-user-flag"), + ], +) +def test_judge_evidence_masks_credentials_after_json_escaped_tabs(text: str, secret: str) -> None: + assert secret not in eval_template._redact_judge_evidence(text) + + for escaped in (json.dumps({"reply": text}), json.dumps(json.dumps({"reply": text}))): + assert "\\t" in escaped + redacted = eval_template._redact_judge_evidence(escaped) + + assert secret not in redacted + assert "" in redacted + + +# Split so that no private key header appears in this file as one literal. +_PRIVATE_KEY = "PRIVATE " + "KEY" +_KEY_BODY_LINES = ("MIIEbodyLineOne", "MIIEbodyLineTwo") + + +# A private key block spans lines, which JSON writes as "\n" escapes. The block +# is masked whole, never only its BEGIN line. +@pytest.mark.parametrize( + "label", + [ + pytest.param(f"RSA {_PRIVATE_KEY}", id="rsa"), + pytest.param(f"EC {_PRIVATE_KEY}", id="ec"), + pytest.param(f"OPENSSH {_PRIVATE_KEY}", id="openssh"), + pytest.param(f"PGP {_PRIVATE_KEY} BLOCK", id="pgp"), + pytest.param(f"ENCRYPTED {_PRIVATE_KEY}", id="encrypted"), + pytest.param(_PRIVATE_KEY, id="pkcs8"), + ], +) +def test_judge_evidence_masks_private_key_blocks_in_json_escaped_text(label: str) -> None: + block = "\n".join((f"-----BEGIN {label}-----", *_KEY_BODY_LINES, f"-----END {label}-----")) + prompt = json.dumps({"user_input": [{"content": f"see\n{block}\nok", "type": "ai"}]}, indent=4) + + for escaped in (json.dumps({"content": block}), json.dumps(json.dumps({"content": block})), prompt): + redacted = eval_template._redact_judge_evidence(escaped) + + assert "" in redacted + assert "-----END" not in redacted + for line in _KEY_BODY_LINES: + assert line not in redacted + + +# A value may hold an escape: a quoted value a line break or tab, a password a +# non-ASCII character (written "\u00e4" by json.dumps), or a path a backslash. +# The whole value is masked in JSON escaped once or twice, and in plain text +# too, where only a real line break ends a quoted value. +@pytest.mark.parametrize( + "text", + [ + pytest.param('tool --password "a\n' + "Tail" * 3 + '" -x', id="quoted-line-break"), + pytest.param('tool --password "a\t' + "Tail" * 3 + '" -x', id="quoted-tab"), + pytest.param("mysql --password p\u00e4ss" + "Tail" * 3 + " -x", id="non-ascii-password"), + pytest.param("tool --token tok\u00e9n" + "Tail" * 3 + " -x", id="non-ascii-token"), + pytest.param("tool -u admin:p\u00e4ss" + "Tail" * 3 + " -x", id="non-ascii-user"), + pytest.param('tool --token "t\u00f6ken' + "Tail" * 3 + '" -x', id="non-ascii-quoted-token"), + pytest.param("tool --password ab\\n" + "Tail" * 3 + " -x", id="backslash-n-password"), + pytest.param("tool --token C:\\new\\" + "Tail" * 3 + " -x", id="windows-path-token"), + ], +) +def test_judge_evidence_masks_values_that_hold_escapes(text: str) -> None: + forms = [json.dumps({"command": text}), json.dumps(json.dumps({"command": text}))] + if "\n" not in text: + forms.append(text) + for form in forms: + redacted = eval_template._redact_judge_evidence(form) + + assert "Tail" not in redacted + assert " -x" in redacted + + +# A credential flag that starts a JSON-escaped line keeps its whole value +# masked, also when the value holds a non-ASCII character. +@pytest.mark.parametrize( + "text", + [ + pytest.param("--password p\u00e4ss" + "Tail" * 3 + " -h db", id="password"), + pytest.param("--token tok\u00e9n" + "Tail" * 3 + " -x", id="token"), + pytest.param("-u admin:p\u00e4ss" + "Tail" * 3 + " -x", id="user"), + pytest.param('--token "t\u00f6ken' + "Tail" * 3 + '" -x', id="quoted-token"), + ], +) +def test_judge_evidence_masks_non_ascii_values_at_json_escaped_line_starts(text: str) -> None: + for escaped in (json.dumps({"reply": f"ok\n{text}"}), json.dumps(json.dumps({"reply": f"ok\n{text}"}))): + redacted = eval_template._redact_judge_evidence(escaped) + + assert "Tail" not in redacted + assert "" in redacted + + +# Tool-call arguments reach the behavior and goal prompts as json.dumps text, +# where the line breaks of a written key file and of a continued command are +# "\n" escapes. +def test_judge_evidence_masks_multi_line_tool_call_arguments() -> None: + block = "\n".join( + (f"-----BEGIN OPENSSH {_PRIVATE_KEY}-----", *_KEY_BODY_LINES, f"-----END OPENSSH {_PRIVATE_KEY}-----") + ) + trajectory = { + "steps": [ + { + "source": "agent", + "tool_calls": [ + {"function_name": "Write", "arguments": {"file_path": "id_ed25519", "content": block}}, + {"function_name": "Bash", "arguments": {"command": "sshpass -p \\\n" + "Tail" * 3 + " ssh host"}}, + ], + }, + ] + } + summary = eval_template.build_conversation_summary(trajectory, "Set up the deploy key.") + assert _KEY_BODY_LINES[0] in summary + assert "Tail" in summary + + redacted = eval_template._redact_judge_evidence(summary) + + assert "" in redacted + assert "sshpass -p ssh host" in redacted + assert "Tail" not in redacted + for line in _KEY_BODY_LINES: + assert line not in redacted + + +_QUOTED_SECRET = "Qx7Quoted" + "Secret9" + + +# Tool-call arguments reach judge prompts as JSON, so a double-quoted shell +# value or argv element arrives with escaped quotes (\"VALUE\"). Each is masked +# there as in plain text, mid-line and at a JSON-escaped line start. +@pytest.mark.parametrize( + "text", + [ + pytest.param(f'curl -u "admin:{_QUOTED_SECRET}" https://x', id="user-flag"), + pytest.param(f'curl --user="admin:{_QUOTED_SECRET}" https://x', id="user-flag-equals"), + pytest.param(f'curl --proxy-user "admin:{_QUOTED_SECRET}" https://x', id="proxy-user-flag"), + pytest.param(f'mysql -uroot -p"{_QUOTED_SECRET}" app', id="mysql-attached-password"), + pytest.param(f'machine db login bot password "{_QUOTED_SECRET}"', id="netrc-password"), + pytest.param(f'subprocess.run(["tool", "--password", "{_QUOTED_SECRET}"])', id="argv-password"), + pytest.param(f'subprocess.run(["curl", "-u", "admin:{_QUOTED_SECRET}", url])', id="argv-user"), + pytest.param(f'subprocess.run(["docker", "login", "-u", "bot", "-p", "{_QUOTED_SECRET}"])', id="argv-login"), + pytest.param(f'subprocess.run(["sshpass", "-p", "{_QUOTED_SECRET}", "ssh", "host"])', id="argv-sshpass"), + pytest.param(f'subprocess.run(["curl", "-b", "sid={_QUOTED_SECRET}", url])', id="argv-cookie"), + pytest.param(f'subprocess.run(["mysql", "-uroot", "-p{_QUOTED_SECRET}"])', id="argv-mysql-attached"), + pytest.param(f'subprocess.run([\n "tool",\n "--token",\n "{_QUOTED_SECRET}",\n])', id="argv-per-line"), + ], +) +def test_judge_evidence_masks_json_escaped_quoted_values(text: str) -> None: + assert _QUOTED_SECRET not in eval_template._redact_judge_evidence(text) + + for escaped in (json.dumps({"command": text}), json.dumps({"reply": f"ok\n{text}"})): + assert '\\"' in escaped + redacted = eval_template._redact_judge_evidence(escaped) + + assert _QUOTED_SECRET not in redacted + assert "" in redacted + + +# An unquoted value that ends a line reads on through a JSON-escaped line +# break, so masking the whole text masks the flag or header name that starts +# the next line with it. That line's value is masked too, as in plain text, +# however short it is. +@pytest.mark.parametrize( + ("text", "second"), + [ + pytest.param("--password aaaaaaaaaaaa\n--token bbbbbbbbbbbb", "bbbbbbbbbbbb", id="password-then-token"), + pytest.param( + "-u uuuu:aaaaaaaaaaaa\nCookie: session=bbbbbbbbbbbb", "session=bbbbbbbbbbbb", id="user-then-cookie" + ), + pytest.param( + "deploy --token aaaaaaaaaaaa\nAuthorization: Bearer bbbbbbbbbbbb", + "bbbbbbbbbbbb", + id="token-then-authorization", + ), + pytest.param("sshpass -p aaaaaaaaaaaa\n--token bbbbbbbbbbbb", "bbbbbbbbbbbb", id="sshpass-then-token"), + pytest.param( + "docker login -u bot -p aaaaaaaaaaaa\nCookie: session=bbbbbbbbbbbb", + "session=bbbbbbbbbbbb", + id="login-then-cookie", + ), + pytest.param("run --password aaaaaaaaaaaa\nls\n--token bbbbbbbbbbbb", "bbbbbbbbbbbb", id="over-two-lines"), + pytest.param("--password aaaaaaaaaaaa\n--token bQ7", "bQ7", id="short-token"), + pytest.param("-u uuuu:aaaaaaaaaaaa\nCookie: s=bQ7", "s=bQ7", id="short-cookie"), + ], +) +def test_judge_evidence_masks_consecutive_credential_lines_in_json_escaped_text(text: str, second: str) -> None: + text += "\ndone" + for form in (text, json.dumps({"command": text}), json.dumps(json.dumps({"command": text}))): + redacted = eval_template._redact_judge_evidence(form) + + assert "aaaaaaaaaaaa" not in redacted + assert second not in redacted + # Only the value is masked; the rest of the text stays as it was. + assert redacted.endswith("" + form.split(second)[-1]) + + +# A value masked on one line is masked only there and where the whole text +# pass took its name. Other copies of it are text, such as a model name after +# a "tokenizer_name:" key, which the shared masker reads as a credential name. +@pytest.mark.parametrize( + ("text", "kept"), + [ + pytest.param( + "model_name: meta-llama/Llama-3.1-8B-Instruct\ntokenizer_name: meta-llama/Llama-3.1-8B-Instruct\n" + "model_name: meta-llama/Llama-3.1-8B-Instruct\nTask: fine-tune meta-llama/Llama-3.1-8B-Instruct", + ["model_name: meta-llama/Llama-3.1-8B-Instruct", "Task: fine-tune meta-llama/Llama-3.1-8B-Instruct"], + id="model-name", + ), + pytest.param( + "class Settings:\n api_key: Optional[str] = None\n name: Optional[str] = None", + ["name: Optional[str] = None"], + id="annotation", + ), + pytest.param( + "fields:\n password: required\n email: required\nAll required fields are validated.", + ["email: required", "All required fields"], + id="yaml-word", + ), + pytest.param( + "run --token $GITHUB_TOKEN\necho $GITHUB_TOKEN_FILE\ncat $GITHUB_TOKEN_FILE", + ["cat $GITHUB_TOKEN_FILE"], + id="variable-name", + ), + pytest.param("docker run -u 1000:1000 img\nchown 1000:1000 /data", ["chown 1000:1000 /data"], id="user-id"), + ], +) +def test_judge_evidence_keeps_copies_of_line_values_elsewhere(text: str, kept: list[str]) -> None: + redacted = eval_template._redact_judge_evidence(json.dumps({"content": text})) + + assert "" in redacted + for part in kept: + assert part in redacted + + @pytest.mark.parametrize( "text", [ @@ -1115,12 +1394,71 @@ def test_judge_evidence_masks_json_escaped_tool_call_headers(command: str, secre "see https://example.com/docs?a=b@c and mailto:user@example.com", "Authorization is required for this endpoint.", "curl --cookie-jar cookies.txt https://x; see the api-key rotation docs", + # JSON-escaped lines, as in RAGAS prompts and tool-call arguments. + json.dumps( + "Authorization is required.\npython -u script.py\n--token-limit 5\n\tcookie-jar ready\r\nC:\\new\\temp" + ), + json.dumps("caf\u00e9 --token-limit 5\t\u201cAuthorization is required\u201d\tpython -u script.py"), + # JSON-escaped quotes around a URL, a remote path, a date format and ordinary argv flags. + json.dumps('pip install -U "git+https://github.com/org/repo" && rsync -u "host:/data" . && date -u "+%H:%M"'), + json.dumps( + 'subprocess.run(["mkdir", "-p", "out"]); ["ssh", "-p", "2222", "host"]; ["find", ".", "-path", "x"]' + ), + json.dumps('["date", "-u", "+%H:%M"]; ["pip", "install", "-U", "git+https://github.com/org/repo"]'), + # A bare "-p" element after a MySQL client or login element, with JSON-escaped quotes. + json.dumps('subprocess.run(["mysql", "-e", "CREATE DATABASE app"]); subprocess.run(["mkdir", "-p", "data"])'), + json.dumps('subprocess.run(["mysql", "-u", "root", "-p", "appdb"])'), + json.dumps('run(["docker", "login", "--password-stdin", "-u", "bot"]); run(["git", "log", "-p"])'), + # The same with the quotes escaped twice, after a plain MySQL client element. + 'run(["mysql", "-e", "x"]); ' + + json.dumps(json.dumps('run(["mkdir", "-p", "data"]); run(["mysql", "-u", "root", "-p", "appdb"])')), ], ) def test_judge_evidence_keeps_ordinary_text(text: str) -> None: assert eval_template._redact_judge_evidence(text) == text +_PASSPHRASE_WORD = "Zq9" + "Leak" + + +# A bare \"-p\" element keeps its escaped closing quote, so a multi-word +# credential later in the same JSON string is still masked to its end. +@pytest.mark.parametrize( + "argv", + [ + pytest.param('["mysql", "-p"]', id="mysql-prompt"), + pytest.param('["docker", "login", "-u", "bot"]); run(["git", "log", "-p"]', id="git-log-after-login"), + ], +) +def test_judge_evidence_masks_passphrase_after_bare_p_element(argv: str) -> None: + text = json.dumps({"command": f"run({argv}); password: correct horse {_PASSPHRASE_WORD} staple"}) + + assert eval_template._redact_judge_evidence(text) == json.dumps({"command": f"run({argv}); password: "}) + + +_MYSQL_ARGUMENTS = json.dumps( + {"command": f'python -c \'import subprocess; subprocess.run(["mysql", "-uroot", "-p{_QUOTED_SECRET}"])\''} +) + + +# A RAGAS request that repeats a tool call writes the call's JSON arguments as +# JSON again, so an attached "-pVALUE" element there is escaped twice +# (\\\"-pVALUE\\\"). After a MySQL client element it is masked with its escapes +# intact. +@pytest.mark.parametrize( + "context", + [ + pytest.param(f'Task: run subprocess.run(["mysql", "-uroot", "-p{_QUOTED_SECRET}"]).', id="plain"), + pytest.param(f"Task: run subprocess.run(['mysql', '-uroot', '-p{_QUOTED_SECRET}']).", id="single-quoted"), + pytest.param(f"Earlier call: {_MYSQL_ARGUMENTS}", id="json-escaped"), + ], +) +def test_judge_evidence_masks_twice_escaped_attached_password(context: str) -> None: + text = f"{context}\nRepeated: {json.dumps(_MYSQL_ARGUMENTS)}" + + assert eval_template._redact_judge_evidence(text) == text.replace(_QUOTED_SECRET, "") + + def test_salvaged_behavior_score_is_saved_as_a_salvage_attempt(tmp_path: Path) -> None: verifier = _stage_verifier(tmp_path) truncated = '{"results":[{"step":1,"passed":true,"reason":"ran the script"},{"step":2,"passed":tr' diff --git a/tests/tier3/test_ragas_judge_evidence.py b/tests/tier3/test_ragas_judge_evidence.py index a1ac02630..d97c51d85 100644 --- a/tests/tier3/test_ragas_judge_evidence.py +++ b/tests/tier3/test_ragas_judge_evidence.py @@ -406,6 +406,166 @@ def test_ragas_evidence_reads_every_request_message_and_tool_call_replies(verifi assert verifier._ragas_reply_text(b"not a chat completion") == "not a chat completion" +def test_ragas_evidence_masks_credentials_at_json_escaped_line_starts( + verifier: ModuleType, monkeypatch: pytest.MonkeyPatch +) -> None: + """RAGAS writes the agent's messages into its prompt as JSON, and a JSON-mode reply quotes them as JSON too. + + Each line break in the agent's text is therefore saved escaped, as the two + characters backslash and n, before the next line's header or flag. + """ + agent_text = ( + "HTTP/1.1 200 OK\nAuthorization: Bearer bbbbbbbbbbbb\nCookie: session=cccccccccccc\n" + "--token tttttttttttt\n-u admin:pppppppppppp" + ) + prompt = "Judge whether the agent reached the goal.\ninput: " + json.dumps( + {"user_input": [{"content": agent_text, "type": "ai"}]}, indent=4 + ) + _install_ragas(monkeypatch, messages=[{"role": "user", "content": prompt}]) + received = _stub_provider(monkeypatch, [_chat_reply(json.dumps({"end_state": agent_text, "verdict": 1}))]) + + with _judge_evidence(verifier): + result = verifier.judge_goal_accuracy("question", "expected", "agent answer") + + assert (result["score"], result["method"]) == (1.0, "ragas") + assert len(received) == 1 + exchange, outcome = _attempts(verifier) + assert [exchange["status"], outcome["status"]] == ["replied", "accepted"] + for field in ("prompt", "reply"): + assert ( + "\\nAuthorization: Bearer \\nCookie: \\n--token \\n-u " + in exchange[field] + ) + saved = (verifier.VERIFIER_DIR / "judge_attempts.json").read_text(encoding="utf-8") + for secret in ("bbbbbbbbbbbb", "cccccccccccc", "tttttttttttt", "pppppppppppp"): + assert secret not in saved + + +def test_ragas_evidence_masks_consecutive_credential_lines_in_tool_calls( + verifier: ModuleType, monkeypatch: pytest.MonkeyPatch +) -> None: + """A tool call's arguments reach the RAGAS prompt and reply as JSON in JSON, so their line breaks are escaped twice. + + A flag value that ends one line must not take the next line's flag or + header name with it and leave that line's value in clear. Text that only + matches a value masked on another line stays. + """ + model = "meta-llama/Llama-3.1-8B-Instruct" + trajectory = { + "steps": [ + { + "source": "agent", + "tool_calls": [ + { + "function_name": "Write", + "arguments": { + "file_path": "deploy.flags", + "content": "--api-key aaaaaaaaaaaa\n--token bbbbbbbbbbbb\n", + }, + }, + { + "function_name": "Bash", + "arguments": {"command": "docker login -u bot -p cccccccccccc\nCookie: session=dddddddddddd"}, + }, + { + "function_name": "Write", + "arguments": { + "file_path": "config.yaml", + "content": f"tokenizer_name: {model}\nmodel_name: {model}\n", + }, + }, + ], + }, + ] + } + secrets = ("aaaaaaaaaaaa", "bbbbbbbbbbbb", "cccccccccccc", "dddddddddddd") + agent_text = verifier.build_conversation_summary(trajectory, "Set up the deploy flags.") + assert all(secret in agent_text for secret in secrets) + prompt = "Judge whether the agent reached the goal.\ninput: " + json.dumps( + {"user_input": [{"content": agent_text, "type": "ai"}]}, indent=4 + ) + _install_ragas(monkeypatch, messages=[{"role": "user", "content": prompt}]) + received = _stub_provider(monkeypatch, [_chat_reply(json.dumps({"end_state": agent_text, "verdict": 1}))]) + + with _judge_evidence(verifier): + result = verifier.judge_goal_accuracy("question", "expected", "agent answer") + + assert (result["score"], result["method"]) == (1.0, "ragas") + assert len(received) == 1 + exchange, outcome = _attempts(verifier) + assert [exchange["status"], outcome["status"]] == ["replied", "accepted"] + for field in ("prompt", "reply"): + assert "deploy.flags" in exchange[field] + assert "docker login -u bot -p " in exchange[field] + assert f"model_name: {model}" in exchange[field] + saved = (verifier.VERIFIER_DIR / "judge_attempts.json").read_text(encoding="utf-8") + for secret in secrets: + assert secret not in saved + + +def test_ragas_evidence_masks_private_key_blocks_in_json_prompts_and_replies( + verifier: ModuleType, monkeypatch: pytest.MonkeyPatch +) -> None: + """A private key block in the agent's text spans "\\n" escapes in the RAGAS prompt and reply, and is masked whole.""" + label = "RSA PRIVATE " + "KEY" + body = ("MIIEbodyLineOne", "MIIEbodyLineTwo") + agent_text = "\n".join(("Wrote the key:", f"-----BEGIN {label}-----", *body, f"-----END {label}-----", "done")) + prompt = "Judge whether the agent reached the goal.\ninput: " + json.dumps( + {"user_input": [{"content": agent_text, "type": "ai"}]}, indent=4 + ) + _install_ragas(monkeypatch, messages=[{"role": "user", "content": prompt}]) + received = _stub_provider(monkeypatch, [_chat_reply(json.dumps({"end_state": agent_text, "verdict": 1}))]) + + with _judge_evidence(verifier): + result = verifier.judge_goal_accuracy("question", "expected", "agent answer") + + assert (result["score"], result["method"]) == (1.0, "ragas") + assert len(received) == 1 + exchange, outcome = _attempts(verifier) + assert [exchange["status"], outcome["status"]] == ["replied", "accepted"] + for field in ("prompt", "reply"): + assert "Wrote the key:\\n\\ndone" in exchange[field] + saved = (verifier.VERIFIER_DIR / "judge_attempts.json").read_text(encoding="utf-8") + assert "-----END" not in saved + for line in body: + assert line not in saved + + +@pytest.mark.parametrize( + ("message", "finish_reason", "kept"), + [ + pytest.param( + {"role": "assistant", "content": None, "refusal": "I can't help with that request."}, + "stop", + "I can't help with that request.", + id="refusal", + ), + pytest.param( + {"role": "assistant", "content": None}, + "content_filter", + '"finish_reason": "content_filter"', + id="content-filter", + ), + pytest.param({"role": "assistant", "content": ""}, "length", '"finish_reason": "length"', id="empty-text"), + ], +) +def test_ragas_reply_without_text_or_tool_calls_is_saved_as_the_reply_body( + verifier: ModuleType, message: dict[str, Any], finish_reason: str, kept: str +) -> None: + """A refusal or a filtered reply is what makes RAGAS fail, so the entry keeps why there was no answer.""" + reply = _chat_reply("") + reply["choices"][0].update(message=message, finish_reason=finish_reason) + request = httpx.Request("POST", _CHAT_URL, json={"model": "gpt-4.1", "messages": _JUDGE_MESSAGES}) + + with _judge_evidence(verifier): + verifier._record_ragas_exchange(httpx.Response(200, content=json.dumps(reply).encode(), request=request)) + + (exchange,) = _attempts(verifier) + assert exchange["status"] == "replied" + assert kept in exchange["reply"] + assert exchange["reply_chars"] == len(exchange["reply"]) + + @pytest.mark.parametrize("broken", ["request-parser", "http-client"]) def test_ragas_evidence_failure_never_changes_the_score( verifier: ModuleType, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, broken: str diff --git a/tests/tier3/test_security_finding_evidence.py b/tests/tier3/test_security_finding_evidence.py index 245cee373..4cec8dd26 100644 --- a/tests/tier3/test_security_finding_evidence.py +++ b/tests/tier3/test_security_finding_evidence.py @@ -1143,12 +1143,61 @@ def test_finding_evidence_redaction_masks_credentials(text: str, secrets: tuple[ 'subprocess.run(["date", "-u", "+%H:%M:%S"])', "go test ./... | grep -- '--- PASS: TestLogin' && rm -rf /tmp/out", 'echo \'{"pass": true, "score": 1}\' > result.json && rm -rf /srv/app', + # A bare "-p" element after a MySQL client or login element, with + # JSON-escaped quotes as in tool-call arguments. + json.dumps('subprocess.run(["mysql", "-e", "CREATE DATABASE app"]); subprocess.run(["mkdir", "-p", "data"])'), + json.dumps('subprocess.run(["mysql", "-u", "root", "-p", "appdb"])'), + json.dumps('run(["docker", "login", "--password-stdin", "-u", "bot"]); run(["git", "log", "-p"])'), + # The same with the quotes escaped twice, after a plain MySQL client element. + 'run(["mysql", "-e", "x"]); ' + + json.dumps(json.dumps('run(["mkdir", "-p", "data"]); run(["mysql", "-u", "root", "-p", "appdb"])')), ], ) def test_finding_evidence_redaction_keeps_ordinary_text(text: str) -> None: assert eval_core_checks._redact_finding_evidence(text) == text +# A bare \"-p\" element keeps its escaped closing quote, so a multi-word +# credential later in the same JSON string is still masked to its end. +@pytest.mark.parametrize( + "argv", + [ + pytest.param('["mysql", "-p"]', id="mysql-prompt"), + pytest.param('["docker", "login", "-u", "bot"]); run(["git", "log", "-p"]', id="git-log-after-login"), + ], +) +def test_finding_evidence_masks_passphrase_after_bare_p_element(argv: str) -> None: + word = "Zq9" + "Leak" + text = json.dumps({"command": f"run({argv}); password: correct horse {word} staple"}) + + assert eval_core_checks._redact_finding_evidence(text) == json.dumps( + {"command": f"run({argv}); password: "} + ) + + +_MYSQL_ARGUMENTS = json.dumps( + {"command": f'python -c \'import subprocess; subprocess.run(["mysql", "-uroot", "-p{_BASIC_PASSWORD}"])\''} +) + + +# A RAGAS request that repeats a tool call writes the call's JSON arguments as +# JSON again, so an attached "-pVALUE" element there is escaped twice +# (\\\"-pVALUE\\\"). After a MySQL client element it is masked with its escapes +# intact. +@pytest.mark.parametrize( + "context", + [ + pytest.param(f'Task: run subprocess.run(["mysql", "-uroot", "-p{_BASIC_PASSWORD}"]).', id="plain"), + pytest.param(f"Task: run subprocess.run(['mysql', '-uroot', '-p{_BASIC_PASSWORD}']).", id="single-quoted"), + pytest.param(f"Earlier call: {_MYSQL_ARGUMENTS}", id="json-escaped"), + ], +) +def test_finding_evidence_masks_twice_escaped_attached_password(context: str) -> None: + text = f"{context}\nRepeated: {json.dumps(_MYSQL_ARGUMENTS)}" + + assert eval_core_checks._redact_finding_evidence(text) == text.replace(_BASIC_PASSWORD, "") + + @pytest.mark.parametrize( ("text", "expected"), [ @@ -1294,6 +1343,21 @@ def test_reviewer_credentials_never_reach_saved_judge_evidence(command: str) -> assert evidence.endswith(" && rm -rf /srv/app") +# Judge prompts render tool-call arguments with json.dumps, where the line +# break of a continued command is a "\n" escape after an escaped backslash. +@pytest.mark.parametrize( + "command", [case for case in _REVIEWER_CREDENTIAL_CASES if str(case.id).startswith("continued-")] +) +def test_continued_credentials_never_reach_json_escaped_judge_evidence(command: str) -> None: + arguments = {"command": command + " && rm -rf /srv/app"} + for escaped in (json.dumps(arguments), json.dumps(json.dumps(arguments))): + evidence = eval_template._redact_judge_evidence(escaped) + + assert "CANARY_REVIEW_SECRET" not in evidence + assert "" in evidence + assert " && rm -rf /srv/app" in evidence + + def test_judge_redaction_preserves_long_evidence_and_masks_credentials_past_finding_scan_limit() -> None: ordinary = "ordinary evidence " * 200 evidence = eval_template._redact_judge_evidence(ordinary + 'export DB_PASSWORD="pa\\"CANARY_REVIEW_SECRET"')