forgedock 1.59.2 → 1.60.1
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/bin/engine/outcome-codes.mjs +3 -3
- package/bin/engine-cli.mjs +50 -10
- package/bin/labels.json +5 -0
- package/bin/lean/batch.mjs +21 -2
- package/bin/lean/batch.test.mjs +116 -1
- package/bin/lean/conformance.mjs +19 -6
- package/bin/lean/conformance.test.mjs +37 -3
- package/bin/lean/depcache.mjs +34 -15
- package/bin/lean/depcache.test.mjs +100 -1
- package/bin/lean/design-gate.mjs +15 -10
- package/bin/lean/design-gate.test.mjs +21 -0
- package/bin/lean/effects.mjs +18 -2
- package/bin/lean/execution.mjs +23 -5
- package/bin/lean/execution.test.mjs +81 -1
- package/bin/lean/gatewatch.test.mjs +5 -5
- package/bin/lean/issuewatch-triage.mjs +68 -0
- package/bin/lean/issuewatch-triage.test.mjs +98 -0
- package/bin/lean/issuewatch.mjs +34 -6
- package/bin/lean/issuewatch.test.mjs +11 -0
- package/bin/lean/lanelock.mjs +5 -4
- package/bin/lean/lean.mjs +144 -21
- package/bin/lean/lean.test.mjs +180 -6
- package/bin/lean/orchestrate-cancel.test.mjs +33 -0
- package/bin/lean/orchestrate-hostfallback.test.mjs +41 -0
- package/bin/lean/orchestrate-recovering.test.mjs +42 -0
- package/bin/lean/orchestrate.mjs +23 -10
- package/bin/lean/pagegate.mjs +50 -12
- package/bin/lean/pagegate.test.mjs +38 -1
- package/bin/lean/phaseledger.mjs +65 -2
- package/bin/lean/phaseledger.test.mjs +70 -2
- package/bin/lean/preflight.mjs +67 -3
- package/bin/lean/preflight.test.mjs +37 -1
- package/bin/lean/prompts.mjs +2 -1
- package/bin/lean/recovery.test.mjs +11 -6
- package/bin/lean/release-classify.mjs +143 -0
- package/bin/lean/release-classify.test.mjs +130 -0
- package/bin/lean/release-conductor.mjs +163 -0
- package/bin/lean/release-conductor.test.mjs +194 -0
- package/bin/lean/release-config.mjs +60 -8
- package/bin/lean/release-config.test.mjs +43 -1
- package/bin/lean/release-control.mjs +22 -5
- package/bin/lean/release-control.test.mjs +22 -0
- package/bin/lean/release-credentials.mjs +40 -0
- package/bin/lean/release-credentials.test.mjs +42 -0
- package/bin/lean/release-deploy.mjs +3 -3
- package/bin/lean/release-deploy.test.mjs +8 -0
- package/bin/lean/release-docs.test.mjs +93 -0
- package/bin/lean/release-fence.mjs +2 -0
- package/bin/lean/release-gate.mjs +88 -0
- package/bin/lean/release-gate.test.mjs +116 -0
- package/bin/lean/release-gates.mjs +5 -1
- package/bin/lean/release-ledger.mjs +47 -1
- package/bin/lean/release-ledger.test.mjs +33 -1
- package/bin/lean/release-mergeback.mjs +148 -0
- package/bin/lean/release-mergeback.test.mjs +129 -0
- package/bin/lean/release-p0.mjs +193 -0
- package/bin/lean/release-p0.test.mjs +127 -0
- package/bin/lean/release-plan.mjs +267 -0
- package/bin/lean/release-plan.test.mjs +202 -0
- package/bin/lean/release-preflight.mjs +16 -0
- package/bin/lean/release-regate.mjs +141 -0
- package/bin/lean/release-regate.test.mjs +149 -0
- package/bin/lean/release-review.mjs +5 -3
- package/bin/lean/release-rollback.mjs +277 -0
- package/bin/lean/release-rollback.test.mjs +245 -0
- package/bin/lean/release-snapshot.mjs +48 -9
- package/bin/lean/release-snapshot.test.mjs +43 -1
- package/bin/lean/release-start.mjs +164 -0
- package/bin/lean/release-start.test.mjs +171 -0
- package/bin/lean/release-status.mjs +6 -2
- package/bin/lean/release-train.mjs +159 -0
- package/bin/lean/release-train.test.mjs +139 -0
- package/bin/lean/release.mjs +127 -5
- package/bin/lean/release.test.mjs +80 -0
- package/bin/lean/sandbox-remote.mjs +2 -0
- package/bin/lean/schedd-load.test.mjs +82 -0
- package/bin/lean/schedd.mjs +67 -31
- package/bin/lean/schedd.test.mjs +80 -1
- package/bin/lean/validate-catalog.mjs +110 -0
- package/bin/lean/validate-catalog.test.mjs +55 -0
- package/bin/pool/agent.mjs +12 -1
- package/bin/pool/lane-tools.mjs +146 -0
- package/bin/pool/lane-tools.test.mjs +26 -0
- package/bin/pool/router.mjs +3 -1
- package/bin/pool/warm.mjs +14 -3
- package/docs/CONFIG.md +225 -1
- package/docs/ISSUE-WATCH.md +1 -0
- package/docs/design/visual-gate.md +10 -0
- package/docs/eval/adversarial-bench.md +1 -0
- package/package.json +1 -1
- package/pool/README.md +2 -0
- package/scripts/acceptance-red-green.sh +5 -2
- package/scripts/acceptance-red-green.test.sh +11 -0
- package/scripts/bench-adversarial.mjs +4 -0
- package/scripts/bench-lightlane.mjs +2 -1
- package/templates/github-actions/forge-conductor.scopes.json +7 -0
- package/templates/github-actions/forge-conductor.yml +57 -0
|
@@ -13,8 +13,12 @@ import { load, JSON_SCHEMA } from "../vendor/js-yaml/js-yaml.mjs";
|
|
|
13
13
|
import { readReleaseConfig } from "./release.mjs";
|
|
14
14
|
import { readBranches } from "./lane.mjs";
|
|
15
15
|
import { catalogueFindings } from "./release-gates.mjs";
|
|
16
|
+
import { matchesAny } from "./release-unitmap.mjs";
|
|
16
17
|
|
|
17
18
|
export const POLICY_PATH = ".forge/release.yaml";
|
|
19
|
+
/** Migration locations and destructive statements the rollback ladder looks for in migration file text (I8, #5563); text only, nothing is executed. */
|
|
20
|
+
export const MIGRATION_PATHS = ["**/migrations/**", "**/migrate/**", "*.sql"];
|
|
21
|
+
export const DESTRUCTIVE_SQL = /\b(DROP\s+(TABLE|COLUMN|SCHEMA|INDEX|CONSTRAINT)|TRUNCATE|DELETE\s+FROM|ALTER\s+TABLE[^;]*\b(DROP|RENAME)\b|RENAME\s+(TO|COLUMN))\b/i;
|
|
18
22
|
export const DEFERRED_KEYS = ["plan.auto_if", "retention_days", "ci.forbid_per_issue_steps", "couplings[].refine", "ci.provider=command", "risk.weights"];
|
|
19
23
|
|
|
20
24
|
export const INIT_PROFILE = `schema: 1
|
|
@@ -36,22 +40,28 @@ export const POLICY_SCHEMA = obj({
|
|
|
36
40
|
branches: obj({ default: S, integration: SN, train: S, release: S, hotfix: S }),
|
|
37
41
|
trust: obj({ actors: list(), require_verified_commits: B }),
|
|
38
42
|
state: obj({ ledger_prefix: S, lease_ttl_s: N, heartbeat_s: N }),
|
|
39
|
-
units: { t: "map", v: obj({ paths: list(), image: SN, criticality: en("low", "medium", "high"), tests: list(), verify: list(), service_pipeline: B, single_host_ok: B }) },
|
|
43
|
+
units: { t: "map", v: obj({ paths: list(), image: SN, criticality: en("low", "medium", "high"), tests: list(), verify: list(), service_pipeline: B, single_host_ok: B, dockerfile: SN, surface: en("service", "web", "edge") }) },
|
|
40
44
|
couplings: list(obj({ paths: list(), affects: list() })),
|
|
41
|
-
contracts: list(obj({ producer: S, consumers: list(), paths: list(), additive_only: B })),
|
|
45
|
+
contracts: list(obj({ producer: S, consumers: list(), paths: list(), additive_only: B, regenerate: SN })),
|
|
42
46
|
forces: list(obj({ paths: list(), pipeline: en("full", "service", "hotfix"), reason: S })),
|
|
43
47
|
classify: obj({ min_confidence: N, text_only_cap: N, triage_max_per_hour: N, exists_in_evidence: en("mechanical", "llm") }),
|
|
44
48
|
risk: obj({ rules: list(obj({ when: obj({ migration: B, paths: list(), contract: B, rolled_units_gt: N, diff_lines_gt: N, requires: S }), risk: en("low", "medium", "high"), forces: S })) }),
|
|
49
|
+
features: obj({ flag_policy: en("require", "warn", "off") }), // #5571: a feature wave adding no rollout key: require = refuse, warn = WARN, off = nothing; lanes.<lane>.flag_policy wins
|
|
45
50
|
plan: obj({ approval: en("wait", "auto", "auto-if"), skip_labels: list(), require_design_gate: B, max_issues: N, stale_snapshot_s: N }),
|
|
46
51
|
lanes: { t: "map", v: obj({ pipeline: S, ci_tier: S, approval: S, budget: S, base: en("live", "integration", "default"), units_max: N, max_risk: en("low", "medium", "high"), train_max_issues: N, train_max_units: N, soak_min: { t: "any" }, flag_policy: en("require", "warn", "off"), requires: list() }) },
|
|
52
|
+
credentials: obj({ gate_app: SN, lane_env_strip: list() }),
|
|
47
53
|
merge: obj({ approval: en("confirm", "with-plan", "auto"), method: en("merge-commit", "squash", "rebase"), trailers: list() }),
|
|
48
54
|
ci: obj({ provider: en("github-actions", "command"), required_checks: ANY, selection: ANY, rerun_budget_min: N, fix: obj({ max_rounds: I, co_start: B, full_run_workflow: S }), flake: obj({ quarantine_after: N, window_days: N }), unskippable: list(), tiers: { t: "map", v: obj({ jobs: list() }) }, nightly: ANY, budget: ANY }),
|
|
49
55
|
preflight: obj({ commands: list(), timeout_s: N, blocking: B }),
|
|
50
56
|
deploy: obj({ live_release_command: S, freeze_variable: S, concurrency_group: S, start_timeout_s: N, stage_timeout_s: N, expected_digests_command: S, recovery: obj({ rerun_max: I, max_attempts: I, signatures: list() }), pipelines: { t: "map", v: PIPELINE } }),
|
|
51
57
|
verify: obj({ workflow: S, results: list(obj({ workflow: S, kind: en("smoke", "edge", "convergence") })), flags: list(obj({ flag: S, off_command: S })), slis: list(ANY), post_deploy_checks_file: S, close_requires: en("verified", "deployed") }),
|
|
52
|
-
rollback: obj({
|
|
58
|
+
rollback: obj({
|
|
59
|
+
triggers: list(en("smoke", "health", "livecheck", "sli", "crashloop", "human")), ladder: list(en("flag", "unit", "full", "stop")), refuse_across: list(en("destructive_migration")), open_revert_pr: B,
|
|
60
|
+
flags: list(obj({ flag: S, kill_command: S })), unit_workflow: S, unit_action: S, full_workflow: S, health_command: S, result_command: S,
|
|
61
|
+
}),
|
|
62
|
+
events: obj({ webhook_url: S }),
|
|
53
63
|
quarantine: obj({ days: N, max: N }),
|
|
54
|
-
gates: obj({ demote_fb_rate: N, demote_window: I, safety: list() }),
|
|
64
|
+
gates: obj({ demote_fb_rate: N, demote_window: I, safety: list(), paths: list(), workflow_steps: list() }),
|
|
55
65
|
controls: obj({ intake: ANY, conductor: ANY, exempt: ANY }),
|
|
56
66
|
});
|
|
57
67
|
|
|
@@ -140,7 +150,39 @@ export function readPolicy({ io, defaultBranch, cwd = process.cwd(), ref }) {
|
|
|
140
150
|
const GATES_PATH_LABEL = ".forge/gates.yaml";
|
|
141
151
|
const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
|
|
142
152
|
|
|
143
|
-
/**
|
|
153
|
+
/** COPY/ADD source paths of a Dockerfile (build-stage copies via `--from` and URLs excluded). */
|
|
154
|
+
export function dockerfileSources(text) {
|
|
155
|
+
const out = [];
|
|
156
|
+
for (const line of String(text ?? "").replace(/\\\n/g, " ").split("\n")) {
|
|
157
|
+
const m = /^\s*(?:COPY|ADD)\s+(.*)$/i.exec(line);
|
|
158
|
+
if (!m) continue;
|
|
159
|
+
const parts = m[1].trim().split(/\s+/);
|
|
160
|
+
if (parts.some((p) => /^--from=/i.test(p))) continue;
|
|
161
|
+
const args = parts.filter((p) => !p.startsWith("--") && !p.startsWith("["));
|
|
162
|
+
out.push(...args.slice(0, -1).filter((p) => !/^[a-z]+:\/\//i.test(p) && p !== "."));
|
|
163
|
+
}
|
|
164
|
+
return out;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Q9: the paths a unit's Dockerfile copies that no `units.<id>.paths` or `couplings[].paths` entry maps. */
|
|
168
|
+
export function dockerfileCoverage(policy, dockerfileText) {
|
|
169
|
+
const globs = [...Object.values(policy?.units ?? {}).flatMap((u) => u?.paths ?? []), ...(policy?.couplings ?? []).flatMap((c) => c.paths ?? [])];
|
|
170
|
+
return dockerfileSources(dockerfileText).map((s) => s.replace(/^\.\//, "").replace(/\/+$/, "")).filter((s) => !matchesAny(globs, s) && !matchesAny(globs, `${s}/x`));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** `check-config --coverage` findings: one per unmapped copied path of each unit's `dockerfile`. */
|
|
174
|
+
function coverageFindings(io, policy, ref) {
|
|
175
|
+
const out = [];
|
|
176
|
+
for (const [id, u] of Object.entries(policy?.units ?? {})) {
|
|
177
|
+
if (!u?.dockerfile) continue;
|
|
178
|
+
let text;
|
|
179
|
+
try { text = io.git(["show", `${ref}:${u.dockerfile}`]); } catch { out.push(`coverage: units.${id}.dockerfile ${u.dockerfile} is not readable at ${ref}`); continue; }
|
|
180
|
+
dockerfileCoverage(policy, text).forEach((p) => out.push(`coverage: units.${id} Dockerfile copies ${p}, which no units.<id>.paths or couplings entry maps`));
|
|
181
|
+
}
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** `forgedock release check-config [--ref <git ref>] [--coverage]`: exit 0 valid (or file absent: flat keys), 1 on any finding. */
|
|
144
186
|
export function checkConfigFromCli(argv, { io, cwd = process.cwd() }) {
|
|
145
187
|
const defaultBranch = readBranches(cwd).default || "main";
|
|
146
188
|
const ref = flagOf(argv, "--ref");
|
|
@@ -152,18 +194,28 @@ export function checkConfigFromCli(argv, { io, cwd = process.cwd() }) {
|
|
|
152
194
|
gatesLines().forEach((l) => io.print(l));
|
|
153
195
|
return gf?.length ? 1 : 0;
|
|
154
196
|
}
|
|
155
|
-
const
|
|
197
|
+
const cov = argv.includes("--coverage") && r.policy ? coverageFindings(io, r.policy, ref ?? `origin/${defaultBranch}`) : [];
|
|
198
|
+
const findings = [...r.findings, ...cov, ...(gf ?? []).map((f) => `${GATES_PATH_LABEL}: ${f}`)];
|
|
156
199
|
findings.forEach((f) => io.print(`release check-config: ${f}`));
|
|
157
200
|
io.print(findings.length ? `release check-config: FAILED (${findings.length})` : `release check-config: ok (sha256 ${r.sha.slice(0, 12)})`);
|
|
158
201
|
return findings.length ? 1 : 0;
|
|
159
202
|
}
|
|
160
203
|
|
|
161
|
-
/** `forgedock release init`: writes the zero-config profile (7.4) to `.forge/release.yaml` and nothing else; never overwrites. */
|
|
162
|
-
export function initFromCli(
|
|
204
|
+
/** `forgedock release init [--conductor]`: writes the zero-config profile (7.4) to `.forge/release.yaml` and nothing else; never overwrites. */
|
|
205
|
+
export function initFromCli(argv, { io, cwd = process.cwd() }) {
|
|
163
206
|
const file = join(cwd, POLICY_PATH);
|
|
207
|
+
if (argv?.includes("--conductor")) return initConductor(file, { io, cwd }); // #5564: async; the plain init stays synchronous
|
|
164
208
|
if (existsSync(file)) { io.print(`release init: ${POLICY_PATH} exists; not overwriting`); return 1; }
|
|
165
209
|
mkdirSync(dirname(file), { recursive: true });
|
|
166
210
|
writeFileSync(file, INIT_PROFILE);
|
|
167
211
|
io.print(`release init: wrote ${POLICY_PATH}`);
|
|
168
212
|
return 0;
|
|
169
213
|
}
|
|
214
|
+
|
|
215
|
+
/** `release init --conductor`: the policy file (left alone when present) plus the version-pinned conductor workflow. */
|
|
216
|
+
async function initConductor(file, { io, cwd }) {
|
|
217
|
+
const { installConductor } = await import("./release-conductor.mjs");
|
|
218
|
+
let pol = null; try { pol = parsePolicy(readFileSync(file, "utf8")).policy; } catch { /* no policy yet: defaults */ }
|
|
219
|
+
if (!existsSync(file)) { mkdirSync(dirname(file), { recursive: true }); writeFileSync(file, INIT_PROFILE); io.print(`release init: wrote ${POLICY_PATH}`); }
|
|
220
|
+
return installConductor({ io, cwd, policy: pol });
|
|
221
|
+
}
|
|
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
|
|
|
5
5
|
import { existsSync, readFileSync, readdirSync, writeFileSync, mkdirSync } from "node:fs";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
8
|
-
import { parsePolicy, validatePolicy, readPolicy, INIT_PROFILE, checkConfigFromCli, initFromCli, POLICY_PATH } from "./release-config.mjs";
|
|
8
|
+
import { parsePolicy, validatePolicy, readPolicy, INIT_PROFILE, checkConfigFromCli, dockerfileCoverage, dockerfileSources, initFromCli, POLICY_PATH } from "./release-config.mjs";
|
|
9
9
|
import { releaseFromCli } from "./release.mjs";
|
|
10
10
|
|
|
11
11
|
const OK = `schema: 1
|
|
@@ -126,6 +126,9 @@ describe("gates catalogue and policy (#5583)", () => {
|
|
|
126
126
|
it("accepts the gates policy keys and rejects a wrong type", () => {
|
|
127
127
|
assert.deepEqual(check(OK + "gates: {demote_fb_rate: 5, demote_window: 20, safety: [a]}\n"), []);
|
|
128
128
|
assert.match(check(OK + "gates: {demote_window: 2.5}\n").join(), /demote_window/);
|
|
129
|
+
assert.deepEqual(check(OK + "gates: {paths: [scripts/deploy/**], workflow_steps: [Smoke]}\n"), []); // #5584
|
|
130
|
+
assert.match(check(OK + "gates: {workflow_steps: Smoke}\n").join(), /workflow_steps/);
|
|
131
|
+
assert.match(check(OK + "gates: {bogus: 1}\n").join(), /bogus/);
|
|
129
132
|
});
|
|
130
133
|
it("check-config reports catalogue errors, passes a valid one, ignores an absent one", () => {
|
|
131
134
|
const bad = gio({ ".forge/gates.yaml": GATE.replace("mode: block", "mode: nope"), [POLICY_PATH]: OK });
|
|
@@ -138,3 +141,42 @@ describe("gates catalogue and policy (#5583)", () => {
|
|
|
138
141
|
assert.doesNotMatch(none.printed.join("\n"), /gates/);
|
|
139
142
|
});
|
|
140
143
|
});
|
|
144
|
+
|
|
145
|
+
describe("rollback and events keys (#5563)", () => {
|
|
146
|
+
const rb = "rollback:\n ladder: [flag, unit, full, stop]\n triggers: [smoke, sli]\n refuse_across: [destructive_migration]\n open_revert_pr: true\n flags: [{flag: f1, kill_command: ./kill}]\n unit_workflow: svc.yml\n full_workflow: rb.yml\n result_command: ./res\nevents: {webhook_url: https://x.test/h}\n";
|
|
147
|
+
it("accepts the typed ladder keys", () => assert.deepEqual(check(`${OK}${rb}`), []));
|
|
148
|
+
it("rejects an unknown rung, trigger and key", () => {
|
|
149
|
+
assert.match(check(`${OK}rollback: {ladder: [nuke]}\n`).join("\n"), /ladder\[0\].*not one of/);
|
|
150
|
+
assert.match(check(`${OK}rollback: {triggers: [moon]}\n`).join("\n"), /triggers\[0\]/);
|
|
151
|
+
assert.match(check(`${OK}rollback: {sql: x}\n`).join("\n"), /rollback\.sql: unknown key/);
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
describe("check-config --coverage and contracts[].regenerate (#5570, Q9)", () => {
|
|
156
|
+
const POL = `${OK.replace("api: {paths", "api: {dockerfile: services/api/Dockerfile, paths")}`;
|
|
157
|
+
const mkio = (docker) => ({ printed: [], print(l) { this.printed.push(l); }, git(a) { const k = a[1].split(":").slice(1).join(":"); if (k === POLICY_PATH) return POL; if (k === "services/api/Dockerfile") return docker; throw new Error("missing"); } });
|
|
158
|
+
it("parses COPY/ADD sources, skipping --from copies and urls", () => {
|
|
159
|
+
assert.deepEqual(dockerfileSources("FROM x\nCOPY --from=build /out /app\nCOPY a/ b.txt /app/\nADD https://x/y /z\nCOPY . /all\n"), ["a/", "b.txt"]);
|
|
160
|
+
});
|
|
161
|
+
it("fails on a Dockerfile copying an unmapped path and passes once it is mapped", () => {
|
|
162
|
+
const bad = mkio("FROM x\nCOPY services/api /app\nCOPY libs/secret /app/libs\n");
|
|
163
|
+
assert.equal(checkConfigFromCli(["--coverage"], { io: bad }), 1);
|
|
164
|
+
assert.match(bad.printed.join("\n"), /copies libs\/secret/);
|
|
165
|
+
assert.deepEqual(dockerfileCoverage(parsePolicy(POL).policy, "COPY services/api /app\nCOPY shared /s\n"), []);
|
|
166
|
+
const good = mkio("FROM x\nCOPY services/api /app\nCOPY shared /s\n");
|
|
167
|
+
assert.equal(checkConfigFromCli(["--coverage"], { io: good }), 0);
|
|
168
|
+
});
|
|
169
|
+
it("without --coverage the Dockerfile is not read", () => assert.equal(checkConfigFromCli([], { io: mkio("COPY nowhere /x\n") }), 0));
|
|
170
|
+
it("accepts an optional contracts[].regenerate and rejects a wrong type", () => {
|
|
171
|
+
const c = (r) => validatePolicy(parsePolicy(`${OK}contracts:\n - {producer: api, consumers: [web], paths: ["c/**"], regenerate: ${r}}\n`).policy);
|
|
172
|
+
assert.deepEqual(c('"make gen"'), []);
|
|
173
|
+
assert.match(c("[1]").join(), /regenerate/);
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
describe("features.flag_policy (#5571)", () => {
|
|
178
|
+
it("accepts require|warn|off and rejects anything else", () => {
|
|
179
|
+
for (const v of ["require", "warn", "off"]) assert.deepEqual(check(OK + `features: {flag_policy: ${v}}\n`), [], v);
|
|
180
|
+
assert.match(check(OK + "features: {flag_policy: maybe}\n").join(), /flag_policy/);
|
|
181
|
+
});
|
|
182
|
+
});
|
|
@@ -15,11 +15,11 @@ import { UNSKIPPABLE_CLASSES, isUnskippable, parseFlakeConfig, canQuarantine } f
|
|
|
15
15
|
|
|
16
16
|
export const CONTROL_SCHEMA = "forgedock.release.control/v1";
|
|
17
17
|
export const CONTROL_MARKER = "FORGE:CONTROL";
|
|
18
|
-
export const VERBS = ["hold", "resume", "cancel", "lane", "exempt", "freeze", "unfreeze", "demote", "promote"];
|
|
18
|
+
export const VERBS = ["hold", "resume", "cancel", "lane", "exempt", "freeze", "unfreeze", "demote", "promote", "rollback", "regate"];
|
|
19
19
|
export { UNSKIPPABLE_CLASSES as UNSKIPPABLE };
|
|
20
20
|
export const EXEMPT_MAX_H = { skip: 24, quarantine: 14 * 24 };
|
|
21
21
|
export const LANES = ["train", "release", "p0", "exclude"];
|
|
22
|
-
const OWNED = ["holds", "cancelled", "lanes", "exemptions", "freeze", "gateModes"];
|
|
22
|
+
const OWNED = ["holds", "cancelled", "lanes", "exemptions", "freeze", "gateModes", "rollbacks", "regates"];
|
|
23
23
|
export const DEMOTE_MAX_H = 30 * 24;
|
|
24
24
|
const BREAK_GLASS = /^(override_freeze|acknowledge_hotfix_revert|override_.*|acknowledge_.*)$/;
|
|
25
25
|
|
|
@@ -46,7 +46,7 @@ export async function holdCheck(lctx, id) {
|
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
const flagOf = (argv, f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };
|
|
49
|
-
const FLAGS = ["--repo", "--reason", "--mode", "--issue", "--until", "--force", "--fixture"];
|
|
49
|
+
const FLAGS = ["--repo", "--reason", "--mode", "--issue", "--until", "--force", "--fixture", "--to", "--ref", "--gate-fix-ref"];
|
|
50
50
|
const positionals = (argv) => argv.filter((a, i) => !a.startsWith("--") && !FLAGS.includes(argv[i - 1]));
|
|
51
51
|
const ttlHours = (s) => { const m = /^(\d+)([hd])$/.exec(String(s ?? "")); return m ? Number(m[1]) * (m[2] === "d" ? 24 : 1) : null; };
|
|
52
52
|
|
|
@@ -115,6 +115,22 @@ export async function runControl(verb, argv, ctx) {
|
|
|
115
115
|
}
|
|
116
116
|
return { patch: { exemptions: { ...(a.exemptions ?? {}), [check]: entry } }, before: a.exemptions?.[check] ?? null, after: entry };
|
|
117
117
|
};
|
|
118
|
+
} else if (verb === "rollback") { // #5563: the audited record of a rollback request; the ladder itself is release-rollback.mjs
|
|
119
|
+
const id = pos[0], to = flagOf(argv, "--to");
|
|
120
|
+
if (!id) return fail("rollback: release id required");
|
|
121
|
+
if (to && !["flag", "unit", "full"].includes(to)) return fail("rollback: --to must be flag, unit or full");
|
|
122
|
+
apply = (a) => { const entry = { reason, actor, at, to: to ?? null }; return { patch: { rollbacks: { ...(a.rollbacks ?? {}), [id]: entry } }, before: a.rollbacks?.[id] ?? null, after: entry }; };
|
|
123
|
+
} else if (verb === "regate") { // #5584: gate-only fix lane; refusals come first, then one audited commit, then one fenced dispatch
|
|
124
|
+
const id = pos[0];
|
|
125
|
+
if (!id) return fail("regate: release id required");
|
|
126
|
+
const state = ctx.state ?? ctx.rel?.load?.();
|
|
127
|
+
if (!state) return fail(`regate: no release ${id}`);
|
|
128
|
+
const R = await import("./release-regate.mjs");
|
|
129
|
+
const p = await R.regatePlan({ io, repo, policy, state }, { ref: flagOf(argv, "--ref"), gateFixRef: flagOf(argv, "--gate-fix-ref") });
|
|
130
|
+
if (p.refuse) return fail(`regate: ${p.refuse}`);
|
|
131
|
+
const entry = { reason, actor, at, ref: p.plan.ref, sha: p.plan.sha, gate_sha: p.plan.gateSha, gate_fix_ref: p.plan.gateFixRef };
|
|
132
|
+
apply = (a) => ({ patch: { regates: { ...(a.regates ?? {}), [id]: entry } }, before: a.regates?.[id] ?? null, after: entry });
|
|
133
|
+
ctx.afterCommit = async () => { ctx.regateResult = await R.regateDispatch({ io, repo, state, fence: ctx.fence, save: () => ctx.rel?.save?.(state) }, p.plan, { actor, host }); };
|
|
118
134
|
} else if (verb === "demote" || verb === "promote") { // #5583: false-block policy on a deploy gate, same audited path
|
|
119
135
|
const gate = pos[0];
|
|
120
136
|
if (!gate) return fail(`${verb}: gate id required`);
|
|
@@ -152,6 +168,7 @@ export async function runControl(verb, argv, ctx) {
|
|
|
152
168
|
});
|
|
153
169
|
if (!r.ok) return fail(r.refused ?? `could not commit the control (lost the race after ${r.attempts} attempts)`);
|
|
154
170
|
if (ctx.afterCommit) await ctx.afterCommit();
|
|
171
|
+
if (ctx.regateResult?.refused) return { ...fail(`regate: ${ctx.regateResult.refused}`), entry: line };
|
|
155
172
|
const issue = r.active.lease?.issue;
|
|
156
173
|
let comment = null;
|
|
157
174
|
if (issue) {
|
|
@@ -162,9 +179,9 @@ export async function runControl(verb, argv, ctx) {
|
|
|
162
179
|
}
|
|
163
180
|
|
|
164
181
|
/** CLI: `[--repo R] [--json]` plus the verb's flags; prints one line or the JSON result; @returns the exit code. */
|
|
165
|
-
export async function controlFromCli(verb, argv, { io, policy, actor, host }) {
|
|
182
|
+
export async function controlFromCli(verb, argv, { io, policy, actor, host, rel }) {
|
|
166
183
|
const repo = flagOf(argv, "--repo") ?? JSON.parse(String(await io.gh(["repo", "view", "--json", "nameWithOwner"]))).nameWithOwner;
|
|
167
|
-
const r = await runControl(verb, argv.filter((a) => a !== "--json"), { io, repo, policy, actor, host, now: io.now?.() });
|
|
184
|
+
const r = await runControl(verb, argv.filter((a) => a !== "--json"), { io, repo, policy, actor, host, rel, now: io.now?.() });
|
|
168
185
|
if (argv.includes("--json")) io.print(JSON.stringify(r));
|
|
169
186
|
else io.print(r.ok ? `release ${verb}: recorded (${r.entry.at})` : `release ${verb}: refused: ${r.error}`);
|
|
170
187
|
return r.ok ? 0 : 1;
|
|
@@ -165,3 +165,25 @@ describe("demote / promote (#5583)", () => {
|
|
|
165
165
|
assert.match((await runControl("promote", ["g", "--fixture", "f", "--reason", "r"], base(w))).error, /not demoted/);
|
|
166
166
|
});
|
|
167
167
|
});
|
|
168
|
+
|
|
169
|
+
describe("rollback verb (#5563)", () => {
|
|
170
|
+
it("needs a reason and a release id, and records an audited line", async () => {
|
|
171
|
+
const w = world();
|
|
172
|
+
assert.match((await runControl("rollback", [RID], base(w))).error, /--reason is required/);
|
|
173
|
+
assert.match((await runControl("rollback", ["--reason", "x"], base(w))).error, /release id required/);
|
|
174
|
+
assert.match((await runControl("rollback", [RID, "--reason", "x", "--to", "stop"], base(w))).error, /--to must be/);
|
|
175
|
+
const r = await runControl("rollback", [RID, "--reason", "smoke red", "--to", "unit"], base(w));
|
|
176
|
+
assert.equal(r.ok, true);
|
|
177
|
+
assert.equal(r.entry.verb, "rollback");
|
|
178
|
+
assert.deepEqual(w.active.rollbacks[RID], { reason: "smoke red", actor: "op", at: new Date(1_700_000_000_000).toISOString(), to: "unit" });
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
describe("release control regate verb (#5584)", () => {
|
|
183
|
+
it("needs a release id and --reason, and is a known verb", async () => {
|
|
184
|
+
const w = world();
|
|
185
|
+
assert.match((await runControl("regate", ["--reason", "r"], base(w))).error, /release id required/);
|
|
186
|
+
assert.match((await runControl("regate", [RID, "--ref", "f"], base(w))).error, /--reason is required/);
|
|
187
|
+
assert.match((await runControl("regate", [RID, "--reason", "r"], base(w))).error, /no release/);
|
|
188
|
+
});
|
|
189
|
+
});
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Credential split (#5561, epic #5549, invariants I1/I12): identity is not capability. Three roles: `driver` (the release
|
|
5
|
+
* host: ledger, merge, release-branch pushes), `lane` (builder/fix/reviewer sandboxes: none of those) and `gate` (the gate
|
|
6
|
+
* workflow: posts the gate status). `laneEnv` strips the driver token from every sandbox environment; `roleRefusal` names the
|
|
7
|
+
* role and action it refuses.
|
|
8
|
+
*/
|
|
9
|
+
export const ROLES = Object.freeze(["driver", "lane", "gate"]);
|
|
10
|
+
|
|
11
|
+
/** Env names that carry the driver credential (the lane gets its own token under another name; a deployment whose driver token is named differently lists it in the policy); the policy `credentials.lane_env_strip` list adds more. */
|
|
12
|
+
export const DRIVER_ENV = Object.freeze(["FORGE_DRIVER_TOKEN", "FORGEDOCK_DRIVER_TOKEN", "FORGE_RELEASE_DRIVER_TOKEN"]);
|
|
13
|
+
|
|
14
|
+
const ALLOWED = { "ledger-write": ["driver"], "gate-post": ["gate"], merge: ["driver"], push: ["driver"] };
|
|
15
|
+
const PROTECTED_BRANCH = /^(release|train)\//;
|
|
16
|
+
|
|
17
|
+
/** A copy of `env` without the driver token and the `extra` names: the only environment lane, fix and reviewer sandboxes get. */
|
|
18
|
+
export function laneEnv(env = process.env, extra = []) {
|
|
19
|
+
const drop = new Set([...DRIVER_ENV, ...(Array.isArray(extra) ? extra : [])]);
|
|
20
|
+
return Object.fromEntries(Object.entries(env).filter(([k]) => !drop.has(k)));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @param {string} role one of ROLES
|
|
25
|
+
* @param {"ledger-write"|"gate-post"|"merge"|"push"} action
|
|
26
|
+
* @param {{branch?: string, fixPush?: boolean}} [opts] a `push` to release/* or train/* is refused unless it is the one allowed fix push (lane) or by the driver
|
|
27
|
+
* @returns {string|null} the refusal naming role and action, null when allowed
|
|
28
|
+
*/
|
|
29
|
+
export function roleRefusal(role, action, opts = {}) {
|
|
30
|
+
if (!ROLES.includes(role)) return `role ${JSON.stringify(role ?? null)} is unknown and may not ${action}`;
|
|
31
|
+
if (action === "push" && !PROTECTED_BRANCH.test(String(opts.branch ?? ""))) return null;
|
|
32
|
+
if (action === "push" && role === "lane" && opts.fixPush === true) return null;
|
|
33
|
+
return ALLOWED[action]?.includes(role) ? null : `role ${role} may not ${action}${opts.branch ? ` on ${opts.branch}` : ""}`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Throws `{refused}` when `ctx.credential` may not `action`. */
|
|
37
|
+
export function assertRole(ctx, action, opts) {
|
|
38
|
+
const why = roleRefusal(ctx?.credential, action, opts);
|
|
39
|
+
if (why) throw Object.assign(new Error(why), { refused: why });
|
|
40
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { spawnSync } from "node:child_process";
|
|
6
|
+
import { laneEnv, roleRefusal, assertRole, DRIVER_ENV, ROLES } from "./release-credentials.mjs";
|
|
7
|
+
import { createReleaseLedger } from "./release-ledger.mjs";
|
|
8
|
+
|
|
9
|
+
describe("release credentials (#5561)", () => {
|
|
10
|
+
it("roles are driver, lane and gate", () => assert.deepEqual([...ROLES], ["driver", "lane", "gate"]));
|
|
11
|
+
|
|
12
|
+
it("laneEnv removes the driver token and every configured variable, keeping the rest", () => {
|
|
13
|
+
const env = { PATH: "/bin", FORGE_DRIVER_TOKEN: "d", FORGEDOCK_DRIVER_TOKEN: "d", FORGE_RELEASE_DRIVER_TOKEN: "d", EXTRA_SECRET: "x", KEEP: "1" };
|
|
14
|
+
assert.deepEqual(laneEnv(env, ["EXTRA_SECRET"]), { PATH: "/bin", KEEP: "1" });
|
|
15
|
+
assert.ok(DRIVER_ENV.every((k) => !(k in laneEnv(env))));
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it("the driver token is absent in a really spawned lane process", () => {
|
|
19
|
+
const env = { ...process.env, FORGE_DRIVER_TOKEN: "sekrit", CUSTOM_DRIVER: "sekrit2" };
|
|
20
|
+
const r = spawnSync(process.execPath, ["-e", "process.stdout.write(JSON.stringify([process.env.FORGE_DRIVER_TOKEN, process.env.CUSTOM_DRIVER]))"], { env: laneEnv(env, ["CUSTOM_DRIVER"]), encoding: "utf8" });
|
|
21
|
+
assert.deepEqual(JSON.parse(r.stdout), [null, null]);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it("I12: a lane-role context is refused ledger write, gate post, merge and out-of-band release/train pushes; each refusal names role and action", async () => {
|
|
25
|
+
assert.match(roleRefusal("lane", "gate-post"), /role lane may not gate-post/);
|
|
26
|
+
assert.match(roleRefusal("lane", "merge", { branch: "main" }), /role lane may not merge/);
|
|
27
|
+
assert.match(roleRefusal("lane", "push", { branch: "release/20240101-1" }), /role lane may not push on release\//);
|
|
28
|
+
assert.match(roleRefusal("lane", "push", { branch: "train/a" }), /role lane may not push/);
|
|
29
|
+
assert.throws(() => assertRole({ credential: "lane" }, "ledger-write"), /role lane may not ledger-write/);
|
|
30
|
+
await assert.rejects(() => createReleaseLedger({ io: {}, repo: "o/r", credential: "lane" }, "r20240101-000000-1", {}), (e) => e.refused === "not-driver" && /role lane may not ledger-write/.test(e.message));
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it("allowed: the one fix push by a lane, the driver's own actions, the gate's post, and any non-release branch", () => {
|
|
34
|
+
assert.equal(roleRefusal("lane", "push", { branch: "release/x", fixPush: true }), null);
|
|
35
|
+
assert.equal(roleRefusal("lane", "push", { branch: "feat/x" }), null);
|
|
36
|
+
for (const a of ["ledger-write", "merge"]) assert.equal(roleRefusal("driver", a), null);
|
|
37
|
+
assert.equal(roleRefusal("driver", "push", { branch: "release/x" }), null);
|
|
38
|
+
assert.equal(roleRefusal("gate", "gate-post"), null);
|
|
39
|
+
assert.match(roleRefusal("driver", "gate-post"), /may not gate-post/);
|
|
40
|
+
assert.match(roleRefusal(undefined, "merge"), /unknown/);
|
|
41
|
+
});
|
|
42
|
+
});
|
|
@@ -37,7 +37,7 @@ export function liveMatches(live, mergeSha, expected) {
|
|
|
37
37
|
return units.length ? units.every(([u, d]) => live.images?.[u] === d) : sameSha(live.sha, mergeSha);
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
async function readTarget(io, cmd) {
|
|
40
|
+
export async function readTarget(io, cmd) {
|
|
41
41
|
if (!cmd) return null;
|
|
42
42
|
const r = await io.rehearse(cmd, { timeout: 120_000 });
|
|
43
43
|
return r?.ok ? parseLiveRelease(r.output) : null;
|
|
@@ -83,7 +83,7 @@ export async function runFor(ctx, { workflow, sha, inputs, key, startPolls, b })
|
|
|
83
83
|
run = await poll(io, Math.max(startPolls, Math.ceil((ctx.config.deploy?.start_timeout_s ?? 60) * 1000 / b.pollMs)), b.pollMs, look);
|
|
84
84
|
return run ? { run, dispatched: false } : { err: `a ${workflow} dispatch for ${sha.slice(0, 8)} was already recorded but no run appeared; check the Actions tab, then resume (never redispatched)` };
|
|
85
85
|
}
|
|
86
|
-
const f = await fenced(ctx.fence, { action: "dispatch", key: idemKey(ctx, key) }, (epoch) => io.gh(buildDispatchArgs({ workflow, repo, ref: ctx.def, inputs: { ...inputs, ...(epoch != null ? { forge_epoch: epoch } : {}) } })));
|
|
86
|
+
const f = await fenced(ctx.fence, { action: "dispatch", key: idemKey(ctx, key) }, (epoch) => io.gh(buildDispatchArgs({ workflow, repo, ref: ctx.deployRef ?? ctx.def, inputs: { ...inputs, ...(epoch != null ? { forge_epoch: epoch } : {}) } })));
|
|
87
87
|
if (f.refused) return { err: `dispatch ${f.refused}` };
|
|
88
88
|
run = await poll(io, startPolls, b.pollMs, look);
|
|
89
89
|
return run ? { run, dispatched: true } : { err: `no ${workflow} run for ${sha.slice(0, 8)} after a dispatch on ${ctx.def}; check the Actions tab, then resume` };
|
|
@@ -176,7 +176,7 @@ export async function deployStep(ctx) {
|
|
|
176
176
|
if (st.phase !== "LIVE_CHECKED" && st.phase !== "LIVE") {
|
|
177
177
|
for (;;) {
|
|
178
178
|
st.phase = "DEPLOYING"; ctx.save();
|
|
179
|
-
const r = await runFor(ctx, { workflow: pipe.workflow, sha, inputs: pipe.inputs ?? {}, key: `deploy:${sha}`, startPolls: pipe.trigger === "dispatch" ? 1 : Math.max(1, Math.ceil((d.start_timeout_s ?? 60) * 1000 / b.pollMs)), b });
|
|
179
|
+
const r = await runFor(ctx, { workflow: pipe.workflow, sha, inputs: { ...(pipe.inputs ?? {}), ...(ctx.config.trainDispatch ? { merge_sha: sha, units: ctx.config.trainDispatch.units.join(",") } : {}) }, key: `deploy:${sha}`, startPolls: pipe.trigger === "dispatch" ? 1 : Math.max(1, Math.ceil((d.start_timeout_s ?? 60) * 1000 / b.pollMs)), b });
|
|
180
180
|
if (r.err) return blocked(r.err);
|
|
181
181
|
st.runId = r.run.databaseId; ctx.save();
|
|
182
182
|
const done = await finished(ctx, pipe.workflow, sha, Math.ceil(stageS(d) * 1000 / b.runPollMs), b);
|
|
@@ -87,6 +87,14 @@ describe("release deploy stages (#5560)", () => {
|
|
|
87
87
|
assert.match(d[0], /forge_epoch=3/); assert.ok(!/override_|acknowledge_/.test(d[0]));
|
|
88
88
|
assert.ok(calls.some((r) => r.key.endsWith(`:deploy:3:deploy:${SHA}`)));
|
|
89
89
|
});
|
|
90
|
+
it("a train wave dispatches the merge sha and the expected unit set (#5570)", async () => {
|
|
91
|
+
const { w, io } = world({ runs: [] }); const calls = [];
|
|
92
|
+
const orig = io.gh; io.gh = async (a) => { const r = await orig(a); if (a[0] === "workflow") w.runs = [{ databaseId: 11, status: "completed", conclusion: "success" }]; return r; };
|
|
93
|
+
const c = mk(io, { fence: fence(calls) }); c.config.trainDispatch = { units: ["api", "web"] };
|
|
94
|
+
await deployStep(c);
|
|
95
|
+
const d = w.gh.find((g) => g.startsWith("workflow run"));
|
|
96
|
+
assert.match(d, new RegExp(`merge_sha=${SHA}`)); assert.match(d, /units=api,web/);
|
|
97
|
+
});
|
|
90
98
|
it("a stale epoch refuses the dispatch", async () => {
|
|
91
99
|
const { io } = world({ runs: [] });
|
|
92
100
|
const f = fence(); f.lctx = { io: { api: async () => active({ lease: { holder: "other", epoch: 4 }, epoch: 4 }) }, repo: "o/r" };
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// #5572: docs/CONFIG.md `release` section stays true to release-config.mjs and release.mjs; drift fails CI.
|
|
4
|
+
import { describe, it } from "node:test";
|
|
5
|
+
import assert from "node:assert/strict";
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
7
|
+
import { POLICY_SCHEMA, INIT_PROFILE, DEFERRED_KEYS, parsePolicy } from "./release-config.mjs";
|
|
8
|
+
import { RELEASE_USAGE } from "./release.mjs";
|
|
9
|
+
|
|
10
|
+
const DOC = readFileSync(new URL("../../docs/CONFIG.md", import.meta.url), "utf8");
|
|
11
|
+
const LEAN = readFileSync(new URL("../../devdocs/modules/lean.md", import.meta.url), "utf8");
|
|
12
|
+
|
|
13
|
+
const sectionOf = (text, re) => { const m = re.exec(text); if (!m) return ""; const rest = text.slice(m.index + m[0].length); const end = rest.search(/^## /m); return end < 0 ? rest : rest.slice(0, end); };
|
|
14
|
+
export const releaseSection = (doc) => sectionOf(doc, /^## `release` \(OPTIONAL\)\n/m);
|
|
15
|
+
const subsection = (sec, title) => { const i = sec.indexOf(title); if (i < 0) return ""; const rest = sec.slice(i + title.length); const e = rest.search(/^#{3,4} /m); return e < 0 ? rest : rest.slice(0, e); };
|
|
16
|
+
const policyRef = (sec) => { const i = sec.indexOf("### Policy reference"); if (i < 0) return ""; const rest = sec.slice(i + 3); const e = rest.search(/^### /m); return sec.slice(i, e < 0 ? undefined : i + 3 + e); };
|
|
17
|
+
|
|
18
|
+
/** Dotted key paths of the schema: `<name>` for map keys, `[]` for list items; every named key is a path. */
|
|
19
|
+
export function schemaPaths(schema) {
|
|
20
|
+
const out = [];
|
|
21
|
+
const walk = (n, p) => {
|
|
22
|
+
if (n.t === "object") for (const [k, c] of Object.entries(n.p)) { const q = p ? `${p}.${k}` : k; out.push(q); walk(c, q); }
|
|
23
|
+
else if (n.t === "map") walk(n.v, `${p}.<name>`);
|
|
24
|
+
else if (n.t === "array") walk(n.i, `${p}[]`);
|
|
25
|
+
};
|
|
26
|
+
walk(schema, "");
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
export const documentedPaths = (ref) => [...ref.matchAll(/^\| `([^`]+)` \|/gm)].map((m) => m[1]);
|
|
30
|
+
export function keyDrift(schema, doc) {
|
|
31
|
+
const want = schemaPaths(schema), have = documentedPaths(policyRef(releaseSection(doc)).split("\n#### ")[0]);
|
|
32
|
+
return { undocumented: want.filter((p) => !have.includes(p)), unknown: have.filter((p) => !want.includes(p)) };
|
|
33
|
+
}
|
|
34
|
+
/** Verbs of RELEASE_USAGE: the word after `forgedock release` in each segment, plus the control verbs. */
|
|
35
|
+
export function usageVerbs(usage) {
|
|
36
|
+
const verbs = new Set();
|
|
37
|
+
for (const seg of usage.split(" | ")) {
|
|
38
|
+
const m = /forgedock release ([a-z][a-z0-9-]*)(?: ([a-z|]+)(?: |$))?/.exec(seg);
|
|
39
|
+
if (!m) continue;
|
|
40
|
+
verbs.add(m[1]);
|
|
41
|
+
if (m[1] === "control" && m[2]) m[2].split("|").forEach((v) => verbs.add(v));
|
|
42
|
+
}
|
|
43
|
+
return [...verbs];
|
|
44
|
+
}
|
|
45
|
+
export const undocumentedVerbs = (usage, doc) => { const cli = subsection(policyRef(releaseSection(doc)), "#### CLI reference"); return usageVerbs(usage).filter((v) => !cli.includes(`\`forgedock release ${v}\``) && !new RegExp(`\`${v}\``).test(cli)); };
|
|
46
|
+
const STALE = [/not automated yet/, /`--watch`[^.\n]*has no effect/, /no `rollback` verb yet/];
|
|
47
|
+
export const stalePhrases = (text) => STALE.filter((re) => re.test(text)).map(String);
|
|
48
|
+
const fenced = (sub) => /```yaml\n([\s\S]*?)```/.exec(sub)?.[1] ?? "";
|
|
49
|
+
const deferredList = (sub) => [...sub.matchAll(/^- `([^`]+)`/gm)].map((m) => m[1]);
|
|
50
|
+
const norm = (k) => k.replace(/: /, "=");
|
|
51
|
+
|
|
52
|
+
describe("release docs (#5572)", () => {
|
|
53
|
+
it("every POLICY_SCHEMA key path is documented and every documented key exists", () => {
|
|
54
|
+
const d = keyDrift(POLICY_SCHEMA, DOC);
|
|
55
|
+
assert.deepEqual(d, { undocumented: [], unknown: [] });
|
|
56
|
+
assert.ok(schemaPaths(POLICY_SCHEMA).length > 100);
|
|
57
|
+
});
|
|
58
|
+
it("seeded: a schema key missing from the doc and a documented key missing from the schema both fail", () => {
|
|
59
|
+
const withNew = { ...POLICY_SCHEMA, p: { ...POLICY_SCHEMA.p, zzz_new_key: { t: "string" } } };
|
|
60
|
+
assert.deepEqual(keyDrift(withNew, DOC).undocumented, ["zzz_new_key"]);
|
|
61
|
+
const doc2 = DOC.replace("| `quarantine.max` |", "| `quarantine.bogus` |");
|
|
62
|
+
assert.deepEqual(keyDrift(POLICY_SCHEMA, doc2), { undocumented: ["quarantine.max"], unknown: ["quarantine.bogus"] });
|
|
63
|
+
});
|
|
64
|
+
it("the documented zero-config YAML equals INIT_PROFILE", () => {
|
|
65
|
+
const sub = subsection(policyRef(releaseSection(DOC)), "#### Zero-config profile");
|
|
66
|
+
assert.equal(fenced(sub), INIT_PROFILE);
|
|
67
|
+
assert.deepEqual(parsePolicy(fenced(sub)).policy, parsePolicy(INIT_PROFILE).policy);
|
|
68
|
+
});
|
|
69
|
+
it("the documented deferred keys equal DEFERRED_KEYS and are described as rejected", () => {
|
|
70
|
+
const sub = subsection(policyRef(releaseSection(DOC)), "#### Deferred keys");
|
|
71
|
+
assert.deepEqual(deferredList(sub).map(norm).sort(), DEFERRED_KEYS.map(norm).sort());
|
|
72
|
+
assert.match(sub, /rejected/);
|
|
73
|
+
});
|
|
74
|
+
it("every verb in RELEASE_USAGE is in the CLI reference, with intake and ci budget", () => {
|
|
75
|
+
assert.deepEqual(undocumentedVerbs(RELEASE_USAGE, DOC), []);
|
|
76
|
+
assert.ok(usageVerbs(RELEASE_USAGE).length >= 14);
|
|
77
|
+
const cli = subsection(policyRef(releaseSection(DOC)), "#### CLI reference");
|
|
78
|
+
for (const s of ["forgedock intake", "forgedock ci budget", "controls log", "ci flakes", "ci nightly"]) assert.ok(cli.includes(s), s);
|
|
79
|
+
});
|
|
80
|
+
it("seeded: an undocumented verb fails", () => {
|
|
81
|
+
assert.deepEqual(undocumentedVerbs(`${RELEASE_USAGE} | forgedock release zzzverb [--x]`, DOC), ["zzzverb"]);
|
|
82
|
+
});
|
|
83
|
+
it("stale phrases stay out of the release section and lean.md", () => {
|
|
84
|
+
assert.deepEqual(stalePhrases(releaseSection(DOC)), []);
|
|
85
|
+
assert.deepEqual(stalePhrases(LEAN), []);
|
|
86
|
+
assert.ok(releaseSection(DOC).length > 1000);
|
|
87
|
+
});
|
|
88
|
+
it("seeded: stale phrases are detected", () => {
|
|
89
|
+
assert.equal(stalePhrases("Review and fixes are not automated yet.").length, 1);
|
|
90
|
+
assert.equal(stalePhrases("`--watch` has no effect").length, 1);
|
|
91
|
+
assert.equal(stalePhrases("there is no `rollback` verb yet").length, 1);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
@@ -11,6 +11,8 @@ import { readActive } from "./release-ledger.mjs";
|
|
|
11
11
|
import { holdCheck } from "./release-control.mjs";
|
|
12
12
|
|
|
13
13
|
export const epochTrailer = (epoch) => `Forge-Epoch: ${epoch}`;
|
|
14
|
+
/** Landing-merge trailers of a fast lane (#5570): lane, release id and lease epoch, one per line. */
|
|
15
|
+
export const laneTrailers = ({ lane, release, epoch }) => [`Forge-Lane: ${lane}`, `Forge-Release: ${release}`, ...(epoch != null ? [epochTrailer(epoch)] : [])].join("\n");
|
|
14
16
|
export const epochMarker = (epoch) => `<!-- FORGE:EPOCH ${epoch} -->`;
|
|
15
17
|
|
|
16
18
|
/** @returns {{ok: true, epoch} | {fenced: true, current} | {unreadable: string}} */
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Release gate (#5561, epic #5549, invariants I1/I5): the merge to the default branch depends on the `forge/release-gate`
|
|
5
|
+
* check run produced by a workflow from real CI conclusions, never on an agent-posted GATE_PASS marker. `computeGate` is the
|
|
6
|
+
* pure function that workflow runs; `readReleaseGate` reads the check run (accepted only from the configured app);
|
|
7
|
+
* `mergeGuard` is the MERGING guard. Every function fails closed on unreadable input.
|
|
8
|
+
*/
|
|
9
|
+
import { checkChain } from "./release-snapshot.mjs";
|
|
10
|
+
import { assertRole } from "./release-credentials.mjs";
|
|
11
|
+
|
|
12
|
+
export const GATE_CHECK = "forge/release-gate";
|
|
13
|
+
const PASS_VERDICTS = ["pass", "approve", "approved", "approve for deploy"]; // the last is the review-staging verdict (bin/review-staging.mjs:650)
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Pass only when every required check concluded `success` on exactly `head` (neutral, skipped, missing and other-sha runs do
|
|
17
|
+
* not count) and the review verdict was recorded for `head`.
|
|
18
|
+
* @param {{checks: {name: string, conclusion: string, head?: string, sha?: string}[], required: string[], reviewVerdict: {head: string, verdict: string}, head: string}} p
|
|
19
|
+
* @returns {{pass: boolean, reasons: string[]}}
|
|
20
|
+
*/
|
|
21
|
+
export function computeGate({ checks, required, reviewVerdict, head } = {}) {
|
|
22
|
+
const no = (...reasons) => ({ pass: false, reasons });
|
|
23
|
+
if (typeof head !== "string" || !head) return no("unreadable input: no head sha");
|
|
24
|
+
if (!Array.isArray(checks)) return no("unreadable input: checks");
|
|
25
|
+
if (!Array.isArray(required) || !required.length || required.some((r) => typeof r !== "string" || !r)) return no("unreadable input: no required checks");
|
|
26
|
+
const reasons = [];
|
|
27
|
+
for (const name of required) {
|
|
28
|
+
const runs = checks.filter((c) => c?.name === name && (c.head ?? c.sha) === head);
|
|
29
|
+
if (!runs.length) reasons.push(`${name}: missing on ${head}`);
|
|
30
|
+
else if (!runs.every((c) => c.conclusion === "success")) reasons.push(`${name}: ${runs.find((c) => c.conclusion !== "success").conclusion ?? "unfinished"}, not success`);
|
|
31
|
+
}
|
|
32
|
+
if (!reviewVerdict || typeof reviewVerdict !== "object") reasons.push("review verdict: not recorded");
|
|
33
|
+
else if (reviewVerdict.head !== head) reasons.push(`review verdict is for ${reviewVerdict.head ?? "no head"}, not ${head}`);
|
|
34
|
+
else if (!PASS_VERDICTS.includes(String(reviewVerdict.verdict ?? "").toLowerCase())) reasons.push(`review verdict is ${reviewVerdict.verdict ?? "absent"}`);
|
|
35
|
+
return reasons.length ? { pass: false, reasons } : { pass: true, reasons: [] };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The `forge/release-gate` check run at `head`, accepted only from the configured gate app.
|
|
40
|
+
* @returns {Promise<{ok: true, conclusion: string} | {ok: false, why: string}>}
|
|
41
|
+
*/
|
|
42
|
+
export async function readReleaseGate({ io, repo, head, identity }) {
|
|
43
|
+
if (!identity?.app) return { ok: false, why: "no gate identity configured (credentials.gate_app)" };
|
|
44
|
+
let runs;
|
|
45
|
+
try { runs = JSON.parse(await io.gh(["api", `repos/${repo}/commits/${head}/check-runs`, "--jq", "[.check_runs[] | {name, conclusion, head: .head_sha, app: .app.slug}]"])); } catch (e) { return { ok: false, why: `cannot read check runs: ${String(e?.message ?? e).split("\n")[0]}` }; }
|
|
46
|
+
if (!Array.isArray(runs)) return { ok: false, why: "cannot read check runs: unexpected shape" };
|
|
47
|
+
const mine = runs.filter((c) => c?.name === GATE_CHECK && c.head === head);
|
|
48
|
+
if (!mine.length) return { ok: false, why: `no ${GATE_CHECK} on ${head}` };
|
|
49
|
+
const trusted = mine.filter((c) => c.app === identity.app);
|
|
50
|
+
if (!trusted.length) return { ok: false, why: `${GATE_CHECK} on ${head} was not posted by ${identity.app}` };
|
|
51
|
+
return { ok: true, conclusion: trusted.every((c) => c.conclusion === "success") ? "success" : String(trusted.find((c) => c.conclusion !== "success").conclusion ?? "pending") };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* MERGING guard (I1): plan approval current (hash match, I2), every required check green on the exact head, the gate status
|
|
56
|
+
* exists for that sha and passed, and head == cut sha + recorded picks (`checkChain`, including main-sync).
|
|
57
|
+
* @returns {Promise<{ok: true} | {ok: false, why: string}>}
|
|
58
|
+
*/
|
|
59
|
+
export async function mergeGuard({ io, repo, head, state, policy, staging }) {
|
|
60
|
+
const no = (why) => ({ ok: false, why });
|
|
61
|
+
const plan = state?.plan;
|
|
62
|
+
if (!policy) return no("release policy is unreadable");
|
|
63
|
+
// I2: a recorded plan must be approved at its current hash. No plan recorded (the plan step is a separate change) is accepted only under `plan.approval: auto`.
|
|
64
|
+
if (plan?.hash ? plan.approved_hash !== plan.hash : policy.plan?.approval !== "auto") return no("plan approval is not current (approved hash does not match the plan hash)");
|
|
65
|
+
const required = policy.ci?.required_checks;
|
|
66
|
+
let checks;
|
|
67
|
+
try { checks = JSON.parse(await io.gh(["api", `repos/${repo}/commits/${head}/check-runs`, "--jq", "[.check_runs[] | {name, conclusion, head: .head_sha}]"])); } catch (e) { return no(`cannot read check runs: ${String(e?.message ?? e).split("\n")[0]}`); }
|
|
68
|
+
const rev = state.steps?.review?.result;
|
|
69
|
+
const g = computeGate({ checks, required, reviewVerdict: rev ? { head: rev.head, verdict: rev.verdict } : null, head });
|
|
70
|
+
if (!g.pass) return no(`required checks not green: ${g.reasons.join("; ")}`);
|
|
71
|
+
const gate = await readReleaseGate({ io, repo, head, identity: { app: policy.credentials?.gate_app } });
|
|
72
|
+
if (!gate.ok) return no(gate.why);
|
|
73
|
+
if (gate.conclusion !== "success") return no(`${GATE_CHECK} is ${gate.conclusion}, not success`);
|
|
74
|
+
if (!state.release) return no("no FORGE:RELEASE record to verify the head against");
|
|
75
|
+
const chain = checkChain({ git: io.git, record: state.release, sha: head, staging, exact: true });
|
|
76
|
+
if (!chain.ok) return no(`release head ${head} is not snapshot + recorded cherry-picks: ${chain.why}`);
|
|
77
|
+
return { ok: true };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The sole in-repo writer of the `forge/release-gate` check run (the gate workflow normally posts it): refused unless the context holds the `gate` role (I12).
|
|
82
|
+
* @returns {Promise<{posted: true}>} throws `{refused}` for any other role
|
|
83
|
+
*/
|
|
84
|
+
export async function postReleaseGate({ io, ctx, repo, head, conclusion }) {
|
|
85
|
+
assertRole(ctx, "gate-post");
|
|
86
|
+
await io.gh(["api", `repos/${repo}/check-runs`, "-f", `name=${GATE_CHECK}`, "-f", `head_sha=${head}`, "-f", "status=completed", "-f", `conclusion=${conclusion}`]);
|
|
87
|
+
return { posted: true };
|
|
88
|
+
}
|