@caelo-cms/provisioning 0.12.16 → 0.12.18

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 (74) hide show
  1. package/dist/adopt-existing.d.ts +18 -0
  2. package/dist/adopt-existing.d.ts.map +1 -1
  3. package/dist/adopt-existing.js +46 -1
  4. package/dist/adopt-existing.js.map +1 -1
  5. package/dist/agent-db.js +1522 -101
  6. package/dist/audit-job-setup.d.ts +0 -9
  7. package/dist/audit-job-setup.d.ts.map +1 -1
  8. package/dist/audit-job-setup.js +17 -27
  9. package/dist/audit-job-setup.js.map +1 -1
  10. package/dist/converge-job-gcp.d.ts +0 -7
  11. package/dist/converge-job-gcp.d.ts.map +1 -1
  12. package/dist/converge-job-gcp.js +1 -36
  13. package/dist/converge-job-gcp.js.map +1 -1
  14. package/dist/infra-contract.d.ts +1 -1
  15. package/dist/infra-contract.d.ts.map +1 -1
  16. package/dist/infra-contract.js +11 -1
  17. package/dist/infra-contract.js.map +1 -1
  18. package/dist/operator-access.d.ts +23 -0
  19. package/dist/operator-access.d.ts.map +1 -1
  20. package/dist/operator-access.js +62 -2
  21. package/dist/operator-access.js.map +1 -1
  22. package/dist/owner-email.d.ts +79 -0
  23. package/dist/owner-email.d.ts.map +1 -0
  24. package/dist/owner-email.js +170 -0
  25. package/dist/owner-email.js.map +1 -0
  26. package/dist/reporting-job-catalog.d.ts.map +1 -1
  27. package/dist/reporting-job-catalog.js +3 -2
  28. package/dist/reporting-job-catalog.js.map +1 -1
  29. package/dist/stack-contract.d.ts +12 -7
  30. package/dist/stack-contract.d.ts.map +1 -1
  31. package/dist/stack-contract.js +24 -6
  32. package/dist/stack-contract.js.map +1 -1
  33. package/dist/wizard.d.ts.map +1 -1
  34. package/dist/wizard.js +30 -12
  35. package/dist/wizard.js.map +1 -1
  36. package/dist/wizards/gcp-cost.d.ts.map +1 -1
  37. package/dist/wizards/gcp-cost.js +7 -2
  38. package/dist/wizards/gcp-cost.js.map +1 -1
  39. package/dist/wizards/gcp-install-job.d.ts +24 -0
  40. package/dist/wizards/gcp-install-job.d.ts.map +1 -1
  41. package/dist/wizards/gcp-install-job.js +119 -13
  42. package/dist/wizards/gcp-install-job.js.map +1 -1
  43. package/dist/wizards/gcp-pulumi.d.ts +0 -6
  44. package/dist/wizards/gcp-pulumi.d.ts.map +1 -1
  45. package/dist/wizards/gcp-pulumi.js +0 -7
  46. package/dist/wizards/gcp-pulumi.js.map +1 -1
  47. package/dist/wizards/gcp.js +0 -1
  48. package/dist/wizards/gcp.js.map +1 -1
  49. package/package.json +2 -2
  50. package/src/admin-memory.test.ts +49 -11
  51. package/src/adopt-existing.test.ts +190 -0
  52. package/src/adopt-existing.ts +56 -1
  53. package/src/audit-job-setup.test.ts +14 -39
  54. package/src/audit-job-setup.ts +17 -35
  55. package/src/converge-job-gcp.test.ts +2 -5
  56. package/src/converge-job-gcp.ts +1 -46
  57. package/src/infra-contract.test.ts +4 -3
  58. package/src/infra-contract.ts +11 -1
  59. package/src/operator-access.ts +81 -2
  60. package/src/owner-email.test.ts +302 -0
  61. package/src/owner-email.ts +214 -0
  62. package/src/reporting-job-catalog.ts +3 -2
  63. package/src/reporting-job-setup.test.ts +1 -1
  64. package/src/stack-contract.ts +25 -7
  65. package/src/stack-converge.test.ts +43 -2
  66. package/src/wizard.ts +30 -10
  67. package/src/wizards/gcp-cost.ts +8 -2
  68. package/src/wizards/gcp-install-job.test.ts +180 -0
  69. package/src/wizards/gcp-install-job.ts +130 -12
  70. package/src/wizards/gcp-pulumi.ts +0 -7
  71. package/src/wizards/gcp.ts +0 -1
  72. package/stacks/azure/index.ts +4 -0
  73. package/stacks/gcp/index.ts +11 -0
  74. package/stacks/gcp-firebase/index.ts +11 -0
@@ -48,7 +48,7 @@
48
48
  */
49
49
 
50
50
  import { ensureCloudSqlIamUser } from "./cloudsql-iam-user.js";
51
- import { gcloud as defaultGcloud, type GcloudResult } from "./gcloud.js";
51
+ import { gcloud as defaultGcloud, type GcloudResult, isGcloudNotFound } from "./gcloud.js";
52
52
  import { type GcloudRunner, realSleep, runWithRetry, type Sleep } from "./gcloud-retry.js";
53
53
  import {
54
54
  gcpNamePrefix,
@@ -130,6 +130,85 @@ export function installIapAllowlist(ownerEmail: string): string[] {
130
130
  return [`user:${ownerEmail.trim().toLowerCase()}`];
131
131
  }
132
132
 
133
+ /** The sync job's env var listing {@link installIapAllowlist}: the install's fixed IAP members. */
134
+ export const STATIC_MEMBERS_ENV = "CAELO_OPERATOR_ACCESS_STATIC_MEMBERS";
135
+
136
+ /**
137
+ * Why install.json's Owner email does not match the IAP members the
138
+ * deployed operator-access job admits ({@link ensureOperatorAccessSync}
139
+ * deploys them as `installIapAllowlist(ownerEmail)`), or null when it does.
140
+ * Read from `gcloud run jobs describe --format=json` (v1 or v2 shape).
141
+ * Anything it cannot read is a mismatch, never a match.
142
+ */
143
+ export function deployedOwnerMismatch(describeJson: string, ownerEmail: string): string | null {
144
+ let parsed: unknown;
145
+ try {
146
+ parsed = JSON.parse(describeJson);
147
+ } catch {
148
+ return "the operator-access job's description is not JSON";
149
+ }
150
+ const p = parsed as {
151
+ spec?: {
152
+ template?: {
153
+ spec?: {
154
+ template?: { spec?: { containers?: { env?: { name?: string; value?: string }[] }[] } };
155
+ };
156
+ };
157
+ };
158
+ template?: { template?: { containers?: { env?: { name?: string; value?: string }[] }[] } };
159
+ };
160
+ const env =
161
+ p.spec?.template?.spec?.template?.spec?.containers?.[0]?.env ??
162
+ p.template?.template?.containers?.[0]?.env ??
163
+ [];
164
+ const deployed = env.find((e) => e.name === STATIC_MEMBERS_ENV)?.value;
165
+ if (deployed === undefined) return `the operator-access job sets no ${STATIC_MEMBERS_ENV}`;
166
+ const want = installIapAllowlist(ownerEmail).join(",");
167
+ const have = deployed
168
+ .split(",")
169
+ .map((m) => m.trim().toLowerCase())
170
+ .filter(Boolean)
171
+ .sort()
172
+ .join(",");
173
+ if (have !== [...installIapAllowlist(ownerEmail)].sort().join(",")) {
174
+ return `the admin admits ${deployed || "nobody"}, the records would make it ${want}`;
175
+ }
176
+ return null;
177
+ }
178
+
179
+ /**
180
+ * {@link deployedOwnerMismatch} against the operator-access job deployed in
181
+ * the project now. A job that does not exist is a mismatch too: the install
182
+ * never got as far as admitting its Owner.
183
+ *
184
+ * @throws when the job cannot be read for another reason, with what to check
185
+ */
186
+ export async function readDeployedOwnerMismatch(
187
+ run: GcloudRunner,
188
+ target: {
189
+ readonly projectId: string;
190
+ readonly region: string;
191
+ readonly env: string;
192
+ readonly ownerEmail: string;
193
+ },
194
+ ): Promise<string | null> {
195
+ const job = operatorAccessJobName(target.env);
196
+ const r = await run([
197
+ "run",
198
+ "jobs",
199
+ "describe",
200
+ job,
201
+ `--region=${target.region}`,
202
+ `--project=${target.projectId}`,
203
+ "--format=json",
204
+ ]);
205
+ if (r.ok) return deployedOwnerMismatch(r.stdout, target.ownerEmail);
206
+ if (isGcloudNotFound(r.stderr)) return `the operator-access job ${job} does not exist`;
207
+ throw new Error(
208
+ `Could not read the operator-access job ${job} in ${target.projectId}: ${r.stderr.trim()}. Check that gcloud is signed in as an Owner of the project (gcloud auth login), then run the installer again.`,
209
+ );
210
+ }
211
+
133
212
  /** Database role migration 0239 creates for the job. */
134
213
  export const OPERATOR_ACCESS_DB_ROLE = "operator_access_reader";
135
214
 
@@ -461,7 +540,7 @@ export async function ensureOperatorAccessSync(
461
540
  const envVars = [
462
541
  `CAELO_OPERATOR_ACCESS_IAP_WEB=${iapWebPath(target.resource, backendServiceId)}`,
463
542
  `CAELO_MCP_IAP_SERVICE_ACCOUNT=${mcpSa}`,
464
- `CAELO_OPERATOR_ACCESS_STATIC_MEMBERS=${installIapAllowlist(target.ownerEmail).join(",")}`,
543
+ `${STATIC_MEMBERS_ENV}=${installIapAllowlist(target.ownerEmail).join(",")}`,
465
544
  `CAELO_OPERATOR_ACCESS_DB_HOST=${target.databaseHost}`,
466
545
  `${OPERATOR_OAUTH_CLIENT_SECRET_ENV}=${operatorOAuthClientSecretResource(projectId, env)}`,
467
546
  ...(target.mcpSigners && target.mcpSigners.length > 0
@@ -0,0 +1,302 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * owner-email.ts: a resumed install corrects its Owner email. The decision
5
+ * against fake prompts, then a resumed local install and a bucket-backed one
6
+ * (job mode's store) on real install-state files, as the wizard settles it
7
+ * before the install's converge pass reads install.json.
8
+ */
9
+
10
+ import { describe, expect, it } from "bun:test";
11
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
12
+ import { tmpdir } from "node:os";
13
+ import { join, resolve } from "node:path";
14
+ import {
15
+ decideOwnerEmail,
16
+ type OwnerEmailPrompts,
17
+ ownerEmailChangeLines,
18
+ ownerEmailProblem,
19
+ sameOwnerEmail,
20
+ } from "./owner-email.js";
21
+
22
+ /** Prompts that answer `answer` / `confirmed` and record what they were asked. */
23
+ function fakePrompts(answer: string | null = null, confirmed: boolean | null = true) {
24
+ const asked: string[] = [];
25
+ const confirms: string[] = [];
26
+ const notes: string[][] = [];
27
+ const prompts: OwnerEmailPrompts = {
28
+ ask: async (recorded) => {
29
+ asked.push(recorded);
30
+ return answer;
31
+ },
32
+ confirm: async (message) => {
33
+ confirms.push(message);
34
+ return confirmed;
35
+ },
36
+ note: (lines) => notes.push([...lines]),
37
+ };
38
+ return { prompts, asked, confirms, notes };
39
+ }
40
+
41
+ const WRONG = "owner@acme.exmaple";
42
+ const RIGHT = "owner@acme.example";
43
+
44
+ describe("decideOwnerEmail — an install not provisioned yet", () => {
45
+ const unfinished = { recorded: WRONG, provisioned: false };
46
+
47
+ it("takes --owner-email as a plain correction: no prompt, no confirmation", async () => {
48
+ const f = fakePrompts();
49
+ const d = await decideOwnerEmail(
50
+ { ...unfinished, requested: ` ${RIGHT} `, nonInteractive: false },
51
+ f.prompts,
52
+ );
53
+ expect(d).toEqual({ kind: "change", from: WRONG, to: RIGHT });
54
+ expect([f.asked, f.confirms, f.notes]).toEqual([[], [], []]);
55
+ });
56
+
57
+ it("asks with the recorded address prefilled, and takes the corrected answer", async () => {
58
+ const f = fakePrompts(RIGHT);
59
+ const d = await decideOwnerEmail({ ...unfinished, nonInteractive: false }, f.prompts);
60
+ expect(f.asked).toEqual([WRONG]);
61
+ expect(d).toEqual({ kind: "change", from: WRONG, to: RIGHT });
62
+ });
63
+
64
+ it("keeps the address when the answer is the recorded one, in any case", async () => {
65
+ const f = fakePrompts("OWNER@acme.EXMAPLE");
66
+ expect(await decideOwnerEmail({ ...unfinished, nonInteractive: false }, f.prompts)).toEqual({
67
+ kind: "keep",
68
+ });
69
+ });
70
+
71
+ it("keeps the recorded address non-interactively without --owner-email, without asking", async () => {
72
+ const f = fakePrompts(RIGHT);
73
+ expect(await decideOwnerEmail({ ...unfinished, nonInteractive: true }, f.prompts)).toEqual({
74
+ kind: "keep",
75
+ });
76
+ expect(f.asked).toEqual([]);
77
+ });
78
+
79
+ it("refuses a malformed --owner-email and a cancelled prompt", async () => {
80
+ expect(
81
+ await decideOwnerEmail(
82
+ { ...unfinished, requested: "owner-at-acme", nonInteractive: true },
83
+ fakePrompts().prompts,
84
+ ),
85
+ ).toEqual({
86
+ kind: "refuse",
87
+ error: "--owner-email owner-at-acme: Looks like an invalid email.",
88
+ });
89
+ expect(
90
+ await decideOwnerEmail({ ...unfinished, nonInteractive: false }, fakePrompts(null).prompts),
91
+ ).toEqual({ kind: "cancelled" });
92
+ });
93
+ });
94
+
95
+ describe("decideOwnerEmail — a provisioned install, which may have an Owner", () => {
96
+ const provisioned = { recorded: WRONG, provisioned: true };
97
+
98
+ it("says what the change does and leaves alone, then asks to confirm", async () => {
99
+ const f = fakePrompts(RIGHT, true);
100
+ const d = await decideOwnerEmail({ ...provisioned, nonInteractive: false }, f.prompts);
101
+ expect(d).toEqual({ kind: "change", from: WRONG, to: RIGHT });
102
+ expect(f.notes).toEqual([ownerEmailChangeLines(WRONG, RIGHT)]);
103
+ expect(f.notes[0]?.join("\n")).toContain("Settings → Users");
104
+ expect(f.confirms).toEqual([`Change the Owner email to ${RIGHT}?`]);
105
+ });
106
+
107
+ it("keeps the recorded address when the change is declined, and stops on a cancel", async () => {
108
+ const declined = fakePrompts(RIGHT, false);
109
+ expect(
110
+ await decideOwnerEmail({ ...provisioned, nonInteractive: false }, declined.prompts),
111
+ ).toEqual({ kind: "keep" });
112
+ const cancelled = fakePrompts(RIGHT, null);
113
+ expect(
114
+ await decideOwnerEmail({ ...provisioned, nonInteractive: false }, cancelled.prompts),
115
+ ).toEqual({ kind: "cancelled" });
116
+ });
117
+
118
+ it("takes --owner-email non-interactively as the decision, and still says what it does", async () => {
119
+ const f = fakePrompts();
120
+ const d = await decideOwnerEmail(
121
+ { ...provisioned, requested: RIGHT, nonInteractive: true },
122
+ f.prompts,
123
+ );
124
+ expect(d).toEqual({ kind: "change", from: WRONG, to: RIGHT });
125
+ expect(f.notes).toHaveLength(1);
126
+ expect(f.confirms).toEqual([]);
127
+ });
128
+ });
129
+
130
+ describe("ownerEmailProblem / sameOwnerEmail", () => {
131
+ it("validates like the first prompt and compares like IAP", () => {
132
+ expect(ownerEmailProblem("")).toBe("Email is required");
133
+ expect(ownerEmailProblem("a@b")).toBe("Looks like an invalid email");
134
+ expect(ownerEmailProblem(" a@b.c ")).toBeUndefined();
135
+ expect(sameOwnerEmail(" A@B.c", "a@b.C ")).toBe(true);
136
+ expect(sameOwnerEmail("a@b.c", "a@b.d")).toBe(false);
137
+ });
138
+ });
139
+
140
+ /**
141
+ * A resumed install on real install-state files. installRoot() resolves ~
142
+ * through os.homedir(), which reads HOME once at process start, so each case
143
+ * runs in a child bun process with its own HOME (as install-version.test.ts
144
+ * does); a bucket-backed install's ops bucket is a directory there.
145
+ */
146
+ describe("settleResumedOwnerEmail — what the resumed install's pass reads", () => {
147
+ const PROJECT = "acme-site";
148
+ const INSTALL_ID = "gcp-firebase-acme-site";
149
+ const meta = {
150
+ installId: INSTALL_ID,
151
+ provider: "gcp-firebase",
152
+ projectId: PROJECT,
153
+ domain: "acme.example",
154
+ ownerEmail: WRONG,
155
+ region: "europe-west1",
156
+ createdAt: "2026-11-26T00:00:00.000Z",
157
+ };
158
+ const bucketBacked = {
159
+ ...meta,
160
+ stateBackend: {
161
+ kind: "gcs",
162
+ bucket: `${PROJECT}-caelo-ops`,
163
+ kmsKey: `projects/${PROJECT}/locations/europe-west1/keyRings/caelo/cryptoKeys/pulumi-state`,
164
+ },
165
+ };
166
+ const unfinished = { lastCompletedStep: "apis", steps: { apis: {} } };
167
+ const provisioned = {
168
+ lastCompletedStep: `pulumi-up-${PROJECT}`,
169
+ steps: { [`pulumi-up-${PROJECT}`]: {} },
170
+ };
171
+
172
+ /**
173
+ * Settle the Owner email of the install in a child process (prompt answer
174
+ * `answer`, confirmation `confirmed`, `--owner-email` `requested`), then
175
+ * read what the converge pass reads: install.json and the IAP members it
176
+ * derives (the stacks' iapAllowlist, the operator-access job's static
177
+ * members).
178
+ */
179
+ function resume(start: {
180
+ readonly install: Record<string, unknown>;
181
+ readonly progress: unknown;
182
+ readonly answer?: string | null;
183
+ readonly confirmed?: boolean;
184
+ readonly requested?: string;
185
+ readonly nonInteractive?: boolean;
186
+ }) {
187
+ const home = mkdtempSync(join(tmpdir(), "caelo-owner-email-"));
188
+ try {
189
+ const mirror = join(home, `.caelo-${INSTALL_ID}`);
190
+ const objects = join(home, "bucket");
191
+ const gcs = start.install.stateBackend !== undefined;
192
+ mkdirSync(mirror, { recursive: true });
193
+ mkdirSync(objects);
194
+ writeFileSync(join(mirror, "install.json"), JSON.stringify(start.install));
195
+ writeFileSync(join(gcs ? objects : mirror, "progress.json"), JSON.stringify(start.progress));
196
+ if (gcs) writeFileSync(join(objects, "install.json"), JSON.stringify(start.install));
197
+ const script = `
198
+ const { existsSync, readFileSync, writeFileSync } = await import("node:fs");
199
+ const m = await import(${JSON.stringify(resolve(import.meta.dir, "install-state.ts"))});
200
+ const o = await import(${JSON.stringify(resolve(import.meta.dir, "owner-email.ts"))});
201
+ const a = await import(${JSON.stringify(resolve(import.meta.dir, "operator-access.ts"))});
202
+ const objects = ${JSON.stringify(objects)};
203
+ const at = (url) => objects + "/" + url.split("/").pop();
204
+ m.setStateStoreGcloud((args, input) => {
205
+ const [, verb, x, y] = args;
206
+ if (verb === "cat") {
207
+ return existsSync(at(x))
208
+ ? { ok: true, stdout: readFileSync(at(x), "utf8"), stderr: "", exitCode: 0 }
209
+ : { ok: false, stdout: "", stderr: "One or more URLs matched no objects.", exitCode: 1 };
210
+ }
211
+ if (verb === "cp" && x === "-") {
212
+ writeFileSync(at(y), input ?? "");
213
+ return { ok: true, stdout: "", stderr: "", exitCode: 0 };
214
+ }
215
+ throw new Error("unexpected gcloud " + args.join(" "));
216
+ });
217
+ const asked = [];
218
+ const confirms = [];
219
+ const prompts = {
220
+ ask: async (recorded) => { asked.push(recorded); return ${JSON.stringify(start.answer ?? null)}; },
221
+ confirm: async (message) => { confirms.push(message); return ${JSON.stringify(start.confirmed ?? true)}; },
222
+ note: () => {},
223
+ };
224
+ const recorded = m.currentMetadata(m.readLocalMetadata(${JSON.stringify(INSTALL_ID)}));
225
+ const ownerEmail = await o.settleResumedOwnerEmail(
226
+ recorded,
227
+ { ${start.requested ? `requested: ${JSON.stringify(start.requested)}, ` : ""}nonInteractive: ${start.nonInteractive === true} },
228
+ prompts,
229
+ );
230
+ const now = m.readMetadata(${JSON.stringify(INSTALL_ID)});
231
+ writeFileSync(${JSON.stringify(join(home, "out.json"))}, JSON.stringify({
232
+ ownerEmail,
233
+ recorded: now.ownerEmail,
234
+ iapAllowlist: a.installIapAllowlist(now.ownerEmail),
235
+ asked,
236
+ confirms,
237
+ }));`;
238
+ const child = Bun.spawnSync([process.execPath, "-e", script], {
239
+ env: { ...process.env, HOME: home },
240
+ stdout: "pipe",
241
+ stderr: "pipe",
242
+ });
243
+ expect(new TextDecoder().decode(child.stderr)).toBe("");
244
+ expect(child.exitCode).toBe(0);
245
+ const read = (path: string) =>
246
+ existsSync(path)
247
+ ? (JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>)
248
+ : null;
249
+ return {
250
+ out: read(join(home, "out.json")) as Record<string, unknown>,
251
+ mirror: read(join(mirror, "install.json")),
252
+ bucket: read(join(objects, "install.json")),
253
+ };
254
+ } finally {
255
+ rmSync(home, { recursive: true, force: true });
256
+ }
257
+ }
258
+
259
+ it("local mode, an unfinished install: the corrected answer is recorded and the pass applies it", () => {
260
+ const r = resume({ install: meta, progress: unfinished, answer: RIGHT });
261
+ expect(r.out).toEqual({
262
+ ownerEmail: RIGHT,
263
+ recorded: RIGHT,
264
+ iapAllowlist: [`user:${RIGHT}`],
265
+ asked: [WRONG],
266
+ confirms: [],
267
+ });
268
+ expect(r.mirror).toEqual({ ...meta, ownerEmail: RIGHT });
269
+ });
270
+
271
+ it("local mode, a provisioned install: the change is confirmed, then recorded", () => {
272
+ const r = resume({ install: meta, progress: provisioned, answer: RIGHT });
273
+ expect(r.out.recorded).toBe(RIGHT);
274
+ expect(r.out.confirms).toEqual([`Change the Owner email to ${RIGHT}?`]);
275
+ });
276
+
277
+ it("local mode, a provisioned install: a declined change keeps install.json as it was", () => {
278
+ const r = resume({ install: meta, progress: provisioned, answer: RIGHT, confirmed: false });
279
+ expect(r.out.recorded).toBe(WRONG);
280
+ expect(r.mirror).toEqual(meta);
281
+ });
282
+
283
+ it("job mode's store: --owner-email lands in the ops bucket's install.json, which the job reads", () => {
284
+ const r = resume({
285
+ install: bucketBacked,
286
+ progress: unfinished,
287
+ requested: RIGHT,
288
+ nonInteractive: true,
289
+ });
290
+ expect(r.out.recorded).toBe(RIGHT);
291
+ expect(r.out.asked).toEqual([]);
292
+ expect(r.bucket).toEqual({ ...bucketBacked, ownerEmail: RIGHT });
293
+ expect(r.mirror?.ownerEmail).toBe(RIGHT);
294
+ });
295
+
296
+ it("an unchanged address writes nothing", () => {
297
+ const r = resume({ install: bucketBacked, progress: provisioned, answer: WRONG });
298
+ expect(r.out.recorded).toBe(WRONG);
299
+ expect(r.out.confirms).toEqual([]);
300
+ expect(r.bucket).toEqual(bucketBacked);
301
+ });
302
+ });
@@ -0,0 +1,214 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * The Owner email of an install the wizard resumes.
5
+ *
6
+ * The address decides who passes the admin's Google sign-in gate before any
7
+ * Caelo user exists: the stacks' `iapAllowlist` and the operator-access
8
+ * job's static members (operator-access.ts installIapAllowlist). A typo
9
+ * therefore locks everyone out of `/setup`, and a re-run is how the operator
10
+ * corrects it: `--owner-email`, or the prompt with the recorded address
11
+ * prefilled. Before, a resumed install always took the recorded address and
12
+ * dropped what the operator typed.
13
+ *
14
+ * install.json is the one record the rest reads (the converge half of the
15
+ * install, `upgrade`, `status`), so a correction is written there before any
16
+ * step runs, and the same run applies it: `pulumi up` sets the stacks' IAP
17
+ * members, the operator-access step redeploys the job with the new static
18
+ * members, the summary names the address the Owner setup link is for. The
19
+ * link's token is not bound to an address and stays valid. The converge job
20
+ * (converge-job-gcp.ts) keeps refusing while install.json and the deployed
21
+ * job disagree, so until this run got that far an in-product cloud-setup
22
+ * update waits; its check is not relaxed.
23
+ *
24
+ * An install that is provisioned may have an Owner already. The address can
25
+ * still change there: whoever runs the installer holds the project's IAM
26
+ * rights and could add any IAP member directly, so refusing would protect
27
+ * nothing, while a dead address would stay an IAP member for good. In a
28
+ * terminal the change is confirmed, and it says what it leaves alone: the
29
+ * Caelo accounts, which Settings → Users manages.
30
+ */
31
+
32
+ import { cancel, confirm, isCancel, log, note, text } from "@clack/prompts";
33
+ import { bold } from "kleur/colors";
34
+ import { type InstallMetadata, isStepDone, readMetadata, writeMetadata } from "./install-state.js";
35
+
36
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
37
+
38
+ /** Why `value` is not a usable Owner email, or undefined when it is. */
39
+ export function ownerEmailProblem(value: string): string | undefined {
40
+ if (value.trim().length === 0) return "Email is required";
41
+ if (!EMAIL.test(value.trim())) return "Looks like an invalid email";
42
+ return undefined;
43
+ }
44
+
45
+ /** Whether two spellings name the same address, as IAP compares them (installIapAllowlist). */
46
+ export function sameOwnerEmail(a: string, b: string): boolean {
47
+ return a.trim().toLowerCase() === b.trim().toLowerCase();
48
+ }
49
+
50
+ /**
51
+ * Whether the install's first `pulumi up` finished, so its admin exists and
52
+ * an Owner may be set up. Read from the progress checkpoint every resume
53
+ * already relies on.
54
+ */
55
+ export function isProvisioned(meta: Pick<InstallMetadata, "installId" | "projectId">): boolean {
56
+ return meta.projectId !== null && isStepDone(meta.installId, `pulumi-up-${meta.projectId}`);
57
+ }
58
+
59
+ /** What a resumed install's Owner email becomes. */
60
+ export type OwnerEmailDecision =
61
+ | { readonly kind: "keep" }
62
+ | { readonly kind: "change"; readonly from: string; readonly to: string }
63
+ | { readonly kind: "cancelled" }
64
+ | { readonly kind: "refuse"; readonly error: string };
65
+
66
+ /** The operator side of {@link decideOwnerEmail}; clack in the CLI, fakes in tests. */
67
+ export interface OwnerEmailPrompts {
68
+ /** Ask for the address with `recorded` prefilled; null when cancelled. */
69
+ readonly ask: (recorded: string) => Promise<string | null>;
70
+ /** Confirm a change on a provisioned install; null when cancelled. */
71
+ readonly confirm: (message: string) => Promise<boolean | null>;
72
+ /** Show the operator what a change does. */
73
+ readonly note: (lines: readonly string[]) => void;
74
+ }
75
+
76
+ /** What changing the address on a provisioned install does, and what it leaves alone. */
77
+ export function ownerEmailChangeLines(from: string, to: string): string[] {
78
+ return [
79
+ `The Owner email changes from ${from} to ${to}:`,
80
+ ` - ${to} gets through the admin's Google sign-in (IAP), and the Owner setup link is for it;`,
81
+ ` - ${from} no longer gets through, unless it belongs to a Caelo user.`,
82
+ "If an Owner is set up already, the Caelo accounts stay as they are: manage them under Settings → Users.",
83
+ "It takes effect when this run has finished the install.",
84
+ ];
85
+ }
86
+
87
+ /**
88
+ * Settle the Owner email of a resumed install: `requested` (`--owner-email`)
89
+ * when given, else the operator's answer to a prompt with the recorded
90
+ * address prefilled, else (non-interactive) the recorded one. A change on an
91
+ * install that is not provisioned is a plain correction. On a provisioned one
92
+ * the operator sees what it does and, in a terminal, confirms it; declining
93
+ * keeps the recorded address.
94
+ */
95
+ export async function decideOwnerEmail(
96
+ input: {
97
+ readonly recorded: string;
98
+ readonly requested?: string;
99
+ readonly nonInteractive: boolean;
100
+ readonly provisioned: boolean;
101
+ },
102
+ prompts: OwnerEmailPrompts,
103
+ ): Promise<OwnerEmailDecision> {
104
+ let wanted: string;
105
+ if (input.requested !== undefined) {
106
+ const problem = ownerEmailProblem(input.requested);
107
+ if (problem) return { kind: "refuse", error: `--owner-email ${input.requested}: ${problem}.` };
108
+ wanted = input.requested.trim();
109
+ } else if (input.nonInteractive) {
110
+ return { kind: "keep" };
111
+ } else {
112
+ const answer = await prompts.ask(input.recorded);
113
+ if (answer === null) return { kind: "cancelled" };
114
+ wanted = answer.trim();
115
+ }
116
+ if (sameOwnerEmail(wanted, input.recorded)) return { kind: "keep" };
117
+ const change = { kind: "change", from: input.recorded, to: wanted } as const;
118
+ if (!input.provisioned) return change;
119
+ prompts.note(ownerEmailChangeLines(input.recorded, wanted));
120
+ if (input.nonInteractive) return change;
121
+ const ok = await prompts.confirm(`Change the Owner email to ${wanted}?`);
122
+ if (ok === null) return { kind: "cancelled" };
123
+ return ok ? change : { kind: "keep" };
124
+ }
125
+
126
+ /**
127
+ * Record `ownerEmail` in install.json (the bucket's copy for an install whose
128
+ * state lives there), over what install.json holds now.
129
+ *
130
+ * @returns the metadata as now recorded
131
+ */
132
+ export function recordOwnerEmail(installId: string, ownerEmail: string): InstallMetadata {
133
+ const current = readMetadata(installId);
134
+ if (!current) throw new Error(`No install.json for install '${installId}'.`);
135
+ const next: InstallMetadata = { ...current, ownerEmail };
136
+ writeMetadata(installId, next);
137
+ return next;
138
+ }
139
+
140
+ /** {@link OwnerEmailPrompts} in the terminal. */
141
+ export const clackOwnerEmailPrompts: OwnerEmailPrompts = {
142
+ ask: async (recorded) => {
143
+ const value = await text({
144
+ message:
145
+ "Owner email (gets through the admin's Google sign-in; the Owner setup link is for this address)",
146
+ initialValue: recorded,
147
+ validate: (v) => ownerEmailProblem(v ?? ""),
148
+ });
149
+ return isCancel(value) ? null : String(value);
150
+ },
151
+ confirm: async (message) => {
152
+ const value = await confirm({ message, initialValue: true });
153
+ return isCancel(value) ? null : value;
154
+ },
155
+ note: (lines) => note(lines.join("\n"), "Owner email"),
156
+ };
157
+
158
+ /** Options of {@link resolveResumedOwnerEmail}. */
159
+ export interface ResumedOwnerEmailOpts {
160
+ /** `--owner-email`, when given. */
161
+ readonly requested?: string | undefined;
162
+ readonly nonInteractive: boolean;
163
+ }
164
+
165
+ /**
166
+ * {@link decideOwnerEmail} in the terminal for a resumed install.
167
+ *
168
+ * @returns the address to record when it changes, or null to keep the
169
+ * recorded one. Exits on a cancel or a malformed `--owner-email`.
170
+ */
171
+ export async function resolveResumedOwnerEmail(
172
+ meta: InstallMetadata,
173
+ opts: ResumedOwnerEmailOpts,
174
+ prompts: OwnerEmailPrompts = clackOwnerEmailPrompts,
175
+ ): Promise<string | null> {
176
+ const decision = await decideOwnerEmail(
177
+ {
178
+ recorded: meta.ownerEmail,
179
+ ...(opts.requested !== undefined ? { requested: opts.requested } : {}),
180
+ nonInteractive: opts.nonInteractive,
181
+ provisioned: isProvisioned(meta),
182
+ },
183
+ prompts,
184
+ );
185
+ switch (decision.kind) {
186
+ case "keep":
187
+ return null;
188
+ case "change":
189
+ log.info(`Owner email: ${decision.from} → ${bold(decision.to)}`);
190
+ return decision.to;
191
+ case "cancelled":
192
+ cancel("Cancelled.");
193
+ process.exit(0);
194
+ break;
195
+ case "refuse":
196
+ cancel(decision.error);
197
+ process.exit(2);
198
+ }
199
+ }
200
+
201
+ /**
202
+ * {@link resolveResumedOwnerEmail}, recorded in install.json when it
203
+ * changes: the Owner email a resumed install continues with. For an install
204
+ * without an install job; job mode records under the job's launch lock
205
+ * (wizards/gcp-install-job.ts).
206
+ */
207
+ export async function settleResumedOwnerEmail(
208
+ meta: InstallMetadata,
209
+ opts: ResumedOwnerEmailOpts,
210
+ prompts: OwnerEmailPrompts = clackOwnerEmailPrompts,
211
+ ): Promise<string> {
212
+ const changed = await resolveResumedOwnerEmail(meta, opts, prompts);
213
+ return changed === null ? meta.ownerEmail : recordOwnerEmail(meta.installId, changed).ownerEmail;
214
+ }
@@ -242,8 +242,9 @@ function collectionIndexJob(place: ReportingJobPlace): ReportingKindJob {
242
242
  ],
243
243
  cpu: "2",
244
244
  memory: "4Gi",
245
- // admin-core JOB_TIMING.collection_index.maxRunSeconds.
246
- taskTimeoutSeconds: 3600,
245
+ // admin-core JOB_TIMING.collection_index.maxRunSeconds: a large index
246
+ // on the few tasks a small CPU quota leaves runs for hours.
247
+ taskTimeoutSeconds: 6 * 3600,
247
248
  readBuckets: [
248
249
  { bucket: store, why: "it reads the Stage's change files and the previous releases" },
249
250
  ],
@@ -456,7 +456,7 @@ describe("the collection index job (epic #1644)", () => {
456
456
  expect(flag(deploy, "cpu")).toBe("2");
457
457
  expect(flag(deploy, "memory")).toBe("4Gi");
458
458
  // admin-core JOB_TIMING.collection_index.maxRunSeconds.
459
- expect(flag(deploy, "task-timeout")).toBe("3600s");
459
+ expect(flag(deploy, "task-timeout")).toBe("21600s");
460
460
  expect(flag(deploy, "set-env-vars")?.split(",").sort()).toEqual([
461
461
  "CAELO_COLLECTIONS_STAGING_STORE=gs://acme-caelo-production-coll-staging",
462
462
  "CAELO_PROVIDER=gcp",