forked from step-security/auto-unapprove
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauto-unapprove.js
More file actions
executable file
·674 lines (584 loc) · 21.6 KB
/
Copy pathauto-unapprove.js
File metadata and controls
executable file
·674 lines (584 loc) · 21.6 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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
#!/usr/bin/env node
/**
* 🚫 Smart Review Dismissal Script
*
* Selectively dismisses PR reviews from code owners whose files were modified.
* Optimized for performance with GitHub API v2022-11-28.
*
* Action Inputs:
* github-token - GitHub API token (required)
* pr-number - Pull request number (required)
* team-start-with - Team prefix (default: @your-org/)
* dry-run - Set to 'false' for actual dismissals (default: true)
* code-owners-file - Path to CODEOWNERS file (default: CODEOWNERS)
* target-branch - Target branch for CODEOWNERS file (default: main)
*
* Environment Variables (GitHub Actions built-ins):
* GITHUB_REPOSITORY - Repository in format owner/repo (required)
* CHANGED_FILES - Newline-separated list of files (for webhook optimization)
*/
const fs = require("fs");
const core = require("@actions/core");
const axios = require("axios");
const token = core.getInput("github-token");
const repository = process.env.GITHUB_REPOSITORY;
const [owner, repo] = repository?.split("/") || [];
const team_start_with = core.getInput("team-start-with") || "@";
const prNumber = core.getInput("pr-number");
const dryRun = core.getInput("dry-run") !== "false";
const codeownersFile = core.getInput("code-owners-file") || "CODEOWNERS";
const targetBranch = core.getInput("target-branch") || "main";
async function validateSubscription() {
let repoPrivate;
const eventPath = process.env.GITHUB_EVENT_PATH;
if (eventPath && fs.existsSync(eventPath)) {
const payload = JSON.parse(fs.readFileSync(eventPath, "utf8"));
repoPrivate = payload?.repository?.private;
}
const upstream = "RotemK1/auto-unapprove";
const action = process.env.GITHUB_ACTION_REPOSITORY;
const docsUrl =
"https://docs.stepsecurity.io/actions/stepsecurity-maintained-actions";
core.info("");
core.info("\u001b[1;36mStepSecurity Maintained Action\u001b[0m");
core.info(`Secure drop-in replacement for ${upstream}`);
if (repoPrivate === false)
core.info("\u001b[32m\u2713 Free for public repositories\u001b[0m");
core.info(`\u001b[36mLearn more:\u001b[0m ${docsUrl}`);
core.info("");
if (repoPrivate === false) return;
const serverUrl = process.env.GITHUB_SERVER_URL || "https://github.com";
const body = { action: action || "" };
if (serverUrl !== "https://github.com") body.ghes_server = serverUrl;
try {
await axios.post(
`https://agent.api.stepsecurity.io/v1/github/${process.env.GITHUB_REPOSITORY}/actions/maintained-actions-subscription`,
body,
{ timeout: 3000 },
);
} catch (error) {
if (axios.isAxiosError(error) && error.response?.status === 403) {
core.error(
`\u001b[1;31mThis action requires a StepSecurity subscription for private repositories.\u001b[0m`,
);
core.error(
`\u001b[31mLearn how to enable a subscription: ${docsUrl}\u001b[0m`,
);
process.exit(1);
}
core.info("Timeout or API not reachable. Continuing to next step.");
}
}
async function smartDismissReviews() {
try {
await validateSubscription();
// Validate inputs
if (!token) {
throw new Error("github-token input is required");
}
if (!prNumber) {
throw new Error("pr-number input is required");
}
if (!repository) {
throw new Error("GITHUB_REPOSITORY environment variable is required");
}
if (!owner || !repo) {
throw new Error('GITHUB_REPOSITORY must be in format "owner/repo"');
}
console.log(`🚀 Smart Review Dismissal`);
console.log(` Repository: ${owner}/${repo}`);
console.log(` PR: #${prNumber}`);
console.log(` Mode: ${dryRun ? "🧪 DRY RUN" : "⚡ LIVE"}`);
console.log(` Target branch: ${targetBranch}`);
console.log(` Team start with: ${team_start_with}`);
console.log(` Codeowners file: ${codeownersFile}`);
console.log("");
const headers = {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${token}`,
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": "dismiss-reviews-action",
};
// Step 1: Get changed files (optimize for webhook payload if available)
let changedFiles = [];
if (process.env.CHANGED_FILES) {
// Ultra-fast: Use webhook payload
changedFiles = process.env.CHANGED_FILES.split("\n").filter((f) =>
f.trim(),
);
console.log(`📁 Files from webhook payload (${changedFiles.length}):`);
} else {
// Fast: Get ALL files changed in the PR with pagination
console.log(`📁 Fetching ALL changed files from PR (with pagination)...`);
changedFiles = await getAllChangedFiles(headers);
console.log(`📁 All changed files in PR (${changedFiles.length}):`);
}
if (changedFiles.length === 0) {
console.log(" No files changed - nothing to analyze");
return;
}
changedFiles.forEach((file) => {
console.log(` 📝 ${file}`);
});
// Step 2: Get PR reviews, CODEOWNERS, and commit authors in parallel
console.log(`\n👥 Fetching PR reviews, CODEOWNERS, and commit authors...`);
console.log(`🎯 Target branch: ${targetBranch}`);
const [codeownersResponse] = await Promise.all([
fetch(
`https://api.github.com/repos/${owner}/${repo}/contents/${codeownersFile}?ref=${targetBranch}`,
{ headers },
),
]);
// Get all reviews and commits with pagination
console.log(`📋 Fetching all reviews and commits...`);
const reviews = await getAllReviews(headers);
const commits = await getAllCommits(headers);
const approvedReviews = reviews.filter(
(review) => review.state === "APPROVED",
);
const approvedReviewers = [
...new Set(approvedReviews.map((review) => review.user.login)),
];
// Get commit authors
const commitAuthors = new Set(
commits.map((commit) => commit.author?.login).filter(Boolean),
);
console.log(
`✅ Found ${approvedReviews.length} approved reviews from ${approvedReviewers.length} reviewers`,
);
console.log(
`📝 Found ${commits.length} commits from authors: ${Array.from(commitAuthors).join(", ")}`,
);
if (approvedReviewers.length === 0) {
console.log(" No approved reviews to analyze");
return;
}
// Step 3: Parse CODEOWNERS
let codeowners = [];
if (codeownersResponse.ok) {
const codeownersData = await codeownersResponse.json();
if (codeownersData.content) {
const decodedContent = Buffer.from(
codeownersData.content,
"base64",
).toString("utf8");
codeowners = parseCodeowners(decodedContent);
console.log(`👑 Parsed ${codeowners.length} CODEOWNERS rules`);
}
} else {
console.log("⚠️ No CODEOWNERS file found - using default ownership");
}
// Step 4: Map changed files to code owners
console.log(`\n🔍 Mapping files to code owners...`);
const changedFileOwners = new Map();
for (const file of changedFiles) {
const owners = getFileOwnersHierarchical(file, codeowners);
changedFileOwners.set(file, owners);
if (owners.length > 0) {
console.log(` ${file} → ${owners.join(", ")}`);
} else {
console.log(` ${file} → No specific owners`);
}
}
// Step 5: Get relevant teams (only for changed files)
const relevantTeams = getRelevantTeams(changedFileOwners);
console.log(`\n🏢 Checking ${relevantTeams.length} relevant teams...`);
// Step 6: Check team memberships for approved reviewers (only relevant teams)
const teamMemberships = new Map();
for (const reviewer of approvedReviewers) {
teamMemberships.set(reviewer, new Map());
for (const team of relevantTeams) {
const isMember = await checkTeamMembership(reviewer, team, headers);
teamMemberships.get(reviewer).set(team, isMember);
if (isMember) {
console.log(` ✅ @${reviewer} ∈ ${team_start_with}${team}`);
}
}
}
// Step 7: STALE APPROVAL ANALYSIS
console.log(`\n🎯 DISMISSAL ANALYSIS:`);
const dismissalTargets = [];
for (const reviewer of approvedReviewers) {
const { isCodeowner, ownedFiles, viaTeams } = isUserCodeownerForFiles(
reviewer,
changedFileOwners,
teamMemberships.get(reviewer),
);
const isCommitAuthor = commitAuthors.has(reviewer);
let hasStaleApproval = false;
let staleReason = "";
let commitsAfterApproval = [];
let affectedOwnedFiles = [];
// Get reviewer's approvals with timestamps
const reviewerApprovals = approvedReviews.filter(
(r) => r.user.login === reviewer,
);
if (isCodeowner && reviewerApprovals.length > 0) {
// Check for commits after approval to owned files
const latestApproval = reviewerApprovals.sort(
(a, b) => new Date(b.submitted_at) - new Date(a.submitted_at),
)[0];
const approvalTime = new Date(latestApproval.submitted_at);
// Get commits after approval
commitsAfterApproval = commits.filter((commit) => {
const commitTime = new Date(commit.commit.committer.date);
return commitTime > approvalTime;
});
if (commitsAfterApproval.length > 0) {
console.log(
` 🕐 Checking commits after ${reviewer}'s approval (${approvalTime.toISOString()})...`,
);
// Check if post-approval commits actually touched owned files
affectedOwnedFiles = [];
for (const commit of commitsAfterApproval) {
console.log(
` 📅 Commit ${commit.sha.substring(0, 7)} at ${commit.commit.committer.date}`,
);
// Get files changed in this commit
try {
const commitDetailsResponse = await fetch(
`https://api.github.com/repos/${owner}/${repo}/commits/${commit.sha}`,
{ headers },
);
if (commitDetailsResponse.ok) {
const commitDetails = await commitDetailsResponse.json();
const commitFiles = commitDetails.files.map((f) => f.filename);
// Check if any commit files are owned by this reviewer
const intersection = commitFiles.filter((file) =>
ownedFiles.includes(file),
);
if (intersection.length > 0) {
affectedOwnedFiles.push(...intersection);
console.log(
` 🎯 Modified owned files: ${intersection.join(", ")}`,
);
}
}
} catch (error) {
console.log(
` ⚠️ Could not fetch commit details: ${error.message}`,
);
}
}
if (affectedOwnedFiles.length > 0) {
hasStaleApproval = true;
staleReason = `Approval became stale - commits modified owned files: ${[...new Set(affectedOwnedFiles)].join(", ")}`;
} else {
console.log(
` ✅ No owned files modified - approval stays valid`,
);
}
}
}
// Dismissal logic: code owner who authored commits OR has stale approval
if (isCodeowner && (isCommitAuthor || hasStaleApproval)) {
const reviewIds = reviewerApprovals.map((r) => r.id);
dismissalTargets.push({
reviewer,
ownedFiles,
viaTeams,
reviewIds,
reason: isCommitAuthor
? "Code owner who authored changes"
: staleReason,
latestCommit:
commitsAfterApproval.length > 0
? commitsAfterApproval[commitsAfterApproval.length - 1]
: null,
affectedFilesCount: hasStaleApproval
? [...new Set(affectedOwnedFiles)].length
: 0,
});
console.log(` `);
console.log(` 🚫 DISMISS @${reviewer}`);
console.log(` 📁 Files: ${ownedFiles.join(", ")}`);
console.log(
` 👑 Owner Via: ${viaTeams.join(", ") || "Direct ownership"}`,
);
console.log(` 🔢 Reviews: ${reviewIds.length}`);
console.log(
` 💡 Reason: ${isCommitAuthor ? "Code owner who authored changes" : staleReason}`,
);
} else {
console.log(` ✅ KEEP @${reviewer}`);
if (viaTeams.length > 0) {
console.log(` 👑 Owner Via: ${viaTeams.join(", ")}`);
}
if (!isCodeowner) {
console.log(` 📄 Not owner of changed files`);
} else if (!isCommitAuthor && !hasStaleApproval) {
console.log(` 👤 Code owner with fresh approval`);
}
}
}
// Step 8: EXECUTION PLAN
console.log(`\n📊 EXECUTION PLAN:`);
console.log(` • Changed files: ${changedFiles.length}`);
console.log(` • Total approvals: ${approvedReviews.length}`);
console.log(` • Dismissals needed: ${dismissalTargets.length}`);
console.log(
` • Approvals preserved: ${approvedReviews.length - dismissalTargets.length}`,
);
// Step 9: Execute dismissals
if (dismissalTargets.length > 0) {
console.log(`\n${dryRun ? "🧪 WOULD DISMISS" : "🚫 DISMISSING"}:`);
for (const target of dismissalTargets) {
console.log(
` @${target.reviewer} (${target.reviewIds.length} reviews)`,
);
console.log(` Reason: ${target.reason}`);
console.log(` Files: ${target.ownedFiles.length} changed file(s)`);
console.log(
` Owner Via: ${target.viaTeams.join(", ") || "Direct ownership"}`,
);
if (!dryRun) {
// Actually dismiss reviews
for (const reviewId of target.reviewIds) {
try {
const dismissResponse = await fetch(
`https://api.github.com/repos/${owner}/${repo}/pulls/${prNumber}/reviews/${reviewId}/dismissals`,
{
method: "PUT",
headers,
body: JSON.stringify({
message: target.latestCommit
? `${target.affectedFilesCount} file(s) changed in commit [${target.latestCommit.sha.substring(0, 7)}](https://github.com/${owner}/${repo}/commit/${target.latestCommit.sha})`
: "Unapproved",
}),
},
);
if (dismissResponse.ok) {
console.log(` ✅ Dismissed review ${reviewId}`);
} else {
console.log(
` ❌ Failed to dismiss review ${reviewId}: ${dismissResponse.status}`,
);
}
} catch (error) {
console.log(
` ❌ Error dismissing review ${reviewId}: ${error.message}`,
);
}
}
}
}
} else {
console.log(`\n✅ NO DISMISSALS NEEDED`);
console.log(
` No reviewers both own changed files AND authored commits.`,
);
}
console.log(`\n🎉 Analysis complete!`);
} catch (error) {
console.error("❌ Error:", error.message);
process.exit(1);
}
}
// Helper functions
async function getAllChangedFiles(headers) {
const allFiles = [];
let page = 1;
const perPage = 100; // Maximum allowed by GitHub API
// eslint-disable-next-line no-constant-condition
while (true) {
const url = `https://api.github.com/repos/${owner}/${repo}/pulls/${prNumber}/files?page=${page}&per_page=${perPage}`;
console.log(` 📄 Fetching page ${page}...`);
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(
`Failed to fetch PR files page ${page}: ${response.status}`,
);
}
const files = await response.json();
if (files.length === 0) {
break; // No more files
}
allFiles.push(...files.map((file) => file.filename));
console.log(` 📄 Page ${page}: ${files.length} files`);
// Check if we've reached the last page
if (files.length < perPage) {
break;
}
page++;
}
return allFiles;
}
async function getAllReviews(headers) {
const allReviews = [];
let page = 1;
const perPage = 100; // Maximum allowed by GitHub API
// eslint-disable-next-line no-constant-condition
while (true) {
const url = `https://api.github.com/repos/${owner}/${repo}/pulls/${prNumber}/reviews?page=${page}&per_page=${perPage}`;
console.log(` 📋 Fetching reviews page ${page}...`);
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(
`Failed to fetch reviews page ${page}: ${response.status}`,
);
}
const reviews = await response.json();
if (reviews.length === 0) {
break; // No more reviews
}
allReviews.push(...reviews);
console.log(` 📋 Reviews page ${page}: ${reviews.length} reviews`);
// Check if we've reached the last page
if (reviews.length < perPage) {
break;
}
page++;
}
return allReviews;
}
async function getAllCommits(headers) {
const allCommits = [];
let page = 1;
const perPage = 100; // Maximum allowed by GitHub API
// eslint-disable-next-line no-constant-condition
while (true) {
const url = `https://api.github.com/repos/${owner}/${repo}/pulls/${prNumber}/commits?page=${page}&per_page=${perPage}`;
console.log(` 📝 Fetching commits page ${page}...`);
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(
`Failed to fetch commits page ${page}: ${response.status}`,
);
}
const commits = await response.json();
if (commits.length === 0) {
break; // No more commits
}
allCommits.push(...commits);
console.log(` 📝 Commits page ${page}: ${commits.length} commits`);
// Check if we've reached the last page
if (commits.length < perPage) {
break;
}
page++;
}
return allCommits;
}
function parseCodeowners(content) {
const lines = content.split("\n");
const owners = [];
lines.forEach((line) => {
const trimmed = line.trim();
if (trimmed && !trimmed.startsWith("#")) {
const parts = trimmed.split(/\s+/);
if (parts.length >= 2) {
const path = parts[0];
const ownersList = parts.slice(1);
owners.push({ path, owners: ownersList });
}
}
});
return owners;
}
function getFileOwnersHierarchical(filename, codeowners) {
const normalizedFile = filename.startsWith("/") ? filename : "/" + filename;
let bestMatch = null;
let bestMatchLength = -1;
codeowners.forEach((entry) => {
if (pathMatches(normalizedFile, entry.path)) {
const pathLength = entry.path.length;
if (pathLength > bestMatchLength) {
bestMatch = entry;
bestMatchLength = pathLength;
}
}
});
return bestMatch ? bestMatch.owners : [];
}
function pathMatches(filename, pattern) {
const normalizedFile = filename.startsWith("/") ? filename : "/" + filename;
const normalizedPattern = pattern.startsWith("/") ? pattern : "/" + pattern;
if (pattern === "*") return true;
if (normalizedPattern === normalizedFile) return true;
// Handle directory patterns (ending with /)
if (pattern.endsWith("/")) {
const dirPattern = pattern.startsWith("/") ? pattern : "/" + pattern;
return normalizedFile.startsWith(dirPattern);
}
// Handle wildcard patterns
if (pattern.includes("*")) {
const regex = normalizedPattern
.replace(/[.+?^${}()|[\]\\]/g, "\\$&")
.replace(/\*/g, ".*");
return new RegExp(`^${regex}$`).test(normalizedFile);
}
// Handle file/directory without trailing slash
const filePattern = normalizedPattern.endsWith("/")
? normalizedPattern
: normalizedPattern + "/";
return (
normalizedFile.startsWith(filePattern) ||
normalizedFile === normalizedPattern
);
}
function getRelevantTeams(fileOwnersMap) {
const teams = new Set();
for (const [filename, owners] of fileOwnersMap) {
owners.forEach((owner) => {
if (owner.startsWith(`${team_start_with}`)) {
const teamName = owner.replace(`${team_start_with}`, "");
teams.add(teamName);
}
});
console.log(`filename: ${filename}`);
console.log(`owners: ${owners}`);
}
return Array.from(teams);
}
async function checkTeamMembership(username, teamSlug, headers) {
try {
const response = await fetch(
`https://api.github.com/orgs/${owner}/teams/${teamSlug}/members/${username}`,
{ headers },
);
return response.status === 204;
} catch (error) {
console.log(`error: ${error}`);
return false;
}
}
function isUserCodeownerForFiles(username, fileOwnersMap, userTeamMemberships) {
let isCodeowner = false;
const ownedFiles = [];
const viaTeams = new Set();
for (const [filename, fileOwners] of fileOwnersMap) {
for (const owner of fileOwners) {
// Direct ownership
if (owner === `@${username}`) {
isCodeowner = true;
ownedFiles.push(filename);
break;
}
// Team ownership
if (owner.startsWith(`${team_start_with}`)) {
const teamName = owner.replace(`${team_start_with}`, "");
if (userTeamMemberships && userTeamMemberships.get(teamName)) {
isCodeowner = true;
ownedFiles.push(filename);
viaTeams.add(`${team_start_with}${teamName}`);
break;
}
}
}
}
return {
isCodeowner,
ownedFiles: [...new Set(ownedFiles)],
viaTeams: Array.from(viaTeams),
};
}
// Run if called directly
if (require.main === module) {
smartDismissReviews();
}
module.exports = {
smartDismissReviews,
getAllChangedFiles,
getAllReviews,
getAllCommits,
};