/ opencodehub / tests / unit / graphql-add-comment-permissions.test.ts
swadhinbiswas Enforce repo and path permissions for comment and review mutations · 2/19/2026
93f6489
67 lines · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { beforeEach, describe, expect, it, vi } from "vitest";

const { canWriteRepoMock } = vi.hoisted(() => ({
  canWriteRepoMock: vi.fn(async () => true),
}));

vi.mock("@/lib/permissions", async () => {
  const actual = await vi.importActual<any>("@/lib/permissions");
  return {
    ...actual,
    canWriteRepo: canWriteRepoMock,
  };
});

import { resolvers } from "@/lib/graphql/resolvers";

function makeContext() {
  const insertCalls: unknown[] = [];
  return {
    db: {
      query: {
        issues: {
          findFirst: vi.fn(async () => null),
        },
        pullRequests: {
          findFirst: vi.fn(async () => ({ id: "pr-1", repositoryId: "repo-1" })),
        },
        repositories: {
          findFirst: vi.fn(async () => ({ id: "repo-1" })),
        },
        pullRequestComments: {
          findFirst: vi.fn(async () => ({ id: "comment-1" })),
        },
      },
      insert: vi.fn(() => ({
        values: vi.fn(async (value: unknown) => {
          insertCalls.push(value);
        }),
      })),
      __state: { insertCalls },
    },
    userId: "user-1",
    user: { isAdmin: false },
  } as any;
}

describe("GraphQL addComment permission enforcement", () => {
  beforeEach(() => {
    canWriteRepoMock.mockResolvedValue(true);
  });

  it("blocks PR comment creation when user lacks repository write permission", async () => {
    const ctx = makeContext();
    canWriteRepoMock.mockResolvedValue(false);

    await expect(
      resolvers.Mutation.addComment(
        {},
        { input: { subjectId: "pr-1", body: "test comment" } },
        ctx
      )
    ).rejects.toThrow("Insufficient repository permissions");

    expect(ctx.db.__state.insertCalls).toHaveLength(0);
  });
});