Skip to content

Commit

Permalink
fix: Rate limiter may reject requests that contain a session token (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
dblythy authored Jan 25, 2023
1 parent 8f7a8f4 commit c114dc8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
21 changes: 21 additions & 0 deletions spec/RateLimit.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,27 @@ describe('rate limit', () => {
);
});

it('can limit cloud functions with user session token', async () => {
await Parse.User.signUp('myUser', 'password');
Parse.Cloud.define('test', () => 'Abc');
await reconfigureServer({
rateLimit: [
{
requestPath: '/functions/*',
requestTimeWindow: 10000,
requestCount: 1,
errorResponseMessage: 'Too many requests',
includeInternalRequests: true,
},
],
});
const response1 = await Parse.Cloud.run('test');
expect(response1).toBe('Abc');
await expectAsync(Parse.Cloud.run('test')).toBeRejectedWith(
new Parse.Error(Parse.Error.CONNECTION_FAILED, 'Too many requests')
);
});

it('can add global limit', async () => {
Parse.Cloud.define('test', () => 'Abc');
await reconfigureServer({
Expand Down
17 changes: 13 additions & 4 deletions src/middlewares.js
Original file line number Diff line number Diff line change
Expand Up @@ -276,15 +276,21 @@ const handleRateLimit = async (req, res, next) => {
if (pathExp.test(req.url)) {
await limit.handler(req, res, err => {
if (err) {
throw err;
if (err.code === Parse.Error.CONNECTION_FAILED) {
throw err;
}
req.config.loggerController.error(
'An unknown error occured when attempting to apply the rate limiter: ',
err
);
}
});
}
})
);
} catch (error) {
res.status(429);
res.json({ code: Parse.Error.CONNECTION_FAILED, error });
res.json({ code: Parse.Error.CONNECTION_FAILED, error: error.message });
return;
}
next();
Expand Down Expand Up @@ -477,7 +483,10 @@ export const addRateLimit = (route, config) => {
max: route.requestCount,
message: route.errorResponseMessage || RateLimitOptions.errorResponseMessage.default,
handler: (request, response, next, options) => {
throw options.message;
throw {
code: Parse.Error.CONNECTION_FAILED,
message: options.message,
};
},
skip: request => {
if (request.ip === '127.0.0.1' && !route.includeInternalRequests) {
Expand All @@ -498,7 +507,7 @@ export const addRateLimit = (route, config) => {
}
}
}
return request.auth.isMaster;
return request.auth?.isMaster;
},
keyGenerator: request => {
return request.config.ip;
Expand Down

0 comments on commit c114dc8

Please sign in to comment.