GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Go Fiber

NoSQL Injection in Go Fiber apps typically occurs when untrusted user input is parsed into a generic map and passed directly to the MongoDB driver's query engine. Attackers exploit this by injecting MongoDB operators like $gt, $ne, or $regex to bypass authentication logic or dump databases. If you're using c.BodyParser into a bson.M or map[string]interface{}, you're likely pwned.

The Vulnerable Pattern

app.Post("/api/v1/login", func(c *fiber.Ctx) error {
	var payload map[string]interface{}
	if err := c.BodyParser(&payload); err != nil {
		return c.Status(400).SendString("Bad Request")
	}
// VULNERABLE: Attackers can send {"user": "admin", "pass": {"$ne": ""}}
// The driver treats the nested object as a query operator.
var result bson.M
err := collection.FindOne(context.TODO(), payload).Decode(&result)
if err != nil {
	return c.Status(401).SendString("Unauthorized")
}
return c.JSON(result)

})

The Secure Implementation

To kill NoSQLi in Go, stop using dynamic maps for database queries. The fix relies on Strict Typing and Schema Enforcement. By defining a Go struct (LoginRequest), the Fiber BodyParser is forced to cast incoming JSON values into specific types (e.g., string). If an attacker passes an object like {"$gt": ""}, the parser will fail or zero-out the field rather than passing the operator to MongoDB. Furthermore, using bson.D with explicit keys ensures that only the intended fields are queried, neutralizing any field-level injection attempts.

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

app.Post(“/api/v1/login”, func(c *fiber.Ctx) error { var req LoginRequest if err := c.BodyParser(&req); err != nil { return c.Status(400).SendString(“Invalid Input”) }

// SECURE: Explicitly defining the filter prevents operator injection.
// Even if the JSON contains objects, BodyParser will only map the string fields.
filter := bson.D{
	{Key: "username", Value: req.Username},
	{Key: "password", Value: req.Password},
}

var result bson.M
err := collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
	return c.Status(401).SendString("Unauthorized")
}
return c.JSON(result)

})

System Alert • ID: 7525
Target: Go Fiber API
Potential Vulnerability

Your Go Fiber API might be exposed to NoSQL Injection

74% of Go Fiber 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.