Skip to content

fix(report): replace translate with str.replace in _json_for_script - #549

Merged
harrycav merged 1 commit into
awslabs:devfrom
digalaviz:fix/457-json-for-script-fast-escape
Nov 10, 2026
Merged

harrycav merged 1 commit into
awslabs:devfrom
digalaviz:fix/457-json-for-script-fast-escape

Conversation

@digalaviz

Copy link
Copy Markdown
Contributor

tl;dr: Since 1.0.1, writing an HTML report with individual_results_jsonl_path escaped its embedded JSON with a multi-character str.translate table, which is about ten times slower than json.dumps. _json_for_script now applies the same five escapes with str.replace. The page bytes are unchanged, so the #431 script-block protection is unchanged.

Closes #457.


for agents

intent

#457 "Done when": use the .replace chain; a test asserting byte-identical output against the translate version for <, >, &, U+2028, U+2029 and non-ASCII text; the existing tests/reporting/html/test_script_embedding.py guards pass; timing re-measured with the tree recorded.

behavior

  • trigger: any report that embeds document data or field thresholds (docs_json, thresholds_json in EvaluationHTMLReporter).
  • effect: the same bytes, faster. <, >, &, U+2028, U+2029 are still written as \uXXXX.
  • unchanged: the callers, the page's JavaScript, json.dumps options, every other report section.

code

  • src/stickler/reporting/html/html_reporter.py: _SCRIPT_SAFE (str.maketrans table) replaced by _SCRIPT_SAFE_ESCAPES (pairs); _json_for_script applies them with str.replace. The comment states why.
  • tests/reporting/html/test_script_embedding.py: test_json_for_script_is_byte_identical_to_the_translate_escape, 9 cases, with the 1.0.1 table kept in the test as the oracle.
  • CHANGELOG.md: [Unreleased] / ### Fixed entry.

commits

  • fix(report): replace translate with str.replace in _json_for_script: patch, fixes a 1.0.1 performance regression; no public contract changes.

verification

  • timing on base dev ce6c100 plus this change (the commit SHA is on this PR), CPython 3.12.13, a 5.2 MB list of dicts whose reason strings contain >= and <: json.dumps 14 ms, _json_for_script before 210 ms, after 22 ms.
  • byte-identical to the 1.0.1 function over 25,000 random values (nested containers, BMP and astral characters, </script>, backslashes, long strings), and over 200,000 strings on CPython 3.10 and 3.14.
  • mutation check: dropping the < or & escape fails the new test. Dropping U+2028/U+2029 changes nothing today, because json.dumps already escapes both under ensure_ascii=True, as the code comment says.
  • pytest tests/ -q -n auto: 4110 passed, 13 skipped, 1 xfailed. ruff check clean on the changed files.

not covered

- a multi-character str.translate table leaves the CPython ASCII fast
  path, so escaping the embedded JSON was ~10x slower than json.dumps
  on large reports (regression since 1.0.1)
- on a 5.2 MB payload: before ~210 ms, after ~22 ms, json.dumps ~14 ms
- str.replace on <, >, &, U+2028 and U+2029 keeps the fast path
- output is byte-identical, checked by a new test against the 1.0.1
  translate table
- add a CHANGELOG entry

Closes awslabs#457
@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-11-08T23:11:43+00:00
  • Time since scan: 3 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-11-08T23:08:25+00:00
  • ASH version: 3.1.2

Summary

Scanner Results

The table below shows findings by scanner, with status based on severity thresholds and dependencies:

  • Severity levels:
    • Suppressed (S): Findings that have been explicitly suppressed and don't affect scanner status
    • Critical (C): Highest severity findings that require immediate attention
    • High (H): Serious findings that should be addressed soon
    • Medium (M): Moderate risk findings
    • Low (L): Lower risk findings
    • Info (I): Informational findings with minimal risk
  • Duration (Time): Time taken by the scanner to complete its execution
  • Actionable: Number of findings at or above the threshold severity level that require attention
  • Result:
    • PASSED = No findings at or above threshold
    • FAILED = Findings at or above threshold
    • MISSING = Required dependencies not available
    • SKIPPED = Scanner explicitly disabled
    • ERROR = Scanner execution error
  • Threshold: The minimum severity level that will cause a scanner to fail
    • Thresholds: ALL, LOW, MEDIUM, HIGH, CRITICAL
    • Source: Values in parentheses indicate where the threshold is set:
      • global (global_settings section in the ASH_CONFIG used)
      • config (scanner config section in the ASH_CONFIG used)
      • scanner (default configuration in the plugin, if explicitly set)
  • Statistics calculation:
    • All statistics are calculated from the final aggregated SARIF report
    • Suppressed findings are counted separately and do not contribute to actionable findings
    • Scanner status is determined by comparing actionable findings to the threshold
Scanner Suppressed Critical High Medium Low Info Actionable Result Threshold
bandit 0 6 0 0 6662 0 6 FAILED MEDIUM (global)
cdk-nag 0 0 0 0 0 0 0 PASSED MEDIUM (global)
cfn-nag 0 0 0 0 0 0 0 MISSING MEDIUM (global)
checkov 0 0 0 0 0 0 0 PASSED MEDIUM (global)
detect-secrets 0 1 0 0 0 0 1 SKIPPED MEDIUM (global)
grype 0 0 0 0 0 0 0 MISSING MEDIUM (global)
npm-audit 0 0 0 0 0 0 0 PASSED MEDIUM (global)
opengrep 0 0 0 0 0 0 0 MISSING MEDIUM (global)
semgrep 3 0 0 0 0 0 0 PASSED MEDIUM (global)
syft 0 0 0 0 0 0 0 MISSING MEDIUM (global)

Top 4 Hotspots

Files with the highest number of security findings:

Finding Count File Location
2 tests/comparators/test_anls_leaf_semantics.py
2 .ash/ash_output/converted/jupyter/examples__notebooks__Strands_Evals_FCC_Live_Agent__ipynb-converted.py
2 tests/structured_object_evaluator/test_rollup_node_semantics.py
1 tests/test_readme_examples.py

Detailed Findings

Show 7 actionable findings

Finding 1: SECRET-HEX-HIGH-ENTROPY-STRING

  • Severity: HIGH
  • Scanner: detect-secrets
  • Rule ID: SECRET-HEX-HIGH-ENTROPY-STRING
  • Location: tests/comparators/test_anls_leaf_semantics.py:89

Description:
Secret of type 'Hex High Entropy String' detected in file 'tests/comparators/test_anls_leaf_semantics.py' at line 89

Code Snippet:

Secret of type Hex High Entropy String detected

Finding 2: B310

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B310
  • Location: .ash/ash_output/converted/jupyter/examples__notebooks__Strands_Evals_FCC_Live_Agent__ipynb-converted.py:83-85

Description:
Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.

Code Snippet:

)
with urllib.request.urlopen(url, timeout=60) as resp:
    rows = [item["row"] for item in json.load(resp)["rows"]]

Finding 3: B108

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B108
  • Location: tests/comparators/test_anls_leaf_semantics.py:210-212

Description:
Probable insecure usage of temp file/directory.

Code Snippet:

uuid.UUID(int=1),
            pathlib.Path("/tmp/x"),
            b"bytes",

Finding 4: B307

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B307
  • Location: tests/structured_object_evaluator/test_rollup_node_semantics.py:1363-1369

Description:
Use of possibly insecure function - consider using safer ast.literal_eval.

Code Snippet:

def published_label(node: dict, section: str, object_lists: set) -> str:
            counts_objects = eval(  # noqa: S307
                cond.group(1),
                {},
                {"data": node, "section": section, "OBJECT_LISTS": object_lists},
            )
            return eval(unit.group(1), {}, {"counts_objects": counts_objects})  # noqa: S307

Finding 5: B307

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B307
  • Location: tests/structured_object_evaluator/test_rollup_node_semantics.py:1368-1370

Description:
Use of possibly insecure function - consider using safer ast.literal_eval.

Code Snippet:

)
            return eval(unit.group(1), {}, {"counts_objects": counts_objects})  # noqa: S307

Finding 6: B102

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B102
  • Location: tests/test_readme_examples.py:55-57

Description:
Use of exec detected.

Code Snippet:

with contextlib.redirect_stdout(out):
        exec(code, namespace)
    prints = [line for line in code.splitlines() if line.startswith("print(")]

Finding 7: B310

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B310
  • Location: .ash/ash_output/converted/jupyter/examples__notebooks__Strands_Evals_FCC_Live_Agent__ipynb-converted.py:83-85

Description:
Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.

Code Snippet:

)
with urllib.request.urlopen(url, timeout=60) as resp:
    rows = [item["row"] for item in json.load(resp)["rows"]]

Report generated by Automated Security Helper (ASH) at 2026-11-08T23:11:45+00:00

@harrycav harrycav left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. I re-ran it on d7f1930 against dev (ce6c100).

  • Byte-identical to the 1.0.1 translate table over about 6,000 generated values: nested containers, astral and lone-surrogate strings, </script>, <!--, literal <, NaN/inf. No differences, and no raw <, > or & in any output.
  • Each replacement only emits a backslash, u and hex digits, so no later pair can rewrite an earlier one; order doesn't matter.
  • Mutation check: dropping the <, > or & entry fails the new tests. Dropping U+2028/2029 doesn't, since json.dumps already escapes both under the default ensure_ascii=True, as your comment says. Fine as a backstop.
  • 4.8 MB payload: json.dumps 23 ms, dev 352 ms, this branch 31 ms.
  • Reporting tests pass (162) and ruff check is clean. test_scalability_characteristics failed once under -n auto on its wall-clock ratio; it passes alone and doesn't touch this code, so I believe it's the known flake (#393).

LGTM.

@harrycav
harrycav merged commit 58f2dd3 into awslabs:dev Nov 10, 2026
10 checks passed
digalaviz pushed a commit that referenced this pull request Nov 19, 2026
The HTML report embeds each document's results in a <script> block via
_json_for_script. json.dumps writes NaN and infinities as bare NaN and
Infinity tokens: valid JavaScript, so the page loaded, but not JSON, so
anything that extracted the payload and parsed it strictly failed. A
blank numeric cell from pandas is NaN, so this was the ordinary case.

_json_for_script now dumps with allow_nan=False. Finite data takes that
first dump unchanged, so its bytes and cost are as before (#549's
str.replace escaping is untouched). Only when the dump raises does a
recursive pass replace NaN/inf/-inf (including numpy float64, nested in
dicts, lists and tuples) with None before dumping again, still with
allow_nan=False so a future miss fails loudly. A non-finite float dict
key keeps the string json.dumps already wrote for it. Both embedded
blobs, the document data and the field thresholds, go through this
helper.

On the page, null renders as an empty cell in the per-document views
(main.js writes these values through textContent), the same as None
already did, where NaN used to show as "NaN".

Fixes #450
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(report): _json_for_script is ~10x slower than json.dumps since 1.0.1

2 participants