@app-vitals/agent-admin 1.17.0 → 1.19.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/openapi.json +193 -0
- package/openapi.platform.json +193 -0
- package/package.json +2 -2
- package/src/admin-boot.ts +14 -2
- package/src/agents-api.smoke.test.ts +144 -0
- package/src/agents-api.ts +88 -0
- package/src/github-access-preview.integration.test.ts +364 -0
- package/src/github-access-preview.ts +19 -0
- package/src/github-enterprise-api.ts +64 -0
- package/src/user-repo-access-resolver.integration.test.ts +156 -0
- package/src/user-repo-access-resolver.ts +257 -0
- package/src/user-repo-access-resolver.unit.test.ts +287 -0
package/src/agents-api.ts
CHANGED
|
@@ -107,6 +107,7 @@ import {
|
|
|
107
107
|
NotFoundError,
|
|
108
108
|
UnprocessableEntityError,
|
|
109
109
|
} from "./errors.ts";
|
|
110
|
+
import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
|
|
110
111
|
import { normalizeGithubUsername } from "./github-username.ts";
|
|
111
112
|
import {
|
|
112
113
|
AddAgentReposBodySchema,
|
|
@@ -255,6 +256,11 @@ export interface AdminDeps {
|
|
|
255
256
|
AgentGitHubInstallationsService,
|
|
256
257
|
"push" | "get"
|
|
257
258
|
>;
|
|
259
|
+
/**
|
|
260
|
+
* GHE-2.4: backs GET /agents/:id/github-access. Optional (additive); absent
|
|
261
|
+
* means the enterprise Apps are not wired, reported as `unconfigured`.
|
|
262
|
+
*/
|
|
263
|
+
githubAccessPreview?: GithubAccessPreviewFn;
|
|
258
264
|
/**
|
|
259
265
|
* Retained solely as a pass-through to deleteAgentFully() (DELETE /agents/:id),
|
|
260
266
|
* which has its own internal prisma.agent/prisma.agentEnv access — out of
|
|
@@ -545,6 +551,46 @@ const GitHubInstallationsSnapshotWrapperSchema = z
|
|
|
545
551
|
.object({ snapshot: AgentGitHubInstallationsSnapshotSchema })
|
|
546
552
|
.openapi("GitHubInstallationsSnapshotWrapper");
|
|
547
553
|
|
|
554
|
+
const GithubAccessOrgSchema = z.object({
|
|
555
|
+
org: z.string(),
|
|
556
|
+
status: z.enum([
|
|
557
|
+
"ok",
|
|
558
|
+
"lookup_app_not_installed",
|
|
559
|
+
"rate_limited",
|
|
560
|
+
"partial",
|
|
561
|
+
"error",
|
|
562
|
+
]),
|
|
563
|
+
repos: z.array(
|
|
564
|
+
z.object({
|
|
565
|
+
fullName: z.string(),
|
|
566
|
+
level: z.enum(["admin", "maintain", "write", "triage", "read", "none"]),
|
|
567
|
+
canPush: z.boolean(),
|
|
568
|
+
}),
|
|
569
|
+
),
|
|
570
|
+
unresolved: z.number().int(),
|
|
571
|
+
});
|
|
572
|
+
|
|
573
|
+
const GithubAccessPreviewSchema = z
|
|
574
|
+
.object({
|
|
575
|
+
status: z.enum(["ok", "user_not_found", "unconfigured"]).openapi({
|
|
576
|
+
description:
|
|
577
|
+
"`unconfigured` when the installer or lookup App is not set (no GitHub call was made).",
|
|
578
|
+
}),
|
|
579
|
+
access: z
|
|
580
|
+
.object({
|
|
581
|
+
username: z.string(),
|
|
582
|
+
outcome: z.enum(["ok", "user_not_found"]),
|
|
583
|
+
userVerified: z.boolean(),
|
|
584
|
+
orgs: z.array(GithubAccessOrgSchema),
|
|
585
|
+
unresolved: z.number().int(),
|
|
586
|
+
complete: z.boolean(),
|
|
587
|
+
checkedAt: z.string(),
|
|
588
|
+
})
|
|
589
|
+
.optional()
|
|
590
|
+
.openapi({ description: "Resolver output; absent when unconfigured." }),
|
|
591
|
+
})
|
|
592
|
+
.openapi("GithubAccessPreview");
|
|
593
|
+
|
|
548
594
|
// ─── Route definitions ──────────────────────────────────────────────────────────
|
|
549
595
|
|
|
550
596
|
const reconcileAgentsRoute = createRoute({
|
|
@@ -1418,6 +1464,26 @@ const getGitHubInstallationsRoute = createRoute({
|
|
|
1418
1464
|
},
|
|
1419
1465
|
});
|
|
1420
1466
|
|
|
1467
|
+
const getGithubAccessRoute = createRoute({
|
|
1468
|
+
method: "get",
|
|
1469
|
+
path: "/agents/{id}/github-access",
|
|
1470
|
+
summary: "Preview the repos the agent's bound GitHub user can reach",
|
|
1471
|
+
description:
|
|
1472
|
+
"Platform-admin only (session members, ops keys and agent keys get 403): the response lists repo names the bound user can reach. Read-only; nothing is stored. 404 for an unknown agent; 422 when no githubUsername is bound. Returns `status: unconfigured` (not an error, no GitHub call) when the enterprise Apps are not configured, and `status: user_not_found` when the user does not exist on GitHub; otherwise `access` is the resolver output (per-org status, repos with level and canPush, unresolved count, complete flag).",
|
|
1473
|
+
request: { params: AgentIdParamSchema },
|
|
1474
|
+
responses: {
|
|
1475
|
+
200: {
|
|
1476
|
+
description: "Access preview",
|
|
1477
|
+
content: { "application/json": { schema: GithubAccessPreviewSchema } },
|
|
1478
|
+
},
|
|
1479
|
+
401: { description: "Unauthorized", ...jsonError },
|
|
1480
|
+
403: { description: "Platform admin required", ...jsonError },
|
|
1481
|
+
404: { description: "Agent not found", ...jsonError },
|
|
1482
|
+
422: { description: "Agent has no githubUsername", ...jsonError },
|
|
1483
|
+
502: { description: "GitHub unavailable or refused", ...jsonError },
|
|
1484
|
+
},
|
|
1485
|
+
});
|
|
1486
|
+
|
|
1421
1487
|
/** `from`/`to` ISO datetime bounds shared by the cron-run report routes. */
|
|
1422
1488
|
export const cronRunStatsQuerySchema = z
|
|
1423
1489
|
.object({
|
|
@@ -2849,6 +2915,28 @@ export function createAdminApp(deps: AdminDeps): OpenAPIHono<AdminAuthEnv> {
|
|
|
2849
2915
|
return c.json({ bakedMarketplaces: stored }, 200);
|
|
2850
2916
|
});
|
|
2851
2917
|
|
|
2918
|
+
// GET /agents/:id/github-access — GHE-2.4 read-only preview. Platform admin
|
|
2919
|
+
// only: never session members, ops/read keys or agent keys.
|
|
2920
|
+
app.openapi(getGithubAccessRoute, async (c) => {
|
|
2921
|
+
if (c.get("isAdmin") !== true) {
|
|
2922
|
+
throw new ForbiddenError(
|
|
2923
|
+
"Admin access required to preview GitHub access",
|
|
2924
|
+
);
|
|
2925
|
+
}
|
|
2926
|
+
const { id: agentId } = c.req.valid("param");
|
|
2927
|
+
const agent = await agentService.getDetail(agentId);
|
|
2928
|
+
if (!agent) throw new NotFoundError(`agent ${agentId} not found`);
|
|
2929
|
+
if (!agent.githubUsername) {
|
|
2930
|
+
throw new UnprocessableEntityError(
|
|
2931
|
+
"agent has no githubUsername bound; set one with PATCH /agents/{id}",
|
|
2932
|
+
);
|
|
2933
|
+
}
|
|
2934
|
+
if (!deps.githubAccessPreview)
|
|
2935
|
+
return c.json({ status: "unconfigured" as const }, 200);
|
|
2936
|
+
const preview = await deps.githubAccessPreview(agent.githubUsername);
|
|
2937
|
+
return c.json(preview, 200);
|
|
2938
|
+
});
|
|
2939
|
+
|
|
2852
2940
|
// GET /agents/:id/github-installations — latest snapshot, 404 if none yet
|
|
2853
2941
|
app.openapi(getGitHubInstallationsRoute, async (c) => {
|
|
2854
2942
|
const { id: agentId } = c.req.valid("param");
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/src/github-access-preview.integration.test.ts
|
|
3
|
+
* Integration tests for GET /agents/:id/github-access (GHE-2.4): the full
|
|
4
|
+
* route against a real PostgreSQL DB (agents + stored enterprise Apps) and the
|
|
5
|
+
* GHE-1.2 / GHE-2.2 cassettes, replayed through an injected fetchFn.
|
|
6
|
+
*
|
|
7
|
+
* Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";
|
|
11
|
+
import { generateKeyPairSync } from "node:crypto";
|
|
12
|
+
import { readFileSync } from "node:fs";
|
|
13
|
+
import { sign } from "hono/jwt";
|
|
14
|
+
import type { PrismaClient } from "../prisma/client/client.ts";
|
|
15
|
+
import { AgentChatTokenService } from "./agent-chat-tokens.ts";
|
|
16
|
+
import { AgentCronJobService } from "./agent-cron-jobs.ts";
|
|
17
|
+
import { AgentCronRunStatsService } from "./agent-cron-run-stats.ts";
|
|
18
|
+
import { AgentCronRunService } from "./agent-cron-runs.ts";
|
|
19
|
+
import { AgentEnvService } from "./agent-envs.ts";
|
|
20
|
+
import { AgentGitHubInstallationsService } from "./agent-github-installations.ts";
|
|
21
|
+
import { AgentMemberService } from "./agent-members.ts";
|
|
22
|
+
import { AgentPluginService } from "./agent-plugins.ts";
|
|
23
|
+
import { NoopAgentProvisioner } from "./agent-provisioner.ts";
|
|
24
|
+
import { AgentTokenService } from "./agent-tokens.ts";
|
|
25
|
+
import { AgentToolService } from "./agent-tools.ts";
|
|
26
|
+
import { AgentService } from "./agents.ts";
|
|
27
|
+
import type { AdminDeps } from "./agents-api.ts";
|
|
28
|
+
import { createAdminApp } from "./agents-api.ts";
|
|
29
|
+
import { NoopChatServiceProvisioningClient } from "./chat-service-provisioning-client.ts";
|
|
30
|
+
import { createGithubAccessPreview } from "./github-enterprise-api.ts";
|
|
31
|
+
import { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
|
|
32
|
+
import { createAdminPrismaClient } from "./prisma-client.ts";
|
|
33
|
+
import type {
|
|
34
|
+
SpecialtyType,
|
|
35
|
+
SpecialtyTypeResolver,
|
|
36
|
+
} from "./specialty-types.ts";
|
|
37
|
+
import { makeStrictTokenCrypto, makeTokenCrypto } from "./token-crypto.ts";
|
|
38
|
+
|
|
39
|
+
const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
|
|
40
|
+
const describeOrSkip = TEST_DB ? describe : describe.skip;
|
|
41
|
+
|
|
42
|
+
const SESSION_SECRET = "test-admin-session-secret-32-bytes!";
|
|
43
|
+
const REAL_KEY =
|
|
44
|
+
"0000000000000000000000000000000000000000000000000000000000000001";
|
|
45
|
+
|
|
46
|
+
async function makeSessionCookie(): Promise<string> {
|
|
47
|
+
return sign(
|
|
48
|
+
{
|
|
49
|
+
isAdmin: true,
|
|
50
|
+
userId: "user-123",
|
|
51
|
+
email: "admin@example.com",
|
|
52
|
+
name: "Admin User",
|
|
53
|
+
iat: Math.floor(Date.now() / 1000),
|
|
54
|
+
exp: Math.floor(Date.now() / 1000) + 3600,
|
|
55
|
+
},
|
|
56
|
+
SESSION_SECRET,
|
|
57
|
+
"HS256",
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function makePrisma(): PrismaClient {
|
|
62
|
+
// TEST_DB is guaranteed set — the describe block is skipped otherwise.
|
|
63
|
+
return createAdminPrismaClient(TEST_DB as string);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const CODING_TYPE: SpecialtyType = {
|
|
67
|
+
name: "coding",
|
|
68
|
+
displayName: "Coding Agent",
|
|
69
|
+
templatesDir: "workspace/",
|
|
70
|
+
tools: ["Read", "Write", "Edit"],
|
|
71
|
+
requiredEnv: [],
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
function fakeSpecialtyTypes(): SpecialtyTypeResolver {
|
|
75
|
+
const byType: Record<string, SpecialtyType> = { coding: CODING_TYPE };
|
|
76
|
+
return {
|
|
77
|
+
getType(specialty: string): SpecialtyType {
|
|
78
|
+
return byType[specialty] ?? (byType.coding as SpecialtyType);
|
|
79
|
+
},
|
|
80
|
+
tryGetType(specialty: string): SpecialtyType | undefined {
|
|
81
|
+
return byType[specialty];
|
|
82
|
+
},
|
|
83
|
+
listTypes() {
|
|
84
|
+
return Object.entries(byType).map(([name, manifest]) => ({
|
|
85
|
+
name,
|
|
86
|
+
displayName: manifest.displayName,
|
|
87
|
+
}));
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function makeDeps(prisma: PrismaClient): AdminDeps {
|
|
93
|
+
const savedKey = process.env.SHIPWRIGHT_ENCRYPTION_KEY;
|
|
94
|
+
process.env.SHIPWRIGHT_ENCRYPTION_KEY = REAL_KEY;
|
|
95
|
+
const crypto = makeTokenCrypto();
|
|
96
|
+
if (savedKey === undefined) {
|
|
97
|
+
delete process.env.SHIPWRIGHT_ENCRYPTION_KEY;
|
|
98
|
+
} else {
|
|
99
|
+
process.env.SHIPWRIGHT_ENCRYPTION_KEY = savedKey;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
agentService: new AgentService(prisma),
|
|
104
|
+
agentEnvService: new AgentEnvService(prisma, crypto),
|
|
105
|
+
agentCronJobService: new AgentCronJobService(prisma),
|
|
106
|
+
agentCronRunService: new AgentCronRunService(prisma),
|
|
107
|
+
agentCronRunStatsService: new AgentCronRunStatsService(prisma),
|
|
108
|
+
agentToolService: new AgentToolService(prisma),
|
|
109
|
+
agentTokenService: new AgentTokenService(prisma),
|
|
110
|
+
agentPluginService: new AgentPluginService(prisma),
|
|
111
|
+
agentMemberService: new AgentMemberService(prisma),
|
|
112
|
+
specialtyRegistry: fakeSpecialtyTypes(),
|
|
113
|
+
agentChatTokenService: new AgentChatTokenService(prisma),
|
|
114
|
+
agentGitHubInstallationsService: new AgentGitHubInstallationsService(
|
|
115
|
+
prisma,
|
|
116
|
+
),
|
|
117
|
+
prisma,
|
|
118
|
+
provisioner: new NoopAgentProvisioner(),
|
|
119
|
+
serviceIntegrations: [
|
|
120
|
+
{
|
|
121
|
+
name: "task-store",
|
|
122
|
+
listTokensForAgent: async () => [],
|
|
123
|
+
revokeToken: async () => {},
|
|
124
|
+
},
|
|
125
|
+
],
|
|
126
|
+
chatService: new NoopChatServiceProvisioningClient(),
|
|
127
|
+
slack: {
|
|
128
|
+
deleteApp: async () => {},
|
|
129
|
+
},
|
|
130
|
+
decrypt: (value: string) => crypto.decrypt(value),
|
|
131
|
+
sessionSecret: SESSION_SECRET,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
type Cassette = Record<
|
|
136
|
+
string,
|
|
137
|
+
{ status: number; headers?: Record<string, string>; body: unknown }
|
|
138
|
+
>;
|
|
139
|
+
const load = (f: string): Cassette =>
|
|
140
|
+
JSON.parse(
|
|
141
|
+
readFileSync(new URL(`./fixtures/${f}`, import.meta.url).pathname, "utf-8"),
|
|
142
|
+
);
|
|
143
|
+
const enterprise = load("github-enterprise-cassette.json");
|
|
144
|
+
const lookup = load("github-lookup-cassette.json");
|
|
145
|
+
|
|
146
|
+
const { privateKey: PEM } = generateKeyPairSync("rsa", {
|
|
147
|
+
modulusLength: 2048,
|
|
148
|
+
privateKeyEncoding: { type: "pkcs8", format: "pem" },
|
|
149
|
+
publicKeyEncoding: { type: "spki", format: "pem" },
|
|
150
|
+
});
|
|
151
|
+
const PEM_BODY = PEM.split("\n")[1] as string;
|
|
152
|
+
const ENC_KEY = "c".repeat(64);
|
|
153
|
+
const NOW = new Date("2026-11-09T12:00:00Z");
|
|
154
|
+
|
|
155
|
+
/** route -> [cassette, entry]. org-1 has the lookup App, org-2 does not. */
|
|
156
|
+
const ROUTES: Record<string, [Cassette, string]> = {
|
|
157
|
+
"GET /enterprises/acme/installation": [
|
|
158
|
+
enterprise,
|
|
159
|
+
"enterprise_installation_success",
|
|
160
|
+
],
|
|
161
|
+
"POST /app/installations/4242/access_tokens": [
|
|
162
|
+
enterprise,
|
|
163
|
+
"access_token_success",
|
|
164
|
+
],
|
|
165
|
+
"GET /enterprises/acme/apps/installable_organizations": [
|
|
166
|
+
enterprise,
|
|
167
|
+
"installable_orgs_success",
|
|
168
|
+
],
|
|
169
|
+
"GET /orgs/org-1/installation": [lookup, "org_installation_success"],
|
|
170
|
+
"GET /orgs/org-2/installation": [lookup, "org_installation_404"],
|
|
171
|
+
"POST /app/installations/7001/access_tokens": [
|
|
172
|
+
lookup,
|
|
173
|
+
"lookup_token_success",
|
|
174
|
+
],
|
|
175
|
+
"GET /installation/repositories": [lookup, "repos_success"],
|
|
176
|
+
"GET /users/octocat": [lookup, "user_success"],
|
|
177
|
+
"GET /repos/org-1/api/collaborators/octocat/permission": [
|
|
178
|
+
lookup,
|
|
179
|
+
"permission_maintain",
|
|
180
|
+
],
|
|
181
|
+
"GET /repos/org-1/web/collaborators/octocat/permission": [
|
|
182
|
+
lookup,
|
|
183
|
+
"permission_triage",
|
|
184
|
+
],
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
describeOrSkip("GET /agents/:id/github-access (integration)", () => {
|
|
188
|
+
let prisma: PrismaClient;
|
|
189
|
+
let cookie: string;
|
|
190
|
+
let calls: string[];
|
|
191
|
+
let logs: string[];
|
|
192
|
+
|
|
193
|
+
beforeEach(async () => {
|
|
194
|
+
prisma = makePrisma();
|
|
195
|
+
await prisma.gitHubEnterpriseApp.deleteMany();
|
|
196
|
+
await prisma.agentWorkQueueSnapshot.deleteMany();
|
|
197
|
+
await prisma.agentPlugin.deleteMany();
|
|
198
|
+
await prisma.agentToken.deleteMany();
|
|
199
|
+
await prisma.agentCronJob.deleteMany();
|
|
200
|
+
await prisma.agentTool.deleteMany();
|
|
201
|
+
await prisma.agentEnv.deleteMany();
|
|
202
|
+
await prisma.agentMember.deleteMany();
|
|
203
|
+
await prisma.agent.deleteMany();
|
|
204
|
+
cookie = await makeSessionCookie();
|
|
205
|
+
calls = [];
|
|
206
|
+
logs = [];
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
afterEach(async () => {
|
|
210
|
+
await prisma.$disconnect();
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
214
|
+
const u = new URL(input.toString());
|
|
215
|
+
const key = `${init?.method ?? "GET"} ${u.pathname}`;
|
|
216
|
+
calls.push(key);
|
|
217
|
+
const hit = ROUTES[key];
|
|
218
|
+
if (!hit) throw new Error(`no route for ${key}`);
|
|
219
|
+
const e = hit[0][hit[1]];
|
|
220
|
+
return new Response(JSON.stringify(e?.body), {
|
|
221
|
+
status: e?.status,
|
|
222
|
+
headers: { "Content-Type": "application/json", ...(e?.headers ?? {}) },
|
|
223
|
+
});
|
|
224
|
+
}) as typeof fetch;
|
|
225
|
+
|
|
226
|
+
async function seedApps() {
|
|
227
|
+
const svc = new GitHubEnterpriseAppService(
|
|
228
|
+
prisma,
|
|
229
|
+
makeStrictTokenCrypto(ENC_KEY),
|
|
230
|
+
);
|
|
231
|
+
await svc.save({
|
|
232
|
+
role: "installer",
|
|
233
|
+
appId: "12345",
|
|
234
|
+
slug: "example-installer",
|
|
235
|
+
enterpriseSlug: "acme",
|
|
236
|
+
privateKey: PEM,
|
|
237
|
+
});
|
|
238
|
+
await svc.save({
|
|
239
|
+
role: "lookup",
|
|
240
|
+
appId: "555",
|
|
241
|
+
slug: "example-lookup",
|
|
242
|
+
enterpriseSlug: null,
|
|
243
|
+
privateKey: PEM,
|
|
244
|
+
});
|
|
245
|
+
return svc;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function build(appService: GitHubEnterpriseAppService) {
|
|
249
|
+
return createAdminApp({
|
|
250
|
+
...makeDeps(prisma),
|
|
251
|
+
githubAccessPreview: createGithubAccessPreview({
|
|
252
|
+
appService,
|
|
253
|
+
fetchFn,
|
|
254
|
+
apiBase: "https://ghe.test",
|
|
255
|
+
now: () => NOW,
|
|
256
|
+
}),
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const get = (app: ReturnType<typeof build>, id: string) =>
|
|
261
|
+
app.request(`/agents/${id}/github-access`, {
|
|
262
|
+
headers: { Cookie: `admin_session=${cookie}` },
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
const svcNoApps = () =>
|
|
266
|
+
new GitHubEnterpriseAppService(prisma, makeStrictTokenCrypto(ENC_KEY));
|
|
267
|
+
|
|
268
|
+
it("returns the resolver output per org, with no key material anywhere", async () => {
|
|
269
|
+
const agent = await prisma.agent.create({
|
|
270
|
+
data: { name: "A", githubUsername: "octocat" },
|
|
271
|
+
});
|
|
272
|
+
const app = build(await seedApps());
|
|
273
|
+
const spies = (["log", "info", "warn", "error"] as const).map((m) =>
|
|
274
|
+
spyOn(console, m).mockImplementation((...a) => {
|
|
275
|
+
logs.push(a.map(String).join(" "));
|
|
276
|
+
}),
|
|
277
|
+
);
|
|
278
|
+
try {
|
|
279
|
+
const res = await get(app, agent.id);
|
|
280
|
+
expect(res.status).toBe(200);
|
|
281
|
+
const text = await res.text();
|
|
282
|
+
const json = JSON.parse(text);
|
|
283
|
+
expect(json.status).toBe("ok");
|
|
284
|
+
expect(json.access.complete).toBe(false); // org-2 has no lookup App
|
|
285
|
+
expect(json.access.orgs).toEqual([
|
|
286
|
+
{
|
|
287
|
+
org: "org-1",
|
|
288
|
+
status: "ok",
|
|
289
|
+
repos: [
|
|
290
|
+
{ fullName: "acme-eng/api", level: "maintain", canPush: true },
|
|
291
|
+
{ fullName: "acme-eng/web", level: "triage", canPush: false },
|
|
292
|
+
],
|
|
293
|
+
unresolved: 0,
|
|
294
|
+
},
|
|
295
|
+
{
|
|
296
|
+
org: "org-2",
|
|
297
|
+
status: "lookup_app_not_installed",
|
|
298
|
+
repos: [],
|
|
299
|
+
unresolved: 0,
|
|
300
|
+
},
|
|
301
|
+
]);
|
|
302
|
+
for (const out of [text, ...logs]) {
|
|
303
|
+
expect(out).not.toContain(PEM_BODY);
|
|
304
|
+
expect(out).not.toContain("BEGIN");
|
|
305
|
+
expect(out).not.toMatch(/ghs_|"token"/);
|
|
306
|
+
}
|
|
307
|
+
} finally {
|
|
308
|
+
for (const s of spies) s.mockRestore();
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
it("unconfigured: 200 status and no GitHub call", async () => {
|
|
313
|
+
const agent = await prisma.agent.create({
|
|
314
|
+
data: { name: "A", githubUsername: "octocat" },
|
|
315
|
+
});
|
|
316
|
+
const res = await get(build(svcNoApps()), agent.id);
|
|
317
|
+
expect(res.status).toBe(200);
|
|
318
|
+
expect(await res.json()).toEqual({ status: "unconfigured" });
|
|
319
|
+
expect(calls).toEqual([]);
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
it("only one App configured is still unconfigured", async () => {
|
|
323
|
+
const agent = await prisma.agent.create({
|
|
324
|
+
data: { name: "A", githubUsername: "octocat" },
|
|
325
|
+
});
|
|
326
|
+
const svc = svcNoApps();
|
|
327
|
+
await svc.save({
|
|
328
|
+
role: "lookup",
|
|
329
|
+
appId: "555",
|
|
330
|
+
slug: "example-lookup",
|
|
331
|
+
enterpriseSlug: null,
|
|
332
|
+
privateKey: PEM,
|
|
333
|
+
});
|
|
334
|
+
const res = await get(build(svc), agent.id);
|
|
335
|
+
expect(await res.json()).toEqual({ status: "unconfigured" });
|
|
336
|
+
expect(calls).toEqual([]);
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
it("user_not_found when the user does not exist on GitHub", async () => {
|
|
340
|
+
const agent = await prisma.agent.create({
|
|
341
|
+
data: { name: "A", githubUsername: "octocat" },
|
|
342
|
+
});
|
|
343
|
+
const saved = ROUTES["GET /users/octocat"];
|
|
344
|
+
ROUTES["GET /users/octocat"] = [lookup, "user_nonexistent"];
|
|
345
|
+
try {
|
|
346
|
+
const res = await get(build(await seedApps()), agent.id);
|
|
347
|
+
expect(res.status).toBe(200);
|
|
348
|
+
const json = await res.json();
|
|
349
|
+
expect(json.status).toBe("user_not_found");
|
|
350
|
+
expect(json.access.orgs).toEqual([]);
|
|
351
|
+
expect(calls.some((c) => c.includes("/permission"))).toBe(false);
|
|
352
|
+
} finally {
|
|
353
|
+
ROUTES["GET /users/octocat"] = saved as [Cassette, string];
|
|
354
|
+
}
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
it("404 for an unknown agent and 422 for an unbound one", async () => {
|
|
358
|
+
const unbound = await prisma.agent.create({ data: { name: "U" } });
|
|
359
|
+
const app = build(await seedApps());
|
|
360
|
+
expect((await get(app, "no-such-agent")).status).toBe(404);
|
|
361
|
+
expect((await get(app, unbound.id)).status).toBe(422);
|
|
362
|
+
expect(calls).toEqual([]);
|
|
363
|
+
});
|
|
364
|
+
});
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* admin/src/github-access-preview.ts
|
|
3
|
+
* Result type and port for GET /agents/:id/github-access (GHE-2.4): a
|
|
4
|
+
* read-only preview of the repos an agent's bound GitHub user can reach.
|
|
5
|
+
* The implementation lives in github-enterprise-api.ts (the only module that
|
|
6
|
+
* may read the App keys); agents-api.ts only sees this port.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { UserRepoAccessResult } from "./user-repo-access-resolver.ts";
|
|
10
|
+
|
|
11
|
+
export type GithubAccessPreview =
|
|
12
|
+
/** The installer or lookup App is not configured; GitHub was not called. */
|
|
13
|
+
| { status: "unconfigured" }
|
|
14
|
+
/** `access` is the resolver output, unchanged. */
|
|
15
|
+
| { status: "ok" | "user_not_found"; access: UserRepoAccessResult };
|
|
16
|
+
|
|
17
|
+
export type GithubAccessPreviewFn = (
|
|
18
|
+
username: string,
|
|
19
|
+
) => Promise<GithubAccessPreview>;
|
|
@@ -29,6 +29,7 @@ import type { AgentTokenService } from "./agent-tokens.ts";
|
|
|
29
29
|
import type { AgentService } from "./agents.ts";
|
|
30
30
|
import {
|
|
31
31
|
ApiError,
|
|
32
|
+
BadGatewayError,
|
|
32
33
|
ConflictError,
|
|
33
34
|
ForbiddenError,
|
|
34
35
|
NotFoundError,
|
|
@@ -47,7 +48,10 @@ import {
|
|
|
47
48
|
type GitHubEnterpriseAppRole,
|
|
48
49
|
type GitHubEnterpriseAppService,
|
|
49
50
|
} from "./github-enterprise-apps.ts";
|
|
51
|
+
import { GithubLookupClient } from "./github-lookup-client.ts";
|
|
52
|
+
import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
|
|
50
53
|
import { ErrorSchema } from "./openapi-schemas.ts";
|
|
54
|
+
import { UserRepoAccessResolver } from "./user-repo-access-resolver.ts";
|
|
51
55
|
|
|
52
56
|
// ─── Deps ─────────────────────────────────────────────────────────────────────
|
|
53
57
|
|
|
@@ -423,6 +427,66 @@ function serializeApp(m: GitHubEnterpriseAppMetadata) {
|
|
|
423
427
|
};
|
|
424
428
|
}
|
|
425
429
|
|
|
430
|
+
// ─── Access preview (GHE-2.4) ─────────────────────────────────────────────────
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Backs GET /agents/:id/github-access. Unconfigured (either App missing, or a
|
|
434
|
+
* stored App without its key / enterprise slug) returns before any GitHub
|
|
435
|
+
* call. A GitHub failure while listing orgs is rethrown as a 502 carrying only
|
|
436
|
+
* the mapped, non-leaky message.
|
|
437
|
+
*/
|
|
438
|
+
export function createGithubAccessPreview(
|
|
439
|
+
deps: Pick<
|
|
440
|
+
GithubEnterpriseApiDeps,
|
|
441
|
+
"appService" | "fetchFn" | "apiBase" | "now"
|
|
442
|
+
>,
|
|
443
|
+
): GithubAccessPreviewFn {
|
|
444
|
+
return async (username) => {
|
|
445
|
+
const [installer, lookup] = await Promise.all([
|
|
446
|
+
deps.appService.get("installer"),
|
|
447
|
+
deps.appService.get("lookup"),
|
|
448
|
+
]);
|
|
449
|
+
if (!installer || !lookup || !installer.enterpriseSlug) {
|
|
450
|
+
return { status: "unconfigured" };
|
|
451
|
+
}
|
|
452
|
+
const [installerKey, lookupKey] = await Promise.all([
|
|
453
|
+
deps.appService.getPrivateKey("installer"),
|
|
454
|
+
deps.appService.getPrivateKey("lookup"),
|
|
455
|
+
]);
|
|
456
|
+
if (!installerKey || !lookupKey) return { status: "unconfigured" };
|
|
457
|
+
|
|
458
|
+
const common = {
|
|
459
|
+
apiBase: deps.apiBase,
|
|
460
|
+
fetchFn: deps.fetchFn,
|
|
461
|
+
now: deps.now,
|
|
462
|
+
};
|
|
463
|
+
const resolver = new UserRepoAccessResolver({
|
|
464
|
+
installer: new GithubEnterpriseClient({
|
|
465
|
+
appId: installer.appId,
|
|
466
|
+
enterprise: installer.enterpriseSlug,
|
|
467
|
+
privateKey: installerKey,
|
|
468
|
+
...common,
|
|
469
|
+
}),
|
|
470
|
+
lookup: new GithubLookupClient({
|
|
471
|
+
appId: lookup.appId,
|
|
472
|
+
privateKey: lookupKey,
|
|
473
|
+
...common,
|
|
474
|
+
}),
|
|
475
|
+
now: deps.now,
|
|
476
|
+
});
|
|
477
|
+
try {
|
|
478
|
+
const access = await resolver.resolve(username);
|
|
479
|
+
return { status: access.outcome, access };
|
|
480
|
+
} catch (err) {
|
|
481
|
+
if (err instanceof GithubEnterpriseError) {
|
|
482
|
+
throw new BadGatewayError(mapEnterpriseFailure(err.kind).message);
|
|
483
|
+
}
|
|
484
|
+
// Anything else (e.g. JWT signing): generic, no detail.
|
|
485
|
+
throw new BadGatewayError("GitHub access could not be resolved.");
|
|
486
|
+
}
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
|
|
426
490
|
// ─── App ──────────────────────────────────────────────────────────────────────
|
|
427
491
|
|
|
428
492
|
export function createGithubEnterpriseApp(
|