Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: check the cap belongs to the org before loading cap analytics

Richie McIlroyf8bec34e1b6c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 37ca3a971..3fa00050e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -122,6 +122,7 @@ jobs:
- name: Test web React compatibility
run: >-
bun run --cwd apps/web test
+ __tests__/unit/dashboard-analytics-cap-access.test.ts
__tests__/unit/dashboard-analytics-space-access.test.ts
__tests__/unit/embed-video-playback-chrome.test.ts
__tests__/unit/folder-videos.test.ts
diff --git a/apps/web/__tests__/unit/dashboard-analytics-cap-access.test.ts b/apps/web/__tests__/unit/dashboard-analytics-cap-access.test.ts
new file mode 100644
index 000000000..416633e91
--- /dev/null
+++ b/apps/web/__tests__/unit/dashboard-analytics-cap-access.test.ts
@@ -0,0 +1,180 @@
+import type { NextRequest } from "next/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { GET } from "@/app/api/dashboard/analytics/route";
+
+const mocks = vi.hoisted(() => ({
+ query: vi.fn(),
+ getOrgAnalyticsData: vi.fn(),
+}));
+
+vi.mock("server-only", () => ({}));
+vi.mock("@cap/database", async () => {
+ const { drizzle } = await import("drizzle-orm/mysql-proxy");
+ const client = drizzle(mocks.query);
+ return { db: () => client };
+});
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: async () => ({ id: "user-1", activeOrganizationId: "org-1" }),
+}));
+vi.mock("@cap/web-backend", async () => {
+ const { AgentManagement } = await import(
+ "../../../../packages/web-backend/src/AgentManagement"
+ );
+ return { AgentManagement };
+});
+vi.mock("@/lib/server", async () => {
+ const { Effect } = await import("effect");
+ const { Database } = await import(
+ "../../../../packages/web-backend/src/Database"
+ );
+ return {
+ runPromise: <A, E>(
+ effect: import("effect").Effect.Effect<
+ A,
+ E,
+ InstanceType<typeof Database>
+ >,
+ ) => Effect.runPromise(Effect.provide(effect, Database.Default)),
+ };
+});
+vi.mock("@/app/(org)/dashboard/analytics/data", () => ({
+ getOrgAnalyticsData: mocks.getOrgAnalyticsData,
+}));
+
+type CapAccessRow = {
+ orgId: string;
+ ownerId: string;
+ sharedWithOrganization: number | string;
+ inOrganizationSpace: number | string;
+};
+
+const capRow = (overrides: Partial<CapAccessRow> = {}) => {
+ const row: CapAccessRow = {
+ orgId: "org-2",
+ ownerId: "someone-else",
+ sharedWithOrganization: 0,
+ inOrganizationSpace: 0,
+ ...overrides,
+ };
+ return [
+ row.orgId,
+ row.ownerId,
+ row.sharedWithOrganization,
+ row.inOrganizationSpace,
+ ];
+};
+
+const request = (params: Record<string, string>) =>
+ ({
+ url: `https://cap.test/api/dashboard/analytics?${new URLSearchParams(params)}`,
+ }) as NextRequest;
+
+beforeEach(() => {
+ mocks.query.mockReset();
+ mocks.query.mockResolvedValue({ rows: [] });
+ mocks.getOrgAnalyticsData.mockReset();
+ mocks.getOrgAnalyticsData.mockResolvedValue({ counts: {}, capName: "Cap" });
+});
+
+describe("dashboard analytics cap access", () => {
+ it("skips the cap lookup when no cap is requested", async () => {
+ const response = await GET(request({ orgId: "org-1" }));
+
+ expect(response.status).toBe(200);
+ expect(mocks.query).not.toHaveBeenCalled();
+ });
+
+ it("scopes the share and space lookups to the requested cap and organization", async () => {
+ mocks.query.mockResolvedValueOnce({
+ rows: [capRow({ orgId: "org-1" })],
+ });
+
+ await GET(request({ orgId: "org-1", capId: "cap-1" }));
+
+ expect(mocks.query).toHaveBeenCalledTimes(1);
+ const [statement, params] = mocks.query.mock.calls[0] as [
+ string,
+ unknown[],
+ ];
+ expect(statement).toContain("`shared_videos`");
+ expect(statement).toContain("`space_videos`");
+ expect(statement).toContain("`spaces`");
+ expect(params.filter((value) => value === "cap-1")).toHaveLength(3);
+ expect(params.filter((value) => value === "org-1")).toHaveLength(3);
+ });
+
+ it.each([
+ ["a cap owned by the organization", { orgId: "org-1" }],
+ ["the user's own cap from another organization", { ownerId: "user-1" }],
+ ["a cap shared into the organization", { sharedWithOrganization: 1 }],
+ ["a cap added to a space in the organization", { inOrganizationSpace: 1 }],
+ ["a share flag returned as a string", { sharedWithOrganization: "1" }],
+ ])("allows %s", async (_, overrides) => {
+ mocks.query.mockResolvedValueOnce({ rows: [capRow(overrides)] });
+
+ const response = await GET(
+ request({ orgId: "org-1", capId: "cap-1", range: "30d" }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(mocks.getOrgAnalyticsData).toHaveBeenCalledWith(
+ "org-1",
+ "30d",
+ undefined,
+ "cap-1",
+ );
+ await expect(response.json()).resolves.toEqual({
+ data: { counts: {}, capName: "Cap" },
+ });
+ });
+
+ it("allows a cap together with an accessible space", async () => {
+ mocks.query
+ .mockResolvedValueOnce({
+ rows: [["org-1", "user-1", "Private", null, "member"]],
+ })
+ .mockResolvedValueOnce({ rows: [capRow({ inOrganizationSpace: 1 })] });
+
+ const response = await GET(
+ request({ orgId: "org-1", spaceId: "space-1", capId: "cap-1" }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(mocks.getOrgAnalyticsData).toHaveBeenCalledWith(
+ "org-1",
+ "7d",
+ "space-1",
+ "cap-1",
+ );
+ });
+
+ it("rejects a cap from another organization that was never shared in", async () => {
+ mocks.query.mockResolvedValueOnce({ rows: [capRow()] });
+
+ const response = await GET(request({ orgId: "org-1", capId: "cap-1" }));
+
+ expect(response.status).toBe(403);
+ expect(mocks.getOrgAnalyticsData).not.toHaveBeenCalled();
+ });
+
+ it("rejects a cap that does not exist", async () => {
+ const response = await GET(request({ orgId: "org-1", capId: "missing" }));
+
+ expect(response.status).toBe(403);
+ expect(mocks.getOrgAnalyticsData).not.toHaveBeenCalled();
+ });
+
+ it("rejects a cap when the space check fails first", async () => {
+ mocks.query.mockResolvedValueOnce({
+ rows: [["org-2", "user-1", "Private", null, "owner"]],
+ });
+
+ const response = await GET(
+ request({ orgId: "org-1", spaceId: "space-1", capId: "cap-1" }),
+ );
+
+ expect(response.status).toBe(403);
+ expect(mocks.query).toHaveBeenCalledTimes(1);
+ expect(mocks.getOrgAnalyticsData).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/app/api/dashboard/analytics/route.ts b/apps/web/app/api/dashboard/analytics/route.ts
index 5c80d175e..38767aa8a 100644
--- a/apps/web/app/api/dashboard/analytics/route.ts
+++ b/apps/web/app/api/dashboard/analytics/route.ts
@@ -3,6 +3,7 @@ import type { NextRequest } from "next/server";
import { getOrgAnalyticsData } from "@/app/(org)/dashboard/analytics/data";
import type { AnalyticsRange } from "@/app/(org)/dashboard/analytics/types";
+import { canViewCapAnalytics } from "@/lib/cap-analytics-access";
import { canViewSpaceAnalytics } from "@/lib/space-analytics-access";
const RANGE_VALUES: AnalyticsRange[] = ["24h", "7d", "30d", "lifetime"];
@@ -36,6 +37,10 @@ export async function GET(request: NextRequest) {
return Response.json({ error: "Forbidden" }, { status: 403 });
}
+ if (capId && !(await canViewCapAnalytics(user.id, orgId, capId))) {
+ return Response.json({ error: "Forbidden" }, { status: 403 });
+ }
+
const data = await getOrgAnalyticsData(orgId, range, spaceId, capId);
return Response.json({ data });
} catch (error) {
diff --git a/apps/web/lib/cap-analytics-access.ts b/apps/web/lib/cap-analytics-access.ts
new file mode 100644
index 000000000..e870c5b66
--- /dev/null
+++ b/apps/web/lib/cap-analytics-access.ts
@@ -0,0 +1,64 @@
+import "server-only";
+
+import { db } from "@cap/database";
+import {
+ sharedVideos,
+ spaces,
+ spaceVideos,
+ videos,
+} from "@cap/database/schema";
+import { Organisation, type User, Video } from "@cap/web-domain";
+import { and, eq, exists, or, sql } from "drizzle-orm";
+
+export const canViewCapAnalytics = async (
+ userId: User.UserId,
+ orgId: string,
+ capId: string,
+) => {
+ const organizationId = Organisation.OrganisationId.make(orgId);
+ const videoId = Video.VideoId.make(capId);
+
+ const [video] = await db()
+ .select({
+ orgId: videos.orgId,
+ ownerId: videos.ownerId,
+ sharedWithOrganization: sql<number>`${exists(
+ db()
+ .select({ id: sharedVideos.id })
+ .from(sharedVideos)
+ .where(
+ and(
+ eq(sharedVideos.videoId, videoId),
+ eq(sharedVideos.organizationId, organizationId),
+ ),
+ ),
+ )}`,
+ inOrganizationSpace: sql<number>`${exists(
+ db()
+ .select({ id: spaceVideos.id })
+ .from(spaceVideos)
+ .leftJoin(spaces, eq(spaces.id, spaceVideos.spaceId))
+ .where(
+ and(
+ eq(spaceVideos.videoId, videoId),
+ or(
+ eq(spaceVideos.spaceId, organizationId),
+ eq(spaces.organizationId, organizationId),
+ ),
+ ),
+ ),
+ )}`,
+ })
+ .from(videos)
+ .where(eq(videos.id, videoId))
+ .limit(1);
+
+ if (!video) return false;
+
+ return (
+ video.orgId === organizationId ||
+ video.ownerId === userId ||
+ Number(video.sharedWithOrganization) === 1 ||
+ Number(video.inOrganizationSpace) === 1
+ );
+};