fix(certificate-manager, smart-proxy): Fix race condition in ACME certificate provisioning and refactor certificate manager initialization to defer provisioning until after port listeners are active
This commit is contained in:
174
test/test.acme-http01-challenge.ts
Normal file
174
test/test.acme-http01-challenge.ts
Normal file
@ -0,0 +1,174 @@
|
||||
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||
import { SmartProxy } from '../ts/index.js';
|
||||
import * as net from 'net';
|
||||
|
||||
// Test that HTTP-01 challenges are properly processed when the initial data arrives
|
||||
tap.test('should correctly handle HTTP-01 challenge requests with initial data chunk', async (tapTest) => {
|
||||
// Prepare test data
|
||||
const challengeToken = 'test-acme-http01-challenge-token';
|
||||
const challengeResponse = 'mock-response-for-challenge';
|
||||
const challengePath = `/.well-known/acme-challenge/${challengeToken}`;
|
||||
|
||||
// Create a handler function that responds to ACME challenges
|
||||
const acmeHandler = (context: any) => {
|
||||
// Log request details for debugging
|
||||
console.log(`Received request: ${context.method} ${context.path}`);
|
||||
|
||||
// Check if this is an ACME challenge request
|
||||
if (context.path.startsWith('/.well-known/acme-challenge/')) {
|
||||
const token = context.path.substring('/.well-known/acme-challenge/'.length);
|
||||
|
||||
// If the token matches our test token, return the response
|
||||
if (token === challengeToken) {
|
||||
return {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'text/plain'
|
||||
},
|
||||
body: challengeResponse
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// For any other requests, return 404
|
||||
return {
|
||||
status: 404,
|
||||
headers: {
|
||||
'Content-Type': 'text/plain'
|
||||
},
|
||||
body: 'Not found'
|
||||
};
|
||||
};
|
||||
|
||||
// Create a proxy with the ACME challenge route
|
||||
const proxy = new SmartProxy({
|
||||
routes: [{
|
||||
name: 'acme-challenge-route',
|
||||
match: {
|
||||
ports: 8080,
|
||||
paths: ['/.well-known/acme-challenge/*']
|
||||
},
|
||||
action: {
|
||||
type: 'static',
|
||||
handler: acmeHandler
|
||||
}
|
||||
}]
|
||||
});
|
||||
|
||||
await proxy.start();
|
||||
|
||||
// Create a client to test the HTTP-01 challenge
|
||||
const testClient = new net.Socket();
|
||||
let responseData = '';
|
||||
|
||||
// Set up client handlers
|
||||
testClient.on('data', (data) => {
|
||||
responseData += data.toString();
|
||||
});
|
||||
|
||||
// Connect to the proxy and send the HTTP-01 challenge request
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
testClient.connect(8080, 'localhost', () => {
|
||||
// Send HTTP request for the challenge token
|
||||
testClient.write(
|
||||
`GET ${challengePath} HTTP/1.1\r\n` +
|
||||
'Host: test.example.com\r\n' +
|
||||
'User-Agent: ACME Challenge Test\r\n' +
|
||||
'Accept: */*\r\n' +
|
||||
'\r\n'
|
||||
);
|
||||
resolve();
|
||||
});
|
||||
|
||||
testClient.on('error', reject);
|
||||
});
|
||||
|
||||
// Wait for the response
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// Verify that we received a valid HTTP response with the challenge token
|
||||
expect(responseData).toContain('HTTP/1.1 200');
|
||||
expect(responseData).toContain('Content-Type: text/plain');
|
||||
expect(responseData).toContain(challengeResponse);
|
||||
|
||||
// Cleanup
|
||||
testClient.destroy();
|
||||
await proxy.stop();
|
||||
});
|
||||
|
||||
// Test that non-existent challenge tokens return 404
|
||||
tap.test('should return 404 for non-existent challenge tokens', async (tapTest) => {
|
||||
// Create a handler function that behaves like a real ACME handler
|
||||
const acmeHandler = (context: any) => {
|
||||
if (context.path.startsWith('/.well-known/acme-challenge/')) {
|
||||
const token = context.path.substring('/.well-known/acme-challenge/'.length);
|
||||
// In this test, we only recognize one specific token
|
||||
if (token === 'valid-token') {
|
||||
return {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'text/plain' },
|
||||
body: 'valid-response'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// For all other paths or unrecognized tokens, return 404
|
||||
return {
|
||||
status: 404,
|
||||
headers: { 'Content-Type': 'text/plain' },
|
||||
body: 'Not found'
|
||||
};
|
||||
};
|
||||
|
||||
// Create a proxy with the ACME challenge route
|
||||
const proxy = new SmartProxy({
|
||||
routes: [{
|
||||
name: 'acme-challenge-route',
|
||||
match: {
|
||||
ports: 8081,
|
||||
paths: ['/.well-known/acme-challenge/*']
|
||||
},
|
||||
action: {
|
||||
type: 'static',
|
||||
handler: acmeHandler
|
||||
}
|
||||
}]
|
||||
});
|
||||
|
||||
await proxy.start();
|
||||
|
||||
// Create a client to test the invalid challenge request
|
||||
const testClient = new net.Socket();
|
||||
let responseData = '';
|
||||
|
||||
testClient.on('data', (data) => {
|
||||
responseData += data.toString();
|
||||
});
|
||||
|
||||
// Connect and send a request for a non-existent token
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
testClient.connect(8081, 'localhost', () => {
|
||||
testClient.write(
|
||||
'GET /.well-known/acme-challenge/invalid-token HTTP/1.1\r\n' +
|
||||
'Host: test.example.com\r\n' +
|
||||
'\r\n'
|
||||
);
|
||||
resolve();
|
||||
});
|
||||
|
||||
testClient.on('error', reject);
|
||||
});
|
||||
|
||||
// Wait for the response
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// Verify we got a 404 Not Found
|
||||
expect(responseData).toContain('HTTP/1.1 404');
|
||||
expect(responseData).toContain('Not found');
|
||||
|
||||
// Cleanup
|
||||
testClient.destroy();
|
||||
await proxy.stop();
|
||||
});
|
||||
|
||||
tap.start();
|
103
test/test.acme-timing-simple.ts
Normal file
103
test/test.acme-timing-simple.ts
Normal file
@ -0,0 +1,103 @@
|
||||
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||
import { SmartProxy } from '../ts/index.js';
|
||||
|
||||
// Test that certificate provisioning is deferred until after ports are listening
|
||||
tap.test('should defer certificate provisioning until ports are ready', async (tapTest) => {
|
||||
// Track when operations happen
|
||||
let portsListening = false;
|
||||
let certProvisioningStarted = false;
|
||||
let operationOrder: string[] = [];
|
||||
|
||||
// Create proxy with certificate route but without real ACME
|
||||
const proxy = new SmartProxy({
|
||||
routes: [{
|
||||
name: 'test-route',
|
||||
match: {
|
||||
ports: 8443,
|
||||
domains: ['test.local']
|
||||
},
|
||||
action: {
|
||||
type: 'forward',
|
||||
target: { host: 'localhost', port: 8181 },
|
||||
tls: {
|
||||
mode: 'terminate',
|
||||
certificate: 'auto',
|
||||
acme: {
|
||||
email: 'test@local.dev',
|
||||
useProduction: false
|
||||
}
|
||||
}
|
||||
}
|
||||
}]
|
||||
});
|
||||
|
||||
// Override the certificate manager creation to avoid real ACME
|
||||
const originalCreateCertManager = proxy['createCertificateManager'];
|
||||
proxy['createCertificateManager'] = async function(...args: any[]) {
|
||||
console.log('Creating mock cert manager');
|
||||
operationOrder.push('create-cert-manager');
|
||||
const mockCertManager = {
|
||||
initialize: async () => {
|
||||
operationOrder.push('cert-manager-init');
|
||||
console.log('Mock cert manager initialized');
|
||||
},
|
||||
provisionAllCertificates: async () => {
|
||||
operationOrder.push('cert-provisioning');
|
||||
certProvisioningStarted = true;
|
||||
// Check that ports are listening when provisioning starts
|
||||
if (!portsListening) {
|
||||
throw new Error('Certificate provisioning started before ports ready!');
|
||||
}
|
||||
console.log('Mock certificate provisioning (ports are ready)');
|
||||
},
|
||||
stop: async () => {},
|
||||
setHttpProxy: () => {},
|
||||
setGlobalAcmeDefaults: () => {},
|
||||
setAcmeStateManager: () => {},
|
||||
setUpdateRoutesCallback: () => {},
|
||||
getAcmeOptions: () => ({}),
|
||||
getState: () => ({ challengeRouteActive: false })
|
||||
};
|
||||
|
||||
// Call initialize immediately as the real createCertificateManager does
|
||||
await mockCertManager.initialize();
|
||||
|
||||
return mockCertManager;
|
||||
};
|
||||
|
||||
// Track port manager operations
|
||||
const originalAddPorts = proxy['portManager'].addPorts;
|
||||
proxy['portManager'].addPorts = async function(ports: number[]) {
|
||||
operationOrder.push('ports-starting');
|
||||
const result = await originalAddPorts.call(this, ports);
|
||||
operationOrder.push('ports-ready');
|
||||
portsListening = true;
|
||||
console.log('Ports are now listening');
|
||||
return result;
|
||||
};
|
||||
|
||||
// Start the proxy
|
||||
await proxy.start();
|
||||
|
||||
// Log the operation order for debugging
|
||||
console.log('Operation order:', operationOrder);
|
||||
|
||||
// Verify operations happened in the correct order
|
||||
expect(operationOrder).toContain('create-cert-manager');
|
||||
expect(operationOrder).toContain('cert-manager-init');
|
||||
expect(operationOrder).toContain('ports-starting');
|
||||
expect(operationOrder).toContain('ports-ready');
|
||||
expect(operationOrder).toContain('cert-provisioning');
|
||||
|
||||
// Verify ports were ready before certificate provisioning
|
||||
const portsReadyIndex = operationOrder.indexOf('ports-ready');
|
||||
const certProvisioningIndex = operationOrder.indexOf('cert-provisioning');
|
||||
|
||||
expect(portsReadyIndex).toBeLessThan(certProvisioningIndex);
|
||||
expect(certProvisioningStarted).toEqual(true);
|
||||
expect(portsListening).toEqual(true);
|
||||
|
||||
await proxy.stop();
|
||||
});
|
||||
|
||||
tap.start();
|
159
test/test.acme-timing.ts
Normal file
159
test/test.acme-timing.ts
Normal file
@ -0,0 +1,159 @@
|
||||
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||
import { SmartProxy } from '../ts/index.js';
|
||||
import * as net from 'net';
|
||||
|
||||
// Test that certificate provisioning waits for ports to be ready
|
||||
tap.test('should defer certificate provisioning until after ports are listening', async (tapTest) => {
|
||||
// Track the order of operations
|
||||
const operationLog: string[] = [];
|
||||
|
||||
// Create a mock server to verify ports are listening
|
||||
let port80Listening = false;
|
||||
const testServer = net.createServer(() => {
|
||||
// We don't need to handle connections, just track that we're listening
|
||||
});
|
||||
|
||||
// Try to use port 8080 instead of 80 to avoid permission issues in testing
|
||||
const acmePort = 8080;
|
||||
|
||||
// Create proxy with ACME certificate requirement
|
||||
const proxy = new SmartProxy({
|
||||
useHttpProxy: [acmePort],
|
||||
httpProxyPort: 8844,
|
||||
acme: {
|
||||
email: 'test@example.com',
|
||||
useProduction: false,
|
||||
port: acmePort
|
||||
},
|
||||
routes: [{
|
||||
name: 'test-acme-route',
|
||||
match: {
|
||||
ports: 8443,
|
||||
domains: ['test.local']
|
||||
},
|
||||
action: {
|
||||
type: 'forward',
|
||||
target: { host: 'localhost', port: 8181 },
|
||||
tls: {
|
||||
mode: 'terminate',
|
||||
certificate: 'auto',
|
||||
acme: {
|
||||
email: 'test@example.com',
|
||||
useProduction: false
|
||||
}
|
||||
}
|
||||
}
|
||||
}]
|
||||
});
|
||||
|
||||
// Mock some internal methods to track operation order
|
||||
const originalAddPorts = proxy['portManager'].addPorts;
|
||||
proxy['portManager'].addPorts = async function(ports: number[]) {
|
||||
operationLog.push('Starting port listeners');
|
||||
const result = await originalAddPorts.call(this, ports);
|
||||
operationLog.push('Port listeners started');
|
||||
port80Listening = true;
|
||||
return result;
|
||||
};
|
||||
|
||||
// Track certificate provisioning
|
||||
const originalProvisionAll = proxy['certManager'] ?
|
||||
proxy['certManager']['provisionAllCertificates'] : null;
|
||||
|
||||
if (proxy['certManager']) {
|
||||
proxy['certManager']['provisionAllCertificates'] = async function() {
|
||||
operationLog.push('Starting certificate provisioning');
|
||||
// Check if port 80 is listening
|
||||
if (!port80Listening) {
|
||||
operationLog.push('ERROR: Certificate provisioning started before ports ready');
|
||||
}
|
||||
// Don't actually provision certificates in the test
|
||||
operationLog.push('Certificate provisioning completed');
|
||||
};
|
||||
}
|
||||
|
||||
// Start the proxy
|
||||
await proxy.start();
|
||||
|
||||
// Verify the order of operations
|
||||
expect(operationLog).toContain('Starting port listeners');
|
||||
expect(operationLog).toContain('Port listeners started');
|
||||
expect(operationLog).toContain('Starting certificate provisioning');
|
||||
|
||||
// Ensure port listeners started before certificate provisioning
|
||||
const portStartIndex = operationLog.indexOf('Port listeners started');
|
||||
const certStartIndex = operationLog.indexOf('Starting certificate provisioning');
|
||||
|
||||
expect(portStartIndex).toBeLessThan(certStartIndex);
|
||||
expect(operationLog).not.toContain('ERROR: Certificate provisioning started before ports ready');
|
||||
|
||||
await proxy.stop();
|
||||
});
|
||||
|
||||
// Test that ACME challenge route is available when certificate is requested
|
||||
tap.test('should have ACME challenge route ready before certificate provisioning', async (tapTest) => {
|
||||
let challengeRouteActive = false;
|
||||
let certificateProvisioningStarted = false;
|
||||
|
||||
const proxy = new SmartProxy({
|
||||
useHttpProxy: [8080],
|
||||
httpProxyPort: 8844,
|
||||
acme: {
|
||||
email: 'test@example.com',
|
||||
useProduction: false,
|
||||
port: 8080
|
||||
},
|
||||
routes: [{
|
||||
name: 'test-route',
|
||||
match: {
|
||||
ports: 8443,
|
||||
domains: ['test.example.com']
|
||||
},
|
||||
action: {
|
||||
type: 'forward',
|
||||
target: { host: 'localhost', port: 8181 },
|
||||
tls: {
|
||||
mode: 'terminate',
|
||||
certificate: 'auto'
|
||||
}
|
||||
}
|
||||
}]
|
||||
});
|
||||
|
||||
// Mock the certificate manager to track operations
|
||||
const originalInitialize = proxy['certManager'] ?
|
||||
proxy['certManager'].initialize : null;
|
||||
|
||||
if (proxy['certManager']) {
|
||||
const certManager = proxy['certManager'];
|
||||
|
||||
// Track when challenge route is added
|
||||
const originalAddChallenge = certManager['addChallengeRoute'];
|
||||
certManager['addChallengeRoute'] = async function() {
|
||||
await originalAddChallenge.call(this);
|
||||
challengeRouteActive = true;
|
||||
};
|
||||
|
||||
// Track when certificate provisioning starts
|
||||
const originalProvisionAcme = certManager['provisionAcmeCertificate'];
|
||||
certManager['provisionAcmeCertificate'] = async function(...args: any[]) {
|
||||
certificateProvisioningStarted = true;
|
||||
// Verify challenge route is active
|
||||
expect(challengeRouteActive).toEqual(true);
|
||||
// Don't actually provision in test
|
||||
return;
|
||||
};
|
||||
}
|
||||
|
||||
await proxy.start();
|
||||
|
||||
// Give it a moment to complete initialization
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// Verify challenge route was added before any certificate provisioning
|
||||
expect(challengeRouteActive).toEqual(true);
|
||||
|
||||
await proxy.stop();
|
||||
});
|
||||
|
||||
tap.start();
|
Reference in New Issue
Block a user