Skip to content

Potential fix for code scanning alert no. 24: Potentially unsafe quoting#5

Draft
Ice1984m wants to merge 1 commit intomainfrom
alert-autofix-24
Draft

Potential fix for code scanning alert no. 24: Potentially unsafe quoting#5
Ice1984m wants to merge 1 commit intomainfrom
alert-autofix-24

Conversation

@Ice1984m
Copy link
Owner

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 use json.Marshal to 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:

  1. Define a small local struct type (or use anonymous structs) inside NewRequest in src/providers/pollinations/pollinations.go that matches the JSON the Pollinations API expects:
    • A top-level object with fields like Messages, Model, Stream, Temperature, TopP, Referrer.
    • Each message being an object with Content and Role.
  2. Convert params.SystemPrompt into a system message; keep params.PrevMessages in 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).
  3. Set the user message Content field directly to the input string – no manual marshaling needed.
  4. Marshal the whole request body with json.Marshal and pass the resulting bytes to strings.NewReader.
  5. Remove the intermediate safeInput and the manual fmt.Sprintf JSON construction.

Because we’re restricted to editing only within files and snippets shown, we will:

  • Modify NewRequest in src/providers/pollinations/pollinations.go to:
    • Introduce small local structs pollinationsMessage and pollinationsRequest inside the function.
    • Build a []pollinationsMessage slice for messages. Since we do not know the exact type of params.PrevMessages, altering its use structurally might change behavior; the simplest, least invasive safe fix is to stop splicing it as raw %v into 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 to PrevMessages is possible, but we cannot correctly and safely re-serialize it without knowing its type. If you consider PrevMessages critical, a follow‑up change outside this snippet would be needed.
    • Parse temperature and top_p strings into their numeric types if Pollinations expects numbers; however, currently they are formatted as %v into 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": %v with temperature := "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 keep temperature and top_p as json.RawMessage wrapping 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 to float64 and float64 respectively.
  • Create the JSON body with json.Marshal and pass that to strings.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.

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
@gemini-code-assist
Copy link

Summary of Changes

Hello @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 json.Marshal function. This change ensures that user-controlled inputs are correctly escaped and formatted, mitigating the risk of injection vulnerabilities and improving the overall robustness of the application's communication with external services.

Highlights

  • Enhanced JSON Serialization: Replaced manual JSON string assembly using fmt.Sprintf with Go structs and json.Marshal to prevent "potentially unsafe quoting" vulnerabilities.
  • Improved Parameter Handling: Converted temperature and top_p parameters from string to float64 with robust parsing, ensuring correct numeric representation in the JSON payload.
  • Code Structure Refinement: Introduced local pollinationsMessage and pollinationsRequest structs to clearly define the Pollinations API request structure, improving readability and maintainability.

🧠 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
  • src/providers/pollinations/pollinations.go
    • Imported the strconv package for string to float conversion.
    • Modified temperature and top_p handling to parse string inputs into float64 values.
    • Defined pollinationsMessage and pollinationsRequest structs for structured JSON serialization.
    • Refactored the request body creation to use json.Marshal with the new structs.
    • Removed the previous fmt.Sprintf based JSON construction.
    • Added error handling for json.Marshal.
Activity
  • No human activity has been recorded on this pull request 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.

Copy link

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

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 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.Marshal should 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.

Comment on lines +77 to +81
if err != nil {
fmt.Println("\nFailed to marshal request body.")
fmt.Println("Error:", err)
os.Exit(0)
}

Choose a reason for hiding this comment

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

high

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)
	}

Comment on lines +35 to 40
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
}
}

Choose a reason for hiding this comment

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

medium

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.

Suggested change
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
}
}

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant