Files
lolympus-tournament-support/apps/api/src/modules/global/secret/infisical-client.spec.ts
T
dahyeon 9117c9c0a4 fix(deps): resolve production high and critical vulnerabilities
Pin vulnerable transitive dependencies to patched releases and replace Infisical SDK bootstrap calls with a compatible HTTP client. Add dependency-security and secret-loading regression coverage.
2026-11-07 20:21:54 +09:00

184 lines
6.1 KiB
TypeScript

import { loadInfisicalSecrets } from './infisical-client';
const options = {
siteUrl: 'https://infisical.example.test/prefix',
clientId: 'test-client',
clientSecret: 'test-secret',
projectId: 'test-project',
environment: 'staging',
};
const secrets = [{ secretKey: 'TEST_SECRET', secretValue: 'value' }];
const json = (value: unknown, status = 200) =>
new Response(JSON.stringify(value), { status });
describe('Infisical bootstrap client', () => {
const originalFetch = global.fetch;
let fetchMock: jest.Mock;
beforeEach(() => {
fetchMock = jest.fn();
global.fetch = fetchMock;
});
afterEach(() => {
global.fetch = originalFetch;
jest.useRealTimers();
jest.restoreAllMocks();
});
it.each([
'https://infisical.example.test/prefix',
'https://infisical.example.test/prefix/',
])(
'preserves SDK URLs, auth headers and list defaults for %s',
async (siteUrl) => {
fetchMock
.mockResolvedValueOnce(json({ accessToken: 'token' }))
.mockResolvedValueOnce(json({ secrets }));
await expect(
loadInfisicalSecrets({ ...options, siteUrl }),
).resolves.toEqual({ secrets });
expect(fetchMock).toHaveBeenNthCalledWith(
1,
'https://infisical.example.test/prefix/api/v1/auth/universal-auth/login',
expect.objectContaining({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
clientId: options.clientId,
clientSecret: options.clientSecret,
}),
}),
);
expect(fetchMock).toHaveBeenNthCalledWith(
2,
'https://infisical.example.test/prefix/api/v3/secrets/raw?workspaceId=test-project&environment=staging&expandSecretReferences=true&include_imports=false&recursive=false&viewSecretValue=true',
expect.objectContaining({
method: 'GET',
headers: { Authorization: 'Bearer token' },
}),
);
},
);
it('retries network errors and 429 using the same request', async () => {
jest.useFakeTimers();
jest.spyOn(Math, 'random').mockReturnValue(0.5);
fetchMock
.mockRejectedValueOnce(new Error('network error'))
.mockResolvedValueOnce(json({}, 429))
.mockResolvedValueOnce(json({ accessToken: 'token' }))
.mockResolvedValueOnce(json({ secrets }));
const result = loadInfisicalSecrets(options);
await jest.runAllTimersAsync();
await expect(result).resolves.toEqual({ secrets });
expect(fetchMock).toHaveBeenCalledTimes(4);
expect(fetchMock.mock.calls.slice(0, 3).map(([url]) => url)).toEqual(
Array(3).fill(
'https://infisical.example.test/prefix/api/v1/auth/universal-auth/login',
),
);
expect(jest.getTimerCount()).toBe(0);
});
it.each([401, 403, 500])(
'does not retry HTTP %i or fetch secrets after failed login',
async (status) => {
fetchMock.mockResolvedValueOnce(json({ message: 'test-secret' }, status));
await expect(loadInfisicalSecrets(options)).rejects.toThrow(
`failed with ${status}`,
);
expect(fetchMock).toHaveBeenCalledTimes(1);
},
);
it('stops after four retries and does not expose response bodies', async () => {
jest.useFakeTimers();
fetchMock.mockImplementation(() =>
Promise.resolve(json({ message: 'test-secret' }, 429)),
);
const error = loadInfisicalSecrets(options).catch(
(value: unknown) => value,
);
await jest.runAllTimersAsync();
expect(await error).toEqual(
expect.objectContaining({
message: expect.stringContaining('failed with 429'),
}),
);
expect(((await error) as Error).message).not.toContain('test-secret');
expect(fetchMock).toHaveBeenCalledTimes(5);
expect(jest.getTimerCount()).toBe(0);
});
it('aborts each stalled attempt after ten seconds and bounds the retries', async () => {
jest.useFakeTimers();
jest.spyOn(Math, 'random').mockReturnValue(0.5);
fetchMock.mockImplementation(
(_url: string, init: RequestInit) =>
new Promise((_resolve, reject) => {
init.signal!.addEventListener(
'abort',
() => reject(new Error('aborted')),
{ once: true },
);
}),
);
const error = loadInfisicalSecrets(options).catch(
(value: unknown) => value,
);
await jest.advanceTimersByTimeAsync(9_999);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect((fetchMock.mock.calls[0][1] as RequestInit).signal!.aborted).toBe(
false,
);
await jest.runAllTimersAsync();
expect(await error).toEqual(new Error('aborted'));
expect(fetchMock).toHaveBeenCalledTimes(5);
expect(jest.getTimerCount()).toBe(0);
});
it.each([{}, { accessToken: '' }, { accessToken: 123 }])(
'rejects invalid login response %j',
async (login) => {
fetchMock.mockResolvedValueOnce(json(login));
await expect(loadInfisicalSecrets(options)).rejects.toThrow(
'did not return an access token',
);
expect(fetchMock).toHaveBeenCalledTimes(1);
},
);
it.each(['login', 'secrets'])(
'does not leak malformed %s response bodies through errors',
async (operation) => {
if (operation === 'secrets') {
fetchMock.mockResolvedValueOnce(json({ accessToken: 'token' }));
}
fetchMock.mockResolvedValueOnce(new Response('sensitive-secret'));
const error = await loadInfisicalSecrets(options).catch(
(value: unknown) => value,
);
expect(error).toHaveProperty(
'message',
'Infisical returned an invalid JSON response',
);
expect((error as Error).stack).not.toContain('sensitive-secret');
expect(fetchMock).toHaveBeenCalledTimes(operation === 'login' ? 1 : 2);
},
);
it.each([
{},
{ secrets: null },
{ secrets: [{ secretKey: 'KEY', secretValue: 123 }] },
])('rejects invalid secrets response %j', async (result) => {
fetchMock
.mockResolvedValueOnce(json({ accessToken: 'token' }))
.mockResolvedValueOnce(json(result));
await expect(loadInfisicalSecrets(options)).rejects.toThrow(
'invalid secrets response',
);
});
});