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.
This commit is contained in:
dahyeon committed 2026-11-07 20:21:54 +09:00
1 parent 5bc748dc4d
commit 9117c9c0a4
7 files changed
+685 -88

No files matched your search

@@ -0,0 +1,183 @@
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',
);
});
});
@@ -0,0 +1,123 @@
interface InfisicalOptions {
siteUrl: string;
clientId: string;
clientSecret: string;
projectId: string;
environment: string;
}
interface InfisicalSecret {
secretKey: string;
secretValue: string;
}
const REQUEST_TIMEOUT_MS = 10_000;
const MAX_RETRIES = 4;
/** The two Infisical operations used during SecretService initialization. */
export async function loadInfisicalSecrets(
options: InfisicalOptions,
): Promise<{ secrets: InfisicalSecret[] }> {
const baseUrl = options.siteUrl.endsWith('/')
? options.siteUrl
: `${options.siteUrl}/`;
const login = await requestJson(
new URL('api/v1/auth/universal-auth/login', baseUrl),
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
clientId: options.clientId,
clientSecret: options.clientSecret,
}),
},
);
if (
!isRecord(login) ||
typeof login.accessToken !== 'string' ||
!login.accessToken
) {
throw new Error('Infisical login did not return an access token');
}
// Preserve the SDK's v3 endpoint and defaults, including self-hosted URL prefixes.
const url = new URL('api/v3/secrets/raw', baseUrl);
url.search = new URLSearchParams({
workspaceId: options.projectId,
environment: options.environment,
expandSecretReferences: 'true',
include_imports: 'false',
recursive: 'false',
viewSecretValue: 'true',
}).toString();
const result = await requestJson(url, {
method: 'GET',
headers: { Authorization: `Bearer ${login.accessToken}` },
});
if (
!isRecord(result) ||
!Array.isArray(result.secrets) ||
!result.secrets.every(isSecret)
) {
throw new Error('Infisical returned an invalid secrets response');
}
return { secrets: result.secrets };
}
async function requestJson(url: URL, init: RequestInit): Promise<unknown> {
for (let attempt = 0; ; attempt += 1) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
let response: Response;
try {
response = await fetch(url.toString(), {
...init,
signal: controller.signal,
});
} catch (error) {
if (attempt >= MAX_RETRIES) throw error;
clearTimeout(timeout);
await retryDelay(attempt);
continue;
} finally {
clearTimeout(timeout);
}
// Match the SDK: retry network errors and 429, but not other HTTP errors.
if (response.status === 429 && attempt < MAX_RETRIES) {
await response.body?.cancel();
await retryDelay(attempt);
continue;
}
if (!response.ok) {
await response.body?.cancel();
throw new Error(
`Infisical ${init.method} ${url.pathname} failed with ${response.status}`,
);
}
try {
return await response.json();
} catch {
// JSON parse errors can contain secrets from the response body.
throw new Error('Infisical returned an invalid JSON response');
}
}
}
function retryDelay(attempt: number): Promise<void> {
const base = 1_000 * 2 ** attempt;
const delay = base + base * 0.2 * (Math.random() * 2 - 1);
return new Promise((resolve) => setTimeout(resolve, delay));
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function isSecret(value: unknown): value is InfisicalSecret {
return (
isRecord(value) &&
typeof value.secretKey === 'string' &&
typeof value.secretValue === 'string'
);
}
@@ -9,6 +9,7 @@ function makeConfig(values: Record<string, string | undefined> = {}) {
describe('SecretService', () => {
const originalEnv = process.env;
const originalFetch = global.fetch;
let fetchMock: jest.Mock;
beforeEach(() => {
@@ -23,9 +24,94 @@ describe('SecretService', () => {
afterEach(() => {
process.env = originalEnv;
global.fetch = originalFetch;
jest.restoreAllMocks();
});
function infisicalConfig() {
return makeConfig({
SECRET_SOURCE: 'infisical',
INFISICAL_SITE_URL: 'https://infisical.example.test/',
INFISICAL_CLIENT_ID: 'test-client',
INFISICAL_CLIENT_SECRET: 'test-secret',
INFISICAL_PROJECT_ID: 'test-project',
CONFIG_FALLBACK: 'config-value',
});
}
it.each([
['prod', 'prod'],
['staging', 'staging'],
['dev', 'dev'],
['production', 'dev'],
])('preserves environment mapping %s -> %s', async (nodeEnv, environment) => {
process.env.NODE_ENV = nodeEnv;
fetchMock
.mockResolvedValueOnce(Response.json({ accessToken: 'token' }))
.mockResolvedValueOnce(Response.json({ secrets: [] }));
await new SecretService(infisicalConfig()).ready();
const url = new URL(fetchMock.mock.calls[1][0] as string);
expect(url.searchParams.get('environment')).toBe(environment);
});
it('shares initialization, caches secrets, and preserves empty values and fallbacks', async () => {
process.env.TEST_EMPTY = 'existing-value';
fetchMock
.mockResolvedValueOnce(Response.json({ accessToken: 'token' }))
.mockResolvedValueOnce(
Response.json({
secrets: [
{ secretKey: 'TEST_SECRET', secretValue: 'first' },
{ secretKey: 'TEST_SECRET', secretValue: 'last' },
{ secretKey: 'TEST_EMPTY', secretValue: '' },
],
imports: [
{ secrets: [{ secretKey: 'TEST_IMPORT', secretValue: 'ignored' }] },
],
}),
);
const service = new SecretService(infisicalConfig());
await Promise.all([
service.ready(),
service.get('TEST_SECRET'),
service.ready(),
]);
await expect(service.get('TEST_SECRET')).resolves.toBe('last');
await expect(service.get('TEST_EMPTY')).resolves.toBe('');
await expect(service.get('CONFIG_FALLBACK')).resolves.toBe('config-value');
await expect(service.get('TEST_IMPORT', 'missing')).resolves.toBe(
'missing',
);
expect(process.env.TEST_SECRET).toBe('last');
expect(process.env.TEST_EMPTY).toBe('existing-value');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('does not publish partial secrets after failure and permits a later retry', async () => {
fetchMock
.mockResolvedValueOnce(Response.json({ accessToken: 'token' }))
.mockResolvedValueOnce(
Response.json({
secrets: [
{ secretKey: 'TEST_SECRET', secretValue: 'partial' },
{ secretKey: 'INVALID', secretValue: 123 },
],
}),
)
.mockResolvedValueOnce(Response.json({ accessToken: 'new-token' }))
.mockResolvedValueOnce(
Response.json({
secrets: [{ secretKey: 'TEST_SECRET', secretValue: 'complete' }],
}),
);
const service = new SecretService(infisicalConfig());
await expect(service.ready()).rejects.toThrow('invalid secrets response');
expect(process.env.TEST_SECRET).toBeUndefined();
await service.ready();
await expect(service.get('TEST_SECRET')).resolves.toBe('complete');
expect(fetchMock).toHaveBeenCalledTimes(4);
});
it('defaults to environment-provided secrets without IMDS lookup', async () => {
process.env.TEST_SECRET = 'from-env';
const service = new SecretService(makeConfig());
@@ -1,6 +1,6 @@
import { Injectable, Logger } from '@nestjs/common';
import { InfisicalSDK } from '@infisical/sdk';
import { ConfigService } from '@nestjs/config';
import { loadInfisicalSecrets } from './infisical-client';
type SecretMap = Record<string, string | undefined>;
type SecretSource = 'env' | 'infisical';
@@ -71,23 +71,14 @@ export class SecretService {
private async fetchInfisicalSecrets(): Promise<void> {
const bootstrapConfig = await this.resolveInfisicalBootstrapConfig();
const infisicalClient = new InfisicalSDK({
siteUrl: bootstrapConfig.siteUrl,
});
await infisicalClient.auth().universalAuth.login({
clientId: bootstrapConfig.clientId,
clientSecret: bootstrapConfig.clientSecret,
});
const res = await infisicalClient.secrets().listSecrets({
const res = await loadInfisicalSecrets({
...bootstrapConfig,
environment:
process.env.NODE_ENV === 'prod'
? 'prod'
: process.env.NODE_ENV === 'staging'
? 'staging'
: 'dev',
projectId: bootstrapConfig.projectId,
});
// 임시 객체에 채운 뒤 한 번에 교체(일관성 보장)