Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Refactor rate limiting logic for API and sessions

Kiran Kd9d80b82552f
diff --git a/apps/web/lib/auth/rate-limit-request.ts b/apps/web/lib/auth/rate-limit-request.ts
new file mode 100644
index 0000000000..3a3e3b27d6
--- /dev/null
+++ b/apps/web/lib/auth/rate-limit-request.ts
@@ -0,0 +1,33 @@
+import { ratelimit } from "../upstash";
+
+export async function rateLimitRequest({
+ identifier,
+ requests,
+ interval,
+}: {
+ identifier: string;
+ requests: number;
+ interval: `${number} s` | `${number} m`;
+}) {
+ const { success, limit, reset, remaining } = await ratelimit(
+ requests,
+ interval,
+ ).limit(identifier);
+
+ if (success) {
+ return {
+ success: true,
+ headers: {},
+ };
+ }
+
+ return {
+ success: false,
+ headers: {
+ "Retry-After": reset.toString(),
+ "X-RateLimit-Limit": limit.toString(),
+ "X-RateLimit-Remaining": remaining.toString(),
+ "X-RateLimit-Reset": reset.toString(),
+ },
+ };
+}
diff --git a/apps/web/lib/auth/token-cache.ts b/apps/web/lib/auth/token-cache.ts
index a0fbc128b7..669c8d9918 100644
--- a/apps/web/lib/auth/token-cache.ts
+++ b/apps/web/lib/auth/token-cache.ts
@@ -6,7 +6,6 @@ const CACHE_KEY_PREFIX = "tokenCache";
const tokenCacheItemSchema = z.object({
scopes: z.string().nullish(),
- rateLimit: z.number().nullish(),
projectId: z.string().nullish(),
expires: z.date().nullish(),
installationId: z.string().nullish(),
@@ -16,6 +15,11 @@ const tokenCacheItemSchema = z.object({
email: z.string().nullable(),
isMachine: z.boolean(),
}),
+ project: z
+ .object({
+ plan: z.string().nullish(),
+ })
+ .nullish(),
});
type TokenCacheItem = z.infer<typeof tokenCacheItemSchema>;
diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.ts
index b193c5ef99..0e4c4aeda0 100644
--- a/apps/web/lib/auth/workspace.ts
+++ b/apps/web/lib/auth/workspace.ts
@@ -2,7 +2,7 @@ import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { BetaFeatures, PlanProps, WorkspaceWithUsers } from "@/lib/types";
import { ratelimit } from "@/lib/upstash";
import { prisma } from "@dub/prisma";
-import { API_DOMAIN, getSearchParams } from "@dub/utils";
+import { API_DOMAIN, getCurrentPlan, getSearchParams } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { AxiomRequest, withAxiom } from "next-axiom";
import { headers } from "next/headers";
@@ -16,9 +16,21 @@ import { normalizeWorkspaceId } from "../api/workspaces/workspace-id";
import { getFeatureFlags } from "../edge-config";
import { logConversionEvent } from "../tinybird/log-conversion-events";
import { hashToken } from "./hash-token";
+import { rateLimitRequest } from "./rate-limit-request";
import { tokenCache } from "./token-cache";
import { Session, getSession } from "./utils";
+export const RATE_LIMIT_FOR_SESSIONS = {
+ api: {
+ limit: 100,
+ interval: "1 m",
+ },
+ analyticsApi: {
+ limit: 10,
+ interval: "1 s",
+ },
+} as const;
+
interface WithWorkspaceHandler {
({
req,
@@ -88,6 +100,8 @@ export const withWorkspace = (
apiKey = authorizationHeader.replace("Bearer ", "");
}
+ const url = new URL(req.url || "", API_DOMAIN);
+
let session: Session | undefined;
let workspaceId: string | undefined;
let workspaceSlug: string | undefined;
@@ -144,6 +158,10 @@ export const withWorkspace = (
}
}
+ const isAnalytics =
+ url.pathname.includes("/analytics") ||
+ url.pathname.includes("/events");
+
if (apiKey) {
const hashedKey = await hashToken(apiKey);
@@ -159,10 +177,14 @@ export const withWorkspace = (
select: {
...(isRestrictedToken && {
scopes: true,
- rateLimit: true,
projectId: true,
expires: true,
installationId: true,
+ project: {
+ select: {
+ plan: true,
+ },
+ },
}),
user: {
select: {
@@ -184,6 +206,8 @@ export const withWorkspace = (
token = cachedToken || token;
+ console.log("token", token);
+
if (!token || !token.user) {
throw new DubApiError({
code: "unauthorized",
@@ -208,19 +232,28 @@ export const withWorkspace = (
}
// Rate limit checks for API keys
- const rateLimit = token.rateLimit || 600;
+ let limit = 0;
+ let interval: `${number} s` | `${number} m` = "1 m";
- const { success, limit, reset, remaining } = await ratelimit(
- rateLimit,
- "1 m",
- ).limit(apiKey);
+ if (token.project?.plan) {
+ const planLimit = getCurrentPlan(token.project?.plan);
+ limit = planLimit.limits[isAnalytics ? "analyticsApi" : "api"];
+ interval = isAnalytics ? "1 s" : "1 m";
+ } else {
+ limit = 600; // default rate limit for personal API keys
+ }
- responseHeaders.set("Retry-After", reset.toString());
- responseHeaders.set("X-RateLimit-Limit", limit.toString());
- responseHeaders.set("X-RateLimit-Remaining", remaining.toString());
- responseHeaders.set("X-RateLimit-Reset", reset.toString());
+ const { success, headers } = await rateLimitRequest({
+ identifier: `workspace:ratelimit:${apiKey}`,
+ requests: limit,
+ interval,
+ });
if (!success) {
+ for (const [key, value] of Object.entries(headers)) {
+ responseHeaders.set(key, value);
+ }
+
throw new DubApiError({
code: "rate_limit_exceeded",
message: "Too many requests.",
@@ -279,6 +312,27 @@ export const withWorkspace = (
message: "Unauthorized: Login required.",
});
}
+
+ // Rate limit checks for session requests
+ const rateLimit =
+ RATE_LIMIT_FOR_SESSIONS[isAnalytics ? "analyticsApi" : "api"];
+
+ const { success, headers } = await rateLimitRequest({
+ identifier: `workspace:ratelimit:${session.user.id}`,
+ requests: rateLimit.limit,
+ interval: rateLimit.interval,
+ });
+
+ if (!success) {
+ for (const [key, value] of Object.entries(headers)) {
+ responseHeaders.set(key, value);
+ }
+
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message: "Too many requests.",
+ });
+ }
}
workspace = (await prisma.project.findUnique({
@@ -380,8 +434,6 @@ export const withWorkspace = (
}
}
- const url = new URL(req.url || "", API_DOMAIN);
-
// plan checks
if (!requiredPlan.includes(workspace.plan)) {
throw new DubApiError({
diff --git a/packages/prisma/schema/token.prisma b/packages/prisma/schema/token.prisma
index 82fd41d6e8..bba8a560b2 100644
--- a/packages/prisma/schema/token.prisma
+++ b/packages/prisma/schema/token.prisma
@@ -21,7 +21,6 @@ model RestrictedToken {
scopes String? // space separated (Eg: "links:write", "domains:read")
expires DateTime?
lastUsed DateTime?
- rateLimit Int @default(60) // rate limit per minute
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userId String