Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 171 additions & 0 deletions apps/cli/e2e/server/backend-tls.e2e-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import { readFileSync } from 'node:fs';
import * as https from 'node:https';
import { join } from 'node:path';
import request from 'supertest';

import * as commandUtils from '../../src/command/utils';
import { ADCServer } from '../../src/server';
import { mockBackend } from '../support/utils';

const tlsAssetsDir = join(__dirname, '../assets/tls');
const readCert = (fileName: string) =>
readFileSync(join(tlsAssetsDir, fileName), 'utf-8');

describe('Server - Backend TLS', () => {
let server: ADCServer;

beforeAll(() => {
server = new ADCServer({
listen: new URL('http://127.0.1:3000'),
listenStatus: 3002,
});
});

afterEach(() => {
vi.restoreAllMocks();
});

it('rejects a request with tlsClientCert but no tlsClientKey', async () => {
const { status, body } = await request(server.TEST_ONLY_getExpress())
.put('/sync')
.send({
task: {
opts: {
backend: 'mock',
server: 'http://1.1.1.1:3000',
token: 'mock',
cacheKey: 'default',
tlsClientCert: readCert('client.cer'),
},
config: {},
},
});

expect(status).toEqual(400);
expect(
(body.errors as Array<{ path: string[] }>).some((issue) =>
issue.path.includes('tlsClientKey'),
),
).toBe(true);
});

it('rejects a caCert that does not look like PEM content', async () => {
const { status, body } = await request(server.TEST_ONLY_getExpress())
.put('/sync')
.send({
task: {
opts: {
backend: 'mock',
server: 'http://1.1.1.1:3000',
token: 'mock',
cacheKey: 'default',
caCert: 'not-a-pem',
},
config: {},
},
});

expect(status).toEqual(400);
expect(
(body.errors as Array<{ path: string[] }>).some((issue) =>
issue.path.includes('caCert'),
),
).toBe(true);
});

it('reuses the same pooled agent across requests with identical TLS material, but not across different material', async () => {
const loadBackendSpy = vi
.spyOn(commandUtils, 'loadBackend')
.mockImplementation(() => mockBackend());

const sendSync = (caCert?: string) =>
request(server.TEST_ONLY_getExpress())
.put('/sync')
.send({
task: {
opts: {
backend: 'mock',
server: 'http://1.1.1.1:3000',
token: 'mock',
cacheKey: 'default',
...(caCert ? { caCert } : {}),
},
config: {},
},
});

const ca = readCert('ca.cer');
await sendSync(ca);
await sendSync(ca);
await sendSync(); // no TLS material at all -> a different, insecure-default agent

expect(loadBackendSpy).toHaveBeenCalledTimes(3);
const httpsAgents = loadBackendSpy.mock.calls.map(
([, opts]) => (opts as { httpsAgent: unknown }).httpsAgent,
);
expect(httpsAgents[0]).toBe(httpsAgents[1]);
expect(httpsAgents[0]).not.toBe(httpsAgents[2]);
});

describe('real backend connection', () => {
let backendServer: https.Server;
let backendPort: number;

beforeAll(async () => {
backendServer = https.createServer(
{ cert: readCert('server.cer'), key: readCert('server.key') },
(_, res) => res.end('{}'),
);
await new Promise<void>((resolve) =>
backendServer.listen(0, '127.0.0.1', resolve),
);
backendPort = (backendServer.address() as { port: number }).port;
});

afterAll(async () => {
await new Promise<void>((resolve) => backendServer.close(() => resolve()));
});

it('fails with a certificate verification error when no caCert is provided', async () => {
const { status, body } = await request(server.TEST_ONLY_getExpress())
.put('/sync')
.send({
task: {
opts: {
backend: 'apisix',
server: `https://127.0.0.1:${backendPort}`,
token: 'mock',
cacheKey: 'default',
},
config: {},
},
});

expect(status).toEqual(500);
expect(body.message).toMatch(/self.signed certificate|unable to verify/i);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
});

it('does not fail on certificate verification once the signing caCert is provided', async () => {
const { status, body } = await request(server.TEST_ONLY_getExpress())
.put('/sync')
.send({
task: {
opts: {
backend: 'apisix',
server: `https://127.0.0.1:${backendPort}`,
token: 'mock',
cacheKey: 'default',
caCert: readCert('ca.cer'),
},
config: {},
},
});

// the fake backend doesn't implement the real Admin API, so the request
// may still fail for unrelated reasons; the point of this assertion is
// that it no longer fails on TLS certificate verification
expect(status).toEqual(500);
expect(body.message).not.toMatch(/self.signed certificate|unable to verify/i);
});
});
});
4 changes: 4 additions & 0 deletions apps/cli/eslint.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ export default config([
'{projectRoot}/vitest.config.{js,ts,mjs,mts}',
'{projectRoot}/e2e/**/*',
],
// false positive: this workspace also resolves an unrelated,
// transitive lru-cache@5.1.1 (via @babel/helper-compilation-targets),
// which confuses the rule's usage detection for our direct dependency
ignoredDependencies: ['lru-cache'],
},
],
},
Expand Down
1 change: 1 addition & 0 deletions apps/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"js-yaml": "catalog:",
"listr2": "catalog:",
"lodash-es": "catalog:",
"lru-cache": "catalog:",
"parse-duration": "^2.1.5",
"pluralize": "^8.0.0",
"qs": "^6.14.1",
Expand Down
138 changes: 138 additions & 0 deletions apps/cli/src/server/agent-pool.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { HttpsAgent } from 'agentkeepalive';
import * as https from 'node:https';
import { join } from 'node:path';
import { readFileSync } from 'node:fs';

import {
fingerprintTlsMaterial,
getHttpsAgent,
type TlsMaterial,
} from './agent-pool';

const tlsAssetsDir = join(__dirname, '../../e2e/assets/tls');
const readAsset = (fileName: string) =>
readFileSync(join(tlsAssetsDir, fileName), 'utf-8');

describe('agent-pool fingerprintTlsMaterial', () => {
it('produces the same fingerprint for identical TLS material', () => {
const tls: TlsMaterial = { caCert: 'ca-content', tlsSkipVerify: true };
expect(fingerprintTlsMaterial(tls)).toEqual(
fingerprintTlsMaterial({ ...tls }),
);
});

it('treats a missing tlsSkipVerify the same as an explicit false', () => {
expect(fingerprintTlsMaterial({ caCert: 'ca-content' })).toEqual(
fingerprintTlsMaterial({ caCert: 'ca-content', tlsSkipVerify: false }),
);
});

it('produces different fingerprints when any field differs', () => {
const base = fingerprintTlsMaterial({ caCert: 'ca-content' });
expect(fingerprintTlsMaterial({ caCert: 'other-content' })).not.toEqual(
base,
);
expect(fingerprintTlsMaterial({ tlsSkipVerify: true })).not.toEqual(base);
expect(
fingerprintTlsMaterial({
caCert: 'ca-content',
tlsClientCert: 'cert',
}),
).not.toEqual(base);
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
});

describe('agent-pool getHttpsAgent pooling', () => {
it('reuses the same agent instance for identical TLS material', () => {
const agent1 = getHttpsAgent({ caCert: 'shared-ca' });
const agent2 = getHttpsAgent({ caCert: 'shared-ca' });
expect(agent1).toBe(agent2);
});

it('returns isolated agent instances for different TLS material', () => {
const agent1 = getHttpsAgent({ caCert: 'ca-a' });
const agent2 = getHttpsAgent({ caCert: 'ca-b' });
expect(agent1).not.toBe(agent2);
});

it('builds an agent with the requested TLS options', () => {
const agent = getHttpsAgent({ tlsSkipVerify: true, caCert: 'ca-c' });
expect(agent).toBeInstanceOf(HttpsAgent);
expect(agent.options.rejectUnauthorized).toBe(false);
expect(agent.options.ca).toEqual('ca-c');
});

it('defaults to rejectUnauthorized: true when no TLS material is given', () => {
const agent = getHttpsAgent();
expect(agent.options.rejectUnauthorized).toBe(true);
});
});

describe('agent-pool getHttpsAgent real TLS handshake', () => {
let server: https.Server;
let port: number;

beforeAll(async () => {
server = https.createServer(
{
cert: readAsset('server.cer'),
key: readAsset('server.key'),
},
(_, res) => res.end('ok'),
);
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
port = (server.address() as { port: number }).port;
});

afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.

// server.cer's CN is "localhost" (no IP SAN), so pin SNI/hostname
// verification to "localhost" while still dialing the loopback IP directly
const request = (agent: https.Agent) =>
new Promise<void>((resolve, reject) => {
https
.get(
{ hostname: '127.0.0.1', servername: 'localhost', port, path: '/', agent },
(res) => {
res.resume();
res.on('end', resolve);
},
)
.on('error', reject);
});

it('connects successfully when trusting the signing CA', async () => {
const agent = getHttpsAgent({ caCert: readAsset('ca.cer') });
await expect(request(agent)).resolves.toBeUndefined();
});

it('fails certificate verification without the CA', async () => {
const agent = getHttpsAgent();
await expect(request(agent)).rejects.toThrow(/self.signed|unable to verify/i);
});
});

describe('agent-pool LRU eviction', () => {
beforeEach(() => {
vi.resetModules();
vi.stubEnv('ADC_INGRESS_TLS_AGENT_POOL_MAX', '2');
});

afterEach(() => {
vi.unstubAllEnvs();
});

it('destroys the least-recently-used agent once the pool exceeds its max size', async () => {
const pool = await import('./agent-pool');

const agentA = pool.getHttpsAgent({ caCert: 'a' });
const destroySpy = vi.spyOn(agentA, 'destroy');
pool.getHttpsAgent({ caCert: 'b' });
// exceeding max size (2) evicts the least-recently-used entry (a)
pool.getHttpsAgent({ caCert: 'c' });

expect(destroySpy).toHaveBeenCalledTimes(1);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
});
Loading
Loading