Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

🔒 Rate limit response submission per IP and per poll (#3476)

Luke Vella3c5d7617c5db
diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts b/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts
index c5bef4d75..8d2149616 100644
--- a/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts
+++ b/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts
@@ -34,7 +34,7 @@ import {
export const scheduleAccountDeletionAction = authActionClient
.metadata({ actionName: "schedule_account_deletion" })
// Each call hits Stripe and sends an email — keep the ceiling low.
- .use(createRateLimitMiddleware(3, "1 h"))
+ .use(createRateLimitMiddleware({ requests: 3, duration: "1 h", by: "user" }))
.action(async ({ ctx }) => {
if (isSelfHosted) {
throw new AppError({
@@ -95,7 +95,7 @@ export const scheduleAccountDeletionAction = authActionClient
// Deletion happens immediately instead; there is no recovery window.
export const deleteAccountAction = authActionClient
.metadata({ actionName: "delete_account" })
- .use(createRateLimitMiddleware(3, "1 h"))
+ .use(createRateLimitMiddleware({ requests: 3, duration: "1 h", by: "user" }))
.action(async ({ ctx }) => {
if (!isSelfHosted) {
throw new AppError({
@@ -121,7 +121,7 @@ export const deleteAccountAction = authActionClient
export const cancelAccountDeletionAction = authActionClient
.metadata({ actionName: "cancel_account_deletion" })
- .use(createRateLimitMiddleware(10, "1 h"))
+ .use(createRateLimitMiddleware({ requests: 10, duration: "1 h", by: "user" }))
.action(async ({ ctx }) => {
await cancelAccountDeletion({ userId: ctx.user.id });
await resumeUserSubscriptionRenewals({ userId: ctx.user.id });
diff --git a/apps/web/src/features/auth/actions.ts b/apps/web/src/features/auth/actions.ts
index 9ca8a18d1..d80a2897a 100644
--- a/apps/web/src/features/auth/actions.ts
+++ b/apps/web/src/features/auth/actions.ts
@@ -63,7 +63,7 @@ export async function setPasswordForUser({
// endpoint directly rather than going through a mutation.
export const setPasswordAction = authActionClient
.metadata({ actionName: "set_password" })
- .use(createRateLimitMiddleware(5, "1 h"))
+ .use(createRateLimitMiddleware({ requests: 5, duration: "1 h", by: "user" }))
.inputSchema(z.object({ password: passwordSchema }))
.action(async ({ ctx, parsedInput }) => {
// The UI hides this behind the emailLogin flag; gate the action too so a
diff --git a/apps/web/src/features/feedback/actions.ts b/apps/web/src/features/feedback/actions.ts
index 1dc27b2fd..711658a51 100644
--- a/apps/web/src/features/feedback/actions.ts
+++ b/apps/web/src/features/feedback/actions.ts
@@ -9,7 +9,7 @@ import { feedbackSchema } from "./schema";
export const submitFeedbackAction = authActionClient
.metadata({ actionName: "submit_feedback" })
- .use(createRateLimitMiddleware(5, "1 h"))
+ .use(createRateLimitMiddleware({ requests: 5, duration: "1 h", by: "user" }))
.inputSchema(feedbackSchema)
.action(async ({ ctx, parsedInput }) => {
await submitFeedback({
diff --git a/apps/web/src/features/poll/comment/actions.ts b/apps/web/src/features/poll/comment/actions.ts
index 5a7c3000f..45ff17fc7 100644
--- a/apps/web/src/features/poll/comment/actions.ts
+++ b/apps/web/src/features/poll/comment/actions.ts
@@ -92,7 +92,7 @@ async function sendNewCommentNotificationEmail({
export const addCommentAction = anyUserActionClient
.metadata({ actionName: "add_comment" })
- .use(createRateLimitMiddleware(10, "1 m"))
+ .use(createRateLimitMiddleware({ requests: 10, duration: "1 m", by: "user" }))
.inputSchema(addCommentSchema)
.action(async ({ ctx, parsedInput }) => {
const { pollId, authorName, content } = parsedInput;
diff --git a/apps/web/src/features/poll/invite/actions.ts b/apps/web/src/features/poll/invite/actions.ts
index 0d7c06488..7525d0bd6 100644
--- a/apps/web/src/features/poll/invite/actions.ts
+++ b/apps/web/src/features/poll/invite/actions.ts
@@ -22,7 +22,7 @@ import {
export const sendPollInviteAction = authActionClient
.metadata({ actionName: "send_poll_invite" })
// One email per call; the daily recipient cap lives in the mutation.
- .use(createRateLimitMiddleware(30, "1 m"))
+ .use(createRateLimitMiddleware({ requests: 30, duration: "1 m", by: "user" }))
.inputSchema(sendPollInviteSchema)
.action(async ({ ctx, parsedInput }) => {
const { pollId, email } = parsedInput;
diff --git a/apps/web/src/features/poll/participant/actions.ts b/apps/web/src/features/poll/participant/actions.ts
index ead775c36..bec0bee28 100644
--- a/apps/web/src/features/poll/participant/actions.ts
+++ b/apps/web/src/features/poll/participant/actions.ts
@@ -35,6 +35,7 @@ import { getLocale } from "@/i18n/server/get-locale";
import { runtime } from "@/lib/effect/runtime";
import { AppError } from "@/lib/errors/app-error";
import { flushPostHog, track, trackSystemEvent } from "@/lib/posthog";
+import { createRateLimitGuard } from "@/lib/rate-limit";
import {
anyUserActionClient,
createRateLimitMiddleware,
@@ -43,6 +44,14 @@ import {
const logger = createLogger("participants");
+// Guest sessions are free to mint, so a per-user limit would reset with a new
+// session, and it would also refuse a host entering responses for others.
+// The per-IP and per-poll limits hold regardless of session.
+// The IP limit is loose because offices, schools and mobile carriers put many
+// people behind one address. The largest poll in 90 days took 295 responses
+// in total, p99 is 23, so the per-poll cap does not touch real use.
+const pollResponseGuard = createRateLimitGuard(200, "1 h");
+
type Actor = { id: string; isGuest: boolean };
/**
@@ -180,10 +189,13 @@ async function sendNewResponseNotificationEmail({
export const addParticipantAction = anyUserActionClient
.metadata({ actionName: "add_participant" })
- .use(createRateLimitMiddleware(10, "1 h"))
+ .use(createRateLimitMiddleware({ requests: 60, duration: "1 m", by: "ip" }))
.inputSchema(addParticipantSchema)
.action(async ({ ctx, parsedInput }) => {
const { pollId, votes, name, email, note, timeZone, token } = parsedInput;
+
+ ctx.event.pollId = pollId;
+ await pollResponseGuard(`add_participant:poll:${pollId}`, ctx.event);
const locale = await getLocale();
const result = await addParticipant({
@@ -284,6 +296,7 @@ export const addParticipantAction = anyUserActionClient
export const updateParticipantVotesAction = optionalUserActionClient
.metadata({ actionName: "update_participant_votes" })
+ .use(createRateLimitMiddleware({ requests: 60, duration: "1 m", by: "ip" }))
.inputSchema(updateParticipantVotesSchema)
.action(async ({ ctx, parsedInput }) => {
const { participantId, votes, token } = parsedInput;
diff --git a/apps/web/src/features/space/actions.ts b/apps/web/src/features/space/actions.ts
index e7660c9ad..a359b6b39 100644
--- a/apps/web/src/features/space/actions.ts
+++ b/apps/web/src/features/space/actions.ts
@@ -96,7 +96,7 @@ export const setActiveSpaceAction = authActionClient
export const createSpaceAction = authActionClient
.metadata({ actionName: "create_space" })
- .use(createRateLimitMiddleware(5, "1 m"))
+ .use(createRateLimitMiddleware({ requests: 5, duration: "1 m", by: "user" }))
.inputSchema(createSpaceSchema)
.action(async ({ ctx, parsedInput }) => {
const space = await createSpace({
diff --git a/apps/web/src/features/user/actions.ts b/apps/web/src/features/user/actions.ts
index 9ed0076da..8e4ff7fad 100644
--- a/apps/web/src/features/user/actions.ts
+++ b/apps/web/src/features/user/actions.ts
@@ -85,7 +85,7 @@ export const updateLocalizationAction = authActionClient
// verify step handles via its own "email already in use" error.
export const checkEmailAvailabilityAction = authActionClient
.metadata({ actionName: "check_email_availability" })
- .use(createRateLimitMiddleware(10, "1 h"))
+ .use(createRateLimitMiddleware({ requests: 10, duration: "1 h", by: "user" }))
.inputSchema(
z.object({
email: z.email(),
@@ -107,7 +107,7 @@ export const checkEmailAvailabilityAction = authActionClient
export const getAvatarUploadUrlAction = authActionClient
.metadata({ actionName: "get_avatar_upload_url" })
- .use(createRateLimitMiddleware(10, "1 h"))
+ .use(createRateLimitMiddleware({ requests: 10, duration: "1 h", by: "user" }))
.inputSchema(
z.object({
fileType: z.enum(avatarAssetProfile.accept),
diff --git a/apps/web/src/features/webhook/actions.ts b/apps/web/src/features/webhook/actions.ts
index 4b40dd805..a954ce2f3 100644
--- a/apps/web/src/features/webhook/actions.ts
+++ b/apps/web/src/features/webhook/actions.ts
@@ -132,7 +132,7 @@ export const deleteWebhookAction = authActionClient
export const sendWebhookTestEventAction = authActionClient
.metadata({ actionName: "send_webhook_test_event" })
.inputSchema(sendWebhookTestEventSchema)
- .use(createRateLimitMiddleware(10, "1 m"))
+ .use(createRateLimitMiddleware({ requests: 10, duration: "1 m", by: "user" }))
.action(async ({ ctx, parsedInput }) => {
const { space } = await requireWebhookAccess();
diff --git a/apps/web/src/lib/rate-limit/index.test.ts b/apps/web/src/lib/rate-limit/index.test.ts
index c3a01cb72..c7552121f 100644
--- a/apps/web/src/lib/rate-limit/index.test.ts
+++ b/apps/web/src/lib/rate-limit/index.test.ts
@@ -1,8 +1,9 @@
+import type { WideEvent } from "@rallly/logger";
import { describe, expect, it, vi } from "vitest";
vi.mock("@/env", () => ({ env: {} }));
-import { createBudget } from "./index";
+import { createBudget, createRateLimitGuard } from "./index";
describe("createBudget", () => {
it("grants what is left and nothing past it", async () => {
@@ -21,3 +22,35 @@ describe("createBudget", () => {
expect(grants.reduce((sum = 0, n = 0) => sum + n, 0)).toBe(10);
});
});
+
+describe("createRateLimitGuard", () => {
+ it("refuses a scripted loop of responses against one poll after the cap", async () => {
+ const guard = createRateLimitGuard(200, "1 h");
+ const key = "add_participant:poll:poll-1";
+
+ for (let i = 0; i < 200; i++) {
+ await guard(key);
+ }
+
+ const event: WideEvent = { service: "action" };
+ await expect(guard(key, event)).rejects.toMatchObject({
+ code: "TOO_MANY_REQUESTS",
+ });
+ expect(event).toMatchObject({
+ rateLimiter: "memory",
+ rateLimiterRemainingPoints: 0,
+ });
+ await expect(guard("add_participant:poll:poll-2")).resolves.toBeUndefined();
+ });
+
+ it("keeps the lowest remaining count when several guards run", async () => {
+ const perIp = createRateLimitGuard(10, "1 m");
+ const perPoll = createRateLimitGuard(200, "1 h");
+ const event: WideEvent = { service: "action" };
+
+ await perIp("ip:1.2.3.4", event);
+ await perPoll("poll:poll-1", event);
+
+ expect(event.rateLimiterRemainingPoints).toBe(9);
+ });
+});
diff --git a/apps/web/src/lib/rate-limit/index.ts b/apps/web/src/lib/rate-limit/index.ts
index 329d3adeb..a3c2bed8e 100644
--- a/apps/web/src/lib/rate-limit/index.ts
+++ b/apps/web/src/lib/rate-limit/index.ts
@@ -1,5 +1,7 @@
import "server-only";
+import type { WideEvent } from "@rallly/logger";
import { Ratelimit } from "@upstash/ratelimit";
+import { AppError } from "@/lib/errors/app-error";
import { redis } from "@/lib/kv";
import { isRateLimitEnabled } from "./constants";
@@ -80,6 +82,42 @@ export function createRatelimit(requests: number, duration: Duration) {
return createMemoryLimiter(requests, duration);
}
+/**
+ * Refuses a key past `requests` per `duration` with TOO_MANY_REQUESTS and
+ * records the limiter and its remaining points on the request's wide event,
+ * as the tRPC middleware does. With several guards on one request the event
+ * keeps the lowest remaining count, the one closest to refusing.
+ */
+export function createRateLimitGuard(requests: number, duration: Duration) {
+ const ratelimit = createRatelimit(requests, duration);
+
+ return async (key: string, event?: WideEvent) => {
+ if (event) {
+ event.rateLimiter = ratelimit?.name ?? "none";
+ }
+
+ if (!ratelimit) {
+ return;
+ }
+
+ const { success, remainingPoints } = await ratelimit.limit(key);
+
+ if (event) {
+ event.rateLimiterRemainingPoints = Math.min(
+ event.rateLimiterRemainingPoints ?? remainingPoints,
+ remainingPoints,
+ );
+ }
+
+ if (!success) {
+ throw new AppError({
+ code: "TOO_MANY_REQUESTS",
+ message: "You are making too many requests.",
+ });
+ }
+ };
+}
+
/**
* A rate shared by every process, for work that should wait its turn rather
* than be refused. `acquire` resolves true once a slot is free, false if
diff --git a/apps/web/src/lib/safe-action/server.ts b/apps/web/src/lib/safe-action/server.ts
index c94c9a07a..081f28cdc 100644
--- a/apps/web/src/lib/safe-action/server.ts
+++ b/apps/web/src/lib/safe-action/server.ts
@@ -1,7 +1,10 @@
import "server-only";
+import type { WideEvent } from "@rallly/logger";
+import { createWideEvent, logger } from "@rallly/logger";
import * as Sentry from "@sentry/nextjs";
import { APIError } from "better-auth/api";
+import { headers } from "next/headers";
import { after } from "next/server";
import { createMiddleware, createSafeActionClient } from "next-safe-action";
import * as z from "zod";
@@ -13,37 +16,40 @@ import { InvalidSessionError } from "@/lib/errors/invalid-session-error";
import { assertAppAvailable } from "@/lib/maintenance-server";
import { flushPostHog } from "@/lib/posthog";
import type { Duration } from "@/lib/rate-limit";
-import { createRatelimit } from "@/lib/rate-limit";
+import { createRateLimitGuard } from "@/lib/rate-limit";
-export const createRateLimitMiddleware = (
- requests: number,
- duration: Duration,
-) =>
- createMiddleware<{
+/**
+ * Limits an action per user or per client address. Limit by address where a
+ * caller can repeat the action under a fresh guest session. An unknown
+ * address (a self-hosted instance with no proxy headers) is not limited, so
+ * unrelated visitors never share one bucket.
+ */
+export const createRateLimitMiddleware = ({
+ requests,
+ duration,
+ by,
+}: {
+ requests: number;
+ duration: Duration;
+ by: "user" | "ip";
+}) => {
+ const guard = createRateLimitGuard(requests, duration);
+
+ return createMiddleware<{
metadata: {
actionName: string;
};
- ctx: { user: { id: string } };
+ ctx: { user?: { id: string } | null; event: WideEvent };
}>().define(async ({ next, metadata, ctx }) => {
- const ratelimit = createRatelimit(requests, duration);
-
- if (!ratelimit) {
- return next();
- }
+ const id = by === "user" ? ctx.user?.id : ctx.event.ip;
- const { success } = await ratelimit.limit(
- `${metadata.actionName}:${ctx.user.id}`,
- );
-
- if (!success) {
- throw new AppError({
- code: "TOO_MANY_REQUESTS",
- message: "You are making too many requests.",
- });
+ if (id) {
+ await guard(`${metadata.actionName}:${by}:${id}`, ctx.event);
}
return next();
});
+};
export const actionClient = createSafeActionClient({
defineMetadataSchema: () =>
@@ -98,6 +104,43 @@ export const actionClient = createSafeActionClient({
return "INTERNAL_SERVER_ERROR" as const;
},
})
+ // One wide event per action call, emitted once the result is known.
+ .use(async ({ next, metadata }) => {
+ const headerList = await headers();
+ const startTime = Date.now();
+ const event = createWideEvent({
+ service: "action",
+ requestId:
+ headerList.get("x-vercel-id") ??
+ headerList.get("x-request-id") ??
+ undefined,
+ actionName: metadata.actionName,
+ // x-real-ip is what Vercel sets; self-hosted proxies set the other.
+ ip:
+ headerList.get("x-real-ip") ??
+ headerList.get("x-forwarded-for")?.split(",")[0]?.trim(),
+ ja4Digest: headerList.get("x-vercel-ja4-digest") ?? undefined,
+ });
+
+ try {
+ const result = await next({ ctx: { event } });
+ if (typeof result.serverError === "string") {
+ event.errorCode = result.serverError;
+ } else if (result.validationErrors) {
+ event.errorCode = "VALIDATION_ERROR";
+ }
+ return result;
+ } finally {
+ event.durationMs = Date.now() - startTime;
+ if (event.errorCode === "INTERNAL_SERVER_ERROR") {
+ logger.error(event);
+ } else if (event.errorCode) {
+ logger.warn(event);
+ } else {
+ logger.info(event);
+ }
+ }
+ })
// The PostHog client only enqueues; a serverless function freezes once the
// action response is sent, so the buffer must be flushed here. Route
// handlers get the same through withPostHog. Runs in finally so a failed
@@ -114,7 +157,7 @@ export const actionClient = createSafeActionClient({
return next();
});
-export const authActionClient = actionClient.use(async ({ next }) => {
+export const authActionClient = actionClient.use(async ({ ctx, next }) => {
const user = await loadOptionalUser();
if (!user) {
@@ -126,6 +169,9 @@ export const authActionClient = actionClient.use(async ({ next }) => {
const ability = defineAbilityFor(user);
+ ctx.event.userId = user.id;
+ ctx.event.isGuest = user.isGuest;
+
return next({
ctx: { user, ability },
});
@@ -135,13 +181,20 @@ export const authActionClient = actionClient.use(async ({ next }) => {
* For writes on public pages: the session user may be a guest, and there
* may be none at all when the credential is a token from an emailed link.
*/
-export const optionalUserActionClient = actionClient.use(async ({ next }) => {
- const user = await loadOptionalActor();
+export const optionalUserActionClient = actionClient.use(
+ async ({ ctx, next }) => {
+ const user = await loadOptionalActor();
- return next({
- ctx: { user },
- });
-});
+ if (user) {
+ ctx.event.userId = user.id;
+ ctx.event.isGuest = user.isGuest;
+ }
+
+ return next({
+ ctx: { user },
+ });
+ },
+);
/**
* For writes a guest may perform. The client creates the guest session