diff --git a/infrastructure/README.md b/infrastructure/README.md index 397c4929e..2c834e3d3 100644 --- a/infrastructure/README.md +++ b/infrastructure/README.md @@ -448,6 +448,8 @@ Invalid answers stay at their prompt instead of ending post-setup. Earlier accep Private `post-sign-in-progress.json` and `post-github-progress.json` files inside the installation workspace retain validated public answers, validated absolute credential paths and confirmed versioned Key Vault references. They are atomically saved with 0600 permissions and bound to the exact installation, action and saved inputs. No credential text, PEM contents, tokens, rejected input or approval is stored. On relaunch, **Resume saved answers** skips completed prompts after revalidation, except for the stored provider revision and enabled-state verification. Not-yet-uploaded credential files are read and validated again; successfully uploaded credentials are checked through their pinned Key Vault references and do not require the old local file. **Start over with the answers** requires confirmation and clears only prompt answers, never stored secrets, desired inputs or cloud resources. Each successful secret write is checkpointed before the next write. If a write's outcome is unknown, post-setup checks the current stored value first; creating another version requires an explicit choice. Resolve the pending credential before uploading a different one; provide its private file again if needed. +If sign-in setup stops after saving desired inputs but before completing its progress file, it can resume with an unchanged secret-backed origin. New progress files retain reference-only evidence to check that transition, including pinning an unversioned origin or shared authentication reference without changing an existing pinned version. They also bind normalization of the image and `deploy_hub` to the verified deployment image. Unrelated input or reference changes still stop resume and preserve the files for review. Older progress files without the relevant evidence still require review when their input fingerprint changes. + Configuration actions disclose secret writes and downtime, then save desired inputs and a private previous-input backup before applying. They correct an obsolete saved `deploy_hub=false` from bootstrap, retain unrelated runtime settings, and use the exact deployed image instead of the saved build candidate. Unrelated saved and live settings or secret references that disagree block configuration before secret writes or input persistence; reconcile them separately instead of overwriting either side. Each fresh Terraform plan is shown for approval. Only an in-place Hub runtime-environment update and intended secret-scoped `Key Vault Secrets User` grants are allowed; infrastructure drift, replacements, deletions, and image changes block the action. Every plan and replan that creates a role grant must first check Azure. A detected assignment missing from Terraform state, an unsuccessful lookup, or an incomplete, malformed, or ambiguous response blocks that plan before approval, apply, or Hub shutdown; review the reported recovery rather than deleting or automatically adopting a grant. Desired inputs or secret versions saved before planning remain available for recovery. Old Hub replicas are stopped only for an actual app update, before Azure creates the new configured revision. A grant-only or no-change plan does not stop Hub. Readiness and protected setup availability are checked afterward; GitHub configuration also checks that GitHub appears in the provider API. Setup-only mode can legitimately leave the provider API unavailable. These checks do not prove GitHub client-secret correctness, OAuth callback registration, repository permissions or signed webhook delivery: complete the browser connection test and administrator enrollment separately. diff --git a/infrastructure/azure/post/configure/index.ts b/infrastructure/azure/post/configure/index.ts index 3370cb992..37ae36d65 100644 --- a/infrastructure/azure/post/configure/index.ts +++ b/infrastructure/azure/post/configure/index.ts @@ -57,7 +57,12 @@ export async function configurePostSetup( return choice }, } - const progress = await postSetupProgress({ ...context, ui: recoveryUI }, action, inputs) + const progress = await postSetupProgress( + { ...context, ui: recoveryUI }, + action, + inputs, + deployment.image, + ) if (progress.pending || Object.keys(progress.references).length) context.onMutation?.() let resume = false if (progress.hasSaved) { diff --git a/infrastructure/azure/post/index.test.ts b/infrastructure/azure/post/index.test.ts index ac18b1013..1082aa5cb 100644 --- a/infrastructure/azure/post/index.test.ts +++ b/infrastructure/azure/post/index.test.ts @@ -12,6 +12,7 @@ import * as installationInputs from "../install/inputs/index.ts" import { installationNames } from "../install/settings.ts" import type { PostInputs, PostSetupTarget } from "./types.ts" import { postSetupAzure } from "./index.ts" +import { postSetupProgress } from "./progress/index.ts" vi.mock("ink", async (importOriginal) => { const ink = await importOriginal() @@ -593,6 +594,71 @@ it("uses the deployed digest despite stale deploy_hub=false and preserves settin expect(test.leases.size).toBe(0) }) +it.each(["verified", "changed"] as const)( + "resumes a secret-backed sign-in checkpoint only with the %s deployed image", + async (image) => { + const test = await scenario() + const originReference = test.reference("hub-application-origin") + delete test.inputs.hub_application_origin + delete test.state.environment.HUB_APPLICATION_ORIGIN + test.inputs.runtime_secret_references!.HUB_APPLICATION_ORIGIN = originReference + test.secretValues.set("hub-application-origin", test.origin) + test.state.environment.AZURE_KEY_VAULT_SECRET_REFERENCES = JSON.stringify({ + ...JSON.parse(test.state.environment.AZURE_KEY_VAULT_SECRET_REFERENCES!), + HUB_APPLICATION_ORIGIN: originReference.secret_id, + }) + const progress = await postSetupProgress( + { config: test.target.config, directory: test.directory, ui: test.ui }, + "sign-in", + test.inputs, + test.image, + ) + await progress.saveAnswer("origin", test.origin) + await progress.saveAnswer("proxyHops", "2") + const savedProgress = await readFile(progress.path, "utf8") + const desired: PostInputs = { + ...test.inputs, + image: image === "verified" ? test.image : `registry.azurecr.io/hub@sha256:${"c".repeat(64)}`, + deploy_hub: true, + runtime_environment_variables: { + ...test.inputs.runtime_environment_variables, + HUB_TRUSTED_PROXY_HOPS: "2", + }, + } + const content = JSON.stringify(desired) + const journalPath = join(test.directory, "post-desired.json") + const journal = JSON.stringify({ + target: JSON.stringify(test.target.config), + hash: createHash("sha256").update(content).digest("hex"), + phase: "pending", + action: "sign-in", + previousReferences: JSON.parse(test.state.environment.AZURE_KEY_VAULT_SECRET_REFERENCES!), + }) + await writeFile(test.inputsPath, content, { mode: 0o600 }) + await writeFile(journalPath, journal, { mode: 0o600 }) + + const result = postSetupAzure(test.target, { + action: "sign-in", + run: test.run, + ui: test.ui, + request: test.request, + }) + if (image === "changed") { + await expect(result).rejects.toThrow(/inputs changed/i) + expect(await readFile(test.inputsPath, "utf8")).toBe(content) + expect(await readFile(journalPath, "utf8")).toBe(journal) + expect(await readFile(progress.path, "utf8")).toBe(savedProgress) + expect(test.plans).toEqual([]) + } else { + await expect(result).resolves.toContain(`${test.origin}/settings/github/setup`) + expect(JSON.parse(await readFile(test.inputsPath, "utf8"))).toEqual(desired) + expect(test.plans).toHaveLength(1) + expect(test.applies).toBe(1) + expect(test.uploads).toEqual([]) + } + }, +) + it("repairs a stopped Hub with saved authentication secrets but no origin only after a valid answer", async () => { const test = await scenario() delete test.inputs.hub_application_origin diff --git a/infrastructure/azure/post/progress/index.test.ts b/infrastructure/azure/post/progress/index.test.ts index 4a38999b0..04b76267d 100644 --- a/infrastructure/azure/post/progress/index.test.ts +++ b/infrastructure/azure/post/progress/index.test.ts @@ -15,6 +15,7 @@ import { afterEach, expect, it, vi } from "vitest" import type { AzureInstallation } from "../../install/types.ts" import { installationNames } from "../../install/settings.ts" +import type { PostInputs } from "../types.ts" import { postSetupProgress } from "./index.ts" const directories: string[] = [] @@ -47,6 +48,276 @@ async function scenario() { return { context: { directory, config, ui }, reference } } +async function signInScenario(versioned = true) { + const test = await scenario() + const originReference = { + ...test.reference, + secret_id: test.reference.secret_id.replace("github-client-secret", "hub-application-origin"), + } + const sharedReferences = { + HUB_AUTHENTICATION_ENCRYPTION_KEY: { + ...test.reference, + secret_id: test.reference.secret_id.replace("github-client-secret", "hub-encryption-key"), + }, + HUB_BOOTSTRAP_SECRET: { + ...test.reference, + secret_id: test.reference.secret_id.replace("github-client-secret", "hub-bootstrap-secret"), + }, + } + const inputs: PostInputs = { + image: `registry.azurecr.io/hub@sha256:${"a".repeat(64)}`, + deploy_hub: true, + runtime_environment_variables: { RETAINED_SETTING: "keep" }, + runtime_secret_references: { + RETAINED_SECRET: test.reference, + HUB_APPLICATION_ORIGIN: { + ...originReference, + secret_id: versioned ? originReference.secret_id : originReference.secret_id.slice(0, -33), + }, + }, + } + const desired: PostInputs = { + ...inputs, + runtime_environment_variables: { + ...inputs.runtime_environment_variables, + HUB_TRUSTED_PROXY_HOPS: "2", + }, + runtime_secret_references: { + ...inputs.runtime_secret_references, + ...sharedReferences, + HUB_APPLICATION_ORIGIN: originReference, + }, + } + return { ...test, inputs, desired, sharedReferences } +} + +it.each(["pinned", "unversioned"] as const)( + "recognizes saved sign-in configuration after a crash with %s secret-backed origin references", + async (origin) => { + const test = await signInScenario(origin === "pinned") + const progress = await postSetupProgress(test.context, "sign-in", test.inputs) + await progress.saveAnswer("origin", "https://sample.example.com") + await progress.saveAnswer("proxyHops", "2") + for (const [key, reference] of Object.entries(test.sharedReferences)) + await progress.saveReference(key, reference) + + const resumed = await postSetupProgress(test.context, "sign-in", test.desired) + + expect(resumed.hasSaved).toBe(false) + expect(resumed.answers).toEqual({}) + expect(resumed.references).toEqual({}) + }, +) + +it("recognizes an unversioned hex-named origin pinned to the same secret", async () => { + const test = await signInScenario(false) + const name = "b".repeat(32) + const unversioned = test.inputs.runtime_secret_references!.HUB_APPLICATION_ORIGIN + unversioned.secret_id = unversioned.secret_id.replace("hub-application-origin", name) + test.desired.runtime_secret_references!.HUB_APPLICATION_ORIGIN = { + ...unversioned, + secret_id: `${unversioned.secret_id}/${"a".repeat(32)}`, + } + const progress = await postSetupProgress(test.context, "sign-in", test.inputs) + await progress.saveAnswer("origin", "https://sample.example.com") + await progress.saveAnswer("proxyHops", "2") + for (const [key, reference] of Object.entries(test.sharedReferences)) + await progress.saveReference(key, reference) + + const resumed = await postSetupProgress(test.context, "sign-in", test.desired) + + expect(resumed.hasSaved).toBe(false) +}) + +it("recognizes original unversioned shared references pinned without uploads", async () => { + const test = await signInScenario(false) + for (const [key, reference] of Object.entries(test.sharedReferences)) + test.inputs.runtime_secret_references![key] = { + ...reference, + secret_id: reference.secret_id.slice(0, -33), + } + const progress = await postSetupProgress(test.context, "sign-in", test.inputs) + await progress.saveAnswer("origin", "https://sample.example.com") + await progress.saveAnswer("proxyHops", "2") + + const resumed = await postSetupProgress(test.context, "sign-in", test.desired) + + expect(resumed.hasSaved).toBe(false) +}) + +it.each(["verified", "changed deployment", "disabled deployment"] as const)( + "reconciles normalized inputs only for the original %s", + async (change) => { + const test = await signInScenario() + test.inputs.deploy_hub = false + const image = `registry.azurecr.io/hub@sha256:${"b".repeat(64)}` + const progress = await postSetupProgress(test.context, "sign-in", test.inputs, image) + await progress.saveAnswer("origin", "https://sample.example.com") + await progress.saveAnswer("proxyHops", "2") + for (const [key, reference] of Object.entries(test.sharedReferences)) + await progress.saveReference(key, reference) + const saved = await readFile(progress.path) + const desired = { + ...test.desired, + image: + change === "changed deployment" ? `registry.azurecr.io/hub@sha256:${"c".repeat(64)}` : image, + deploy_hub: change !== "disabled deployment", + } + + const resumed = postSetupProgress(test.context, "sign-in", desired, desired.image) + if (change === "verified") expect((await resumed).hasSaved).toBe(false) + else { + await expect(resumed).rejects.toThrow(/inputs changed/i) + expect(await readFile(progress.path)).toEqual(saved) + } + }, +) + +it.each([ + "image", + "unrelated environment", + "unrelated reference", + "origin vault", + "origin name", + "origin version", + "origin source", + "shared reference", +] as const)( + "rejects a changed %s when reconciling saved sign-in configuration and preserves progress", + async (change) => { + const test = await signInScenario() + const progress = await postSetupProgress(test.context, "sign-in", test.inputs) + await progress.saveAnswer("origin", "https://sample.example.com") + await progress.saveAnswer("proxyHops", "2") + for (const [key, reference] of Object.entries(test.sharedReferences)) + await progress.saveReference(key, reference) + const desired = structuredClone(test.desired) + const references = desired.runtime_secret_references! + if (change === "image") desired.image = `registry.azurecr.io/hub@sha256:${"b".repeat(64)}` + if (change === "unrelated environment") + desired.runtime_environment_variables!.RETAINED_SETTING = "changed" + if (change === "unrelated reference") + references.RETAINED_SECRET.secret_id = references.RETAINED_SECRET.secret_id.replace( + "a".repeat(32), + "b".repeat(32), + ) + if (change === "origin vault") { + references.HUB_APPLICATION_ORIGIN.key_vault_id = + references.HUB_APPLICATION_ORIGIN.key_vault_id.replace(/\/vaults\/[^/]+$/, "/vaults/other") + references.HUB_APPLICATION_ORIGIN.secret_id = + references.HUB_APPLICATION_ORIGIN.secret_id.replace(/https:\/\/[^.]+/, "https://other") + } + if (change === "origin name") + references.HUB_APPLICATION_ORIGIN.secret_id = + references.HUB_APPLICATION_ORIGIN.secret_id.replace("hub-application-origin", "other-origin") + if (change === "origin version") + references.HUB_APPLICATION_ORIGIN.secret_id = + references.HUB_APPLICATION_ORIGIN.secret_id.replace("a".repeat(32), "b".repeat(32)) + if (change === "origin source") { + delete references.HUB_APPLICATION_ORIGIN + desired.hub_application_origin = "https://sample.example.com" + } + if (change === "shared reference") + references.HUB_BOOTSTRAP_SECRET.secret_id = + references.HUB_BOOTSTRAP_SECRET.secret_id.replace("a".repeat(32), "b".repeat(32)) + const saved = await readFile(progress.path) + + await expect(postSetupProgress(test.context, "sign-in", desired)).rejects.toThrow( + /inputs changed/i, + ) + + expect(await readFile(progress.path)).toEqual(saved) + }, +) + +it("rejects pinning an unrelated unversioned reference and preserves sign-in progress", async () => { + const test = await signInScenario(false) + test.inputs.runtime_secret_references!.RETAINED_SECRET = { + ...test.reference, + secret_id: test.reference.secret_id.slice(0, -33), + } + const progress = await postSetupProgress(test.context, "sign-in", test.inputs) + await progress.saveAnswer("origin", "https://sample.example.com") + await progress.saveAnswer("proxyHops", "2") + for (const [key, reference] of Object.entries(test.sharedReferences)) + await progress.saveReference(key, reference) + const saved = await readFile(progress.path) + + await expect(postSetupProgress(test.context, "sign-in", test.desired)).rejects.toThrow( + /inputs changed/i, + ) + + expect(await readFile(progress.path)).toEqual(saved) +}) + +it.each(["unrelated setting", "proxy hops"] as const)( + "rejects changed %s after starting over with confirmed references", + async (change) => { + const test = await signInScenario() + const progress = await postSetupProgress(test.context, "sign-in", test.inputs) + await progress.saveAnswer("origin", "https://sample.example.com") + await progress.saveReference("HUB_BOOTSTRAP_SECRET", test.sharedReferences.HUB_BOOTSTRAP_SECRET) + await progress.startOver() + const saved = await readFile(progress.path) + const changed = structuredClone(test.desired) + if (change === "unrelated setting") + changed.runtime_environment_variables!.RETAINED_SETTING = "changed" + else changed.runtime_environment_variables!.HUB_TRUSTED_PROXY_HOPS = "10" + + await expect(postSetupProgress(test.context, "sign-in", changed)).rejects.toThrow( + /inputs changed/i, + ) + + expect(await readFile(progress.path)).toEqual(saved) + const resumed = await postSetupProgress(test.context, "sign-in", test.inputs) + expect(resumed.references).toEqual({ + HUB_BOOTSTRAP_SECRET: test.sharedReferences.HUB_BOOTSTRAP_SECRET, + }) + expect(resumed.answers).toEqual({}) + }, +) + +it("preserves an unresolved sign-in upload instead of accepting written desired inputs", async () => { + const test = await signInScenario() + const progress = await postSetupProgress(test.context, "sign-in", test.inputs) + await progress.saveAnswer("origin", "https://sample.example.com") + await progress.saveAnswer("proxyHops", "2") + await progress.saveReference( + "HUB_AUTHENTICATION_ENCRYPTION_KEY", + test.sharedReferences.HUB_AUTHENTICATION_ENCRYPTION_KEY, + ) + await progress.pendingUpload("HUB_BOOTSTRAP_SECRET") + const saved = await readFile(progress.path) + + await expect(postSetupProgress(test.context, "sign-in", test.desired)).rejects.toThrow( + /inputs changed/i, + ) + + expect(await readFile(progress.path)).toEqual(saved) + const resumed = await postSetupProgress(test.context, "sign-in", test.inputs) + expect(resumed.pending).toBe("HUB_BOOTSTRAP_SECRET") +}) + +it("preserves legacy sign-in progress without origin-reference proof when inputs change", async () => { + const test = await signInScenario() + const progress = await postSetupProgress(test.context, "sign-in", test.inputs) + await progress.saveAnswer("origin", "https://sample.example.com") + await progress.saveAnswer("proxyHops", "2") + for (const [key, reference] of Object.entries(test.sharedReferences)) + await progress.saveReference(key, reference) + const { version, target, action, inputs, answers, references, complete } = JSON.parse( + await readFile(progress.path, "utf8"), + ) + const legacy = JSON.stringify({ version, target, action, inputs, answers, references, complete }) + await writeFile(progress.path, legacy) + + await expect(postSetupProgress(test.context, "sign-in", test.desired)).rejects.toThrow( + /inputs changed/i, + ) + + expect(await readFile(progress.path, "utf8")).toBe(legacy) +}) + it("persists only validated public answers, credential paths and versioned references in a private file", async () => { const test = await scenario() const progress = await postSetupProgress(test.context, "github") @@ -196,6 +467,45 @@ it("rejects foreign-vault and unversioned references before recording a successf expect(await readFile(progress.path, "utf8")).toBe(saved) }) +it("rejects saving a hex-named unversioned reference as a confirmed upload", async () => { + const test = await scenario() + const progress = await postSetupProgress(test.context, "github") + await progress.saveAnswer("github_app_id", "123") + const saved = await readFile(progress.path, "utf8") + const unversioned = { + ...test.reference, + secret_id: test.reference.secret_id.replace( + /github-client-secret\/[a-f0-9]{32}$/, + "b".repeat(32), + ), + } + + await expect(progress.saveReference("GITHUB_CLIENT_SECRET", unversioned)).rejects.toThrow( + /invalid/i, + ) + expect(await readFile(progress.path, "utf8")).toBe(saved) +}) + +it("rejects a saved hex-named unversioned confirmed upload without changing the file", async () => { + const test = await scenario() + const progress = await postSetupProgress(test.context, "github") + await progress.saveAnswer("github_app_id", "123") + const saved = await readFile(progress.path, "utf8") + const unversioned = { + ...test.reference, + secret_id: test.reference.secret_id.replace( + /github-client-secret\/[a-f0-9]{32}$/, + "b".repeat(32), + ), + } + const damaged = JSON.parse(saved) + damaged.references.GITHUB_CLIENT_SECRET = unversioned + const content = JSON.stringify(damaged) + await writeFile(progress.path, content) + await expect(postSetupProgress(test.context, "github")).rejects.toThrow(/invalid/i) + expect(await readFile(progress.path, "utf8")).toBe(content) +}) + it("retains confirmed uploads and unresolved writes when starting over, then completes without retaining prompts", async () => { const test = await scenario() const progress = await postSetupProgress(test.context, "github") diff --git a/infrastructure/azure/post/progress/index.ts b/infrastructure/azure/post/progress/index.ts index 3c6d255d5..da4a0ffdf 100644 --- a/infrastructure/azure/post/progress/index.ts +++ b/infrastructure/azure/post/progress/index.ts @@ -33,12 +33,18 @@ interface Progress { pending?: string complete: boolean inputs: string + secretOrigin?: { + inputs: string + normalizedInputs?: string + references: Record + } } export async function postSetupProgress( context: Pick, action: "sign-in" | "github", inputs?: PostInputs, + verifiedImage?: string, ) { const path = join(context.directory, `post-${action}-progress.json`) const target = JSON.stringify(context.config) @@ -48,6 +54,13 @@ export async function postSetupProgress( const fingerprint = createHash("sha256") .update(JSON.stringify(inputs ?? {})) .digest("hex") + function retainedFingerprint(value: PostInputs | undefined) { + const { runtime_environment_variables, runtime_secret_references, ...retained } = value ?? {} + const { HUB_TRUSTED_PROXY_HOPS, ...environment } = runtime_environment_variables ?? {} + return createHash("sha256") + .update(JSON.stringify({ ...retained, runtime_environment_variables: environment })) + .digest("hex") + } const empty = (): Progress => ({ version: 1, target, @@ -56,8 +69,26 @@ export async function postSetupProgress( answers: {}, references: {}, complete: false, + ...(action === "sign-in" && + inputs?.runtime_secret_references?.HUB_APPLICATION_ORIGIN && { + secretOrigin: { + inputs: retainedFingerprint(inputs), + ...(verifiedImage && { + normalizedInputs: retainedFingerprint({ + ...inputs, + image: verifiedImage, + deploy_hub: true, + }), + }), + references: Object.fromEntries( + Object.entries(inputs.runtime_secret_references).map(([key, value]) => [ + key, + reference(key, value, true), + ]), + ), + }, + }), }) - let data = empty() function invalid(): never { throw new Error( "Post-setup answers are invalid or belong to another installation/action. The private progress file was preserved.", @@ -68,6 +99,8 @@ export async function postSetupProgress( return value as Record } const keys: readonly string[] = action === "github" ? credentialKeys : sharedKeys + const pinned = (secretId: string) => + /\/secrets\/[a-z0-9-]{1,127}\/[a-f0-9]{32}$/i.test(secretId) function answer(key: string, value: unknown): string { if (typeof value !== "string" || value.length > 4096 || /[\u0000-\u001f\u007f]/.test(value)) invalid() @@ -89,26 +122,28 @@ export async function postSetupProgress( invalid() return value } - function reference(key: string, value: unknown): Reference { - if (!keys.includes(key)) invalid() + function reference(key: string, value: unknown, retained = false): Reference { + if (retained ? !/^[A-Z][A-Z0-9_]{0,40}$/.test(key) : !keys.includes(key)) invalid() const raw = record(value) if ( Object.keys(raw).some((key) => !["key_vault_id", "secret_id"].includes(key)) || typeof raw.key_vault_id !== "string" || typeof raw.secret_id !== "string" || - raw.key_vault_id.toLowerCase() !== vaultId.toLowerCase() || + (!retained && raw.key_vault_id.toLowerCase() !== vaultId.toLowerCase()) || !/^\/subscriptions\/[a-f0-9-]{36}\/resourceGroups\/[^/]+\/providers\/Microsoft.KeyVault\/vaults\/[a-z0-9-]{1,24}$/i.test( raw.key_vault_id, ) || - !/^https:\/\/[a-z0-9-]{1,24}\.vault\.azure\.net\/secrets\/[a-z0-9-]{1,127}\/[a-f0-9]{32}$/i.test( + !/^https:\/\/[a-z0-9-]{1,24}\.vault\.azure\.net\/secrets\/[a-z0-9-]{1,127}(\/[a-f0-9]{32})?$/i.test( raw.secret_id, ) || + (!retained && !pinned(raw.secret_id)) || new URL(raw.secret_id).hostname.toLowerCase() !== `${raw.key_vault_id.split("/").at(-1)?.toLowerCase()}.vault.azure.net` ) invalid() return { key_vault_id: raw.key_vault_id, secret_id: raw.secret_id } } + let data = empty() if (original !== undefined) { let value: unknown try { @@ -135,12 +170,42 @@ export async function postSetupProgress( "references", "pending", "complete", + "secretOrigin", ].includes(key), ) || (raw.pending !== undefined && (typeof raw.pending !== "string" || !keys.includes(raw.pending))) ) invalid() + let secretOrigin: Progress["secretOrigin"] + if (raw.secretOrigin !== undefined) { + const saved = record(raw.secretOrigin) + if ( + action !== "sign-in" || + Object.keys(saved).some( + (key) => !["inputs", "normalizedInputs", "references"].includes(key), + ) || + typeof saved.inputs !== "string" || + !/^[a-f0-9]{64}$/.test(saved.inputs) || + (saved.normalizedInputs !== undefined && + (typeof saved.normalizedInputs !== "string" || + !/^[a-f0-9]{64}$/.test(saved.normalizedInputs))) + ) + invalid() + secretOrigin = { + inputs: saved.inputs, + ...(typeof saved.normalizedInputs === "string" && { + normalizedInputs: saved.normalizedInputs, + }), + references: Object.fromEntries( + Object.entries(record(saved.references)).map(([key, value]) => [ + key, + reference(key, value, true), + ]), + ), + } + if (!secretOrigin.references.HUB_APPLICATION_ORIGIN) invalid() + } data = { version: 1, target, @@ -154,6 +219,7 @@ export async function postSetupProgress( Object.entries(record(raw.references)).map(([key, value]) => [key, reference(key, value)]), ), ...(raw.pending !== undefined && { pending: String(raw.pending) }), + ...(secretOrigin && { secretOrigin }), } if (data.complete) data = empty() else if (data.inputs !== fingerprint) { @@ -167,11 +233,41 @@ export async function postSetupProgress( github_app_installation_id: inputs?.github_app_installation_id, github_provider_revision: inputs?.github_provider_revision, } + const retainedReferences = { ...data.secretOrigin?.references, ...data.references } + const currentReferences = inputs?.runtime_secret_references ?? {} + const secretOriginMatches = + desired.origin === undefined && + (data.secretOrigin?.inputs === retainedFingerprint(inputs) || + (verifiedImage !== undefined && + inputs?.image === verifiedImage && + inputs.deploy_hub === true && + data.secretOrigin?.normalizedInputs === retainedFingerprint(inputs))) && + Object.keys(retainedReferences).length === Object.keys(currentReferences).length && + Object.entries(retainedReferences).every(([key, saved]) => { + const current = currentReferences[key] + if (!current) return false + const checked = reference(key, current, true) + return ( + checked.key_vault_id.toLowerCase() === saved.key_vault_id.toLowerCase() && + (checked.secret_id.toLowerCase() === saved.secret_id.toLowerCase() || + ((key === "HUB_APPLICATION_ORIGIN" || sharedKeys.some((name) => name === key)) && + !pinned(saved.secret_id) && + checked.secret_id.toLowerCase().replace(/\/[a-f0-9]{32}$/i, "") === + saved.secret_id.toLowerCase())) + ) + }) if ( data.pending === undefined && + (!data.secretOrigin || + (data.answers.origin !== undefined && + data.answers.proxyHops !== undefined && + secretOriginMatches)) && Object.entries(data.answers).every( ([key, value]) => - key.endsWith("_FILE") || String(desired[key as keyof typeof desired]) === value, + key.endsWith("_FILE") || + (key === "origin" && data.secretOrigin + ? secretOriginMatches + : String(desired[key as keyof typeof desired]) === value), ) && Object.entries(data.references).every( ([key, ref]) =>