Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/guide/platform/administration/zero-trust.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<your domain>`, 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.<your domain>`. 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

Expand Down
6 changes: 3 additions & 3 deletions docs/guide/platform/installation/maintenance.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
7 changes: 4 additions & 3 deletions docs/reference/cli/platform-zero-trust.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 9 additions & 2 deletions packages/void/src/cli/operator-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ export class OperatorClient {
body?: Record<string, unknown>;
signal?: AbortSignal;
timeoutMs?: number;
/** Replaces the generic note when a mutation times out or loses its connection. */
unknownOutcome?: string;
} = {},
): Promise<Record<string, unknown>> {
if (
Expand Down Expand Up @@ -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',
);
}
Expand Down
20 changes: 20 additions & 0 deletions packages/void/src/cli/operator-cmd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>, 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;
Expand Down Expand Up @@ -788,10 +800,18 @@ export async function runOperatorCommand(args: OperatorArgs): Promise<void> {
: {}),
...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'));
Expand Down
82 changes: 82 additions & 0 deletions packages/void/test/unit/operator-cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>) {
const output = stubOperator(
vi
.fn<typeof fetch>()
.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<typeof fetch>()
.mockResolvedValueOnce(
Response.json({ dryRun: true, action: 'zero-trust.reconcile', target: 'platform' }),
)
.mockImplementationOnce(async (_input, init) => {
const signal = init?.signal as AbortSignal;
return new Promise<Response>((_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<string, unknown>, flags: Array<string> = []) {
connect('https://one.example');
Expand Down
35 changes: 29 additions & 6 deletions platform/packages/api/src/zero-trust/installation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 };
}
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -375,16 +382,25 @@ async function claimReconcileOperation(db: Db): Promise<ZeroTrustConfiguration>
});
}

async function runClaimedOperation(
env: ApiEnv['Bindings'],
db: Db,
configuration: ZeroTrustConfiguration,
): Promise<ZeroTrustConfiguration> {
return configuration.operation?.kind === 'disable'
? runDisableOperation(env, db, configuration)
: runConfigureOperation(env, db, configuration);
}

export async function reconcilePlatformZeroTrust(
env: ApiEnv['Bindings'],
db: Db,
): Promise<ReturnType<typeof redactedZeroTrustConfiguration>> {
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(
Expand Down Expand Up @@ -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));
}

Expand All @@ -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;
}
Loading