@app-vitals/agent-admin 1.54.1 → 1.55.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.
@@ -0,0 +1,21 @@
1
+ -- Surrogate primary key: existing rows (the deployment-wide pair) get a
2
+ -- deterministic id derived from their role; no data is otherwise touched.
3
+ ALTER TABLE "GitHubEnterpriseApp" DROP CONSTRAINT "GitHubEnterpriseApp_pkey";
4
+ ALTER TABLE "GitHubEnterpriseApp" ADD COLUMN "id" TEXT;
5
+ UPDATE "GitHubEnterpriseApp" SET "id" = 'ghe_' || "role";
6
+ ALTER TABLE "GitHubEnterpriseApp" ALTER COLUMN "id" SET NOT NULL;
7
+ ALTER TABLE "GitHubEnterpriseApp" ADD CONSTRAINT "GitHubEnterpriseApp_pkey" PRIMARY KEY ("id");
8
+
9
+ -- Nullable account scope; existing rows stay NULL (deployment-wide).
10
+ ALTER TABLE "GitHubEnterpriseApp" ADD COLUMN "accountId" TEXT;
11
+
12
+ -- CreateIndex
13
+ CREATE UNIQUE INDEX "GitHubEnterpriseApp_accountId_role_key" ON "GitHubEnterpriseApp"("accountId", "role");
14
+
15
+ -- AddForeignKey
16
+ ALTER TABLE "GitHubEnterpriseApp" ADD CONSTRAINT "GitHubEnterpriseApp_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
17
+
18
+ -- Partial unique index (not expressible in Prisma; see the GitHubEnterpriseApp
19
+ -- comment in schema.prisma). The plain (accountId, role) index above cannot
20
+ -- enforce one deployment-wide row per role because NULLs compare distinct.
21
+ CREATE UNIQUE INDEX "GitHubEnterpriseApp_role_global_key" ON "GitHubEnterpriseApp"("role") WHERE "accountId" IS NULL;
@@ -130,12 +130,23 @@ model AgentEnv {
130
130
  }
131
131
 
132
132
  // ─── GitHub Enterprise Apps ───────────────────────────────────────────────────
133
- // Optional admin-level GitHub Apps, one per role ('installer' | 'lookup'), at most
134
- // two rows per deployment; no rows means the feature is off. Deliberately NOT in
135
- // AgentEnv so the private key can never reach the agent config bundle.
133
+ // Optional admin-level GitHub Apps, one per (accountId, role) where role is
134
+ // 'installer' | 'lookup'. accountId null = the deployment-wide pair (at most two
135
+ // rows); an account row overrides it for that account. No rows means the feature
136
+ // is off. Deliberately NOT in AgentEnv so the private key can never reach the
137
+ // agent config bundle.
138
+ //
139
+ // UNIQUENESS: NULLs compare distinct in a plain unique index, so the
140
+ // deployment-wide (accountId NULL) uniqueness is a partial unique index
141
+ // hand-written in 20261116000000_github_enterprise_app_account_id/migration.sql:
142
+ // GitHubEnterpriseApp_role_global_key (accountId NULL)
143
+ // Prisma's schema diff does not see it; keep it when editing this model.
136
144
 
137
145
  model GitHubEnterpriseApp {
138
- role String @id // 'installer' | 'lookup'
146
+ id String @id @default(cuid())
147
+ accountId String?
148
+ account Account? @relation(fields: [accountId], references: [id], onDelete: Cascade)
149
+ role String // 'installer' | 'lookup'
139
150
  appId String
140
151
  slug String
141
152
  enterpriseSlug String? // installer only
@@ -145,6 +156,8 @@ model GitHubEnterpriseApp {
145
156
  lastValidationError String?
146
157
  createdAt DateTime @default(now())
147
158
  updatedAt DateTime @updatedAt
159
+
160
+ @@unique([accountId, role])
148
161
  }
149
162
 
150
163
  // ─── Agent Cron Jobs ──────────────────────────────────────────────────────────
@@ -279,6 +292,7 @@ model Account {
279
292
  members AccountMember[]
280
293
  invites AccountInvite[]
281
294
  templates AgentTemplate[]
295
+ githubEnterpriseApps GitHubEnterpriseApp[]
282
296
  }
283
297
 
284
298
  // ─── Agent Templates ──────────────────────────────────────────────────────────
@@ -145,7 +145,7 @@ describeOrSkip("github-enterprise API (integration)", () => {
145
145
  const base = "/admin/settings/github-enterprise/apps/lookup";
146
146
  const fields = { appId: "777", slug: "example-lookup" };
147
147
  const snapshot = async () => {
148
- const row = await prisma.gitHubEnterpriseApp.findUnique({
148
+ const row = await prisma.gitHubEnterpriseApp.findFirst({
149
149
  where: { role: "lookup" },
150
150
  });
151
151
  return {
@@ -169,7 +169,7 @@ describeOrSkip("github-enterprise API (integration)", () => {
169
169
  const res = await ui.request(base, { method: "POST", body: upload });
170
170
  expect(res.status).toBe(302);
171
171
  expect(await snapshot()).toEqual(pasted);
172
- const row = await prisma.gitHubEnterpriseApp.findUnique({
172
+ const row = await prisma.gitHubEnterpriseApp.findFirst({
173
173
  where: { role: "lookup" },
174
174
  });
175
175
  expect(row?.privateKeyEncrypted).not.toContain(PEM_BODY);
@@ -194,7 +194,7 @@ describeOrSkip("github-enterprise API (integration)", () => {
194
194
  expect(text).not.toContain("ghs_cassette");
195
195
  expect(JSON.parse(text)).toMatchObject({ ok: true, status: "valid" });
196
196
 
197
- const row = await prisma.gitHubEnterpriseApp.findUnique({
197
+ const row = await prisma.gitHubEnterpriseApp.findFirst({
198
198
  where: { role: "installer" },
199
199
  });
200
200
  expect(row?.lastValidationStatus).toBe("valid");
@@ -223,7 +223,7 @@ describeOrSkip("github-enterprise API (integration)", () => {
223
223
  },
224
224
  );
225
225
  expect(await res.json()).toMatchObject({ ok: false, status: "error" });
226
- const row = await prisma.gitHubEnterpriseApp.findUnique({
226
+ const row = await prisma.gitHubEnterpriseApp.findFirst({
227
227
  where: { role: "installer" },
228
228
  });
229
229
  expect(row?.lastValidationStatus).toBe("error");
@@ -304,7 +304,7 @@ describeOrSkip("github-enterprise API (integration)", () => {
304
304
  const envService = new AgentEnvService(prisma, identityCrypto);
305
305
  await envService.upsert(agent.id, { GH_APP_SLUG: "example-agent-app" });
306
306
  await put(build());
307
- const row = await prisma.gitHubEnterpriseApp.findUnique({
307
+ const row = await prisma.gitHubEnterpriseApp.findFirst({
308
308
  where: { role: "installer" },
309
309
  });
310
310
  const needles = [
@@ -88,7 +88,7 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
88
88
 
89
89
  it("stores the key encrypted and round-trips it via getPrivateKey", async () => {
90
90
  await service.save(installer);
91
- const row = await prisma.gitHubEnterpriseApp.findUnique({
91
+ const row = await prisma.gitHubEnterpriseApp.findFirst({
92
92
  where: { role: "installer" },
93
93
  });
94
94
  expect(row?.privateKeyEncrypted).not.toContain("SUPERSECRETPEMBODY");
@@ -134,14 +134,14 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
134
134
 
135
135
  it("strict decrypt: tampered and legacy plain-text values throw", async () => {
136
136
  await service.save(installer);
137
- const row = await prisma.gitHubEnterpriseApp.findUnique({
137
+ const row = await prisma.gitHubEnterpriseApp.findFirst({
138
138
  where: { role: "installer" },
139
139
  });
140
140
  const [iv, ct, tag] = (row?.privateKeyEncrypted ?? "").split(":");
141
141
  const flipped = (ct[0] === "0" ? "1" : "0") + ct.slice(1);
142
142
  for (const bad of [`${iv}:${flipped}:${tag}`, PEM]) {
143
143
  await prisma.gitHubEnterpriseApp.update({
144
- where: { role: "installer" },
144
+ where: { id: row?.id },
145
145
  data: { privateKeyEncrypted: bad },
146
146
  });
147
147
  const err = await service.getPrivateKey("installer").catch((e) => e);
@@ -149,4 +149,102 @@ describeOrSkip("GitHubEnterpriseAppService (integration)", () => {
149
149
  expect(err.message).not.toContain("SUPERSECRETPEMBODY");
150
150
  }
151
151
  });
152
+
153
+ describe("account scope", () => {
154
+ const lookup = { ...installer, role: "lookup" as const, appId: "900" };
155
+ let acctA: string;
156
+ let acctB: string;
157
+
158
+ beforeEach(async () => {
159
+ await prisma.account.deleteMany({
160
+ where: { name: { in: ["ghe-a", "ghe-b"] } },
161
+ });
162
+ acctA = (await prisma.account.create({ data: { name: "ghe-a" } })).id;
163
+ acctB = (await prisma.account.create({ data: { name: "ghe-b" } })).id;
164
+ });
165
+
166
+ afterEach(async () => {
167
+ await prisma.gitHubEnterpriseApp.deleteMany();
168
+ await prisma.account.deleteMany({
169
+ where: { id: { in: [acctA, acctB] } },
170
+ });
171
+ });
172
+
173
+ it("get(role, accountId) prefers the account row, else falls back to deployment-wide", async () => {
174
+ await service.save(lookup);
175
+ expect((await service.get("lookup", acctA))?.appId).toBe("900");
176
+ await service.save({ ...lookup, accountId: acctA, appId: "901" });
177
+ const own = await service.get("lookup", acctA);
178
+ expect(own?.appId).toBe("901");
179
+ expect(own?.accountId).toBe(acctA);
180
+ expect((await service.get("lookup", acctB))?.appId).toBe("900");
181
+ expect((await service.get("lookup"))?.appId).toBe("900");
182
+ });
183
+
184
+ it("get(role) without accountId never sees an account row", async () => {
185
+ await service.save({ ...lookup, accountId: acctA });
186
+ expect(await service.get("lookup")).toBeNull();
187
+ expect(await service.list()).toEqual([]);
188
+ expect(await service.list(acctA)).toHaveLength(1);
189
+ });
190
+
191
+ it("accounts are isolated: save/delete/recordValidation hit only the targeted row", async () => {
192
+ await service.save(lookup);
193
+ await service.save({ ...lookup, accountId: acctA, appId: "A" });
194
+ await service.save({ ...lookup, accountId: acctB, appId: "B" });
195
+ await service.recordValidation("lookup", { status: "ok" }, acctA);
196
+ expect((await service.get("lookup", acctA))?.lastValidationStatus).toBe(
197
+ "ok",
198
+ );
199
+ expect((await service.get("lookup", acctB))?.lastValidationStatus).toBe(
200
+ null,
201
+ );
202
+ expect((await service.get("lookup"))?.lastValidationStatus).toBe(null);
203
+ await service.delete("lookup", acctA);
204
+ expect((await service.get("lookup", acctA))?.appId).toBe("900");
205
+ expect((await service.get("lookup", acctB))?.appId).toBe("B");
206
+ expect(await prisma.gitHubEnterpriseApp.count()).toBe(2);
207
+ });
208
+
209
+ it("getPrivateKey follows the same fallback and decrypts the right row", async () => {
210
+ await service.save(lookup);
211
+ await service.save({
212
+ ...lookup,
213
+ accountId: acctA,
214
+ privateKey: `${PEM}-ACCT`,
215
+ });
216
+ expect(await service.getPrivateKey("lookup", acctA)).toBe(`${PEM}-ACCT`);
217
+ expect(await service.getPrivateKey("lookup", acctB)).toBe(PEM);
218
+ expect(await service.getPrivateKey("lookup")).toBe(PEM);
219
+ });
220
+
221
+ it("save is idempotent per (accountId, role), including the NULL scope", async () => {
222
+ await service.save(lookup);
223
+ await service.save({ ...lookup, appId: "again" });
224
+ await service.save({ ...lookup, accountId: acctA });
225
+ await service.save({ ...lookup, accountId: acctA, appId: "again" });
226
+ expect(await prisma.gitHubEnterpriseApp.count()).toBe(2);
227
+ });
228
+
229
+ it("the database rejects a second deployment-wide row for a role", async () => {
230
+ await service.save(lookup);
231
+ const dup = async () =>
232
+ prisma.gitHubEnterpriseApp.create({
233
+ data: {
234
+ role: "lookup",
235
+ appId: "x",
236
+ slug: "x",
237
+ privateKeyEncrypted: "x",
238
+ },
239
+ });
240
+ await expect(dup()).rejects.toThrow();
241
+ });
242
+
243
+ it("deleting an account cascades to its apps only", async () => {
244
+ await service.save(lookup);
245
+ await service.save({ ...lookup, accountId: acctA });
246
+ await prisma.account.delete({ where: { id: acctA } });
247
+ expect(await prisma.gitHubEnterpriseApp.count()).toBe(1);
248
+ });
249
+ });
152
250
  });
@@ -1,8 +1,11 @@
1
1
  /**
2
2
  * admin/src/github-enterprise-apps.ts
3
3
  * GitHubEnterpriseAppService — storage for the two optional admin-level GitHub
4
- * Apps ('installer' and 'lookup'), at most one row per role. No rows means the
5
- * feature is off.
4
+ * Apps ('installer' and 'lookup'), at most one row per (accountId, role).
5
+ * accountId null is the deployment-wide pair; an account row overrides it for
6
+ * that account (get() falls back to the deployment-wide row). Every method takes
7
+ * an optional accountId; omitting it behaves as before (deployment-wide row).
8
+ * No rows means the feature is off.
6
9
  *
7
10
  * The private key is encrypted on write (AES-256-GCM via TokenCrypto) and is
8
11
  * never returned by any read path: reads return metadata plus a `keySet` flag.
@@ -26,6 +29,8 @@ export type GitHubEnterpriseAppRole =
26
29
  (typeof GITHUB_ENTERPRISE_APP_ROLES)[number];
27
30
 
28
31
  export interface GitHubEnterpriseAppMetadata {
32
+ /** Null/absent for the deployment-wide app. */
33
+ accountId?: string | null;
29
34
  role: string;
30
35
  appId: string;
31
36
  slug: string;
@@ -40,6 +45,8 @@ export interface GitHubEnterpriseAppMetadata {
40
45
  }
41
46
 
42
47
  export interface SaveGitHubEnterpriseAppInput {
48
+ /** Omit/null for the deployment-wide app. */
49
+ accountId?: string | null;
43
50
  role: GitHubEnterpriseAppRole;
44
51
  appId: string;
45
52
  slug: string;
@@ -50,6 +57,7 @@ export interface SaveGitHubEnterpriseAppInput {
50
57
  }
51
58
 
52
59
  interface GitHubEnterpriseAppRow {
60
+ accountId?: string | null;
53
61
  role: string;
54
62
  appId: string;
55
63
  slug: string;
@@ -86,6 +94,7 @@ export function toGitHubEnterpriseAppMetadata(
86
94
  row: GitHubEnterpriseAppRow,
87
95
  ): GitHubEnterpriseAppMetadata {
88
96
  return {
97
+ accountId: row.accountId ?? null,
89
98
  role: row.role,
90
99
  appId: row.appId,
91
100
  slug: row.slug,
@@ -115,7 +124,23 @@ export class GitHubEnterpriseAppService {
115
124
  private clock: Clock = SystemClock(),
116
125
  ) {}
117
126
 
118
- /** Create or replace the app for a role. Resets validation state. */
127
+ /** Exact-scope row lookup: no fallback. */
128
+ private findExact(role: GitHubEnterpriseAppRole, accountId: string | null) {
129
+ return this.prisma.gitHubEnterpriseApp.findFirst({
130
+ where: { role, accountId },
131
+ });
132
+ }
133
+
134
+ /** Account row if present, else the deployment-wide row. */
135
+ private async resolve(
136
+ role: GitHubEnterpriseAppRole,
137
+ accountId: string | null,
138
+ ) {
139
+ const own = accountId ? await this.findExact(role, accountId) : null;
140
+ return own ?? (await this.findExact(role, null));
141
+ }
142
+
143
+ /** Create or replace the app for a (accountId, role). Resets validation state. */
119
144
  async save(
120
145
  input: SaveGitHubEnterpriseAppInput,
121
146
  ): Promise<GitHubEnterpriseAppMetadata> {
@@ -124,6 +149,7 @@ export class GitHubEnterpriseAppService {
124
149
  if (!input.privateKey) {
125
150
  throw new UnprocessableEntityError("privateKey is required");
126
151
  }
152
+ const accountId = input.accountId ?? null;
127
153
  const data = {
128
154
  appId: input.appId,
129
155
  slug: input.slug,
@@ -135,48 +161,66 @@ export class GitHubEnterpriseAppService {
135
161
  lastValidationError: null,
136
162
  updatedAt: this.clock.now(),
137
163
  };
138
- const row = await this.prisma.gitHubEnterpriseApp.upsert({
139
- where: { role: input.role },
140
- create: { role: input.role, ...data },
141
- update: data,
142
- });
164
+ // Not upsert: Prisma cannot target the NULL accountId side of the
165
+ // composite unique. The partial unique indexes still reject a racing
166
+ // duplicate insert.
167
+ const existing = await this.findExact(input.role, accountId);
168
+ const row = existing
169
+ ? await this.prisma.gitHubEnterpriseApp.update({
170
+ where: { id: existing.id },
171
+ data,
172
+ })
173
+ : await this.prisma.gitHubEnterpriseApp.create({
174
+ data: { role: input.role, accountId, ...data },
175
+ });
143
176
  return toGitHubEnterpriseAppMetadata(row);
144
177
  }
145
178
 
179
+ /** The account's row if present, otherwise the deployment-wide row. */
146
180
  async get(
147
181
  role: GitHubEnterpriseAppRole,
182
+ accountId?: string | null,
148
183
  ): Promise<GitHubEnterpriseAppMetadata | null> {
149
184
  assertRole(role);
150
- const row = await this.prisma.gitHubEnterpriseApp.findUnique({
151
- where: { role },
152
- });
185
+ const row = await this.resolve(role, accountId ?? null);
153
186
  return row ? toGitHubEnterpriseAppMetadata(row) : null;
154
187
  }
155
188
 
156
- async list(): Promise<GitHubEnterpriseAppMetadata[]> {
189
+ /** Rows at exactly this scope (deployment-wide when accountId is omitted). */
190
+ async list(
191
+ accountId?: string | null,
192
+ ): Promise<GitHubEnterpriseAppMetadata[]> {
157
193
  const rows = await this.prisma.gitHubEnterpriseApp.findMany({
194
+ where: { accountId: accountId ?? null },
158
195
  orderBy: { role: "asc" },
159
196
  });
160
197
  return rows.map(toGitHubEnterpriseAppMetadata);
161
198
  }
162
199
 
163
- /** Delete the app for a role. No-ops if absent. */
164
- async delete(role: GitHubEnterpriseAppRole): Promise<void> {
200
+ /** Delete the app at exactly this (accountId, role). No-ops if absent. */
201
+ async delete(
202
+ role: GitHubEnterpriseAppRole,
203
+ accountId?: string | null,
204
+ ): Promise<void> {
165
205
  assertRole(role);
166
- await this.prisma.gitHubEnterpriseApp.deleteMany({ where: { role } });
206
+ await this.prisma.gitHubEnterpriseApp.deleteMany({
207
+ where: { role, accountId: accountId ?? null },
208
+ });
167
209
  }
168
210
 
169
211
  /**
170
- * Server-side only: decrypt the stored PEM. Strict — any failure throws
212
+ * Server-side only: decrypt the stored PEM of the row get() would return
213
+ * (account row, else deployment-wide). Strict — any failure throws
171
214
  * PrivateKeyDecryptError (never includes the PEM or ciphertext). Returns
172
- * null when the role has no row.
215
+ * null when no row resolves.
173
216
  */
174
- async getPrivateKey(role: GitHubEnterpriseAppRole): Promise<string | null> {
217
+ async getPrivateKey(
218
+ role: GitHubEnterpriseAppRole,
219
+ accountId?: string | null,
220
+ ): Promise<string | null> {
175
221
  assertRole(role);
176
222
  if (!this.crypto) throw new PrivateKeyEncryptionUnavailableError();
177
- const row = await this.prisma.gitHubEnterpriseApp.findUnique({
178
- where: { role },
179
- });
223
+ const row = await this.resolve(role, accountId ?? null);
180
224
  if (!row) return null;
181
225
  try {
182
226
  return this.crypto.decrypt(row.privateKeyEncrypted);
@@ -185,14 +229,15 @@ export class GitHubEnterpriseAppService {
185
229
  }
186
230
  }
187
231
 
188
- /** Record the outcome of a validation attempt. The error text must not contain key material. */
232
+ /** Record the outcome of a validation attempt on exactly this (accountId, role). The error text must not contain key material. */
189
233
  async recordValidation(
190
234
  role: GitHubEnterpriseAppRole,
191
235
  result: { status: string; error?: string | null },
236
+ accountId?: string | null,
192
237
  ): Promise<void> {
193
238
  assertRole(role);
194
239
  await this.prisma.gitHubEnterpriseApp.updateMany({
195
- where: { role },
240
+ where: { role, accountId: accountId ?? null },
196
241
  data: {
197
242
  lastValidationStatus: result.status,
198
243
  lastValidatedAt: this.clock.now(),
@@ -79,6 +79,16 @@ describe("GitHub Enterprise key isolation", () => {
79
79
  ]);
80
80
  });
81
81
 
82
+ it("no source outside the allowlist reaches the key through the Account relation", () => {
83
+ const offenders = files
84
+ .map((f) => relative(REPO, f))
85
+ .filter((rel) => !ALLOWED.has(rel))
86
+ .filter((rel) =>
87
+ /githubEnterpriseApps/.test(readFileSync(join(REPO, rel), "utf-8")),
88
+ );
89
+ expect(offenders).toEqual([]);
90
+ });
91
+
82
92
  it("the config bundle and env serializers never read the enterprise table", () => {
83
93
  for (const rel of ["admin/src/agent-envs.ts", "admin/src/api.ts"]) {
84
94
  const src = readFileSync(join(REPO, rel), "utf-8");