Skip to content
Merged
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions .changeset/eight-llamas-mate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@envelop/rate-limiter': patch
---

Fix rate limiting being wrongly applied to all fields with a default configuration.
5 changes: 3 additions & 2 deletions packages/plugins/rate-limiter/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,10 @@ export const useRateLimiter = (options: RateLimiterPluginOptions): Plugin<RateLi
);
}

const rateLimitConfig = { ...(rateLimitDirective ?? fieldConfig) };
const baseConfig = rateLimitDirective ?? fieldConfig;

if (rateLimitConfig) {
if (baseConfig) {
const rateLimitConfig = { ...baseConfig };
rateLimitConfig.max = rateLimitConfig.max && Number(rateLimitConfig.max);

if (fieldConfig?.identifyFn) {
Expand Down
50 changes: 50 additions & 0 deletions packages/plugins/rate-limiter/tests/use-rate-limiter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -448,4 +448,54 @@ describe('Rate-Limiter', () => {
),
).toThrow(`Config error: field 'Query.foo' has both a configuration and a directive`);
});
it('should not rate limit fields that are not in configByField', async () => {
const schema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
type Query {
limitedField: String
unlimitedField: String
}
`,
resolvers: {
Query: {
limitedField: () => 'limited',
unlimitedField: () => 'unlimited',
},
},
});

const testkit = createTestkit(
[
useRateLimiter({
identifyFn: (ctx: any) => ctx.ip,
configByField: [
{
type: 'Query',
field: 'limitedField',
max: 1,
window: '60s',
},
],
}),
],
schema,
);

const context = { ip: '127.0.0.1' };

const result1 = await testkit.execute(`{ limitedField }`, {}, context);
expect(result1).toEqual({ data: { limitedField: 'limited' } });

const result2 = await testkit.execute(`{ limitedField }`, {}, context);
assertSingleExecutionValue(result2);
expect(result2.errors?.[0]?.message).toBe("You are trying to access 'limitedField' too often");

// unlimitedField should not be rate limited at all, so we should be able to call it many times
for (let i = 0; i < 10; i++) {
const result = await testkit.execute(`{ unlimitedField }`, {}, context);
assertSingleExecutionValue(result);
expect(result).toEqual({ data: { unlimitedField: 'unlimited' } });
expect(result.errors).toBeUndefined();
}
});
});