fix(panel): harden CloudCode proxy tunnels, pooling, and crash recovery

- Support SOCKS5/SOCKS5h (RFC 1928/1929 auth + IPv4/domain/IPv6 targets), authenticated HTTP/HTTPS CONNECT proxies, tunnel timeouts, and Windows <local>/wildcard NO_PROXY rules without mangling non-HTTP schemes
- Pool upstream TLS tunnels via a Keep-Alive HTTPS agent with explicit http/1.1 ALPN and hop-by-hop header stripping instead of re-handshaking per request
- Attach upfront stream and socket error guards across passthrough and rewrite paths and tear down active upstream requests immediately on client disconnect
- Persist sticky local proxy port and switched state in cloudcode-proxy-state.json to reuse ports across reloads and self-heal orphaned SetCloudCodeURL after unexpected exits
This commit is contained in:
fish
2026-11-24 14:37:49 +09:00
parent e4e597931d
commit 030d894988
2 changed files with 1047 additions and 74 deletions
@@ -1,13 +1,21 @@
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import http from 'node:http';
import https from 'node:https';
import net from 'node:net';
import test from 'node:test';
import tls from 'node:tls';
import vm from 'node:vm';
import { createContextWindowSyncExpression } from '../backend/context-windows.mjs';
import {
createCloudCodeProxyController,
detectSystemHttpsProxy,
extractUpstreamCheckpointDefaults,
isValidUpstreamCloudCodeUrl,
normalizeCcProxyCandidateUrl,
openCcProxyTunnelSocket,
rewriteFetchAvailableModelsPayload,
shouldCcProxyBypassHost,
} from '../backend/cloudcode-proxy.mjs';
import { createWindowBridgeController } from '../backend/window-bridge.mjs';
import { backendHarness } from './backend-harness.mjs';
@@ -784,3 +792,423 @@ test('SettingsOtherTab renders independent Main Agent and Subagents/Swarm switch
globalThis.fetch = origFetch;
}
});
function createSelfSignedTlsFixture() {
const derLen = (len) => {
if (len < 0x80) return Buffer.from([len]);
const hex = len.toString(16).padStart(len > 0xff ? 4 : 2, '0');
const bytes = Buffer.from(hex, 'hex');
return Buffer.concat([Buffer.from([0x80 | bytes.length]), bytes]);
};
const asn1 = (tag, body) => Buffer.concat([Buffer.from([tag]), derLen(body.length), body]);
const seq = (...items) => asn1(0x30, Buffer.concat(items));
const set = (...items) => asn1(0x31, Buffer.concat(items));
const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
namedCurve: 'prime256v1',
});
const spkiDer = publicKey.export({ type: 'spki', format: 'der' });
// ecdsa-with-SHA256 (1.2.840.10045.4.3.2)
const sigAlg = seq(Buffer.from([0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02]));
const cnAttr = seq(
Buffer.from([0x06, 0x03, 0x55, 0x04, 0x03]),
asn1(0x0c, Buffer.from('localhost', 'utf8'))
);
const name = seq(set(cnAttr));
const validity = seq(
asn1(0x17, Buffer.from('250101000000Z', 'ascii')),
asn1(0x17, Buffer.from('350101000000Z', 'ascii'))
);
const tbs = seq(
asn1(0xa0, Buffer.from([0x02, 0x01, 0x02])),
asn1(0x02, Buffer.from([0x01])),
sigAlg,
name,
validity,
name,
spkiDer
);
const sig = crypto.sign('sha256', tbs, privateKey);
const certDer = seq(tbs, sigAlg, asn1(0x03, Buffer.concat([Buffer.from([0x00]), sig])));
const certPem = `-----BEGIN CERTIFICATE-----\n${certDer.toString('base64').match(/.{1,64}/g).join('\n')}\n-----END CERTIFICATE-----\n`;
const keyPem = privateKey.export({ type: 'pkcs8', format: 'pem' });
return { key: keyPem, cert: certPem };
}
test('cloudcode-proxy handles socks5:// and authenticated HTTP/HTTPS proxies, enforces tunnel timeouts, and destroys upstream requests on client abort', async () => {
// 1. Proxy URL normalization & environment detection (no http://socks5://... mangling!)
assert.equal(normalizeCcProxyCandidateUrl('socks5://127.0.0.1:1080'), 'socks5://127.0.0.1:1080');
assert.equal(
normalizeCcProxyCandidateUrl('socks5h://dev:p%40ss@127.0.0.1:1080'),
'socks5h://dev:p%40ss@127.0.0.1:1080'
);
assert.equal(normalizeCcProxyCandidateUrl('socks://127.0.0.1:1080'), 'socks5://127.0.0.1:1080');
assert.equal(normalizeCcProxyCandidateUrl('127.0.0.1:7890'), 'http://127.0.0.1:7890');
assert.equal(normalizeCcProxyCandidateUrl('https://proxy.example:8443'), 'https://proxy.example:8443');
assert.equal(normalizeCcProxyCandidateUrl('socks4://127.0.0.1:1080'), '');
assert.equal(normalizeCcProxyCandidateUrl('pac+http://127.0.0.1/proxy.pac'), '');
assert.equal(
await detectSystemHttpsProxy('daily-cloudcode-pa.googleapis.com', {
env: { ALL_PROXY: 'socks5://127.0.0.1:1080' },
platform: 'linux',
}),
'socks5://127.0.0.1:1080'
);
assert.equal(
await detectSystemHttpsProxy('daily-cloudcode-pa.googleapis.com', {
env: { ALL_PROXY: 'socks4://127.0.0.1:1080' },
platform: 'linux',
}),
''
);
assert.equal(shouldCcProxyBypassHost('intranet-host', 'localhost;127.*;<local>'), true);
assert.equal(shouldCcProxyBypassHost('127.0.0.1', 'localhost;127.*;<local>'), true);
assert.equal(shouldCcProxyBypassHost('daily-cloudcode-pa.googleapis.com', 'localhost;127.*;<local>'), false);
assert.equal(shouldCcProxyBypassHost('daily-cloudcode-pa.googleapis.com', '*.googleapis.com'), true);
assert.equal(shouldCcProxyBypassHost('[::1]', '[::1]:8080'), true);
// 2. Real HTTPS upstream + pooled SOCKS5 proxy + mid-stream upstream reset + HTTP CONNECT auth + hung timeout + crash recovery
const tlsCreds = createSelfSignedTlsFixture();
let resolveUpstreamAborted;
const upstreamAbortedPromise = new Promise((r) => {
resolveUpstreamAborted = r;
});
const httpsUpstream = https.createServer(tlsCreds, (req, res) => {
if (req.url?.includes('fetchAvailableModels')) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(
JSON.stringify({
models: {
'gemini-4-carbon-high': {
model: carbon,
maxTokens: 1048576,
modelExperiments: {
experiments: {
CASCADE_USE_EXPERIMENT_CHECKPOINTER: {
stringValue: JSON.stringify({ max_token_limit: '512000' }),
},
},
},
},
},
})
);
return;
}
if (req.url?.includes('slowStream')) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('first-chunk\n');
res.on('close', () => {
resolveUpstreamAborted(true);
});
return;
}
if (req.url?.includes('upstreamMidStreamReset')) {
res.writeHead(200, { 'Content-Type': 'text/plain', 'Transfer-Encoding': 'chunked' });
res.write('partial-token-chunk\n', () => {
setTimeout(() => {
const rawTcp = res.socket?._parent || null;
if (rawTcp && typeof rawTcp.resetAndDestroy === 'function') {
rawTcp.resetAndDestroy();
} else {
res.socket?.destroy();
}
}, 15).unref();
});
return;
}
res.writeHead(200);
res.end('ok');
});
await new Promise((r) => httpsUpstream.listen(0, '127.0.0.1', r));
const upstreamPort = httpsUpstream.address().port;
const upstreamHttpsUrl = `https://127.0.0.1:${upstreamPort}`;
// Minimal RFC 1928 + RFC 1929 SOCKS5 test server requiring dev:s3cr3t (supports IPv4 0x01, domain 0x03, IPv6 0x04)
let socksConnectCount = 0;
let lastSocksAtyp = 0;
let lastSocksIpv6Hex = '';
const testServerSockets = new Set();
const trackSock = (s) => {
testServerSockets.add(s);
s.on('close', () => testServerSockets.delete(s));
};
httpsUpstream.on('connection', trackSock);
const socksServer = net.createServer((clientSock) => {
trackSock(clientSock);
let stage = 0;
clientSock.on('data', (buf) => {
if (stage === 0) {
assert.equal(buf[0], 0x05);
assert.ok(buf.subarray(2, 2 + buf[1]).includes(0x02), 'client offers RFC1929 user/pass');
stage = 1;
clientSock.write(Buffer.from([0x05, 0x02]));
return;
}
if (stage === 1) {
const uLen = buf[1];
const user = buf.subarray(2, 2 + uLen).toString('utf8');
const pLen = buf[2 + uLen];
const pass = buf.subarray(3 + uLen, 3 + uLen + pLen).toString('utf8');
if (user !== 'dev' || pass !== 's3cr3t') {
clientSock.end(Buffer.from([0x01, 0x01]));
return;
}
stage = 2;
clientSock.write(Buffer.from([0x01, 0x00]));
return;
}
if (stage === 2) {
stage = 3;
socksConnectCount += 1;
lastSocksAtyp = buf[3];
let portOffset = 4;
if (buf[3] === 0x01) portOffset = 8;
else if (buf[3] === 0x03) portOffset = 5 + buf[4];
else if (buf[3] === 0x04) {
lastSocksIpv6Hex = buf.subarray(4, 20).toString('hex');
portOffset = 20;
}
const dstPort = buf.readUInt16BE(portOffset);
const upstreamSock = net.connect({ host: '127.0.0.1', port: dstPort }, () => {
clientSock.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0, 0]));
clientSock.pipe(upstreamSock);
upstreamSock.pipe(clientSock);
});
trackSock(upstreamSock);
upstreamSock.on('error', () => clientSock.destroy());
clientSock.on('error', () => upstreamSock.destroy());
}
});
});
await new Promise((r) => socksServer.listen(0, '127.0.0.1', r));
const socksPort = socksServer.address().port;
// HTTP CONNECT proxy requiring Basic alice:p@ss
let seenProxyAuth = '';
const httpProxyServer = http.createServer();
httpProxyServer.on('connection', trackSock);
httpProxyServer.on('connect', (req, clientSock, head) => {
trackSock(clientSock);
seenProxyAuth = String(req.headers['proxy-authorization'] || '');
const expected = `Basic ${Buffer.from('alice:p@ss', 'utf8').toString('base64')}`;
if (seenProxyAuth !== expected) {
clientSock.write('HTTP/1.1 407 Proxy Authentication Required\r\n\r\n');
clientSock.destroy();
return;
}
const [, rawPort] = String(req.url || '').split(':');
const upSock = net.connect({ host: '127.0.0.1', port: Number(rawPort) }, () => {
clientSock.write('HTTP/1.1 200 Connection Established\r\n\r\n');
if (head && head.length > 0) upSock.write(head);
clientSock.pipe(upSock);
upSock.pipe(clientSock);
});
trackSock(upSock);
upSock.on('error', () => clientSock.destroy());
clientSock.on('error', () => upSock.destroy());
});
await new Promise((r) => httpProxyServer.listen(0, '127.0.0.1', r));
const httpProxyPort = httpProxyServer.address().port;
// Hung proxy server that accepts TCP and never responds
const hungSockets = new Set();
const hungProxyServer = net.createServer((s) => {
hungSockets.add(s);
s.on('close', () => hungSockets.delete(s));
});
await new Promise((r) => hungProxyServer.listen(0, '127.0.0.1', r));
const hungPort = hungProxyServer.address().port;
let activeProxyUrl = `socks5://dev:s3cr3t@127.0.0.1:${socksPort}`;
const makeProxyCtrl = (extraOpts = {}) =>
createCloudCodeProxyController({
allowHttpUpstream: true,
allowTestEndpoint: true,
tunnelTimeoutMs: 120,
upstreamTlsOptions: { rejectUnauthorized: false },
detectUpstreamFn: () => upstreamHttpsUrl,
detectProxyFn: async () => activeProxyUrl,
getEndpointFn: () => ({ addr: '127.0.0.1:44444', baseUrl: 'http://127.0.0.1:44444', csrfToken: 'tok' }),
callRpcFn: async () => ({}),
...extraOpts,
});
const ctrlSocks = makeProxyCtrl();
const ctrlHttpAuth = makeProxyCtrl();
const ctrlHung = makeProxyCtrl();
try {
// A. SOCKS5 tunnel rewrites fetchAvailableModels over real TLS and POOLS Keep-Alive tunnel across consecutive requests
const stSocks = await ctrlSocks.reconcile({ enabled: true, rulesByModelId: { [carbon]: 400000 } });
const resSocks = await fetch(`${stSocks.localUrl}/v1internal:fetchAvailableModels`, {
method: 'POST',
body: '{}',
});
const rawSocksBody = await resSocks.text();
assert.equal(resSocks.status, 200, rawSocksBody);
assert.equal(socksConnectCount, 1);
const jsonSocks = JSON.parse(rawSocksBody);
assert.equal(
JSON.parse(
jsonSocks.models['gemini-4-carbon-high'].modelExperiments.experiments.CASCADE_USE_EXPERIMENT_CHECKPOINTER
.stringValue
).max_token_limit,
'400000'
);
const resPassReuse = await fetch(`${stSocks.localUrl}/v1internal:countTokens`, {
method: 'POST',
body: '{}',
});
assert.equal(await resPassReuse.text(), 'ok');
assert.equal(socksConnectCount, 1, 'Keep-Alive reuses warm SOCKS5 TLS tunnel without re-handshaking');
// B. Client mid-stream abort immediately closes upstream request/socket over SOCKS5 tunnel
await new Promise((resolve, reject) => {
const clientReq = http.request(`${stSocks.localUrl}/v1internal:slowStream`, { method: 'POST' }, (res) => {
res.once('data', () => {
clientReq.destroy();
resolve();
});
});
clientReq.on('error', () => {});
clientReq.end('{}');
setTimeout(() => reject(new Error('Did not receive first chunk')), 2000).unref();
});
const abortedCleanly = await Promise.race([
upstreamAbortedPromise,
new Promise((_, rej) => setTimeout(() => rej(new Error('Upstream stream leaked after client abort')), 1500)),
]);
assert.equal(abortedCleanly, true);
// B2. Upstream mid-stream TCP reset in streaming passthrough terminates client response cleanly without unhandled error
const resetHandled = await new Promise((resolve, reject) => {
let seenChunk = '';
const clientReq = http.request(
`${stSocks.localUrl}/v1internal:upstreamMidStreamReset`,
{ method: 'POST' },
(res) => {
res.on('data', (c) => {
seenChunk += c.toString('utf8');
});
res.on('error', () => resolve(seenChunk));
res.on('aborted', () => resolve(seenChunk));
res.on('close', () => resolve(seenChunk));
}
);
clientReq.on('error', () => resolve(seenChunk));
clientReq.end('{}');
setTimeout(() => reject(new Error('Mid-stream upstream reset hung client response')), 2000).unref();
});
assert.match(resetHandled, /partial-token-chunk/);
// B3. SOCKS5 IPv6 target ([::1]) encodes ATYP = 0x04 16-byte binary address
const ipv6TlsSock = await openCcProxyTunnelSocket(
{ http, https, net, tls },
'[::1]',
upstreamPort,
`socks5://dev:s3cr3t@127.0.0.1:${socksPort}`,
{ timeoutMs: 2000, tlsOptions: { rejectUnauthorized: false } }
);
assert.equal(lastSocksAtyp, 0x04);
assert.equal(lastSocksIpv6Hex, '00000000000000000000000000000001');
ipv6TlsSock.destroy();
// C. Authenticated HTTP CONNECT proxy sends Proxy-Authorization: Basic
activeProxyUrl = `http://alice:p%40ss@127.0.0.1:${httpProxyPort}`;
const stHttp = await ctrlHttpAuth.reconcile({ enabled: true, rulesByModelId: { [carbon]: 320000 } });
const resHttp = await fetch(`${stHttp.localUrl}/v1internal:fetchAvailableModels`, {
method: 'POST',
body: '{}',
});
assert.equal(resHttp.status, 200);
assert.ok(seenProxyAuth.startsWith('Basic '), 'Proxy-Authorization header sent');
// D. Hung proxy times out cleanly with 502 instead of hanging forever
activeProxyUrl = `http://127.0.0.1:${hungPort}`;
const stHung = await ctrlHung.reconcile({ enabled: true, rulesByModelId: { [carbon]: 320000 } });
const resHung = await fetch(`${stHung.localUrl}/v1internal:fetchAvailableModels`, {
method: 'POST',
body: '{}',
});
assert.equal(resHung.status, 502);
assert.match(await resHung.text(), /timed out/i);
// E. Sticky localPort across reloads and automatic SetCloudCodeURL crash healing on next startup
activeProxyUrl = '';
let diskState = null;
const crashRpcLog = [];
const ctrlBeforeReload = makeProxyCtrl({
stateFilePath: '/virtual/cloudcode-proxy-state.json',
loadJsonFn: () => diskState,
saveJsonFn: (_p, data) => {
diskState = data;
},
callRpcFn: async (method, body) => {
crashRpcLog.push({ method, body });
return {};
},
});
const stBefore = await ctrlBeforeReload.reconcile({ enabled: true, rulesByModelId: { [carbon]: 300000 } });
const stickyPort = Number(new URL(stBefore.localUrl).port);
assert.equal(diskState?.switched, true);
assert.equal(diskState?.localPort, stickyPort);
await ctrlBeforeReload.stop();
assert.equal(diskState?.switched, false);
assert.equal(diskState?.localPort, stickyPort);
// Re-enabling in a new controller re-binds the exact same sticky port
const ctrlAfterReload = makeProxyCtrl({
stateFilePath: '/virtual/cloudcode-proxy-state.json',
loadJsonFn: () => diskState,
saveJsonFn: (_p, data) => {
diskState = data;
},
callRpcFn: async (method, body) => {
crashRpcLog.push({ method, body });
return {};
},
});
const stAfter = await ctrlAfterReload.reconcile({ enabled: true, rulesByModelId: { [carbon]: 300000 } });
assert.equal(stAfter.localUrl, stBefore.localUrl, 'reuses sticky local port across worker reloads');
await ctrlAfterReload.stop();
// Simulate hard crash where previous worker left switched=true on disk, then new worker boots with Swarm disabled
diskState = { switched: true, localPort: stickyPort, upstreamUrl: upstreamHttpsUrl, updatedAtMs: Date.now() };
crashRpcLog.length = 0;
const ctrlHealer = makeProxyCtrl({
stateFilePath: '/virtual/cloudcode-proxy-state.json',
loadJsonFn: () => diskState,
saveJsonFn: (_p, data) => {
diskState = data;
},
callRpcFn: async (method, body) => {
crashRpcLog.push({ method, body });
return {};
},
});
await ctrlHealer.reconcile({ enabled: false, rulesByModelId: {} });
assert.equal(crashRpcLog.length, 1);
assert.equal(crashRpcLog[0].method, 'SetCloudCodeURL');
assert.equal(crashRpcLog[0].body.url, upstreamHttpsUrl, 'heals orphaned Language Server CloudCode URL');
assert.equal(diskState?.switched, false);
await ctrlHealer.stop();
} finally {
await ctrlSocks.stop();
await ctrlHttpAuth.stop();
await ctrlHung.stop();
httpsUpstream.closeAllConnections?.();
httpProxyServer.closeAllConnections?.();
for (const s of hungSockets) s.destroy();
for (const s of testServerSockets) s.destroy();
await Promise.all([
new Promise((r) => httpsUpstream.close(() => r())),
new Promise((r) => socksServer.close(() => r())),
new Promise((r) => httpProxyServer.close(() => r())),
new Promise((r) => hungProxyServer.close(() => r())),
]);
}
});