Skip to content

fix: json body corruption when string variables contain special characters - #32317

Closed
Mr-Neutr0n wants to merge 1 commit into
langgenius:mainfrom
Mr-Neutr0n:fix/http-request-json-body-variable-escaping
Closed

fix: json body corruption when string variables contain special characters#32317
Mr-Neutr0n wants to merge 1 commit into
langgenius:mainfrom
Mr-Neutr0n:fix/http-request-json-body-variable-escaping

Conversation

@Mr-Neutr0n

Copy link
Copy Markdown

When the HTTP Request node builds a JSON body from a template like {"content": {{#node.result#}}}, it was doing raw string substitution via convert_template().text and then running repair_json on the result. If the variable value contains quotes, backslashes, newlines, or pipe characters (common in markdown), the substitution breaks the JSON structure and repair_json corrupts the data rather than fixing it.

The root cause is that string values weren't being JSON-escaped before substitution. For example, a value like hello "world" would produce {"content": hello "world"} — broken JSON that repair_json can't reliably reconstruct.

Fixed by adding _convert_template_for_json() which uses json.dumps() to properly encode string variable values before they land in the JSON structure. Numbers, objects, and arrays continue to use their existing .text representation which already produces valid JSON tokens. Also handles the edge case where template authors already wrap variables in quotes (e.g. "{{#var#}}").

Added two regression tests covering strings with quotes/backslashes/newlines and markdown table content.

Closes #31927

…ters

the http request node was doing raw string substitution for template
variables in json bodies, then relying on repair_json to fix the
resulting broken json. this corrupted data when string values contained
quotes, backslashes, newlines, or other json-special characters.

now string variable values are properly json-encoded before substitution
using json.dumps, which correctly escapes special characters. also handles
the case where template authors pre-wrap variables in quotes.

fixes langgenius#31927
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Feb 13, 2026
@Mr-Neutr0n Mr-Neutr0n mentioned this pull request Feb 13, 2026
6 tasks
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @Mr-Neutr0n, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a critical bug in the HTTP Request node where JSON bodies would become corrupted if string variables contained special characters. The previous raw string substitution method failed to properly escape these characters, leading to invalid JSON. The solution involves a new, JSON-aware templating function that correctly encodes string variable values, ensuring the integrity of the generated JSON body and preventing data corruption.

Highlights

  • JSON Body Corruption Fix: Resolved an issue where the HTTP Request node's JSON body was corrupted when string variables contained special characters like quotes, backslashes, or newlines.
  • JSON-Aware Templating: Introduced a new method, _convert_template_for_json(), to properly JSON-escape string variable values before substitution into the JSON structure.
  • Edge Case Handling: Implemented logic to detect and correctly handle string variables that are already wrapped in quotes within the template, preventing double-escaping.
  • Improved Robustness: Modified JSON parsing logic to first attempt direct json.loads() and then fall back to repair_json if initial parsing fails, ensuring better error handling for malformed templates.
  • Regression Tests: Included two new unit tests to validate the fix for strings with special characters and markdown table content, ensuring the issue does not reoccur.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • api/core/workflow/nodes/http_request/executor.py
    • Imported StringSegment and VARIABLE_PATTERN for enhanced variable handling.
    • Replaced the generic convert_template().text with a new _convert_template_for_json() method for JSON body construction.
    • Modified JSON parsing logic to first attempt direct json.loads() and then fall back to repair_json if initial parsing fails.
    • Implemented _convert_template_for_json() to split templates, resolve variables, and JSON-escape string values, including handling pre-quoted variables.
  • api/tests/unit_tests/core/workflow/nodes/http_request/test_http_request_executor.py
    • Added test_executor_with_json_body_and_string_with_special_chars to verify correct handling of strings with quotes, backslashes, and newlines.
    • Added test_executor_with_json_body_and_markdown_table_string to ensure markdown table content with pipe characters is not corrupted.
Activity
  • The pull request introduces a fix for issue HTTP Request corrupts input #31927, addressing JSON body corruption.
  • Two new regression tests have been added to validate the implemented solution.
  • No other review comments or activities have been recorded yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request aims to resolve JSON body corruption when HTTP request nodes use string variables with special characters, introducing _convert_template_for_json for proper escaping and repair_json for backward compatibility, along with comprehensive regression tests. However, a critical vulnerability exists: the logic for detecting quoted variables in _convert_template_for_json is flawed, potentially leading to invalid JSON. Furthermore, error handling for JSON parsing failures exposes sensitive variables in exception messages, posing an information exposure risk. Additionally, consider refactoring the new method for improved readability.

Comment on lines +304 to +311
if preceding.rstrip().endswith('"') and following.lstrip().startswith('"'):
# Already quoted — just escape special chars without adding quotes
escaped = json.dumps(variable.value, ensure_ascii=False)
# Strip the outer quotes that json.dumps adds
result.append(escaped[1:-1])
else:
# Not quoted — json.dumps adds quotes and escapes
result.append(json.dumps(variable.value, ensure_ascii=False))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

The logic for detecting "already quoted" variables is flawed. It only works correctly if the variable is the sole content of the quotes in the template. If a variable is part of a larger string (e.g., ""prefix-{{#var#}}""), preceding.rstrip().endswith('"') will be false, and json.dumps() will be called on the variable value, adding extra quotes (e.g., ""prefix-"val"""). This results in invalid JSON, which breaks functionality and can be used to trigger the RequestBodyError mentioned above, potentially leaking other sensitive variables in the JSON body.

repaired = repair_json(json_string)
json_object = json.loads(repaired, strict=False)
except json.JSONDecodeError as e:
raise RequestBodyError(f"Failed to parse JSON: {json_string}") from e

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

The RequestBodyError exception includes the full json_string in its message. This string contains resolved variable values, which may include sensitive information such as API keys, secrets, or PII. Since this error message is often returned to the user or logged, it can lead to unauthorized disclosure of sensitive data. It is recommended to avoid including the full json_string in the error message and instead provide only the specific parsing error details.

Suggested change
raise RequestBodyError(f"Failed to parse JSON: {json_string}") from e
raise RequestBodyError(f"Failed to parse JSON: {e}") from e

@MezentsevIlya

MezentsevIlya commented Feb 18, 2026

Copy link
Copy Markdown

Why not just remove this JSON "repairing" and modification? It's non-obvious behaviour (hidden changes that the user cannot know about or turn off) and definitely an anti-pattern. If a user creates JSON, they want to send it to the endpoint as-is. If the JSON is invalid, it's the user's problem and the user fixes it. Period.

Or at least there should be an option to disable this behaviour.

@Mr-Neutr0n

Copy link
Copy Markdown
Author

@MezentsevIlya you're right in direction, and I owe you a proper answer — sorry it took this long.

But I think the disagreement dissolves once we're precise about who produces the invalid JSON, because it isn't the user.

The user's JSON is valid. Dify breaks it.

The template from #31927 is well-formed:

{"model": "pro", "messages": [{"role": "user", "content": {{#node.result#}}}]}

The node then pastes the raw variable value into a JSON string position with no encoding. Reproduced against the real code path:

substituted:                    {"model": "pro", ... "content": ### a\n\n| a | a\a\a | a : "[a.a](a://a)" ...
valid JSON after substitution?  NO — Expecting value
after repair_json:              content = ''        <-- the whole value, discarded

So "If the JSON is invalid, it's the user's problem and the user fixes it" doesn't have a target here. There is nothing for the author to fix — they wrote valid JSON and got a corrupted request. That's the platform's bug, and repair_json exists to paper over it.

And note what "repairing" actually did: not a hidden modification, a silent total data loss. The request went out with "content": "". There's a second variant too, where it injects a character: {"content": "prefix {{#var#}} suffix"} with value a"b comes back as prefix a"b suffix".

Which makes your position and this patch the same position

Escaping at substitution time means well-formed templates never produce invalid JSON, so repair_json stops being load-bearing. This is the change that makes removing it possible — right now it can't be removed, because the platform depends on it to clean up its own mess.

I kept it as a fallback only for templates that were malformed before substitution, since some existing workflows likely lean on that and dropping it is a breaking change. If you'd rather it be removed outright or put behind a switch, I agree that's the better end state, and it's a clean follow-up once the cause is fixed. I'd just rather not bundle a breaking change with a data-loss fix.

This PR can't merge, though — the code moved

While this sat, api/core/workflow/nodes/http_request/ was extracted into langgenius/graphon (api/pyproject.toml pins graphon==0.6.0). The file this PR edits no longer exists in this repo, which is why the branch shows as conflicting.

The bug is verbatim intact in graphon 0.7.0 (src/graphon/nodes/http_request/executor.py:275), so I've rewritten the fix against it and opened langgenius/graphon#235. It's a cleaner implementation than what's here: quote state is tracked across the literal parts instead of the fragile "is it already wrapped in quotes" adjacency check, the log-safe copy is encoded the same way, and there are six regression tests, three of which fail on unpatched main.

Closing this one in favour of that. Thanks for pushing on the design — the rewrite is better for it.

@Mr-Neutr0n Mr-Neutr0n closed this Jul 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

HTTP Request corrupts input

2 participants