-
Notifications
You must be signed in to change notification settings - Fork 8
368 lines (326 loc) · 17.3 KB
/
Copy pathcla-check.yaml
File metadata and controls
368 lines (326 loc) · 17.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
# -----------------------------------------------------------------------------
# (C) Crown copyright Met Office. All rights reserved.
# The file LICENCE, distributed with this code, contains details of the terms
# under which the code may be used.
# -----------------------------------------------------------------------------
name: CLA Checker
on:
workflow_call:
inputs:
runner:
description: 'The runner to use for the job'
required: false
type: string
default: 'ubuntu-24.04'
cla-url:
description: 'URL to the CLA document'
required: false
type: string
default: 'https://github.com/MetOffice/Momentum/blob/main/CLA.md'
permissions: {}
jobs:
manage-cla:
name: check-cla
permissions:
contents: read
pull-requests: write # Required to add labels and comments
runs-on: ${{ inputs.runner }}
steps:
- name: Checkout Base Branch
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
token: ${{ secrets.GITHUB_TOKEN }}
ref: ${{ github.ref }}
path: base_branch
- name: Validate Author Username
id: validate_author
env:
PR_AUTHOR_LOGIN: ${{ github.event.pull_request.user.login }}
run: |
AUTHOR="$PR_AUTHOR_LOGIN"
# GitHub usernames: alphanumeric + hyphen, 1-39 chars,
# cannot start/end with hyphen, cannot contain consecutive hyphens
if [[ ! "$AUTHOR" =~ ^[a-zA-Z0-9]([a-zA-Z0-9]|-[a-zA-Z0-9]){0,37}[a-zA-Z0-9]?$ ]]; then
echo "::error::Invalid GitHub username format detected: $AUTHOR"
echo "This may indicate a security issue or data integrity problem."
exit 1
fi
echo "✅ Username validation passed for: $AUTHOR"
echo "validated_author=$AUTHOR" >> "$GITHUB_OUTPUT"
- name: Determine if contributor exists in base
id: check_contributor_base
working-directory: ./base_branch
env:
VALIDATED_AUTHOR: ${{ steps.validate_author.outputs.validated_author }}
run: |
AUTHOR="$VALIDATED_AUTHOR"
if [ -f "CONTRIBUTORS.md" ]; then
if grep -qP "^\s*\|\s*\Q$AUTHOR\E\s*\|" CONTRIBUTORS.md; then
echo "on_base=true" >> "$GITHUB_OUTPUT"
echo "🎉 $AUTHOR has already signed the CLA on base branch."
else
echo "on_base=false" >> "$GITHUB_OUTPUT"
echo "⚠️ $AUTHOR not on base. Proceeding to check PR branch."
fi
else
# If CONTRIBUTORS.md file doesn't exist, we must check PR branch
echo "on_base=undefined" >> "$GITHUB_OUTPUT"
echo "🔴 CONTRIBUTORS.md file does not exist on base. Proceeding to check PR branch."
fi
- name: Checkout PR Branch
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
token: ${{ secrets.GITHUB_TOKEN }}
persist-credentials: false
ref: ${{ github.event.pull_request.head.sha }}
path: pr_branch
allow-unsafe-pr-checkout: true # allow checking out PR head refs from forks
- name: Determine if contributor exists in PR branch
id: check_contributor_pr
working-directory: pr_branch
env:
AUTHOR: ${{ steps.validate_author.outputs.validated_author }}
run: |
if [ -f "CONTRIBUTORS.md" ]; then
# if grep -qE "\|\s*$AUTHOR\s*\|" CONTRIBUTORS.md; then
if grep -qP "^\s*\|\s*\Q$AUTHOR\E\s*\|" CONTRIBUTORS.md; then
echo "on_pr=true" >> "$GITHUB_OUTPUT"
echo "✅ $AUTHOR is in the CONTRIBUTORS.md file on PR branch."
else
echo "on_pr=false" >> "$GITHUB_OUTPUT"
echo "⚠️ $AUTHOR is not in the CONTRIBUTORS.md file on PR branch."
fi
else
echo "on_pr=undefined" >> "$GITHUB_OUTPUT"
echo "🔴 CONTRIBUTORS.md file does not exist on PR branch."
fi
- name: Check Merge Ref Exists
id: check_merge_ref
working-directory: ./base_branch
shell: bash
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPOSITORY: ${{ github.repository }}
PR_NUMBER: ${{ github.event.number }}
run: |
# Use gh api to query pull request metadata directly
# without network git ls-remote authentication
mergeable=$(gh api "repos/$REPOSITORY/pulls/$PR_NUMBER" --jq ".mergeable" 2>/dev/null || echo "undefined")
if [ "$mergeable" != "undefined" ]; then
echo "merge_ref_defined=true" >> "$GITHUB_ENV"
else
echo "merge_ref_defined=false" >> "$GITHUB_ENV"
fi
- name: Checkout Merge Branch
if: env.merge_ref_defined == 'true'
id: checkout_merge
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
continue-on-error: true
with:
token: ${{ secrets.GITHUB_TOKEN }}
persist-credentials: false
ref: "refs/pull/${{ github.event.number }}/merge"
path: merge_branch
allow-unsafe-pr-checkout: true # allow checking out PR head refs from forks
- name: Check if CONTRIBUTORS.md was modified in PR
id: check_contributors_modified
shell: bash
env:
# This token is safely scoped to job-level permissions
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPOSITORY: ${{ github.repository }}
BASE_REF: ${{ github.event.pull_request.base.ref }}
# Use the safe PR number context to completely avoid the private fork 404
PR_NUMBER: ${{ github.event.number }}
run: |
if [ "$merge_ref_defined" = "false" ]; then
echo "::warning::Merge conflicts detected. The CONTRIBUTORS.md modification check was skipped, but the workflow has been allowed to pass. Please resolve conflicts."
echo "modified=false" >> "$GITHUB_OUTPUT"
else
# 1. Fetch raw CONTRIBUTORS.md from the base branch path securely
gh api "repos/$REPOSITORY/contents/CONTRIBUTORS.md?ref=$BASE_REF" \
--jq '.content' | base64 -d > base_raw.txt 2>/dev/null || touch base_raw.txt
# 2. Fetch CONTRIBUTORS.md from the repository using the unified PR head reference.
# This completely bypasses the private fork 404 authentication barrier.
gh api "repos/$REPOSITORY/contents/CONTRIBUTORS.md?ref=refs/pull/$PR_NUMBER/head" \
--jq '.content' | base64 -d > pr_raw.txt 2>/dev/null || touch pr_raw.txt
# 3. Clean and normalise files using pure shell primitives
tr -d '[:space:]' < base_raw.txt > base_clean.txt 2>/dev/null || touch base_clean.txt
tr -d '[:space:]' < pr_raw.txt > pr_clean.txt 2>/dev/null || touch pr_clean.txt
# 4. Perform a direct text comparison on the squashed data
if ! cmp -s base_clean.txt pr_clean.txt; then
echo "modified=true" >> "$GITHUB_OUTPUT"
echo "📝 CONTRIBUTORS.md content was substantively modified (additions or deletions detected)."
else
echo "modified=false" >> "$GITHUB_OUTPUT"
echo "ℹ️ CONTRIBUTORS.md content was NOT substantively modified (whitespace only or unchanged)."
fi
# Clean up the localised workspace
rm -f base_raw.txt pr_raw.txt base_clean.txt pr_clean.txt
fi
# -- Manage PR Labels, Comments, and Final Status (Consolidated)
- name: Manage CLA Status, Labels, and Comments
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
# Using 'always()' here so this step runs regardless of previous
# success/failure to manage labels correctly
if: always()
env:
SIGNED_ON_BASE: ${{ steps.check_contributor_base.outputs.on_base }}
SIGNED_ON_PR: ${{ steps.check_contributor_pr.outputs.on_pr }}
CONTRIBUTORS_MODIFIED: ${{ steps.check_contributors_modified.outputs.modified }}
CLA_URL: ${{ inputs.cla-url }}
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const signedOnBase = process.env.SIGNED_ON_BASE === 'true';
const signedOnPr = process.env.SIGNED_ON_PR === 'true';
const contributorsModified = process.env.CONTRIBUTORS_MODIFIED === 'true';
const issue_number = context.issue.number;
const owner = context.repo.owner;
const repo = context.repo.repo;
const author = context.payload.pull_request.user.login;
// Validate author (GitHub usernames are alphanumeric + hyphens)
if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?$/.test(author)) {
console.error(`::error::Invalid username format: ${author}`);
process.exit(1);
}
const claUrl = process.env.CLA_URL;
// Validate CLA URL
try {
const url = new URL(claUrl);
if (url.protocol !== 'https:') {
throw new Error('CLA URL must use HTTPS protocol');
}
} catch (error) {
console.error(`Invalid CLA URL: ${error.message}`);
throw error;
}
// Check if contributor was on base but modified the file
// This may be valid but will require an admin to ok it
const invalidModify = signedOnBase && contributorsModified;
// Helper function to create or update a label with a specific COLOUR
async function ensureLabel(name, COLOUR, description) {
try {
await github.rest.issues.updateLabel({
owner: owner,
repo: repo,
name: name,
description: description,
color: COLOUR
});
console.log(`Updated label: ${name} with COLOUR ${COLOUR}`);
} catch (error) {
// If update fails (label doesn't exist), create it
try {
await github.rest.issues.createLabel({
owner: owner,
repo: repo,
name: name,
description: description,
color: COLOUR
});
console.log(`Created new label: ${name} with COLOUR ${COLOUR}`);
} catch (createError) {
console.log(`Error with label ${name}:`, createError.message);
}
}
}
// Define desired COLOURs and descriptions for consistency
const COLOUR_SIGNED = '0052cc'; // Blue
const COLOUR_REQUIRED = 'b60205'; // Red
const COLOUR_MODIFIED = 'f56f27'; // Orange
// Helper function to delete old CLA-related comments from this bot
async function deleteOldClaComments() {
try {
const comments = await github.rest.issues.listComments({
owner,
repo,
issue_number
});
// Filter comments from GitHub Actions bot that contain CLA-related content
// GitHub Actions bot username is 'github-actions[bot]'
const botComments = comments.data.filter(comment =>
(comment.user.login === 'github-actions[bot]' || comment.user.type === 'Bot') &&
(comment.body.includes('CLA') ||
comment.body.includes('CONTRIBUTORS') ||
comment.body.includes('Contributor Licence Agreement'))
);
console.log(`Found ${botComments.length} old CLA comment(s) to delete`);
// Delete all old CLA comments
for (const comment of botComments) {
await github.rest.issues.deleteComment({
owner,
repo,
comment_id: comment.id
});
console.log(`Deleted old CLA comment #${comment.id} from ${comment.user.login}`);
}
} catch (error) {
console.log('Error deleting old comments:', error.message);
}
}
console.log(`Base: ${signedOnBase}, PR: ${signedOnPr}, Modified: ${contributorsModified}, Invalid Modify: ${invalidModify}`);
// Handle case where contributor modified the file when already on it
if (invalidModify) {
await ensureLabel('cla-modified', COLOUR_MODIFIED, 'The CLA has been modified as part of this PR - added by GA');
console.log('⚠️ Contributor was in base branch but has modified the file.');
// Ensure labels are correct
await Promise.allSettled([
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-signed' }),
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-required' }),
github.rest.issues.addLabels({ owner, repo, issue_number, labels: ['cla-modified'] })
]);
// Delete old CLA comments before posting new one
await deleteOldClaComments();
// Post warning comment
const commentBody = `⚠️ Hello @${author}!\n\nYour CLA signature was found on the base branch, but you appear to have modified the _CONTRIBUTORS.md_ file in this PR.\n\nPlease do not edit the _CONTRIBUTORS.md_ file. If you have already signed the CLA, revert changes to the file and your signature will be picked up.`;
await github.rest.issues.createComment({ owner, repo, issue_number, body: commentBody });
// Fail the GitHub Action run
console.error("⚠️ Contributor edited the CONTRIBUTORS file when already on base.");
process.exit(1);
}
if (signedOnBase) {
// Different messages based on scenario
if (signedOnBase && !contributorsModified) {
console.log('✅ CLA already signed on base branch, and CONTRIBUTORS.md not modified in PR.');
} else {
console.log('✅ CLA condition met. Removing required label and adding signed label.');
}
// Remove all CLA-related labels when signed on base and file not modified
await Promise.allSettled([
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-required' }),
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-modified' }),
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-signed' })
]);
// Delete old CLA comments since CLA is satisfied
await deleteOldClaComments();
} else if (signedOnPr) {
// New contributor signing CLA for the first time
await ensureLabel('cla-signed', COLOUR_SIGNED, 'The CLA has been signed as part of this PR - added by GA');
console.log('✅ New contributor has signed the CLA in PR branch.');
await Promise.allSettled([
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-required' }),
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-modified' }),
github.rest.issues.addLabels({ owner, repo, issue_number, labels: ['cla-signed'] })
]);
// Delete old CLA comments since CLA is now signed
await deleteOldClaComments();
} else {
await ensureLabel('cla-required', COLOUR_REQUIRED, 'The CLA has not yet been signed by the author of this PR - added by GA');
console.log('❌ CLA condition NOT met. Adding required label and ensuring signed label is absent.');
// Ensure labels are correct
await Promise.allSettled([
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-signed' }),
github.rest.issues.removeLabel({ owner, repo, issue_number, name: 'cla-modified' }),
github.rest.issues.addLabels({ owner, repo, issue_number, labels: ['cla-required'] })
]);
// Delete old CLA comments before posting new one
await deleteOldClaComments();
// Post CLA comment
const commentBody = `Hello @${author}! 👋\n\nThank you for your contribution. Since this is your first time contributing to this repository, we ask that you sign our Contributor Licence Agreement (CLA).\n\n📄 [You can read the CLA here](${claUrl}).\n\nTo agree to the CLA, please add your details (**GitHub username**, Real Name, Affiliation, and Date) to the _CONTRIBUTORS.md_ file (create one, if required) in the development branch for this PR. After signing the CLA, you won't need to do this again for future PRs.`;
await github.rest.issues.createComment({ owner, repo, issue_number, body: commentBody });
// Fail the GitHub Action run
console.error("⚠️ Please add yourself to the CONTRIBUTORS.md file to sign the CLA.");
process.exit(1);
}