GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Chi

In Go's Chi framework, NoSQL Injection typically manifests when unsanitized input from `chi.URLParam` or JSON request bodies is passed directly into MongoDB filters. If you use `map[string]interface{}` or `bson.M` without strict type enforcement, attackers can inject operator objects like `{"$ne": null}` to bypass authentication or leak sensitive data. The fix isn't just escaping—it's strict schema enforcement.

The Vulnerable Pattern

func GetUser(w http.ResponseWriter, r *http.Request) {
	var input map[string]interface{}
	json.NewDecoder(r.Body).Decode(&input)
// VULNERABLE: If input["password"] is {"$ne": ""}, 
// the query returns the first user regardless of password.
filter := bson.M{"username": input["username"], "password": input["password"]}

var result User
err := collection.FindOne(ctx, filter).Decode(&result)
// ... handle response

}

The Secure Implementation

The vulnerability lies in the dynamic nature of `interface{}`. When decoding JSON into a map, the parser allows nested objects which the MongoDB driver interprets as query operators. By defining a strict Go `struct` with `string` types, the `json.NewDecoder` enforces type safety. If an attacker attempts to pass a `$ne` object into a field expected to be a string, the decoder will either throw an error or treat the entire object as a literal string value, effectively neutralizing the injection attempt.

type LoginRequest struct {
	Username string `json:"username"` 
	Password string `json:"password"` 
}

func GetUser(w http.ResponseWriter, r *http.Request) { var req LoginRequest // SECURE: json.NewDecoder will fail or force types if the input is an object instead of a string if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, “Invalid input”, 400) return }

// Using typed struct fields ensures the driver treats values as literals, not operators
filter := bson.M{"username": req.Username, "password": req.Password}

var result User
err := collection.FindOne(ctx, filter).Decode(&result)
// ... handle response

}

System Alert • ID: 5265
Target: Chi API
Potential Vulnerability

Your Chi API might be exposed to NoSQL Injection

74% of Chi apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.