From 33abda997f42cad182951b39c91075cfdd2e2e6c Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sat, 6 Jun 2026 13:12:48 -0700 Subject: [PATCH] Default secrets to environment source --- .../global/secret/secret.service.spec.ts | 69 +++++++++++++ .../modules/global/secret/secret.service.ts | 99 ++++++++++++------- 2 files changed, 133 insertions(+), 35 deletions(-) create mode 100644 apps/api/src/modules/global/secret/secret.service.spec.ts diff --git a/apps/api/src/modules/global/secret/secret.service.spec.ts b/apps/api/src/modules/global/secret/secret.service.spec.ts new file mode 100644 index 00000000..d0282c2d --- /dev/null +++ b/apps/api/src/modules/global/secret/secret.service.spec.ts @@ -0,0 +1,69 @@ +import { ConfigService } from '@nestjs/config'; +import { SecretService } from './secret.service'; + +function makeConfig(values: Record = {}) { + 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(); + }); +}); diff --git a/apps/api/src/modules/global/secret/secret.service.ts b/apps/api/src/modules/global/secret/secret.service.ts index a6c28034..6e2ac1f5 100644 --- a/apps/api/src/modules/global/secret/secret.service.ts +++ b/apps/api/src/modules/global/secret/secret.service.ts @@ -3,6 +3,7 @@ import { InfisicalSDK } from '@infisical/sdk'; import { ConfigService } from '@nestjs/config'; type SecretMap = Record; +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('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 { + 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 { const [clientId, clientSecret, projectId] = await Promise.all([ this.resolveBootstrapValue('INFISICAL_CLIENT_ID'),