chore: system wide ratelimit per path (#25080)
* chore: Add system wide rate limiting * Handle and convert HttpError to 429 * Make algo 32-bit to prevent <ES2020 error + fix sms manager unit test * Change core to common to go from 10 requests per minute to 200 * Remove redundant function * Fix integration tests * Make sure we allow all legal POST routes * Allow tRPC post calls * Add matcher tests on middleware * Add matcher tests on middleware * Fix matcher to not use regex * Fix missing POST allow rule for /api/auth/callback/credentials * Missed the api/book/event endpoints * Add missing pages/api routes * Remove POST middleware for now, very risky * Remove tests for POST protection --------- Co-authored-by: Volnei Munhoz <[email protected]>
This commit is contained in:
1 parent
a3fc17bc75
commit
1d6959c4ac
11 files changed
+251
-160
No files matched your search
@@ -2,7 +2,7 @@ import type { NextRequest } from "next/server";
|
||||
import TwilioClient from "twilio";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { checkSMSRateLimit } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import { checkSMSRateLimit } from "@calcom/lib/smsLockState";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { setTestSMS } from "@calcom/lib/testSMS";
|
||||
@@ -85,6 +85,7 @@ export const sendSMS = async ({
|
||||
}
|
||||
|
||||
if (isWhatsapp) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const messageOptions: any = {
|
||||
contentSid: contentSid,
|
||||
to: getSMSNumber(phoneNumber, isWhatsapp),
|
||||
@@ -172,6 +173,7 @@ export const scheduleSMS = async ({
|
||||
}
|
||||
|
||||
if (isWhatsapp) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const messageOptions: any = {
|
||||
contentSid: contentSid,
|
||||
to: getSMSNumber(phoneNumber, isWhatsapp),
|
||||
@@ -225,7 +227,7 @@ export const verifyNumber = async (phoneNumber: string, code: string) => {
|
||||
.services(process.env.TWILIO_VERIFY_SID)
|
||||
.verificationChecks.create({ to: phoneNumber, code: code });
|
||||
return verification_check.status;
|
||||
} catch (e) {
|
||||
} catch {
|
||||
return "failed";
|
||||
}
|
||||
}
|
||||
@@ -265,7 +267,7 @@ async function isLockedForSMSSending(userId?: number | null, teamId?: number | n
|
||||
(membership) => membership.team.smsLockState === SMSLockState.LOCKED
|
||||
);
|
||||
|
||||
if (!!memberOfLockedTeam) {
|
||||
if (memberOfLockedTeam) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import * as twilio from "@calcom/features/ee/workflows/lib/reminders/providers/t
|
||||
import type { Workflow, WorkflowStep } from "@calcom/features/ee/workflows/lib/types";
|
||||
import { getSubmitterEmail } from "@calcom/features/tasker/tasks/triggerFormSubmittedNoEvent/formSubmissionValidation";
|
||||
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
|
||||
import { checkSMSRateLimit } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import { checkSMSRateLimit } from "@calcom/lib/smsLockState";
|
||||
import { SENDER_NAME } from "@calcom/lib/constants";
|
||||
import { formatCalEventExtended } from "@calcom/lib/formatCalendarEvent";
|
||||
import { withReporting } from "@calcom/lib/sentryWrapper";
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { SMSLockState } from "@calcom/prisma/enums";
|
||||
|
||||
import { HttpError } from "./http-error";
|
||||
import type { RateLimitHelper } from "./rateLimit";
|
||||
import { rateLimiter } from "./rateLimit";
|
||||
@@ -12,10 +9,8 @@ export async function checkRateLimitAndThrowError({
|
||||
opts,
|
||||
}: RateLimitHelper) {
|
||||
const response = await rateLimiter()({ rateLimitingType, identifier, opts });
|
||||
const { success, reset } = response;
|
||||
|
||||
if (onRateLimiterResponse) onRateLimiterResponse(response);
|
||||
|
||||
const { success, reset } = response;
|
||||
if (!success) {
|
||||
const convertToSeconds = (ms: number) => Math.floor(ms / 1000);
|
||||
const secondsToWait = convertToSeconds(reset - Date.now());
|
||||
@@ -26,63 +21,3 @@ export async function checkRateLimitAndThrowError({
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
export async function checkSMSRateLimit({
|
||||
rateLimitingType = "sms",
|
||||
identifier,
|
||||
onRateLimiterResponse,
|
||||
opts,
|
||||
}: RateLimitHelper) {
|
||||
const response = await rateLimiter()({ rateLimitingType, identifier, opts });
|
||||
const { success } = response;
|
||||
|
||||
if (onRateLimiterResponse) onRateLimiterResponse(response);
|
||||
|
||||
if (!success) {
|
||||
await changeSMSLockState(
|
||||
identifier,
|
||||
rateLimitingType === "sms" ? SMSLockState.LOCKED : SMSLockState.REVIEW_NEEDED
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function changeSMSLockState(identifier: string, status: SMSLockState) {
|
||||
let userId, teamId;
|
||||
|
||||
if (identifier.startsWith("sms:user:")) {
|
||||
userId = Number(identifier.slice(9));
|
||||
} else if (identifier.startsWith("sms:team:")) {
|
||||
teamId = Number(identifier.slice(9));
|
||||
}
|
||||
|
||||
if (userId) {
|
||||
const user = await prisma.user.findUnique({ where: { id: userId, profiles: { none: {} } } });
|
||||
if (user?.smsLockReviewedByAdmin) return;
|
||||
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: userId,
|
||||
profiles: { none: {} },
|
||||
},
|
||||
data: {
|
||||
smsLockState: status,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId, parentId: null, isOrganization: false },
|
||||
});
|
||||
if (team?.smsLockReviewedByAdmin) return;
|
||||
|
||||
await prisma.team.update({
|
||||
where: {
|
||||
id: teamId,
|
||||
parentId: null,
|
||||
isOrganization: false,
|
||||
},
|
||||
data: {
|
||||
smsLockState: status,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -5,16 +5,24 @@ describe("PII Hasher Test Suite", () => {
|
||||
|
||||
const hasher = new Md5PiiHasher("test-salt");
|
||||
|
||||
it("can hash email addresses", async () => {
|
||||
it("can hash email addresses deterministically and preserve domain", async () => {
|
||||
const email = "[email protected]";
|
||||
const hashedEmail = hashEmail(email, hasher);
|
||||
expect(hashedEmail).toBe("[email protected]");
|
||||
// Domain must be preserved
|
||||
expect(hashedEmail.endsWith("@example.com")).toBe(true);
|
||||
// Local part should change
|
||||
expect(hashedEmail.split("@")[0]).not.toBe("sensitive_data");
|
||||
// Deterministic
|
||||
expect(hashEmail(email, hasher)).toBe(hashedEmail);
|
||||
});
|
||||
|
||||
it("can hash PII with saltyMd5", async () => {
|
||||
it("can hash PII deterministically to a 128-bit hex string", async () => {
|
||||
const pii = "sensitive_data";
|
||||
const hashedPii = hasher.hash(pii);
|
||||
expect(hashedPii).toBe("2e74ca9edc8add1709b0d049aa2a0959");
|
||||
// 128-bit hex (32 hex chars)
|
||||
expect(hashedPii).toMatch(/^[0-9a-f]{32}$/);
|
||||
// Deterministic
|
||||
expect(hasher.hash(pii)).toBe(hashedPii);
|
||||
});
|
||||
|
||||
it("handles hashing with different salt", () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createHash } from "crypto";
|
||||
// Note: avoid Node's crypto to support runtimes where it's unavailable (e.g., edge/browsers)
|
||||
|
||||
export interface PiiHasher {
|
||||
hash(input: string): string;
|
||||
@@ -7,9 +7,24 @@ export interface PiiHasher {
|
||||
export class Md5PiiHasher implements PiiHasher {
|
||||
constructor(private readonly salt: string) {}
|
||||
hash(input: string) {
|
||||
return createHash("md5")
|
||||
.update(this.salt + input)
|
||||
.digest("hex");
|
||||
// FNV-1a 32-bit using Math.imul, repeated 4 times with variant salt to get 128-bit hex
|
||||
const fnv1a32 = (str: string) => {
|
||||
// Convert to UTF-8 bytes without relying on TextEncoder/Buffer
|
||||
const data = unescape(encodeURIComponent(str));
|
||||
let hash = 0x811c9dc5; // offset basis (2166136261)
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
hash = Math.imul(hash ^ data.charCodeAt(i), 0x01000193); // 16777619
|
||||
}
|
||||
return hash >>> 0; // unsigned 32-bit
|
||||
};
|
||||
|
||||
// Four independent 32-bit hashes to produce a stable 128-bit hex string
|
||||
const h1 = fnv1a32(`${this.salt}::1::${input}`);
|
||||
const h2 = fnv1a32(`${this.salt}::2::${input}`);
|
||||
const h3 = fnv1a32(`${this.salt}::3::${input}`);
|
||||
const h4 = fnv1a32(`${this.salt}::4::${input}`);
|
||||
const toHex8 = (n: number) => n.toString(16).padStart(8, "0");
|
||||
return `${toHex8(h1)}${toHex8(h2)}${toHex8(h3)}${toHex8(h4)}`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { SMSLockState } from "@calcom/prisma/enums";
|
||||
import type { RateLimitHelper } from "./rateLimit";
|
||||
import { rateLimiter } from "./rateLimit";
|
||||
|
||||
export async function checkSMSRateLimit({
|
||||
rateLimitingType = "sms",
|
||||
identifier,
|
||||
onRateLimiterResponse,
|
||||
opts,
|
||||
}: RateLimitHelper) {
|
||||
const response = await rateLimiter()({ rateLimitingType, identifier, opts });
|
||||
const { success } = response;
|
||||
|
||||
if (onRateLimiterResponse) onRateLimiterResponse(response);
|
||||
|
||||
if (!success) {
|
||||
await changeSMSLockState(
|
||||
identifier,
|
||||
rateLimitingType === "sms" ? SMSLockState.LOCKED : SMSLockState.REVIEW_NEEDED
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function changeSMSLockState(identifier: string, status: SMSLockState) {
|
||||
let userId, teamId;
|
||||
|
||||
if (identifier.startsWith("sms:user:")) {
|
||||
userId = Number(identifier.slice(9));
|
||||
} else if (identifier.startsWith("sms:team:")) {
|
||||
teamId = Number(identifier.slice(9));
|
||||
}
|
||||
|
||||
if (userId) {
|
||||
const user = await prisma.user.findUnique({ where: { id: userId, profiles: { none: {} } } });
|
||||
if (user?.smsLockReviewedByAdmin) return;
|
||||
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: userId,
|
||||
profiles: { none: {} },
|
||||
},
|
||||
data: {
|
||||
smsLockState: status,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId, parentId: null, isOrganization: false },
|
||||
});
|
||||
if (team?.smsLockReviewedByAdmin) return;
|
||||
|
||||
await prisma.team.update({
|
||||
where: {
|
||||
id: teamId,
|
||||
parentId: null,
|
||||
isOrganization: false,
|
||||
},
|
||||
data: {
|
||||
smsLockState: status,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { getSenderId } from "@calcom/features/ee/workflows/lib/alphanumericSenderIdSupport";
|
||||
import { sendSmsOrFallbackEmail } from "@calcom/features/ee/workflows/lib/reminders/messageDispatcher";
|
||||
import { checkSMSRateLimit } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import { checkSMSRateLimit } from "@calcom/lib/smsLockState";
|
||||
import { SENDER_ID } from "@calcom/lib/constants";
|
||||
import isSmsCalEmail from "@calcom/lib/isSmsCalEmail";
|
||||
import { piiHasher } from "@calcom/lib/server/PiiHasher";
|
||||
@@ -42,7 +42,7 @@ const handleSendingSMS = async ({
|
||||
phoneNumber: reminderPhone,
|
||||
body: smsMessage,
|
||||
sender: senderID,
|
||||
...(!!teamId ? { teamId } : { userId: organizerUserId }),
|
||||
...(teamId ? { teamId } : { userId: organizerUserId }),
|
||||
bookingUid,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -2,13 +2,13 @@ import type { TFunction } from "i18next";
|
||||
import { describe, expect, test, vi, beforeEach } from "vitest";
|
||||
|
||||
import { sendSmsOrFallbackEmail } from "@calcom/features/ee/workflows/lib/reminders/messageDispatcher";
|
||||
import { checkSMSRateLimit } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import { checkSMSRateLimit } from "@calcom/lib/smsLockState";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { CalendarEvent, Person } from "@calcom/types/Calendar";
|
||||
|
||||
import SMSManager from "../sms-manager";
|
||||
|
||||
vi.mock("@calcom/lib/checkRateLimitAndThrowError");
|
||||
vi.mock("@calcom/lib/smsLockState");
|
||||
vi.mock("@calcom/features/ee/workflows/lib/reminders/messageDispatcher");
|
||||
vi.mock("@calcom/prisma", () => ({
|
||||
default: {
|
||||
|
||||
Reference in new issue
Block a user