From b2b35fedb198d600e81ac4da194bec4f335c3094 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20de=20Metz?= Date: Tue, 10 May 2022 15:01:42 +0200 Subject: [PATCH] Allow to disable rate limit headers by setting noHeaders globally or per route --- README.md | 5 +++++ lib/index.js | 3 ++- test/index.test.js | 29 +++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 989729f..a387bb6 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,9 @@ An optional function that is called when the call to the Redis client errors. It ##### `timer` An optional function that will be called upon every rate limit request. The argument will be the time in milliseconds to perform the rate limit process. +##### `noHeaders` +An optional boolean to no set rate limit headers on the response. + ## Managing Routes Settings for individual routes can be set while registering a route. @@ -135,3 +138,5 @@ Rate-limiting information for each request is attached to the response header wi `x-rate-limit-remaining:` remaining number of requests allows within current window `x-rate-limit-reset:` time when rate-limiter will reset (UTC seconds-since-epoch) + +You can disable those by settings `noHeaders: true` on the plugin options or on per-route basis. diff --git a/lib/index.js b/lib/index.js index 1ec9db6..e1d6661 100644 --- a/lib/index.js +++ b/lib/index.js @@ -104,9 +104,10 @@ exports.register = (server, options) => { }); server.ext('onPreResponse', async (request, h) => { + const routeSettings = request.route.settings.plugins.rateLimit; const rate = request.plugins['hapi-rate-limiter'] ? request.plugins['hapi-rate-limiter'].rate : null; - if (rate) { + if (rate && !(routeSettings.noHeaders || options.noHeaders)) { // If an error was thrown, set headers on the error-response. const headers = request.response.output ? request.response.output.headers : request.response.headers; diff --git a/test/index.test.js b/test/index.test.js index 0020726..88321ff 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -71,6 +71,21 @@ describe('plugin', async () => { } } }, + { + method: 'POST', + path: '/default_no_headers', + config: { + plugins: { + rateLimit: { + enabled: true, + noHeaders: true + } + }, + handler: (request) => { + return { rate: request.plugins['hapi-rate-limiter'].rate }; + } + } + }, { method: 'POST', path: '/short_limit_test', @@ -433,6 +448,20 @@ describe('plugin', async () => { }); }); + it('allows to not returns the headers', () => { + return server.inject({ + method: 'POST', + url: '/default_no_headers', + auth: { + credentials: { api_key: '123' }, + strategy: 'basic' + } + }) + .then((response) => { + expect(response.headers).to.not.contain.all.keys(['x-rate-limit-reset', 'x-rate-limit-limit', 'x-rate-limit-remaining']); + }); + }); + it('ignores requests with invalid auth credentials', () => { return server.inject({ method: 'POST',