@app-vitals/agent-admin 1.32.0 → 1.34.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.
@@ -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 {
@@ -34,6 +35,11 @@ import {
34
35
  fakeOpenWork,
35
36
  fakePrisma,
36
37
  } from "./github-reconcile-wiring.unit.test.ts";
38
+ import type { OpenWorkPort } from "./reconcile-open-work.ts";
39
+ import {
40
+ repoLostAccessBlockReason,
41
+ repoRemovedFromAgentBlockReason,
42
+ } from "./repo-removal-open-work.ts";
37
43
  import type { SpecialtyType } from "./specialty-types.ts";
38
44
  import { identityCrypto } from "./token-crypto.ts";
39
45
 
@@ -6045,6 +6051,224 @@ describe("admin API — POST/DELETE /agents/:id/repos", () => {
6045
6051
  });
6046
6052
  });
6047
6053
 
6054
+ // ─── Repo removal blocks open work (IRM-1.7) ─────────────────────────────────
6055
+
6056
+ describe("admin API — repo removal blocks open work", () => {
6057
+ const MEMBER_EMAIL = "member@example.com";
6058
+ const ADMIN_KEY = "irm-admin-key";
6059
+ const ITEMS = [{ id: "T-1", repo: "a/one", title: "work" }];
6060
+ const makeApp = (initial: string[], port?: Partial<OpenWorkPort> | null) => {
6061
+ let repos = [...initial];
6062
+ const calls: unknown[][] = [];
6063
+ const base = makeMockDeps();
6064
+ const detail = () => ({
6065
+ id: AGENT_ID,
6066
+ name: "Existing Agent",
6067
+ slackId: null,
6068
+ selfHosted: false,
6069
+ repos: [...repos],
6070
+ reviewAuthorAllowlist: [],
6071
+ patchAuthorAllowlist: [],
6072
+ restrictSlackToMembers: false,
6073
+ specialty: "coding",
6074
+ createdAt: new Date("2024-01-01"),
6075
+ updatedAt: new Date("2024-01-01"),
6076
+ missingRequiredEnv: [],
6077
+ });
6078
+ const openWork: OpenWorkPort | undefined =
6079
+ port === null
6080
+ ? undefined
6081
+ : {
6082
+ listOpenWork: async (...a) => {
6083
+ calls.push(["list", ...a]);
6084
+ return ITEMS;
6085
+ },
6086
+ blockOpenWork: async (...a) => {
6087
+ calls.push(["block", ...a]);
6088
+ },
6089
+ ...port,
6090
+ };
6091
+ const app = createAdminApp({
6092
+ ...base,
6093
+ ...(openWork ? { openWork } : {}),
6094
+ adminApiKeys: parseAdminApiKeys(`admin:${ADMIN_KEY}:*`),
6095
+ agentMemberService: {
6096
+ ...base.agentMemberService,
6097
+ exists: async (agentId: string, email: string) =>
6098
+ agentId === AGENT_ID && email === MEMBER_EMAIL,
6099
+ listByEmail: async (email: string) =>
6100
+ email === MEMBER_EMAIL
6101
+ ? [
6102
+ {
6103
+ id: "m1",
6104
+ agentId: AGENT_ID,
6105
+ email,
6106
+ createdAt: new Date("2024-01-01"),
6107
+ },
6108
+ ]
6109
+ : [],
6110
+ },
6111
+ agentService: {
6112
+ ...base.agentService,
6113
+ exists: async () => true,
6114
+ getDetail: async (id: string) => (id === AGENT_ID ? detail() : null),
6115
+ updateSelfHosted: async (_id: string, input: { repos?: string[] }) => {
6116
+ if (input.repos) repos = input.repos;
6117
+ return detail();
6118
+ },
6119
+ },
6120
+ });
6121
+ return { app, calls, repos: () => repos };
6122
+ };
6123
+ const adminCall = (
6124
+ app: ReturnType<typeof createAdminApp>,
6125
+ method: string,
6126
+ path: string,
6127
+ body?: unknown,
6128
+ ) =>
6129
+ app.request(path, {
6130
+ method,
6131
+ body: body === undefined ? undefined : JSON.stringify(body),
6132
+ headers: {
6133
+ "Content-Type": "application/json",
6134
+ Authorization: `Bearer ${ADMIN_KEY}`,
6135
+ },
6136
+ });
6137
+ const memberCall = async (
6138
+ app: ReturnType<typeof createAdminApp>,
6139
+ method: string,
6140
+ path: string,
6141
+ body?: unknown,
6142
+ ) => {
6143
+ const cookie = await sign(
6144
+ {
6145
+ isAdmin: false,
6146
+ userId: "user-m",
6147
+ email: MEMBER_EMAIL,
6148
+ iat: Math.floor(Date.now() / 1000),
6149
+ exp: Math.floor(Date.now() / 1000) + 3600,
6150
+ },
6151
+ SESSION_SECRET,
6152
+ "HS256",
6153
+ );
6154
+ return app.request(path, {
6155
+ method,
6156
+ body: body === undefined ? undefined : JSON.stringify(body),
6157
+ headers: {
6158
+ "Content-Type": "application/json",
6159
+ Cookie: `admin_session=${cookie}`,
6160
+ },
6161
+ });
6162
+ };
6163
+ const url = `/agents/${AGENT_ID}/repos`;
6164
+ const blockCall = (repo: string) => [
6165
+ "block",
6166
+ AGENT_ID,
6167
+ [repo],
6168
+ repoRemovedFromAgentBlockReason(repo),
6169
+ ];
6170
+
6171
+ it("DELETE as platform admin blocks open work with a reason naming the repo", async () => {
6172
+ const { app, calls } = makeApp(["a/one", "b/two"]);
6173
+ const res = await adminCall(app, "DELETE", `${url}/a/one`);
6174
+ expect(res.status).toBe(200);
6175
+ expect((await res.json()).repos).toEqual(["b/two"]);
6176
+ expect(calls).toEqual([blockCall("a/one")]);
6177
+ });
6178
+
6179
+ it("DELETE as a session member blocks open work too", async () => {
6180
+ const { app, calls } = makeApp(["a/one", "b/two"]);
6181
+ const res = await memberCall(app, "DELETE", `${url}/a/one`);
6182
+ expect(res.status).toBe(200);
6183
+ expect(calls).toEqual([blockCall("a/one")]);
6184
+ });
6185
+
6186
+ it("a port failure is a warning and the removal still succeeds", async () => {
6187
+ const { app, repos } = makeApp(["a/one"], {
6188
+ blockOpenWork: async () => {
6189
+ throw new Error("store down");
6190
+ },
6191
+ });
6192
+ const res = await adminCall(app, "DELETE", `${url}/a/one`);
6193
+ expect(res.status).toBe(200);
6194
+ const body = await res.json();
6195
+ expect(body.repos).toEqual([]);
6196
+ expect(body.warning).toContain("store down");
6197
+ expect(repos()).toEqual([]);
6198
+ });
6199
+
6200
+ it("DELETE without a port just removes the repo", async () => {
6201
+ const { app } = makeApp(["a/one"], null);
6202
+ const res = await adminCall(app, "DELETE", `${url}/a/one`);
6203
+ expect(res.status).toBe(200);
6204
+ expect((await res.json()).warning).toBeUndefined();
6205
+ });
6206
+
6207
+ it("PATCH that drops repos blocks only the dropped ones", async () => {
6208
+ const { app, calls } = makeApp(["a/one", "b/two", "c/three"]);
6209
+ const res = await memberCall(app, "PATCH", `/agents/${AGENT_ID}`, {
6210
+ repos: ["b/two"],
6211
+ });
6212
+ expect(res.status).toBe(200);
6213
+ expect(calls).toEqual([blockCall("a/one"), blockCall("c/three")]);
6214
+ });
6215
+
6216
+ it("adding a repo (POST, or PATCH that only adds) never touches open work", async () => {
6217
+ const { app, calls } = makeApp(["a/one"]);
6218
+ expect(
6219
+ (await adminCall(app, "POST", url, { repos: ["b/two"] })).status,
6220
+ ).toBe(200);
6221
+ expect(
6222
+ (
6223
+ await adminCall(app, "PATCH", `/agents/${AGENT_ID}`, {
6224
+ repos: ["a/one", "b/two", "c/three"],
6225
+ })
6226
+ ).status,
6227
+ ).toBe(200);
6228
+ expect(calls).toEqual([]);
6229
+ });
6230
+
6231
+ it("preview lists open work for admin and member without changing anything", async () => {
6232
+ const { app, calls, repos } = makeApp(["a/one", "b/two"]);
6233
+ for (const res of [
6234
+ await adminCall(app, "GET", `${url}/a/one/removal-preview`),
6235
+ await memberCall(app, "GET", `${url}/a/one/removal-preview`),
6236
+ ]) {
6237
+ expect(res.status).toBe(200);
6238
+ expect(await res.json()).toEqual({
6239
+ repo: "a/one",
6240
+ openWork: ITEMS,
6241
+ warnings: [],
6242
+ });
6243
+ }
6244
+ expect(calls.every((c) => c[0] === "list")).toBe(true);
6245
+ expect(repos()).toEqual(["a/one", "b/two"]);
6246
+ });
6247
+
6248
+ it("preview is empty with no port, warns on a port failure, 404s for a repo the agent lacks", async () => {
6249
+ const none = makeApp(["a/one"], null);
6250
+ expect(
6251
+ await (
6252
+ await adminCall(none.app, "GET", `${url}/a/one/removal-preview`)
6253
+ ).json(),
6254
+ ).toEqual({ repo: "a/one", openWork: [], warnings: [] });
6255
+ const failing = makeApp(["a/one"], {
6256
+ listOpenWork: async () => {
6257
+ throw new Error("nope");
6258
+ },
6259
+ });
6260
+ const body = await (
6261
+ await adminCall(failing.app, "GET", `${url}/a/one/removal-preview`)
6262
+ ).json();
6263
+ expect(body.openWork).toEqual([]);
6264
+ expect(body.warnings[0]).toContain("nope");
6265
+ expect(
6266
+ (await adminCall(failing.app, "GET", `${url}/z/nope/removal-preview`))
6267
+ .status,
6268
+ ).toBe(404);
6269
+ });
6270
+ });
6271
+
6048
6272
  // ─── Platform scopes (COS-28.1) ─────────────────────────────────────────────
6049
6273
 
6050
6274
  describe("platform.read / platform.ops keys over the real route table", () => {
@@ -7556,3 +7780,275 @@ describe("admin API — agent App installation repos (IRM-1.2)", () => {
7556
7780
  expect((await app.request(url(), { headers: asAdmin })).status).toBe(503);
7557
7781
  });
7558
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
+ });