Added DisposedError
Wrapped zeroMemory() in its own try/catch in finally
Generic error message; fixed ArrayBufferLike TypeScript type issue
Generic error message; password/salt/IV wrapped in SecureByteContext
Password ≥8 chars enforced; zeroKeys(); rotateKeys(); debug-gated logs; TS type fix
Zero source ArrayBuffer after req.write()
Added timeout, debug, keyRotationInterval, keyRotationDir, keyRotationPassword
dispose(), assertNotDisposed(), startKeyRotationTimer(), rotateKeys(); Promise-mutex on ensureKeys(); new URL() validation; CR/LF API key check; server error detail truncation; response schema validation; all console.log behind debugMode
Propagates new config fields; dispose()
Tests for dispose, timer, header injection, URL validation, error sanitization, debug flag
Tests for generic error messages, password validation, zeroKeys()
This commit is contained in:
Alpha Nerd 2026-04-01 14:28:05 +02:00
parent 76703e2e3e
commit d9d2ec98db
11 changed files with 582 additions and 129 deletions

View file

@ -10,6 +10,7 @@ import {
ForbiddenError,
ServiceUnavailableError,
RateLimitError,
DisposedError,
} from '../../src/errors';
import { stringToArrayBuffer } from '../../src/core/crypto/utils';
@ -50,20 +51,74 @@ describe('SecureCompletionClient constructor', () => {
test('removes trailing slash from routerUrl', () => {
const client = new SecureCompletionClient({ routerUrl: 'https://api.example.com:12434/' });
// We can verify indirectly via fetchServerPublicKey URL construction
expect((client as unknown as { routerUrl: string }).routerUrl).toBe('https://api.example.com:12434');
client.dispose();
});
test('throws on invalid URL', () => {
expect(() => new SecureCompletionClient({ routerUrl: 'not-a-url' }))
.toThrow('Invalid routerUrl');
});
test('http:// URL with allowHttp=true does not throw', () => {
expect(() => new SecureCompletionClient({
routerUrl: 'http://localhost:1234',
allowHttp: true,
})).not.toThrow();
});
});
describe('SecureCompletionClient.dispose()', () => {
test('calling dispose() twice does not throw', () => {
const client = new SecureCompletionClient({ routerUrl: 'https://api.example.com', keyRotationInterval: 0 });
client.dispose();
expect(() => client.dispose()).not.toThrow();
});
test('methods throw DisposedError after dispose()', async () => {
const client = new SecureCompletionClient({ routerUrl: 'https://api.example.com', keyRotationInterval: 0 });
client.dispose();
await expect(client.fetchServerPublicKey()).rejects.toBeInstanceOf(DisposedError);
await expect(client.encryptPayload({})).rejects.toBeInstanceOf(DisposedError);
await expect(client.sendSecureRequest({}, 'id')).rejects.toBeInstanceOf(DisposedError);
});
test('dispose() clears key rotation timer', () => {
jest.useFakeTimers();
const client = new SecureCompletionClient({
routerUrl: 'https://api.example.com',
keyRotationInterval: 1000,
});
const timerBefore = (client as unknown as { keyRotationTimer: unknown }).keyRotationTimer;
expect(timerBefore).toBeDefined();
client.dispose();
const timerAfter = (client as unknown as { keyRotationTimer: unknown }).keyRotationTimer;
expect(timerAfter).toBeUndefined();
jest.useRealTimers();
});
test('keyRotationInterval=0 does not start timer', () => {
const client = new SecureCompletionClient({
routerUrl: 'https://api.example.com',
keyRotationInterval: 0,
});
const timer = (client as unknown as { keyRotationTimer: unknown }).keyRotationTimer;
expect(timer).toBeUndefined();
client.dispose();
});
});
describe('SecureCompletionClient.fetchServerPublicKey', () => {
test('throws SecurityError over HTTP without allowHttp', async () => {
const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
const client = new SecureCompletionClient({
routerUrl: 'http://localhost:1234',
allowHttp: false,
keyRotationInterval: 0,
});
// Suppress console.warn from constructor
jest.spyOn(console, 'warn').mockImplementation(() => undefined);
await expect(client.fetchServerPublicKey()).rejects.toBeInstanceOf(SecurityError);
client.dispose();
warnSpy.mockRestore();
});
});
@ -71,42 +126,122 @@ describe('SecureCompletionClient.sendSecureRequest — security tier validation'
test('throws for invalid security tier', async () => {
const client = new SecureCompletionClient({
routerUrl: 'https://api.example.com:12434',
keyRotationInterval: 0,
});
await expect(
client.sendSecureRequest({}, 'test-id', undefined, 'ultra')
).rejects.toThrow("Invalid securityTier: 'ultra'");
client.dispose();
});
test('accepts valid security tiers', async () => {
// We just need to verify no validation error is thrown at the tier check stage
// (subsequent network call will fail, which is expected in unit tests)
const client = new SecureCompletionClient({
routerUrl: 'https://api.example.com:12434',
keyRotationInterval: 0,
});
for (const tier of ['standard', 'high', 'maximum']) {
// Should not throw a tier validation error (will throw something else)
await expect(
client.sendSecureRequest({}, 'test-id', undefined, tier)
).rejects.not.toThrow("Invalid securityTier");
}
client.dispose();
});
});
describe('SecureCompletionClient — header injection validation', () => {
test('apiKey containing CR throws SecurityError', async () => {
const client = new SecureCompletionClient({
routerUrl: 'https://api.example.com',
keyRotationInterval: 0,
});
await (client as unknown as { generateKeys: () => Promise<void> }).generateKeys();
jest.spyOn(client as unknown as { encryptPayload: (p: object) => Promise<ArrayBuffer> }, 'encryptPayload')
.mockResolvedValue(new ArrayBuffer(8));
await expect(
client.sendSecureRequest({}, 'id', 'key\rwith\rcr')
).rejects.toBeInstanceOf(SecurityError);
client.dispose();
}, 30000);
test('apiKey containing LF throws SecurityError', async () => {
const client = new SecureCompletionClient({
routerUrl: 'https://api.example.com',
keyRotationInterval: 0,
});
await (client as unknown as { generateKeys: () => Promise<void> }).generateKeys();
jest.spyOn(client as unknown as { encryptPayload: (p: object) => Promise<ArrayBuffer> }, 'encryptPayload')
.mockResolvedValue(new ArrayBuffer(8));
await expect(
client.sendSecureRequest({}, 'id', 'key\nwith\nlf')
).rejects.toBeInstanceOf(SecurityError);
client.dispose();
}, 30000);
});
describe('SecureCompletionClient — error detail sanitization', () => {
test('long server detail is truncated to ≤100 chars in error message', async () => {
const client = new SecureCompletionClient({
routerUrl: 'https://api.example.com:12434',
keyRotationInterval: 0,
});
const http = mockHttpClient(async () => makeJsonResponse(400, { detail: 'x'.repeat(200) }));
(client as unknown as { httpClient: typeof http }).httpClient = http;
await (client as unknown as { generateKeys: () => Promise<void> }).generateKeys();
jest.spyOn(client as unknown as { encryptPayload: (p: object) => Promise<ArrayBuffer> }, 'encryptPayload')
.mockResolvedValue(new ArrayBuffer(8));
try {
await client.sendSecureRequest({}, 'id');
} catch (err) {
expect(err).toBeInstanceOf(Error);
// "Bad request: " prefix + max 100 char detail
expect((err as Error).message.length).toBeLessThanOrEqual(115);
}
client.dispose();
}, 30000);
});
describe('SecureCompletionClient — debug flag', () => {
test('console.log not called during construction when debug=false', () => {
const spy = jest.spyOn(console, 'log').mockImplementation(() => undefined);
const client = new SecureCompletionClient({
routerUrl: 'https://api.example.com',
debug: false,
keyRotationInterval: 0,
});
expect(spy).not.toHaveBeenCalled();
spy.mockRestore();
client.dispose();
});
test('console.log called during construction when debug=true', () => {
const spy = jest.spyOn(console, 'log').mockImplementation(() => undefined);
const client = new SecureCompletionClient({
routerUrl: 'https://api.example.com',
debug: true,
keyRotationInterval: 0,
});
expect(spy).toHaveBeenCalled();
spy.mockRestore();
client.dispose();
});
});
describe('SecureCompletionClient.buildErrorFromResponse (via sendSecureRequest)', () => {
// We can test error mapping by making the HTTP mock return specific status codes
// and verifying the correct typed error is thrown.
async function clientWithMockedHttp(statusCode: number, body: object) {
const client = new SecureCompletionClient({
routerUrl: 'https://api.example.com:12434',
keyRotationInterval: 0,
});
// Inject mocked HTTP client
const http = mockHttpClient(async (url: string) => {
if (url.includes('/pki/public_key')) {
// Should not be reached in error tests
throw new Error('unexpected pki call');
}
return makeJsonResponse(statusCode, body);
@ -118,104 +253,99 @@ describe('SecureCompletionClient.buildErrorFromResponse (via sendSecureRequest)'
test('401 → AuthenticationError', async () => {
const client = await clientWithMockedHttp(401, { detail: 'bad key' });
// Keys must be generated first, so inject a pre-generated key set
await (client as unknown as { generateKeys: () => Promise<void> }).generateKeys();
// Mock encryptPayload to skip actual encryption
jest.spyOn(client as unknown as { encryptPayload: () => Promise<ArrayBuffer> }, 'encryptPayload')
jest.spyOn(client as unknown as { encryptPayload: (p: object) => Promise<ArrayBuffer> }, 'encryptPayload')
.mockResolvedValue(new ArrayBuffer(8));
await expect(
client.sendSecureRequest({ model: 'test', messages: [] }, 'id-1')
).rejects.toBeInstanceOf(AuthenticationError);
client.dispose();
}, 30000);
test('403 → ForbiddenError', async () => {
const client = await clientWithMockedHttp(403, { detail: 'not allowed' });
await (client as unknown as { generateKeys: () => Promise<void> }).generateKeys();
jest.spyOn(client as unknown as { encryptPayload: () => Promise<ArrayBuffer> }, 'encryptPayload')
jest.spyOn(client as unknown as { encryptPayload: (p: object) => Promise<ArrayBuffer> }, 'encryptPayload')
.mockResolvedValue(new ArrayBuffer(8));
await expect(
client.sendSecureRequest({ model: 'test', messages: [] }, 'id-1')
).rejects.toBeInstanceOf(ForbiddenError);
client.dispose();
}, 30000);
test('429 → RateLimitError', async () => {
const client = await clientWithMockedHttp(429, { detail: 'too many' });
await (client as unknown as { generateKeys: () => Promise<void> }).generateKeys();
jest.spyOn(client as unknown as { encryptPayload: () => Promise<ArrayBuffer> }, 'encryptPayload')
jest.spyOn(client as unknown as { encryptPayload: (p: object) => Promise<ArrayBuffer> }, 'encryptPayload')
.mockResolvedValue(new ArrayBuffer(8));
await expect(
client.sendSecureRequest({ model: 'test', messages: [] }, 'id-1')
).rejects.toBeInstanceOf(RateLimitError);
client.dispose();
}, 30000);
test('503 → ServiceUnavailableError', async () => {
const client = await clientWithMockedHttp(503, { detail: 'down' });
await (client as unknown as { generateKeys: () => Promise<void> }).generateKeys();
jest.spyOn(client as unknown as { encryptPayload: () => Promise<ArrayBuffer> }, 'encryptPayload')
jest.spyOn(client as unknown as { encryptPayload: (p: object) => Promise<ArrayBuffer> }, 'encryptPayload')
.mockResolvedValue(new ArrayBuffer(8));
await expect(
client.sendSecureRequest({ model: 'test', messages: [] }, 'id-1')
).rejects.toBeInstanceOf(ServiceUnavailableError);
client.dispose();
}, 30000);
test('network error → APIConnectionError (not wrapping typed errors)', async () => {
test('network error → APIConnectionError', async () => {
const client = new SecureCompletionClient({
routerUrl: 'https://api.example.com:12434',
keyRotationInterval: 0,
});
const http = mockHttpClient(async () => { throw new Error('ECONNREFUSED'); });
(client as unknown as { httpClient: typeof http }).httpClient = http;
await (client as unknown as { generateKeys: () => Promise<void> }).generateKeys();
jest.spyOn(client as unknown as { encryptPayload: () => Promise<ArrayBuffer> }, 'encryptPayload')
jest.spyOn(client as unknown as { encryptPayload: (p: object) => Promise<ArrayBuffer> }, 'encryptPayload')
.mockResolvedValue(new ArrayBuffer(8));
await expect(
client.sendSecureRequest({ model: 'test', messages: [] }, 'id-1')
).rejects.toBeInstanceOf(APIConnectionError);
client.dispose();
}, 30000);
});
describe('SecureCompletionClient encrypt/decrypt roundtrip', () => {
test('encryptPayload + decryptResponse roundtrip', async () => {
// Use two clients: one for "client", one to simulate "server"
const clientA = new SecureCompletionClient({ routerUrl: 'https://x', allowHttp: true });
const clientB = new SecureCompletionClient({ routerUrl: 'https://x', allowHttp: true });
const clientA = new SecureCompletionClient({ routerUrl: 'https://x', allowHttp: true, keyRotationInterval: 0 });
const clientB = new SecureCompletionClient({ routerUrl: 'https://x', allowHttp: true, keyRotationInterval: 0 });
await (clientA as unknown as { generateKeys: () => Promise<void> }).generateKeys();
await (clientB as unknown as { generateKeys: () => Promise<void> }).generateKeys();
const payload = { model: 'test', messages: [{ role: 'user', content: 'hi' }] };
// clientA encrypts, clientB decrypts (simulating server responding)
// We can only test the client-side encrypt → client-side decrypt roundtrip
// because the server uses its own key pair to encrypt the response.
// Directly test encryptPayload → decryptResponse using the SAME client's keys
// (as the server would decrypt with its private key and re-encrypt with client's public key)
// For a full roundtrip test we encrypt with clientB's public key and decrypt with clientB's private key.
const serverPublicKeyPem = await (clientB as unknown as { keyManager: { getPublicKeyPEM: () => Promise<string> } }).keyManager.getPublicKeyPEM();
// Mock fetchServerPublicKey on clientA to return clientB's public key
jest.spyOn(clientA as unknown as { fetchServerPublicKey: () => Promise<string> }, 'fetchServerPublicKey')
.mockResolvedValue(serverPublicKeyPem);
const encrypted = await clientA.encryptPayload(payload);
expect(encrypted.byteLength).toBeGreaterThan(0);
// Now simulate clientB decrypting (server decrypts the payload — we can only test
// structure here since decryptResponse expects server-format encrypted response)
const pkg = JSON.parse(new TextDecoder().decode(encrypted));
expect(pkg.version).toBe('1.0');
expect(pkg.algorithm).toBe('hybrid-aes256-rsa4096');
expect(pkg.encrypted_payload.ciphertext).toBeTruthy();
expect(pkg.encrypted_payload.nonce).toBeTruthy();
expect(pkg.encrypted_payload.tag).toBeTruthy(); // tag must be present
expect(pkg.encrypted_payload.tag).toBeTruthy();
expect(pkg.encrypted_aes_key).toBeTruthy();
clientA.dispose();
clientB.dispose();
}, 60000);
});