@intentius/chant 0.124.75 → 0.124.77

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.
Files changed (147) hide show
  1. package/dist/__fixtures__/agent-guard/plywood.d.ts +8 -0
  2. package/dist/__fixtures__/agent-guard/plywood.d.ts.map +1 -0
  3. package/dist/__fixtures__/agent-guard/plywood.js +19 -0
  4. package/dist/__fixtures__/agent-guard/terragucci.d.ts +8 -0
  5. package/dist/__fixtures__/agent-guard/terragucci.d.ts.map +1 -0
  6. package/dist/__fixtures__/agent-guard/terragucci.js +30 -0
  7. package/dist/__fixtures__/gated-ledger.d.ts +10 -0
  8. package/dist/__fixtures__/gated-ledger.d.ts.map +1 -0
  9. package/dist/__fixtures__/gated-ledger.js +51 -0
  10. package/dist/agent-guard.d.ts +143 -0
  11. package/dist/agent-guard.d.ts.map +1 -0
  12. package/dist/agent-guard.js +456 -0
  13. package/dist/ci-commit.d.ts +54 -3
  14. package/dist/ci-commit.d.ts.map +1 -1
  15. package/dist/ci-commit.js +69 -7
  16. package/dist/ci-own-jobs.d.ts +81 -0
  17. package/dist/ci-own-jobs.d.ts.map +1 -0
  18. package/dist/ci-own-jobs.js +234 -0
  19. package/dist/ci-product.d.ts +39 -0
  20. package/dist/ci-product.d.ts.map +1 -1
  21. package/dist/ci-product.js +40 -0
  22. package/dist/cli/handlers/approve.d.ts +5 -1
  23. package/dist/cli/handlers/approve.d.ts.map +1 -1
  24. package/dist/cli/handlers/approve.js +17 -11
  25. package/dist/cli/handlers/build.d.ts +1 -1
  26. package/dist/cli/handlers/build.d.ts.map +1 -1
  27. package/dist/cli/handlers/build.js +88 -2
  28. package/dist/cli/handlers/commit.d.ts.map +1 -1
  29. package/dist/cli/handlers/commit.js +3 -1
  30. package/dist/cli/handlers/notify-relay.d.ts +18 -1
  31. package/dist/cli/handlers/notify-relay.d.ts.map +1 -1
  32. package/dist/cli/handlers/notify-relay.js +90 -14
  33. package/dist/cli/handlers/pr.d.ts.map +1 -1
  34. package/dist/cli/handlers/pr.js +3 -1
  35. package/dist/cli/handlers/release.d.ts +9 -1
  36. package/dist/cli/handlers/release.d.ts.map +1 -1
  37. package/dist/cli/handlers/release.js +34 -6
  38. package/dist/cli/handlers/run-generate.d.ts.map +1 -1
  39. package/dist/cli/handlers/run-generate.js +2 -1
  40. package/dist/cli/main.d.ts.map +1 -1
  41. package/dist/cli/main.js +21 -1
  42. package/dist/cli/parse-args.d.ts.map +1 -1
  43. package/dist/cli/parse-args.js +60 -4
  44. package/dist/cli/registry.d.ts +16 -0
  45. package/dist/cli/registry.d.ts.map +1 -1
  46. package/dist/components/pr-env-components.d.ts +65 -0
  47. package/dist/components/pr-env-components.d.ts.map +1 -0
  48. package/dist/components/pr-env-components.js +163 -0
  49. package/dist/components/pr-policy.d.ts +15 -0
  50. package/dist/components/pr-policy.d.ts.map +1 -1
  51. package/dist/components/pr-policy.js +24 -1
  52. package/dist/components/release-compile.d.ts +15 -3
  53. package/dist/components/release-compile.d.ts.map +1 -1
  54. package/dist/components/release-compile.js +66 -15
  55. package/dist/gate-policy.d.ts +14 -1
  56. package/dist/gate-policy.d.ts.map +1 -1
  57. package/dist/gate-policy.js +16 -6
  58. package/dist/lexicon.d.ts +17 -1
  59. package/dist/lexicon.d.ts.map +1 -1
  60. package/dist/lexicon.js +1 -0
  61. package/dist/lifecycle/gated-op.d.ts +95 -0
  62. package/dist/lifecycle/gated-op.d.ts.map +1 -0
  63. package/dist/lifecycle/gated-op.js +96 -0
  64. package/dist/lifecycle/git.d.ts.map +1 -1
  65. package/dist/lifecycle/git.js +83 -2
  66. package/dist/notify-relay-repo.d.ts +131 -0
  67. package/dist/notify-relay-repo.d.ts.map +1 -0
  68. package/dist/notify-relay-repo.js +202 -0
  69. package/dist/notify-relay.d.ts +25 -1
  70. package/dist/notify-relay.d.ts.map +1 -1
  71. package/dist/notify-relay.js +28 -2
  72. package/dist/op/op-waves-capability.js +2 -2
  73. package/dist/policy-engine.d.ts +95 -0
  74. package/dist/policy-engine.d.ts.map +1 -0
  75. package/dist/policy-engine.js +158 -0
  76. package/dist/release-floors.d.ts +1 -1
  77. package/dist/release-floors.js +1 -1
  78. package/dist/state-export.d.ts +126 -0
  79. package/dist/state-export.d.ts.map +1 -0
  80. package/dist/state-export.js +157 -0
  81. package/dist/state-migration.d.ts +148 -0
  82. package/dist/state-migration.d.ts.map +1 -0
  83. package/dist/state-migration.js +147 -0
  84. package/dist/state-unlock.d.ts +167 -0
  85. package/dist/state-unlock.d.ts.map +1 -0
  86. package/dist/state-unlock.js +197 -0
  87. package/dist/wave-runtime.mjs +329 -329
  88. package/dist/workspace/declaration.schema.json +1 -1
  89. package/dist/workspace/release-workflow.d.ts +10 -0
  90. package/dist/workspace/release-workflow.d.ts.map +1 -1
  91. package/dist/workspace/release-workflow.js +8 -3
  92. package/package.json +1 -1
  93. package/src/__fixtures__/agent-guard/plywood.ts +27 -0
  94. package/src/__fixtures__/agent-guard/terragucci.ts +39 -0
  95. package/src/__fixtures__/gated-ledger.ts +58 -0
  96. package/src/agent-guard.test.ts +320 -0
  97. package/src/agent-guard.ts +548 -0
  98. package/src/ci-commit.test.ts +50 -2
  99. package/src/ci-commit.ts +93 -9
  100. package/src/ci-own-jobs.test.ts +109 -0
  101. package/src/ci-own-jobs.ts +253 -0
  102. package/src/ci-product.ts +81 -0
  103. package/src/cli/handlers/approve-cwd.test.ts +112 -0
  104. package/src/cli/handlers/approve.ts +22 -11
  105. package/src/cli/handlers/build-own-jobs.test.ts +80 -0
  106. package/src/cli/handlers/build-pr-loop-control.test.ts +88 -0
  107. package/src/cli/handlers/build-run-group.test.ts +60 -0
  108. package/src/cli/handlers/build.ts +83 -3
  109. package/src/cli/handlers/commit.ts +3 -0
  110. package/src/cli/handlers/notify-relay.ts +99 -17
  111. package/src/cli/handlers/pr.ts +3 -1
  112. package/src/cli/handlers/release-cut-archives.test.ts +21 -0
  113. package/src/cli/handlers/release.ts +31 -6
  114. package/src/cli/handlers/run-generate.ts +2 -1
  115. package/src/cli/main.ts +21 -1
  116. package/src/cli/parse-args.ts +45 -3
  117. package/src/cli/registry.ts +16 -0
  118. package/src/components/pr-env-components.test.ts +138 -0
  119. package/src/components/pr-env-components.ts +214 -0
  120. package/src/components/pr-policy.test.ts +41 -1
  121. package/src/components/pr-policy.ts +25 -1
  122. package/src/components/release-compile.test.ts +47 -0
  123. package/src/components/release-compile.ts +70 -13
  124. package/src/gate-policy-bundle.test.ts +14 -0
  125. package/src/gate-policy.test.ts +7 -0
  126. package/src/gate-policy.ts +22 -7
  127. package/src/lexicon.ts +18 -1
  128. package/src/lifecycle/gated-op.ts +158 -0
  129. package/src/lifecycle/git.test.ts +92 -0
  130. package/src/lifecycle/git.ts +71 -2
  131. package/src/notify-relay-repo.test.ts +284 -0
  132. package/src/notify-relay-repo.ts +234 -0
  133. package/src/notify-relay.test.ts +12 -0
  134. package/src/notify-relay.ts +30 -3
  135. package/src/op/op-waves-capability.ts +2 -2
  136. package/src/policy-engine.test.ts +163 -0
  137. package/src/policy-engine.ts +201 -0
  138. package/src/release-floors.ts +1 -1
  139. package/src/state-export.test.ts +125 -0
  140. package/src/state-export.ts +228 -0
  141. package/src/state-migration.test.ts +134 -0
  142. package/src/state-migration.ts +237 -0
  143. package/src/state-unlock.test.ts +166 -0
  144. package/src/state-unlock.ts +294 -0
  145. package/src/workspace/declaration.schema.json +1 -1
  146. package/src/workspace/release-workflow.test.ts +34 -0
  147. package/src/workspace/release-workflow.ts +17 -3
@@ -0,0 +1,163 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { gzipSync } from "node:zlib";
6
+ import { afterAll, describe, expect, test } from "vitest";
7
+ import {
8
+ CONFTEST_VERSION,
9
+ installPolicyEngine,
10
+ OPA_VERSION,
11
+ pinnedPolicyEngineSha256,
12
+ POLICY_ENGINE_INSTALL_FLOOR,
13
+ POLICY_ENGINE_PLATFORMS,
14
+ POLICY_ENGINE_SHA256,
15
+ policyEngineBinary,
16
+ policyEnginePlatform,
17
+ policyEngineRelease,
18
+ tarEntry,
19
+ } from "./policy-engine";
20
+ import { NEXT_RELEASE } from "./release-floors";
21
+
22
+ const scratch: string[] = [];
23
+ afterAll(() => {
24
+ for (const d of scratch) rmSync(d, { recursive: true, force: true });
25
+ });
26
+ const tmp = (): string => {
27
+ const d = mkdtempSync(join(tmpdir(), "policy-engine-"));
28
+ scratch.push(d);
29
+ return d;
30
+ };
31
+ const sha = (b: Uint8Array): string => createHash("sha256").update(b).digest("hex");
32
+
33
+ /** A ustar archive of `files`, as a release's `.tar.gz` holds them. */
34
+ function tarGz(files: Record<string, string>): Uint8Array {
35
+ const blocks: Buffer[] = [];
36
+ for (const [name, text] of Object.entries(files)) {
37
+ const body = Buffer.from(text);
38
+ const h = Buffer.alloc(512);
39
+ h.write(name, 0, "utf-8");
40
+ h.write("0000755\0", 100);
41
+ h.write("0000000\0", 108);
42
+ h.write("0000000\0", 116);
43
+ h.write(body.length.toString(8).padStart(11, "0") + "\0", 124);
44
+ h.write("00000000000\0", 136);
45
+ h.write("0", 156);
46
+ h.write("ustar\0", 257);
47
+ h.write("00", 263);
48
+ h.fill(" ", 148, 156);
49
+ let sum = 0;
50
+ for (const b of h) sum += b;
51
+ h.write(sum.toString(8).padStart(6, "0") + "\0 ", 148);
52
+ blocks.push(h, body, Buffer.alloc((512 - (body.length % 512)) % 512));
53
+ }
54
+ blocks.push(Buffer.alloc(1024));
55
+ return gzipSync(Buffer.concat(blocks));
56
+ }
57
+
58
+ /** A download that records what it was asked for and never reaches the network. */
59
+ function fakeDownload(bytes: Uint8Array): { download: (url: string) => Promise<Uint8Array>; urls: string[] } {
60
+ const urls: string[] = [];
61
+ return { urls, download: async (url) => (urls.push(url), bytes) };
62
+ }
63
+
64
+ describe("the pins (#4774)", () => {
65
+ test("every platform has a sha256 for the default conftest and OPA", () => {
66
+ for (const platform of POLICY_ENGINE_PLATFORMS) {
67
+ for (const engine of ["conftest", "opa"] as const) {
68
+ expect(pinnedPolicyEngineSha256(policyEngineRelease(engine, platform)), `${engine} ${platform}`).toMatch(/^[0-9a-f]{64}$/);
69
+ }
70
+ }
71
+ expect(Object.keys(POLICY_ENGINE_SHA256)).toHaveLength(POLICY_ENGINE_PLATFORMS.length * 2);
72
+ expect(POLICY_ENGINE_INSTALL_FLOOR).toBe(NEXT_RELEASE);
73
+ });
74
+
75
+ test("the release files are the ones each project publishes", () => {
76
+ expect(policyEngineRelease("conftest", "linux-x64").url).toBe(`https://github.com/open-policy-agent/conftest/releases/download/v${CONFTEST_VERSION}/conftest_${CONFTEST_VERSION}_Linux_x86_64.tar.gz`);
77
+ expect(policyEngineRelease("conftest", "darwin-arm64").asset).toBe(`conftest_${CONFTEST_VERSION}_Darwin_arm64.tar.gz`);
78
+ expect(policyEngineRelease("opa", "linux-arm64").url).toBe(`https://github.com/open-policy-agent/opa/releases/download/v${OPA_VERSION}/opa_linux_arm64_static`);
79
+ expect(policyEngineRelease("opa", "darwin-x64").asset).toBe("opa_darwin_amd64");
80
+ expect(policyEngineRelease("opa", "darwin-arm64").asset).toBe("opa_darwin_arm64_static");
81
+ expect(() => policyEngineRelease("opa", "linux-x64", "latest")).toThrow(/not a release version/);
82
+ });
83
+
84
+ test("the platform comes from node's names, and one with no pin is refused", () => {
85
+ expect(policyEnginePlatform("linux", "x64")).toBe("linux-x64");
86
+ expect(policyEnginePlatform("darwin", "arm64")).toBe("darwin-arm64");
87
+ expect(policyEnginePlatform("linux", "aarch64")).toBe("linux-arm64");
88
+ expect(() => policyEnginePlatform("win32", "x64")).toThrow(/put the engine on PATH/);
89
+ });
90
+ });
91
+
92
+ describe("installPolicyEngine (#4774)", () => {
93
+ test("unpacks conftest from its archive into the cache, once", async () => {
94
+ const cache = tmp();
95
+ const archive = tarGz({ LICENSE: "license", "README.md": "readme", conftest: "#!/bin/sh\necho conftest\n" });
96
+ const fake = fakeDownload(archive);
97
+ const options = { cache, platform: "linux-x64" as const, version: "9.9.9", sha256: { "linux-x64": sha(archive) }, download: fake.download };
98
+ const bin = await installPolicyEngine("conftest", options);
99
+ expect(bin).toBe(join(cache, "conftest-9.9.9-linux-x64", "conftest"));
100
+ expect(readFileSync(bin, "utf-8")).toBe("#!/bin/sh\necho conftest\n");
101
+ expect(statSync(bin).mode & 0o777).toBe(0o755);
102
+ expect(fake.urls).toEqual(["https://github.com/open-policy-agent/conftest/releases/download/v9.9.9/conftest_9.9.9_Linux_x86_64.tar.gz"]);
103
+ expect(await installPolicyEngine("conftest", options)).toBe(bin);
104
+ expect(fake.urls).toHaveLength(1);
105
+ expect(readdirSync(join(cache, "conftest-9.9.9-linux-x64"))).toEqual(["conftest"]);
106
+ });
107
+
108
+ test("takes OPA's bare binary as it is", async () => {
109
+ const cache = tmp();
110
+ const body = new Uint8Array(Buffer.from("opa binary"));
111
+ const fake = fakeDownload(body);
112
+ const bin = await installPolicyEngine("opa", { cache, platform: "darwin-arm64", version: "1.0.0", sha256: { "darwin-arm64": sha(body) }, download: fake.download });
113
+ expect(readFileSync(bin, "utf-8")).toBe("opa binary");
114
+ expect(fake.urls).toEqual(["https://github.com/open-policy-agent/opa/releases/download/v1.0.0/opa_darwin_arm64_static"]);
115
+ });
116
+
117
+ test("checks the default release against chant's pin, and keeps nothing that does not match", async () => {
118
+ const cache = tmp();
119
+ const fake = fakeDownload(new Uint8Array(Buffer.from("not opa")));
120
+ await expect(installPolicyEngine("opa", { cache, platform: "linux-x64", download: fake.download })).rejects.toThrow(
121
+ new RegExp(`opa ${OPA_VERSION} from .*opa_linux_amd64_static does not match its pinned sha256 \\(want ${POLICY_ENGINE_SHA256[`opa-${OPA_VERSION}-linux-x64`]}`),
122
+ );
123
+ expect(fake.urls).toHaveLength(1);
124
+ expect(readdirSync(cache)).toEqual([]);
125
+ });
126
+
127
+ test("fetches nothing for a release with no pin", async () => {
128
+ const fake = fakeDownload(new Uint8Array());
129
+ await expect(installPolicyEngine("conftest", { cache: tmp(), platform: "linux-arm64", version: "0.1.0", download: fake.download })).rejects.toThrow(/records no sha256 for conftest 0.1.0 on linux-arm64/);
130
+ await expect(installPolicyEngine("conftest", { cache: tmp(), platform: "linux-arm64", version: "0.1.0", sha256: { "linux-x64": "a".repeat(64) }, download: fake.download })).rejects.toThrow(/records no sha256/);
131
+ expect(fake.urls).toEqual([]);
132
+ });
133
+
134
+ test("an archive without the binary is refused", async () => {
135
+ const cache = tmp();
136
+ const archive = tarGz({ "README.md": "readme" });
137
+ await expect(installPolicyEngine("conftest", { cache, platform: "linux-x64", version: "9.9.9", sha256: { "linux-x64": sha(archive) }, download: fakeDownload(archive).download })).rejects.toThrow(/holds no conftest binary/);
138
+ expect(existsSync(join(cache, "conftest-9.9.9-linux-x64", "conftest"))).toBe(false);
139
+ });
140
+ });
141
+
142
+ describe("policyEngineBinary (#4774)", () => {
143
+ test("uses the engine on PATH when it answers, and the pinned release otherwise", async () => {
144
+ const body = new Uint8Array(Buffer.from("opa"));
145
+ const fake = fakeDownload(body);
146
+ const pin = { platform: "linux-x64" as const, version: "1.0.0", sha256: { "linux-x64": sha(body) }, download: fake.download };
147
+ expect(await policyEngineBinary("opa", { ...pin, cache: tmp(), probe: () => true })).toBe("opa");
148
+ expect(fake.urls).toEqual([]);
149
+ const cache = tmp();
150
+ expect(await policyEngineBinary("opa", { ...pin, cache, probe: () => false })).toBe(join(cache, "opa-1.0.0-linux-x64", "opa"));
151
+ expect(await policyEngineBinary("opa", { ...pin, cache: tmp(), probe: () => true, pinnedOnly: true })).toMatch(/opa-1\.0\.0-linux-x64\/opa$/);
152
+ expect(fake.urls).toHaveLength(2);
153
+ });
154
+ });
155
+
156
+ describe("tarEntry", () => {
157
+ test("finds a file at the top or under ./, and nothing else", async () => {
158
+ const { gunzipSync } = await import("node:zlib");
159
+ const tar = gunzipSync(tarGz({ "./conftest": "a", "sub/conftest": "b" }));
160
+ expect(Buffer.from(tarEntry(tar, "conftest")!).toString()).toBe("a");
161
+ expect(tarEntry(gunzipSync(tarGz({ "sub/conftest": "b" })), "conftest")).toBeUndefined();
162
+ });
163
+ });
@@ -0,0 +1,201 @@
1
+ /**
2
+ * The policy engine's binary (#4774): conftest or OPA at a pinned release,
3
+ * fetched once, checked against the sha256 chant records for it, and kept in
4
+ * a cache directory.
5
+ *
6
+ * `ci.policy.install: true` makes the pull-request jobs and Op waves use it
7
+ * (`./components/pr-policy.ts`). A product that runs the engine itself calls
8
+ * {@link policyEngineBinary} with its own `download`, `cache` and `exec`, so
9
+ * it keeps no download code. Tests pass `download`, so nothing reaches the
10
+ * network.
11
+ *
12
+ * The digests are the release's own: conftest's `checksums.txt` and OPA's
13
+ * `.sha256` files, checked against the archives themselves when the pins
14
+ * were set. A download that does not match its pin is never written to the
15
+ * cache. A caller pinning another release passes its `version` and the
16
+ * sha256 for the platform; chant fetches nothing without a pin.
17
+ *
18
+ * Like `./gate-policy.ts` this module imports only node built-ins (and the
19
+ * release-floor constant), so a product can bundle it.
20
+ */
21
+
22
+ import { spawnSync } from "node:child_process";
23
+ import { createHash, randomBytes } from "node:crypto";
24
+ import { chmodSync, existsSync, mkdirSync, renameSync, writeFileSync } from "node:fs";
25
+ import { tmpdir } from "node:os";
26
+ import { join } from "node:path";
27
+ import { gunzipSync } from "node:zlib";
28
+ import { NEXT_RELEASE } from "./release-floors";
29
+
30
+ /** The first chant with `ci.policy.install` and `@intentius/chant/policy-engine` (#4774). Products feature-detect on it. */
31
+ export const POLICY_ENGINE_INSTALL_FLOOR = NEXT_RELEASE;
32
+
33
+ export type PolicyEngineName = "conftest" | "opa";
34
+
35
+ /** The platforms chant has pins for. */
36
+ export type PolicyEnginePlatform = "linux-x64" | "linux-arm64" | "darwin-x64" | "darwin-arm64";
37
+ export const POLICY_ENGINE_PLATFORMS: readonly PolicyEnginePlatform[] = ["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64"];
38
+
39
+ /** The conftest release chant installs. */
40
+ export const CONFTEST_VERSION = "0.71.1";
41
+ /** The OPA release chant installs. */
42
+ export const OPA_VERSION = "1.21.4";
43
+
44
+ /**
45
+ * The sha256 of each pinned release file, as `<engine>-<version>-<platform>`,
46
+ * copied from the release's checksums (conftest's `checksums.txt`, OPA's
47
+ * `<asset>.sha256`) and checked against the files. The files are conftest's
48
+ * `conftest_<v>_<OS>_<arch>.tar.gz` and OPA's static builds, except on
49
+ * darwin-x64, where OPA builds none and the file is `opa_darwin_amd64`. Add
50
+ * a release's lines when moving a default version.
51
+ */
52
+ export const POLICY_ENGINE_SHA256: Readonly<Record<string, string>> = {
53
+ "conftest-0.71.1-linux-x64": "c3f6b2a753bd56e377a1e51a95ae3e057f926f2e9139f7d5b5dfbbaf810f7985",
54
+ "conftest-0.71.1-linux-arm64": "218c682e110ae7e826dc14a746a6f9b43eb782643dbe730b771fd305634e3f47",
55
+ "conftest-0.71.1-darwin-x64": "a309853b5763c18486768157442d440248ee683b20a2aa1f6b28214e818bd780",
56
+ "conftest-0.71.1-darwin-arm64": "e1cc50d2590b6c5e3da6912666a71264bae82d60bdd62d7ae2b99971ccc8eedd",
57
+ "opa-1.21.4-linux-x64": "2ab571f367f293bb19523b76f92f1945bbf245003392c7f392903f95c2b9b630",
58
+ "opa-1.21.4-linux-arm64": "810aa96e44f1f852d044888cf830324e44eafd0f510345339011347ab4deaab1",
59
+ "opa-1.21.4-darwin-x64": "8802bd39bc14b58a705e6b3d4f4dd14f7f24ee657f0362c737338be243190c7e",
60
+ "opa-1.21.4-darwin-arm64": "4c105208a9282f590385bccbe600875c011f0894ccf9431782dfe855e1f99aa6",
61
+ };
62
+
63
+ /** One release file of one engine for one platform. */
64
+ export interface PolicyEngineRelease {
65
+ engine: PolicyEngineName;
66
+ version: string;
67
+ platform: PolicyEnginePlatform;
68
+ /** The release file's name. OPA ships a bare binary, conftest a `.tar.gz` holding `conftest`. */
69
+ asset: string;
70
+ url: string;
71
+ /** Whether the file is a `.tar.gz` to unpack. */
72
+ archive: boolean;
73
+ }
74
+
75
+ const VERSION = /^\d+\.\d+\.\d+$/;
76
+ const SHA256 = /^[0-9a-f]{64}$/;
77
+
78
+ /** The release file of `engine` at `version` for `platform`. A version is a plain semver. */
79
+ export function policyEngineRelease(engine: PolicyEngineName, platform: PolicyEnginePlatform, version = engine === "opa" ? OPA_VERSION : CONFTEST_VERSION): PolicyEngineRelease {
80
+ if (!VERSION.test(version)) throw new Error(`${engine} version ${JSON.stringify(version)} is not a release version such as ${engine === "opa" ? OPA_VERSION : CONFTEST_VERSION}`);
81
+ const [os, cpu] = platform.split("-") as ["linux" | "darwin", "x64" | "arm64"];
82
+ if (engine === "conftest") {
83
+ const asset = `conftest_${version}_${os === "linux" ? "Linux" : "Darwin"}_${cpu === "x64" ? "x86_64" : "arm64"}.tar.gz`;
84
+ return { engine, version, platform, asset, url: `https://github.com/open-policy-agent/conftest/releases/download/v${version}/${asset}`, archive: true };
85
+ }
86
+ // OPA builds no static binary for darwin on amd64.
87
+ const asset = `opa_${os}_${cpu === "x64" ? "amd64" : "arm64"}${platform === "darwin-x64" ? "" : "_static"}`;
88
+ return { engine, version, platform, asset, url: `https://github.com/open-policy-agent/opa/releases/download/v${version}/${asset}`, archive: false };
89
+ }
90
+
91
+ /** The sha256 chant records for a release file, or undefined when it records none. */
92
+ export function pinnedPolicyEngineSha256(release: PolicyEngineRelease): string | undefined {
93
+ return POLICY_ENGINE_SHA256[`${release.engine}-${release.version}-${release.platform}`];
94
+ }
95
+
96
+ /** This process's platform as chant pins it. Throws on one with no pin. */
97
+ export function policyEnginePlatform(platform: string = process.platform, arch: string = process.arch): PolicyEnginePlatform {
98
+ const os = platform === "linux" || platform === "darwin" ? platform : undefined;
99
+ const cpu = arch === "x64" || arch === "x86_64" || arch === "amd64" ? "x64" : arch === "arm64" || arch === "aarch64" ? "arm64" : undefined;
100
+ if (!os || !cpu) throw new Error(`chant pins conftest and OPA for ${POLICY_ENGINE_PLATFORMS.join(", ")}, not ${platform}-${arch}; put the engine on PATH instead`);
101
+ return `${os}-${cpu}`;
102
+ }
103
+
104
+ /** Where installed engines are kept by default: `CHANT_TOOL_CACHE`, else `chant-tools` in the temp directory. */
105
+ export function defaultPolicyEngineCache(): string {
106
+ return process.env.CHANT_TOOL_CACHE || join(tmpdir(), "chant-tools");
107
+ }
108
+
109
+ export interface InstallPolicyEngineOptions {
110
+ /** Fetches a release file. Default: Node's fetch. Tests pass their own. */
111
+ download?: (url: string) => Promise<Uint8Array>;
112
+ /** Where installed engines are kept. Default {@link defaultPolicyEngineCache}. */
113
+ cache?: string;
114
+ /** The platform to fetch for. Default this process's ({@link policyEnginePlatform}). */
115
+ platform?: PolicyEnginePlatform;
116
+ /** Another release than chant's default. Needs `sha256` for the platform. */
117
+ version?: string;
118
+ /** The release file's sha256 by platform, in place of {@link POLICY_ENGINE_SHA256}. */
119
+ sha256?: Partial<Record<PolicyEnginePlatform, string>>;
120
+ }
121
+
122
+ async function fetchBytes(url: string): Promise<Uint8Array> {
123
+ const res = await fetch(url);
124
+ if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`);
125
+ return new Uint8Array(await res.arrayBuffer());
126
+ }
127
+
128
+ /** The bytes of the regular file `name` (at the top, or under `./`) in a tar stream. Undefined when it holds none. */
129
+ export function tarEntry(tar: Uint8Array, name: string): Uint8Array | undefined {
130
+ const text = (from: number, len: number): string => {
131
+ const raw = Buffer.from(tar.subarray(from, from + len)).toString("utf-8");
132
+ const nul = raw.indexOf("\0");
133
+ return nul < 0 ? raw : raw.slice(0, nul);
134
+ };
135
+ let at = 0;
136
+ while (at + 512 <= tar.length) {
137
+ if (tar.subarray(at, at + 512).every((b) => b === 0)) return undefined;
138
+ const prefix = text(at + 345, 155);
139
+ const entry = (prefix ? `${prefix}/` : "") + text(at, 100);
140
+ const size = parseInt(text(at + 124, 12).trim() || "0", 8);
141
+ const type = text(at + 156, 1);
142
+ const body = at + 512;
143
+ if ((type === "" || type === "0") && entry.replace(/^\.\//, "") === name) return tar.subarray(body, body + size);
144
+ at = body + Math.ceil(size / 512) * 512;
145
+ }
146
+ return undefined;
147
+ }
148
+
149
+ /**
150
+ * Install `engine` into the cache and return the binary's path. A binary
151
+ * already installed there for that release and platform is returned without
152
+ * a download. Throws when the platform has no pin, the download fails, or
153
+ * the file does not match its pin.
154
+ */
155
+ export async function installPolicyEngine(engine: PolicyEngineName, options: InstallPolicyEngineOptions = {}): Promise<string> {
156
+ const platform = options.platform ?? policyEnginePlatform();
157
+ const release = policyEngineRelease(engine, platform, options.version);
158
+ const want = options.sha256 ? options.sha256[platform] : pinnedPolicyEngineSha256(release);
159
+ if (want === undefined) throw new Error(`chant records no sha256 for ${engine} ${release.version} on ${platform} (${release.asset}); pass sha256 for it, or use ${engine === "opa" ? OPA_VERSION : CONFTEST_VERSION}`);
160
+ if (!SHA256.test(want)) throw new Error(`the sha256 for ${release.asset} is not 64 hex digits`);
161
+ const dir = join(options.cache ?? defaultPolicyEngineCache(), `${engine}-${release.version}-${platform}`);
162
+ const bin = join(dir, engine);
163
+ if (existsSync(bin)) return bin;
164
+ const body = await (options.download ?? fetchBytes)(release.url);
165
+ const sum = createHash("sha256").update(body).digest("hex");
166
+ if (sum !== want) throw new Error(`${engine} ${release.version} from ${release.url} does not match its pinned sha256 (want ${want}, got ${sum}); not running it`);
167
+ const binary = release.archive ? tarEntry(gunzipSync(body), engine) : body;
168
+ if (!binary) throw new Error(`${release.asset} holds no ${engine} binary`);
169
+ mkdirSync(dir, { recursive: true });
170
+ // Written beside its final name and renamed, so a job that stops halfway leaves no binary behind.
171
+ const part = join(dir, `.${engine}.${randomBytes(6).toString("hex")}`);
172
+ writeFileSync(part, binary);
173
+ chmodSync(part, 0o755);
174
+ renameSync(part, bin);
175
+ return bin;
176
+ }
177
+
178
+ /** Whether the engine on PATH answers. Default: runs `conftest --version` or `opa version`. */
179
+ export type PolicyEngineProbe = (engine: PolicyEngineName) => boolean;
180
+
181
+ export const defaultPolicyEngineProbe: PolicyEngineProbe = (engine) => {
182
+ const r = spawnSync(engine, engine === "opa" ? ["version"] : ["--version"], { stdio: "ignore" });
183
+ return !r.error && r.status === 0;
184
+ };
185
+
186
+ export interface PolicyEngineBinaryOptions extends InstallPolicyEngineOptions {
187
+ /** Checks the engine on PATH. Default {@link defaultPolicyEngineProbe}. */
188
+ probe?: PolicyEngineProbe;
189
+ /** Skip the PATH and always use the pinned release. Default false. */
190
+ pinnedOnly?: boolean;
191
+ }
192
+
193
+ /**
194
+ * The engine's executable: its name when the one on PATH answers (an image
195
+ * that carries the engine pays nothing), else the pinned release installed
196
+ * by {@link installPolicyEngine}.
197
+ */
198
+ export async function policyEngineBinary(engine: PolicyEngineName, options: PolicyEngineBinaryOptions = {}): Promise<string> {
199
+ if (!options.pinnedOnly && (options.probe ?? defaultPolicyEngineProbe)(engine)) return engine;
200
+ return installPolicyEngine(engine, options);
201
+ }
@@ -19,4 +19,4 @@
19
19
  * this constant to the next patch (#4501). The check fails while a floor
20
20
  * still names this constant after its version shipped.
21
21
  */
22
- export const NEXT_RELEASE = "0.124.74";
22
+ export const NEXT_RELEASE = "0.124.77";
@@ -0,0 +1,125 @@
1
+ /**
2
+ * #4762: the engine-neutral state export, on an in-memory version source and
3
+ * an in-memory gated-request ledger. Nothing reaches a store or git.
4
+ */
5
+ import { mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { describe, expect, test } from "vitest";
9
+ import { fakeLedger } from "./__fixtures__/gated-ledger";
10
+ import { NEXT_RELEASE } from "./release-floors";
11
+ import { exportStateVersion, exportRefusal, STATE_EXPORT_FLOOR, StateExportError, type StateVersionSource } from "./state-export";
12
+
13
+ const NO_CI = {};
14
+
15
+ function source(versions: Record<string, string>, current?: string): StateVersionSource & { reads: string[] } {
16
+ const reads: string[] = [];
17
+ return {
18
+ location: "s3://states/net.tfstate",
19
+ reads,
20
+ current: async () => (current ? { exists: true, versionId: current } : Object.keys(versions).length ? { exists: true, off: "bucket versioning is off" } : { exists: false }),
21
+ hasVersion: async (id) => id in versions,
22
+ readVersion: async (id) => {
23
+ reads.push(id);
24
+ return versions[id];
25
+ },
26
+ };
27
+ }
28
+
29
+ const outside = (): string => mkdtempSync(join(tmpdir(), "chant-export-test-"));
30
+
31
+ const base = (ledger: ReturnType<typeof fakeLedger>, src: StateVersionSource, extra: Record<string, unknown> = {}) => ({
32
+ subject: "net",
33
+ by: "ana",
34
+ source: src,
35
+ words: { op: "tf-state-export", approveCommand: (s: string, d: string) => `product approve export ${s} --plan ${d}` },
36
+ rules: { mode: "ledger" as const },
37
+ ledger,
38
+ env: NO_CI,
39
+ now: "2026-11-08T09:00:00Z",
40
+ ...extra,
41
+ });
42
+
43
+ describe("exportStateVersion", () => {
44
+ test("asks without reading the state, then writes the approved version once, mode 0600, and records its digest", async () => {
45
+ const ledger = fakeLedger();
46
+ const src = source({ v1: '{"serial":1}', v2: '{"serial":2}' }, "v2");
47
+ const out = join(outside(), "net.tfstate");
48
+ const first = await exportStateVersion(base(ledger, src, { out }));
49
+ expect(first).toMatchObject({ status: "waiting", exit: 3, version: "v2", location: "s3://states/net.tfstate" });
50
+ expect(first.status === "waiting" && first.command).toBe(`product approve export net --plan ${first.digest}`);
51
+ expect(src.reads).toEqual([]);
52
+
53
+ ledger.approve("bo");
54
+ const second = await exportStateVersion(base(ledger, src, { out, now: "2026-11-08T12:00:00Z" }));
55
+ expect(second).toMatchObject({ status: "written", exit: 0, file: out, version: "v2", approvedBy: "bo", digest: first.digest });
56
+ expect(readFileSync(out, "utf-8")).toBe('{"serial":2}');
57
+ expect(statSync(out).mode & 0o777).toBe(0o600);
58
+ expect(ledger.writes).toEqual(["pending", "applied", "finished:applied"]);
59
+ expect(ledger.details[0]).toMatchObject({ by: "ana", version_id: "v2", approved_by: "bo", location: "s3://states/net.tfstate" });
60
+ expect(String(ledger.details[0]!.content_digest)).toMatch(/^sha256:[0-9a-f]{64}$/);
61
+ expect(JSON.stringify(ledger.details)).not.toContain("serial");
62
+
63
+ const third = await exportStateVersion(base(ledger, src, { out: join(outside(), "again.tfstate") }));
64
+ expect(third).toMatchObject({ status: "spent", exit: 1 });
65
+ expect(src.reads).toEqual(["v2"]);
66
+ });
67
+
68
+ test("an approval by the requester does not count", async () => {
69
+ const ledger = fakeLedger();
70
+ ledger.approve("ana");
71
+ const r = await exportStateVersion(base(ledger, source({ v1: "{}" }, "v1"), { out: join(outside(), "s") }));
72
+ expect(r).toMatchObject({ status: "refused", exit: 3 });
73
+ });
74
+
75
+ test("with no destination the file goes to a new private directory, named by the product", async () => {
76
+ const ledger = fakeLedger();
77
+ ledger.approve("bo");
78
+ const r = await exportStateVersion(base(ledger, source({ "v/1": "{}" }), { version: "v/1", words: { op: "tf-state-export", fileName: (s: string, v: string) => `${s}.${v.replace("/", "_")}.tfstate`, tmpPrefix: "product-export-" } }));
79
+ expect(r.status).toBe("written");
80
+ if (r.status !== "written") return;
81
+ expect(r.file).toMatch(/product-export-[^/]+\/net\.v_1\.tfstate$/);
82
+ });
83
+
84
+ test("refuses a version the store does not keep, a store with no versions, and no state, before asking", async () => {
85
+ const ledger = fakeLedger();
86
+ await expect(exportStateVersion(base(ledger, source({ v1: "{}" }), { version: "v9" }))).rejects.toThrow(/has no version v9/);
87
+ await expect(exportStateVersion(base(ledger, source({ v1: "{}" })))).rejects.toThrow(/keeps no versions.*bucket versioning is off/);
88
+ await expect(exportStateVersion(base(ledger, source({})))).rejects.toThrow(/holds no state/);
89
+ expect(ledger.writes).toEqual([]);
90
+ });
91
+
92
+ test("refuses a CI job, a destination inside a git working tree, and a file that is there", async () => {
93
+ const ledger = fakeLedger();
94
+ const src = source({ v1: "{}" }, "v1");
95
+ await expect(exportStateVersion(base(ledger, src, { env: { GITLAB_CI: "true" } }))).rejects.toThrow(/GITLAB_CI is set/);
96
+ const repo = outside();
97
+ mkdirSync(join(repo, ".git"));
98
+ mkdirSync(join(repo, "sub"));
99
+ await expect(exportStateVersion(base(ledger, src, { out: join(repo, "sub", "net.tfstate") }))).rejects.toBeInstanceOf(StateExportError);
100
+ expect(exportRefusal(join(repo, "sub", "net.tfstate"))).toMatch(/inside the git working tree/);
101
+ const there = join(outside(), "there");
102
+ writeFileSync(there, "x");
103
+ await expect(exportStateVersion(base(ledger, src, { out: there }))).rejects.toThrow(/never writes over a file/);
104
+ const ok = await exportStateVersion(base(ledger, src, { env: { GITLAB_CI: "true" }, allowCi: true, out: join(outside(), "ci") }));
105
+ expect(ok.status).toBe("waiting");
106
+ });
107
+
108
+ test("a version deleted while the request waited fails the request, and writes nothing", async () => {
109
+ const ledger = fakeLedger();
110
+ const versions: Record<string, string> = { v1: "{}" };
111
+ const src = source(versions, "v1");
112
+ const out = join(outside(), "gone");
113
+ await exportStateVersion(base(ledger, src, { out }));
114
+ ledger.approve("bo");
115
+ delete versions.v1;
116
+ src.hasVersion = async () => true;
117
+ const r = await exportStateVersion(base(ledger, src, { out, version: "v1" }));
118
+ expect(r).toMatchObject({ status: "failed", exit: 1 });
119
+ expect(ledger.writes.at(-1)).toBe("finished:failed");
120
+ });
121
+
122
+ test("its floor is the next release", () => {
123
+ expect(STATE_EXPORT_FLOOR).toBe(NEXT_RELEASE);
124
+ });
125
+ });