diff --git a/packages/void/src/cli/platform-access-health.ts b/packages/void/src/cli/platform-access-health.ts index 2557343da..265c09729 100644 --- a/packages/void/src/cli/platform-access-health.ts +++ b/packages/void/src/cli/platform-access-health.ts @@ -68,14 +68,28 @@ async function verifyHealthException( } } -/** Keep the same path-only exception used by project Zero Trust available during bootstrap. */ -export async function ensurePlatformAccessHealthChecks(input: { +type AccessHealthInput = { plan: PlatformInstallPlan; manifest: PlatformInstallationManifest; client: Partial>; checkpoint: Readonly>; - save: (encoded: string) => void; -}): Promise { +}; + +export function verifyPlatformAccessHealthChecks(input: AccessHealthInput): Promise { + return reconcilePlatformAccessHealthChecks(input); +} + +/** Keep the same path-only exception used by project Zero Trust available during bootstrap. */ +export function ensurePlatformAccessHealthChecks( + input: AccessHealthInput & { save: (encoded: string) => void }, +): Promise { + return reconcilePlatformAccessHealthChecks(input, input.save); +} + +async function reconcilePlatformAccessHealthChecks( + input: AccessHealthInput, + writeCheckpoint?: (encoded: string) => void, +): Promise { // The server owns ongoing app access after setup. Its token may have been // rotated or its settings changed by an administrator since installation. const appAccess = @@ -131,7 +145,7 @@ export async function ensurePlatformAccessHealthChecks(input: { ) { throw new Error('platform: Access health recovery data belongs to a different installation.'); } - const save = () => input.save(JSON.stringify(state)); + const save = () => writeCheckpoint?.(JSON.stringify(state)); const inventory = await access.list('apps'); for (const { key, destination } of platformAccessHealthTargets(input.plan)) { const expected = { @@ -190,6 +204,9 @@ export async function ensurePlatformAccessHealthChecks(input: { 'platform: An Access health application with this installation identity already exists. Inspect it before resuming.', ); } + if (!writeCheckpoint) { + continue; + } recorded = { name, fingerprint, pending: true }; state.resources[key] = recorded; save(); diff --git a/packages/void/src/cli/platform-access-setup.ts b/packages/void/src/cli/platform-access-setup.ts index dd0437cc7..6da11ca4e 100644 --- a/packages/void/src/cli/platform-access-setup.ts +++ b/packages/void/src/cli/platform-access-setup.ts @@ -373,9 +373,15 @@ export function activatePlatformAccessCredentials( encoded: string | undefined, origins: ReadonlyArray, ): void { - if (!encoded) { - return; + if (encoded) { + process.env.VOID_ACCESS_CREDENTIALS = mergePlatformAccessCredentials(encoded, origins); } +} + +export function mergePlatformAccessCredentials( + encoded: string, + origins: ReadonlyArray, +): string { const entries: unknown = JSON.parse(encoded); if (!entries || typeof entries !== 'object' || Array.isArray(entries)) { throw new Error('platform: Invalid saved Access credentials.'); @@ -401,7 +407,7 @@ export function activatePlatformAccessCredentials( if (!current || typeof current !== 'object' || Array.isArray(current)) { throw new Error('platform: VOID_ACCESS_CREDENTIALS must contain an origin-keyed object.'); } - process.env.VOID_ACCESS_CREDENTIALS = JSON.stringify({ ...current, ...entries }); + return JSON.stringify({ ...current, ...entries }); } export async function preparePlatformAccessSetup(input: { diff --git a/packages/void/src/cli/platform-install-preparation.ts b/packages/void/src/cli/platform-install-preparation.ts index a94714257..53b1a44be 100644 --- a/packages/void/src/cli/platform-install-preparation.ts +++ b/packages/void/src/cli/platform-install-preparation.ts @@ -7,10 +7,13 @@ import { } from '@void/platform'; import type { PlatformDeploymentManifest } from '@void/platform'; import type { PlatformRuntimeManifest } from '@void/platform/installer'; -import { ensurePlatformAccessHealthChecks } from './platform-access-health.ts'; +import { + ensurePlatformAccessHealthChecks, + verifyPlatformAccessHealthChecks, +} from './platform-access-health.ts'; import { verifyInstalledPlatformAccessProtection } from './platform-access-preflight.ts'; import { - activatePlatformAccessCredentials, + mergePlatformAccessCredentials, isPlatformAuthenticationPreparationKey, } from './platform-access-setup.ts'; import { PlatformAppAccessCredentialError } from './platform-app-access.ts'; @@ -27,6 +30,7 @@ import type { PlatformDatabaseLifecycleLock, PlatformInstallerDependencies, PlatformInstallRunState, + PlatformLiveAuthenticationState, } from './platform-installer-types.ts'; import { readPendingInstallationSecrets, @@ -49,25 +53,17 @@ function withAuthentication( }); } -export async function prepareInstallationAuthentication(input: { - readonly state: PlatformInstallRunState; - readonly releaseDatabaseLock: PlatformDatabaseLifecycleLock; - readonly runtime: PlatformRuntimeManifest; - readonly authenticationProtocolTransition: boolean; - readonly now: () => string; - readonly dependencies: PlatformInstallerDependencies; -}): Promise { - const { - state, - releaseDatabaseLock, - runtime, - authenticationProtocolTransition, - now, - dependencies, - } = input; - const { workerSecretUpdateIntent } = state; +type InstallationAuthenticationInput = Readonly<{ + state: PlatformInstallRunState; + runtime: PlatformRuntimeManifest; + authenticationProtocolTransition: boolean; + dependencies: PlatformInstallerDependencies; +}>; - const liveAuthentication = await releaseDatabaseLock.readAuthenticationState?.(); +function applyInstallationAuthentication( + { state, runtime, authenticationProtocolTransition }: InstallationAuthenticationInput, + liveAuthentication: PlatformLiveAuthenticationState | null | undefined, +): void { if (liveAuthentication) { state.authenticationEnforcementActive = liveAuthentication.sessionsRequired; if (liveAuthentication.sessionsRequired && runtime.authenticationProtocolVersion !== 1) { @@ -106,25 +102,104 @@ export async function prepareInstallationAuthentication(input: { }), }; } - const activateAccessCredentials = () => { - if (!state.secrets.accessCredentialsJson) { - return; +} + +async function verifyInstallationAccessSetup( + { state, dependencies }: InstallationAuthenticationInput, + liveAuthentication: PlatformLiveAuthenticationState | null | undefined, +): Promise { + const protection = liveAuthentication + ? liveAuthentication.protection + : state.secrets.authenticationSetupJson + ? parsePlatformAuthenticationSetup(JSON.parse(state.secrets.authenticationSetupJson)) + .protection + : null; + if (!protection) { + throw new Error( + 'platform: The active Access protection configuration is unavailable. Restore its database and encrypted setup checkpoint before maintenance.', + ); + } + dependencies.onProgress?.('Verifying current Access policies and protected origins'); + await (dependencies.verifyAccessProtection ?? verifyInstalledPlatformAccessProtection)({ + client: dependencies.client, + manifest: state.manifest, + plan: state.plan, + dashboardUrl: platformDashboardUrl(state.plan.deployment), + protection, + checkpoint: secretCheckpoint(state.secrets, state.workerSecretUpdateIntent), + }); +} + +function installationAccessCredentials(state: PlatformInstallRunState): string | undefined { + if (!state.secrets.accessCredentialsJson) { + return undefined; + } + const credentials: unknown = JSON.parse(state.secrets.accessCredentialsJson); + if (!credentials || typeof credentials !== 'object' || Array.isArray(credentials)) { + throw new Error('platform: Invalid saved Access credentials.'); + } + // Lifecycle HTTP calls use API/proxy origins. Retain optional dashboard credentials + // in recovery storage without activating them, including after protection removal. + const origins = [state.plan.apiUrl, state.plan.proxyUrl]; + return mergePlatformAccessCredentials( + JSON.stringify( + Object.fromEntries( + Object.entries(credentials).filter(([origin]) => origins.includes(origin)), + ), + ), + origins, + ); +} + +export async function preflightInstallationAuthentication( + input: InstallationAuthenticationInput, + lock: Pick, +): Promise { + const liveAuthentication = (await lock.readAuthenticationState?.()) ?? null; + // Use the same deployment decisions as preparation while keeping the current checkpoint. + const preview = { ...input, state: { ...input.state } }; + applyInstallationAuthentication(preview, liveAuthentication); + installationAccessCredentials(preview.state); + checkpointAuthenticationResources( + preview.state.manifest, + preview.state.secrets, + preview.state.manifest.updatedAt, + ); + if (preview.state.plan.deployment.authentication.accessProtection) { + await verifyInstallationAccessSetup(preview, liveAuthentication); + if (!input.dependencies.prepareHealthAccess) { + await verifyPlatformAccessHealthChecks({ + client: preview.dependencies.client, + manifest: preview.state.manifest, + plan: preview.state.plan, + checkpoint: secretCheckpoint(preview.state.secrets, preview.state.workerSecretUpdateIntent), + }); } - const credentials: unknown = JSON.parse(state.secrets.accessCredentialsJson); - if (!credentials || typeof credentials !== 'object' || Array.isArray(credentials)) { - throw new Error('platform: Invalid saved Access credentials.'); + } + return liveAuthentication; +} + +export async function prepareInstallationAuthentication( + input: InstallationAuthenticationInput & + Readonly<{ + releaseDatabaseLock: PlatformDatabaseLifecycleLock; + now: () => string; + checkedAuthentication?: PlatformLiveAuthenticationState | null; + }>, +): Promise { + const { state, releaseDatabaseLock, runtime, now, dependencies, checkedAuthentication } = input; + const { authenticationProtocolTransition } = input; + const { workerSecretUpdateIntent } = state; + const liveAuthentication = + checkedAuthentication === undefined + ? await releaseDatabaseLock.readAuthenticationState?.() + : checkedAuthentication; + applyInstallationAuthentication(input, liveAuthentication); + const activateAccessCredentials = () => { + const credentials = installationAccessCredentials(state); + if (credentials !== undefined) { + process.env.VOID_ACCESS_CREDENTIALS = credentials; } - // Lifecycle HTTP calls use API/proxy origins. Retain optional dashboard credentials - // in recovery storage without activating them, including after protection removal. - const origins = [state.plan.apiUrl, state.plan.proxyUrl]; - activatePlatformAccessCredentials( - JSON.stringify( - Object.fromEntries( - Object.entries(credentials).filter(([origin]) => origins.includes(origin)), - ), - ), - origins, - ); }; activateAccessCredentials(); state.manifest = checkpointAuthenticationResources(state.manifest, state.secrets, now()); @@ -282,27 +357,11 @@ export async function prepareInstallationAuthentication(input: { }); } } - if (state.plan.deployment.authentication.accessProtection) { - const protection = liveAuthentication - ? liveAuthentication.protection - : state.secrets.authenticationSetupJson - ? parsePlatformAuthenticationSetup(JSON.parse(state.secrets.authenticationSetupJson)) - .protection - : null; - if (!protection) { - throw new Error( - 'platform: The active Access protection configuration is unavailable. Restore its database and encrypted setup checkpoint before maintenance.', - ); - } - dependencies.onProgress?.('Verifying current Access policies and protected origins'); - await (dependencies.verifyAccessProtection ?? verifyInstalledPlatformAccessProtection)({ - client: dependencies.client, - manifest: state.manifest, - plan: state.plan, - dashboardUrl: platformDashboardUrl(state.plan.deployment), - protection, - checkpoint: secretCheckpoint(state.secrets, workerSecretUpdateIntent), - }); + if ( + checkedAuthentication === undefined && + state.plan.deployment.authentication.accessProtection + ) { + await verifyInstallationAccessSetup(input, liveAuthentication); } if ( state.plan.deployment.authentication.accessProtection || diff --git a/packages/void/src/cli/platform-installer-database.ts b/packages/void/src/cli/platform-installer-database.ts index 541a30921..6e71a4267 100644 --- a/packages/void/src/cli/platform-installer-database.ts +++ b/packages/void/src/cli/platform-installer-database.ts @@ -37,6 +37,10 @@ import type { QueryConnection, } from './platform-zero-trust-uninstall.ts'; +function platformDatabaseSchemaStep(database: PlatformRuntimeDatabaseManifest): string { + return `database-schema:${database.schemaDigest}`; +} + // onManifestChange keeps migration checkpoints visible to the outer failure handler. export async function preparePlatformDatabaseSchema( manifest: PlatformInstallationManifest, @@ -53,7 +57,7 @@ export async function preparePlatformDatabaseSchema( ): Promise { dependencies.onProgress?.('Checking the platform database schema'); const rollbackDatabase = dependencies.databaseRollbackSource; - const migrationStep = `database-schema:${runtime.database.schemaDigest}`; + const migrationStep = platformDatabaseSchemaStep(runtime.database); if (rollbackDatabase) { const verifyDatabase = releaseDatabaseLock.verifyDatabase; if (!verifyDatabase) { @@ -460,26 +464,18 @@ export async function inspectPlatformDatabaseStateConnection( }; } -export async function preparePlatformDatabaseConnection( +async function inspectPlatformDatabaseUpgrade( client: QueryConnection, - runtimeDirectory: string, database: PlatformRuntimeDatabaseManifest, sourcePlatformVersion: string | null, hasPriorWorkers: boolean, -): Promise { - verifyPlatformDatabaseArtifacts(runtimeDirectory, database); +): Promise { const before = await inspectPlatformDatabaseStateConnection(client, database); if (before.pendingMigrations.length === 0) { if (before.schemaDigest !== database.schemaDigest) { throw new Error('platform: PostgreSQL schema digest does not match the packaged runtime.'); } - return { - appliedMigrations: 0, - previousSchemaDigest: before.schemaDigest, - schemaDigest: before.schemaDigest, - }; - } - if ( + } else if ( hasPriorWorkers && !database.rollbackSafeFrom.some( (entry) => @@ -492,6 +488,31 @@ export async function preparePlatformDatabaseConnection( ); } + return before; +} + +export async function preparePlatformDatabaseConnection( + client: QueryConnection, + runtimeDirectory: string, + database: PlatformRuntimeDatabaseManifest, + sourcePlatformVersion: string | null, + hasPriorWorkers: boolean, +): Promise { + verifyPlatformDatabaseArtifacts(runtimeDirectory, database); + const before = await inspectPlatformDatabaseUpgrade( + client, + database, + sourcePlatformVersion, + hasPriorWorkers, + ); + if (before.pendingMigrations.length === 0) { + return { + appliedMigrations: 0, + previousSchemaDigest: before.schemaDigest, + schemaDigest: before.schemaDigest, + }; + } + await client.query('BEGIN'); try { await client.query('CREATE SCHEMA IF NOT EXISTS "drizzle"'); @@ -716,6 +737,24 @@ export async function acquirePlatformDatabaseLifecycleLockConnection( } release.authoritativeManifest = manifest; }; + release.preflightDatabaseUpgrade = async ( + runtimeDirectory, + database, + manifest, + hasPriorWorkers, + ) => { + const schemaStep = platformDatabaseSchemaStep(database); + if (manifest.steps.some((step) => step.key === schemaStep)) { + await verifyPlatformDatabaseConnection(client, runtimeDirectory, database); + } else { + await inspectPlatformDatabaseUpgrade( + client, + database, + manifest.platformVersion, + hasPriorWorkers, + ); + } + }; release.prepareDatabase = (runtimeDirectory, database, sourcePlatformVersion, hasPriorWorkers) => preparePlatformDatabaseConnection( client, diff --git a/packages/void/src/cli/platform-installer-types.ts b/packages/void/src/cli/platform-installer-types.ts index 7a5881943..e50393ac1 100644 --- a/packages/void/src/cli/platform-installer-types.ts +++ b/packages/void/src/cli/platform-installer-types.ts @@ -117,6 +117,12 @@ export type PlatformDatabaseLifecycleLock = (() => Promise) & { } | null>; authoritativeManifest?: PlatformInstallationManifest | null; checkpoint?: (manifest: PlatformInstallationManifest) => Promise; + preflightDatabaseUpgrade?: ( + runtimeDirectory: string, + database: PlatformRuntimeDatabaseManifest, + manifest: PlatformInstallationManifest, + hasPriorWorkers: boolean, + ) => Promise; prepareDatabase?: ( runtimeDirectory: string, database: PlatformRuntimeDatabaseManifest, @@ -159,7 +165,7 @@ export type PlatformDatabaseLifecycleLock = (() => Promise) & { ) => Promise; }; -type PlatformLiveAuthenticationState = NonNullable< +export type PlatformLiveAuthenticationState = NonNullable< Awaited>> >; @@ -276,6 +282,11 @@ export type PlatformInstallerDependencies = Readonly<{ installationId: string, ownershipNonce: string, ) => Promise; + /** The upgrade command already holds this lock before the installer can write any state. */ + upgradePreflightLock?: Pick< + PlatformDatabaseLifecycleLock, + 'preflightDatabaseUpgrade' | 'readAuthenticationState' | 'requiredSafetyProtocols' + >; claimDatabase?: ( databaseUrl: string, installationId: string, @@ -293,6 +304,7 @@ export type PlatformInstallerDependencies = Readonly<{ now?: () => string; onProgress?: (message: string) => void; operation?: PlatformLifecycleOperation['action']; + onFirstWrite?: () => void; prepareDatabase?: ( runtimeDirectory: string, database: PlatformRuntimeDatabaseManifest, diff --git a/packages/void/src/cli/platform-installer.ts b/packages/void/src/cli/platform-installer.ts index 4844eaaf2..0be15934e 100644 --- a/packages/void/src/cli/platform-installer.ts +++ b/packages/void/src/cli/platform-installer.ts @@ -26,7 +26,10 @@ import { import { verifyExternalPlatformHyperdrive } from './platform-auth-database.ts'; import { parsePostgresConnectionString } from './platform-cloudflare.ts'; import { enableInstallationServices } from './platform-install-activation.ts'; -import { prepareInstallationAuthentication } from './platform-install-preparation.ts'; +import { + preflightInstallationAuthentication, + prepareInstallationAuthentication, +} from './platform-install-preparation.ts'; import { provisionInstallationServices } from './platform-install-provisioning.ts'; import { uploadInstallationWorkers } from './platform-install-workers.ts'; import { workerCutoverRollsForward } from './platform-installer-cutover.ts'; @@ -57,6 +60,7 @@ import type { PlatformInstallationSecrets, PlatformInstallationResult, PlatformInstallRunState, + PlatformLiveAuthenticationState, PlatformWorkerKey, PlatformWorkerSecretUpdateIntent, InstallerClient, @@ -407,11 +411,43 @@ export async function installPlatform( workerDeploymentCommitted: false, authenticationEnforcementActive: false, }; + const assertSecretUpdateAuthority = () => + assertPlatformWorkerSecretUpdateAuthority({ + explicitUpdates: explicitWorkerSecretUpdates, + localIntent: state.secrets.pendingWorkerSecretUpdateIntent, + manifest: state.manifest, + requiresEmailSigningSecret: + state.manifest.deployment.capabilities.email || state.plan.deployment.capabilities.email, + }); + const upgradePreflightLock = dependencies.upgradePreflightLock; + const authenticationInput = { state, runtime, authenticationProtocolTransition, dependencies }; + let checkedAuthentication: PlatformLiveAuthenticationState | null | undefined; + if (upgradePreflightLock) { + assertSecretUpdateAuthority(); + assertPlatformRuntimeSafety( + runtime, + state.manifest.safetyProtocols, + upgradePreflightLock.requiredSafetyProtocols, + ); + await upgradePreflightLock.preflightDatabaseUpgrade?.( + runtimeDirectory, + runtime.database, + state.manifest, + hadPriorWorkers, + ); + checkedAuthentication = await preflightInstallationAuthentication( + authenticationInput, + upgradePreflightLock, + ); + } + const pendingSecrets = secretCheckpoint(state.secrets, state.workerSecretUpdateIntent); - writePendingInstallationSecrets(state.manifest, { - ...pendingSecrets, - databaseClaimState: 'claiming', - }); + writePendingInstallationSecrets( + state.manifest, + { ...pendingSecrets, databaseClaimState: 'claiming' }, + undefined, + dependencies.onFirstWrite, + ); dependencies.onProgress?.('Preparing the platform database'); try { @@ -456,17 +492,13 @@ export async function installPlatform( 'platform: This installation changed on another host. Local state was refreshed; rerun the command to review a current plan.', ); } - try { - assertPlatformWorkerSecretUpdateAuthority({ - explicitUpdates: explicitWorkerSecretUpdates, - localIntent: state.secrets.pendingWorkerSecretUpdateIntent, - manifest: state.manifest, - requiresEmailSigningSecret: - state.manifest.deployment.capabilities.email || state.plan.deployment.capabilities.email, - }); - } catch (error) { - await releaseDatabaseLock(); - throw error; + if (!upgradePreflightLock) { + try { + assertSecretUpdateAuthority(); + } catch (error) { + await releaseDatabaseLock(); + throw error; + } } // Progress is checkpointed under the same lifecycle lock as mutations. Do not // update it from parallel Worker upload callbacks. @@ -485,11 +517,13 @@ export async function installPlatform( }; let operationStarted = false; try { - assertPlatformRuntimeSafety( - runtime, - state.manifest.safetyProtocols, - releaseDatabaseLock.requiredSafetyProtocols, - ); + if (!upgradePreflightLock) { + assertPlatformRuntimeSafety( + runtime, + state.manifest.safetyProtocols, + releaseDatabaseLock.requiredSafetyProtocols, + ); + } if (existing) { await dependencies.verifyExistingOwnership?.( state.manifest, @@ -521,12 +555,10 @@ export async function installPlatform( }; await checkpointOperation('preparing'); await prepareInstallationAuthentication({ - state, + ...authenticationInput, releaseDatabaseLock, - runtime, - authenticationProtocolTransition, + checkedAuthentication, now, - dependencies, }); // Establish the durable installation checkpoint before creating any diff --git a/packages/void/src/cli/platform-management.ts b/packages/void/src/cli/platform-management.ts index 987e6b4bd..60a4971e3 100644 --- a/packages/void/src/cli/platform-management.ts +++ b/packages/void/src/cli/platform-management.ts @@ -351,6 +351,8 @@ export async function runInstalledPlatformCommand( args.subcommand === 'rollback' ? loadPlatformRuntime(args.fromRuntime) : null; let progress: ReturnType | undefined; let reportResult: (() => void) | undefined; + let upgradeWritten = false; + let savedManifest: PlatformInstallationManifest | undefined; const execute = async ( manifest: PlatformInstallationManifest, @@ -815,6 +817,14 @@ export async function runInstalledPlatformCommand( } : {}), databaseRollbackSource: rollbackSourceRuntime ?? undefined, + ...(args.subcommand === 'upgrade' + ? { + upgradePreflightLock: databaseLock, + onFirstWrite: () => { + upgradeWritten = true; + }, + } + : {}), onProgress: (message) => { markPhase(message); progress?.message(message); @@ -941,6 +951,7 @@ export async function runInstalledPlatformCommand( const authoritative = releaseDatabase.authoritativeManifest; const databaseCheckpointExists = authoritative !== null && authoritative !== undefined; const currentManifest = selectAuthoritativePlatformManifest(current, authoritative); + savedManifest = currentManifest; if (authoritative && JSON.stringify(authoritative) !== JSON.stringify(current)) { writeInstallationManifest(authoritative); } @@ -954,19 +965,37 @@ export async function runInstalledPlatformCommand( reportResult?.(); markPhase('complete'); } catch (error) { - const operationStarted = progress !== undefined; - progress?.error(`Platform ${args.subcommand} failed.`); + const operation = savedManifest?.operation; + const interruptedOperation = operation !== undefined && operation.phase !== 'complete'; + const needsRecovery = + args.subcommand === 'upgrade' + ? upgradeWritten || interruptedOperation || savedManifest?.status === 'failed' + : progress !== undefined; + if (needsRecovery) { + progress?.error(`Platform ${args.subcommand} failed.`); + } else { + progress?.clear(); + } progress = undefined; - if (operationStarted && args.subcommand !== 'uninstall' && args.subcommand !== 'disable') { - note( - [ - 'Traffic may remain paused. Inspect the saved state before continuing:', - `void platform status ${commandArgument(manifest.id)}`, + if (needsRecovery && args.subcommand !== 'uninstall' && args.subcommand !== 'disable') { + const guidance = [ + 'Traffic may remain paused. Inspect the saved state before continuing:', + `void platform status ${commandArgument(manifest.id)}`, + ]; + if ( + args.subcommand !== 'upgrade' || + upgradeWritten || + (interruptedOperation && + operation.action === 'upgrade' && + operation.toVersion === runtime?.manifest.platformVersion && + operation.runtimeManifestSha256 === runtime.manifestSha256) + ) { + guidance.push( 'After resolving the error, resume with the same runtime:', platformLifecycleResumeCommand(args, manifest.id), - ].join('\n'), - 'Recovery', - ); + ); + } + note(guidance.join('\n'), 'Recovery'); } throw error; } finally { diff --git a/packages/void/src/cli/platform-registry.ts b/packages/void/src/cli/platform-registry.ts index bec0b8726..0b1b8ed6d 100644 --- a/packages/void/src/cli/platform-registry.ts +++ b/packages/void/src/cli/platform-registry.ts @@ -460,6 +460,7 @@ export function writePendingInstallationSecrets( manifest: PlatformInstallationManifest, secrets: Record, directory: string = platformRegistryDirectory(), + onWritten?: () => void, ): void { const manifestPath = installationManifestPath(manifest.account.id, manifest.id, directory); writeEncryptedRecoveryMaterial( @@ -469,6 +470,8 @@ export function writePendingInstallationSecrets( secrets, directory, ); + // The encrypted checkpoint remains on disk if legacy cleanup fails. + onWritten?.(); rmSync(manifestPath.replace(/\.json$/, '.secrets'), { force: true }); } diff --git a/packages/void/test/unit/platform-installer.test.ts b/packages/void/test/unit/platform-installer.test.ts index 90021b9a5..64b9e044b 100644 --- a/packages/void/test/unit/platform-installer.test.ts +++ b/packages/void/test/unit/platform-installer.test.ts @@ -21,6 +21,7 @@ import { setInstallationDesiredState, transitionInstallation, } from '@void/platform'; +import type { PlatformInstallationManifest } from '@void/platform'; import { getPlatformRuntimeDirectory, platformDatabaseSchemaDigest, @@ -31,6 +32,7 @@ import type { PlatformRuntimeDatabaseManifest } from '@void/platform/installer'; import { toSlash } from 'pathslash'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import { Buffer } from '../../src/cli/node-buffer.ts'; +import { platformAccessHealthTargets } from '../../src/cli/platform-access-health.ts'; import type { AiLoggingProjectionKv } from '../../src/cli/platform-ai-logging-projection.ts'; import { PlatformCloudflareApiError } from '../../src/cli/platform-cloudflare.ts'; import { @@ -5923,16 +5925,344 @@ describe('platform installer', () => { ]); }); + it.each([ + { reason: 'missing rollback compatibility', error: 'cannot safely roll back' }, + { reason: 'divergent migration history', error: 'not an exact prefix' }, + { reason: 'target schema step already saved', error: 'not at the exact forward-only schema' }, + { + reason: 'unsupported Sandbox protocol', + error: 'predates the required sandbox-drain safety protocol', + }, + ])( + 'preserves the checkpoint when upgrade preflight refuses $reason', + async ({ reason, error }) => { + const { directory, secrets, upgradedPlan, sourceManifest, upgradeClient, upgradeKvWrites } = + await installedPlatform(); + const runtime = resolvePlatformRuntime(getPlatformRuntimeDirectory()); + const database = runtime.manifest.database; + const before0065 = database.migrations.findIndex(({ tag }) => tag.startsWith('0065_')); + expect(before0065).toBeGreaterThan(0); + const migrations = database.migrations.slice(0, before0065); + const schemaDigest = platformDatabaseSchemaDigest(database.lineage, migrations); + const savedStep = reason === 'target schema step already saved'; + const installed = parsePlatformInstallationManifest({ + ...sourceManifest, + platformVersion: '1.11.0', + databaseSchemaDigest: savedStep ? database.schemaDigest : schemaDigest, + ...(savedStep + ? { + status: 'verifying', + operation: { ...sourceManifest.operation, action: 'upgrade', phase: 'verifying' }, + } + : { + steps: sourceManifest.steps.filter( + (step) => !step.key.startsWith('database-schema:'), + ), + }), + }); + writeInstallationManifest(installed); + if (savedStep) { + writePendingInstallationSecrets(installed, { + databaseUrl: secrets.databaseUrl, + databaseClaimState: 'claimed', + }); + } + const pendingBefore = readPendingInstallationSecrets(installed); + const connection = migrationConnection( + migrations.map((migration, index) => ({ + created_at: migration.timestampMillis, + hash: + index === 0 && reason === 'divergent migration history' + ? '0'.repeat(64) + : migration.sha256, + id: index + 1, + })), + ); + const checkpoints: Array = []; + const lock = await acquirePlatformDatabaseLifecycleLockConnection( + { + async query>( + sql: string, + values?: ReadonlyArray, + ) { + const rows = (values: ReadonlyArray) => ({ + rows: values as ReadonlyArray, + }); + if (sql.includes('FROM "__void_platform_installation"')) { + return rows([ + { + installation_id: installed.id, + ownership_nonce: installed.ownershipNonce, + lifecycle_manifest: installed, + }, + ]); + } + if (sql.includes('pg_try_advisory_lock')) { + return rows([{ acquired: true }]); + } + if (sql.includes("current_setting('max_connections')")) { + return rows([{ max: 100, superuser: 3, reserved: 0 }]); + } + if (sql.includes('UPDATE "__void_platform_installation"')) { + const manifest = parsePlatformInstallationManifest(JSON.parse(String(values?.[0]))); + checkpoints.push(manifest.status); + return rows([{ singleton: true }]); + } + return connection.query(sql, values); + }, + }, + installed.id, + installed.ownershipNonce, + ); + const deployWorker = vi.fn(async () => {}); + const claim = vi.fn(claimDatabase); + const onFirstWrite = vi.fn(); + try { + await expect( + installPlatform(upgradedPlan, secrets, installed, { + acquireDatabaseLifecycleLock: async () => lock, + upgradePreflightLock: lock, + claimDatabase: claim, + client: upgradeClient, + deployWorker, + operation: 'upgrade', + onFirstWrite, + revalidateBeforeWorkerDeploy: async () => {}, + runtime: { + ...runtime, + manifest: { + ...runtime.manifest, + database: + reason === 'missing rollback compatibility' + ? { + ...database, + rollbackSafeFrom: database.rollbackSafeFrom.filter( + ({ platformVersion }) => platformVersion !== installed.platformVersion, + ), + } + : database, + safetyProtocols: + reason === 'unsupported Sandbox protocol' + ? { sandboxDrain: 0 } + : runtime.manifest.safetyProtocols, + }, + }, + verifyHealth: async () => {}, + }), + ).rejects.toThrow(error); + + expect(connection.queries).not.toContain('BEGIN'); + expect(deployWorker).not.toHaveBeenCalled(); + expect(upgradeKvWrites).toEqual([]); + expect(checkpoints).toEqual([]); + expect(lock.authoritativeManifest).toEqual(installed); + expect(listInstallationManifests(directory)[0]).toEqual(installed); + expect(readPendingInstallationSecrets(installed)).toEqual(pendingBefore); + expect(claim).not.toHaveBeenCalled(); + expect(onFirstWrite).not.toHaveBeenCalled(); + } finally { + await lock(); + } + }, + ); + + it('preserves deployment admission when the upgrade Access checkpoint is missing', async () => { + const { directory, sourceManifest, upgradedPlan, secrets, upgradeClient, upgradeKvWrites } = + await installedPlatform(); + const deployment = createPlatformDeploymentManifest({ + ...sourceManifest.deployment, + capabilities: { ...sourceManifest.deployment.capabilities, githubOAuth: false }, + authentication: { + providers: ['cloudflare-access'], + configurable: true, + accessProtection: true, + }, + }); + const installation = parsePlatformInstallationManifest({ ...sourceManifest, deployment }); + writeInstallationManifest(installation); + const pendingBefore = readPendingInstallationSecrets(installation); + const checkpoint = vi.fn(async (_manifest: PlatformInstallationManifest) => {}); + const preflightDatabaseUpgrade = vi.fn(async () => {}); + const readAuthenticationState = vi.fn(async () => ({ + enabledProviders: ['cloudflare-access'] as const, + sessionsRequired: true, + protectedByAccess: true, + protection: { + teamDomain: 'https://company.cloudflareaccess.com', + applications: [ + { origin: upgradedPlan.apiUrl, audience: 'api-audience' }, + { origin: upgradedPlan.proxyUrl, audience: 'proxy-audience' }, + ], + }, + })); + const lock = Object.assign(async () => {}, { + authoritativeManifest: installation, + checkpoint, + preflightDatabaseUpgrade, + readAuthenticationState, + }); + const claim = vi.fn(claimDatabase); + const deployWorker = vi.fn(async () => {}); + const prepareHealthAccess = vi.fn(async () => {}); + + await expect( + installPlatform( + { ...upgradedPlan, deployment }, + { ...secrets, accessProvisioningJson: undefined, authenticationPreparation: {} }, + installation, + { + acquireDatabaseLifecycleLock: async () => lock, + upgradePreflightLock: lock, + claimDatabase: claim, + client: upgradeClient, + deployWorker, + operation: 'upgrade', + prepareHealthAccess, + revalidateBeforeWorkerDeploy: async () => {}, + }, + ), + ).rejects.toThrow('Restore the current encrypted Access setup checkpoint'); + + expect(preflightDatabaseUpgrade).toHaveBeenCalledOnce(); + expect(readAuthenticationState).toHaveBeenCalledOnce(); + expect(listInstallationManifests(directory)[0]).toEqual(installation); + expect(readPendingInstallationSecrets(installation)).toEqual(pendingBefore); + expect(checkpoint).not.toHaveBeenCalled(); + expect(claim).not.toHaveBeenCalled(); + expect(prepareHealthAccess).not.toHaveBeenCalled(); + expect(deployWorker).not.toHaveBeenCalled(); + expect(upgradeKvWrites).toEqual([]); + }); + + it('preserves deployment admission when the reserved Access health policy has changed', async () => { + const { directory, sourceManifest, upgradedPlan, secrets, upgradeClient, upgradeKvWrites } = + await installedPlatform(); + const deployment = createPlatformDeploymentManifest({ + ...sourceManifest.deployment, + capabilities: { ...sourceManifest.deployment.capabilities, githubOAuth: false }, + authentication: { + providers: ['cloudflare-access'], + configurable: true, + accessProtection: true, + }, + }); + const installation = { ...sourceManifest, deployment }; + const plan = { ...upgradedPlan, deployment }; + writeInstallationManifest(installation); + const checkpoint = vi.fn(async (_manifest: PlatformInstallationManifest) => {}); + const lock = Object.assign(async () => {}, { + authoritativeManifest: installation, + checkpoint, + readAuthenticationState: async () => ({ + enabledProviders: ['cloudflare-access'] as const, + sessionsRequired: true, + protectedByAccess: true, + protection: { teamDomain: 'https://company.cloudflareaccess.com', applications: [] }, + }), + }); + const claim = vi.fn(claimDatabase); + const destination = platformAccessHealthTargets(plan)[0].destination; + const request = vi.fn(async (path: string, init?: RequestInit) => { + expect(init?.method ?? 'GET').toBe('GET'); + if (path.includes('/apps?')) { + return [ + { + id: 'health-app', + name: 'Project health', + type: 'self_hosted', + domain: destination, + destinations: [{ type: 'public', uri: destination }], + }, + ]; + } + expect(path).toContain('/apps/health-app/policies'); + return [{ decision: 'allow', include: [{ everyone: {} }] }]; + }); + await expect( + installPlatform( + plan, + { ...secrets, authenticationPreparation: { accessSetupSpecJson: '{"mode":"create"}' } }, + installation, + { + acquireDatabaseLifecycleLock: async () => lock, + upgradePreflightLock: lock, + claimDatabase: claim, + client: { + ...upgradeClient, + request: async (path: string, init?: RequestInit) => + (await request(path, init)) as T, + }, + operation: 'upgrade', + revalidateBeforeWorkerDeploy: async () => {}, + verifyAccessProtection: async () => {}, + }, + ), + ).rejects.toThrow('does not match the reserved health-check exception'); + + expect(listInstallationManifests(directory)[0]).toEqual(installation); + expect(checkpoint).not.toHaveBeenCalled(); + expect(claim).not.toHaveBeenCalled(); + expect(upgradeKvWrites).toEqual([]); + }); + + it('refuses invalid Access credentials before checkpointing an upgrade', async () => { + const { directory, sourceManifest, upgradedPlan, secrets, upgradeClient, upgradeKvWrites } = + await installedPlatform(); + writeInstallationManifest(sourceManifest); + process.env.VOID_ACCESS_CREDENTIALS = '[]'; + const pendingBefore = readPendingInstallationSecrets(sourceManifest); + const checkpoint = vi.fn(async (_manifest: PlatformInstallationManifest) => {}); + const lock = Object.assign(async () => {}, { + authoritativeManifest: sourceManifest, + checkpoint, + readAuthenticationState: async () => null, + }); + const claim = vi.fn(claimDatabase); + + await expect( + installPlatform( + upgradedPlan, + { + ...secrets, + accessCredentialsJson: JSON.stringify({ + [upgradedPlan.apiUrl]: { + CF_ACCESS_CLIENT_ID: 'access-client', + CF_ACCESS_CLIENT_SECRET: 'test-secret', + }, + }), + }, + sourceManifest, + { + acquireDatabaseLifecycleLock: async () => lock, + upgradePreflightLock: lock, + claimDatabase: claim, + client: upgradeClient, + operation: 'upgrade', + revalidateBeforeWorkerDeploy: async () => {}, + }, + ), + ).rejects.toThrow('VOID_ACCESS_CREDENTIALS must contain an origin-keyed object'); + + expect(listInstallationManifests(directory)[0]).toEqual(sourceManifest); + expect(readPendingInstallationSecrets(sourceManifest)).toEqual(pendingBefore); + expect(checkpoint).not.toHaveBeenCalled(); + expect(claim).not.toHaveBeenCalled(); + expect(upgradeKvWrites).toEqual([]); + }); + it('keeps the source version when upgrade health fails', async () => { const { directory, secrets, upgradedPlan, upgradeClient, sourceManifest } = await installedPlatform(); let verifiedTargetVersion = ''; + const checkpoint = vi.fn(async (_manifest: PlatformInstallationManifest) => {}); + const deployWorker = vi.fn(async () => async () => {}); await expect( installPlatform(upgradedPlan, secrets, sourceManifest, { - acquireDatabaseLifecycleLock, + acquireDatabaseLifecycleLock: async () => + Object.assign(await acquireDatabaseLifecycleLock(), { checkpoint }), claimDatabase, client: upgradeClient, - deployWorker: async () => async () => {}, + deployWorker, prepareDatabase, revalidateBeforeWorkerDeploy: async () => {}, verifyHealth: async (_api, _id, _proxy, _domain, platformVersion) => { @@ -5942,11 +6272,14 @@ describe('platform installer', () => { }), ).rejects.toThrow('upgrade health failed'); expect(verifiedTargetVersion).toBe(readPlatformRuntimeManifest().platformVersion); - expect(listInstallationManifests(directory)[0]?.platformVersion).toBe('0.10.13'); - expect(listInstallationManifests(directory)[0]?.operation).toMatchObject({ - action: 'upgrade', - phase: 'failed', + expect(deployWorker).toHaveBeenCalled(); + const failed = listInstallationManifests(directory)[0]; + expect(failed).toMatchObject({ + platformVersion: '0.10.13', + status: 'failed', + operation: { action: 'upgrade', phase: 'failed' }, }); + expect(checkpoint).toHaveBeenLastCalledWith(failed); }); it('rolls the database schema back and forward from recorded manifests', async () => { diff --git a/packages/void/test/unit/platform-management-upgrade.test.ts b/packages/void/test/unit/platform-management-upgrade.test.ts index f3597a862..a65023059 100644 --- a/packages/void/test/unit/platform-management-upgrade.test.ts +++ b/packages/void/test/unit/platform-management-upgrade.test.ts @@ -46,6 +46,7 @@ const state = vi.hoisted(() => ({ events: [] as Array, manifest: undefined as PlatformInstallationManifest | undefined, prepareDatabase: vi.fn(), + preflightDatabaseUpgrade: vi.fn(), publishAiLogging: vi.fn(), readAdministratorSetup: vi.fn(), readAuthenticationState: vi.fn(), @@ -192,6 +193,7 @@ vi.mock('../../src/cli/platform-installer.ts', async (importOriginal) => { authoritativeManifest: state.manifest, checkpoint: vi.fn(), prepareDatabase: state.prepareDatabase, + preflightDatabaseUpgrade: state.preflightDatabaseUpgrade, publishAiLogging: state.publishAiLogging, readAdministratorSetup: state.readAdministratorSetup, readAuthenticationState: state.readAuthenticationState, @@ -216,6 +218,7 @@ vi.mock('../../src/cli/platform-installer.ts', async (importOriginal) => { expect(borrowed.publishAiLogging).toBe(state.publishAiLogging); expect(borrowed.readAuthenticationState).toBe(state.readAuthenticationState); await borrowed.readAuthenticationState!(); + dependencies.onFirstWrite?.(); state.events.push('installer-start'); dependencies.onProgress?.('Deploying the api service'); await borrowed.prepareDatabase!( @@ -405,6 +408,7 @@ describe('installed platform upgrade', () => { state.releaseDatabase.mockReset().mockResolvedValue(undefined); state.createSecrets.mockReset().mockReturnValue({}); state.events.length = 0; + state.preflightDatabaseUpgrade.mockReset().mockResolvedValue(undefined); state.prepareDatabase.mockReset().mockImplementation(async (_directory, database) => { state.events.push(`prepare:${database.schemaDigest}`); return { @@ -469,6 +473,41 @@ describe('installed platform upgrade', () => { delete process.env.VOID_PLATFORM_PROJECT_SECRET_KEYS_JSON; }); + it.each([ + { action: 'upgrade', sameRuntime: true, canResume: true }, + { action: 'upgrade', sameRuntime: false, canResume: false }, + { action: 'repair', sameRuntime: true, canResume: false }, + ] as const)( + 'reports saved $action state when upgrade is refused before writing (same runtime: $sameRuntime)', + async ({ action, sameRuntime, canResume }) => { + const installed = state.manifest!; + state.manifest = { + ...installed, + status: 'verifying', + operation: { + id: 'interrupted-operation', + fromVersion: installed.platformVersion, + toVersion: state.runtime!.manifest.platformVersion, + runtimeManifestSha256: sameRuntime ? state.runtime!.manifestSha256 : '0'.repeat(64), + action, + phase: 'verifying', + startedAt: installed.updatedAt, + updatedAt: installed.updatedAt, + }, + }; + const refusal = new Error( + 'platform: The PostgreSQL database is not at the exact forward-only schema required for runtime rollback.', + ); + vi.mocked(installPlatform).mockRejectedValueOnce(refusal); + + await expect(upgrade()).rejects.toBe(refusal); + + const recovery = vi.mocked(note).mock.calls.find(([, title]) => title === 'Recovery'); + expect(recovery?.[0]).toContain('void platform status ' + installed.id); + expect(recovery?.[0]?.includes('void platform upgrade ' + installed.id)).toBe(canResume); + }, + ); + it.each([false, true])( 'plans an upgrade with management authority instead of its runtime token (environment override: %s)', async (override) => { @@ -856,6 +895,172 @@ describe('installed platform upgrade', () => { ); }); + it('reports a refused upgrade preflight directly and releases both locks', async () => { + const refusal = new Error('platform: PostgreSQL migration history is not an exact prefix.'); + state.preflightDatabaseUpgrade.mockImplementationOnce(async () => { + state.events.push('preflight-refused'); + state.progress.clear.mockClear(); + throw refusal; + }); + vi.mocked(installPlatform).mockImplementationOnce(async (_plan, _secrets, manifest, deps) => { + const preflight = deps.upgradePreflightLock?.preflightDatabaseUpgrade; + expect(preflight).toBe(state.preflightDatabaseUpgrade); + await preflight?.( + state.runtime!.directory, + state.runtime!.manifest.database, + manifest!, + true, + ); + return expectedRejection(); + }); + + await expect(upgrade()).rejects.toBe(refusal); + + expect(state.events).toEqual(['preflight-refused', 'outer-release', 'local-release']); + expect(writeInstallationManifest).not.toHaveBeenCalled(); + expect(writePendingInstallationSecrets).not.toHaveBeenCalled(); + expect(state.progress.clear).toHaveBeenCalledOnce(); + expect(state.progress.error).not.toHaveBeenCalled(); + expect(note).not.toHaveBeenCalledWith(expect.any(String), 'Recovery'); + }); + + it('keeps enable recovery after an old Sandbox runtime is refused', async () => { + const actual = await vi.importActual( + '../../src/cli/platform-installer.ts', + ); + const manifest = state.manifest!; + const disabled = { + ...recordInstallationStep( + manifest, + { key: 'bootstrap-access:v1', completedAt: manifest.updatedAt, resultHash: 'bootstrap' }, + manifest.updatedAt, + ), + status: 'disabled' as const, + desiredState: 'disabled' as const, + safetyProtocols: { sandboxDrain: 3 as const }, + }; + state.manifest = disabled; + state.runtime = { + ...state.runtime!, + manifest: { ...state.runtime!.manifest, safetyProtocols: { sandboxDrain: 0 } }, + }; + state.createSecrets.mockReturnValue({ databaseUrl: 'postgres://database' }); + const checkpoint = vi.fn(async (_manifest: PlatformInstallationManifest) => {}); + const claimDatabase = vi.fn(async () => {}); + vi.mocked(acquirePlatformDatabaseLifecycleLock).mockResolvedValueOnce( + Object.assign(state.releaseDatabase, { + authoritativeManifest: disabled, + checkpoint, + readAuthenticationState: state.readAuthenticationState, + }), + ); + vi.mocked(installPlatform).mockImplementationOnce((plan, secrets, existing, dependencies) => + actual.installPlatform(plan, secrets, existing, { ...dependencies, claimDatabase }), + ); + + await expect( + runInstalledPlatformCommand({ + subcommand: 'enable', + selector: disabled.id, + plan: false, + runtime: '', + yes: true, + }), + ).rejects.toThrow('predates the required sandbox-drain safety protocol'); + + expect(claimDatabase).toHaveBeenCalledOnce(); + expect( + vi + .mocked(writePendingInstallationSecrets) + .mock.calls.map(([, values]) => values.databaseClaimState), + ).toEqual(['claiming', 'claimed']); + expect( + vi + .mocked(writeInstallationManifest) + .mock.calls.map(([value]) => [value.status, value.desiredState]), + ).toEqual([ + ['disabled', 'enabled'], + ['failed', 'enabled'], + ]); + expect(checkpoint).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ status: 'failed', desiredState: 'enabled' }), + ); + expect(state.progress.error).toHaveBeenCalledWith('Platform enable failed.'); + expect(note).toHaveBeenCalledWith(expect.stringContaining('void platform enable'), 'Recovery'); + expect(state.releaseDatabase).toHaveBeenCalledOnce(); + expect(state.events.at(-1)).toBe('local-release'); + }); + + it('shows upgrade recovery after a database re-claim fails with a saved credential update', async () => { + const actual = await vi.importActual( + '../../src/cli/platform-installer.ts', + ); + const { createPlatformInstallationSecrets } = + await import('../../src/cli/platform-installer-secrets.ts'); + const registry = await vi.importActual( + '../../src/cli/platform-registry.ts', + ); + const directory = await mkdtemp(join(tmpdir(), 'void-upgrade-claim-refusal-')); + vi.stubEnv('VOID_PLATFORM_RECOVERY_KEY', Buffer.alloc(32, 7).toString('base64')); + vi.stubEnv('VOID_PLATFORM_REGISTRY_DIR', directory); + const manifest = state.manifest!; + const installation = recordInstallationStep( + manifest, + { key: 'bootstrap-access:v1', completedAt: manifest.updatedAt, resultHash: 'bootstrap' }, + manifest.updatedAt, + ); + state.manifest = installation; + registry.writeInstallationManifest(installation, directory); + const createSecretsInput = vi.fn((input) => + createPlatformInstallationSecrets({ ...input, githubClientSecret: 'replacement' }), + ); + state.createSecrets.mockImplementationOnce(createSecretsInput); + vi.mocked(writePendingInstallationSecrets).mockImplementation( + (saved, values, _dir, onWritten) => { + registry.writePendingInstallationSecrets(saved, values, directory, onWritten); + }, + ); + const refusal = new Error('too many clients already'); + const claimDatabase = vi.fn(async () => { + throw refusal; + }); + vi.mocked(installPlatform).mockImplementationOnce((plan, secrets, existing, dependencies) => + actual.installPlatform(plan, secrets, existing, { ...dependencies, claimDatabase }), + ); + + try { + await expect(upgrade()).rejects.toBe(refusal); + expect(claimDatabase).toHaveBeenCalledOnce(); + const pending = registry.readInstallationRecoverySecrets(installation, directory)!; + expect(pending.databaseClaimState).toBe('failed'); + const retry = createPlatformInstallationSecrets({ + ...createSecretsInput.mock.calls[0][0], + checkpoint: pending, + githubClientSecret: '', + }); + expect(retry.workerSecretUpdates).toEqual({}); + expect(retry.pendingWorkerSecretUpdateIntent?.updates).toEqual({ + GITHUB_CLIENT_SECRET: 'replacement', + }); + expect( + registry.platformWorkerSecretUpdateIntentState( + installation, + retry.pendingWorkerSecretUpdateIntent!, + ), + ).toBe('active'); + expect(writeInstallationManifest).not.toHaveBeenCalled(); + expect(state.progress.error).toHaveBeenCalledWith('Platform upgrade failed.'); + expect(note).toHaveBeenCalledWith( + expect.stringContaining('void platform upgrade'), + 'Recovery', + ); + expect(state.events).toEqual(['outer-release', 'local-release']); + } finally { + vi.mocked(writePendingInstallationSecrets).mockReset(); + await rm(directory, { recursive: true, force: true }); + } + }); + it('releases the held lifecycle lock when database preparation fails', async () => { state.prepareDatabase.mockImplementationOnce(async () => { state.events.push('prepare:failed'); @@ -1971,6 +2176,7 @@ describe('installed platform upgrade', () => { const installer = vi.mocked(installPlatform).getMockImplementation()!; vi.mocked(installPlatform).mockImplementation( async (plan, _secrets, existing, dependencies) => { + dependencies.onFirstWrite?.(); state.events.push('installer-start', 'create:isr-cache-kv'); await dependencies.uploadOutsideChanges!([ {