-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbranch-protection.script.ts
More file actions
456 lines (410 loc) · 14.3 KB
/
Copy pathbranch-protection.script.ts
File metadata and controls
456 lines (410 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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
#!/usr/bin/env bun
/**
* `bun run scripts/gates/branch-protection.script.ts`
*
* Verifica en GitHub que `develop` y cualquier `release/*` existente
* tengan branch protection activada y exijan los checks del workflow
* principal de validación.
*
* Ejecución real:
* GITHUB_TOKEN=<token> GITHUB_REPOSITORY=<owner/repo> \
* bun run scripts/gates/branch-protection.script.ts
*
* Para tests no hace falta credenciales: `fetch` y `baseUrl` son
* inyectables desde `validateBranchProtection()`.
*/
import { readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const DEFAULT_GITHUB_API_BASE_URL = "https://api.github.com";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
const CI_CONFIG = JSON.parse(readFileSync(resolve(ROOT, "delendai.config.json"), "utf8")) as {
ci: {
requiredChecks: ReadonlyArray<string>;
branchProtection: {
rulesetName: string;
requiredStatusChecksStrict: boolean;
enforceAdmins: boolean;
requiredApprovingReviewCount: number;
dismissStaleReviews: boolean;
requireCodeOwnerReviews: boolean;
requiredLinearHistory: boolean;
allowForcePushes: boolean;
allowDeletions: boolean;
requiredConversationResolution: boolean;
};
};
};
export const REQUIRED_CHECKS = CI_CONFIG.ci.requiredChecks;
export const BRANCH_PROTECTION_POLICY = CI_CONFIG.ci.branchProtection;
export type FetchLike = typeof fetch;
interface IResponseLike {
readonly ok: boolean;
readonly status: number;
json(): Promise<unknown>;
text(): Promise<string>;
}
interface IRequestUrlLike {
readonly hostname: string;
readonly protocol: string;
readonly port: string;
readonly pathname: string;
readonly search: string;
}
export interface IBranchProtectionOptions {
readonly repository?: string;
readonly token?: string;
readonly baseUrl?: string;
readonly fetchImpl?: FetchLike;
readonly branches?: ReadonlyArray<string>;
}
export interface IBranchCheckResult {
readonly branch: string;
readonly ok: boolean;
readonly detail: string;
}
export interface IBranchProtectionResult {
readonly ok: boolean;
readonly repository: string;
readonly checkedBranches: ReadonlyArray<string>;
readonly results: ReadonlyArray<IBranchCheckResult>;
}
interface IGitHubBranchSummary {
readonly name?: string;
}
interface IGitHubBranchDetails {
readonly name?: string;
readonly protected?: boolean;
readonly required_status_checks?: {
readonly strict?: boolean;
readonly contexts?: ReadonlyArray<string> | null;
} | null;
readonly enforce_admins?: { readonly enabled?: boolean } | null;
readonly required_pull_request_reviews?: {
readonly required_approving_review_count?: number;
readonly dismiss_stale_reviews?: boolean;
readonly require_code_owner_reviews?: boolean;
} | null;
readonly required_linear_history?: boolean;
readonly allow_force_pushes?: boolean;
readonly allow_deletions?: boolean;
readonly required_conversation_resolution?: boolean;
}
interface IGitHubRuleset {
readonly name?: string;
readonly target?: string;
readonly enforcement?: string;
readonly conditions?: {
readonly ref_name?: {
readonly include?: ReadonlyArray<string>;
};
};
}
interface IGitHubErrorPayload {
readonly message?: string;
}
export async function validateBranchProtection(
options: IBranchProtectionOptions,
): Promise<IBranchProtectionResult> {
const repository = normalizeRepository(options.repository);
const fetchImpl = options.fetchImpl ?? fetch;
const baseUrl = normalizeBaseUrl(options.baseUrl);
const branches = await resolveBranches({
repository,
token: options.token,
baseUrl,
fetchImpl,
requestedBranches: options.branches,
});
const results: IBranchCheckResult[] = [];
for (const branch of branches) {
results.push(
await checkBranchProtection({
repository,
branch,
token: options.token,
baseUrl,
fetchImpl,
}),
);
}
return {
ok: results.every((result) => result.ok),
repository,
checkedBranches: branches,
results,
};
}
interface IResolveBranchesOptions {
readonly repository: string;
readonly token?: string;
readonly baseUrl: string;
readonly fetchImpl: FetchLike;
readonly requestedBranches?: ReadonlyArray<string>;
}
async function resolveBranches(options: IResolveBranchesOptions): Promise<ReadonlyArray<string>> {
const requested = (options.requestedBranches ?? [])
.map((branch) => branch.trim())
.filter((branch) => branch.length > 0);
if (requested.length > 0) {
return [...new Set(requested)];
}
const branchesUrl = new URL(
`/repos/${options.repository}/branches?per_page=100`,
`${options.baseUrl}/`,
);
const response = await fetchImplWithAuth(options.fetchImpl, branchesUrl, options.token);
if (response.status === 404) {
throw new Error(
`Repositorio o API inexistente para ${options.repository}. ` +
`GitHub devolvió 404 al listar ramas.`,
);
}
if (!response.ok) {
throw new Error(await formatGitHubError(response, `No se pudo listar ramas en ${options.repository}`));
}
const payload = (await response.json()) as unknown;
if (!Array.isArray(payload)) {
throw new Error(`GitHub devolvió una respuesta inesperada al listar ramas de ${options.repository}.`);
}
const releaseBranches = payload
.map((entry) => (entry as IGitHubBranchSummary).name)
.filter((name): name is string => typeof name === "string" && name.startsWith("release/"));
return ["develop", ...releaseBranches];
}
interface ICheckBranchProtectionOptions {
readonly repository: string;
readonly branch: string;
readonly token?: string;
readonly baseUrl: string;
readonly fetchImpl: FetchLike;
}
async function checkBranchProtection(
options: ICheckBranchProtectionOptions,
): Promise<IBranchCheckResult> {
const branchUrl = new URL(
`/repos/${options.repository}/branches/${encodeURIComponent(options.branch)}`,
`${options.baseUrl}/`,
);
const branchResponse = await fetchImplWithAuth(options.fetchImpl, branchUrl, options.token);
if (branchResponse.status === 404) {
return {
branch: options.branch,
ok: false,
detail: `rama inexistente o API no expone ${options.branch} (404)`,
};
}
if (!branchResponse.ok) {
return {
branch: options.branch,
ok: false,
detail: await formatGitHubError(
branchResponse,
`GitHub rechazó la consulta de ${options.branch}`,
),
};
}
const branchPayload = (await branchResponse.json()) as IGitHubBranchDetails;
if (branchPayload.protected !== true) {
return {
branch: options.branch,
ok: false,
detail: `protected=true ausente`,
};
}
const protectionUrl = new URL(
`/repos/${options.repository}/branches/${encodeURIComponent(options.branch)}/protection`,
`${options.baseUrl}/`,
);
const protectionResponse = await fetchImplWithAuth(
options.fetchImpl,
protectionUrl,
options.token,
);
if (protectionResponse.status === 404) {
// 404 en `/protection` significa "la rama no tiene regla", no
// "faltan contexts". Decirlo mal manda a corregir un campo dentro
// de una protección que no existe.
return {
branch: options.branch,
ok: false,
detail: `la rama no tiene ninguna regla de protección`,
};
}
if (protectionResponse.status === 401 || protectionResponse.status === 403) {
// NO es lo mismo que "la protección está mal". No se ha leído nada,
// así que no se concluye nada sobre ella: leer branch protection
// exige Administration: read, y el token por defecto de Actions no
// lo tiene. Un check que no pudo verificar una propiedad tampoco
// puede certificarla, así que sigue siendo un fallo — pero con el
// motivo correcto y el remedio a mano.
return {
branch: options.branch,
ok: false,
detail: `no se pudo leer la protección (HTTP ${protectionResponse.status}); nada se concluye de ello. Configura BRANCH_PROTECTION_TOKEN con Administration: read`,
};
}
if (!protectionResponse.ok) {
return {
branch: options.branch,
ok: false,
detail: await formatGitHubError(
protectionResponse,
`GitHub rechazó la protección de ${options.branch}`,
),
};
}
const payload = (await protectionResponse.json()) as IGitHubBranchDetails;
const contexts = payload.required_status_checks?.contexts;
if (!Array.isArray(contexts) || contexts.length === 0) {
return {
branch: options.branch,
ok: false,
detail: `required_status_checks.contexts ausente`,
};
}
const missingChecks = REQUIRED_CHECKS.filter((check) => !contexts.includes(check));
if (missingChecks.length > 0) {
return {
branch: options.branch,
ok: false,
detail: `faltan required checks: ${missingChecks.join(", ")}`,
};
}
if (payload.required_status_checks?.strict !== BRANCH_PROTECTION_POLICY.requiredStatusChecksStrict ||
payload.enforce_admins?.enabled !== BRANCH_PROTECTION_POLICY.enforceAdmins) {
return { branch: options.branch, ok: false, detail: "strict o enforce_admins divergen de la política" };
}
const reviews = payload.required_pull_request_reviews;
if (reviews?.required_approving_review_count !== BRANCH_PROTECTION_POLICY.requiredApprovingReviewCount ||
reviews.dismiss_stale_reviews !== BRANCH_PROTECTION_POLICY.dismissStaleReviews ||
reviews.require_code_owner_reviews !== BRANCH_PROTECTION_POLICY.requireCodeOwnerReviews) {
return {
branch: options.branch,
ok: false,
detail: `required_pull_request_reviews diverge de la política`,
};
}
if (payload.required_linear_history !== BRANCH_PROTECTION_POLICY.requiredLinearHistory ||
payload.allow_force_pushes !== BRANCH_PROTECTION_POLICY.allowForcePushes ||
payload.allow_deletions !== BRANCH_PROTECTION_POLICY.allowDeletions ||
payload.required_conversation_resolution !== BRANCH_PROTECTION_POLICY.requiredConversationResolution) {
return { branch: options.branch, ok: false, detail: "historial, force-push, borrado o conversaciones divergen de la política" };
}
const rulesetsUrl = new URL(
`/repos/${options.repository}/rulesets?includes_parents=true&per_page=100`,
`${options.baseUrl}/`,
);
const rulesetsResponse = await fetchImplWithAuth(options.fetchImpl, rulesetsUrl, options.token);
if (!rulesetsResponse.ok) {
return {
branch: options.branch,
ok: false,
detail: await formatGitHubError(rulesetsResponse, `GitHub rechazó la consulta de rulesets`),
};
}
const rulesets = (await rulesetsResponse.json()) as unknown;
if (!Array.isArray(rulesets) || !rulesets.some((ruleset) => {
const candidate = ruleset as IGitHubRuleset;
const branchRef = `refs/heads/${options.branch}`;
return candidate.name === BRANCH_PROTECTION_POLICY.rulesetName && candidate.target === "branch" && candidate.enforcement === "active" &&
candidate.conditions?.ref_name?.include?.some((pattern) =>
pattern === options.branch || pattern === branchRef || pattern === "refs/heads/*");
})) {
return {
branch: options.branch,
ok: false,
detail: `ruleset activo ausente para ${options.branch}`,
};
}
return {
branch: options.branch,
ok: true,
detail: `protected=true, ${REQUIRED_CHECKS.length} checks requeridos, PR review y ruleset activo presentes`,
};
}
function normalizeRepository(repository?: string): string {
const value = repository?.trim();
if (!value) {
throw new Error(
"Falta GITHUB_REPOSITORY. La ejecución real requiere GITHUB_TOKEN y GITHUB_REPOSITORY.",
);
}
if (!/^[^/]+\/[^/]+$/.test(value)) {
throw new Error(`GITHUB_REPOSITORY debe tener la forma owner/repo; recibido: ${value}`);
}
return value;
}
function normalizeBaseUrl(baseUrl?: string): string {
const value = (baseUrl ?? DEFAULT_GITHUB_API_BASE_URL).trim();
return value.endsWith("/") ? value.slice(0, -1) : value;
}
async function fetchImplWithAuth(
fetchImpl: FetchLike,
url: IRequestUrlLike,
token?: string,
): Promise<IResponseLike> {
const headers: Record<string, string> = {
Accept: "application/vnd.github+json",
"User-Agent": "tanit-branch-protection-gate",
};
if (token?.trim()) {
headers.Authorization = `Bearer ${token.trim()}`;
}
const port = url.port ? `:${url.port}` : "";
return fetchImpl(
`${url.protocol}//${url.hostname}${port}${url.pathname}${url.search}`,
{ headers },
) as Promise<IResponseLike>;
}
async function formatGitHubError(response: IResponseLike, prefix: string): Promise<string> {
let message = "respuesta sin detalle";
try {
const payload = (await response.json()) as IGitHubErrorPayload;
if (typeof payload.message === "string" && payload.message.trim().length > 0) {
message = payload.message.trim();
}
} catch {
const text = await response.text();
if (text.trim().length > 0) {
message = text.trim();
}
}
return `${prefix}: HTTP ${response.status} ${message}`;
}
export async function main(): Promise<number> {
const token = process.env.GITHUB_TOKEN;
const repository = process.env.GITHUB_REPOSITORY;
if (!token?.trim() || !repository?.trim()) {
console.error(
"branch-protection — la ejecución real requiere GITHUB_TOKEN y GITHUB_REPOSITORY. " +
"Para tests, usa validateBranchProtection() con fetch/baseUrl inyectables.",
);
return 1;
}
try {
const result = await validateBranchProtection({ token, repository });
for (const branchResult of result.results) {
const prefix = branchResult.ok ? "ok " : "FAIL ";
console.log(`${prefix}${branchResult.branch.padEnd(20)} ${branchResult.detail}`);
}
if (!result.ok) {
console.error(
`\nbranch-protection — ${result.repository} no cumple la política de protección requerida.`,
);
return 1;
}
console.log(
`\nbranch-protection — ${result.repository} exige ${REQUIRED_CHECKS.join(", ")} ` +
`en ${result.checkedBranches.join(", ")}.`,
);
return 0;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error(`branch-protection — FAIL ${message}`);
return 1;
}
}
if (import.meta.main) {
process.exit(await main());
}