Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
fix(redaction): make sensitive-key, JWT, and private-key matching linear-time (#172)
Narendran Raghavana2b01c74a2c0
diff --git a/.gitleaks.toml b/.gitleaks.tomlindex df15291c..41ff4d10 100644--- a/.gitleaks.toml+++ b/.gitleaks.toml@@ -9,3 +9,9 @@ condition = "AND"targetRules = ["generic-api-key"]regexes = ['''^sk-AbCdEf1234567890$''']paths = ['''^tests/test_tier3_(progress|result_display)\.py$''']++[[allowlists]]+description = "Synthetic JWT and private-key fixtures in the first revision of the redaction tests (PR #172); the file now assembles them from split literals"+condition = "AND"+commits = ["97a0616f7786fc5b10c49aa24b0a55f8d446bcab"]+paths = ['''^tests/test_redaction_assignments\.py$''']diff --git a/src/skillevaluator/utils/redaction.py b/src/skillevaluator/utils/redaction.pyindex 33611c11..027f2564 100644--- a/src/skillevaluator/utils/redaction.py+++ b/src/skillevaluator/utils/redaction.py@@ -33,17 +33,53 @@ _TOKEN_COUNT_KEYS = {"tokens","total_tokens",}+# Assignment keys are runs of [a-z0-9_.-] (the patterns below are case-insensitive).+# A key used to be ``\b[a-z0-9_.-]*(?:word)[a-z0-9_.-]*``, which the regex engine+# retried at every word boundary inside a run and for every way of splitting the+# run around a sensitive word, so one substitution took cubic time on text such as+# ``"token-" * n``. The pattern below captures the same ``key``: the part of a+# maximal key-character run that starts at the run's first word boundary and+# contains a sensitive word. It only starts matching at the beginning of a run,+# captures the characters before that first boundary (the ``--`` of ``--api-key``)+# as ``lead`` so they are written back unchanged, and never backtracks into the+# key, so each substitution is linear in the input length.+_SENSITIVE_KEY_CHAR = r"[a-z0-9_.-]"+_SENSITIVE_KEY_WORD = (+ r"(?:api[_-]?key|secret|password|credential|authorization|bearer|token|"+ r"access[_-]?key|session[_-]?token|private[_-]?key)"+)_SENSITIVE_KEY_PATTERN = (- r"[a-z0-9_.-]*(?:api[_-]?key|secret|password|credential|authorization|bearer|token|"- r"access[_-]?key|session[_-]?token|private[_-]?key)[a-z0-9_.-]*"+ rf"(?<!{_SENSITIVE_KEY_CHAR})"+ # ``lead`` is empty when the run starts at a word boundary. Otherwise the first+ # boundary follows the run's leading [.-] characters ("--api-key"), or its+ # leading [a-z0-9_] characters when the run is glued to a word character that+ # is not a key character ("é" in "étoken.secret").+ r"(?P<lead>\b|(?<=\w)[a-z0-9_]++(?=[.-])|(?<!\w)[.-]++(?=[a-z0-9_]))"+ rf"(?P<key>(?>{_SENSITIVE_KEY_CHAR}*?{_SENSITIVE_KEY_WORD}){_SENSITIVE_KEY_CHAR}*+)")_AUTH_HEADER_RE = re.compile(r"(?im)\b(?P<key>(?:proxy-)?authorization)\s*:\s*(?P<scheme>[A-Za-z]+)\s+[^\r\n]+")_SENSITIVE_QUOTED_ASSIGNMENT_RE = re.compile(- rf"(?i)\b(?P<key>{_SENSITIVE_KEY_PATTERN})\s*(?P<sep>[:=])\s*(?P<quote>[\"'])(?P<value>[^\r\n]*?)(?P=quote)"+ rf"(?i){_SENSITIVE_KEY_PATTERN}\s*+(?P<sep>[:=])\s*+(?:\"[^\"\r\n]*+\"|'[^'\r\n]*+')")-_SENSITIVE_COLON_ASSIGNMENT_RE = re.compile(rf"(?im)\b(?P<key>{_SENSITIVE_KEY_PATTERN})\s*(?P<sep>:)\s*[^\r\n,;]+")-_SENSITIVE_EQUALS_ASSIGNMENT_RE = re.compile(rf"(?i)\b(?P<key>{_SENSITIVE_KEY_PATTERN})\s*(?P<sep>=)\s*[^\s\"',;]+")-_PRIVATE_KEY_LABEL = r"(?:[A-Z0-9][A-Z0-9-]* )*PRIVATE KEY(?: [A-Z0-9][A-Z0-9-]*)*"+# The whitespace after ":" must stay backtrackable: in "token: ," the value is the last blank.+_SENSITIVE_COLON_ASSIGNMENT_RE = re.compile(rf"(?im){_SENSITIVE_KEY_PATTERN}\s*+(?P<sep>:)\s*[^\r\n,;]+")+_SENSITIVE_EQUALS_ASSIGNMENT_RE = re.compile(rf"(?i){_SENSITIVE_KEY_PATTERN}\s*+(?P<sep>=)\s*+[^\s\"',;]+")+# A PEM label word is letters and digits joined by single "-" (the RFC 7468 label+# shape). It used to be ``[A-Z0-9][A-Z0-9-]*``, which can contain "-----", so the+# label of one "-----BEGIN " header ran on across every later header on the line and+# each header rescanned the rest of the text ("-----BEGIN A" * n was quadratic).+# Trade-off: a header is no longer read as a private-key header when a label word has+# "--" or a trailing "-" ("X- PRIVATE KEY"), or when the label only reaches "PRIVATE+# KEY" by running on into the next delimiter on the same line ("-----BEGIN+# CERTIFICATE----------END RSA PRIVATE KEY-----"). RFC 7468 labels do neither.+_PEM_LABEL_WORD = r"[A-Z0-9]++(?:-[A-Z0-9]++)*+"+# The label is committed at its first "PRIVATE KEY" pair that is followed by a space+# or "-----". The former ``(?:word )*PRIVATE KEY`` retried every later pair and+# rescanned the words after it ("PRIVATE KEY " * n was quadratic), but a later pair+# can only reach the same label end, because the words after the first pair lead to+# the same end.+_PRIVATE_KEY_LABEL = rf"(?>(?:{_PEM_LABEL_WORD} )*?PRIVATE KEY(?= |-----))(?: {_PEM_LABEL_WORD})*+"+_PRIVATE_KEY_HEADER_RE = re.compile(rf"-----BEGIN {_PRIVATE_KEY_LABEL}-----")_PEM_REDACTIONS = ((re.compile(@@ -61,19 +97,21 @@ _PEM_REDACTIONS = (),"private-key-<redacted>",),- (- re.compile(- rf"-----BEGIN {_PRIVATE_KEY_LABEL}-----"- r"(?![\s\S]*-----END )[\s\S]*\Z"- ),- "private-key-<redacted>",- ),+)+# A JWT used to start at any ``\beyJ``, so in a run of JWT characters such as+# "eyJ-" * n every "-eyJ" was a start, and each start scanned to the end of the run+# looking for ".". Now a match starts only at the beginning of a run. The part of+# the run before its first ``\beyJ`` is captured as ``lead`` and written back+# unchanged, which keeps JWTs glued to a "-" (x-eyJ...) redacted. Later starts in the+# same run are never tried: their first segment reaches the same "." with fewer+# characters, so they could only fail where the first start failed.+_JWT_CHAR = r"[A-Za-z0-9_-]"+_JWT_RE = re.compile(+ rf"(?<!{_JWT_CHAR})(?P<lead>(?>(?:\b|{_JWT_CHAR}*?-)(?=eyJ)))"+ rf"eyJ{_JWT_CHAR}{{10,}}+\.eyJ{_JWT_CHAR}{{10,}}+\.{_JWT_CHAR}{{10,}}\b")_REDACTIONS = (- (- re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b"),- "jwt-<redacted>",- ),+ (_JWT_RE, r"\g<lead>jwt-<redacted>"),(re.compile(r"(?:AKIA|ASIA)[A-Z0-9]{16}"), "aws-access-key-<redacted>"),(re.compile(r"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]{8,}"), "Bearer <redacted>"),(re.compile(r"(?<![A-Za-z0-9_-])sk-[a-zA-Z0-9_-]{8,}"), "sk-<redacted>"),@@ -109,13 +147,28 @@ def _redact_sensitive_assignment(match: re.Match[str]) -> str:key = match.group("key")if not is_sensitive_key(key):return match.group(0)- return f"{key}{match.group('sep')}<redacted>"+ return f"{match.group('lead')}{key}{match.group('sep')}<redacted>"def _redact_auth_header(match: re.Match[str]) -> str:return f"{match.group('key')}: {match.group('scheme')} <redacted>"+def _redact_unterminated_private_key(text: str) -> str:+ """Redact from the first private-key header with no later ``-----END `` to the end of the text."""+ # Same result as substituting ``HEADER(?![\s\S]*-----END )[\s\S]*\Z``, whose+ # lookahead rescanned the rest of the text from every header. A header qualifies+ # when the last "-----END " in the text starts before the header ends.+ last_end = text.rfind("-----END ")+ match = _PRIVATE_KEY_HEADER_RE.search(text)+ while match is not None:+ if match.end() > last_end:+ return f"{text[: match.start()]}private-key-<redacted>"+ # Headers can overlap ("...PRIVATE KEY-----BEGIN ..."), so resume inside this one.+ match = _PRIVATE_KEY_HEADER_RE.search(text, match.start() + 1)+ return text++def redact_sensitive_text(value: str, *, max_len: int | None = None) -> str:"""Best-effort masking for credentials before writing logs or artifacts."""out = value@@ -123,6 +176,7 @@ def redact_sensitive_text(value: str, *, max_len: int | None = None) -> str:# or header rule can consume only its BEGIN delimiter and orphan the body.for pattern, replacement in _PEM_REDACTIONS:out = pattern.sub(replacement, out)+ out = _redact_unterminated_private_key(out)out = _AUTH_HEADER_RE.sub(_redact_auth_header, out)out = _SENSITIVE_QUOTED_ASSIGNMENT_RE.sub(_redact_sensitive_assignment, out)out = _SENSITIVE_COLON_ASSIGNMENT_RE.sub(_redact_sensitive_assignment, out)diff --git a/tests/test_redaction_assignments.py b/tests/test_redaction_assignments.pynew file mode 100644index 00000000..b7a1998f--- /dev/null+++ b/tests/test_redaction_assignments.py@@ -0,0 +1,185 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Credential redaction: representative outputs and linear-time matching."""++from __future__ import annotations++import time++import pytest++from skillevaluator.utils.redaction import redact_sensitive_text+++ ("source", "expected"),+ [+ pytest.param('api_key = "abc def"', "api_key=<redacted>", id="quoted-double"),+ pytest.param("API_KEY: 'abc def'", "API_KEY:<redacted>", id="quoted-single-colon"),+ pytest.param(+ 'password="it\'s a secret" user=bob',+ "password=<redacted> user=bob",+ id="mixed-quotes-single-inside-double",+ ),+ pytest.param("token='say \"hi\"' next", "token=<redacted> next", id="mixed-quotes-double-inside-single"),+ pytest.param(+ "name=\"bob\" token=\"t1\" note='ok' secret='s2'",+ "name=\"bob\" token=<redacted> note='ok' secret=<redacted>",+ id="quoted-sensitive-and-plain-keys",+ ),+ pytest.param(+ 'client_secret: "s3cr3t", region: us-east-1',+ "client_secret:<redacted>, region: us-east-1",+ id="quoted-then-colon",+ ),+ pytest.param("password: hunter2, user: bob", "password:<redacted>, user: bob", id="colon"),+ pytest.param("db.password : hunter2; retries: 3", "db.password:<redacted>; retries: 3", id="colon-dotted-key"),+ pytest.param(+ "token=a; secret=b, password=c",+ "token=<redacted>; secret=<redacted>, password=<redacted>",+ id="equals-several",+ ),+ pytest.param("--api-key=abc123 --verbose", "--api-key=<redacted> --verbose", id="equals-cli-flag"),+ pytest.param("..secret=abc", "..secret=<redacted>", id="equals-leading-dots"),+ pytest.param("étoken.secret=abc", "étoken.secret=<redacted>", id="equals-key-after-non-ascii-word"),+ pytest.param(+ "token_count=42 total_tokens: 100 max_tokens=5",+ "token_count=42 total_tokens: 100 max_tokens=5",+ id="token-counts-kept",+ ),+ pytest.param("password:\n hunter2\nuser: bob", "password:<redacted>\nuser: bob", id="multiline-colon-value"),+ pytest.param(+ "export GITHUB_TOKEN=ghp_example\nexport PATH=/usr/bin\nsession_token: 'abc'\nprivate-key = \"xyz\"",+ "export GITHUB_TOKEN=<redacted>\nexport PATH=/usr/bin\nsession_token:<redacted>\nprivate-key=<redacted>",+ id="multiline-mixed",+ ),+ ],+)+def test_redact_sensitive_text_redacts_assignments(source: str, expected: str) -> None:+ assert redact_sensitive_text(source) == expected+++# Synthetic fixtures are assembled from split literals so secret scanners do not flag them.+_JWT = "eyJhbGciOiJIUzI1NiJ9." + "eyJzdWIiOiIxMjM0NTY3ODkwIn0." + "dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U"+++ ("source", "expected"),+ [+ pytest.param(_JWT, "jwt-<redacted>", id="start-of-text"),+ pytest.param(f"x {_JWT} y", "x jwt-<redacted> y", id="after-space"),+ pytest.param(f'"{_JWT}"', '"jwt-<redacted>"', id="quoted"),+ pytest.param(f"jwt={_JWT}", "jwt=jwt-<redacted>", id="after-equals"),+ pytest.param(f"Bearer {_JWT}", "Bearer jwt-<redacted>", id="after-bearer"),+ pytest.param(f"x-{_JWT}", "x-jwt-<redacted>", id="glued-to-dash"),+ pytest.param(f"abc-def-{_JWT}", "abc-def-jwt-<redacted>", id="glued-to-dashed-run"),+ pytest.param(f"eyJ-eyJ-{_JWT}", "jwt-<redacted>", id="run-starts-with-eyJ"),+ pytest.param(f"{_JWT}.{_JWT}", "jwt-<redacted>.jwt-<redacted>", id="two-dotted"),+ pytest.param(f"a_{_JWT}", f"a_{_JWT}", id="glued-to-underscore-kept"),+ pytest.param(f"x{_JWT}", f"x{_JWT}", id="glued-to-letter-kept"),+ pytest.param(f"é{_JWT}", f"é{_JWT}", id="glued-to-non-ascii-letter-kept"),+ ],+)+def test_redact_sensitive_text_redacts_jwt_by_position(source: str, expected: str) -> None:+ assert redact_sensitive_text(source) == expected+++_BEGIN = "-----BEGIN "+_END = "-----END "+_PEM_BODY = "synthetic-key-material"+++ ("source", "expected"),+ [+ pytest.param(+ f"{_BEGIN}X-Y PRIVATE KEY-----\n{_PEM_BODY}\n{_END}X-Y PRIVATE KEY-----",+ "private-key-<redacted>",+ id="dashed-label-word",+ ),+ pytest.param(+ f"{_BEGIN}A-B-C PRIVATE KEY 1-----\n{_PEM_BODY}\n{_END}A-B-C PRIVATE KEY 1-----",+ "private-key-<redacted>",+ id="words-before-and-after",+ ),+ pytest.param(+ f"{_BEGIN}PRIVATE KEYS PRIVATE KEY-----\n{_PEM_BODY}\n{_END}PRIVATE KEYS PRIVATE KEY-----",+ "private-key-<redacted>",+ id="later-private-key-pair",+ ),+ pytest.param(+ f"{_BEGIN}PRIVATE KEY-----{_PEM_BODY}{_END}PRIVATE KEY-----",+ "private-key-<redacted>",+ id="single-line",+ ),+ pytest.param(+ f"{_BEGIN}A{_BEGIN}RSA PRIVATE KEY-----\n{_PEM_BODY}\n{_END}RSA PRIVATE KEY-----",+ f"{_BEGIN}Aprivate-key-<redacted>",+ id="glued-to-earlier-header",+ ),+ pytest.param(+ f"{_END}CERTIFICATE-----\n{_BEGIN}PRIVATE KEY-----\n{_PEM_BODY}",+ "-----END CERTIFICATE-----\nprivate-key-<redacted>",+ id="truncated-after-earlier-end",+ ),+ pytest.param(f"{_BEGIN}PRIVATE KEY-----END x", "private-key-<redacted>", id="truncated-header-runs-into-end"),+ pytest.param(+ f"{_BEGIN}PRIVATE KEY{_BEGIN}PRIVATE KEY-----\n{_PEM_BODY}",+ "private-key-<redacted>",+ id="truncated-overlapping-headers",+ ),+ ],+)+def test_redact_sensitive_text_redacts_private_key_labels(source: str, expected: str) -> None:+ assert redact_sensitive_text(source) == expected+++# Inputs shaped to make the former patterns backtrack. For the assignment key pattern,+# ``\b[a-z0-9_.-]*(?:word)[a-z0-9_.-]*``: a word boundary at every offset of one long+# key-character run, many sensitive words in one run, and runs followed by a value+# that never matches. For the JWT pattern: an ``eyJ`` start after every "-" of one+# run. For the private-key patterns: header labels that ran on across later headers,+# many "PRIVATE KEY" pairs in one label, and many headers before one final "-----END ".+# Each took seconds with the former patterns and takes milliseconds now.+_ADVERSARIAL_INPUTS = {+ "boundary-at-every-offset": "a-" * 5_000,+ "dotted-boundary-at-every-offset": "x." * 5_000,+ "repeated-word-without-separator": "token" * 10_000,+ "dashed-repeated-word-without-separator": "token-" * 400,+ "unterminated-quote": "token-" * 300 + "token='" + "x" * 3_000,+ "blank-colon-value": "token" * 5_000 + ":" + "\n" * 25_000 + ",",+ "blank-equals-value": "token" * 5_000 + "=" + " " * 25_000 + ",",+ "jwt-start-after-every-dash": "eyJ-" * 32_768,+ "pem-label-across-headers": f"{_BEGIN}A" * 10_923,+ "pem-repeated-private-key-headers": f"{_BEGIN}PRIVATE KEY-----" * 4_855,+ "pem-repeated-private-key-pairs": _BEGIN + "PRIVATE KEY " * 5_000,+ "pem-headers-before-final-end": f"{_BEGIN}PRIVATE KEY-----\n" * 7_000 + f"{_END}x",+ "pem-label-word-ending-in-dash": f"{_BEGIN}PRIVATE KEY X-" * 2_622,+}+# Every other adversarial input must come back unchanged.+_ADVERSARIAL_OUTPUTS = {+ "pem-repeated-private-key-headers": "private-key-<redacted>",+ "pem-label-word-ending-in-dash": "private-key-<redacted>",+}++[email protected](("name", "source"), list(_ADVERSARIAL_INPUTS.items()), ids=list(_ADVERSARIAL_INPUTS))+def test_redact_sensitive_text_is_fast_on_adversarial_inputs(name: str, source: str) -> None:+ started = time.perf_counter()+ redacted = redact_sensitive_text(source)+ elapsed = time.perf_counter() - started++ assert elapsed < 1.0, f"redaction took {elapsed:.2f}s on a {len(source)}-character input"+ assert redacted == _ADVERSARIAL_OUTPUTS.get(name, source)+++def test_redact_sensitive_text_redacts_value_after_long_key_run() -> None:+ prefix = "a-" * 5_000++ started = time.perf_counter()+ redacted = redact_sensitive_text(f"{prefix}token=s3cr3t\n{prefix}secret: 's3cr3t'")+ elapsed = time.perf_counter() - started++ assert elapsed < 1.0, f"redaction took {elapsed:.2f}s"+ assert redacted == f"{prefix}token=<redacted>\n{prefix}secret:<redacted>"