Log Injection in Chi with Cockroachdb
Log Injection in Chi with Cockroachdb — how this specific combination creates or exposes the vulnerability
Log injection occurs when untrusted input from a request is written into application logs without proper sanitization or formatting. In a Chi-based service that uses Cockroachdb as the backend datastore, the combination of structured HTTP routing with a relational database driver creates multiple points where attacker-controlled data can reach logs. If user-supplied values such as IDs, query parameters, or request bodies are interpolated into log statements without escaping, an attacker can inject new log lines or forge context that obscures the true event sequence.
Chi does not provide built-in logging guards; it passes request context through middleware and handlers where developers commonly log request metadata, SQL query parameters, and error details. When a Cockroachdb driver call receives tainted input and that input is later included in log output—whether via direct string concatenation or formatted with a helper like log.Printf—the log stream can be polluted. For example, injecting a newline and crafted message into a user ID parameter can produce additional fabricated log entries, complicating incident response and potentially hiding related attacks. Because Cockroachdb logs can also capture query text, an attacker may attempt to manipulate what appears in application or database-side logs through the application’s logging layer.
In a microservice architecture where structured JSON logging is common, injected content can break log parsers, trigger noisy alerts, or be misinterpreted as legitimate diagnostic data. The vulnerability is not in Cockroachdb itself but in how the application logs data that originates from the database or user input. Without validation, escaping, or structured context boundaries, logs lose fidelity and security tooling may produce false negatives. middleBrick’s LLM/AI Security checks highlight risks where system prompt leakage or output data could inadvertently reveal internal logic; similarly, log injection undermines the integrity of recorded operational data.
Concrete risk patterns include inserting newlines to fabricate entries, injecting structured separators that confuse log aggregation tools, and adding misleading metadata that appears authoritative. Since Chi routes often pass database handles through request context, developers must ensure that any logged identifiers, SQL parameters, or error messages are sanitized. middleBrick scans can detect unsafe logging practices by correlating input validation checks with log emission points, emphasizing the need to treat logs as untrusted output.
Cockroachdb-Specific Remediation in Chi — concrete code fixes
Remediation focuses on strict separation of data and log content, using structured logging with explicit fields, and avoiding string interpolation of request- or database-derived values into log messages. In Chi, apply validation and sanitization in middleware before values reach handlers, and ensure log statements receive already-sanitized values or safe representations.
Use a structured logger that supports key-value fields rather than plain text concatenation. This preserves machine-readability and reduces parsing issues. Below is an example of a safe Chi handler with Cockroachdb that logs only sanitized, typed fields:
// Chi handler with safe logging and Cockroachdb query
package main
import (
"context"
"fmt"
"log/slog"
"net/http"
"regexp"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// sanitizeInput allows only alphanumeric and a limited safe set.
var safeID = regexp.MustCompile(`^[a-zA-Z0-9\-_]+$`).MatchString
func userHandler(db *pgxpool.Pool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userID := chi.URLParam(r, "userID")
if !safeID(userID) {
slog.Warn("invalid userID rejected", "userID", userID)
http.Error(w, "invalid identifier", http.StatusBadRequest)
return
}
var username string
err := db.QueryRow(r.Context(), "SELECT username FROM users WHERE id = $1", userID).Scan(&username)
if err != nil {
slog.Error("db query failed", "userID", userID, "error", err.Error())
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
// Safe: logging structured fields, not injecting raw input into message text.
slog.Info("user fetched",
"userID", userID,
"username", username,
)
fmt.Fprintf(w, "OK")
}
}
func main() {
db, err := pgxpool.New(context.Background(), "postgresql://user:pass@localhost:26257/mydb?sslmode=disable")
if err != nil {
panic(err)
}
defer db.Close()
r := chi.NewRouter()
r.Get("/users/{userID}", userHandler(db))
http.ListenAndServe(":8080", r)
}
Key practices:
- Validate and restrict characters for identifiers using a strict allowlist (regex) before using them in SQL or logs.
- Log using structured fields (e.g.,
slog) so that log parsers treat each field independently; avoid injecting raw strings into the message template. - Ensure database driver usage is consistent with Cockroachdb’s PostgreSQL wire protocol, using parameterized queries to avoid SQL injection that could lead to unexpected log content.
- Do not log full SQL queries with embedded values; if necessary, use placeholders and log values separately.
- Apply middleware-level input normalization to remove or escape newline and carriage return characters that could break log line boundaries.
By combining input validation, safe logging patterns, and parameterized database access, the Chi + Cockroachdb stack can avoid log injection while maintaining clear, reliable audit trails.