@app-vitals/agent-admin 1.33.0 → 1.35.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.
package/src/admin-ui.ts CHANGED
@@ -63,6 +63,21 @@ import {
63
63
  renderGithubReconcileApplyResult,
64
64
  renderGithubReconcilePlanResult,
65
65
  } from "./admin-ui-github-reconcile-pages.ts";
66
+ import {
67
+ actuallyBlockedWork,
68
+ type InstallationReposView,
69
+ type LostAccessPreviewView,
70
+ type LostAccessRemoveView,
71
+ type OpenWorkView,
72
+ type RepoRemovalPreviewView,
73
+ renderInstallationChangeResult,
74
+ renderInstallationReposBody,
75
+ renderInstallationReposError,
76
+ renderLostAccessPreview,
77
+ renderLostAccessResult,
78
+ renderRepoRemovalConfirm,
79
+ renderRepoRemovalResult,
80
+ } from "./admin-ui-installation-repos-pages.ts";
66
81
  import {
67
82
  type AgentDetail,
68
83
  type AgentOption,
@@ -1985,6 +2000,233 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
1985
2000
  },
1986
2001
  );
1987
2002
 
2003
+ // IRM-1.4: thin proxies over the installation repos (IRM-1.2) and
2004
+ // lost-access (IRM-1.3) routes, plus the repo-removal preview (IRM-1.7).
2005
+ // They return HTML fragments for the Installation repos card and the agent's
2006
+ // repos list; the agents API enforces platform-admin too.
2007
+ const apiErrorFragment = async (res: Response | null, fallback: string) => {
2008
+ let message = fallback;
2009
+ try {
2010
+ const j = (await res?.json()) as { error?: unknown };
2011
+ if (typeof j.error === "string" && j.error) message = j.error;
2012
+ } catch {
2013
+ // keep the fallback
2014
+ }
2015
+ const status = res && res.status >= 400 ? res.status : 502;
2016
+ return html(renderInstallationReposError(status, message), { status });
2017
+ };
2018
+ const readBody = async (c: Context<AdminUIEnv>) => {
2019
+ try {
2020
+ const parsed = await c.req.json();
2021
+ if (parsed && typeof parsed === "object") {
2022
+ return parsed as Record<string, unknown>;
2023
+ }
2024
+ } catch {
2025
+ // empty body
2026
+ }
2027
+ return {} as Record<string, unknown>;
2028
+ };
2029
+ const stringList = (v: unknown): string[] =>
2030
+ Array.isArray(v) ? v.filter((r): r is string => typeof r === "string") : [];
2031
+ const postJson = (c: Context<AdminUIEnv>, path: string, body: unknown) =>
2032
+ callApi(c, agentsApi as NonNullable<typeof agentsApi>, path, {
2033
+ method: "POST",
2034
+ headers: { "content-type": "application/json" },
2035
+ body: JSON.stringify(body),
2036
+ });
2037
+ const apiId = (c: Context<AdminUIEnv>) =>
2038
+ encodeURIComponent(c.req.param("id") ?? "");
2039
+
2040
+ app.get("/admin/agents/:id/github-installation", requireAuth, async (c) => {
2041
+ if (!c.var.isAdmin || !agentsApi) {
2042
+ return new Response("Forbidden", { status: 403 });
2043
+ }
2044
+ const agentId = c.req.param("id") ?? "";
2045
+ const res = await callApi(
2046
+ c,
2047
+ agentsApi,
2048
+ `/agents/${apiId(c)}/github-installation/repos`,
2049
+ );
2050
+ if (!res?.ok) {
2051
+ return apiErrorFragment(res, "Could not load the installation repos.");
2052
+ }
2053
+ const agent = await agentService.getDetail(agentId);
2054
+ return html(
2055
+ renderInstallationReposBody(
2056
+ (await res.json()) as InstallationReposView,
2057
+ agent?.githubUsername,
2058
+ ),
2059
+ );
2060
+ });
2061
+
2062
+ for (const kind of ["add", "remove"] as const) {
2063
+ app.post(
2064
+ `/admin/agents/:id/github-installation/repos/${kind}`,
2065
+ requireAuth,
2066
+ async (c) => {
2067
+ if (!c.var.isAdmin || !agentsApi) {
2068
+ return new Response("Forbidden", { status: 403 });
2069
+ }
2070
+ const repos = stringList((await readBody(c)).repos);
2071
+ const res = await postJson(
2072
+ c,
2073
+ `/agents/${apiId(c)}/github-installation/repos${kind === "add" ? "" : "/remove"}`,
2074
+ { repos },
2075
+ );
2076
+ if (!res?.ok) {
2077
+ return apiErrorFragment(res, `Could not ${kind} the repos.`);
2078
+ }
2079
+ return html(
2080
+ renderInstallationChangeResult(
2081
+ kind,
2082
+ (await res.json()) as { auditId?: string; repos?: string[] },
2083
+ ),
2084
+ );
2085
+ },
2086
+ );
2087
+ }
2088
+
2089
+ app.get(
2090
+ "/admin/agents/:id/github-lost-access/preview",
2091
+ requireAuth,
2092
+ async (c) => {
2093
+ if (!c.var.isAdmin || !agentsApi) {
2094
+ return new Response("Forbidden", { status: 403 });
2095
+ }
2096
+ const res = await callApi(
2097
+ c,
2098
+ agentsApi,
2099
+ `/agents/${apiId(c)}/github-lost-access/preview`,
2100
+ );
2101
+ if (!res?.ok) {
2102
+ return apiErrorFragment(res, "Could not preview the removal.");
2103
+ }
2104
+ return html(
2105
+ renderLostAccessPreview((await res.json()) as LostAccessPreviewView),
2106
+ );
2107
+ },
2108
+ );
2109
+
2110
+ app.post(
2111
+ "/admin/agents/:id/github-lost-access/remove",
2112
+ requireAuth,
2113
+ async (c) => {
2114
+ if (!c.var.isAdmin || !agentsApi) {
2115
+ return new Response("Forbidden", { status: 403 });
2116
+ }
2117
+ const body = await readBody(c);
2118
+ const repos = stringList(body.repos);
2119
+ // The open work the removal will block, read just before it happens so
2120
+ // the result can show what was actually blocked.
2121
+ let seen: OpenWorkView[] = [];
2122
+ const pre = await callApi(
2123
+ c,
2124
+ agentsApi,
2125
+ `/agents/${apiId(c)}/github-lost-access/preview`,
2126
+ );
2127
+ if (pre?.ok) {
2128
+ try {
2129
+ seen = ((await pre.json()) as LostAccessPreviewView).openWork ?? [];
2130
+ } catch {
2131
+ // no preview: nothing is claimed as blocked
2132
+ }
2133
+ }
2134
+ const res = await postJson(
2135
+ c,
2136
+ `/agents/${apiId(c)}/github-lost-access/remove`,
2137
+ { repos, confirmRemovals: body.confirmRemovals === true },
2138
+ );
2139
+ if (!res?.ok) {
2140
+ return apiErrorFragment(res, "Could not remove the repos.");
2141
+ }
2142
+ const result = (await res.json()) as LostAccessRemoveView;
2143
+ const blocked =
2144
+ result.status === "applied"
2145
+ ? actuallyBlockedWork(seen, result.repos ?? [], result.warnings ?? [])
2146
+ : [];
2147
+ return html(renderLostAccessResult(result, blocked));
2148
+ },
2149
+ );
2150
+
2151
+ const splitRepo = (repo: string): [string, string] | null =>
2152
+ isOrgRepo(repo) ? (repo.split("/") as [string, string]) : null;
2153
+ const repoApiPath = (c: Context<AdminUIEnv>, repo: [string, string]) =>
2154
+ `/agents/${apiId(c)}/repos/${encodeURIComponent(repo[0])}/${encodeURIComponent(repo[1])}`;
2155
+
2156
+ app.get("/admin/agents/:id/repos/removal-confirm", requireAuth, async (c) => {
2157
+ if (!c.var.isAdmin || !agentsApi) {
2158
+ return new Response("Forbidden", { status: 403 });
2159
+ }
2160
+ const repo = splitRepo(c.req.query("repo") ?? "");
2161
+ if (!repo) {
2162
+ return html(renderInstallationReposError(400, "Invalid repo."), {
2163
+ status: 400,
2164
+ });
2165
+ }
2166
+ const res = await callApi(
2167
+ c,
2168
+ agentsApi,
2169
+ `${repoApiPath(c, repo)}/removal-preview`,
2170
+ );
2171
+ if (!res?.ok) {
2172
+ return apiErrorFragment(res, "Could not preview the removal.");
2173
+ }
2174
+ return html(
2175
+ renderRepoRemovalConfirm(
2176
+ c.req.param("id") ?? "",
2177
+ (await res.json()) as RepoRemovalPreviewView,
2178
+ ),
2179
+ );
2180
+ });
2181
+
2182
+ app.post(
2183
+ "/admin/agents/:id/repos/remove-confirmed",
2184
+ requireAuth,
2185
+ async (c) => {
2186
+ if (!c.var.isAdmin || !agentsApi) {
2187
+ return new Response("Forbidden", { status: 403 });
2188
+ }
2189
+ const name = String((await readBody(c)).repo ?? "");
2190
+ const repo = splitRepo(name);
2191
+ if (!repo) {
2192
+ return html(renderInstallationReposError(400, "Invalid repo."), {
2193
+ status: 400,
2194
+ });
2195
+ }
2196
+ let seen: OpenWorkView[] = [];
2197
+ const pre = await callApi(
2198
+ c,
2199
+ agentsApi,
2200
+ `${repoApiPath(c, repo)}/removal-preview`,
2201
+ );
2202
+ if (pre?.ok) {
2203
+ try {
2204
+ seen = ((await pre.json()) as RepoRemovalPreviewView).openWork ?? [];
2205
+ } catch {
2206
+ // no preview: nothing is claimed as blocked
2207
+ }
2208
+ }
2209
+ const res = await callApi(c, agentsApi, repoApiPath(c, repo), {
2210
+ method: "DELETE",
2211
+ });
2212
+ if (!res?.ok) return apiErrorFragment(res, "Could not remove the repo.");
2213
+ let warning = "";
2214
+ try {
2215
+ warning = ((await res.json()) as { warning?: string }).warning ?? "";
2216
+ } catch {
2217
+ // no warning
2218
+ }
2219
+ const warnings = warning ? warning.split("; ") : [];
2220
+ return html(
2221
+ renderRepoRemovalResult(
2222
+ name,
2223
+ actuallyBlockedWork(seen, [name], warnings),
2224
+ warnings,
2225
+ ),
2226
+ );
2227
+ },
2228
+ );
2229
+
1988
2230
  app.get("/admin/agents/:id", requireAuth, async (c) => {
1989
2231
  const agentId = c.req.param("id");
1990
2232
  const agent = await agentService.getDetail(agentId);
@@ -2073,6 +2315,31 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2073
2315
  },
2074
2316
  );
2075
2317
 
2318
+ // IRM-1.4: the repos the agent App's installation covers, for the repos
2319
+ // list's coverage warning. Best effort: unknown means no warning.
2320
+ const enterpriseConfigured = await githubEnterpriseConfigured(c);
2321
+ let installationRepos: string[] | undefined;
2322
+ if (
2323
+ enterpriseConfigured &&
2324
+ agentsApi &&
2325
+ "GH_APP_ID" in (envResult.env ?? {})
2326
+ ) {
2327
+ const res = await callApi(
2328
+ c,
2329
+ agentsApi,
2330
+ `/agents/${encodeURIComponent(agentId)}/github-installation/repos`,
2331
+ );
2332
+ if (res?.ok) {
2333
+ try {
2334
+ installationRepos = (
2335
+ (await res.json()) as InstallationReposView
2336
+ ).orgs.flatMap((o) => o.repos.map((r) => r.fullName));
2337
+ } catch {
2338
+ // unknown: no coverage warning
2339
+ }
2340
+ }
2341
+ }
2342
+
2076
2343
  return html(
2077
2344
  renderAgentDetailPage(
2078
2345
  agentDetail,
@@ -2095,7 +2362,8 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2095
2362
  configurationCardsHtml: cards.configuration,
2096
2363
  queueActivityLinks: deps.queueActivityLinks,
2097
2364
  marketplaces,
2098
- githubEnterpriseConfigured: await githubEnterpriseConfigured(c),
2365
+ githubEnterpriseConfigured: enterpriseConfigured,
2366
+ ...(installationRepos ? { installationRepos } : {}),
2099
2367
  },
2100
2368
  ),
2101
2369
  );
@@ -26,6 +26,7 @@ import { createAdminApp, parseAdminApiKeys } from "./agents-api.ts";
26
26
  import { PLATFORM_OPS_ROUTES } from "./api-auth.ts";
27
27
  import {
28
28
  createGithubInstallationRepos,
29
+ createGithubLostAccessRemoval,
29
30
  createGithubReconcile,
30
31
  } from "./github-reconcile-wiring.ts";
31
32
  import {
@@ -35,7 +36,10 @@ import {
35
36
  fakePrisma,
36
37
  } from "./github-reconcile-wiring.unit.test.ts";
37
38
  import type { OpenWorkPort } from "./reconcile-open-work.ts";
38
- import { repoRemovedFromAgentBlockReason } from "./repo-removal-open-work.ts";
39
+ import {
40
+ repoLostAccessBlockReason,
41
+ repoRemovedFromAgentBlockReason,
42
+ } from "./repo-removal-open-work.ts";
39
43
  import type { SpecialtyType } from "./specialty-types.ts";
40
44
  import { identityCrypto } from "./token-crypto.ts";
41
45
 
@@ -7776,3 +7780,275 @@ describe("admin API — agent App installation repos (IRM-1.2)", () => {
7776
7780
  expect((await app.request(url(), { headers: asAdmin })).status).toBe(503);
7777
7781
  });
7778
7782
  });
7783
+
7784
+ // ─── IRM-1.3: /agents/:id/github-lost-access ──────────────────────────────────
7785
+
7786
+ describe("admin API — remove repos the bound user lost access to (IRM-1.3)", () => {
7787
+ const OPS = "irm13-ops-token";
7788
+ const AGENT_KEY = "irm13-agent-token";
7789
+
7790
+ function setup(
7791
+ opts: {
7792
+ repos?: string[];
7793
+ installed?: string[];
7794
+ username?: string | null;
7795
+ known?: boolean;
7796
+ openWork?: Partial<OpenWorkPort> | null;
7797
+ access?: AdminDeps["githubAccessPreview"];
7798
+ } = {},
7799
+ ) {
7800
+ const state = {
7801
+ repos: [...(opts.repos ?? ["acme/api", "acme/old"])],
7802
+ installed: [...(opts.installed ?? ["acme/api", "acme/old", "acme/gone"])],
7803
+ };
7804
+ const audits: Array<Record<string, unknown>> = [];
7805
+ const calls: unknown[][] = [];
7806
+ const prisma = {
7807
+ agent: {
7808
+ findUnique: async () =>
7809
+ opts.known === false
7810
+ ? null
7811
+ : {
7812
+ id: AGENT_ID,
7813
+ repos: [...state.repos],
7814
+ githubUsername:
7815
+ opts.username === undefined ? "dev" : opts.username,
7816
+ },
7817
+ update: async (args: { data: { repos: string[] } }) => {
7818
+ calls.push(["setRepos", args.data.repos]);
7819
+ state.repos = args.data.repos;
7820
+ },
7821
+ },
7822
+ gitHubReconcileAudit: {
7823
+ create: async (args: { data: Record<string, unknown> }) => {
7824
+ calls.push(["audit"]);
7825
+ audits.push(args.data);
7826
+ return { id: `audit-${audits.length}` };
7827
+ },
7828
+ },
7829
+ } as unknown as Parameters<
7830
+ typeof createGithubLostAccessRemoval
7831
+ >[0]["prisma"];
7832
+ const openWork: OpenWorkPort | undefined =
7833
+ opts.openWork === null
7834
+ ? undefined
7835
+ : {
7836
+ listOpenWork: async (...a) => {
7837
+ calls.push(["list", ...a]);
7838
+ return [{ id: "T-1", repo: "acme/old", title: "fix it" }];
7839
+ },
7840
+ blockOpenWork: async (...a) => {
7841
+ calls.push(["block", ...a]);
7842
+ },
7843
+ ...opts.openWork,
7844
+ };
7845
+ const githubLostAccessRemoval = createGithubLostAccessRemoval({
7846
+ prisma,
7847
+ appService: { get: async () => null, getPrivateKey: async () => null },
7848
+ access: opts.access ?? accessFor(["acme/api"]),
7849
+ agentEnv: envWith({ GH_APP_ID: "42" }),
7850
+ installationRepos: {
7851
+ listInstalled: async () => [
7852
+ { org: "acme", repos: [...state.installed] },
7853
+ ],
7854
+ listRepos: async () => ({ acme: [...state.installed] }),
7855
+ addRepos: async () => {},
7856
+ removeRepos: async (_appId, org, repos) => {
7857
+ calls.push(["removeRepos", org, [...repos]]);
7858
+ state.installed = state.installed.filter((r) => !repos.includes(r));
7859
+ },
7860
+ },
7861
+ ...(openWork ? { openWork } : {}),
7862
+ });
7863
+ const base = makeMockDeps();
7864
+ const app = createAdminApp({
7865
+ ...base,
7866
+ adminApiKeys: parseAdminApiKeys(
7867
+ `root:${ADMIN_API_KEY}:*,operator:${OPS}:platform.ops`,
7868
+ ),
7869
+ agentTokenService: {
7870
+ ...base.agentTokenService,
7871
+ validate: async (t: string) =>
7872
+ t === AGENT_KEY ? { agentId: AGENT_ID } : null,
7873
+ },
7874
+ githubLostAccessRemoval,
7875
+ });
7876
+ return { app, audits, calls, state };
7877
+ }
7878
+
7879
+ const asAdmin = { Authorization: `Bearer ${ADMIN_API_KEY}` };
7880
+ const previewUrl = `/agents/${AGENT_ID}/github-lost-access/preview`;
7881
+ const removeUrl = `/agents/${AGENT_ID}/github-lost-access/remove`;
7882
+ const remove = (
7883
+ app: ReturnType<typeof createAdminApp>,
7884
+ body: unknown,
7885
+ headers: Record<string, string> = asAdmin,
7886
+ ) =>
7887
+ app.request(removeUrl, {
7888
+ method: "POST",
7889
+ headers: { "Content-Type": "application/json", ...headers },
7890
+ body: JSON.stringify(body),
7891
+ });
7892
+
7893
+ it("preview lists the repos that would be removed and their open work, changing nothing", async () => {
7894
+ const { app, audits, calls, state } = setup();
7895
+ const res = await app.request(previewUrl, { headers: asAdmin });
7896
+ expect(res.status).toBe(200);
7897
+ expect(await res.json()).toEqual({
7898
+ status: "previewed",
7899
+ repos: ["acme/gone", "acme/old"],
7900
+ installationRemoves: ["acme/gone", "acme/old"],
7901
+ configRemoves: ["acme/old"],
7902
+ skippedOrgs: [],
7903
+ openWork: [{ id: "T-1", repo: "acme/old", title: "fix it" }],
7904
+ warnings: [],
7905
+ });
7906
+ expect(audits).toEqual([]);
7907
+ expect(calls.map((c) => c[0])).toEqual(["list"]);
7908
+ expect(state.repos).toEqual(["acme/api", "acme/old"]);
7909
+ });
7910
+
7911
+ it("preview reports a failing open-work port as a warning", async () => {
7912
+ const { app } = setup({
7913
+ openWork: {
7914
+ listOpenWork: async () => {
7915
+ throw new Error("store down");
7916
+ },
7917
+ },
7918
+ });
7919
+ const body = (await (
7920
+ await app.request(previewUrl, { headers: asAdmin })
7921
+ ).json()) as { openWork: unknown[]; warnings: string[] };
7922
+ expect(body.openWork).toEqual([]);
7923
+ expect(body.warnings.join()).toContain("store down");
7924
+ });
7925
+
7926
+ it("remove applies the confirmed repos in order, audits once, and blocks open work", async () => {
7927
+ const { app, audits, calls, state } = setup();
7928
+ const res = await remove(app, { repos: ["acme/old", "acme/api"] });
7929
+ expect(res.status).toBe(200);
7930
+ expect(await res.json()).toEqual({
7931
+ status: "applied",
7932
+ auditId: "audit-1",
7933
+ repos: ["acme/old"],
7934
+ installationRemoves: ["acme/old"],
7935
+ configRemoves: ["acme/old"],
7936
+ notRemoved: [
7937
+ {
7938
+ repo: "acme/api",
7939
+ reason: "the bound user can still push to this repo",
7940
+ },
7941
+ ],
7942
+ skippedOrgs: [],
7943
+ warnings: [],
7944
+ });
7945
+ expect(calls).toEqual([
7946
+ ["removeRepos", "acme", ["acme/old"]],
7947
+ ["setRepos", ["acme/api"]],
7948
+ ["audit"],
7949
+ ["block", AGENT_ID, ["acme/old"], repoLostAccessBlockReason("acme/old")],
7950
+ ]);
7951
+ expect(state.repos).toEqual(["acme/api"]);
7952
+ expect(state.installed).toEqual(["acme/api", "acme/gone"]);
7953
+ expect(audits).toHaveLength(1);
7954
+ expect(audits[0]).toMatchObject({
7955
+ agentId: AGENT_ID,
7956
+ caller: "root",
7957
+ planHash: "lost-access:remove",
7958
+ result: { status: "applied" },
7959
+ });
7960
+ });
7961
+
7962
+ it("a failing open-work port is a warning, not a failed call", async () => {
7963
+ const { app, state, audits } = setup({
7964
+ openWork: {
7965
+ blockOpenWork: async () => {
7966
+ throw new Error("store down");
7967
+ },
7968
+ },
7969
+ });
7970
+ const res = await remove(app, { repos: ["acme/old"] });
7971
+ expect(res.status).toBe(200);
7972
+ const body = (await res.json()) as { status: string; warnings: string[] };
7973
+ expect(body.status).toBe("applied");
7974
+ expect(body.warnings[0]).toContain("acme/old");
7975
+ expect(body.warnings[0]).toContain("store down");
7976
+ expect(state.repos).toEqual(["acme/api"]);
7977
+ expect(audits).toHaveLength(1);
7978
+ });
7979
+
7980
+ it("skipped for an unbound user: nothing changed, no audit", async () => {
7981
+ const { app, audits, calls } = setup({ username: null });
7982
+ const res = await remove(app, { repos: ["acme/old"] });
7983
+ expect(res.status).toBe(200);
7984
+ expect(await res.json()).toMatchObject({ status: "skipped" });
7985
+ expect((await app.request(previewUrl, { headers: asAdmin })).status).toBe(
7986
+ 200,
7987
+ );
7988
+ expect(audits).toEqual([]);
7989
+ expect(calls).toEqual([]);
7990
+ });
7991
+
7992
+ it("skipped for an unverified user: nothing changed, no audit", async () => {
7993
+ const verified = accessFor(["acme/api"]);
7994
+ const { app, audits, calls } = setup({
7995
+ access: async (u) => {
7996
+ const r = await verified(u);
7997
+ return r.status === "ok"
7998
+ ? { ...r, access: { ...r.access, userVerified: false } }
7999
+ : r;
8000
+ },
8001
+ });
8002
+ const res = await remove(app, { repos: ["acme/old"] });
8003
+ const body = (await res.json()) as { status: string; reason: string };
8004
+ expect(body.status).toBe("skipped");
8005
+ expect(body.reason).toContain("verified");
8006
+ expect(audits).toEqual([]);
8007
+ expect(calls).toEqual([]);
8008
+ });
8009
+
8010
+ it("422 for more than 10 removals without confirmRemovals; nothing changed", async () => {
8011
+ const many = Array.from({ length: 11 }, (_, i) => `acme/r${i}`);
8012
+ const { app, audits, state } = setup({ repos: many, installed: many });
8013
+ const res = await remove(app, { repos: many });
8014
+ expect(res.status).toBe(422);
8015
+ expect(JSON.stringify(await res.json())).toContain("confirmRemovals");
8016
+ expect(audits).toEqual([]);
8017
+ expect(state.repos).toEqual(many);
8018
+ const ok = await remove(app, { repos: many, confirmRemovals: true });
8019
+ expect(ok.status).toBe(200);
8020
+ expect(state.repos).toEqual([]);
8021
+ });
8022
+
8023
+ it("noop when nothing named still lacks access; no audit", async () => {
8024
+ const { app, audits } = setup();
8025
+ const res = await remove(app, { repos: ["acme/api"] });
8026
+ expect(res.status).toBe(200);
8027
+ expect(await res.json()).toMatchObject({ status: "noop", repos: [] });
8028
+ expect(audits).toEqual([]);
8029
+ });
8030
+
8031
+ it("403 for ops and agent keys; 404 unknown agent; 400 bad body; 503 unwired", async () => {
8032
+ const { app, audits } = setup();
8033
+ for (const key of [OPS, AGENT_KEY]) {
8034
+ const h = { Authorization: `Bearer ${key}` };
8035
+ expect((await app.request(previewUrl, { headers: h })).status).toBe(403);
8036
+ expect((await remove(app, { repos: ["acme/old"] }, h)).status).toBe(403);
8037
+ }
8038
+ expect((await remove(app, { repos: [] })).status).toBe(400);
8039
+ expect((await remove(app, { repos: ["nope"] })).status).toBe(400);
8040
+ expect(audits).toEqual([]);
8041
+ const unknown = setup({ known: false }).app;
8042
+ expect(
8043
+ (await unknown.request(previewUrl, { headers: asAdmin })).status,
8044
+ ).toBe(404);
8045
+ expect((await remove(unknown, { repos: ["acme/old"] })).status).toBe(404);
8046
+ const unwired = createAdminApp({
8047
+ ...makeMockDeps(),
8048
+ adminApiKeys: parseAdminApiKeys(`root:${ADMIN_API_KEY}:*`),
8049
+ });
8050
+ expect(
8051
+ (await unwired.request(previewUrl, { headers: asAdmin })).status,
8052
+ ).toBe(503);
8053
+ });
8054
+ });