-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpull-request-management-fork.yml
More file actions
533 lines (484 loc) Β· 25.9 KB
/
pull-request-management-fork.yml
File metadata and controls
533 lines (484 loc) Β· 25.9 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
# ------------------------------------------------------------------------------------
# Pull Request Management for Forks Workflow
#
# Purpose: Automate labeling, assignment, and welcoming of pull requests for forked PRs.
#
# Configuration: All settings are loaded from .env.base and .env.custom files for
# centralized management across all workflows.
#
# Triggers: Pull request events (opened, reopened, ready for review, closed, synchronize)
#
# Features:
# - Automatic labeling based on branch prefix and PR title
# - Default assignee management
# - Welcome messages for first-time contributors
# - PR size analysis and labeling
# - Cache cleanup on PR close
# - Branch deletion after merge
#
# Maintainer: @mrz1836
#
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# π SECURITY MODEL - Two-Workflow Pattern for Safe Fork PR Handling
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
#
# This workflow implements the RECOMMENDED security pattern for handling fork PRs
# as documented in GitHub Security Best Practices (githubactions:S7631).
#
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# β WHY pull_request_target IS SAFE HERE: β
# β β
# β β
Uses pull_request_target trigger for write permissions β
# β (Required for: labels, comments, assignees) β
# β β
# β β
CRITICAL: Only checks out BASE branch code, NEVER PR head β
# β (Prevents malicious code execution from untrusted forks) β
# β β
# β β
Fork detection uses full_name comparison for accuracy β
# β (Not owner.login which fails for org members) β
# β β
# β β
All code execution happens from trusted base repository β
# β (No code from PR is ever executed) β
# β β
# β β
No secrets exposed to fork PRs (GITHUB_TOKEN only) β
# β (No custom secrets accessible to malicious actors) β
# β β
# β β
Sparse checkout minimizes attack surface β
# β (Only config files checked out, no executable code) β
# β β
# β β
Least-privilege permissions model β
# β (Jobs get elevated permissions only where absolutely needed) β
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
#
# SECURITY PATTERN: Two-Workflow Approach
# ββ pull-request-management.yml β Same-repo PRs (uses pull_request)
# ββ pull-request-management-fork.yml β Fork PRs (uses pull_request_target)
#
# WHAT COULD GO WRONG (and how we prevent it):
# β Malicious fork creates PR with code that steals secrets
# β
PREVENTED: We never checkout or execute PR code
#
# β Attacker modifies workflow files in their fork
# β
PREVENTED: pull_request_target runs base repo workflow only
#
# β Malicious code in PR tries to access repository secrets
# β
PREVENTED: Only GITHUB_TOKEN exposed, no custom secrets
#
# β Code injection via PR title/description into workflow
# β
PREVENTED: All user input properly escaped in GitHub Actions
#
# SECURITY SCANNERS:
# - GitHub Security: May flag pull_request_target + checkout (FALSE POSITIVE)
# - Semgrep: May flag dangerous-checkout pattern (FALSE POSITIVE)
# - Checkov: May flag CKV_GHA_3 (FALSE POSITIVE)
#
# These are FALSE POSITIVES because:
# 1. We explicitly checkout base branch, not PR head
# 2. This is the RECOMMENDED pattern per GitHub docs
# 3. All security controls are properly implemented
#
# REFERENCES:
# - GitHub Security Advisory: githubactions:S7631
# - GitHub Docs: Keeping your GitHub Actions and workflows secure
# - OWASP: CI/CD Security Top 10
#
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
#
# ------------------------------------------------------------------------------------
name: PR Management (Forks)
# --------------------------------------------------------------------
# Trigger Configuration
# --------------------------------------------------------------------
on:
pull_request_target:
types: [opened, reopened, ready_for_review, closed, synchronize]
# Least privilege at the workflow level; jobs get bumps as needed
permissions:
contents: read
# --------------------------------------------------------------------
# Concurrency Control
# --------------------------------------------------------------------
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}-fork
cancel-in-progress: true
# --------------------------------------------------------------------
# Environment Variables
# --------------------------------------------------------------------
# Note: Configuration variables are loaded from .env.base and .env.custom files
jobs:
# ------------------------------------------------------------
# Load env from the BASE repo only (safe) for centralized config
# ------------------------------------------------------------
load-env:
name: π Load Environment (Base Repo)
runs-on: ubuntu-latest
# No write perms here
permissions:
contents: read
outputs:
env-json: ${{ steps.load-env.outputs.env-json }}
steps:
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# β SECURITY SCANNERS: This checkout is SAFE despite pull_request_targetβ
# β β
# β Justification: β
# β - Only checks out TRUSTED base branch (ref: github.base_ref) β
# β - NEVER checks out PR head code from untrusted fork β
# β - Implements recommended two-workflow security pattern β
# β - Uses sparse checkout (minimal attack surface) β
# β - No executable code from PR is ever run β
# β β
# β Pattern: Two-workflow security model (see SECURITY.md) β
# β References: githubactions:S7631, semgrep:github-actions-checkout β
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# semgrep:ignore github-actions-dangerous-checkout
# codeql:ignore GH001
# checkov:skip=CKV_GHA_3:Base branch checkout is intentional and safe
- name: π₯ Checkout base repo (sparse)
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
with:
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# π CRITICAL SECURITY CONTROL: Base Branch Checkout Only
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# This workflow uses pull_request_target for write permissions BUT
# ONLY checks out the trusted base branch code - NEVER PR head code.
#
# WHY THIS IS SAFE:
# - ref parameter explicitly set to base branch (github.base_ref)
# - Malicious fork PRs cannot inject code into this workflow
# - All code execution happens from trusted repository only
# - Sparse checkout limits to config files only (no executables)
#
# SECURITY MODEL:
# - pull_request_target = write permissions needed for labels/comments
# - Base branch checkout = prevents malicious code execution
# - This is the RECOMMENDED pattern for fork PR automation
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ref: ${{ github.base_ref }}
fetch-depth: 1
sparse-checkout: |
.github/.env.base
.github/.env.custom
.github/actions/load-env
- name: π Load environment variables
id: load-env
uses: ./.github/actions/load-env
# ------------------------------------------------------------
# Detect if this is truly a fork PR with proper null handling
# ------------------------------------------------------------
detect-fork:
name: π Detect Fork PR
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
is-fork: ${{ steps.detection.outputs.is-fork }}
steps:
- name: π Fork detection with null checks
id: detection
env:
PR_HEAD_REPO: ${{ github.event.pull_request.head.repo && github.event.pull_request.head.repo.full_name || '' }}
BASE_REPO: ${{ github.repository }}
run: |
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
echo "π Fork Detection Debug"
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
echo " PR Head Repo: '${PR_HEAD_REPO}'"
echo " Base Repo: '${BASE_REPO}'"
echo " Event: ${{ github.event_name }}"
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
# Check if this is a fork PR with proper null/empty handling
# A fork PR is when:
# 1. PR_HEAD_REPO is not empty (not null/undefined)
# 2. PR_HEAD_REPO != BASE_REPO (different repositories)
if [[ -n "$PR_HEAD_REPO" ]] && [[ "$PR_HEAD_REPO" != "$BASE_REPO" ]]; then
echo "π¨ FORK PR DETECTED"
echo "is-fork=true" >> $GITHUB_OUTPUT
else
echo "β
NOT A FORK PR (Same repository or invalid head repo)"
echo "is-fork=false" >> $GITHUB_OUTPUT
fi
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
# ------------------------------------------------------------
# Fork detector + labeller/commenter/assignee
# ------------------------------------------------------------
handle-fork:
name: π·οΈ Label/Assign/Comment (Fork PR)
needs: [load-env, detect-fork]
runs-on: ubuntu-latest
# Only run for fork PRs (different repository) - using detection output
if: needs.detect-fork.outputs.is-fork == 'true'
permissions:
# We need to WRITE to PR for labels/comments/assignees
pull-requests: write
issues: write
contents: read
steps:
- name: π§ Extract config
id: cfg
env:
ENV_JSON: ${{ needs.load-env.outputs.env-json }}
run: |
# pull minimal config, with sensible fallbacks
DEFAULT_ASSIGNEE=$(echo "$ENV_JSON" | jq -r '.PR_MANAGEMENT_DEFAULT_ASSIGNEE // ""')
SKIP_BOT_USERS=$(echo "$ENV_JSON" | jq -r '.PR_MANAGEMENT_SKIP_BOT_USERS // ""')
FORK_LABEL=$(echo "$ENV_JSON" | jq -r '.PR_MANAGEMENT_FORK_LABEL // "fork-pr"')
TRIAGE_LABEL=$(echo "$ENV_JSON" | jq -r '.PR_MANAGEMENT_TRIAGE_LABEL // "requires-manual-review"')
WELCOME_FORKS=$(echo "$ENV_JSON" | jq -r '.PR_MANAGEMENT_WELCOME_FORKS // "true"')
echo "DEFAULT_ASSIGNEE=$DEFAULT_ASSIGNEE" >> "$GITHUB_ENV"
echo "SKIP_BOT_USERS=$SKIP_BOT_USERS" >> "$GITHUB_ENV"
echo "FORK_LABEL=$FORK_LABEL" >> "$GITHUB_ENV"
echo "TRIAGE_LABEL=$TRIAGE_LABEL" >> "$GITHUB_ENV"
echo "WELCOME_FORKS=$WELCOME_FORKS" >> "$GITHUB_ENV"
- name: π·οΈ Add fork + triage labels
id: labels
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const pr = context.payload.pull_request;
const prNumber = pr.number;
const author = pr.user.login;
// Skip bots if configured
const skip = (process.env.SKIP_BOT_USERS || '')
.split(',').map(s => s.trim()).filter(Boolean);
if (skip.includes(author)) {
core.info(`Skipping labels for bot user: ${author}`);
return;
}
const ensureLabels = async (names) => {
// create missing labels lazily (safe colors)
for (const name of names) {
try {
await github.rest.issues.getLabel({
owner: context.repo.owner, repo: context.repo.repo, name
});
} catch (e) {
if (e.status === 404) {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name,
color: name === process.env.TRIAGE_LABEL ? "d876e3" : "ededed",
});
core.info(`Created missing label: ${name}`);
} else {
throw e;
}
}
}
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
labels: [process.env.FORK_LABEL, process.env.TRIAGE_LABEL]
});
};
await ensureLabels([process.env.FORK_LABEL, process.env.TRIAGE_LABEL]);
- name: π€ Assign default assignee (optional)
id: assign
if: env.DEFAULT_ASSIGNEE != ''
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const pr = context.payload.pull_request;
const author = pr.user.login;
const skip = (process.env.SKIP_BOT_USERS || '')
.split(',').map(s => s.trim()).filter(Boolean);
if (skip.includes(author)) {
core.info(`Skipping assignment for bot user: ${author}`);
return;
}
if ((pr.assignees || []).length === 0) {
await github.rest.issues.addAssignees({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
assignees: [process.env.DEFAULT_ASSIGNEE],
});
core.info(`Assigned to @${process.env.DEFAULT_ASSIGNEE}`);
} else {
core.info('PR already has assignees; skipping.');
}
- name: π¬ Comment notice for fork PR
id: comment
if: env.WELCOME_FORKS == 'true' && github.event.action == 'opened'
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const pr = context.payload.pull_request;
const author = pr.user.login;
const repoName = context.repo.repo;
const repoOwner = context.repo.owner;
const body = `## π Thanks, @${author}!
This pull request comes from a **fork**. For security, our CI runs in a restricted mode.
A maintainer will triage this shortly and run any additional checks as needed.
- π·οΈ Labeled: \`${process.env.FORK_LABEL}\`, \`${process.env.TRIAGE_LABEL}\`
- π We'll review and follow up here if anything else is needed.
Thanks for contributing to **${repoOwner}/${repoName}**! π
<!-- fork-welcome-v1 -->`;
// Check for existing welcome comment to avoid duplicates
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
per_page: 100
});
const welcomeExists = comments.some(comment =>
comment.body.includes('<!-- fork-welcome-v1 -->') &&
comment.user.login === 'github-actions[bot]'
);
if (!welcomeExists) {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
body
});
core.info(`β
Posted welcome comment for fork PR from @${author}`);
} else {
core.info(`βΉοΈ Welcome comment already exists, skipping duplicate`);
}
# ------------------------------------------------------------
# Clean Runner Cache (on PR close)
# ------------------------------------------------------------
clean-cache:
name: π§Ή Clean Runner Cache
needs: [load-env, detect-fork]
runs-on: ubuntu-latest
permissions:
actions: write # Required: Delete GitHub Actions caches for closed PRs
contents: read # Read repository content for cache management
if: github.event.action == 'closed' && needs.detect-fork.outputs.is-fork == 'true'
outputs:
caches-cleaned: ${{ steps.clean.outputs.caches-cleaned }}
steps:
# --------------------------------------------------------------------
# Extract configuration from env-json
# --------------------------------------------------------------------
- name: π§ Extract configuration
id: config
env:
ENV_JSON: ${{ needs.load-env.outputs.env-json }}
run: |
echo "π Extracting PR management configuration from environment..."
# Extract all needed variables
CLEAN_CACHE=$(echo "$ENV_JSON" | jq -r '.PR_MANAGEMENT_CLEAN_CACHE_ON_CLOSE // "true"')
# Set as environment variables for all subsequent steps
echo "CLEAN_CACHE=$CLEAN_CACHE" >> $GITHUB_ENV
# Log configuration
echo "π Configuration loaded:"
echo " π§Ή Clean cache on close: $CLEAN_CACHE"
# --------------------------------------------------------------------
# Clean up caches associated with the PR
# --------------------------------------------------------------------
- name: π§Ή Cleanup caches
id: clean
if: env.CLEAN_CACHE == 'true'
env:
PR_NUMBER: ${{ github.event.pull_request.number }}
PR_HEAD_REF: ${{ github.event.pull_request.head.ref }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
run: |
echo "π§Ή Cleaning up caches for fork PR #$PR_NUMBER..."
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
# Fetch the list of cache keys for this PR
echo "π Fetching cache list for PR #$PR_NUMBER..."
# Get all caches and filter for this PR (checking multiple possible refs)
allCaches=$(gh cache list --limit 100 --json id,key,ref)
# Debug: Show what refs we're looking for
echo "π Looking for caches with refs:"
echo " - refs/pull/$PR_NUMBER/merge"
echo " - refs/pull/$PR_NUMBER/head"
echo " - refs/heads/$PR_HEAD_REF"
# Filter caches that belong to this PR (multiple possible refs)
cacheKeysForPR=$(echo "$allCaches" | jq -r --arg pr "$PR_NUMBER" --arg branch "$PR_HEAD_REF" \
'.[] | select(
.ref == "refs/pull/\($pr)/merge" or
.ref == "refs/pull/\($pr)/head" or
.ref == "refs/heads/\($branch)"
) | .id')
# Count caches - handle empty results properly
if [ -z "$cacheKeysForPR" ]; then
cacheCount=0
else
cacheCount=$(echo "$cacheKeysForPR" | wc -l | tr -d ' ')
fi
if [ "$cacheCount" -eq "0" ]; then
echo "βΉοΈ No caches found for this PR"
echo "caches-cleaned=0" >> $GITHUB_OUTPUT
exit 0
fi
echo "ποΈ Found $cacheCount cache(s) to clean"
# Setting this to not fail the workflow while deleting cache keys
set +e
cleanedCount=0
# Delete each cache
for cacheKey in $cacheKeysForPR; do
if gh cache delete "$cacheKey"; then
echo " β
Deleted cache: $cacheKey"
((cleanedCount++))
else
echo " β οΈ Failed to delete cache: $cacheKey"
fi
done
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
echo "β
Cleaned $cleanedCount out of $cacheCount cache(s)"
echo "caches-cleaned=$cleanedCount" >> $GITHUB_OUTPUT
# ------------------------------------------------------------
# Human-friendly run summary
# ------------------------------------------------------------
summary:
name: π Summary
runs-on: ubuntu-latest
if: always()
needs: [load-env, detect-fork, handle-fork, clean-cache]
steps:
- name: π Write summary
env:
PR_NUMBER: ${{ github.event.pull_request.number }}
PR_TITLE: ${{ github.event.pull_request.title }}
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
PR_ACTION: ${{ github.event.action }}
IS_FORK: ${{ needs.detect-fork.outputs.is-fork }}
PR_HEAD_REPO: ${{ github.event.pull_request.head.repo && github.event.pull_request.head.repo.full_name || '' }}
BASE_REPO: ${{ github.repository }}
run: |
echo "# π§ Fork PR Management Summary" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**PR:** #$PR_NUMBER β $PR_TITLE" >> $GITHUB_STEP_SUMMARY
echo "**Author:** @$PR_AUTHOR" >> $GITHUB_STEP_SUMMARY
echo "**Action:** $PR_ACTION" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
# Show fork detection results
echo "## π Fork Detection" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Property | Value |" >> $GITHUB_STEP_SUMMARY
echo "|----------|-------|" >> $GITHUB_STEP_SUMMARY
echo "| PR Head Repo | \`$PR_HEAD_REPO\` |" >> $GITHUB_STEP_SUMMARY
echo "| Base Repo | \`$BASE_REPO\` |" >> $GITHUB_STEP_SUMMARY
echo "| Is Fork PR? | **$IS_FORK** |" >> $GITHUB_STEP_SUMMARY
if [ "$IS_FORK" = "true" ]; then
echo "| Status | β
Fork PR - Handled with restricted permissions |" >> $GITHUB_STEP_SUMMARY
else
echo "| Status | βΉοΈ **NOT a fork PR** - This workflow should not have processed this PR |" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
# Show cache cleanup results if PR was closed
if [ "$PR_ACTION" = "closed" ]; then
echo "## π§Ή Cleanup Actions" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Action | Result |" >> $GITHUB_STEP_SUMMARY
echo "|--------|--------|" >> $GITHUB_STEP_SUMMARY
# Cache cleanup
if [ "${{ needs.clean-cache.result }}" = "success" ]; then
CACHES="${{ needs.clean-cache.outputs.caches-cleaned }}"
echo "| π§Ή Cache Cleanup | $CACHES cache(s) cleaned |" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
fi
echo "---" >> $GITHUB_STEP_SUMMARY
echo "**Security:** This workflow used **pull_request_target** and did **not** check out or execute the PR's code." >> $GITHUB_STEP_SUMMARY