Default secrets to environment source

This commit is contained in:
dahyeon committed 2026-06-06 13:12:48 -07:00
1 parent 85ba8044da
commit 33abda997f
2 files changed
+133 -35

No files matched your search

@@ -0,0 +1,69 @@
import { ConfigService } from '@nestjs/config';
import { SecretService } from './secret.service';
function makeConfig(values: Record<string, string | undefined> = {}) {
return {
get: jest.fn((key: string) => values[key] ?? process.env[key]),
} as unknown as ConfigService;
}
describe('SecretService', () => {
const originalEnv = process.env;
let fetchMock: jest.Mock;
beforeEach(() => {
process.env = { ...originalEnv };
delete process.env.SECRET_SOURCE;
delete process.env.TEST_SECRET;
fetchMock = jest
.fn()
.mockRejectedValue(new Error('network calls are disabled in tests'));
global.fetch = fetchMock;
});
afterEach(() => {
process.env = originalEnv;
jest.restoreAllMocks();
});
it('defaults to environment-provided secrets without IMDS lookup', async () => {
process.env.TEST_SECRET = 'from-env';
const service = new SecretService(makeConfig());
await service.ready();
await expect(service.get('TEST_SECRET')).resolves.toBe('from-env');
expect(fetchMock).not.toHaveBeenCalled();
});
it('uses environment-provided secrets when SECRET_SOURCE is env', async () => {
process.env.SECRET_SOURCE = 'env';
process.env.TEST_SECRET = 'from-env-source';
const service = new SecretService(makeConfig());
await service.ready();
await expect(service.get('TEST_SECRET')).resolves.toBe('from-env-source');
expect(fetchMock).not.toHaveBeenCalled();
});
it('uses the IMDS and Infisical bootstrap path only when SECRET_SOURCE is infisical', async () => {
process.env.SECRET_SOURCE = 'infisical';
const service = new SecretService(makeConfig());
await expect(service.ready()).rejects.toThrow(
'Missing required bootstrap secret: INFISICAL_CLIENT_ID',
);
expect(fetchMock).toHaveBeenCalled();
});
it('rejects unsupported SECRET_SOURCE values', async () => {
process.env.SECRET_SOURCE = 'kubernetes';
const service = new SecretService(makeConfig());
await expect(service.ready()).rejects.toThrow(
'Invalid SECRET_SOURCE="kubernetes". Expected "env" or "infisical".',
);
expect(fetchMock).not.toHaveBeenCalled();
});
});
@@ -3,6 +3,7 @@ import { InfisicalSDK } from '@infisical/sdk';
import { ConfigService } from '@nestjs/config';
type SecretMap = Record<string, string | undefined>;
type SecretSource = 'env' | 'infisical';
const DEFAULT_INFISICAL_SITE_URL = 'https://secret-manager.dahyeon.us/';
const IMDS_TOKEN_TTL_SECONDS = 60;
@@ -34,43 +35,13 @@ export class SecretService {
if (this.loading) return this.loading; // 로드 중이면 그거 기다리기
this.loading = (async () => {
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({
environment:
process.env.NODE_ENV === 'prod'
? 'prod'
: process.env.NODE_ENV === 'test'
? 'staging'
: 'dev',
projectId: bootstrapConfig.projectId,
});
// 임시 객체에 채운 뒤 한 번에 교체(일관성 보장)
const map: SecretMap = {};
for (const s of res.secrets) {
map[s.secretKey] = s.secretValue;
const secretSource = this.resolveSecretSource();
if (secretSource === 'env') {
this.loadEnvironmentSecrets();
return;
}
// 앱 생명주기에서 필요한 env는 모두 SecretService가 process.env에 반영한다.
for (const [k, v] of Object.entries(map)) {
if (typeof v === 'string' && v.length > 0) {
process.env[k] = v;
}
}
this.secrets = map;
this.logger.log(
`Fetched ${Object.keys(map).length} secrets from Infisical`,
);
await this.fetchInfisicalSecrets();
})();
try {
@@ -80,6 +51,64 @@ export class SecretService {
}
}
private resolveSecretSource(): SecretSource {
const source = this.config
.get<string>('SECRET_SOURCE')
?.trim()
.toLowerCase();
if (!source || source === 'env') return 'env';
if (source === 'infisical') return 'infisical';
throw new Error(
`Invalid SECRET_SOURCE="${source}". Expected "env" or "infisical".`,
);
}
private loadEnvironmentSecrets(): void {
this.secrets = { ...process.env };
this.logger.log('Using environment-provided secrets');
}
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({
environment:
process.env.NODE_ENV === 'prod'
? 'prod'
: process.env.NODE_ENV === 'test'
? 'staging'
: 'dev',
projectId: bootstrapConfig.projectId,
});
// 임시 객체에 채운 뒤 한 번에 교체(일관성 보장)
const map: SecretMap = {};
for (const s of res.secrets) {
map[s.secretKey] = s.secretValue;
}
// 앱 생명주기에서 필요한 env는 모두 SecretService가 process.env에 반영한다.
for (const [k, v] of Object.entries(map)) {
if (typeof v === 'string' && v.length > 0) {
process.env[k] = v;
}
}
this.secrets = map;
this.logger.log(
`Fetched ${Object.keys(map).length} secrets from Infisical`,
);
}
private async resolveInfisicalBootstrapConfig(): Promise<InfisicalBootstrapConfig> {
const [clientId, clientSecret, projectId] = await Promise.all([
this.resolveBootstrapValue('INFISICAL_CLIENT_ID'),