@caelo-cms/provisioning 0.11.20 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/dist/adapter.d.ts +6 -1
  2. package/dist/adapter.d.ts.map +1 -1
  3. package/dist/admin-internal-google.d.ts +13 -1
  4. package/dist/admin-internal-google.d.ts.map +1 -1
  5. package/dist/admin-internal-google.js +47 -0
  6. package/dist/admin-internal-google.js.map +1 -1
  7. package/dist/agent/command.d.ts +1 -1
  8. package/dist/agent-db.js +133 -8
  9. package/dist/bootstrap-token.d.ts +4 -3
  10. package/dist/bootstrap-token.d.ts.map +1 -1
  11. package/dist/bootstrap-token.js.map +1 -1
  12. package/dist/cli-routing.d.ts.map +1 -1
  13. package/dist/cli-routing.js +7 -2
  14. package/dist/cli-routing.js.map +1 -1
  15. package/dist/cli.js +9 -0
  16. package/dist/cli.js.map +1 -1
  17. package/dist/converge-checkpoint.d.ts +6 -0
  18. package/dist/converge-checkpoint.d.ts.map +1 -1
  19. package/dist/converge-job-gcp.d.ts +1 -16
  20. package/dist/converge-job-gcp.d.ts.map +1 -1
  21. package/dist/converge-job-gcp.js +10 -97
  22. package/dist/converge-job-gcp.js.map +1 -1
  23. package/dist/converge-job.d.ts +7 -46
  24. package/dist/converge-job.d.ts.map +1 -1
  25. package/dist/converge-job.js +22 -57
  26. package/dist/converge-job.js.map +1 -1
  27. package/dist/dns/manual.d.ts +5 -1
  28. package/dist/dns/manual.d.ts.map +1 -1
  29. package/dist/dns/manual.js +2 -1
  30. package/dist/dns/manual.js.map +1 -1
  31. package/dist/gateway-armor.d.ts.map +1 -1
  32. package/dist/gateway-armor.js +11 -3
  33. package/dist/gateway-armor.js.map +1 -1
  34. package/dist/gcp-names.d.ts +2 -0
  35. package/dist/gcp-names.d.ts.map +1 -1
  36. package/dist/gcp-names.js +4 -0
  37. package/dist/gcp-names.js.map +1 -1
  38. package/dist/index.d.ts +3 -2
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +1 -1
  41. package/dist/index.js.map +1 -1
  42. package/dist/infra-contract.d.ts +1 -1
  43. package/dist/infra-contract.d.ts.map +1 -1
  44. package/dist/infra-contract.js +14 -1
  45. package/dist/infra-contract.js.map +1 -1
  46. package/dist/install-job-runner.d.ts.map +1 -1
  47. package/dist/install-job-runner.js +4 -3
  48. package/dist/install-job-runner.js.map +1 -1
  49. package/dist/install-job.d.ts +25 -1
  50. package/dist/install-job.d.ts.map +1 -1
  51. package/dist/install-job.js +72 -3
  52. package/dist/install-job.js.map +1 -1
  53. package/dist/job-handover-gcp.d.ts +40 -0
  54. package/dist/job-handover-gcp.d.ts.map +1 -0
  55. package/dist/job-handover-gcp.js +108 -0
  56. package/dist/job-handover-gcp.js.map +1 -0
  57. package/dist/job-handover.d.ts +141 -0
  58. package/dist/job-handover.d.ts.map +1 -0
  59. package/dist/job-handover.js +141 -0
  60. package/dist/job-handover.js.map +1 -0
  61. package/dist/operator-access.d.ts +7 -2
  62. package/dist/operator-access.d.ts.map +1 -1
  63. package/dist/operator-access.js +37 -6
  64. package/dist/operator-access.js.map +1 -1
  65. package/dist/owner-setup-token.d.ts +52 -0
  66. package/dist/owner-setup-token.d.ts.map +1 -0
  67. package/dist/owner-setup-token.js +111 -0
  68. package/dist/owner-setup-token.js.map +1 -0
  69. package/dist/project-status.d.ts +128 -0
  70. package/dist/project-status.d.ts.map +1 -0
  71. package/dist/project-status.js +303 -0
  72. package/dist/project-status.js.map +1 -0
  73. package/dist/stack-converge.d.ts.map +1 -1
  74. package/dist/stack-converge.js +9 -5
  75. package/dist/stack-converge.js.map +1 -1
  76. package/dist/state-attach.d.ts +17 -0
  77. package/dist/state-attach.d.ts.map +1 -1
  78. package/dist/state-attach.js +27 -9
  79. package/dist/state-attach.js.map +1 -1
  80. package/dist/static-security-headers.d.ts +6 -0
  81. package/dist/static-security-headers.d.ts.map +1 -1
  82. package/dist/static-security-headers.js +11 -1
  83. package/dist/static-security-headers.js.map +1 -1
  84. package/dist/upgrader-assess.d.ts +30 -3
  85. package/dist/upgrader-assess.d.ts.map +1 -1
  86. package/dist/upgrader-assess.js +77 -24
  87. package/dist/upgrader-assess.js.map +1 -1
  88. package/dist/upgrader-gcp.d.ts +4 -2
  89. package/dist/upgrader-gcp.d.ts.map +1 -1
  90. package/dist/upgrader-gcp.js +16 -3
  91. package/dist/upgrader-gcp.js.map +1 -1
  92. package/dist/upgrader-iam-preflight.d.ts +14 -3
  93. package/dist/upgrader-iam-preflight.d.ts.map +1 -1
  94. package/dist/upgrader-iam-preflight.js +40 -6
  95. package/dist/upgrader-iam-preflight.js.map +1 -1
  96. package/dist/upgrader-job.d.ts +51 -9
  97. package/dist/upgrader-job.d.ts.map +1 -1
  98. package/dist/upgrader-job.js +92 -37
  99. package/dist/upgrader-job.js.map +1 -1
  100. package/dist/upgrader-setup.d.ts +1 -1
  101. package/dist/upgrader-setup.d.ts.map +1 -1
  102. package/dist/upgrader-setup.js +5 -2
  103. package/dist/upgrader-setup.js.map +1 -1
  104. package/dist/wizards/gcp-install-job.d.ts +27 -4
  105. package/dist/wizards/gcp-install-job.d.ts.map +1 -1
  106. package/dist/wizards/gcp-install-job.js +73 -33
  107. package/dist/wizards/gcp-install-job.js.map +1 -1
  108. package/dist/wizards/gcp-pulumi.d.ts +0 -13
  109. package/dist/wizards/gcp-pulumi.d.ts.map +1 -1
  110. package/dist/wizards/gcp-pulumi.js +0 -12
  111. package/dist/wizards/gcp-pulumi.js.map +1 -1
  112. package/dist/wizards/gcp.d.ts +3 -0
  113. package/dist/wizards/gcp.d.ts.map +1 -1
  114. package/dist/wizards/gcp.js +30 -53
  115. package/dist/wizards/gcp.js.map +1 -1
  116. package/package.json +2 -2
  117. package/src/adapter.ts +6 -1
  118. package/src/admin-internal-google.ts +48 -0
  119. package/src/bootstrap-token.ts +4 -3
  120. package/src/caddy-redirects.docker.test.ts +5 -0
  121. package/src/cli-routing.test.ts +1 -1
  122. package/src/cli-routing.ts +9 -2
  123. package/src/cli.ts +9 -0
  124. package/src/converge-job-gcp.test.ts +1 -40
  125. package/src/converge-job-gcp.ts +10 -100
  126. package/src/converge-job.test.ts +9 -3
  127. package/src/converge-job.ts +33 -115
  128. package/src/dns/manual.ts +4 -1
  129. package/src/gateway-armor.ts +14 -3
  130. package/src/gateway-edge.test.ts +16 -1
  131. package/src/gcp-names.ts +4 -0
  132. package/src/gcp-url-map.test.ts +2 -0
  133. package/src/index.ts +3 -0
  134. package/src/infra-contract.test.ts +4 -3
  135. package/src/infra-contract.ts +14 -1
  136. package/src/install-job-runner.ts +4 -2
  137. package/src/install-job.ts +86 -4
  138. package/src/job-handover-gcp.test.ts +129 -0
  139. package/src/job-handover-gcp.ts +135 -0
  140. package/src/job-handover.ts +259 -0
  141. package/src/operator-access.test.ts +43 -0
  142. package/src/operator-access.ts +38 -6
  143. package/src/owner-setup-token.test.ts +195 -0
  144. package/src/owner-setup-token.ts +138 -0
  145. package/src/project-status.test.ts +571 -0
  146. package/src/project-status.ts +430 -0
  147. package/src/stack-converge.ts +12 -5
  148. package/src/state-attach.ts +46 -16
  149. package/src/static-security-headers.test.ts +16 -0
  150. package/src/static-security-headers.ts +12 -1
  151. package/src/upgrader-assess.test.ts +75 -1
  152. package/src/upgrader-assess.ts +121 -57
  153. package/src/upgrader-gcp.ts +19 -5
  154. package/src/upgrader-iam-preflight.test.ts +28 -1
  155. package/src/upgrader-iam-preflight.ts +46 -6
  156. package/src/upgrader-job.test.ts +365 -31
  157. package/src/upgrader-job.ts +177 -53
  158. package/src/upgrader-setup.test.ts +17 -0
  159. package/src/upgrader-setup.ts +5 -2
  160. package/src/url-map-redirects-access.test.ts +1 -1
  161. package/src/wizards/gcp-install-job.ts +101 -47
  162. package/src/wizards/gcp-pulumi.ts +0 -18
  163. package/src/wizards/gcp.ts +37 -67
  164. package/stacks/aws/README.md +4 -2
  165. package/stacks/aws/index.ts +4 -8
  166. package/stacks/azure/README.md +4 -2
  167. package/stacks/azure/index.ts +4 -8
  168. package/stacks/gcp/README.md +6 -3
  169. package/stacks/gcp/index.ts +7 -8
  170. package/stacks/gcp-firebase/index.ts +4 -6
@@ -0,0 +1,430 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * `cms-provision status --project <id>` (#822): where an install stands, on
5
+ * any machine. The install job keeps running after the Cloud Shell tab is
6
+ * gone, and a reset Cloud Shell has no `~/.caelo-*` left, so this command
7
+ * needs nothing but a signed-in gcloud identity: it reads the project
8
+ * (install.json, install-job.json and progress.json in the ops bucket, the
9
+ * Owner setup link and token in Secret Manager) and writes nothing, here or
10
+ * there.
11
+ *
12
+ * The setup link is a secret (#656). It goes to a terminal only: with stdout
13
+ * piped or redirected it stays unprinted, so it can't land in a CI log or a
14
+ * file. Once Owner setup is done the command says so instead of showing a
15
+ * used link; a link past its 24 hours (#1476) is not shown either.
16
+ *
17
+ * `setup-link --project <id>` is the one command here that writes: what a
18
+ * late Owner runs for a new link ({@link setupLinkCommand}).
19
+ */
20
+
21
+ import type { OwnerBootstrapToken } from "@caelo-cms/shared";
22
+ import { log } from "@clack/prompts";
23
+ import { bold, cyan, dim, green, red, yellow } from "kleur/colors";
24
+ import { z } from "zod";
25
+ import type { AdminInternalResult, GoogleAdminTarget } from "./admin-internal.js";
26
+ import { readOwnerSetupState } from "./admin-internal-google.js";
27
+ import {
28
+ type DnsRecordGroups,
29
+ formatDnsRecordGroups,
30
+ groupDnsRecords,
31
+ type InstallDnsRecord,
32
+ } from "./dns/groups.js";
33
+ import { checkRecord } from "./dns/manual.js";
34
+ import { checkGcloudAuth, gcloud } from "./gcloud.js";
35
+ import type { GcloudRunner } from "./gcloud-retry.js";
36
+ import {
37
+ INSTALL_SETUP_LINK_SECRET,
38
+ isGcpProjectId,
39
+ readRecordedStackOutputs,
40
+ readSetupLink,
41
+ recordedDnsRecords,
42
+ } from "./install-job.js";
43
+ import {
44
+ issueOwnerSetup,
45
+ type OwnerSetupIssued,
46
+ readOwnerBootstrapToken,
47
+ } from "./owner-setup-token.js";
48
+ import { selfCommand } from "./self-command.js";
49
+ import { readProjectInstall } from "./state-attach.js";
50
+ import { realSyncGcloud, type SyncGcloud } from "./state-store.js";
51
+ import {
52
+ type InstallJobView,
53
+ installerCommand,
54
+ installJobViewLines,
55
+ readInstallJobView,
56
+ } from "./wizards/gcp-install-job.js";
57
+
58
+ /** The parts of install.json this command reads. */
59
+ const InstallRecordSchema = z.object({
60
+ installId: z.string().min(1),
61
+ provider: z.enum(["gcp", "gcp-firebase"]),
62
+ domain: z.string().min(1),
63
+ ownerEmail: z.string().min(1),
64
+ projectId: z.string().min(1),
65
+ region: z.string().min(1).nullable().default(null),
66
+ });
67
+ type InstallRecord = z.infer<typeof InstallRecordSchema>;
68
+
69
+ /** The DNS records of an install that public DNS does not answer yet. */
70
+ export interface DnsToSet extends DnsRecordGroups<InstallDnsRecord> {
71
+ /** How many records the install knows about, set or not; 0 before the stack ran. */
72
+ readonly total: number;
73
+ }
74
+
75
+ /** Where Owner setup stands, as far as this command can tell. */
76
+ export type OwnerSetup =
77
+ /** The install has not got far enough for a link to exist. */
78
+ | { readonly kind: "not-yet" }
79
+ /** An Owner exists; the link is used. */
80
+ | { readonly kind: "done" }
81
+ /** Setup is open, or could not be checked ({@link unverified} says why). */
82
+ | {
83
+ readonly kind: "link";
84
+ readonly link: string;
85
+ readonly expiresAt: string;
86
+ readonly unverified: string | null;
87
+ }
88
+ /** A link exists, but stdout is not a terminal. */
89
+ | { readonly kind: "withheld"; readonly expiresAt: string }
90
+ /**
91
+ * A link exists but cannot work: its token expired on {@link expiresAt}, or
92
+ * (null) it does not carry the stored token. That is an install that finished
93
+ * before #1476, whose admin refuses `/setup` until it has a token, or a new
94
+ * token stored without its link by an interrupted run.
95
+ */
96
+ | { readonly kind: "stale"; readonly expiresAt: string | null }
97
+ /** No link in Secret Manager. */
98
+ | { readonly kind: "no-link" }
99
+ /** Reading the link failed; the message says what the account needs. */
100
+ | { readonly kind: "error"; readonly message: string };
101
+
102
+ /** Everything `status --project` shows. */
103
+ export interface ProjectStatus {
104
+ readonly install: InstallRecord;
105
+ readonly job: InstallJobView | null;
106
+ /** Whether the stack ran (its outputs are recorded). */
107
+ readonly provisioned: boolean;
108
+ readonly adminUrl: string | null;
109
+ readonly dns: DnsToSet;
110
+ readonly owner: OwnerSetup;
111
+ }
112
+
113
+ /** Side effects of {@link readProjectStatus}, injectable for tests. */
114
+ export interface ProjectStatusDeps {
115
+ readonly run: GcloudRunner;
116
+ readonly syncRun: SyncGcloud;
117
+ /** Whether public DNS answers the record with its value. */
118
+ readonly resolves: (record: InstallDnsRecord) => Promise<boolean>;
119
+ /** Whether the admin still offers Owner setup ({@link readOwnerSetupState}). */
120
+ readonly ownerSetupState: (
121
+ target: GoogleAdminTarget,
122
+ ) => Promise<AdminInternalResult<"open" | "done">>;
123
+ /** Whether stdout is a terminal: the only place the setup link may go. */
124
+ readonly isTerminal: boolean;
125
+ /** The current time in ms. */
126
+ readonly now: () => number;
127
+ }
128
+
129
+ /** The admin's origin from the stack's outputs; null before the stack ran. */
130
+ export function adminUrlFromOutputs(
131
+ provider: InstallRecord["provider"],
132
+ outputs: Record<string, unknown>,
133
+ ): string | null {
134
+ // gcp-firebase binds admin.<domain> only on request; the setup link and
135
+ // the install's summary use the Cloud Run URL there (wizards/gcp.ts).
136
+ if (provider === "gcp-firebase") {
137
+ const url = outputs.adminCloudRunUrlOut;
138
+ return typeof url === "string" && url !== "" ? url : null;
139
+ }
140
+ const host = outputs.adminDomainOut;
141
+ return typeof host === "string" && host !== "" ? `https://${host}` : null;
142
+ }
143
+
144
+ /**
145
+ * Split `records` by what still has to happen: a record public DNS already
146
+ * answers is dropped, the rest fall into {@link groupDnsRecords}'s two groups.
147
+ */
148
+ export async function dnsRecordsToSet(
149
+ records: readonly InstallDnsRecord[],
150
+ domain: string,
151
+ resolves: ProjectStatusDeps["resolves"],
152
+ ): Promise<DnsToSet> {
153
+ const unique = [
154
+ ...new Map(records.map((r) => [`${r.type}:${r.hostname}:${r.value}`, r])).values(),
155
+ ];
156
+ const answered = await Promise.all(unique.map(resolves));
157
+ const open = unique.filter((_, i) => !answered[i]);
158
+ return { ...groupDnsRecords(open, domain), total: unique.length };
159
+ }
160
+
161
+ /** Where {@link readOwnerSetupState} reaches the admin; null without a recorded region. */
162
+ function adminTarget(install: InstallRecord): GoogleAdminTarget | null {
163
+ const { provider, projectId, domain, region } = install;
164
+ if (provider === "gcp") return { provider, projectId, domain };
165
+ return region ? { provider, projectId, region } : null;
166
+ }
167
+
168
+ async function readOwnerSetup(
169
+ args: {
170
+ readonly install: InstallRecord;
171
+ readonly adminUrl: string | null;
172
+ readonly job: InstallJobView | null;
173
+ readonly provisioned: boolean;
174
+ },
175
+ deps: ProjectStatusDeps,
176
+ ): Promise<OwnerSetup> {
177
+ const unfinished = args.job ? args.job.decision.kind !== "done" : !args.provisioned;
178
+ if (unfinished || args.adminUrl === null) return { kind: "not-yet" };
179
+ let link: string | null;
180
+ try {
181
+ link = await readSetupLink(deps.run, args.install.projectId);
182
+ } catch (e) {
183
+ return { kind: "error", message: e instanceof Error ? e.message : String(e) };
184
+ }
185
+ if (link === null) return { kind: "no-link" };
186
+ const target = adminTarget(args.install);
187
+ const state: AdminInternalResult<"open" | "done"> = target
188
+ ? await deps.ownerSetupState(target)
189
+ : { ok: false, error: "install.json records no region" };
190
+ if (state.ok && state.value === "done") return { kind: "done" };
191
+ // Only now: an install with an Owner has no use for the token, so nothing
192
+ // about that secret may change what it reports.
193
+ let token: OwnerBootstrapToken | null;
194
+ try {
195
+ token = await readOwnerBootstrapToken(deps.run, args.install.projectId);
196
+ } catch (e) {
197
+ return { kind: "error", message: e instanceof Error ? e.message : String(e) };
198
+ }
199
+ // A run of `setup-link` stopped between the two secrets leaves a new token
200
+ // beside the old link: that link is not the one the admin accepts.
201
+ if (token === null || !link.endsWith(`token=${token.token}`)) {
202
+ return { kind: "stale", expiresAt: null };
203
+ }
204
+ if (Date.parse(token.expiresAt) <= deps.now()) {
205
+ return { kind: "stale", expiresAt: token.expiresAt };
206
+ }
207
+ if (!deps.isTerminal) return { kind: "withheld", expiresAt: token.expiresAt };
208
+ return {
209
+ kind: "link",
210
+ link,
211
+ expiresAt: token.expiresAt,
212
+ unverified: state.ok ? null : state.error,
213
+ };
214
+ }
215
+
216
+ /**
217
+ * Read where the install in `projectId` stands from the project alone.
218
+ *
219
+ * @throws when a read fails, with what to do about it
220
+ */
221
+ export async function readProjectStatus(
222
+ projectId: string,
223
+ deps: ProjectStatusDeps,
224
+ ): Promise<ProjectStatus> {
225
+ const record = readProjectInstall(projectId, deps.syncRun);
226
+ if (!record.ok) throw new Error(record.error);
227
+ const parsed = InstallRecordSchema.safeParse(JSON.parse(record.text));
228
+ if (!parsed.success) {
229
+ throw new Error(
230
+ `install.json of ${projectId} is not a Google Cloud install this CLI understands (${parsed.error.message}). Run this command with the CLI of the release the install runs.`,
231
+ );
232
+ }
233
+ const install = parsed.data;
234
+ const job = await readInstallJobView(install, deps);
235
+ const outputs = readRecordedStackOutputs(projectId, deps.syncRun);
236
+ const provisioned = Object.keys(outputs).length > 0;
237
+ const adminUrl = adminUrlFromOutputs(install.provider, outputs);
238
+ const dns = await dnsRecordsToSet(
239
+ [...recordedDnsRecords(outputs), ...(job?.status.dnsRecords ?? [])],
240
+ install.domain,
241
+ deps.resolves,
242
+ );
243
+ const owner = await readOwnerSetup({ install, adminUrl, job, provisioned }, deps);
244
+ return { install, job, provisioned, adminUrl, dns, owner };
245
+ }
246
+
247
+ function jobLines(s: ProjectStatus): string[] {
248
+ if (s.job) return installJobViewLines(s.job, s.install);
249
+ return s.provisioned
250
+ ? ["Install job: none. This install ran from a terminal, not through the job."]
251
+ : [`Install job: not started. Start or resume it: ${installerCommand(s.install)}`];
252
+ }
253
+
254
+ function dnsLines(s: ProjectStatus): string[] {
255
+ const { dns, install } = s;
256
+ if (dns.total === 0) {
257
+ return ["DNS: not known yet; the install reports its records once its resources exist."];
258
+ }
259
+ const lines =
260
+ dns.setNow.length + dns.atGoLive.length === 0
261
+ ? [`DNS: ${green(`all set (${dns.total} of ${dns.total}).`)}`]
262
+ : [
263
+ `DNS records still to set for ${bold(install.domain)}:`,
264
+ ...formatDnsRecordGroups(dns, install.domain).map((l) => ` ${l}`),
265
+ ];
266
+ // The staging host's records reach the status document only through the
267
+ // job; a terminal install or an older job recorded none there.
268
+ if (!s.job?.status.dnsRecords) {
269
+ lines.push(dim(" The staging host's records are under Settings → Updates in the admin."));
270
+ }
271
+ return lines;
272
+ }
273
+
274
+ function ownerLines(s: ProjectStatus): string[] {
275
+ const { owner, install, adminUrl } = s;
276
+ const newLink = selfCommand("setup-link", "--project", install.projectId);
277
+ switch (owner.kind) {
278
+ case "not-yet":
279
+ return ["Owner setup: the link appears here when the install has finished."];
280
+ case "done":
281
+ return [`Owner setup: ${green("done.")} Sign in at ${cyan(adminUrl ?? "")}`];
282
+ case "withheld":
283
+ return [
284
+ `Owner setup: ${yellow(`a link is stored, valid until ${owner.expiresAt}, but it is a secret and only goes to a terminal.`)} Run this command in your own terminal, without a pipe or redirect.`,
285
+ ];
286
+ case "stale":
287
+ return [
288
+ `Owner setup: ${yellow(owner.expiresAt ? `the stored link expired on ${owner.expiresAt}.` : "the stored link has no token the admin can use.")} Nobody can use it. Get a new one: ${newLink}`,
289
+ ];
290
+ case "no-link":
291
+ return [
292
+ `Owner setup: no link is stored in this project (${INSTALL_SETUP_LINK_SECRET}). If Owner setup is done, sign in at ${cyan(adminUrl ?? "")}`,
293
+ ` If it is not, this stores a link and prints it: ${newLink}`,
294
+ ];
295
+ case "error":
296
+ return [`Owner setup: ${red(owner.message)}`];
297
+ case "link":
298
+ return [
299
+ `Owner setup: open this link in your browser, signed in as ${install.ownerEmail}. Do not share it. It works until ${owner.expiresAt}, then: ${newLink}`,
300
+ ` ${bold(cyan(owner.link))}`,
301
+ ...(owner.unverified === null
302
+ ? []
303
+ : [
304
+ yellow(
305
+ ` Could not check whether it was already used (${owner.unverified}). A used link just opens the sign-in page.`,
306
+ ),
307
+ ]),
308
+ ];
309
+ }
310
+ }
311
+
312
+ /** {@link ProjectStatus} as text. Holds the setup link only for {@link OwnerSetup} `link`. */
313
+ export function projectStatusLines(s: ProjectStatus): string[] {
314
+ return [
315
+ `Install: ${bold(s.install.installId)} ${dim(`(${s.install.provider})`)}`,
316
+ `Domain: ${bold(s.install.domain)}`,
317
+ `Project: ${bold(s.install.projectId)}`,
318
+ ...jobLines(s),
319
+ `Admin: ${s.adminUrl ? cyan(s.adminUrl) : "not known yet"}`,
320
+ ...dnsLines(s),
321
+ ...ownerLines(s),
322
+ ];
323
+ }
324
+
325
+ /** What to tell the operator about a failure of the command. */
326
+ export function projectStatusFailure(e: unknown): string {
327
+ if ((e as NodeJS.ErrnoException | undefined)?.code === "ENOENT") {
328
+ return "gcloud is not installed on this machine. Install the Google Cloud CLI (https://cloud.google.com/sdk/docs/install) or use Cloud Shell, run `gcloud auth login`, then run this command again.";
329
+ }
330
+ return e instanceof Error ? e.message : String(e);
331
+ }
332
+
333
+ /** The real {@link ProjectStatusDeps}: the operator's gcloud, public DNS, this process. */
334
+ function realProjectStatusDeps(): ProjectStatusDeps {
335
+ return {
336
+ run: gcloud,
337
+ syncRun: realSyncGcloud,
338
+ resolves: checkRecord,
339
+ ownerSetupState: (target) => readOwnerSetupState(target),
340
+ isTerminal: process.stdout.isTTY === true,
341
+ now: Date.now,
342
+ };
343
+ }
344
+
345
+ /**
346
+ * What `setup-link` does for an install in `status`: a line to print and stop
347
+ * on, or null to go on and issue a link. There is nothing to issue before the
348
+ * install finished or after an Owner exists, and a refused read must not
349
+ * read as "no link".
350
+ */
351
+ export function setupLinkRefusal(status: ProjectStatus): string | null {
352
+ switch (status.owner.kind) {
353
+ case "not-yet":
354
+ return "The install has not finished. Its last step stores the Owner setup link.";
355
+ case "done":
356
+ return `Owner setup is done; no link is needed. Sign in at ${status.adminUrl ?? "the admin"}.`;
357
+ case "error":
358
+ return status.owner.message;
359
+ default:
360
+ return null;
361
+ }
362
+ }
363
+
364
+ /**
365
+ * Lines of `setup-link`'s result. Holds the link only on a terminal, like
366
+ * {@link projectStatusLines}.
367
+ */
368
+ export function setupLinkLines(issued: OwnerSetupIssued, isTerminal: boolean): string[] {
369
+ const state = issued.minted ? "A new link is stored" : "The current link still works";
370
+ return isTerminal
371
+ ? [
372
+ `${state}, until ${issued.expiresAt}. Open it in your browser. Do not share it.`,
373
+ ` ${bold(cyan(issued.link))}`,
374
+ ]
375
+ : [`${state}, until ${issued.expiresAt}. It is a secret and only goes to a terminal.`];
376
+ }
377
+
378
+ /**
379
+ * `setup-link --project <id>` (#1476): a working Owner setup link for an
380
+ * install without an Owner, from any signed-in terminal. Exit 1 when none
381
+ * could be given.
382
+ */
383
+ export async function setupLinkCommand(argv: readonly string[]): Promise<void> {
384
+ const projectId = argv[argv.indexOf("--project") + 1] ?? "";
385
+ if (!argv.includes("--project") || !isGcpProjectId(projectId)) {
386
+ console.error("Usage: cms-provision setup-link --project <gcp-project-id>");
387
+ process.exit(2);
388
+ }
389
+ try {
390
+ const auth = await checkGcloudAuth();
391
+ if (!auth.ok) throw new Error(auth.error);
392
+ const deps = realProjectStatusDeps();
393
+ const status = await readProjectStatus(projectId, deps);
394
+ const refusal = setupLinkRefusal(status);
395
+ if (refusal !== null) {
396
+ console.log(refusal);
397
+ if (status.owner.kind !== "done") process.exitCode = 1;
398
+ return;
399
+ }
400
+ const { region } = status.install;
401
+ if (region === null || status.adminUrl === null) {
402
+ throw new Error(`install.json of ${projectId} records no region or admin URL.`);
403
+ }
404
+ const issued = await issueOwnerSetup(deps.run, { projectId, region }, status.adminUrl);
405
+ if (!issued.ok) throw new Error(issued.error);
406
+ for (const line of setupLinkLines(issued, deps.isTerminal)) console.log(line);
407
+ } catch (e) {
408
+ log.error(red(projectStatusFailure(e)));
409
+ process.exit(1);
410
+ }
411
+ }
412
+
413
+ /** `status --project <id>`: print where the install stands; exit 1 when part of it can't be read. */
414
+ export async function projectStatusCommand(argv: readonly string[]): Promise<void> {
415
+ const projectId = argv[argv.indexOf("--project") + 1] ?? "";
416
+ if (!isGcpProjectId(projectId) || argv.includes("--install")) {
417
+ console.error("Usage: cms-provision status --project <gcp-project-id>");
418
+ process.exit(2);
419
+ }
420
+ try {
421
+ const auth = await checkGcloudAuth();
422
+ if (!auth.ok) throw new Error(auth.error);
423
+ const status = await readProjectStatus(projectId, realProjectStatusDeps());
424
+ for (const line of projectStatusLines(status)) console.log(line);
425
+ if (status.owner.kind === "error") process.exitCode = 1;
426
+ } catch (e) {
427
+ log.error(red(projectStatusFailure(e)));
428
+ process.exit(1);
429
+ }
430
+ }
@@ -68,7 +68,10 @@ import {
68
68
  stagingGatewayEnvContract,
69
69
  staticBackendBucketPrefix,
70
70
  } from "./stack-contract.js";
71
- import { GCP_STATIC_RESPONSE_HEADERS } from "./static-security-headers.js";
71
+ import {
72
+ GCP_STATIC_RESPONSE_HEADERS,
73
+ withStaticResponseHeaders,
74
+ } from "./static-security-headers.js";
72
75
  import { ensureSvgDownloads } from "./static-svg-gcp.js";
73
76
 
74
77
  // ===========================================================================
@@ -590,19 +593,22 @@ async function ensureCdnPolicy(
590
593
  project,
591
594
  "--format=json",
592
595
  ]);
596
+ let liveHeaders: readonly string[] = [];
593
597
  if (describe.ok) {
594
598
  const live = JSON.parse(describe.stdout) as {
595
599
  cdnPolicy?: Record<string, unknown>;
596
600
  customResponseHeaders?: unknown;
597
601
  };
598
602
  const cdn = live.cdnPolicy;
603
+ if (Array.isArray(live.customResponseHeaders)) {
604
+ liveHeaders = live.customResponseHeaders.map(String);
605
+ }
599
606
  const inShape =
600
607
  cdn !== undefined &&
601
608
  (Object.keys(STATIC_CDN_POLICY) as (keyof typeof STATIC_CDN_POLICY)[]).every(
602
609
  (k) => String(cdn[k]) === String(STATIC_CDN_POLICY[k]),
603
610
  ) &&
604
- JSON.stringify(live.customResponseHeaders ?? []) ===
605
- JSON.stringify(GCP_STATIC_RESPONSE_HEADERS);
611
+ GCP_STATIC_RESPONSE_HEADERS.every((h) => liveHeaders.includes(h));
606
612
  if (inShape) return { ...base, status: "present" };
607
613
  }
608
614
  const update = await run([
@@ -615,8 +621,9 @@ async function ensureCdnPolicy(
615
621
  `--default-ttl=${STATIC_CDN_POLICY.defaultTtl}`,
616
622
  `--max-ttl=${STATIC_CDN_POLICY.maxTtl}`,
617
623
  `--client-ttl=${STATIC_CDN_POLICY.clientTtl}`,
618
- // Replaces the bucket's list, so this is the complete set.
619
- ...GCP_STATIC_RESPONSE_HEADERS.map((h) => `--custom-response-header=${h}`),
624
+ // Replaces the bucket's list, so this is the complete set: the stack's
625
+ // own headers and those of the live build (#1454, Publish live writes them).
626
+ ...withStaticResponseHeaders(liveHeaders).map((h) => `--custom-response-header=${h}`),
620
627
  "--quiet",
621
628
  ]);
622
629
  return update.ok
@@ -29,33 +29,35 @@ export type AttachResult =
29
29
  /** Install ids are `<provider>-<slug>` (install-state.ts deriveInstallId). */
30
30
  const INSTALL_ID = /^[a-z0-9][a-z0-9-]{0,80}$/;
31
31
 
32
+ /** The install record in a project's ops bucket, checked. */
33
+ export type ProjectInstallRecord =
34
+ | {
35
+ readonly ok: true;
36
+ readonly installId: string;
37
+ readonly domain: string;
38
+ /** install.json exactly as the bucket held it. */
39
+ readonly text: string;
40
+ }
41
+ | { readonly ok: false; readonly error: string };
42
+
32
43
  /**
33
- * Attach the install in `projectId` to this machine.
34
- *
35
- * @param deps.run gcloud runner (tests pass a fake bucket)
36
- * @param deps.rootFor `~/.caelo-<id>` for an install id
37
- * @param deps.hasLocalState whether a dir holds a local Pulumi stack
44
+ * Read and check `gs://<project>-caelo-ops/install/install.json`, touching
45
+ * nothing on this machine: shared by `attach` and `status --project`, which
46
+ * has to work with no local install directory at all (#822).
38
47
  */
39
- export function attachInstall(
40
- projectId: string,
41
- deps: {
42
- run: SyncGcloud;
43
- rootFor: (installId: string) => string;
44
- hasLocalState: (root: string) => boolean;
45
- },
46
- ): AttachResult {
48
+ export function readProjectInstall(projectId: string, run: SyncGcloud): ProjectInstallRecord {
47
49
  const bucket = opsBucketName(projectId);
48
50
  let text: string | null;
49
51
  try {
50
52
  // Peek: the directory to mirror into isn't known (or checked) yet.
51
- text = new GcsStateStore(bucket, "/nonexistent", deps.run).peek("install.json");
53
+ text = new GcsStateStore(bucket, "/nonexistent", run).peek("install.json");
52
54
  } catch (e) {
53
55
  return { ok: false, error: e instanceof Error ? e.message : String(e) };
54
56
  }
55
57
  if (text === null) {
56
58
  return {
57
59
  ok: false,
58
- error: `gs://${bucket} holds no install.json. If this install's state is still on the machine that installed it, run \`${selfCommand("state", "migrate")}\` there first.`,
60
+ error: `gs://${bucket} holds no install.json. Check the project id. If this install's state is still on the machine that installed it, run \`${selfCommand("state", "migrate")}\` there first.`,
59
61
  };
60
62
  }
61
63
  let remote: {
@@ -95,6 +97,34 @@ export function attachInstall(
95
97
  };
96
98
  }
97
99
 
100
+ return {
101
+ ok: true,
102
+ installId,
103
+ domain: typeof remote.domain === "string" ? remote.domain : installId,
104
+ text,
105
+ };
106
+ }
107
+
108
+ /**
109
+ * Attach the install in `projectId` to this machine.
110
+ *
111
+ * @param deps.run gcloud runner (tests pass a fake bucket)
112
+ * @param deps.rootFor `~/.caelo-<id>` for an install id
113
+ * @param deps.hasLocalState whether a dir holds a local Pulumi stack
114
+ */
115
+ export function attachInstall(
116
+ projectId: string,
117
+ deps: {
118
+ run: SyncGcloud;
119
+ rootFor: (installId: string) => string;
120
+ hasLocalState: (root: string) => boolean;
121
+ },
122
+ ): AttachResult {
123
+ const bucket = opsBucketName(projectId);
124
+ const record = readProjectInstall(projectId, deps.run);
125
+ if (!record.ok) return record;
126
+ const { installId, domain, text } = record;
127
+
98
128
  const root = deps.rootFor(installId);
99
129
  const localText = new LocalStateStore(root).read("install.json");
100
130
  // Local Pulumi state blocks the attach whether or not an install.json
@@ -126,7 +156,7 @@ export function attachInstall(
126
156
  return {
127
157
  ok: true,
128
158
  installId,
129
- domain: typeof remote.domain === "string" ? remote.domain : installId,
159
+ domain,
130
160
  status,
131
161
  };
132
162
  }
@@ -19,11 +19,27 @@ import {
19
19
  FRONT_DOOR_SECURITY_RULE_SET,
20
20
  frontDoorSecurityRules,
21
21
  GCP_STATIC_RESPONSE_HEADERS,
22
+ withStaticResponseHeaders,
22
23
  } from "./static-security-headers.js";
23
24
 
24
25
  const stack = (provider: string): string =>
25
26
  readFileSync(resolve(import.meta.dir, "..", "stacks", provider, "index.ts"), "utf8");
26
27
 
28
+ describe("GCP backend bucket (#1454)", () => {
29
+ it("a converge keeps the live build's page headers beside the stack's own", () => {
30
+ const live = ["Referrer-Policy: no-referrer", ...GCP_STATIC_RESPONSE_HEADERS];
31
+ expect(withStaticResponseHeaders(live)).toEqual([
32
+ ...GCP_STATIC_RESPONSE_HEADERS,
33
+ "Referrer-Policy: no-referrer",
34
+ ]);
35
+ expect(withStaticResponseHeaders([])).toEqual([...GCP_STATIC_RESPONSE_HEADERS]);
36
+ });
37
+
38
+ it("the stack does not reset what Publish live wrote", () => {
39
+ expect(stack("gcp")).toContain('ignoreChanges: ["customResponseHeaders"]');
40
+ });
41
+ });
42
+
27
43
  describe("AWS CloudFront response headers policies", () => {
28
44
  it("site: nosniff only (a CSP with sandbox would break every page)", () => {
29
45
  const p = cloudFrontHeadersPolicy("site");
@@ -22,7 +22,8 @@
22
22
  * - Firebase Hosting: version-config headers the publisher writes
23
23
  * (admin-core static-publisher-firebase.ts).
24
24
  * - GCP (`gcp` stack): the static backend bucket's custom response header
25
- * carries nosniff; the CSP cannot be attached per file on that load
25
+ * carries nosniff (and, written by Publish live, the live build's page
26
+ * headers, #1454); the CSP cannot be attached per file on that load
26
27
  * balancer (see `gcsObjectMetadata` in admin-core for why), so SVG
27
28
  * objects are stored `Content-Disposition: attachment` instead and the
28
29
  * converge backfills them (static-svg-gcp.ts).
@@ -44,6 +45,16 @@ export const GCP_STATIC_RESPONSE_HEADERS: readonly string[] = [
44
45
  `X-Content-Type-Options: ${NOSNIFF}`,
45
46
  ];
46
47
 
48
+ /**
49
+ * The list a converge writes: the stack's headers first, then whatever the
50
+ * bucket carries beside them. Those are the live build's page headers
51
+ * (#1454), which Publish live writes; the stack does not own them.
52
+ */
53
+ export function withStaticResponseHeaders(live: readonly string[]): string[] {
54
+ const own = new Set(GCP_STATIC_RESPONSE_HEADERS);
55
+ return [...GCP_STATIC_RESPONSE_HEADERS, ...live.filter((h) => !own.has(h))];
56
+ }
57
+
47
58
  // ===========================================================================
48
59
  // AWS — CloudFront
49
60
  // ===========================================================================