@app-vitals/agent-admin 1.60.0 → 1.62.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.
@@ -200,7 +200,9 @@ describe("githubLookup.listRepositories", () => {
200
200
  fetchFn: replay((_u, id) =>
201
201
  Response.json({
202
202
  repositories:
203
- id === 1 ? [repo("acme", "api", false, 10)] : [repo("beta", "web", false, 20)],
203
+ id === 1
204
+ ? [repo("acme", "api", false, 10)]
205
+ : [repo("beta", "web", false, 20)],
204
206
  }),
205
207
  ),
206
208
  now: () => NOW,
@@ -233,29 +235,157 @@ describe("githubLookup.listRepositories", () => {
233
235
  const svc = createGithubLookupService({
234
236
  appService: stored(null),
235
237
  fetchFn: (async () =>
236
- Response.json({ message: "boom" }, { status: 500 })) as unknown as typeof fetch,
238
+ Response.json(
239
+ { message: "boom" },
240
+ { status: 500 },
241
+ )) as unknown as typeof fetch,
237
242
  now: () => NOW,
238
243
  });
239
- await expect(svc.listRepositories()).rejects.toBeInstanceOf(GithubEnterpriseError);
244
+ await expect(svc.listRepositories()).rejects.toBeInstanceOf(
245
+ GithubEnterpriseError,
246
+ );
240
247
  });
241
248
 
242
249
  it("an installer with a slug but no key stays unconfigured", async () => {
243
250
  const svc = createGithubLookupService({
244
251
  appService: {
245
252
  get: async (kind: string) =>
246
- kind === "lookup" ? lookupApp : { appId: "1", enterpriseSlug: "ent" },
253
+ kind === "lookup"
254
+ ? lookupApp
255
+ : { appId: "1", enterpriseSlug: "ent" },
247
256
  getPrivateKey: async (kind: string) =>
248
257
  kind === "lookup" ? privateKey : null,
249
258
  } as unknown as GitHubEnterpriseAppService,
250
259
  });
251
- expect(await svc.listRepositories()).toEqual({ configured: false, repos: [] });
260
+ expect(await svc.listRepositories()).toEqual({
261
+ configured: false,
262
+ repos: [],
263
+ });
252
264
  });
253
265
 
254
266
  it("with an installer configured the org list still comes from it", async () => {
255
- const svc = service(["acme"], replay(() => Response.json({ repositories: [repo("acme", "api")] })));
267
+ const svc = service(
268
+ ["acme"],
269
+ replay(() => Response.json({ repositories: [repo("acme", "api")] })),
270
+ );
256
271
  expect((await svc.listRepositories()).repos).toEqual([
257
272
  { fullName: "acme/api", archived: false },
258
273
  ]);
259
274
  });
260
275
  });
261
276
  });
277
+
278
+ describe("githubLookup.listRepositories(accountId)", () => {
279
+ type Row = { appId: string; enterpriseSlug: string | null };
280
+ /** In-memory app service with the real account-then-deployment-wide fallback. */
281
+ function scopedApps(rows: Record<string, Row | undefined>) {
282
+ const key = (role: string, accountId?: string | null) =>
283
+ `${accountId ?? ""}:${role}`;
284
+ const resolve = (role: string, accountId?: string | null) =>
285
+ (accountId ? rows[key(role, accountId)] : undefined) ??
286
+ rows[key(role, null)];
287
+ return {
288
+ get: async (role: string, accountId?: string | null) =>
289
+ resolve(role, accountId) ?? null,
290
+ getPrivateKey: async (role: string, accountId?: string | null) =>
291
+ resolve(role, accountId) ? privateKey : null,
292
+ } as unknown as GitHubEnterpriseAppService;
293
+ }
294
+
295
+ /** The lookup App id (JWT iss) decides which org installation it sees. */
296
+ const byApp: typeof fetch = (async (
297
+ input: RequestInfo | URL,
298
+ init?: RequestInit,
299
+ ) => {
300
+ const u = new URL(input.toString());
301
+ const bearer = String(new Headers(init?.headers).get("authorization"));
302
+ const jwt = bearer.replace(/^Bearer /, "");
303
+ if (u.pathname === "/app/installations") {
304
+ const iss = JSON.parse(
305
+ Buffer.from(jwt.split(".")[1], "base64url").toString(),
306
+ ).iss;
307
+ const org = String(iss) === "777" ? "gamma" : "acme";
308
+ return Response.json([
309
+ {
310
+ id: org === "gamma" ? 3 : 1,
311
+ account: { login: org, type: "Organization" },
312
+ },
313
+ ]);
314
+ }
315
+ const inst = u.pathname.match(/^\/orgs\/([^/]+)\/installation$/);
316
+ if (inst) {
317
+ return Response.json({
318
+ id: inst[1] === "gamma" ? 3 : 1,
319
+ repository_selection: "all",
320
+ });
321
+ }
322
+ if (u.pathname.match(/^\/app\/installations\/(\d+)\/access_tokens$/)) {
323
+ const id = u.pathname.match(/installations\/(\d+)/)?.[1];
324
+ return Response.json({
325
+ token: `ghs_tok${id}`,
326
+ expires_at: "2026-11-09T13:00:00Z",
327
+ });
328
+ }
329
+ if (u.pathname === "/installation/repositories") {
330
+ return Response.json({
331
+ repositories: bearer.endsWith("tok3")
332
+ ? [repo("gamma", "tenant", false, 30)]
333
+ : [repo("acme", "shared", false, 10)],
334
+ });
335
+ }
336
+ return Response.json({ message: "Not Found" }, { status: 404 });
337
+ }) as unknown as typeof fetch;
338
+
339
+ const lookup = (appId: string): Row => ({ appId, enterpriseSlug: null });
340
+
341
+ it("lists through the account's own lookup App", async () => {
342
+ const svc = createGithubLookupService({
343
+ appService: scopedApps({
344
+ ":lookup": lookup("555"),
345
+ "acct-1:lookup": lookup("777"),
346
+ }),
347
+ fetchFn: byApp,
348
+ now: () => NOW,
349
+ });
350
+ expect((await svc.listRepositories("acct-1")).repos).toEqual([
351
+ { fullName: "gamma/tenant", archived: false },
352
+ ]);
353
+ });
354
+
355
+ it("falls back to the deployment-wide pair when the account has none", async () => {
356
+ const svc = createGithubLookupService({
357
+ appService: scopedApps({ ":lookup": lookup("555") }),
358
+ fetchFn: byApp,
359
+ now: () => NOW,
360
+ });
361
+ expect((await svc.listRepositories("acct-2")).repos).toEqual([
362
+ { fullName: "acme/shared", archived: false },
363
+ ]);
364
+ });
365
+
366
+ it("with no argument uses the deployment-wide pair, ignoring account rows", async () => {
367
+ const svc = createGithubLookupService({
368
+ appService: scopedApps({
369
+ ":lookup": lookup("555"),
370
+ "acct-1:lookup": lookup("777"),
371
+ }),
372
+ fetchFn: byApp,
373
+ now: () => NOW,
374
+ });
375
+ expect((await svc.listRepositories()).repos).toEqual([
376
+ { fullName: "acme/shared", archived: false },
377
+ ]);
378
+ });
379
+
380
+ it("is unconfigured when neither the account nor the deployment has a lookup App", async () => {
381
+ const svc = createGithubLookupService({
382
+ appService: scopedApps({}),
383
+ fetchFn: byApp,
384
+ now: () => NOW,
385
+ });
386
+ expect(await svc.listRepositories("acct-1")).toEqual({
387
+ configured: false,
388
+ repos: [],
389
+ });
390
+ });
391
+ });
@@ -25,7 +25,10 @@ export interface GithubLookupRepositories {
25
25
 
26
26
  /** The extension-facing lister (optional member of AdminPlatformServices). */
27
27
  export interface GithubLookupService {
28
- listRepositories(): Promise<GithubLookupRepositories>;
28
+ /** Lists the account's App pair, else the deployment-wide pair (no argument: deployment-wide). */
29
+ listRepositories(
30
+ accountId?: string | null,
31
+ ): Promise<GithubLookupRepositories>;
29
32
  }
30
33
 
31
34
  /** The installer-side client surface the lister needs. */
@@ -382,7 +382,7 @@ export class GithubSyncService {
382
382
  if (!username) {
383
383
  return skippedPlan(accessSkipReason(username, null) as string);
384
384
  }
385
- const preview = await this.deps.access(username);
385
+ const preview = await this.deps.access(username, agent.accountId);
386
386
  if (preview.status === "unconfigured") {
387
387
  return skippedPlan("GitHub Apps are not configured");
388
388
  }
@@ -31,6 +31,8 @@ export const MAX_UNCONFIRMED_REMOVALS = 10;
31
31
 
32
32
  export interface InstallationAgentRecord {
33
33
  id: string;
34
+ /** The agent's account; selects that account's GitHub App pair (null/absent: deployment-wide). */
35
+ accountId?: string | null;
34
36
  repos: string[];
35
37
  githubUsername: string | null;
36
38
  /** The agent's own GitHub App id (its stored GH_APP_ID); undefined when unset or not numeric. */
@@ -48,6 +50,8 @@ export interface InstallationAgentRecord {
48
50
  export interface AppIdentity {
49
51
  clientId?: string;
50
52
  slug?: string;
53
+ /** Account whose installer App makes the calls (null/absent: deployment-wide pair). */
54
+ accountId?: string | null;
51
55
  }
52
56
 
53
57
  export interface InstallationAgentsPort {
@@ -139,7 +143,7 @@ export class PrismaInstallationAgents implements InstallationAgentsPort {
139
143
  async get(agentId: string): Promise<InstallationAgentRecord | null> {
140
144
  const agent = await this.prisma.agent.findUnique({
141
145
  where: { id: agentId },
142
- select: { id: true, repos: true, githubUsername: true },
146
+ select: { id: true, repos: true, githubUsername: true, accountId: true },
143
147
  });
144
148
  if (!agent) return null;
145
149
  const env = (await this.env.getConfigBundle(agentId))?.env;
@@ -165,7 +169,10 @@ export class PrismaInstallationAgents implements InstallationAgentsPort {
165
169
 
166
170
  /** The slice of GithubEnterpriseClient the installation port needs. */
167
171
  export interface InstallationRepoClient {
168
- listOrgInstallations(org: string): Promise<
172
+ listOrgInstallations(
173
+ org: string,
174
+ accountId?: string | null,
175
+ ): Promise<
169
176
  {
170
177
  id: number;
171
178
  /** Absent on the enterprise-organization-installation schema. */
@@ -177,16 +184,19 @@ export interface InstallationRepoClient {
177
184
  listInstallationRepositories(
178
185
  org: string,
179
186
  installationId: number,
187
+ accountId?: string | null,
180
188
  ): Promise<{ fullName: string }[]>;
181
189
  addRepositories(
182
190
  org: string,
183
191
  installationId: number,
184
192
  names: readonly string[],
193
+ accountId?: string | null,
185
194
  ): Promise<unknown>;
186
195
  removeRepositories(
187
196
  org: string,
188
197
  installationId: number,
189
198
  names: readonly string[],
199
+ accountId?: string | null,
190
200
  ): Promise<unknown>;
191
201
  }
192
202
 
@@ -239,7 +249,7 @@ export function createInstallationPort(
239
249
  identity?: AppIdentity,
240
250
  ): Promise<number> => {
241
251
  const found = matchInstallation(
242
- await client.listOrgInstallations(org),
252
+ await client.listOrgInstallations(org, identity?.accountId),
243
253
  appId,
244
254
  identity,
245
255
  );
@@ -255,6 +265,7 @@ export function createInstallationPort(
255
265
  const repos = await client.listInstallationRepositories(
256
266
  org,
257
267
  await installationId(appId, org, identity),
268
+ identity?.accountId,
258
269
  );
259
270
  out[org] = repos.map((r) => r.fullName);
260
271
  }
@@ -265,6 +276,7 @@ export function createInstallationPort(
265
276
  org,
266
277
  await installationId(appId, org, identity),
267
278
  repos.map(baseName),
279
+ identity?.accountId,
268
280
  );
269
281
  },
270
282
  async removeRepos(appId, org, repos, identity) {
@@ -272,6 +284,7 @@ export function createInstallationPort(
272
284
  org,
273
285
  await installationId(appId, org, identity),
274
286
  repos.map(baseName),
287
+ identity?.accountId,
275
288
  );
276
289
  },
277
290
  };
@@ -64,8 +64,10 @@ export interface InstallationReposDeps {
64
64
  export function identityOf(agent: {
65
65
  clientId?: string;
66
66
  slug?: string;
67
+ accountId?: string | null;
67
68
  }): AppIdentity {
68
69
  return {
70
+ ...(agent.accountId ? { accountId: agent.accountId } : {}),
69
71
  ...(agent.clientId ? { clientId: agent.clientId } : {}),
70
72
  ...(agent.slug ? { slug: agent.slug } : {}),
71
73
  };
@@ -130,7 +132,7 @@ export class InstallationReposService {
130
132
  let access: UserRepoAccessResult | undefined;
131
133
  if (username) {
132
134
  try {
133
- const preview = await this.deps.access(username);
135
+ const preview = await this.deps.access(username, agent.accountId);
134
136
  if (preview.status === "ok") access = preview.access;
135
137
  } catch {
136
138
  // The hint is advisory: a failed lookup omits it.
@@ -149,7 +151,9 @@ export class InstallationReposService {
149
151
 
150
152
  /** The slice of the installer client the installation-repos port needs. */
151
153
  export interface InstalledOrgsClient {
152
- listInstallableOrganizations(): Promise<{ login: string }[]>;
154
+ listInstallableOrganizations(
155
+ accountId?: string | null,
156
+ ): Promise<{ login: string }[]>;
153
157
  }
154
158
 
155
159
  /**
@@ -164,7 +168,9 @@ export function createInstallationReposPort(
164
168
  ...base,
165
169
  async listInstalled(appId, identity) {
166
170
  const out: { org: string; repos: string[] }[] = [];
167
- for (const { login } of await client.listInstallableOrganizations()) {
171
+ for (const { login } of await client.listInstallableOrganizations(
172
+ identity?.accountId,
173
+ )) {
168
174
  try {
169
175
  const repos = await base.listRepos(appId, [login], identity);
170
176
  out.push({ org: login, repos: repos[login] ?? [] });
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Integration tests for SlackConfigTokenService against a real PostgreSQL DB.
3
+ *
4
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
5
+ */
6
+
7
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
8
+ import type { PrismaClient } from "../prisma/client/client.ts";
9
+ import { createAdminPrismaClient } from "./prisma-client.ts";
10
+ import {
11
+ SlackConfigTokenEncryptionUnavailableError,
12
+ SlackConfigTokenService,
13
+ toSlackConfigTokenMetadata,
14
+ } from "./slack-config-token.ts";
15
+ import { makeStrictTokenCrypto } from "./token-crypto.ts";
16
+
17
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
18
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
19
+
20
+ const KEY = "a".repeat(64);
21
+ const REFRESH = "test-refresh-SUPERSECRET";
22
+ const ACCESS = "test-access-SUPERSECRET";
23
+
24
+ describeOrSkip("SlackConfigTokenService (integration)", () => {
25
+ let prisma: PrismaClient;
26
+ let service: SlackConfigTokenService;
27
+ let acctA: string;
28
+ let acctB: string;
29
+
30
+ beforeEach(async () => {
31
+ prisma = createAdminPrismaClient(TEST_DB as string);
32
+ await prisma.slackConfigToken.deleteMany();
33
+ await prisma.agentTemplateItem.deleteMany();
34
+ await prisma.agentTemplate.deleteMany();
35
+ await prisma.agent.deleteMany();
36
+ await prisma.accountInvite.deleteMany();
37
+ await prisma.accountMember.deleteMany();
38
+ await prisma.account.deleteMany();
39
+ acctA = (await prisma.account.create({ data: { name: "A" } })).id;
40
+ acctB = (await prisma.account.create({ data: { name: "B" } })).id;
41
+ service = new SlackConfigTokenService(prisma, makeStrictTokenCrypto(KEY));
42
+ });
43
+
44
+ afterEach(async () => {
45
+ await prisma.$disconnect();
46
+ });
47
+
48
+ it("returns null / empty when nothing is saved", async () => {
49
+ expect(await service.get(null)).toBeNull();
50
+ expect(await service.get(acctA)).toBeNull();
51
+ expect(await service.resolveForAccount(acctA)).toBeNull();
52
+ expect(await service.list()).toEqual([]);
53
+ });
54
+
55
+ it("saves, gets and clears per scope; metadata only", async () => {
56
+ const exp = new Date("2030-01-01T00:00:00Z");
57
+ const saved = await service.save(acctA, {
58
+ refreshToken: REFRESH,
59
+ accessToken: ACCESS,
60
+ accessTokenExpiresAt: exp,
61
+ slackTeamId: "T1",
62
+ slackUserId: "U1",
63
+ });
64
+ expect(saved).toMatchObject({
65
+ accountId: acctA,
66
+ refreshTokenSet: true,
67
+ accessTokenSet: true,
68
+ slackTeamId: "T1",
69
+ slackUserId: "U1",
70
+ });
71
+ expect(saved.accessTokenExpiresAt).toEqual(exp);
72
+ expect(saved.lastRotatedAt).not.toBeNull();
73
+ const got = await service.get(acctA);
74
+ expect(got?.id).toBe(saved.id);
75
+ for (const out of [saved, got, await service.list()]) {
76
+ const json = JSON.stringify(out);
77
+ expect(json).not.toContain("SUPERSECRET");
78
+ expect(json).not.toContain("Encrypted");
79
+ }
80
+ // stored encrypted, not plain
81
+ const raw = await prisma.slackConfigToken.findFirstOrThrow({
82
+ where: { accountId: acctA },
83
+ });
84
+ expect(raw.refreshTokenEncrypted).not.toContain("SUPERSECRET");
85
+ expect(raw.accessTokenEncrypted).not.toContain("SUPERSECRET");
86
+
87
+ await service.clear(acctA);
88
+ expect(await service.get(acctA)).toBeNull();
89
+ await service.clear(acctA); // no-op
90
+ });
91
+
92
+ it("allows a token with no access token", async () => {
93
+ const saved = await service.save(null, { refreshToken: REFRESH });
94
+ expect(saved.accessTokenSet).toBe(false);
95
+ });
96
+
97
+ it("upserts one row per scope, including two NULL-scope saves", async () => {
98
+ const first = await service.save(null, { refreshToken: REFRESH });
99
+ const second = await service.save(null, {
100
+ refreshToken: "test-refresh-OTHER",
101
+ slackTeamId: "T2",
102
+ });
103
+ expect(second.id).toBe(first.id);
104
+ expect(second.slackTeamId).toBe("T2");
105
+ expect(
106
+ await prisma.slackConfigToken.count({ where: { accountId: null } }),
107
+ ).toBe(1);
108
+
109
+ const a1 = await service.save(acctA, { refreshToken: REFRESH });
110
+ const a2 = await service.save(acctA, { refreshToken: REFRESH });
111
+ expect(a2.id).toBe(a1.id);
112
+ await service.save(acctB, { refreshToken: REFRESH });
113
+ expect(await prisma.slackConfigToken.count()).toBe(3);
114
+ });
115
+
116
+ it("enforces both partial unique indexes at the database", async () => {
117
+ const base = { refreshTokenEncrypted: "x" };
118
+ await prisma.slackConfigToken.create({
119
+ data: { ...base, accountId: null },
120
+ });
121
+ await expect(
122
+ (async () =>
123
+ prisma.slackConfigToken.create({
124
+ data: { ...base, accountId: null },
125
+ }))(),
126
+ ).rejects.toThrow();
127
+ await prisma.slackConfigToken.create({
128
+ data: { ...base, accountId: acctA },
129
+ });
130
+ await expect(
131
+ (async () =>
132
+ prisma.slackConfigToken.create({
133
+ data: { ...base, accountId: acctA },
134
+ }))(),
135
+ ).rejects.toThrow();
136
+ });
137
+
138
+ it("resolveForAccount prefers the account row, then default, then null", async () => {
139
+ expect(await service.resolveForAccount(acctA)).toBeNull();
140
+ const def = await service.save(null, { refreshToken: REFRESH });
141
+ expect((await service.resolveForAccount(acctA))?.id).toBe(def.id);
142
+ const own = await service.save(acctA, { refreshToken: REFRESH });
143
+ expect((await service.resolveForAccount(acctA))?.id).toBe(own.id);
144
+ expect((await service.resolveForAccount(acctB))?.id).toBe(def.id);
145
+ await service.clear(null);
146
+ await service.clear(acctA);
147
+ expect(await service.resolveForAccount(acctA)).toBeNull();
148
+ });
149
+
150
+ it("clears only the targeted scope", async () => {
151
+ await service.save(null, { refreshToken: REFRESH });
152
+ await service.save(acctA, { refreshToken: REFRESH });
153
+ await service.clear(acctA);
154
+ expect(await service.get(null)).not.toBeNull();
155
+ expect(await service.get(acctA)).toBeNull();
156
+ });
157
+
158
+ it("deleting an account cascades its token", async () => {
159
+ await service.save(acctA, { refreshToken: REFRESH });
160
+ await prisma.account.delete({ where: { id: acctA } });
161
+ expect(await prisma.slackConfigToken.count()).toBe(0);
162
+ });
163
+
164
+ it("refuses to save without an encryption key", async () => {
165
+ const noKey = new SlackConfigTokenService(prisma, null);
166
+ await expect(
167
+ noKey.save(null, { refreshToken: REFRESH }),
168
+ ).rejects.toBeInstanceOf(SlackConfigTokenEncryptionUnavailableError);
169
+ expect(await prisma.slackConfigToken.count()).toBe(0);
170
+ });
171
+ });
172
+
173
+ describe("toSlackConfigTokenMetadata", () => {
174
+ it("never includes secret fields", () => {
175
+ const now = new Date();
176
+ const out = toSlackConfigTokenMetadata({
177
+ id: "i",
178
+ accountId: null,
179
+ refreshTokenEncrypted: "SECRETREFRESHCIPHER",
180
+ accessTokenEncrypted: "SECRETACCESSCIPHER",
181
+ accessTokenExpiresAt: now,
182
+ slackTeamId: "T",
183
+ slackUserId: "U",
184
+ lastRotatedAt: now,
185
+ lastError: null,
186
+ createdAt: now,
187
+ updatedAt: now,
188
+ });
189
+ expect(Object.keys(out).sort()).toEqual(
190
+ [
191
+ "id",
192
+ "accountId",
193
+ "refreshTokenSet",
194
+ "accessTokenSet",
195
+ "accessTokenExpiresAt",
196
+ "slackTeamId",
197
+ "slackUserId",
198
+ "lastRotatedAt",
199
+ "lastError",
200
+ "createdAt",
201
+ "updatedAt",
202
+ ].sort(),
203
+ );
204
+ expect(JSON.stringify(out)).not.toContain("SECRET");
205
+ expect(out.refreshTokenSet).toBe(true);
206
+ expect(out.accessTokenSet).toBe(true);
207
+ });
208
+ });