Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Query Params Parsing #3012

Merged
merged 2 commits into from
Jan 6, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions src/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,47 @@ const createServer = (): Express => {
// X-Forwarded-For header values (cf. https://expressjs.com/en/guide/behind-proxies.html)
// This is necessary for accurately logging the IP address in rate limiter calls.
server.set('trust proxy', true);

/**
* Essentially express query parameter parsing will convert a value of a query parameter
* into an array if it sees multiple keys for that parameter.
* e.g.
*
* `?foo=bar&foo=baz&hello=world`
*
* would get parsed into
*
* ```javascript
* {
* foo: ['bar', 'baz'],
* hello: 'world'
* }
* ```
*
* In Gateway we don’t use duplicate query parameters and they should never exist.
*
* By default, express will use https://www.npmjs.com/package/qs to parse query params,
* which is more powerful than what we need (called 'extended' in the express docs, see
* https://expressjs.com/en/api.html#app.settings.table).
*
* Even the "simple" mode in express uses node's querystring api doesn't work.
* This will also parse duplicate query params into an array, which is not what we want,
* as shown by the example in:
* https://nodejs.org/api/querystring.html#querystringparsestr-sep-eq-options
*
* However, we can use a custom query parser to use the native `URLSearchParams` API,
* which will parse duplicate query params into the last value, which is exactly what we want.
* So that `?foo=bar&foo=baz&hello=world` => `{ foo: 'baz', hello: 'world' }`.
*
* This can be tested in a node repl or browser console by running:
* ```js
* Object.fromEntries(new URLSearchParams(`foo=bar&foo=baz&hello=world`).entries())
* ```
* which returns the expected result.
*/
server.set('query parser', (str: string) =>
Object.fromEntries(new URLSearchParams(str).entries()),
);
applyMiddleware(server);
return server;
};
Expand Down
Loading