返回 CodeWhale
security-boundary-behavior.test.ts
根目录 / web / lib / security-boundary-behavior.test.ts
1 import { FakeDraftClaimLock } from "./draft-claim-lock.fake";
2 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
4 const securityMocks = vi.hoisted(() => ({
5 agentChat: vi.fn(),
6 fetchFeed: vi.fn(),
7 getAgentEnv: vi.fn(),
8 validateSession: vi.fn(),
9 }));
10
11 vi.mock("@/lib/community-agent", async (importOriginal) => {
12 const actual = await importOriginal<typeof import("./community-agent")>();
13 return {
14 ...actual,
15 agentChat: securityMocks.agentChat,
16 getAgentEnv: securityMocks.getAgentEnv,
17 validateSession: securityMocks.validateSession,
18 };
19 });
20
21 vi.mock("@/lib/github", async (importOriginal) => {
22 const actual = await importOriginal<typeof import("./github")>();
23 return {
24 ...actual,
25 fetchFeed: securityMocks.fetchFeed,
26 };
27 });
28
29 import { POST as adminPost } from "../app/api/admin/post/route";
30 import { GET as publicFeed } from "../app/api/github/feed/route";
31 import { reviewedBodyHash } from "./community-agent";
32 import { runPrReview, runTriage } from "./community-agent-tasks";
33
34 class FakeKv {
35 readonly values = new Map<string, string>();
36 readonly reads: string[] = [];
37 readonly deleted: string[] = [];
38
39 async get(key: string): Promise<string | null> {
40 this.reads.push(key);
41 return this.values.get(key) ?? null;
42 }
43
44 async put(key: string, value: string): Promise<void> {
45 this.values.set(key, value);
46 }
47
48 async list(options?: { prefix?: string; limit?: number }): Promise<{ keys: { name: string }[] }> {
49 const prefix = options?.prefix ?? "";
50 const limit = options?.limit ?? Number.POSITIVE_INFINITY;
51 return {
52 keys: [...this.values.keys()]
53 .filter((key) => key.startsWith(prefix))
54 .slice(0, limit)
55 .map((name) => ({ name })),
56 };
57 }
58
59 async delete(key: string): Promise<void> {
60 this.deleted.push(key);
61 this.values.delete(key);
62 }
63 }
64
65 function jsonResponse(value: unknown): Response {
66 return new Response(JSON.stringify(value), {
67 status: 200,
68 headers: { "content-type": "application/json" },
69 });
70 }
71
72 function inputUrl(input: string | URL | Request): string {
73 if (typeof input === "string") return input;
74 return input instanceof URL ? input.toString() : input.url;
75 }
76
77 beforeEach(() => {
78 securityMocks.agentChat.mockReset();
79 securityMocks.fetchFeed.mockReset();
80 securityMocks.getAgentEnv.mockReset();
81 securityMocks.validateSession.mockReset();
82 securityMocks.validateSession.mockResolvedValue(true);
83 });
84
85 afterEach(() => {
86 vi.unstubAllEnvs();
87 vi.unstubAllGlobals();
88 });
89
90 describe("public security boundaries", () => {
91 it("rejects a non-draft admin key before any draft KV read or delete", async () => {
92 const kv = new FakeKv();
93 kv.values.set("dispatch:latest", JSON.stringify({ state: "running" }));
94 securityMocks.getAgentEnv.mockResolvedValue({
95 CURATED_KV: kv,
96 MAINTAINER_TOKEN: "configured",
97 });
98
99 const response = await adminPost(new Request("https://codewhale.net/api/admin/post", {
100 method: "POST",
101 headers: {
102 "content-type": "application/json",
103 cookie: "mt_sid=test-session",
104 origin: "https://codewhale.net",
105 },
106 body: JSON.stringify({ action: "discard", draftKey: "dispatch:latest" }),
107 }));
108
109 await expect(response.json()).resolves.toEqual({ error: "invalid draftKey namespace" });
110 expect(response.status).toBe(400);
111 expect(securityMocks.validateSession).toHaveBeenCalledOnce();
112 expect(kv.reads).toEqual([]);
113 expect(kv.deleted).toEqual([]);
114 expect(kv.values.has("dispatch:latest")).toBe(true);
115 });
116
117 it("never forwards an ambient server token through the public feed route", async () => {
118 vi.stubEnv("GITHUB_TOKEN", "server-secret-must-not-cross-public-boundary");
119 securityMocks.fetchFeed.mockResolvedValue([]);
120
121 const response = await publicFeed();
122
123 expect(response.status).toBe(200);
124 await expect(response.json()).resolves.toMatchObject({ items: [] });
125 expect(securityMocks.fetchFeed).toHaveBeenCalledExactlyOnceWith(undefined, 50);
126 });
127
128 it("does not make another model call for unchanged triage or PR inputs", async () => {
129 securityMocks.agentChat.mockResolvedValue({
130 content: JSON.stringify({ bodyEn: "review", bodyZh: "审阅" }),
131 usage: { input: 10, output: 5 },
132 });
133
134 const triageKv = new FakeKv();
135 const triageFetch = vi.fn(async (input: string | URL | Request) => {
136 const url = inputUrl(input);
137 if (!url.includes("/issues?")) throw new Error(`unexpected triage URL: ${url}`);
138 return jsonResponse([{
139 number: 42,
140 title: "Unchanged issue",
141 body: "same body",
142 updated_at: "2020-01-01T00:00:00.000Z",
143 html_url: "https://github.com/codewhale-hq/CodeWhale/issues/42",
144 labels: [],
145 }]);
146 });
147 vi.stubGlobal("fetch", triageFetch);
148
149 const triageEnv = { CURATED_KV: triageKv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock(), DEEPSEEK_API_KEY: "test-key" };
150 await expect(runTriage(triageEnv)).resolves.toMatchObject({ processed: 1, skipped: 0 });
151 expect(securityMocks.agentChat).toHaveBeenCalledOnce();
152 securityMocks.agentChat.mockClear();
153 await expect(runTriage(triageEnv)).resolves.toMatchObject({ processed: 0, skipped: 1 });
154 expect(securityMocks.agentChat).not.toHaveBeenCalled();
155 expect(triageKv.values.has("draft:triage:42")).toBe(true);
156
157 const prKv = new FakeKv();
158 const prFetch = vi.fn(async (input: string | URL | Request) => {
159 const url = inputUrl(input);
160 if (!url.includes("/pulls?")) throw new Error(`unexpected PR URL: ${url}`);
161 return jsonResponse([{
162 number: 84,
163 title: "Unchanged PR",
164 body: "same body",
165 updated_at: "2020-01-01T00:00:00.000Z",
166 html_url: "https://github.com/codewhale-hq/CodeWhale/pull/84",
167 changed_files: 3,
168 additions: 10,
169 deletions: 2,
170 user: { login: "contributor" },
171 }]);
172 });
173 vi.stubGlobal("fetch", prFetch);
174
175 const prEnv = { CURATED_KV: prKv, DRAFT_CLAIM_LOCK: new FakeDraftClaimLock(), DEEPSEEK_API_KEY: "test-key" };
176 await expect(runPrReview(prEnv)).resolves.toMatchObject({ processed: 1, skipped: 0 });
177 expect(securityMocks.agentChat).toHaveBeenCalledOnce();
178 securityMocks.agentChat.mockClear();
179 await expect(runPrReview(prEnv)).resolves.toMatchObject({ processed: 0, skipped: 1 });
180 expect(securityMocks.agentChat).not.toHaveBeenCalled();
181 expect(prKv.values.has("draft:pr-review:84")).toBe(true);
182 });
183
184 it("posts bodyZh when lang=zh and no editedBody is supplied", async () => {
185 const draft = {
186 id: "42",
187 type: "triage",
188 targetNumber: 42,
189 bodyEn: "English body",
190 bodyZh: "中文正文",
191 generatedAt: "2026-01-01T00:00:00.000Z",
192 posted: false,
193 };
194 const kv = new FakeKv();
195 kv.values.set("draft:triage:42", JSON.stringify(draft));
196
197 const capturedBodies: string[] = [];
198 const mockFetch = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
199 const url = inputUrl(input);
200 if (url.includes("/issues/42/comments")) {
201 const reqBody = JSON.parse((init?.body as string) ?? "{}");
202 capturedBodies.push(reqBody.body);
203 return new Response(JSON.stringify({ id: 1 }), { status: 201, headers: { "content-type": "application/json" } });
204 }
205 throw new Error(`unexpected URL: ${url}`);
206 });
207 vi.stubGlobal("fetch", mockFetch);
208
209 securityMocks.getAgentEnv.mockResolvedValue({
210 CURATED_KV: kv,
211 MAINTAINER_TOKEN: "configured",
212 MAINTAINER_GITHUB_PAT: "ghp_test",
213 GITHUB_REPO: "codewhale-hq/CodeWhale",
214 });
215
216 const response = await adminPost(new Request("https://codewhale.net/api/admin/post", {
217 method: "POST",
218 headers: {
219 "content-type": "application/json",
220 cookie: "mt_sid=test-session",
221 origin: "https://codewhale.net",
222 },
223 body: JSON.stringify({
224 action: "post",
225 draftKey: "draft:triage:42",
226 lang: "zh",
227 reviewedSha256: await reviewedBodyHash("中文正文"),
228 }),
229 }));
230
231 await expect(response.json()).resolves.toMatchObject({ ok: true });
232 expect(capturedBodies).toHaveLength(1);
233 expect(capturedBodies[0]).toBe("中文正文");
234 });
235 });
236
236 lines TYPESCRIPT