@app-vitals/agent-admin 1.109.0 → 1.110.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.
@@ -28,6 +28,7 @@ import {
28
28
  sealTemplateItemPayload,
29
29
  type TemplateItemPayload,
30
30
  } from "./agent-template-items.ts";
31
+ import { assertDeploymentWideAllowed } from "./deployment-wide-settings.ts";
31
32
  import {
32
33
  ConflictError,
33
34
  ForbiddenError,
@@ -397,7 +398,9 @@ export class AgentTemplateService {
397
398
  return item;
398
399
  });
399
400
 
400
- if (accountId !== null) {
401
+ if (accountId === null) {
402
+ await assertDeploymentWideAllowed(this.prisma, "an agent template");
403
+ } else {
401
404
  const account = await this.prisma.account.findUnique({
402
405
  where: { id: accountId },
403
406
  select: { id: true },
@@ -470,6 +473,9 @@ export class AgentTemplateService {
470
473
  input: TemplateItemInput,
471
474
  ): Promise<TemplateView> {
472
475
  const existing = await this.load(actor, templateId);
476
+ if (existing.accountId === null) {
477
+ await assertDeploymentWideAllowed(this.prisma, "an agent template");
478
+ }
473
479
  const item = normalizeTemplateItem(input);
474
480
  const prior = existing.items.find(
475
481
  (it) => it.kind === item.kind && it.key === item.key,
@@ -0,0 +1,309 @@
1
+ /**
2
+ * Integration: deployment-wide (accountId null) settings against real Postgres.
3
+ * With more than one account the Slack config token, the enterprise GitHub
4
+ * Apps and agent templates cannot be created or updated without an account;
5
+ * existing deployment-wide rows stay readable and removable. With one account
6
+ * or none nothing changes.
7
+ *
8
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
9
+ */
10
+
11
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
12
+ import type { PrismaClient } from "../prisma/client/client.ts";
13
+ import { AgentTemplateService } from "./agent-templates.ts";
14
+ import { createAgentTemplatesApp } from "./agent-templates-api.ts";
15
+ import { parseAdminApiKeys } from "./api-auth.ts";
16
+ import { DeploymentWideSettingBlockedError } from "./deployment-wide-settings.ts";
17
+ import { createGithubLookupService } from "./github-enterprise-api.ts";
18
+ import { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
19
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
20
+ import { createAdminPrismaClient } from "./prisma-client.ts";
21
+ import {
22
+ hasStoredSlackConfigToken,
23
+ SlackConfigTokenService,
24
+ } from "./slack-config-token.ts";
25
+ import { SpecialtyTypes } from "./specialty-types.ts";
26
+ import { makeStrictTokenCrypto } from "./token-crypto.ts";
27
+
28
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
29
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
30
+
31
+ const KEY = "ab".repeat(32);
32
+ const PEM =
33
+ "-----BEGIN RSA PRIVATE KEY-----\nMADEUPPEMBODY0123456789\n-----END RSA PRIVATE KEY-----";
34
+ const NOW = new Date("2026-11-20T12:00:00Z");
35
+
36
+ describeOrSkip("deployment-wide settings (integration)", () => {
37
+ let prisma: PrismaClient;
38
+ const crypto = makeStrictTokenCrypto(KEY);
39
+ if (!crypto) throw new Error("test crypto");
40
+
41
+ const addAccount = async (name: string) =>
42
+ (await prisma.account.create({ data: { name } })).id;
43
+
44
+ const slack = () => new SlackConfigTokenService(prisma, crypto);
45
+ const apps = () => new GitHubEnterpriseAppService(prisma, crypto);
46
+ const templates = () =>
47
+ new AgentTemplateService(
48
+ prisma,
49
+ crypto,
50
+ new SpecialtyTypes({ defaultTypeName: "specialist" }),
51
+ );
52
+ const lookupApp = (accountId?: string | null) => ({
53
+ accountId,
54
+ role: "lookup" as const,
55
+ appId: "555",
56
+ slug: "example-lookup",
57
+ privateKey: PEM,
58
+ });
59
+ const envItem = {
60
+ kind: "env" as const,
61
+ key: "EXAMPLE_VAR",
62
+ payload: { value: "made-up" },
63
+ };
64
+ const admin = { kind: "admin" as const };
65
+
66
+ beforeEach(async () => {
67
+ prisma = createAdminPrismaClient(TEST_DB as string);
68
+ await prisma.slackConfigToken.deleteMany();
69
+ await prisma.gitHubEnterpriseApp.deleteMany();
70
+ await prisma.gitHubCachedRepo.deleteMany();
71
+ await prisma.gitHubRepoSnapshot.deleteMany();
72
+ await prisma.agentTemplateItem.deleteMany();
73
+ await prisma.agentTemplate.deleteMany();
74
+ await prisma.agent.deleteMany();
75
+ await prisma.accountInvite.deleteMany();
76
+ await prisma.accountMember.deleteMany();
77
+ await prisma.account.deleteMany();
78
+ });
79
+
80
+ afterEach(async () => {
81
+ await prisma.gitHubCachedRepo.deleteMany();
82
+ await prisma.gitHubRepoSnapshot.deleteMany();
83
+ await prisma.slackConfigToken.deleteMany();
84
+ await prisma.gitHubEnterpriseApp.deleteMany();
85
+ await prisma.agentTemplate.deleteMany();
86
+ await prisma.account.deleteMany();
87
+ await prisma.$disconnect();
88
+ });
89
+
90
+ describe("Slack config token", () => {
91
+ it("saves a deployment-wide token with no account or one account", async () => {
92
+ await slack().save(null, { refreshToken: "made-up-refresh-1" });
93
+ await addAccount("A");
94
+ await slack().save(null, { refreshToken: "made-up-refresh-2" });
95
+ expect(await slack().get(null)).not.toBeNull();
96
+ });
97
+
98
+ it("rejects creating and updating a deployment-wide token with several accounts", async () => {
99
+ const a = await addAccount("A");
100
+ await addAccount("B");
101
+ await expect(
102
+ slack().save(null, { refreshToken: "made-up-refresh" }),
103
+ ).rejects.toBeInstanceOf(DeploymentWideSettingBlockedError);
104
+ expect(await slack().get(null)).toBeNull();
105
+ // An account's own token is still fine.
106
+ await slack().save(a, { refreshToken: "made-up-refresh" });
107
+ expect(await slack().get(a)).not.toBeNull();
108
+ });
109
+
110
+ it("keeps an existing deployment-wide token readable and removable, not updatable", async () => {
111
+ const a = await addAccount("A");
112
+ await slack().save(null, { refreshToken: "made-up-refresh" });
113
+ await addAccount("B");
114
+ expect(await slack().get(null)).not.toBeNull();
115
+ // The shared row still backs an account with no token of its own.
116
+ expect((await slack().resolveForAccount(a))?.accountId).toBeNull();
117
+ await expect(
118
+ slack().save(null, { refreshToken: "made-up-refresh-new" }),
119
+ ).rejects.toBeInstanceOf(DeploymentWideSettingBlockedError);
120
+ await slack().clear(null);
121
+ expect(await slack().get(null)).toBeNull();
122
+ });
123
+
124
+ it("gives an account without its own token none once no deployment-wide row exists", async () => {
125
+ const a = await addAccount("A");
126
+ await addAccount("B");
127
+ expect(await slack().resolveForAccount(a)).toBeNull();
128
+ expect(await hasStoredSlackConfigToken(slack(), a)).toBe(false);
129
+ // An agent with no account only sees the deployment-wide row.
130
+ expect(await hasStoredSlackConfigToken(slack(), null)).toBe(false);
131
+ });
132
+ });
133
+
134
+ describe("GitHub Apps", () => {
135
+ it("saves a deployment-wide App with no account or one account", async () => {
136
+ await apps().save(lookupApp());
137
+ await addAccount("A");
138
+ await apps().save(lookupApp(null));
139
+ expect((await apps().get("lookup"))?.accountId).toBeNull();
140
+ });
141
+
142
+ it("rejects creating and updating a deployment-wide App with several accounts", async () => {
143
+ const a = await addAccount("A");
144
+ await addAccount("B");
145
+ await expect(apps().save(lookupApp())).rejects.toBeInstanceOf(
146
+ DeploymentWideSettingBlockedError,
147
+ );
148
+ await expect(apps().save(lookupApp(null))).rejects.toBeInstanceOf(
149
+ DeploymentWideSettingBlockedError,
150
+ );
151
+ expect(await apps().list()).toEqual([]);
152
+ await apps().save(lookupApp(a));
153
+ expect((await apps().get("lookup", a))?.accountId).toBe(a);
154
+ });
155
+
156
+ it("keeps an existing deployment-wide App readable and removable, not updatable", async () => {
157
+ const a = await addAccount("A");
158
+ await apps().save(lookupApp());
159
+ await addAccount("B");
160
+ expect((await apps().get("lookup", a))?.accountId).toBeNull();
161
+ expect(await apps().list()).toHaveLength(1);
162
+ await expect(apps().save(lookupApp())).rejects.toBeInstanceOf(
163
+ DeploymentWideSettingBlockedError,
164
+ );
165
+ await apps().delete("lookup");
166
+ expect(await apps().get("lookup", a)).toBeNull();
167
+ });
168
+
169
+ describe("repo listings and caches", () => {
170
+ let cache: GitHubRepoCacheService;
171
+ const listing = () =>
172
+ createGithubLookupService({
173
+ appService: apps(),
174
+ cache,
175
+ now: () => NOW,
176
+ });
177
+
178
+ async function seedSnapshot(accountId: string, appRef: string) {
179
+ const key = {
180
+ accountId,
181
+ appKind: "lookup" as const,
182
+ appRef,
183
+ org: "example-org",
184
+ };
185
+ const snap = await cache.upsertSnapshot(key, {
186
+ crawlPage: 1,
187
+ crawlStartedAt: NOW,
188
+ totalCount: 1,
189
+ });
190
+ await cache.upsertRepos(snap.id, [
191
+ { githubId: 1, fullName: "example-org/repo-one" },
192
+ ]);
193
+ await cache.upsertSnapshot(key, { completedAt: NOW });
194
+ }
195
+
196
+ beforeEach(() => {
197
+ cache = new GitHubRepoCacheService(prisma, { now: () => NOW });
198
+ });
199
+
200
+ it("lists nothing for an account or an agent with no account when no deployment-wide App exists", async () => {
201
+ const a = await addAccount("A");
202
+ await addAccount("B");
203
+ // A snapshot left behind by a removed deployment-wide App.
204
+ await seedSnapshot("deployment", "555");
205
+ expect(await listing().listRepositories(a)).toEqual({
206
+ configured: false,
207
+ repos: [],
208
+ });
209
+ expect(await listing().listRepositories(null)).toEqual({
210
+ configured: false,
211
+ repos: [],
212
+ });
213
+ });
214
+
215
+ it("serves the deployment-wide listing as the fallback while the row exists", async () => {
216
+ const a = await addAccount("A");
217
+ await apps().save(lookupApp());
218
+ await addAccount("B");
219
+ await seedSnapshot("deployment", "555");
220
+ const r = await listing().listRepositories(a);
221
+ expect(r.configured).toBe(true);
222
+ expect(r.repos).toEqual([
223
+ { fullName: "example-org/repo-one", archived: false },
224
+ ]);
225
+ expect((await listing().listRepositories(null)).configured).toBe(true);
226
+ });
227
+
228
+ it("does not mix the deployment-wide cache into an account with its own App", async () => {
229
+ const a = await addAccount("A");
230
+ await addAccount("B");
231
+ await apps().save(lookupApp(a));
232
+ await seedSnapshot("deployment", "555");
233
+ const r = await listing().listRepositories(a);
234
+ expect(r.configured).toBe(true);
235
+ expect(r.repos).toEqual([]);
236
+ });
237
+ });
238
+ });
239
+
240
+ describe("agent templates", () => {
241
+ it("saves a deployment-wide template with no account or one account", async () => {
242
+ expect((await templates().replace(admin, {}, [envItem])).created).toBe(
243
+ true,
244
+ );
245
+ await addAccount("A");
246
+ const again = await templates().replace(admin, {}, [envItem]);
247
+ expect(again.created).toBe(false);
248
+ expect(again.template.accountId).toBeNull();
249
+ });
250
+
251
+ it("rejects creating and updating a deployment-wide template with several accounts", async () => {
252
+ const a = await addAccount("A");
253
+ await addAccount("B");
254
+ await expect(
255
+ templates().replace(admin, {}, [envItem]),
256
+ ).rejects.toBeInstanceOf(DeploymentWideSettingBlockedError);
257
+ await expect(
258
+ templates().replace(admin, { accountId: null, specialty: null }, []),
259
+ ).rejects.toBeInstanceOf(DeploymentWideSettingBlockedError);
260
+ expect(await prisma.agentTemplate.count()).toBe(0);
261
+ const own = await templates().replace(admin, { accountId: a }, [envItem]);
262
+ expect(own.template.accountId).toBe(a);
263
+ });
264
+
265
+ it("keeps an existing deployment-wide template readable and removable, not updatable", async () => {
266
+ const { template } = await templates().replace(admin, {}, [envItem]);
267
+ await addAccount("A");
268
+ await addAccount("B");
269
+ expect(await templates().list(admin, {})).toHaveLength(1);
270
+ await expect(
271
+ templates().replace(admin, {}, [envItem]),
272
+ ).rejects.toBeInstanceOf(DeploymentWideSettingBlockedError);
273
+ await expect(
274
+ templates().putItem(admin, template.id, {
275
+ kind: "env",
276
+ key: "OTHER_VAR",
277
+ payload: { value: "x" },
278
+ }),
279
+ ).rejects.toBeInstanceOf(DeploymentWideSettingBlockedError);
280
+ await templates().deleteItem(admin, template.id, "env", "EXAMPLE_VAR");
281
+ await templates().delete(admin, template.id);
282
+ expect(await prisma.agentTemplate.count()).toBe(0);
283
+ });
284
+
285
+ it("answers PUT /templates for a deployment-wide scope with 422 once there are several accounts", async () => {
286
+ const app = createAgentTemplatesApp({
287
+ templateService: templates(),
288
+ callerScopeResolver: async () => ({ kind: "all" }),
289
+ sessionSecret: "test-session-secret-32-chars-long!!",
290
+ adminApiKeys: parseAdminApiKeys("root:tok-admin:*"),
291
+ agentTokenService: { validate: async () => null },
292
+ });
293
+ const put = (body: unknown) =>
294
+ app.request("/templates", {
295
+ method: "PUT",
296
+ headers: {
297
+ Authorization: "Bearer tok-admin",
298
+ "Content-Type": "application/json",
299
+ },
300
+ body: JSON.stringify(body),
301
+ });
302
+ const a = await addAccount("A");
303
+ expect((await put({ items: [] })).status).toBe(201);
304
+ await addAccount("B");
305
+ expect((await put({ items: [] })).status).toBe(422);
306
+ expect((await put({ accountId: a, items: [] })).status).toBe(201);
307
+ });
308
+ });
309
+ });
@@ -0,0 +1,42 @@
1
+ /**
2
+ * admin/src/deployment-wide-settings.ts
3
+ * Guard for settings that can be stored with no account (accountId null): the
4
+ * Slack config token, the enterprise GitHub Apps and agent templates. A row
5
+ * with no account is a fallback for every account, so once there is more than
6
+ * one account nobody may create or update one: the admin picks an account.
7
+ * Existing deployment-wide rows stay readable and removable. With one account
8
+ * or none, shared settings work as before.
9
+ */
10
+
11
+ import type { PrismaClient } from "../prisma/client/client.ts";
12
+ import { UnprocessableEntityError } from "./errors.ts";
13
+
14
+ export class DeploymentWideSettingBlockedError extends UnprocessableEntityError {
15
+ constructor(what: string) {
16
+ super(
17
+ `There is more than one account, so ${what} cannot be created or changed deployment-wide. Choose an account. An existing deployment-wide setting can still be removed.`,
18
+ );
19
+ this.name = "DeploymentWideSettingBlockedError";
20
+ }
21
+ }
22
+
23
+ /** True when more than one account exists. */
24
+ export async function hasMultipleAccounts(
25
+ prisma: Pick<PrismaClient, "account">,
26
+ ): Promise<boolean> {
27
+ const rows = await prisma.account.findMany({
28
+ select: { id: true },
29
+ take: 2,
30
+ });
31
+ return rows.length > 1;
32
+ }
33
+
34
+ /** Throws DeploymentWideSettingBlockedError when several accounts exist. */
35
+ export async function assertDeploymentWideAllowed(
36
+ prisma: Pick<PrismaClient, "account">,
37
+ what: string,
38
+ ): Promise<void> {
39
+ if (await hasMultipleAccounts(prisma)) {
40
+ throw new DeploymentWideSettingBlockedError(what);
41
+ }
42
+ }
@@ -45,6 +45,22 @@ export function lookupAccountKeys(accountId?: string | null): string[] {
45
45
  : [DEPLOYMENT_WIDE_ACCOUNT_KEY];
46
46
  }
47
47
 
48
+ /**
49
+ * lookupAccountKeys for an agent whose lookup App resolved to `app`. The
50
+ * deployment key holds snapshots of the deployment-wide App only, so it is
51
+ * left out when the agent uses its own account's App and no deployment-wide
52
+ * lookup App exists any more (a removed App's cache must not leak to accounts).
53
+ * `hasDeploymentApp` is asked only in that case.
54
+ */
55
+ export async function lookupKeysForApp(
56
+ app: { accountId?: string | null },
57
+ accountId: string | null | undefined,
58
+ hasDeploymentApp: () => Promise<boolean>,
59
+ ): Promise<string[]> {
60
+ if (app.accountId && !(await hasDeploymentApp())) return [app.accountId];
61
+ return lookupAccountKeys(accountId);
62
+ }
63
+
48
64
  /**
49
65
  * Reads per-user access rows under every key in lookupAccountKeys(accountId)
50
66
  * and merges them. The writer files rows under the resolved lookup App's scope
@@ -213,7 +229,8 @@ export async function crawlAgentInstallation(
213
229
  let selection: "all" | "selected" | null;
214
230
  try {
215
231
  selection = (await source.resolveRepositorySelection?.()) ?? null;
216
- if (!source.resolveRepositorySelection) await source.resolveInstallationId();
232
+ if (!source.resolveRepositorySelection)
233
+ await source.resolveInstallationId();
217
234
  } catch (err) {
218
235
  if (!(err instanceof AppNotInstalledError)) {
219
236
  // Let the engine record GitHub failures and rate limits on the snapshot.
@@ -107,6 +107,10 @@ describeOrSkip("github-enterprise API (integration)", () => {
107
107
  await prisma.agentCronJob.deleteMany();
108
108
  await prisma.agentTool.deleteMany();
109
109
  await prisma.agent.deleteMany();
110
+ // Deployment-wide Apps cannot be saved while there are several accounts.
111
+ await prisma.accountInvite.deleteMany();
112
+ await prisma.accountMember.deleteMany();
113
+ await prisma.account.deleteMany();
110
114
  appService = new GitHubEnterpriseAppService(
111
115
  prisma,
112
116
  makeStrictTokenCrypto(ENC_KEY),
@@ -371,6 +375,9 @@ describeOrSkip("DELETE /orgs/{org}/install (integration)", () => {
371
375
  await prisma.agentCronJob.deleteMany();
372
376
  await prisma.agentTool.deleteMany();
373
377
  await prisma.agent.deleteMany();
378
+ await prisma.accountInvite.deleteMany();
379
+ await prisma.accountMember.deleteMany();
380
+ await prisma.account.deleteMany();
374
381
  });
375
382
 
376
383
  afterEach(async () => {
@@ -36,7 +36,7 @@ import {
36
36
  UnprocessableEntityError,
37
37
  } from "./errors.ts";
38
38
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
39
- import { lookupAccountKeys } from "./github-agent-installation-crawler.ts";
39
+ import { lookupKeysForApp } from "./github-agent-installation-crawler.ts";
40
40
  import { fetchAuthenticatedApp, fetchPublicApp } from "./github-app-api.ts";
41
41
  import {
42
42
  GITHUB_ENTERPRISE_APP_ROLES,
@@ -660,7 +660,11 @@ export function createGithubLookupService(
660
660
  return { configured: false, repos: [] };
661
661
  }
662
662
  const snapshots = await deps.cache.listLookupSnapshots(
663
- lookupAccountKeys(accountId),
663
+ await lookupKeysForApp(
664
+ lookup,
665
+ accountId,
666
+ async () => (await deps.appService.get("lookup", null)) !== null,
667
+ ),
664
668
  lookup.appId,
665
669
  );
666
670
  return summarizeLookupSnapshots(
@@ -155,6 +155,31 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
155
155
  let acctA: string;
156
156
  let acctB: string;
157
157
 
158
+ /** A deployment-wide row that predates the second account. */
159
+ const seedGlobal = async (input: typeof lookup) => {
160
+ const data = {
161
+ appId: input.appId,
162
+ slug: input.slug,
163
+ enterpriseSlug: null,
164
+ privateKeyEncrypted: (
165
+ makeStrictTokenCrypto(KEY_A) as { encrypt(v: string): string }
166
+ ).encrypt(input.privateKey),
167
+ };
168
+ const existing = await prisma.gitHubEnterpriseApp.findFirst({
169
+ where: { role: input.role, accountId: null },
170
+ });
171
+ if (existing) {
172
+ await prisma.gitHubEnterpriseApp.update({
173
+ where: { id: existing.id },
174
+ data,
175
+ });
176
+ } else {
177
+ await prisma.gitHubEnterpriseApp.create({
178
+ data: { role: input.role, accountId: null, ...data },
179
+ });
180
+ }
181
+ };
182
+
158
183
  beforeEach(async () => {
159
184
  await prisma.account.deleteMany({
160
185
  where: { name: { in: ["ghe-a", "ghe-b"] } },
@@ -171,7 +196,7 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
171
196
  });
172
197
 
173
198
  it("get(role, accountId) prefers the account row, else falls back to deployment-wide", async () => {
174
- await service.save(lookup);
199
+ await seedGlobal(lookup);
175
200
  expect((await service.get("lookup", acctA))?.appId).toBe("900");
176
201
  await service.save({ ...lookup, accountId: acctA, appId: "901" });
177
202
  const own = await service.get("lookup", acctA);
@@ -182,7 +207,7 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
182
207
  });
183
208
 
184
209
  it("listAccountIds returns each account with Apps of its own once, never the deployment scope", async () => {
185
- await service.save(lookup);
210
+ await seedGlobal(lookup);
186
211
  expect(await service.listAccountIds()).toEqual([]);
187
212
  await service.save({ ...lookup, accountId: acctA });
188
213
  await service.save({ ...installer, accountId: acctA });
@@ -200,7 +225,7 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
200
225
  });
201
226
 
202
227
  it("accounts are isolated: save/delete/recordValidation hit only the targeted row", async () => {
203
- await service.save(lookup);
228
+ await seedGlobal(lookup);
204
229
  await service.save({ ...lookup, accountId: acctA, appId: "A" });
205
230
  await service.save({ ...lookup, accountId: acctB, appId: "B" });
206
231
  await service.recordValidation("lookup", { status: "ok" }, acctA);
@@ -218,7 +243,7 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
218
243
  });
219
244
 
220
245
  it("getPrivateKey follows the same fallback and decrypts the right row", async () => {
221
- await service.save(lookup);
246
+ await seedGlobal(lookup);
222
247
  await service.save({
223
248
  ...lookup,
224
249
  accountId: acctA,
@@ -230,15 +255,15 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
230
255
  });
231
256
 
232
257
  it("save is idempotent per (accountId, role), including the NULL scope", async () => {
233
- await service.save(lookup);
234
- await service.save({ ...lookup, appId: "again" });
258
+ await seedGlobal(lookup);
259
+ await seedGlobal({ ...lookup, appId: "again" });
235
260
  await service.save({ ...lookup, accountId: acctA });
236
261
  await service.save({ ...lookup, accountId: acctA, appId: "again" });
237
262
  expect(await prisma.gitHubEnterpriseApp.count()).toBe(2);
238
263
  });
239
264
 
240
265
  it("the database rejects a second deployment-wide row for a role", async () => {
241
- await service.save(lookup);
266
+ await seedGlobal(lookup);
242
267
  const dup = async () =>
243
268
  prisma.gitHubEnterpriseApp.create({
244
269
  data: {
@@ -252,7 +277,7 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
252
277
  });
253
278
 
254
279
  it("deleting an account cascades to its apps only", async () => {
255
- await service.save(lookup);
280
+ await seedGlobal(lookup);
256
281
  await service.save({ ...lookup, accountId: acctA });
257
282
  await prisma.account.delete({ where: { id: acctA } });
258
283
  expect(await prisma.gitHubEnterpriseApp.count()).toBe(1);
@@ -21,6 +21,7 @@
21
21
 
22
22
  import type { PrismaClient } from "../prisma/client/client.ts";
23
23
  import { type Clock, SystemClock } from "./clock.ts";
24
+ import { assertDeploymentWideAllowed } from "./deployment-wide-settings.ts";
24
25
  import { ApiError, UnprocessableEntityError } from "./errors.ts";
25
26
  import type { TokenCrypto } from "./token-crypto.ts";
26
27
 
@@ -150,6 +151,9 @@ export class GitHubEnterpriseAppService {
150
151
  throw new UnprocessableEntityError("privateKey is required");
151
152
  }
152
153
  const accountId = input.accountId ?? null;
154
+ if (accountId === null) {
155
+ await assertDeploymentWideAllowed(this.prisma, "a GitHub App");
156
+ }
153
157
  const data = {
154
158
  appId: input.appId,
155
159
  slug: input.slug,
@@ -17,7 +17,10 @@ import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
17
17
  import type { Clock } from "./clock.ts";
18
18
  import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
19
19
  import { GithubEnterpriseClient } from "./github-enterprise-client.ts";
20
- import { lookupAccountKeys } from "./github-agent-installation-crawler.ts";
20
+ import {
21
+ DEPLOYMENT_WIDE_ACCOUNT_KEY,
22
+ lookupKeysForApp,
23
+ } from "./github-agent-installation-crawler.ts";
21
24
  import { GithubLookupClient } from "./github-lookup-client.ts";
22
25
  import { GitHubRepoCacheService } from "./github-repo-cache.ts";
23
26
  import type { CrawlStore } from "./github-repo-crawler.ts";
@@ -131,6 +134,24 @@ function appsStateDep(
131
134
  : { appsState: githubAppsStateProbe(deps) };
132
135
  }
133
136
 
137
+ /**
138
+ * The repo cache for the access-row reads. Rows filed under the deployment key
139
+ * belong to the deployment-wide lookup App; once that App is gone they are
140
+ * stale and must not reach any account.
141
+ */
142
+ export function accessCache(
143
+ deps: Pick<InstallationReposWiringDeps, "prisma" | "appService">,
144
+ ): GitHubRepoCacheService {
145
+ const cache = new GitHubRepoCacheService(deps.prisma);
146
+ const read = cache.getAccessRows.bind(cache);
147
+ cache.getAccessRows = async (query) =>
148
+ query.accountId === DEPLOYMENT_WIDE_ACCOUNT_KEY &&
149
+ (await deps.appService.get("lookup", null)) === null
150
+ ? []
151
+ : read(query);
152
+ return cache;
153
+ }
154
+
134
155
  export interface InstallationReposWiringDeps
135
156
  extends GithubInstallationWiringDeps {
136
157
  /** Test seam: replaces the installer-App-backed port. */
@@ -153,7 +174,7 @@ export function createGithubInstallationRepos(
153
174
  installation:
154
175
  deps.installationRepos ??
155
176
  createInstallationReposPort(createInstallationPort(client), client),
156
- cache: new GitHubRepoCacheService(deps.prisma),
177
+ cache: accessCache(deps),
157
178
  ...appsStateDep(deps),
158
179
  });
159
180
  }
@@ -168,7 +189,7 @@ export function createGithubSync(
168
189
  deps: InstallationReposWiringDeps,
169
190
  ): GithubSyncService {
170
191
  const client = lazyInstallerClient(deps);
171
- const cache = new GitHubRepoCacheService(deps.prisma);
192
+ const cache = accessCache(deps);
172
193
  const lookupClients = new Map<string, GithubLookupClient>();
173
194
  // The lookup client per App (and key version), reused with its installation tokens.
174
195
  const lookupClient = async (accountId?: string | null) => {
@@ -188,7 +209,15 @@ export function createGithubSync(
188
209
  });
189
210
  lookupClients.set(cacheKey, c);
190
211
  }
191
- return { client: c, appId: meta.appId };
212
+ return {
213
+ client: c,
214
+ appId: meta.appId,
215
+ keys: await lookupKeysForApp(
216
+ meta,
217
+ accountId,
218
+ async () => (await deps.appService.get("lookup", null)) !== null,
219
+ ),
220
+ };
192
221
  };
193
222
  return new GithubSyncService({
194
223
  agents: new PrismaInstallationAgents(deps.prisma, deps.agentEnv),
@@ -199,7 +228,7 @@ export function createGithubSync(
199
228
  const lookup = await lookupClient(accountId);
200
229
  if (!lookup) return [];
201
230
  const snapshots = await cache.listLookupOrgSnapshots(
202
- lookupAccountKeys(accountId),
231
+ lookup.keys,
203
232
  lookup.appId,
204
233
  );
205
234
  return snapshots.map((s) => ({