Skip to content

[Bug]: A message text with a literal \u003c is serialized as invalid JSON #1292

Closed

Description

@WMK666666

What happened?

HtmlEscapeUtils.removeHtmlEscaping strips the HTML escapes that JsonFormat adds to the JSON it
prints (\u003c, \u003e, \u0026, \u003d, \u0027) with a plain String.replace over the
whole document, without checking whether the sequence it matches is itself escaped.

A message whose text really contains those six characters — a code snippet, a regex, a note about an
escape sequence — is printed by JsonFormat as "\\u003c": two backslashes for the literal one, then
the text u003c. The replacement matches from the second backslash and leaves "\<", which is
not a valid JSON escape, so ProtoJsonUtils.toJson returns a body that no JSON parser accepts:

com.google.protobuf.InvalidProtocolBufferException:
com.google.gson.stream.MalformedJsonException:
    Invalid escape sequence at line 7 column 22 path $.message.parts[0].text

The response is produced by the same ProtoJsonUtils.toJson that every JSON-RPC response body goes
through (spec-grpc and compat-0.3/spec-grpc), so the client fails to parse a reply the server
believed it had serialized correctly.

Expected behavior

Removing an HTML escape must only look at an escape sequence that is not escaped itself:

JsonFormat prints Which means Expected after removing HTML escaping
\u003c < <
\\u003c a literal backslash, then the text u003c \\u003c (unchanged)
\\\u003c a literal backslash, then < \\< (the escape goes, the escaped backslash stays)

The document stays valid JSON in all three cases, and JsonFormat.parser() can read it back.

Relevant log output

org.opentest4j.AssertionFailedError: expected: <{"text":"a\\u003c b"}>
                                     but was: <{"text":"a\< b"}>

plus the MalformedJsonException above when the corrupted body is parsed.

Code of Conduct

  • I agree to follow this project's Code of Conduct

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions