Skip to content

Commit 986919e

Browse files
committed
Block HTK server CSRF requests by Origin header
1 parent fc0b221 commit 986919e

File tree

3 files changed

+33
-15
lines changed

3 files changed

+33
-15
lines changed

package-lock.json

Lines changed: 14 additions & 14 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
"@types/aws-lambda": "^8.10.15",
4949
"@types/chai": "^4.1.6",
5050
"@types/env-paths": "^1.0.2",
51+
"@types/express": "^4.16.1",
5152
"@types/lodash": "^4.14.117",
5253
"@types/mocha": "^5.2.5",
5354
"@types/node": "^10.12.0",

src/httptoolkit-server.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as _ from 'lodash';
22
import * as events from 'events';
3-
import { GraphQLServer } from 'graphql-yoga'
3+
import { GraphQLServer } from 'graphql-yoga';
4+
import * as Express from 'express';
45
import { GraphQLScalarType } from 'graphql';
56

67
import { HtkConfig } from './config';
@@ -152,6 +153,22 @@ export class HttpToolkitServer extends events.EventEmitter {
152153
typeDefs,
153154
resolvers: buildResolvers(config, interceptors, this)
154155
});
156+
157+
// TODO: This logic also exists in Mockttp - probably good to commonize it somewhere.
158+
this.graphql.use((req: Express.Request, res: Express.Response, next: () => void) => {
159+
const origin = req.headers['origin'];
160+
// This will have been set (or intentionally not set), by the CORS middleware
161+
const allowedOrigin = res.getHeader('Access-Control-Allow-Origin');
162+
163+
// If origin is set (null or an origin) but was not accepted by the CORS options
164+
// Note that if no options.cors is provided, allowedOrigin is always *.
165+
if (origin !== undefined && allowedOrigin !== '*' && allowedOrigin !== origin) {
166+
// Don't process the request: error out & skip the lot (to avoid CSRF)
167+
res.status(403).send('CORS request sent by unacceptable origin');
168+
} else {
169+
next();
170+
}
171+
});
155172
}
156173

157174
async start() {

0 commit comments

Comments
 (0)