Bola Idor in Fiber with Hmac Signatures
Bola Idor in Fiber with Hmac Signatures — how this specific combination creates or exposes the vulnerability
Broken Object Level Authorization (BOLA) is an API security risk where an attacker can access or modify resources that belong to another user by changing object identifiers such as IDs. When endpoints in Fiber use Hmac Signatures for request authentication but do not enforce proper resource ownership checks, the combination can expose BOLA despite the presence of signature validation.
Consider an endpoint like GET /users/:userId/orders/:orderId. The API may validate an Hmac Signature to verify the request originates from a trusted source or client, but if it only checks the signature and then directly queries the database for orderId scoped to the provided userId without confirming that the authenticated principal owns that user, an attacker can manipulate userId or orderId to access others' orders. Hmac Signatures ensure integrity and authenticity of the request, yet they do not by themselves enforce authorization boundaries. This gap maps to the OWASP API Top 10 2023 A1: Broken Object Level Authorization and can lead to unauthorized data access or tampering.
In a typical Fiber route setup, developers might use middleware that verifies the Hmac Signature and attaches user context, but then skip a definitive ownership check. For example, if the middleware decodes the signature and extracts a sub claim representing the client, but the route logic queries orders by userId taken directly from the URL without comparing it to the authenticated client’s allowed resources, the authorization decision is incomplete. An attacker who knows or guesses another user’s numeric or UUID identifiers can iterate through them, and because the endpoint trusts the URL parameters and the valid Hmac Signature, it returns data that should be restricted.
Real-world scenarios include APIs that expose administrative endpoints with Hmac-based service-to-service authentication but fail to scope data to the authenticated service’s permitted tenant or user. For instance, a procurement API might use Hmac Signatures to authenticate a supplier service, yet if a route like GET /suppliers/:supplierId/invoices/:invoiceId does not verify that the invoice belongs to the given supplier, an attacker can change supplierId to access invoices of other suppliers. This is a BOLA flaw enabled by trusting identifiers without cross-checking relationships, even when request integrity is cryptographically verified.
The risk is particularly concerning when endpoints expose sensitive objects such as payment records, personal identifiable information, or configuration details. Because Hmac Signatures do not encode authorization policies, developers must explicitly enforce that the authenticated subject has the right to access the specific object instance. Without this, the API returns a valid response with a 200 status code, but the data exposure occurs silently, making it harder to detect without authorization-specific logging and monitoring.
To detect this using middleBrick’s 12 security checks, the scanner tests unauthenticated attack surfaces and validates whether changing resource identifiers leads to unauthorized data access, even when Hmac Signatures are valid. It correlates findings from the Authentication, BOLA/IDOR, and Property Authorization checks to highlight cases where signature validation exists but ownership checks are missing. The scanner also cross-references the OpenAPI/Swagger specification to ensure that path parameters and security schemes are correctly modeled, identifying inconsistencies between declared authentication and expected authorization behavior.
Hmac Signatures-Specific Remediation in Fiber — concrete code fixes
Remediation focuses on ensuring that after Hmac Signature validation, every data access enforces strict ownership or scoping. In Fiber, this means combining signature verification middleware with explicit resource-level checks and designing routes so that identifiers are not trusted without validation.
Below is a complete, syntactically correct example of Hmac Signature verification in Fiber using the crypto module. The middleware validates the signature and attaches an authenticated subject to the context. The subsequent route then performs a resource ownership check before querying data. This pattern prevents BOLA by ensuring the authenticated subject matches the resource owner.
import { app, Router, Request, Response } from 'tsoa';
import crypto from 'crypto';
const SHARED_SECRET = process.env.HMAC_SHARED_SECRET;
interface AuthenticatedContext {
subject: string; // e.g., user ID or service ID
}
function verifyHmac(req: Request, res: Response, buf: Buffer, encoding: string): void {
const signature = req.headers['x-hmac-signature'] as string | undefined;
const timestamp = req.headers['x-timestamp'] as string | undefined;
if (!signature || !timestamp) {
res.status(401).json({ error: 'Missing signature or timestamp' });
return;
}
const payload = `${timestamp}.${buf.toString()}`;
const expected = crypto.createHmac('sha256', SHARED_SECRET)
.update(payload)
.digest('hex');
if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature))) {
res.status(401).json({ error: 'Invalid signature' });
return;
}
// Optional: reject requests with stale timestamps (e.g., >5 minutes)
const now = Math.floor(Date.now() / 1000);
if (Math.abs(now - Number(timestamp)) > 300) {
res.status(401).json({ error: 'Stale request' });
return;
}
(req.context as AuthenticatedContext).subject = verifySubjectFromPayload(payload);
}
function verifySubjectFromPayload(payload: string): string {
// Implement extraction logic based on your payload format
// For example, if payload is JSON with a 'sub' field:
try {
const parsed = JSON.parse(Buffer.from(payload.split('.')[1], 'base64').toString());
return parsed.sub;
} catch {
throw new Error('Invalid payload');
}
}
const orderRouter = Router();
orderRouter.get('/users/:userId/orders/:orderId', async (req: Request, res: Response) => {
const userId = req.params.userId;
const orderId = req.params.orderId;
const subject = (req.context as AuthenticatedContext).subject;
// Enforce ownership: subject must match userId
if (subject !== userId) {
res.status(403).json({ error: 'Forbidden: insufficient permissions' });
return;
}
// Proceed to fetch order only if it belongs to the user
const order = await db.orders.findFirst({ where: { id: orderId, userId } });
if (!order) {
res.status(404).json({ error: 'Order not found' });
return;
}
res.json(order);
});
app.use(verifyHmac);
app.register(orderRouter);
For service-to-service flows where the subject is a service identity rather than a user, scope the data access to the service’s permitted resources. For example, if a service can only access its own tenant data, include a tenantId claim in the Hmac payload and ensure that all queries filter by that tenantId. This prevents horizontal BOLA where one service attempts to access another service’s data by manipulating resource IDs.
Additionally, avoid exposing internal identifiers directly in URLs when possible; use opaque tokens mapped to server-side resources, or ensure that IDs are unguessable (e.g., UUIDs). Combine this with logging of subject-to-resource access attempts to detect enumeration patterns that may indicate BOLA probing. middleBrick’s scans can validate these controls by checking whether endpoints enforce ownership and by reviewing the OpenAPI/Swagger definitions for accurate security scheme descriptions.
Remediation also involves updating the API specification to reflect that Hmac Signatures provide integrity and authentication, while explicit authorization checks are required for each sensitive operation. Document expected behavior in the security scheme and operation descriptions so that consumers understand the necessity of additional ownership checks beyond signature validation.
Related CWEs: bolaAuthorization
| CWE ID | Name | Severity |
|---|---|---|
| CWE-250 | Execution with Unnecessary Privileges | HIGH |
| CWE-639 | Insecure Direct Object Reference | CRITICAL |
| CWE-732 | Incorrect Permission Assignment | HIGH |