@app-vitals/agent-admin 1.109.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.
Files changed (53) hide show
  1. package/openapi.json +0 -193
  2. package/openapi.platform.json +1 -238
  3. package/package.json +2 -2
  4. package/src/admin-boot.ts +6 -5
  5. package/src/admin-ui-github-enterprise-pages.ts +13 -2
  6. package/src/admin-ui-github-enterprise.smoke.test.ts +20 -1
  7. package/src/admin-ui-github-enterprise.ts +16 -1
  8. package/src/admin-ui-github-identity-pages.ts +35 -139
  9. package/src/admin-ui-github-identity-pages.unit.test.ts +50 -173
  10. package/src/admin-ui-github-identity.smoke.test.ts +103 -63
  11. package/src/admin-ui-installation-repos-pages.ts +2 -23
  12. package/src/admin-ui-installation-repos-pages.unit.test.ts +41 -36
  13. package/src/admin-ui-installation-repos.smoke.test.ts +9 -8
  14. package/src/admin-ui-pages.ts +4 -5
  15. package/src/admin-ui-slack-config-token-pages.ts +11 -2
  16. package/src/admin-ui-slack-config-token.smoke.test.ts +39 -3
  17. package/src/admin-ui-slack-config-token.ts +51 -9
  18. package/src/admin-ui-templates-pages.ts +7 -1
  19. package/src/admin-ui-templates.smoke.test.ts +31 -5
  20. package/src/admin-ui-templates.ts +43 -8
  21. package/src/admin-ui.ts +51 -36
  22. package/src/agent-templates-api.integration.test.ts +29 -7
  23. package/src/agent-templates.ts +7 -1
  24. package/src/agents-api.smoke.test.ts +26 -315
  25. package/src/agents-api.ts +1 -107
  26. package/src/deployment-wide-settings.integration.test.ts +309 -0
  27. package/src/deployment-wide-settings.ts +42 -0
  28. package/src/github-access-preview.ts +2 -2
  29. package/src/github-agent-installation-crawler.ts +18 -1
  30. package/src/github-enterprise-api.integration.test.ts +7 -0
  31. package/src/github-enterprise-api.smoke.test.ts +26 -0
  32. package/src/github-enterprise-api.ts +24 -4
  33. package/src/github-enterprise-apps.integration.test.ts +33 -8
  34. package/src/github-enterprise-apps.ts +4 -0
  35. package/src/github-enterprise-client.integration.test.ts +0 -41
  36. package/src/github-enterprise-client.ts +0 -25
  37. package/src/github-enterprise-client.unit.test.ts +0 -18
  38. package/src/github-installation-wiring.ts +48 -13
  39. package/src/github-installation-wiring.unit.test.ts +38 -1
  40. package/src/github-sync-all-repos.unit.test.ts +116 -0
  41. package/src/github-sync-cache.integration.test.ts +9 -2
  42. package/src/github-sync-snapshot-refresh.integration.test.ts +168 -0
  43. package/src/github-sync-snapshot-refresh.unit.test.ts +144 -0
  44. package/src/github-sync.ts +103 -137
  45. package/src/github-sync.unit.test.ts +82 -1
  46. package/src/installation-ports.ts +1 -40
  47. package/src/installation-repos-service.ts +7 -4
  48. package/src/reconcile-open-work.integration.test.ts +0 -1
  49. package/src/slack-config-token.integration.test.ts +19 -2
  50. package/src/slack-config-token.ts +6 -1
  51. package/src/github-access-preview.integration.test.ts +0 -399
  52. package/src/github-sync-switch.integration.test.ts +0 -297
  53. package/src/github-sync-switch.unit.test.ts +0 -467
@@ -83,17 +83,6 @@ export interface AppInstallationPort {
83
83
  repos: readonly string[],
84
84
  identity?: AppIdentity,
85
85
  ): Promise<void>;
86
- /**
87
- * Switch the installation from "all" to "selected" with exactly `repos`
88
- * (owner/repo, all in `org`, at most 50). Optional so existing
89
- * implementations stay valid.
90
- */
91
- setRepositorySelection?(
92
- appId: number,
93
- org: string,
94
- repos: readonly string[],
95
- identity?: AppIdentity,
96
- ): Promise<void>;
97
86
  }
98
87
 
99
88
  /** Repos changed by one audited change, on the installation and in the agent's config. */
@@ -102,7 +91,7 @@ export interface InstallationAuditDiff {
102
91
  installationRemoves: string[];
103
92
  configAdds: string[];
104
93
  configRemoves: string[];
105
- /** "all" installations switched to "selected", with the repos that landed. */
94
+ /** Legacy: old audit rows only; Sync no longer switches installations. Keep optional so they still read. */
106
95
  selectionSwitches?: { org: string; repos: string[] }[];
107
96
  }
108
97
 
@@ -227,13 +216,6 @@ export interface InstallationRepoClient {
227
216
  names: readonly string[],
228
217
  accountId?: string | null,
229
218
  ): Promise<unknown>;
230
- /** Optional: needed only to switch an "all" installation to "selected". */
231
- setRepositorySelection?(
232
- org: string,
233
- installationId: number,
234
- input: { repositorySelection: "selected"; repositories: readonly string[] },
235
- accountId?: string | null,
236
- ): Promise<unknown>;
237
219
  }
238
220
 
239
221
  /** The agent App has no installation on the org (distinct from a GitHub failure). */
@@ -294,7 +276,6 @@ export function createInstallationPort(
294
276
  }
295
277
  return found.id;
296
278
  };
297
- const setSelection = client.setRepositorySelection?.bind(client);
298
279
  return {
299
280
  async listRepos(appId, orgs, identity) {
300
281
  const out: Record<string, string[]> = {};
@@ -324,25 +305,5 @@ export function createInstallationPort(
324
305
  identity?.accountId,
325
306
  );
326
307
  },
327
- ...(setSelection
328
- ? {
329
- async setRepositorySelection(
330
- appId: number,
331
- org: string,
332
- repos: readonly string[],
333
- identity?: AppIdentity,
334
- ) {
335
- await setSelection(
336
- org,
337
- await installationId(appId, org, identity),
338
- {
339
- repositorySelection: "selected",
340
- repositories: repos.map(baseName),
341
- },
342
- identity?.accountId,
343
- );
344
- },
345
- }
346
- : {}),
347
308
  };
348
309
  }
@@ -311,7 +311,13 @@ export class InstallationReposService {
311
311
  const snapshots = cache
312
312
  ? await cache.listAgentSnapshots(accountId, String(agent.appId))
313
313
  : [];
314
- const username = agent.githubUsername?.trim();
314
+ const state = this.deps.appsState
315
+ ? await this.deps.appsState(agent.accountId)
316
+ : "both";
317
+ // Without a usable lookup App no access rows apply (they may be left over
318
+ // from a removed deployment-wide App).
319
+ const username =
320
+ state === "lookup_missing" ? undefined : agent.githubUsername?.trim();
315
321
  const orgs: InstallationOrgView[] = [];
316
322
  for (const s of snapshots) {
317
323
  const names = s.repos.map((r) => r.fullName);
@@ -353,9 +359,6 @@ export class InstallationReposService {
353
359
  ...(s.lastTickAt ? { lastTickAt: iso(s.lastTickAt) } : {}),
354
360
  });
355
361
  }
356
- const state = this.deps.appsState
357
- ? await this.deps.appsState(agent.accountId)
358
- : "both";
359
362
  return {
360
363
  status: "ok",
361
364
  appId: agent.appId,
@@ -137,7 +137,6 @@ describeOrSkip("reconcile-open-work (integration)", () => {
137
137
  calls.push("removeRepos");
138
138
  if (removeFails) throw new Error("installation PATCH failed");
139
139
  },
140
- setRepositorySelection: async () => {},
141
140
  },
142
141
  audit: new PrismaInstallationAudit(prisma),
143
142
  ...(openWork ? { openWork } : {}),
@@ -97,12 +97,27 @@ describeOrSkip("SlackConfigTokenService (integration)", () => {
97
97
  await service.clear(acctA); // no-op
98
98
  });
99
99
 
100
+ /** A deployment-wide row that predates the second account. */
101
+ const seedDefault = async () => {
102
+ const row = await prisma.slackConfigToken.create({
103
+ data: {
104
+ accountId: null,
105
+ refreshTokenEncrypted: (
106
+ makeStrictTokenCrypto(KEY) as TokenCrypto
107
+ ).encrypt(REFRESH),
108
+ },
109
+ });
110
+ return row;
111
+ };
112
+
100
113
  it("allows a token with no access token", async () => {
114
+ await prisma.account.deleteMany();
101
115
  const saved = await service.save(null, { refreshToken: REFRESH });
102
116
  expect(saved.accessTokenSet).toBe(false);
103
117
  });
104
118
 
105
119
  it("upserts one row per scope, including two NULL-scope saves", async () => {
120
+ await prisma.account.deleteMany();
106
121
  const first = await service.save(null, { refreshToken: REFRESH });
107
122
  const second = await service.save(null, {
108
123
  refreshToken: "test-refresh-OTHER",
@@ -114,6 +129,8 @@ describeOrSkip("SlackConfigTokenService (integration)", () => {
114
129
  await prisma.slackConfigToken.count({ where: { accountId: null } }),
115
130
  ).toBe(1);
116
131
 
132
+ acctA = (await prisma.account.create({ data: { name: "A" } })).id;
133
+ acctB = (await prisma.account.create({ data: { name: "B" } })).id;
117
134
  const a1 = await service.save(acctA, { refreshToken: REFRESH });
118
135
  const a2 = await service.save(acctA, { refreshToken: REFRESH });
119
136
  expect(a2.id).toBe(a1.id);
@@ -145,7 +162,7 @@ describeOrSkip("SlackConfigTokenService (integration)", () => {
145
162
 
146
163
  it("resolveForAccount prefers the account row, then default, then null", async () => {
147
164
  expect(await service.resolveForAccount(acctA)).toBeNull();
148
- const def = await service.save(null, { refreshToken: REFRESH });
165
+ const def = await seedDefault();
149
166
  expect((await service.resolveForAccount(acctA))?.id).toBe(def.id);
150
167
  const own = await service.save(acctA, { refreshToken: REFRESH });
151
168
  expect((await service.resolveForAccount(acctA))?.id).toBe(own.id);
@@ -156,7 +173,7 @@ describeOrSkip("SlackConfigTokenService (integration)", () => {
156
173
  });
157
174
 
158
175
  it("clears only the targeted scope", async () => {
159
- await service.save(null, { refreshToken: REFRESH });
176
+ await seedDefault();
160
177
  await service.save(acctA, { refreshToken: REFRESH });
161
178
  await service.clear(acctA);
162
179
  expect(await service.get(null)).not.toBeNull();
@@ -19,6 +19,7 @@
19
19
 
20
20
  import type { PrismaClient } from "../prisma/client/client.ts";
21
21
  import { type Clock, SystemClock } from "./clock.ts";
22
+ import { assertDeploymentWideAllowed } from "./deployment-wide-settings.ts";
22
23
  import {
23
24
  BadGatewayError,
24
25
  NotFoundError,
@@ -202,7 +203,8 @@ export class SlackConfigTokenService {
202
203
 
203
204
  /**
204
205
  * Create or replace the token for a scope (accountId null = deployment-wide
205
- * default). Resets lastError; stamps lastRotatedAt.
206
+ * default, refused while there are several accounts). Resets lastError;
207
+ * stamps lastRotatedAt.
206
208
  */
207
209
  async save(
208
210
  accountId: string | null,
@@ -212,6 +214,9 @@ export class SlackConfigTokenService {
212
214
  if (!input.refreshToken) {
213
215
  throw new UnprocessableEntityError("refreshToken is required");
214
216
  }
217
+ if (accountId === null) {
218
+ await assertDeploymentWideAllowed(this.prisma, "the Slack config token");
219
+ }
215
220
  const now = this.clock.now();
216
221
  const data = {
217
222
  refreshTokenEncrypted: this.crypto.encrypt(input.refreshToken),
@@ -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
- });