From 6415e617302cd39b996825305f09ebe7a8d7eff1 Mon Sep 17 00:00:00 2001 From: Lenin Mookiah <2639584+leninworld@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:09:58 -0800 Subject: [PATCH] fix(workflows): escape lone surrogates in to_json output `to_json` serializes with ensure_ascii=False, so a surrogate code point (U+D800..U+DFFF) in a string was emitted raw. `from_json` accepts the valid JSON text "\ud800" and returns such a string, so `{{ inputs.p | from_json | to_json }}` produced text that cannot be encoded as UTF-8: a shell step using it in `run` failed the workflow with "'utf-8' codec can't encode character '\ud800' ... surrogates not allowed", and as an `env` value the step failed to start. Escape only the code points UTF-8 cannot encode (the surrogates) as JSON \uXXXX sequences, which is what ensure_ascii=True emits for them, via a UTF-8 backslashreplace round trip. Ordinary non-ASCII text stays readable and the output stays byte-stable and valid JSON; from_json round-trips it. Assisted-by: OpenAI Codex CLI (model: gpt-5.6-sol, autonomous) Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- .../workflows/expressions/filters.py | 8 +- .../workflows/expressions/test_filters.py | 116 +++++++++++++++++- 2 files changed, 122 insertions(+), 2 deletions(-) diff --git a/src/specify_cli/workflows/expressions/filters.py b/src/specify_cli/workflows/expressions/filters.py index 7dcee8d825..1914d903f4 100644 --- a/src/specify_cli/workflows/expressions/filters.py +++ b/src/specify_cli/workflows/expressions/filters.py @@ -228,10 +228,16 @@ def _filter_to_json(value: Any) -> str: surfacing as an ordering ``TypeError`` from ``sort_keys=True`` (mixed key types) or as silent ``1`` → ``"1"`` coercion that collides with an existing ``"1"`` key. + + Unpaired surrogates accepted by ``from_json`` cannot be encoded as UTF-8, + so they are escaped as JSON ``\\uXXXX`` sequences after serialization. + The result remains valid JSON and round-trips through ``from_json``, while + every ordinarily UTF-8-encodable non-ASCII character remains readable. """ _check_json_keys(value) try: - return json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False) + text = json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False) + return text.encode("utf-8", "backslashreplace").decode("utf-8") except (TypeError, ValueError) as exc: raise ValueError(f"to_json: value is not JSON-serializable: {exc}") from exc diff --git a/tests/specify_cli/workflows/expressions/test_filters.py b/tests/specify_cli/workflows/expressions/test_filters.py index f6d487fc98..9c855adcfd 100644 --- a/tests/specify_cli/workflows/expressions/test_filters.py +++ b/tests/specify_cli/workflows/expressions/test_filters.py @@ -2,9 +2,14 @@ from __future__ import annotations +import json +import os + import pytest +import yaml -from specify_cli.workflows.base import StepContext +from specify_cli.workflows.base import RunStatus, StepContext +from specify_cli.workflows.engine import WorkflowDefinition, WorkflowEngine from specify_cli.workflows.expressions import ( BUILTIN_FILTERS, FILTER_TABLE, @@ -427,3 +432,112 @@ def test_result_round_trips_through_to_json(self): assert evaluate_expression("{{ inputs.s | make | to_json }}", ctx(s="x")) == ( '{"a": [1]}' ) + + +# -- UTF-8-safe to_json output ----------------------------------------------- + + +class TestToJson: + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("\ud800", '"\\ud800"'), + ("\udfff", '"\\udfff"'), + (["\ud800"], '["\\ud800"]'), + ({"value": "\udfff"}, '{"value": "\\udfff"}'), + ({"\ud800": "value"}, '{"\\ud800": "value"}'), + ( + {"outer": [{"\udfff": ["ok", "\ud800"]}]}, + '{"outer": [{"\\udfff": ["ok", "\\ud800"]}]}', + ), + ("ascii-\ud800-\u00e9", '"ascii-\\ud800-\u00e9"'), + ], + ids=[ + "high", + "low", + "list", + "dict-value", + "dict-key", + "nested", + "mixed", + ], + ) + def test_to_json_escapes_only_surrogates(self, value, expected): + result = evaluate_expression("{{ inputs.value | to_json }}", ctx(value=value)) + + dumped = json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False) + assert result == dumped.encode("utf-8", "backslashreplace").decode("utf-8") + assert result == expected + assert result.encode("utf-8").decode("utf-8") == result + assert json.loads(result) == value + + def test_to_json_escapes_two_code_point_surrogate_pair(self): + result = evaluate_expression( + "{{ inputs.value | to_json }}", ctx(value="\ud83d\ude00") + ) + + assert result == '"\\ud83d\\ude00"' + assert result.encode("utf-8").decode("utf-8") == result + + def test_from_json_to_json_round_trips_lone_surrogate(self): + result = evaluate_expression( + "{{ inputs.p | from_json | to_json }}", ctx(p='"\\ud800"') + ) + + assert result == '"\\ud800"' + + @pytest.mark.parametrize("value", ["\u00e9", "\u4e2d", "\U0001f600"]) + def test_to_json_keeps_utf8_encodable_non_ascii_raw(self, value): + result = evaluate_expression("{{ inputs.value | to_json }}", ctx(value=value)) + + assert result == f'"{value}"' + assert "\\u" not in result + + def test_to_json_preserves_stable_key_order_and_existing_backslashes(self): + context = ctx(obj={"b": 2, "a": 1}, path="a\\b") + + assert evaluate_expression("{{ inputs.obj | to_json }}", context) == ( + '{"a": 1, "b": 2}' + ) + assert evaluate_expression("{{ inputs.path | to_json }}", context) == '"a\\\\b"' + + def test_to_json_preserves_error_contracts(self): + context = ctx(nan=float("nan"), bad_key={1: "value"}) + + with pytest.raises(ValueError, match="to_json"): + evaluate_expression("{{ inputs.nan | to_json }}", context) + with pytest.raises(ValueError, match="to_json: mapping keys must be strings"): + evaluate_expression("{{ inputs.bad_key | to_json }}", context) + + @pytest.mark.skipif(os.name != "posix", reason="shell command uses POSIX quoting") + def test_shell_step_writes_from_json_surrogate_as_utf8(self, project_dir): + output_path = project_dir / "out.json" + definition = WorkflowDefinition.from_string( + yaml.safe_dump( + { + "schema_version": "1.0", + "workflow": { + "id": "surrogate-json", + "name": "Surrogate JSON", + "version": "1.0.0", + }, + "inputs": {"p": {"type": "string"}}, + "steps": [ + { + "id": "write", + "type": "shell", + "run": ( + "printf '%s' " + "'{{ inputs.p | from_json | to_json }}' > out.json" + ), + } + ], + } + ) + ) + + state = WorkflowEngine(project_dir).execute(definition, {"p": '"\\ud800"'}) + + assert state.status == RunStatus.COMPLETED + assert output_path.exists() + assert output_path.read_bytes() == b'"\\ud800"'