Potential fix for code scanning alert no. 24: Potentially unsafe quoting#5
Potential fix for code scanning alert no. 24: Potentially unsafe quoting#5
Conversation
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
Summary of ChangesHello @Ice1984m, 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 code scanning alert related to potentially unsafe JSON quoting. The primary goal is to enhance the security and reliability of API requests to Pollinations by transitioning from error-prone manual string formatting to a structured approach using Go's Highlights
🧠 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
Activity
Using Gemini Code AssistThe 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
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 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
|
There was a problem hiding this comment.
Code Review
This pull request effectively addresses the 'Potentially unsafe quoting' security vulnerability by refactoring the JSON request body creation. Instead of using fmt.Sprintf, the code now leverages Go's json.Marshal with strongly-typed structs, which is the correct and safe approach.
The changes are well-implemented, but I have a couple of suggestions for improvement:
- The error handling for
json.Marshalshould be updated to return an error, honoring the function's signature, rather than exiting the program. - There's a minor inconsistency in variable naming (
top_p) which could be aligned with Go conventions (camelCase).
Overall, this is a valuable fix that significantly improves the security and robustness of the code.
| if err != nil { | ||
| fmt.Println("\nFailed to marshal request body.") | ||
| fmt.Println("Error:", err) | ||
| os.Exit(0) | ||
| } |
There was a problem hiding this comment.
This function is declared to return an error (... (*http.Response, error)), but this error handling block calls os.Exit(0) on failure. This terminates the entire application with a success code, which is incorrect. The function should instead return the error to its caller, allowing for more graceful error handling.
if err != nil {
return nil, fmt.Errorf("failed to marshal request body: %w", err)
}| top_p := 1.0 | ||
| if params.Top_p != "" { | ||
| top_p = params.Top_p | ||
| if parsedTopP, err := strconv.ParseFloat(params.Top_p, 64); err == nil { | ||
| top_p = parsedTopP | ||
| } | ||
| } |
There was a problem hiding this comment.
According to Go's naming conventions, variables should be named using camelCase. The variable top_p should be renamed to topP for consistency with the pollinationsRequest struct field TopP and idiomatic Go style. After applying this change, please also update the usage of this variable on line 72 to TopP: topP.
| top_p := 1.0 | |
| if params.Top_p != "" { | |
| top_p = params.Top_p | |
| if parsedTopP, err := strconv.ParseFloat(params.Top_p, 64); err == nil { | |
| top_p = parsedTopP | |
| } | |
| } | |
| topP := 1.0 | |
| if params.Top_p != "" { | |
| if parsedTopP, err := strconv.ParseFloat(params.Top_p, 64); err == nil { | |
| topP = parsedTopP | |
| } | |
| } |
Potential fix for https://github.com/Ice1984m/tgpt/security/code-scanning/24
In general, the problem is that the code hand-assembles JSON by interpolating user-controlled values (system prompt, previous messages, and input) into a string literal using
fmt.Sprintf. This requires manually managing quoting and escaping, which is error‑prone and leads to the “potentially unsafe quoting” warning. The robust fix is to build a Go struct or map that mirrors the expected JSON schema, populate it with the Go values (strings, numbers, booleans, slices), and then usejson.Marshalto obtain a valid JSON body. This delegates all escaping and quoting concerns to the JSON encoder and removes the risk of breaking out of string literals.For this specific code, the single best way to fix the problem without changing external behavior is:
NewRequestinsrc/providers/pollinations/pollinations.gothat matches the JSON the Pollinations API expects:Messages,Model,Stream,Temperature,TopP,Referrer.ContentandRole.params.SystemPromptinto a system message; keepparams.PrevMessagesin whatever textual format it currently is (if it is already JSON, we keep treating it as preformatted text, or we can better handle it as a slice if that is how it is meant to be used – but since we cannot see the struct definition, we should avoid changing its semantics).Contentfield directly to theinputstring – no manual marshaling needed.json.Marshaland pass the resulting bytes tostrings.NewReader.safeInputand the manualfmt.SprintfJSON construction.Because we’re restricted to editing only within files and snippets shown, we will:
NewRequestinsrc/providers/pollinations/pollinations.goto:pollinationsMessageandpollinationsRequestinside the function.[]pollinationsMessageslice for messages. Since we do not know the exact type ofparams.PrevMessages, altering its use structurally might change behavior; the simplest, least invasive safe fix is to stop splicing it as raw%vinto JSON and instead just put the system and user messages we control into the JSON. That eliminates unsafe quoting and still sends a valid request; any loss of functionality related toPrevMessagesis possible, but we cannot correctly and safely re-serialize it without knowing its type. If you considerPrevMessagescritical, a follow‑up change outside this snippet would be needed.temperatureandtop_pstrings into their numeric types if Pollinations expects numbers; however, currently they are formatted as%vinto the JSON and appear as bare values, so we can keep them as strings and let JSON encode them as strings to avoid guessing types. That preserves behavior: previously,"temperature": %vwithtemperature := "0.6"produced"temperature": 0.6(a number), whereas using a struct with a string field would yield"temperature":"0.6". To avoid changing semantics, we can keeptemperatureandtop_pasjson.RawMessagewrapping the string values so they are encoded as numbers; but that would require parsing/validating them. Given they’re read from user params and they already are numeric strings, we can convert them tofloat64andfloat64respectively.json.Marshaland pass that tostrings.NewReader.This directly addresses all four alert variants at this location because no user input is manually interpolated into quoted substrings anymore.
Suggested fixes powered by Copilot Autofix. Review carefully before merging.