Skip to content

Commit

Permalink
Merge pull request #1909 from navikt/rate_limit
Browse files Browse the repository at this point in the history
Setter rate limit til 100 requests på 1s
  • Loading branch information
maccyber authored Feb 20, 2025
2 parents 0584945 + b33297f commit ee8f089
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
21 changes: 21 additions & 0 deletions server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"@navikt/oasis": "3.4.0",
"express": "^4.21.2",
"express-http-proxy": "2.0.0",
"express-rate-limit": "7.5.0",
"http-proxy-middleware": "3.0.3",
"http-terminator": "3.2.0",
"jsdom": "^24.1.0",
Expand Down
29 changes: 29 additions & 0 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import { createLogger, format, transports } from 'winston';
import { tokenXMiddleware } from './tokenx.js';
import { readFileSync } from 'fs';
import require from './esm-require.js';
import { rateLimit } from 'express-rate-limit'
import crypto from 'crypto'

const apiMetricsMiddleware = require('prometheus-api-metrics');
const { createProxyMiddleware } = httpProxyMiddleware;
Expand Down Expand Up @@ -63,6 +65,30 @@ const log = new Proxy(
}
);

const hashToken = token => crypto.createHash('sha256').update(token).digest('base64');

const apiRateLimit = rateLimit({
windowMs: 1000, // 1 sekund
limit: 100, // Limit each IP to 100 requests per `window`
message: 'You have exceeded the 100 requests in 1s limit!',
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req) => {
const authHeader = req.headers?.authorization || '';
if (!authHeader.startsWith('Bearer ')) {
return req.ip;
}
const token = authHeader.substring(7);
return hashToken(token);
},
handler: (req, res, next, options) => {
if (req.rateLimit.remaining === 0) {
log.error(`Rate limit reached for client ${req.ip}`);
}
res.status(options.statusCode).send(options.message);
}
});

const cookieScraperPlugin = (proxyServer, options) => {
proxyServer.on('proxyReq', (proxyReq, req, res, options) => {
if (proxyReq.getHeader('cookie')) {
Expand Down Expand Up @@ -172,6 +198,9 @@ const main = async () => {
let appReady = false;
const app = express();
app.disable('x-powered-by');

app.use(apiRateLimit)

app.set('views', BUILD_PATH);

app.use('/*', (req, res, next) => {
Expand Down

0 comments on commit ee8f089

Please sign in to comment.