-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreflight.ts
More file actions
400 lines (363 loc) · 14.3 KB
/
preflight.ts
File metadata and controls
400 lines (363 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/**
* MIT No Attribution
*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Admission / pre-invoke checks before orchestration. See docs/design/ORCHESTRATOR.md (admission control).
// Tests: cdk/test/handlers/shared/preflight.test.ts
import { resolveGitHubToken } from './context-hydration';
import { logger } from './logger';
import type { BlueprintConfig } from './repo-config';
import type { TaskType } from './types';
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export const PreflightFailureReason = {
GITHUB_UNREACHABLE: 'GITHUB_UNREACHABLE',
INSUFFICIENT_GITHUB_REPO_PERMISSIONS: 'INSUFFICIENT_GITHUB_REPO_PERMISSIONS',
REPO_NOT_FOUND_OR_NO_ACCESS: 'REPO_NOT_FOUND_OR_NO_ACCESS',
RUNTIME_UNAVAILABLE: 'RUNTIME_UNAVAILABLE',
PR_NOT_FOUND_OR_CLOSED: 'PR_NOT_FOUND_OR_CLOSED',
} as const;
export type PreflightFailureReasonType = typeof PreflightFailureReason[keyof typeof PreflightFailureReason];
export interface PreflightCheckResult {
readonly check: string;
readonly passed: boolean;
readonly reason?: PreflightFailureReasonType;
readonly detail?: string;
readonly httpStatus?: number;
readonly durationMs: number;
}
export interface PreflightResult {
readonly passed: boolean;
readonly checks: readonly PreflightCheckResult[];
readonly failureReason?: PreflightFailureReasonType;
readonly failureDetail?: string;
}
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const GITHUB_API_TIMEOUT_MS = 5_000;
/** GitHub GraphQL `viewerPermission` values that allow pushing branches (new_task / pr_iteration). */
const CONTENTS_WRITE_LEVELS = new Set(['WRITE', 'MAINTAIN', 'ADMIN']);
/**
* Minimum `viewerPermission` for pr_review (issue/PR comments without Contents write).
* See GitHub collaborator roles; TRIAGE can manage PRs without push.
*/
const PR_REVIEW_INTERACTION_LEVELS = new Set(['TRIAGE', 'WRITE', 'MAINTAIN', 'ADMIN']);
function taskRequiresContentsWrite(taskType: TaskType): boolean {
return taskType === 'new_task' || taskType === 'pr_iteration';
}
function splitRepo(repo: string): { owner: string; name: string } | undefined {
const idx = repo.indexOf('/');
if (idx <= 0 || idx === repo.length - 1) {
return undefined;
}
return { owner: repo.slice(0, idx), name: repo.slice(idx + 1) };
}
async function fetchViewerPermission(repo: string, token: string): Promise<string | undefined> {
const parts = splitRepo(repo);
if (!parts) {
return undefined;
}
try {
const resp = await fetch('https://api.github.com/graphql', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query: 'query($owner:String!,$name:String!){repository(owner:$owner,name:$name){viewerPermission}}',
variables: { owner: parts.owner, name: parts.name },
}),
signal: AbortSignal.timeout(GITHUB_API_TIMEOUT_MS),
});
if (!resp.ok) {
return undefined;
}
const body = await resp.json() as { data?: { repository?: { viewerPermission?: string | null } } };
const perm = body.data?.repository?.viewerPermission;
return perm ?? undefined;
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
logger.warn('GitHub GraphQL viewerPermission lookup failed', { repo, error: detail });
return undefined;
}
}
// ---------------------------------------------------------------------------
// Internal check functions
// ---------------------------------------------------------------------------
async function checkGitHubReachability(token: string): Promise<PreflightCheckResult> {
const start = Date.now();
try {
const resp = await fetch('https://api.github.com/rate_limit', {
headers: {
Authorization: `token ${token}`,
Accept: 'application/vnd.github.v3+json',
},
signal: AbortSignal.timeout(GITHUB_API_TIMEOUT_MS),
});
const durationMs = Date.now() - start;
if (resp.ok) {
return { check: 'github_reachability', passed: true, durationMs };
}
return {
check: 'github_reachability',
passed: false,
reason: PreflightFailureReason.GITHUB_UNREACHABLE,
detail: `GitHub API returned HTTP ${resp.status}`,
httpStatus: resp.status,
durationMs,
};
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
logger.warn('GitHub reachability check failed', { error: detail });
return {
check: 'github_reachability',
passed: false,
reason: PreflightFailureReason.GITHUB_UNREACHABLE,
detail,
durationMs: Date.now() - start,
};
}
}
async function checkRepoAccess(repo: string, token: string, taskType: TaskType): Promise<PreflightCheckResult> {
const start = Date.now();
try {
const resp = await fetch(`https://api.github.com/repos/${repo}`, {
headers: {
Authorization: `token ${token}`,
Accept: 'application/vnd.github.v3+json',
},
signal: AbortSignal.timeout(GITHUB_API_TIMEOUT_MS),
});
const durationMs = Date.now() - start;
if (!resp.ok) {
if (resp.status === 404 || resp.status === 403) {
return {
check: 'repo_access',
passed: false,
reason: PreflightFailureReason.REPO_NOT_FOUND_OR_NO_ACCESS,
detail: `GitHub API returned HTTP ${resp.status} for ${repo}`,
httpStatus: resp.status,
durationMs,
};
}
return {
check: 'repo_access',
passed: false,
reason: PreflightFailureReason.GITHUB_UNREACHABLE,
detail: `GitHub API returned HTTP ${resp.status} for ${repo}`,
httpStatus: resp.status,
durationMs,
};
}
let body: unknown;
try {
body = await resp.json();
} catch {
return {
check: 'repo_access',
passed: false,
reason: PreflightFailureReason.GITHUB_UNREACHABLE,
detail: `GitHub API returned invalid JSON for ${repo}`,
durationMs: Date.now() - start,
};
}
const permissions = (body as { permissions?: { push?: boolean } }).permissions;
const restPush = permissions?.push === true;
let viewerPermission: string | undefined;
if (!restPush) {
viewerPermission = await fetchViewerPermission(repo, token);
}
const contentsWriteOk = restPush || (viewerPermission !== undefined && CONTENTS_WRITE_LEVELS.has(viewerPermission));
const prReviewOk = restPush || (viewerPermission !== undefined && PR_REVIEW_INTERACTION_LEVELS.has(viewerPermission));
const needsWrite = taskRequiresContentsWrite(taskType);
const sufficient = needsWrite ? contentsWriteOk : prReviewOk;
if (!sufficient) {
const need = needsWrite
? 'Contents write (push branches) for this repository'
: 'Pull request interaction (e.g. TRIAGE or Contents write) for this repository';
const permHint = viewerPermission !== undefined ? ` GitHub reports viewerPermission=${viewerPermission}.` : '';
const restHint = permissions?.push === false
? ' REST API reports push=false for this token.'
: '';
return {
check: 'repo_access',
passed: false,
reason: PreflightFailureReason.INSUFFICIENT_GITHUB_REPO_PERMISSIONS,
detail:
`Token cannot ${needsWrite ? 'push to' : 'interact with pull requests on'} ${repo}.${restHint}${permHint}`
+ ` Required: ${need}. For fine-grained PATs use Contents **Read and write**, Pull requests **Read and write**, and Issues **Read** on this repo (see developer guide / agent README).`,
durationMs: Date.now() - start,
};
}
return { check: 'repo_access', passed: true, durationMs: Date.now() - start };
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
logger.warn('Repo access check failed', { repo, error: detail });
return {
check: 'repo_access',
passed: false,
reason: PreflightFailureReason.GITHUB_UNREACHABLE,
detail,
durationMs: Date.now() - start,
};
}
}
async function checkPrAccessible(repo: string, prNumber: number, token: string): Promise<PreflightCheckResult> {
const start = Date.now();
try {
const resp = await fetch(`https://api.github.com/repos/${repo}/pulls/${prNumber}`, {
headers: {
Authorization: `token ${token}`,
Accept: 'application/vnd.github.v3+json',
},
signal: AbortSignal.timeout(GITHUB_API_TIMEOUT_MS),
});
const durationMs = Date.now() - start;
if (!resp.ok) {
return {
check: 'pr_accessible',
passed: false,
reason: PreflightFailureReason.PR_NOT_FOUND_OR_CLOSED,
detail: `GitHub API returned HTTP ${resp.status} for PR #${prNumber} in ${repo}`,
httpStatus: resp.status,
durationMs,
};
}
const pr = await resp.json() as Record<string, unknown>;
if (pr.state !== 'open') {
return {
check: 'pr_accessible',
passed: false,
reason: PreflightFailureReason.PR_NOT_FOUND_OR_CLOSED,
detail: `PR #${prNumber} in ${repo} is ${pr.state}, not open`,
durationMs,
};
}
return { check: 'pr_accessible', passed: true, durationMs };
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
logger.warn('PR accessibility check failed', { repo, pr_number: prNumber, error: detail });
return {
check: 'pr_accessible',
passed: false,
reason: PreflightFailureReason.GITHUB_UNREACHABLE,
detail,
durationMs: Date.now() - start,
};
}
}
async function checkRuntimeAvailability(): Promise<PreflightCheckResult> {
const start = Date.now();
return { check: 'runtime_availability', passed: true, durationMs: Date.now() - start };
}
/** Order for surfacing the most actionable failure when multiple checks fail. */
const PREFLIGHT_FAILURE_PRIORITY: readonly PreflightFailureReasonType[] = [
PreflightFailureReason.GITHUB_UNREACHABLE,
PreflightFailureReason.INSUFFICIENT_GITHUB_REPO_PERMISSIONS,
PreflightFailureReason.REPO_NOT_FOUND_OR_NO_ACCESS,
PreflightFailureReason.PR_NOT_FOUND_OR_CLOSED,
PreflightFailureReason.RUNTIME_UNAVAILABLE,
];
function pickPrimaryPreflightFailure(failedChecks: PreflightCheckResult[]): PreflightCheckResult {
for (const reason of PREFLIGHT_FAILURE_PRIORITY) {
const hit = failedChecks.find(c => c.reason === reason);
if (hit) {
return hit;
}
}
return failedChecks[0];
}
// ---------------------------------------------------------------------------
// Main pre-flight check runner
// ---------------------------------------------------------------------------
export async function runPreflightChecks(
repo: string,
blueprintConfig: BlueprintConfig,
prNumber?: number,
taskType: TaskType = 'new_task',
): Promise<PreflightResult> {
const checks: PreflightCheckResult[] = [];
if (blueprintConfig.github_token_secret_arn) {
// Resolve token — fail immediately if token resolution fails
let token: string;
const tokenStart = Date.now();
try {
token = await resolveGitHubToken(blueprintConfig.github_token_secret_arn);
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
logger.error('GitHub token resolution failed', { repo, error: detail });
checks.push({
check: 'github_token_resolution',
passed: false,
reason: PreflightFailureReason.GITHUB_UNREACHABLE,
detail,
durationMs: Date.now() - tokenStart,
});
return {
passed: false,
checks,
failureReason: PreflightFailureReason.GITHUB_UNREACHABLE,
failureDetail: detail,
};
}
// Run reachability + repo access checks in parallel
// eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism
const results = await Promise.allSettled([
checkGitHubReachability(token),
checkRepoAccess(repo, token, taskType),
...(prNumber !== undefined ? [checkPrAccessible(repo, prNumber, token)] : []),
]);
for (const result of results) {
if (result.status === 'fulfilled') {
checks.push(result.value);
} else {
// Defensive: inner check functions catch internally, but handle unexpected rejections fail-closed
const errorDetail = result.reason instanceof Error ? result.reason.message : String(result.reason);
logger.error('Pre-flight check promise rejected unexpectedly', { repo, error: errorDetail });
checks.push({
check: 'unknown',
passed: false,
reason: PreflightFailureReason.GITHUB_UNREACHABLE,
detail: `Internal error: ${errorDetail}`,
durationMs: 0,
});
}
}
} else {
logger.warn('No GitHub token configured — skipping GitHub pre-flight checks', { repo });
}
// Runtime check (behind feature flag — read at call time so tests can toggle)
if (process.env.PREFLIGHT_CHECK_RUNTIME === 'true') {
checks.push(await checkRuntimeAvailability());
}
// Aggregate: passed only if all checks passed
const failedChecks = checks.filter(c => !c.passed);
if (failedChecks.length === 0) {
return { passed: true, checks };
}
const primaryFailure = pickPrimaryPreflightFailure(failedChecks);
return {
passed: false,
checks,
failureReason: primaryFailure.reason,
failureDetail: primaryFailure.detail,
};
}