Skip to content

Commit

Permalink
fix(cmd-api-server): add express static rate limiting
Browse files Browse the repository at this point in the history
Introduces rate limiting to the static file serving express
middleware that returns the index.html of the single
page web applications that the API server can host.

The lack of rate limiting was highlighted as a problem by
CodeQL

Fixes hyperledger-cacti#1840

Signed-off-by: Peter Somogyvari <peter.somogyvari@accenture.com>
  • Loading branch information
petermetz committed Mar 14, 2022
1 parent 618bf47 commit 9cf5592
Show file tree
Hide file tree
Showing 3 changed files with 316 additions and 293 deletions.
1 change: 1 addition & 0 deletions packages/cactus-cmd-api-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
"express-http-proxy": "1.6.2",
"express-jwt": "6.0.0",
"express-openapi-validator": "4.12.12",
"express-rate-limit": "6.3.0",
"fs-extra": "10.0.0",
"google-protobuf": "3.18.0-rc.2",
"jose": "4.1.0",
Expand Down
13 changes: 12 additions & 1 deletion packages/cactus-cmd-api-server/src/main/typescript/api-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import compression from "compression";
import bodyParser from "body-parser";
import cors from "cors";

import rateLimit from "express-rate-limit";
import { Server as SocketIoServer } from "socket.io";
import type { ServerOptions as SocketIoServerOptions } from "socket.io";
import type { Socket as SocketIoSocket } from "socket.io";
Expand Down Expand Up @@ -507,11 +508,21 @@ export class ApiServer {
},
});

const rateLimiterIndexHtml = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});

const middlewareIndexHtml: RequestHandler = (_, res) =>
res.sendFile(resolvedIndexHtml);

app.use("/api/v*", apiProxyMiddleware);
app.use(compression());
app.use(corsMiddleware);
app.use(express.static(resolvedWwwRoot));
app.get("/*", (_, res) => res.sendFile(resolvedIndexHtml));
app.get("/*", rateLimiterIndexHtml, middlewareIndexHtml);

const cockpitPort: number = this.options.config.cockpitPort;
const cockpitHost: string = this.options.config.cockpitHost;
Expand Down
Loading

0 comments on commit 9cf5592

Please sign in to comment.