@jakobm/peacekeeper 0.26.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +294 -98
- package/dist/cmdabra.yaml +174 -116
- package/dist/package.json +5 -5
- package/dist/src/modules/cli/legacy-commands.js +37 -0
- package/dist/src/modules/cli/service.js +48 -40
- package/dist/src/modules/configuration/facade.js +1 -0
- package/dist/src/modules/configuration/project-config-defaults.json +2 -1
- package/dist/src/modules/configuration/project-config.js +20 -8
- package/dist/src/modules/configuration/update-config.js +16 -2
- package/dist/src/modules/dependencies.yaml +1 -1
- package/dist/src/modules/lifecycle/checkpoint-instructions.js +1 -1
- package/dist/src/modules/lifecycle/cleanup-ended-session.js +1 -1
- package/dist/src/modules/maintenance/cleanup-merged-branches.js +4 -4
- package/dist/src/modules/maintenance/initialize-codex-worktree.js +1 -1
- package/dist/src/modules/maintenance/remove-empty-directories.js +1 -1
- package/dist/src/modules/projects/check-project-requirements.txt +32 -31
- package/dist/src/modules/projects/check-project.js +16 -16
- package/dist/src/modules/projects/codex-setup-prefix.sh +2 -2
- package/dist/src/modules/projects/create-project-core.js +13 -28
- package/dist/src/modules/projects/generate-github-setup.js +16 -55
- package/dist/src/modules/projects/github-setup-prefix.sh +29 -2
- package/dist/src/modules/projects/github-setup-repository-template.sh +1 -40
- package/dist/src/modules/projects/github-setup-suffix-template.sh +7 -5
- package/dist/src/modules/projects/install-hooks.js +6 -5
- package/dist/src/modules/releases/configure-github.js +57 -0
- package/dist/src/modules/releases/facade.js +3 -2
- package/dist/src/modules/releases/github-configuration.js +166 -0
- package/dist/src/modules/releases/github-policy.js +45 -11
- package/dist/src/modules/releases/github-remote.js +230 -0
- package/dist/src/modules/testing/check-test-receipt.js +17 -22
- package/dist/src/modules/testing/receipt-state.js +27 -1
- package/dist/src/modules/testing/record-test-receipt.js +14 -13
- package/dist/src/modules/testing/run-tests.js +23 -14
- package/dist/src/modules/testing/types.js +1 -0
- package/package.json +5 -5
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
export default ({ githubConfiguration, external: { fs, packageVersion, runtime } }) => {
|
|
2
|
+
function run(options) {
|
|
3
|
+
let result;
|
|
4
|
+
try {
|
|
5
|
+
if (options.execute) {
|
|
6
|
+
if (!options.planFile || options.policyPr || options.sourceRef) {
|
|
7
|
+
throw new Error('--execute requires --plan-file and cannot override the policy source.');
|
|
8
|
+
}
|
|
9
|
+
if (fs.statSync(options.planFile).size > 16 * 1024 * 1024)
|
|
10
|
+
throw new Error('Plan file exceeds 16 MiB.');
|
|
11
|
+
const saved = JSON.parse(fs.readFileSync(options.planFile, 'utf8'));
|
|
12
|
+
if (options.repository && options.repository.toLowerCase() !== saved?.repository?.slug?.toLowerCase()) {
|
|
13
|
+
throw new Error('--repository does not match the saved plan target.');
|
|
14
|
+
}
|
|
15
|
+
result = githubConfiguration.execute(saved);
|
|
16
|
+
}
|
|
17
|
+
else {
|
|
18
|
+
if (!options.repository)
|
|
19
|
+
throw new Error('--repository is required when planning.');
|
|
20
|
+
const plan = githubConfiguration.plan(options);
|
|
21
|
+
if (options.planFile)
|
|
22
|
+
fs.writeFileSync(options.planFile, `${JSON.stringify(plan, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
|
|
23
|
+
result = { status: plan.blockers.length ? 'blocked' : 'planned', plan };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
28
|
+
result = { status: options.execute ? 'failed' : 'blocked', error: message, blockers: [message],
|
|
29
|
+
...(options.execute ? { completed: [] } : {}) };
|
|
30
|
+
}
|
|
31
|
+
result = { resultFormatVersion: 1, peacekeeperVersion: packageVersion, ...result };
|
|
32
|
+
if (options.json)
|
|
33
|
+
runtime.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
34
|
+
else {
|
|
35
|
+
runtime.stdout.write(`GitHub configuration: ${result.status}\n`);
|
|
36
|
+
if (result.plan) {
|
|
37
|
+
runtime.stdout.write(`${result.plan.repository.slug} at ${result.plan.source.sha}\n`);
|
|
38
|
+
runtime.stdout.write(`${result.plan.changes.length} change(s); configuration source: ${result.plan.configSource}.\n`);
|
|
39
|
+
runtime.stdout.write('Scope: all repository-owned branch rulesets and all classic protections, including other branches.\n');
|
|
40
|
+
runtime.stdout.write(`${JSON.stringify(result.plan.changes, null, 2)}\n`);
|
|
41
|
+
for (const blocker of result.plan.blockers)
|
|
42
|
+
runtime.stdout.write(`Blocker: ${blocker}\n`);
|
|
43
|
+
}
|
|
44
|
+
if (result.bootstrap || result.plan?.bootstrap)
|
|
45
|
+
runtime.stdout.write('Bootstrap: CODEOWNERS from the policy PR takes effect after merging into the default branch.\n');
|
|
46
|
+
for (const blocker of result.blockers || [])
|
|
47
|
+
runtime.stdout.write(`Blocker: ${blocker}\n`);
|
|
48
|
+
if (result.error)
|
|
49
|
+
runtime.stderr.write(`${result.error}\n`);
|
|
50
|
+
if (result.completed)
|
|
51
|
+
runtime.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
52
|
+
}
|
|
53
|
+
if (!['planned', 'succeeded'].includes(result.status))
|
|
54
|
+
runtime.exitCode = 1;
|
|
55
|
+
}
|
|
56
|
+
return { run };
|
|
57
|
+
};
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
export const porticoFacade = ({ assessRelease, githubPolicy, release, releaseCore, verifyRelease, verifyReleaseProtection, verifyReleaseVersion }) => ({
|
|
1
|
+
export const porticoFacade = ({ assessRelease, configureGithub, githubConfiguration, githubPolicy, release, releaseCore, verifyRelease, verifyReleaseProtection, verifyReleaseVersion }) => ({
|
|
2
2
|
assessRelease: assessRelease.run,
|
|
3
|
+
configureGithub: configureGithub.run,
|
|
4
|
+
planGithub: githubConfiguration.plan,
|
|
3
5
|
createGithubPolicy: githubPolicy.createGithubPolicy,
|
|
4
6
|
ensureLockfilesMatch: releaseCore.ensureLockfilesMatch,
|
|
5
|
-
githubSetupPlan: githubPolicy.setupPlan,
|
|
6
7
|
inspectWorkflow: releaseCore.inspectWorkflow,
|
|
7
8
|
release: release.run,
|
|
8
9
|
verifyRelease: verifyRelease.run,
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
export default ({ githubPolicy, githubRemote, external: { packageVersion } }) => {
|
|
2
|
+
const { canonical, createGithubPolicy, exactPolicy, same } = githubPolicy;
|
|
3
|
+
const { loadSource, inventory, request, graphql } = githubRemote;
|
|
4
|
+
function inheritedBlockers(observed, desired) {
|
|
5
|
+
// A matching inherited rule is compatible when it contributes an already
|
|
6
|
+
// canonical requirement. Otherwise only its organization can resolve it.
|
|
7
|
+
const canonicalRules = desired.rulesets.flatMap(ruleset => ruleset.rules);
|
|
8
|
+
return observed.inheritedRulesets.filter(item => item.policy.enforcement === 'active'
|
|
9
|
+
&& item.policy.rules.some(rule => !canonicalRules.some(expected => same(rule, expected))))
|
|
10
|
+
.map(item => `Inherited branch ruleset ${item.id} (${item.source}: ${item.policy.name}) prevents proving the exact policy; resolve it at its source.`);
|
|
11
|
+
}
|
|
12
|
+
function changesFor(observed, desired) {
|
|
13
|
+
const changes = [];
|
|
14
|
+
if (!same(observed.repository, desired.repository))
|
|
15
|
+
changes.push({ kind: 'repository', action: 'update',
|
|
16
|
+
before: observed.repository, after: desired.repository });
|
|
17
|
+
const retained = new Set();
|
|
18
|
+
for (const wanted of desired.rulesets) {
|
|
19
|
+
const candidates = observed.rulesets.filter(item => item.policy.name === wanted.name)
|
|
20
|
+
.sort((a, b) => Number(same(b.policy, wanted)) - Number(same(a.policy, wanted)) || a.id - b.id);
|
|
21
|
+
const existing = candidates[0];
|
|
22
|
+
if (!existing)
|
|
23
|
+
changes.push({ kind: 'ruleset', action: 'create', after: wanted });
|
|
24
|
+
else {
|
|
25
|
+
retained.add(existing.id);
|
|
26
|
+
if (!same(existing.policy, wanted))
|
|
27
|
+
changes.push({ kind: 'ruleset', action: 'update',
|
|
28
|
+
id: existing.id, before: existing.policy, after: wanted });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
for (const item of [...observed.rulesets].sort((a, b) => a.id - b.id)) {
|
|
32
|
+
if (!retained.has(item.id))
|
|
33
|
+
changes.push({ kind: 'ruleset', action: 'delete', id: item.id, before: item.policy });
|
|
34
|
+
}
|
|
35
|
+
for (const item of observed.classicProtections)
|
|
36
|
+
changes.push({ kind: 'classic-protection', action: 'delete', id: item.id, before: item });
|
|
37
|
+
return changes;
|
|
38
|
+
}
|
|
39
|
+
function plan(options) {
|
|
40
|
+
const { metadata, source, config, configSource, requiredApprover, blockers } = loadSource(options);
|
|
41
|
+
const policy = createGithubPolicy({ branch: source.defaultBranch, checks: config.git.releaseRequiredChecks, requiredApprover });
|
|
42
|
+
const desired = exactPolicy(policy, metadata.owner.id);
|
|
43
|
+
const observed = inventory(metadata, desired.repository);
|
|
44
|
+
return {
|
|
45
|
+
formatVersion: 1, peacekeeperVersion: packageVersion,
|
|
46
|
+
repository: { id: metadata.id, slug: metadata.full_name }, source,
|
|
47
|
+
bootstrap: source.kind === 'pull-request', configSource, observed, desired,
|
|
48
|
+
changes: changesFor(observed, desired), blockers: [...blockers, ...inheritedBlockers(observed, desired)].sort(),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function refreshed(saved) {
|
|
52
|
+
return plan({ repository: saved.repository.slug,
|
|
53
|
+
...(saved.source.kind === 'pull-request' ? { policyPr: String(saved.source.policyPr) } : {}),
|
|
54
|
+
sourceRef: saved.source.sha });
|
|
55
|
+
}
|
|
56
|
+
function validate(saved) {
|
|
57
|
+
if (!saved || saved.formatVersion !== 1 || saved.peacekeeperVersion !== packageVersion) {
|
|
58
|
+
throw new Error('Plan format or Peacekeeper version does not match; create a new plan with this version.');
|
|
59
|
+
}
|
|
60
|
+
if (!Number.isSafeInteger(saved.repository?.id) || typeof saved.repository?.slug !== 'string'
|
|
61
|
+
|| !['default-branch', 'pull-request'].includes(saved.source?.kind)
|
|
62
|
+
|| typeof saved.source.sha !== 'string' || !/^[a-f0-9]{40}$/u.test(saved.source.sha)
|
|
63
|
+
|| (saved.source.kind === 'pull-request' && (!Number.isSafeInteger(saved.source.policyPr) || saved.source.policyPr <= 0))) {
|
|
64
|
+
throw new Error('Invalid saved plan identity or policy source.');
|
|
65
|
+
}
|
|
66
|
+
const current = refreshed(saved);
|
|
67
|
+
if (!same(saved, current))
|
|
68
|
+
throw new Error('Plan does not match the canonical policy and current GitHub preconditions; create a new plan.');
|
|
69
|
+
return current;
|
|
70
|
+
}
|
|
71
|
+
function readback(plan) {
|
|
72
|
+
// Inspect remaining configuration even when the policy ref moved or its PR
|
|
73
|
+
// closed. Such a source must not prevent reporting a partially applied state.
|
|
74
|
+
try {
|
|
75
|
+
const metadata = request(`repos/${plan.repository.slug}`);
|
|
76
|
+
if (metadata?.id !== plan.repository.id || metadata.full_name !== plan.repository.slug) {
|
|
77
|
+
throw new Error('Repository identity changed during read-back.');
|
|
78
|
+
}
|
|
79
|
+
return { observed: inventory(metadata, plan.desired.repository) };
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
return { readbackError: message(error) };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function assertCurrent(plan, expected, deleting) {
|
|
86
|
+
const current = refreshed(plan);
|
|
87
|
+
const { changes: _changes, observed: _observed, ...identity } = current;
|
|
88
|
+
const { changes: _originalChanges, observed: _originalObserved, ...originalIdentity } = plan;
|
|
89
|
+
if (!same(identity, originalIdentity) || !same(current.observed, expected)) {
|
|
90
|
+
throw new Error('GitHub preconditions changed during execution; stop and create a new plan.');
|
|
91
|
+
}
|
|
92
|
+
if (deleting && plan.desired.rulesets.some(wanted => !current.observed.rulesets.some(item => same(item.policy, wanted)))) {
|
|
93
|
+
throw new Error('Canonical branch protections must be established and read back before any deletion.');
|
|
94
|
+
}
|
|
95
|
+
return current;
|
|
96
|
+
}
|
|
97
|
+
function apply(slug, change, expected) {
|
|
98
|
+
const base = `repos/${slug}`;
|
|
99
|
+
if (change.kind === 'repository') {
|
|
100
|
+
request(base, 'PATCH', change.after);
|
|
101
|
+
expected.repository = change.after;
|
|
102
|
+
}
|
|
103
|
+
else if (change.kind === 'classic-protection') {
|
|
104
|
+
const result = graphql(`mutation PeacekeeperDeleteProtection($id:ID!) {
|
|
105
|
+
deleteBranchProtectionRule(input:{branchProtectionRuleId:$id}) { clientMutationId }
|
|
106
|
+
}`, { id: change.id });
|
|
107
|
+
if (!result.deleteBranchProtectionRule)
|
|
108
|
+
throw new Error('GitHub did not confirm classic protection deletion.');
|
|
109
|
+
expected.classicProtections = expected.classicProtections.filter(item => item.id !== change.id);
|
|
110
|
+
}
|
|
111
|
+
else if (change.action === 'delete') {
|
|
112
|
+
request(`${base}/rulesets/${change.id}`, 'DELETE');
|
|
113
|
+
expected.rulesets = expected.rulesets.filter(item => item.id !== change.id);
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
const endpoint = change.action === 'create' ? `${base}/rulesets` : `${base}/rulesets/${change.id}`;
|
|
117
|
+
const result = request(endpoint, change.action === 'create' ? 'POST' : 'PUT', change.after);
|
|
118
|
+
const id = change.action === 'create' ? result?.id : change.id;
|
|
119
|
+
if (!Number.isSafeInteger(id) || (change.action === 'create' && expected.rulesets.some(item => item.id === id))) {
|
|
120
|
+
throw new Error('GitHub did not return a valid new ruleset identity.');
|
|
121
|
+
}
|
|
122
|
+
expected.rulesets = expected.rulesets.filter(item => item.id !== id);
|
|
123
|
+
expected.rulesets.push({ id: id, policy: change.after });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function execute(saved) {
|
|
127
|
+
let current;
|
|
128
|
+
try {
|
|
129
|
+
current = validate(saved);
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
return { status: 'stale', error: message(error), completed: [] };
|
|
133
|
+
}
|
|
134
|
+
if (current.blockers.length)
|
|
135
|
+
return { status: 'blocked', blockers: current.blockers,
|
|
136
|
+
completed: [], bootstrap: current.bootstrap };
|
|
137
|
+
const expected = canonical(current.observed);
|
|
138
|
+
const completed = [];
|
|
139
|
+
let attempted;
|
|
140
|
+
try {
|
|
141
|
+
for (const change of current.changes) {
|
|
142
|
+
assertCurrent(current, expected, change.action === 'delete');
|
|
143
|
+
attempted = change;
|
|
144
|
+
apply(current.repository.slug, change, expected);
|
|
145
|
+
completed.push(change);
|
|
146
|
+
attempted = undefined;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
return { status: completed.length || attempted ? 'partial' : 'stale', error: message(error),
|
|
151
|
+
completed, ...(attempted ? { attempted } : {}), ...readback(current), bootstrap: current.bootstrap };
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
const final = assertCurrent(current, expected, false);
|
|
155
|
+
if (final.blockers.length || final.changes.length)
|
|
156
|
+
throw new Error('Read-back state does not match the exact canonical policy.');
|
|
157
|
+
return { status: 'succeeded', completed, observed: final.observed, bootstrap: current.bootstrap };
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
return { status: 'verification-failed', completed, error: message(error),
|
|
161
|
+
...readback(current), bootstrap: current.bootstrap };
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
function message(error) { return error instanceof Error ? error.message : String(error); }
|
|
165
|
+
return { plan, execute };
|
|
166
|
+
};
|
|
@@ -63,18 +63,52 @@ export default ({ external: { fs, modulesRoot, path, structuredClone } }) => {
|
|
|
63
63
|
repository: base.repository,
|
|
64
64
|
baseRuleset: base.ruleset,
|
|
65
65
|
approvalRuleset: ownerApproval.ruleset,
|
|
66
|
+
absence: { otherRepositoryBranchRulesets: true, classicBranchProtections: true },
|
|
66
67
|
};
|
|
67
68
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
.
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
.
|
|
77
|
-
|
|
69
|
+
// All policy arrays represent unordered sets (rules, actors, refs and checks).
|
|
70
|
+
// Preserve unknown policy fields, but ignore GitHub's response metadata.
|
|
71
|
+
function canonical(value) {
|
|
72
|
+
if (Array.isArray(value))
|
|
73
|
+
return value.map(canonical)
|
|
74
|
+
.sort((a, b) => JSON.stringify(a) < JSON.stringify(b) ? -1 : JSON.stringify(a) > JSON.stringify(b) ? 1 : 0);
|
|
75
|
+
if (value && typeof value === 'object')
|
|
76
|
+
return Object.fromEntries(Object.keys(value).sort()
|
|
77
|
+
.map(key => [key, canonical(value[key])]));
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
80
|
+
function normalizeRuleset(ruleset) {
|
|
81
|
+
const rules = ruleset.rules.map(rule => {
|
|
82
|
+
const parameters = structuredClone(rule.parameters || {});
|
|
83
|
+
if (rule.type === 'pull_request') {
|
|
84
|
+
// GitHub defaults this newer parameter to true when it is omitted.
|
|
85
|
+
parameters.require_extra_approval_for_unattributed_changes ??= true;
|
|
86
|
+
// GitHub adds this empty field even when it was not supplied.
|
|
87
|
+
if (Array.isArray(parameters.required_reviewers) && parameters.required_reviewers.length === 0)
|
|
88
|
+
delete parameters.required_reviewers;
|
|
89
|
+
}
|
|
90
|
+
if (rule.type === 'required_status_checks' && Array.isArray(parameters.required_status_checks)) {
|
|
91
|
+
parameters.required_status_checks = parameters.required_status_checks.map(check => {
|
|
92
|
+
const result = { ...check };
|
|
93
|
+
if (result.integration_id === null)
|
|
94
|
+
delete result.integration_id;
|
|
95
|
+
return result;
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
const { parameters: _parameters, ...fields } = rule;
|
|
99
|
+
return { ...fields, ...(Object.keys(parameters).length ? { parameters } : {}) };
|
|
100
|
+
});
|
|
101
|
+
return canonical({ name: ruleset.name, target: ruleset.target, enforcement: ruleset.enforcement,
|
|
102
|
+
bypass_actors: ruleset.bypass_actors, conditions: ruleset.conditions, rules });
|
|
103
|
+
}
|
|
104
|
+
function exactPolicy(policy, ownerId) {
|
|
105
|
+
const approval = structuredClone(policy.approvalRuleset);
|
|
106
|
+
approval.bypass_actors[0].actor_id = ownerId;
|
|
107
|
+
return canonical({ repository: policy.repository,
|
|
108
|
+
rulesets: [policy.baseRuleset, approval].map(normalizeRuleset), absence: policy.absence });
|
|
109
|
+
}
|
|
110
|
+
function same(actual, expected) {
|
|
111
|
+
return JSON.stringify(canonical(actual)) === JSON.stringify(canonical(expected));
|
|
78
112
|
}
|
|
79
113
|
function sameMembers(actual, expected) {
|
|
80
114
|
return actual.length === expected.length
|
|
@@ -122,6 +156,6 @@ export default ({ external: { fs, modulesRoot, path, structuredClone } }) => {
|
|
|
122
156
|
return matchesShape(withoutBypass(expected), actual);
|
|
123
157
|
}
|
|
124
158
|
const api = { approvalParameters, createGithubPolicy, managedRulesetMatches,
|
|
125
|
-
requiredCheckContexts, sameMembers,
|
|
159
|
+
requiredCheckContexts, sameMembers, canonical, normalizeRuleset, exactPolicy, same };
|
|
126
160
|
return api;
|
|
127
161
|
};
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
export default ({ configuration, githubPolicy, external: { buffer: Buffer, projectConfigDefaults, spawnSync, structuredClone, YAML, } }) => {
|
|
2
|
+
const { canonical, normalizeRuleset } = githubPolicy;
|
|
3
|
+
const shaPattern = /^[a-f0-9]{40}$/u;
|
|
4
|
+
function request(endpoint, method = 'GET', body) {
|
|
5
|
+
const args = ['api', '--hostname', 'github.com', '--method', method, endpoint];
|
|
6
|
+
if (body !== undefined)
|
|
7
|
+
args.push('--input', '-');
|
|
8
|
+
const result = spawnSync('gh', args, { encoding: 'utf8',
|
|
9
|
+
...(body === undefined ? {} : { input: JSON.stringify(body) }) });
|
|
10
|
+
if (result.error || result.status !== 0)
|
|
11
|
+
throw new Error(`GitHub ${method} ${endpoint}: ${result.error?.message || result.stderr?.trim() || `exit ${result.status}`}`);
|
|
12
|
+
if (method === 'DELETE' && !result.stdout?.trim())
|
|
13
|
+
return undefined;
|
|
14
|
+
let response;
|
|
15
|
+
try {
|
|
16
|
+
response = JSON.parse(result.stdout);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
throw new Error(`GitHub returned invalid JSON for ${endpoint}.`);
|
|
20
|
+
}
|
|
21
|
+
if (response?.errors?.length)
|
|
22
|
+
throw new Error(`GitHub ${endpoint}: ${response.errors.map(error => error.message).join('; ')}`);
|
|
23
|
+
return response;
|
|
24
|
+
}
|
|
25
|
+
function graphql(query, variables) {
|
|
26
|
+
const result = request('graphql', 'POST', { query, variables });
|
|
27
|
+
if (!result?.data)
|
|
28
|
+
throw new Error('GitHub returned incomplete GraphQL data.');
|
|
29
|
+
return result.data;
|
|
30
|
+
}
|
|
31
|
+
function repositorySlug(value) {
|
|
32
|
+
if (typeof value !== 'string' || !/^[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+$/u.test(value)
|
|
33
|
+
|| ['.', '..'].includes(value.split('/')[1]))
|
|
34
|
+
throw new Error('--repository must be OWNER/REPO on github.com.');
|
|
35
|
+
return value;
|
|
36
|
+
}
|
|
37
|
+
function commitSha(value) {
|
|
38
|
+
if (typeof value !== 'string' || !shaPattern.test(value))
|
|
39
|
+
throw new Error('GitHub did not return an exact commit SHA.');
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
function readTree(slug, sha) {
|
|
43
|
+
const response = request(`repos/${slug}/git/trees/${sha}`);
|
|
44
|
+
if (!Array.isArray(response?.tree) || response.truncated !== false)
|
|
45
|
+
throw new Error('Cannot completely inspect the policy source tree.');
|
|
46
|
+
return response.tree;
|
|
47
|
+
}
|
|
48
|
+
function readBlob(slug, sha, name, tree, basename = name) {
|
|
49
|
+
const entry = tree.find(item => item.path === basename);
|
|
50
|
+
if (!entry)
|
|
51
|
+
return undefined;
|
|
52
|
+
if (entry.type !== 'blob' || !['100644', '100755'].includes(entry.mode))
|
|
53
|
+
throw new Error(`${name} must be a regular file.`);
|
|
54
|
+
const file = request(`repos/${slug}/contents/${name}?ref=${sha}`);
|
|
55
|
+
if (file?.type !== 'file' || file.encoding !== 'base64' || typeof file.content !== 'string' || file.sha !== entry.sha) {
|
|
56
|
+
throw new Error(`GitHub returned invalid policy file contents for ${name}.`);
|
|
57
|
+
}
|
|
58
|
+
return Buffer.from(file.content, 'base64').toString('utf8');
|
|
59
|
+
}
|
|
60
|
+
function loadSource({ repository, policyPr, sourceRef }) {
|
|
61
|
+
const slug = repositorySlug(repository);
|
|
62
|
+
if (sourceRef !== undefined && !shaPattern.test(sourceRef))
|
|
63
|
+
throw new Error('--source-ref must be a full lowercase commit SHA.');
|
|
64
|
+
const metadata = request(`repos/${slug}`);
|
|
65
|
+
if (!Number.isSafeInteger(metadata?.id) || typeof metadata.full_name !== 'string'
|
|
66
|
+
|| metadata.full_name.toLowerCase() !== slug.toLowerCase()
|
|
67
|
+
|| typeof metadata.default_branch !== 'string' || !metadata.default_branch
|
|
68
|
+
|| !Number.isSafeInteger(metadata.owner?.id) || typeof metadata.owner.login !== 'string') {
|
|
69
|
+
throw new Error('GitHub returned incomplete repository metadata.');
|
|
70
|
+
}
|
|
71
|
+
const base = `repos/${metadata.full_name}`;
|
|
72
|
+
const defaultSha = commitSha(request(`${base}/commits/${encodeURIComponent(metadata.default_branch)}`).sha);
|
|
73
|
+
let sha = defaultSha;
|
|
74
|
+
let number;
|
|
75
|
+
if (policyPr !== undefined) {
|
|
76
|
+
if (!/^[1-9][0-9]*$/u.test(String(policyPr)) || !Number.isSafeInteger(Number(policyPr)))
|
|
77
|
+
throw new Error('--policy-pr must be a positive PR number.');
|
|
78
|
+
number = Number(policyPr);
|
|
79
|
+
const pr = request(`${base}/pulls/${number}`);
|
|
80
|
+
if (pr?.number !== number || pr.state !== 'open' || pr.base?.repo?.id !== metadata.id
|
|
81
|
+
|| pr.head?.repo?.id !== metadata.id || pr.base?.ref !== metadata.default_branch) {
|
|
82
|
+
throw new Error('Policy PR must be open, originate in this repository and target its current default branch.');
|
|
83
|
+
}
|
|
84
|
+
sha = commitSha(pr.head.sha);
|
|
85
|
+
}
|
|
86
|
+
if (sourceRef !== undefined && sourceRef !== sha)
|
|
87
|
+
throw new Error('Policy source moved from --source-ref; create a new plan.');
|
|
88
|
+
const root = readTree(metadata.full_name, sha);
|
|
89
|
+
const contents = readBlob(metadata.full_name, sha, 'peacekeeper.config.yaml', root);
|
|
90
|
+
let config;
|
|
91
|
+
if (contents === undefined) {
|
|
92
|
+
if (root.some(item => item.path === 'peacekeeper.config.json'))
|
|
93
|
+
throw new Error('Rename legacy peacekeeper.config.json to peacekeeper.config.yaml and convert it to YAML.');
|
|
94
|
+
config = structuredClone(projectConfigDefaults);
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
try {
|
|
98
|
+
config = YAML.parse(contents);
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
throw new Error(`peacekeeper.config.yaml: ${error instanceof Error ? error.message : String(error)}`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
configuration.validateConfig(config, `${metadata.full_name}/peacekeeper.config.yaml`);
|
|
105
|
+
const requiredApprover = config.git.requiredApprover || metadata.owner.login;
|
|
106
|
+
const blockers = [];
|
|
107
|
+
if (metadata.owner.type !== 'User' || requiredApprover.toLowerCase() !== metadata.owner.login.toLowerCase()) {
|
|
108
|
+
blockers.push('git.requiredApprover must be the personal GitHub repository owner.');
|
|
109
|
+
}
|
|
110
|
+
const github = root.find(item => item.path === '.github');
|
|
111
|
+
if (github && github.type !== 'tree')
|
|
112
|
+
throw new Error('.github must be a directory in the policy source.');
|
|
113
|
+
const tree = github ? readTree(metadata.full_name, github.sha) : [];
|
|
114
|
+
const codeowners = readBlob(metadata.full_name, sha, '.github/CODEOWNERS', tree, 'CODEOWNERS');
|
|
115
|
+
const codeownersError = configuration.codeownersError(codeowners, requiredApprover);
|
|
116
|
+
if (codeownersError)
|
|
117
|
+
blockers.push(codeownersError);
|
|
118
|
+
const source = { kind: number === undefined ? 'default-branch' : 'pull-request',
|
|
119
|
+
sha, defaultBranch: metadata.default_branch, defaultSha, ...(number === undefined ? {} : { policyPr: number }) };
|
|
120
|
+
return { metadata, config, requiredApprover, blockers, source,
|
|
121
|
+
configSource: contents === undefined ? 'defaults' : 'remote' };
|
|
122
|
+
}
|
|
123
|
+
function restPages(endpoint) {
|
|
124
|
+
const all = [];
|
|
125
|
+
for (let page = 1;; page += 1) {
|
|
126
|
+
const batch = request(`${endpoint}${endpoint.includes('?') ? '&' : '?'}per_page=100&page=${page}`);
|
|
127
|
+
if (!Array.isArray(batch))
|
|
128
|
+
throw new Error(`Cannot completely inventory ${endpoint}.`);
|
|
129
|
+
all.push(...batch);
|
|
130
|
+
if (batch.length < 100)
|
|
131
|
+
return all;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function connectionPages(read) {
|
|
135
|
+
let cursor = null;
|
|
136
|
+
const cursors = new Set();
|
|
137
|
+
const result = [];
|
|
138
|
+
for (;;) {
|
|
139
|
+
const connection = read(cursor);
|
|
140
|
+
if (!Array.isArray(connection?.nodes) || connection.nodes.some(node => !node)
|
|
141
|
+
|| typeof connection.pageInfo?.hasNextPage !== 'boolean')
|
|
142
|
+
throw new Error('Cannot completely inventory GitHub protection rules.');
|
|
143
|
+
result.push(...connection.nodes);
|
|
144
|
+
if (!connection.pageInfo.hasNextPage)
|
|
145
|
+
return result;
|
|
146
|
+
cursor = connection.pageInfo.endCursor;
|
|
147
|
+
if (!cursor || cursors.has(cursor))
|
|
148
|
+
throw new Error('GitHub returned invalid protection pagination.');
|
|
149
|
+
cursors.add(cursor);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const protectionFields = `id pattern allowsDeletions allowsForcePushes blocksCreations
|
|
153
|
+
dismissesStaleReviews isAdminEnforced lockAllowsFetchAndMerge lockBranch requireLastPushApproval
|
|
154
|
+
requiredApprovingReviewCount requiredDeploymentEnvironments requiredStatusCheckContexts
|
|
155
|
+
requiredStatusChecks { context app { id } }
|
|
156
|
+
requiresApprovingReviews requiresCodeOwnerReviews requiresCommitSignatures
|
|
157
|
+
requiresConversationResolution requiresDeployments requiresLinearHistory requiresStatusChecks
|
|
158
|
+
requiresStrictStatusChecks restrictsPushes restrictsReviewDismissals`;
|
|
159
|
+
function classicProtections(slug) {
|
|
160
|
+
const [owner, name] = slug.split('/');
|
|
161
|
+
const query = `query PeacekeeperProtections($owner:String!,$name:String!,$cursor:String) {
|
|
162
|
+
repository(owner:$owner,name:$name) { branchProtectionRules(first:100,after:$cursor) {
|
|
163
|
+
nodes { ${protectionFields} } pageInfo { hasNextPage endCursor }
|
|
164
|
+
} }
|
|
165
|
+
}`;
|
|
166
|
+
const rules = connectionPages(cursor => graphql(query, { owner, name, cursor }).repository?.branchProtectionRules);
|
|
167
|
+
if (new Set(rules.map(rule => rule.id)).size !== rules.length)
|
|
168
|
+
throw new Error('Duplicate classic protection IDs in inventory.');
|
|
169
|
+
for (const rule of rules) {
|
|
170
|
+
if (typeof rule.id !== 'string' || !rule.id || typeof rule.pattern !== 'string')
|
|
171
|
+
throw new Error('GitHub returned invalid classic protection.');
|
|
172
|
+
for (const field of ['pushAllowances', 'reviewDismissalAllowances', 'bypassPullRequestAllowances', 'bypassForcePushAllowances']) {
|
|
173
|
+
const allowances = connectionPages(cursor => graphql(`query PeacekeeperAllowances($id:ID!,$cursor:String) {
|
|
174
|
+
node(id:$id) { ... on BranchProtectionRule { ${field}(first:100,after:$cursor) {
|
|
175
|
+
nodes { actor { __typename ... on Node { id } } } pageInfo { hasNextPage endCursor }
|
|
176
|
+
} } }
|
|
177
|
+
}`, { id: rule.id, cursor }).node?.[field]);
|
|
178
|
+
if (allowances.some(item => typeof item.actor?.id !== 'string'))
|
|
179
|
+
throw new Error('Cannot inspect classic protection allowance actors.');
|
|
180
|
+
rule[field] = allowances;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return canonical(rules);
|
|
184
|
+
}
|
|
185
|
+
function readRuleset(base, summary) {
|
|
186
|
+
if (!Number.isSafeInteger(summary.id))
|
|
187
|
+
throw new Error('GitHub returned invalid ruleset identity.');
|
|
188
|
+
const ruleset = request(`${base}/rulesets/${summary.id}`);
|
|
189
|
+
if (ruleset?.id !== summary.id || ruleset.target !== 'branch'
|
|
190
|
+
|| ruleset.source !== summary.source || ruleset.source_type !== summary.source_type
|
|
191
|
+
|| typeof ruleset.name !== 'string' || !['active', 'disabled', 'evaluate'].includes(ruleset.enforcement)
|
|
192
|
+
|| !Array.isArray(ruleset.rules) || !Array.isArray(ruleset.bypass_actors)
|
|
193
|
+
|| !ruleset.conditions?.ref_name || !Array.isArray(ruleset.conditions.ref_name.include)
|
|
194
|
+
|| !Array.isArray(ruleset.conditions.ref_name.exclude))
|
|
195
|
+
throw new Error(`Cannot fully inspect branch ruleset ${summary.id}, including bypass actors.`);
|
|
196
|
+
return { id: summary.id, policy: normalizeRuleset(ruleset) };
|
|
197
|
+
}
|
|
198
|
+
function inventory(metadata, repositoryFields) {
|
|
199
|
+
const base = `repos/${metadata.full_name}`;
|
|
200
|
+
const repository = Object.fromEntries(Object.keys(repositoryFields).map(key => {
|
|
201
|
+
if (typeof metadata[key] !== 'boolean')
|
|
202
|
+
throw new Error(`Cannot inspect repository setting ${key}.`);
|
|
203
|
+
return [key, metadata[key]];
|
|
204
|
+
}));
|
|
205
|
+
const owned = restPages(`${base}/rulesets?includes_parents=false`);
|
|
206
|
+
const all = restPages(`${base}/rulesets?includes_parents=true`);
|
|
207
|
+
if (owned.some(rule => rule.source_type !== 'Repository' || rule.source !== metadata.full_name)) {
|
|
208
|
+
throw new Error('Cannot determine repository ruleset ownership.');
|
|
209
|
+
}
|
|
210
|
+
if (owned.some(rule => !['branch', 'tag', 'push'].includes(rule.target)))
|
|
211
|
+
throw new Error('Cannot determine ruleset target.');
|
|
212
|
+
if (all.some(rule => !['branch', 'tag', 'push'].includes(rule.target)
|
|
213
|
+
|| !['Repository', 'Organization', 'Enterprise'].includes(rule.source_type)))
|
|
214
|
+
throw new Error('Cannot determine inherited ruleset ownership.');
|
|
215
|
+
const ownedIds = owned.filter(rule => rule.target === 'branch').map(rule => rule.id);
|
|
216
|
+
const allOwnedIds = all.filter(rule => rule.target === 'branch' && rule.source_type === 'Repository'
|
|
217
|
+
&& rule.source === metadata.full_name).map(rule => rule.id);
|
|
218
|
+
if (new Set(all.map(rule => rule.id)).size !== all.length
|
|
219
|
+
|| !githubPolicy.same(ownedIds, allOwnedIds))
|
|
220
|
+
throw new Error('Ruleset inventory changed between requests; create a new plan.');
|
|
221
|
+
const rulesets = owned.filter(rule => rule.target === 'branch').map(rule => readRuleset(base, rule));
|
|
222
|
+
const inheritedRulesets = all.filter(rule => rule.target === 'branch'
|
|
223
|
+
&& (rule.source_type !== 'Repository' || rule.source !== metadata.full_name))
|
|
224
|
+
.map(rule => ({ ...readRuleset(base, rule), source: rule.source }));
|
|
225
|
+
if (new Set(rulesets.map(rule => rule.id)).size !== rulesets.length)
|
|
226
|
+
throw new Error('Duplicate ruleset IDs in inventory.');
|
|
227
|
+
return canonical({ repository, rulesets, inheritedRulesets, classicProtections: classicProtections(metadata.full_name) });
|
|
228
|
+
}
|
|
229
|
+
return { request, graphql, repositorySlug, loadSource, inventory };
|
|
230
|
+
};
|
|
@@ -1,40 +1,35 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
// --- Implementation ---
|
|
2
|
+
export default ({ configuration, receiptState, external: { clock, output, runtime } }) => {
|
|
3
|
+
const { ROOT, environmentFingerprint, readReceipts, snapshot } = receiptState;
|
|
3
4
|
const { projectConfig, requireTestCommands } = configuration;
|
|
4
|
-
function successMessage(root = ROOT()) {
|
|
5
|
+
function successMessage(root = ROOT(), checkpoint = false) {
|
|
5
6
|
const command = projectConfig(root).tests.npmTestUsesRunner
|
|
6
|
-
?
|
|
7
|
-
:
|
|
7
|
+
? `npm test -- --force${checkpoint ? ' --checkpoint' : ''}`
|
|
8
|
+
: `node node_modules/@jakobm/peacekeeper/dist/bin/peacekeeper.js test run --force${checkpoint ? ' --checkpoint' : ''}`;
|
|
8
9
|
return `Tests already passed for this change set. In order to rerun tests anyway, use: ${command}`;
|
|
9
10
|
}
|
|
10
11
|
function matchesReceipt(receipt, root = ROOT()) {
|
|
11
12
|
const { receiptMaxAgeMinutes } = projectConfig(root).tests;
|
|
12
|
-
if (!receipt || receipt.
|
|
13
|
-
|
|
14
|
-
receipt.
|
|
13
|
+
if (!receipt || typeof receipt.command !== 'string' || typeof receipt.baseCommit !== 'string'
|
|
14
|
+
|| !Array.isArray(receipt.changedFiles) || !Number.isFinite(receipt.passedAt)
|
|
15
|
+
|| clock.now() < receipt.passedAt || clock.now() - receipt.passedAt > receiptMaxAgeMinutes * 60_000
|
|
16
|
+
|| receipt.environment !== environmentFingerprint())
|
|
15
17
|
return false;
|
|
16
18
|
const current = snapshot(root, receipt.baseCommit);
|
|
17
19
|
return JSON.stringify(current.changedFiles) === JSON.stringify(receipt.changedFiles);
|
|
18
20
|
}
|
|
19
|
-
function checkReceipt(root = ROOT()) {
|
|
21
|
+
function checkReceipt(root = ROOT(), commands = projectConfig(root).tests.all) {
|
|
20
22
|
requireTestCommands(root);
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
receipt = JSON.parse(fs.readFileSync(receiptPath(root), 'utf8'));
|
|
24
|
-
}
|
|
25
|
-
catch (error) {
|
|
26
|
-
if (error.code === 'ENOENT' || error instanceof SyntaxError)
|
|
27
|
-
return false;
|
|
28
|
-
throw error;
|
|
29
|
-
}
|
|
30
|
-
return matchesReceipt(receipt, root);
|
|
23
|
+
const receipts = readReceipts(root);
|
|
24
|
+
return commands.every(command => receipts.some(receipt => receipt?.command === command && matchesReceipt(receipt, root)));
|
|
31
25
|
}
|
|
32
|
-
function run() {
|
|
26
|
+
function run({ checkpoint = false } = {}) {
|
|
33
27
|
try {
|
|
34
|
-
|
|
28
|
+
const config = projectConfig();
|
|
29
|
+
if (!checkReceipt(config.root, config.tests[checkpoint ? 'checkpoint' : 'all']))
|
|
35
30
|
runtime.exitCode = 1;
|
|
36
31
|
else
|
|
37
|
-
output.log(successMessage());
|
|
32
|
+
output.log(successMessage(config.root, checkpoint));
|
|
38
33
|
}
|
|
39
34
|
catch (error) {
|
|
40
35
|
output.error(error instanceof Error ? error.message : String(error));
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// --- Implementation ---
|
|
1
2
|
export default ({ configuration, external: { clock, crypto, execFileSync, fs, modulesRoot, os, path, runtime, } }) => {
|
|
2
3
|
const { repositoryRoot } = configuration;
|
|
3
4
|
const ROOT = repositoryRoot;
|
|
@@ -94,6 +95,31 @@ export default ({ configuration, external: { clock, crypto, execFileSync, fs, mo
|
|
|
94
95
|
const id = crypto.createHash('sha256').update(fs.realpathSync(root)).digest('hex');
|
|
95
96
|
return path.join(os.tmpdir(), RECEIPT_DIRECTORY, `${id}.git.json`);
|
|
96
97
|
}
|
|
97
|
-
|
|
98
|
+
function readReceipts(root = ROOT()) {
|
|
99
|
+
try {
|
|
100
|
+
const stored = JSON.parse(fs.readFileSync(receiptPath(root), 'utf8'));
|
|
101
|
+
return stored?.version === 2 && Array.isArray(stored.receipts) ? stored.receipts : [];
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
if (error.code === 'ENOENT' || error instanceof SyntaxError)
|
|
105
|
+
return [];
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function writeReceipts(root, receipts) {
|
|
110
|
+
const destination = receiptPath(root);
|
|
111
|
+
if (!receipts.length) {
|
|
112
|
+
fs.rmSync(destination, { force: true });
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
|
116
|
+
const temporary = `${destination}.${runtime.pid}.tmp`;
|
|
117
|
+
fs.writeFileSync(temporary, `${JSON.stringify({ version: 2, receipts })}\n`);
|
|
118
|
+
fs.renameSync(temporary, destination);
|
|
119
|
+
}
|
|
120
|
+
function invalidateReceipts(root = ROOT(), commands) {
|
|
121
|
+
writeReceipts(root, commands ? readReceipts(root).filter(receipt => !commands.includes(receipt?.command)) : []);
|
|
122
|
+
}
|
|
123
|
+
const api = { ROOT, environmentFingerprint, receiptPath, snapshot, readReceipts, writeReceipts, invalidateReceipts };
|
|
98
124
|
return api;
|
|
99
125
|
};
|