/ opencodehub / tests / integration / pr-comments-path-permissions.test.ts
swadhinbiswas Polish path-scoped review visibility and gate reporting · 2/19/2026
870606d
297 lines · 10.2 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import { beforeEach, describe, expect, it, vi } from "vitest";

const { getUserFromRequestMock, checkPathPermissionsMock, canReadRepoMock, canWriteRepoMock, fakeSchema } = vi.hoisted(() => ({
  getUserFromRequestMock: vi.fn(async () => ({ userId: "user-1", isAdmin: false })),
  checkPathPermissionsMock: vi.fn(async () => ({ allowed: true, deniedPaths: [] })),
  canReadRepoMock: vi.fn(async () => true),
  canWriteRepoMock: vi.fn(async () => true),
  fakeSchema: {
    users: { username: {}, id: {} },
    repositories: { ownerId: {}, name: {}, id: {} },
    pullRequests: { number: {}, repositoryId: {} },
    pullRequestComments: { id: {}, pullRequestId: {} },
  } as any,
}));

let mockDb: any;

vi.mock("@/db", () => ({
  getDatabase: () => mockDb,
  schema: fakeSchema,
}));

vi.mock("@/lib/auth", () => ({
  getUserFromRequest: getUserFromRequestMock,
}));

vi.mock("@/lib/path-scoping", () => ({
  checkPathPermissions: checkPathPermissionsMock,
}));

vi.mock("@/lib/permissions", () => ({
  canReadRepo: canReadRepoMock,
  canWriteRepo: canWriteRepoMock,
}));

import { GET as listCommentsGet } from "@/pages/api/repos/[owner]/[repo]/pulls/[number]/comments";
import { POST as createCommentPost } from "@/pages/api/repos/[owner]/[repo]/pulls/[number]/comments";
import { PATCH as updateCommentPatch } from "@/pages/api/repos/[owner]/[repo]/pulls/[number]/comments";
import { DELETE as deleteCommentDelete } from "@/pages/api/repos/[owner]/[repo]/pulls/[number]/comments";

function makeDb() {
  const pr = {
    id: "pr-1",
    repositoryId: "repo-1",
    repository: { id: "repo-1", ownerId: "owner-1" },
  };
  const commentForMutation = {
    id: "comment-1",
    authorId: "user-1",
    path: "secure/config.yml",
    pullRequest: {
      repositoryId: "repo-1",
      repository: { ownerId: "owner-1" },
    },
  };
  const insertCalls: unknown[] = [];
  const updateCalls: unknown[] = [];
  const deleteCalls: unknown[] = [];

  return {
    query: {
      users: {
        findFirst: vi.fn(async () => ({ id: "owner-1" })),
      },
      repositories: {
        findFirst: vi.fn(async () => ({ id: "repo-1", ownerId: "owner-1", name: "demo" })),
      },
      pullRequests: {
        findFirst: vi.fn(async () => pr),
      },
      pullRequestComments: {
        findFirst: vi.fn(async (_args?: any) => {
          if (_args?.with?.pullRequest) return commentForMutation;
          return { id: "comment-1", author: { username: "user-1" } };
        }),
        findMany: vi.fn(async () => ([
          {
            id: "comment-1",
            pullRequestId: "pr-1",
            authorId: "user-1",
            body: "public",
            path: "src/app.ts",
            inReplyToId: null,
            createdAt: new Date("2026-02-19T00:00:00Z"),
            author: { username: "user-1" },
          },
          {
            id: "comment-2",
            pullRequestId: "pr-1",
            authorId: "user-2",
            body: "secret",
            path: "secure/config.yml",
            inReplyToId: null,
            createdAt: new Date("2026-02-19T00:01:00Z"),
            author: { username: "user-2" },
          },
        ])),
      },
    },
    insert: vi.fn(() => ({
      values: vi.fn(async (value: unknown) => {
        insertCalls.push(value);
      }),
    })),
    update: vi.fn(() => ({
      set: vi.fn((value: unknown) => ({
        where: vi.fn(async () => {
          updateCalls.push(value);
        }),
      })),
    })),
    delete: vi.fn(() => ({
      where: vi.fn(async (value: unknown) => {
        deleteCalls.push(value);
      }),
    })),
    __state: { insertCalls },
    __mutationState: { updateCalls, deleteCalls },
  };
}

async function readJson(response: Response): Promise<any> {
  return response.json();
}

describe("PR comments path permissions", () => {
  beforeEach(() => {
    mockDb = makeDb();
    getUserFromRequestMock.mockResolvedValue({ userId: "user-1", isAdmin: false });
    checkPathPermissionsMock.mockResolvedValue({ allowed: true, deniedPaths: [] });
    canReadRepoMock.mockResolvedValue(true);
    canWriteRepoMock.mockResolvedValue(true);
  });

  it("blocks inline comment creation when path write permission is denied", async () => {
    checkPathPermissionsMock.mockResolvedValue({
      allowed: false,
      deniedPaths: ["secure/config.yml"],
      reason: "Insufficient permissions for paths: secure/config.yml",
    });

    const response = await createCommentPost({
      params: { owner: "owner-1", repo: "demo", number: "42" },
      request: new Request("http://localhost/api/repos/owner-1/demo/pulls/42/comments", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ body: "blocked", path: "secure/config.yml", line: 1 }),
      }),
    } as any);

    const body = await readJson(response);
    expect(response.status).toBe(403);
    expect(body?.error?.code).toBe("FORBIDDEN");
    expect(mockDb.__state.insertCalls).toHaveLength(0);
  });

  it("filters hidden comment paths in list responses", async () => {
    checkPathPermissionsMock.mockResolvedValue({
      allowed: false,
      deniedPaths: ["secure/config.yml"],
      reason: "Insufficient permissions for paths: secure/config.yml",
    });

    const response = await listCommentsGet({
      params: { owner: "owner-1", repo: "demo", number: "42" },
      request: new Request("http://localhost/api/repos/owner-1/demo/pulls/42/comments", {
        method: "GET",
      }),
    } as any);

    const body = await readJson(response);
    expect(response.status).toBe(200);
    expect(body?.data?.comments).toHaveLength(1);
    expect(body?.data?.comments?.[0]?.path).toBe("src/app.ts");
    expect(body?.data?.hiddenCount).toBe(1);
    expect(checkPathPermissionsMock).toHaveBeenCalledWith(
      "user-1",
      "repo-1",
      ["src/app.ts", "secure/config.yml"],
      "read"
    );
  });

  it("blocks comment creation when repository write permission is denied", async () => {
    canWriteRepoMock.mockResolvedValue(false);

    const response = await createCommentPost({
      params: { owner: "owner-1", repo: "demo", number: "42" },
      request: new Request("http://localhost/api/repos/owner-1/demo/pulls/42/comments", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ body: "blocked", path: "src/app.ts", line: 1 }),
      }),
    } as any);

    const body = await readJson(response);
    expect(response.status).toBe(403);
    expect(body?.error?.code).toBe("FORBIDDEN");
    expect(mockDb.__state.insertCalls).toHaveLength(0);
  });

  it("allows comment creation when path permission check passes", async () => {
    const response = await createCommentPost({
      params: { owner: "owner-1", repo: "demo", number: "42" },
      request: new Request("http://localhost/api/repos/owner-1/demo/pulls/42/comments", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ body: "allowed", path: "src/app.ts", line: 3 }),
      }),
    } as any);

    const body = await readJson(response);
    expect(response.status).toBe(200);
    expect(body?.success).toBe(true);
    expect(checkPathPermissionsMock).toHaveBeenCalledWith("user-1", "repo-1", ["src/app.ts"], "write");
    expect(mockDb.__state.insertCalls).toHaveLength(1);
  });

  it("blocks comment edits when path write permission is denied", async () => {
    checkPathPermissionsMock.mockResolvedValue({
      allowed: false,
      deniedPaths: ["secure/config.yml"],
      reason: "Insufficient permissions for paths: secure/config.yml",
    });

    const response = await updateCommentPatch({
      params: { owner: "owner-1", repo: "demo", number: "42", commentId: "comment-1" },
      request: new Request("http://localhost/api/repos/owner-1/demo/pulls/42/comments/comment-1", {
        method: "PATCH",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ body: "updated" }),
      }),
    } as any);

    const body = await readJson(response);
    expect(response.status).toBe(403);
    expect(body?.error?.code).toBe("FORBIDDEN");
    expect(mockDb.__mutationState.updateCalls).toHaveLength(0);
  });

  it("blocks comment deletion for non-admin when path write permission is denied", async () => {
    checkPathPermissionsMock.mockResolvedValue({
      allowed: false,
      deniedPaths: ["secure/config.yml"],
      reason: "Insufficient permissions for paths: secure/config.yml",
    });

    const response = await deleteCommentDelete({
      params: { owner: "owner-1", repo: "demo", number: "42", commentId: "comment-1" },
      request: new Request("http://localhost/api/repos/owner-1/demo/pulls/42/comments/comment-1", {
        method: "DELETE",
      }),
    } as any);

    const body = await readJson(response);
    expect(response.status).toBe(403);
    expect(body?.error?.code).toBe("FORBIDDEN");
    expect(mockDb.__mutationState.deleteCalls).toHaveLength(0);
  });

  it("allows admin to delete comment even when path is restricted", async () => {
    getUserFromRequestMock.mockResolvedValue({ userId: "admin-1", isAdmin: true });
    checkPathPermissionsMock.mockResolvedValue({
      allowed: false,
      deniedPaths: ["secure/config.yml"],
      reason: "Insufficient permissions for paths: secure/config.yml",
    });

    const response = await deleteCommentDelete({
      params: { owner: "owner-1", repo: "demo", number: "42", commentId: "comment-1" },
      request: new Request("http://localhost/api/repos/owner-1/demo/pulls/42/comments/comment-1", {
        method: "DELETE",
      }),
    } as any);

    const body = await readJson(response);
    expect(response.status).toBe(200);
    expect(body?.success).toBe(true);
    expect(mockDb.__mutationState.deleteCalls).toHaveLength(1);
  });

  it("requires commentId for comment mutation routes", async () => {
    const response = await updateCommentPatch({
      params: { owner: "owner-1", repo: "demo", number: "42" },
      request: new Request("http://localhost/api/repos/owner-1/demo/pulls/42/comments", {
        method: "PATCH",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ body: "updated" }),
      }),
    } as any);

    const body = await readJson(response);
    expect(response.status).toBe(400);
    expect(body?.error?.code).toBe("BAD_REQUEST");
  });
});