Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): fail open when the firewall rate limit check throws

Richie McIlroy301342b7ef83
diff --git a/apps/web/__tests__/unit/loom-import.test.ts b/apps/web/__tests__/unit/loom-import.test.ts
index 98bf61372..e9e03b769 100644
--- a/apps/web/__tests__/unit/loom-import.test.ts
+++ b/apps/web/__tests__/unit/loom-import.test.ts
@@ -395,6 +395,64 @@ describe("importFromLoom", () => {
expect(valuesMock).not.toHaveBeenCalled();
});
+ it("fails open when the Loom import rate limit check throws", async () => {
+ checkRateLimitMock.mockRejectedValueOnce(
+ new Error("Unexpected response 494"),
+ );
+ const consoleErrorSpy = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+
+ const fetchMock = vi.mocked(fetch);
+ fetchMock.mockImplementation(async (input) => {
+ const url = typeof input === "string" ? input : input.toString();
+
+ if (url.includes("/transcoded-url")) {
+ return {
+ ok: true,
+ status: 200,
+ text: async () =>
+ JSON.stringify({ url: "https://cdn.loom.com/video.mp4" }),
+ } as Response;
+ }
+
+ if (url === "https://www.loom.com/graphql") {
+ return {
+ ok: true,
+ json: async () => ({
+ data: { getVideo: { name: "Imported video" } },
+ }),
+ } as Response;
+ }
+
+ if (url.includes("/v1/oembed")) {
+ return {
+ ok: true,
+ json: async () => ({ duration: 42, width: 1920, height: 1080 }),
+ } as Response;
+ }
+
+ throw new Error(`Unexpected fetch: ${url}`);
+ });
+
+ const { importFromLoom } = await import("@/actions/loom");
+
+ const result = await importFromLoom({
+ loomUrl: "https://www.loom.com/share/loom-abc1234567",
+ orgId: "org-1" as never,
+ });
+
+ expect(result).toEqual({
+ success: true,
+ videoId: "video-123",
+ });
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
+ 'Rate limit check failed for "rl_loom_import_per_user":',
+ expect.any(Error),
+ );
+ expect(startMock).toHaveBeenCalledTimes(1);
+ });
+
it("removes a stale Loom row and recreates it with the Cap video id", async () => {
whereMock
.mockResolvedValueOnce([{ importedVideoId: "stale-row", videoId: null }])
diff --git a/apps/web/__tests__/unit/send-download-link.test.ts b/apps/web/__tests__/unit/send-download-link.test.ts
new file mode 100644
index 000000000..a23722d63
--- /dev/null
+++ b/apps/web/__tests__/unit/send-download-link.test.ts
@@ -0,0 +1,75 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const checkRateLimitMock = vi.hoisted(() => vi.fn());
+const headersMock = vi.hoisted(() => vi.fn());
+const sendEmailMock = vi.hoisted(() => vi.fn());
+
+vi.mock("@vercel/firewall", () => ({
+ checkRateLimit: checkRateLimitMock,
+}));
+
+vi.mock("next/headers", () => ({
+ headers: headersMock,
+}));
+
+vi.mock("@cap/database/emails/config", () => ({
+ sendEmail: sendEmailMock,
+}));
+
+vi.mock("@cap/database/emails/download-link", () => ({
+ DownloadLink: vi.fn(() => null),
+}));
+
+describe("sendDownloadLink", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ checkRateLimitMock.mockResolvedValue({ rateLimited: false });
+ headersMock.mockResolvedValue(
+ new Headers({ host: "cap.test", "x-real-ip": "127.0.0.1" }),
+ );
+ sendEmailMock.mockResolvedValue(undefined);
+ });
+
+ it("sends the email when the rate limit check passes", async () => {
+ const { sendDownloadLink } = await import("@/actions/send-download-link");
+
+ const result = await sendDownloadLink("[email protected]");
+
+ expect(result).toEqual({ success: true });
+ expect(sendEmailMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("rejects the request when rate limited", async () => {
+ checkRateLimitMock.mockResolvedValueOnce({ rateLimited: true });
+
+ const { sendDownloadLink } = await import("@/actions/send-download-link");
+
+ const result = await sendDownloadLink("[email protected]");
+
+ expect(result).toEqual({
+ success: false,
+ error: "You've sent too many requests. Please try again later.",
+ });
+ expect(sendEmailMock).not.toHaveBeenCalled();
+ });
+
+ it("fails open when the rate limit check throws", async () => {
+ checkRateLimitMock.mockRejectedValueOnce(
+ new Error("Unexpected response 494"),
+ );
+ const consoleErrorSpy = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+
+ const { sendDownloadLink } = await import("@/actions/send-download-link");
+
+ const result = await sendDownloadLink("[email protected]");
+
+ expect(result).toEqual({ success: true });
+ expect(sendEmailMock).toHaveBeenCalledTimes(1);
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
+ 'Rate limit check failed for "rl_send_download_link":',
+ expect.any(Error),
+ );
+ });
+});
diff --git a/apps/web/actions/loom.ts b/apps/web/actions/loom.ts
index 7d03ced00..64056bc93 100644
--- a/apps/web/actions/loom.ts
+++ b/apps/web/actions/loom.ts
@@ -107,11 +107,20 @@ async function createLoomImportRateLimitCheck(userId: User.UserId) {
});
return async () => {
- const { rateLimited } = await checkRateLimit(LOOM_IMPORT_RATE_LIMIT_ID, {
- request,
- rateLimitKey: `loom-import:${userId}`,
- });
- return rateLimited;
+ try {
+ const { rateLimited } = await checkRateLimit(LOOM_IMPORT_RATE_LIMIT_ID, {
+ request,
+ rateLimitKey: `loom-import:${userId}`,
+ });
+ return rateLimited;
+ } catch (error) {
+ // Fail open: a firewall/edge outage must never block Loom imports.
+ console.error(
+ `Rate limit check failed for "${LOOM_IMPORT_RATE_LIMIT_ID}":`,
+ error,
+ );
+ return false;
+ }
};
}
diff --git a/apps/web/actions/send-download-link.ts b/apps/web/actions/send-download-link.ts
index 6d3c4a64c..402c1d500 100644
--- a/apps/web/actions/send-download-link.ts
+++ b/apps/web/actions/send-download-link.ts
@@ -38,9 +38,19 @@ export async function sendDownloadLink(email: string) {
headers: headersList,
});
- const { rateLimited } = await checkRateLimit("rl_send_download_link", {
- request,
- });
+ let rateLimited = false;
+ try {
+ const result = await checkRateLimit("rl_send_download_link", {
+ request,
+ });
+ rateLimited = result.rateLimited;
+ } catch (error) {
+ // Fail open: a firewall/edge outage must never block download emails.
+ console.error(
+ 'Rate limit check failed for "rl_send_download_link":',
+ error,
+ );
+ }
if (rateLimited) {
return {