@app-vitals/agent-admin 1.31.0 → 1.33.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.
@@ -7,6 +7,8 @@
7
7
  */
8
8
 
9
9
  import { beforeAll, describe, expect, it, spyOn } from "bun:test";
10
+ import { generateKeyPairSync } from "node:crypto";
11
+ import { readFileSync } from "node:fs";
10
12
  import { sign } from "hono/jwt";
11
13
  import type { Prisma } from "../prisma/client/client.ts";
12
14
  import { getSelfServeSpecialty } from "./account-agent-create.ts";
@@ -22,12 +24,18 @@ import type { AgentTokenService } from "./agent-tokens.ts";
22
24
  import type { AdminDeps } from "./agents-api.ts";
23
25
  import { createAdminApp, parseAdminApiKeys } from "./agents-api.ts";
24
26
  import { PLATFORM_OPS_ROUTES } from "./api-auth.ts";
25
- import { createGithubReconcile } from "./github-reconcile-wiring.ts";
27
+ import {
28
+ createGithubInstallationRepos,
29
+ createGithubReconcile,
30
+ } from "./github-reconcile-wiring.ts";
26
31
  import {
27
32
  accessFor,
33
+ envWith,
28
34
  fakeOpenWork,
29
35
  fakePrisma,
30
36
  } from "./github-reconcile-wiring.unit.test.ts";
37
+ import type { OpenWorkPort } from "./reconcile-open-work.ts";
38
+ import { repoRemovedFromAgentBlockReason } from "./repo-removal-open-work.ts";
31
39
  import type { SpecialtyType } from "./specialty-types.ts";
32
40
  import { identityCrypto } from "./token-crypto.ts";
33
41
 
@@ -6039,6 +6047,224 @@ describe("admin API — POST/DELETE /agents/:id/repos", () => {
6039
6047
  });
6040
6048
  });
6041
6049
 
6050
+ // ─── Repo removal blocks open work (IRM-1.7) ─────────────────────────────────
6051
+
6052
+ describe("admin API — repo removal blocks open work", () => {
6053
+ const MEMBER_EMAIL = "member@example.com";
6054
+ const ADMIN_KEY = "irm-admin-key";
6055
+ const ITEMS = [{ id: "T-1", repo: "a/one", title: "work" }];
6056
+ const makeApp = (initial: string[], port?: Partial<OpenWorkPort> | null) => {
6057
+ let repos = [...initial];
6058
+ const calls: unknown[][] = [];
6059
+ const base = makeMockDeps();
6060
+ const detail = () => ({
6061
+ id: AGENT_ID,
6062
+ name: "Existing Agent",
6063
+ slackId: null,
6064
+ selfHosted: false,
6065
+ repos: [...repos],
6066
+ reviewAuthorAllowlist: [],
6067
+ patchAuthorAllowlist: [],
6068
+ restrictSlackToMembers: false,
6069
+ specialty: "coding",
6070
+ createdAt: new Date("2024-01-01"),
6071
+ updatedAt: new Date("2024-01-01"),
6072
+ missingRequiredEnv: [],
6073
+ });
6074
+ const openWork: OpenWorkPort | undefined =
6075
+ port === null
6076
+ ? undefined
6077
+ : {
6078
+ listOpenWork: async (...a) => {
6079
+ calls.push(["list", ...a]);
6080
+ return ITEMS;
6081
+ },
6082
+ blockOpenWork: async (...a) => {
6083
+ calls.push(["block", ...a]);
6084
+ },
6085
+ ...port,
6086
+ };
6087
+ const app = createAdminApp({
6088
+ ...base,
6089
+ ...(openWork ? { openWork } : {}),
6090
+ adminApiKeys: parseAdminApiKeys(`admin:${ADMIN_KEY}:*`),
6091
+ agentMemberService: {
6092
+ ...base.agentMemberService,
6093
+ exists: async (agentId: string, email: string) =>
6094
+ agentId === AGENT_ID && email === MEMBER_EMAIL,
6095
+ listByEmail: async (email: string) =>
6096
+ email === MEMBER_EMAIL
6097
+ ? [
6098
+ {
6099
+ id: "m1",
6100
+ agentId: AGENT_ID,
6101
+ email,
6102
+ createdAt: new Date("2024-01-01"),
6103
+ },
6104
+ ]
6105
+ : [],
6106
+ },
6107
+ agentService: {
6108
+ ...base.agentService,
6109
+ exists: async () => true,
6110
+ getDetail: async (id: string) => (id === AGENT_ID ? detail() : null),
6111
+ updateSelfHosted: async (_id: string, input: { repos?: string[] }) => {
6112
+ if (input.repos) repos = input.repos;
6113
+ return detail();
6114
+ },
6115
+ },
6116
+ });
6117
+ return { app, calls, repos: () => repos };
6118
+ };
6119
+ const adminCall = (
6120
+ app: ReturnType<typeof createAdminApp>,
6121
+ method: string,
6122
+ path: string,
6123
+ body?: unknown,
6124
+ ) =>
6125
+ app.request(path, {
6126
+ method,
6127
+ body: body === undefined ? undefined : JSON.stringify(body),
6128
+ headers: {
6129
+ "Content-Type": "application/json",
6130
+ Authorization: `Bearer ${ADMIN_KEY}`,
6131
+ },
6132
+ });
6133
+ const memberCall = async (
6134
+ app: ReturnType<typeof createAdminApp>,
6135
+ method: string,
6136
+ path: string,
6137
+ body?: unknown,
6138
+ ) => {
6139
+ const cookie = await sign(
6140
+ {
6141
+ isAdmin: false,
6142
+ userId: "user-m",
6143
+ email: MEMBER_EMAIL,
6144
+ iat: Math.floor(Date.now() / 1000),
6145
+ exp: Math.floor(Date.now() / 1000) + 3600,
6146
+ },
6147
+ SESSION_SECRET,
6148
+ "HS256",
6149
+ );
6150
+ return app.request(path, {
6151
+ method,
6152
+ body: body === undefined ? undefined : JSON.stringify(body),
6153
+ headers: {
6154
+ "Content-Type": "application/json",
6155
+ Cookie: `admin_session=${cookie}`,
6156
+ },
6157
+ });
6158
+ };
6159
+ const url = `/agents/${AGENT_ID}/repos`;
6160
+ const blockCall = (repo: string) => [
6161
+ "block",
6162
+ AGENT_ID,
6163
+ [repo],
6164
+ repoRemovedFromAgentBlockReason(repo),
6165
+ ];
6166
+
6167
+ it("DELETE as platform admin blocks open work with a reason naming the repo", async () => {
6168
+ const { app, calls } = makeApp(["a/one", "b/two"]);
6169
+ const res = await adminCall(app, "DELETE", `${url}/a/one`);
6170
+ expect(res.status).toBe(200);
6171
+ expect((await res.json()).repos).toEqual(["b/two"]);
6172
+ expect(calls).toEqual([blockCall("a/one")]);
6173
+ });
6174
+
6175
+ it("DELETE as a session member blocks open work too", async () => {
6176
+ const { app, calls } = makeApp(["a/one", "b/two"]);
6177
+ const res = await memberCall(app, "DELETE", `${url}/a/one`);
6178
+ expect(res.status).toBe(200);
6179
+ expect(calls).toEqual([blockCall("a/one")]);
6180
+ });
6181
+
6182
+ it("a port failure is a warning and the removal still succeeds", async () => {
6183
+ const { app, repos } = makeApp(["a/one"], {
6184
+ blockOpenWork: async () => {
6185
+ throw new Error("store down");
6186
+ },
6187
+ });
6188
+ const res = await adminCall(app, "DELETE", `${url}/a/one`);
6189
+ expect(res.status).toBe(200);
6190
+ const body = await res.json();
6191
+ expect(body.repos).toEqual([]);
6192
+ expect(body.warning).toContain("store down");
6193
+ expect(repos()).toEqual([]);
6194
+ });
6195
+
6196
+ it("DELETE without a port just removes the repo", async () => {
6197
+ const { app } = makeApp(["a/one"], null);
6198
+ const res = await adminCall(app, "DELETE", `${url}/a/one`);
6199
+ expect(res.status).toBe(200);
6200
+ expect((await res.json()).warning).toBeUndefined();
6201
+ });
6202
+
6203
+ it("PATCH that drops repos blocks only the dropped ones", async () => {
6204
+ const { app, calls } = makeApp(["a/one", "b/two", "c/three"]);
6205
+ const res = await memberCall(app, "PATCH", `/agents/${AGENT_ID}`, {
6206
+ repos: ["b/two"],
6207
+ });
6208
+ expect(res.status).toBe(200);
6209
+ expect(calls).toEqual([blockCall("a/one"), blockCall("c/three")]);
6210
+ });
6211
+
6212
+ it("adding a repo (POST, or PATCH that only adds) never touches open work", async () => {
6213
+ const { app, calls } = makeApp(["a/one"]);
6214
+ expect(
6215
+ (await adminCall(app, "POST", url, { repos: ["b/two"] })).status,
6216
+ ).toBe(200);
6217
+ expect(
6218
+ (
6219
+ await adminCall(app, "PATCH", `/agents/${AGENT_ID}`, {
6220
+ repos: ["a/one", "b/two", "c/three"],
6221
+ })
6222
+ ).status,
6223
+ ).toBe(200);
6224
+ expect(calls).toEqual([]);
6225
+ });
6226
+
6227
+ it("preview lists open work for admin and member without changing anything", async () => {
6228
+ const { app, calls, repos } = makeApp(["a/one", "b/two"]);
6229
+ for (const res of [
6230
+ await adminCall(app, "GET", `${url}/a/one/removal-preview`),
6231
+ await memberCall(app, "GET", `${url}/a/one/removal-preview`),
6232
+ ]) {
6233
+ expect(res.status).toBe(200);
6234
+ expect(await res.json()).toEqual({
6235
+ repo: "a/one",
6236
+ openWork: ITEMS,
6237
+ warnings: [],
6238
+ });
6239
+ }
6240
+ expect(calls.every((c) => c[0] === "list")).toBe(true);
6241
+ expect(repos()).toEqual(["a/one", "b/two"]);
6242
+ });
6243
+
6244
+ it("preview is empty with no port, warns on a port failure, 404s for a repo the agent lacks", async () => {
6245
+ const none = makeApp(["a/one"], null);
6246
+ expect(
6247
+ await (
6248
+ await adminCall(none.app, "GET", `${url}/a/one/removal-preview`)
6249
+ ).json(),
6250
+ ).toEqual({ repo: "a/one", openWork: [], warnings: [] });
6251
+ const failing = makeApp(["a/one"], {
6252
+ listOpenWork: async () => {
6253
+ throw new Error("nope");
6254
+ },
6255
+ });
6256
+ const body = await (
6257
+ await adminCall(failing.app, "GET", `${url}/a/one/removal-preview`)
6258
+ ).json();
6259
+ expect(body.openWork).toEqual([]);
6260
+ expect(body.warnings[0]).toContain("nope");
6261
+ expect(
6262
+ (await adminCall(failing.app, "GET", `${url}/z/nope/removal-preview`))
6263
+ .status,
6264
+ ).toBe(404);
6265
+ });
6266
+ });
6267
+
6042
6268
  // ─── Platform scopes (COS-28.1) ─────────────────────────────────────────────
6043
6269
 
6044
6270
  describe("platform.read / platform.ops keys over the real route table", () => {
@@ -7186,13 +7412,16 @@ describe("admin API — GitHub reconcile routes (GHE-3.4)", () => {
7186
7412
  });
7187
7413
 
7188
7414
  describe("admin API — reconcile open-work seam, in-process composition (GHE-3.9)", () => {
7189
- const compose = (openWork?: ReturnType<typeof fakeOpenWork>["port"]) => {
7415
+ const compose = (
7416
+ openWork?: ReturnType<typeof fakeOpenWork>["port"],
7417
+ env: Record<string, string> | undefined = { GH_APP_ID: "42" },
7418
+ ) => {
7190
7419
  const { prisma, state } = fakePrisma(["acme/old"]);
7191
7420
  const githubReconcile = createGithubReconcile({
7192
7421
  prisma,
7193
7422
  appService: { get: async () => null, getPrivateKey: async () => null },
7194
7423
  access: accessFor(["acme/api"]),
7195
- agentAppId: 42,
7424
+ agentEnv: envWith(env),
7196
7425
  installation: {
7197
7426
  listRepos: async () => ({ acme: ["acme/old", "acme/api"] }),
7198
7427
  addRepos: async () => {},
@@ -7226,6 +7455,20 @@ describe("admin API — reconcile open-work seam, in-process composition (GHE-3.
7226
7455
  expect(state.repos).toEqual(["acme/old"]);
7227
7456
  });
7228
7457
 
7458
+ it("plans for an agent whose GH_APP_ID is in its stored env", async () => {
7459
+ const res = await compose(undefined, { GH_APP_ID: "42" }).plan();
7460
+ expect(res.status).toBe(200);
7461
+ expect(await res.json()).toMatchObject({ status: "planned" });
7462
+ });
7463
+
7464
+ it("reports skipped naming GH_APP_ID for an agent without one", async () => {
7465
+ const res = await compose(undefined, {}).plan();
7466
+ expect(res.status).toBe(200);
7467
+ const body = (await res.json()) as { status: string; reason?: string };
7468
+ expect(body.status).toBe("skipped");
7469
+ expect(body.reason).toContain("GH_APP_ID");
7470
+ });
7471
+
7229
7472
  it("without a port plan lists nothing", async () => {
7230
7473
  const res = await compose().plan();
7231
7474
  expect(res.status).toBe(200);
@@ -7233,3 +7476,303 @@ describe("admin API — reconcile open-work seam, in-process composition (GHE-3.
7233
7476
  expect(body.affectedOpenWork).toEqual([]);
7234
7477
  });
7235
7478
  });
7479
+
7480
+ // ─── IRM-1.2: /agents/:id/github-installation/repos ───────────────────────────
7481
+
7482
+ describe("admin API — agent App installation repos (IRM-1.2)", () => {
7483
+ const OPS = "irm-ops-token";
7484
+ const READER = "irm-read-token";
7485
+ const AGENT_KEY = "irm-agent-token";
7486
+ const { privateKey: PEM } = generateKeyPairSync("rsa", {
7487
+ modulusLength: 2048,
7488
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
7489
+ publicKeyEncoding: { type: "spki", format: "pem" },
7490
+ });
7491
+ const cassette: Record<string, { status: number; body: unknown }> =
7492
+ JSON.parse(
7493
+ readFileSync(
7494
+ new URL("./fixtures/github-enterprise-cassette.json", import.meta.url)
7495
+ .pathname,
7496
+ "utf-8",
7497
+ ),
7498
+ );
7499
+ // The recorded org installation belongs to App 777 (installation 501).
7500
+ const INST = "/enterprises/acme/apps/organizations/acme-eng/installations";
7501
+ const routes: Record<string, string | unknown> = {
7502
+ "GET /enterprises/acme/installation": "enterprise_installation_success",
7503
+ "POST /app/installations/4242/access_tokens": "access_token_success",
7504
+ "GET /enterprises/acme/apps/installable_organizations":
7505
+ "installable_orgs_success",
7506
+ [`GET ${INST}`]: "org_installations_success",
7507
+ [`GET ${INST}/501/repositories`]: "install_repos_success",
7508
+ [`PATCH ${INST}/501/repositories/add`]: "install_repos_add_success",
7509
+ [`PATCH ${INST}/501/repositories/remove`]: "install_repos_remove_success",
7510
+ };
7511
+
7512
+ function setup(
7513
+ opts: {
7514
+ env?: Record<string, string>;
7515
+ username?: string | null;
7516
+ known?: boolean;
7517
+ override?: Record<string, string>;
7518
+ } = {},
7519
+ ) {
7520
+ const audits: Array<Record<string, unknown>> = [];
7521
+ const gh: string[] = [];
7522
+ const table = { ...routes, ...(opts.override ?? {}) };
7523
+ const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
7524
+ const u = new URL(input.toString());
7525
+ const key = `${init?.method ?? "GET"} ${u.pathname}`;
7526
+ gh.push(key);
7527
+ // The recorded installable orgs are org-1/org-2; this agent's App lives on acme-eng.
7528
+ if (key === "GET /enterprises/acme/apps/installable_organizations") {
7529
+ return new Response(JSON.stringify([{ id: 5010, login: "acme-eng" }]), {
7530
+ status: 200,
7531
+ });
7532
+ }
7533
+ const name = table[key] as string | undefined;
7534
+ if (!name) throw new Error(`no route for ${key}`);
7535
+ const entry = cassette[name];
7536
+ if (!entry) throw new Error(`no cassette entry ${name}`);
7537
+ return new Response(JSON.stringify(entry.body), {
7538
+ status: entry.status,
7539
+ headers: { "Content-Type": "application/json" },
7540
+ });
7541
+ }) as typeof fetch;
7542
+ const prisma = {
7543
+ agent: {
7544
+ findUnique: async () =>
7545
+ opts.known === false
7546
+ ? null
7547
+ : {
7548
+ id: AGENT_ID,
7549
+ repos: [],
7550
+ githubUsername:
7551
+ opts.username === undefined ? "dev" : opts.username,
7552
+ },
7553
+ },
7554
+ gitHubReconcileAudit: {
7555
+ create: async (args: { data: Record<string, unknown> }) => {
7556
+ audits.push(args.data);
7557
+ return { id: `audit-${audits.length}` };
7558
+ },
7559
+ },
7560
+ } as unknown as Parameters<
7561
+ typeof createGithubInstallationRepos
7562
+ >[0]["prisma"];
7563
+ const githubInstallationRepos = createGithubInstallationRepos({
7564
+ prisma,
7565
+ appService: {
7566
+ get: async () => ({ appId: 12345, enterpriseSlug: "acme" }) as never,
7567
+ getPrivateKey: async () => PEM,
7568
+ },
7569
+ access: async (username) => {
7570
+ const base = await accessFor(["acme-eng/repo-1"])(username);
7571
+ if (base.status === "unconfigured") return base;
7572
+ const [org] = base.access.orgs;
7573
+ return {
7574
+ ...base,
7575
+ access: {
7576
+ ...base.access,
7577
+ orgs: org ? [{ ...org, org: "acme-eng" }] : [],
7578
+ },
7579
+ };
7580
+ },
7581
+ agentEnv: envWith(opts.env ?? { GH_APP_ID: "777" }),
7582
+ fetchFn,
7583
+ });
7584
+ const base = makeMockDeps();
7585
+ const app = createAdminApp({
7586
+ ...base,
7587
+ adminApiKeys: parseAdminApiKeys(
7588
+ `root:${ADMIN_API_KEY}:*,operator:${OPS}:platform.ops,reader:${READER}:platform.read`,
7589
+ ),
7590
+ agentTokenService: {
7591
+ ...base.agentTokenService,
7592
+ validate: async (t: string) =>
7593
+ t === AGENT_KEY ? { agentId: AGENT_ID } : null,
7594
+ },
7595
+ githubInstallationRepos,
7596
+ });
7597
+ return { app, audits, gh };
7598
+ }
7599
+
7600
+ const asAdmin = { Authorization: `Bearer ${ADMIN_API_KEY}` };
7601
+ const url = (suffix = "", id = AGENT_ID) =>
7602
+ `/agents/${id}/github-installation/repos${suffix}`;
7603
+ const send = (
7604
+ app: ReturnType<typeof createAdminApp>,
7605
+ path: string,
7606
+ headers: Record<string, string>,
7607
+ body: unknown = { repos: ["acme-eng/repo-3"] },
7608
+ ) =>
7609
+ app.request(path, {
7610
+ method: "POST",
7611
+ headers: { "Content-Type": "application/json", ...headers },
7612
+ body: JSON.stringify(body),
7613
+ });
7614
+
7615
+ it("GET lists repos per org with push hints from the access lookup", async () => {
7616
+ const { app } = setup();
7617
+ const res = await app.request(url(), { headers: asAdmin });
7618
+ expect(res.status).toBe(200);
7619
+ expect(await res.json()).toEqual({
7620
+ appId: 777,
7621
+ orgs: [
7622
+ {
7623
+ org: "acme-eng",
7624
+ repos: [
7625
+ { fullName: "acme-eng/repo-1", userCanPush: true },
7626
+ { fullName: "acme-eng/repo-2" },
7627
+ ],
7628
+ },
7629
+ ],
7630
+ });
7631
+ });
7632
+
7633
+ it("GET omits the hint entirely for an agent with no bound username", async () => {
7634
+ const { app } = setup({ username: null });
7635
+ const body = (await (
7636
+ await app.request(url(), { headers: asAdmin })
7637
+ ).json()) as {
7638
+ orgs: { repos: Record<string, unknown>[] }[];
7639
+ };
7640
+ expect(body.orgs[0]?.repos.map((r) => "userCanPush" in r)).toEqual([
7641
+ false,
7642
+ false,
7643
+ ]);
7644
+ });
7645
+
7646
+ it("403 for ops, read and agent keys on every route; no GitHub call, no audit", async () => {
7647
+ const { app, audits, gh } = setup();
7648
+ for (const key of [OPS, READER, AGENT_KEY]) {
7649
+ const h = { Authorization: `Bearer ${key}` };
7650
+ expect((await app.request(url(), { headers: h })).status).toBe(403);
7651
+ expect((await send(app, url(), h)).status).toBe(403);
7652
+ expect((await send(app, url("/remove"), h)).status).toBe(403);
7653
+ }
7654
+ expect(audits).toEqual([]);
7655
+ expect(gh).toEqual([]);
7656
+ });
7657
+
7658
+ it("403 for a non-admin session member", async () => {
7659
+ const { app } = setup();
7660
+ const cookie = await sign(
7661
+ {
7662
+ isAdmin: false,
7663
+ userId: "user-acct",
7664
+ email: "owner@acct-a.example.com",
7665
+ iat: Math.floor(Date.now() / 1000),
7666
+ exp: Math.floor(Date.now() / 1000) + 3600,
7667
+ },
7668
+ SESSION_SECRET,
7669
+ "HS256",
7670
+ );
7671
+ const memberApp = createAdminApp({
7672
+ ...makeMockDeps(),
7673
+ callerScopeResolver: async () => ({
7674
+ kind: "scoped",
7675
+ accountId: "acct-a",
7676
+ agentIds: [AGENT_ID],
7677
+ }),
7678
+ });
7679
+ const res = await memberApp.request(url(), {
7680
+ headers: { Cookie: `admin_session=${cookie}` },
7681
+ });
7682
+ expect(res.status).toBe(403);
7683
+ void app;
7684
+ });
7685
+
7686
+ it("404 for an unknown agent on every route", async () => {
7687
+ const { app, audits } = setup({ known: false });
7688
+ expect((await app.request(url(), { headers: asAdmin })).status).toBe(404);
7689
+ expect((await send(app, url(), asAdmin)).status).toBe(404);
7690
+ expect((await send(app, url("/remove"), asAdmin)).status).toBe(404);
7691
+ expect(audits).toEqual([]);
7692
+ });
7693
+
7694
+ it("422 naming GH_APP_ID when the agent has none", async () => {
7695
+ const { app, audits } = setup({ env: {} });
7696
+ const res = await app.request(url(), { headers: asAdmin });
7697
+ expect(res.status).toBe(422);
7698
+ expect(JSON.stringify(await res.json())).toContain("GH_APP_ID");
7699
+ expect((await send(app, url(), asAdmin)).status).toBe(422);
7700
+ expect(audits).toEqual([]);
7701
+ });
7702
+
7703
+ it("409 when the agent's App is not installed on the org; nothing audited", async () => {
7704
+ // App 999 has no recorded installation on acme-eng.
7705
+ const { app, audits, gh } = setup({ env: { GH_APP_ID: "999" } });
7706
+ const res = await send(app, url(), asAdmin);
7707
+ expect(res.status).toBe(409);
7708
+ expect(JSON.stringify(await res.json())).toContain("not installed");
7709
+ expect(audits).toEqual([]);
7710
+ expect(gh.some((k) => k.startsWith("PATCH"))).toBe(false);
7711
+ });
7712
+
7713
+ it("POST add changes the installation and writes one audit entry with the caller", async () => {
7714
+ const { app, audits, gh } = setup();
7715
+ const res = await send(app, url(), asAdmin, {
7716
+ repos: ["acme-eng/repo-3"],
7717
+ });
7718
+ expect(res.status).toBe(200);
7719
+ expect(await res.json()).toEqual({
7720
+ status: "applied",
7721
+ auditId: "audit-1",
7722
+ repos: ["acme-eng/repo-3"],
7723
+ });
7724
+ expect(gh).toContain(`PATCH ${INST}/501/repositories/add`);
7725
+ expect(audits).toHaveLength(1);
7726
+ expect(audits[0]).toMatchObject({
7727
+ agentId: AGENT_ID,
7728
+ caller: "root",
7729
+ planHash: "direct:add",
7730
+ diff: { installationAdds: ["acme-eng/repo-3"], installationRemoves: [] },
7731
+ result: { status: "applied" },
7732
+ });
7733
+ });
7734
+
7735
+ it("POST remove changes the installation and writes one audit entry", async () => {
7736
+ const { app, audits, gh } = setup();
7737
+ const res = await send(app, url("/remove"), asAdmin, {
7738
+ repos: ["acme-eng/repo-2"],
7739
+ });
7740
+ expect(res.status).toBe(200);
7741
+ expect(gh).toContain(`PATCH ${INST}/501/repositories/remove`);
7742
+ expect(audits).toHaveLength(1);
7743
+ expect(audits[0]).toMatchObject({
7744
+ caller: "root",
7745
+ planHash: "direct:remove",
7746
+ diff: { installationRemoves: ["acme-eng/repo-2"], installationAdds: [] },
7747
+ });
7748
+ });
7749
+
7750
+ it("502 and a failed audit entry when GitHub refuses the change", async () => {
7751
+ const { app, audits } = setup({
7752
+ override: {
7753
+ [`PATCH ${INST}/501/repositories/add`]: "install_repos_add_403",
7754
+ },
7755
+ });
7756
+ const res = await send(app, url(), asAdmin);
7757
+ expect(res.status).toBe(502);
7758
+ expect(audits).toHaveLength(1);
7759
+ expect(audits[0]?.result).toMatchObject({ status: "failed" });
7760
+ });
7761
+
7762
+ it("400 for a body that is not owner/repo names", async () => {
7763
+ const { app, audits } = setup();
7764
+ expect((await send(app, url(), asAdmin, { repos: ["nope"] })).status).toBe(
7765
+ 400,
7766
+ );
7767
+ expect((await send(app, url(), asAdmin, { repos: [] })).status).toBe(400);
7768
+ expect(audits).toEqual([]);
7769
+ });
7770
+
7771
+ it("503 when the Apps are not wired", async () => {
7772
+ const app = createAdminApp({
7773
+ ...makeMockDeps(),
7774
+ adminApiKeys: parseAdminApiKeys(`root:${ADMIN_API_KEY}:*`),
7775
+ });
7776
+ expect((await app.request(url(), { headers: asAdmin })).status).toBe(503);
7777
+ });
7778
+ });