Sql Injection in Fiber with Api Keys
Sql Injection in Fiber with Api Keys — how this specific combination creates or exposes the vulnerability
SQL Injection in a Fiber-based API that relies on API keys for identification can occur when keys are handled inconsistently between authentication and data access layers. If an API key is accepted as a user-supplied parameter (e.g., via query string or header) and then used to dynamically construct SQL queries without proper validation or parameterization, injection becomes possible.
For example, concatenating an API key value into a SQL string allows an attacker to manipulate the query logic. Consider a route that identifies a user by an api_key query parameter and builds a query to fetch user-specific resources. If the api_key is interpolated directly, an attacker can inject crafted SQL fragments that alter WHERE conditions, extract data, or bypass intended filters. This pattern is especially risky when developers assume API keys are opaque random strings and therefore skip input sanitization.
In a black-box scan, middleBrick tests unauthenticated endpoints that accept API keys as identifiers. It checks whether inputs are properly parameterized across the request lifecycle. Findings may include missing prepared statements, concatenated query construction, and weak validation of key formats. These issues map to OWASP API Top 10:2023 —2 ‘Broken Object Level Authorization’ and A03 ‘Injection’, and can align with PCI-DSS and SOC2 controls that require secure data access practices.
An OpenAPI specification that defines an api_key as a header or query parameter does not inherently prevent runtime injection if the implementation does not enforce strict parameterization. middleBrick cross-references spec definitions with runtime behavior to detect mismatches, such as a declared api_key location that feeds into dynamic SQL. The scanner also evaluates whether input validation restricts key formats and whether rate limiting and authentication checks are consistently applied across endpoints.
Api Keys-Specific Remediation in Fiber — concrete code fixes
To remediate SQL Injection risks when using API keys in Fiber, ensure keys are treated as opaque identifiers and never interpolated into SQL strings. Use parameterized queries or prepared statements for all database operations, and validate key formats before use. Below are concrete examples using the Fiber framework with a PostgreSQL client.
Example 1: Safe parameterized query with API key as a user identifier
const query = require('pg');
const app = new fibers.Fiber();
app.get('/resources', async (req, res) => {
const client = await pool.connect();
try {
// Assume apiKey is extracted from a header and validated as a UUID format
const apiKey = req.headers['x-api-key'];
if (!apiKey || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(apiKey)) {
return res.status(400).send({ error: 'Invalid API key format' });
}
// Parameterized query prevents SQL injection
const result = await client.query(
'SELECT id, name FROM resources WHERE api_key = $1',
[apiKey]
);
res.json(result.rows);
} catch (err) {
res.status(500).send({ error: 'Internal server error' });
} finally {
client.release();
}
});
Example 2: Validate key format and use placeholders in DELETE operations
app.delete('/resources/:resource_id', async (req, res) => {
const apiKey = req.headers['x-api-key'];
const resourceId = req.params.resource_id;
// Validate resourceId as integer to avoid injection via path parameter
const id = parseInt(resourceId, 10);
if (isNaN(id)) {
return res.status(400).send({ error: 'Invalid resource ID' });
}
const client = await pool.connect();
try {
// Use two separate parameters: one for key, one for ID
const result = await client.query(
'DELETE FROM resources WHERE api_key = $1 AND id = $2',
[apiKey, id]
);
if (result.rowCount === 0) {
return res.status(404).send({ error: 'Not found' });
}
res.status(204).send();
} catch (err) {
res.status(500).send({ error: 'Internal server error' });
} finally {
client.release();
}
});
General best practices
- Never concatenate API keys or any user-influenced values into SQL strings.
- Define and enforce allowed key formats using strict validation (e.g., regex for UUIDs or base64-encoded tokens).
- Use environment-managed configuration for database credentials, not request-supplied values.
- Apply consistent authentication checks across routes; consider integrating with a centralized auth handler.
- Leverage middleware to validate headers early, reducing the risk of accidental misuse downstream.
These changes reduce the attack surface and align with secure coding guidance. middleBrick can verify that such mitigations are reflected in both your OpenAPI spec and runtime behavior, supporting compliance mappings to OWASP API Top 10 and related frameworks.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |