@caelo-cms/provisioning 0.11.20 → 0.11.21

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 (57) hide show
  1. package/dist/admin-internal-google.d.ts +13 -1
  2. package/dist/admin-internal-google.d.ts.map +1 -1
  3. package/dist/admin-internal-google.js +47 -0
  4. package/dist/admin-internal-google.js.map +1 -1
  5. package/dist/agent/command.d.ts +1 -1
  6. package/dist/cli-routing.d.ts.map +1 -1
  7. package/dist/cli-routing.js +2 -2
  8. package/dist/cli-routing.js.map +1 -1
  9. package/dist/cli.js +5 -0
  10. package/dist/cli.js.map +1 -1
  11. package/dist/converge-checkpoint.d.ts +6 -0
  12. package/dist/converge-checkpoint.d.ts.map +1 -1
  13. package/dist/dns/manual.d.ts +5 -1
  14. package/dist/dns/manual.d.ts.map +1 -1
  15. package/dist/dns/manual.js +2 -1
  16. package/dist/dns/manual.js.map +1 -1
  17. package/dist/install-job-runner.d.ts.map +1 -1
  18. package/dist/install-job-runner.js +4 -3
  19. package/dist/install-job-runner.js.map +1 -1
  20. package/dist/install-job.d.ts +25 -1
  21. package/dist/install-job.d.ts.map +1 -1
  22. package/dist/install-job.js +72 -3
  23. package/dist/install-job.js.map +1 -1
  24. package/dist/operator-access.d.ts +7 -2
  25. package/dist/operator-access.d.ts.map +1 -1
  26. package/dist/operator-access.js +37 -6
  27. package/dist/operator-access.js.map +1 -1
  28. package/dist/project-status.d.ts +95 -0
  29. package/dist/project-status.d.ts.map +1 -0
  30. package/dist/project-status.js +213 -0
  31. package/dist/project-status.js.map +1 -0
  32. package/dist/state-attach.d.ts +17 -0
  33. package/dist/state-attach.d.ts.map +1 -1
  34. package/dist/state-attach.js +27 -9
  35. package/dist/state-attach.js.map +1 -1
  36. package/dist/wizards/gcp-install-job.d.ts +27 -4
  37. package/dist/wizards/gcp-install-job.d.ts.map +1 -1
  38. package/dist/wizards/gcp-install-job.js +62 -32
  39. package/dist/wizards/gcp-install-job.js.map +1 -1
  40. package/dist/wizards/gcp.d.ts +3 -0
  41. package/dist/wizards/gcp.d.ts.map +1 -1
  42. package/dist/wizards/gcp.js +10 -4
  43. package/dist/wizards/gcp.js.map +1 -1
  44. package/package.json +2 -2
  45. package/src/admin-internal-google.ts +48 -0
  46. package/src/cli-routing.ts +3 -2
  47. package/src/cli.ts +5 -0
  48. package/src/dns/manual.ts +4 -1
  49. package/src/install-job-runner.ts +4 -2
  50. package/src/install-job.ts +86 -4
  51. package/src/operator-access.test.ts +43 -0
  52. package/src/operator-access.ts +38 -6
  53. package/src/project-status.test.ts +462 -0
  54. package/src/project-status.ts +306 -0
  55. package/src/state-attach.ts +46 -16
  56. package/src/wizards/gcp-install-job.ts +91 -46
  57. package/src/wizards/gcp.ts +14 -7
@@ -20,6 +20,7 @@ import { CAELO_VERSION } from "@caelo-cms/shared";
20
20
  import { assertNoSecrets } from "./checkpoint-secrets.js";
21
21
  import {
22
22
  type InstallJobStatus,
23
+ isGcpProjectId,
23
24
  readInstallJobStatus,
24
25
  writeInstallJobStatus,
25
26
  } from "./install-job.js";
@@ -28,14 +29,13 @@ import { attachInstall } from "./state-attach.js";
28
29
  import { hasLocalPulumiState, opsBucketName, resolveBackend } from "./state-backend.js";
29
30
  import { realSyncGcloud, type SyncGcloud } from "./state-store.js";
30
31
 
31
- const PROJECT_ID = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/;
32
32
  const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;?]*[A-Za-z]`, "g");
33
33
 
34
34
  /** The `--project` value of `argv`, validated. */
35
35
  export function installJobProject(argv: readonly string[]): string {
36
36
  const i = argv.indexOf("--project");
37
37
  const value = i === -1 ? undefined : argv[i + 1];
38
- if (!value || !PROJECT_ID.test(value)) {
38
+ if (!value || !isGcpProjectId(value)) {
39
39
  throw new Error("install-job needs --project <gcp-project-id>");
40
40
  }
41
41
  return value;
@@ -117,6 +117,7 @@ export async function installJobCommand(
117
117
  execution,
118
118
  state: "running",
119
119
  phase: "Starting",
120
+ ...(previous?.dnsRecords ? { dnsRecords: previous.dnsRecords } : {}),
120
121
  caeloVersion: CAELO_VERSION,
121
122
  startedAt: previous?.execution === execution ? previous.startedAt : now,
122
123
  updatedAt: now,
@@ -161,6 +162,7 @@ export async function installJobCommand(
161
162
  nonInteractive: true,
162
163
  setupLink: "secret",
163
164
  onPhase: (phase, detail) => record({ phase, detail }),
165
+ onDnsRecords: (dnsRecords) => record({ dnsRecords, detail: status.detail }),
164
166
  });
165
167
  record({ state: "succeeded", phase: "Done" });
166
168
  }
@@ -28,15 +28,20 @@
28
28
  * The Owner setup link is a secret (#656): it never reaches the bucket or
29
29
  * the job's logs. The job stores it in Secret Manager
30
30
  * ({@link INSTALL_SETUP_LINK_SECRET}); the operator's terminal reads it there.
31
+ *
32
+ * All of this is readable from the project alone, so `status --project`
33
+ * (project-status.ts, #822) shows the install on any machine signed in to
34
+ * gcloud, after the terminal that started it is gone.
31
35
  */
32
36
 
33
37
  import { z } from "zod";
34
38
  import { assertNoSecrets } from "./checkpoint-secrets.js";
39
+ import type { InstallDnsRecord } from "./dns/groups.js";
35
40
  import type { GcloudRunner } from "./gcloud-retry.js";
36
41
  import { GCP_STACK_ENV } from "./gcp-names.js";
37
42
  import { createInstallSecret } from "./runtime-secrets.js";
38
- import { OPS_INSTALL_PREFIX } from "./state-backend.js";
39
- import type { SyncGcloud } from "./state-store.js";
43
+ import { OPS_INSTALL_PREFIX, opsBucketName } from "./state-backend.js";
44
+ import { GcsStateStore, type SyncGcloud } from "./state-store.js";
40
45
  import { IMAGE_DIGEST } from "./upgrade/release-images.js";
41
46
 
42
47
  /** Name of the Cloud Run job that runs the install. */
@@ -99,6 +104,20 @@ export function opsImageRef(digest: string): string {
99
104
  return `${OPS_IMAGE_REPOSITORY}@${digest}`;
100
105
  }
101
106
 
107
+ const GCP_PROJECT_ID = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/;
108
+
109
+ /** Whether `value` has the shape of a Google Cloud project id. */
110
+ export function isGcpProjectId(value: string): boolean {
111
+ return GCP_PROJECT_ID.test(value);
112
+ }
113
+
114
+ const DnsRecordSchema = z.object({
115
+ hostname: z.string().min(1),
116
+ type: z.string().min(1),
117
+ value: z.string().min(1),
118
+ purpose: z.string().optional(),
119
+ });
120
+
102
121
  /** What `install/install-job.json` records. */
103
122
  export const InstallJobStatusSchema = z.object({
104
123
  statusVersion: z.literal(1),
@@ -110,6 +129,12 @@ export const InstallJobStatusSchema = z.object({
110
129
  phase: z.string(),
111
130
  /** Extra context for the phase (the DNS records to set, a failure reason). */
112
131
  detail: z.string().optional(),
132
+ /**
133
+ * DNS records the job found out about that are not in the stack's outputs
134
+ * (the staging host's, #822), so `status --project` lists them on any
135
+ * machine. Not secret: anyone can read them from public DNS once set.
136
+ */
137
+ dnsRecords: z.array(DnsRecordSchema).optional(),
113
138
  /** Caelo release the job's image belongs to. */
114
139
  caeloVersion: z.string(),
115
140
  startedAt: z.string(),
@@ -134,7 +159,9 @@ export function readJobStatusDoc<T>(url: string, schema: z.ZodType<T>, run: Sync
134
159
  const r = run(["storage", "cat", url]);
135
160
  if (!r.ok) {
136
161
  if (NOT_FOUND.test(r.stderr)) return null;
137
- throw new Error(`Could not read ${url}: ${r.stderr.trim() || `gcloud exited ${r.exitCode}`}`);
162
+ throw new Error(
163
+ `Could not read ${url}: ${r.stderr.trim() || `gcloud exited ${r.exitCode}`}. Check that you are signed in (gcloud auth login) as an account with access to the install's ops bucket.`,
164
+ );
138
165
  }
139
166
  let json: unknown;
140
167
  try {
@@ -285,7 +312,7 @@ export async function describeExecution(
285
312
  if (!r.ok) {
286
313
  if (NOT_FOUND.test(r.stderr)) return "missing";
287
314
  throw new Error(
288
- `Could not read execution ${target.execution}: ${r.stderr.trim() || `gcloud exited ${r.exitCode}`}`,
315
+ `Could not read execution ${target.execution}: ${r.stderr.trim() || `gcloud exited ${r.exitCode}`}. Your gcloud account needs run.executions.get on ${target.projectId} (e.g. roles/run.viewer or project Owner).`,
289
316
  );
290
317
  }
291
318
  const d = JSON.parse(r.stdout || "{}") as ExecutionDescription;
@@ -296,6 +323,61 @@ export async function describeExecution(
296
323
  : "failed";
297
324
  }
298
325
 
326
+ const RecordedProgressSchema = z.object({ steps: z.record(z.string(), z.unknown()) });
327
+ const RecordedStepSchema = z.object({ outputs: z.record(z.string(), z.unknown()).optional() });
328
+
329
+ /**
330
+ * The stack's outputs as the `pulumi-up` step recorded them in the ops
331
+ * bucket's progress.json — current, never cached (the job writes it), and
332
+ * without touching this machine's install directory. Empty before that step
333
+ * finished.
334
+ *
335
+ * @throws when the bucket can't be read or progress.json is malformed
336
+ */
337
+ export function readRecordedStackOutputs(
338
+ projectId: string,
339
+ run: SyncGcloud,
340
+ ): Record<string, unknown> {
341
+ const bucket = opsBucketName(projectId);
342
+ const text = new GcsStateStore(bucket, "/nonexistent", run).peek("progress.json");
343
+ if (text === null) return {};
344
+ const url = `gs://${bucket}/${OPS_INSTALL_PREFIX}/progress.json`;
345
+ let json: unknown;
346
+ try {
347
+ json = JSON.parse(text);
348
+ } catch {
349
+ throw new Error(`${url} is not valid JSON. Re-run the installer to write it again.`);
350
+ }
351
+ const progress = RecordedProgressSchema.safeParse(json);
352
+ if (!progress.success) {
353
+ throw new Error(
354
+ `${url} is not a checkpoint this CLI understands (${progress.error.message}). Re-run the installer to write it again.`,
355
+ );
356
+ }
357
+ const raw = progress.data.steps[`pulumi-up-${projectId}`];
358
+ if (raw === undefined) return {};
359
+ const step = RecordedStepSchema.safeParse(raw);
360
+ if (!step.success) {
361
+ throw new Error(
362
+ `${url} records the pulumi-up step in a shape this CLI does not understand (${step.error.message}). Re-run the installer to write it again.`,
363
+ );
364
+ }
365
+ return step.data.outputs ?? {};
366
+ }
367
+
368
+ /** The stack's `dnsRecordsRequiredOut` from {@link readRecordedStackOutputs}. */
369
+ export function recordedDnsRecords(outputs: Record<string, unknown>): InstallDnsRecord[] {
370
+ const raw = outputs.dnsRecordsRequiredOut;
371
+ if (raw === undefined) return [];
372
+ const records = z.array(DnsRecordSchema).safeParse(raw);
373
+ if (!records.success) {
374
+ throw new Error(
375
+ `The recorded stack output dnsRecordsRequiredOut is malformed (${records.error.message}). Re-run the installer to refresh it.`,
376
+ );
377
+ }
378
+ return records.data;
379
+ }
380
+
299
381
  /** What the launcher does with an install that may already have a job. */
300
382
  export type InstallJobDecision =
301
383
  | { readonly kind: "start"; readonly previous: InstallJobStatus | null; readonly why: string }
@@ -15,6 +15,7 @@ import { withIamAuthFlag } from "./cloudsql-iam-user.js";
15
15
  import type { GcloudResult } from "./gcloud.js";
16
16
  import {
17
17
  ensureOperatorAccessSync,
18
+ iapWebPath,
18
19
  installIapAllowlist,
19
20
  OPERATOR_ACCESS_PROJECT_IAP_ROLE,
20
21
  OPERATOR_ACCESS_ROLE,
@@ -205,6 +206,48 @@ describe("ensureOperatorAccessSync", () => {
205
206
  );
206
207
  });
207
208
 
209
+ it("#1120 — on plain gcp the job addresses the backend by its numeric id", async () => {
210
+ const { run, calls } = freshInstall();
211
+ const withId: typeof run = async (args) =>
212
+ args.slice(0, 3).join(" ") === "compute backend-services describe"
213
+ ? ok("6948347336569833444\n")
214
+ : run(args);
215
+ const r = await ensureOperatorAccessSync(
216
+ {
217
+ ...target,
218
+ resource: { kind: "backend-services", service: "caelo-production-admin-backend-1a2b" },
219
+ },
220
+ { run: withId, sleep: async () => {} },
221
+ );
222
+ expect(r.ok).toBe(true);
223
+ const deploy = calls.find((c) => c.slice(0, 3).join(" ") === "run jobs deploy") ?? [];
224
+ expect(deploy.find((a) => a.startsWith("--set-env-vars="))).toContain(
225
+ "CAELO_OPERATOR_ACCESS_IAP_WEB=compute/services/6948347336569833444|",
226
+ );
227
+ });
228
+
229
+ it("#1120 — iapWebPath refuses a backend without its numeric id", () => {
230
+ expect(() => iapWebPath({ kind: "backend-services", service: "b" })).toThrow("numeric id");
231
+ });
232
+
233
+ it("#1120 — refuses a backend whose id cannot be read instead of deploying by name", async () => {
234
+ const { run, calls } = freshInstall();
235
+ const noId: typeof run = async (args) =>
236
+ args.slice(0, 3).join(" ") === "compute backend-services describe"
237
+ ? fail("PERMISSION_DENIED")
238
+ : run(args);
239
+ const r = await ensureOperatorAccessSync(
240
+ {
241
+ ...target,
242
+ resource: { kind: "backend-services", service: "caelo-production-admin-backend-1a2b" },
243
+ },
244
+ { run: noId, sleep: async () => {} },
245
+ );
246
+ expect(r.ok).toBe(false);
247
+ // It stops before anything is written, the revoke of the old path included.
248
+ expect(calls).toEqual([]);
249
+ });
250
+
208
251
  it("#1140 — tells the job which service accounts keep IAP access (the scheduler tick)", async () => {
209
252
  const { run, calls } = freshInstall();
210
253
  await ensureOperatorAccessSync(
@@ -136,11 +136,20 @@ export const OPERATOR_ACCESS_DB_ROLE = "operator_access_reader";
136
136
  /** Where the admin image ships the job's entry point. */
137
137
  const SYNC_JOB_SCRIPT = "/app/packages/admin-core/src/security/operator-access/sync-job.ts";
138
138
 
139
- /** The `iap_web` path of an IAP resource, as the IAP REST API names it. */
140
- export function iapWebPath(resource: IapResource): string {
141
- return resource.kind === "cloud-run"
142
- ? `cloud_run-${resource.region}/services/${resource.service}`
143
- : `compute/services/${resource.service}`;
139
+ /**
140
+ * The `iap_web` path of an IAP resource, as the IAP REST API names it. A
141
+ * backend service goes by its numeric id: IAM on the job's account is
142
+ * evaluated there, and addressed by name `:iapSettings` answers 403 even with
143
+ * the role bound, so the sync failed every hour on plain gcp (#1120).
144
+ */
145
+ export function iapWebPath(resource: IapResource, backendServiceId?: string): string {
146
+ if (resource.kind === "cloud-run") {
147
+ return `cloud_run-${resource.region}/services/${resource.service}`;
148
+ }
149
+ if (!backendServiceId) {
150
+ throw new Error(`${resource.service}: an IAP backend is addressed by its numeric id`);
151
+ }
152
+ return `compute/services/${backendServiceId}`;
144
153
  }
145
154
 
146
155
  /** Create the custom role, or bring an existing / soft-deleted one to spec. */
@@ -261,6 +270,29 @@ export async function ensureOperatorAccessSync(
261
270
  const customRole = customRoleName(projectId, OPERATOR_ACCESS_ROLE.roleId);
262
271
  const jobName = operatorAccessJobName(env);
263
272
  const done: string[] = [];
273
+
274
+ // Before any write: the steps below revoke the old access path, so an
275
+ // unreadable id must not leave the install without a replacement job.
276
+ let backendServiceId: string | undefined;
277
+ if (target.resource.kind === "backend-services") {
278
+ const described = await run([
279
+ "compute",
280
+ "backend-services",
281
+ "describe",
282
+ target.resource.service,
283
+ "--global",
284
+ project,
285
+ "--format=value(id)",
286
+ ]);
287
+ backendServiceId = described.stdout.trim();
288
+ if (!described.ok || !/^\d+$/.test(backendServiceId)) {
289
+ return {
290
+ ok: false,
291
+ done,
292
+ error: `read the id of ${target.resource.service}: ${described.stderr.trim() || "no numeric id"}`,
293
+ };
294
+ }
295
+ }
264
296
  const fail = (step: string, r: GcloudResult): OperatorAccessSyncResult => ({
265
297
  ok: false,
266
298
  done,
@@ -427,7 +459,7 @@ export async function ensureOperatorAccessSync(
427
459
  // 6. The job: the admin image with another entry point, the job's own SA,
428
460
  // and its whole input as env the admin cannot override.
429
461
  const envVars = [
430
- `CAELO_OPERATOR_ACCESS_IAP_WEB=${iapWebPath(target.resource)}`,
462
+ `CAELO_OPERATOR_ACCESS_IAP_WEB=${iapWebPath(target.resource, backendServiceId)}`,
431
463
  `CAELO_MCP_IAP_SERVICE_ACCOUNT=${mcpSa}`,
432
464
  `CAELO_OPERATOR_ACCESS_STATIC_MEMBERS=${installIapAllowlist(target.ownerEmail).join(",")}`,
433
465
  `CAELO_OPERATOR_ACCESS_DB_HOST=${target.databaseHost}`,