forgedock 1.59.2 → 1.60.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/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 +12 -5
- package/bin/lean/conformance.test.mjs +30 -2
- 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 +123 -17
- package/bin/lean/lean.test.mjs +154 -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 +5 -2
- package/bin/lean/preflight.test.mjs +7 -0
- 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 +94 -0
- package/bin/lean/validate-catalog.test.mjs +42 -0
- package/bin/pool/agent.mjs +4 -1
- package/bin/pool/lane-tools.mjs +115 -0
- package/bin/pool/lane-tools.test.mjs +26 -0
- package/bin/pool/warm.mjs +1 -1
- 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/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
|
@@ -0,0 +1,194 @@
|
|
|
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 { readFileSync, existsSync } from "node:fs";
|
|
6
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { CAPABILITIES, REFUSED, capability, conductorConfig, conductorGuard, renderConductor, installConductor, recover, recoverFromCli, CONDUCTOR_WORKFLOW_PATH } from "./release-conductor.mjs";
|
|
9
|
+
import { fenced } from "./release-fence.mjs";
|
|
10
|
+
import { renderReleaseStatus } from "./release-status.mjs";
|
|
11
|
+
import { initFromCli } from "./release-config.mjs";
|
|
12
|
+
|
|
13
|
+
const ID = "r20260101-000000-1", NOW = 1_700_000_000_000;
|
|
14
|
+
const b64 = (o) => ({ content: Buffer.from(typeof o === "string" ? o : JSON.stringify(o)).toString("base64") });
|
|
15
|
+
const POLICY = { trust: { actors: ["github-actions[bot]"] }, deploy: { pipelines: { full: { workflow: "deploy.yml" } } }, rollback: { full_workflow: "rb.yml" } };
|
|
16
|
+
|
|
17
|
+
/** Fake GitHub: `_active`, the lease heartbeat comment and the release ledger; `commits` records every ledger write. */
|
|
18
|
+
function world({ active = {}, state, heartbeatAgeS = 3600, policy = POLICY } = {}) {
|
|
19
|
+
const w = { active: { epoch: 4, lease: { holder: "host-1", release: ID, epoch: 4, commentId: 9 }, ...active }, commits: [], gh: [], holds: [] };
|
|
20
|
+
w.state = state ?? { id: ID, repo: "o/r", lane: "release", steps: { "post-merge": { result: { merge: "bbbb2222" } } }, deploy: { phase: "DEPLOYING", merge: "bbbb2222", target: { sha: "aaaa1111" } } };
|
|
21
|
+
const io = {
|
|
22
|
+
now: () => NOW, print: () => {},
|
|
23
|
+
api: async (m, path, body) => {
|
|
24
|
+
if (/contents\/active\.json\?ref=_active$/.test(path)) return b64(w.active);
|
|
25
|
+
if (/controls\.jsonl/.test(path)) return b64("");
|
|
26
|
+
if (/issues\/comments\/9$/.test(path)) return { updated_at: new Date(NOW - heartbeatAgeS * 1000).toISOString() };
|
|
27
|
+
if (/git\/ref\/heads\//.test(path)) return { object: { sha: "h0" } };
|
|
28
|
+
if (/contents\/state\.json/.test(path)) return b64(w.state);
|
|
29
|
+
if (m === "POST" && /git\/trees$/.test(path)) { w.commits.push(JSON.parse(body.tree[0].content)); return { sha: "t1" }; }
|
|
30
|
+
if (/git\/commits\/h/.test(path)) return { tree: { sha: "t0" } };
|
|
31
|
+
if (m === "POST" && /git\/commits$/.test(path)) return { sha: "c1" };
|
|
32
|
+
if (m === "PATCH" && /git\/refs/.test(path)) return {};
|
|
33
|
+
if (m === "POST" && /issues\/\d+\/comments$/.test(path)) return { id: 1 };
|
|
34
|
+
throw new Error(`unrouted ${m} ${path}`);
|
|
35
|
+
},
|
|
36
|
+
gh: async (a) => { w.gh.push(a); if (a[0] === "issue" && a[1] === "list") return "[]"; if (a[0] === "issue" && a[1] === "create") return "https://github.com/o/r/issues/42"; return ""; },
|
|
37
|
+
};
|
|
38
|
+
const fence = { lctx: { io, repo: "o/r", credential: "driver" }, lease: { holder: "conductor-gh", release: ID, epoch: 5 }, record: async () => {}, now: () => "t" };
|
|
39
|
+
const takeFence = async () => ({ fence });
|
|
40
|
+
return { w, io, policy, takeFence, ctx: { io, repo: "o/r", id: ID, policy, def: "main", actor: "github-actions[bot]", host: "gh" } };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
describe("capability matrix (#5564)", () => {
|
|
44
|
+
it("github-only actions run, host-only actions wait, plan/build/review/merge/patch are refused", () => {
|
|
45
|
+
for (const [a, c] of Object.entries(CAPABILITIES)) {
|
|
46
|
+
const r = capability(a, POLICY);
|
|
47
|
+
assert.ok(c.where === "host" ? r.host : r.run, a);
|
|
48
|
+
}
|
|
49
|
+
for (const a of REFUSED) assert.ok(capability(a, POLICY).refused, a);
|
|
50
|
+
assert.ok(capability("nonsense", POLICY).refused);
|
|
51
|
+
});
|
|
52
|
+
it("full rollback runs only when the rollback workflow is configured", () => {
|
|
53
|
+
assert.ok(capability("rollback_full", POLICY).run);
|
|
54
|
+
assert.match(capability("rollback_full", {}).why, /rollback\.full_workflow/);
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
describe("recover (#5564)", () => {
|
|
59
|
+
it("fresh lease: does nothing", async () => {
|
|
60
|
+
const { ctx, takeFence } = world({ heartbeatAgeS: 10 });
|
|
61
|
+
let took = 0;
|
|
62
|
+
const r = await recover(ctx, { takeFence: async (...a) => { took++; return takeFence(...a); } });
|
|
63
|
+
assert.match(r.noop, /fresh/);
|
|
64
|
+
assert.equal(took, 0);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it("I17: stale lease at DEPLOYING: takes epoch + 1, replays the deploy and finishes", async () => {
|
|
68
|
+
const { ctx, w, takeFence } = world();
|
|
69
|
+
const seen = [];
|
|
70
|
+
const r = await recover(ctx, { takeFence, deploy: async (c) => { seen.push(c.fence.lease.epoch); c.state.deploy.phase = "LIVE"; return { live: true }; } });
|
|
71
|
+
assert.equal(r.live, true);
|
|
72
|
+
assert.equal(r.epoch, 5);
|
|
73
|
+
assert.deepEqual(seen, [5]);
|
|
74
|
+
assert.equal(w.commits.at(-1).deploy.phase, "LIVE");
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("deploy blocked, rollback workflow configured: rolls back to the recorded target", async () => {
|
|
78
|
+
const { ctx, takeFence } = world();
|
|
79
|
+
let to = null;
|
|
80
|
+
const r = await recover(ctx, { takeFence, deploy: async () => ({ blocked: true, reason: "LIVE_CHECK failed" }), rollback: async (_c, a) => { to = a.to; return { ok: true, rung: "full" }; } });
|
|
81
|
+
assert.equal(r.ended, "rolled-back");
|
|
82
|
+
assert.equal(to, "full");
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it("rollback workflow unconfigured: holds at last healthy and files needs-agent", async () => {
|
|
86
|
+
const { ctx, w, takeFence } = world({ policy: { ...POLICY, rollback: undefined } });
|
|
87
|
+
const r = await recover(ctx, { takeFence, deploy: async () => ({ blocked: true, reason: "LIVE_CHECK failed" }), rollback: async () => { throw new Error("must not roll back"); } });
|
|
88
|
+
assert.equal(r.ended, "held");
|
|
89
|
+
assert.ok(w.gh.some((a) => a[0] === "issue" && a[1] === "create" && a.includes("needs-agent")));
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it("a hold from the deploy (freeze, deterministic failure) never rolls back blindly", async () => {
|
|
93
|
+
const { ctx, takeFence } = world();
|
|
94
|
+
const r = await recover(ctx, { takeFence, deploy: async () => ({ blocked: true, reason: "freeze set", hold: "x" }), rollback: async () => { throw new Error("must not roll back"); } });
|
|
95
|
+
assert.equal(r.ended, "held");
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it("HELD: with a hold set the conductor performs no action", async () => {
|
|
99
|
+
const { ctx, w } = world({ active: { holds: { [ID]: { reason: "owner" } } } });
|
|
100
|
+
const r = await recover(ctx, { takeFence: async () => { throw new Error("must not take the lease"); }, deploy: async () => { throw new Error("must not act"); } });
|
|
101
|
+
assert.match(r.refused, /held/);
|
|
102
|
+
assert.equal(w.commits.length, 0);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it("refuses a non-allowlisted actor and an unmerged ledger", async () => {
|
|
106
|
+
const a = world();
|
|
107
|
+
assert.match((await recover({ ...a.ctx, actor: "mallory" }, { takeFence: a.takeFence })).refused, /trust\.actors/);
|
|
108
|
+
const b = world({ state: { id: ID, steps: {} } });
|
|
109
|
+
assert.match((await recover(b.ctx, { takeFence: b.takeFence })).refused, /merged/);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it("zombie: the old driver's epoch is refused after the takeover", async () => {
|
|
113
|
+
const { w, io } = world();
|
|
114
|
+
w.active = { epoch: 5, lease: { holder: "conductor-gh", epoch: 5 } };
|
|
115
|
+
let ran = 0;
|
|
116
|
+
const r = await fenced({ lctx: { io, repo: "o/r" }, lease: { holder: "host-1", epoch: 4 }, record: async () => {}, now: () => "t" }, { action: "dispatch", key: "k" }, async () => { ran++; });
|
|
117
|
+
assert.match(r.refused, /fenced/);
|
|
118
|
+
assert.equal(ran, 0);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it("host-only SLI soak is listed as waiting and shown by release status", async () => {
|
|
122
|
+
const { ctx, takeFence } = world({ policy: { ...POLICY, verify: { workflow: "v.yml", slis: [{ name: "p99" }] } } });
|
|
123
|
+
const seen = {};
|
|
124
|
+
const r = await recover(ctx, { takeFence, deploy: async (c) => { seen.slis = c.config.verify.slis; c.state.deploy.phase = "LIVE"; return { live: true }; } });
|
|
125
|
+
assert.deepEqual(r.waiting, ["sli_soak (host-only)"]);
|
|
126
|
+
assert.deepEqual(seen.slis, []);
|
|
127
|
+
const s = { id: ID, repo: "o/r", status: "running", source: "ledger", steps: [], waiting_host: r.waiting, next_actions: [] };
|
|
128
|
+
assert.match(renderReleaseStatus(s), /waiting on a host: sli_soak/);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it("recoverFromCli maps outcomes to exit codes", async () => {
|
|
132
|
+
const { w, io, policy } = world({ heartbeatAgeS: 5 });
|
|
133
|
+
const out = []; io.print = (l) => out.push(l);
|
|
134
|
+
assert.equal(await recoverFromCli([ID, "--repo", "o/r"], { io, policy, def: "main", actor: "github-actions[bot]" }), 0);
|
|
135
|
+
assert.match(out[0], /nothing to do/);
|
|
136
|
+
w.active.holds = { [ID]: {} };
|
|
137
|
+
w.active.lease.commentId = undefined; w.active.lease.expires = 0;
|
|
138
|
+
assert.equal(await recoverFromCli([ID, "--repo", "o/r"], { io, policy, def: "main", actor: "github-actions[bot]" }), 1);
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
describe("conductor template (#5564)", () => {
|
|
143
|
+
const tpl = readFileSync(new URL("../../templates/github-actions/forge-conductor.yml", import.meta.url), "utf8");
|
|
144
|
+
const scopes = JSON.parse(readFileSync(new URL("../../templates/github-actions/forge-conductor.scopes.json", import.meta.url), "utf8"));
|
|
145
|
+
const rendered = renderConductor({ version: "1.59.1", cron: "0 */6 * * *", workflows: ["Deploy"] });
|
|
146
|
+
|
|
147
|
+
it("pins an exact forgedock version", () => {
|
|
148
|
+
assert.match(tpl, /forgedock@__FORGEDOCK_VERSION__/);
|
|
149
|
+
assert.match(rendered, /forgedock@1\.59\.1 release recover/);
|
|
150
|
+
assert.doesNotMatch(rendered, /__[A-Z_]+__|@latest/);
|
|
151
|
+
});
|
|
152
|
+
it("has the four triggers and the configured watchdog cron", () => {
|
|
153
|
+
for (const t of ["workflow_run:", "deployment_status:", "workflow_dispatch:", "schedule:"]) assert.ok(rendered.includes(t), t);
|
|
154
|
+
assert.match(rendered, /types: \[completed\]/);
|
|
155
|
+
assert.match(rendered, /cron: '0 \*\/6 \* \* \*'/);
|
|
156
|
+
assert.match(renderConductor({ version: "1.0.0", cron: "0 3 * * *", workflows: ["A", "B"] }), /workflows: \["A","B"\]/);
|
|
157
|
+
});
|
|
158
|
+
it("the no-op path runs before any checkout step", () => {
|
|
159
|
+
const find = tpl.indexOf("_active"), checkout = tpl.indexOf("actions/checkout");
|
|
160
|
+
assert.ok(find > 0 && checkout > find);
|
|
161
|
+
assert.ok(tpl.indexOf("if: steps.active.outputs.release != ''") < checkout);
|
|
162
|
+
});
|
|
163
|
+
it("token scopes: the workflow permissions equal the scope file; no secrets, no merge, no PR write", () => {
|
|
164
|
+
const block = /permissions:\n((?: \w[\w-]*: \w+\n)+)/.exec(tpl)[1];
|
|
165
|
+
const perms = Object.fromEntries(block.trim().split("\n").map((l) => l.trim().split(": ")));
|
|
166
|
+
assert.deepEqual(perms, scopes.permissions);
|
|
167
|
+
assert.ok(!("pull-requests" in perms) && !("id-token" in perms));
|
|
168
|
+
assert.doesNotMatch(tpl, /secrets\.(?!GITHUB_TOKEN)|pr merge|gh api[^\n]*merge/);
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
describe("bootstrap guard and init --conductor (#5564)", () => {
|
|
173
|
+
const on = { controls: { conductor: { enabled: true } } };
|
|
174
|
+
it("refuses while the workflow is absent from the default branch", () => {
|
|
175
|
+
const gitHas = (has) => ({ git: (a) => { if (!has) throw new Error("not found"); assert.equal(a[1], `origin/main:${CONDUCTOR_WORKFLOW_PATH}`); return "x"; } });
|
|
176
|
+
assert.match(conductorGuard({ io: gitHas(false), policy: on, def: "main" }), /absent from origin\/main/);
|
|
177
|
+
assert.equal(conductorGuard({ io: gitHas(true), policy: on, def: "main" }), null);
|
|
178
|
+
assert.equal(conductorGuard({ io: gitHas(false), policy: {}, def: "main" }), null);
|
|
179
|
+
});
|
|
180
|
+
it("conductorConfig defaults the watchdog to every 6 h", () => {
|
|
181
|
+
assert.equal(conductorConfig({}).watchdogCron, "0 */6 * * *");
|
|
182
|
+
assert.equal(conductorConfig({ controls: { conductor: { watchdog_cron: "0 1 * * *" } } }).watchdogCron, "0 1 * * *");
|
|
183
|
+
});
|
|
184
|
+
it("init --conductor writes the pinned workflow, never overwrites, and plain init is unchanged", async () => {
|
|
185
|
+
const cwd = tmpDir("conductor-");
|
|
186
|
+
const out = [], io = { print: (l) => out.push(l) };
|
|
187
|
+
assert.equal(await initFromCli(["--conductor"], { io, cwd }), 0);
|
|
188
|
+
const { version } = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
|
|
189
|
+
assert.ok(readFileSync(join(cwd, CONDUCTOR_WORKFLOW_PATH), "utf8").includes(`forgedock@${version} release recover`));
|
|
190
|
+
assert.equal(installConductor({ io, cwd, policy: null }), 1);
|
|
191
|
+
assert.equal(initFromCli([], { io, cwd }), 1); // policy file now exists
|
|
192
|
+
assert.ok(existsSync(join(cwd, ".forge/release.yaml")));
|
|
193
|
+
});
|
|
194
|
+
});
|
|
@@ -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" };
|