Xpath Injection in Chi with Cockroachdb
Xpath Injection in Chi with Cockroachdb — how this specific combination creates or exposes the vulnerability
Chi is a minimal, composable router for Go that encourages explicit route definitions and structured handling of requests. When Chi endpoints construct dynamic queries for CockroachDB, a distributed SQL database, they can inadvertently introduce XPath Injection if user input is used to build XPath expressions without proper safeguards. XPath is commonly used when interacting with XML data stored in CockroachDB, for example when columns contain XML type values or when application logic parses external feeds stored as XML.
An Xpath Injection occurs when an attacker can manipulate the structure of an XPath expression to bypass intended filters or access unauthorized nodes. In the context of Chi + CockroachDB, the risk arises when a handler builds an XPath string using concatenation or interpolation with request parameters. Consider an endpoint that retrieves user preferences stored as XML:
// Example vulnerability: building XPath from user input in Chi handler
func getUserSettings(w http.ResponseWriter, r *http.Request) {
userID := chi.URLParam(r, "userID")
query := fmt.Sprintf("/settings/user[id='%s']", userID)
rows, err := db.Exec(context.Background(), "SELECT xml_data FROM users WHERE id = $1", userID)
// ... then apply query to rows[0].xml_data in application code
}
If userID is controlled by the client and not validated, an attacker can supply something like ' or '1'='1 or more specifically for XPath: ' or 1=1 or ' to alter the semantics of the XPath. In a broader architecture where XPath is evaluated server-side or in application logic after retrieving XML from CockroachDB, this can lead to reading arbitrary XML nodes, bypassing access controls, or extracting sensitive data embedded in XML documents. Because CockroachDB stores and indexes XML columns much like traditional SQL columns, these XML fields become another attack surface when combined with an unsafe XPath construction in Chi handlers.
The scanner checks such patterns by correlating endpoint definitions in Chi with database interaction code and by flagging dynamic XPath construction from request parameters. Findings include severity levels, mapping to OWASP API Top 10 and common weaknesses, with remediation guidance focused on input validation and safe composition of expressions. No internal engine details are disclosed; the report highlights the risky code patterns and points to safer alternatives.
Cockroachdb-Specific Remediation in Chi — concrete code fixes
To prevent Xpath Injection in Chi applications that use CockroachDB, avoid building XPath expressions via string concatenation with user input. Instead, use parameterized approaches and restrict XPath construction to known-safe templates. Below are concrete examples for Chi handlers that interact with XML data stored in CockroachDB.
Safe approach with parameterized XPath-like filtering in application logic:
Keep XPath static and filter using structured data after retrieving XML from CockroachDB:
// Safe pattern: retrieve XML then filter in Go code
func getUserSettingsSafe(w http.ResponseWriter, r *http.Request) {
userID := chi.URLParam(r, "userID")
// Validate userID format strictly
if !isValidUserID(userID) {
http.Error(w, "invalid user ID", http.StatusBadRequest)
return
}
var xmlData string
err := db.QueryRow(context.Background(), "SELECT xml_data FROM users WHERE id = $1", userID).Scan(&xmlData)
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
doc, err := xquery.Parse(strings.NewReader(xmlData))
if err != nil {
http.Error(w, "invalid data", http.StatusInternalServerError)
return
}
// Use a static XPath and filter by userID attribute in the XML document
nodes := doc.Find("//settings/user")
for _, node := range nodes {
id, _ := node.Attr("id")
if id == userID {
// process node
}
}
}
Alternative: Use JSON where possible and avoid XPath entirely:
If your CockroachDB schema allows, store data as JSON and use SQL/JSON functions to extract values safely:
// Example using JSONB column in CockroachDB with Chi
func getProfileSafe(w http.ResponseWriter, r *http.Request) {
userID := chi.URLParam(r, "userID")
var profile string
// CockroachDB JSONB extraction using parameterized queries
err := db.QueryRow(context.Background(),
"SELECT profile->>'email' FROM profiles WHERE id = $1", userID).Scan(&profile)
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
fmt.Fprint(w, profile)
}
Input validation and allowlists:
When XPath must be used, enforce a strict allowlist pattern for identifiers (e.g., alphanumeric and hyphens) and avoid any direct concatenation with user input. Treat user input as data, not as part of the expression language.
middleBrick scans can help identify these risky patterns in your Chi routes and database interaction code, providing prioritized findings and remediation guidance mapped to compliance frameworks. With the Pro plan you can enable continuous monitoring so changes to Chi handlers or CockroachDB queries are automatically assessed for regressions, and the GitHub Action can fail builds if a risk score drops below your chosen threshold.