diff --git a/CHANGELOG.md b/CHANGELOG.md index e4e8ad36..01d516d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,63 @@ Each release links to full notes on the ## [Unreleased] +## [1.0.1] - 2026-10-26 + +### Security + +- **A document value can no longer run as script in the HTML report.** With + `individual_results_jsonl_path`, the report embeds each document's values as + JSON inside a `` ran as its own script when the + report was opened. Values are model output or third-party documents, so this + needed no access to stickler or the host. A JSON Schema property name reached + the same block through the field thresholds. `<`, `>` and `&` are now written + as `\uXXXX`, which the page's JavaScript reads as the same characters; + U+2028 and U+2029 were already escaped by `json.dumps` and stay covered + defensively + ([#431](https://github.com/awslabs/stickler/issues/431)) + +- **A field name can no longer inject markup into the report.** The field + performance table wrote each name into the page as raw HTML while the chart + beside it escaped the same name, so a name containing `<`, `>` or `&` was + read by the browser as markup. Field names come from a JSON Schema or a + Stickler config, so they are arbitrary strings. This section renders whether + or not `individual_results_jsonl_path` is passed. The table's confusion + counts and the confusion-matrix cell are escaped alongside it; those are + library-computed integers on the `ProcessEvaluation` path and were reachable + only by passing `generate_report()` a hand-assembled metrics dict + ([#422](https://github.com/awslabs/stickler/issues/422)) + +- **Affected versions.** Every release from 0.1.3 to 1.0.0 carries the + ``` used to +run as its own script when the report was opened. Values are model output or +third-party documents, so this needs no access to stickler or the host. + +See https://github.com/awslabs/stickler/issues/431 +""" + +import json +from html.parser import HTMLParser + +import pytest + +from stickler import ComparableField, StructuredModel +from stickler.reporting.html.html_reporter import ( + EvaluationHTMLReporter, + _json_for_script, +) +from stickler.structured_object_evaluator.bulk_structured_model_evaluator import ( + BulkStructuredModelEvaluator, +) + +PAYLOAD = "" + + +class Invoice(StructuredModel): + vendor: str = ComparableField() + + +class _ScriptBodies(HTMLParser): + """Collect the text of every ``": [""]}, None], +) +def test_json_for_script_round_trips_and_leaves_no_markup(value): + out = _json_for_script(value) + + assert json.loads(out) == value + for ch in "<>&\u2028\u2029": + assert ch not in out diff --git a/tests/reporting/html/test_section_generator.py b/tests/reporting/html/test_section_generator.py index 14db9be0..626d7eb9 100644 --- a/tests/reporting/html/test_section_generator.py +++ b/tests/reporting/html/test_section_generator.py @@ -246,7 +246,25 @@ def test_generate_non_matches_truncate_long_values(self, mock_extract_non_matche truncated_value = long_value[:100] assert truncated_value in result assert long_value not in result # Full value should not be present - + + @patch('stickler.reporting.html.utils.data_extractors.DataExtractor.extract_non_matches') + def test_generate_non_matches_truncation_never_splits_an_entity(self, mock_extract_non_matches): + """Truncate first, then escape, so the cut cannot land inside ``&``.""" + mock_extract_non_matches.return_value = [ + { + 'doc_id': 'doc1', + 'field_path': 'description', + 'non_match_type': 'MISMATCH', + 'ground_truth_value': "x" * 97 + "&", + 'prediction_value': 'short' + } + ] + + result = self.section_generator.generate_non_matches(ReportConfig()) + + assert "x" * 97 + "&" in result + assert "&am<" not in result + def test_generate_document_gallery_image_mode(self): """Test document gallery generation in image mode.""" document_images = { @@ -347,3 +365,62 @@ def test_generate_sections_with_individual_results(self): assert 'price' in field_analysis assert 'TP' in confusion_matrix assert 'category' in non_matches + + +class TestNonStrDocId: + """A non-`str` doc_id must not take the whole report down. + + `BulkStructuredModelEvaluator.update` annotates `doc_id` as `Optional[str]`, but + Python does not enforce that at runtime and `evaluate_dataframe` reads the value + straight off a DataFrame column (`doc_id = row.get("doc_id", ...)`). An integer + id — the ordinary case for one read from CSV, parquet or a database — used to + reach `html.escape` unconverted and raise, so `generate_report` returned + `success=False` and wrote no page at all. + """ + + def test_non_matches_table_renders_a_non_str_doc_id(self): + viz = Mock(spec=VisualizationEngine) + results = Mock(spec=ProcessEvaluation) + results.non_matches = [ + { + "doc_id": 1001, + "field_path": 7, + "non_match_type": "NonMatchType.FALSE_DISCOVERY", + "ground_truth_value": "Acme", + "prediction_value": "Globex", + } + ] + html_out = SectionGenerator(results, viz).generate_non_matches(ReportConfig()) + assert "1001" in html_out + assert ">7<" in html_out + + def test_a_dataframe_with_an_integer_doc_id_still_produces_a_report(self, tmp_path): + import json + + import pandas as pd + + from stickler import StructuredModel + from stickler.reporting.html.html_reporter import EvaluationHTMLReporter + from stickler.structured_object_evaluator.bulk_structured_model_evaluator import ( + BulkStructuredModelEvaluator, + ) + + class Invoice(StructuredModel): + vendor: str + + df = pd.DataFrame( + [ + { + "doc_id": 1001, + "expected": json.dumps({"vendor": "Acme"}), + "predicted": json.dumps({"vendor": "Globex"}), + } + ] + ) + results = BulkStructuredModelEvaluator(Invoice).evaluate_dataframe(df) + assert {type(nm.get("doc_id")) for nm in results.non_matches} == {int} + + out = tmp_path / "report.html" + report = EvaluationHTMLReporter().generate_report(results, str(out)) + assert report.success, report.errors + assert out.exists() diff --git a/tests/reporting/html/test_visualization_engine.py b/tests/reporting/html/test_visualization_engine.py index 55b53d14..694b6af8 100644 --- a/tests/reporting/html/test_visualization_engine.py +++ b/tests/reporting/html/test_visualization_engine.py @@ -99,6 +99,15 @@ def test_generate_field_performance_chart_with_f1_fallback(self, mock_color_util assert 'width: 75%' in result mock_color_utils.assert_called_once_with(0.75, config.color_thresholds) + def test_generate_field_performance_chart_escapes_field_names(self): + """The chart escapes field names, so a later edit cannot quietly undo it (#422).""" + field_metrics = {"vendor & co": {"f1": 1.0}} + + result = self.viz_engine.generate_field_performance_chart(field_metrics, ReportConfig()) + + assert '
<b>vendor</b> & co
' in result + assert "vendor" not in result + def test_generate_field_performance_chart_empty_metrics(self): """Test field performance chart with empty metrics.""" field_metrics = {} @@ -162,6 +171,23 @@ def test_generate_field_performance_table(self, mock_color_utils): assert mock_color_utils.call_count == 2 + def test_generate_field_performance_table_escapes_field_names(self): + """A field name is text, not markup, as in the chart (#422).""" + field_metrics = {"vendor & co": {"precision": 1.0, "recall": 1.0, "f1": 1.0}} + + result = self.viz_engine.generate_field_performance_table(field_metrics, ReportConfig()) + + assert "<b>vendor</b> & co" in result + assert "vendor" not in result + + def test_field_name_that_is_not_a_string_does_not_raise(self): + """A hand-built results dict can key a field by a non-``str``.""" + field_metrics = {7: {"precision": 1.0, "recall": 1.0, "f1": 1.0}} + config = ReportConfig() + + assert "7" in self.viz_engine.generate_field_performance_table(field_metrics, config) + assert '
7
' in self.viz_engine.generate_field_performance_chart(field_metrics, config) + def test_generate_field_performance_table_with_fallback_keys(self): """Test field performance table with fallback metric keys.""" field_metrics = { @@ -270,3 +296,120 @@ def test_generate_confusion_matrix_heatmap_missing_metrics(self, mock_color_util assert '57.1%' in result # 20/35 * 100 assert '42.9%' in result # 15/35 * 100 assert '0.0%' in result # 0/35 * 100 + + +class TestFieldPerformanceValuesAreEscaped: + """The confusion counts in the field performance table are rendered, not trusted. + + `generate_report` publicly accepts a plain dict, so a caller who assembles + their own metrics — rather than passing a `ProcessEvaluation`, where these + are library-computed ints — can put a string in `tp`/`fd`/`fa`/`fn`. Those + four cells carried no escaping and no format spec, unlike the + `precision`/`recall`/`f1` cells beside them, whose `:.3f` rejects a string + by accident. #431 closed the `", + "fa": "", + "fn": "", + } + } + + def _table(self, field_metrics): + from stickler.reporting.html.report_config import ReportConfig + from stickler.reporting.html.visualization_engine import VisualizationEngine + + return VisualizationEngine().generate_field_performance_table( + field_metrics, ReportConfig() + ) + + @staticmethod + def _parse(markup): + """What a browser would actually see: elements, attributes, script bodies.""" + from html.parser import HTMLParser + + class Seen(HTMLParser): + def __init__(self): + super().__init__(convert_charrefs=True) + self.attrs = [] + self.scripts = [] + self._in_script = False + + def handle_starttag(self, tag, attrs): + self.attrs += [(tag, k, v) for k, v in attrs] + if tag == "script": + self._in_script = True + + def handle_endtag(self, tag): + if tag == "script": + self._in_script = False + + def handle_data(self, data): + if self._in_script and data.strip(): + self.scripts.append(data.strip()) + + p = Seen() + p.feed(markup) + return p + + def test_a_hostile_value_is_inert_in_the_table(self): + out = self._table(self.HOSTILE) + seen = self._parse(out) + # The characters survive as text; what must not survive is any parse of + # them as markup. + assert [a for a in seen.attrs if a[1].startswith("on")] == [] + assert seen.scripts == [] + assert "<img src=x" in out + assert "<script>" in out + # the row key is a field name, which is its own injection route (#422) + assert "ven&" not in out + assert "ven<dor>&" in out + + def test_the_confusion_matrix_cell_is_inert(self): + """A numeric subclass with a hostile __str__ reaches the cell. + + `generate_confusion_matrix_heatmap` sums the counts first, so a plain + string raises `TypeError` before rendering — which is why this looked + unreachable. An `int` subclass sums and divides fine and then renders + through `str()`, so the escape there is load-bearing, and this test + reddens when it is reverted. + """ + from stickler.reporting.html.report_config import ReportConfig + from stickler.reporting.html.visualization_engine import VisualizationEngine + + class Hostile(int): + def __str__(self): + return "" + + out = VisualizationEngine().generate_confusion_matrix_heatmap( + {"tp": Hostile(1), "fd": 0, "fa": 0, "fn": 0}, ReportConfig() + ) + seen = self._parse(out) + assert [a for a in seen.attrs if a[1].startswith("on")] == [] + assert seen.scripts == [] + assert "{n}" in out diff --git a/uv.lock b/uv.lock index 318dc1ab..6952806e 100644 --- a/uv.lock +++ b/uv.lock @@ -1876,7 +1876,7 @@ wheels = [ [[package]] name = "mkdocs-material" -version = "9.7.6" +version = "9.7.7" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "babel" }, @@ -1891,9 +1891,9 @@ dependencies = [ { name = "pymdown-extensions" }, { name = "requests" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/45/29/6d2bcf41ae40802c4beda2432396fff97b8456fb496371d1bc7aad6512ec/mkdocs_material-9.7.6.tar.gz", hash = "sha256:00bdde50574f776d328b1862fe65daeaf581ec309bd150f7bff345a098c64a69", size = 4097959, upload-time = "2026-03-19T15:41:58.161Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f1/cd/c05d3a530ba7934f144fb45f7203cd236adc25c7bdcc34673d202f4b0278/mkdocs_material-9.7.7.tar.gz", hash = "sha256:c0649c065b1b0512d60aad8c10f947f8e455284475239b364b610f2deb4d0855", size = 4097923, upload-time = "2026-07-17T16:21:33.156Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2c/01/bc663630c510822c95c47a66af9fa7a443c295b47d5f041e5e6ae62ef659/mkdocs_material-9.7.6-py3-none-any.whl", hash = "sha256:71b84353921b8ea1ba84fe11c50912cc512da8fe0881038fcc9a0761c0e635ba", size = 9305470, upload-time = "2026-03-19T15:41:55.217Z" }, + { url = "https://files.pythonhosted.org/packages/ad/21/17c1bc9e6f47c972ad66fb2ac2568f99f90f1207eeb6fc3b34d094dba7b5/mkdocs_material-9.7.7-py3-none-any.whl", hash = "sha256:8ea9bb1737a5b524a5f9dcf2e1b4ebda8274ae3008aa7845720a97083bef708f", size = 9305438, upload-time = "2026-07-17T16:21:30.017Z" }, ] [[package]] @@ -4042,7 +4042,7 @@ wheels = [ [[package]] name = "stickler-eval" -version = "1.0.0" +version = "1.0.1" source = { editable = "." } dependencies = [ { name = "json-schema-to-pydantic" },