-
Notifications
You must be signed in to change notification settings - Fork 13.8k
feat: support per-user rate limiting on REST endpoints #41970
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
Open
ricardogarim
wants to merge
4
commits into
develop
Choose a base branch
from
feat/rate-limiter-per-user
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
a724e1a
feat: support per-user rate limiting on REST endpoints
ricardogarim e93e4f0
chore: mark api test skipped on ci
ricardogarim 94d0198
chore: make the REST rate limiter exercisable in tests
ricardogarim 0900a79
chore: skip the rate limiter setting restore when setup failed
ricardogarim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@rocket.chat/meteor': minor | ||
| --- | ||
|
|
||
| Adds support for rate limiting REST endpoints per user rather than per IP address, through the new `per` option of `rateLimiterOptions`, and applies it to `chat.sendMessage` — users connecting from a shared address no longer compete for a single message allowance. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| import { buildRateLimiterInput, buildRateLimiterRule } from './rateLimiterKey'; | ||
|
|
||
| const ROUTE = '/v1/chat.sendMessagepost'; | ||
|
|
||
| const bucketOf = (rule: Record<string, unknown>) => Object.keys(rule).sort(); | ||
|
|
||
| describe('buildRateLimiterRule', () => { | ||
| it('should bucket by address by default', () => { | ||
| expect(bucketOf(buildRateLimiterRule(ROUTE))).toEqual(['IPAddr', 'route']); | ||
| }); | ||
|
|
||
| it("should bucket by address when per is 'ip'", () => { | ||
| expect(bucketOf(buildRateLimiterRule(ROUTE, 'ip'))).toEqual(['IPAddr', 'route']); | ||
| }); | ||
|
|
||
| it("should bucket by user when per is 'user'", () => { | ||
| expect(bucketOf(buildRateLimiterRule(ROUTE, 'user'))).toEqual(['route', 'userId']); | ||
| }); | ||
|
|
||
| it('should carry the route so each endpoint counts separately', () => { | ||
| expect(buildRateLimiterRule(ROUTE, 'user')).toMatchObject({ route: ROUTE }); | ||
| expect(buildRateLimiterRule(ROUTE, 'ip')).toMatchObject({ route: ROUTE }); | ||
| }); | ||
|
|
||
| it('should match a subject by returning it, so the package treats the rule as applicable', () => { | ||
| const rule = buildRateLimiterRule(ROUTE, 'user') as { userId: (input: string) => unknown }; | ||
|
|
||
| expect(rule.userId('alice')).toBe('alice'); | ||
| }); | ||
| }); | ||
|
|
||
| describe('buildRateLimiterInput', () => { | ||
| it('should carry both subjects so either rule shape matches it', () => { | ||
| expect(buildRateLimiterInput({ route: ROUTE, IPAddr: '1.2.3.4', userId: 'alice' })).toEqual({ | ||
| IPAddr: '1.2.3.4', | ||
| userId: 'alice', | ||
| route: ROUTE, | ||
| }); | ||
| }); | ||
|
|
||
| it('should fall back to the address as the user subject when unauthenticated', () => { | ||
| expect(buildRateLimiterInput({ route: ROUTE, IPAddr: '1.2.3.4' })).toEqual({ | ||
| IPAddr: '1.2.3.4', | ||
| userId: 'ip:1.2.3.4', | ||
| route: ROUTE, | ||
| }); | ||
| }); | ||
|
|
||
| it('should never produce a falsy subject', () => { | ||
| const anonymous = buildRateLimiterInput({ route: ROUTE, IPAddr: '1.2.3.4', userId: '' }); | ||
|
|
||
| expect(anonymous.userId).toBe('ip:1.2.3.4'); | ||
| expect(anonymous.IPAddr).toBe('1.2.3.4'); | ||
| }); | ||
|
|
||
| it('should keep unauthenticated subjects apart per address', () => { | ||
| const first = buildRateLimiterInput({ route: ROUTE, IPAddr: '1.2.3.4' }); | ||
| const second = buildRateLimiterInput({ route: ROUTE, IPAddr: '5.6.7.8' }); | ||
|
|
||
| expect(first.userId).not.toBe(second.userId); | ||
| }); | ||
|
|
||
| it('should keep the user subject stable across addresses', () => { | ||
| const home = buildRateLimiterInput({ route: ROUTE, IPAddr: '1.2.3.4', userId: 'alice' }); | ||
| const office = buildRateLimiterInput({ route: ROUTE, IPAddr: '5.6.7.8', userId: 'alice' }); | ||
|
|
||
| expect(home.userId).toBe(office.userId); | ||
| }); | ||
|
|
||
| it('should keep users on a shared address apart', () => { | ||
| const alice = buildRateLimiterInput({ route: ROUTE, IPAddr: '1.2.3.4', userId: 'alice' }); | ||
| const bob = buildRateLimiterInput({ route: ROUTE, IPAddr: '1.2.3.4', userId: 'bob' }); | ||
|
|
||
| expect(alice.userId).not.toBe(bob.userId); | ||
| expect(alice.IPAddr).toBe(bob.IPAddr); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import type { RateLimiterOptionsToCheck, RateLimiterRule } from 'meteor/rate-limit'; | ||
|
|
||
| import type { RateLimiterSubject } from './definition'; | ||
|
|
||
| export const buildRateLimiterRule = (route: string, per: RateLimiterSubject = 'ip'): RateLimiterRule => | ||
| per === 'user' ? { userId: (input: string) => input, route } : { IPAddr: (input: string) => input, route }; | ||
|
|
||
| export const buildRateLimiterInput = ({ | ||
| route, | ||
| IPAddr, | ||
| userId, | ||
| }: { | ||
| route: string; | ||
| IPAddr: string; | ||
| userId?: string; | ||
| }): RateLimiterOptionsToCheck => ({ | ||
| IPAddr, | ||
| route, | ||
| userId: userId || `ip:${IPAddr}`, | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| import type { Credentials } from '@rocket.chat/api-client'; | ||
| import type { IUser } from '@rocket.chat/core-typings'; | ||
| import { expect } from 'chai'; | ||
| import { after, before, describe, it } from 'mocha'; | ||
|
|
||
| import { api, credentials, request } from '../../data/api-data'; | ||
| import { updateSetting } from '../../data/permissions.helper'; | ||
| import type { TestUser } from '../../data/users.helper'; | ||
| import { createUser, deleteUser, login } from '../../data/users.helper'; | ||
|
|
||
| const PASSWORD = 'rate-limiter-spec'; | ||
|
|
||
| describe('[Rate Limiter]', () => { | ||
| let alice: TestUser<IUser>; | ||
| let bob: TestUser<IUser>; | ||
| let aliceCredentials: Credentials; | ||
| let bobCredentials: Credentials; | ||
|
|
||
| before(async function () { | ||
| [alice, bob] = await Promise.all([ | ||
| createUser({ password: PASSWORD } as Partial<IUser>), | ||
| createUser({ password: PASSWORD } as Partial<IUser>), | ||
| ]); | ||
| [aliceCredentials, bobCredentials] = await Promise.all([login(alice.username, PASSWORD), login(bob.username, PASSWORD)]); | ||
|
|
||
| await updateSetting('API_Enable_Rate_Limiter_Dev', true); | ||
|
|
||
| const probe = await request | ||
| .post(api('chat.sendMessage')) | ||
| .set(aliceCredentials) | ||
| .send({ message: { rid: 'GENERAL', msg: 'probe' } }); | ||
| if (!probe.headers['x-ratelimit-limit']) { | ||
| this.skip(); | ||
| } | ||
| }); | ||
|
|
||
| after(async () => { | ||
| await updateSetting('API_Enable_Rate_Limiter_Dev', false); | ||
| await Promise.all([deleteUser(alice), deleteUser(bob)]); | ||
| }); | ||
|
|
||
| describe('per user', () => { | ||
| const send = (who: Credentials, msg: string) => | ||
| request | ||
| .post(api('chat.sendMessage')) | ||
| .set(who) | ||
| .send({ message: { rid: 'GENERAL', msg } }); | ||
|
|
||
| it('should reject a user past the endpoint allowance', async () => { | ||
| const statuses = await Promise.all([...Array(12)].map((_, i) => send(aliceCredentials, `burst ${i}`).then((res) => res.status))); | ||
|
|
||
| expect(statuses).to.include(200); | ||
| expect(statuses).to.include(429); | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
|
||
| }); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| it('should leave another user on the same address with a full allowance', async () => { | ||
| const res = await send(bobCredentials, 'bob'); | ||
|
|
||
| expect(res.status).to.equal(200); | ||
| expect(res.headers['x-ratelimit-remaining']).to.equal('4'); | ||
| }); | ||
| }); | ||
|
|
||
| describe('bypass', () => { | ||
| it('should not limit a user holding api-bypass-rate-limit', async () => { | ||
| const statuses = await Promise.all( | ||
| [...Array(12)].map((_, i) => | ||
| request | ||
| .post(api('chat.sendMessage')) | ||
| .set(credentials) | ||
| .send({ message: { rid: 'GENERAL', msg: `admin burst ${i}` } }) | ||
| .then((res) => res.status), | ||
| ), | ||
| ); | ||
|
|
||
| expect(statuses).to.deep.equal(Array(12).fill(200)); | ||
| }); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| import type { ISetting } from '@rocket.chat/core-typings'; | ||
| import { after, before } from 'mocha'; | ||
|
|
||
| import { getCredentials } from '../data/api-data'; | ||
| import { getSettingValueById, updateSetting } from '../data/permissions.helper'; | ||
|
|
||
| let rateLimiterInDevWasEnabled: ISetting['value']; | ||
|
|
||
| before(async () => { | ||
| await new Promise<void>((resolve, reject) => getCredentials((err?: Error) => (err ? reject(err) : resolve()))); | ||
| rateLimiterInDevWasEnabled = await getSettingValueById('API_Enable_Rate_Limiter_Dev'); | ||
| await updateSetting('API_Enable_Rate_Limiter_Dev', false); | ||
| }); | ||
|
|
||
| after(async () => { | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
|
||
| if (rateLimiterInDevWasEnabled !== undefined) { | ||
| await updateSetting('API_Enable_Rate_Limiter_Dev', rateLimiterInDevWasEnabled); | ||
| } | ||
| }); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.