Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
🔒️ Enforce Pro tier in API key authentication (#2540)
Luke Vellaed4a474ddf32
diff --git a/apps/web/src/app/api/private/[...route]/route.test.ts b/apps/web/src/app/api/private/[...route]/route.test.tsindex 2b6e74452..47b2a1b5f 100644--- a/apps/web/src/app/api/private/[...route]/route.test.ts+++ b/apps/web/src/app/api/private/[...route]/route.test.ts@@ -78,6 +78,7 @@ const mockApiKey = {updatedAt: new Date("2025-01-01"),space: {ownerId: "test-user-id",+ tier: "pro",},};@@ -184,6 +185,129 @@ describe("Private API - /polls", () => {});});+ describe("Pro tier enforcement", () => {+ it("should return 403 with SPACE_NOT_PRO when the space is not pro", async () => {+ const hobbyApiKey = {+ ...mockApiKey,+ space: { ...mockApiKey.space, tier: "hobby" },+ };+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([hobbyApiKey]);++ const res = await app.request("/api/private/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Test Poll",+ dates: ["2025-01-15"],+ }),+ });++ expect(res.status).toBe(403);+ const json = await res.json();+ expect(json.error.code).toBe("SPACE_NOT_PRO");+ });++ it("should return 200 with a valid key when the space is pro", async () => {+ const res = await app.request("/api/private/polls", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${testApiKey}`,+ },+ body: JSON.stringify({+ title: "Test Poll",+ dates: ["2025-01-15"],+ }),+ });++ expect(res.status).toBe(200);+ });+ });++ describe("lastUsedAt throttling", () => {+ it("should not schedule a write when lastUsedAt is recent", async () => {+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([+ {+ ...mockApiKey,+ hashedKey: hashApiKey(testApiKey),+ lastUsedAt: new Date(Date.now() - 30_000),+ },+ ]);++ const res = await app.request("/api/private/polls/test-poll-id", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).not.toBe(401);+ expect(after).not.toHaveBeenCalled();+ });++ it("should schedule a write when lastUsedAt is stale", async () => {+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([+ {+ ...mockApiKey,+ hashedKey: hashApiKey(testApiKey),+ lastUsedAt: new Date(Date.now() - 120_000),+ },+ ]);++ const res = await app.request("/api/private/polls/test-poll-id", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).not.toBe(401);+ expect(after).toHaveBeenCalledTimes(1);+ });++ it("should schedule a write when lastUsedAt is null", async () => {+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([+ {+ ...mockApiKey,+ hashedKey: hashApiKey(testApiKey),+ lastUsedAt: null,+ },+ ]);++ const res = await app.request("/api/private/polls/test-poll-id", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).not.toBe(401);+ expect(after).toHaveBeenCalledTimes(1);+ });++ it("should still re-hash a legacy key when lastUsedAt is recent", async () => {+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([+ {+ ...mockApiKey,+ lastUsedAt: new Date(Date.now() - 30_000),+ },+ ]);++ const res = await app.request("/api/private/polls/test-poll-id", {+ method: "GET",+ headers: {+ Authorization: `Bearer ${testApiKey}`,+ },+ });++ expect(res.status).not.toBe(401);+ expect(after).toHaveBeenCalledTimes(1);+ });+ });+describe("Hash migration (scrypt -> sha256)", () => {// The lastUsedAt/re-hash update runs in an after() callback; invoke the// captured callbacks to simulate the post-response phasediff --git a/apps/web/src/app/api/private/[...route]/route.ts b/apps/web/src/app/api/private/[...route]/route.tsindex a78beed30..88a87ba24 100644--- a/apps/web/src/app/api/private/[...route]/route.ts+++ b/apps/web/src/app/api/private/[...route]/route.ts@@ -1,4 +1,5 @@import { RedisStore } from "@hono-rate-limiter/redis";+import type { SpaceTier } from "@rallly/database";import { prisma } from "@rallly/database";import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";import { Scalar } from "@scalar/hono-api-reference";@@ -37,6 +38,7 @@ type Env = {apiAuth: {spaceId: string;spaceOwnerId: string;+ spaceTier: SpaceTier;apiKeyId: string;};};@@ -46,6 +48,16 @@ const app = new Hono<Env>().basePath("/api/private");const MAX_OPTIONS = 100;+const spaceNotProResponse = {+ description:+ "The space associated with the API key does not have a Pro subscription",+ content: {+ "application/json": {+ schema: resolver(errorResponseSchema),+ },+ },+};+app.get("/openapi",openAPIRouteHandler(app, {@@ -110,6 +122,7 @@ app.post(},},},+ 403: spaceNotProResponse,},}),validator("json", createPollInputSchema),@@ -335,6 +348,7 @@ app.get(},},},+ 403: spaceNotProResponse,404: {description: "Poll not found",content: {@@ -446,6 +460,7 @@ app.get(},},},+ 403: spaceNotProResponse,404: {description: "Poll not found",content: {@@ -505,6 +520,7 @@ app.get(},},},+ 403: spaceNotProResponse,404: {description: "Poll not found",content: {@@ -564,6 +580,7 @@ app.delete(},},},+ 403: spaceNotProResponse,404: {description: "Poll not found",content: {diff --git a/apps/web/src/app/api/private/utils/api-key.ts b/apps/web/src/app/api/private/utils/api-key.tsindex d14ddd1e9..f89a39a1f 100644--- a/apps/web/src/app/api/private/utils/api-key.ts+++ b/apps/web/src/app/api/private/utils/api-key.ts@@ -1,6 +1,9 @@import crypto from "node:crypto";+import type { SpaceTier } from "@rallly/database";import { prisma } from "@rallly/database";import { bearerAuth } from "hono/bearer-auth";+import { every } from "hono/combine";+import { createMiddleware } from "hono/factory";import { after } from "next/server";import {extractApiKeyPrefix,@@ -8,8 +11,12 @@ import {isLegacyApiKeyHash,verifyApiKey,} from "@/features/api-keys/api-key";+import { isSelfHosted } from "@/utils/constants";+import { apiError } from "./poll";-export const spaceApiKeyAuth = bearerAuth({+const LAST_USED_AT_WRITE_INTERVAL_MS = 60_000;++const verifyKey = bearerAuth({verifyToken: async (rawKey, c) => {const prefix = extractApiKeyPrefix(rawKey);const prefixBuffer = Buffer.from(prefix);@@ -30,11 +37,13 @@ export const spaceApiKeyAuth = bearerAuth({prefix: true,spaceId: true,hashedKey: true,+ lastUsedAt: true,expiresAt: true,revokedAt: true,space: {select: {ownerId: true,+ tier: true,},},},@@ -43,6 +52,8 @@ export const spaceApiKeyAuth = bearerAuth({let apiKeyId: string | null = null;let spaceId: string | null = null;let spaceOwnerId: string | null = null;+ let spaceTier: SpaceTier | null = null;+ let lastUsedAt: Date | null = null;let needsRehash = false;for (const candidate of candidateKeys) {// Timing-safe prefix comparison@@ -57,18 +68,21 @@ export const spaceApiKeyAuth = bearerAuth({apiKeyId = candidate.id;spaceId = candidate.spaceId;spaceOwnerId = candidate.space.ownerId;+ spaceTier = candidate.space.tier;+ lastUsedAt = candidate.lastUsedAt;needsRehash = isLegacyApiKeyHash(candidate.hashedKey);}}}- if (!apiKeyId || !spaceId || !spaceOwnerId) {+ if (!apiKeyId || !spaceId || !spaceOwnerId || !spaceTier) {return false;}c.set("apiAuth", {spaceId,spaceOwnerId,+ spaceTier: isSelfHosted ? ("pro" as const) : spaceTier,apiKeyId,});@@ -76,16 +90,44 @@ export const spaceApiKeyAuth = bearerAuth({// raw key during verification, so this is the one place we can re-hash.const rehashedKey = needsRehash ? hashApiKey(rawKey) : null;- after(() =>- prisma.spaceApiKey.update({- where: { id: apiKeyId },- data: {- lastUsedAt: new Date(),- ...(rehashedKey ? { hashedKey: rehashedKey } : {}),- },- }),- );+ // lastUsedAt is only read at coarse precision, so throttle the write+ // rather than issue an UPDATE on every request. Concurrent requests+ // racing past this check are harmless (the write is idempotent).+ const isLastUsedAtStale =+ !lastUsedAt ||+ now.getTime() - lastUsedAt.getTime() > LAST_USED_AT_WRITE_INTERVAL_MS;++ if (rehashedKey || isLastUsedAtStale) {+ after(() =>+ prisma.spaceApiKey.update({+ where: { id: apiKeyId },+ data: {+ lastUsedAt: new Date(),+ ...(rehashedKey ? { hashedKey: rehashedKey } : {}),+ },+ }),+ );+ }return true;},});++// hono/bearer-auth can only turn a failed verifyToken into a 401, so the+// tier check runs as a follow-up middleware to respond with a 403 instead.+const requireProSpace = createMiddleware<{+ Variables: { apiAuth: { spaceTier: SpaceTier } };+}>(async (c, next) => {+ if (c.get("apiAuth").spaceTier !== "pro") {+ return c.json(+ apiError(+ "SPACE_NOT_PRO",+ "API access requires a Pro subscription. Upgrade this space in Settings > Billing.",+ ),+ 403,+ );+ }+ await next();+});++export const spaceApiKeyAuth = every(verifyKey, requireProSpace);