* chore: Upgrade prisma to 6.7.0 * Build fixes * type fixes Signed-off-by: Omar López <zomars@me.com> * Update schema.prisma * Patching * Revert "Update schema.prisma" This reverts commit 47d8618bf89ef4d007b30084df766f17281e21a1. * Revert "Patching" This reverts commit a1d2e3040e71690a44d4324db95d73b4d68c6adb. * Revert schema changes Signed-off-by: Omar López <zomars@me.com> * WIP Signed-off-by: Omar López <zomars@me.com> * Update getPublicEvent.ts * Update imports Signed-off-by: Omar López <zomars@me.com> * Update gitignore Signed-off-by: Omar López <zomars@me.com> * update remaining imports Signed-off-by: Omar López <zomars@me.com> * Delete .cursor/config.json * Discard changes to packages/features/eventtypes/lib/getPublicEvent.ts * Update _get.ts * Update user.ts * Update .gitignore * update * Update WorkflowStepContainer.tsx * Update next-auth-custom-adapter.ts * Update getPublicEvent.ts * Update workflow.ts * Update next-auth-custom-adapter.ts * Update next-auth-options.ts * Update bookingScenario.ts * fix missing imports * upgrades prismock Signed-off-by: Omar López <zomars@me.com> * patches prismock Signed-off-by: Omar López <zomars@me.com> * Update reschedule.test.ts * Update prisma.ts * patch prismock Signed-off-by: Omar López <zomars@me.com> * fix enums imports Signed-off-by: Omar López <zomars@me.com> * Revert "Update prisma.ts" This reverts commit 64edcf8db54171ff4456c209d563b5d431d99619. * Revert "patch prismock" This reverts commit e95819113dc9d88e7130947aa120cd42710977c8. * fix patch * Fix test that overrun the boundary, it shouldn't test too much * Move prisma import to changeSMSLockState * Bring back broken test without illegal imports * Merge with main and fix filter hosts by same round robin host * Fixed buildDryRunBooking fn tests * Fix and move ooo create or update handler test * Fix packages/features/eventtypes/lib/isCurrentlyAvailable.test.ts * Fix packages/trpc/server/routers/viewer/organizations/listMembers.handler.test.ts * Mock @calcom/prisma * Fix: verify-email.test.ts * fix: Moved WebhookService test and fixed default import mock * Fix: Added missing prisma mock, handleNewBooking uses that of course * We're not testing createContext here * fix: Prisma mock fix for listMembers.test.ts * More fixes to broken testcases * Forgot to remove borked test * Prevent the need to mock a lot of dependencies by moving out buildBaseWhereCondition to its own file * Temporarily skip getCalendarEvents, needs a rewrite * Fix: turns out you can access protected in testcases * fix further mocks * Added packages/features/insights/server/buildBaseWhereCondition.ts, types * Always great to have a mock and then not use it * And one less again. * fix: confirm.handler.test, didn't mock prisma * fix: Address minor nit by @eunjae & fix ImpersonationProvider test * Updated isPrismaAvailableCheck that doesn't crash on import * fix: Get Prisma directly from the client, it usually involves the Validator and does not need 'local' inclusion * Add zod-prisma-types without the generator enabled (commented out) * Uncomment and see what happens * Change method of import as imports did not work in Input Schemas * Remove custom 'zod' booking model, it does not belong with Prisma * Fix all other global Model imports * Rewrite most schema includes AND remove barrel file * Add bookingCreateBodySchema to features/bookings * Flurry of type fixes for compatibility with new zod gen * Refactor out the custom prisma type createEventTypeInput * Work around nullable eventTypeLocations * HandlePayment type fix * More fixes, final fix remaining is CompleteEventType * Should fix a bunch more booking related type errors * Missed one * Some props missing from BookingCreateBodySchema * Fix location type in handleChildrenEventTypes * Little bit hacky imo but it works * Final type error \o/ * Forgot to include Prisma * Do not include zod-utils in booker/types * Oops, was already including Booker/types * Fix membership type, also disallow updating createdAt/updatedAt, make part of patch/post * Fix api v1 type errors * Fix EventTypeDescription typings * Remove getParserWithGeneric, use userBodySchema with UserSchema * use centralized timeZoneSchema * Implement feedback by @zomars * Couple of WIP pushes * Fix tests * Type fixes in `handleChildrenEventTypes` test * Try and parse metadata before use * Change zod-prisma-types configuration for optimal performance * Fix prisma validator error in `prisma/selects/credential` * Disable seperate relations model, hits a bug * Import absolute - this makes rollup work in @platform/libraries * Attempt at removing resolutions override * Refactor using `Prisma.validator` to `satisfies` * Build atoms using @calcom/prisma/client * Build atoms using @calcom/prisma/client * fixes * Update eventTypeSelect.ts * Adjust `eventTypeMetaDataSchemaWithUntypedApps` from `unknown` to `record(any)` * `EventTypeDescription` rely on `descriptionAsSafeHTML` instead of `description` * Add `seatsPerTimeSlot` to event type public select * Fix typing in `users-public-view` getServerSide props * Add missing `schedulingType` to prop * chore: bump platform libraries * Function return type is illegal, not sure how this passed eslint (#21567) * Merged with main * Update updateTokenObject.ts * Update handleResponse.ts * Update index.ts * Update handleChildrenEventTypes.ts * Update booking-idempotency-key.ts * Update WebhookService.test.ts * Update events.test.ts * Update queued-response.test.ts * Update events.test.ts * Update getRoutedUrl.test.ts * fix: type checks Signed-off-by: Omar López <zomars@me.com> * fixes Signed-off-by: Omar López <zomars@me.com> * chore: bump platform libraries * Update yarn.lock * more fixes Signed-off-by: Omar López <zomars@me.com> * fixes Signed-off-by: Omar López <zomars@me.com> * biuld fixes * chore: bump platform libraries * Update conferencing.repository.ts * Update conferencing.repository.ts * Update getCalendarsEvents.test.ts * Update vite.config.js * chore: bump platform libraries * Update users.ts * Discard changes to docs/api-reference/v2/openapi.json * Update vite.config.ts * updated platform libraries * Update get.handler.test.ts * Update get.handler.test.ts * Update schema.prisma * Discard changes to docs/api-reference/v2/openapi.json * Update next-auth-custom-adapter.ts * Update team.ts * Flurry of type fixes * Fix majority of insight related type errors * Type fixes for unlink of account * Make user nullable again * Fixed a bunch of unit tests and one type error * Attempted mock fix * Attempted fix for Attribute type * Ensure default import becomes prisma, but not direct usage * Import default as prisma in prisma.module * Add attributeOption to attribute type * Fix calcom/prisma mock * Refactor Prisma client imports to @calcom/prisma/client Updated all imports from '@prisma/client' to '@calcom/prisma/client' across tests and repository files for consistency and to use the correct Prisma client package. This change improves maintainability and ensures the correct client is referenced throughout the codebase. * Undo removal of max-warnings=0 to get main to merge * Remove unit tests for e2e fixtures, provide new prisma mock * Mock @calcom/prisma in event manager * Mock @calcom/prisma in event manager * Add correct format even with --no-verify * Mock prisma in CalendarManager * Add mock for permission-check.service * Better injection in PrismaApiKeyRepository imports * More mock fixes :) * Fix listMembers.handler.test * Fix User import * Appropriately adjust all types to be imported as types, there were a lot of types imported as normal deps * Why was this a thing? * Strictly speaking; Not using prismock anymore * Ditched patch file for prismock * Fix output.service.ts platform type imports, need concrete for plainToClass * Better typing and tests for unlinkConnectedAccount.handler * Small type fix * Disable calendar cache tests as they are dependent on prismock * chore: bump platform lib * getRoutedUrl test remove of unused import * Extract select to external const on getEventTypesFromDB * Direct select of userSelect from selects/user * fix type error from merging 23653 * Fixed integration tests by removing hardcoded values that were possible due to mocking, but as its now directly hitting the db no longer * fix: vite config atoms prisma client type location * revert: example app prisma client * revert: example app prisma client * bump platform libs * fix: use class instead of type for DI of PlatformBookingsService * update platform libs * remove unused variable * chore: generate prisma client for api v2 * fix: api v2 e2e * fix: atoms e2e * fix: atoms e2e * fix: atoms e2e * fix: api v2 e2e * fix: tsconfig apiv2 enums * publish libraries * Simplify check for existence teamId --------- Signed-off-by: Omar López <zomars@me.com> Co-authored-by: Alex van Andel <me@alexvanandel.com> Co-authored-by: Joe Au-Yeung <j.auyeung419@gmail.com> Co-authored-by: supalarry <laurisskraucis@gmail.com> Co-authored-by: cal.com <morgan@cal.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> Co-authored-by: Benny Joo <sldisek783@gmail.com>
399 lines
18 KiB
TypeScript
399 lines
18 KiB
TypeScript
import { AppModule } from "@/app.module";
|
|
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
|
|
import { CustomThrottlerGuard } from "@/lib/throttler-guard";
|
|
import { PrismaModule } from "@/modules/prisma/prisma.module";
|
|
import { TokensModule } from "@/modules/tokens/tokens.module";
|
|
import { UsersModule } from "@/modules/users/users.module";
|
|
import { INestApplication } from "@nestjs/common";
|
|
import { TestingModule } from "@nestjs/testing";
|
|
import { Test } from "@nestjs/testing";
|
|
import * as request from "supertest";
|
|
import { ApiKeysRepositoryFixture } from "test/fixtures/repository/api-keys.repository.fixture";
|
|
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
|
|
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";
|
|
import { OrganizationRepositoryFixture } from "test/fixtures/repository/organization.repository.fixture";
|
|
import { ProfileRepositoryFixture } from "test/fixtures/repository/profiles.repository.fixture";
|
|
import { RateLimitRepositoryFixture } from "test/fixtures/repository/rate-limit.repository.fixture";
|
|
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
|
|
import { randomString } from "test/utils/randomString";
|
|
|
|
import { X_CAL_CLIENT_ID, X_CAL_SECRET_KEY } from "@calcom/platform-constants";
|
|
import type { User, PlatformOAuthClient, Team, RateLimit } from "@calcom/prisma/client";
|
|
|
|
describe("AppController", () => {
|
|
describe("Rate limiting", () => {
|
|
let app: INestApplication;
|
|
let userRepositoryFixture: UserRepositoryFixture;
|
|
let apiKeysRepositoryFixture: ApiKeysRepositoryFixture;
|
|
let rateLimitRepositoryFixture: RateLimitRepositoryFixture;
|
|
const userEmail = `app-rate-limits-user-${randomString()}@api.com`;
|
|
let user: User;
|
|
|
|
let organization: Team;
|
|
let oAuthClient: PlatformOAuthClient;
|
|
let organizationsRepositoryFixture: OrganizationRepositoryFixture;
|
|
let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;
|
|
let profilesRepositoryFixture: ProfileRepositoryFixture;
|
|
let membershipRepositoryFixture: MembershipRepositoryFixture;
|
|
|
|
let apiKeyString: string;
|
|
|
|
let rateLimit: RateLimit;
|
|
let apiKeyStringWithRateLimit: string;
|
|
|
|
let apiKeyStringWithMultipleLimits: string;
|
|
let firstRateLimitWithMultipleLimits: RateLimit;
|
|
let secondRateLimitWithMultipleLimits: RateLimit;
|
|
|
|
const mockDefaultLimit = 5;
|
|
const mockDefaultTtl = 2500;
|
|
const mockDefaultBlockDuration = 5000;
|
|
|
|
beforeEach(async () => {
|
|
const moduleRef: TestingModule = await Test.createTestingModule({
|
|
imports: [AppModule, PrismaModule, UsersModule, TokensModule, SchedulesModule_2024_04_15],
|
|
}).compile();
|
|
|
|
jest.spyOn(CustomThrottlerGuard.prototype, "getDefaultLimit").mockReturnValue(mockDefaultLimit);
|
|
jest.spyOn(CustomThrottlerGuard.prototype, "getDefaultTtl").mockReturnValue(mockDefaultTtl);
|
|
jest
|
|
.spyOn(CustomThrottlerGuard.prototype, "getDefaultBlockDuration")
|
|
.mockReturnValue(mockDefaultBlockDuration);
|
|
|
|
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
|
|
user = await userRepositoryFixture.create({
|
|
email: userEmail,
|
|
username: userEmail,
|
|
});
|
|
|
|
apiKeysRepositoryFixture = new ApiKeysRepositoryFixture(moduleRef);
|
|
const { keyString } = await apiKeysRepositoryFixture.createApiKey(user.id, null);
|
|
apiKeyString = `cal_test_${keyString}`;
|
|
|
|
rateLimitRepositoryFixture = new RateLimitRepositoryFixture(moduleRef);
|
|
const { apiKey, keyString: keyStringWithRateLimit } = await apiKeysRepositoryFixture.createApiKey(
|
|
user.id,
|
|
null
|
|
);
|
|
apiKeyStringWithRateLimit = `cal_test_${keyStringWithRateLimit}`;
|
|
rateLimit = await rateLimitRepositoryFixture.createRateLimit("long", apiKey.id, 2000, 3, 4000);
|
|
|
|
const { apiKey: apiKeyWithMultipleLimits, keyString: keyStringWithMultipleLimits } =
|
|
await apiKeysRepositoryFixture.createApiKey(user.id, null);
|
|
apiKeyStringWithMultipleLimits = `cal_test_${keyStringWithMultipleLimits}`;
|
|
firstRateLimitWithMultipleLimits = await rateLimitRepositoryFixture.createRateLimit(
|
|
"short",
|
|
apiKeyWithMultipleLimits.id,
|
|
1000,
|
|
2,
|
|
2000
|
|
);
|
|
secondRateLimitWithMultipleLimits = await rateLimitRepositoryFixture.createRateLimit(
|
|
"long",
|
|
apiKeyWithMultipleLimits.id,
|
|
2000,
|
|
3,
|
|
4000
|
|
);
|
|
|
|
organizationsRepositoryFixture = new OrganizationRepositoryFixture(moduleRef);
|
|
organization = await organizationsRepositoryFixture.create({
|
|
name: `app-rate-limits-organization-${randomString()}`,
|
|
});
|
|
oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
|
|
oAuthClient = await createOAuthClient(organization.id);
|
|
profilesRepositoryFixture = new ProfileRepositoryFixture(moduleRef);
|
|
await profilesRepositoryFixture.create({
|
|
uid: "asd-asd",
|
|
username: userEmail,
|
|
user: { connect: { id: user.id } },
|
|
organization: { connect: { id: organization.id } },
|
|
});
|
|
|
|
membershipRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
|
|
await membershipRepositoryFixture.create({
|
|
user: { connect: { id: user.id } },
|
|
team: { connect: { id: organization.id } },
|
|
role: "OWNER",
|
|
accepted: true,
|
|
});
|
|
|
|
app = moduleRef.createNestApplication();
|
|
await app.init();
|
|
});
|
|
|
|
async function createOAuthClient(organizationId: number) {
|
|
const data = {
|
|
logo: "logo-url",
|
|
name: "name",
|
|
redirectUris: ["http://localhost:5555"],
|
|
permissions: 1023,
|
|
};
|
|
const secret = "secret";
|
|
|
|
const client = await oauthClientRepositoryFixture.create(organizationId, data, secret);
|
|
return client;
|
|
}
|
|
|
|
it(
|
|
"api key with default rate limit - should enforce rate limits and reset after block duration",
|
|
async () => {
|
|
const limit = mockDefaultLimit;
|
|
const blockDuration = mockDefaultBlockDuration;
|
|
|
|
for (let i = 1; i <= limit; i++) {
|
|
const response = await request(app.getHttpServer())
|
|
.get("/v2/me")
|
|
.set({ Authorization: `Bearer ${apiKeyString}` })
|
|
.expect(200);
|
|
|
|
expect(response.headers["x-ratelimit-limit-default"]).toBe(limit.toString());
|
|
expect(response.headers["x-ratelimit-remaining-default"]).toBe((limit - i).toString());
|
|
expect(Number(response.headers["x-ratelimit-reset-default"])).toBeGreaterThan(0);
|
|
}
|
|
|
|
const blockedResponse = await request(app.getHttpServer())
|
|
.get("/v2/me")
|
|
.set("Authorization", `Bearer ${apiKeyString}`)
|
|
.expect(429);
|
|
|
|
expect(blockedResponse.headers["x-ratelimit-limit-default"]).toBe(limit.toString());
|
|
expect(blockedResponse.headers["x-ratelimit-remaining-default"]).toBe("0");
|
|
expect(Number(blockedResponse.headers["x-ratelimit-reset-default"])).toBeGreaterThanOrEqual(
|
|
blockDuration / 1000
|
|
);
|
|
|
|
await new Promise((resolve) => setTimeout(resolve, blockDuration));
|
|
|
|
const afterBlockResponse = await request(app.getHttpServer())
|
|
.get("/v2/me")
|
|
.set("Authorization", `Bearer ${apiKeyString}`)
|
|
.expect(200);
|
|
|
|
expect(afterBlockResponse.headers["x-ratelimit-limit-default"]).toBe(limit.toString());
|
|
expect(afterBlockResponse.headers["x-ratelimit-remaining-default"]).toBe((limit - 1).toString());
|
|
expect(Number(afterBlockResponse.headers["x-ratelimit-reset-default"])).toBeGreaterThan(0);
|
|
},
|
|
15 * 1000
|
|
);
|
|
|
|
it(
|
|
"api key with custom rate limit - should enforce rate limits and reset after block duration",
|
|
async () => {
|
|
const limit = rateLimit.limit;
|
|
const blockDuration = rateLimit.blockDuration;
|
|
const name = rateLimit.name;
|
|
|
|
for (let i = 1; i <= limit; i++) {
|
|
const response = await request(app.getHttpServer())
|
|
.get("/v2/me")
|
|
.set({ Authorization: `Bearer ${apiKeyStringWithRateLimit}` })
|
|
.expect(200);
|
|
|
|
expect(response.headers[`x-ratelimit-limit-${name}`]).toBe(limit.toString());
|
|
expect(response.headers[`x-ratelimit-remaining-${name}`]).toBe((limit - i).toString());
|
|
expect(Number(response.headers[`x-ratelimit-reset-${name}`])).toBeGreaterThan(0);
|
|
}
|
|
|
|
const blockedResponse = await request(app.getHttpServer())
|
|
.get("/v2/me")
|
|
.set("Authorization", `Bearer ${apiKeyStringWithRateLimit}`)
|
|
.expect(429);
|
|
|
|
expect(blockedResponse.headers[`x-ratelimit-limit-${name}`]).toBe(limit.toString());
|
|
expect(blockedResponse.headers[`x-ratelimit-remaining-${name}`]).toBe("0");
|
|
expect(Number(blockedResponse.headers[`x-ratelimit-reset-${name}`])).toBeGreaterThanOrEqual(
|
|
blockDuration / 1000
|
|
);
|
|
|
|
await new Promise((resolve) => setTimeout(resolve, blockDuration));
|
|
|
|
const afterBlockResponse = await request(app.getHttpServer())
|
|
.get("/v2/me")
|
|
.set("Authorization", `Bearer ${apiKeyStringWithRateLimit}`)
|
|
.expect(200);
|
|
|
|
expect(afterBlockResponse.headers[`x-ratelimit-limit-${name}`]).toBe(limit.toString());
|
|
expect(afterBlockResponse.headers[`x-ratelimit-remaining-${name}`]).toBe((limit - 1).toString());
|
|
expect(Number(afterBlockResponse.headers[`x-ratelimit-reset-${name}`])).toBeGreaterThan(0);
|
|
},
|
|
15 * 1000
|
|
);
|
|
|
|
it(
|
|
"api key with multiple rate limits - should enforce both short and long rate limits",
|
|
async () => {
|
|
const shortLimit = firstRateLimitWithMultipleLimits.limit;
|
|
const longLimit = secondRateLimitWithMultipleLimits.limit;
|
|
const shortName = firstRateLimitWithMultipleLimits.name;
|
|
const longName = secondRateLimitWithMultipleLimits.name;
|
|
const shortBlock = firstRateLimitWithMultipleLimits.blockDuration;
|
|
const longBlock = secondRateLimitWithMultipleLimits.blockDuration;
|
|
|
|
let requestsMade = 0;
|
|
// note(Lauris): exhaust short limit to have remaining 0 for it
|
|
for (let i = 1; i <= shortLimit; i++) {
|
|
const response = await request(app.getHttpServer())
|
|
.get("/v2/me")
|
|
.set({ Authorization: `Bearer ${apiKeyStringWithMultipleLimits}` })
|
|
.expect(200);
|
|
|
|
requestsMade++;
|
|
|
|
expect(response.headers[`x-ratelimit-limit-${shortName}`]).toBe(shortLimit.toString());
|
|
expect(response.headers[`x-ratelimit-remaining-${shortName}`]).toBe((shortLimit - i).toString());
|
|
expect(Number(response.headers[`x-ratelimit-reset-${shortName}`])).toBeGreaterThan(0);
|
|
|
|
expect(response.headers[`x-ratelimit-limit-${longName}`]).toBe(longLimit.toString());
|
|
expect(response.headers[`x-ratelimit-remaining-${longName}`]).toBe((longLimit - i).toString());
|
|
expect(Number(response.headers[`x-ratelimit-reset-${longName}`])).toBeGreaterThan(0);
|
|
}
|
|
|
|
// note(Lauris): short limit exhausted, now exhaust long limit to have remaining 0 for it
|
|
for (let i = requestsMade; i < longLimit; i++) {
|
|
const responseAfterShortLimit = await request(app.getHttpServer())
|
|
.get("/v2/me")
|
|
.set({ Authorization: `Bearer ${apiKeyStringWithMultipleLimits}` })
|
|
.expect(200);
|
|
|
|
requestsMade++;
|
|
|
|
expect(responseAfterShortLimit.headers[`x-ratelimit-limit-${shortName}`]).toBe(
|
|
shortLimit.toString()
|
|
);
|
|
expect(responseAfterShortLimit.headers[`x-ratelimit-remaining-${shortName}`]).toBe("0");
|
|
expect(Number(responseAfterShortLimit.headers[`x-ratelimit-reset-${shortName}`])).toBeGreaterThan(
|
|
0
|
|
);
|
|
|
|
expect(responseAfterShortLimit.headers[`x-ratelimit-limit-${longName}`]).toBe(longLimit.toString());
|
|
expect(responseAfterShortLimit.headers[`x-ratelimit-remaining-${longName}`]).toBe(
|
|
(longLimit - requestsMade).toString()
|
|
);
|
|
expect(Number(responseAfterShortLimit.headers[`x-ratelimit-reset-${longName}`])).toBeGreaterThan(0);
|
|
}
|
|
|
|
// note(Lauris): both have remaining 0 so now exceed both
|
|
const blockedResponseLong = await request(app.getHttpServer())
|
|
.get("/v2/me")
|
|
.set({ Authorization: `Bearer ${apiKeyStringWithMultipleLimits}` })
|
|
.expect(429);
|
|
|
|
expect(blockedResponseLong.headers[`x-ratelimit-limit-${shortName}`]).toBe(shortLimit.toString());
|
|
expect(blockedResponseLong.headers[`x-ratelimit-remaining-${shortName}`]).toBe("0");
|
|
expect(Number(blockedResponseLong.headers[`x-ratelimit-reset-${shortName}`])).toBeGreaterThanOrEqual(
|
|
firstRateLimitWithMultipleLimits.blockDuration / 1000
|
|
);
|
|
|
|
expect(blockedResponseLong.headers[`x-ratelimit-limit-${longName}`]).toBe(longLimit.toString());
|
|
expect(blockedResponseLong.headers[`x-ratelimit-remaining-${longName}`]).toBe("0");
|
|
expect(Number(blockedResponseLong.headers[`x-ratelimit-reset-${longName}`])).toBeGreaterThanOrEqual(
|
|
secondRateLimitWithMultipleLimits.blockDuration / 1000
|
|
);
|
|
|
|
// note(Lauris): wait for short limit to reset
|
|
await new Promise((resolve) => setTimeout(resolve, shortBlock));
|
|
const responseAfterShortLimitReload = await request(app.getHttpServer())
|
|
.get("/v2/me")
|
|
.set({ Authorization: `Bearer ${apiKeyStringWithMultipleLimits}` })
|
|
.expect(200);
|
|
expect(responseAfterShortLimitReload.headers[`x-ratelimit-limit-${shortName}`]).toBe(
|
|
shortLimit.toString()
|
|
);
|
|
expect(responseAfterShortLimitReload.headers[`x-ratelimit-remaining-${shortName}`]).toBe(
|
|
(shortLimit - 1).toString()
|
|
);
|
|
expect(
|
|
Number(responseAfterShortLimitReload.headers[`x-ratelimit-reset-${shortName}`])
|
|
).toBeGreaterThan(0);
|
|
expect(responseAfterShortLimitReload.headers[`x-ratelimit-limit-${longName}`]).toBe(
|
|
longLimit.toString()
|
|
);
|
|
expect(responseAfterShortLimitReload.headers[`x-ratelimit-remaining-${longName}`]).toBe(
|
|
(longLimit - requestsMade).toString()
|
|
);
|
|
expect(
|
|
Number(responseAfterShortLimitReload.headers[`x-ratelimit-reset-${longName}`])
|
|
).toBeGreaterThan(0);
|
|
|
|
// note(Lauris): wait for long limit to reset
|
|
await new Promise((resolve) => setTimeout(resolve, longBlock));
|
|
const responseAfterLongLimitReload = await request(app.getHttpServer())
|
|
.get("/v2/me")
|
|
.set({ Authorization: `Bearer ${apiKeyStringWithMultipleLimits}` })
|
|
.expect(200);
|
|
expect(responseAfterLongLimitReload.headers[`x-ratelimit-limit-${shortName}`]).toBe(
|
|
shortLimit.toString()
|
|
);
|
|
expect(responseAfterLongLimitReload.headers[`x-ratelimit-remaining-${shortName}`]).toBe(
|
|
(shortLimit - 1).toString()
|
|
);
|
|
expect(
|
|
Number(responseAfterLongLimitReload.headers[`x-ratelimit-reset-${shortName}`])
|
|
).toBeGreaterThan(0);
|
|
expect(responseAfterLongLimitReload.headers[`x-ratelimit-limit-${longName}`]).toBe(
|
|
longLimit.toString()
|
|
);
|
|
expect(responseAfterLongLimitReload.headers[`x-ratelimit-remaining-${longName}`]).toBe(
|
|
(longLimit - 1).toString()
|
|
);
|
|
expect(Number(responseAfterLongLimitReload.headers[`x-ratelimit-reset-${longName}`])).toBeGreaterThan(
|
|
0
|
|
);
|
|
},
|
|
30 * 1000
|
|
);
|
|
|
|
it(
|
|
"non api key with default rate limit - should enforce rate limits and reset after block duration",
|
|
async () => {
|
|
const limit = mockDefaultLimit;
|
|
const blockDuration = mockDefaultBlockDuration;
|
|
|
|
for (let i = 1; i <= limit; i++) {
|
|
const response = await request(app.getHttpServer())
|
|
.get("/v2/me")
|
|
.set(X_CAL_CLIENT_ID, oAuthClient.id)
|
|
.set(X_CAL_SECRET_KEY, oAuthClient.secret)
|
|
.expect(200);
|
|
|
|
expect(response.headers["x-ratelimit-limit-default"]).toBe(limit.toString());
|
|
expect(response.headers["x-ratelimit-remaining-default"]).toBe((limit - i).toString());
|
|
expect(Number(response.headers["x-ratelimit-reset-default"])).toBeGreaterThan(0);
|
|
}
|
|
|
|
const blockedResponse = await request(app.getHttpServer())
|
|
.get("/v2/me")
|
|
.set(X_CAL_CLIENT_ID, oAuthClient.id)
|
|
.set(X_CAL_SECRET_KEY, oAuthClient.secret)
|
|
.expect(429);
|
|
|
|
expect(blockedResponse.headers["x-ratelimit-limit-default"]).toBe(limit.toString());
|
|
expect(blockedResponse.headers["x-ratelimit-remaining-default"]).toBe("0");
|
|
expect(Number(blockedResponse.headers["x-ratelimit-reset-default"])).toBeGreaterThanOrEqual(
|
|
blockDuration / 1000
|
|
);
|
|
|
|
await new Promise((resolve) => setTimeout(resolve, blockDuration));
|
|
|
|
const afterBlockResponse = await request(app.getHttpServer())
|
|
.get("/v2/me")
|
|
.set(X_CAL_CLIENT_ID, oAuthClient.id)
|
|
.set(X_CAL_SECRET_KEY, oAuthClient.secret)
|
|
.expect(200);
|
|
|
|
expect(afterBlockResponse.headers["x-ratelimit-limit-default"]).toBe(limit.toString());
|
|
expect(afterBlockResponse.headers["x-ratelimit-remaining-default"]).toBe((limit - 1).toString());
|
|
expect(Number(afterBlockResponse.headers["x-ratelimit-reset-default"])).toBeGreaterThan(0);
|
|
},
|
|
15 * 1000
|
|
);
|
|
|
|
afterAll(async () => {
|
|
await userRepositoryFixture.deleteByEmail(userEmail);
|
|
await organizationsRepositoryFixture.delete(organization.id);
|
|
await app.close();
|
|
});
|
|
});
|
|
});
|