Nosql Injection in Chi with Cockroachdb
Nosql Injection in Chi with Cockroachdb — how this specific combination creates or exposes the vulnerability
Nosql Injection occurs when user-controlled input is interpreted as part of the query language rather than as data. In a Chi application using Cockroachdb, this typically arises when building SQL strings dynamically with values from request parameters, headers, or JSON payloads. Cockroachdb implements PostgreSQL wire protocol and syntax, so injection patterns that work against PostgreSQL can apply when SQL is constructed incorrectly in Go handlers.
Chi routes often use URL parameters or path variables that are concatenated into SQL strings. For example, extracting a userID from the request context and inserting it directly into a string that is then executed exposes the endpoint to injection. Even though Cockroachdb supports prepared statements and parameterized queries, developers sometimes bypass them for dynamic table names or operators, which cannot be parameterized and require careful sanitization.
Consider a Chi endpoint that retrieves a user by tenant and status:
// Unsafe: string concatenation with user input
userID := chi.URLParam(r, "userID")
status := chi.URLParam(r, "status")
query := fmt.Sprintf("SELECT id, email FROM users WHERE tenant_id = '%s' AND status = '%s'", tenantID, status)
rows, err := db.Query(query)
If an attacker provides userID as ' OR '1'='1, the resulting query can bypass intended filters and return unintended rows. Cockroachdb will execute the modified logic, potentially exposing data across tenants. This is a classic BOLA/IDOR vector facilitated by unsafe string building.
Another scenario involves JSON input where keys or values are interpreted as identifiers or operators. If a handler unmarshals JSON and uses fields to construct dynamic SQL without validation, injection can occur. For example, using a field to specify a sort column without allowlisting enables injection:
// Unsafe: using JSON field directly in ORDER BY
var payload struct {
SortField string `json:"sort_field"`
}
if json.NewDecoder(r.Body).Decode(&payload) == nil {
query := fmt.Sprintf("SELECT id, name FROM users ORDER BY %s", payload.SortField)
rows, err := db.Query(query)
}
Here, an attacker can supply name; DROP TABLE users-- as sort_field
LLM/AI Security checks in middleBrick detect scenarios where prompts or generated code encourage unsafe concatenation, and they highlight findings that map to OWASP API Top 10 A03:2023 Injection. Continuous monitoring in the Pro plan can alert you when new endpoints or changes introduce such patterns before they reach production.
Cockroachdb-Specific Remediation in Chi — concrete code fixes
Remediation centers on using parameterized queries, allowlisting, and strict input validation. For Cockroachdb in Chi, always prefer placeholders for values and avoid interpolating user input into SQL text.
Safe query using placeholders:
// Safe: parameterized query
userID := chi.URLParam(r, "userID")
status := chi.URLParam(r, "status")
query := "SELECT id, email FROM users WHERE tenant_id = $1 AND status = $2"
rows, err := db.Query(query, tenantID, status)
Note the use of $1 and $2 placeholders. Cockroachdb recognizes this style and treats the provided values strictly as data, preventing injection.
For dynamic table or column names (which cannot be parameterized), implement strict allowlisting:
// Safe: allowlist for column names
validColumns := map[string]bool{"name": true, "email": true, "created_at": true}
sortField := chi.URLParam(r, "sort_field")
if !validColumns[sortField] {
http.Error(w, "invalid sort field", http.StatusBadRequest)
return
}
query := "SELECT id, name FROM users ORDER BY " + sortField
rows, err := db.Query(query)
This ensures only known-safe identifiers are used. In a Chi middleware, you can centralize such checks to keep handlers clean.
When working with JSON input, validate and sanitize each field rather than directly interpolating:
// Safe: validate and use parameterized queries with JSON input
var payload struct {
TenantID string `json:"tenant_id"`
Status string `json:"status"`
Sort string `json:"sort"`
}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
if payload.Sort != "asc" && payload.Sort != "desc" {
payload.Sort = "asc"
}
query := "SELECT id, email FROM users WHERE tenant_id = $1 AND status = $2 ORDER BY created_at " + payload.Sort
rows, err := db.Query(query, payload.TenantID, payload.Status)
For scans that verify these patterns, the CLI tool can be used locally: middlebrick scan <url>. In CI/CD, the GitHub Action can enforce a minimum security score and fail builds if unsafe patterns are detected. The MCP Server enables scanning from AI coding assistants, helping catch issues during development.
Remediation guidance from findings includes using parameterized queries, allowlisting identifiers, and validating JSON against schemas. These steps reduce the attack surface and align with compliance mappings to OWASP API Top 10 and SOC2 controls.