Skip to content

Commit 911cf23

Browse files
committed
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.
1 parent e3c1ed8 commit 911cf23

7 files changed

Lines changed: 126 additions & 50 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@
1313
exchange `X25519MLKEM768` when VS Code and the deployment support it, and fall
1414
back to classical key exchange otherwise.
1515

16+
### Fixed
17+
18+
- When the deployment redirects to another URL, the extension reports the
19+
redirect instead of mistaking it for a TLS client certificate error.
20+
1621
## [v1.18.4](https://github.com/coder/vscode-coder/releases/tag/v1.18.4) 2026-12-03
1722

1823
### Added

‎docs/ARCHITECTURE.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,8 +178,9 @@ OpenSSH. Run it unelevated as well as in CI to catch privilege assumptions.
178178
REST and WebSocket connections to the deployment offer the post-quantum hybrid
179179
group `X25519MLKEM768` (`src/api/keyExchange.ts`). Electron before 44 does not
180180
offer it by default, and VS Code's proxy support replaces our agent, so the
181-
groups are set on each request. Remove the module once the minimum supported
182-
VS Code ships Electron 44.
181+
groups are set on each request. A network that drops the larger ClientHello
182+
this sends fails with a generic connection error, as Chrome would. Remove the
183+
module once the minimum supported VS Code ships Electron 44.
183184

184185
## Other features
185186

‎src/api/keyExchange.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,14 @@ export function createKeyExchangeTransport(
5555
callback: (res: IncomingMessage) => void,
5656
) {
5757
options.ecdhCurve = ecdhCurve;
58-
// Axios only wires these into follow-redirects for its own transport.
59-
if (config.maxRedirects) {
60-
options.maxRedirects = config.maxRedirects;
58+
// Axios wires these into follow-redirects only for its own transport.
59+
// It also wires `auth` and `sensitiveHeaders`, which we don't use;
60+
// mirror them here if that changes.
61+
const maxRedirects = own(config, "maxRedirects");
62+
if (maxRedirects) {
63+
options.maxRedirects = maxRedirects;
6164
}
62-
options.beforeRedirects.config = config.beforeRedirect;
65+
options.beforeRedirects.config = own(config, "beforeRedirect");
6366
const scheme =
6467
options.protocol === "https:"
6568
? followRedirects.https
@@ -68,3 +71,11 @@ export function createKeyExchangeTransport(
6871
},
6972
};
7073
}
74+
75+
/** Reads an own property only, as axios does, so a polluted prototype can't supply it. */
76+
function own<K extends keyof AxiosRequestConfig>(
77+
config: Pick<AxiosRequestConfig, K>,
78+
key: K,
79+
): AxiosRequestConfig[K] | undefined {
80+
return Object.hasOwn(config, key) ? config[key] : undefined;
81+
}

‎src/error/clientCertificateError.ts‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as vscode from "vscode";
22

33
import { CertificateError } from "./certificateError";
4+
import { CrossOriginRedirectError } from "./crossOriginRedirectError";
45
import { toError } from "./normalize";
56

67
/**
@@ -50,12 +51,18 @@ function isClientCertAlert(code: number): code is CLIENT_CERT_ALERT {
5051
}
5152

5253
/**
53-
* Patterns to match SSL alert types in error messages (case-insensitive).
54+
* Alert names as OpenSSL and BoringSSL render them, such as
55+
* `SSLV3_ALERT_CERTIFICATE_EXPIRED` or `tlsv1 alert unknown ca`.
5456
*/
55-
const ALERT_PATTERNS: ReadonlyArray<[string, CLIENT_CERT_ALERT]> =
57+
const ALERT_PATTERNS: ReadonlyArray<[RegExp, CLIENT_CERT_ALERT]> =
5658
Object.entries(CLIENT_CERT_ALERT)
5759
.filter(isNumericEnumEntry)
58-
.map(([name, code]) => [name.toLowerCase(), code]);
60+
.map(([name, code]) => [
61+
new RegExp(
62+
`(?:sslv3|tlsv1|ssl)[ _]alert[ _]${name.toLowerCase().replaceAll("_", "[ _]")}`,
63+
),
64+
code,
65+
]);
5966

6067
/**
6168
* Alert codes that may be recoverable by refreshing the certificate.
@@ -134,14 +141,18 @@ export class ClientCertificateError extends CertificateError {
134141
* Returns undefined if the error is not a recognized client certificate error.
135142
*/
136143
private static detectAlertCode(err: unknown): CLIENT_CERT_ALERT | undefined {
144+
// A refused redirect's message holds a deployment-chosen hostname, which
145+
// can spell an alert name.
146+
if (CrossOriginRedirectError.find(err)) {
147+
return undefined;
148+
}
137149
const message = this.extractErrorMessage(err).toLowerCase();
138150
if (!message) {
139151
return undefined;
140152
}
141153

142-
// Check for alert patterns (case-insensitive via lowercase)
143154
for (const [pattern, alertCode] of ALERT_PATTERNS) {
144-
if (message.includes(pattern)) {
155+
if (pattern.test(message)) {
145156
return alertCode;
146157
}
147158
}

‎test/unit/api/coderApi.origin.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,16 @@ describe("CoderApi origin scoping", () => {
5555
expect(moved.requests).toHaveLength(0);
5656
});
5757

58+
it("refuses a redirect to a host named like a TLS alert", async () => {
59+
const deployment = await startRecordingServer(
60+
() => "https://sslv3_alert_certificate_expired.example.com/api",
61+
);
62+
63+
await expect(get(deployment.origin, "/api")).rejects.toBeInstanceOf(
64+
CrossOriginRedirectError,
65+
);
66+
});
67+
5868
it("sends no auth headers to another origin", async () => {
5969
const deployment = await startRecordingServer();
6070
const other = await startRecordingServer();

‎test/unit/api/keyExchange.test.ts‎

Lines changed: 47 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,14 @@ import fs from "node:fs/promises";
22
import https from "node:https";
33
import tls from "node:tls";
44
import { ProxyAgent } from "proxy-agent";
5-
import {
6-
afterAll,
7-
beforeAll,
8-
describe,
9-
expect,
10-
it,
11-
onTestFinished,
12-
vi,
13-
} from "vitest";
5+
import { describe, expect, it, onTestFinished, vi } from "vitest";
146
import { WebSocketServer } from "ws";
157

168
import { CoderApi } from "@/api/coderApi";
179
import { createHttpAgent } from "@/api/httpAgent";
10+
import { CrossOriginRedirectError } from "@/error/crossOriginRedirectError";
1811

12+
import { startRecordingServer } from "../../mocks/recordingServer";
1913
import {
2014
clearProxyEnv,
2115
config,
@@ -46,71 +40,90 @@ vi.mock("@/api/httpAgent", async (importActual) => ({
4640

4741
describe("TLS key exchange", () => {
4842
const certPath = getFixturePath("tls", "self-signed.crt");
49-
let ca: Buffer;
50-
let origin: string;
51-
let server: https.Server;
5243

53-
beforeAll(async () => {
54-
ca = await fs.readFile(certPath);
44+
/**
45+
* Serves HTTPS and WebSocket with only the test groups. `redirects` maps a
46+
* path to a 302 location; every other path answers 200.
47+
*/
48+
async function setup(redirects: Record<string, string> = {}) {
49+
const ca = await fs.readFile(certPath);
5550
vi.mocked(createHttpAgent).mockResolvedValue(
5651
new ProxyAgent({ ca, getProxyForUrl: () => "" }),
5752
);
58-
server = https.createServer(
53+
const server = https.createServer(
5954
{
6055
key: await fs.readFile(getFixturePath("tls", "self-signed.key")),
6156
cert: ca,
6257
ecdhCurve: TEST_ECDH_CURVE,
6358
},
6459
(req, res) => {
65-
if (req.url === "/old") {
66-
res.writeHead(302, { location: "/new" });
60+
const location = redirects[req.url ?? ""];
61+
if (location) {
62+
res.writeHead(302, { location });
6763
}
6864
res.end();
6965
},
7066
);
7167
new WebSocketServer({ server }).on("connection", (ws) => ws.close());
68+
onTestFinished(
69+
() => new Promise<void>((resolve) => server.close(() => resolve())),
70+
);
7271
// The fixture certificate is issued for localhost.
7372
await new Promise<void>((resolve) =>
7473
server.listen(0, "localhost", resolve),
7574
);
76-
origin = `https://localhost:${(server.address() as AddressInfo).port}`;
77-
});
78-
79-
afterAll(() => server.close());
80-
81-
function get(options: https.RequestOptions): Promise<number | undefined> {
82-
return new Promise((resolve, reject) =>
83-
https
84-
.get(`${origin}/`, options, (res) => resolve(res.statusCode))
85-
.on("error", reject),
86-
);
87-
}
75+
const origin = `https://localhost:${(server.address() as AddressInfo).port}`;
8876

89-
function createApi(): CoderApi {
90-
new MockConfigurationProvider();
91-
const api = CoderApi.create(origin, "token", createMockLogger());
92-
onTestFinished(() => api.dispose());
93-
return api;
77+
const get = (options: https.RequestOptions) =>
78+
new Promise<number | undefined>((resolve, reject) =>
79+
https
80+
.get(`${origin}/`, options, (res) => resolve(res.statusCode))
81+
.on("error", reject),
82+
);
83+
const createApi = () => {
84+
new MockConfigurationProvider();
85+
const api = CoderApi.create(origin, "token", createMockLogger());
86+
onTestFinished(() => api.dispose());
87+
return api;
88+
};
89+
return { ca, get, createApi };
9490
}
9591

9692
it("fails the handshake without the requested groups", async () => {
93+
const { ca, get } = await setup();
94+
9795
await expect(get({ ca })).rejects.toThrow(/HANDSHAKE_FAILURE/);
9896
});
9997

10098
it("offers the groups on REST requests, across redirects", async () => {
99+
const { createApi } = await setup({ "/old": "/new" });
100+
101101
const response = await createApi().getAxiosInstance().get("/old");
102102

103103
expect(response.status).toBe(200);
104104
});
105105

106+
it("refuses REST redirects to another origin", async () => {
107+
const elsewhere = await startRecordingServer();
108+
const { createApi } = await setup({ "/moved": `${elsewhere.origin}/api` });
109+
110+
await expect(
111+
createApi().getAxiosInstance().get("/moved"),
112+
).rejects.toBeInstanceOf(CrossOriginRedirectError);
113+
expect(elsewhere.requests).toHaveLength(0);
114+
});
115+
106116
it("offers the groups on WebSocket connections", async () => {
117+
const { createApi } = await setup();
118+
107119
const socket = await createApi().watchBuildLogsByBuildId("build", []);
108120

109121
await expect(socket.opened).resolves.toBeUndefined();
110122
});
111123

112124
it("offers the groups from our own agent", async () => {
113125
clearProxyEnv();
126+
const { get } = await setup();
114127
const { createHttpAgent: createRealAgent } =
115128
await vi.importActual<typeof import("@/api/httpAgent")>(
116129
"@/api/httpAgent",

‎test/unit/error/clientCertificateError.test.ts‎

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
CLIENT_CERT_ALERT,
66
CLIENT_CERT_MESSAGES,
77
} from "@/error/clientCertificateError";
8+
import { CrossOriginRedirectError } from "@/error/crossOriginRedirectError";
89

910
type AlertName = keyof typeof CLIENT_CERT_ALERT;
1011
type AlertTestCase = [AlertName, string];
@@ -40,18 +41,42 @@ describe("ClientCertificateError.fromError", () => {
4041
});
4142
});
4243

43-
describe("lowercase patterns", () => {
44+
describe("OpenSSL text patterns", () => {
4445
it.each<LowercaseTestCase>([
45-
["certificate_expired", CLIENT_CERT_ALERT.CERTIFICATE_EXPIRED],
46-
["bad_certificate", CLIENT_CERT_ALERT.BAD_CERTIFICATE],
47-
["unknown_ca", CLIENT_CERT_ALERT.UNKNOWN_CA],
46+
[
47+
"sslv3 alert certificate expired",
48+
CLIENT_CERT_ALERT.CERTIFICATE_EXPIRED,
49+
],
50+
["sslv3 alert bad certificate", CLIENT_CERT_ALERT.BAD_CERTIFICATE],
51+
["tlsv1 alert unknown ca", CLIENT_CERT_ALERT.UNKNOWN_CA],
4852
])("should detect %s", (pattern, expectedCode) => {
4953
const certError = ClientCertificateError.fromError(
50-
new Error(`SSL error: ${pattern}`),
54+
new Error(`SSL routines:ssl3_read_bytes:${pattern}`),
5155
);
5256
expect(certError).toBeDefined();
5357
expect(certError!.alertCode).toBe(expectedCode);
5458
});
59+
60+
it("should ignore an alert name outside an alert", () => {
61+
expect(
62+
ClientCertificateError.fromError(
63+
new Error("getaddrinfo ENOTFOUND certificate_expired.example.com"),
64+
),
65+
).toBeUndefined();
66+
});
67+
68+
it("should ignore a refused redirect, whose hostname the deployment picks", () => {
69+
const redirect = new CrossOriginRedirectError(
70+
"https://sslv3_alert_certificate_expired.example.com/",
71+
);
72+
expect(
73+
ClientCertificateError.fromError(
74+
new Error(`Redirected request failed: ${redirect.message}`, {
75+
cause: redirect,
76+
}),
77+
),
78+
).toBeUndefined();
79+
});
5580
});
5681

5782
describe("SSL alert number fallback", () => {

0 commit comments

Comments
 (0)