From 67a30f4af7ddddf487434b31bf6169c9b4e162ce Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 10:48:19 +0800 Subject: [PATCH] fix(zero-trust): run platform changes in short steps so the cron resumes them A platform Zero Trust reconcile, configure or disable ran the whole operation inside one request. On a 40-project install that took longer than the CLI's 300 s timeout; the cancelled request kept its 15-minute lease, so the scheduled job could not continue the change until the lease ran out. Each run now stops taking projects after 60 s (always after at least one) and releases the operation, the lease is 5 minutes, and a request arms the two-minute cron as soon as it holds the lease. The CLI says the change is still running and how to follow it. The docs describe the health-check exception as /health and the paths under it. Co-Authored-By: Claude Opus 5.5 --- .../platform/administration/zero-trust.md | 2 +- .../platform/installation/maintenance.md | 6 +- docs/reference/cli/platform-zero-trust.md | 7 +- packages/void/src/cli/operator-client.ts | 11 +- packages/void/src/cli/operator-cmd.ts | 20 +++ packages/void/test/unit/operator-cli.test.ts | 82 +++++++++ .../api/src/zero-trust/installation.ts | 35 +++- .../packages/api/src/zero-trust/operation.ts | 49 +++++- .../zero-trust-operation-failures.test.ts | 43 +++++ .../zero-trust-operation-generation.test.ts | 166 ++++++++++++++++++ 10 files changed, 397 insertions(+), 24 deletions(-) diff --git a/docs/guide/platform/administration/zero-trust.md b/docs/guide/platform/administration/zero-trust.md index 28cc4c1d8..303812c85 100644 --- a/docs/guide/platform/administration/zero-trust.md +++ b/docs/guide/platform/administration/zero-trust.md @@ -22,7 +22,7 @@ choose to protect apps. To renew their token in Admin, leave the policy fields b - A Cloudflare Zero Trust organization in the account that hosts the platform, with the identity providers and reusable Access policies you want to use. Select at least one Allow policy that matches people by identity. Void rejects Bypass and Service Auth policies, and rules that allow Everyone or any service token. - A Cloudflare API token for that account with **Access: Apps and Policies Write** and **Access: Organizations, Identity Providers, and Groups Read**. Void keeps it separate from the platform runtime token, stores it encrypted, and never shows it again. - Free Access applications in the account. Cloudflare's default limit is 500 per account. Count the applications you already manage outside Void, then add the ones Void needs, as described in [Access Applications Void Creates](#access-applications-void-creates). -- Platform API, proxy, and email gateway hostnames outside the project application domain. Configuration is rejected when project protection would cover one of them. Any other hostname under the project application domain also asks for sign-in, except the `/health` path of `void-platform-health.`, which Void keeps open for its health checks and never serves from a project. New projects cannot use that name. A project that already uses it keeps every other path, protected or public like any other project. +- Platform API, proxy, and email gateway hostnames outside the project application domain. Configuration is rejected when project protection would cover one of them. Any other hostname under the project application domain also asks for sign-in, except `/health` and the paths under it on `void-platform-health.`. Void keeps these open for its health checks and answers them itself, never from a project. New projects cannot use that name. A project that already uses it keeps its other paths, protected or public like any other project, but cannot serve paths that start with `/health`. ## Enable Zero Trust diff --git a/docs/guide/platform/installation/maintenance.md b/docs/guide/platform/installation/maintenance.md index 156a0953c..2ca804732 100644 --- a/docs/guide/platform/installation/maintenance.md +++ b/docs/guide/platform/installation/maintenance.md @@ -30,9 +30,9 @@ that the application covers the printed API and proxy origins. A Cloudflare management API token does not authenticate an Access-protected HTTP request. For automatic setup, resuming also creates or verifies an Access exception -limited to `/health` on the reserved dispatch health hostname. Void still requires -its private probe token on that endpoint; requests without it cannot reach an -application. This lets installation check routing while employee protection and +limited to `/health` and the paths under it on the reserved dispatch health +hostname. Void still requires its private probe token on that endpoint; requests +without it cannot reach an application. This lets installation check routing while employee protection and account-wide Default-Deny remain enabled. It does not bypass Access for an entire Worker or for deployed apps. diff --git a/docs/reference/cli/platform-zero-trust.md b/docs/reference/cli/platform-zero-trust.md index 0a3add818..2a9d2b5dc 100644 --- a/docs/reference/cli/platform-zero-trust.md +++ b/docs/reference/cli/platform-zero-trust.md @@ -50,9 +50,10 @@ hosts the platform. Omit `--protect-new-projects` to make new projects public by default. `--existing-projects` is required when you enable Zero Trust and rejected once it is enabled; later configuration changes keep each project's protection. `status` reports saved state; `--check` also compares it with -Cloudflare Access. If status remains `configuring` or `disabling`, run -`void platform zero-trust reconcile` to resume the saved operation. Protected -projects support up to 100 custom domains. +Cloudflare Access. Large changes run in steps: `configure`, `reconcile`, and +`disable` can return while status is still `configuring` or `disabling`. Void +continues the change within a few minutes; run `void platform zero-trust reconcile` +to continue it right away. Protected projects support up to 100 custom domains. The token needs **Access: Apps and Policies Write** plus **Access: Organizations, Identity Providers, and Groups Read**, scoped to the platform's diff --git a/packages/void/src/cli/operator-client.ts b/packages/void/src/cli/operator-client.ts index 93c0a26a8..04d5e09b6 100644 --- a/packages/void/src/cli/operator-client.ts +++ b/packages/void/src/cli/operator-client.ts @@ -50,6 +50,8 @@ export class OperatorClient { body?: Record; signal?: AbortSignal; timeoutMs?: number; + /** Replaces the generic note when a mutation times out or loses its connection. */ + unknownOutcome?: string; } = {}, ): Promise> { if ( @@ -103,14 +105,19 @@ export class OperatorClient { if (options.signal?.aborted) { throw error; } + const next = + options.method === 'POST' + ? (options.unknownOutcome ?? + 'Its outcome may be unknown; inspect platform state before retrying.') + : 'Check connectivity and try again.'; if (timeoutController.signal.aborted) { throw new OperatorClientError( - `Operator request exceeded the ${timeoutMs / 1000}-second timeout. ${options.method === 'POST' ? 'Its outcome may be unknown; inspect platform state before retrying.' : 'Check connectivity and try again.'}`, + `Operator request exceeded the ${timeoutMs / 1000}-second timeout. ${next}`, 'request_timeout', ); } throw new OperatorClientError( - `Operator request to ${this.origin} failed. ${options.method === 'POST' ? 'Its outcome may be unknown; inspect platform state before retrying.' : 'Check connectivity and try again.'}`, + `Operator request to ${this.origin} failed. ${next}`, 'connection_failed', ); } diff --git a/packages/void/src/cli/operator-cmd.ts b/packages/void/src/cli/operator-cmd.ts index 2517e07f2..4c4de9c8a 100644 --- a/packages/void/src/cli/operator-cmd.ts +++ b/packages/void/src/cli/operator-cmd.ts @@ -168,10 +168,22 @@ export function output(value: unknown, json: boolean): void { console.log(json ? JSON.stringify(value) : humanLines(value).join('\n')); } +const ZERO_TRUST_STATUS_COMMAND = '`void platform zero-trust status`'; + export function outputMutation(result: Record, args: OperatorArgs): void { output(result, args.json); // Some successful HTTP responses checkpoint work rather than complete it. const configuration = result.configuration as { status?: string } | undefined; + if ( + !args.json && + args.group === 'zero-trust' && + (configuration?.status === 'configuring' || configuration?.status === 'disabling') + ) { + // Each request applies one step and releases the saved operation to scheduled maintenance. + console.log( + `Zero Trust is still applying this change. Void continues it within a few minutes; follow it with ${ZERO_TRUST_STATUS_COMMAND}.`, + ); + } const project = result.project as { state?: string; last_error?: string | null } | undefined; // A public request that is still open has not made the project public. const publicRequest = result.publicRequest as { state?: string } | null | undefined; @@ -788,10 +800,18 @@ export async function runOperatorCommand(args: OperatorArgs): Promise { : {}), ...recoveryFence, }; + const zeroTrustOperation = + args.group === 'zero-trust' && + (args.action === 'configure' || args.action === 'reconcile' || args.action === 'disable'); const result = await client.request(args.path, { method: 'POST', body, timeoutMs: args.timeoutMs, + ...(zeroTrustOperation + ? { + unknownOutcome: `Void continues a started Zero Trust change within a few minutes; follow it with ${ZERO_TRUST_STATUS_COMMAND} before retrying.`, + } + : {}), }); if (aiLogging && !args.json) { console.log(aiLoggingChangeLines(aiLoggingProjectId(args), result).join('\n')); diff --git a/packages/void/test/unit/operator-cli.test.ts b/packages/void/test/unit/operator-cli.test.ts index 742a5b1d8..6264fd2a9 100644 --- a/packages/void/test/unit/operator-cli.test.ts +++ b/packages/void/test/unit/operator-cli.test.ts @@ -84,6 +84,88 @@ describe('operator text output labels', () => { }); }); +describe('zero-trust operator output', () => { + function stubOperator(fetcher: typeof fetch) { + connect('https://one.example'); + vi.stubEnv('VOID_API_URL', 'https://one.example'); + vi.stubEnv('VOID_OPERATOR_TOKEN', 'operator'); + vi.spyOn(process.stderr, 'write').mockReturnValue(true); + const details = vi.spyOn(console, 'log').mockImplementation(() => {}); + let terminal = ''; + vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => { + terminal += String(chunk); + return true; + }); + vi.stubGlobal('fetch', fetcher); + return { + printed: () => details.mock.calls.map(([line]) => String(line)).join('\n'), + terminal: () => stripVTControlCharacters(terminal), + }; + } + + async function reconcile(configuration: Record) { + const output = stubOperator( + vi + .fn() + .mockResolvedValueOnce( + Response.json({ dryRun: true, action: 'zero-trust.reconcile', target: 'platform' }), + ) + .mockResolvedValueOnce(Response.json({ ok: true, configuration })), + ); + await runOperatorCommand(parseOperatorArgs(['zero-trust', 'reconcile', '--yes'])); + return output; + } + + it('says a checkpointed change keeps running and how to follow it', async () => { + const output = await reconcile({ + status: 'configuring', + operation: { kind: 'reconcile', phase: 'projects', existingProjects: null }, + lastError: null, + }); + expect(output.printed()).toContain( + 'Zero Trust is still applying this change. Void continues it within a few minutes; follow it with `void platform zero-trust status`.', + ); + expect(output.terminal()).not.toContain('✓'); + }); + + it('reports a finished change as completed', async () => { + const output = await reconcile({ status: 'ready', operation: null, lastError: null }); + expect(output.printed()).not.toContain('still applying'); + expect(output.terminal()).toContain('✓ Platform zero-trust reconcile completed.'); + }); + + it('points to status instead of an unknown outcome when the request times out', async () => { + vi.useFakeTimers(); + try { + stubOperator( + vi + .fn() + .mockResolvedValueOnce( + Response.json({ dryRun: true, action: 'zero-trust.reconcile', target: 'platform' }), + ) + .mockImplementationOnce(async (_input, init) => { + const signal = init?.signal as AbortSignal; + return new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => reject(signal.reason), { once: true }); + }); + }), + ); + const command = runOperatorCommand( + parseOperatorArgs(['zero-trust', 'reconcile', '--yes', '--timeout', '2']), + ); + const failure = expect(command).rejects.toMatchObject({ + code: 'request_timeout', + message: + 'Operator request exceeded the 2-second timeout. Void continues a started Zero Trust change within a few minutes; follow it with `void platform zero-trust status` before retrying.', + }); + await vi.advanceTimersByTimeAsync(2000); + await failure; + } finally { + vi.useRealTimers(); + } + }); +}); + describe('operator mutation completion output', () => { async function runMutation(result: Record, flags: Array = []) { connect('https://one.example'); diff --git a/platform/packages/api/src/zero-trust/installation.ts b/platform/packages/api/src/zero-trust/installation.ts index 019445d3a..f92c3de41 100644 --- a/platform/packages/api/src/zero-trust/installation.ts +++ b/platform/packages/api/src/zero-trust/installation.ts @@ -6,6 +6,7 @@ import { import type { PlatformApplication } from '@void/platform'; import type { Db } from '../db.ts'; import type { ApiEnv } from '../env.ts'; +import { armFastMaintenance } from '../fast-maintenance.ts'; import { getPlatformSetting, setPlatformSetting } from '../platform-settings.ts'; import { encryptPlatformCredential } from '../project-secrets.ts'; import { assertPublicGateOff } from '../security/public-gate.ts'; @@ -104,6 +105,9 @@ export async function activatePlatformApplication( if (!claim.configuration) { return { ready: claim.ready }; } + // A cancelled request never reaches the after-request hook, so arm the two-minute + // cron here; it resumes the operation once the lease frees. + await armFastMaintenance(env); const completed = await runConfigureOperation(env, db, claim.configuration); return { ready: completed.operation === null }; } @@ -328,6 +332,9 @@ export async function configurePlatformZeroTrust( }, input.publicAccess ? { refuseWhileGateOn: env } : undefined, ); + // A cancelled request never reaches the after-request hook, so arm the two-minute + // cron here; it resumes the operation once the lease frees. + await armFastMaintenance(env); return redactedZeroTrustConfiguration( configuration.operation?.kind === 'disable' ? await runDisableOperation(env, db, configuration) @@ -375,16 +382,25 @@ async function claimReconcileOperation(db: Db): Promise }); } +async function runClaimedOperation( + env: ApiEnv['Bindings'], + db: Db, + configuration: ZeroTrustConfiguration, +): Promise { + return configuration.operation?.kind === 'disable' + ? runDisableOperation(env, db, configuration) + : runConfigureOperation(env, db, configuration); +} + export async function reconcilePlatformZeroTrust( env: ApiEnv['Bindings'], db: Db, ): Promise> { const configuration = await claimReconcileOperation(db); - const result = - configuration.operation?.kind === 'disable' - ? await runDisableOperation(env, db, configuration) - : await runConfigureOperation(env, db, configuration); - return redactedZeroTrustConfiguration(result); + // A cancelled request never reaches the after-request hook, so arm the two-minute + // cron here; it resumes the operation once the lease frees. + await armFastMaintenance(env); + return redactedZeroTrustConfiguration(await runClaimedOperation(env, db, configuration)); } export async function disablePlatformZeroTrust( @@ -426,6 +442,9 @@ export async function disablePlatformZeroTrust( }, { refuseWhileGateOn: env }, ); + // A cancelled request never reaches the after-request hook, so arm the two-minute + // cron here; it resumes the operation once the lease frees. + await armFastMaintenance(env); return redactedZeroTrustConfiguration(await runDisableOperation(env, db, configuration)); } @@ -449,6 +468,10 @@ export async function resumePlatformZeroTrustOperation( ) { return false; } - await reconcilePlatformZeroTrust(env, db); + // A run that stopped at its step limit leaves the rest to the two-minute cron, + // including after an hourly retry of a failed operation. + if ((await runClaimedOperation(env, db, await claimReconcileOperation(db))).operation) { + await armFastMaintenance(env); + } return true; } diff --git a/platform/packages/api/src/zero-trust/operation.ts b/platform/packages/api/src/zero-trust/operation.ts index 702ff8a8a..02232460f 100644 --- a/platform/packages/api/src/zero-trust/operation.ts +++ b/platform/packages/api/src/zero-trust/operation.ts @@ -52,8 +52,25 @@ import { updateProjectState, } from './state.ts'; -const OPERATION_LEASE_MS = 15 * 60 * 1000; +// A live runner renews the lease after every project. A lease left by a +// cancelled request or a killed invocation frees within this time, and the +// two-minute cron then resumes the operation. Revision checks keep a slow +// runner that lost it from writing over the next one. +const OPERATION_LEASE_MS = 5 * 60 * 1000; const MAX_PROJECTS_PER_RUN = 100; +// One request or cron run stops taking new projects after this long and +// releases the operation, well inside the CLI timeout and the cron wall limit. +const OPERATION_STEP_MS = 60_000; + +/** + * True when this run should release the operation for the next one. A run + * always finishes at least one project, so every run makes progress. + */ +function stepLimit(projectsProcessed: number, stepEndsAt: number): boolean { + return ( + projectsProcessed >= MAX_PROJECTS_PER_RUN || (projectsProcessed > 0 && Date.now() >= stepEndsAt) + ); +} async function setInitialProjectProtection( db: Db, @@ -376,6 +393,7 @@ export async function runConfigureOperation( ): Promise { let configuration = initial; let projectsProcessed = 0; + const stepEndsAt = Date.now() + OPERATION_STEP_MS; const routingBudget: RoutingBudget = { remaining: MAX_ROUTING_KEYS_PER_RUN }; try { env = await resolveZeroTrustApplicationEnvironment(env, db, configuration); @@ -413,8 +431,11 @@ export async function runConfigureOperation( ); projectsProcessed += 1; configuration = await heartbeatConfiguration(db, configuration); + if (stepLimit(projectsProcessed, stepEndsAt)) { + break; + } } - if (projectsProcessed >= MAX_PROJECTS_PER_RUN) { + if (stepLimit(projectsProcessed, stepEndsAt)) { return await releaseOperation(db, configuration); } } @@ -433,8 +454,11 @@ export async function runConfigureOperation( ); projectsProcessed += 1; configuration = await heartbeatConfiguration(db, configuration); + if (stepLimit(projectsProcessed, stepEndsAt)) { + break; + } } - if (projectsProcessed >= MAX_PROJECTS_PER_RUN) { + if (stepLimit(projectsProcessed, stepEndsAt)) { return await releaseOperation(db, configuration); } configuration = await advanceOperation( @@ -470,8 +494,11 @@ export async function runConfigureOperation( if (routingBudget.exhausted || routingBudget.remaining === 0) { return await releaseOperation(db, configuration); } + if (stepLimit(projectsProcessed, stepEndsAt)) { + break; + } } - if (projectsProcessed >= MAX_PROJECTS_PER_RUN) { + if (stepLimit(projectsProcessed, stepEndsAt)) { return await releaseOperation(db, configuration); } configuration = await advanceOperation(db, configuration, 'wildcard'); @@ -557,11 +584,11 @@ export async function runConfigureOperation( } projectsProcessed += 1; configuration = await heartbeatConfiguration(db, configuration); - if (projectsProcessed >= MAX_PROJECTS_PER_RUN) { + if (stepLimit(projectsProcessed, stepEndsAt)) { break; } } - if (stoppedForRoutingBudget || projectsProcessed >= MAX_PROJECTS_PER_RUN) { + if (stoppedForRoutingBudget || stepLimit(projectsProcessed, stepEndsAt)) { return await releaseOperation(db, configuration); } continue; @@ -668,6 +695,7 @@ export async function runDisableOperation( ): Promise { let configuration = initial; let projectsProcessed = 0; + const stepEndsAt = Date.now() + OPERATION_STEP_MS; const routingBudget: RoutingBudget = { remaining: MAX_ROUTING_KEYS_PER_RUN }; try { const client = await clientForConfiguration(env, configuration); @@ -698,11 +726,11 @@ export async function runDisableOperation( ); projectsProcessed += 1; configuration = await heartbeatConfiguration(db, configuration); - if (projectsProcessed >= MAX_PROJECTS_PER_RUN) { + if (stepLimit(projectsProcessed, stepEndsAt)) { break; } } - if (stoppedForRoutingBudget || projectsProcessed >= MAX_PROJECTS_PER_RUN) { + if (stoppedForRoutingBudget || stepLimit(projectsProcessed, stepEndsAt)) { return await releaseOperation(db, configuration); } continue; @@ -753,8 +781,11 @@ export async function runDisableOperation( ); projectsProcessed += 1; configuration = await heartbeatConfiguration(db, configuration); + if (stepLimit(projectsProcessed, stepEndsAt)) { + break; + } } - if (projectsProcessed >= MAX_PROJECTS_PER_RUN) { + if (stepLimit(projectsProcessed, stepEndsAt)) { return await releaseOperation(db, configuration); } configuration = await withZeroTrustOperationLock(db, configuration, async (lockedDb) => { diff --git a/platform/packages/api/test/integration/zero-trust-operation-failures.test.ts b/platform/packages/api/test/integration/zero-trust-operation-failures.test.ts index bbee9f7bf..52d3bbad5 100644 --- a/platform/packages/api/test/integration/zero-trust-operation-failures.test.ts +++ b/platform/packages/api/test/integration/zero-trust-operation-failures.test.ts @@ -278,6 +278,49 @@ describe('Zero Trust operation failures', () => { }); }); + it('does not arm the two-minute cron for an hourly retry that fails again', async () => { + const owner = await createTestUser(env.db, 'hourly-retry-owner'); + await createTestProject(env.db, owner.id, 'hourly-retry-project'); + const cloudflare = accessApi(); + vi.stubGlobal('fetch', cloudflare.fetcher); + const platform = bindings(); + await configurePlatformZeroTrust(platform, env.db, configurationInput()); + const saved = (await readZeroTrustConfigurationStrict(env.db))!; + await env.db + .update(platformSettings) + .set({ + value: { + ...saved, + revision: saved.revision + 1, + lastError: 'Access token was revoked', + operation: { + id: 'failed-operation', + kind: 'reconcile', + phase: 'seed', + owner: null, + leaseExpiresAt: null, + startedAt: new Date().toISOString(), + existingProjects: null, + }, + }, + }) + .where(eq(platformSettings.key, 'zeroTrust.configuration')); + cloudflare.revoke(true); + await env.ROUTING.delete(FAST_MAINTENANCE_KEY); + + await scheduled( + { cron: '0 * * * *', scheduledTime: Date.now() } as ScheduledController, + platform, + createMockExecutionContext(), + ); + expect(await readZeroTrustConfigurationStrict(env.db)).toMatchObject({ + lastError: expect.stringContaining('Access token was revoked'), + operation: { id: 'failed-operation', owner: null }, + }); + // Two-minute ticks would only skip the failed operation while keeping the database awake. + expect(await env.ROUTING.get(FAST_MAINTENANCE_KEY)).toBeNull(); + }); + it('finishes configuration around a project over the protected domain cap', async () => { const owner = await createTestUser(env.db, 'domain-cap-owner'); const large = await createTestProject(env.db, owner.id, 'domain-cap-large'); diff --git a/platform/packages/api/test/integration/zero-trust-operation-generation.test.ts b/platform/packages/api/test/integration/zero-trust-operation-generation.test.ts index 6e63d05c7..39e4d7645 100644 --- a/platform/packages/api/test/integration/zero-trust-operation-generation.test.ts +++ b/platform/packages/api/test/integration/zero-trust-operation-generation.test.ts @@ -10,6 +10,7 @@ import { vi, } from 'vite-plus/test'; import type { ApiEnv } from '../../src/env.ts'; +import { FAST_MAINTENANCE_KEY } from '../../src/fast-maintenance.ts'; import { domains, platformSettings } from '../../src/schema.ts'; import { readZeroTrustConfigurationStrict, @@ -20,12 +21,16 @@ import { configurePlatformZeroTrust, disablePlatformZeroTrust, reconcilePlatformZeroTrust, + resumePlatformZeroTrustOperation, } from '../../src/zero-trust/installation.ts'; +import { leaseExpiresAt, operationStartedAt } from '../../src/zero-trust/operation.ts'; import { reconcileProjectZeroTrustDomains, initializeNewProjectZeroTrust, } from '../../src/zero-trust/project.ts'; import { resolveProjectZeroTrustRouting } from '../../src/zero-trust/routing.ts'; +// oxlint-disable-next-line import/no-namespace -- The test replaces or spies on members of the module object. +import * as zeroTrustState from '../../src/zero-trust/state.ts'; import { getProjectZeroTrustState } from '../../src/zero-trust/state.ts'; import { clearTables, @@ -472,3 +477,164 @@ describe('Zero Trust operation completion', () => { }, ); }); + +describe('Zero Trust operation steps', () => { + /** Date.now that only moves forward, by real time plus whatever the test adds. */ + function advancingClock() { + const realNow = Date.now.bind(Date); + let offset = 0; + vi.spyOn(Date, 'now').mockImplementation(() => realNow() + offset); + return { + advance(ms: number) { + offset += ms; + }, + }; + } + + /** Each project write takes a little over a minute, as on a slow provider. */ + function slowProjectWrites(clock: ReturnType): void { + const original = zeroTrustState.putProjectState; + vi.spyOn(zeroTrustState, 'putProjectState').mockImplementation(async (...args) => { + clock.advance(61_000); + return original(...args); + }); + } + + async function protectedInstallation(prefix: string) { + const owner = await createTestUser(env.db, `${prefix}-owner`); + const projects = []; + for (let index = 0; index < 3; index++) { + projects.push(await createTestProject(env.db, owner.id, `${prefix}-project-${index}`)); + } + const cloudflare = accessApi(); + const platform = bindings(); + vi.stubGlobal('fetch', cloudflare.fetcher); + await configurePlatformZeroTrust(platform, env.db, configurationInput()); + return { platform, projects }; + } + + async function resumeUntilDone(platform: ApiEnv['Bindings']): Promise { + for (let run = 0; run < 5; run++) { + if (!(await readZeroTrustConfigurationStrict(env.db))!.operation) { + return; + } + expect(await resumePlatformZeroTrustOperation(platform, env.db)).toBe(true); + } + throw new Error('The Zero Trust operation did not finish.'); + } + + it('stops a long reconcile at its time budget and lets scheduled maintenance finish it', async () => { + const { platform, projects } = await protectedInstallation('steps-reconcile'); + slowProjectWrites(advancingClock()); + + expect(await reconcilePlatformZeroTrust(platform, env.db)).toMatchObject({ + status: 'configuring', + operation: { kind: 'reconcile', phase: 'projects' }, + }); + const saved = (await readZeroTrustConfigurationStrict(env.db))!; + expect(saved.operation).toMatchObject({ owner: null, leaseExpiresAt: null }); + const operationId = saved.operation!.id; + const pending = await Promise.all( + projects.map((project) => getProjectZeroTrustState(env.db, project.id)), + ); + expect(pending.filter((row) => row?.reconciled_operation === operationId)).toHaveLength(1); + + // A scheduled step that leaves work keeps the two-minute cron on for the rest. + await env.ROUTING.delete(FAST_MAINTENANCE_KEY); + expect(await resumePlatformZeroTrustOperation(platform, env.db)).toBe(true); + expect((await readZeroTrustConfigurationStrict(env.db))!.operation).not.toBeNull(); + expect(await env.ROUTING.get(FAST_MAINTENANCE_KEY)).not.toBeNull(); + + await resumeUntilDone(platform); + expect(zeroTrustConfigurationStatus((await readZeroTrustConfigurationStrict(env.db))!)).toBe( + 'ready', + ); + for (const project of projects) { + expect(await getProjectZeroTrustState(env.db, project.id)).toMatchObject({ + status: 'ready', + effective_protected: true, + reconciled_operation: operationId, + }); + } + }); + + it('stops a long disable at its time budget and lets scheduled maintenance finish it', async () => { + const { platform, projects } = await protectedInstallation('steps-disable'); + slowProjectWrites(advancingClock()); + + expect(await disablePlatformZeroTrust(platform, env.db)).toMatchObject({ + status: 'disabling', + operation: { kind: 'disable', phase: 'projects' }, + }); + expect((await readZeroTrustConfigurationStrict(env.db))!.operation).toMatchObject({ + owner: null, + leaseExpiresAt: null, + }); + + await resumeUntilDone(platform); + expect(await readZeroTrustConfigurationStrict(env.db)).toMatchObject({ + enabled: false, + operation: null, + lastError: null, + }); + for (const project of projects) { + expect(await getProjectZeroTrustState(env.db, project.id)).toMatchObject({ + status: 'ready', + effective_protected: false, + }); + } + }); + + it('arms the two-minute cron before a request starts the work', async () => { + const { platform } = await protectedInstallation('steps-armed'); + await env.ROUTING.delete(FAST_MAINTENANCE_KEY); + // A request cancelled mid-run never reaches the after-request hook; a failed + // run stands in for it here, since both stop before the step ends. + vi.stubGlobal('fetch', async () => { + throw new TypeError('network connection lost'); + }); + + await expect(reconcilePlatformZeroTrust(platform, env.db)).rejects.toThrow(TypeError); + expect(await env.ROUTING.get(FAST_MAINTENANCE_KEY)).not.toBeNull(); + }); + + it('resumes an operation left by a cancelled request within five minutes', async () => { + const { platform, projects } = await protectedInstallation('steps-abandoned'); + const saved = (await readZeroTrustConfigurationStrict(env.db))!; + // A request that claimed the operation and then stopped, so it never released it. + await env.db + .update(platformSettings) + .set({ + value: { + ...saved, + revision: saved.revision + 1, + operation: { + id: 'abandoned-operation', + kind: 'reconcile', + phase: 'projects', + owner: 'cancelled-request', + leaseExpiresAt: leaseExpiresAt(), + startedAt: await operationStartedAt(env.db), + existingProjects: null, + }, + }, + }) + .where(eq(platformSettings.key, 'zeroTrust.configuration')); + const clock = advancingClock(); + + clock.advance(5 * 60_000 - 1000); + expect(await resumePlatformZeroTrustOperation(platform, env.db)).toBe(false); + clock.advance(2000); + expect(await resumePlatformZeroTrustOperation(platform, env.db)).toBe(true); + expect(await readZeroTrustConfigurationStrict(env.db)).toMatchObject({ + operation: null, + lastError: null, + }); + for (const project of projects) { + expect(await getProjectZeroTrustState(env.db, project.id)).toMatchObject({ + status: 'ready', + reconciled_operation: 'abandoned-operation', + }); + } + }); +});