Api Rate Abuse in Hapi with Saml
Api Rate Abuse in Hapi with Saml — how this specific combination creates or exposes the vulnerability
Rate abuse in Hapi when SAML is used for authentication can occur when unauthenticated or partially authenticated endpoints are exposed before SAML assertions are validated. Hapi routes typically rely on cookies or session tokens for state, but SAML-based flows often redirect through IdP endpoints that may not enforce strict rate limits on the initial request or on metadata endpoints (e.g., /saml/metadata or /saml/acs). Without explicit rate limiting, an attacker can send many requests to these endpoints to probe for valid users, harvest SAML responses, or trigger authentication loops that lead to account enumeration or session fixation.
In a black-box scan, middleBrick checks for missing rate limiting on authentication and SAML-related routes. If these routes accept high request volumes without throttling, the scan flags a high risk for credential stuffing or brute-force attacks. SAML responses may contain user identifiers in NameID elements; if rate limits are absent, attackers can automate submissions with different user identifiers to infer valid accounts. Even when SAML assertions are cryptographically signed, the endpoint processing them must enforce per-identity or per-IP throttling to prevent abuse of login or Single Logout flows.
Moreover, SAML bindings (HTTP-POST, HTTP-Redirect) can embed signed assertions in query parameters or form bodies. If Hapi does not apply rate limits to the assertion consumer service route (/saml/acs), an attacker can flood the endpoint with forged or intercepted assertions, testing replay patterns or attempting to exploit timing differences in signature validation. MiddleBrick’s 12 security checks run in parallel and include rate limiting analysis; when SAML routes lack token bucket or leaky bucket controls, the finding highlights missing protection on the authentication path, which can enable bypass of other protections such as property authorization or input validation.
Saml-Specific Remediation in Hapi — concrete code fixes
To mitigate rate abuse in Hapi with SAML, apply rate limiting at the route level for SAML-related paths and enforce per-identity throttling on assertion consumption. Use a shared store such as Redis to coordinate limits across instances. The following example shows a Hapi server with two protected routes: one for SAML metadata discovery and one for the assertion consumer service, each guarded by a rate limit policy.
const Hapi = require('@hapi/hapi');
const RateLimit = require('hapi-ratelimit');
const Redis = require('ioredis');
const init = async () => {
const server = Hapi.server({ port: 443, tls: { /* cert and key */ } });
const redis = new Redis({ host: 'redis.example.com' });
const rateLimit = new RateLimit({
redis,
rules: [
{
path: '/saml/metadata',
methods: ['GET'],
mode: 'redis',
limit: 10,
duration: 60
},
{
path: '/saml/acs',
methods: ['POST'],
mode: 'redis',
limit: 5,
duration: 10,
// optional: key by NameID when available
key: (request) => {
const nameId = request.payload && request.payload.SAMLResponse ? extractNameId(request.payload.SAMLResponse) : request.info.remoteAddress;
return nameId;
}
}
]
});
await server.register(rateLimit);
server.route([
{
method: 'GET',
path: '/saml/metadata',
handler: (request, h) => {
// return IdP metadata XML
return fs.readFileSync('metadata/idp-metadata.xml');
}
},
{
method: 'POST',
path: '/saml/acs',
handler: (request, h) => {
// validate SAMLResponse and NameID
const samlResponse = request.payload.SAMLResponse;
if (!validateSignature(samlResponse)) {
return Boom.unauthorized('Invalid signature');
}
const nameId = extractNameId(samlResponse);
// proceed with login logic
return h.response({ user: nameId }).code(200);
}
}
]);
await server.start();
};
function extractNameId(samlResponse) {
// simplified extraction; use proper SAML parsing library
const match = samlResponse.match(/<saml:NameID[^>]*>([^<]+)</saml:NameID>/);
return match ? match[1] : 'unknown';
}
init().catch(err => {
console.error(err);
process.exit(1);
});
In this setup, the /saml/metadata route is limited to 10 requests per minute per IP, while /saml/acs allows 5 POST requests per 10 seconds, keyed by NameID when extractable. This reduces the risk of enumeration and replay. For IdP-initiated flows where SAML responses are posted from external endpoints, validate signatures before processing and apply stricter limits on unauthenticated sessions. MiddleBrick’s dashboard can track score changes after implementing these controls, and the CLI (middlebrick scan <url>) can be integrated into CI/CD to ensure new deployments do not regress on rate limiting.
Frequently Asked Questions
How can I test if my Hapi SAML endpoints are protected against rate abuse?
middlebrick scan <your-api-url>. The scan checks rate limiting on authentication and SAML routes and reports findings. You can also simulate requests with varying assertions or NameIDs while monitoring logs to confirm throttling triggers.