Repository navigation
424 lines (392 loc) · 19.2 KB
/
Copy pathpr-metadata-validation.yml
File metadata and controls
424 lines (392 loc) · 19.2 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
# Copyright 2026 Collate
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
name: PR Metadata Validation
# Fails the PR check unless it links a GitHub issue that (a) has a real
# description and (b) is tracked in the "Shipping" project with the Status,
# Source, Priority, Domain and Release fields set.
#
# Linked issues are resolved from two sources:
# * Same-repo: GitHub's native `closingIssuesReferences` (the PR "Development"
# section + same-repo closing keywords). This is authoritative and also
# catches issues linked via the sidebar without a body keyword.
# * Cross-repo (same org only): parsed from the PR body, because GitHub cannot
# represent a cross-repo link in `closingIssuesReferences`. This path is
# restricted to trusted authors and an explicit repo allowlist so the
# privileged PROJECTS_TOKEN is never pointed at attacker-chosen repositories
# under pull_request_target, and the public PR comment never echoes private
# issue content (only numbers and field names).
#
# Projects v2 data is only available via GraphQL and the default GITHUB_TOKEN
# cannot read org-level projects (nor private same-org repos), so a PROJECTS_TOKEN
# secret (a PAT or GitHub App token with `read:project` and read access to the
# allowlisted repos) is required. Only PR / issue / project metadata is read
# through the API — no untrusted checkout — so pull_request_target is safe here.
on:
pull_request_target:
types: [opened, edited, reopened, synchronize, ready_for_review]
workflow_dispatch:
inputs:
pr_number:
description: "PR number to validate"
required: true
type: number
permissions:
contents: read
issues: read
pull-requests: write
concurrency:
# Serialize runs per PR (avoids duplicate sticky comments) but never cancel:
# this check gates merges, so every event must reach a definitive conclusion.
group: pr-metadata-validation-${{ github.event.pull_request.number || github.event.inputs.pr_number || github.run_id }}
cancel-in-progress: false
jobs:
validate-pr-metadata:
name: Validate PR Metadata
runs-on: ubuntu-latest
steps:
- name: Check linked issue and Shipping project fields
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
env:
PROJECTS_TOKEN: ${{ secrets.PROJECTS_TOKEN }}
with:
script: |
const CHECK_MARKER = '<!-- pr-metadata-check -->';
const BYPASS_LABEL = 'skip-pr-checks';
const { owner, repo } = context.repo;
// ---- Policy --------------------------------------------------------
const REQUIRE_LINKED_ISSUE = true;
const MIN_DESCRIPTION_WORDS = 25;
const PROJECT_NAME = 'Shipping';
const REQUIRED_PROJECT_FIELDS = ['Status', 'Source', 'Priority', 'Domain', 'Release'];
const FAIL_WHEN_PROJECT_UNVERIFIABLE = true;
// ---- Cross-repo policy (security-sensitive) ------------------------
// closingIssuesReferences is same-repo only, so a cross-repo link can
// only live in the PR body. Honor it ONLY for trusted authors and ONLY
// for these same-org repos, so untrusted fork PRs can never drive the
// privileged token at arbitrary repositories or probe private issues.
const CLOSING_KEYWORDS = '(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)';
const ALLOWED_CROSS_REPOS = new Set(['openmetadata-collate']);
const TRUSTED_ASSOCIATIONS = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']);
const PR_LINKS_QUERY = `
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) {
closingIssuesReferences(first: 25) {
nodes { number repository { name owner { login } } }
}
}
}
}`;
const ISSUE_PROJECT_QUERY = `
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
issue(number: $number) {
projectItems(first: 25) {
nodes {
project { title }
fieldValues(first: 50) {
nodes {
__typename
... on ProjectV2ItemFieldSingleSelectValue { name field { ... on ProjectV2FieldCommon { name } } }
... on ProjectV2ItemFieldTextValue { text field { ... on ProjectV2FieldCommon { name } } }
... on ProjectV2ItemFieldNumberValue { number field { ... on ProjectV2FieldCommon { name } } }
... on ProjectV2ItemFieldIterationValue { title field { ... on ProjectV2FieldCommon { name } } }
... on ProjectV2ItemFieldDateValue { date field { ... on ProjectV2FieldCommon { name } } }
}
}
}
}
}
}
}`;
function elevatedClient() {
const token = process.env.PROJECTS_TOKEN;
return token ? new github.constructor({ auth: token }) : null;
}
const isSameRepo = (ref) => ref.owner === owner && ref.repo === repo;
const refKey = (ref) => `${ref.owner}/${ref.repo}#${ref.number}`;
const refLabel = (ref) => (isSameRepo(ref) ? `#${ref.number}` : refKey(ref));
const dedupeRefs = (refs) => [...new Map(refs.map((r) => [refKey(r), r])).values()];
async function loadPullRequest() {
if (context.payload.pull_request) {
return context.payload.pull_request;
}
const pull_number = Number(context.payload.inputs.pr_number);
const { data } = await github.rest.pulls.get({ owner, repo, pull_number });
return data;
}
// Same-repo links: authoritative, includes sidebar-linked issues.
async function nativeLinkedRefs(prNumber) {
const data = await github.graphql(PR_LINKS_QUERY, { owner, repo, number: prNumber });
const nodes =
(data.repository &&
data.repository.pullRequest &&
data.repository.pullRequest.closingIssuesReferences.nodes) ||
[];
return nodes.map((node) => ({
owner: node.repository.owner.login,
repo: node.repository.name,
number: node.number,
}));
}
// Trust the author for cross-repo refs if their PR association is already a trusted
// value, or — since the default GITHUB_TOKEN cannot see *private* org membership and
// reports such authors as CONTRIBUTOR — by confirming org membership with the elevated
// token. Fork PRs from non-members still resolve to untrusted.
async function isTrustedAuthor(pr) {
let trusted = TRUSTED_ASSOCIATIONS.has(pr.author_association);
const client = elevatedClient();
if (!trusted && client && pr.user && pr.user.login) {
try {
await client.rest.orgs.checkMembershipForUser({ org: owner, username: pr.user.login });
trusted = true; // 204 => org member (including private membership)
} catch (error) {
trusted = false; // 404 => not a member
}
}
return trusted;
}
// Cross-repo links: body-parsed, allowlisted repos only (caller gates on author trust).
function crossRepoRefsFromBody(text) {
const refs = [];
const add = (refOwner, refRepo, number) => {
if (refOwner === owner && ALLOWED_CROSS_REPOS.has(refRepo)) {
refs.push({ owner: refOwner, repo: refRepo, number: Number(number) });
}
};
const shorthand = new RegExp(
`\\b${CLOSING_KEYWORDS}\\b\\s*:?\\s*([\\w.-]+)/([\\w.-]+)#(\\d+)`,
'gi'
);
const url = new RegExp(
`\\b${CLOSING_KEYWORDS}\\b\\s*:?\\s*https?://github\\.com/([\\w.-]+)/([\\w.-]+)/issues/(\\d+)`,
'gi'
);
let match;
while ((match = shorthand.exec(text)) !== null) {
add(match[1], match[2], match[3]);
}
while ((match = url.exec(text)) !== null) {
add(match[1], match[2], match[3]);
}
return refs;
}
function hasProperDescription(body) {
if (!body) {
return false;
}
const meaningful = body.replace(/<!--[\s\S]*?-->/g, ' ').replace(/\s+/g, ' ').trim();
const wordCount = meaningful ? meaningful.split(' ').filter(Boolean).length : 0;
return wordCount >= MIN_DESCRIPTION_WORDS;
}
async function loadIssue(ref) {
const client = isSameRepo(ref) ? github : elevatedClient();
if (!client) {
return { error: 'missing-token' };
}
try {
const { data } = await client.rest.issues.get({
owner: ref.owner,
repo: ref.repo,
issue_number: ref.number,
});
return { issue: data };
} catch (error) {
return { error: error.status === 404 ? 'not-found' : error.message };
}
}
async function loadIssueProjectItems(ref) {
const client = elevatedClient();
if (!client) {
return { error: 'missing-token' };
}
try {
const data = await client.graphql(ISSUE_PROJECT_QUERY, {
owner: ref.owner,
repo: ref.repo,
number: ref.number,
});
return { items: data.repository.issue.projectItems.nodes };
} catch (error) {
return { error: error.message };
}
}
function resolveFieldValue(fieldValue) {
const candidates = [fieldValue.name, fieldValue.text, fieldValue.title, fieldValue.date];
const text = candidates.find((value) => value != null && String(value).trim() !== '');
if (text != null) {
return text;
}
return fieldValue.number != null ? String(fieldValue.number) : null;
}
function collectSetFields(item) {
const setFields = new Map();
for (const fieldValue of item.fieldValues.nodes) {
const fieldName = fieldValue.field && fieldValue.field.name;
const resolved = resolveFieldValue(fieldValue);
if (fieldName && resolved != null) {
setFields.set(fieldName, resolved);
}
}
return setFields;
}
async function collectProjectProblems(ref) {
const result = await loadIssueProjectItems(ref);
if (result.error) {
if (!FAIL_WHEN_PROJECT_UNVERIFIABLE) {
core.warning(`Skipping project validation for ${refLabel(ref)}: ${result.error}`);
return [];
}
core.warning(`Project verification failed for ${refLabel(ref)}: ${result.error}`);
const detail = result.error === 'missing-token'
? 'the `PROJECTS_TOKEN` secret (a token with `read:project` and access to the linked repo) is not configured'
: 'the project query could not be completed (see the workflow run logs)';
return [`Could not verify the **${PROJECT_NAME}** project on issue ${refLabel(ref)}: ${detail}.`];
}
const projectItem = (result.items || []).find(
(item) => item.project && item.project.title === PROJECT_NAME
);
if (!projectItem) {
return [`Linked issue ${refLabel(ref)} is not added to the **${PROJECT_NAME}** project.`];
}
const setFields = collectSetFields(projectItem);
const problems = [];
for (const field of REQUIRED_PROJECT_FIELDS) {
if (!setFields.has(field)) {
problems.push(`Issue ${refLabel(ref)} is missing **${PROJECT_NAME} → ${field}**.`);
}
}
return problems;
}
async function validateIssue(ref) {
const loaded = await loadIssue(ref);
if (loaded.error === 'not-found') {
return { ref, problems: [`Linked issue ${refLabel(ref)} does not exist or is not accessible.`] };
}
if (loaded.error) {
const detail = loaded.error === 'missing-token'
? 'the `PROJECTS_TOKEN` secret is not configured'
: 'the issue lookup could not be completed (see the workflow run logs)';
core.warning(`Issue lookup failed for ${refLabel(ref)}: ${loaded.error}`);
return { ref, problems: [`Could not read linked issue ${refLabel(ref)}: ${detail}.`] };
}
const issue = loaded.issue;
if (issue.pull_request) {
return { ref, problems: [`${refLabel(ref)} is a pull request, not an issue.`] };
}
const problems = [];
if (!hasProperDescription(issue.body)) {
problems.push(
`Linked issue ${refLabel(ref)} needs a real description ` +
`(at least ${MIN_DESCRIPTION_WORDS} words covering the problem, repro, and expected behavior).`
);
}
problems.push(...(await collectProjectProblems(ref)));
return { ref, problems };
}
async function collectIssueProblems(pr) {
const native = await nativeLinkedRefs(pr.number);
const cross = (await isTrustedAuthor(pr))
? crossRepoRefsFromBody(`${pr.title || ''}\n${pr.body || ''}`)
: [];
const refs = dedupeRefs([...native, ...cross]);
if (refs.length === 0) {
return [
'No GitHub issue is linked. Link an issue in the **Development** section of the PR ' +
'(or add `Fixes #12345` to the description). For a same-org cross-repo issue, add ' +
'`Fixes open-metadata/<repo>#123` to the description.',
];
}
const validations = await Promise.all(refs.map(validateIssue));
const validIssues = validations.filter((validation) => validation.problems.length === 0);
const problems = [];
if (validIssues.length === 0) {
for (const validation of validations) {
problems.push(...validation.problems);
}
}
return problems;
}
function buildFailureComment(problems) {
const lines = [
CHECK_MARKER,
'### ❌ PR checklist incomplete',
'',
'This PR cannot be merged until the following are addressed on its linked issue:',
'',
];
for (const problem of problems) {
lines.push(`- ${problem}`);
}
lines.push('');
lines.push(
`The fields live on the **linked issue** in the **${PROJECT_NAME}** project ` +
'(open the issue → right sidebar → **Projects**). After you set them, ' +
'**re-run this check** (or push a commit) — issue/project changes do not re-trigger it automatically.'
);
lines.push('');
lines.push(`_Maintainers can bypass this check by adding the \`${BYPASS_LABEL}\` label._`);
return lines.join('\n');
}
function buildSuccessComment() {
return [
CHECK_MARKER,
'### ✅ PR checks passed',
'',
`The linked issue has a description and all required **${PROJECT_NAME}** project fields set. Thanks!`,
].join('\n');
}
async function syncStickyComment(prNumber, body, hadFailure) {
const comments = await github.paginate(github.rest.issues.listComments, {
owner,
repo,
issue_number: prNumber,
per_page: 100,
});
const existing = comments.find((comment) => comment.body && comment.body.includes(CHECK_MARKER));
if (hadFailure) {
if (existing) {
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
} else {
await github.rest.issues.createComment({ owner, repo, issue_number: prNumber, body });
}
} else if (existing) {
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
}
}
const pr = await loadPullRequest();
if (pr.draft) {
core.info('Draft PR — skipping metadata validation.');
return;
}
if (pr.user && pr.user.type === 'Bot') {
core.info(`PR opened by bot ${pr.user.login} — skipping metadata validation.`);
return;
}
const labels = (pr.labels || []).map((label) => label.name);
if (labels.includes(BYPASS_LABEL)) {
core.info(`'${BYPASS_LABEL}' label present — skipping metadata validation.`);
return;
}
const problems = [];
if (REQUIRE_LINKED_ISSUE) {
problems.push(...(await collectIssueProblems(pr)));
}
const hadFailure = problems.length > 0;
const body = hadFailure ? buildFailureComment(problems) : buildSuccessComment();
await syncStickyComment(pr.number, body, hadFailure);
if (hadFailure) {
core.setFailed(
`PR metadata checklist incomplete: ${problems.length} item(s) need attention. See the PR comment.`
);
} else {
core.info('All PR metadata checks passed.');
}