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 + `": "\\u003e", + "&": "\\u0026", + "\u2028": "\\u2028", + "\u2029": "\\u2029", +}) + + +def _json_for_script(value: Any) -> str: + """Serialize ``value`` as JSON that is safe to place inside ```` 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 '