Skip to content

Preserve literal Unicode escape text in JSON string values #14929

Open

Description

@coygeek

Summary

JSON response sanitization changes literal backslash-u text inside a string value, even when that value contains no terminal control character. This silently changes issue body content returned by gh api and gh issue view --json body. A valid JSON example stored inside a Markdown body can become invalid after readback. The outer API response remains valid JSON; this report concerns its changed string value, not a failure to parse that outer response.

Steps to reproduce

Run the following Python 3 script with the tested release on PATH. It serves only a local fixture, uses an isolated configuration directory and a dummy token, and creates no GitHub resource. The body field contains a JSON string example made of ordinary printable text; control separately contains an actual ESC character as a sanitization control.

import http.server
import json
import os
import subprocess
import tempfile
import threading

fixture = {"body": '"\\u001b[31mexample"', "control": "\x1b[31mexample", "plain": "example"}
payload = json.dumps(fixture).encode()

class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(payload)
    def log_message(self, *args):
        pass

server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
    with tempfile.TemporaryDirectory() as config:
        env = {k: v for k, v in os.environ.items() if not k.startswith(("GH_", "GITHUB_"))}
        env.update(GH_CONFIG_DIR=config, GH_TOKEN="local-fixture-placeholder", NO_COLOR="1")
        result = subprocess.run(["gh", "api", f"http://127.0.0.1:{server.server_port}/fixture"], env=env, capture_output=True, text=True, check=True)
        actual = json.loads(result.stdout)
        print("input:", repr(fixture["body"]))
        print("output:", repr(actual["body"]))
        print("body equal:", actual["body"] == fixture["body"])
        print("actual ESC neutralized:", actual["control"] == "^[[31mexample")
        print("plain unchanged:", actual["plain"] == fixture["plain"])
        json.loads(fixture["body"])
        try:
            json.loads(actual["body"])
        except json.JSONDecodeError as error:
            print("embedded JSON:", error.msg)
finally:
    server.shutdown()
    server.server_close()
    thread.join()

The fixture was reduced from a public issue body and executed locally. The same failure was also reproduced by fetching the existing issue through both affected commands and comparing its decoded body with a direct REST response. No issue write is necessary to reproduce it.

Expected behavior

Preserve literal \u001b text that is already escaped in the outer JSON string. Decoding that outer string produces printable backslash-u notation, not an ESC character. Keep neutralizing actual control characters, as demonstrated by the separate control field.

This distinction matches the review requirement on the original sanitization change: already escaped Unicode codepoints should remain unchanged. It also matches the sanitizer's stated scope: bytes that are not part of a control character are not modified. This report does not assume that gh api generally bypasses sanitization or preserves the entire wire response byte for byte.

Actual behavior

Both the installed executable and a separately downloaded official release executable produced the following result with stdout captured through a pipe and color disabled. Each command exited successfully. The source body and its embedded JSON parse successfully; the returned body's embedded JSON does not.

input: '"\\u001b[31mexample"'
output: '"\\^[[31mexample"'
body equal: False
actual ESC neutralized: True
plain unchanged: True
embedded JSON: Invalid \escape

The two repr lines above display a Python representation of the strings. The replacement leaves a literal backslash before caret notation. Adding --allow-escape-sequences did not preserve the value, and --jq .body returned the same changed text. Actual ESC sanitization and ordinary text preservation both passed the controls.

Evidence

  • Expected source: The original change's review requirement linked above and asciisanitizer.Sanitizer.Transform's documented scope distinguish actual control characters from other bytes.
  • Failure source: The executed self-contained fixture and output above, reproduced with both release executables; an independent live REST comparison also showed five literal escape tokens changed in a stored issue body while GitHub retained the original content.
  • Evidence provenance: observed
  • Local verification: reproduced
  • Reproduction completeness: complete

The HTTP response path applies the JSON sanitizer to application/json responses. The matching branch recognizes the six-byte escape pattern even after an escaped backslash. Its extra-backslash handling keeps the outer JSON valid, but still changes the decoded literal text. This is a source explanation, not a prescribed implementation.

There is counterevidence worth making explicit: the current sanitizer test and the CLI's HTTP client test encode the existing replacement for escaped patterns. They protect outer-JSON validity but do not preserve the printable literal value. The narrower failure here is the content change demonstrated above, rather than a request to remove control-character protection.

Restoration check

With the same fixture, the returned body must equal the input body, and json.loads(actual["body"]) must succeed as it does for the input. The control field must still contain caret notation rather than an actual ESC character, and plain must remain unchanged. Check both direct API output and issue-body structured output so that a passing outer JSON parse alone cannot hide the content change.

Runtime or environment

  • Runtime-tested: GitHub CLI 2.103.3 on macOS arm64, both the installed Mach-O executable and the official macOS arm64 release archive; the archive's SHA-256 matched the published checksums. All output was captured without a TTY.
  • Source-inspected, not built: current default branch trunk at eeb44bc432c0107de002dadd34a61b4e2bd15882; the HTTP client and its sanitization tests are unchanged from the release. Both pin github.com/cli/go-gh/v2 v2.17.0, which was also the library's latest published release when checked.

References

  • Closed issue #8336 concerned invalid outer JSON causing issue view to fail; its fix restored parseability. This report reproduces changed string content while the outer response remains parseable.
  • Closed issue #14545 was not reproduced and was closed requesting exact current reproduction; it alleged backslash loss and invalid outer JSON. This report provides a current local fixture for a different observable result and makes no user-agent-dependent or reserialization claim.

Triage assessment

  • Impact level: P2
  • Assessment status: supported
  • Impact basis: Structured readback silently changes valid literal source text, making an embedded JSON example invalid and preventing exact issue-body verification; the observed scope is strings containing escaped control-code notation.
  • Workaround status: available
  • Workaround basis: A direct REST request using Python urllib preserved the decoded issue body and its valid embedded example in the live comparison; this avoids the CLI response sanitizer without changing the stored issue or weakening terminal protection in gh.

Activity

  1. added
    needs-triage
    on Nov 3, 2026
  2. BagToad commented on Nov 3, 2026

    @BagToad
    Member

    Hi @coygeek, thanks for the issue. What situation caused this? What were you trying to do?

    I'm not running your python reproduction program, sorry - do you have a reproduction available against a public github.com repo?

  3. added
    more-info-needed
    on Nov 3, 2026
  4. coygeek commented on Nov 3, 2026

    @coygeek
    Author

    Yes—this came up while verifying that the stored body of a newly filed issue matched the Markdown submitted with gh issue create --body-file. The issue contained a fenced JSON example with escaped ANSI sequences. Reading the body back through gh issue view --json body changed those literal sequences, so the returned body no longer matched the submitted text.

    There is a reproduction against this existing public issue: vercel-labs/ai-cli#124

    Run these commands in an empty directory with gh, curl, and jq available:

    curl -fsSL https://api.github.com/repos/vercel-labs/ai-cli/issues/124 \
      | jq -r .body > rest-body.md
    
    gh api repos/vercel-labs/ai-cli/issues/124 --jq .body > gh-body.md
    
    diff -u rest-body.md gh-body.md

    On gh 2.103.3, the diff shows five replacements inside the fenced JSON diagnostic. For example, the stored literal text \u001b[1m comes back through gh as \^[[1m. The direct REST response preserves the original text.

    The same difference is visible with the command used for the original readback:

    gh issue view https://github.com/vercel-labs/ai-cli/issues/124 \
      --json body --jq .body > gh-body.md
    
    diff -u rest-body.md gh-body.md

    The outer API JSON remains valid. The problem is that the JSON example inside the Markdown body changes and becomes invalid because \^ is not a valid JSON escape. The requested behavior is to preserve that printable literal text while retaining sanitization of actual terminal control characters.

  5. removed
    more-info-needed
    on Nov 3, 2026
  6. changed the title [-]fix(api): preserve literal Unicode escape text in JSON string values[/-] [+]Preserve literal Unicode escape text in JSON string values[/+] on Nov 4, 2026
  7. YevheniiKotyrlo commented on Nov 6, 2026

    @YevheniiKotyrlo

    The same on Windows. gh gist edit also writes the rewritten text back to GitHub, and the C1 escapes are rewritten too.

    Steps to reproduce, on Windows 11 with gh signed in: steps 1 and 2 with gh 2.103.3, step 3 with gh built from trunk at 233b470 (2026-11-11).

    1. Read Android: a Metro error answer that names no file, line or column shows in the red box as its raw JSON body, escape sequences and all react/react-native#59821, whose body holds the literal text \u001b three times, with curl -fsS https://api.github.com/repos/react/react-native/issues/59821, with gh issue view 59821 --repo react/react-native --json body --jq .body and with gh api repos/react/react-native/issues/59821 --jq .body.
    2. Create a secret gist with one file, probe.txt holding first, and a description holding \u001b: gh gist create --desc 'writeback probe, literal \u001b text' probe.txt. Change the file to second with gh gist edit <gist> --filename probe.txt probe.txt, then read the stored description with curl from GET /gists/<gist>.
    3. On an issue, post a comment with gh issue comment <issue> --body-file <file>, the file holding Escapes as text: \u0000 \u001f \u0041 \u007f \u0080 \u0081 \u009f \u00a0 \u00ff \u0100 \uffff and then each escape on a line of its own in a fenced code block. Read it with curl from GET /repos/{owner}/{repo}/issues/comments/{comment_id} and with gh api repos/{owner}/{repo}/issues/comments/{comment_id} --jq .body.

    Actual result:

    1. curl's copy holds \u001b three times; gh issue view and gh api print each as \^[.
    2. After gh gist edit, GitHub stores the description with \^[ where it held \u001b; probe.txt holds second.
    3. gh prints \u0000 and \u0080 as \^@, \u0081 as \^A, and \u001f and \u009f as \^_; \u0041, \u007f, \u00a0, \u00ff, \u0100 and \uffff read as posted.

    Expected result: gh prints, and writes back to GitHub, the text GitHub returns, each \u00XX posted as text as it was posted; a control character a response really holds still prints in caret notation.

    repro.sh runs steps 1 and 2 through the gist's readback.sh and writeback.sh, which deletes the gist it creates. It prints:

    win32 x64 10.0.26300, gh version 2.103.3 (2026-10-26)
    curl: \u001b 3, \^[ 0
    gh-issue-view: \u001b 0, \^[ 3
    gh-api: \u001b 0, \^[ 3
    gh-issue-view is curl's copy with each \u001b turned into \^[
    gh-api is curl's copy with each \u001b turned into \^[
    
    win32 x64 10.0.26300, gh version 2.103.3 (2026-10-26)
    description sent: \u001b 1, \^[ 0
    stored after gh gist create: \u001b 1, \^[ 0
    stored after gh gist edit --filename: \u001b 0, \^[ 1
    probe.txt stored after gh gist edit --filename: second
    gh gist edit stored the description with each \u001b turned into \^[
    

    reproduce.sh runs step 3 and prints:

    MINGW64_NT-10.0-26300 x86_64, gh version 2.0.0-20261111142639-233b470d3a18, curl 8.23.0, jq-1.8.1
      line 1 GitHub: Escapes as text: \u0000 \u001f \u0041 \u007f \u0080 \u0081 \u009f \u00a0 \u00ff \u0100 \uffff
      line 1 gh:     Escapes as text: \^@ \^_ \u0041 \u007f \^@ \^A \^_ \u00a0 \u00ff \u0100 \uffff
      6 of 15 lines read other than GitHub returns them; 183 characters returned, 153 read
    
  8. cli-triage commented on Nov 9, 2026

    @cli-triage

    Reproducible on 2.103.3.

    Using test data with a JSON string containing printable \u001b text:

    $ gh api (fixture.example.invalid/redacted)
    {"body":"\"\\^[[31mexample\"","control":"^[[31mexample","plain":"example"}

    Exit status: 0.

    The literal sequence in body changed to caret notation, while the actual ESC in control was neutralized and plain text stayed unchanged. gh issue view 1 -R example.invalid/hello --json body showed the same mutation. The latest release and source build behaved the same. --allow-escape-sequences did not preserve the JSON string value.

    Supporting reports

    Generated by issue triage.

  9. added
    bug
    priority-3
    gh-api
    on Nov 9, 2026
  10. removed
    needs-triage
    on Nov 9, 2026
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

    buggh-apipriority-3

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions