feat: rate limiter (#4011)

This commit is contained in:
DarkSky
2023-08-31 20:29:25 +08:00
committed by GitHub
parent 8e48255ef8
commit 4ef1425299
15 changed files with 184 additions and 12 deletions

View File

@@ -11,6 +11,7 @@ import { MetricsModule } from '../metrics';
import { AuthModule } from '../modules/auth';
import { AuthService } from '../modules/auth/service';
import { PrismaModule } from '../prisma';
import { RateLimiterModule } from '../throttler';
let auth: AuthService;
let module: TestingModule;
@@ -36,6 +37,7 @@ beforeEach(async () => {
GqlModule,
AuthModule,
MetricsModule,
RateLimiterModule,
],
}).compile();
auth = module.get(AuthService);

View File

@@ -1,4 +1,4 @@
import { ok } from 'node:assert';
import { ok, rejects } from 'node:assert';
import { afterEach, beforeEach, describe, it } from 'node:test';
import type { INestApplication } from '@nestjs/common';
@@ -71,7 +71,6 @@ describe('User Module', () => {
`,
})
.expect(200);
const current = await currentUser(app, user.token.token);
ok(current == null);
rejects(currentUser(app, user.token.token));
});
});

View File

@@ -43,13 +43,14 @@ async function currentUser(app: INestApplication, token: string) {
query: `
query {
currentUser {
id, name, email, emailVerified, avatarUrl, createdAt, hasPassword
id, name, email, emailVerified, avatarUrl, createdAt, hasPassword,
token { token }
}
}
`,
})
.expect(200);
return res.body?.data?.currentUser;
return res.body.data.currentUser;
}
async function createWorkspace(
@@ -440,7 +441,7 @@ async function getInviteInfo(
`,
})
.expect(200);
return res.body.data.workspace;
return res.body.data.getInviteInfo;
}
export {

View File

@@ -12,6 +12,7 @@ import { AppModule } from '../app';
import {
acceptInvite,
createWorkspace,
currentUser,
getPublicWorkspace,
getWorkspaceSharedPages,
inviteUser,
@@ -61,6 +62,18 @@ describe('Workspace Module', () => {
ok(user.email === 'u1@affine.pro', 'user.email is not valid');
});
it('should be throttled at call signUp', async () => {
let token = '';
for (let i = 0; i < 10; i++) {
token = (await signUp(app, `u${i}`, `u${i}@affine.pro`, `${i}`)).token
.token;
// throttles are applied to each endpoint separately
await currentUser(app, token);
}
await rejects(signUp(app, 'u11', 'u11@affine.pro', '11'));
await rejects(currentUser(app, token));
});
it('should create a workspace', async () => {
const user = await signUp(app, 'u1', 'u1@affine.pro', '1');