Pii Leakage in Gorilla Mux with Cockroachdb
Pii Leakage in Gorilla Mux with Cockroachdb — how this specific combination creates or exposes the vulnerability
Gorilla Mux is a widely used HTTP router for Go that provides pattern-based routing and variable extraction from requests. When paired with CockroachDB, a distributed SQL database, developers often build APIs that handle personally identifiable information (PII) such as email addresses, phone numbers, or government IDs. PII leakage in this combination typically occurs not because of CockroachDB itself, but due to insecure routing patterns, missing authorization checks, and unsafe data handling in handler functions.
One common scenario: a route like /users/{id} uses Gorilla Mux to extract the id parameter and then queries CockroachDB with a raw SQL string that interpolates the ID without proper validation. If the handler does not verify that the requesting user has permission to view that record, any authenticated or even unauthenticated user can enumerate IDs and access other users’ PII. This becomes an IDOR (Insecure Direct Object Reference) pattern, which is explicitly covered in middleBrick’s BOLA/IDOR checks.
Another leakage vector is logging and error reporting. If CockroachDB driver errors or application logs inadvertently include PII—such as email or full names—in responses or stdout, and those logs are exposed through debug endpoints or insecure monitoring, sensitive data is exposed. middleBrick’s Data Exposure checks scan for such risky outputs, including detection of PII in LLM responses when AI integrations are present.
Additionally, if the API response does not explicitly filter fields before serialization, struct fields that contain PII may be included in JSON output even when not intended. With Gorilla Mux, developers might marshal a database model directly into JSON without applying selective filtering or view models. middleBrick’s Property Authorization checks help identify whether authorization is consistently enforced across properties, reducing the risk of accidental PII exposure through over-permissive serialization.
Input validation gaps also contribute to PII leakage. For example, accepting arbitrary query parameters that influence SQL construction without sanitization can lead to injection or data scraping. middleBrick’s Input Validation checks test for these weaknesses, ensuring that only expected, safe inputs reach CockroachDB.
Cockroachdb-Specific Remediation in Gorilla Mux — concrete code fixes
To prevent PII leakage when using Gorilla Mux with CockroachDB, adopt strict parameter handling, prepared statements, and explicit field-level authorization. Below are concrete, safe patterns.
1. Use parameterized queries with placeholders
Never interpolate user input directly into SQL strings. Use CockroachDB’s support for prepared statements with placeholders to avoid injection and ensure type-safe queries.
import (
"context"
"database/sql"
"net/http"
"github.com/gorilla/mux"
)
func getUserHandler(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
userID := vars["id"]
ctx := context.Background()
var email string
// Use ? placeholder style supported by CockroachDB via the pgx driver
err := db.QueryRowContext(ctx, "SELECT email FROM users WHERE id = $1", userID).Scan(&email)
if err != nil {
http.Error(w, "User not found", http.StatusNotFound)
return
}
// Explicitly return only non-PII or authorized fields
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"email": "` + email + `"}`))
}
}
2. Enforce ownership and authorization per request
Always validate that the requesting user has the right to access the requested resource. Do not rely on client-supplied IDs alone.
func getUserDataHandler(db *sql.DB, currentUserID string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
requestedID := vars["id"]
if requestedID != currentUserID {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
ctx := context.Background()
var name, email string
err := db.QueryRowContext(ctx,
"SELECT name, email FROM profiles WHERE user_id = $1",
requestedID).Scan(&name, &email)
if err != nil {
http.Error(w, "Data unavailable", http.StatusNotFound)
return
}
// Apply property-level filtering to avoid exposing PII unintentionally
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"name": "` + name + `", "email": "` + email + `"}`))
}
}
3. Apply field filtering and avoid struct leakage
Define explicit response structs that include only necessary fields. Do not expose full database models.
type SafeUserResponse struct {
ID string `json:"id"`
Email string `json:"email"`
}
func safeUserHandler(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
userID := vars["id"]
ctx := context.Background()
var resp SafeUserResponse
err := db.QueryRowContext(ctx,
"SELECT id, email FROM users WHERE id = $1",
userID).Scan(&resp.ID, &resp.Email)
if err != nil {
http.Error(w, "Not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
// Only serialized fields in SafeUserResponse are included
// This prevents accidental PII leakage via other struct fields
}
}
4. Secure logging and error handling
Ensure logs and error messages do not contain PII. Use structured logging with redaction for sensitive fields.
import "log"
func handleQueryError(err error) {
// Avoid logging raw query inputs or user data
if err != nil {
log.Printf("db query failed: %v", err)
}
}
By combining these patterns—parameterized queries, per-request ownership checks, strict field filtering, and safe logging—you significantly reduce the risk of PII leakage in a Gorilla Mux and CockroachDB stack. middleBrick’s checks for BOLA/IDOR, Property Authorization, and Data Exposure are aligned with these practices and help validate that controls are in place.
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |