@app-vitals/agent-admin 1.110.0 → 1.111.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/openapi.json +0 -193
- package/openapi.platform.json +1 -238
- package/package.json +2 -2
- package/src/admin-boot.ts +6 -5
- package/src/admin-ui-github-identity-pages.ts +35 -139
- package/src/admin-ui-github-identity-pages.unit.test.ts +50 -173
- package/src/admin-ui-github-identity.smoke.test.ts +103 -63
- package/src/admin-ui-installation-repos-pages.ts +2 -23
- package/src/admin-ui-installation-repos-pages.unit.test.ts +41 -36
- package/src/admin-ui-installation-repos.smoke.test.ts +9 -8
- package/src/admin-ui-pages.ts +4 -5
- package/src/admin-ui.ts +51 -36
- package/src/agents-api.smoke.test.ts +26 -315
- package/src/agents-api.ts +1 -107
- package/src/github-access-preview.ts +2 -2
- package/src/github-enterprise-api.smoke.test.ts +26 -0
- package/src/github-enterprise-api.ts +18 -2
- package/src/github-enterprise-client.integration.test.ts +0 -41
- package/src/github-enterprise-client.ts +0 -25
- package/src/github-enterprise-client.unit.test.ts +0 -18
- package/src/github-installation-wiring.ts +18 -12
- package/src/github-sync-all-repos.unit.test.ts +116 -0
- package/src/github-sync-snapshot-refresh.integration.test.ts +168 -0
- package/src/github-sync-snapshot-refresh.unit.test.ts +144 -0
- package/src/github-sync.ts +103 -137
- package/src/github-sync.unit.test.ts +82 -1
- package/src/installation-ports.ts +1 -40
- package/src/reconcile-open-work.integration.test.ts +0 -1
- package/src/github-access-preview.integration.test.ts +0 -399
- package/src/github-sync-switch.integration.test.ts +0 -297
- package/src/github-sync-switch.unit.test.ts +0 -467
|
@@ -1,399 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* admin/src/github-access-preview.integration.test.ts
|
|
3
|
-
* Integration tests for GET /agents/:id/github-access (GHE-2.4): the full
|
|
4
|
-
* route against a real PostgreSQL DB (agents + stored enterprise Apps) and the
|
|
5
|
-
* GHE-1.2 / GHE-2.2 cassettes, replayed through an injected fetchFn.
|
|
6
|
-
*
|
|
7
|
-
* Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";
|
|
11
|
-
import { generateKeyPairSync } from "node:crypto";
|
|
12
|
-
import { readFileSync } from "node:fs";
|
|
13
|
-
import { sign } from "hono/jwt";
|
|
14
|
-
import type { PrismaClient } from "../prisma/client/client.ts";
|
|
15
|
-
import { AgentChatTokenService } from "./agent-chat-tokens.ts";
|
|
16
|
-
import { AgentCronJobService } from "./agent-cron-jobs.ts";
|
|
17
|
-
import { AgentCronRunStatsService } from "./agent-cron-run-stats.ts";
|
|
18
|
-
import { AgentCronRunService } from "./agent-cron-runs.ts";
|
|
19
|
-
import { AgentEnvService } from "./agent-envs.ts";
|
|
20
|
-
import { AgentGitHubInstallationsService } from "./agent-github-installations.ts";
|
|
21
|
-
import { AgentMemberService } from "./agent-members.ts";
|
|
22
|
-
import { AgentPluginService } from "./agent-plugins.ts";
|
|
23
|
-
import { NoopAgentProvisioner } from "./agent-provisioner.ts";
|
|
24
|
-
import { AgentTokenService } from "./agent-tokens.ts";
|
|
25
|
-
import { AgentToolService } from "./agent-tools.ts";
|
|
26
|
-
import { AgentService } from "./agents.ts";
|
|
27
|
-
import type { AdminDeps } from "./agents-api.ts";
|
|
28
|
-
import { createAdminApp } from "./agents-api.ts";
|
|
29
|
-
import { NoopChatServiceProvisioningClient } from "./chat-service-provisioning-client.ts";
|
|
30
|
-
import { createGithubAccessPreview } from "./github-enterprise-api.ts";
|
|
31
|
-
import { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
|
|
32
|
-
import { createAdminPrismaClient } from "./prisma-client.ts";
|
|
33
|
-
import type {
|
|
34
|
-
SpecialtyType,
|
|
35
|
-
SpecialtyTypeResolver,
|
|
36
|
-
} from "./specialty-types.ts";
|
|
37
|
-
import { makeStrictTokenCrypto, makeTokenCrypto } from "./token-crypto.ts";
|
|
38
|
-
|
|
39
|
-
const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
|
|
40
|
-
const describeOrSkip = TEST_DB ? describe : describe.skip;
|
|
41
|
-
|
|
42
|
-
const SESSION_SECRET = "test-admin-session-secret-32-bytes!";
|
|
43
|
-
const REAL_KEY =
|
|
44
|
-
"0000000000000000000000000000000000000000000000000000000000000001";
|
|
45
|
-
|
|
46
|
-
async function makeSessionCookie(): Promise<string> {
|
|
47
|
-
return sign(
|
|
48
|
-
{
|
|
49
|
-
isAdmin: true,
|
|
50
|
-
userId: "user-123",
|
|
51
|
-
email: "admin@example.com",
|
|
52
|
-
name: "Admin User",
|
|
53
|
-
iat: Math.floor(Date.now() / 1000),
|
|
54
|
-
exp: Math.floor(Date.now() / 1000) + 3600,
|
|
55
|
-
},
|
|
56
|
-
SESSION_SECRET,
|
|
57
|
-
"HS256",
|
|
58
|
-
);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
function makePrisma(): PrismaClient {
|
|
62
|
-
// TEST_DB is guaranteed set — the describe block is skipped otherwise.
|
|
63
|
-
return createAdminPrismaClient(TEST_DB as string);
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
const CODING_TYPE: SpecialtyType = {
|
|
67
|
-
name: "coding",
|
|
68
|
-
displayName: "Coding Agent",
|
|
69
|
-
templatesDir: "workspace/",
|
|
70
|
-
tools: ["Read", "Write", "Edit"],
|
|
71
|
-
requiredEnv: [],
|
|
72
|
-
};
|
|
73
|
-
|
|
74
|
-
function fakeSpecialtyTypes(): SpecialtyTypeResolver {
|
|
75
|
-
const byType: Record<string, SpecialtyType> = { coding: CODING_TYPE };
|
|
76
|
-
return {
|
|
77
|
-
getType(specialty: string): SpecialtyType {
|
|
78
|
-
return byType[specialty] ?? (byType.coding as SpecialtyType);
|
|
79
|
-
},
|
|
80
|
-
tryGetType(specialty: string): SpecialtyType | undefined {
|
|
81
|
-
return byType[specialty];
|
|
82
|
-
},
|
|
83
|
-
listTypes() {
|
|
84
|
-
return Object.entries(byType).map(([name, manifest]) => ({
|
|
85
|
-
name,
|
|
86
|
-
displayName: manifest.displayName,
|
|
87
|
-
}));
|
|
88
|
-
},
|
|
89
|
-
};
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
function makeDeps(prisma: PrismaClient): AdminDeps {
|
|
93
|
-
const savedKey = process.env.SHIPWRIGHT_ENCRYPTION_KEY;
|
|
94
|
-
process.env.SHIPWRIGHT_ENCRYPTION_KEY = REAL_KEY;
|
|
95
|
-
const crypto = makeTokenCrypto();
|
|
96
|
-
if (savedKey === undefined) {
|
|
97
|
-
delete process.env.SHIPWRIGHT_ENCRYPTION_KEY;
|
|
98
|
-
} else {
|
|
99
|
-
process.env.SHIPWRIGHT_ENCRYPTION_KEY = savedKey;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
return {
|
|
103
|
-
agentService: new AgentService(prisma),
|
|
104
|
-
agentEnvService: new AgentEnvService(prisma, crypto),
|
|
105
|
-
agentCronJobService: new AgentCronJobService(prisma),
|
|
106
|
-
agentCronRunService: new AgentCronRunService(prisma),
|
|
107
|
-
agentCronRunStatsService: new AgentCronRunStatsService(prisma),
|
|
108
|
-
agentToolService: new AgentToolService(prisma),
|
|
109
|
-
agentTokenService: new AgentTokenService(prisma),
|
|
110
|
-
agentPluginService: new AgentPluginService(prisma),
|
|
111
|
-
agentMemberService: new AgentMemberService(prisma),
|
|
112
|
-
specialtyRegistry: fakeSpecialtyTypes(),
|
|
113
|
-
agentChatTokenService: new AgentChatTokenService(prisma),
|
|
114
|
-
agentGitHubInstallationsService: new AgentGitHubInstallationsService(
|
|
115
|
-
prisma,
|
|
116
|
-
),
|
|
117
|
-
prisma,
|
|
118
|
-
provisioner: new NoopAgentProvisioner(),
|
|
119
|
-
serviceIntegrations: [
|
|
120
|
-
{
|
|
121
|
-
name: "task-store",
|
|
122
|
-
listTokensForAgent: async () => [],
|
|
123
|
-
revokeToken: async () => {},
|
|
124
|
-
},
|
|
125
|
-
],
|
|
126
|
-
chatService: new NoopChatServiceProvisioningClient(),
|
|
127
|
-
slack: {
|
|
128
|
-
deleteApp: async () => {},
|
|
129
|
-
},
|
|
130
|
-
decrypt: (value: string) => crypto.decrypt(value),
|
|
131
|
-
sessionSecret: SESSION_SECRET,
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
type Cassette = Record<
|
|
136
|
-
string,
|
|
137
|
-
{ status: number; headers?: Record<string, string>; body: unknown }
|
|
138
|
-
>;
|
|
139
|
-
const load = (f: string): Cassette =>
|
|
140
|
-
JSON.parse(
|
|
141
|
-
readFileSync(new URL(`./fixtures/${f}`, import.meta.url).pathname, "utf-8"),
|
|
142
|
-
);
|
|
143
|
-
const enterprise = load("github-enterprise-cassette.json");
|
|
144
|
-
const lookup = load("github-lookup-cassette.json");
|
|
145
|
-
|
|
146
|
-
const { privateKey: PEM } = generateKeyPairSync("rsa", {
|
|
147
|
-
modulusLength: 2048,
|
|
148
|
-
privateKeyEncoding: { type: "pkcs8", format: "pem" },
|
|
149
|
-
publicKeyEncoding: { type: "spki", format: "pem" },
|
|
150
|
-
});
|
|
151
|
-
const PEM_BODY = PEM.split("\n")[1] as string;
|
|
152
|
-
const ENC_KEY = "c".repeat(64);
|
|
153
|
-
const NOW = new Date("2026-11-09T12:00:00Z");
|
|
154
|
-
|
|
155
|
-
/** route -> [cassette, entry]. org-1 has the lookup App, org-2 does not. */
|
|
156
|
-
const ROUTES: Record<string, [Cassette, string]> = {
|
|
157
|
-
"GET /enterprises/acme/installation": [
|
|
158
|
-
enterprise,
|
|
159
|
-
"enterprise_installation_success",
|
|
160
|
-
],
|
|
161
|
-
"POST /app/installations/4242/access_tokens": [
|
|
162
|
-
enterprise,
|
|
163
|
-
"access_token_success",
|
|
164
|
-
],
|
|
165
|
-
"GET /enterprises/acme/apps/installable_organizations": [
|
|
166
|
-
enterprise,
|
|
167
|
-
"installable_orgs_success",
|
|
168
|
-
],
|
|
169
|
-
"GET /app/installations": [
|
|
170
|
-
{
|
|
171
|
-
lookup_only_installations: {
|
|
172
|
-
status: 200,
|
|
173
|
-
body: [{ id: 7001, account: { login: "org-1", type: "Organization" } }],
|
|
174
|
-
},
|
|
175
|
-
},
|
|
176
|
-
"lookup_only_installations",
|
|
177
|
-
],
|
|
178
|
-
"GET /orgs/org-1/installation": [lookup, "org_installation_success"],
|
|
179
|
-
"GET /orgs/org-2/installation": [lookup, "org_installation_404"],
|
|
180
|
-
"POST /app/installations/7001/access_tokens": [
|
|
181
|
-
lookup,
|
|
182
|
-
"lookup_token_success",
|
|
183
|
-
],
|
|
184
|
-
"GET /installation/repositories": [lookup, "repos_success"],
|
|
185
|
-
"GET /users/octocat": [lookup, "user_success"],
|
|
186
|
-
"GET /repos/org-1/api/collaborators/octocat/permission": [
|
|
187
|
-
lookup,
|
|
188
|
-
"permission_maintain",
|
|
189
|
-
],
|
|
190
|
-
"GET /repos/org-1/web/collaborators/octocat/permission": [
|
|
191
|
-
lookup,
|
|
192
|
-
"permission_triage",
|
|
193
|
-
],
|
|
194
|
-
};
|
|
195
|
-
|
|
196
|
-
describeOrSkip("GET /agents/:id/github-access (integration)", () => {
|
|
197
|
-
let prisma: PrismaClient;
|
|
198
|
-
let cookie: string;
|
|
199
|
-
let calls: string[];
|
|
200
|
-
let logs: string[];
|
|
201
|
-
|
|
202
|
-
beforeEach(async () => {
|
|
203
|
-
prisma = makePrisma();
|
|
204
|
-
await prisma.gitHubEnterpriseApp.deleteMany();
|
|
205
|
-
await prisma.agentWorkQueueSnapshot.deleteMany();
|
|
206
|
-
await prisma.agentPlugin.deleteMany();
|
|
207
|
-
await prisma.agentToken.deleteMany();
|
|
208
|
-
await prisma.agentCronJob.deleteMany();
|
|
209
|
-
await prisma.agentTool.deleteMany();
|
|
210
|
-
await prisma.agentEnv.deleteMany();
|
|
211
|
-
await prisma.agentMember.deleteMany();
|
|
212
|
-
await prisma.agent.deleteMany();
|
|
213
|
-
cookie = await makeSessionCookie();
|
|
214
|
-
calls = [];
|
|
215
|
-
logs = [];
|
|
216
|
-
});
|
|
217
|
-
|
|
218
|
-
afterEach(async () => {
|
|
219
|
-
await prisma.$disconnect();
|
|
220
|
-
});
|
|
221
|
-
|
|
222
|
-
const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
223
|
-
const u = new URL(input.toString());
|
|
224
|
-
const key = `${init?.method ?? "GET"} ${u.pathname}`;
|
|
225
|
-
calls.push(key);
|
|
226
|
-
const hit = ROUTES[key];
|
|
227
|
-
if (!hit) throw new Error(`no route for ${key}`);
|
|
228
|
-
const e = hit[0][hit[1]];
|
|
229
|
-
return new Response(JSON.stringify(e?.body), {
|
|
230
|
-
status: e?.status,
|
|
231
|
-
headers: { "Content-Type": "application/json", ...(e?.headers ?? {}) },
|
|
232
|
-
});
|
|
233
|
-
}) as typeof fetch;
|
|
234
|
-
|
|
235
|
-
async function seedApps() {
|
|
236
|
-
const svc = new GitHubEnterpriseAppService(
|
|
237
|
-
prisma,
|
|
238
|
-
makeStrictTokenCrypto(ENC_KEY),
|
|
239
|
-
);
|
|
240
|
-
await svc.save({
|
|
241
|
-
role: "installer",
|
|
242
|
-
appId: "12345",
|
|
243
|
-
slug: "example-installer",
|
|
244
|
-
enterpriseSlug: "acme",
|
|
245
|
-
privateKey: PEM,
|
|
246
|
-
});
|
|
247
|
-
await svc.save({
|
|
248
|
-
role: "lookup",
|
|
249
|
-
appId: "555",
|
|
250
|
-
slug: "example-lookup",
|
|
251
|
-
enterpriseSlug: null,
|
|
252
|
-
privateKey: PEM,
|
|
253
|
-
});
|
|
254
|
-
return svc;
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
function build(appService: GitHubEnterpriseAppService) {
|
|
258
|
-
return createAdminApp({
|
|
259
|
-
...makeDeps(prisma),
|
|
260
|
-
githubAccessPreview: createGithubAccessPreview({
|
|
261
|
-
appService,
|
|
262
|
-
fetchFn,
|
|
263
|
-
apiBase: "https://ghe.test",
|
|
264
|
-
now: () => NOW,
|
|
265
|
-
}),
|
|
266
|
-
});
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
const get = (app: ReturnType<typeof build>, id: string) =>
|
|
270
|
-
app.request(`/agents/${id}/github-access`, {
|
|
271
|
-
headers: { Cookie: `admin_session=${cookie}` },
|
|
272
|
-
});
|
|
273
|
-
|
|
274
|
-
const svcNoApps = () =>
|
|
275
|
-
new GitHubEnterpriseAppService(prisma, makeStrictTokenCrypto(ENC_KEY));
|
|
276
|
-
|
|
277
|
-
it("returns the resolver output per org, with no key material anywhere", async () => {
|
|
278
|
-
const agent = await prisma.agent.create({
|
|
279
|
-
data: { name: "A", githubUsername: "octocat" },
|
|
280
|
-
});
|
|
281
|
-
const app = build(await seedApps());
|
|
282
|
-
const spies = (["log", "info", "warn", "error"] as const).map((m) =>
|
|
283
|
-
spyOn(console, m).mockImplementation((...a) => {
|
|
284
|
-
logs.push(a.map(String).join(" "));
|
|
285
|
-
}),
|
|
286
|
-
);
|
|
287
|
-
try {
|
|
288
|
-
const res = await get(app, agent.id);
|
|
289
|
-
expect(res.status).toBe(200);
|
|
290
|
-
const text = await res.text();
|
|
291
|
-
const json = JSON.parse(text);
|
|
292
|
-
expect(json.status).toBe("ok");
|
|
293
|
-
expect(json.access.complete).toBe(false); // org-2 has no lookup App
|
|
294
|
-
expect(json.access.orgs).toEqual([
|
|
295
|
-
{
|
|
296
|
-
org: "org-1",
|
|
297
|
-
status: "ok",
|
|
298
|
-
repos: [
|
|
299
|
-
{ fullName: "acme-eng/api", level: "maintain", canPush: true },
|
|
300
|
-
{ fullName: "acme-eng/web", level: "triage", canPush: false },
|
|
301
|
-
],
|
|
302
|
-
unresolved: 0,
|
|
303
|
-
},
|
|
304
|
-
{
|
|
305
|
-
org: "org-2",
|
|
306
|
-
status: "lookup_app_not_installed",
|
|
307
|
-
repos: [],
|
|
308
|
-
unresolved: 0,
|
|
309
|
-
},
|
|
310
|
-
]);
|
|
311
|
-
for (const out of [text, ...logs]) {
|
|
312
|
-
expect(out).not.toContain(PEM_BODY);
|
|
313
|
-
expect(out).not.toContain("BEGIN");
|
|
314
|
-
expect(out).not.toMatch(/ghs_|"token"/);
|
|
315
|
-
}
|
|
316
|
-
} finally {
|
|
317
|
-
for (const s of spies) s.mockRestore();
|
|
318
|
-
}
|
|
319
|
-
});
|
|
320
|
-
|
|
321
|
-
it("unconfigured: 200 status and no GitHub call", async () => {
|
|
322
|
-
const agent = await prisma.agent.create({
|
|
323
|
-
data: { name: "A", githubUsername: "octocat" },
|
|
324
|
-
});
|
|
325
|
-
const res = await get(build(svcNoApps()), agent.id);
|
|
326
|
-
expect(res.status).toBe(200);
|
|
327
|
-
expect(await res.json()).toEqual({ status: "unconfigured" });
|
|
328
|
-
expect(calls).toEqual([]);
|
|
329
|
-
});
|
|
330
|
-
|
|
331
|
-
it("only the installer configured is still unconfigured", async () => {
|
|
332
|
-
const agent = await prisma.agent.create({
|
|
333
|
-
data: { name: "A", githubUsername: "octocat" },
|
|
334
|
-
});
|
|
335
|
-
const svc = svcNoApps();
|
|
336
|
-
await svc.save({
|
|
337
|
-
role: "installer",
|
|
338
|
-
appId: "12345",
|
|
339
|
-
slug: "example-installer",
|
|
340
|
-
enterpriseSlug: "acme",
|
|
341
|
-
privateKey: PEM,
|
|
342
|
-
});
|
|
343
|
-
const res = await get(build(svc), agent.id);
|
|
344
|
-
expect(await res.json()).toEqual({ status: "unconfigured" });
|
|
345
|
-
expect(calls).toEqual([]);
|
|
346
|
-
});
|
|
347
|
-
|
|
348
|
-
it("only the lookup App configured resolves through its own installations", async () => {
|
|
349
|
-
const agent = await prisma.agent.create({
|
|
350
|
-
data: { name: "A", githubUsername: "octocat" },
|
|
351
|
-
});
|
|
352
|
-
const svc = svcNoApps();
|
|
353
|
-
await svc.save({
|
|
354
|
-
role: "lookup",
|
|
355
|
-
appId: "555",
|
|
356
|
-
slug: "example-lookup",
|
|
357
|
-
enterpriseSlug: null,
|
|
358
|
-
privateKey: PEM,
|
|
359
|
-
});
|
|
360
|
-
const res = await get(build(svc), agent.id);
|
|
361
|
-
const json = (await res.json()) as {
|
|
362
|
-
status: string;
|
|
363
|
-
access: { orgs: { org: string; status: string }[] };
|
|
364
|
-
};
|
|
365
|
-
expect(json.status).toBe("ok");
|
|
366
|
-
expect(json.access.orgs.map((o) => [o.org, o.status])).toEqual([
|
|
367
|
-
["org-1", "ok"],
|
|
368
|
-
]);
|
|
369
|
-
expect(calls).not.toContain(
|
|
370
|
-
"GET /enterprises/acme/apps/installable_organizations",
|
|
371
|
-
);
|
|
372
|
-
});
|
|
373
|
-
|
|
374
|
-
it("user_not_found when the user does not exist on GitHub", async () => {
|
|
375
|
-
const agent = await prisma.agent.create({
|
|
376
|
-
data: { name: "A", githubUsername: "octocat" },
|
|
377
|
-
});
|
|
378
|
-
const saved = ROUTES["GET /users/octocat"];
|
|
379
|
-
ROUTES["GET /users/octocat"] = [lookup, "user_nonexistent"];
|
|
380
|
-
try {
|
|
381
|
-
const res = await get(build(await seedApps()), agent.id);
|
|
382
|
-
expect(res.status).toBe(200);
|
|
383
|
-
const json = await res.json();
|
|
384
|
-
expect(json.status).toBe("user_not_found");
|
|
385
|
-
expect(json.access.orgs).toEqual([]);
|
|
386
|
-
expect(calls.some((c) => c.includes("/permission"))).toBe(false);
|
|
387
|
-
} finally {
|
|
388
|
-
ROUTES["GET /users/octocat"] = saved as [Cassette, string];
|
|
389
|
-
}
|
|
390
|
-
});
|
|
391
|
-
|
|
392
|
-
it("404 for an unknown agent and 422 for an unbound one", async () => {
|
|
393
|
-
const unbound = await prisma.agent.create({ data: { name: "U" } });
|
|
394
|
-
const app = build(await seedApps());
|
|
395
|
-
expect((await get(app, "no-such-agent")).status).toBe(404);
|
|
396
|
-
expect((await get(app, unbound.id)).status).toBe(422);
|
|
397
|
-
expect(calls).toEqual([]);
|
|
398
|
-
});
|
|
399
|
-
});
|
|
@@ -1,297 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* admin/src/github-sync-switch.integration.test.ts
|
|
3
|
-
* GIS-1.2: apply ordering for an "all" installation against the recorded
|
|
4
|
-
* enterprise cassette (real GithubEnterpriseClient, fetch replaced by the
|
|
5
|
-
* recording) with the real cache and a real GitHubReconcileAudit row.
|
|
6
|
-
*
|
|
7
|
-
* Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
|
|
11
|
-
import { generateKeyPairSync } from "node:crypto";
|
|
12
|
-
import { readFileSync } from "node:fs";
|
|
13
|
-
import type { PrismaClient } from "../prisma/client/client.ts";
|
|
14
|
-
import { GithubSyncService } from "./github-sync.ts";
|
|
15
|
-
import { lazyInstallerClient } from "./github-installation-wiring.ts";
|
|
16
|
-
import { GitHubRepoCacheService } from "./github-repo-cache.ts";
|
|
17
|
-
import { DEPLOYMENT_WIDE_ACCOUNT_KEY } from "./github-agent-installation-crawler.ts";
|
|
18
|
-
import {
|
|
19
|
-
createInstallationPort,
|
|
20
|
-
PrismaInstallationAudit,
|
|
21
|
-
} from "./installation-ports.ts";
|
|
22
|
-
import { createInstallationReposPort } from "./installation-repos-service.ts";
|
|
23
|
-
import { createAdminPrismaClient } from "./prisma-client.ts";
|
|
24
|
-
|
|
25
|
-
const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
|
|
26
|
-
const describeOrSkip = TEST_DB ? describe : describe.skip;
|
|
27
|
-
|
|
28
|
-
const { privateKey: PEM } = generateKeyPairSync("rsa", {
|
|
29
|
-
modulusLength: 2048,
|
|
30
|
-
privateKeyEncoding: { type: "pkcs8", format: "pem" },
|
|
31
|
-
publicKeyEncoding: { type: "spki", format: "pem" },
|
|
32
|
-
});
|
|
33
|
-
const cassette = JSON.parse(
|
|
34
|
-
readFileSync(
|
|
35
|
-
new URL("./fixtures/github-enterprise-cassette.json", import.meta.url)
|
|
36
|
-
.pathname,
|
|
37
|
-
"utf-8",
|
|
38
|
-
),
|
|
39
|
-
) as Record<string, { status: number; body: unknown }>;
|
|
40
|
-
|
|
41
|
-
const INST = "/enterprises/acme/apps/organizations/acme-eng/installations";
|
|
42
|
-
const APP_ID = 777;
|
|
43
|
-
const AGENT_ID = "gis-it-agent";
|
|
44
|
-
const ORG = "acme-eng";
|
|
45
|
-
const REPOS = ["acme-eng/repo-1", "acme-eng/repo-2"];
|
|
46
|
-
|
|
47
|
-
function routeTable(selection: string): Record<string, string> {
|
|
48
|
-
return {
|
|
49
|
-
"GET /enterprises/acme/installation": "enterprise_installation_success",
|
|
50
|
-
"POST /app/installations/4242/access_tokens": "access_token_success",
|
|
51
|
-
[`GET ${INST}`]: selection,
|
|
52
|
-
[`GET ${INST}/501/repositories`]: "install_repos_success",
|
|
53
|
-
[`PATCH ${INST}/501/repositories`]: "install_selection_success",
|
|
54
|
-
[`PATCH ${INST}/501/repositories/add`]: "install_repos_add_success",
|
|
55
|
-
[`PATCH ${INST}/501/repositories/remove`]: "install_repos_remove_success",
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
describeOrSkip("GitHub Sync all-to-selected switch (integration)", () => {
|
|
60
|
-
let prisma: PrismaClient;
|
|
61
|
-
let cache: GitHubRepoCacheService;
|
|
62
|
-
const checkedAt = new Date(Date.now() - 60_000);
|
|
63
|
-
|
|
64
|
-
const clean = async () => {
|
|
65
|
-
await prisma.gitHubReconcileAudit.deleteMany({
|
|
66
|
-
where: { agentId: AGENT_ID },
|
|
67
|
-
});
|
|
68
|
-
await prisma.gitHubRepoAccess.deleteMany({
|
|
69
|
-
where: { accountId: DEPLOYMENT_WIDE_ACCOUNT_KEY, org: ORG },
|
|
70
|
-
});
|
|
71
|
-
await prisma.gitHubCachedRepo.deleteMany();
|
|
72
|
-
await prisma.gitHubRepoSnapshot.deleteMany();
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
async function seed(selection: "all" | "selected", repos: string[]) {
|
|
76
|
-
const key = {
|
|
77
|
-
accountId: DEPLOYMENT_WIDE_ACCOUNT_KEY,
|
|
78
|
-
appKind: "agent" as const,
|
|
79
|
-
appRef: String(APP_ID),
|
|
80
|
-
org: ORG,
|
|
81
|
-
};
|
|
82
|
-
const snap = await cache.upsertSnapshot(key, {
|
|
83
|
-
completedAt: checkedAt,
|
|
84
|
-
totalCount: repos.length,
|
|
85
|
-
repositorySelection: selection,
|
|
86
|
-
lastError: null,
|
|
87
|
-
});
|
|
88
|
-
await cache.upsertRepos(
|
|
89
|
-
snap.id,
|
|
90
|
-
repos.map((fullName, i) => ({ githubId: i + 1, fullName })),
|
|
91
|
-
checkedAt,
|
|
92
|
-
);
|
|
93
|
-
for (const full of REPOS) {
|
|
94
|
-
await prisma.gitHubRepoAccess.upsert({
|
|
95
|
-
where: {
|
|
96
|
-
accountId_org_repo_username: {
|
|
97
|
-
accountId: DEPLOYMENT_WIDE_ACCOUNT_KEY,
|
|
98
|
-
org: ORG,
|
|
99
|
-
repo: full.split("/")[1] as string,
|
|
100
|
-
username: "dev",
|
|
101
|
-
},
|
|
102
|
-
},
|
|
103
|
-
create: {
|
|
104
|
-
accountId: DEPLOYMENT_WIDE_ACCOUNT_KEY,
|
|
105
|
-
org: ORG,
|
|
106
|
-
repo: full.split("/")[1] as string,
|
|
107
|
-
username: "dev",
|
|
108
|
-
canPush: full === "acme-eng/repo-1",
|
|
109
|
-
level: full === "acme-eng/repo-1" ? "write" : "read",
|
|
110
|
-
checkedAt,
|
|
111
|
-
status: "ok",
|
|
112
|
-
},
|
|
113
|
-
update: {},
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
function service(requests: string[], patchBodies: unknown[]) {
|
|
119
|
-
// The installation's repo list follows a landed selection switch.
|
|
120
|
-
let installed = [...REPOS];
|
|
121
|
-
const table = routeTable("org_installations_success");
|
|
122
|
-
const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
123
|
-
const u = new URL(input.toString());
|
|
124
|
-
const key = `${init?.method ?? "GET"} ${u.pathname}`;
|
|
125
|
-
if (key === "GET /enterprises/acme/apps/installable_organizations") {
|
|
126
|
-
return new Response(JSON.stringify([{ id: 5010, login: ORG }]), {
|
|
127
|
-
status: 200,
|
|
128
|
-
});
|
|
129
|
-
}
|
|
130
|
-
const name = table[key];
|
|
131
|
-
if (!name) throw new Error(`no route for ${key}`);
|
|
132
|
-
if (key.startsWith("PATCH") || key.startsWith("DELETE")) {
|
|
133
|
-
requests.push(key);
|
|
134
|
-
patchBodies.push(JSON.parse(String(init?.body ?? "{}")));
|
|
135
|
-
}
|
|
136
|
-
const entry = cassette[name];
|
|
137
|
-
if (!entry) throw new Error(`no cassette entry ${name}`);
|
|
138
|
-
if (key === `GET ${INST}/501/repositories`) {
|
|
139
|
-
return new Response(
|
|
140
|
-
JSON.stringify(
|
|
141
|
-
installed.map((full_name, i) => ({
|
|
142
|
-
id: i + 1,
|
|
143
|
-
name: full_name.split("/")[1],
|
|
144
|
-
full_name,
|
|
145
|
-
})),
|
|
146
|
-
),
|
|
147
|
-
{ status: 200, headers: { "Content-Type": "application/json" } },
|
|
148
|
-
);
|
|
149
|
-
}
|
|
150
|
-
if (key === `PATCH ${INST}/501/repositories` && entry.status === 200) {
|
|
151
|
-
installed = (
|
|
152
|
-
patchBodies.at(-1) as { repositories: string[] }
|
|
153
|
-
).repositories.map((n) => `${ORG}/${n}`);
|
|
154
|
-
}
|
|
155
|
-
return new Response(JSON.stringify(entry.body), {
|
|
156
|
-
status: entry.status,
|
|
157
|
-
headers: { "Content-Type": "application/json" },
|
|
158
|
-
});
|
|
159
|
-
}) as typeof fetch;
|
|
160
|
-
const client = lazyInstallerClient({
|
|
161
|
-
appService: {
|
|
162
|
-
get: async () => ({ appId: 12345, enterpriseSlug: "acme" }) as never,
|
|
163
|
-
getPrivateKey: async () => PEM,
|
|
164
|
-
},
|
|
165
|
-
fetchFn,
|
|
166
|
-
});
|
|
167
|
-
let repos = ["acme-eng/repo-2"];
|
|
168
|
-
return new GithubSyncService({
|
|
169
|
-
agents: {
|
|
170
|
-
get: async () => ({
|
|
171
|
-
id: AGENT_ID,
|
|
172
|
-
githubUsername: "dev",
|
|
173
|
-
appId: APP_ID,
|
|
174
|
-
repos,
|
|
175
|
-
}),
|
|
176
|
-
setRepos: async (_id, next) => {
|
|
177
|
-
requests.push("setRepos");
|
|
178
|
-
repos = next;
|
|
179
|
-
},
|
|
180
|
-
},
|
|
181
|
-
access: async () => {
|
|
182
|
-
throw new Error("live resolver must not be used");
|
|
183
|
-
},
|
|
184
|
-
cache,
|
|
185
|
-
lookupRepos: async () => [
|
|
186
|
-
{ org: ORG, completedAt: checkedAt, repos: REPOS },
|
|
187
|
-
],
|
|
188
|
-
verifyPush: async (_u, repo) => repo === "acme-eng/repo-1",
|
|
189
|
-
installation: createInstallationReposPort(
|
|
190
|
-
createInstallationPort(client),
|
|
191
|
-
client,
|
|
192
|
-
),
|
|
193
|
-
audit: new PrismaInstallationAudit(prisma),
|
|
194
|
-
});
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
beforeEach(async () => {
|
|
198
|
-
prisma = createAdminPrismaClient(TEST_DB as string);
|
|
199
|
-
cache = new GitHubRepoCacheService(prisma);
|
|
200
|
-
await clean();
|
|
201
|
-
});
|
|
202
|
-
afterEach(async () => {
|
|
203
|
-
await clean();
|
|
204
|
-
await prisma.$disconnect();
|
|
205
|
-
});
|
|
206
|
-
|
|
207
|
-
it("switches first, folds the removal, writes the audit row; a later preview has nothing to do", async () => {
|
|
208
|
-
await seed("all", REPOS);
|
|
209
|
-
const requests: string[] = [];
|
|
210
|
-
const bodies: unknown[] = [];
|
|
211
|
-
const svc = service(requests, bodies);
|
|
212
|
-
|
|
213
|
-
const before = await svc.preview(AGENT_ID);
|
|
214
|
-
if (before.status !== "previewed") throw new Error(before.status);
|
|
215
|
-
expect(before.plan.selectionSwitches).toEqual([
|
|
216
|
-
{ org: ORG, repos: ["acme-eng/repo-1"] },
|
|
217
|
-
]);
|
|
218
|
-
expect(before.plan.appRemoves).toEqual(["acme-eng/repo-2"]);
|
|
219
|
-
expect(requests).toEqual([]);
|
|
220
|
-
|
|
221
|
-
const r = await svc.apply({
|
|
222
|
-
agentId: AGENT_ID,
|
|
223
|
-
caller: "root",
|
|
224
|
-
appAdds: [],
|
|
225
|
-
appRemoves: ["acme-eng/repo-2"],
|
|
226
|
-
agentRemoves: ["acme-eng/repo-2"],
|
|
227
|
-
});
|
|
228
|
-
expect(r.status).toBe("applied");
|
|
229
|
-
// PATCH selection (no /add or /remove: the removal is folded), then agent repos.
|
|
230
|
-
expect(requests).toEqual([`PATCH ${INST}/501/repositories`, "setRepos"]);
|
|
231
|
-
expect(bodies[0]).toEqual({
|
|
232
|
-
repository_selection: "selected",
|
|
233
|
-
repositories: ["repo-1"],
|
|
234
|
-
});
|
|
235
|
-
|
|
236
|
-
const rows = await prisma.gitHubReconcileAudit.findMany({
|
|
237
|
-
where: { agentId: AGENT_ID },
|
|
238
|
-
});
|
|
239
|
-
expect(rows).toHaveLength(1);
|
|
240
|
-
expect(rows[0]?.result).toEqual({ status: "applied" });
|
|
241
|
-
expect(rows[0]?.diff).toMatchObject({
|
|
242
|
-
installationRemoves: ["acme-eng/repo-2"],
|
|
243
|
-
configRemoves: ["acme-eng/repo-2"],
|
|
244
|
-
selectionSwitches: [{ org: ORG, repos: ["acme-eng/repo-1"] }],
|
|
245
|
-
});
|
|
246
|
-
|
|
247
|
-
// The next crawl records "selected" and the shrunk repo list.
|
|
248
|
-
await prisma.gitHubCachedRepo.deleteMany();
|
|
249
|
-
await prisma.gitHubRepoSnapshot.deleteMany();
|
|
250
|
-
await seed("selected", ["acme-eng/repo-1"]);
|
|
251
|
-
const after = await svc.preview(AGENT_ID);
|
|
252
|
-
if (after.status !== "previewed") throw new Error(after.status);
|
|
253
|
-
expect(after.plan.selectionSwitches).toEqual([]);
|
|
254
|
-
expect([
|
|
255
|
-
after.plan.appAdds,
|
|
256
|
-
after.plan.appRemoves,
|
|
257
|
-
after.plan.agentRemoves,
|
|
258
|
-
]).toEqual([[], [], []]);
|
|
259
|
-
});
|
|
260
|
-
|
|
261
|
-
it("records a failed audit row with nothing landed when GitHub answers 403", async () => {
|
|
262
|
-
await seed("all", REPOS);
|
|
263
|
-
const requests: string[] = [];
|
|
264
|
-
const svc = service(requests, []);
|
|
265
|
-
// Swap the recorded success for the recorded 403 on the PATCH.
|
|
266
|
-
const original = cassette.install_selection_success;
|
|
267
|
-
cassette.install_selection_success =
|
|
268
|
-
cassette.install_selection_403 as never;
|
|
269
|
-
try {
|
|
270
|
-
const r = await svc.apply({
|
|
271
|
-
agentId: AGENT_ID,
|
|
272
|
-
caller: "root",
|
|
273
|
-
appAdds: [],
|
|
274
|
-
appRemoves: ["acme-eng/repo-2"],
|
|
275
|
-
agentRemoves: [],
|
|
276
|
-
});
|
|
277
|
-
if (r.status !== "failed") throw new Error(r.status);
|
|
278
|
-
expect(r.error).toContain(
|
|
279
|
-
"enterprise_organization_installation_repositories",
|
|
280
|
-
);
|
|
281
|
-
} finally {
|
|
282
|
-
cassette.install_selection_success = original as never;
|
|
283
|
-
}
|
|
284
|
-
expect(requests).toEqual([`PATCH ${INST}/501/repositories`]);
|
|
285
|
-
const rows = await prisma.gitHubReconcileAudit.findMany({
|
|
286
|
-
where: { agentId: AGENT_ID },
|
|
287
|
-
});
|
|
288
|
-
expect(rows).toHaveLength(1);
|
|
289
|
-
expect(rows[0]?.result).toMatchObject({ status: "failed" });
|
|
290
|
-
expect(rows[0]?.diff).toEqual({
|
|
291
|
-
installationAdds: [],
|
|
292
|
-
installationRemoves: [],
|
|
293
|
-
configAdds: [],
|
|
294
|
-
configRemoves: [],
|
|
295
|
-
});
|
|
296
|
-
});
|
|
297
|
-
});
|