From 8f2c9e5bd8f8b2f8afe13be024b23c6a82c8ec30 Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:26:10 -0800 Subject: [PATCH 1/2] feat(infrastructure): manage public sharing in setup Add the public sharing Terraform root, setup wizard choice, release workflow keeper and docs. Sharing is off by default; Remove deletes the reader and grants but keeps the export storage and data. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/hub-azure-deploy.yml | 11 + .github/workflows/hub-infrastructure.yml | 4 +- hub/docs/deployment.md | 4 + infrastructure/README.md | 54 ++ .../azure/deploy-hub/private-preview/index.ts | 8 +- .../deploy-hub/public-share/index.test.ts | 336 +++++++++++ .../azure/deploy-hub/public-share/index.ts | 247 ++++++++ .../azure/install/approval/index.ts | 9 + .../azure/install/effective-grants/index.ts | 53 ++ infrastructure/azure/install/index.test.ts | 81 ++- infrastructure/azure/install/index.ts | 16 +- .../install/managed-certificate/index.ts | 49 ++ .../install/private-preview/grants/index.ts | 49 +- .../azure/install/private-preview/index.ts | 33 +- .../private-preview/state-guard/index.ts | 7 +- .../install/public-share/grants/index.ts | 60 ++ .../hub-environment/index.test.ts | 87 +++ .../public-share/hub-environment/index.ts | 99 ++++ .../azure/install/public-share/index.test.ts | 525 ++++++++++++++++++ .../azure/install/public-share/index.ts | 303 ++++++++++ .../install/public-share/plan/index.test.ts | 91 +++ .../azure/install/public-share/plan/index.ts | 59 ++ .../public-share/settings/index.test.ts | 24 + .../install/public-share/settings/index.ts | 93 ++++ .../azure/post/configure/index.test.ts | 27 + infrastructure/azure/post/configure/index.ts | 9 + .../azure/public-share/.terraform.lock.hcl | 23 + infrastructure/azure/public-share/main.tf | 346 ++++++++++++ .../public-share/tests/disabled.tftest.hcl | 137 +++++ .../azure/public-share/tests/modes.tftest.hcl | 182 ++++++ infrastructure/installer/config/index.test.ts | 24 + infrastructure/installer/config/index.ts | 36 +- infrastructure/installer/index.tsx | 2 +- .../public-share-choice/index.test.ts | 86 +++ .../installer/public-share-choice/index.ts | 58 ++ infrastructure/installer/types.ts | 11 + infrastructure/installer/wizard/index.ts | 21 + .../wizard/public-share-settings.test.ts | 204 +++++++ scripts/check-ci-workflows/index.ts | 9 + 39 files changed, 3397 insertions(+), 80 deletions(-) create mode 100644 infrastructure/azure/deploy-hub/public-share/index.test.ts create mode 100644 infrastructure/azure/deploy-hub/public-share/index.ts create mode 100644 infrastructure/azure/install/effective-grants/index.ts create mode 100644 infrastructure/azure/install/managed-certificate/index.ts create mode 100644 infrastructure/azure/install/public-share/grants/index.ts create mode 100644 infrastructure/azure/install/public-share/hub-environment/index.test.ts create mode 100644 infrastructure/azure/install/public-share/hub-environment/index.ts create mode 100644 infrastructure/azure/install/public-share/index.test.ts create mode 100644 infrastructure/azure/install/public-share/index.ts create mode 100644 infrastructure/azure/install/public-share/plan/index.test.ts create mode 100644 infrastructure/azure/install/public-share/plan/index.ts create mode 100644 infrastructure/azure/install/public-share/settings/index.test.ts create mode 100644 infrastructure/azure/install/public-share/settings/index.ts create mode 100644 infrastructure/azure/public-share/.terraform.lock.hcl create mode 100644 infrastructure/azure/public-share/main.tf create mode 100644 infrastructure/azure/public-share/tests/disabled.tftest.hcl create mode 100644 infrastructure/azure/public-share/tests/modes.tftest.hcl create mode 100644 infrastructure/installer/public-share-choice/index.test.ts create mode 100644 infrastructure/installer/public-share-choice/index.ts create mode 100644 infrastructure/installer/wizard/public-share-settings.test.ts diff --git a/.github/workflows/hub-azure-deploy.yml b/.github/workflows/hub-azure-deploy.yml index dbc430479..668e533b4 100644 --- a/.github/workflows/hub-azure-deploy.yml +++ b/.github/workflows/hub-azure-deploy.yml @@ -423,6 +423,17 @@ jobs: --state-resource-group "$AZURE_STATE_RESOURCE_GROUP" \ --state-account "$AZURE_STATE_STORAGE_ACCOUNT" \ --state-container "$AZURE_STATE_CONTAINER" + - name: Keep public sharing + env: + TF_DATA_DIR: ${{ runner.temp }}/public-share-terraform + HUB_IMAGE: ${{ steps.image.outputs.reference }} + run: | + node infrastructure/azure/deploy-hub/public-share/index.ts \ + --variables "$RUNNER_TEMP/installation.tfvars.json" \ + --image "$HUB_IMAGE" \ + --state-resource-group "$AZURE_STATE_RESOURCE_GROUP" \ + --state-account "$AZURE_STATE_STORAGE_ACCOUNT" \ + --state-container "$AZURE_STATE_CONTAINER" - name: Run the serialized maintenance-window release env: TF_DATA_DIR: ${{ runner.temp }}/terraform diff --git a/.github/workflows/hub-infrastructure.yml b/.github/workflows/hub-infrastructure.yml index 30ce0be8e..c4b6e069a 100644 --- a/.github/workflows/hub-infrastructure.yml +++ b/.github/workflows/hub-infrastructure.yml @@ -20,7 +20,7 @@ jobs: fail-fast: false matrix: version: ["1.13.4", "1.17.1"] - module: [".", "foundation", "provision", "private-preview"] + module: [".", "foundation", "provision", "private-preview", "public-share"] command: ["fmt -check -recursive", "validate", "test"] defaults: run: @@ -48,7 +48,7 @@ jobs: - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 - - run: node --test deploy-hub/index.test.ts deploy-hub/private-preview/index.test.ts stop-hub/index.test.ts ../installer/command/describe/index.test.ts + - run: node --test deploy-hub/index.test.ts deploy-hub/private-preview/index.test.ts deploy-hub/public-share/index.test.ts stop-hub/index.test.ts ../installer/command/describe/index.test.ts installer: name: Installer ${{ matrix.command }} diff --git a/hub/docs/deployment.md b/hub/docs/deployment.md index f817fe0eb..2ac17196e 100644 --- a/hub/docs/deployment.md +++ b/hub/docs/deployment.md @@ -58,6 +58,10 @@ Versioned references make rotation explicit. An unversioned runtime/setup URL is The Azure entrypoint also supports the scoped [GitHub author repair and webhook checks](github-actions-builds.md#commit-authors). These maintenance targets load the same runtime secret references into their own process before importing the command. +### Public share reader + +The same image runs the read-only [public share reader](public-share-reader.md) with `node dist/server/scripts/start-public-share-reader/index.js`. It is a separate deployment with its own settings and identity; never give it Hub's settings, which stop it at startup. The Azure installation runs it as an optional component, off by default, in its own Container Apps environment with a separate export storage account. Turning [public sharing](../../infrastructure/README.md#public-sharing) on with setup Update also sets Hub's `HUB_PUBLIC_SHARE_ENABLED`, `HUB_PUBLIC_SHARE_ORIGIN`, `HUB_PUBLIC_SHARE_STORAGE_ACCOUNT` and `HUB_PUBLIC_SHARE_STORAGE_CONTAINER`, plus `HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE=true` only for a non-production installation that accepts the shared-site override. Hub uses its existing managed identity for the export container. Setup Update owns these settings; do not set them by hand or through the release workflow's runtime JSON. + ## Setup before release Run `npm run setup` from `hub/`, or invoke `node dist/server/scripts/setup/index.js` inside the image. Normal API and worker startup never runs setup. diff --git a/infrastructure/README.md b/infrastructure/README.md index abdc756e9..32cc82418 100644 --- a/infrastructure/README.md +++ b/infrastructure/README.md @@ -291,6 +291,50 @@ The wizard sets these Hub settings itself and replaces manual values: `HUB_PRIVA **Staging pilot.** Staging's hand-created pilot inline app, `rep-hub-cai-stage-1-inline`, and its identity and grants are not in Terraform state. The wizard neither imports nor manages them. Retire them manually after the shared reader is verified on Staging. Its Terraform-managed reader, `rep-hub-cai-stage-1-preview`, is kept and upgraded in place. If the reader identity or Hub's identity still has access to `private-preview-artifacts` that the wizard did not create, Update stops before any change and names each grant; remove or review it, then rerun. +### Public sharing + +Public sharing lets signed-in Hub users give anyone a link to one Build. Hub copies the Build into a separate export storage, and a separate read-only reader serves the copy. [ADR 0003](../docs/adr/0003-public-sharing-export-reader.md) is the design and the [public share reader guide](../hub/docs/public-share-reader.md) describes the reader. Update asks for this setting after the private prototype service. Create keeps it off, because the choice depends on Hub's hostname, which exists only after the first release. + +- **Off** (default). Hub has no public sharing settings and the reader has no ingress. A configuration that never turned sharing on creates nothing, and no Terraform runs for it. After sharing has been on, Off keeps the reader as a placeholder without ingress, removes Hub's export grant, and keeps the export storage and every copied export. +- **On.** Creates or updates the export storage, the reader and its grants, and Hub's export grant, then releases Hub with the sharing settings below. +- **Remove** is the rollback. It deletes the reader app, its custom hostname, every reader grant and Hub's export grant, and turns sharing off in Hub. It keeps the export storage account, container and data, and the reader's resource group, environment and identity. + +Non-default choices are saved in the installation configuration as `publicShare`, for example `{ "reader": "on" }`. Non-interactive Update applies the saved choice. Rerunning Update with the same choice changes nothing except the image that Hub and the reader run. + +**Hub's hostname.** Browsers treat every generated `azurecontainerapps.io` hostname as one site, so a Hub on its generated hostname would be same-site with every shared prototype. Update therefore refuses to turn sharing on while Hub's `HUB_APPLICATION_ORIGIN` is a generated hostname; give Hub a custom domain with [post-setup](#post-setup-configuration) first. A non-production installation, such as Staging, may accept the trade-off instead: Update offers this only while Hub uses a generated hostname, shows the warning, and requires you to select that the installation is not production. It then saves `"allowSharedSite": true` and sets `HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE=true` on Hub. Update refuses the override when Hub has a custom domain, so a Production Hub on its custom domain never receives it. Post-setup refuses to change Hub's origin while sharing is on; turn it off with Update first. + +**Link hostname.** Links use the reader's generated hostname, `-share.`, in every installation. You can enter an optional custom domain for links. It must be outside `azurecontainerapps.io` and under a different registered domain from Hub's, such as `share.example.net` beside `replica.example.com`. The first Update with a custom domain prints its CNAME and TXT records; add them and run Update again. The wizard checks that both resolve, adds the hostname to the reader, and asks Azure for a managed certificate. Until the certificate is bound, new links keep using the generated hostname. The reader accepts both origins, so links on the generated hostname keep working after a custom domain is added. Changing or removing the custom domain while sharing is on is not supported; turn sharing off first. Links on the generated hostname stop working if the reader app or its environment is recreated. + +**What is created.** In the `-share` resource group: + +- The export storage account `pub` and its private `public-share-exports` container. Shared keys and anonymous access are off. Blobs are not versioned or soft-deleted, because Hub deletes copied files within 24 hours of revocation or expiry; the container can be restored for 7 days. +- The reader's Container Apps environment, without a subnet, so the reader has no network path to Hub's database, Key Vault or storage. It sends logs to Hub's existing Log Analytics workspace and pulls from the installation registry. +- The reader app `-share`. It runs Hub's immutable image digest with `node dist/server/scripts/start-public-share-reader/index.js`, as the non-root user, behind HTTPS-only ingress, with one replica and TCP startup, readiness and liveness probes. +- The reader's user-assigned identity `-share`. + +**What is granted.** The reader identity gets `AcrPull` on the installation registry and one `Storage Blob Data Reader` assignment on `public-share-exports` with an ABAC 2.0 condition that denies blob listing. It cannot list, write or delete exports, and gets nothing else. Hub's identity, which runs the API and workers, gets `Storage Blob Data Contributor` on `public-share-exports` only, while sharing is on. Before and after every change, the wizard checks both identities' effective grants, including grants through groups and at parent scopes, and stops on any grant it didn't create. + +**Settings.** The wizard sets these Hub settings itself and replaces manual values; a Key Vault reference for any of them blocks Update: + +| Setting | Value | +| --- | --- | +| `HUB_PUBLIC_SHARE_ENABLED` | `true` while sharing is on; unset otherwise | +| `HUB_PUBLIC_SHARE_ORIGIN` | The custom origin once its certificate is bound, otherwise the generated origin | +| `HUB_PUBLIC_SHARE_STORAGE_ACCOUNT`, `HUB_PUBLIC_SHARE_STORAGE_CONTAINER` | The export account and `public-share-exports` | +| `HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE` | `true` only with the non-production override; unset otherwise | + +The reader gets only its own settings: `PUBLIC_SHARE_GENERATED_ORIGIN`, `PUBLIC_SHARE_CUSTOM_ORIGIN` once a custom domain is bound, `PUBLIC_SHARE_TRUSTED_PROXY_HOPS=1`, `PUBLIC_SHARE_STORAGE_PROVIDER=azure`, the export account and container, and its own `AZURE_CLIENT_ID`. It refuses to start beside any Hub setting. + +**Order.** Before the Hub release, the wizard applies everything Hub may still use: a reader that is turning off stays on, with its custom hostname and Hub's export grant. On first enablement it waits for the reader's revision to become ready; if it doesn't, Hub's sharing stays off and the next Update rechecks. After the release, it disables or removes what the new Hub no longer uses, only if the serving Hub still has the settings this release gave it. Every plan is checked: only public sharing resources may change, nothing may be imported or moved, only the reader app may be updated, and the storage account, container, environment, identity and resource group are never updated, replaced or deleted. They also have Terraform's `prevent_destroy`. Saved state uses the same [fail-closed lineage checks](#private-prototype-service) as the private prototype service, with the `public-share.tfstate` key and the `-share` group. + +**Turn sharing on in Staging.** After this change and the Hub change that reads these settings are released to Staging: + +1. Run `npm run setup:server`, choose **Update**, and select Staging's configuration. +2. Choose **Public sharing: On** and leave the custom domain blank. Staging's Hub uses its generated hostname, so Update shows the shared-site warning; select the non-production option. +3. Review and approve the deployment. Update creates the `-share` resources, waits for the reader, releases Hub with the sharing settings, and prints the link origin. + +To roll back, run Update and choose **Remove** (or **Off** to keep a disabled reader). Exports stay in `public-share-exports`. + ### Local checks ```sh @@ -444,6 +488,16 @@ Before the release, the workflow keeps the [private prototype service](#private- Missing saved state while Hub has private preview settings, or state from the earlier preparation step, also stops the workflow. Use setup Update for every other change. The deployment identity needs Container Apps write access on the reader's resource group and Blob data access to the `private-preview.tfstate` key in the state container. +### Public sharing releases + +The workflow keeps [public sharing](#public-sharing) the same way, in its own step after the private prototype service. It never turns sharing on or off: + +- It copies Hub's current `HUB_PUBLIC_SHARE_*` settings from the running Hub into the release inputs. Do not put those names in `AZURE_RUNTIME_ENVIRONMENT_JSON` or `AZURE_RUNTIME_SECRET_REFERENCES_JSON`; the workflow stops if they are there. +- If Hub shares, it checks that the reader is on, Hub's export grant is in saved state, Hub's link origin is one of the reader's origins, Hub and the reader use the same export account and container, and the shared-site override is set exactly when Hub's origin is a generated hostname. +- It moves the reader to the release image. The public-share plan may change only that image. The apply holds the release lock and the same saved-state checks as Update. + +Missing `public-share.tfstate` while Hub has sharing settings also stops the workflow. The deployment identity needs Container Apps write access and resource read access on the `-share` resource group, and Blob data access to the `public-share.tfstate` key in the state container. + ### Deploy, recover, and verify Select **Actions**, **Deploy Hub to Azure development**, **Run workflow**, then approve the `hub-azure-development` Environment deployment. The release command retains its infinite lease when setup, rollout, digest verification, readiness, health, or provider-configuration checks fail. Review the failed setup execution, active revision and image digest, and Terraform state before following the existing [interrupted-installation recovery](#interrupted-installation) procedure. Do not cancel a running deployment or break its lease. diff --git a/infrastructure/azure/deploy-hub/private-preview/index.ts b/infrastructure/azure/deploy-hub/private-preview/index.ts index 612a3f46e..9d09fa388 100644 --- a/infrastructure/azure/deploy-hub/private-preview/index.ts +++ b/infrastructure/azure/deploy-hub/private-preview/index.ts @@ -222,7 +222,11 @@ export async function keepPrivatePreview({ } // Returns whether the plan moves the reader to the image, and rejects any other change. -export function onlyImageChange(plan: { resource_changes?: Change[] }, image: string): boolean { +export function onlyImageChange( + plan: { resource_changes?: Change[] }, + image: string, + fail: (reason: string) => never = block, +): boolean { let changed = false for (const { address, change } of plan.resource_changes ?? []) { const actions = Array.isArray(change?.actions) ? change.actions.join("/") : "" @@ -239,7 +243,7 @@ export function onlyImageChange(plan: { resource_changes?: Change[] }, image: st after?.template?.[0]?.container?.[0]?.image !== image || keys.some((name) => !sameJson((withImage as Record)[name], (after as Record)[name])) ) - block(`the release would ${actions} ${String(address)} beyond moving the reader to the new image.`) + fail(`the release would ${actions} ${String(address)} beyond moving the reader to the new image.`) changed = true } return changed diff --git a/infrastructure/azure/deploy-hub/public-share/index.test.ts b/infrastructure/azure/deploy-hub/public-share/index.test.ts new file mode 100644 index 000000000..9bc7362fa --- /dev/null +++ b/infrastructure/azure/deploy-hub/public-share/index.test.ts @@ -0,0 +1,336 @@ +import assert from "node:assert/strict" +import { randomUUID } from "node:crypto" +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { join, resolve } from "node:path" +import { afterEach, beforeEach, describe, it } from "node:test" + +import type { Run } from "../private-preview/index.ts" +import { keepPublicShare } from "./index.ts" + +const subscriptionId = "00000000-0000-0000-0000-000000000001" +const lineage = "11111111-1111-4111-8111-111111111111" +const oldImage = `example.azurecr.io/hub@sha256:${"a".repeat(64)}` +const newImage = `example.azurecr.io/hub@sha256:${"c".repeat(64)}` +const customHubOrigin = "https://replica.coreai.design" +const generatedHubOrigin = "https://sample-hub.example.eastus2.azurecontainerapps.io" +const generatedOrigin = "https://sample-hub-share.example.eastus2.azurecontainerapps.io" +const customOrigin = "https://share.example.net" +const writerPrincipal = "22222222-2222-4222-8222-222222222222" + +let directory: string +beforeEach(() => { + directory = resolve(import.meta.dirname, `.keep-share-test-${randomUUID()}`) + mkdirSync(directory, { mode: 0o700 }) +}) +afterEach(() => { + rmSync(directory, { recursive: true, force: true }) +}) + +// What the running Hub app has from the last setup Update that turned sharing on. +const sharingHub = { + HUB_PUBLIC_SHARE_ENABLED: "true", + HUB_PUBLIC_SHARE_ORIGIN: customOrigin, + HUB_PUBLIC_SHARE_STORAGE_ACCOUNT: "samplehubpub", + HUB_PUBLIC_SHARE_STORAGE_CONTAINER: "public-share-exports", +} + +function readerEnvironment(overrides: Record = {}) { + return Object.entries({ + PUBLIC_SHARE_GENERATED_ORIGIN: generatedOrigin, + PUBLIC_SHARE_CUSTOM_ORIGIN: customOrigin, + PUBLIC_SHARE_STORAGE_ACCOUNT: "samplehubpub", + PUBLIC_SHARE_STORAGE_CONTAINER: "public-share-exports", + ...overrides, + }).map(([name, value]) => ({ name, value })) +} + +function readerApp(image: string, { ingress = true, env = readerEnvironment() } = {}) { + return { + template: [{ container: [{ name: "reader", image, env }] }], + ingress: ingress ? [{ external_enabled: true, target_port: 3003 }] : [], + registry: [{ server: "example.azurecr.io" }], + identity: [{ type: "UserAssigned" }], + workload_profile_name: "Consumption", + } +} + +const update = (address: string, before: unknown, after: unknown) => ({ + address, + change: { actions: ["update"], before, after }, +}) + +function scenario({ + hub = sharingHub as Record, + hubOrigin = customHubOrigin, + stateExists = true, + reader = readerApp(oldImage) as ReturnType | null, + domain = true, + writer = true, + openedLineage = lineage, + plan, + applyFails = false, + supplied = {} as Record, + suppliedReferences = {} as Record, +}: { + hub?: Record + // The origin the release gives Hub; null leaves it out of the release inputs. + hubOrigin?: string | null + stateExists?: boolean + reader?: ReturnType | null + domain?: boolean + writer?: boolean + openedLineage?: string + plan?: { resource_changes: unknown[] } + applyFails?: boolean + supplied?: Record + suppliedReferences?: Record +} = {}) { + const variablesPath = join(directory, "hub.tfvars.json") + writeFileSync(variablesPath, JSON.stringify({ + subscription_id: subscriptionId, + name: "sample-hub", + owner: "sample-team", + location: "eastus2", + resource_group_name: "sample-hub-rg", + acr_id: `/subscriptions/${subscriptionId}/resourceGroups/sample-hub-foundation/providers/Microsoft.ContainerRegistry/registries/example`, + image: newImage, + ...(hubOrigin && { hub_application_origin: hubOrigin }), + runtime_environment_variables: { HUB_TRUSTED_PROXY_HOPS: "1", PUBLIC_SETTING: "kept", ...supplied }, + runtime_secret_references: suppliedReferences, + }), { mode: 0o600 }) + const savedState = JSON.stringify({ version: 4, terraform_version: "1.13.0", serial: 7, lineage, outputs: {}, resources: [] }) + const resources = [ + ...[ + "azurerm_resource_group.share", + "azurerm_storage_account.exports", + "azurerm_storage_container.exports", + "azurerm_container_app_environment.share", + "azurerm_user_assigned_identity.reader", + ].map((address) => ({ address, values: {} })), + ...(reader ? [{ address: "azurerm_container_app.reader[0]", values: reader }] : []), + ...(domain ? [{ address: "azurerm_container_app_custom_domain.reader[0]", values: { name: "share.example.net" } }] : []), + ...(writer ? [{ address: "azurerm_role_assignment.writer[0]", values: { principal_id: writerPrincipal } }] : []), + ] + const imageOnly = reader + ? { resource_changes: [update("azurerm_container_app.reader[0]", reader, readerApp(newImage, { + ingress: reader.ingress.length > 0, + env: reader.template[0]!.container[0]!.env, + }))] } + : { resource_changes: [] } + const commands: string[][] = [] + const planVariables: Record[] = [] + const logs: string[] = [] + const run: Run = async (executable, args) => { + commands.push([executable, ...args]) + if (executable === "az") { + const operation = args.slice(0, 4).join(" ") + if (operation.startsWith("containerapp list")) + return JSON.stringify([{ + env: [ + { name: "HUB_APPLICATION_ORIGIN", value: hubOrigin ?? customHubOrigin }, + ...Object.entries(hub).map(([name, value]) => ({ name, value })), + ], + }]) + if (operation.startsWith("storage blob exists")) return JSON.stringify({ exists: stateExists }) + if (operation.startsWith("storage blob download")) { + writeFileSync(args[args.indexOf("--file") + 1]!, savedState) + return "" + } + if (operation === "storage blob lease acquire" || operation === "storage blob lease release") return "" + } + if (executable === "terraform") { + const [, operation, ...rest] = args + if (operation === "init") return "" + if (operation === "state" && rest[0] === "pull") + return JSON.stringify({ ...JSON.parse(savedState), lineage: openedLineage }) + if (operation === "show" && rest.length === 1) + return JSON.stringify({ format_version: "1.0", values: { root_module: { resources } } }) + if (operation === "plan") { + const file = rest.find((arg) => arg.startsWith("-var-file="))!.slice("-var-file=".length) + planVariables.push(JSON.parse(readFileSync(file, "utf8"))) + return "" + } + if (operation === "show") return JSON.stringify(plan ?? imageOnly) + if (operation === "apply") { + if (applyFails) throw new Error("terraform apply failed") + return "" + } + } + throw new Error(`Unexpected command ${executable} ${args.join(" ")}`) + } + const keep = () => keepPublicShare({ + run, + variablesPath, + image: newImage, + state: { resourceGroup: "sample-hub-state", account: "replicastatesample", container: "terraform" }, + dataDirectory: join(directory, "terraform"), + log: (message) => logs.push(message), + }) + const ran = (...prefix: string[]) => + commands.filter((command) => prefix.every((part, index) => + command[0] === "terraform" ? command[index + (index ? 1 : 0)] === part : command[index] === part)) + const tfvars = () => readFileSync(variablesPath, "utf8") + return { keep, commands, ran, planVariables, logs, tfvars } +} + +describe("keepPublicShare", () => { + it("runs no Terraform and leaves the release inputs unchanged when sharing was never set up", async () => { + const s = scenario({ hub: {}, stateExists: false }) + const before = s.tfvars() + + await s.keep() + + assert.deepEqual(s.ran("terraform"), []) + assert.equal(s.tfvars(), before) + }) + + it("blocks when Hub has public sharing settings but the saved state is missing", async () => { + const s = scenario({ stateExists: false }) + + await assert.rejects(s.keep(), /public-share\.tfstate is missing/) + assert.deepEqual(s.ran("terraform"), []) + }) + + for (const [label, supplied] of [ + ["a GitHub Environment setting", { supplied: { HUB_PUBLIC_SHARE_ORIGIN: "https://manual.example.net" } }], + ["a GitHub Environment secret reference", { suppliedReferences: { HUB_PUBLIC_SHARE_ENABLED: { secret_id: "x" } } }], + ] as const) + it(`blocks public sharing settings supplied as ${label} before any command`, async () => { + const s = scenario(supplied) + + await assert.rejects(s.keep(), /from the GitHub Environment/) + assert.deepEqual(s.commands, []) + }) + + it("copies Hub's share settings into the release and moves only the reader image under the release lease", async () => { + const s = scenario() + + await s.keep() + + assert.deepEqual(JSON.parse(s.tfvars()).runtime_environment_variables, { + HUB_TRUSTED_PROXY_HOPS: "1", + PUBLIC_SETTING: "kept", + ...sharingHub, + }) + assert.equal(s.planVariables.length, 1) + const variables = s.planVariables[0]! + assert.equal(variables.image, newImage) + assert.equal(variables.reader, "enabled") + assert.equal(variables.custom_hostname, "share.example.net") + assert.equal(variables.bind_custom_hostname, true) + assert.equal(variables.writer_principal_id, writerPrincipal) + const order = s.commands.map((command) => command.slice(0, 6).join(" ")) + const acquire = order.findIndex((command) => command.includes("lease acquire")) + const apply = order.findIndex((command) => / apply /.test(` ${command} `)) + const release = order.findIndex((command) => command.includes("lease release")) + assert.ok(acquire >= 0 && acquire < apply && apply < release) + }) + + it("keeps the non-production override for a Hub on its generated hostname", async () => { + const hub = { ...sharingHub, HUB_PUBLIC_SHARE_ORIGIN: generatedOrigin, HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE: "true" } + const s = scenario({ hub, hubOrigin: generatedHubOrigin }) + + await s.keep() + + assert.equal(JSON.parse(s.tfvars()).runtime_environment_variables.HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE, "true") + assert.equal(s.ran("terraform", "apply").length, 1) + }) + + it("keeps sharing off: Hub gets no share settings and the reader stays disabled without Hub's grant", async () => { + const s = scenario({ hub: {}, reader: readerApp(oldImage, { ingress: false, env: [] }), domain: false, writer: false }) + + await s.keep() + + const saved = JSON.parse(s.tfvars()).runtime_environment_variables + assert.deepEqual(Object.keys(saved).filter((name) => name.startsWith("HUB_PUBLIC_SHARE_")), []) + assert.equal(s.planVariables[0]!.reader, "disabled") + assert.equal(s.planVariables[0]!.writer_principal_id, null) + assert.equal(s.planVariables[0]!.custom_hostname, null) + }) + + it("plans nothing after Remove", async () => { + const s = scenario({ hub: {}, reader: null, domain: false, writer: false }) + + await s.keep() + + assert.deepEqual(s.ran("terraform", "plan"), []) + assert.deepEqual(s.ran("az", "storage", "blob", "lease"), []) + }) +}) + +describe("keepPublicShare blocks a release that disagrees with saved reader state", () => { + for (const [label, options, message] of [ + ["Hub shares while the reader is off", { reader: readerApp(oldImage, { ingress: false, env: [] }) }, /reader is not on/], + ["Hub shares while the reader is removed", { reader: null }, /reader is not on/], + ["Hub's export grant is not in saved state", { writer: false }, /export grant is not in saved state/], + ["Hub's origin is not one of the reader's", { hub: { ...sharingHub, HUB_PUBLIC_SHARE_ORIGIN: "https://other.example.net" } }, /the link origin/], + ["the export storage account differs", { hub: { ...sharingHub, HUB_PUBLIC_SHARE_STORAGE_ACCOUNT: "otherpub" } }, /the export storage account/], + ["the export container differs", { hub: { ...sharingHub, HUB_PUBLIC_SHARE_STORAGE_CONTAINER: "other" } }, /the export container/], + [ + "a Hub on its generated hostname shares without the override", + { hubOrigin: generatedHubOrigin, hub: { ...sharingHub, HUB_PUBLIC_SHARE_ORIGIN: generatedOrigin } }, + /without the non-production shared-site override/, + ], + ["the release inputs have no Hub origin", { hubOrigin: null }, /release inputs have no HUB_APPLICATION_ORIGIN/], + [ + "Hub's custom origin may be the same site as the reader's custom domain", + { hubOrigin: "https://hub.example.net" }, + /may be the same site as the reader's custom domain/, + ], + [ + "a Hub on a custom domain has the override", + { hub: { ...sharingHub, HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE: "true" } }, + /override is set, but Hub's origin is not a generated hostname/, + ], + ] as const) + it(`blocks before planning when ${label} and leaves the inputs untouched`, async () => { + const s = scenario(options) + const before = s.tfvars() + + await assert.rejects(s.keep(), message) + assert.equal(s.tfvars(), before) + assert.deepEqual(s.ran("terraform", "plan"), []) + assert.deepEqual(s.ran("terraform", "apply"), []) + }) + + it("blocks when Terraform opens a different state than the saved one", async () => { + const s = scenario({ openedLineage: randomUUID() }) + + await assert.rejects(s.keep(), /different state/) + assert.deepEqual(s.ran("terraform", "plan"), []) + }) +}) + +describe("keepPublicShare accepts only an image change", () => { + const before = readerApp(oldImage) + for (const [label, change] of [ + ["removes Hub's grant", { address: "azurerm_role_assignment.writer[0]", change: { actions: ["delete"] } }], + ["updates the export storage", update("azurerm_storage_account.exports", {}, { shared_access_key_enabled: true })], + ["changes the reader ingress", update("azurerm_container_app.reader[0]", before, { ...readerApp(newImage), ingress: [] })], + ] as const) + it(`blocks a plan that ${label} without taking the lease or applying`, async () => { + const s = scenario({ plan: { resource_changes: [change] } }) + + await assert.rejects(s.keep(), /Public sharing check failed: .*beyond moving the reader to the new image/) + assert.deepEqual(s.ran("terraform", "apply"), []) + assert.deepEqual(s.ran("az", "storage", "blob", "lease"), []) + }) + + it("takes no lease and applies nothing when the reader already runs the image", async () => { + const s = scenario({ plan: { resource_changes: [{ address: "azurerm_container_app.reader[0]", change: { actions: ["no-op"] } }] } }) + + await s.keep() + + assert.deepEqual(s.ran("terraform", "apply"), []) + assert.deepEqual(s.ran("az", "storage", "blob", "lease"), []) + }) + + it("keeps the release lease when the apply fails", async () => { + const s = scenario({ applyFails: true }) + + await assert.rejects(s.keep(), /terraform apply failed/) + assert.equal(s.ran("az", "storage", "blob", "lease", "acquire").length, 1) + assert.deepEqual(s.ran("az", "storage", "blob", "lease", "release"), []) + assert.ok(s.logs.some((message) => /lease is retained/.test(message))) + }) +}) diff --git a/infrastructure/azure/deploy-hub/public-share/index.ts b/infrastructure/azure/deploy-hub/public-share/index.ts new file mode 100644 index 000000000..5e6b135df --- /dev/null +++ b/infrastructure/azure/deploy-hub/public-share/index.ts @@ -0,0 +1,247 @@ +import childProcess from "node:child_process" +import { randomUUID } from "node:crypto" +import { mkdir, readFile, rm, writeFile } from "node:fs/promises" +import { join, resolve } from "node:path" +import { pathToFileURL } from "node:url" +import { parseArgs } from "node:util" + +import { describeCommand } from "../../../installer/command/describe/index.ts" +import { + isGeneratedHost, + mayBeSameSite, + ownedHubShareSettings, +} from "../../install/public-share/hub-environment/index.ts" +import { guardPreviewState } from "../../install/private-preview/state-guard/index.ts" +import { onlyImageChange, type Run } from "../private-preview/index.ts" + +type Env = { name?: unknown; value?: unknown } +type StateResource = { address?: unknown; values?: Record } +type Variables = { + subscription_id: string + name: string + owner: string + location: string + resource_group_name: string + acr_id: string + hub_application_origin?: string + runtime_environment_variables?: Record + runtime_secret_references?: Record +} + +const owned: readonly string[] = ownedHubShareSettings +const shareRoot = resolve(import.meta.dirname, "../../public-share") + +const block = (reason: string): never => { + throw new Error( + `Public sharing check failed: ${reason} Hub was not released. Use setup Update to change public sharing.`, + ) +} + +/* + * Keeps public sharing exactly as setup Update left it. Copies Hub's current public sharing + * settings into the release inputs, checks them against the reader's saved state, and moves the + * reader to the new image with a plan that may change nothing else. + */ +export async function keepPublicShare({ + run, + variablesPath, + image, + state, + dataDirectory, + log = console.log, +}: { + run: Run + variablesPath: string + image: string + state: { resourceGroup: string; account: string; container: string } + dataDirectory: string + log?(message: string): void +}): Promise { + const variables = JSON.parse(await readFile(variablesPath, "utf8")) as Variables + const environment = { ...variables.runtime_environment_variables } + const supplied = owned.filter((key) => key in environment || key in (variables.runtime_secret_references ?? {})) + if (supplied.length) + block(`remove ${supplied.join(", ")} from the GitHub Environment; the release copies them from Hub.`) + const azure = (...args: string[]) => + run("az", [...args, "--subscription", variables.subscription_id, "--only-show-errors", "--output", "json"]) + const read = async (...args: string[]) => JSON.parse(await azure(...args)) as T + + const apps = await read<{ env?: Env[] | null }[]>( + "containerapp", "list", "--resource-group", variables.resource_group_name, + "--query", `[?name=='${variables.name}-hub'].{env:properties.template.containers[?name=='hub'] | [0].env}`, + ) + if (!Array.isArray(apps) || apps.length > 1) block("Hub's current settings could not be read.") + const live = new Map() + for (const { name, value } of apps[0]?.env ?? []) + if (typeof name === "string" && typeof value === "string") live.set(name, value) + const hubSettings = Object.fromEntries(owned.flatMap((key) => (live.has(key) ? [[key, live.get(key)!]] : []))) + + const key = `${variables.name}/public-share.tfstate` + const { exists } = await read<{ exists?: unknown }>( + "storage", "blob", "exists", "--account-name", state.account, "--container-name", state.container, + "--name", key, "--auth-mode", "login", + ) + if (typeof exists !== "boolean") block("Azure did not confirm whether saved public sharing state exists.") + if (!exists) { + if (Object.keys(hubSettings).length) block(`Hub has public sharing settings but ${key} is missing.`) + log("Public sharing is not set up; nothing to keep.") + return + } + + await mkdir(dataDirectory, { recursive: true, mode: 0o700 }) + const terraform = (...args: string[]) => run("terraform", [`-chdir=${shareRoot}`, ...args]) + const guard = await guardPreviewState({ + azure, + directory: dataDirectory, + target: { account: state.account, container: state.container, key }, + resourcesExist: async () => true, + subject: "Public sharing", + }) + const backend = join(dataDirectory, "public-share-backend.hcl") + await writeFile(backend, [ + `resource_group_name = ${JSON.stringify(state.resourceGroup)}`, + `storage_account_name = ${JSON.stringify(state.account)}`, + `container_name = ${JSON.stringify(state.container)}`, + `key = ${JSON.stringify(key)}`, + "use_azuread_auth = true", + "use_oidc = true", + "", + ].join("\n"), { mode: 0o600 }) + await terraform("init", "-input=false", "-lock-timeout=60s", `-backend-config=${backend}`) + guard.verify(JSON.parse(await terraform("state", "pull"))) + const snapshot = JSON.parse(await terraform("show", "-json")) as { + values?: { root_module?: { resources?: StateResource[] } } + } + const resources = snapshot.values?.root_module?.resources ?? [] + const find = (address: string) => resources.find((resource) => resource.address === address)?.values + const app = find("azurerm_container_app.reader[0]") + const container = (app?.template as { container?: { env?: Env[] }[] }[] | undefined)?.[0]?.container?.[0] + const readerEnv = new Map( + (container?.env ?? []).flatMap(({ name, value }) => (typeof name === "string" && typeof value === "string" ? [[name, value]] : [])), + ) + const enabled = Boolean((app?.ingress as unknown[] | undefined)?.length) + const domain = find("azurerm_container_app_custom_domain.reader[0]")?.name + const writerPrincipal = find("azurerm_role_assignment.writer[0]")?.principal_id + + if (hubSettings.HUB_PUBLIC_SHARE_ENABLED === "true") { + if (!enabled) block("Hub shares Builds publicly, but the reader is not on.") + if (typeof writerPrincipal !== "string") block("Hub shares Builds publicly, but its export grant is not in saved state.") + const origins = [readerEnv.get("PUBLIC_SHARE_GENERATED_ORIGIN"), readerEnv.get("PUBLIC_SHARE_CUSTOM_ORIGIN")] + const mismatched = [ + ["the link origin", origins.includes(hubSettings.HUB_PUBLIC_SHARE_ORIGIN)], + ["the export storage account", hubSettings.HUB_PUBLIC_SHARE_STORAGE_ACCOUNT === readerEnv.get("PUBLIC_SHARE_STORAGE_ACCOUNT")], + ["the export container", hubSettings.HUB_PUBLIC_SHARE_STORAGE_CONTAINER === readerEnv.get("PUBLIC_SHARE_STORAGE_CONTAINER")], + ].filter(([, same]) => !same).map(([label]) => label) + if (mismatched.length) block(`Hub and the reader disagree on ${mismatched.join(", ")}.`) + // The origin this release gives Hub, which Hub compares with the link origin at startup. + const hubOrigin = variables.hub_application_origin ?? environment.HUB_APPLICATION_ORIGIN + if (typeof hubOrigin !== "string" || !URL.canParse(hubOrigin)) + block("the release inputs have no HUB_APPLICATION_ORIGIN, which Hub needs to share Builds.") + const hubHost = new URL(hubOrigin!).hostname + const generatedHub = isGeneratedHost(hubHost) + const customLinkHost = readerEnv.get("PUBLIC_SHARE_CUSTOM_ORIGIN") + if (!generatedHub && customLinkHost && mayBeSameSite(hubHost, new URL(customLinkHost).hostname)) + block(`Hub's origin ${hubOrigin} may be the same site as the reader's custom domain.`) + if (generatedHub !== (hubSettings.HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE === "true")) + block( + generatedHub + ? "Hub would share from a generated hostname without the non-production shared-site override." + : "the shared-site override is set, but Hub's origin is not a generated hostname.", + ) + } + + await writeFile(variablesPath, JSON.stringify({ + ...variables, + runtime_environment_variables: { ...environment, ...hubSettings }, + }), { mode: 0o600 }) + + if (!app) { + log("The share reader app is removed; Hub's public sharing settings were kept.") + return + } + const shareVariables = join(dataDirectory, "public-share.tfvars.json") + await writeFile(shareVariables, JSON.stringify({ + subscription_id: variables.subscription_id, + resource_group_name: variables.resource_group_name, + location: variables.location, + name: variables.name, + owner: variables.owner, + acr_id: variables.acr_id, + registry_server: image.split("/")[0], + image, + reader: enabled ? "enabled" : "disabled", + custom_hostname: typeof domain === "string" ? domain : null, + bind_custom_hostname: typeof domain === "string", + writer_principal_id: typeof writerPrincipal === "string" ? writerPrincipal : null, + }), { mode: 0o600 }) + const planPath = join(dataDirectory, `public-share-${randomUUID()}.tfplan`) + try { + await terraform("plan", "-input=false", "-lock-timeout=60s", `-var-file=${shareVariables}`, `-out=${planPath}`) + const plan = JSON.parse(await terraform("show", "-json", planPath)) as Parameters[0] + if (!onlyImageChange(plan, image, block)) { + log("The share reader already runs this image.") + return + } + const releaseLock = [ + "--account-name", `${variables.name.replaceAll("-", "")}hub`, "--container-name", "releases", + "--blob-name", "deployment.lock", "--auth-mode", "login", + ] + const lease = randomUUID() + await azure("storage", "blob", "lease", "acquire", ...releaseLock, "--lease-duration", "-1", "--proposed-lease-id", lease) + try { + guard.verify(JSON.parse(await terraform("state", "pull"))) + await terraform("apply", "-input=false", "-lock-timeout=60s", planPath) + guard.verify(JSON.parse(await terraform("state", "pull"))) + } catch (error) { + log("The release lease is retained. Verify the share reader and saved state before an operator breaks it.") + throw error + } + await azure("storage", "blob", "lease", "release", ...releaseLock, "--lease-id", lease) + log("The share reader now runs the release image.") + } finally { + await rm(planPath, { force: true }) + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + const { values } = parseArgs({ + options: { + variables: { type: "string" }, + image: { type: "string" }, + "state-resource-group": { type: "string" }, + "state-account": { type: "string" }, + "state-container": { type: "string" }, + }, + }) + const run: Run = async (executable, args) => { + try { + return childProcess.execFileSync(executable, args, { + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + maxBuffer: 32 * 1024 * 1024, + }) + } catch { + // Tool output can contain credentials and lease identifiers. + throw new Error(`${describeCommand(executable, args).label} failed. Tool output remains private.`) + } + } + try { + const required = (name: keyof typeof values) => values[name] ?? block(`--${name} is required.`) + const image = required("image") + if (!/^[a-z0-9][a-z0-9.:/-]+@sha256:[a-f0-9]{64}$/.test(image)) block("--image must name an immutable digest.") + await keepPublicShare({ + run, + variablesPath: resolve(required("variables")), + image, + state: { + resourceGroup: required("state-resource-group"), + account: required("state-account"), + container: required("state-container"), + }, + dataDirectory: resolve(process.env.TF_DATA_DIR ?? ".terraform"), + }) + } catch (error) { + console.error(error instanceof Error ? error.message : "Unknown failure") + process.exitCode = 1 + } +} diff --git a/infrastructure/azure/install/approval/index.ts b/infrastructure/azure/install/approval/index.ts index 6138c2f52..457649c81 100644 --- a/infrastructure/azure/install/approval/index.ts +++ b/infrastructure/azure/install/approval/index.ts @@ -16,6 +16,14 @@ function describePrivatePreview({ privatePreview: choice }: AzureInstallation["c return `off. No reader ingress; an existing disabled reader is kept and its grant is limited to deny listing.${writer}` } +function describePublicShare({ publicShare: choice }: AzureInstallation["config"]) { + if (choice?.reader === "on") + return `on. Export storage account and container, reader ${choice.hostname ? `on its generated hostname and ${choice.hostname} (DNS records are printed if missing)` : "on its generated hostname"}, its identity and grants, and Hub's container-scoped export grant are created or updated.${choice.allowSharedSite ? " Non-production shared-site override accepted: Hub keeps its generated hostname." : ""}` + if (choice?.reader === "removed") + return "remove. The reader app, its hostname and every reader and Hub export grant are deleted; export storage and data are kept." + return "off. No public links. Nothing is created; an existing reader is kept disabled without ingress, Hub's export grant is removed, and export storage and data are kept." +} + const readerLocation = (hostname: string | undefined) => hostname ? `on ${hostname} (DNS records are printed if missing)` : "on its generated hostname" @@ -55,6 +63,7 @@ export async function approveDeployment( "- Compute and logs: Container Apps environment, Hub app, setup job, and Log Analytics.", "- Access: separate workload identities and scoped deployment/workload grants for state, Blob, registry, and Key Vault.", `- Private prototype service: ${describePrivatePreview(config)}`, + `- Public sharing: ${describePublicShare(config)}`, `- First-installation provisioning: temporary job and identity ${config.name}-provision and their scoped grants; these temporary resources are removed after success.`, "", `Source: ${sourceRevision}${sourceStatus ? " with uncommitted changes" : " (clean checkout)"}.`, diff --git a/infrastructure/azure/install/effective-grants/index.ts b/infrastructure/azure/install/effective-grants/index.ts new file mode 100644 index 000000000..4141e093c --- /dev/null +++ b/infrastructure/azure/install/effective-grants/index.ts @@ -0,0 +1,53 @@ +import { listingDeniedCondition } from "../private-preview/plan/index.ts" + +export interface Assignment { + id: string + scope: string + principalId: string + roleDefinitionName: string + condition: string | null + conditionVersion: string | null +} + +const query = + "[].{id:id,scope:scope,principalId:principalId,roleDefinitionName:roleDefinitionName,condition:condition,conditionVersion:conditionVersion}" + +export const sameResource = (left: string, right: string) => + left.replace(/\/+$/, "").toLowerCase() === right.replace(/\/+$/, "").toLowerCase() + +const compact = (value: string | null) => value?.replace(/\s+/g, "") ?? "" +export const deniesListing = (grant: Assignment) => + compact(grant.condition) === compact(listingDeniedCondition) && grant.conditionVersion === "2.0" + +// Any grant at the resource or one of its parents, including management groups, reaches it. +export function reaches(scope: string, resourceId: string) { + const parent = scope.replace(/\/+$/, "").toLowerCase() + const resource = resourceId.toLowerCase() + return !parent.startsWith("/subscriptions/") || resource === parent || resource.startsWith(`${parent}/`) +} + +/* + * Every role assignment that applies to a principal, including grants to groups that contain it. + * --all does not inspect parent management groups; a scoped query does not inspect children. + */ +export async function effectiveGrants( + read: (...args: string[]) => Promise, + subscriptionId: string, + principalId: string, +): Promise { + const list = async (...args: string[]) => { + const value = await read("role", "assignment", "list", ...args, "--fill-principal-name", "false", "--query", query) + if (!Array.isArray(value) || + value.some((item) => !item || typeof item.id !== "string" || typeof item.scope !== "string" || + typeof item.principalId !== "string" || typeof item.roleDefinitionName !== "string")) + throw new Error("Grants could not be verified: Azure returned incomplete role assignments.") + return value as Assignment[] + } + return [ + ...(await list("--assignee-object-id", principalId, "--all", "--include-groups")), + ...(await list( + "--assignee-object-id", principalId, "--scope", `/subscriptions/${subscriptionId}`, + "--include-inherited", "--include-groups", + )), + ].filter((grant, index, all) => all.findIndex((other) => sameResource(other.id, grant.id)) === index) +} diff --git a/infrastructure/azure/install/index.test.ts b/infrastructure/azure/install/index.test.ts index ba2674364..4acbbd4fc 100644 --- a/infrastructure/azure/install/index.test.ts +++ b/infrastructure/azure/install/index.test.ts @@ -21,6 +21,7 @@ import { installAzure } from "./index.ts" import * as recovery from "./lease/recover/index.ts" import { leaseOwnership } from "./lease/ownership/index.ts" import * as privatePreview from "./private-preview/index.ts" +import * as publicShare from "./public-share/index.ts" import { installationNames } from "./settings.ts" import { guidedPostgresProfile, @@ -226,7 +227,7 @@ async function scenario({ }) if (operation === "storage blob exists") return JSON.stringify({ - exists: !args[args.indexOf("--name") + 1]!.endsWith("/private-preview.tfstate"), + exists: !/\/(?:private-preview|public-share)\.tfstate$/.test(args[args.indexOf("--name") + 1]!), }) if (operation === "storage container-rm exists") return JSON.stringify({ exists: false }) if (operation === "storage blob show") @@ -1713,6 +1714,84 @@ it("does not finish the private prototype service when the release fails", async expect(finish).not.toHaveBeenCalled() }) +function shareStep(order: string[]) { + const note = "Public sharing: new links use https://test-hub-share.example.eastus2.azurecontainerapps.io." + const finish = vi.fn(async () => { + order.push("share finish") + return [note] + }) + vi.spyOn(publicShare, "preparePublicShare").mockImplementation(async (_, { inputs }) => { + order.push("share prepare") + return { + inputs: { + ...inputs, + runtime_environment_variables: { ...inputs.runtime_environment_variables, HUB_PUBLIC_SHARE_ENABLED: "true" }, + }, + finish, + } + }) + return { note, finish } +} + +it("releases Hub with both services' settings and finishes public sharing after the release and the private prototype service", async () => { + const s = await scenario() + await withSignIn(s) + const order: string[] = [] + const preview = previewStep(order) + const share = shareStep(order) + let released: Record | undefined + const run = vi.fn(async (executable, args, options) => { + if (executable === process.execPath) { + order.push("release") + released = JSON.parse(await readFile(args[args.indexOf("--variables") + 1]!, "utf8")).runtime_environment_variables + } + return s.run(executable, args, options) + }) + + const result = await installAzure(s.config, { ...s, run }) + + // The existing service's cleanup runs first, so public sharing can never block it. + expect(order).toEqual(["prepare", "share prepare", "release", "finish", "share finish"]) + expect(released).toMatchObject({ HUB_PRIVATE_PREVIEW_ENABLED: "true", HUB_PUBLIC_SHARE_ENABLED: "true" }) + expect(result.notes).toEqual(expect.arrayContaining([preview.note, share.note])) +}) + +it("does not finish public sharing when the release fails", async () => { + const s = await scenario() + await withSignIn(s) + const order: string[] = [] + previewStep(order) + const { finish } = shareStep(order) + const run = vi.fn(async (executable, args, options) => { + if (executable === process.execPath) throw new CommandExecutionError("Release failed") + return s.run(executable, args, options) + }) + + await expect(installAzure(s.config, { ...s, run })).rejects.toThrow("Release failed") + + expect(order).toEqual(["prepare", "share prepare"]) + expect(finish).not.toHaveBeenCalled() +}) + +it("blocks a saved shared-site override for a Hub on a custom domain before approval or cloud changes", async () => { + const s = await scenario() + await withSignIn(s) + const filename = join(installationWorkspace(s.config, s.directory), "installation.tfvars.json") + await writeFile(filename, JSON.stringify({ + ...JSON.parse(await readFile(filename, "utf8")), + hub_application_origin: "https://replica.coreai.design", + }), { mode: 0o600 }) + delete s.config.privatePreview + s.config.publicShare = { reader: "on", allowSharedSite: true } + s.events.length = 0 + s.ui.confirm = vi.fn(async () => true) + + await expect(installAzure(s.config, s)).rejects.toThrow(/^Public sharing blocked: .*shared-site override/) + + expect(s.events.map(({ command }) => command.slice(0, 3))).toEqual([["az", "account", "show"]]) + expect(s.ui.confirm).not.toHaveBeenCalled() +}) + it.each([ { record: "no private preview lease record", saved: false, renews: true, recoversFirst: true }, { record: "a record whose lease Azure no longer accepts", saved: true, renews: false, recoversFirst: true }, diff --git a/infrastructure/azure/install/index.ts b/infrastructure/azure/install/index.ts index 702770408..a42bb6287 100644 --- a/infrastructure/azure/install/index.ts +++ b/infrastructure/azure/install/index.ts @@ -19,6 +19,8 @@ import type { AzureInstallation, DeploymentResult, Foundation, Installation } fr import { openInstallationWorkspace } from "./workspace/index.ts" import { preparePrivatePreview } from "./private-preview/index.ts" import { checkPrivatePreviewChoice } from "./private-preview/hub-environment/index.ts" +import { preparePublicShare } from "./public-share/index.ts" +import { checkPublicShareChoice } from "./public-share/hub-environment/index.ts" import { readInstallationInputs } from "./inputs/index.ts" import { approveDeployment } from "./approval/index.ts" import { retryableProvisioningFailure } from "./retryable-provisioning-failure/index.ts" @@ -93,6 +95,7 @@ async function install( ): Promise { const operatorInputs = await readInstallationInputs(directory, config) checkPrivatePreviewChoice(config.privatePreview, operatorInputs) + checkPublicShareChoice(config.publicShare, operatorInputs) const postgres = { postgres_sku: operatorInputs.postgres_sku ?? guidedPostgresProfile.postgres_sku, postgres_version: operatorInputs.postgres_version ?? guidedPostgresProfile.postgres_version, @@ -286,7 +289,7 @@ async function install( await state.backend("provision"), ) // A failed earlier release can retain the release lock. Offer the usual recovery first, - // unless the preview step itself retained it and can resume by proof of ownership. + // unless the preview or sharing step itself retained it and can resume by proof of ownership. const previewLease = ( await leaseOwnership(context, installation.storage_account, "releases", "deployment.lock", "private-preview") ).lease @@ -305,7 +308,14 @@ async function install( readerSecret: () => secrets.privatePreviewReader(), lock, }) - await writePrivateFile(variables, JSON.stringify({ ...inputs, ...preview.inputs })) + const share = await preparePublicShare(context, { + image, + foundation: resources, + inputs: preview.inputs, + lock, + releaseAccount: installation.storage_account, + }) + await writePrivateFile(variables, JSON.stringify({ ...inputs, ...share.inputs })) await ui.phase?.("release") await recoverLease(context, installation.storage_account, "releases", "deployment.lock") ui.status("Running the serialized maintenance-window release") @@ -340,7 +350,7 @@ async function install( ) throw error } - const notes = await preview.finish() + const notes = [...(await preview.finish()), ...(await share.finish())] await ui.phase?.("verify") const released = await app.output("installation") const result = deploymentResult({ diff --git a/infrastructure/azure/install/managed-certificate/index.ts b/infrastructure/azure/install/managed-certificate/index.ts new file mode 100644 index 000000000..1bee760fd --- /dev/null +++ b/infrastructure/azure/install/managed-certificate/index.ts @@ -0,0 +1,49 @@ +/* + * Asks Azure for a managed certificate on a hostname already added to a Container App, after the + * wizard has seen its CNAME and TXT records. Returns whether the hostname serves TLS (SniEnabled). + */ +export async function bindManagedCertificate({ + azure, + app, + group, + environmentId, + hostname, + consequence, + warn, + signal, +}: { + azure(...args: string[]): Promise + app: string + group: string + environmentId: string + hostname: string + // What stays off until the certificate is bound, such as "Hub playback stays off." + consequence: string + warn(message: string): void + signal?: AbortSignal +}): Promise { + const binding = async () => { + const hosts: unknown = JSON.parse(await azure( + "containerapp", "hostname", "list", "--name", app, "--resource-group", group, + "--query", "[].{name:name,bindingType:bindingType}", + )) + return (Array.isArray(hosts) ? (hosts as { name?: unknown; bindingType?: unknown }[]) : []) + .find(({ name }) => name === hostname)?.bindingType + } + if ((await binding()) === "SniEnabled") return true + try { + await azure( + "containerapp", "hostname", "bind", "--hostname", hostname, "--name", app, + "--resource-group", group, "--environment", environmentId, "--validation-method", "CNAME", + ) + } catch (error) { + if (signal?.aborted) throw error + warn( + `Azure did not bind ${hostname}: ${error instanceof Error ? error.message : "the request failed."} ${consequence} Check the DNS records and the setup identity's access to the reader, then run Update again.`, + ) + return false + } + if ((await binding()) === "SniEnabled") return true + warn(`Azure accepted ${hostname} but has not bound its certificate yet. ${consequence} Run Update again later.`) + return false +} diff --git a/infrastructure/azure/install/private-preview/grants/index.ts b/infrastructure/azure/install/private-preview/grants/index.ts index fbd1b26ac..7b84243bd 100644 --- a/infrastructure/azure/install/private-preview/grants/index.ts +++ b/infrastructure/azure/install/private-preview/grants/index.ts @@ -1,15 +1,12 @@ -import { listingDeniedCondition } from "../plan/index.ts" +import { + deniesListing as listingDenied, + effectiveGrants, + reaches as reachesResource, + sameResource as same, + type Assignment, +} from "../../effective-grants/index.ts" import type { ReaderMode } from "../settings/index.ts" -interface Assignment { - id: string - scope: string - principalId: string - roleDefinitionName: string - condition: string | null - conditionVersion: string | null -} - export interface ExpectedGrants { subscriptionId: string reader: ReaderMode @@ -23,14 +20,6 @@ export interface ExpectedGrants { secretScope?: string } -const query = - "[].{id:id,scope:scope,principalId:principalId,roleDefinitionName:roleDefinitionName,condition:condition,conditionVersion:conditionVersion}" -const same = (left: string, right: string) => - left.replace(/\/+$/, "").toLowerCase() === right.replace(/\/+$/, "").toLowerCase() -const compact = (value: string | null) => value?.replace(/\s+/g, "") ?? "" -const listingDenied = (grant: Assignment) => - compact(grant.condition) === compact(listingDeniedCondition) && grant.conditionVersion === "2.0" - // Checks role, scope, and the ABAC condition and version of every grant, not only role names. export async function verifyPreviewGrants( read: (...args: string[]) => Promise, @@ -38,24 +27,8 @@ export async function verifyPreviewGrants( // Before a change, only grants the wizard would never create are problems. { unexpectedOnly = false }: { unexpectedOnly?: boolean } = {}, ): Promise { - const list = async (...args: string[]) => { - const value = await read("role", "assignment", "list", ...args, "--fill-principal-name", "false", "--query", query) - if (!Array.isArray(value) || - value.some((item) => !item || typeof item.id !== "string" || typeof item.scope !== "string" || - typeof item.principalId !== "string" || typeof item.roleDefinitionName !== "string")) - throw new Error("Private preview grants could not be verified: Azure returned incomplete role assignments.") - return value as Assignment[] - } const problems: string[] = [] - // --all does not inspect parent management groups; a scoped query does not inspect children. - // Both include grants made to groups that contain the identity. - const effective = async (principalId: string) => [ - ...(await list("--assignee-object-id", principalId, "--all", "--include-groups")), - ...(await list( - "--assignee-object-id", principalId, "--scope", `/subscriptions/${expected.subscriptionId}`, - "--include-inherited", "--include-groups", - )), - ].filter((grant, index, all) => all.findIndex((other) => same(other.id, grant.id)) === index) + const effective = (principalId: string) => effectiveGrants(read, expected.subscriptionId, principalId) const reader = expected.readerPrincipalId ? await effective(expected.readerPrincipalId) : [] const wanted: [string, string, (grant: Assignment) => boolean][] = [] if (expected.reader !== "absent") { @@ -74,11 +47,7 @@ export async function verifyPreviewGrants( if (!reader.some((grant) => grant.roleDefinitionName === role && same(grant.scope, scope))) problems.push(`The reader identity is missing ${role} on ${scope}.`) // Any Hub grant at the container or one of its parents reaches the published Builds. - const reaches = (scope: string) => { - const parent = scope.replace(/\/+$/, "").toLowerCase() - const container = expected.containerId.toLowerCase() - return !parent.startsWith("/subscriptions/") || container === parent || container.startsWith(`${parent}/`) - } + const reaches = (scope: string) => reachesResource(scope, expected.containerId) const hub = (await effective(expected.hubPrincipalId)).filter((grant) => reaches(grant.scope)) const writers = hub.filter((grant) => grant.roleDefinitionName === expected.writerRole && same(grant.scope, expected.containerId) && diff --git a/infrastructure/azure/install/private-preview/index.ts b/infrastructure/azure/install/private-preview/index.ts index 784e72505..beaf1595a 100644 --- a/infrastructure/azure/install/private-preview/index.ts +++ b/infrastructure/azure/install/private-preview/index.ts @@ -5,6 +5,7 @@ import { writePrivateFile } from "../../../installer/private-files/index.ts" import { terraformModule } from "../../../terraform/index.ts" import { writeBackendFile } from "../backend/index.ts" import { existingRoleAssignment } from "../existing-role-assignment/index.ts" +import { bindManagedCertificate } from "../managed-certificate/index.ts" import { acquireLease } from "../lease/index.ts" import { installationNames } from "../settings.ts" import type { AzureInstallation, Foundation, Installation } from "../types.ts" @@ -181,33 +182,11 @@ export async function preparePrivatePreview( const sharedSecret = async () => savedSecret ?? (await readerSecret()) const variablesFile = join(directory, "private-preview.tfvars.json") const warn = (message: string) => (ui.notice ? ui.notice("warning", message) : ui.status(message)) - const bindCertificate = async (hostname: string) => { - const list = async () => { - const hosts = await read( - "containerapp", "hostname", "list", "--name", previewName, "--resource-group", previewName, - "--query", "[].{name:name,bindingType:bindingType}", - ) - return Array.isArray(hosts) ? (hosts as { name?: unknown; bindingType?: unknown }[]) : [] - } - const binding = async () => (await list()).find(({ name }) => name === hostname)?.bindingType - if ((await binding()) === "SniEnabled") return true - try { - // Azure issues a managed certificate after it validates the CNAME and TXT records. - await context.azure( - "containerapp", "hostname", "bind", "--hostname", hostname, "--name", previewName, - "--resource-group", previewName, "--environment", environmentId, "--validation-method", "CNAME", - ) - } catch (error) { - if (signal?.aborted) throw error - warn( - `Azure did not bind ${hostname}: ${error instanceof Error ? error.message : "the request failed."} Hub playback stays off. Check the DNS records and the setup identity's access to the reader, then run Update again.`, - ) - return false - } - if ((await binding()) === "SniEnabled") return true - warn(`Azure accepted ${hostname} but has not bound its certificate yet. Hub playback stays off. Run Update again later.`) - return false - } + const bindCertificate = (hostname: string) => + bindManagedCertificate({ + azure: context.azure, app: previewName, group: previewName, environmentId, hostname, + consequence: "Hub playback stays off.", warn, ...(signal && { signal }), + }) const expectedGrants = (variables: PreviewVariables, readerPrincipalId: string | undefined) => ({ subscriptionId, reader: variables.reader, diff --git a/infrastructure/azure/install/private-preview/state-guard/index.ts b/infrastructure/azure/install/private-preview/state-guard/index.ts index 4f5fe71ce..7b38862e2 100644 --- a/infrastructure/azure/install/private-preview/state-guard/index.ts +++ b/infrastructure/azure/install/private-preview/state-guard/index.ts @@ -35,11 +35,14 @@ export async function guardPreviewState({ directory, target, resourcesExist, + subject = "Private preview", }: { azure(...args: string[]): Promise directory: string target: StateTarget resourcesExist(): Promise + // Names the service in errors, such as "Public sharing". + subject?: string }) { const blob = [ "--account-name", target.account, "--container-name", target.container, "--name", target.key, @@ -47,7 +50,7 @@ export async function guardPreviewState({ ] const block = (reason: string): never => { throw new Error( - `Private preview state blocked: ${reason} Terraform was not run. Review ${target.account}/${target.container}/${target.key} and restore it from a blob version before retrying.`, + `${subject} state blocked: ${reason} Terraform was not run. Review ${target.account}/${target.container}/${target.key} and restore it from a blob version before retrying.`, ) } const download = async () => { @@ -74,7 +77,7 @@ export async function guardPreviewState({ expected = await download() } else { if (await resourcesExist()) - return block("saved state is missing, but private preview resources exist.") + return block(`saved state is missing, but ${subject.toLowerCase()} resources exist.`) const seed = { version: 4, terraform_version: "1.13.0", serial: 0, lineage: randomUUID(), outputs: {}, resources: [], check_results: null } const file = join(directory, `preview-seed-${randomBytes(8).toString("hex")}.json`) try { diff --git a/infrastructure/azure/install/public-share/grants/index.ts b/infrastructure/azure/install/public-share/grants/index.ts new file mode 100644 index 000000000..1ac40ffbc --- /dev/null +++ b/infrastructure/azure/install/public-share/grants/index.ts @@ -0,0 +1,60 @@ +import { + deniesListing, + effectiveGrants, + reaches, + sameResource as same, +} from "../../effective-grants/index.ts" +import type { ReaderMode } from "../../private-preview/settings/index.ts" + +export interface ExpectedShareGrants { + subscriptionId: string + reader: ReaderMode + // Absent before the reader identity exists. + readerPrincipalId?: string + hubPrincipalId: string + writer: boolean + acrId: string + containerId: string +} + +const writerRole = "Storage Blob Data Contributor" + +// Checks role, scope, and the reader's listing condition, not only role names. +export async function verifyShareGrants( + read: (...args: string[]) => Promise, + expected: ExpectedShareGrants, + // Before a change, only grants the wizard would never create are problems. + { unexpectedOnly = false }: { unexpectedOnly?: boolean } = {}, +): Promise { + const problems: string[] = [] + const reader = expected.readerPrincipalId + ? await effectiveGrants(read, expected.subscriptionId, expected.readerPrincipalId) + : [] + const wanted: [string, string, (grant: Parameters[0]) => boolean][] = + expected.reader === "absent" + ? [] + : [ + ["AcrPull", expected.acrId, () => true], + ["Storage Blob Data Reader", expected.containerId, deniesListing], + ] + for (const grant of reader) { + const match = wanted.find(([role, scope]) => grant.roleDefinitionName === role && same(grant.scope, scope)) + if (!match) problems.push(`The share reader identity has an unexpected grant: ${grant.id}.`) + else if (!unexpectedOnly && !match[2](grant)) + problems.push(`The share reader grant ${grant.id} does not deny blob listing with condition version 2.0.`) + } + for (const [role, scope] of unexpectedOnly || !expected.readerPrincipalId ? [] : wanted) + if (!reader.some((grant) => grant.roleDefinitionName === role && same(grant.scope, scope))) + problems.push(`The share reader identity is missing ${role} on ${scope}.`) + const hub = (await effectiveGrants(read, expected.subscriptionId, expected.hubPrincipalId)) + .filter((grant) => reaches(grant.scope, expected.containerId)) + const writers = hub.filter((grant) => + grant.roleDefinitionName === writerRole && same(grant.scope, expected.containerId) && + same(grant.principalId, expected.hubPrincipalId)) + for (const grant of hub) + if (!expected.writer || !writers.includes(grant)) + problems.push(`The Hub identity has access to the export container that the wizard does not manage: ${grant.id}.`) + if (!unexpectedOnly && expected.writer && writers.length !== 1) + problems.push(`The Hub identity does not have exactly one ${writerRole} grant on the export container.`) + return problems +} diff --git a/infrastructure/azure/install/public-share/hub-environment/index.test.ts b/infrastructure/azure/install/public-share/hub-environment/index.test.ts new file mode 100644 index 000000000..8dc81d1e7 --- /dev/null +++ b/infrastructure/azure/install/public-share/hub-environment/index.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from "vitest" + +import type { PublicShareChoice } from "../../../../installer/types.ts" +import { checkPublicShareChoice, hubShareInputs, PublicShareChoiceError } from "./index.ts" + +const customHub = { + hub_application_origin: "https://replica.coreai.design", + runtime_environment_variables: { HUB_TRUSTED_PROXY_HOPS: "1" }, +} +const generatedHub = { ...customHub, hub_application_origin: "https://sample-hub.example.eastus2.azurecontainerapps.io" } +const share = { + origin: "https://sample-hub-share.example.eastus2.azurecontainerapps.io", + storageAccount: "samplehubpub", + storageContainer: "public-share-exports", + allowSharedSite: false, +} +const reference = { + key_vault_id: "/subscriptions/sample/resourceGroups/sample/providers/Microsoft.KeyVault/vaults/sample", + secret_id: "https://sample.vault.azure.net/secrets/share-origin/1", +} + +describe("hubShareInputs", () => { + it("replaces manually saved share values with the released ones and keeps other settings", () => { + const inputs = { + ...customHub, + runtime_environment_variables: { + HUB_TRUSTED_PROXY_HOPS: "1", + HUB_PUBLIC_SHARE_ORIGIN: "https://manual.example.net", + HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE: "true", + }, + } + + expect(hubShareInputs(inputs, share).runtime_environment_variables).toEqual({ + HUB_TRUSTED_PROXY_HOPS: "1", + HUB_PUBLIC_SHARE_ENABLED: "true", + HUB_PUBLIC_SHARE_ORIGIN: share.origin, + HUB_PUBLIC_SHARE_STORAGE_ACCOUNT: "samplehubpub", + HUB_PUBLIC_SHARE_STORAGE_CONTAINER: "public-share-exports", + }) + }) + + it("blocks a wizard-owned share setting saved as a Key Vault reference", () => { + const inputs = { ...customHub, runtime_secret_references: { HUB_PUBLIC_SHARE_ORIGIN: reference } } + + expect(() => hubShareInputs(inputs)).toThrow(/Key Vault references for HUB_PUBLIC_SHARE_ORIGIN/) + }) +}) + +describe("checkPublicShareChoice", () => { + it.each([ + ["off", { reader: "off" }], + ["removed", { reader: "removed" }], + ] as const)("never blocks turning sharing %s, even for a Hub on its generated hostname", (_, choice) => { + expect(() => checkPublicShareChoice(choice, generatedHub, { reader: "on", allowSharedSite: true })).not.toThrow() + }) + + it.each([ + ["Hub has no origin", { reader: "on" }, {}, /needs Hub's origin/], + ["Hub uses its generated hostname without the override", { reader: "on" }, generatedHub, /generated hostname/], + ["the override is saved for a Hub on a custom domain", { reader: "on", allowSharedSite: true }, customHub, /shared-site override/], + ["the share hostname may be the same site as Hub", { reader: "on", hostname: "share.coreai.design" }, customHub, /same site/], + [ + "the share hostname shares Hub's generated site", + { reader: "on", hostname: "share.eastus2.azurecontainerapps.io", allowSharedSite: true }, + generatedHub, + /same site/, + ], + ] as [string, PublicShareChoice, object, RegExp][])("blocks turning sharing on when %s", (_, choice, inputs, message) => { + expect(() => checkPublicShareChoice(choice, inputs)).toThrow(PublicShareChoiceError) + expect(() => checkPublicShareChoice(choice, inputs)).toThrow(message) + }) + + it.each([ + ["a custom domain under another registered domain", { reader: "on", hostname: "share.coreai.net" }, customHub], + ["the non-production override for a generated Hub", { reader: "on", allowSharedSite: true }, generatedHub], + ] as [string, PublicShareChoice, object][])("accepts %s", (_, choice, inputs) => { + expect(() => checkPublicShareChoice(choice, inputs)).not.toThrow() + }) + + it("blocks changing the share hostname while sharing stays on", () => { + const previous: PublicShareChoice = { reader: "on", hostname: "share.coreai.net" } + + expect(() => checkPublicShareChoice({ reader: "on", hostname: "links.coreai.net" }, customHub, previous)).toThrow( + /Changing or removing its custom hostname/, + ) + }) +}) diff --git a/infrastructure/azure/install/public-share/hub-environment/index.ts b/infrastructure/azure/install/public-share/hub-environment/index.ts new file mode 100644 index 000000000..ab80a4fb4 --- /dev/null +++ b/infrastructure/azure/install/public-share/hub-environment/index.ts @@ -0,0 +1,99 @@ +import type { PublicShareChoice } from "../../../../installer/types.ts" +import { hubOrigin, type HubPreviewInputs } from "../../private-preview/hub-environment/index.ts" + +// The wizard owns these Hub settings; manual values are replaced on every deployment. +export const ownedHubShareSettings = [ + "HUB_PUBLIC_SHARE_ENABLED", + "HUB_PUBLIC_SHARE_ORIGIN", + "HUB_PUBLIC_SHARE_STORAGE_ACCOUNT", + "HUB_PUBLIC_SHARE_STORAGE_CONTAINER", + "HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE", +] as const + +export interface HubShare { + // The custom origin once its certificate is bound, otherwise the generated one. + origin: string + storageAccount: string + storageContainer: string + allowSharedSite: boolean +} + +export class PublicShareChoiceError extends Error {} + +const generatedDomain = ".azurecontainerapps.io" + +function rejectOwnedReferences(inputs: HubPreviewInputs, block: (reason: string) => never) { + const referenced = ownedHubShareSettings.filter((name) => name in (inputs.runtime_secret_references ?? {})) + if (referenced.length) + block(`remove the Key Vault references for ${referenced.join(", ")} from the saved Hub inputs. The wizard sets those values.`) +} + +// Returns Hub's inputs with exactly the public sharing settings this run releases. +export function hubShareInputs(inputs: T, share?: HubShare): T { + rejectOwnedReferences(inputs, (reason) => { + throw new Error(`Public sharing blocked: ${reason} No changes were made.`) + }) + const environment = Object.fromEntries( + Object.entries(inputs.runtime_environment_variables ?? {}).filter( + ([name]) => !(ownedHubShareSettings as readonly string[]).includes(name), + ), + ) + if (share) + Object.assign(environment, { + HUB_PUBLIC_SHARE_ENABLED: "true", + HUB_PUBLIC_SHARE_ORIGIN: share.origin, + HUB_PUBLIC_SHARE_STORAGE_ACCOUNT: share.storageAccount, + HUB_PUBLIC_SHARE_STORAGE_CONTAINER: share.storageContainer, + ...(share.allowSharedSite && { HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE: "true" }), + }) + const next: T = { ...inputs } + if (Object.keys(environment).length || inputs.runtime_environment_variables) + next.runtime_environment_variables = environment + return next +} + +export const isGeneratedHost = (host: string) => host.endsWith(generatedDomain) + +/* + * Hub checks the full Public Suffix List at startup. Without it, the last two labels are a + * conservative stand-in: hosts whose last two labels differ are always different sites. + */ +export function mayBeSameSite(left: string, right: string): boolean { + const site = (host: string) => host.split(".").slice(-2).join(".") + return site(left) === site(right) +} + +// Checks a choice against saved Hub inputs; setup runs it before saving the choice or any Azure change. +export function checkPublicShareChoice( + choice: PublicShareChoice | undefined, + inputs: HubPreviewInputs, + previous?: PublicShareChoice, +): void { + const block = (reason: string): never => { + throw new PublicShareChoiceError(`Public sharing blocked: ${reason} Public sharing was not changed.`) + } + rejectOwnedReferences(inputs, block) + if (choice?.reader !== "on") return + const origin = hubOrigin(inputs) + if (!origin) + block( + "turning on public sharing needs Hub's origin, HUB_APPLICATION_ORIGIN. Choose Off, run npm run setup:post to configure sign-in, then run Update and choose On.", + ) + const hubHost = new URL(origin!).hostname + if (isGeneratedHost(hubHost) && !choice.allowSharedSite) + block( + `Hub uses its generated hostname ${hubHost}, which is the same site as every Container Apps hostname, including the share reader's. Give Hub a custom domain with npm run setup:post first. Only a non-production installation may accept the shared-site override instead.`, + ) + if (!isGeneratedHost(hubHost) && choice.allowSharedSite) + block( + `the shared-site override applies only while Hub uses a generated hostname, and Hub uses ${hubHost}. Remove allowSharedSite from the saved choice.`, + ) + if (choice.hostname && (choice.hostname === hubHost || mayBeSameSite(hubHost, choice.hostname))) + block( + `${choice.hostname} may be the same site as Hub's hostname ${hubHost}. Use a hostname under a different registered domain.`, + ) + if (previous?.reader === "on" && previous.hostname && previous.hostname !== choice.hostname) + block( + `the reader uses ${previous.hostname}. Changing or removing its custom hostname while sharing is on is not supported. Choose Off first, run Update, then choose the new hostname.`, + ) +} diff --git a/infrastructure/azure/install/public-share/index.test.ts b/infrastructure/azure/install/public-share/index.test.ts new file mode 100644 index 000000000..1eedae780 --- /dev/null +++ b/infrastructure/azure/install/public-share/index.test.ts @@ -0,0 +1,525 @@ +import { mkdir, readFile, rm, writeFile } from "node:fs/promises" +import { randomUUID } from "node:crypto" +import { resolve } from "node:path" +import { afterEach, describe, expect, it, vi } from "vitest" + +import type { DeploymentConfig, PublicShareChoice } from "../../../installer/types.ts" +import type { DnsResolver } from "../private-preview/dns/index.ts" +import { listingDeniedCondition } from "../private-preview/plan/index.ts" +import { preparePublicShare } from "./index.ts" + +const fake = vi.hoisted(() => ({ + terraform: undefined as undefined | ((options: { beforeApply?(): Promise }) => unknown), + lease: undefined as undefined | (() => unknown), +})) +vi.mock("../../../terraform/index.ts", () => ({ + terraformModule: (options: { beforeApply?(): Promise }) => fake.terraform!(options), +})) +vi.mock("../lease/index.ts", () => ({ acquireLease: async () => fake.lease!() })) + +const directories: string[] = [] +afterEach(async () => { + await Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true, force: true }))) +}) + +interface Variables { + reader: "absent" | "disabled" | "enabled" + custom_hostname: string | null + bind_custom_hostname: boolean + writer_principal_id: string | null + image: string +} + +// What the public-share Terraform state records before this run. +interface Current { + reader: "absent" | "disabled" | "enabled" + writer?: boolean + boundHostname?: string +} + +const subscriptionId = "00000000-0000-0000-0000-000000000001" +const hubPrincipal = "22222222-2222-4222-8222-222222222222" +const readerPrincipal = "33333333-3333-4333-8333-333333333333" +const lineage = "11111111-1111-4111-8111-111111111111" +const image = `registry.azurecr.io/replica-hub@sha256:${"a".repeat(64)}` +const generated = "sample-hub-share.example.eastus2.azurecontainerapps.io" +const shareHostname = "share.example.net" +const exportAccountId = `/subscriptions/${subscriptionId}/resourceGroups/sample-hub-share/providers/Microsoft.Storage/storageAccounts/samplehubpub` +const containerId = `${exportAccountId}/blobServices/default/containers/public-share-exports` +const registryId = `/subscriptions/${subscriptionId}/resourceGroups/sample-hub-foundation/providers/Microsoft.ContainerRegistry/registries/sample` +const vaultId = `/subscriptions/${subscriptionId}/resourceGroups/sample-hub-foundation/providers/Microsoft.KeyVault/vaults/samplevault` +const customHub = { + hub_application_origin: "https://replica.coreai.design", + runtime_environment_variables: { HUB_TRUSTED_PROXY_HOPS: "1", HUB_LOCAL_SIGN_IN: "true" }, +} +const generatedHub = { ...customHub, hub_application_origin: "https://sample-hub.example.eastus2.azurecontainerapps.io" } +const shareSettings = (origin = `https://${generated}`) => ({ + HUB_PUBLIC_SHARE_ENABLED: "true", + HUB_PUBLIC_SHARE_ORIGIN: origin, + HUB_PUBLIC_SHARE_STORAGE_ACCOUNT: "samplehubpub", + HUB_PUBLIC_SHARE_STORAGE_CONTAINER: "public-share-exports", +}) +// Hub inputs saved by an earlier run that turned sharing on. +const sharingHub = { + ...customHub, + runtime_environment_variables: { ...customHub.runtime_environment_variables, ...shareSettings() }, +} +const on = (choice: Partial = {}): PublicShareChoice => ({ reader: "on", ...choice }) +const dnsReady: DnsResolver = { + cname: async () => [generated], + txt: async () => [["VERIFY123"]], +} + +function stateSnapshot(current: Current | undefined) { + if (!current) return { format_version: "1.0" } + const resources: unknown[] = [] + if (current.reader !== "absent") + resources.push({ + address: "azurerm_container_app.reader[0]", + values: { name: "sample-hub-share", ingress: current.reader === "enabled" ? [{ external_enabled: true }] : [] }, + }) + if (current.boundHostname) + resources.push({ address: "azurerm_container_app_custom_domain.reader[0]", values: { name: current.boundHostname } }) + if (current.writer) resources.push({ address: "azurerm_role_assignment.writer[0]", values: { principal_id: hubPrincipal } }) + return { format_version: "1.0", values: { root_module: { resources } } } +} + +const grant = (principalId: string, roleDefinitionName: string, scope: string, condition: string | null = null) => ({ + id: `${scope}/providers/Microsoft.Authorization/roleAssignments/${roleDefinitionName.replaceAll(" ", "-")}`, + scope, + principalId, + roleDefinitionName, + condition, + conditionVersion: condition ? "2.0" : null, +}) + +async function fixture({ + choice, + current, + orphaned = false, + unexpectedReaderGrant = false, + unmanagedHubGrant = false, + readyAfterChecks = 1, + bindFailure, + conditionDroppedOnApply = false, + planBlocked = false, + serving, + servingAfterRelease, +}: { + choice?: PublicShareChoice + current?: Current + // The share group exists without saved state. + orphaned?: boolean + unexpectedReaderGrant?: boolean + // Hub can reach the export container through a grant the wizard does not manage. + unmanagedHubGrant?: boolean + // How many readiness checks see the latest revision not ready yet, plus one; Infinity never. + readyAfterChecks?: number + bindFailure?: "never bound" + conditionDroppedOnApply?: boolean + planBlocked?: boolean + // The serving Hub's HUB_PUBLIC_SHARE_* settings; by default, those in the saved inputs. + serving?: Record + // After the release; by default, the settings this run returned for the release. + servingAfterRelease?: Record +}) { + const directory = resolve(`.share-prepare-test-${randomUUID()}`) + directories.push(directory) + await mkdir(directory, { mode: 0o700 }) + const config: DeploymentConfig = { + version: 1, + cloud: "azure", + name: "sample-hub", + owner: "sample-team", + ...(choice && { publicShare: choice }), + azure: { subscriptionId, tenantId: subscriptionId, location: "eastus2", resourceGroup: "sample-hub-rg" }, + } + let blob = current + ? JSON.stringify({ version: 4, terraform_version: "1.13.0", serial: 3, lineage, outputs: {}, resources: [] }) + : undefined + // What Azure has now; each apply replaces it with what the applied variables declare. + const live = { + reader: current?.reader ?? "absent", + writer: Boolean(current?.writer), + unconditioned: false, + hostname: current?.boundHostname ?? null, + bindings: new Map(current?.boundHostname ? [[current.boundHostname, "SniEnabled"]] : []), + } + const applied: Variables[] = [] + const inits = vi.fn() + fake.terraform = ({ beforeApply }) => ({ + init: inits, + rawState: async () => JSON.parse(blob!), + stateSnapshot: async () => stateSnapshot(current), + async output() { + const enabled = live.reader === "enabled" + return { + generated_origin: enabled ? `https://${generated}` : null, + custom_origin: enabled && live.hostname ? `https://${live.hostname}` : null, + generated_hostname: enabled ? generated : null, + custom_domain_verification_id: enabled ? "VERIFY123" : null, + storage_account: "samplehubpub", + storage_container: "public-share-exports", + } + }, + async apply(file: string) { + if (planBlocked) throw new Error("Public sharing plan blocked: synthetic.") + await beforeApply?.() + const variables = JSON.parse(await readFile(file, "utf8")) as Variables + applied.push(variables) + live.reader = variables.reader + live.writer = variables.writer_principal_id !== null + live.unconditioned = conditionDroppedOnApply + live.hostname = variables.reader === "enabled" && variables.bind_custom_hostname ? variables.custom_hostname : null + for (const name of live.bindings.keys()) if (name !== live.hostname) live.bindings.delete(name) + if (live.hostname && !live.bindings.has(live.hostname)) live.bindings.set(live.hostname, "Disabled") + const state = JSON.parse(blob!) as { serial: number } + blob = JSON.stringify({ ...state, serial: state.serial + 1 }) + }, + }) + const leases: { verify: ReturnType; release: ReturnType; reportRetained: ReturnType }[] = [] + fake.lease = () => { + const lease = { held: true, verify: vi.fn(), release: vi.fn(), reportRetained: vi.fn() } + leases.push(lease) + return lease + } + let readinessChecks = 0 + let servingEnv: Record = {} + const shareEnv = (inputs: Record) => Object.fromEntries( + Object.entries((inputs.runtime_environment_variables ?? {}) as Record) + .filter(([name]) => name.startsWith("HUB_PUBLIC_SHARE_")), + ) + const groupExists = () => orphaned || current !== undefined || applied.length > 0 + const azure = vi.fn(async (...args: string[]) => { + const operation = args.slice(0, 3).join(" ") + const value = (flag: string) => args[args.indexOf(flag) + 1]! + if (operation === "storage blob exists") return JSON.stringify({ exists: blob !== undefined }) + if (operation === "storage blob download") { + await writeFile(value("--file"), blob!) + return "" + } + if (operation === "storage blob upload") { + blob = await readFile(value("--file"), "utf8") + return "" + } + if (operation === "group exists --name") return JSON.stringify(groupExists()) + if (operation === "identity list --resource-group") return JSON.stringify(groupExists() ? [readerPrincipal] : []) + if (operation === "identity show --ids") + return JSON.stringify(value("--ids").endsWith("/sample-hub-hub") ? hubPrincipal : readerPrincipal) + if (operation === "containerapp list --resource-group") + return JSON.stringify([{ env: Object.entries(servingEnv).map(([name, value]) => ({ name, value })) }]) + if (operation === "role assignment list") { + if (value("--assignee-object-id") === hubPrincipal) + return JSON.stringify([ + ...(live.writer ? [grant(hubPrincipal, "Storage Blob Data Contributor", containerId)] : []), + ...(unmanagedHubGrant ? [grant(hubPrincipal, "Storage Blob Data Owner", exportAccountId)] : []), + ]) + return JSON.stringify([ + ...(live.reader !== "absent" + ? [ + grant(readerPrincipal, "AcrPull", registryId), + grant(readerPrincipal, "Storage Blob Data Reader", containerId, live.unconditioned ? null : listingDeniedCondition), + ] + : []), + ...(unexpectedReaderGrant ? [grant(readerPrincipal, "Key Vault Secrets User", vaultId)] : []), + ]) + } + if (operation === "containerapp show --name") { + readinessChecks++ + return JSON.stringify({ latest: "share--2", ready: readinessChecks >= readyAfterChecks ? "share--2" : "share--1" }) + } + if (operation === "containerapp hostname list") + return JSON.stringify([...live.bindings].map(([name, bindingType]) => ({ name, bindingType }))) + if (operation === "containerapp hostname bind") { + if (bindFailure !== "never bound") live.bindings.set(value("--hostname"), "SniEnabled") + return "" + } + throw new Error(`Unexpected Azure command: ${args.join(" ")}`) + }) + const status = vi.fn() + const notice = vi.fn() + const prepare = async (inputs: Record, resolver?: DnsResolver) => { + servingEnv = serving ?? shareEnv(inputs) + const prepared = await preparePublicShare( + { config, directory, run: vi.fn(), azure, env: {}, ui: { status, notice, confirm: vi.fn(), wait: vi.fn() } }, + { + image, + foundation: { vault_id: vaultId, vault_url: "https://samplevault.vault.azure.net/", registry_id: registryId, registry_url: "registry.azurecr.io" }, + inputs, + lock: { verify: vi.fn() }, + releaseAccount: "samplehubhub", + resolver: resolver ?? { cname: async () => [], txt: async () => [] }, + // Keep every case off the real ten-second polling delay. + readiness: { attempts: 3, delayMs: 0 }, + }, + ) + // The Hub release deploys the returned inputs before finish() runs. + servingEnv = servingAfterRelease ?? shareEnv(prepared.inputs) + return prepared + } + const uploads = () => azure.mock.calls.filter((call) => call.slice(0, 3).join(" ") === "storage blob upload") + const binds = () => azure.mock.calls.filter((call) => call.slice(0, 3).join(" ") === "containerapp hostname bind") + return { prepare, applied, inits, leases, uploads, binds, readiness: () => readinessChecks } +} + +describe("preparePublicShare", () => { + it.each([ + ["an earlier configuration without a public sharing choice", undefined], + ["sharing that was only ever off", { reader: "off", hostname: shareHostname } as const], + ])("leaves %s without Terraform, state, or Hub share settings", async (_, choice) => { + const { prepare, inits, uploads } = await fixture({ ...(choice && { choice }) }) + // Manually saved values are replaced: Hub gets no share settings while sharing is off. + const inputs = { + ...customHub, + runtime_environment_variables: { ...customHub.runtime_environment_variables, HUB_PUBLIC_SHARE_ENABLED: "true" }, + } + + const prepared = await prepare(inputs) + + expect(prepared.inputs).toEqual(customHub) + await expect(prepared.finish()).resolves.toEqual([]) + expect(inits).not.toHaveBeenCalled() + expect(uploads()).toEqual([]) + }) + + it.each([ + ["sharing stays off", undefined], + ["sharing is turned on", on()], + ])("blocks before Terraform when saved state is missing but the share group exists and %s", async (_, choice) => { + const { prepare, inits, uploads, applied } = await fixture({ orphaned: true, ...(choice && { choice }) }) + + await expect(prepare(customHub)).rejects.toThrow(/missing, but public sharing resources exist/) + expect(inits).not.toHaveBeenCalled() + expect(uploads()).toEqual([]) + expect(applied).toEqual([]) + }) + + it("turns on the reader, Hub's export grant, and Hub's share settings on the generated origin in one apply", async () => { + const { prepare, applied, leases } = await fixture({ choice: on() }) + + const prepared = await prepare(customHub) + await prepared.finish() + + expect(applied).toEqual([expect.objectContaining({ + reader: "enabled", + custom_hostname: null, + bind_custom_hostname: false, + writer_principal_id: hubPrincipal, + image, + })]) + expect(prepared.inputs).toEqual(sharingHub) + expect(leases[0]!.release).toHaveBeenCalledOnce() + }) + + it("refuses to turn on sharing while Hub uses its generated hostname, before any change", async () => { + const { prepare, inits, uploads } = await fixture({ choice: on() }) + + await expect(prepare(generatedHub)).rejects.toThrow(/generated hostname/) + expect(inits).not.toHaveBeenCalled() + expect(uploads()).toEqual([]) + }) + + it("turns on sharing for a Hub on its generated hostname with the non-production override", async () => { + const { prepare, applied } = await fixture({ choice: on({ allowSharedSite: true }) }) + + const prepared = await prepare(generatedHub) + + expect(applied).toHaveLength(1) + expect(prepared.inputs.runtime_environment_variables).toEqual({ + ...generatedHub.runtime_environment_variables, + ...shareSettings(), + HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE: "true", + }) + }) + + it("refuses a saved shared-site override while Hub uses a custom domain, before any change", async () => { + const { prepare, inits, uploads } = await fixture({ choice: on({ allowSharedSite: true }) }) + + await expect(prepare(customHub)).rejects.toThrow(/shared-site override/) + expect(inits).not.toHaveBeenCalled() + expect(uploads()).toEqual([]) + }) + + it("re-runs unchanged sharing with one apply, the same Hub settings, and nothing to remove afterwards", async () => { + const { prepare, applied } = await fixture({ choice: on(), current: { reader: "enabled", writer: true } }) + + const prepared = await prepare(sharingHub) + await prepared.finish() + + expect(applied).toHaveLength(1) + expect(prepared.inputs).toEqual(sharingHub) + }) + + it("keeps the reader and Hub's grant for the running Hub when turning sharing off, then disables them after the release", async () => { + const { prepare, applied } = await fixture({ choice: { reader: "off" }, current: { reader: "enabled", writer: true } }) + + const prepared = await prepare(sharingHub) + + expect(applied).toEqual([expect.objectContaining({ reader: "enabled", writer_principal_id: hubPrincipal })]) + expect(prepared.inputs).toEqual(customHub) + + await prepared.finish() + + expect(applied).toHaveLength(2) + expect(applied[1]).toMatchObject({ reader: "disabled", writer_principal_id: null, custom_hostname: null }) + }) + + it("removes the reader, its custom domain, and Hub's grant only after the release", async () => { + const { prepare, applied } = await fixture({ + choice: { reader: "removed" }, + current: { reader: "enabled", writer: true, boundHostname: shareHostname }, + }) + const inputs = { + ...customHub, + runtime_environment_variables: { ...customHub.runtime_environment_variables, ...shareSettings(`https://${shareHostname}`) }, + } + + const prepared = await prepare(inputs) + + expect(applied).toEqual([expect.objectContaining({ + reader: "enabled", + custom_hostname: shareHostname, + bind_custom_hostname: true, + writer_principal_id: hubPrincipal, + })]) + expect(prepared.inputs).toEqual(customHub) + + await prepared.finish() + + expect(applied[1]).toMatchObject({ + reader: "absent", + custom_hostname: null, + bind_custom_hostname: false, + writer_principal_id: null, + }) + }) + + it("keeps Hub sharing off when the reader revision of a first opt-in is not ready", async () => { + const { prepare, readiness } = await fixture({ choice: on(), readyAfterChecks: Infinity }) + + const prepared = await prepare(customHub) + const notes = (await prepared.finish()).join("\n") + + expect(readiness()).toBe(3) + expect(prepared.inputs).toEqual(customHub) + expect(notes).toMatch(/not ready/) + }) + + it("waits for the reader revision before turning on Hub sharing", async () => { + const { prepare, readiness } = await fixture({ choice: on(), readyAfterChecks: 2 }) + + const prepared = await prepare(customHub) + + expect(readiness()).toBe(2) + expect(prepared.inputs).toEqual(sharingHub) + }) + + it("keeps a sharing Hub sharing while a new reader revision is not ready", async () => { + const { prepare } = await fixture({ choice: on(), current: { reader: "enabled", writer: true }, readyAfterChecks: Infinity }) + + const prepared = await prepare(sharingHub) + + expect(prepared.inputs).toEqual(sharingHub) + }) + + it("keeps links on the generated origin and lists the DNS records until the custom domain can be bound", async () => { + const { prepare, applied, binds } = await fixture({ choice: on({ hostname: shareHostname }) }) + + const prepared = await prepare(customHub) + const notes = (await prepared.finish()).join("\n") + + expect(applied).toEqual([expect.objectContaining({ custom_hostname: shareHostname, bind_custom_hostname: false })]) + expect(binds()).toEqual([]) + expect(prepared.inputs).toEqual(sharingHub) + expect(notes).toMatch(new RegExp(`CNAME\\s+${shareHostname}\\b.*${generated}`)) + expect(notes).toMatch(new RegExp(`TXT\\s+asuid\\.${shareHostname}\\b.*VERIFY123`)) + }) + + it("binds the custom domain once DNS is ready and gives Hub the custom origin", async () => { + const { prepare, applied, binds } = await fixture({ + choice: on({ hostname: shareHostname }), + current: { reader: "enabled", writer: true }, + }) + + const prepared = await prepare(sharingHub, dnsReady) + await prepared.finish() + + expect(applied).toEqual([expect.objectContaining({ custom_hostname: shareHostname, bind_custom_hostname: true })]) + expect(binds()).toHaveLength(1) + expect(prepared.inputs.runtime_environment_variables).toEqual({ + ...customHub.runtime_environment_variables, + ...shareSettings(`https://${shareHostname}`), + }) + }) + + it("keeps Hub on the generated origin when the custom domain's certificate is not bound", async () => { + const { prepare } = await fixture({ + choice: on({ hostname: shareHostname }), + current: { reader: "enabled", writer: true }, + bindFailure: "never bound", + }) + + const prepared = await prepare(sharingHub, dnsReady) + const notes = (await prepared.finish()).join("\n") + + expect(prepared.inputs).toEqual(sharingHub) + expect(notes).toContain(`certificate for ${shareHostname} is not bound yet`) + }) + + it("blocks before any apply when the reader identity has a grant the wizard does not manage", async () => { + const { prepare, applied, leases } = await fixture({ + choice: on(), + current: { reader: "disabled" }, + unexpectedReaderGrant: true, + }) + + await expect(prepare(customHub)).rejects.toThrow(/unexpected grant/) + expect(applied).toEqual([]) + expect(leases).toEqual([]) + }) + + it("blocks before any apply when Hub reaches the export container through a grant the wizard does not manage", async () => { + const { prepare, applied, leases } = await fixture({ + choice: on(), + current: { reader: "enabled", writer: true }, + unmanagedHubGrant: true, + }) + + await expect(prepare(sharingHub)).rejects.toThrow(/does not manage/) + expect(applied).toEqual([]) + expect(leases).toEqual([]) + }) + + it("stops before the Hub release and keeps the release lock when the reader may list exports after apply", async () => { + const { prepare, applied, leases } = await fixture({ choice: on(), conditionDroppedOnApply: true }) + + await expect(prepare(customHub)).rejects.toThrow(/does not deny blob listing/) + + expect(applied).toHaveLength(1) + expect(leases[0]!.release).not.toHaveBeenCalled() + expect(leases[0]!.reportRetained).toHaveBeenCalled() + }) + + it("releases the release lock when the plan is blocked before anything is applied", async () => { + const { prepare, applied, leases } = await fixture({ choice: on(), current: { reader: "disabled" }, planBlocked: true }) + + await expect(prepare(customHub)).rejects.toThrow(/plan blocked/) + + expect(applied).toEqual([]) + expect(leases[0]!.release).toHaveBeenCalledOnce() + }) + + it("removes nothing after the release when the serving Hub's share settings differ from the released ones", async () => { + const { prepare, applied } = await fixture({ + choice: { reader: "off" }, + current: { reader: "enabled", writer: true }, + servingAfterRelease: shareSettings(), + }) + + const prepared = await prepare(sharingHub) + await expect(prepared.finish()).rejects.toThrow(/settings changed after this release/) + + expect(applied).toHaveLength(1) + expect(applied[0]).toMatchObject({ reader: "enabled", writer_principal_id: hubPrincipal }) + }) +}) diff --git a/infrastructure/azure/install/public-share/index.ts b/infrastructure/azure/install/public-share/index.ts new file mode 100644 index 000000000..e6bf04b3e --- /dev/null +++ b/infrastructure/azure/install/public-share/index.ts @@ -0,0 +1,303 @@ +import { join, resolve } from "node:path" +import { setTimeout as delay } from "node:timers/promises" + +import { writePrivateFile } from "../../../installer/private-files/index.ts" +import { terraformModule } from "../../../terraform/index.ts" +import { writeBackendFile } from "../backend/index.ts" +import { existingRoleAssignment } from "../existing-role-assignment/index.ts" +import { acquireLease } from "../lease/index.ts" +import { bindManagedCertificate } from "../managed-certificate/index.ts" +import { + dnsRecordsReady, + formatDnsRecords, + readerDnsRecords, + systemResolver, + type DnsResolver, +} from "../private-preview/dns/index.ts" +import type { HubPreviewInputs } from "../private-preview/hub-environment/index.ts" +import { guardPreviewState } from "../private-preview/state-guard/index.ts" +import { installationNames } from "../settings.ts" +import type { AzureInstallation, Foundation } from "../types.ts" +import { verifyShareGrants } from "./grants/index.ts" +import { checkPublicShareChoice, hubShareInputs, type HubShare } from "./hub-environment/index.ts" +import { allowedShareDeletion, validatePublicSharePlan } from "./plan/index.ts" +import { + expandShareVariables, + needsShareRoot, + offShareChoice, + readShareState, + sameShareVariables, + targetShareVariables, + type ShareVariables, +} from "./settings/index.ts" + +type ShareOutput = { + generated_origin: string | null + custom_origin: string | null + generated_hostname: string | null + custom_domain_verification_id: string | null + storage_account: string + storage_container: string +} + +const guid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i + +/* + * Runs before the Hub release. It applies everything the running Hub may still use (expand), and + * returns Hub's public sharing settings for the release. finish() then removes what the new Hub + * no longer uses (contract). The export storage and its data are never removed. + */ +export async function preparePublicShare( + context: AzureInstallation, + { + image, + foundation, + inputs, + lock, + releaseAccount, + resolver = systemResolver, + readiness = { attempts: 30, delayMs: 10_000 }, + }: { + image: string + foundation: Foundation + inputs: T + lock: { verify(): Promise } + // Hub's storage account, which holds the release lock. + releaseAccount: string + resolver?: DnsResolver + // A new revision usually becomes ready within a few minutes of apply. + readiness?: { attempts: number; delayMs: number } + }, +): Promise<{ inputs: T; finish(): Promise }> { + const { config, directory, run, ui, signal } = context + const choice = config.publicShare ?? offShareChoice + const { subscriptionId } = config.azure + const names = installationNames(config) + const shareName = `${config.name}-share` + const shareGroupId = `/subscriptions/${subscriptionId}/resourceGroups/${shareName}` + const environmentId = `${shareGroupId}/providers/Microsoft.App/managedEnvironments/${shareName}-environment` + const readerIdentityId = `${shareGroupId}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/${shareName}` + const containerId = `${shareGroupId}/providers/Microsoft.Storage/storageAccounts/${config.name.replaceAll("-", "")}pub/blobServices/default/containers/public-share-exports` + const read = async (...args: string[]): Promise => JSON.parse(await context.azure(...args)) + const block = (reason: string): never => { + throw new Error(`Public sharing blocked: ${reason}`) + } + const stateTarget = { + account: names.stateAccount, + container: "terraform", + key: `${config.name}/public-share.tfstate`, + } + // The export storage account lives in this group, so the group is the evidence. + const resourcesExist = async () => (await read("group", "exists", "--name", shareName)) === true + const stateBlob = (await read( + "storage", "blob", "exists", "--account-name", stateTarget.account, "--container-name", + stateTarget.container, "--name", stateTarget.key, "--auth-mode", "login", + )) as { exists?: unknown } + if (typeof stateBlob.exists !== "boolean") block("Azure did not confirm whether saved public sharing state exists.") + if (!needsShareRoot(choice, stateBlob.exists === true)) { + if (await resourcesExist()) + block( + `saved state ${stateTarget.key} is missing, but public sharing resources exist. Restore the state from a blob version before retrying. No changes were made.`, + ) + return { inputs: hubShareInputs(inputs), finish: async () => [] } + } + checkPublicShareChoice(choice, inputs) + + const guard = await guardPreviewState({ + azure: context.azure, directory, target: stateTarget, resourcesExist, subject: "Public sharing", + }) + let releaseLock: Awaited> | undefined + let applying = false + const terraform = terraformModule({ + directory: resolve(import.meta.dirname, "../../public-share"), + dataDirectory: join(directory, "terraform", "public-share"), + run, + ui, + env: context.env, + signal, + preapproved: true, + validatePlan: validatePublicSharePlan, + allowDeletion: allowedShareDeletion, + findUntracked: existingRoleAssignment(context.azure, subscriptionId), + requireUntrackedCheck: true, + beforeApply: async () => { + applying = true + guard.verify(await terraform.rawState()) + await lock.verify() + await releaseLock?.verify() + }, + }) + await terraform.init(await writeBackendFile(context, "public-share")) + guard.verify(await terraform.rawState()) + const current = readShareState(await terraform.stateSnapshot()) + const output = () => terraform.output("share") + + const hubPrincipalId = await read( + "identity", "show", "--ids", `/subscriptions/${subscriptionId}/resourceGroups/${config.azure.resourceGroup}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/${config.name}-hub`, + "--query", "principalId", + ) + if (typeof hubPrincipalId !== "string" || !guid.test(hubPrincipalId)) return block("Hub's identity could not be verified.") + + const recordsFor = (share: ShareOutput) => + choice.hostname && share.generated_hostname && share.custom_domain_verification_id + ? readerDnsRecords(choice.hostname, share.generated_hostname, share.custom_domain_verification_id) + : undefined + const knownRecords = + choice.reader === "on" && choice.hostname && current.reader === "enabled" && + current.boundHostname !== choice.hostname + ? recordsFor(await output()) + : undefined + const dnsReady = knownRecords ? await dnsRecordsReady(knownRecords, resolver) : false + const target = targetShareVariables(choice, current, { dnsReady }) + const expand = expandShareVariables(current, target) + // Saved inputs may hold a release that never happened; the serving Hub is the evidence. + const servingHub = async () => { + const apps = await read( + "containerapp", "list", "--resource-group", config.azure.resourceGroup, + "--query", `[?name=='${config.name}-hub'].{env:properties.template.containers[?name=='hub'] | [0].env}`, + ) + if (!Array.isArray(apps) || apps.length > 1) return block("Hub's current settings could not be read.") + const env = (apps[0] as { env?: { name?: unknown; value?: unknown }[] | null } | undefined)?.env ?? [] + return new Map(env.flatMap(({ name, value }) => + typeof name === "string" && typeof value === "string" && name.startsWith("HUB_PUBLIC_SHARE_") ? [[name, value]] : [])) + } + const hubShares = (await servingHub()).get("HUB_PUBLIC_SHARE_ENABLED") === "true" + + const variablesFile = join(directory, "public-share.tfvars.json") + const warn = (message: string) => (ui.notice ? ui.notice("warning", message) : ui.status(message)) + const expectedGrants = (variables: ShareVariables, readerPrincipalId: string | undefined) => ({ + subscriptionId, + reader: variables.reader, + readerPrincipalId, + hubPrincipalId, + writer: variables.writer, + acrId: foundation.registry_id, + containerId, + }) + const readerPrincipal = async () => { + const id = await read("identity", "show", "--ids", readerIdentityId, "--query", "principalId") + return typeof id === "string" && guid.test(id) ? id : block("the share reader identity could not be verified.") + } + const applyVariables = async (variables: ShareVariables, underLease?: () => Promise) => { + await writePrivateFile(variablesFile, JSON.stringify({ + subscription_id: subscriptionId, + resource_group_name: config.azure.resourceGroup, + location: config.azure.location, + name: config.name, + owner: config.owner, + acr_id: foundation.registry_id, + registry_server: foundation.registry_url, + image, + reader: variables.reader, + custom_hostname: variables.custom_hostname, + bind_custom_hostname: variables.bind_custom_hostname, + writer_principal_id: variables.writer ? hubPrincipalId : null, + })) + signal?.throwIfAborted() + // Shares the private preview step's lease record, so a lock retained by either step resumes + // in whichever runs first next time. + releaseLock = await acquireLease( + context, releaseAccount, "releases", "deployment.lock", false, { operation: "private-preview" }, + ) + applying = false + try { + await underLease?.() + await terraform.apply(variablesFile) + guard.verify(await terraform.rawState()) + const bound = variables.bind_custom_hostname && variables.custom_hostname + ? await bindManagedCertificate({ + azure: context.azure, app: shareName, group: shareName, environmentId, + hostname: variables.custom_hostname, + consequence: "New links keep using the generated hostname.", warn, ...(signal && { signal }), + }) + : false + const problems = await verifyShareGrants(read, expectedGrants(variables, await readerPrincipal())) + if (problems.length) block(`${problems.join("\n")}\nReview access before retrying; the release lock is kept.`) + await releaseLock.release() + return { bound } + } catch (error) { + // A plan that stopped before apply changed nothing, so the lock is not needed for recovery. + if (!applying && releaseLock.held && !signal?.aborted) await releaseLock.release() + throw error + } finally { + releaseLock.reportRetained() + } + } + + ui.status("Preparing public sharing") + // Stop before any change on grants the wizard did not make. The reader identity survives Remove. + const existingReader = (await resourcesExist()) + ? await read("identity", "list", "--resource-group", shareName, "--query", `[?name=='${shareName}'].principalId`) + : [] + if (!Array.isArray(existingReader) || existingReader.length > 1 || + existingReader.some((id) => typeof id !== "string" || !guid.test(id))) + block("the share reader identity could not be verified.") + const problems = await verifyShareGrants( + read, expectedGrants(expand, (existingReader as string[])[0]), { unexpectedOnly: true }, + ) + if (problems.length) block(`${problems.join("\n")}\nRemove or review that access before retrying. No changes were made.`) + const { bound } = await applyVariables(expand) + const notes: string[] = [] + let share: HubShare | undefined + if (target.reader === "enabled") { + const reader = await output() + const generated = reader.generated_origin ?? block("Terraform did not report the reader's generated origin.") + const readerReady = async () => { + const status = (await read( + "containerapp", "show", "--name", shareName, "--resource-group", shareName, + "--query", "{latest:properties.latestRevisionName,ready:properties.latestReadyRevisionName}", + )) as { latest?: unknown; ready?: unknown } + return typeof status.latest === "string" && status.latest === status.ready + } + let ready = await readerReady() + for (let attempt = 1; !ready && attempt < readiness.attempts; attempt++) { + if (attempt === 1) ui.status("Waiting for the share reader revision to become ready") + await delay(readiness.delayMs, undefined, { signal }) + ready = await readerReady() + } + const records = recordsFor(reader) + if (choice.hostname && !bound && !target.bind_custom_hostname && records) { + const message = `Add these DNS records for ${choice.hostname}, then run Update again. Until Azure binds its certificate, new links use ${generated}.\n${formatDnsRecords(records)}` + notes.push(message) + ui.notice?.("warning", message) + } else if (choice.hostname && !bound) { + notes.push(`The certificate for ${choice.hostname} is not bound yet. New links use ${generated}; run Update again later.`) + } + // A sharing Hub keeps sharing while a new reader revision starts; first enablement waits for it. + if (ready || hubShares) { + const origin = choice.hostname && bound ? `https://${choice.hostname}` : generated + share = { + origin, + storageAccount: reader.storage_account, + storageContainer: reader.storage_container, + allowSharedSite: choice.allowSharedSite === true, + } + notes.push(`Public sharing: new links use ${origin}.`) + } + if (!ready) + notes.push( + hubShares + ? "The share reader's new revision is not ready yet. Check it in Azure before relying on new links." + : "The share reader revision is not ready yet. Public sharing stays off in Hub; run Update again to recheck.", + ) + } + const released = hubShareInputs(inputs, share) + // Another release may have run between the Hub release and this cleanup. + const hubUnchanged = async () => { + const serving = await servingHub() + const expected = new Map(Object.entries(released.runtime_environment_variables ?? {}) + .filter(([name]) => name.startsWith("HUB_PUBLIC_SHARE_"))) + if (serving.size !== expected.size || [...expected].some(([name, value]) => serving.get(name) !== value)) + block("Hub's public sharing settings changed after this release. Nothing was removed; review the serving Hub and run Update again.") + } + return { + inputs: released, + async finish() { + if (!sameShareVariables(expand, target)) { + ui.status("Removing public sharing access that Hub no longer uses") + await applyVariables(target, hubUnchanged) + } + return notes + }, + } +} diff --git a/infrastructure/azure/install/public-share/plan/index.test.ts b/infrastructure/azure/install/public-share/plan/index.test.ts new file mode 100644 index 000000000..965513537 --- /dev/null +++ b/infrastructure/azure/install/public-share/plan/index.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from "vitest" + +import { allowedShareDeletion, validatePublicSharePlan } from "./index.ts" + +function change(address: string, actions: string[], extra: Record = {}) { + return { address, change: { actions, ...extra } } +} + +const plan = (...resource_changes: unknown[]) => ({ resource_changes }) + +const kept = [ + "azurerm_resource_group.share", + "azurerm_storage_account.exports", + "azurerm_storage_container.exports", + "azurerm_container_app_environment.share", + "azurerm_user_assigned_identity.reader", +] + +describe("validatePublicSharePlan", () => { + it("accepts a first opt-in that creates the storage, reader, grants, and custom domain", () => { + const creations = [ + ...kept, + "azurerm_container_app.reader[0]", + "azurerm_role_assignment.image_pull[0]", + "azurerm_role_assignment.reader_exports[0]", + "azurerm_container_app_custom_domain.reader[0]", + "azurerm_role_assignment.writer[0]", + ].map((address) => change(address, ["create"])) + + expect(() => validatePublicSharePlan(plan(...creations))).not.toThrow() + }) + + it("accepts a rollback that deletes the reader app, its grants, the custom domain, and Hub's grant", () => { + const deletions = [ + "azurerm_container_app.reader[0]", + "azurerm_role_assignment.image_pull[0]", + "azurerm_role_assignment.reader_exports[0]", + "azurerm_container_app_custom_domain.reader[0]", + "azurerm_role_assignment.writer[0]", + ].map((address) => change(address, ["delete"])) + + expect(() => + validatePublicSharePlan(plan(...deletions, ...kept.map((address) => change(address, ["no-op"])))), + ).not.toThrow() + expect(deletions.every(allowedShareDeletion)).toBe(true) + }) + + it("accepts disabling the reader in place", () => { + expect(() => + validatePublicSharePlan(plan( + change("azurerm_container_app.reader[0]", ["update"]), + change("azurerm_role_assignment.writer[0]", ["delete"]), + )), + ).not.toThrow() + }) + + it.each(kept.flatMap((address) => [ + [address, ["delete"]], + [address, ["delete", "create"]], + [address, ["create", "delete"]], + [address, ["update"]], + ] as const))("blocks %s with %j so exports are never lost or rewritten", (address, actions) => { + const destructive = change(address, [...actions]) + + expect(() => validatePublicSharePlan(plan(destructive))).toThrow(/blocked/) + expect(allowedShareDeletion(destructive)).toBe(false) + }) + + it.each([ + ["replacing the reader app", [change("azurerm_container_app.reader[0]", ["delete", "create"])]], + ["updating a grant", [change("azurerm_role_assignment.reader_exports[0]", ["update"])]], + ["replacing Hub's grant", [change("azurerm_role_assignment.writer[0]", ["delete", "create"])]], + ["an import", [change("azurerm_role_assignment.writer[0]", ["no-op"], { importing: { id: "/existing" } })]], + ["a move", [{ ...change("azurerm_container_app.reader[0]", ["no-op"]), previous_address: "azurerm_container_app.reader" }]], + ["a resource outside public sharing", [change("azurerm_role_assignment.hub_storage", ["create"])]], + ["a duplicate address", [ + change("azurerm_container_app.reader[0]", ["create"]), + change("azurerm_container_app.reader[0]", ["no-op"]), + ]], + ])("blocks %s", (_, changes) => { + expect(() => validatePublicSharePlan(plan(...changes))).toThrow(/blocked/) + }) + + it.each([ + ["no resource changes list", {}], + ["deferred changes", { complete: false, resource_changes: [] }], + ["errors", { errored: true, resource_changes: [] }], + ])("blocks a plan with %s", (_, value) => { + expect(() => validatePublicSharePlan(value)).toThrow(/blocked/) + }) +}) diff --git a/infrastructure/azure/install/public-share/plan/index.ts b/infrastructure/azure/install/public-share/plan/index.ts new file mode 100644 index 000000000..1e853584f --- /dev/null +++ b/infrastructure/azure/install/public-share/plan/index.ts @@ -0,0 +1,59 @@ +const fixed = new Set([ + "azurerm_resource_group.share", + "azurerm_storage_account.exports", + "azurerm_storage_container.exports", + "azurerm_container_app_environment.share", + "azurerm_user_assigned_identity.reader", +]) +// Only these may be removed, and only because their count dropped to zero. +const optional = new Set([ + "azurerm_container_app.reader[0]", + "azurerm_role_assignment.image_pull[0]", + "azurerm_role_assignment.reader_exports[0]", + "azurerm_container_app_custom_domain.reader[0]", + "azurerm_role_assignment.writer[0]", +]) +const updatable = new Set(["azurerm_container_app.reader[0]"]) + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value) +} + +// The export storage, environment and identity are only ever created or left unchanged. +export function validatePublicSharePlan(plan: unknown): void { + const reject = (reason: string): never => { + throw new Error(`Public sharing plan blocked: ${reason} No changes were applied.`) + } + if (!isRecord(plan) || plan.complete === false || plan.errored === true || + !Array.isArray(plan.resource_changes)) + return reject("Terraform did not return a complete plan.") + const seen = new Set() + for (const resource of plan.resource_changes) { + if (!isRecord(resource) || typeof resource.address !== "string" || !isRecord(resource.change) || + !Array.isArray(resource.change.actions)) + return reject("the plan has an unreadable resource change.") + const { address, change } = resource + const actions = (change.actions as unknown[]).join("/") + if ((!fixed.has(address) && !optional.has(address)) || seen.has(address)) + return reject(`${address} is outside public sharing.`) + seen.add(address) + if (change.importing !== undefined) return reject(`${address} would be imported.`) + if (resource.previous_address !== undefined) return reject(`${address} would move from another address.`) + if (!allowedAction(address, actions)) return reject(`${actions} ${address} is not allowed.`) + } +} + +function allowedAction(address: string, actions: string) { + return ( + actions === "create" || + actions === "no-op" || + (actions === "update" && updatable.has(address)) || + (actions === "delete" && optional.has(address)) + ) +} + +// Terraform's generic guard blocks every deletion; these are the reviewed exceptions. +export function allowedShareDeletion({ address, change }: { address: string; change: { actions: string[] } }) { + const actions = change.actions.join("/") + return actions === "delete" && allowedAction(address, actions) +} diff --git a/infrastructure/azure/install/public-share/settings/index.test.ts b/infrastructure/azure/install/public-share/settings/index.test.ts new file mode 100644 index 000000000..912614fbc --- /dev/null +++ b/infrastructure/azure/install/public-share/settings/index.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest" + +import { readShareState, targetShareVariables } from "./index.ts" + +describe("public sharing settings", () => { + it.each([ + ["another hostname", "links.example.net"], + ["no hostname", undefined], + ])("blocks changing a bound custom domain to %s while sharing stays on", (_, hostname) => { + const current = { reader: "enabled", writer: true, boundHostname: "share.example.net" } as const + + expect(() => + targetShareVariables({ reader: "on", ...(hostname && { hostname }) }, current, { dnsReady: true }), + ).toThrow(/already bound to share\.example\.net/) + }) + + it.each([ + ["another state format", { format_version: "0.2", values: {} }], + ["child modules", { format_version: "1.0", values: { root_module: { resources: [], child_modules: [{}] } } }], + ["unreadable resources", { format_version: "1.0", values: { root_module: { resources: {} } } }], + ])("blocks saved state with %s instead of treating it as empty", (_, snapshot) => { + expect(() => readShareState(snapshot)).toThrow(/unexpected shape/) + }) +}) diff --git a/infrastructure/azure/install/public-share/settings/index.ts b/infrastructure/azure/install/public-share/settings/index.ts new file mode 100644 index 000000000..7dc7e5c85 --- /dev/null +++ b/infrastructure/azure/install/public-share/settings/index.ts @@ -0,0 +1,93 @@ +import type { PublicShareChoice } from "../../../../installer/types.ts" +import type { ReaderMode } from "../../private-preview/settings/index.ts" + +// What saved public-share Terraform state records. +export interface ShareState { + reader: ReaderMode + writer: boolean + boundHostname?: string +} + +export interface ShareVariables { + reader: ReaderMode + custom_hostname: string | null + bind_custom_hostname: boolean + writer: boolean +} + +export const noShareState: ShareState = { reader: "absent", writer: false } + +export const offShareChoice: PublicShareChoice = { reader: "off" } + +const rank: Record = { absent: 0, disabled: 1, enabled: 2 } + +export function targetShareVariables( + choice: PublicShareChoice, + current: ShareState, + { dnsReady }: { dnsReady: boolean }, +): ShareVariables { + const reader: ReaderMode = + choice.reader === "on" + ? "enabled" + : choice.reader === "removed" || current.reader === "absent" + ? "absent" + : "disabled" + const enabled = reader === "enabled" + const hostname = enabled ? (choice.hostname ?? null) : null + if (enabled && current.boundHostname && current.boundHostname !== hostname) + throw new Error( + `Public sharing blocked: the reader is already bound to ${current.boundHostname}. Changing or removing its hostname is not supported while sharing is on. Turn sharing off first, then choose the new hostname. No changes were made.`, + ) + return { + reader, + custom_hostname: hostname, + bind_custom_hostname: hostname !== null && (current.boundHostname === hostname || dnsReady), + writer: enabled, + } +} + +// Before Hub changes, keep everything the running Hub may still use; afterwards, apply the target. +export function expandShareVariables(current: ShareState, target: ShareVariables): ShareVariables { + const reader = rank[current.reader] > rank[target.reader] ? current.reader : target.reader + const enabled = reader === "enabled" + const hostname = target.custom_hostname ?? (enabled ? (current.boundHostname ?? null) : null) + return { + reader, + custom_hostname: hostname, + bind_custom_hostname: + hostname !== null && (current.boundHostname === hostname || target.bind_custom_hostname), + writer: target.writer || current.writer, + } +} + +export function sameShareVariables(left: ShareVariables, right: ShareVariables) { + return JSON.stringify(left) === JSON.stringify(right) +} + +// Sharing that was never turned on needs no Terraform root, state or Azure resources. +export function needsShareRoot(choice: PublicShareChoice, stateExists: boolean) { + return stateExists || choice.reader === "on" +} + +type StateResource = { address?: unknown; values?: { name?: unknown; ingress?: unknown[] } } + +// Reads `terraform show -json` of the public-share root. +export function readShareState(snapshot: unknown): ShareState { + const invalid = () => new Error("Public sharing blocked: saved state has an unexpected shape. No changes were made.") + if (typeof snapshot !== "object" || snapshot === null) throw invalid() + const { format_version: format, values } = snapshot as { format_version?: unknown; values?: unknown } + if (format !== "1.0") throw invalid() + if (values === undefined) return noShareState + const root = (values as { root_module?: { resources?: unknown; child_modules?: unknown[] } }).root_module + if (!root || root.child_modules?.length || (root.resources !== undefined && !Array.isArray(root.resources))) + throw invalid() + const resources = (root.resources ?? []) as StateResource[] + const find = (address: string) => resources.find((resource) => resource.address === address) + const app = find("azurerm_container_app.reader[0]") + const domain = find("azurerm_container_app_custom_domain.reader[0]")?.values?.name + return { + reader: !app ? "absent" : app.values?.ingress?.length ? "enabled" : "disabled", + writer: Boolean(find("azurerm_role_assignment.writer[0]")), + ...(typeof domain === "string" ? { boundHostname: domain } : {}), + } +} diff --git a/infrastructure/azure/post/configure/index.test.ts b/infrastructure/azure/post/configure/index.test.ts index 2584258a5..c64576c81 100644 --- a/infrastructure/azure/post/configure/index.test.ts +++ b/infrastructure/azure/post/configure/index.test.ts @@ -374,6 +374,33 @@ it.each([ expect(test.run.mock.calls.filter(([, args]) => args[2] === "set")).toEqual([]) }) +it.each(["saved inputs", "serving Hub"] as const)( + "blocks changing the origin while public sharing is on in the %s", + async (source) => { + const test = await scenario() + await configuredGithub(test) + Object.assign( + source === "saved inputs" ? test.inputs.runtime_environment_variables! : test.deployment.environment, + { HUB_PUBLIC_SHARE_ENABLED: "true" }, + ) + const original = structuredClone(test.inputs) + // Only the origin and hop count come before the guard; a later prompt means it did not stop. + vi.mocked(test.ui.text).mockImplementation(async (label) => { + if (label.startsWith("Public HTTPS origin")) return "https://bound.example.com" + if (label.startsWith("Verified protected proxy hop count")) return "2" + throw new Error(`Unexpected prompt: ${label}`) + }) + + await expect( + configurePostSetup(test.context, "sign-in", test.inputs, test.deployment), + ).rejects.toThrow(/Public sharing depends on Hub's origin/) + + expect(test.inputs).toEqual(original) + expect(test.run.mock.calls.filter(([, args]) => args[2] === "set")).toEqual([]) + expect(test.provider.verifications).toBe(0) + }, +) + it("rejects a bound hostname with an unbound port and accepts its canonical HTTPS origin", async () => { const test = await scenario() test.deployment.customHosts = ["BoUnD.ExAmPlE.CoM"] diff --git a/infrastructure/azure/post/configure/index.ts b/infrastructure/azure/post/configure/index.ts index a3771929c..160a7ef91 100644 --- a/infrastructure/azure/post/configure/index.ts +++ b/infrastructure/azure/post/configure/index.ts @@ -419,6 +419,15 @@ export async function configurePostSetup( "The private prototype service uses Hub's origin and proxy hop count. Turn it off with setup Update, change these settings, then turn it on again. Existing settings were preserved.", ) if (previewServing && originChanged) throw previewBlocked() + // Hub refuses to share while its hostname is a generated one, unless the saved override allows it. + if ( + originChanged && + (inputs.runtime_environment_variables?.HUB_PUBLIC_SHARE_ENABLED === "true" || + deployment.environment.HUB_PUBLIC_SHARE_ENABLED === "true") + ) + throw new PostSetupExit( + "Public sharing depends on Hub's origin. Turn it off with setup Update, change the origin, then turn it on again. Existing settings were preserved.", + ) if ( originChanged && [ diff --git a/infrastructure/azure/public-share/.terraform.lock.hcl b/infrastructure/azure/public-share/.terraform.lock.hcl new file mode 100644 index 000000000..0bd5c5290 --- /dev/null +++ b/infrastructure/azure/public-share/.terraform.lock.hcl @@ -0,0 +1,23 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/hashicorp/azurerm" { + version = "4.50.0" + constraints = "4.50.0" + hashes = [ + "h1:Q/JIe7B0F7cziHSDBE7Yr+mFxhtNCDe3JjxuobOGh6w=", + "h1:j2bM6QYxBw4dKDlNLR2lAWP6Dggv5lhyGU5VREOfaDw=", + "zh:11899f771a9f03c4e5d222d73ce842e930d26af8aaba88b99a2f0638265331dc", + "zh:2450a4258f40f6ba1f6705a10b2bdb6ff2067ab4c2a6938135391df03c974251", + "zh:2754e761370a18dab5748e020f595e08a7859522889e800204e7a5f65b026590", + "zh:6072e006b1c1b5c1e0a39d373bb6beebf5b4dbb619627c510b6a741521d226c6", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:8ddb7263f15bc16f3b85be8377c9e32ffa4db4cf809586d8010633698ff66105", + "zh:96f973bc54db728defca4817fbd9b1a412c538542e497536d1ce5f6be9946801", + "zh:aa519b7bad1e75930d84ec9ea8462ec384ed26a6ea172281cbd93244ecf8059b", + "zh:adbc238c95915d23d610990770f4b83e576311d4114b9662c4e967d0b0065b1b", + "zh:eaf94d50425ad88cdd42170e9737d8cb1a557ca3737cb905ce34e0218ec621f3", + "zh:f7aa0004e92e67fcee5d8725b878c8de7e6db6f0f766cbe2257d49a994b314f7", + "zh:fbb1195ea2784d67c690ed399b27d59d015c417dec21667f07a6aaf4099cd174", + ] +} diff --git a/infrastructure/azure/public-share/main.tf b/infrastructure/azure/public-share/main.tf new file mode 100644 index 000000000..88cdb3ee0 --- /dev/null +++ b/infrastructure/azure/public-share/main.tf @@ -0,0 +1,346 @@ +terraform { + required_version = ">= 1.13.0, < 2.0.0" + + backend "azurerm" {} + + required_providers { + azurerm = { + source = "hashicorp/azurerm" + version = "= 4.50.0" + } + } +} + +provider "azurerm" { + subscription_id = var.subscription_id + storage_use_azuread = true + resource_provider_registrations = "none" + features { + resource_group { + prevent_deletion_if_contains_resources = true + } + } +} + +variable "subscription_id" { + type = string +} + +variable "resource_group_name" { + description = "Hub's resource group. Only its Log Analytics workspace is reused." + type = string +} + +variable "location" { + type = string +} + +variable "name" { + type = string +} + +variable "owner" { + type = string +} + +variable "acr_id" { + type = string +} + +variable "registry_server" { + type = string +} + +variable "image" { + type = string + validation { + condition = startswith(var.image, "${var.registry_server}/") && can(regex("^[a-z0-9][a-z0-9.:/-]+@sha256:[a-f0-9]{64}$", var.image)) + error_message = "Use an immutable image digest from the installation registry." + } +} + +variable "reader" { + description = "absent removes the reader app and its grants, disabled keeps a placeholder without ingress, enabled serves public shares." + type = string + default = "disabled" + nullable = false + validation { + condition = contains(["absent", "disabled", "enabled"], var.reader) + error_message = "Set reader to absent, disabled, or enabled." + } +} + +variable "custom_hostname" { + type = string + default = null + validation { + condition = var.custom_hostname == null || (can(regex("^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$", var.custom_hostname)) && !endswith(".${coalesce(var.custom_hostname, "-")}", ".azurecontainerapps.io")) + error_message = "Use one lowercase DNS hostname outside azurecontainerapps.io, without a wildcard, scheme, or port." + } +} + +variable "bind_custom_hostname" { + description = "Add the custom hostname to the reader after its DNS records exist." + type = bool + default = false + nullable = false +} + +variable "writer_principal_id" { + description = "Hub workload identity that writes and revokes exports. Null keeps Hub's grant absent." + type = string + default = null +} + +locals { + share_name = "${var.name}-share" + enabled = var.reader == "enabled" + present = var.reader != "absent" + workspace_id = "/subscriptions/${var.subscription_id}/resourceGroups/${var.resource_group_name}/providers/Microsoft.OperationalInsights/workspaces/${var.name}-logs" + container_id = "${azurerm_storage_account.exports.id}/blobServices/default/containers/${azurerm_storage_container.exports.name}" + # Every link keeps working on the generated origin after a custom domain is added. + generated_origin = "https://${local.share_name}.${azurerm_container_app_environment.share.default_domain}" + custom_origin = local.enabled && var.bind_custom_hostname && var.custom_hostname != null ? "https://${var.custom_hostname}" : null + # Exact text the wizard compares with Azure before accepting a grant. + without_listing = trimspace(<<-EOT + ( + ( + !(ActionMatches{'Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read'} AND SubOperationMatches{'Blob.List'}) + ) + ) + EOT + ) + disabled_command = ["node", "-e", "require('node:net').createServer(socket => socket.destroy()).listen(3003, '0.0.0.0')"] + # Only the reader's own settings: it refuses to start beside any Hub setting. + reader_environment = local.enabled ? merge({ + NODE_ENV = "production" + HOST = "0.0.0.0" + PORT = "3003" + PUBLIC_SHARE_GENERATED_ORIGIN = local.generated_origin + PUBLIC_SHARE_TRUSTED_PROXY_HOPS = "1" + PUBLIC_SHARE_STORAGE_PROVIDER = "azure" + PUBLIC_SHARE_STORAGE_ACCOUNT = azurerm_storage_account.exports.name + PUBLIC_SHARE_STORAGE_CONTAINER = azurerm_storage_container.exports.name + AZURE_CLIENT_ID = azurerm_user_assigned_identity.reader.client_id + }, local.custom_origin == null ? {} : { PUBLIC_SHARE_CUSTOM_ORIGIN = local.custom_origin }) : {} + tags = { + application = "replica-hub" + installation = var.name + owner = var.owner + managed_by = "terraform" + } +} + +resource "azurerm_resource_group" "share" { + name = local.share_name + location = var.location + tags = local.tags + + lifecycle { + prevent_destroy = true + } +} + +# Public export copies. Turning sharing off or removing the reader never deletes them. +resource "azurerm_storage_account" "exports" { + name = "${replace(var.name, "-", "")}pub" + location = var.location + resource_group_name = azurerm_resource_group.share.name + account_tier = "Standard" + account_replication_type = "LRS" + min_tls_version = "TLS1_2" + https_traffic_only_enabled = true + allow_nested_items_to_be_public = false + shared_access_key_enabled = false + default_to_oauth_authentication = true + tags = local.tags + + # Copies are deleted within 24 hours of revocation, so blobs are not versioned or soft-deleted. + # The container itself can be restored for a week. + blob_properties { + container_delete_retention_policy { + days = 7 + } + } + + lifecycle { + prevent_destroy = true + } +} + +resource "azurerm_storage_container" "exports" { + name = "public-share-exports" + storage_account_id = azurerm_storage_account.exports.id + container_access_type = "private" + + lifecycle { + prevent_destroy = true + } +} + +# Its own environment, without a subnet: no network path to Hub's database, Key Vault or storage. +resource "azurerm_container_app_environment" "share" { + name = "${local.share_name}-environment" + resource_group_name = azurerm_resource_group.share.name + location = var.location + log_analytics_workspace_id = local.workspace_id + logs_destination = "log-analytics" + tags = local.tags + + workload_profile { + name = "Consumption" + workload_profile_type = "Consumption" + minimum_count = 0 + maximum_count = 0 + } + + lifecycle { + prevent_destroy = true + ignore_changes = [infrastructure_resource_group_name] + } +} + +resource "azurerm_user_assigned_identity" "reader" { + name = local.share_name + resource_group_name = azurerm_resource_group.share.name + location = var.location + tags = local.tags + + lifecycle { + prevent_destroy = true + } +} + +resource "azurerm_role_assignment" "image_pull" { + count = local.present ? 1 : 0 + scope = var.acr_id + role_definition_name = "AcrPull" + principal_id = azurerm_user_assigned_identity.reader.principal_id +} + +# The reader reads exports by exact key, but cannot list, write or delete them. +resource "azurerm_role_assignment" "reader_exports" { + count = local.present ? 1 : 0 + scope = local.container_id + role_definition_name = "Storage Blob Data Reader" + principal_id = azurerm_user_assigned_identity.reader.principal_id + condition_version = "2.0" + condition = local.without_listing +} + +resource "azurerm_container_app" "reader" { + count = local.present ? 1 : 0 + name = local.share_name + resource_group_name = azurerm_resource_group.share.name + container_app_environment_id = azurerm_container_app_environment.share.id + workload_profile_name = "Consumption" + revision_mode = "Single" + tags = local.tags + + identity { + type = "UserAssigned" + identity_ids = [azurerm_user_assigned_identity.reader.id] + } + + registry { + server = var.registry_server + identity = azurerm_user_assigned_identity.reader.id + } + + dynamic "ingress" { + for_each = local.enabled ? [1] : [] + content { + external_enabled = true + allow_insecure_connections = false + target_port = 3003 + transport = "http" + traffic_weight { + latest_revision = true + percentage = 100 + } + } + } + + template { + min_replicas = 1 + max_replicas = 1 + + container { + name = local.enabled ? "reader" : "disabled" + image = var.image + cpu = 0.25 + memory = "0.5Gi" + # The image runs as its non-root user. The disabled listener only checks that the image can start. + command = local.enabled ? ["node", "dist/server/scripts/start-public-share-reader/index.js"] : local.disabled_command + + dynamic "env" { + for_each = local.reader_environment + content { + name = env.key + value = env.value + } + } + + startup_probe { + transport = "TCP" + port = 3003 + } + + readiness_probe { + transport = "TCP" + port = 3003 + } + + liveness_probe { + transport = "TCP" + port = 3003 + } + } + } + + lifecycle { + precondition { + condition = !var.bind_custom_hostname || (local.enabled && var.custom_hostname != null) + error_message = "Bind a custom hostname only to an enabled reader." + } + } + + depends_on = [azurerm_role_assignment.image_pull] +} + +# Azure issues and binds the managed certificate after the wizard verifies DNS. +resource "azurerm_container_app_custom_domain" "reader" { + count = local.enabled && var.bind_custom_hostname ? 1 : 0 + name = var.custom_hostname + container_app_id = azurerm_container_app.reader[0].id + + lifecycle { + ignore_changes = [certificate_binding_type, container_app_environment_certificate_id] + } +} + +# Hub creates, overwrites, reads and deletes exports, in this container only. +resource "azurerm_role_assignment" "writer" { + count = var.writer_principal_id != null ? 1 : 0 + scope = local.container_id + role_definition_name = "Storage Blob Data Contributor" + principal_id = var.writer_principal_id + principal_type = "ServicePrincipal" +} + +output "share" { + # The verification ID is published in DNS, so it is not secret. + description = "Reader and export coordinates and the DNS values for a custom hostname. No credentials are emitted." + value = { + mode = var.reader + generated_origin = local.enabled ? local.generated_origin : null + custom_origin = local.custom_origin + generated_hostname = local.enabled ? try(azurerm_container_app.reader[0].ingress[0].fqdn, null) : null + custom_domain_verification_id = local.enabled ? try(nonsensitive(azurerm_container_app.reader[0].custom_domain_verification_id), null) : null + storage_account = azurerm_storage_account.exports.name + storage_container = azurerm_storage_container.exports.name + app_name = local.share_name + resource_group = azurerm_resource_group.share.name + environment_id = azurerm_container_app_environment.share.id + } +} diff --git a/infrastructure/azure/public-share/tests/disabled.tftest.hcl b/infrastructure/azure/public-share/tests/disabled.tftest.hcl new file mode 100644 index 000000000..1e181376b --- /dev/null +++ b/infrastructure/azure/public-share/tests/disabled.tftest.hcl @@ -0,0 +1,137 @@ +mock_provider "azurerm" { + override_during = plan + + mock_resource "azurerm_storage_account" { + defaults = { + id = "/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/test-hub-share/providers/Microsoft.Storage/storageAccounts/testhubpub" + } + } + + mock_resource "azurerm_container_app_environment" { + defaults = { + default_domain = "calm-1234.eastus2.azurecontainerapps.io" + id = "/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/test-hub-share/providers/Microsoft.App/managedEnvironments/test-hub-share-environment" + } + } + + mock_resource "azurerm_user_assigned_identity" { + defaults = { + id = "/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/test-hub-share/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-hub-share" + principal_id = "00000000-0000-0000-0000-000000000002" + client_id = "00000000-0000-0000-0000-000000000003" + } + } +} + +variables { + subscription_id = "00000000-0000-0000-0000-000000000001" + resource_group_name = "test-hub-rg" + location = "eastus2" + name = "test-hub" + owner = "test-team" + acr_id = "/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/test-hub-foundation/providers/Microsoft.ContainerRegistry/registries/testhubregistry" + registry_server = "testhubregistry.azurecr.io" + image = "testhubregistry.azurecr.io/replica-hub@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +} + +run "a_disabled_reader_serves_nothing_and_hub_gets_no_access" { + command = plan + + assert { + condition = ( + azurerm_resource_group.share.name == "test-hub-share" && + azurerm_container_app.reader[0].resource_group_name == azurerm_resource_group.share.name && + azurerm_container_app.reader[0].container_app_environment_id == azurerm_container_app_environment.share.id && + azurerm_container_app_environment.share.infrastructure_subnet_id == null && + length(azurerm_container_app.reader[0].ingress) == 0 && + length(one(azurerm_container_app.reader[0].template[0].container).env) == 0 && + length(azurerm_container_app.reader[0].secret) == 0 && + !can(regex("start-public-share-reader", join(" ", one(azurerm_container_app.reader[0].template[0].container).command))) && + length(azurerm_role_assignment.writer) == 0 && + output.share.generated_origin == null && + output.share.custom_origin == null + ) + error_message = "A disabled reader runs only a placeholder, in its own environment without a subnet, ingress or settings, and Hub gets no export grant." + } + + assert { + condition = ( + azurerm_container_app_environment.share.log_analytics_workspace_id == "/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/test-hub-rg/providers/Microsoft.OperationalInsights/workspaces/test-hub-logs" && + one(azurerm_container_app.reader[0].registry).server == var.registry_server && + one(azurerm_container_app.reader[0].registry).identity == azurerm_user_assigned_identity.reader.id && + azurerm_role_assignment.image_pull[0].scope == var.acr_id && + azurerm_role_assignment.image_pull[0].role_definition_name == "AcrPull" && + azurerm_role_assignment.image_pull[0].principal_id == azurerm_user_assigned_identity.reader.principal_id + ) + error_message = "The reader reuses Hub's registry and Log Analytics workspace with its own identity." + } + + assert { + condition = ( + azurerm_storage_account.exports.name == "testhubpub" && + azurerm_storage_account.exports.resource_group_name == azurerm_resource_group.share.name && + !azurerm_storage_account.exports.shared_access_key_enabled && + !azurerm_storage_account.exports.allow_nested_items_to_be_public && + azurerm_storage_account.exports.default_to_oauth_authentication && + azurerm_storage_account.exports.https_traffic_only_enabled && + azurerm_storage_account.exports.min_tls_version == "TLS1_2" && + azurerm_storage_container.exports.name == "public-share-exports" && + azurerm_storage_container.exports.storage_account_id == azurerm_storage_account.exports.id && + azurerm_storage_container.exports.container_access_type == "private" + ) + error_message = "Exports live in a separate private storage account and container with shared keys and anonymous access off." + } + + assert { + condition = ( + azurerm_role_assignment.reader_exports[0].scope == "${azurerm_storage_account.exports.id}/blobServices/default/containers/public-share-exports" && + azurerm_role_assignment.reader_exports[0].role_definition_name == "Storage Blob Data Reader" && + azurerm_role_assignment.reader_exports[0].principal_id == azurerm_user_assigned_identity.reader.principal_id && + azurerm_role_assignment.reader_exports[0].condition_version == "2.0" && + # The wizard compares this exact text with Azure before accepting a grant. + azurerm_role_assignment.reader_exports[0].condition == "(\n (\n !(ActionMatches{'Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read'} AND SubOperationMatches{'Blob.List'})\n )\n)" + ) + error_message = "The reader may only read exact objects in the export container, without listing." + } +} + +run "reject_a_mutable_reader_image" { + command = plan + + variables { + image = "testhubregistry.azurecr.io/replica-hub:latest" + } + + expect_failures = [var.image] +} + +run "reject_a_generated_custom_hostname" { + command = plan + + variables { + custom_hostname = "share.other-5678.eastus2.azurecontainerapps.io" + } + + expect_failures = [var.custom_hostname] +} + +run "reject_the_generated_apex_as_a_custom_hostname" { + command = plan + + variables { + custom_hostname = "azurecontainerapps.io" + } + + expect_failures = [var.custom_hostname] +} + +run "reject_binding_a_hostname_to_a_disabled_reader" { + command = plan + + variables { + custom_hostname = "share.example.net" + bind_custom_hostname = true + } + + expect_failures = [azurerm_container_app.reader] +} diff --git a/infrastructure/azure/public-share/tests/modes.tftest.hcl b/infrastructure/azure/public-share/tests/modes.tftest.hcl new file mode 100644 index 000000000..d17926cc3 --- /dev/null +++ b/infrastructure/azure/public-share/tests/modes.tftest.hcl @@ -0,0 +1,182 @@ +mock_provider "azurerm" { + override_during = plan + + mock_resource "azurerm_storage_account" { + defaults = { + id = "/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/test-hub-share/providers/Microsoft.Storage/storageAccounts/testhubpub" + } + } + + mock_resource "azurerm_container_app_environment" { + defaults = { + default_domain = "calm-1234.eastus2.azurecontainerapps.io" + id = "/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/test-hub-share/providers/Microsoft.App/managedEnvironments/test-hub-share-environment" + } + } + + mock_resource "azurerm_user_assigned_identity" { + defaults = { + id = "/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/test-hub-share/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-hub-share" + principal_id = "00000000-0000-0000-0000-000000000002" + client_id = "00000000-0000-0000-0000-000000000003" + } + } + + mock_resource "azurerm_container_app" { + defaults = { + id = "/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/test-hub-share/providers/Microsoft.App/containerApps/test-hub-share" + custom_domain_verification_id = "VERIFICATIONID" + } + } +} + +variables { + subscription_id = "00000000-0000-0000-0000-000000000001" + resource_group_name = "test-hub-rg" + location = "eastus2" + name = "test-hub" + owner = "test-team" + acr_id = "/subscriptions/00000000-0000-0000-0000-000000000001/resourceGroups/test-hub-foundation/providers/Microsoft.ContainerRegistry/registries/testhubregistry" + registry_server = "testhubregistry.azurecr.io" + image = "testhubregistry.azurecr.io/replica-hub@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + writer_principal_id = "00000000-0000-0000-0000-000000000004" +} + +run "enable_the_reader_on_its_generated_hostname" { + command = plan + + variables { + reader = "enabled" + } + + assert { + condition = ( + one(azurerm_container_app.reader[0].ingress).external_enabled && + !one(azurerm_container_app.reader[0].ingress).allow_insecure_connections && + one(azurerm_container_app.reader[0].ingress).target_port == 3003 && + one(azurerm_container_app.reader[0].template[0].container).command == tolist(["node", "dist/server/scripts/start-public-share-reader/index.js"]) && + one(azurerm_container_app.reader[0].template[0].container).image == var.image && + one(azurerm_container_app.reader[0].template[0].container).liveness_probe[0].transport == "TCP" && + length(azurerm_container_app_custom_domain.reader) == 0 + ) + error_message = "An enabled reader runs the pinned image's public share reader behind HTTPS-only ingress with a TCP liveness probe." + } + + assert { + condition = ( + output.share.generated_origin == "https://test-hub-share.calm-1234.eastus2.azurecontainerapps.io" && + output.share.custom_origin == null && + output.share.storage_account == "testhubpub" && + output.share.storage_container == "public-share-exports" && + { for setting in one(azurerm_container_app.reader[0].template[0].container).env : setting.name => setting.value } == { + NODE_ENV = "production" + HOST = "0.0.0.0" + PORT = "3003" + PUBLIC_SHARE_GENERATED_ORIGIN = "https://test-hub-share.calm-1234.eastus2.azurecontainerapps.io" + PUBLIC_SHARE_TRUSTED_PROXY_HOPS = "1" + PUBLIC_SHARE_STORAGE_PROVIDER = "azure" + PUBLIC_SHARE_STORAGE_ACCOUNT = "testhubpub" + PUBLIC_SHARE_STORAGE_CONTAINER = "public-share-exports" + AZURE_CLIENT_ID = "00000000-0000-0000-0000-000000000003" + } && + length(azurerm_container_app.reader[0].secret) == 0 + ) + error_message = "The reader gets only its own settings and no secrets, so it never holds Hub's settings or credentials." + } + + assert { + condition = ( + azurerm_role_assignment.writer[0].principal_id == var.writer_principal_id && + azurerm_role_assignment.writer[0].role_definition_name == "Storage Blob Data Contributor" && + azurerm_role_assignment.writer[0].scope == "${azurerm_storage_account.exports.id}/blobServices/default/containers/public-share-exports" && + azurerm_role_assignment.writer[0].principal_type == "ServicePrincipal" + ) + error_message = "Hub's identity may create, overwrite, read and delete exports in the export container only." + } +} + +run "wait_for_dns_before_binding_a_custom_hostname" { + command = plan + + variables { + reader = "enabled" + custom_hostname = "share.example.net" + } + + assert { + condition = ( + length(azurerm_container_app_custom_domain.reader) == 0 && + output.share.custom_origin == null && + output.share.custom_domain_verification_id == "VERIFICATIONID" && + !contains([for setting in one(azurerm_container_app.reader[0].template[0].container).env : setting.name], "PUBLIC_SHARE_CUSTOM_ORIGIN") + ) + error_message = "A custom hostname is neither bound nor accepted until its DNS records exist." + } +} + +run "bind_a_custom_hostname_and_keep_the_generated_origin" { + command = plan + + variables { + reader = "enabled" + custom_hostname = "share.example.net" + bind_custom_hostname = true + } + + assert { + condition = ( + azurerm_container_app_custom_domain.reader[0].name == "share.example.net" && + azurerm_container_app_custom_domain.reader[0].container_app_id == azurerm_container_app.reader[0].id && + output.share.custom_origin == "https://share.example.net" && + output.share.generated_origin == "https://test-hub-share.calm-1234.eastus2.azurecontainerapps.io" && + { for setting in one(azurerm_container_app.reader[0].template[0].container).env : setting.name => setting.value }["PUBLIC_SHARE_CUSTOM_ORIGIN"] == "https://share.example.net" && + { for setting in one(azurerm_container_app.reader[0].template[0].container).env : setting.name => setting.value }["PUBLIC_SHARE_GENERATED_ORIGIN"] == "https://test-hub-share.calm-1234.eastus2.azurecontainerapps.io" + ) + error_message = "A bound custom hostname is accepted beside the generated origin, so existing links keep working." + } +} + +run "turning_sharing_off_keeps_exports_and_removes_hub_access" { + command = plan + + variables { + reader = "disabled" + custom_hostname = "share.example.net" + writer_principal_id = null + } + + assert { + condition = ( + length(azurerm_container_app.reader) == 1 && + length(azurerm_container_app.reader[0].ingress) == 0 && + length(azurerm_container_app_custom_domain.reader) == 0 && + length(azurerm_role_assignment.writer) == 0 && + azurerm_storage_container.exports.name == "public-share-exports" + ) + error_message = "Off keeps the storage and a placeholder reader without ingress, its hostname or Hub's grant." + } +} + +run "rollback_removes_the_reader_and_every_grant_but_keeps_exports" { + command = plan + + variables { + reader = "absent" + writer_principal_id = null + } + + assert { + condition = ( + length(azurerm_container_app.reader) == 0 && + length(azurerm_container_app_custom_domain.reader) == 0 && + length(azurerm_role_assignment.image_pull) == 0 && + length(azurerm_role_assignment.reader_exports) == 0 && + length(azurerm_role_assignment.writer) == 0 && + azurerm_storage_account.exports.name == "testhubpub" && + azurerm_storage_container.exports.name == "public-share-exports" && + azurerm_user_assigned_identity.reader.name == "test-hub-share" && + azurerm_container_app_environment.share.name == "test-hub-share-environment" + ) + error_message = "Rollback removes the reader app and every grant and keeps the storage, environment and identity." + } +} diff --git a/infrastructure/installer/config/index.test.ts b/infrastructure/installer/config/index.test.ts index b0b783f03..798c0e4fc 100644 --- a/infrastructure/installer/config/index.test.ts +++ b/infrastructure/installer/config/index.test.ts @@ -209,6 +209,30 @@ describe("deployment configuration", () => { expect(() => parseConfig({ ...configuration(), privatePreview })).toThrow(/private preview/) }) + it("saves and reloads a public sharing choice so non-interactive updates keep it", async () => { + const file = path.join(await configDirectory(), "installation.json") + const config = { + ...configuration(), + publicShare: { reader: "on" as const, hostname: "share.example.net", allowSharedSite: true as const }, + } + + await saveConfig(file, config, { exclusive: true }) + + expect(await loadConfig(file)).toEqual(config) + }) + + it.each([ + ["a hostname under azurecontainerapps.io", { reader: "on", hostname: "share.eastus2.azurecontainerapps.io" }], + ["the azurecontainerapps.io apex", { reader: "on", hostname: "azurecontainerapps.io" }], + ["a hostname with a scheme", { reader: "on", hostname: "https://share.example.net" }], + ["a hostname when the reader is removed", { reader: "removed", hostname: "share.example.net" }], + ["a shared-site override other than true", { reader: "on", allowSharedSite: false }], + ["an unknown reader mode", { reader: "disabled" }], + ["an unknown field", { reader: "on", origin: "https://share.example.net" }], + ])("rejects public sharing settings with %s", (_, publicShare) => { + expect(() => parseConfig({ ...configuration(), publicShare })).toThrow(/public sharing/) + }) + it("saves and reloads only the non-secret configuration with private file permissions", async () => { const directory = await configDirectory() const filename = path.join(directory, "config.json") diff --git a/infrastructure/installer/config/index.ts b/infrastructure/installer/config/index.ts index 2a5807817..752e424f5 100644 --- a/infrastructure/installer/config/index.ts +++ b/infrastructure/installer/config/index.ts @@ -1,4 +1,4 @@ -import type { DeploymentConfig, PrivatePreviewChoice } from "../types.ts" +import type { DeploymentConfig, PrivatePreviewChoice, PublicShareChoice } from "../types.ts" import { configurationFields, parseAzureId } from "./fields/index.ts" import { writePrivateJson } from "../write-private-json/index.ts" import { readPrivateFile } from "../private-files/index.ts" @@ -41,7 +41,7 @@ export function parseConfig(value: unknown): DeploymentConfig { } } const config = record(value) - keys(config, ["version", "cloud", "name", "owner", "npmRegistry", "azure", "privatePreview"]) + keys(config, ["version", "cloud", "name", "owner", "npmRegistry", "azure", "privatePreview", "publicShare"]) if (config.version !== 1 || config.cloud !== "azure") { throw new Error("This installer supports configuration version 1 and cloud azure.") } @@ -55,6 +55,8 @@ export function parseConfig(value: unknown): DeploymentConfig { : configurationFields.npmRegistry.parse(config.npmRegistry) const privatePreview = config.privatePreview === undefined ? undefined : parsePrivatePreview(record(config.privatePreview)) + const publicShare = + config.publicShare === undefined ? undefined : parsePublicShare(record(config.publicShare)) return { version: 1, cloud: "azure", @@ -62,6 +64,7 @@ export function parseConfig(value: unknown): DeploymentConfig { owner: configurationFields.owner.parse(config.owner), ...(npmRegistry ? { npmRegistry } : {}), ...(privatePreview ? { privatePreview } : {}), + ...(publicShare ? { publicShare } : {}), azure: { subscriptionId: parseAzureId(azure.subscriptionId), tenantId: parseAzureId(azure.tenantId), @@ -102,6 +105,35 @@ function parsePrivatePreview(value: Record): PrivatePreviewChoi } } +// Every generated Container Apps hostname is one site, so a custom domain must be outside it. +export function isShareHostname(value: unknown): value is string { + return ( + typeof value === "string" && + value.length <= 253 && + readerHostname.test(value) && + value !== "azurecontainerapps.io" && + !value.endsWith(".azurecontainerapps.io") + ) +} + +function parsePublicShare(value: Record): PublicShareChoice { + const invalid = () => new Error("Invalid public sharing settings in installation configuration.") + if (Object.keys(value).some((key) => !["reader", "hostname", "allowSharedSite"].includes(key))) + throw invalid() + const { reader, hostname, allowSharedSite } = value + if ( + (reader !== "off" && reader !== "on" && reader !== "removed") || + (hostname !== undefined && (reader === "removed" || !isShareHostname(hostname))) || + (allowSharedSite !== undefined && (allowSharedSite !== true || reader !== "on")) + ) + throw invalid() + return { + reader, + ...(typeof hostname === "string" ? { hostname } : {}), + ...(allowSharedSite ? { allowSharedSite } : {}), + } +} + export async function loadConfig(path: string): Promise { const content = await readPrivateFile(path, { createDirectory: false }) if (content === undefined) diff --git a/infrastructure/installer/index.tsx b/infrastructure/installer/index.tsx index 1cb92feaa..2046196b8 100644 --- a/infrastructure/installer/index.tsx +++ b/infrastructure/installer/index.tsx @@ -33,7 +33,7 @@ if (values.help) { console.log( values.post ? "Usage: npm run setup:post -- [--config FILE] [--no-fullscreen]\nConfigure sign-in/setup access, configure GitHub App, or restart an existing saved Hub.\nInteractive only. Reuses the deployed image; never builds, bootstraps infrastructure, or runs database setup.\nSecret input uses private files, never command-line values. Configuration actions review a scoped Terraform plan; restart targets only the active serving revision." - : "Usage: npm run setup:server -- [--config FILE] [--configure-only] [--no-fullscreen]\nStart by choosing Create, Update, Resume (when available), or Exit before local writes or Azure calls.\nConfig paths are relative to infrastructure/ when using the root shortcut.\nCreate keeps previous files and uses a fresh path; --config FILE uses that path only when unused.\nUpdate/Resume can select local configurations or explicit config-file paths.\nInteractive setup progress is saved in a private companion draft; restart to resume setup.\nCreate and Update ask for private prototype service settings; they stay off unless you turn them on.\nAutomation: --config FILE --non-interactive --approve-deployment\nApproval includes billable resources, role assignments, image publication, temporary provisioning cleanup, and a maintenance-window release.\nAutomation requires a clean source checkout and does not authorize removing state network restrictions; rerun interactively for separate consent.", + : "Usage: npm run setup:server -- [--config FILE] [--configure-only] [--no-fullscreen]\nStart by choosing Create, Update, Resume (when available), or Exit before local writes or Azure calls.\nConfig paths are relative to infrastructure/ when using the root shortcut.\nCreate keeps previous files and uses a fresh path; --config FILE uses that path only when unused.\nUpdate/Resume can select local configurations or explicit config-file paths.\nInteractive setup progress is saved in a private companion draft; restart to resume setup.\nCreate and Update ask for private prototype service settings, and Update asks for public sharing; they stay off unless you turn them on.\nAutomation: --config FILE --non-interactive --approve-deployment\nApproval includes billable resources, role assignments, image publication, temporary provisioning cleanup, and a maintenance-window release.\nAutomation requires a clean source checkout and does not authorize removing state network restrictions; rerun interactively for separate consent.", ) } else { const abort = new AbortController() diff --git a/infrastructure/installer/public-share-choice/index.test.ts b/infrastructure/installer/public-share-choice/index.test.ts new file mode 100644 index 000000000..f5f47b42f --- /dev/null +++ b/infrastructure/installer/public-share-choice/index.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it, vi } from "vitest" + +import type { PublicShareChoice, WizardUI } from "../types.ts" +import { askPublicShare } from "./index.ts" + +const generatedHost = "sample-hub.example.eastus2.azurecontainerapps.io" +const customHost = "replica.coreai.design" + +// Answers each select with the given value, or the first (default) option, and each text in order. +function fakeUI({ selects = [], texts = [] }: { selects?: string[]; texts?: string[] }) { + return { + cloud: vi.fn(async () => "azure" as const), + select: vi.fn(async (_: string, options: { value: string }[]) => selects.shift() ?? options[0]!.value), + text: vi.fn(async (_message: string, initial?: string) => texts.shift() ?? initial ?? ""), + confirm: vi.fn(), + wait: vi.fn(), + status: vi.fn(), + notice: vi.fn(), + } satisfies WizardUI +} + +const overridePrompts = (ui: ReturnType) => + ui.select.mock.calls.filter(([message]) => message.startsWith("Hub uses a generated hostname")) + +describe("askPublicShare", () => { + it("keeps sharing off on a first install without asking", async () => { + const ui = fakeUI({ selects: ["on"] }) + + await expect(askPublicShare(ui, undefined, { firstInstall: true, hubHost: customHost })).resolves.toEqual({ reader: "off" }) + expect(ui.select).not.toHaveBeenCalled() + expect(ui.text).not.toHaveBeenCalled() + }) + + it("turns sharing on for a Hub on a custom domain without offering the shared-site override", async () => { + const ui = fakeUI({ selects: ["on"], texts: ["share.example.net"] }) + + await expect(askPublicShare(ui, undefined, { hubHost: customHost })).resolves.toEqual({ + reader: "on", + hostname: "share.example.net", + }) + expect(overridePrompts(ui)).toEqual([]) + }) + + it("keeps sharing off for a Hub on its generated hostname unless the operator selects the override", async () => { + const ui = fakeUI({ selects: ["on"] }) + + await expect(askPublicShare(ui, undefined, { hubHost: generatedHost })).resolves.toEqual({ reader: "off" }) + expect(ui.notice).toHaveBeenCalledWith("warning", expect.stringMatching(/non-production/)) + expect(overridePrompts(ui)).toHaveLength(1) + }) + + it("records the non-production override when the operator accepts it for a generated Hub", async () => { + const ui = fakeUI({ selects: ["on", "accept"] }) + + await expect(askPublicShare(ui, undefined, { hubHost: generatedHost })).resolves.toEqual({ + reader: "on", + allowSharedSite: true, + }) + }) + + it("offers the saved choice first so an unchanged re-run keeps it", async () => { + const saved: PublicShareChoice = { reader: "on", hostname: "share.example.net", allowSharedSite: true } + const ui = fakeUI({}) + + await expect(askPublicShare(ui, saved, { hubHost: generatedHost })).resolves.toEqual(saved) + }) + + it("asks again for a hostname under azurecontainerapps.io", async () => { + const ui = fakeUI({ selects: ["on"], texts: ["share.eastus2.azurecontainerapps.io", "share.example.net"] }) + + await expect(askPublicShare(ui, undefined, { hubHost: customHost })).resolves.toEqual({ + reader: "on", + hostname: "share.example.net", + }) + expect(ui.notice).toHaveBeenCalledWith("error", expect.any(String)) + }) + + it("removes the reader without asking for a hostname or the override", async () => { + const ui = fakeUI({ selects: ["removed"] }) + const saved: PublicShareChoice = { reader: "on", hostname: "share.example.net", allowSharedSite: true } + + await expect(askPublicShare(ui, saved, { hubHost: generatedHost })).resolves.toEqual({ reader: "removed" }) + expect(ui.text).not.toHaveBeenCalled() + expect(overridePrompts(ui)).toEqual([]) + }) +}) diff --git a/infrastructure/installer/public-share-choice/index.ts b/infrastructure/installer/public-share-choice/index.ts new file mode 100644 index 000000000..48e18bdb6 --- /dev/null +++ b/infrastructure/installer/public-share-choice/index.ts @@ -0,0 +1,58 @@ +import { isShareHostname } from "../config/index.ts" +import type { PublicShareChoice, WizardUI } from "../types.ts" + +const readerOptions = [ + { label: "Off: no public share reader or links (default). Existing exports are kept.", value: "off" }, + { label: "On: run the public share reader and let Hub create public links", value: "on" }, + { label: "Remove: delete the reader app and its grants. Export storage and data are kept.", value: "removed" }, +] as const + +const sharedSiteWarning = + "Hub uses its generated Container Apps hostname. Browsers treat every azurecontainerapps.io hostname as one site, so shared prototypes, which anyone can publish, would be same-site with Hub. Hub's host-only cookies and exact-origin checks still apply. Accept this only for a non-production installation, such as Staging; production installations must give Hub a custom domain first." + +export async function askPublicShare( + ui: WizardUI, + saved: PublicShareChoice | undefined, + { firstInstall = false, hubHost }: { firstInstall?: boolean; hubHost?: string } = {}, +): Promise { + // Hub's hostname, which decides whether sharing is allowed, exists only after the first release. + if (firstInstall) { + ui.status("Public sharing stays off on a new installation. After the first release, run Update to turn it on.") + return { reader: "off" } + } + const current = saved?.reader ?? "off" + const reader = (await ui.select( + "Public sharing. Off is the default; turning it on lets signed-in users give anyone a link to a Build.", + [...readerOptions].sort((left, right) => Number(right.value === current) - Number(left.value === current)), + )) as PublicShareChoice["reader"] + if (!readerOptions.some(({ value }) => value === reader)) + throw new Error("Choose a supported public sharing setting.") + if (reader === "removed") return { reader } + if (reader === "off") return { reader, ...(saved?.hostname ? { hostname: saved.hostname } : {}) } + let value = saved?.hostname ?? "" + let hostname: string | undefined + while (true) { + value = (await ui.text( + "Optional custom domain for public links, outside Hub's registered domain, such as share.example.net. Leave blank to use the reader's generated hostname.", + value, + )).trim() + if (!value || isShareHostname(value)) { + hostname = value || undefined + break + } + ui.notice?.("error", "Enter one lowercase hostname outside azurecontainerapps.io, without a scheme, path, port, or wildcard.") + } + const choice: PublicShareChoice = { reader, ...(hostname ? { hostname } : {}) } + if (!hubHost?.endsWith(".azurecontainerapps.io")) return choice + ui.notice?.("warning", sharedSiteWarning) + const options = [ + { label: "Keep public sharing off until Hub has a custom domain", value: "off" }, + { label: "This is a non-production installation: accept the shared-site risk and turn sharing on", value: "accept" }, + ] + if (saved?.allowSharedSite) options.reverse() + const accept = + (await ui.select("Hub uses a generated hostname. How should public sharing continue?", options)) === "accept" + return accept + ? { ...choice, allowSharedSite: true } + : { reader: "off", ...(hostname ? { hostname } : {}) } +} diff --git a/infrastructure/installer/types.ts b/infrastructure/installer/types.ts index 2388cfdec..51936b4b7 100644 --- a/infrastructure/installer/types.ts +++ b/infrastructure/installer/types.ts @@ -6,6 +6,16 @@ export interface PrivatePreviewChoice { writerRepositoryIds: string[] } +export interface PublicShareChoice { + // off keeps any existing reader disabled without ingress; removed deletes it and its grants. + // Neither deletes the export storage or its data. + reader: "off" | "on" | "removed" + // Optional custom domain; links on the generated hostname keep working. + hostname?: string + // Non-production only: accept sharing while Hub uses a generated hostname. + allowSharedSite?: true +} + export interface DeploymentConfig { version: 1 cloud: "azure" @@ -13,6 +23,7 @@ export interface DeploymentConfig { owner: string npmRegistry?: string privatePreview?: PrivatePreviewChoice + publicShare?: PublicShareChoice azure: { subscriptionId: string tenantId: string diff --git a/infrastructure/installer/wizard/index.ts b/infrastructure/installer/wizard/index.ts index 89698efb3..55b7330ef 100644 --- a/infrastructure/installer/wizard/index.ts +++ b/infrastructure/installer/wizard/index.ts @@ -10,8 +10,14 @@ import { installationWorkspace } from "../workspace/index.ts" import { readInstallationInputs } from "../../azure/install/inputs/index.ts" import { checkPrivatePreviewChoice, + hubOrigin, PrivatePreviewChoiceError, } from "../../azure/install/private-preview/hub-environment/index.ts" +import { + checkPublicShareChoice, + PublicShareChoiceError, +} from "../../azure/install/public-share/hub-environment/index.ts" +import { askPublicShare } from "../public-share-choice/index.ts" export async function runWizard({ ui, @@ -123,6 +129,7 @@ export async function runWizard({ } // Resuming a started deployment keeps the saved choice instead of changing its target. let privatePreview = existing?.privatePreview + let publicShare = existing?.publicShare if (!(entryAction === "resume" && existing)) { const inputs = await readInstallationInputs(installationWorkspace(config, directory), config) // Ask again until the choice fits Hub's saved settings, so a saved choice never blocks Resume. @@ -136,6 +143,18 @@ export async function runWizard({ ui.notice?.("error", error.message) } } + const origin = hubOrigin(inputs) + const hubHost = origin ? new URL(origin).hostname : undefined + while (true) { + publicShare = await askPublicShare(ui, publicShare, { firstInstall: !existing, ...(hubHost && { hubHost }) }) + try { + checkPublicShareChoice(publicShare, inputs, existing?.publicShare) + break + } catch (error) { + if (!(error instanceof PublicShareChoiceError)) throw error + ui.notice?.("error", error.message) + } + } } // The default needs no saved setting, so earlier configurations stay unchanged. if ( @@ -143,6 +162,8 @@ export async function runWizard({ (existing?.privatePreview || privatePreview.reader !== "off" || privatePreview.writerRepositoryIds.length) ) config.privatePreview = privatePreview + if (publicShare && (existing?.publicShare || publicShare.reader !== "off" || publicShare.hostname)) + config.publicShare = publicShare await ui.phase?.("review") const save = async (next: DeploymentConfig, previous?: DeploymentConfig) => checkpoint(async () => { diff --git a/infrastructure/installer/wizard/public-share-settings.test.ts b/infrastructure/installer/wizard/public-share-settings.test.ts new file mode 100644 index 000000000..c3e17637d --- /dev/null +++ b/infrastructure/installer/wizard/public-share-settings.test.ts @@ -0,0 +1,204 @@ +import { randomUUID } from "node:crypto" +import { mkdir, readFile, rm, writeFile } from "node:fs/promises" +import { join, resolve } from "node:path" +import { afterEach, expect, it, vi } from "vitest" + +import * as azureConfiguration from "../../azure/install/configure/index.ts" +import * as azureInstaller from "../../azure/install/index.ts" +import type { DeploymentResult } from "../../azure/install/types.ts" +import { saveConfig } from "../config/index.ts" +import { openSession } from "../session/index.ts" +import { installationWorkspace } from "../workspace/index.ts" +import type { DeploymentConfig, PublicShareChoice, RunCommand, WizardUI } from "../types.ts" +import { runWizard } from "./index.ts" + +const directories: string[] = [] +const sessions: Awaited>[] = [] + +afterEach(async () => { + vi.restoreAllMocks() + await Promise.all(sessions.splice(0).map((session) => session.close())) + await Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true, force: true }))) +}) + +const target: DeploymentConfig = { + version: 1, + cloud: "azure", + name: "test-hub", + owner: "test-team", + azure: { + subscriptionId: "00000000-0000-0000-0000-000000000001", + tenantId: "00000000-0000-0000-0000-000000000002", + location: "eastus2", + resourceGroup: "test-hub-rg", + }, +} +const sharePrompt = "Public sharing" +const domainPrompt = "Optional custom domain for public links" +const overridePrompt = "Hub uses a generated hostname" + +async function fixture({ + publicShare, + answers = {}, + saved: savedConfig = true, + hubOrigin = "https://replica.coreai.design", +}: { + publicShare?: PublicShareChoice + // Answers for prompts starting with each key, in order; other prompts take their default. + answers?: Record + saved?: boolean + hubOrigin?: string | null +}) { + const directory = resolve(`.installer-wizard-share-test-${randomUUID()}`) + directories.push(directory) + await mkdir(directory, { mode: 0o700 }) + const path = join(directory, "installation.json") + const existing: DeploymentConfig = { ...target, ...(publicShare && { publicShare }) } + if (savedConfig) await saveConfig(path, existing, { exclusive: true }) + if (hubOrigin) { + const vaultReference = (secret: string) => ({ + key_vault_id: `/subscriptions/${target.azure.subscriptionId}/resourceGroups/test-hub-foundation/providers/Microsoft.KeyVault/vaults/testvault`, + secret_id: `https://testvault.vault.azure.net/secrets/${secret}/${"a".repeat(32)}`, + }) + // Hub's settings, saved by post-setup in the installation workspace that installAzure reads. + const workspace = installationWorkspace(target, directory) + await mkdir(workspace, { mode: 0o700 }) + await writeFile( + join(workspace, "installation.tfvars.json"), + JSON.stringify({ + subscription_id: target.azure.subscriptionId, + name: target.name, + owner: target.owner, + location: target.azure.location, + resource_group_name: target.azure.resourceGroup, + hub_application_origin: hubOrigin, + runtime_environment_variables: { HUB_TRUSTED_PROXY_HOPS: "1", HUB_LOCAL_SIGN_IN: "true" }, + setup_database_secret: vaultReference("setup-database"), + runtime_secret_references: { + HUB_AUTHENTICATION_ENCRYPTION_KEY: vaultReference("hub-authentication-encryption-key"), + HUB_BOOTSTRAP_SECRET: vaultReference("hub-bootstrap-secret"), + }, + }), + { mode: 0o600 }, + ) + } + vi.spyOn(azureConfiguration, "configureAzure").mockResolvedValue(structuredClone(target)) + const group = `/subscriptions/${target.azure.subscriptionId}/resourceGroups/${target.azure.resourceGroup}` + const result: DeploymentResult = { + name: target.name, + subscriptionId: target.azure.subscriptionId, + tenantId: target.azure.tenantId, + location: target.azure.location, + url: "https://hub.example.com", + image: `testhubregistry.azurecr.io/replica-hub@sha256:${"a".repeat(64)}`, + resources: { + resourceGroup: group, + app: `${group}/providers/Microsoft.App/containerApps/test-hub`, + environment: `${group}/providers/Microsoft.App/managedEnvironments/test-hub`, + database: `${group}/providers/Microsoft.DBforPostgreSQL/flexibleServers/test-hub`, + storage: `${group}/providers/Microsoft.Storage/storageAccounts/testhub`, + registry: `${group}/providers/Microsoft.ContainerRegistry/registries/testhubregistry`, + vault: `${group}/providers/Microsoft.KeyVault/vaults/testvault`, + stateStorage: `${group}/providers/Microsoft.Storage/storageAccounts/teststate`, + }, + } + const install = vi.spyOn(azureInstaller, "installAzure").mockResolvedValue(result) + // A wizard that keeps asking would otherwise loop forever on the default answers. + let prompts = 0 + const answer = (message: string) => { + if (++prompts > 20) throw new Error("The wizard kept asking the same questions.") + const key = Object.keys(answers).find((prefix) => message.startsWith(prefix) && answers[prefix]!.length) + return key ? answers[key]!.shift() : undefined + } + const ui = { + cloud: vi.fn(async () => "azure" as const), + select: vi.fn(async (message: string, options: { value: string }[]) => answer(message) ?? options[0]!.value), + text: vi.fn(async (message: string, initial?: string) => answer(message) ?? initial ?? ""), + confirm: vi.fn(async () => true), + wait: vi.fn(), + status: vi.fn(), + notice: vi.fn(), + } satisfies WizardUI + const run = vi.fn(async (executable, args) => { + throw new Error(`Unexpected command ${executable} ${args.join(" ")}`) + }) + const saved = async () => JSON.parse(await readFile(path, "utf8")) as Record + const prompted = (prefix: string) => ui.select.mock.calls.filter(([message]) => message.startsWith(prefix)) + return { options: { directory, path, run, ui, ...(savedConfig && { existing }) }, path, install, ui, saved, prompted } +} + +it("keeps public sharing off on Create without asking or saving a choice", async () => { + const { options, install, saved, prompted } = await fixture({ saved: false, hubOrigin: null }) + + await runWizard({ ...options, entryAction: "create" }) + + expect(prompted(sharePrompt)).toEqual([]) + expect(await saved()).not.toHaveProperty("publicShare") + expect(install.mock.calls[0]![0]).not.toHaveProperty("publicShare") +}) + +it("leaves an earlier configuration without a public sharing choice when Update keeps the default", async () => { + const { options, install, saved, prompted } = await fixture({}) + + await runWizard({ ...options, entryAction: "update" }) + + expect(prompted(sharePrompt)).toHaveLength(1) + expect(await saved()).not.toHaveProperty("publicShare") + expect(install.mock.calls[0]![0]).not.toHaveProperty("publicShare") +}) + +it("saves sharing turned on during Update for a Hub on a custom domain and deploys with it", async () => { + const { options, install, saved, prompted } = await fixture({ + answers: { [sharePrompt]: ["on"], [domainPrompt]: ["share.example.net"] }, + }) + const choice = { reader: "on", hostname: "share.example.net" } + + await runWizard({ ...options, entryAction: "update" }) + + expect(prompted(overridePrompt)).toEqual([]) + expect((await saved()).publicShare).toEqual(choice) + expect(install.mock.calls[0]![0].publicShare).toEqual(choice) +}) + +it("saves the non-production override only when the operator selects it for a Hub on its generated hostname", async () => { + const { options, install, saved } = await fixture({ + hubOrigin: "https://test-hub.example.eastus2.azurecontainerapps.io", + answers: { [sharePrompt]: ["on"], [overridePrompt]: ["accept"] }, + }) + const choice = { reader: "on", allowSharedSite: true } + + await runWizard({ ...options, entryAction: "update" }) + + expect((await saved()).publicShare).toEqual(choice) + expect(install.mock.calls[0]![0].publicShare).toEqual(choice) +}) + +it("asks again when the share domain may be the same site as Hub, then deploys only the valid choice", async () => { + const { options, install, ui, saved, prompted } = await fixture({ + answers: { [sharePrompt]: ["on", "on"], [domainPrompt]: ["share.coreai.design", "share.example.net"] }, + }) + + await runWizard({ ...options, entryAction: "update" }) + + expect(prompted(sharePrompt)).toHaveLength(2) + expect(ui.notice).toHaveBeenCalledWith("error", expect.stringMatching(/^Public sharing blocked: .*same site/)) + expect(ui.notice.mock.invocationCallOrder[0]).toBeLessThan(install.mock.invocationCallOrder[0]!) + expect((await saved()).publicShare).toEqual({ reader: "on", hostname: "share.example.net" }) + expect(install).toHaveBeenCalledOnce() +}) + +it("resumes an interrupted deployment with the saved sharing choice without asking again", async () => { + const publicShare: PublicShareChoice = { reader: "on", hostname: "share.example.net" } + const { options, path, install, saved, prompted } = await fixture({ publicShare }) + const draft = await openSession(path) + await draft.phase("release") + await draft.close() + const session = await openSession(path) + sessions.push(session) + + await runWizard({ ...options, session, entryAction: "resume" }) + + expect(prompted(sharePrompt)).toEqual([]) + expect((await saved()).publicShare).toEqual(publicShare) + expect(install.mock.calls[0]![0].publicShare).toEqual(publicShare) +}) diff --git a/scripts/check-ci-workflows/index.ts b/scripts/check-ci-workflows/index.ts index c5c150354..8f85322db 100644 --- a/scripts/check-ci-workflows/index.ts +++ b/scripts/check-ci-workflows/index.ts @@ -252,6 +252,15 @@ export function checkWorkflows(root: string): void { names.indexOf("Keep the private prototype service") < names.indexOf("Run the serialized maintenance-window release"), "Deployment must keep the private prototype service settings and image before the release", ) + const share = deploy.steps?.find((step) => step.name === "Keep public sharing") + assert( + share?.run?.includes("node infrastructure/azure/deploy-hub/public-share/index.ts") && + share.run.includes('--image "$HUB_IMAGE"') && + share.env?.HUB_IMAGE === "${{ steps.image.outputs.reference }}" && + names.indexOf("Keep the private prototype service") < names.indexOf("Keep public sharing") && + names.indexOf("Keep public sharing") < names.indexOf("Run the serialized maintenance-window release"), + "Deployment must keep the public sharing settings and image before the release", + ) const release = deploy.steps?.find( (step) => step.name === "Run the serialized maintenance-window release", ) From f6dac1cdfd43ece7756e570ed6b8b51e0f9b603e Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:48:51 -0800 Subject: [PATCH 2/2] fix(infrastructure): require GitHub sign-in and skip empty share state Public sharing now needs complete GitHub sign-in, matching Hub's startup check. Off or Remove after an On that stopped before creating anything no longer creates the export storage from empty saved state. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- hub/docs/deployment.md | 2 +- infrastructure/README.md | 6 +- infrastructure/azure/install/index.test.ts | 16 ++++- .../private-preview/hub-environment/index.ts | 9 ++- .../hub-environment/index.test.ts | 15 ++++- .../public-share/hub-environment/index.ts | 11 +++- .../azure/install/public-share/index.test.ts | 65 ++++++++++++++++++- .../azure/install/public-share/index.ts | 6 +- .../install/public-share/settings/index.ts | 7 ++ .../wizard/public-share-settings.test.ts | 10 ++- 10 files changed, 131 insertions(+), 16 deletions(-) diff --git a/hub/docs/deployment.md b/hub/docs/deployment.md index 2ac17196e..eb5c3e8d0 100644 --- a/hub/docs/deployment.md +++ b/hub/docs/deployment.md @@ -60,7 +60,7 @@ The Azure entrypoint also supports the scoped [GitHub author repair and webhook ### Public share reader -The same image runs the read-only [public share reader](public-share-reader.md) with `node dist/server/scripts/start-public-share-reader/index.js`. It is a separate deployment with its own settings and identity; never give it Hub's settings, which stop it at startup. The Azure installation runs it as an optional component, off by default, in its own Container Apps environment with a separate export storage account. Turning [public sharing](../../infrastructure/README.md#public-sharing) on with setup Update also sets Hub's `HUB_PUBLIC_SHARE_ENABLED`, `HUB_PUBLIC_SHARE_ORIGIN`, `HUB_PUBLIC_SHARE_STORAGE_ACCOUNT` and `HUB_PUBLIC_SHARE_STORAGE_CONTAINER`, plus `HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE=true` only for a non-production installation that accepts the shared-site override. Hub uses its existing managed identity for the export container. Setup Update owns these settings; do not set them by hand or through the release workflow's runtime JSON. +The same image runs the read-only [public share reader](public-share-reader.md) with `node dist/server/scripts/start-public-share-reader/index.js`. It is a separate deployment with its own settings and identity; never give it Hub's settings, which stop it at startup. The Azure installation runs it as an optional component, off by default, in its own Container Apps environment with a separate export storage account. Turning [public sharing](../../infrastructure/README.md#public-sharing) on with setup Update also sets Hub's `HUB_PUBLIC_SHARE_ENABLED`, `HUB_PUBLIC_SHARE_ORIGIN`, `HUB_PUBLIC_SHARE_STORAGE_ACCOUNT` and `HUB_PUBLIC_SHARE_STORAGE_CONTAINER`, plus `HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE=true` only for a non-production installation that accepts the shared-site override. Hub uses its existing managed identity for the export container. Sharing also needs complete GitHub sign-in, which setup Update checks before turning it on. Setup Update owns these settings; do not set them by hand or through the release workflow's runtime JSON. ## Setup before release diff --git a/infrastructure/README.md b/infrastructure/README.md index 32cc82418..d58b5c01d 100644 --- a/infrastructure/README.md +++ b/infrastructure/README.md @@ -295,8 +295,8 @@ The wizard sets these Hub settings itself and replaces manual values: `HUB_PRIVA Public sharing lets signed-in Hub users give anyone a link to one Build. Hub copies the Build into a separate export storage, and a separate read-only reader serves the copy. [ADR 0003](../docs/adr/0003-public-sharing-export-reader.md) is the design and the [public share reader guide](../hub/docs/public-share-reader.md) describes the reader. Update asks for this setting after the private prototype service. Create keeps it off, because the choice depends on Hub's hostname, which exists only after the first release. -- **Off** (default). Hub has no public sharing settings and the reader has no ingress. A configuration that never turned sharing on creates nothing, and no Terraform runs for it. After sharing has been on, Off keeps the reader as a placeholder without ingress, removes Hub's export grant, and keeps the export storage and every copied export. -- **On.** Creates or updates the export storage, the reader and its grants, and Hub's export grant, then releases Hub with the sharing settings below. +- **Off** (default). Hub has no public sharing settings and the reader has no ingress. A configuration that never turned sharing on creates nothing, and no Terraform runs for it, including after an attempt to turn it on stopped before creating anything. After sharing has been on, Off keeps the reader as a placeholder without ingress, removes Hub's export grant, and keeps the export storage and every copied export. +- **On.** Creates or updates the export storage, the reader and its grants, and Hub's export grant, then releases Hub with the sharing settings below. Turning sharing on needs Hub's `HUB_APPLICATION_ORIGIN` and complete GitHub sign-in from [post-setup](#post-setup-configuration), because Hub refuses to share without them; local administrator sign-in alone is not enough. The installation always configures Hub's artifact storage. Update checks the choice against Hub's saved settings before saving it or changing Azure, and asks again if it doesn't fit. - **Remove** is the rollback. It deletes the reader app, its custom hostname, every reader grant and Hub's export grant, and turns sharing off in Hub. It keeps the export storage account, container and data, and the reader's resource group, environment and identity. Non-default choices are saved in the installation configuration as `publicShare`, for example `{ "reader": "on" }`. Non-interactive Update applies the saved choice. Rerunning Update with the same choice changes nothing except the image that Hub and the reader run. @@ -329,7 +329,7 @@ The reader gets only its own settings: `PUBLIC_SHARE_GENERATED_ORIGIN`, `PUBLIC_ **Turn sharing on in Staging.** After this change and the Hub change that reads these settings are released to Staging: -1. Run `npm run setup:server`, choose **Update**, and select Staging's configuration. +1. Confirm Staging's saved inputs have complete GitHub sign-in and `HUB_APPLICATION_ORIGIN`. Run `npm run setup:server`, choose **Update**, and select Staging's configuration. 2. Choose **Public sharing: On** and leave the custom domain blank. Staging's Hub uses its generated hostname, so Update shows the shared-site warning; select the non-production option. 3. Review and approve the deployment. Update creates the `-share` resources, waits for the reader, releases Hub with the sharing settings, and prints the link origin. diff --git a/infrastructure/azure/install/index.test.ts b/infrastructure/azure/install/index.test.ts index 4acbbd4fc..9b6b8eb1a 100644 --- a/infrastructure/azure/install/index.test.ts +++ b/infrastructure/azure/install/index.test.ts @@ -1777,9 +1777,23 @@ it("blocks a saved shared-site override for a Hub on a custom domain before appr const s = await scenario() await withSignIn(s) const filename = join(installationWorkspace(s.config, s.directory), "installation.tfvars.json") + const saved = JSON.parse(await readFile(filename, "utf8")) + const vault = `/subscriptions/${s.config.azure.subscriptionId}/resourceGroups/secrets/providers/Microsoft.KeyVault/vaults/service` + const secret = (name: string) => ({ key_vault_id: vault, secret_id: `https://service.vault.azure.net/secrets/${name}` }) + // Complete GitHub sign-in, so only the override can block sharing. await writeFile(filename, JSON.stringify({ - ...JSON.parse(await readFile(filename, "utf8")), + ...saved, hub_application_origin: "https://replica.coreai.design", + github_app_id: "123", + github_client_id: "Iv23synthetic", + github_app_installation_id: "456", + github_provider_revision: 1, + runtime_secret_references: { + ...saved.runtime_secret_references, + GITHUB_APP_PRIVATE_KEY_BASE64: secret("github-app-private-key"), + GITHUB_WEBHOOK_SECRET: secret("github-webhook-secret"), + GITHUB_CLIENT_SECRET: secret("github-client-secret"), + }, }), { mode: 0o600 }) delete s.config.privatePreview s.config.publicShare = { reader: "on", allowSharedSite: true } diff --git a/infrastructure/azure/install/private-preview/hub-environment/index.ts b/infrastructure/azure/install/private-preview/hub-environment/index.ts index 3f9d342f0..2c0fe6290 100644 --- a/infrastructure/azure/install/private-preview/hub-environment/index.ts +++ b/infrastructure/azure/install/private-preview/hub-environment/index.ts @@ -83,7 +83,8 @@ const githubSignIn = [ "GITHUB_PROVIDER_REVISION", ] as const -function signInConfigured(inputs: HubPreviewInputs) { +// Every GitHub App and sign-in setting is supplied, directly or as a Key Vault reference. +export function githubSignInConfigured(inputs: HubPreviewInputs) { const named: Record = { GITHUB_APP_ID: inputs.github_app_id, GITHUB_CLIENT_ID: inputs.github_client_id, @@ -94,8 +95,12 @@ function signInConfigured(inputs: HubPreviewInputs) { named[name] != null || Boolean(inputs.runtime_environment_variables?.[name]?.trim()) || name in (inputs.runtime_secret_references ?? {}) + return githubSignIn.every(supplied) +} + +function signInConfigured(inputs: HubPreviewInputs) { return ( - githubSignIn.every(supplied) || + githubSignInConfigured(inputs) || inputs.runtime_environment_variables?.HUB_LOCAL_SIGN_IN?.trim() === "true" || "HUB_LOCAL_SIGN_IN" in (inputs.runtime_secret_references ?? {}) ) diff --git a/infrastructure/azure/install/public-share/hub-environment/index.test.ts b/infrastructure/azure/install/public-share/hub-environment/index.test.ts index 8dc81d1e7..89f84c39a 100644 --- a/infrastructure/azure/install/public-share/hub-environment/index.test.ts +++ b/infrastructure/azure/install/public-share/hub-environment/index.test.ts @@ -3,9 +3,22 @@ import { describe, expect, it } from "vitest" import type { PublicShareChoice } from "../../../../installer/types.ts" import { checkPublicShareChoice, hubShareInputs, PublicShareChoiceError } from "./index.ts" +const githubSecret = (name: string) => ({ + key_vault_id: "/subscriptions/sample/resourceGroups/sample/providers/Microsoft.KeyVault/vaults/sample", + secret_id: `https://sample.vault.azure.net/secrets/${name}/1`, +}) const customHub = { hub_application_origin: "https://replica.coreai.design", + github_app_id: "123", + github_client_id: "Iv23synthetic", + github_app_installation_id: "456", + github_provider_revision: 1, runtime_environment_variables: { HUB_TRUSTED_PROXY_HOPS: "1" }, + runtime_secret_references: { + GITHUB_APP_PRIVATE_KEY_BASE64: githubSecret("github-app-private-key"), + GITHUB_WEBHOOK_SECRET: githubSecret("github-webhook-secret"), + GITHUB_CLIENT_SECRET: githubSecret("github-client-secret"), + }, } const generatedHub = { ...customHub, hub_application_origin: "https://sample-hub.example.eastus2.azurecontainerapps.io" } const share = { @@ -40,7 +53,7 @@ describe("hubShareInputs", () => { }) it("blocks a wizard-owned share setting saved as a Key Vault reference", () => { - const inputs = { ...customHub, runtime_secret_references: { HUB_PUBLIC_SHARE_ORIGIN: reference } } + const inputs = { ...customHub, runtime_secret_references: { ...customHub.runtime_secret_references, HUB_PUBLIC_SHARE_ORIGIN: reference } } expect(() => hubShareInputs(inputs)).toThrow(/Key Vault references for HUB_PUBLIC_SHARE_ORIGIN/) }) diff --git a/infrastructure/azure/install/public-share/hub-environment/index.ts b/infrastructure/azure/install/public-share/hub-environment/index.ts index ab80a4fb4..e35a27e8c 100644 --- a/infrastructure/azure/install/public-share/hub-environment/index.ts +++ b/infrastructure/azure/install/public-share/hub-environment/index.ts @@ -1,5 +1,9 @@ import type { PublicShareChoice } from "../../../../installer/types.ts" -import { hubOrigin, type HubPreviewInputs } from "../../private-preview/hub-environment/index.ts" +import { + githubSignInConfigured, + hubOrigin, + type HubPreviewInputs, +} from "../../private-preview/hub-environment/index.ts" // The wizard owns these Hub settings; manual values are replaced on every deployment. export const ownedHubShareSettings = [ @@ -74,10 +78,11 @@ export function checkPublicShareChoice( } rejectOwnedReferences(inputs, block) if (choice?.reader !== "on") return + // The installation always configures Hub's artifact storage; sharing also needs GitHub sign-in. const origin = hubOrigin(inputs) - if (!origin) + if (!origin || !githubSignInConfigured(inputs)) block( - "turning on public sharing needs Hub's origin, HUB_APPLICATION_ORIGIN. Choose Off, run npm run setup:post to configure sign-in, then run Update and choose On.", + "turning on public sharing needs Hub's origin, HUB_APPLICATION_ORIGIN, and complete GitHub sign-in. Choose Off, run npm run setup:post to configure sign-in and the GitHub App, then run Update and choose On.", ) const hubHost = new URL(origin!).hostname if (isGeneratedHost(hubHost) && !choice.allowSharedSite) diff --git a/infrastructure/azure/install/public-share/index.test.ts b/infrastructure/azure/install/public-share/index.test.ts index 1eedae780..b4f7a1d4a 100644 --- a/infrastructure/azure/install/public-share/index.test.ts +++ b/infrastructure/azure/install/public-share/index.test.ts @@ -48,8 +48,25 @@ const exportAccountId = `/subscriptions/${subscriptionId}/resourceGroups/sample- const containerId = `${exportAccountId}/blobServices/default/containers/public-share-exports` const registryId = `/subscriptions/${subscriptionId}/resourceGroups/sample-hub-foundation/providers/Microsoft.ContainerRegistry/registries/sample` const vaultId = `/subscriptions/${subscriptionId}/resourceGroups/sample-hub-foundation/providers/Microsoft.KeyVault/vaults/samplevault` +const githubSecret = (name: string) => ({ + key_vault_id: vaultId, + secret_id: `https://samplevault.vault.azure.net/secrets/${name}/1`, +}) +// Sharing needs complete GitHub sign-in; local administrator sign-in alone is not enough. +const githubSignIn = { + github_app_id: "123", + github_client_id: "Iv23synthetic", + github_app_installation_id: "456", + github_provider_revision: 1, + runtime_secret_references: { + GITHUB_APP_PRIVATE_KEY_BASE64: githubSecret("github-app-private-key"), + GITHUB_WEBHOOK_SECRET: githubSecret("github-webhook-secret"), + GITHUB_CLIENT_SECRET: githubSecret("github-client-secret"), + }, +} const customHub = { hub_application_origin: "https://replica.coreai.design", + ...githubSignIn, runtime_environment_variables: { HUB_TRUSTED_PROXY_HOPS: "1", HUB_LOCAL_SIGN_IN: "true" }, } const generatedHub = { ...customHub, hub_application_origin: "https://sample-hub.example.eastus2.azurecontainerapps.io" } @@ -70,9 +87,17 @@ const dnsReady: DnsResolver = { txt: async () => [["VERIFY123"]], } -function stateSnapshot(current: Current | undefined) { +function stateSnapshot(current: Current | undefined, emptyState: boolean) { if (!current) return { format_version: "1.0" } - const resources: unknown[] = [] + if (emptyState) return { format_version: "1.0", values: { root_module: {} } } + // Export storage, environment, identity and group survive every mode. + const resources: unknown[] = [ + "azurerm_resource_group.share", + "azurerm_storage_account.exports", + "azurerm_storage_container.exports", + "azurerm_container_app_environment.share", + "azurerm_user_assigned_identity.reader", + ].map((address) => ({ address, values: {} })) if (current.reader !== "absent") resources.push({ address: "azurerm_container_app.reader[0]", @@ -97,6 +122,7 @@ async function fixture({ choice, current, orphaned = false, + emptyState = false, unexpectedReaderGrant = false, unmanagedHubGrant = false, readyAfterChecks = 1, @@ -110,6 +136,8 @@ async function fixture({ current?: Current // The share group exists without saved state. orphaned?: boolean + // Saved state exists but records no resources, as after an On that failed once state was seeded. + emptyState?: boolean unexpectedReaderGrant?: boolean // Hub can reach the export container through a grant the wizard does not manage. unmanagedHubGrant?: boolean @@ -150,7 +178,7 @@ async function fixture({ fake.terraform = ({ beforeApply }) => ({ init: inits, rawState: async () => JSON.parse(blob!), - stateSnapshot: async () => stateSnapshot(current), + stateSnapshot: async () => stateSnapshot(current, emptyState), async output() { const enabled = live.reader === "enabled" return { @@ -282,6 +310,17 @@ describe("preparePublicShare", () => { expect(uploads()).toEqual([]) }) + it("creates nothing for Off when saved state exists but records no resources", async () => { + const { prepare, applied, leases } = await fixture({ choice: { reader: "off" }, current: { reader: "absent" }, emptyState: true }) + + const prepared = await prepare(sharingHub) + await prepared.finish() + + expect(applied).toEqual([]) + expect(leases).toEqual([]) + expect(prepared.inputs).toEqual(customHub) + }) + it.each([ ["sharing stays off", undefined], ["sharing is turned on", on()], @@ -319,6 +358,26 @@ describe("preparePublicShare", () => { expect(uploads()).toEqual([]) }) + it.each([ + ["only local administrator sign-in", { + hub_application_origin: customHub.hub_application_origin, + runtime_environment_variables: customHub.runtime_environment_variables, + }], + ["the GitHub webhook secret missing", { + ...customHub, + runtime_secret_references: { + GITHUB_APP_PRIVATE_KEY_BASE64: githubSecret("github-app-private-key"), + GITHUB_CLIENT_SECRET: githubSecret("github-client-secret"), + }, + }], + ])("refuses to turn on sharing with %s, before any change", async (_, inputs) => { + const { prepare, inits, uploads } = await fixture({ choice: on() }) + + await expect(prepare(inputs)).rejects.toThrow(/complete GitHub sign-in/) + expect(inits).not.toHaveBeenCalled() + expect(uploads()).toEqual([]) + }) + it("turns on sharing for a Hub on its generated hostname with the non-production override", async () => { const { prepare, applied } = await fixture({ choice: on({ allowSharedSite: true }) }) diff --git a/infrastructure/azure/install/public-share/index.ts b/infrastructure/azure/install/public-share/index.ts index e6bf04b3e..0aa7a2885 100644 --- a/infrastructure/azure/install/public-share/index.ts +++ b/infrastructure/azure/install/public-share/index.ts @@ -27,6 +27,7 @@ import { offShareChoice, readShareState, sameShareVariables, + stateHasResources, targetShareVariables, type ShareVariables, } from "./settings/index.ts" @@ -129,7 +130,10 @@ export async function preparePublicShare( }) await terraform.init(await writeBackendFile(context, "public-share")) guard.verify(await terraform.rawState()) - const current = readShareState(await terraform.stateSnapshot()) + const snapshot = await terraform.stateSnapshot() + if (choice.reader !== "on" && !stateHasResources(snapshot)) + return { inputs: hubShareInputs(inputs), finish: async () => [] } + const current = readShareState(snapshot) const output = () => terraform.output("share") const hubPrincipalId = await read( diff --git a/infrastructure/azure/install/public-share/settings/index.ts b/infrastructure/azure/install/public-share/settings/index.ts index 7dc7e5c85..ae86c7fe5 100644 --- a/infrastructure/azure/install/public-share/settings/index.ts +++ b/infrastructure/azure/install/public-share/settings/index.ts @@ -69,6 +69,13 @@ export function needsShareRoot(choice: PublicShareChoice, stateExists: boolean) return stateExists || choice.reader === "on" } +// An earlier On can stop after seeding empty state; Off or Remove must not create resources then. +export function stateHasResources(snapshot: unknown) { + const resources = (snapshot as { values?: { root_module?: { resources?: unknown } } } | null) + ?.values?.root_module?.resources + return Array.isArray(resources) && resources.length > 0 +} + type StateResource = { address?: unknown; values?: { name?: unknown; ingress?: unknown[] } } // Reads `terraform show -json` of the public-share root. diff --git a/infrastructure/installer/wizard/public-share-settings.test.ts b/infrastructure/installer/wizard/public-share-settings.test.ts index c3e17637d..a3844f16d 100644 --- a/infrastructure/installer/wizard/public-share-settings.test.ts +++ b/infrastructure/installer/wizard/public-share-settings.test.ts @@ -72,11 +72,19 @@ async function fixture({ location: target.azure.location, resource_group_name: target.azure.resourceGroup, hub_application_origin: hubOrigin, - runtime_environment_variables: { HUB_TRUSTED_PROXY_HOPS: "1", HUB_LOCAL_SIGN_IN: "true" }, + // Sharing needs complete GitHub sign-in. + github_app_id: "123", + github_client_id: "Iv23synthetic", + github_app_installation_id: "456", + github_provider_revision: 1, + runtime_environment_variables: { HUB_TRUSTED_PROXY_HOPS: "1" }, setup_database_secret: vaultReference("setup-database"), runtime_secret_references: { HUB_AUTHENTICATION_ENCRYPTION_KEY: vaultReference("hub-authentication-encryption-key"), HUB_BOOTSTRAP_SECRET: vaultReference("hub-bootstrap-secret"), + GITHUB_APP_PRIVATE_KEY_BASE64: vaultReference("github-app-private-key"), + GITHUB_WEBHOOK_SECRET: vaultReference("github-webhook-secret"), + GITHUB_CLIENT_SECRET: vaultReference("github-client-secret"), }, }), { mode: 0o600 },