diff --git a/.changeset/remove-cf-vite.md b/.changeset/remove-cf-vite.md new file mode 100644 index 0000000000..c1bfd052b4 --- /dev/null +++ b/.changeset/remove-cf-vite.md @@ -0,0 +1,9 @@ +--- +"@cloudflare/vite-plugin": minor +--- + +Remove the experimental internal `cf-vite` executable + +Run development and builds through Vite's CLI or your framework's own commands instead. Configure `cloudflare({ remoteBindings: false })` to disable remote bindings. + +When using the plugin through `cf`, upgrade to `cf@1.0.0-rc.0` or newer. This is the first cf release that runs the project's native Vite or Vite+ commands instead of the removed executable. diff --git a/.changeset/vpc-custom-certificates.md b/.changeset/vpc-custom-certificates.md deleted file mode 100644 index c3d3373ae3..0000000000 --- a/.changeset/vpc-custom-certificates.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -"wrangler": minor ---- - -Add custom CA and client certificate references to Workers VPC service TLS settings - -Workers VPC (open beta) service create and update commands accept `--certificate-authority` and `--client-certificate` UUIDs. Use either flag alone or both together. Whenever you supply either reference, explicitly choose `--cert-verification-mode`: - -- `verify_full`: verify the origin certificate chain and hostname (the platform default). -- `verify_ca`: verify the chain but skip hostname verification, weakening origin identity checks. -- `disabled`: do not verify the origin certificate; this allows connections to impersonated origins and is unsafe for production. - -For HTTP services, these settings apply to HTTPS connections, not plaintext HTTP. TCP services can use them for upstream TLS, including PostgreSQL. - -TLS settings are per-service only: host and resolver networks have no TLS settings or inheritance. Omitting TLS settings uses platform defaults (certificate chain and hostname verification). Explicit mode-only configuration, including `verify_full`, is accepted. A custom CA cannot be combined with `disabled`; a client certificate without a custom CA can. - -Upload certificates using the existing commands, then use the returned IDs below. Replace ``, ``, ``, and service IDs with your own values; certificate references must be valid UUIDs. Upload replacement certificates the same way before rotating their references. - -```sh -pnpm exec wrangler cert upload certificate-authority --ca-cert ./ca.pem --name private-ca -pnpm exec wrangler cert upload mtls-certificate --cert ./client.pem --key ./client-key.pem --name private-client -``` - -Create an HTTPS service with both a custom trust chain and an mTLS client certificate, or a PostgreSQL TCP service with only a custom CA: - -```sh -pnpm exec wrangler vpc service create private-web \ - --type http --https-port 443 --ipv4 10.0.0.10 --tunnel-id \ - --certificate-authority --client-certificate \ - --cert-verification-mode verify_full - -pnpm exec wrangler vpc service create private-db \ - --type tcp --tcp-port 5432 --app-protocol postgresql \ - --hostname db.internal.example --resolver-ips 10.0.0.53 --tunnel-id \ - --certificate-authority --cert-verification-mode verify_full -``` - -For client-certificate-only configuration, use `--client-certificate --cert-verification-mode verify_full` instead of the certificate flags in either create command. - -Updates replace the complete service configuration, including TLS settings, in a single request, the same as `cf workers-vpc services update`. Pass every TLS option the service should keep: certificate references and the verification mode that you omit are cleared, and an update without TLS options returns the service to the platform defaults. Removing a reference releases its backend certificate binding but does not delete the uploaded account certificate. For example, rotate the web service's client certificate while keeping its CA: - -```sh -pnpm exec wrangler vpc service update \ - --name private-web --type http --https-port 443 \ - --ipv4 10.0.0.10 --tunnel-id \ - --certificate-authority --client-certificate \ - --cert-verification-mode verify_full -``` - -To remove the CA while keeping the client certificate, repeat the update with only `--client-certificate ` and a verification mode. - -Inspect the service's verification mode and CA/client certificate UUIDs (or `None`), without exposing certificate or private-key contents: - -```sh -pnpm exec wrangler vpc service get -``` diff --git a/packages/vite-plugin-cloudflare/AGENTS.md b/packages/vite-plugin-cloudflare/AGENTS.md index 9178e34493..193c6fbc71 100644 --- a/packages/vite-plugin-cloudflare/AGENTS.md +++ b/packages/vite-plugin-cloudflare/AGENTS.md @@ -7,8 +7,6 @@ Vite plugin for Cloudflare Workers development. Exports `cloudflare()` plugin fa ## STRUCTURE - `src/index.ts` — Plugin factory -- `src/cf-vite.ts` — `cf-vite` delegate binary entry (see below) -- `bin/cf-vite` — shebang shim that dynamic-imports `dist/cf-vite.mjs` - `src/workers/` — 4 internal worker entries: `asset-worker`, `router-worker`, `runner-worker`, `vite-proxy-worker` - `playground/` — ~47 playground apps, each a workspace member (nested workspace under this package) - `e2e/` — E2E tests with Playwright @@ -18,64 +16,17 @@ Vite plugin for Cloudflare Workers development. Exports `cloudflare()` plugin fa - Only package using `tsdown` as build tool - Outputs ESM (`.mjs`) to `dist/index.mjs` -- `src/cf-vite.ts` is a second top-level tsdown entry, bundled to `dist/cf-vite.mjs` (no dts) - Also bundles 4 internal worker scripts from `src/workers/*/index.ts` as separate neutral-platform outputs to `dist/workers/` - Release builds set `SOURCEMAPS=false` to omit the plugin's JavaScript and declaration maps. Normal builds retain maps for debugging; the setting does not change source maps for applications built with the plugin. -## cf-vite DELEGATE BINARY (experimental / internal) +## CLOUDFLARE TOOLING -`bin/cf-vite` is an experimental, internal delegate binary spawned by -Cloudflare's "cf-dev" parent process — NOT part of the plugin's public -API and not meant for direct end-user invocation. It is the sibling of -`wrangler`'s `cf-wrangler` binary, and the two MUST keep a shared spawn -contract so the parent can drive either impl interchangeably. - -- **Verb dispatch.** `cf-vite [flags]`. `dev` and `build` are the - verbs today; future verbs (`deploy`) follow the same shape. - Unknown/missing verbs exit `2` (this doubles as the parent's - version-detection signal — no JSON handshake). -- **Shared flag vocabulary (`dev`).** For `dev`, only `--mode`, `--port`, - `--host`, `--local` are accepted, mirroring `cf-wrangler` exactly. - Parsed with `node:util.parseArgs` strict mode → unknown flags exit `2`. - Do NOT add flags here unless `cf-wrangler` grows them too. (There is no - `--config` flag: the wrangler config is discovered by `cloudflare()` - itself.) -- **`build`** `cf-vite build` runs Vite's full multi-environment - app build via `createBuilder().buildApp()` (NOT the legacy - single-environment `build()` helper, which would skip the plugin's - worker/build-output orchestration — mirrors Vite's own `vite build` - CLI). It accepts only `--mode` (`--port`/`--host`/`--local` don't apply to - a build and exit `2`). Preview build context is supplied through - `CLOUDFLARE_PREVIEW_BUILD`, which also works when a framework runs Vite as - part of its own build command. -- **Build Output Specification is the core build pipeline.** Every build emits - Build Output; there is no feature flag or legacy output-config path. Preview - reads Workers and Containers exclusively from that output. The v2 plugin - always installs its build-output plugin, so `cf-vite` does not need the - internal force-build-output flag used by v1. -- **Caller identity.** The plugin is only compatible with `cf`, so actionable - messages always name `cf` (`CLI_DISPLAY_NAME` in `src/constants.ts`), whether - or not Vite was started by `cf-vite`. Do not fall back to Wrangler. -- **`dev`** `cf-vite dev` boots Vite via `createServer()` - against the user's own `vite.config.ts` (which must include - `cloudflare()`). Plugin-owned flags are bridged via env vars the plugin - already reads (`--local` → `CLOUDFLARE_VITE_FORCE_LOCAL`); Vite-owned - flags go through inline config (`--port`/`--host` → `server.*`, - `--mode` → `mode`). -- **Authentication.** Profiles resolve through `@cloudflare/workers-auth`, including - `CLOUDFLARE_AUTH_PROFILE` inherited from the parent. Remote-binding credentials - are keyed by the resolved profile as well as project directory and account, - so a profile change on restart replaces the session's authentication. -- **`--local`** forces remote bindings off. There is no plugin env knob - for `remoteBindings` other than `CLOUDFLARE_VITE_FORCE_LOCAL`, which - `resolvePluginConfig` in `plugin-config.ts` honours by overriding the - `remoteBindings` config option. Keep that override in sync if the flag - semantics change. -- **Hotkeys differ by design.** `cf-vite` uses Vite's own - `bindCLIShortcuts` (`h`/`r`/`q`/…), not wrangler's hotkey set. The - parent process should not assume identical hotkey UX across delegates. -- **Exit codes.** `0` graceful, `2` unknown verb / argv parse error, - `130` SIGINT, `143` SIGTERM. +- Run development and builds through Vite's CLI or the framework's own commands. +- Every build emits Build Output; Preview reads Workers and Containers from that output. +- Preview build context is supplied through `CLOUDFLARE_PREVIEW_BUILD`, including when a framework runs Vite as part of its build command. +- Configure `cloudflare({ remoteBindings: false })` to disable remote bindings. +- Actionable messages name `cf` through `CLI_DISPLAY_NAME` in `src/constants.ts`. +- Authentication profiles resolve through `@cloudflare/workers-auth`, including `CLOUDFLARE_AUTH_PROFILE` inherited from the parent. Remote-binding credentials are keyed by the resolved profile as well as project directory and account, so a profile change on restart replaces the session's authentication. ## CONVENTIONS diff --git a/packages/vite-plugin-cloudflare/bin/cf-vite b/packages/vite-plugin-cloudflare/bin/cf-vite deleted file mode 100755 index 76b7d62164..0000000000 --- a/packages/vite-plugin-cloudflare/bin/cf-vite +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -import("../dist/cf-vite.mjs"); diff --git a/packages/vite-plugin-cloudflare/package.json b/packages/vite-plugin-cloudflare/package.json index c680556e73..994c7de458 100644 --- a/packages/vite-plugin-cloudflare/package.json +++ b/packages/vite-plugin-cloudflare/package.json @@ -19,11 +19,7 @@ "url": "https://github.com/cloudflare/workers-sdk.git", "directory": "packages/vite-plugin-cloudflare" }, - "bin": { - "cf-vite": "./bin/cf-vite" - }, "files": [ - "bin", "dist" ], "type": "module", diff --git a/packages/vite-plugin-cloudflare/src/__tests__/package-sourcemaps.spec.ts b/packages/vite-plugin-cloudflare/src/__tests__/package-sourcemaps.spec.ts index 76feadcac8..58c07e1556 100644 --- a/packages/vite-plugin-cloudflare/src/__tests__/package-sourcemaps.spec.ts +++ b/packages/vite-plugin-cloudflare/src/__tests__/package-sourcemaps.spec.ts @@ -11,12 +11,10 @@ it("respects the package source-map setting for all built entry points", ({ const files = fs.readdirSync(distPath, { recursive: true, encoding: "utf8" }); expect(files).toContain("index.mjs"); expect(files).toContain("index.d.mts"); - expect(files).toContain("cf-vite.mjs"); if (process.env.SOURCEMAPS !== "false") { expect(files).toContain("index.mjs.map"); expect(files).toContain("index.d.mts.map"); - expect(files).toContain("cf-vite.mjs.map"); return; } diff --git a/packages/vite-plugin-cloudflare/src/__tests__/resolve-plugin-config.spec.ts b/packages/vite-plugin-cloudflare/src/__tests__/resolve-plugin-config.spec.ts index 50f7c15b1f..92f1802f93 100644 --- a/packages/vite-plugin-cloudflare/src/__tests__/resolve-plugin-config.spec.ts +++ b/packages/vite-plugin-cloudflare/src/__tests__/resolve-plugin-config.spec.ts @@ -814,23 +814,23 @@ describe("resolvePluginConfig", () => { fs.mkdirSync(envDir); fs.writeFileSync( path.join(envDir, ".env.production"), - "CLOUDFLARE_VITE_FORCE_LOCAL=true\nCLOUDFLARE_ACCOUNT_ID=test-account-id" + "CLOUDFLARE_ACCOUNT_ID=test-account-id" ); fs.writeFileSync( path.join(envDir, ".dev.vars.production"), "CLOUDFLARE_ACCOUNT_ID=from-dev-vars" ); - vi.stubEnv("CLOUDFLARE_VITE_FORCE_LOCAL", undefined); vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", undefined); const result = await resolvePluginConfig( - { remoteBindings: true }, + {}, { root, envDir: "environment" }, buildEnv ); - expect(result.remoteBindings).toBe(false); - expect(result.localEnv.values.CLOUDFLARE_VITE_FORCE_LOCAL).toBe("true"); + expect(result.localEnv.values.CLOUDFLARE_ACCOUNT_ID).toBe( + "test-account-id" + ); expect(result.devVars?.CLOUDFLARE_ACCOUNT_ID).toBe("from-dev-vars"); expect(process.env.CLOUDFLARE_ACCOUNT_ID).toBe("test-account-id"); }); @@ -839,17 +839,18 @@ describe("resolvePluginConfig", () => { writeEntryConfig(); fs.writeFileSync( path.join(root, ".env.production"), - "CLOUDFLARE_VITE_FORCE_LOCAL=true" + "CLOUDFLARE_ACCOUNT_ID=test-account-id" ); - vi.stubEnv("CLOUDFLARE_VITE_FORCE_LOCAL", undefined); + + vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", undefined); const result = await resolvePluginConfig( - { remoteBindings: true }, + {}, { root, envDir: false }, buildEnv ); - expect(result.remoteBindings).toBe(true); + expect(result.localEnv.values.CLOUDFLARE_ACCOUNT_ID).toBeUndefined(); }); test("rejects duplicate Vite environment names", async ({ expect }) => { diff --git a/packages/vite-plugin-cloudflare/src/cf-vite.ts b/packages/vite-plugin-cloudflare/src/cf-vite.ts deleted file mode 100644 index 1c64c961fd..0000000000 --- a/packages/vite-plugin-cloudflare/src/cf-vite.ts +++ /dev/null @@ -1,239 +0,0 @@ -/** - * `cf-vite` delegate binary entry point for `@cloudflare/vite-plugin`. - * - * EXPERIMENTAL / internal: spawned by Cloudflare's "cf-dev" parent - * process, not invoked directly by end users. Contract may change. - * - * Usage: `/bin/cf-vite [flags...]`. `dev` and `build` - * are the verbs today; future verbs follow the same shape. - * Unknown/missing verbs exit 2 (also the parent's version-detection - * signal). - * - * Spawn contract for `dev`: parent uses `stdio: "inherit"` and forwards - * SIGINT/SIGTERM. Accepted flags mirror the sibling `cf-wrangler` - * delegate (`--mode`, `--port`, `--host`, `--local`) so the parent can - * drive either impl interchangeably; everything else lives in the user's - * `vite.config.ts` / `cloudflare.config.ts`. `cf-vite` boots - * Vite via `createServer()` against the user's own config (expected to - * include `cloudflare()`); flags are bridged to it as documented inline. - * - * `build` runs Vite's full multi-environment app build via - * `createBuilder().buildApp()` (NOT the legacy single-environment - * `build()` helper, which would skip the plugin's worker builds). It - * accepts only `--mode`. Preview build context is supplied through the - * `CLOUDFLARE_PREVIEW_BUILD` environment variable so framework-owned build - * commands can use the same contract. - * - * Exit codes: 0 graceful, 2 unknown verb / parse error, 130 SIGINT, - * 143 SIGTERM. - */ - -import { parseArgs as nodeParseArgs } from "node:util"; -import { createBuilder, createServer } from "vite"; -import type { InlineConfig, ServerOptions } from "vite"; - -interface DevArgs { - mode?: string; - port?: number; - host?: string; - local?: boolean; -} - -class ArgParseError extends Error { - constructor(message: string) { - super(message); - this.name = "ArgParseError"; - } -} - -/** Strict argv parser; mirrors `cf-wrangler`'s flags (unknown → throw). */ -function parseDevArgs(argv: string[]): DevArgs { - let parsed; - try { - parsed = nodeParseArgs({ - args: argv, - options: { - mode: { type: "string" }, - host: { type: "string" }, - // `node:util.parseArgs` has no `number` type; coerce below. - port: { type: "string" }, - local: { type: "boolean" }, - }, - strict: true, - allowPositionals: false, - }); - } catch (err) { - throw new ArgParseError(err instanceof Error ? err.message : String(err)); - } - - const out: DevArgs = {}; - if (parsed.values.mode !== undefined) { - out.mode = parsed.values.mode; - } - if (parsed.values.host !== undefined) { - out.host = parsed.values.host; - } - if (parsed.values.port !== undefined) { - const raw = parsed.values.port; - const n = Number(raw); - // TCP port range; 0 = OS-assigned. - if (!Number.isInteger(n) || n < 0 || n > 65535) { - throw new ArgParseError( - `--port expects an integer between 0 and 65535, got "${raw}"` - ); - } - out.port = n; - } - if (parsed.values.local !== undefined) { - out.local = parsed.values.local; - } - - return out; -} - -interface BuildArgs { - mode?: string; -} - -function parseBuildArgs(argv: string[]): BuildArgs { - let parsed; - try { - parsed = nodeParseArgs({ - args: argv, - options: { - mode: { type: "string" }, - }, - strict: true, - allowPositionals: false, - }); - } catch (err) { - throw new ArgParseError(err instanceof Error ? err.message : String(err)); - } - - const out: BuildArgs = {}; - if (parsed.values.mode !== undefined) { - out.mode = parsed.values.mode; - } - - return out; -} - -async function main(): Promise { - // argv: [0] node [1] cf-vite.mjs [2] verb [3+] forwarded flags. - const verb = process.argv[2]; - const userArgv = process.argv.slice(3); - - if (verb === "dev") { - return runDev(userArgv); - } - - if (verb === "build") { - return runBuild(userArgv); - } - - // Format mirrors `cf-wrangler`. - process.stderr.write( - `Error: unknown subcommand "${verb ?? ""}".\n` + - `Usage: cf-vite [args]\n` - ); - return 2; -} - -async function runDev(userArgv: string[]): Promise { - let args: DevArgs; - try { - args = parseDevArgs(userArgv); - } catch (err) { - if (err instanceof ArgParseError) { - process.stderr.write(`Error: ${err.message}\n`); - return 2; - } - throw err; - } - - // Bridge plugin-owned flags via env vars the plugin reads during config - // resolution — must be set before `createServer()`. - // - `--local`: overrides `remoteBindings` outright, mirroring - // `wrangler dev --local` (force local even if config opts into - // remote). - if (args.local) { - process.env.CLOUDFLARE_VITE_FORCE_LOCAL = "true"; - } - - // Bridge Vite-owned flags via inline config; the rest auto-loads from - // the user's `vite.config.{ts,js,mjs}` (which supplies `cloudflare()`). - const serverOptions: ServerOptions = {}; - if (args.port !== undefined) { - serverOptions.port = args.port; - } - if (args.host !== undefined) { - serverOptions.host = args.host; - } - const inlineConfig: InlineConfig = { server: serverOptions }; - if (args.mode !== undefined) { - inlineConfig.mode = args.mode; - } - - const server = await createServer(inlineConfig); - - await server.listen(); - server.printUrls(); - server.bindCLIShortcuts({ print: true }); - - // Close cleanly on signal so the dev registry entry, workerd - // subprocess, and ports release. `closing` guards against a - // double-signal (e.g. rapid Ctrl+C, or SIGINT then SIGTERM) racing - // two `server.close()` / `process.exit()` calls. - let closing = false; - const shutdown = (signal: NodeJS.Signals) => { - if (closing) { - return; - } - closing = true; - // Signal handlers can't be async; void the IIFE to avoid unhandled - // rejections if `close()` throws. - void (async () => { - try { - await server.close(); - process.exit(0); - } catch { - // Forced-exit: terminate with the 128+N code rather than - // hang. SIGINT=130, SIGTERM=143. - process.exit(signal === "SIGINT" ? 130 : 143); - } - })(); - }; - process.on("SIGINT", () => shutdown("SIGINT")); - process.on("SIGTERM", () => shutdown("SIGTERM")); - - // Keep the event loop alive until a signal handler exits; Vite's own - // handles (HTTP listener, watchers, workerd) hold the process open. - return new Promise(() => {}); -} - -async function runBuild(userArgv: string[]): Promise { - let args: BuildArgs; - try { - args = parseBuildArgs(userArgv); - } catch (err) { - if (err instanceof ArgParseError) { - process.stderr.write(`Error: ${err.message}\n`); - return 2; - } - throw err; - } - - const inlineConfig: InlineConfig = {}; - if (args.mode !== undefined) { - inlineConfig.mode = args.mode; - } - const builder = await createBuilder(inlineConfig); - await builder.buildApp(); - - return 0; -} - -// Let unhandled rejections propagate — Node prints the stack and exits -// non-zero, which the parent surfaces via inherited stdio. -const exitCode = await main(); -process.exit(exitCode); diff --git a/packages/vite-plugin-cloudflare/src/plugin-config.ts b/packages/vite-plugin-cloudflare/src/plugin-config.ts index 94a1a7147c..e4e1d799e1 100644 --- a/packages/vite-plugin-cloudflare/src/plugin-config.ts +++ b/packages/vite-plugin-cloudflare/src/plugin-config.ts @@ -324,13 +324,7 @@ export async function resolvePluginConfig( devVars, }; - // The `cf-vite` delegate binary's `--local` flag sets this env var to - // force remote bindings off, overriding any `remoteBindings` value in the - // plugin config (mirrors `wrangler dev --local`). - const remoteBindings = - localEnv.values.CLOUDFLARE_VITE_FORCE_LOCAL === "true" - ? false - : (pluginConfig.remoteBindings ?? true); + const remoteBindings = pluginConfig.remoteBindings ?? true; if (preview !== undefined) { const { accountId, complianceRegion } = preview.rootConfig.settings ?? {}; diff --git a/packages/vite-plugin-cloudflare/tsdown.config.ts b/packages/vite-plugin-cloudflare/tsdown.config.ts index 9c65b80f1f..848a1928a1 100644 --- a/packages/vite-plugin-cloudflare/tsdown.config.ts +++ b/packages/vite-plugin-cloudflare/tsdown.config.ts @@ -26,21 +26,6 @@ export default defineConfig([ }, ignoreWatch, }, - { - // `cf-vite` delegate-binary entry. Bundled separately from the - // plugin itself so the bin shim (`bin/cf-vite`) can - // dynamic-import it without dragging the plugin's type-export - // overhead. The entry exposes a small subcommand-based CLI - // (currently just `dev`) that any parent process can spawn - // (see `src/cf-vite.ts` for the protocol). - entry: "src/cf-vite.ts", - platform: "node", - sourcemap, - outDir: "dist", - tsconfig: "tsconfig.plugin.json", - dts: false, - ignoreWatch, - }, worker("asset-worker"), worker("router-worker"), worker("runner-worker", { diff --git a/packages/wrangler/src/__tests__/vpc-tls.test.ts b/packages/wrangler/src/__tests__/vpc-tls.test.ts deleted file mode 100644 index ba6052ff36..0000000000 --- a/packages/wrangler/src/__tests__/vpc-tls.test.ts +++ /dev/null @@ -1,325 +0,0 @@ -import { runInTempDir } from "@cloudflare/workers-utils/test-helpers"; -import { http, HttpResponse } from "msw"; -import { beforeEach, describe, it, vi } from "vitest"; -import { ServiceType } from "../vpc/index"; -import { mockAccountId, mockApiToken } from "./helpers/mock-account-id"; -import { mockConsoleMethods } from "./helpers/mock-console"; -import { createFetchResult, msw } from "./helpers/msw"; -import { runWrangler } from "./helpers/run-wrangler"; -import type { - ConnectivityService, - ConnectivityServiceRequest, - TlsSettings, -} from "../vpc/index"; - -const servicesUrl = "*/accounts/:accountId/connectivity/directory/services"; -const serviceUrl = `${servicesUrl}/:serviceId`; -const tunnelId = "550e8400-e29b-41d4-a716-446655440000"; -const caId = "550e8400-e29b-41d4-a716-446655440001"; -const clientId = "550e8400-e29b-41d4-a716-446655440002"; -const serviceTls: TlsSettings = { - certificate_authority: caId, - client_certificate: clientId, - cert_verification_mode: "verify_ca", -}; - -function fixture( - hostname = false, - type = ServiceType.Tcp -): ConnectivityService { - return { - service_id: "service-uuid", - name: "database", - type, - ...(type === ServiceType.Tcp ? { tcp_port: 5432 } : { https_port: 443 }), - host: hostname - ? { - hostname: "db.example.com", - resolver_network: { - tunnel_id: tunnelId, - resolver_ips: ["10.0.0.53"], - }, - } - : { - ipv4: "10.0.0.1", - network: { - tunnel_id: tunnelId, - }, - }, - tls_settings: { ...serviceTls }, - created_at: "2024-01-01T00:00:00Z", - updated_at: "2024-01-01T00:00:00Z", - }; -} - -function command( - operation: "create" | "update", - hostname = false, - port = 5432, - type = ServiceType.Tcp -) { - return `vpc service ${operation} ${operation === "create" ? "database" : "service-uuid --name database"} --type ${type} --${type === ServiceType.Tcp ? "tcp" : "https"}-port ${port} --tunnel-id ${tunnelId} ${hostname ? "--hostname db.example.com --resolver-ips 10.0.0.53" : "--ipv4 10.0.0.1"}`; -} - -/** Simulate the replacement API: each write replaces the saved service. */ -function savedService(initial = fixture()) { - let saved = initial; - const calls: string[] = []; - const writes: ConnectivityServiceRequest[] = []; - function replace(body: ConnectivityServiceRequest) { - writes.push(body); - saved = { - ...body, - service_id: initial.service_id, - created_at: initial.created_at, - updated_at: "2024-01-02T00:00:00Z", - }; - return HttpResponse.json(createFetchResult(saved, true)); - } - msw.use( - http.post(servicesUrl, async ({ request }) => { - calls.push("POST"); - return replace((await request.json()) as ConnectivityServiceRequest); - }), - http.get(serviceUrl, () => { - calls.push("GET"); - return HttpResponse.json(createFetchResult(saved, true)); - }), - http.put(serviceUrl, async ({ request }) => { - calls.push("PUT"); - return replace((await request.json()) as ConnectivityServiceRequest); - }) - ); - return { calls, writes, current: () => saved }; -} - -function rejectAllApiCalls() { - const requests = vi.fn(() => - HttpResponse.json(createFetchResult(null, false), { status: 500 }) - ); - msw.use(http.all("*", requests)); - return requests; -} - -describe("VPC TLS configuration", () => { - mockAccountId(); - mockApiToken(); - runInTempDir(); - const std = mockConsoleMethods(); - - beforeEach(() => { - // Avoid the command banner's artificial delay. - // @ts-expect-error this mock only needs to schedule the callback - vi.spyOn(global, "setTimeout").mockImplementation((fn, _period) => { - setImmediate(fn); - }); - }); - - describe.each(["create", "update"] as const)("%s validation", (operation) => { - it.for([ - ["certificate-authority", caId], - ["client-certificate", clientId], - ])( - "requires an explicit mode for --%s before any API call", - async ([flag, id], { expect }) => { - const requests = rejectAllApiCalls(); - await expect( - runWrangler(`${command(operation)} --${flag} ${id}`) - ).rejects.toThrow( - "--cert-verification-mode is required when providing --certificate-authority or --client-certificate. Choose verify_full, verify_ca, or disabled." - ); - expect(requests).not.toHaveBeenCalled(); - } - ); - - it.for(["certificate-authority", "client-certificate"])( - "rejects invalid --%s UUIDs before any API call", - async (flag, { expect }) => { - const requests = rejectAllApiCalls(); - await expect( - runWrangler( - `${command(operation)} --${flag} not-a-uuid --cert-verification-mode verify_ca` - ) - ).rejects.toThrow(); - expect(requests).not.toHaveBeenCalled(); - expect(std.err).toContain(flag); - } - ); - - it("rejects an invalid verification mode before any API call", async ({ - expect, - }) => { - const requests = rejectAllApiCalls(); - await expect( - runWrangler(`${command(operation)} --cert-verification-mode not-a-mode`) - ).rejects.toThrow(); - expect(requests).not.toHaveBeenCalled(); - expect(std.err).toContain("cert-verification-mode"); - }); - - it("rejects a CA with disabled verification before any API call", async ({ - expect, - }) => { - const requests = rejectAllApiCalls(); - await expect( - runWrangler( - `${command(operation)} --certificate-authority ${caId} --cert-verification-mode disabled` - ) - ).rejects.toThrow(/certificate.authority/i); - expect(requests).not.toHaveBeenCalled(); - expect(std.out).not.toContain("Created VPC service"); - expect(std.out).not.toContain("Updated VPC service"); - }); - - it.for([ - `--network-certificate-authority ${caId}`, - `--network-client-certificate ${clientId}`, - "--network-cert-verification-mode verify_ca", - "--remove-network-certificate-authority", - "--remove-network-client-certificate", - "--remove-network-tls-settings", - "--use-network-tls-settings", - "--remove-certificate-authority", - "--remove-client-certificate", - ])( - "rejects unsupported TLS flags rather than silently ignoring them: %s", - async (flags, { expect }) => { - const requests = rejectAllApiCalls(); - await expect( - runWrangler(`${command(operation)} ${flags}`) - ).rejects.toThrow(/Unknown argument/); - expect(requests).not.toHaveBeenCalled(); - } - ); - }); - - const tlsCases = [ - ["no TLS options", "", undefined], - [ - "mode-only verify_full", - "--cert-verification-mode verify_full", - { cert_verification_mode: "verify_full" }, - ], - [ - "mode-only disabled", - "--cert-verification-mode disabled", - { cert_verification_mode: "disabled" }, - ], - [ - "a custom CA", - `--certificate-authority ${caId} --cert-verification-mode verify_full`, - { certificate_authority: caId, cert_verification_mode: "verify_full" }, - ], - [ - "a client certificate with verification disabled", - `--client-certificate ${clientId} --cert-verification-mode disabled`, - { client_certificate: clientId, cert_verification_mode: "disabled" }, - ], - [ - "both certificates", - `--certificate-authority ${caId} --client-certificate ${clientId} --cert-verification-mode verify_ca`, - serviceTls, - ], - ] as const; - - describe.each([ServiceType.Tcp, ServiceType.Http])("%s services", (type) => { - it.for(tlsCases)( - "creates a service with %s", - async ([_label, flags, tls], { expect }) => { - const api = savedService(fixture(false, type)); - await runWrangler(`${command("create", false, 443, type)} ${flags}`); - expect(api.calls).toEqual(["POST"]); - expect(api.writes[0].tls_settings).toEqual(tls); - } - ); - }); - - it.for(tlsCases)( - "replaces the service TLS settings with %s in a single PUT", - async ([_label, flags, tls], { expect }) => { - const api = savedService(); - await runWrangler(`${command("update")} ${flags}`); - expect(api.calls).toEqual(["PUT"]); - expect(api.writes[0].tls_settings).toEqual(tls); - expect(api.current().tls_settings).toEqual(tls); - } - ); - - it.for([false, true])( - "reports configured service TLS without private data (hostname=%s)", - async (hostname, { expect }) => { - const service = { - ...fixture(hostname), - internal_id: "internal-secret-marker", - private_key: "private-key-marker", - certificate: "certificate-pem-marker", - }; - msw.use( - http.get(serviceUrl, () => - HttpResponse.json(createFetchResult(service, true)) - ) - ); - await runWrangler("vpc service get service-uuid"); - for (const id of [caId, clientId]) { - expect(std.out).toContain(id); - } - expect(std.out).toContain("verify_ca"); - for (const secret of [ - "internal-secret-marker", - "private-key-marker", - "certificate-pem-marker", - ]) { - expect(std.out).not.toContain(secret); - } - } - ); - - it.for([ - ["disabled", "None"], - ["verify_ca", "None (system trust store)"], - ["verify_full", "None (system trust store)"], - ] as const)( - "reports the default certificate authority for %s verification", - async ([mode, authority], { expect }) => { - const service = fixture(); - service.tls_settings = { cert_verification_mode: mode }; - savedService(service); - await runWrangler("vpc service get service-uuid"); - expect(std.out).toContain(`Certificate Authority: ${authority}\n`); - } - ); - - it.for(["create", "update"] as const)( - "surfaces certificate API errors on %s without reporting success", - async (operation, { expect }) => { - const writes: ConnectivityServiceRequest[] = []; - const failure = HttpResponse.json( - { - success: false, - errors: [{ code: 1000, message: "Certificate not found" }], - messages: [], - result: null, - }, - { status: 400 } - ); - msw.use( - http.post(servicesUrl, async ({ request }) => { - writes.push((await request.json()) as ConnectivityServiceRequest); - return failure; - }), - http.put(serviceUrl, async ({ request }) => { - writes.push((await request.json()) as ConnectivityServiceRequest); - return failure; - }) - ); - await expect( - runWrangler( - `${command(operation)} --certificate-authority ${caId} --cert-verification-mode verify_ca` - ) - ).rejects.toThrow(); - expect(writes).toHaveLength(1); - expect(std.out).not.toContain("Created VPC service"); - expect(std.out).not.toContain("Updated VPC service"); - } - ); -}); diff --git a/packages/wrangler/src/__tests__/vpc.test.ts b/packages/wrangler/src/__tests__/vpc.test.ts index b6099db892..0468ab365a 100644 --- a/packages/wrangler/src/__tests__/vpc.test.ts +++ b/packages/wrangler/src/__tests__/vpc.test.ts @@ -573,6 +573,177 @@ describe("vpc service commands", () => { `); }); + it("should handle creating a TCP service with --cert-verification-mode verify_ca", async ({ + expect, + }) => { + const reqProm = mockWvpcServiceCreate(); + await runWrangler( + "vpc service create test-tcp-tls --type tcp --tcp-port 5432 --ipv4 10.0.0.5 --tunnel-id 550e8400-e29b-41d4-a716-446655440000 --cert-verification-mode verify_ca" + ); + + await expect(reqProm).resolves.toMatchInlineSnapshot(` + { + "host": { + "ipv4": "10.0.0.5", + "network": { + "tunnel_id": "550e8400-e29b-41d4-a716-446655440000", + }, + }, + "name": "test-tcp-tls", + "tcp_port": 5432, + "tls_settings": { + "cert_verification_mode": "verify_ca", + }, + "type": "tcp", + } + `); + + expect(std.out).toMatchInlineSnapshot(` + " + ⛅️ wrangler x.x.x + ────────────────── + 🚧 Creating VPC service 'test-tcp-tls' + ✅ Created VPC service: service-uuid + Name: test-tcp-tls + Type: tcp + TCP Port: 5432 + Cert Verification Mode: verify_ca + IPv4: 10.0.0.5 + Tunnel ID: 550e8400-e29b-41d4-a716-446655440000" + `); + }); + + it("should handle creating an HTTP service with --cert-verification-mode disabled", async ({ + expect, + }) => { + const reqProm = mockWvpcServiceCreate(); + await runWrangler( + "vpc service create test-http-tls --type http --http-port 80 --ipv4 10.0.0.1 --tunnel-id 550e8400-e29b-41d4-a716-446655440000 --cert-verification-mode disabled" + ); + + await expect(reqProm).resolves.toMatchInlineSnapshot(` + { + "host": { + "ipv4": "10.0.0.1", + "network": { + "tunnel_id": "550e8400-e29b-41d4-a716-446655440000", + }, + }, + "http_port": 80, + "name": "test-http-tls", + "tls_settings": { + "cert_verification_mode": "disabled", + }, + "type": "http", + } + `); + + expect(std.out).toMatchInlineSnapshot(` + " + ⛅️ wrangler x.x.x + ────────────────── + 🚧 Creating VPC service 'test-http-tls' + ✅ Created VPC service: service-uuid + Name: test-http-tls + Type: http + HTTP Port: 80 + Cert Verification Mode: disabled + IPv4: 10.0.0.1 + Tunnel ID: 550e8400-e29b-41d4-a716-446655440000" + `); + }); + + it("should not include tls_settings when --cert-verification-mode is not specified", async ({ + expect, + }) => { + const reqProm = mockWvpcServiceCreate(); + await runWrangler( + "vpc service create test-no-tls --type tcp --tcp-port 5432 --ipv4 10.0.0.5 --tunnel-id 550e8400-e29b-41d4-a716-446655440000" + ); + + const reqBody = await reqProm; + expect(reqBody.tls_settings).toBeUndefined(); + }); + + it("should handle getting a service with tls_settings", async ({ + expect, + }) => { + const serviceWithTls: ConnectivityService = { + ...mockTcpService, + tls_settings: { + cert_verification_mode: "verify_ca", + }, + }; + + msw.use( + http.get( + "*/accounts/:accountId/connectivity/directory/services/:serviceId", + () => { + return HttpResponse.json(createFetchResult(serviceWithTls, true)); + }, + { once: true } + ) + ); + + await runWrangler("vpc service get tcp-service-uuid"); + + expect(std.out).toMatchInlineSnapshot(` + " + ⛅️ wrangler x.x.x + ────────────────── + 🔍 Getting VPC service 'tcp-service-uuid' + ✅ Retrieved VPC service: tcp-service-uuid + Name: test-tcp-service + Type: tcp + TCP Port: 5432 + App Protocol: postgresql + Cert Verification Mode: verify_ca + IPv4: 10.0.0.5 + Tunnel ID: 550e8400-e29b-41d4-a716-446655440000 + Created: 1/1/2024, 12:00:00 AM + Modified: 1/1/2024, 12:00:00 AM" + `); + }); + + it("should handle updating a service with --cert-verification-mode", async ({ + expect, + }) => { + const reqProm = mockWvpcServiceUpdate(); + await runWrangler( + "vpc service update service-uuid --name test-updated --type http --http-port 80 --ipv4 10.0.0.2 --tunnel-id 550e8400-e29b-41d4-a716-446655440001 --cert-verification-mode verify_full" + ); + + await expect(reqProm).resolves.toMatchInlineSnapshot(` + { + "host": { + "ipv4": "10.0.0.2", + "network": { + "tunnel_id": "550e8400-e29b-41d4-a716-446655440001", + }, + }, + "http_port": 80, + "name": "test-updated", + "tls_settings": { + "cert_verification_mode": "verify_full", + }, + "type": "http", + } + `); + }); + + it("should reject --cert-verification-mode with invalid value", async ({ + expect, + }) => { + await expect(() => + runWrangler( + "vpc service create test-bad-tls --type tcp --tcp-port 5432 --ipv4 10.0.0.1 --tunnel-id 550e8400-e29b-41d4-a716-446655440000 --cert-verification-mode invalid" + ) + ).rejects.toThrow(); + expect(std.err).toContain("Invalid values"); + expect(std.err).toContain("cert-verification-mode"); + expect(std.err).toContain('"invalid"'); + }); + it("should extract port from hostname for TCP services", async ({ expect, }) => { diff --git a/packages/wrangler/src/vpc/index.ts b/packages/wrangler/src/vpc/index.ts index 6d0689f955..942b1cfc05 100644 --- a/packages/wrangler/src/vpc/index.ts +++ b/packages/wrangler/src/vpc/index.ts @@ -26,8 +26,6 @@ export type CertVerificationMode = "verify_full" | "verify_ca" | "disabled"; export interface TlsSettings { cert_verification_mode: CertVerificationMode; - certificate_authority?: string; - client_certificate?: string; } export interface ServicePortOptions { @@ -169,17 +167,7 @@ export const serviceOptions = { type: "string", choices: ["verify_full", "verify_ca", "disabled"] as const, description: - "Origin verification: verify_full checks chain and hostname; verify_ca checks chain only; disabled skips verification and cannot be used with a custom CA. Required when providing certificates. On update, TLS options you omit are cleared", - group: "TLS Options", - }, - "certificate-authority": { - type: "string", - description: "UUID returned by wrangler cert upload certificate-authority", - group: "TLS Options", - }, - "client-certificate": { - type: "string", - description: "UUID returned by wrangler cert upload mtls-certificate", + "TLS certificate verification mode for the connection to the origin", group: "TLS Options", }, } as const; diff --git a/packages/wrangler/src/vpc/shared.ts b/packages/wrangler/src/vpc/shared.ts index 8abc8a3f20..0a8c7a57ac 100644 --- a/packages/wrangler/src/vpc/shared.ts +++ b/packages/wrangler/src/vpc/shared.ts @@ -23,20 +23,11 @@ export function displayServiceDetails(service: ConnectivityService) { } } + // Display TLS settings if (service.tls_settings) { - const defaultCertificateAuthority = - service.tls_settings.cert_verification_mode === "disabled" - ? "None" - : "None (system trust store)"; logger.log( ` Cert Verification Mode: ${service.tls_settings.cert_verification_mode}` ); - logger.log( - ` Certificate Authority: ${service.tls_settings.certificate_authority ?? defaultCertificateAuthority}` - ); - logger.log( - ` Client Certificate: ${service.tls_settings.client_certificate ?? "None"}` - ); } // Display host details diff --git a/packages/wrangler/src/vpc/tls.ts b/packages/wrangler/src/vpc/tls.ts deleted file mode 100644 index b0191bc38c..0000000000 --- a/packages/wrangler/src/vpc/tls.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { UserError } from "@cloudflare/workers-utils"; -import type { CertVerificationMode, TlsSettings } from "./index"; - -export interface TlsArgs { - certificateAuthority?: string; - clientCertificate?: string; - certVerificationMode?: string; -} - -/** - * Validates the TLS flags of `vpc service create` and `vpc service update` - * before any API call. - * - * A certificate reference requires an explicit verification mode, and a custom - * CA cannot be combined with `disabled`, because it is used only to verify the - * origin certificate. - * - * @param args - The TLS flags supplied on the command line. - * @throws {UserError} If the flags describe invalid TLS settings. - */ -export function validateTlsArgs(args: TlsArgs): void { - if ( - (args.certificateAuthority !== undefined || - args.clientCertificate !== undefined) && - args.certVerificationMode === undefined - ) { - throw new UserError( - "--cert-verification-mode is required when providing --certificate-authority or --client-certificate. Choose verify_full, verify_ca, or disabled.", - { telemetryMessage: "vpc tls missing cert verification mode" } - ); - } - if ( - args.certVerificationMode !== undefined && - !["verify_full", "verify_ca", "disabled"].includes( - args.certVerificationMode - ) - ) { - throw new UserError( - "Invalid --cert-verification-mode. Choose verify_full, verify_ca, or disabled.", - { telemetryMessage: "vpc tls invalid cert verification mode" } - ); - } - for (const [flag, id] of [ - ["certificate-authority", args.certificateAuthority], - ["client-certificate", args.clientCertificate], - ] as const) { - if ( - id !== undefined && - !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( - id - ) - ) { - throw new UserError( - `Invalid --${flag}: '${id}'. Provide the certificate UUID returned by wrangler cert upload.`, - { telemetryMessage: `vpc tls invalid ${flag}` } - ); - } - } - if ( - args.certificateAuthority !== undefined && - args.certVerificationMode === "disabled" - ) { - throw new UserError( - "--certificate-authority requires --cert-verification-mode verify_ca or verify_full; disabled cannot verify a custom CA.", - { - telemetryMessage: - "vpc tls certificate authority with disabled verification", - } - ); - } -} - -/** - * Builds the service TLS settings from the command-line flags alone. - * - * Service updates replace the whole configuration, so settings omitted here are - * not carried over from the existing service. - * - * @param args - TLS flags that have passed {@link validateTlsArgs}. - * @returns The TLS settings to send, or `undefined` when no TLS flags were - * supplied, which leaves the service on the platform defaults. - */ -export function tlsSettingsFromArgs(args: TlsArgs): TlsSettings | undefined { - if (args.certVerificationMode === undefined) { - return undefined; - } - return { - cert_verification_mode: args.certVerificationMode as CertVerificationMode, - certificate_authority: args.certificateAuthority, - client_certificate: args.clientCertificate, - }; -} diff --git a/packages/wrangler/src/vpc/validation.ts b/packages/wrangler/src/vpc/validation.ts index 277f08da85..aa3db185e2 100644 --- a/packages/wrangler/src/vpc/validation.ts +++ b/packages/wrangler/src/vpc/validation.ts @@ -1,11 +1,13 @@ import net from "node:net"; import { UserError } from "@cloudflare/workers-utils"; -import { tlsSettingsFromArgs, validateTlsArgs } from "./tls"; import { ServiceType } from "./index"; -import type { ConnectivityServiceRequest, ServiceHost } from "./index"; -import type { TlsArgs } from "./tls"; +import type { + CertVerificationMode, + ConnectivityServiceRequest, + ServiceHost, +} from "./index"; -export interface ServiceArgs extends TlsArgs { +export interface ServiceArgs { name: string; type: ServiceType; tcpPort?: number; @@ -17,6 +19,7 @@ export interface ServiceArgs extends TlsArgs { hostname?: string; tunnelId: string; resolverIps?: string; + certVerificationMode?: string; } export function validateHostname(hostname: string): void { @@ -113,21 +116,20 @@ export function extractPortFromHostname(hostname: string): { * `--hostname db.internal:5432` is equivalent to * `--hostname db.internal --tcp-port 5432`. */ -export function toServiceArgs( - args: { - name: string; - type: string; - tcpPort?: number; - appProtocol?: string; - httpPort?: number; - httpsPort?: number; - ipv4?: string; - ipv6?: string; - hostname?: string; - tunnelId: string; - resolverIps?: string; - } & TlsArgs -): ServiceArgs { +export function toServiceArgs(args: { + name: string; + type: string; + tcpPort?: number; + appProtocol?: string; + httpPort?: number; + httpsPort?: number; + ipv4?: string; + ipv6?: string; + hostname?: string; + tunnelId: string; + resolverIps?: string; + certVerificationMode?: string; +}): ServiceArgs { const type = args.type as ServiceType; let { hostname } = args; let tcpPort = args.tcpPort; @@ -159,13 +161,10 @@ export function toServiceArgs( tunnelId: args.tunnelId, resolverIps: args.resolverIps, certVerificationMode: args.certVerificationMode, - certificateAuthority: args.certificateAuthority, - clientCertificate: args.clientCertificate, }; } export function validateRequest(args: ServiceArgs) { - validateTlsArgs(args); // Validate host configuration - must have either IP addresses or hostname, not both const hasIpAddresses = Boolean(args.ipv4 || args.ipv6); const hasHostname = Boolean(args.hostname); @@ -262,7 +261,12 @@ export function buildRequest(args: ServiceArgs): ConnectivityServiceRequest { request.https_port = args.httpsPort; } - request.tls_settings = tlsSettingsFromArgs(args); + // Add TLS settings if specified + if (args.certVerificationMode) { + request.tls_settings = { + cert_verification_mode: args.certVerificationMode as CertVerificationMode, + }; + } return request; }