@app-vitals/agent-admin 1.33.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.
@@ -0,0 +1,333 @@
1
+ /**
2
+ * admin/src/lost-access-removal.ts
3
+ * Lost-access removal (IRM-1.3): removes, from both the agent App's
4
+ * installation and the agent's own repos, every repo the agent's bound GitHub
5
+ * user can no longer push to. It never adds repos.
6
+ *
7
+ * The admin reviews a read-only preview, then sends the exact repos they
8
+ * confirmed; the server re-checks each against the user's current access and
9
+ * removes only those still without it (no plan hash). The safety rules are the
10
+ * reconcile planner's (accessSkipReason / orgSkipReason): unknown is never
11
+ * none, so orgs with a missing, partial or failed listing, or a selected-only
12
+ * lookup install, are skipped and reported; an unbound, not-found or
13
+ * unverified user skips the whole call. More than MAX_UNCONFIRMED_REMOVALS
14
+ * removals need confirmRemovals.
15
+ *
16
+ * Order: installation removals, then the agent's repos, then one audit entry,
17
+ * then the agent's open work on the removed repos is blocked through the
18
+ * optional OpenWorkPort (a port failure is a warning, never a failed call).
19
+ */
20
+
21
+ import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
22
+ import type { InstallationReposPort } from "./installation-repos-service.ts";
23
+ import {
24
+ MAX_UNCONFIRMED_REMOVALS,
25
+ MISSING_APP_ID_REASON,
26
+ type ReconcileAgentRecord,
27
+ type ReconcileAgentsPort,
28
+ type ReconcileAuditPort,
29
+ } from "./reconcile-apply-service.ts";
30
+ import type { OpenWorkItem, OpenWorkPort } from "./reconcile-open-work.ts";
31
+ import {
32
+ accessSkipReason,
33
+ type OrgSkip,
34
+ orgSkipReason,
35
+ repoOrg,
36
+ } from "./reconcile-planner.ts";
37
+ import {
38
+ blockRepoRemovalWork,
39
+ previewRepoRemovalWork,
40
+ repoLostAccessBlockReason,
41
+ } from "./repo-removal-open-work.ts";
42
+ import type { UserRepoAccessResult } from "./user-repo-access-resolver.ts";
43
+
44
+ /** `planHash` of the audit row a lost-access removal writes. */
45
+ export const LOST_ACCESS_AUDIT_PLAN_HASH = "lost-access:remove";
46
+
47
+ export const STILL_PUSHABLE_REASON =
48
+ "the bound user can still push to this repo";
49
+ export const NOT_PRESENT_REASON =
50
+ "not on the agent installation or in the agent's repos";
51
+
52
+ export interface LostAccessPlanInput {
53
+ username: string | null | undefined;
54
+ /** Null when the resolver was not run. */
55
+ access: UserRepoAccessResult | null;
56
+ agentRepos: readonly string[];
57
+ /** Repos the agent App's installation covers, per org login. */
58
+ installationRepos: Readonly<Record<string, readonly string[]>>;
59
+ /**
60
+ * The repos the admin confirmed. When set, only these are candidates and
61
+ * every one left alone is reported in `notRemoved`; when unset (preview),
62
+ * every installation and agent repo is a candidate.
63
+ */
64
+ requested?: readonly string[];
65
+ }
66
+
67
+ export interface NotRemovedRepo {
68
+ repo: string;
69
+ reason: string;
70
+ }
71
+
72
+ export interface LostAccessPlan {
73
+ skipped: boolean;
74
+ skipReason?: string;
75
+ /** Every repo removed from either place, sorted. */
76
+ repos: string[];
77
+ installationRemoves: string[];
78
+ configRemoves: string[];
79
+ skippedOrgs: OrgSkip[];
80
+ notRemoved: NotRemovedRepo[];
81
+ warnings: string[];
82
+ }
83
+
84
+ const lower = (s: string): string => s.toLowerCase();
85
+ const sorted = (xs: Iterable<string>): string[] => [...xs].sort();
86
+
87
+ function skippedPlan(reason: string): LostAccessPlan {
88
+ return {
89
+ skipped: true,
90
+ skipReason: reason,
91
+ repos: [],
92
+ installationRemoves: [],
93
+ configRemoves: [],
94
+ skippedOrgs: [],
95
+ notRemoved: [],
96
+ warnings: [],
97
+ };
98
+ }
99
+
100
+ /** Pure: the repos to remove because the bound user lost push access. */
101
+ export function planLostAccessRemoval(
102
+ input: LostAccessPlanInput,
103
+ ): LostAccessPlan {
104
+ const skip = accessSkipReason(input.username, input.access);
105
+ if (skip) return skippedPlan(skip);
106
+ const access = input.access as UserRepoAccessResult;
107
+
108
+ const orgResults = new Map(access.orgs.map((o) => [lower(o.org), o]));
109
+ const pushable = new Set<string>();
110
+ for (const o of access.orgs) {
111
+ for (const r of o.repos) if (r.canPush) pushable.add(lower(r.fullName));
112
+ }
113
+ // Keyed by lower-case name; values keep the stored spelling.
114
+ const installed = new Map<string, string>();
115
+ for (const repos of Object.values(input.installationRepos)) {
116
+ for (const r of repos) installed.set(lower(r), r);
117
+ }
118
+ const configured = new Map(input.agentRepos.map((r) => [lower(r), r]));
119
+
120
+ const candidates = input.requested
121
+ ? sorted(new Set(input.requested))
122
+ : sorted(new Set([...configured.values(), ...installed.values()]));
123
+
124
+ const skipReasons = new Map<string, string>();
125
+ const notRemoved: NotRemovedRepo[] = [];
126
+ const leave = (repo: string, reason: string) => {
127
+ if (input.requested) notRemoved.push({ repo, reason });
128
+ };
129
+ const installationRemoves = new Set<string>();
130
+ const configRemoves = new Set<string>();
131
+ for (const repo of candidates) {
132
+ const org = repoOrg(repo);
133
+ const orgSkip = orgSkipReason(orgResults.get(lower(org)));
134
+ if (orgSkip) {
135
+ // Unknown is never none.
136
+ skipReasons.set(org, orgSkip);
137
+ leave(repo, `removals skipped for org: ${orgSkip}`);
138
+ continue;
139
+ }
140
+ if (pushable.has(lower(repo))) {
141
+ leave(repo, STILL_PUSHABLE_REASON);
142
+ continue;
143
+ }
144
+ const inInstallation = installed.get(lower(repo));
145
+ const inConfig = configured.get(lower(repo));
146
+ if (!inInstallation && !inConfig) {
147
+ leave(repo, NOT_PRESENT_REASON);
148
+ continue;
149
+ }
150
+ if (inInstallation) installationRemoves.add(inInstallation);
151
+ if (inConfig) configRemoves.add(inConfig);
152
+ }
153
+
154
+ const skippedOrgs = sorted(skipReasons.keys()).map((org) => ({
155
+ org,
156
+ reason: skipReasons.get(org) as string,
157
+ }));
158
+ return {
159
+ skipped: false,
160
+ repos: sorted(new Set([...installationRemoves, ...configRemoves])),
161
+ installationRemoves: sorted(installationRemoves),
162
+ configRemoves: sorted(configRemoves),
163
+ skippedOrgs,
164
+ notRemoved,
165
+ warnings: skippedOrgs.map(
166
+ (s) => `${s.org}: removals skipped (${s.reason})`,
167
+ ),
168
+ };
169
+ }
170
+
171
+ export interface LostAccessRemovalDeps {
172
+ agents: ReconcileAgentsPort;
173
+ access: GithubAccessPreviewFn;
174
+ installation: Pick<InstallationReposPort, "listInstalled" | "removeRepos">;
175
+ audit: ReconcileAuditPort;
176
+ /** Optional: with none, nothing is listed or blocked. */
177
+ openWork?: OpenWorkPort;
178
+ }
179
+
180
+ export type LostAccessPreviewResult =
181
+ | { status: "agent_not_found" }
182
+ | { status: "skipped"; reason: string }
183
+ | {
184
+ status: "previewed";
185
+ plan: LostAccessPlan;
186
+ openWork: OpenWorkItem[];
187
+ warnings: string[];
188
+ };
189
+
190
+ export interface LostAccessRemoveInput {
191
+ agentId: string;
192
+ /** Who asked (audit trail). */
193
+ caller: string;
194
+ /** The repos the admin confirmed from the preview. */
195
+ repos: readonly string[];
196
+ confirmRemovals?: boolean;
197
+ }
198
+
199
+ export type LostAccessRemoveResult =
200
+ | { status: "agent_not_found" }
201
+ | { status: "skipped"; reason: string }
202
+ | { status: "noop"; plan: LostAccessPlan }
203
+ | { status: "removal_cap"; plan: LostAccessPlan; removals: number }
204
+ | {
205
+ status: "applied";
206
+ plan: LostAccessPlan;
207
+ auditId: string;
208
+ warnings: string[];
209
+ }
210
+ | { status: "failed"; plan: LostAccessPlan; auditId: string; error: string };
211
+
212
+ function groupByOrg(repos: readonly string[]): Map<string, string[]> {
213
+ const byOrg = new Map<string, string[]>();
214
+ for (const r of repos) {
215
+ const org = repoOrg(r);
216
+ byOrg.set(org, [...(byOrg.get(org) ?? []), r]);
217
+ }
218
+ return byOrg;
219
+ }
220
+
221
+ export class LostAccessRemovalService {
222
+ constructor(private readonly deps: LostAccessRemovalDeps) {}
223
+
224
+ /** Read-only: what would be removed and the open work it would block. */
225
+ async preview(agentId: string): Promise<LostAccessPreviewResult> {
226
+ const agent = await this.deps.agents.get(agentId);
227
+ if (!agent) return { status: "agent_not_found" };
228
+ const plan = await this.planFor(agent);
229
+ if (plan.skipped) {
230
+ return { status: "skipped", reason: plan.skipReason ?? "skipped" };
231
+ }
232
+ const work = await previewRepoRemovalWork(
233
+ this.deps.openWork,
234
+ agentId,
235
+ plan.repos,
236
+ );
237
+ return {
238
+ status: "previewed",
239
+ plan,
240
+ openWork: work.openWork,
241
+ warnings: [...plan.warnings, ...work.warnings],
242
+ };
243
+ }
244
+
245
+ async remove(input: LostAccessRemoveInput): Promise<LostAccessRemoveResult> {
246
+ const agent = await this.deps.agents.get(input.agentId);
247
+ if (!agent) return { status: "agent_not_found" };
248
+ const plan = await this.planFor(agent, input.repos);
249
+ if (plan.skipped) {
250
+ return { status: "skipped", reason: plan.skipReason ?? "skipped" };
251
+ }
252
+ if (plan.repos.length === 0) return { status: "noop", plan };
253
+ const removals = plan.repos.length;
254
+ if (removals > MAX_UNCONFIRMED_REMOVALS && !input.confirmRemovals) {
255
+ return { status: "removal_cap", plan, removals };
256
+ }
257
+
258
+ const appId = agent.appId as number;
259
+ const removedFromInstallation: string[] = [];
260
+ let configDone = false;
261
+ let error: string | undefined;
262
+ try {
263
+ for (const [org, repos] of groupByOrg(plan.installationRemoves)) {
264
+ await this.deps.installation.removeRepos(appId, org, repos);
265
+ removedFromInstallation.push(...repos);
266
+ }
267
+ if (plan.configRemoves.length > 0) {
268
+ const drop = new Set(plan.configRemoves);
269
+ await this.deps.agents.setRepos(
270
+ agent.id,
271
+ agent.repos.filter((r) => !drop.has(r)),
272
+ );
273
+ }
274
+ configDone = true;
275
+ } catch (err) {
276
+ error = err instanceof Error ? err.message : String(err);
277
+ }
278
+ // Record what actually changed; on failure, only what landed.
279
+ const auditId = await this.deps.audit.write({
280
+ agentId: input.agentId,
281
+ caller: input.caller,
282
+ planHash: LOST_ACCESS_AUDIT_PLAN_HASH,
283
+ diff: {
284
+ installationAdds: [],
285
+ installationRemoves: removedFromInstallation,
286
+ configAdds: [],
287
+ configRemoves: configDone ? plan.configRemoves : [],
288
+ },
289
+ result:
290
+ error === undefined
291
+ ? { status: "applied" }
292
+ : { status: "failed", error },
293
+ });
294
+ if (error !== undefined) {
295
+ return { status: "failed", plan, auditId, error };
296
+ }
297
+ const warnings = await blockRepoRemovalWork(
298
+ this.deps.openWork,
299
+ input.agentId,
300
+ plan.repos,
301
+ repoLostAccessBlockReason,
302
+ );
303
+ return { status: "applied", plan, auditId, warnings };
304
+ }
305
+
306
+ private async planFor(
307
+ agent: ReconcileAgentRecord,
308
+ requested?: readonly string[],
309
+ ): Promise<LostAccessPlan> {
310
+ const username = agent.githubUsername?.trim();
311
+ if (!username) {
312
+ return skippedPlan(accessSkipReason(username, null) as string);
313
+ }
314
+ const preview = await this.deps.access(username);
315
+ if (preview.status === "unconfigured") {
316
+ return skippedPlan("GitHub Apps are not configured");
317
+ }
318
+ // Whole-call skips need no installation calls.
319
+ const skip = accessSkipReason(username, preview.access);
320
+ if (skip) return skippedPlan(skip);
321
+ if (agent.appId === undefined) return skippedPlan(MISSING_APP_ID_REASON);
322
+ const installed = await this.deps.installation.listInstalled(agent.appId);
323
+ return planLostAccessRemoval({
324
+ username,
325
+ access: preview.access,
326
+ agentRepos: agent.repos,
327
+ installationRepos: Object.fromEntries(
328
+ installed.map(({ org, repos }) => [org, repos]),
329
+ ),
330
+ ...(requested ? { requested } : {}),
331
+ });
332
+ }
333
+ }