From e7517ff8407008b44cb704410e38abbdd11e9b82 Mon Sep 17 00:00:00 2001 From: iacsha <122627209+iacsha@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:49:52 +0000 Subject: [PATCH] Keep XML-illegal characters from failing JSON responses (fixes #566) ObjectJSONSerializer converts an object to XML with XStream and then parses that XML to build the JSON. XStream writes characters that XML 1.0 does not allow, such as U+FFFE or a C0 control, as character references like ￾, and the parser rejects those. A single code template with such a character in its code failed the whole JSON code template list. Before parsing, swap each of those references for a private-use placeholder that does not occur in the document, then turn the placeholders into JSON \uXXXX escapes in the output. The characters come through unchanged instead of being stripped. Adds two ObjectJSONSerializerTest cases; both fail without this change. Signed-off-by: iacsha <122627209+iacsha@users.noreply.github.com> --- .../converters/ObjectJSONSerializer.java | 61 ++++++++++++++++++- .../converters/ObjectJSONSerializerTest.java | 58 ++++++++++++++++++ 2 files changed, 118 insertions(+), 1 deletion(-) diff --git a/server/src/main/java/com/mirth/connect/model/converters/ObjectJSONSerializer.java b/server/src/main/java/com/mirth/connect/model/converters/ObjectJSONSerializer.java index 15b20f829..9e60eacbb 100644 --- a/server/src/main/java/com/mirth/connect/model/converters/ObjectJSONSerializer.java +++ b/server/src/main/java/com/mirth/connect/model/converters/ObjectJSONSerializer.java @@ -5,6 +5,8 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -33,7 +35,7 @@ public void serialize(Object object, OutputStream outputStream) throws IOExcepti // Our xml util xml to json try { - jsonString = JsonXmlUtil.xmlToJson(xmlString); + jsonString = xmlToJson(xmlString); } catch (Exception e) { logger.error(e); throw new SerializerException(e); @@ -42,6 +44,63 @@ public void serialize(Object object, OutputStream outputStream) throws IOExcepti outputStream.write(jsonString.getBytes()); } + /** + * A character reference to a character that XML 1.0 does not allow, such as U+FFFE or a C0 + * control other than tab, LF or CR. XStream writes these for such characters in free text + * (code templates, scripts, descriptions), and the XML parser in JsonXmlUtil rejects them, which + * failed the whole response. See OpenIntegrationEngine/engine#566. + */ + private static final Pattern CHARACTER_REFERENCE = Pattern.compile("&#(?:[xX]([0-9a-fA-F]+)|([0-9]+));"); + + /** + * Converts the XML to JSON. Character references that XML 1.0 does not allow are swapped for a + * private-use placeholder that does not occur in this document, and turned back into JSON + * escapes afterwards, so the characters come through unchanged. + */ + static String xmlToJson(String xml) throws Exception { + char marker = unusedPrivateUseCharacter(xml); + StringBuilder protectedXml = new StringBuilder(xml.length()); + Matcher matcher = CHARACTER_REFERENCE.matcher(xml); + boolean replaced = false; + + while (matcher.find()) { + int codePoint = parseCodePoint(matcher); + String replacement = matcher.group(); + + if (codePoint >= 0 && codePoint <= 0xFFFF && !isXml10Char(codePoint)) { + replacement = marker + String.format("%04x", codePoint); + replaced = true; + } + + matcher.appendReplacement(protectedXml, Matcher.quoteReplacement(replacement)); + } + matcher.appendTail(protectedXml); + + String json = JsonXmlUtil.xmlToJson(replaced ? protectedXml.toString() : xml); + return replaced ? json.replaceAll(Pattern.quote(String.valueOf(marker)) + "([0-9a-f]{4})", "\\\\u$1") : json; + } + + private static int parseCodePoint(Matcher matcher) { + try { + return matcher.group(1) != null ? Integer.parseInt(matcher.group(1), 16) : Integer.parseInt(matcher.group(2)); + } catch (NumberFormatException e) { + return -1; + } + } + + private static boolean isXml10Char(int codePoint) { + return codePoint == 0x9 || codePoint == 0xA || codePoint == 0xD || (codePoint >= 0x20 && codePoint <= 0xD7FF) || (codePoint >= 0xE000 && codePoint <= 0xFFFD); + } + + private static char unusedPrivateUseCharacter(String text) { + for (char candidate = ''; candidate <= ''; candidate++) { + if (text.indexOf(candidate) < 0) { + return candidate; + } + } + throw new IllegalStateException("No unused private-use character is available for the XML to JSON conversion"); + } + /* Converts a source JSON string to XML then calls ObjectXMLSerializer.deserialize(...) * JSON -> XML -> Object */ diff --git a/server/src/test/java/com/mirth/connect/model/converters/ObjectJSONSerializerTest.java b/server/src/test/java/com/mirth/connect/model/converters/ObjectJSONSerializerTest.java index 70e17013d..7d1db3e34 100644 --- a/server/src/test/java/com/mirth/connect/model/converters/ObjectJSONSerializerTest.java +++ b/server/src/test/java/com/mirth/connect/model/converters/ObjectJSONSerializerTest.java @@ -7,10 +7,15 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import javax.json.Json; +import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; +import javax.json.JsonString; +import javax.json.JsonValue; import org.junit.BeforeClass; import org.junit.Test; @@ -18,6 +23,9 @@ import com.mirth.connect.client.core.Version; import com.mirth.connect.model.Channel; import com.mirth.connect.model.InvalidChannel; +import com.mirth.connect.model.codetemplates.CodeTemplate; +import com.mirth.connect.model.codetemplates.CodeTemplateContextSet; +import com.mirth.connect.model.codetemplates.CodeTemplateProperties.CodeTemplateType; public class ObjectJSONSerializerTest { @@ -64,6 +72,56 @@ public void testSerializeChannel() throws IOException { assertEquals(channelId, id); } + /** + * Characters that XML 1.0 does not allow (U+FFFE, U+FFFF and C0 controls other than tab, LF + * and CR) must not stop JSON serialization, and must come through unchanged. See + * OpenIntegrationEngine/engine#566. + */ + @Test + public void testSerializeCodeTemplateWithXmlIllegalCharacters() throws IOException { + String code = "s.replace(/[￾￿]/g, \"\"); // \u0001 \u001F \u0008"; + CodeTemplate codeTemplate = new CodeTemplate("illegal characters", CodeTemplateType.FUNCTION, CodeTemplateContextSet.getGlobalContextSet(), code); + + JsonValue json = serializeToJson(codeTemplate); + + assertTrue("the code template's code is in the JSON unchanged", containsString(json, code)); + } + + /** The placeholder used for those characters must not collide with text already present. */ + @Test + public void testSerializeKeepsPrivateUseCharactersAlongsideXmlIllegalCharacters() throws IOException { + String description = "fffe; then ￾ then "; + Channel channel = new Channel(); + channel.setId(GOOD_OLD_CHANNEL_ID); + channel.setDescription(description); + + JsonValue json = serializeToJson(channel); + + assertEquals(description, ((JsonObject) json).getJsonObject("channel").getString("description")); + } + + private static JsonValue serializeToJson(Object object) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectJSONSerializer.getInstance().serialize(object, baos); + + try (JsonReader jsonReader = Json.createReader(new InputStreamReader(new ByteArrayInputStream(baos.toByteArray()), StandardCharsets.UTF_8))) { + return jsonReader.read(); + } + } + + private static boolean containsString(JsonValue value, String expected) { + switch (value.getValueType()) { + case STRING: + return expected.equals(((JsonString) value).getString()); + case OBJECT: + return ((JsonObject) value).values().stream().anyMatch(child -> containsString(child, expected)); + case ARRAY: + return ((JsonArray) value).stream().anyMatch(child -> containsString(child, expected)); + default: + return false; + } + } + private static final String GOOD_OLD_CHANNEL_ID = "e084f86d-7743-4df8-a6eb-91d1cdf2ab0f"; // @formatter:off private static final String GOOD_OLD_CHANNEL =