Nosql Injection in Fiber with Basic Auth
Nosql Injection in Fiber with Basic Auth
When a Fiber application uses HTTP Basic Authentication and interacts with a NoSQL database, specific architectural choices can expose injection surfaces despite the presence of authentication. Consider a login endpoint in Fiber that retrieves a user document from MongoDB based on a username provided in a request header. Even though the request includes an Authorization header, the server may construct the query by directly concatenating the header value into a database command. For example, a developer might write code that takes the username from req.Get("Authorization") and uses it to build a MongoDB filter without validation, such as bson.D{{"username", username}}. If the username contains special characters used by the NoSQL query language, such as dollar signs or nested document operators, the database may interpret them as part of the query structure rather than as literal data. This can lead to unauthorized data access, where an attacker manipulates the header to change the query logic, bypassing intended access controls or extracting other users’ documents. The authentication layer confirms a user exists but does not sanitize the input before it reaches the database, creating a gap between identity verification and data access. The NoSQL injection occurs because the application treats untrusted input as query language instead of safe data, a common issue when dynamic queries are built from request headers. MiddleBrick scans this attack surface by testing endpoints that combine authentication headers with database interactions, identifying places where untrusted input reaches the query builder. Its checks include input validation and authentication testing, highlighting cases where credentials are accepted but not properly constrained before database use. These findings map to OWASP API Top 10 categories such as Broken Object Level Authorization and Injection, and they can be correlated with compliance frameworks like PCI-DSS and SOC2. The risk is particularly high when the same header is reused across multiple database operations without normalization or strict allow-listing of permitted characters.
Basic Auth-Specific Remediation in Fiber
To secure a Fiber application using Basic Authentication, you should treat the credentials as untrusted data and enforce strict validation before any database interaction. Instead of directly embedding header values into queries, normalize the input and use parameterized queries or schema-based parsing that does not interpret special characters as operators. Below is a safe pattern using a hardcoded user store for comparison, avoiding dynamic NoSQL query construction from raw headers.
func verifyUser(c *fiber.Ctx) error {
auth := c.Get("Authorization")
if auth == "" {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "authorization header required"})
}
// Expecting Basic base64(credentials)
if !strings.HasPrefix(auth, "Basic ") {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "invalid authorization type"})
}
encoded := strings.TrimPrefix(auth, "Basic ")
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "malformed credentials"})
}
parts := strings.SplitN(string(decoded), ":", 2)
if len(parts) != 2 {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid credentials format"})
}
username, password := parts[0], parts[1]
// Allow-list usernames and use constant-time comparison
if !isValidUsername(username) || !constantTimeCompare(username, "admin") {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "invalid credentials"})
}
if !constantTimeCompare(password, "correct-hashed-password") {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "invalid credentials"})
}
return c.Next()
}
func isValidUsername(input string) bool {
matched, _ := regexp.MatchString(`^[a-zA-Z0-9_-]{1,64}$`, input)
return matched
}
In this example, the Authorization header is parsed and validated before any lookup. The username is checked against a strict allow-list using a regular expression, and constant-time comparison is used to prevent timing attacks. No user-supplied string is directly inserted into a NoSQL query, eliminating the risk of injection. If you use a database, pass only verified, allow-listed identifiers to query functions, and avoid building filters by string concatenation. MiddleBrick’s CLI can be run as middlebrick scan <url> to detect whether your endpoints follow this pattern. Its reports highlight authentication and input validation findings, and the Pro plan supports automated scanning in CI/CD pipelines to catch regressions before deployment.
Frequently Asked Questions
Does Basic Authentication alone prevent NoSQL injection in Fiber?
How can I test my Fiber endpoints for injection risks?
middlebrick scan <url>. The tool checks input validation and authentication handling, providing remediation guidance without requiring credentials.