-
Notifications
You must be signed in to change notification settings - Fork 15
feat(server): support custom tls config per endpoint #552
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); | ||
|
|
||
| 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); | ||
| }); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); | ||
|
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())); | ||
| }); | ||
|
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); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| }); | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
| }); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.