From 7fab2e7b3cb0664ccef754d587960e2114b30909 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Thu, 12 Nov 2026 12:19:19 -0800 Subject: [PATCH 01/18] fix(tier3): mask credentials after JSON-escaped line breaks in judge evidence RAGAS writes the agent's messages into its prompt as JSON, and tool-call arguments are JSON, so a line break in the quoted text reaches the judge evidence redactor as the two characters "\n". Every credential pattern checks the character before the credential, which is then the letter "n", so a line that starts with an Authorization, Cookie or API-key header, a --token or -u user:password flag, or a key shape such as sk-proj-... was saved in clear in the RAGAS prompt and reply, while the same plain text was masked. _redact_judge_evidence now also redacts the text after each escaped "\n", "\r" or "\t" as the start of a line. The first pass over the whole text is unchanged, so nothing that was masked before is kept. The credential flag patterns also accept a JSON-escaped double-quoted value (--token \"value\"), as the header patterns already did. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- docs/tier3-live-evaluation.mdx | 3 +- .../tier3/harbor/templates/eval.py | 37 ++++++++--- tests/tier3/test_judge_contracts.py | 63 +++++++++++++++++++ tests/tier3/test_ragas_judge_evidence.py | 43 +++++++++++++ 4 files changed, 135 insertions(+), 11 deletions(-) diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx index d3f225e1d..884a03571 100644 --- a/docs/tier3-live-evaluation.mdx +++ b/docs/tier3-live-evaluation.mdx @@ -1116,7 +1116,8 @@ in [Judge evidence budgets](environment-variables.mdx#judge-evidence-budgets). 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 + (`--token`, `--password`, `curl -u user:password`) are masked, also in + JSON-escaped text such as RAGAS prompts and tool-call arguments, 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. diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py index 01a2fc42a..d7ca7645c 100644 --- a/src/skillevaluator/tier3/harbor/templates/eval.py +++ b/src/skillevaluator/tier3/harbor/templates/eval.py @@ -2831,7 +2831,8 @@ def _judge_retry_feedback(problem): # ("-H 'Name: value'"), JSON ('"name": "value"') and Python subscript # ('headers["Name"] = f"value"') forms, also with the quotes JSON-escaped # ('\"Name\": \"value\"'), as tool-call arguments appear in the behavior and -# goal prompts. +# goal prompts. The flag patterns accept a JSON-escaped quoted value too +# ('--token \"value\"'). _JUDGE_EVIDENCE_URL_USERINFO_RE = re.compile(r"(://)[^\s/?#@'\"`<>]{1,256}@") _JUDGE_EVIDENCE_HEADER_SEPARATOR = r"\\?[\"']?\]?[ \t]{0,8}[:=][ \t]{0,8}(?:[bfru]{0,2}\\?[\"'])?" # Digest values hold quoted fields (username="...", response="..."), so the rest @@ -2865,23 +2866,28 @@ def _judge_retry_feedback(problem): ) _JUDGE_EVIDENCE_CREDENTIAL_FLAG_RE = re.compile( r"((?", redacted) - redacted = _JUDGE_EVIDENCE_URL_USERINFO_RE.sub(r"\1@", redacted) + text = pattern.sub("", text) + text = _JUDGE_EVIDENCE_URL_USERINFO_RE.sub(r"\1@", text) for pattern in ( _JUDGE_EVIDENCE_DIGEST_AUTH_HEADER_RE, _JUDGE_EVIDENCE_AUTH_HEADER_RE, @@ -2890,8 +2896,19 @@ def _redact_judge_evidence(text): _JUDGE_EVIDENCE_CREDENTIAL_FLAG_RE, _JUDGE_EVIDENCE_USER_FLAG_RE, ): - redacted = pattern.sub(r"\1", redacted) - return redacted + text = pattern.sub(r"\1", text) + return text + + +def _redact_judge_evidence(text): + """Mask credentials in a judge prompt, reply, or problem before it is saved.""" + redacted = _redact_judge_evidence_patterns(_redact_configured_credentials(_redact_evidence_text(text))) + # Text and escaped breaks alternate; the text before the first break was redacted above. + parts = _JUDGE_EVIDENCE_ESCAPED_BREAK_RE.split(redacted) + for index in range(2, len(parts), 2): + if parts[index]: + parts[index] = _redact_judge_evidence_patterns(redact_secrets_in_log_line(parts[index])) + return "".join(parts) def _verifier_output_dir(): diff --git a/tests/tier3/test_judge_contracts.py b/tests/tier3/test_judge_contracts.py index 628bdfb6f..e37fd21c2 100644 --- a/tests/tier3/test_judge_contracts.py +++ b/tests/tier3/test_judge_contracts.py @@ -739,6 +739,65 @@ def test_judge_evidence_masks_json_escaped_tool_call_headers(command: str, secre assert "" in redacted +@pytest.mark.parametrize( + ("command", "secret"), + [ + pytest.param('deploy --token "tttt tttt"', "tttt tttt", id="token-flag"), + pytest.param('tool --user "admin:pppp pppp"', "pppp pppp", id="user-flag"), + ], +) +def test_judge_evidence_masks_json_escaped_quoted_flag_values(command: str, secret: str) -> None: + trajectory = { + "steps": [ + {"source": "agent", "tool_calls": [{"function_name": "Bash", "arguments": {"command": command}}]}, + ] + } + summary = eval_template.build_conversation_summary(trajectory, "Deploy the service.") + assert secret + '\\"' in summary + + redacted = eval_template._redact_judge_evidence(summary) + + assert secret not in redacted + 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("-u uuuu:pppppppppppp", "pppppppppppp", "-u ", id="user-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 + + @pytest.mark.parametrize( "text", [ @@ -747,6 +806,10 @@ 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" + ), ], ) def test_judge_evidence_keeps_ordinary_text(text: str) -> None: diff --git a/tests/tier3/test_ragas_judge_evidence.py b/tests/tier3/test_ragas_judge_evidence.py index a1ac02630..c6969285c 100644 --- a/tests/tier3/test_ragas_judge_evidence.py +++ b/tests/tier3/test_ragas_judge_evidence.py @@ -406,6 +406,49 @@ 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 _tool_call_reply(arguments: str, *, content: str | None = None) -> dict[str, Any]: + reply = _chat_reply("") + reply["choices"][0]["message"] = { + "role": "assistant", + "content": content, + "tool_calls": [{"id": "call-1", "type": "function", "function": {"name": "Verdict", "arguments": arguments}}], + } + reply["choices"][0]["finish_reason"] = "tool_calls" + return reply + + +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 tool-call arguments are 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" + ) + 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}]) + reply = _tool_call_reply(json.dumps({"end_state": agent_text, "verdict": 1})) + received = _stub_provider(monkeypatch, [reply]) + + 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 " in exchange[field] + saved = (verifier.VERIFIER_DIR / "judge_attempts.json").read_text(encoding="utf-8") + for secret in ("bbbbbbbbbbbb", "cccccccccccc", "tttttttttttt"): + assert secret not in saved + + @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 From cfa306f31f60e175838f14f659be4764c209bcb1 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Thu, 12 Nov 2026 12:19:43 -0800 Subject: [PATCH 02/18] fix(tier3): keep tool-call arguments and empty-reply bodies in RAGAS replies A RAGAS judge reply was saved as its text whenever it had any, so a reply with text and a tool call lost the tool-call arguments RAGAS parses. A reply with neither, such as a refusal or a content-filter stop, was saved as an empty "replied" entry, which dropped the refusal text and the finish reason behind the RAGAS failure that follows. The saved reply now holds the text and every tool call's arguments, one per line. A reply with neither is saved as the whole reply body, as an unparseable one already was. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- docs/tier3-live-evaluation.mdx | 7 +-- .../tier3/harbor/templates/eval.py | 16 +++++-- tests/tier3/test_ragas_judge_evidence.py | 46 +++++++++++++++++++ 3 files changed, 61 insertions(+), 8 deletions(-) diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx index 884a03571..f9fac7444 100644 --- a/docs/tier3-live-evaluation.mdx +++ b/docs/tier3-live-evaluation.mdx @@ -1107,9 +1107,10 @@ in [Judge evidence budgets](environment-variables.mdx#judge-evidence-budgets). 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 + request. A `replied` entry holds the judge's reply: the text and the + tool-call arguments RAGAS parses, or the whole reply body when it has + neither, such as a refusal. 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 diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py index d7ca7645c..a77154afb 100644 --- a/src/skillevaluator/tier3/harbor/templates/eval.py +++ b/src/skillevaluator/tier3/harbor/templates/eval.py @@ -3314,14 +3314,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 and the tool-call arguments RAGAS parses. + + A reply with neither, such as a refusal or a filtered reply, 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"]) + answer = [str(message["content"])] if message.get("content") else [] + answer.extend(str(call["function"]["arguments"]) for call in message.get("tool_calls") or ()) + if answer: + return "\n".join(answer) 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_ragas_judge_evidence.py b/tests/tier3/test_ragas_judge_evidence.py index c6969285c..35cdc92f2 100644 --- a/tests/tier3/test_ragas_judge_evidence.py +++ b/tests/tier3/test_ragas_judge_evidence.py @@ -449,6 +449,52 @@ def test_ragas_evidence_masks_credentials_at_json_escaped_line_starts( assert secret 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"]) + + +def test_ragas_reply_keeps_tool_call_arguments_next_to_text(verifier: ModuleType) -> None: + reply = _tool_call_reply('{"verdict": 0}', content="Calling the verdict tool.") + two_calls = _tool_call_reply('{"verdict": 0}') + two_calls["choices"][0]["message"]["tool_calls"].append( + {"id": "call-2", "type": "function", "function": {"name": "Verdict", "arguments": '{"verdict": 1}'}} + ) + + assert verifier._ragas_reply_text(json.dumps(reply).encode()) == 'Calling the verdict tool.\n{"verdict": 0}' + assert verifier._ragas_reply_text(json.dumps(two_calls).encode()) == '{"verdict": 0}\n{"verdict": 1}' + + @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 From 53a09faa8d27f5e71debde24b563eed7f0ccf3c0 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Thu, 12 Nov 2026 14:57:56 -0800 Subject: [PATCH 03/18] docs(changelog): note judge evidence masking at JSON-escaped line starts Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index efbd63944..88ce4e8e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -885,6 +885,17 @@ All notable changes to SkillEvaluator are documented in this file. with a `destructive_command` finding, already gets FAIL from that check (see Changed). +- `judge_attempts.json` now masks credentials at the start of a JSON-escaped + line, as in RAGAS prompts and in the tool-call arguments that judge prompts + quote. A line break there is the two characters `\n`, so an + `Authorization`, API-key or `Cookie` header value, a `--token` or + `-u user:password` flag value, or a key such as `sk-proj-...` that started + the next line was saved in clear. A flag value in JSON-escaped quotes + (`--token \"value\"`) is masked too. RAGAS `replied` entries now keep the + tool-call arguments when the reply also has text, and save the whole reply + body when it has neither, such as a refusal or a content-filter stop, + instead of an empty reply. + ## 0.8.0 - 2026-11-05 ### Added From 9455fc3e426aec1819d6836a617f43abc02f8d7f Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Thu, 12 Nov 2026 15:12:04 -0800 Subject: [PATCH 04/18] docs(changelog): place the judge evidence masking entry with the judge fixes Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 88ce4e8e3..aced0101f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -702,6 +702,17 @@ All notable changes to SkillEvaluator are documented in this file. `Bedrock request failed`, like a Bedrock error that ends the judge and like the default `legacy` policy. +- `judge_attempts.json` now masks credentials at the start of a JSON-escaped + line, as in RAGAS prompts and in the tool-call arguments that judge prompts + quote. A line break there is the two characters `\n`, so an + `Authorization`, API-key or `Cookie` header value, a `--token` or + `-u user:password` flag value, or a key such as `sk-proj-...` that started + the next line was saved in clear. A flag value in JSON-escaped quotes + (`--token \"value\"`) is masked too. RAGAS `replied` entries now keep the + tool-call arguments when the reply also has text, and save the whole reply + body when it has neither, such as a refusal or a content-filter stop, + instead of an empty reply. + - The interactive Tier 3 progress view (`--progress rich`, or `auto` in a terminal) now keeps one height for the whole run, so redraws no longer leave repeated or jumbled table frames. The Provider and Run plan rows show a @@ -885,17 +896,6 @@ All notable changes to SkillEvaluator are documented in this file. with a `destructive_command` finding, already gets FAIL from that check (see Changed). -- `judge_attempts.json` now masks credentials at the start of a JSON-escaped - line, as in RAGAS prompts and in the tool-call arguments that judge prompts - quote. A line break there is the two characters `\n`, so an - `Authorization`, API-key or `Cookie` header value, a `--token` or - `-u user:password` flag value, or a key such as `sk-proj-...` that started - the next line was saved in clear. A flag value in JSON-escaped quotes - (`--token \"value\"`) is masked too. RAGAS `replied` entries now keep the - tool-call arguments when the reply also has text, and save the whole reply - body when it has neither, such as a refusal or a content-filter stop, - instead of an empty reply. - ## 0.8.0 - 2026-11-05 ### Added From e3b545a43f5f2bee9b6eded97f983efa4918b54e Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Thu, 12 Nov 2026 17:00:29 -0800 Subject: [PATCH 05/18] fix(tier3): mask quoted credentials escaped twice in judge evidence A RAGAS request that repeats an earlier tool call writes the call's JSON arguments as JSON again, so each quote in them reaches the saved prompt after three backslashes. The header separator, the quote after an Authorization scheme, and the quoted-value openers of the credential and user flag patterns accepted at most one backslash, so a quoted `--token "value"`, `--user "user:password"` or a JSON or Python `Authorization`, API-key or `Cookie` header value escaped twice was saved in clear. These places now accept a run of up to eight backslashes before the quote, which covers three levels of escaping and keeps each pattern a bounded literal run. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- .../tier3/harbor/templates/eval.py | 12 +++--- tests/tier3/test_judge_contracts.py | 20 +++++++--- tests/tier3/test_ragas_judge_evidence.py | 37 +++++++++++++++++++ 3 files changed, 58 insertions(+), 11 deletions(-) diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py index a77154afb..5dc35a5cc 100644 --- a/src/skillevaluator/tier3/harbor/templates/eval.py +++ b/src/skillevaluator/tier3/harbor/templates/eval.py @@ -2832,9 +2832,11 @@ def _judge_retry_feedback(problem): # ('headers["Name"] = f"value"') forms, also with the quotes JSON-escaped # ('\"Name\": \"value\"'), as tool-call arguments appear in the behavior and # goal prompts. The flag patterns accept a JSON-escaped quoted value too -# ('--token \"value\"'). +# ('--token \"value\"'). Text escaped again, such as tool-call JSON quoted in a +# RAGAS prompt, puts a run of backslashes before each quote, so a short run is +# accepted. _JUDGE_EVIDENCE_URL_USERINFO_RE = re.compile(r"(://)[^\s/?#@'\"`<>]{1,256}@") -_JUDGE_EVIDENCE_HEADER_SEPARATOR = r"\\?[\"']?\]?[ \t]{0,8}[:=][ \t]{0,8}(?:[bfru]{0,2}\\?[\"'])?" +_JUDGE_EVIDENCE_HEADER_SEPARATOR = r"\\{0,8}[\"']?\]?[ \t]{0,8}[:=][ \t]{0,8}(?:[bfru]{0,2}\\{0,8}[\"'])?" # Digest values hold quoted fields (username="...", response="..."), so the rest # of the value is masked up to a single quote, a backtick or the end of the line. _JUDGE_EVIDENCE_DIGEST_AUTH_HEADER_RE = re.compile( @@ -2848,7 +2850,7 @@ def _judge_retry_feedback(problem): _JUDGE_EVIDENCE_AUTH_HEADER_RE = re.compile( r"(\bauthorization" + _JUDGE_EVIDENCE_HEADER_SEPARATOR - + r"(?:(?:bearer|basic|token|digest)[ \t]{1,8}(?:\\?[\"'])?)?)" + + r"(?:(?:bearer|basic|token|digest)[ \t]{1,8}(?:\\{0,8}[\"'])?)?)" r"[^\s'\"`,;\\][^'\"`\r\n\\]*", re.IGNORECASE, ) @@ -2866,14 +2868,14 @@ def _judge_retry_feedback(problem): ) _JUDGE_EVIDENCE_CREDENTIAL_FLAG_RE = re.compile( r"((?" in redacted + assert secret not in redacted + assert "" in redacted @pytest.mark.parametrize( @@ -754,11 +758,15 @@ def test_judge_evidence_masks_json_escaped_quoted_flag_values(command: str, secr } summary = eval_template.build_conversation_summary(trajectory, "Deploy the service.") assert secret + '\\"' in summary + # Escaped again, as when a RAGAS prompt repeats an earlier tool call. + twice = json.dumps(summary) + assert secret + '\\\\\\"' in twice - redacted = eval_template._redact_judge_evidence(summary) + for text in (summary, twice): + redacted = eval_template._redact_judge_evidence(text) - assert secret not in redacted - assert "" in redacted + assert secret not in redacted + assert "" in redacted # RAGAS writes the agent's messages into its prompt as JSON, and tool-call diff --git a/tests/tier3/test_ragas_judge_evidence.py b/tests/tier3/test_ragas_judge_evidence.py index 35cdc92f2..234fb0dd3 100644 --- a/tests/tier3/test_ragas_judge_evidence.py +++ b/tests/tier3/test_ragas_judge_evidence.py @@ -449,6 +449,43 @@ def test_ragas_evidence_masks_credentials_at_json_escaped_line_starts( assert secret not in saved +def test_ragas_evidence_masks_quoted_credentials_in_a_repeated_tool_call(verifier: ModuleType) -> None: + """A request that repeats an earlier tool call writes its JSON arguments as JSON again. + + The quotes in the arguments then reach the prompt escaped twice, as a run of + backslashes before each quote. + """ + end_state = 'Ran deploy --token "tttt qqqq" with headers={"Authorization": "Bearer jjjjjjjjjjjj"}' + arguments = json.dumps({"end_state": end_state, "verdict": 1}) + messages = [ + {"role": "user", "content": "Judge the agent.\ninput: " + json.dumps({"end_state": end_state})}, + { + "role": "assistant", + "content": None, + "tool_calls": [ + {"id": "call-1", "type": "function", "function": {"name": "Verdict", "arguments": arguments}} + ], + }, + {"role": "tool", "tool_call_id": "call-1", "content": "error: the verdict could not be parsed"}, + ] + request = httpx.Request("POST", _CHAT_URL, json={"model": "gpt-4.1", "messages": messages}) + reply = json.dumps(_tool_call_reply(arguments)).encode() + + with _judge_evidence(verifier): + verifier._record_ragas_exchange(httpx.Response(200, content=reply, request=request)) + + (exchange,) = _attempts(verifier) + assert exchange["status"] == "replied" + # Once escaped in the user message and the reply, twice in the repeated tool call. + assert exchange["prompt"].count("--token ") == 2 + assert exchange["prompt"].count("Bearer ") == 2 + assert "--token " in exchange["reply"] + assert "Bearer " in exchange["reply"] + saved = (verifier.VERIFIER_DIR / "judge_attempts.json").read_text(encoding="utf-8") + for secret in ("tttt qqqq", "jjjjjjjjjjjj"): + assert secret not in saved + + @pytest.mark.parametrize( ("message", "finish_reason", "kept"), [ From 86776ef12a1c5fef41fa6e09a7676219ebf70e8a Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Thu, 12 Nov 2026 17:01:45 -0800 Subject: [PATCH 06/18] fix(tier3): mask judge evidence credentials after escaped tabs and non-ASCII characters json.dumps writes a tab as the two characters "\t" and, by default, a non-ASCII character as "\uXXXX". A header or flag whose name and value were separated by a tab therefore had the letter t between them, which no separator accepted, and a key, header or flag right after a no-break space, a curly quote or an arrow followed a hex digit, which defeats the word boundary and lookbehind checks. Both were saved in clear in RAGAS prompts and in the tool-call arguments that judge prompts quote. An escaped tab now counts as a blank in the header separator, after an Authorization scheme and between a credential flag and its value. The second redaction pass, which already treats the text after an escaped line break as the start of a line, now does the same after a "\uXXXX" escape, so it covers every JSON writer, not only the template's own. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- .../tier3/harbor/templates/eval.py | 37 +++++++++++++------ tests/tier3/test_judge_contracts.py | 30 +++++++++++++++ 2 files changed, 56 insertions(+), 11 deletions(-) diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py index 5dc35a5cc..02cb00057 100644 --- a/src/skillevaluator/tier3/harbor/templates/eval.py +++ b/src/skillevaluator/tier3/harbor/templates/eval.py @@ -2833,14 +2833,25 @@ def _judge_retry_feedback(problem): # ('\"Name\": \"value\"'), as tool-call arguments appear in the behavior and # goal prompts. The flag patterns accept a JSON-escaped quoted value too # ('--token \"value\"'). Text escaped again, such as tool-call JSON quoted in a -# RAGAS prompt, puts a run of backslashes before each quote, so a short run is -# accepted. +# RAGAS prompt, puts a run of backslashes before each quote, and an escaped tab +# ("\t") can stand between a name and its value, so both are accepted. _JUDGE_EVIDENCE_URL_USERINFO_RE = re.compile(r"(://)[^\s/?#@'\"`<>]{1,256}@") -_JUDGE_EVIDENCE_HEADER_SEPARATOR = r"\\{0,8}[\"']?\]?[ \t]{0,8}[:=][ \t]{0,8}(?:[bfru]{0,2}\\{0,8}[\"'])?" +_JUDGE_EVIDENCE_BLANK = r"(?:[ \t]|\\{1,8}t)" +_JUDGE_EVIDENCE_HEADER_SEPARATOR = ( + r"\\{0,8}[\"']?\]?" + + _JUDGE_EVIDENCE_BLANK + + r"{0,8}[:=]" + + _JUDGE_EVIDENCE_BLANK + + r"{0,8}(?:[bfru]{0,2}\\{0,8}[\"'])?" +) # Digest values hold quoted fields (username="...", response="..."), so the rest # of the value is masked up to a single quote, a backtick or the end of the line. _JUDGE_EVIDENCE_DIGEST_AUTH_HEADER_RE = re.compile( - r"(\bauthorization" + _JUDGE_EVIDENCE_HEADER_SEPARATOR + r"digest[ \t]{1,8})[^'`\r\n]{1,512}", + r"(\bauthorization" + + _JUDGE_EVIDENCE_HEADER_SEPARATOR + + r"digest" + + _JUDGE_EVIDENCE_BLANK + + r"{1,8})[^'`\r\n]{1,512}", re.IGNORECASE, ) # Other Authorization schemes vary (Bearer, Basic, ApiKey, Bot, SSWS, ...), so the @@ -2850,7 +2861,9 @@ def _judge_retry_feedback(problem): _JUDGE_EVIDENCE_AUTH_HEADER_RE = re.compile( r"(\bauthorization" + _JUDGE_EVIDENCE_HEADER_SEPARATOR - + r"(?:(?:bearer|basic|token|digest)[ \t]{1,8}(?:\\{0,8}[\"'])?)?)" + + r"(?:(?:bearer|basic|token|digest)" + + _JUDGE_EVIDENCE_BLANK + + r"{1,8}(?:\\{0,8}[\"'])?)?)" r"[^\s'\"`,;\\][^'\"`\r\n\\]*", re.IGNORECASE, ) @@ -2867,22 +2880,24 @@ def _judge_retry_feedback(problem): re.IGNORECASE, ) _JUDGE_EVIDENCE_CREDENTIAL_FLAG_RE = re.compile( - r"((? 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 or "\\u" in escaped + redacted = eval_template._redact_judge_evidence(escaped) + + assert secret not in redacted + assert "" in redacted + + @pytest.mark.parametrize( "text", [ @@ -818,6 +847,7 @@ def test_judge_evidence_masks_credentials_after_json_escaped_line_breaks( 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"), ], ) def test_judge_evidence_keeps_ordinary_text(text: str) -> None: From 76b5a4c1fd1435fafaabff33208d10d49992d540 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Thu, 12 Nov 2026 17:02:07 -0800 Subject: [PATCH 07/18] docs(changelog): cover escaped tabs, non-ASCII escapes and twice-escaped quotes in judge evidence masking Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aced0101f..3b2f4f202 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -702,16 +702,18 @@ All notable changes to SkillEvaluator are documented in this file. `Bedrock request failed`, like a Bedrock error that ends the judge and like the default `legacy` policy. -- `judge_attempts.json` now masks credentials at the start of a JSON-escaped - line, as in RAGAS prompts and in the tool-call arguments that judge prompts - quote. A line break there is the two characters `\n`, so an - `Authorization`, API-key or `Cookie` header value, a `--token` or - `-u user:password` flag value, or a key such as `sk-proj-...` that started - the next line was saved in clear. A flag value in JSON-escaped quotes - (`--token \"value\"`) is masked too. RAGAS `replied` entries now keep the - tool-call arguments when the reply also has text, and save the whole reply - body when it has neither, such as a refusal or a content-filter stop, - instead of an empty reply. +- `judge_attempts.json` now masks credentials in JSON-escaped text, as in + RAGAS prompts and in the tool-call arguments that judge prompts quote. A + line break there is the two characters `\n`, so an `Authorization`, API-key + or `Cookie` header value, a `--token` or `-u user:password` flag value, or a + key such as `sk-proj-...` that started the next line was saved in clear. The + same held after an escaped non-ASCII character such as `\u00a0`, for a + header or flag value after an escaped tab (`\t`), for a flag value in + escaped quotes (`--token \"value\"`), and for a quoted header or flag value + escaped twice, as when a RAGAS prompt repeats an earlier tool call. RAGAS + `replied` entries now keep the tool-call arguments when the reply also has + text, and save the whole reply body when it has neither, such as a refusal + or a content-filter stop, instead of an empty reply. - The interactive Tier 3 progress view (`--progress rich`, or `auto` in a terminal) now keeps one height for the whole run, so redraws no longer leave From 42b964bc5e078e0a449db4ef5d42bc4111d158ed Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Thu, 12 Nov 2026 18:40:23 -0800 Subject: [PATCH 08/18] fix(tier3): mask judge evidence after an escaped tab at a JSON-escaped line start An escaped tab between a header or flag and its value was only accepted mid-line. At the start of a JSON-escaped line, or right after a \uXXXX escape, the character before the name is the last letter or digit of the escape, so the first pass did not match, and the second pass split the text at the escaped tab and cut the name off from its value. An Authorization, Digest or API-key header value and a --token or -u value were then saved in clear, for example "\nAuthorization:\tBearer " in a RAGAS prompt or "\n--token\t" in a heredoc in tool-call arguments. The Authorization, Digest and API-key header patterns and the two flag patterns now also start right after an escaped \n, \r, \t or \uXXXX, so the first pass over the whole text handles these line starts. The second pass still covers key shapes such as sk-proj-... after an escape. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +- .../tier3/harbor/templates/eval.py | 33 +++++++++---- tests/tier3/test_judge_contracts.py | 47 +++++++++++++++++++ 3 files changed, 74 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b2f4f202..1d09a26c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -707,8 +707,9 @@ All notable changes to SkillEvaluator are documented in this file. line break there is the two characters `\n`, so an `Authorization`, API-key or `Cookie` header value, a `--token` or `-u user:password` flag value, or a key such as `sk-proj-...` that started the next line was saved in clear. The - same held after an escaped non-ASCII character such as `\u00a0`, for a - header or flag value after an escaped tab (`\t`), for a flag value in + same held after an escaped non-ASCII character such as `\u00a0`, for an + `Authorization` or API-key header value or a flag value after an escaped + tab (`\t`), also when the header or flag starts a line, for a flag value in escaped quotes (`--token \"value\"`), and for a quoted header or flag value escaped twice, as when a RAGAS prompt repeats an earlier tool call. RAGAS `replied` entries now keep the tool-call arguments when the reply also has diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py index 02cb00057..69d9c6418 100644 --- a/src/skillevaluator/tier3/harbor/templates/eval.py +++ b/src/skillevaluator/tier3/harbor/templates/eval.py @@ -2834,9 +2834,15 @@ def _judge_retry_feedback(problem): # goal prompts. The flag patterns accept a JSON-escaped quoted value too # ('--token \"value\"'). Text escaped again, such as tool-call JSON quoted in a # RAGAS prompt, puts a run of backslashes before each quote, and an escaped tab -# ("\t") can stand between a name and its value, so both are accepted. +# ("\t") can stand between a name and its value, so both are accepted. In +# JSON-escaped text a header or flag that starts a line, or follows a tab or a +# non-ASCII character, comes right after the escape ("\n", "\t", "\u00a0"), +# so the header and flag patterns also start there. _JUDGE_EVIDENCE_URL_USERINFO_RE = re.compile(r"(://)[^\s/?#@'\"`<>]{1,256}@") _JUDGE_EVIDENCE_BLANK = r"(?:[ \t]|\\{1,8}t)" +_JUDGE_EVIDENCE_AFTER_ESCAPE = r"(?<=\\[nrt])|(?<=\\u[0-9a-fA-F]{4})" +_JUDGE_EVIDENCE_LINE_START = r"(?:\b|" + _JUDGE_EVIDENCE_AFTER_ESCAPE + r")" +_JUDGE_EVIDENCE_FLAG_START = r"(?:(?" in redacted +# The same headers and flags at the start of a line, or right after a non-ASCII +# character, follow the escape itself ("\n" or "\u00a0"), and the escaped tab +# then separates the name from its value. +@pytest.mark.parametrize( + ("line", "secret", "kept"), + [ + pytest.param( + "Authorization:\tBearer bbbbbbbbbbbb", "bbbbbbbbbbbb", "Bearer ", id="tab-authorization" + ), + pytest.param("Authorization: Bearer\tbbbbbbbbbbbb", "bbbbbbbbbbbb", "Authorization:", id="tab-after-scheme"), + pytest.param( + 'Authorization:\tDigest response="dddddddddddd"', "dddddddddddd", "Digest ", id="tab-digest" + ), + pytest.param("Api-Key:\tkkkkkkkkkkkk", "kkkkkkkkkkkk", "Api-Key:", id="tab-api-key"), + pytest.param("--token\tvvvvvvvvvvvv", "vvvvvvvvvvvv", "--token", id="tab-token-flag"), + pytest.param("-u\tuuuu:pppppppppppp", "pppppppppppp", "-u", id="tab-user-flag"), + ], +) +@pytest.mark.parametrize("before", ["HTTP/1.1 200 OK\n", "\u00a0"], ids=["line-start", "after-non-ascii"]) +def test_judge_evidence_masks_credentials_after_json_escaped_tabs_at_line_starts( + line: str, secret: str, kept: str, before: str +) -> None: + text = before + line + 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 + assert "" in redacted + + +def test_judge_evidence_masks_tab_separated_credentials_in_ragas_prompts_and_heredocs() -> None: + agent_text = "HTTP/1.1 200 OK\nAuthorization:\tBearer bbbbbbbbbbbb\nApi-Key:\tkkkkkkkkkkkk" + prompt = json.dumps({"user_input": [{"content": agent_text, "type": "ai"}]}, indent=4) + arguments = json.dumps({"command": "cat <\\nApi-Key:\\t" in redacted_prompt + assert "\\nApi-Key:\\t\\n--token\\t\\nEOF" in redacted_arguments + for secret in ("bbbbbbbbbbbb", "kkkkkkkkkkkk", "vvvvvvvvvvvv"): + assert secret not in redacted_prompt + redacted_arguments + + @pytest.mark.parametrize( "text", [ From ea146fe54308da9fa18bf336e52138b1b576831e Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Thu, 12 Nov 2026 18:40:45 -0800 Subject: [PATCH 09/18] docs(tier3): name the JSON-escaped Cookie shapes judge evidence still keeps The judge evidence section said Cookie header values are masked also in JSON-escaped text. Two escaped shapes are not: a pair after ";" and an escaped tab, and a value after an escaped tab when the Cookie header itself follows an escape such as "\n". Say so, so the page matches what judge_attempts.json holds. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- docs/tier3-live-evaluation.mdx | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx index f9fac7444..82f7c05ca 100644 --- a/docs/tier3-live-evaluation.mdx +++ b/docs/tier3-live-evaluation.mdx @@ -1119,9 +1119,12 @@ in [Judge evidence budgets](environment-variables.mdx#judge-evidence-budgets). API-key, token and `Cookie` header values, and credential flag values (`--token`, `--password`, `curl -u user:password`) are masked, also in JSON-escaped text such as RAGAS prompts and tool-call arguments, 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. + prompts and replies are shortened. In JSON-escaped text, `Cookie` pairs + after an escaped tab (`\t`) are not masked when the tab follows a `;`, or + when the header itself follows an escape such as a line break (`\n`). 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 From 960d86ca08fc2d420bd009f9e3ee5bca4c9a5e8d Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Fri, 13 Nov 2026 05:07:32 -0800 Subject: [PATCH 10/18] fix(tier3): keep RAGAS reply evidence to the text RAGAS parses RAGAS 0.4 asks an OpenAI judge for a JSON-mode reply and parses its text, so a reply that has text keeps saving only that text, as before. Only a reply with no text and no tool call, such as a refusal or a content-filter stop, now saves the whole reply body, so the refusal or the finish reason is kept instead of an empty reply. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++++---- docs/tier3-live-evaluation.mdx | 5 +++-- src/skillevaluator/tier3/harbor/templates/eval.py | 14 +++++++------- tests/tier3/test_ragas_judge_evidence.py | 11 ----------- 4 files changed, 14 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8902a533f..023800856 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,10 +54,10 @@ All notable changes to SkillEvaluator are documented in this file. `Authorization` or API-key header value or a flag value after an escaped tab (`\t`), also when the header or flag starts a line, for a flag value in escaped quotes (`--token \"value\"`), and for a quoted header or flag value - escaped twice, as when a RAGAS prompt repeats an earlier tool call. RAGAS - `replied` entries now keep the tool-call arguments when the reply also has - text, and save the whole reply body when it has neither, such as a refusal - or a content-filter stop, instead of an empty reply. + escaped twice, as when a RAGAS prompt repeats an earlier tool call. 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. ## 0.9.0 - 2026-11-13 diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx index 5aba731ca..84ca5be47 100644 --- a/docs/tier3-live-evaluation.mdx +++ b/docs/tier3-live-evaluation.mdx @@ -1326,9 +1326,10 @@ in [Judge evidence budgets](/skills/skillevaluator/environment-variables#judge-e 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. A `replied` entry holds the judge's reply: the text and 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. An `error` entry holds the HTTP status and + 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 diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py index 48ca77a8e..7b4cf1b45 100644 --- a/src/skillevaluator/tier3/harbor/templates/eval.py +++ b/src/skillevaluator/tier3/harbor/templates/eval.py @@ -3236,17 +3236,17 @@ def _ragas_request_text(body): def _ragas_reply_text(body): - """Return the judge's answer in one chat-completions reply: its text and 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 filtered reply, is returned - whole, so the refusal or the finish reason is kept. + 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"] - answer = [str(message["content"])] if message.get("content") else [] - answer.extend(str(call["function"]["arguments"]) for call in message.get("tool_calls") or ()) - if answer: - return "\n".join(answer) + 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): pass return body.decode("utf-8", "replace") diff --git a/tests/tier3/test_ragas_judge_evidence.py b/tests/tier3/test_ragas_judge_evidence.py index 234fb0dd3..930d8b413 100644 --- a/tests/tier3/test_ragas_judge_evidence.py +++ b/tests/tier3/test_ragas_judge_evidence.py @@ -521,17 +521,6 @@ def test_ragas_reply_without_text_or_tool_calls_is_saved_as_the_reply_body( assert exchange["reply_chars"] == len(exchange["reply"]) -def test_ragas_reply_keeps_tool_call_arguments_next_to_text(verifier: ModuleType) -> None: - reply = _tool_call_reply('{"verdict": 0}', content="Calling the verdict tool.") - two_calls = _tool_call_reply('{"verdict": 0}') - two_calls["choices"][0]["message"]["tool_calls"].append( - {"id": "call-2", "type": "function", "function": {"name": "Verdict", "arguments": '{"verdict": 1}'}} - ) - - assert verifier._ragas_reply_text(json.dumps(reply).encode()) == 'Calling the verdict tool.\n{"verdict": 0}' - assert verifier._ragas_reply_text(json.dumps(two_calls).encode()) == '{"verdict": 0}\n{"verdict": 1}' - - @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 From f2235071c3e88cd6cd029eb4ae21aaac5dde8041 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Fri, 13 Nov 2026 05:07:52 -0800 Subject: [PATCH 11/18] fix(tier3): mask judge evidence credentials after JSON escapes Judge evidence now goes through the shared finding masker. In JSON-escaped text, such as a RAGAS prompt or a JSON-mode reply, a line break is the two characters \n, so a Cookie header, a credential flag (--token, --password, -token, -u user:password, --cookie) or a key such as sk-proj- that starts the next line follows the letter n. The patterns that need a line start, a space or a word boundary there did not match, and those values were saved in clear. The same held after an escaped tab or non-ASCII character. The text between JSON escapes is now masked line by line before the whole text is masked as before. Masking line by line first also keeps an unquoted value on one line from reading through the escape into the next line's header name. This replaces the judge-only header and flag patterns this branch added before the shared masker landed, with their tests and docs. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 22 ++--- docs/tier3-live-evaluation.mdx | 39 ++++---- .../tier3/harbor/templates/eval.py | 26 ++++- tests/tier3/test_judge_contracts.py | 98 ++----------------- tests/tier3/test_ragas_judge_evidence.py | 63 ++---------- 5 files changed, 70 insertions(+), 178 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 023800856..ea1081fef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,20 +44,14 @@ All notable changes to SkillEvaluator are documented in this file. `/bin/bash -lc 'cat skills/x/SKILL.md'`, which some agent harnesses record instead of the bare command. Searches inside a wrapper (`bash -c 'grep SKILL config.json'`) are still not counted. - -- `judge_attempts.json` now masks credentials in JSON-escaped text, as in - RAGAS prompts and in the tool-call arguments that judge prompts quote. A - line break there is the two characters `\n`, so an `Authorization`, API-key - or `Cookie` header value, a `--token` or `-u user:password` flag value, or a - key such as `sk-proj-...` that started the next line was saved in clear. The - same held after an escaped non-ASCII character such as `\u00a0`, for an - `Authorization` or API-key header value or a flag value after an escaped - tab (`\t`), also when the header or flag starts a line, for a flag value in - escaped quotes (`--token \"value\"`), and for a quoted header or flag value - escaped twice, as when a RAGAS prompt repeats an earlier tool call. 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. +- `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`) or non-ASCII character + (`\u00a0`). 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. ## 0.9.0 - 2026-11-13 diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx index 84ca5be47..3806cee56 100644 --- a/docs/tier3-live-evaluation.mdx +++ b/docs/tier3-live-evaluation.mdx @@ -1324,27 +1324,24 @@ in [Judge evidence budgets](/skills/skillevaluator/environment-variables#judge-e 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. 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 in - JSON-escaped text such as RAGAS prompts and tool-call arguments, and long - prompts and replies are shortened. In JSON-escaped text, `Cookie` pairs - after an escaped tab (`\t`) are not masked when the tab follows a `;`, or - when the header itself follows an escape such as a line break (`\n`). 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`. 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/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py index 7b4cf1b45..6f343aa08 100644 --- a/src/skillevaluator/tier3/harbor/templates/eval.py +++ b/src/skillevaluator/tier3/harbor/templates/eval.py @@ -2822,11 +2822,35 @@ def _judge_retry_feedback(problem): ) +# 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", and a non-ASCII character such as a no-break space as "\u00a0". +# A header, flag or key that starts a line there follows the last letter or +# digit of the escape, where patterns that need a line start, a space or a word +# boundary before it do not match, and an unquoted value on the line before +# can read on through the escape into the next line's header name. So the +# text between escapes is masked line by line first, and the whole text after. +_JUDGE_EVIDENCE_ESCAPE_RE = re.compile(r"(\\(?:[nrt]|u[0-9a-fA-F]{4}))") + + +def _mask_judge_evidence_shapes(text): + """Mask the credential forms and key shapes that depend on what precedes them.""" + 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 + + def _redact_judge_evidence(text): """Mask credentials in a judge prompt, reply, or problem before it is saved.""" + # Text and escapes alternate. + parts = _JUDGE_EVIDENCE_ESCAPE_RE.split(str(text)) + if len(parts) > 1: + parts[::2] = [_mask_judge_evidence_shapes(part) if part else part for part in parts[::2]] # 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("".join(parts), preserve_header_format=True) redacted = _redact_configured_credentials(_redact_evidence_text(redacted)) for pattern in _SECRET_PATTERNS: redacted = pattern.sub("", redacted) diff --git a/tests/tier3/test_judge_contracts.py b/tests/tier3/test_judge_contracts.py index fdcc5f2c1..0763ffea9 100644 --- a/tests/tier3/test_judge_contracts.py +++ b/tests/tier3/test_judge_contracts.py @@ -732,41 +732,11 @@ def test_judge_evidence_masks_json_escaped_tool_call_headers(command: str, secre summary = eval_template.build_conversation_summary(trajectory, "Fetch the index.") assert secret in summary assert '\\"' in summary - # Escaped again, as when a RAGAS prompt repeats an earlier tool call. - twice = json.dumps(summary) - assert '\\\\\\"' in twice - for text in (summary, twice): - redacted = eval_template._redact_judge_evidence(text) + redacted = eval_template._redact_judge_evidence(summary) - assert secret not in redacted - assert "" in redacted - - -@pytest.mark.parametrize( - ("command", "secret"), - [ - pytest.param('deploy --token "tttt tttt"', "tttt tttt", id="token-flag"), - pytest.param('tool --user "admin:pppp pppp"', "pppp pppp", id="user-flag"), - ], -) -def test_judge_evidence_masks_json_escaped_quoted_flag_values(command: str, secret: str) -> None: - trajectory = { - "steps": [ - {"source": "agent", "tool_calls": [{"function_name": "Bash", "arguments": {"command": command}}]}, - ] - } - summary = eval_template.build_conversation_summary(trajectory, "Deploy the service.") - assert secret + '\\"' in summary - # Escaped again, as when a RAGAS prompt repeats an earlier tool call. - twice = json.dumps(summary) - assert secret + '\\\\\\"' in twice - - for text in (summary, twice): - redacted = eval_template._redact_judge_evidence(text) - - assert secret not in redacted - assert "" in redacted + assert secret not in redacted + assert "" in redacted # RAGAS writes the agent's messages into its prompt as JSON, and tool-call @@ -787,7 +757,10 @@ def test_judge_evidence_masks_json_escaped_quoted_flag_values(command: str, secr 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"), ], @@ -811,16 +784,12 @@ def test_judge_evidence_masks_credentials_after_json_escaped_line_breaks( @pytest.mark.parametrize( ("text", "secret"), [ - pytest.param("Authorization:\tBearer bbbbbbbbbbbb", "bbbbbbbbbbbb", id="tab-authorization"), - pytest.param("Authorization: Bearer\tbbbbbbbbbbbb", "bbbbbbbbbbbb", id="tab-after-scheme"), - pytest.param('Authorization:\tDigest response="dddddddddddd"', "dddddddddddd", id="tab-digest"), - pytest.param("X-Api-Key:\tkkkkkkkkkkkk", "kkkkkkkkkkkk", id="tab-api-key"), - pytest.param("Cookie:\tsession=cccccccccccc", "cccccccccccc", id="tab-cookie"), - pytest.param("deploy --token\tvvvvvvvvvvvv", "vvvvvvvvvvvv", id="tab-token-flag"), - pytest.param("curl -u\tuuuu:pppppppppppp", "pppppppppppp", id="tab-user-flag"), + 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"), pytest.param("key\u00a0ghp_" + "g" * 36, "g" * 36, id="no-break-space-github-token"), pytest.param("\u201csk-proj-" + "a" * 24 + "\u201d", "a" * 24, id="curly-quote-openai-key"), - pytest.param("\u2192Authorization: Bearer bbbbbbbbbbbb", "bbbbbbbbbbbb", id="arrow-authorization"), + pytest.param("\u2192Cookie: session=cccccccccccc", "cccccccccccc", id="arrow-cookie"), pytest.param("run\u00a0--token tttttttttttt", "tttttttttttt", id="no-break-space-token-flag"), ], ) @@ -835,53 +804,6 @@ def test_judge_evidence_masks_credentials_after_json_escaped_tabs_and_non_ascii( assert "" in redacted -# The same headers and flags at the start of a line, or right after a non-ASCII -# character, follow the escape itself ("\n" or "\u00a0"), and the escaped tab -# then separates the name from its value. -@pytest.mark.parametrize( - ("line", "secret", "kept"), - [ - pytest.param( - "Authorization:\tBearer bbbbbbbbbbbb", "bbbbbbbbbbbb", "Bearer ", id="tab-authorization" - ), - pytest.param("Authorization: Bearer\tbbbbbbbbbbbb", "bbbbbbbbbbbb", "Authorization:", id="tab-after-scheme"), - pytest.param( - 'Authorization:\tDigest response="dddddddddddd"', "dddddddddddd", "Digest ", id="tab-digest" - ), - pytest.param("Api-Key:\tkkkkkkkkkkkk", "kkkkkkkkkkkk", "Api-Key:", id="tab-api-key"), - pytest.param("--token\tvvvvvvvvvvvv", "vvvvvvvvvvvv", "--token", id="tab-token-flag"), - pytest.param("-u\tuuuu:pppppppppppp", "pppppppppppp", "-u", id="tab-user-flag"), - ], -) -@pytest.mark.parametrize("before", ["HTTP/1.1 200 OK\n", "\u00a0"], ids=["line-start", "after-non-ascii"]) -def test_judge_evidence_masks_credentials_after_json_escaped_tabs_at_line_starts( - line: str, secret: str, kept: str, before: str -) -> None: - text = before + line - 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 - assert "" in redacted - - -def test_judge_evidence_masks_tab_separated_credentials_in_ragas_prompts_and_heredocs() -> None: - agent_text = "HTTP/1.1 200 OK\nAuthorization:\tBearer bbbbbbbbbbbb\nApi-Key:\tkkkkkkkkkkkk" - prompt = json.dumps({"user_input": [{"content": agent_text, "type": "ai"}]}, indent=4) - arguments = json.dumps({"command": "cat <\\nApi-Key:\\t" in redacted_prompt - assert "\\nApi-Key:\\t\\n--token\\t\\nEOF" in redacted_arguments - for secret in ("bbbbbbbbbbbb", "kkkkkkkkkkkk", "vvvvvvvvvvvv"): - assert secret not in redacted_prompt + redacted_arguments - - @pytest.mark.parametrize( "text", [ diff --git a/tests/tier3/test_ragas_judge_evidence.py b/tests/tier3/test_ragas_judge_evidence.py index 930d8b413..41cfbb41e 100644 --- a/tests/tier3/test_ragas_judge_evidence.py +++ b/tests/tier3/test_ragas_judge_evidence.py @@ -406,34 +406,23 @@ 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 _tool_call_reply(arguments: str, *, content: str | None = None) -> dict[str, Any]: - reply = _chat_reply("") - reply["choices"][0]["message"] = { - "role": "assistant", - "content": content, - "tool_calls": [{"id": "call-1", "type": "function", "function": {"name": "Verdict", "arguments": arguments}}], - } - reply["choices"][0]["finish_reason"] = "tool_calls" - return reply - - 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 tool-call arguments are JSON too. + """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" + "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}]) - reply = _tool_call_reply(json.dumps({"end_state": agent_text, "verdict": 1})) - received = _stub_provider(monkeypatch, [reply]) + 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") @@ -443,46 +432,12 @@ def test_ragas_evidence_masks_credentials_at_json_escaped_line_starts( exchange, outcome = _attempts(verifier) assert [exchange["status"], outcome["status"]] == ["replied", "accepted"] for field in ("prompt", "reply"): - assert "\\nAuthorization: Bearer \\nCookie: \\n--token " in exchange[field] - saved = (verifier.VERIFIER_DIR / "judge_attempts.json").read_text(encoding="utf-8") - for secret in ("bbbbbbbbbbbb", "cccccccccccc", "tttttttttttt"): - assert secret not in saved - - -def test_ragas_evidence_masks_quoted_credentials_in_a_repeated_tool_call(verifier: ModuleType) -> None: - """A request that repeats an earlier tool call writes its JSON arguments as JSON again. - - The quotes in the arguments then reach the prompt escaped twice, as a run of - backslashes before each quote. - """ - end_state = 'Ran deploy --token "tttt qqqq" with headers={"Authorization": "Bearer jjjjjjjjjjjj"}' - arguments = json.dumps({"end_state": end_state, "verdict": 1}) - messages = [ - {"role": "user", "content": "Judge the agent.\ninput: " + json.dumps({"end_state": end_state})}, - { - "role": "assistant", - "content": None, - "tool_calls": [ - {"id": "call-1", "type": "function", "function": {"name": "Verdict", "arguments": arguments}} - ], - }, - {"role": "tool", "tool_call_id": "call-1", "content": "error: the verdict could not be parsed"}, - ] - request = httpx.Request("POST", _CHAT_URL, json={"model": "gpt-4.1", "messages": messages}) - reply = json.dumps(_tool_call_reply(arguments)).encode() - - with _judge_evidence(verifier): - verifier._record_ragas_exchange(httpx.Response(200, content=reply, request=request)) - - (exchange,) = _attempts(verifier) - assert exchange["status"] == "replied" - # Once escaped in the user message and the reply, twice in the repeated tool call. - assert exchange["prompt"].count("--token ") == 2 - assert exchange["prompt"].count("Bearer ") == 2 - assert "--token " in exchange["reply"] - assert "Bearer " in exchange["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 ("tttt qqqq", "jjjjjjjjjjjj"): + for secret in ("bbbbbbbbbbbb", "cccccccccccc", "tttttttttttt", "pppppppppppp"): assert secret not in saved From 862a355bfb64f86fd9c081c86b2d45049e419861 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Fri, 13 Nov 2026 07:14:28 -0800 Subject: [PATCH 12/18] fix(tier3): mask whole judge evidence text before its escaped lines _redact_judge_evidence split the text at JSON escapes and masked each piece on its own before it masked the whole text. A form that runs over an escape was then cut there. The BEGIN line of a private key block was replaced on its own, so the whole-text pass no longer found the block and kept the key body. A continued command (sshpass -p, docker login -p and --password followed by an escaped backslash and line break), a quoted value with an escaped line break or tab, and a value that holds a non-ASCII escape (p\u00e4ss) or a backslash (C:\new) kept the part after the escape. Main masks all of these. The whole text is now masked first, as on main, and the text between "\n", "\r" and "\t" escapes is masked after it as lines of their own. A "\uXXXX" escape no longer splits the text, so a value that holds one and starts a line is masked whole. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +- .../tier3/harbor/templates/eval.py | 46 ++++--- tests/tier3/test_judge_contracts.py | 120 ++++++++++++++++-- tests/tier3/test_ragas_judge_evidence.py | 28 ++++ tests/tier3/test_security_finding_evidence.py | 15 +++ 5 files changed, 185 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea1081fef..90676dcf5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,10 +48,9 @@ All notable changes to SkillEvaluator are documented in this file. (`--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`) or non-ASCII character - (`\u00a0`). 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. + saved in clear after it or after an escaped tab (`\t`). 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. ## 0.9.0 - 2026-11-13 diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py index 6f343aa08..fbd5591ef 100644 --- a/src/skillevaluator/tier3/harbor/templates/eval.py +++ b/src/skillevaluator/tier3/harbor/templates/eval.py @@ -2824,17 +2824,26 @@ def _judge_retry_feedback(problem): # 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", and a non-ASCII character such as a no-break space as "\u00a0". -# A header, flag or key that starts a line there follows the last letter or -# digit of the escape, where patterns that need a line start, a space or a word -# boundary before it do not match, and an unquoted value on the line before -# can read on through the escape into the next line's header name. So the -# text between escapes is masked line by line first, and the whole text after. -_JUDGE_EVIDENCE_ESCAPE_RE = re.compile(r"(\\(?:[nrt]|u[0-9a-fA-F]{4}))") +# "\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_shapes(text): - """Mask the credential forms and key shapes that depend on what precedes them.""" +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(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: @@ -2844,17 +2853,16 @@ def _mask_judge_evidence_shapes(text): def _redact_judge_evidence(text): """Mask credentials in a judge prompt, reply, or problem before it is saved.""" + # 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(str(text)) + parts = _JUDGE_EVIDENCE_ESCAPE_RE.split(redacted) + if len(parts) == 1: + return redacted # Text and escapes alternate. - parts = _JUDGE_EVIDENCE_ESCAPE_RE.split(str(text)) - if len(parts) > 1: - parts[::2] = [_mask_judge_evidence_shapes(part) if part else part for part in parts[::2]] - # 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("".join(parts), preserve_header_format=True) - redacted = _redact_configured_credentials(_redact_evidence_text(redacted)) - for pattern in _SECRET_PATTERNS: - redacted = pattern.sub("", redacted) - return redacted + parts[::2] = [_mask_judge_evidence_line(part) if part else part for part in parts[::2]] + return "".join(parts) def _verifier_output_dir(): diff --git a/tests/tier3/test_judge_contracts.py b/tests/tier3/test_judge_contracts.py index 0763ffea9..8cd66ba36 100644 --- a/tests/tier3/test_judge_contracts.py +++ b/tests/tier3/test_judge_contracts.py @@ -779,31 +779,135 @@ def test_judge_evidence_masks_credentials_after_json_escaped_line_breaks( assert kept in redacted -# json.dumps writes a tab as "\t" and, by default, a non-ASCII character as -# "\uXXXX", so in JSON a credential can follow the letter t or a hex digit. +# 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"), - pytest.param("key\u00a0ghp_" + "g" * 36, "g" * 36, id="no-break-space-github-token"), - pytest.param("\u201csk-proj-" + "a" * 24 + "\u201d", "a" * 24, id="curly-quote-openai-key"), - pytest.param("\u2192Cookie: session=cccccccccccc", "cccccccccccc", id="arrow-cookie"), - pytest.param("run\u00a0--token tttttttttttt", "tttttttttttt", id="no-break-space-token-flag"), ], ) -def test_judge_evidence_masks_credentials_after_json_escaped_tabs_and_non_ascii(text: str, secret: str) -> None: +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 or "\\u" in escaped + 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 + + @pytest.mark.parametrize( "text", [ diff --git a/tests/tier3/test_ragas_judge_evidence.py b/tests/tier3/test_ragas_judge_evidence.py index 41cfbb41e..68c307016 100644 --- a/tests/tier3/test_ragas_judge_evidence.py +++ b/tests/tier3/test_ragas_judge_evidence.py @@ -441,6 +441,34 @@ def test_ragas_evidence_masks_credentials_at_json_escaped_line_starts( 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"), [ diff --git a/tests/tier3/test_security_finding_evidence.py b/tests/tier3/test_security_finding_evidence.py index 245cee373..85e4853ab 100644 --- a/tests/tier3/test_security_finding_evidence.py +++ b/tests/tier3/test_security_finding_evidence.py @@ -1294,6 +1294,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"') From 6661151f8460f184737942317c4db49a03f87ef9 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Fri, 13 Nov 2026 21:42:18 -0800 Subject: [PATCH 13/18] fix(tier3): mask credential values in JSON-escaped quotes Tool-call arguments reach every judge prompt as JSON text, so a quoted shell value arrives with escaped quotes (\"...\"). The shared finding masker read that form for credential flag values and assignments, but not for a quoted -u, --user or --proxy-user value, an attached MySQL -p value, a .netrc password, or the elements of an argv list. So `curl -u "admin:SECRET"`, `mysql -p"SECRET"` and `subprocess.run(["tool", "--password", "SECRET"])` in a tool call were saved in clear in judge_attempts.json, on main as well. Those patterns now take the escaped-quote form that credential flag values already use. The argv patterns also take escaped quotes, and "\n" escapes between elements. The -u URL, remote-path and date-format exclusions also see an escaped quote, so `pip install -U \"git+https://...\"`, `rsync -u \"host:/data\"` and `date -u \"+%H:%M\"` stay unmasked. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 ++- docs/tier3-live-evaluation.mdx | 3 +- src/skillevaluator/tier3/eval_core/checks.py | 70 +++++++++++++++----- tests/tier3/test_judge_contracts.py | 40 +++++++++++ 4 files changed, 105 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a864430b..be677ddb9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -262,9 +262,14 @@ All notable changes to SkillEvaluator are documented in this file. (`--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`). 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. + saved in clear after it or after an escaped tab (`\t`). 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 5207fd336..3e7847ca4 100644 --- a/docs/tier3-live-evaluation.mdx +++ b/docs/tier3-live-evaluation.mdx @@ -1393,7 +1393,8 @@ the case is judged and scored normally. 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`. Long prompts and replies are shortened. The prompts + two characters `\n`, and inside JSON-escaped quotes (`-u \"user:password\"`), + as in tool-call arguments. 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. diff --git a/src/skillevaluator/tier3/eval_core/checks.py b/src/skillevaluator/tier3/eval_core/checks.py index fdfe623b7..e772358bd 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,47 @@ 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". +_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( + "(" + _FINDING_EVIDENCE_ARGV_QUOTE + r")-p(?!ath\b|erm\b|rint|rune\b)([^\"'\r\n]+)\1" ) -_FINDING_EVIDENCE_ARGV_ATTACHED_PASSWORD_RE = re.compile(r"([\"'])-p(?!ath\b|erm\b|rint|rune\b)([^\"'\r\n]+)\1") # Bearer, Basic, Token and Digest stay visible after a credential name too # ("Authorization: Bearer "). _FINDING_EVIDENCE_AUTH_SCHEME = r"(?:(?:bearer|basic|token|digest)[ \t]+)?" diff --git a/tests/tier3/test_judge_contracts.py b/tests/tier3/test_judge_contracts.py index 1b2d5c365..4161ddab9 100644 --- a/tests/tier3/test_judge_contracts.py +++ b/tests/tier3/test_judge_contracts.py @@ -1276,6 +1276,40 @@ def test_judge_evidence_masks_multi_line_tool_call_arguments() -> None: 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 + + @pytest.mark.parametrize( "text", [ @@ -1289,6 +1323,12 @@ def test_judge_evidence_masks_multi_line_tool_call_arguments() -> None: "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"]'), ], ) def test_judge_evidence_keeps_ordinary_text(text: str) -> None: From f81cb6a7416dceb57ecce628dac388cfb39582bb Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Fri, 13 Nov 2026 21:47:44 -0800 Subject: [PATCH 14/18] ci(gitleaks): allow the JSON-escaped-quote judge evidence test placeholder The judge evidence tests added in 6661151f build `curl -u "admin:{_QUOTED_SECRET}"` fixtures, and Gitleaks' curl-auth-user rule reads the f-string placeholder as a basic-auth credential. Allow exactly that placeholder in tests/tier3/test_judge_contracts.py, as the existing entry does for "admin:quoted-user-password". History scans keep 6661151f, so the test text itself is left as is. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- .gitleaks.toml | 7 +++++++ 1 file changed, 7 insertions(+) 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" From aac2a96c7dc25fcac033fac2b3278a968f6347f1 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Fri, 13 Nov 2026 22:54:24 -0800 Subject: [PATCH 15/18] fix(tier3): mask the line after a credential value that reads through a JSON escape An unquoted credential value that ends a line in JSON-escaped text reads the "\n" escape as one escaped character, so the whole-text pass masked the next line's flag or header name together with it: `--password A\n--token B` became `--password B`. The line pass then found no name before B, and B was saved in clear in judge_attempts.json. This happened after --token, --password, -u, sshpass -p, docker login -p, aws configure set and npm config set values, inside quoted tool-call arguments and RAGAS prompts, escaped once or twice. _redact_judge_evidence keeps masking the whole text first, so forms that run over an escape stay masked whole. It now also runs the line pass over the lines of the original text, recovers the values it replaced there, and masks each of them wherever it is left in the result. As with configured credentials, only values of at least 8 characters are masked that way, so a shorter value after such a line is still kept; the CHANGELOG and docs say so. Each distinct line is masked once per call. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 ++- docs/tier3-live-evaluation.mdx | 6 +- .../tier3/harbor/templates/eval.py | 95 ++++++++++++++++++- tests/tier3/test_judge_contracts.py | 24 +++++ tests/tier3/test_ragas_judge_evidence.py | 52 ++++++++++ 5 files changed, 179 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index be677ddb9..7e833522b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -262,11 +262,15 @@ All notable changes to SkillEvaluator are documented in this file. (`--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`). 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. + saved in clear after it or after an escaped tab (`\t`). That includes a line + after one whose unquoted credential value read on through the escape and was + masked together with the next line's flag or header name + (`--password ...\n--token ...`); there a value shorter than 8 characters is + still kept. 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. diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx index 3e7847ca4..dd7d262d5 100644 --- a/docs/tier3-live-evaluation.mdx +++ b/docs/tier3-live-evaluation.mdx @@ -1394,8 +1394,10 @@ the case is judged and scored normally. `--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. Long prompts and replies are shortened. The prompts - contain the task question, expected answer, and agent evidence. Pass + as in tool-call arguments. A value that starts the line after an unquoted + credential flag value (`--password ...\n--token ...`) is masked there only if + it has at least 8 characters. 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 diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py index c638ac5f4..080008490 100644 --- a/src/skillevaluator/tier3/harbor/templates/eval.py +++ b/src/skillevaluator/tier3/harbor/templates/eval.py @@ -2872,18 +2872,103 @@ def _mask_judge_evidence_line(text): 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")+" +) + + +def _judge_evidence_line_values(text, masked): + """Return the values that the line pass, which wrote *masked*, replaced in *text*. + + 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 [] + values = [] + for between in kept[1:-1]: + found = text.find(between, start, end) + if found < 0: + return values + values.append(text[start:found]) + start = found + len(between) + values.append(text[start:end]) + return values + + +def _mask_judge_evidence_values(text, values): + """Replace each of the set *values*, none shorter than _MIN_EXACT_SECRET_LENGTH, in *text*, the longest first.""" + # The text is read once, however many values there are: at each position + # its first characters name the lengths of the values that start with them. + lengths = {} + for value in values: + lengths.setdefault(value[:_MIN_EXACT_SECRET_LENGTH], set()).add(len(value)) + lengths = {start: sorted(found, reverse=True) for start, found in lengths.items()} + parts = [] + pos = index = 0 + last = len(text) - _MIN_EXACT_SECRET_LENGTH + while index <= last: + for length in lengths.get(text[index : index + _MIN_EXACT_SECRET_LENGTH], ()): + if text[index : index + length] in values: + parts.append(text[pos:index]) + parts.append("") + index = pos = index + length + break + else: + index += 1 + 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(str(text)) + 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: + 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 - # Text and escapes alternate. - parts[::2] = [_mask_judge_evidence_line(part) if part else part for part in parts[::2]] - return "".join(parts) + # 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 starts a line. The lines of the original text still hold that + # name, so each value the line pass masks there is masked wherever it is + # left. As with configured credentials, a shorter value is too likely to be + # an ordinary word to be masked everywhere. 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". + values = set() + for line in dict.fromkeys(lines): + masked = mask_line(line) if line else line + if masked != line: + values.update(value.rstrip("\\") for value in _judge_evidence_line_values(line, masked)) + values = { + value + for value in values + if len(value) >= _MIN_EXACT_SECRET_LENGTH and " None: 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. +@pytest.mark.parametrize( + "text", + [ + pytest.param("--password aaaaaaaaaaaa\n--token bbbbbbbbbbbb", id="password-then-token"), + pytest.param("-u uuuu:aaaaaaaaaaaa\nCookie: session=bbbbbbbbbbbb", id="user-then-cookie"), + pytest.param("deploy --token aaaaaaaaaaaa\nAuthorization: Bearer bbbbbbbbbbbb", id="token-then-authorization"), + pytest.param("sshpass -p aaaaaaaaaaaa\n--token bbbbbbbbbbbb", id="sshpass-then-token"), + pytest.param("docker login -u bot -p aaaaaaaaaaaa\nCookie: session=bbbbbbbbbbbb", id="login-then-cookie"), + ], +) +def test_judge_evidence_masks_consecutive_credential_lines_in_json_escaped_text(text: 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 "bbbbbbbbbbbb" not in redacted + # Only the value is masked; the rest of the text stays as it was. + assert redacted.endswith("" + form.split("bbbbbbbbbbbb")[-1]) + + @pytest.mark.parametrize( "text", [ diff --git a/tests/tier3/test_ragas_judge_evidence.py b/tests/tier3/test_ragas_judge_evidence.py index 68c307016..e3b84929a 100644 --- a/tests/tier3/test_ragas_judge_evidence.py +++ b/tests/tier3/test_ragas_judge_evidence.py @@ -441,6 +441,58 @@ def test_ragas_evidence_masks_credentials_at_json_escaped_line_starts( 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. + """ + 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"}, + }, + ], + }, + ] + } + 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] + 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: From 2ef8839f7ea624a7a3ba8cec79968d5e778aea2c Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Fri, 13 Nov 2026 23:41:31 -0800 Subject: [PATCH 16/18] fix(tier3): mask a line's value only where the whole pass took its name aac2a96c masked each value that the line pass recovered from the original lines everywhere in the saved text, as a plain substring. A value that the shared masker flags by mistake (tokenizer_name: MODEL, api_key: Optional[str], password: required) was then erased from the whole prompt, also inside words ($GITHUB_TOKEN_FILE), and values shorter than 8 characters were still kept after a swallowed name. The value is now masked only where the whole pass left it: in the text between a marker and the next escape or marker that equals the rest of its line, from a character where an unquoted value that read on into the line stops, up to the next value masked there or the line end. Values of any length are masked there; other copies of a value are left as before. The lookup is one dict get per marker, so redaction stays linear: the inputs that took 11 to 17 s with aac2a96c take 0.3 to 1.0 s, as on f81cb6a7. Tests pin short values, a value two lines after the swallowing value, and ordinary copies of masked values (model name, type annotation, YAML word, variable name, user id) that must stay. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 18 +-- docs/tier3-live-evaluation.mdx | 12 +- .../tier3/harbor/templates/eval.py | 135 ++++++++++++------ tests/tier3/test_judge_contracts.py | 72 ++++++++-- tests/tier3/test_ragas_judge_evidence.py | 12 +- 5 files changed, 177 insertions(+), 72 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e833522b..71ddf37f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -262,15 +262,15 @@ All notable changes to SkillEvaluator are documented in this file. (`--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 a line - after one whose unquoted credential value read on through the escape and was - masked together with the next line's flag or header name - (`--password ...\n--token ...`); there a value shorter than 8 characters is - still kept. 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. + 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. diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx index dd7d262d5..8c59754f7 100644 --- a/docs/tier3-live-evaluation.mdx +++ b/docs/tier3-live-evaluation.mdx @@ -1394,12 +1394,12 @@ the case is judged and scored normally. `--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. A value that starts the line after an unquoted - credential flag value (`--password ...\n--token ...`) is masked there only if - it has at least 8 characters. 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. + 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/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py index 080008490..b3d76a5e3 100644 --- a/src/skillevaluator/tier3/harbor/templates/eval.py +++ b/src/skillevaluator/tier3/harbor/templates/eval.py @@ -2877,10 +2877,17 @@ def _mask_judge_evidence_line(text): _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_values(text, masked): - """Return the values that the line pass, which wrote *masked*, replaced in *text*. +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. @@ -2891,38 +2898,85 @@ def _judge_evidence_line_values(text, 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 [] - values = [] + return text, [] + spans = [] for between in kept[1:-1]: found = text.find(between, start, end) if found < 0: - return values - values.append(text[start:found]) + return text, spans + spans.append((start, found)) start = found + len(between) - values.append(text[start:end]) - return values - - -def _mask_judge_evidence_values(text, values): - """Replace each of the set *values*, none shorter than _MIN_EXACT_SECRET_LENGTH, in *text*, the longest first.""" - # The text is read once, however many values there are: at each position - # its first characters name the lengths of the values that start with them. - lengths = {} - for value in values: - lengths.setdefault(value[:_MIN_EXACT_SECRET_LENGTH], set()).add(len(value)) - lengths = {start: sorted(found, reverse=True) for start, found in lengths.items()} - parts = [] - pos = index = 0 - last = len(text) - _MIN_EXACT_SECRET_LENGTH - while index <= last: - for length in lengths.get(text[index : index + _MIN_EXACT_SECRET_LENGTH], ()): - if text[index : index + length] in values: - parts.append(text[pos:index]) - parts.append("") - index = pos = index + length - break + 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: - index += 1 + 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) @@ -2952,23 +3006,12 @@ def mask_line(line): # 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 starts a line. The lines of the original text still hold that - # name, so each value the line pass masks there is masked wherever it is - # left. As with configured credentials, a shorter value is too likely to be - # an ordinary word to be masked everywhere. 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". - values = set() - for line in dict.fromkeys(lines): - masked = mask_line(line) if line else line - if masked != line: - values.update(value.rstrip("\\") for value in _judge_evidence_line_values(line, masked)) - values = { - value - for value in values - if len(value) >= _MIN_EXACT_SECRET_LENGTH and " None: # 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. +# the next line with it. That line's value is masked too, as in plain text, +# however short it is. @pytest.mark.parametrize( - "text", + ("text", "second"), [ - pytest.param("--password aaaaaaaaaaaa\n--token bbbbbbbbbbbb", id="password-then-token"), - pytest.param("-u uuuu:aaaaaaaaaaaa\nCookie: session=bbbbbbbbbbbb", id="user-then-cookie"), - pytest.param("deploy --token aaaaaaaaaaaa\nAuthorization: Bearer bbbbbbbbbbbb", id="token-then-authorization"), - pytest.param("sshpass -p aaaaaaaaaaaa\n--token bbbbbbbbbbbb", id="sshpass-then-token"), - pytest.param("docker login -u bot -p aaaaaaaaaaaa\nCookie: session=bbbbbbbbbbbb", id="login-then-cookie"), + 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) -> None: +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 "bbbbbbbbbbbb" 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("bbbbbbbbbbbb")[-1]) + 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( diff --git a/tests/tier3/test_ragas_judge_evidence.py b/tests/tier3/test_ragas_judge_evidence.py index e3b84929a..d97c51d85 100644 --- a/tests/tier3/test_ragas_judge_evidence.py +++ b/tests/tier3/test_ragas_judge_evidence.py @@ -447,8 +447,10 @@ def test_ragas_evidence_masks_consecutive_credential_lines_in_tool_calls( """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. + 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": [ { @@ -465,6 +467,13 @@ def test_ragas_evidence_masks_consecutive_credential_lines_in_tool_calls( "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", + }, + }, ], }, ] @@ -488,6 +497,7 @@ def test_ragas_evidence_masks_consecutive_credential_lines_in_tool_calls( 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 From 19d5c9808f5abd95e9075e546d68110affe44a59 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Sat, 14 Nov 2026 00:07:47 -0800 Subject: [PATCH 17/18] fix(tier3): keep a bare -p argv element in JSON-escaped text 6661151f let the argv login and MySQL context patterns read JSON-escaped quotes, so a \"login\" or \"mysql\" element now gives the attached -pVALUE rule a context in tool-call arguments. That rule failed at the backslash of a bare \"-p\" element and matched again from the bare quote after it, taking the backslash of the closing \" as the value. mkdir -p, ssh -p, git log -p and a prompting mysql -p within 256 characters of such an element became \"-p", an invented password with the escape gone. The leftover bare quote also ended the JSON string for the assignment scanner, so a later "password: correct horse ..." was masked to its first word only. The attached -pVALUE element no longer starts at the bare quote of an escaped one. A real \"-pVALUE\" element is still masked. The other argv patterns cannot start there: the flag pattern needs the same quote on both sides of a name without backslashes, and the login, MySQL and sshpass patterns only find context. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- src/skillevaluator/tier3/eval_core/checks.py | 7 ++++-- tests/tier3/test_judge_contracts.py | 22 ++++++++++++++++++ tests/tier3/test_security_finding_evidence.py | 23 +++++++++++++++++++ 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/src/skillevaluator/tier3/eval_core/checks.py b/src/skillevaluator/tier3/eval_core/checks.py index e772358bd..732d61576 100644 --- a/src/skillevaluator/tier3/eval_core/checks.py +++ b/src/skillevaluator/tier3/eval_core/checks.py @@ -3484,7 +3484,10 @@ def _security_finding( # sit on its own line, as a formatter writes a long list, so up to 64 spaces # 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". +# break is the two characters "\n". An attached "-pVALUE" element never starts +# at the bare quote of an escaped one, so a bare \"-p\" element (mkdir -p, a +# prompting mysql -p) does not read the backslash of its closing quote as a +# value. _FINDING_EVIDENCE_ARGV_QUOTE = r"\\?[\"']" _FINDING_EVIDENCE_ARGV_SPACE = r"(?:\s|\\[nrt]){0,64}" _FINDING_EVIDENCE_ARGV_FLAG_RE = re.compile( @@ -3521,7 +3524,7 @@ def _security_finding( + r"[ \t]*," ) _FINDING_EVIDENCE_ARGV_ATTACHED_PASSWORD_RE = re.compile( - "(" + _FINDING_EVIDENCE_ARGV_QUOTE + r")-p(?!ath\b|erm\b|rint|rune\b)([^\"'\r\n]+)\1" + r"(?"). diff --git a/tests/tier3/test_judge_contracts.py b/tests/tier3/test_judge_contracts.py index ec6205e24..5ab6458a9 100644 --- a/tests/tier3/test_judge_contracts.py +++ b/tests/tier3/test_judge_contracts.py @@ -1405,12 +1405,34 @@ def test_judge_evidence_keeps_copies_of_line_values_elsewhere(text: str, kept: l '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"])'), ], ) 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: "}) + + 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_security_finding_evidence.py b/tests/tier3/test_security_finding_evidence.py index 85e4853ab..0af6da176 100644 --- a/tests/tier3/test_security_finding_evidence.py +++ b/tests/tier3/test_security_finding_evidence.py @@ -1143,12 +1143,35 @@ 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"])'), ], ) 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: "} + ) + + @pytest.mark.parametrize( ("text", "expected"), [ From 19e4f0804a8fd66efef7ca7efad17e889fa4aff5 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Sat, 14 Nov 2026 00:35:01 -0800 Subject: [PATCH 18/18] fix(tier3): mask a twice-escaped attached -pVALUE argv element again 19d5c980 kept the attached -pVALUE rule from starting at any quote with a backslash before it. In an element escaped twice (\\\"-pVALUE\\\"), as when a RAGAS request repeats a tool call's JSON arguments as JSON, every quote has a backslash before it, so the rule could no longer match there and the value was left in clear. 2ef8839f masked it after a mysql or login element in plain, single-quoted or JSON-escaped text, and main after one in plain or single-quoted text. The rule now opens at the start of a backslash run, takes the whole run and its quote, and closes only with the same run and quote. An attached -pVALUE element is masked with its escapes intact at one, two or three escape levels, and a bare -p element (mkdir -p, a prompting mysql -p) is still not read as one at any of them. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- src/skillevaluator/tier3/eval_core/checks.py | 12 +++++---- tests/tier3/test_judge_contracts.py | 26 +++++++++++++++++++ tests/tier3/test_security_finding_evidence.py | 26 +++++++++++++++++++ 3 files changed, 59 insertions(+), 5 deletions(-) diff --git a/src/skillevaluator/tier3/eval_core/checks.py b/src/skillevaluator/tier3/eval_core/checks.py index 732d61576..fe0695f8b 100644 --- a/src/skillevaluator/tier3/eval_core/checks.py +++ b/src/skillevaluator/tier3/eval_core/checks.py @@ -3484,10 +3484,12 @@ def _security_finding( # sit on its own line, as a formatter writes a long list, so up to 64 spaces # 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 never starts -# at the bare quote of an escaped one, so a bare \"-p\" element (mkdir -p, a -# prompting mysql -p) does not read the backslash of its closing quote as a -# value. +# 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( @@ -3524,7 +3526,7 @@ def _security_finding( + r"[ \t]*," ) _FINDING_EVIDENCE_ARGV_ATTACHED_PASSWORD_RE = re.compile( - r"(?"). diff --git a/tests/tier3/test_judge_contracts.py b/tests/tier3/test_judge_contracts.py index 5ab6458a9..cbb4436ae 100644 --- a/tests/tier3/test_judge_contracts.py +++ b/tests/tier3/test_judge_contracts.py @@ -1409,6 +1409,9 @@ def test_judge_evidence_keeps_copies_of_line_values_elsewhere(text: str, kept: l 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: @@ -1433,6 +1436,29 @@ def test_judge_evidence_masks_passphrase_after_bare_p_element(argv: str) -> None 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_security_finding_evidence.py b/tests/tier3/test_security_finding_evidence.py index 0af6da176..4cec8dd26 100644 --- a/tests/tier3/test_security_finding_evidence.py +++ b/tests/tier3/test_security_finding_evidence.py @@ -1148,6 +1148,9 @@ def test_finding_evidence_redaction_masks_credentials(text: str, secrets: tuple[ 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: @@ -1172,6 +1175,29 @@ def test_finding_evidence_masks_passphrase_after_bare_p_element(argv: str) -> No ) +_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"), [