From e3c1ed88e6f761fec5f38b2876899df2ea276f2f Mon Sep 17 00:00:00 2001 From: Ehab Younes Date: Fri, 4 Dec 2026 11:18:50 +0000 Subject: [PATCH 1/2] feat(api): prefer post-quantum TLS key exchange Offer X25519MLKEM768 with classical fallback on REST and WebSocket connections to the deployment. Electron before 44 does not offer it by default, and VS Code's default proxy support replaces our agent, so the groups go on each request: in ws options and an axios transport over follow-redirects. The group list is probed once because an unsupported name breaks every TLS connection. --- CHANGELOG.md | 8 ++ docs/ARCHITECTURE.md | 8 ++ package.json | 2 + pnpm-lock.yaml | 13 +++ src/api/coderApi.ts | 4 + src/api/httpAgent.ts | 2 + src/api/keyExchange.ts | 70 ++++++++++++++ test/unit/api/coderApi.test.ts | 5 + test/unit/api/keyExchange.test.ts | 148 ++++++++++++++++++++++++++++++ 9 files changed, 260 insertions(+) create mode 100644 src/api/keyExchange.ts create mode 100644 test/unit/api/keyExchange.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index fa56f31662..50fdfd4dbe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ from published versions since it shows up in the VS Code extension changelog tab and is confusing to users. Add it back between releases if needed. --> +## Unreleased + +### Added + +- Connections to the Coder deployment prefer the post-quantum hybrid key + exchange `X25519MLKEM768` when VS Code and the deployment support it, and fall + back to classical key exchange otherwise. + ## [v1.18.4](https://github.com/coder/vscode-coder/releases/tag/v1.18.4) 2026-12-03 ### Added diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 53dd4584e9..01b833edb6 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -173,6 +173,14 @@ Worth knowing: `windowsAcl.native.test.ts` drives the real `icacls.exe`, `whoami.exe`, and OpenSSH. Run it unelevated as well as in CI to catch privilege assumptions. +## TLS key exchange + +REST and WebSocket connections to the deployment offer the post-quantum hybrid +group `X25519MLKEM768` (`src/api/keyExchange.ts`). Electron before 44 does not +offer it by default, and VS Code's proxy support replaces our agent, so the +groups are set on each request. Remove the module once the minimum supported +VS Code ships Electron 44. + ## Other features The extension provides several sidebar panels: diff --git a/package.json b/package.json index cc635265ee..1b8e96eb4e 100644 --- a/package.json +++ b/package.json @@ -843,6 +843,7 @@ "date-fns": "catalog:", "fflate": "^0.8.3", "find-process": "^2.1.1", + "follow-redirects": "^1.16.3", "jsonc-parser": "^3.3.1", "openpgp": "^6.3.3", "pretty-bytes": "^7.2.0", @@ -868,6 +869,7 @@ "@testing-library/react": "^16.3.3", "@testing-library/user-event": "catalog:", "@tsconfig/node22": "^22.0.7", + "@types/follow-redirects": "^1.14.4", "@types/mocha": "^10.0.10", "@types/node": "^22.20.7", "@types/proper-lockfile": "^4.1.4", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 28cb397807..fadd640280 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -287,6 +287,9 @@ importers: find-process: specifier: ^2.1.1 version: 2.1.1 + follow-redirects: + specifier: ^1.16.3 + version: 1.16.3(debug@4.4.3) jsonc-parser: specifier: ^3.3.1 version: 3.3.1 @@ -357,6 +360,9 @@ importers: '@tsconfig/node22': specifier: ^22.0.7 version: 22.0.7 + '@types/follow-redirects': + specifier: ^1.14.4 + version: 1.14.4 '@types/mocha': specifier: ^10.0.10 version: 10.0.10 @@ -2409,6 +2415,9 @@ packages: '@types/estree@1.0.11': resolution: {integrity: sha512-YBdNe5JcjYR0sPhJW1QIeRCmI11YhYvaRuGCs9+WCeTTb+Yhb2BE2XMe5/wAqF10FK5g3+q1PDhQABfT7aX0gg==} + '@types/follow-redirects@1.14.4': + resolution: {integrity: sha512-GWXfsD0Jc1RWiFmMuMFCpXMzi9L7oPDVwxUnZdg89kDNnqsRfUKXEtUYtA98A6lig1WXH/CYY/fvPW9HuN5fTA==} + '@types/gensync@1.0.5': resolution: {integrity: sha512-MbsRCT7mTikHwKZ0X+LVUTLRrZZRLipTuXEO9qOYO+zmjMVk81axyClMROf6uoPD9MRVu46bx8zoR0Ad9q3NAg==} @@ -6590,6 +6599,10 @@ snapshots: '@types/estree@1.0.11': {} + '@types/follow-redirects@1.14.4': + dependencies: + '@types/node': 22.20.7 + '@types/gensync@1.0.5': {} '@types/hast@3.0.5': diff --git a/src/api/coderApi.ts b/src/api/coderApi.ts index 0f8ad53682..b84582d1a4 100644 --- a/src/api/coderApi.ts +++ b/src/api/coderApi.ts @@ -54,6 +54,7 @@ import { import { getRefreshCommand, refreshCertificates } from "./certificateRefresh"; import { createHttpAgent } from "./httpAgent"; +import { createKeyExchangeTransport, getEcdhCurve } from "./keyExchange"; import { parseApiResponse, VALIDATED_RESPONSES, @@ -451,6 +452,8 @@ export class CoderApi extends Api implements vscode.Disposable { options: { ...configs.options, agent: httpAgent, + // On the request too: VS Code's proxy support replaces the agent. + ecdhCurve: getEcdhCurve(), followRedirects: true, // A stalled handshake would otherwise never error or retry. handshakeTimeout: DEFAULT_REQUEST_TIMEOUT_MS, @@ -582,6 +585,7 @@ function setupInterceptors( config.httpsAgent = agent; config.httpAgent = agent; config.proxy = false; + config.transport = createKeyExchangeTransport(config, getEcdhCurve()); return config; }); diff --git a/src/api/httpAgent.ts b/src/api/httpAgent.ts index d53919b2a9..d76455768d 100644 --- a/src/api/httpAgent.ts +++ b/src/api/httpAgent.ts @@ -5,6 +5,7 @@ import { type WorkspaceConfiguration } from "vscode"; import { expandPath } from "../common/fs"; import { LocalProxySettings, type LocalProxySetting } from "../settings/proxy"; +import { getEcdhCurve } from "./keyExchange"; import { getProxyForUrl, joinNoProxy } from "./proxy"; /** Whether requests carry a TLS client certificate (mTLS). */ @@ -73,6 +74,7 @@ export async function createHttpAgent( key, ca, servername: altHost === "" ? undefined : altHost, + ecdhCurve: getEcdhCurve(), // TLS verification is disabled if either: // - http.proxyStrictSSL is false (VS Code's proxy SSL setting) // - coder.insecure is true (backward compatible override for Coder server) diff --git a/src/api/keyExchange.ts b/src/api/keyExchange.ts new file mode 100644 index 0000000000..7a6c92eb06 --- /dev/null +++ b/src/api/keyExchange.ts @@ -0,0 +1,70 @@ +import followRedirects, { type FollowOptions } from "follow-redirects"; +import tls from "node:tls"; + +import type { AxiosRequestConfig } from "axios"; +import type { IncomingMessage } from "node:http"; +import type { RequestOptions } from "node:https"; + +/** + * Electron 44+ offers this list by default. Delete this module once the + * minimum supported VS Code ships Electron 44. + */ +const PREFERRED_ECDH_CURVE = "X25519MLKEM768:X25519:P-256:P-384"; + +/** The cached probe result; unset until `getEcdhCurve` first runs. */ +let probed: { ecdhCurve: string | undefined } | undefined; + +/** + * The TLS key exchange groups to offer, or undefined for the runtime default. + * An unsupported group name makes every TLS connection throw, so the list is + * probed once before it is used. + */ +export function getEcdhCurve(): string | undefined { + if (!probed) { + try { + tls.createSecureContext({ ecdhCurve: PREFERRED_ECDH_CURVE }); + probed = { ecdhCurve: PREFERRED_ECDH_CURVE }; + } catch { + probed = { ecdhCurve: undefined }; + } + } + return probed.ecdhCurve; +} + +type TransportOptions = RequestOptions & + FollowOptions & { + beforeRedirects: Record; + }; + +/** + * An axios transport that puts `ecdhCurve` on each request, since axios has + * no per-request TLS options and VS Code's proxy support replaces our agent. + * Returns undefined, keeping the axios transport, when there is nothing to add. + */ +export function createKeyExchangeTransport( + config: Pick, + ecdhCurve: string | undefined, +) { + // Without redirects axios uses its native transport, which this would replace. + if (!ecdhCurve || config.maxRedirects === 0) { + return undefined; + } + return { + request( + options: TransportOptions, + callback: (res: IncomingMessage) => void, + ) { + options.ecdhCurve = ecdhCurve; + // Axios only wires these into follow-redirects for its own transport. + if (config.maxRedirects) { + options.maxRedirects = config.maxRedirects; + } + options.beforeRedirects.config = config.beforeRedirect; + const scheme = + options.protocol === "https:" + ? followRedirects.https + : followRedirects.http; + return scheme.request(options, callback); + }, + }; +} diff --git a/test/unit/api/coderApi.test.ts b/test/unit/api/coderApi.test.ts index 2d5ab6dcbc..511236a436 100644 --- a/test/unit/api/coderApi.test.ts +++ b/test/unit/api/coderApi.test.ts @@ -22,6 +22,7 @@ import { } from "@/api/certificateRefresh"; import { CoderApi, DEFAULT_REQUEST_TIMEOUT_MS } from "@/api/coderApi"; import { createHttpAgent } from "@/api/httpAgent"; +import { getEcdhCurve } from "@/api/keyExchange"; import { InvalidApiResponseError, VALIDATED_RESPONSES, @@ -515,6 +516,7 @@ describe("CoderApi", () => { expect(Ws).toHaveBeenCalledWith(wsUrl, undefined, { agent: mockAgent, + ecdhCurve: getEcdhCurve(), followRedirects: true, handshakeTimeout: DEFAULT_REQUEST_TIMEOUT_MS, headers: { @@ -531,6 +533,7 @@ describe("CoderApi", () => { expect(Ws).toHaveBeenCalledWith(wsUrl, undefined, { agent: undefined, + ecdhCurve: getEcdhCurve(), followRedirects: true, handshakeTimeout: DEFAULT_REQUEST_TIMEOUT_MS, headers: { @@ -549,6 +552,7 @@ describe("CoderApi", () => { expect(Ws).toHaveBeenCalledWith(wsUrl, undefined, { agent: undefined, + ecdhCurve: getEcdhCurve(), followRedirects: true, handshakeTimeout: DEFAULT_REQUEST_TIMEOUT_MS, headers: { @@ -571,6 +575,7 @@ describe("CoderApi", () => { expect(Ws).toHaveBeenCalledWith(wsUrl, undefined, { agent: undefined, + ecdhCurve: getEcdhCurve(), followRedirects: true, handshakeTimeout: DEFAULT_REQUEST_TIMEOUT_MS, headers: { diff --git a/test/unit/api/keyExchange.test.ts b/test/unit/api/keyExchange.test.ts new file mode 100644 index 0000000000..2a24089bb9 --- /dev/null +++ b/test/unit/api/keyExchange.test.ts @@ -0,0 +1,148 @@ +import fs from "node:fs/promises"; +import https from "node:https"; +import tls from "node:tls"; +import { ProxyAgent } from "proxy-agent"; +import { + afterAll, + beforeAll, + describe, + expect, + it, + onTestFinished, + vi, +} from "vitest"; +import { WebSocketServer } from "ws"; + +import { CoderApi } from "@/api/coderApi"; +import { createHttpAgent } from "@/api/httpAgent"; + +import { + clearProxyEnv, + config, + createMockLogger, + MockConfigurationProvider, +} from "../../mocks/testHelpers"; +import { getFixturePath } from "../../utils/fixtures"; + +import type { AddressInfo } from "node:net"; + +/** + * Electron 44 already offers the preferred groups by default, so the + * handshakes below request P-521, which BoringSSL never offers on its own. + */ +const TEST_ECDH_CURVE = "P-521"; + +vi.mock("@/api/keyExchange", async (importActual) => ({ + ...(await importActual()), + getEcdhCurve: vi.fn(() => TEST_ECDH_CURVE), +})); + +// Stands in for the agent VS Code swaps in under `http.proxySupport: override`, +// which keeps only `ca` from our TLS options. +vi.mock("@/api/httpAgent", async (importActual) => ({ + ...(await importActual()), + createHttpAgent: vi.fn(), +})); + +describe("TLS key exchange", () => { + const certPath = getFixturePath("tls", "self-signed.crt"); + let ca: Buffer; + let origin: string; + let server: https.Server; + + beforeAll(async () => { + ca = await fs.readFile(certPath); + vi.mocked(createHttpAgent).mockResolvedValue( + new ProxyAgent({ ca, getProxyForUrl: () => "" }), + ); + server = https.createServer( + { + key: await fs.readFile(getFixturePath("tls", "self-signed.key")), + cert: ca, + ecdhCurve: TEST_ECDH_CURVE, + }, + (req, res) => { + if (req.url === "/old") { + res.writeHead(302, { location: "/new" }); + } + res.end(); + }, + ); + new WebSocketServer({ server }).on("connection", (ws) => ws.close()); + // The fixture certificate is issued for localhost. + await new Promise((resolve) => + server.listen(0, "localhost", resolve), + ); + origin = `https://localhost:${(server.address() as AddressInfo).port}`; + }); + + afterAll(() => server.close()); + + function get(options: https.RequestOptions): Promise { + return new Promise((resolve, reject) => + https + .get(`${origin}/`, options, (res) => resolve(res.statusCode)) + .on("error", reject), + ); + } + + function createApi(): CoderApi { + new MockConfigurationProvider(); + const api = CoderApi.create(origin, "token", createMockLogger()); + onTestFinished(() => api.dispose()); + return api; + } + + it("fails the handshake without the requested groups", async () => { + await expect(get({ ca })).rejects.toThrow(/HANDSHAKE_FAILURE/); + }); + + it("offers the groups on REST requests, across redirects", async () => { + const response = await createApi().getAxiosInstance().get("/old"); + + expect(response.status).toBe(200); + }); + + it("offers the groups on WebSocket connections", async () => { + const socket = await createApi().watchBuildLogsByBuildId("build", []); + + await expect(socket.opened).resolves.toBeUndefined(); + }); + + it("offers the groups from our own agent", async () => { + clearProxyEnv(); + const { createHttpAgent: createRealAgent } = + await vi.importActual( + "@/api/httpAgent", + ); + const agent = await createRealAgent( + config({ "coder.tlsCaFile": certPath }), + ); + + await expect(get({ agent })).resolves.toBe(200); + }); +}); + +describe("getEcdhCurve", () => { + // Re-imported so each test runs the probe, bypassing the mock above. + async function probe(): Promise { + vi.resetModules(); + const actual = + await vi.importActual( + "@/api/keyExchange", + ); + return actual.getEcdhCurve(); + } + + it("prefers the post-quantum hybrid group when the runtime supports it", async () => { + await expect(probe()).resolves.toBe("X25519MLKEM768:X25519:P-256:P-384"); + }); + + it("keeps the runtime default when the runtime rejects the groups", async () => { + vi.spyOn(tls, "createSecureContext").mockImplementationOnce(() => { + throw new Error("Failed to set ECDH curve"); + }); + + await expect(probe()).resolves.toBeUndefined(); + }); +}); From 911cf2388b1772f3f229c413153bc3ae3f02ed8d Mon Sep 17 00:00:00 2001 From: Ehab Younes Date: Fri, 4 Dec 2026 15:21:28 +0000 Subject: [PATCH 2/2] fix(api): stop reporting refused redirects as certificate errors A refused cross-origin redirect carries the target hostname in its message, and the client certificate classifier matched alert names anywhere in a message. Match alert names only in TLS error shapes and skip errors caused by a refused redirect. The key exchange transport reads axios options as own properties, and a test covers its cross-origin redirect guard with the transport active. --- CHANGELOG.md | 5 ++ docs/ARCHITECTURE.md | 5 +- src/api/keyExchange.ts | 19 ++++- src/error/clientCertificateError.ts | 21 +++-- test/unit/api/coderApi.origin.test.ts | 10 +++ test/unit/api/keyExchange.test.ts | 81 +++++++++++-------- .../unit/error/clientCertificateError.test.ts | 35 ++++++-- 7 files changed, 126 insertions(+), 50 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50fdfd4dbe..19fa49074c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,11 @@ exchange `X25519MLKEM768` when VS Code and the deployment support it, and fall back to classical key exchange otherwise. +### Fixed + +- When the deployment redirects to another URL, the extension reports the + redirect instead of mistaking it for a TLS client certificate error. + ## [v1.18.4](https://github.com/coder/vscode-coder/releases/tag/v1.18.4) 2026-12-03 ### Added diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 01b833edb6..8ee992c184 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -178,8 +178,9 @@ OpenSSH. Run it unelevated as well as in CI to catch privilege assumptions. REST and WebSocket connections to the deployment offer the post-quantum hybrid group `X25519MLKEM768` (`src/api/keyExchange.ts`). Electron before 44 does not offer it by default, and VS Code's proxy support replaces our agent, so the -groups are set on each request. Remove the module once the minimum supported -VS Code ships Electron 44. +groups are set on each request. A network that drops the larger ClientHello +this sends fails with a generic connection error, as Chrome would. Remove the +module once the minimum supported VS Code ships Electron 44. ## Other features diff --git a/src/api/keyExchange.ts b/src/api/keyExchange.ts index 7a6c92eb06..bee76419a7 100644 --- a/src/api/keyExchange.ts +++ b/src/api/keyExchange.ts @@ -55,11 +55,14 @@ export function createKeyExchangeTransport( callback: (res: IncomingMessage) => void, ) { options.ecdhCurve = ecdhCurve; - // Axios only wires these into follow-redirects for its own transport. - if (config.maxRedirects) { - options.maxRedirects = config.maxRedirects; + // Axios wires these into follow-redirects only for its own transport. + // It also wires `auth` and `sensitiveHeaders`, which we don't use; + // mirror them here if that changes. + const maxRedirects = own(config, "maxRedirects"); + if (maxRedirects) { + options.maxRedirects = maxRedirects; } - options.beforeRedirects.config = config.beforeRedirect; + options.beforeRedirects.config = own(config, "beforeRedirect"); const scheme = options.protocol === "https:" ? followRedirects.https @@ -68,3 +71,11 @@ export function createKeyExchangeTransport( }, }; } + +/** Reads an own property only, as axios does, so a polluted prototype can't supply it. */ +function own( + config: Pick, + key: K, +): AxiosRequestConfig[K] | undefined { + return Object.hasOwn(config, key) ? config[key] : undefined; +} diff --git a/src/error/clientCertificateError.ts b/src/error/clientCertificateError.ts index b6d852d2d7..b52dc04950 100644 --- a/src/error/clientCertificateError.ts +++ b/src/error/clientCertificateError.ts @@ -1,6 +1,7 @@ import * as vscode from "vscode"; import { CertificateError } from "./certificateError"; +import { CrossOriginRedirectError } from "./crossOriginRedirectError"; import { toError } from "./normalize"; /** @@ -50,12 +51,18 @@ function isClientCertAlert(code: number): code is CLIENT_CERT_ALERT { } /** - * Patterns to match SSL alert types in error messages (case-insensitive). + * Alert names as OpenSSL and BoringSSL render them, such as + * `SSLV3_ALERT_CERTIFICATE_EXPIRED` or `tlsv1 alert unknown ca`. */ -const ALERT_PATTERNS: ReadonlyArray<[string, CLIENT_CERT_ALERT]> = +const ALERT_PATTERNS: ReadonlyArray<[RegExp, CLIENT_CERT_ALERT]> = Object.entries(CLIENT_CERT_ALERT) .filter(isNumericEnumEntry) - .map(([name, code]) => [name.toLowerCase(), code]); + .map(([name, code]) => [ + new RegExp( + `(?:sslv3|tlsv1|ssl)[ _]alert[ _]${name.toLowerCase().replaceAll("_", "[ _]")}`, + ), + code, + ]); /** * Alert codes that may be recoverable by refreshing the certificate. @@ -134,14 +141,18 @@ export class ClientCertificateError extends CertificateError { * Returns undefined if the error is not a recognized client certificate error. */ private static detectAlertCode(err: unknown): CLIENT_CERT_ALERT | undefined { + // A refused redirect's message holds a deployment-chosen hostname, which + // can spell an alert name. + if (CrossOriginRedirectError.find(err)) { + return undefined; + } const message = this.extractErrorMessage(err).toLowerCase(); if (!message) { return undefined; } - // Check for alert patterns (case-insensitive via lowercase) for (const [pattern, alertCode] of ALERT_PATTERNS) { - if (message.includes(pattern)) { + if (pattern.test(message)) { return alertCode; } } diff --git a/test/unit/api/coderApi.origin.test.ts b/test/unit/api/coderApi.origin.test.ts index 4bccbda97f..b7ba32cad1 100644 --- a/test/unit/api/coderApi.origin.test.ts +++ b/test/unit/api/coderApi.origin.test.ts @@ -55,6 +55,16 @@ describe("CoderApi origin scoping", () => { expect(moved.requests).toHaveLength(0); }); + it("refuses a redirect to a host named like a TLS alert", async () => { + const deployment = await startRecordingServer( + () => "https://sslv3_alert_certificate_expired.example.com/api", + ); + + await expect(get(deployment.origin, "/api")).rejects.toBeInstanceOf( + CrossOriginRedirectError, + ); + }); + it("sends no auth headers to another origin", async () => { const deployment = await startRecordingServer(); const other = await startRecordingServer(); diff --git a/test/unit/api/keyExchange.test.ts b/test/unit/api/keyExchange.test.ts index 2a24089bb9..83641b0707 100644 --- a/test/unit/api/keyExchange.test.ts +++ b/test/unit/api/keyExchange.test.ts @@ -2,20 +2,14 @@ import fs from "node:fs/promises"; import https from "node:https"; import tls from "node:tls"; import { ProxyAgent } from "proxy-agent"; -import { - afterAll, - beforeAll, - describe, - expect, - it, - onTestFinished, - vi, -} from "vitest"; +import { describe, expect, it, onTestFinished, vi } from "vitest"; import { WebSocketServer } from "ws"; import { CoderApi } from "@/api/coderApi"; import { createHttpAgent } from "@/api/httpAgent"; +import { CrossOriginRedirectError } from "@/error/crossOriginRedirectError"; +import { startRecordingServer } from "../../mocks/recordingServer"; import { clearProxyEnv, config, @@ -46,64 +40,82 @@ vi.mock("@/api/httpAgent", async (importActual) => ({ describe("TLS key exchange", () => { const certPath = getFixturePath("tls", "self-signed.crt"); - let ca: Buffer; - let origin: string; - let server: https.Server; - beforeAll(async () => { - ca = await fs.readFile(certPath); + /** + * Serves HTTPS and WebSocket with only the test groups. `redirects` maps a + * path to a 302 location; every other path answers 200. + */ + async function setup(redirects: Record = {}) { + const ca = await fs.readFile(certPath); vi.mocked(createHttpAgent).mockResolvedValue( new ProxyAgent({ ca, getProxyForUrl: () => "" }), ); - server = https.createServer( + const server = https.createServer( { key: await fs.readFile(getFixturePath("tls", "self-signed.key")), cert: ca, ecdhCurve: TEST_ECDH_CURVE, }, (req, res) => { - if (req.url === "/old") { - res.writeHead(302, { location: "/new" }); + const location = redirects[req.url ?? ""]; + if (location) { + res.writeHead(302, { location }); } res.end(); }, ); new WebSocketServer({ server }).on("connection", (ws) => ws.close()); + onTestFinished( + () => new Promise((resolve) => server.close(() => resolve())), + ); // The fixture certificate is issued for localhost. await new Promise((resolve) => server.listen(0, "localhost", resolve), ); - origin = `https://localhost:${(server.address() as AddressInfo).port}`; - }); - - afterAll(() => server.close()); - - function get(options: https.RequestOptions): Promise { - return new Promise((resolve, reject) => - https - .get(`${origin}/`, options, (res) => resolve(res.statusCode)) - .on("error", reject), - ); - } + const origin = `https://localhost:${(server.address() as AddressInfo).port}`; - function createApi(): CoderApi { - new MockConfigurationProvider(); - const api = CoderApi.create(origin, "token", createMockLogger()); - onTestFinished(() => api.dispose()); - return api; + const get = (options: https.RequestOptions) => + new Promise((resolve, reject) => + https + .get(`${origin}/`, options, (res) => resolve(res.statusCode)) + .on("error", reject), + ); + const createApi = () => { + new MockConfigurationProvider(); + const api = CoderApi.create(origin, "token", createMockLogger()); + onTestFinished(() => api.dispose()); + return api; + }; + return { ca, get, createApi }; } it("fails the handshake without the requested groups", async () => { + const { ca, get } = await setup(); + await expect(get({ ca })).rejects.toThrow(/HANDSHAKE_FAILURE/); }); it("offers the groups on REST requests, across redirects", async () => { + const { createApi } = await setup({ "/old": "/new" }); + const response = await createApi().getAxiosInstance().get("/old"); expect(response.status).toBe(200); }); + it("refuses REST redirects to another origin", async () => { + const elsewhere = await startRecordingServer(); + const { createApi } = await setup({ "/moved": `${elsewhere.origin}/api` }); + + await expect( + createApi().getAxiosInstance().get("/moved"), + ).rejects.toBeInstanceOf(CrossOriginRedirectError); + expect(elsewhere.requests).toHaveLength(0); + }); + it("offers the groups on WebSocket connections", async () => { + const { createApi } = await setup(); + const socket = await createApi().watchBuildLogsByBuildId("build", []); await expect(socket.opened).resolves.toBeUndefined(); @@ -111,6 +123,7 @@ describe("TLS key exchange", () => { it("offers the groups from our own agent", async () => { clearProxyEnv(); + const { get } = await setup(); const { createHttpAgent: createRealAgent } = await vi.importActual( "@/api/httpAgent", diff --git a/test/unit/error/clientCertificateError.test.ts b/test/unit/error/clientCertificateError.test.ts index 9271a644dc..fc503cd4a7 100644 --- a/test/unit/error/clientCertificateError.test.ts +++ b/test/unit/error/clientCertificateError.test.ts @@ -5,6 +5,7 @@ import { CLIENT_CERT_ALERT, CLIENT_CERT_MESSAGES, } from "@/error/clientCertificateError"; +import { CrossOriginRedirectError } from "@/error/crossOriginRedirectError"; type AlertName = keyof typeof CLIENT_CERT_ALERT; type AlertTestCase = [AlertName, string]; @@ -40,18 +41,42 @@ describe("ClientCertificateError.fromError", () => { }); }); - describe("lowercase patterns", () => { + describe("OpenSSL text patterns", () => { it.each([ - ["certificate_expired", CLIENT_CERT_ALERT.CERTIFICATE_EXPIRED], - ["bad_certificate", CLIENT_CERT_ALERT.BAD_CERTIFICATE], - ["unknown_ca", CLIENT_CERT_ALERT.UNKNOWN_CA], + [ + "sslv3 alert certificate expired", + CLIENT_CERT_ALERT.CERTIFICATE_EXPIRED, + ], + ["sslv3 alert bad certificate", CLIENT_CERT_ALERT.BAD_CERTIFICATE], + ["tlsv1 alert unknown ca", CLIENT_CERT_ALERT.UNKNOWN_CA], ])("should detect %s", (pattern, expectedCode) => { const certError = ClientCertificateError.fromError( - new Error(`SSL error: ${pattern}`), + new Error(`SSL routines:ssl3_read_bytes:${pattern}`), ); expect(certError).toBeDefined(); expect(certError!.alertCode).toBe(expectedCode); }); + + it("should ignore an alert name outside an alert", () => { + expect( + ClientCertificateError.fromError( + new Error("getaddrinfo ENOTFOUND certificate_expired.example.com"), + ), + ).toBeUndefined(); + }); + + it("should ignore a refused redirect, whose hostname the deployment picks", () => { + const redirect = new CrossOriginRedirectError( + "https://sslv3_alert_certificate_expired.example.com/", + ); + expect( + ClientCertificateError.fromError( + new Error(`Redirected request failed: ${redirect.message}`, { + cause: redirect, + }), + ), + ).toBeUndefined(); + }); }); describe("SSL alert number fallback", () => {