HIGH sql injectionecho goapi keys

Sql Injection in Echo Go with Api Keys

Sql Injection in Echo Go with Api Keys — how this specific combination creates or exposes the vulnerability

SQL injection in an Echo Go service becomes significantly riskier when API keys are used for routing, tenant isolation, or feature gating. If the API key influences which database query is built or which schema is selected, an attacker who can influence the key value may be able to change query logic, bypass tenant boundaries, or escalate access.

Consider an Echo Go handler that selects a database schema based on an API key passed as a header:

// Unsafe: schema selected from API key header
apiKey := req.Header.Get("X-API-Key")
schema := apiKey // directly used in query building
query := fmt.Sprintf("SELECT * FROM %s.users WHERE id = $1", schema)
row := db.QueryRow(query, userID)

If the API key is attacker-controlled (e.g., via a leaked key, a subdomain takeover, or a misconfigured proxy that reflects the key), they can manipulate the schema name and perform SQL injection on the constructed table or schema name. Sprintf-style query building with string concatenation on the API key is a common root cause, and it maps directly to the BFLA/Privilege Escalation and Input Validation checks in middleBrick’s 12 security checks.

Another scenario involves using the API key to select a tenant ID that is then interpolated into SQL without proper validation:

// Unsafe: tenant derived from API key and concatenated into SQL
tenant := req.Header.Get("X-Tenant-Key")
var users []User
db.Select("mydb", fmt.Sprintf("SELECT * FROM %s.users", tenant))

This pattern can enable SQL injection if the tenant value is not strictly validated or enumerated. Even when placeholders are used for values, dynamically changing the table or database name via string interpolation remains unsafe. The scanner’s SQL injection checks correlate such practices with the OWASP API Top 10 A03:2023 injection risks and can surface path-specific findings tied to the API key handling logic.

Additionally, if an endpoint echoes the API key in error messages or logs, it may aid reconnaissance for injection attempts. middleBrick’s Data Exposure and Input Validation checks help surface these secondary risks, providing prioritized findings with severity and remediation guidance.

Api Keys-Specific Remediation in Echo Go — concrete code fixes

Remediation centers on never using API key values directly in SQL construction and enforcing strict allowlists for schema or tenant identifiers.

1) Use a mapping from API key to allowed schema/tenant, and apply parameterized queries for all data values:

// Safe: map API key to a validated schema
type tenantDB map[string]string
validSchemas := tenantDB{
    "ak_live_abc123": "tenant_a",
    "ak_test_xyz789": "tenant_b",
}
schema, ok := validSchemas[apiKey]
if !ok {
    echo.ErrAbort(http.StatusUnauthorized)
    return
}
query := "SELECT * FROM " + schema + ".users WHERE id = $1"
row := db.QueryRow(query, userID)

2) Alternatively, enforce tenant IDs via a strict allowlist and use placeholders for values only:

// Safe: enumerated tenants, parameterized values
allowedTenants := map[string]bool{"tenant_a": true, "tenant_b": true}
tenant := req.Header.Get("X-Tenant-ID")
if !allowedTenants[tenant] {
    echo.ErrAbort(http.StatusForbidden)
    return
}
query := "SELECT * FROM mydb." + tenant + ".users WHERE id = $1"
row := db.QueryRow(query, userID)

3) For higher assurance, avoid runtime SQL name construction entirely. Store tenant-specific data in separate schemas or databases and select at connection time, or use row-level security where supported. Always validate and scope the API key against a registry before use.

After applying fixes, rerun the scan using middleBrick’s CLI to confirm risk reduction:

middlebrick scan https://api.example.com

Compare the before/after reports in the Web Dashboard to ensure findings tied to API key handling are resolved. The Pro plan’s continuous monitoring and GitHub Action integration can prevent regressions by failing builds if new SQL injection patterns are introduced.

Related CWEs: inputValidation

CWE IDNameSeverity
CWE-20Improper Input Validation HIGH
CWE-22Path Traversal HIGH
CWE-74Injection CRITICAL
CWE-77Command Injection CRITICAL
CWE-78OS Command Injection CRITICAL
CWE-79Cross-site Scripting (XSS) HIGH
CWE-89SQL Injection CRITICAL
CWE-90LDAP Injection HIGH
CWE-91XML Injection HIGH
CWE-94Code Injection CRITICAL

Frequently Asked Questions

Can middleBrick detect SQL injection when API keys are used for tenant selection?
Yes. middleBrick’s Input Validation and BFLA checks analyze how API key values influence query construction and flag unsafe string interpolation or missing allowlists that could lead to SQL injection.
Does fixing SQL injection require changes to the API key management process?
Yes. Remediation typically requires mapping keys to validated schema/tenant identifiers, using allowlists, and avoiding dynamic SQL name assembly that includes the key or tenant value.