Description
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
trunkateeb44bc432c0107de002dadd34a61b4e2bd15882; the HTTP client and its sanitization tests are unchanged from the release. Both pingithub.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
BagToad commentedon Nov 3, 2026
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?
coygeek commentedon Nov 3, 2026
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 throughgh issue view --json bodychanged 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, andjqavailable:On
gh 2.103.3, the diff shows five replacements inside the fenced JSON diagnostic. For example, the stored literal text\u001b[1mcomes back throughghas\^[[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.mdThe 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.[-]fix(api): preserve literal Unicode escape text in JSON string values[/-][+]Preserve literal Unicode escape text in JSON string values[/+]YevheniiKotyrlo commentedon Nov 6, 2026
The same on Windows.
gh gist editalso 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
trunkat 233b470 (2026-11-11).\u001bthree times, withcurl -fsS https://api.github.com/repos/react/react-native/issues/59821, withgh issue view 59821 --repo react/react-native --json body --jq .bodyand withgh api repos/react/react-native/issues/59821 --jq .body.probe.txtholdingfirst, and a description holding\u001b:gh gist create --desc 'writeback probe, literal \u001b text' probe.txt. Change the file tosecondwithgh gist edit <gist> --filename probe.txt probe.txt, then read the stored description withcurlfromGET /gists/<gist>.gh issue comment <issue> --body-file <file>, the file holdingEscapes as text: \u0000 \u001f \u0041 \u007f \u0080 \u0081 \u009f \u00a0 \u00ff \u0100 \uffffand then each escape on a line of its own in a fenced code block. Read it withcurlfromGET /repos/{owner}/{repo}/issues/comments/{comment_id}and withgh api repos/{owner}/{repo}/issues/comments/{comment_id} --jq .body.Actual result:
\u001bthree times;gh issue viewandgh apiprint each as\^[.gh gist edit, GitHub stores the description with\^[where it held\u001b;probe.txtholdssecond.\u0000and\u0080as\^@,\u0081as\^A, and\u001fand\u009fas\^_;\u0041,\u007f,\u00a0,\u00ff,\u0100and\uffffread as posted.Expected result: gh prints, and writes back to GitHub, the text GitHub returns, each
\u00XXposted as text as it was posted; a control character a response really holds still prints in caret notation.repro.shruns steps 1 and 2 through the gist'sreadback.shandwriteback.sh, which deletes the gist it creates. It prints:reproduce.shruns step 3 and prints:cli-triage commentedon Nov 9, 2026
Reproducible on 2.103.3.
Using test data with a JSON string containing printable
\u001btext:Exit status:
0.The literal sequence in
bodychanged to caret notation, while the actual ESC incontrolwas neutralized and plain text stayed unchanged.gh issue view 1 -R example.invalid/hello --json bodyshowed the same mutation. The latest release and source build behaved the same.--allow-escape-sequencesdid not preserve the JSON string value.Supporting reports
Duplicate analysis
Label reasoning
Reproduction log
Investigation notes
Generated by issue triage.