Integrity Failures in Fiber with Api Keys
Integrity Failures in Fiber with Api Keys — how this specific combination creates or exposes the vulnerability
An integrity failure occurs when an API accepts, processes, or reflects untrusted data in a way that compromises the correctness or trustworthiness of the system. In Fiber, using API keys in an insecure manner can directly enable integrity failures by allowing tampered or untrusted requests to be treated as valid. This typically happens when API keys are transmitted in an easily observable or mutable location, such as URL query strings, headers that are not integrity-protected in transit, or within request bodies that are not authenticated as part of the payload.
When API keys are used without additional integrity mechanisms (e.g., signatures or HMACs), an attacker who can observe or modify network traffic might alter request parameters while keeping the key valid. Because Fiber does not inherently enforce message-level integrity, the server may act on the manipulated data, leading to unauthorized behavior changes, such as modifying resource identifiers, toggling feature flags, or changing processing logic. For example, an attacker could change a user identifier in a query parameter while retaining a valid API key, leading to unauthorized data access or privilege escalation across user boundaries.
Another common scenario involves API keys stored in client-side code or configuration files that are exposed to the end user. If these keys are used to sign or authorize requests without additional safeguards, an attacker who extracts the key can craft requests that appear legitimate, potentially modifying server state in ways that violate integrity constraints. In distributed systems where multiple services share API keys for convenience, the blast radius of a compromised key increases, as it may be reused across endpoints with different trust boundaries, further undermining integrity controls.
Middleware in Fiber applications that log or mirror request data without verifying integrity can also exacerbate the issue. If a request containing an API key and mutable parameters is echoed back or stored without validation, an attacker might use this behavior to inject malicious content that is later reflected to other systems or users. Because API keys in this context serve primarily as an authentication token and not as a cryptographic integrity proof, the system cannot distinguish between legitimate and tampered requests that carry the same key.
Using the built-in LLM/AI Security checks available in middleBrick, such scenarios are detectable through active prompt injection testing and output scanning, which can reveal whether API key usage patterns expose integrity boundaries. The scanner identifies places where keys are accepted without cryptographic binding to the request content, highlighting risks that could lead to unauthorized state changes or data manipulation.
Api Keys-Specific Remediation in Fiber — concrete code fixes
To mitigate integrity failures when using API keys in Fiber, apply cryptographic binding between the key and the request payload or parameters. This ensures that any modification to the request invalidates the authentication. Below are concrete, syntactically correct examples demonstrating secure practices.
1. Use HMAC-Signed Requests
Instead of sending the API key as a plain header, compute an HMAC over selected request attributes (e.g., method, path, timestamp, and body) using the API key as the secret. The server verifies the HMAC before processing the request.
// Client-side: Compute HMAC in Node.js using crypto module
const crypto = require('crypto');
const apiKey = 'your_api_key';
const apiSecret = 'your_api_secret';
const timestamp = Date.now().toString();
const body = JSON.stringify({ action: 'update', userId: '123' });
const message = ['POST', '/v1/users', timestamp, body].join('\n');
const signature = crypto.createHmac('sha256', apiSecret).update(message).digest('hex');
const headers = {
'X-API-Key': apiKey,
'X-API-Timestamp': timestamp,
'X-API-Signature': signature,
'Content-Type': 'application/json'
};
// Send request to Fiber endpoint
fetch('https://api.example.com/v1/users', {
method: 'POST',
headers: headers,
body: body
}).then(response => response.json()).then(console.log);
On the Fiber server, verify the signature before processing:
// Server-side: Verify HMAC in Fiber handler
const crypto = require('crypto');
const apiSecrets = {
'your_api_key': 'your_api_secret'
};
app.post('/v1/users', (req, res) => {
const apiKey = req.headers['x-api-key'];
const timestamp = req.headers['x-api-timestamp'];
const receivedSignature = req.headers['x-api-signature'];
const body = JSON.stringify(req.body);
const message = [`${req.method}`, req.path, timestamp, body].join('\n');
const expectedSignature = crypto.createHmac('sha256', apiSecrets[apiKey])
.update(message)
.digest('hex');
if (!apiKey || !apiSecrets[apiKey] || receivedSignature !== expectedSignature) {
return res.status(401).send({ error: 'Invalid signature' });
}
// Optional: reject stale timestamps to prevent replay
const now = Date.now();
if (Math.abs(now - parseInt(timestamp, 10)) > 30000) {
return res.status(400).send({ error: 'Request expired' });
}
res.send({ status: 'ok' });
});
2. Avoid Sending API Keys in URLs
Never include API keys in query parameters or URL paths, as they can be logged in server logs, browser history, and referrer headers. Use headers instead.
// ❌ Insecure: API key in URL
fetch('https://api.example.com/v1/data?api_key=abc123');
// ✅ Secure: API key in header
fetch('https://api.example.com/v1/data', {
headers: {
'X-API-Key': 'abc123'
}
});
3. Rotate Keys and Scope Permissions
Use distinct API keys per client or service with minimal required permissions. Rotate keys periodically and monitor usage patterns for anomalies that may indicate key compromise.
4. Combine with Request Validation
Even with integrity protections, validate all incoming data strictly. Use a validation library to ensure parameters conform to expected formats and ranges.
const { body, header, param } = require('app/validator');
app.post('/v1/users/:id', [
header('x-api-key').notEmpty().withMessage('API key required'),
param('id').isUUID().withMessage('Invalid user ID'),
body('email').isEmail().normalizeEmail(),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Proceed with trusted data
});