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.
264 lines
7.8 KiB
TypeScript
264 lines
7.8 KiB
TypeScript
import { Injectable, Logger } from '@nestjs/common';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { loadInfisicalSecrets } from './infisical-client';
|
|
|
|
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;
|
|
const IMDS_REQUEST_TIMEOUT_MS = 1500;
|
|
const FALLBACK_IMDS_BASE_URLS = [
|
|
'http://169.254.169.254',
|
|
'http://host.docker.internal:8675',
|
|
];
|
|
|
|
interface InfisicalBootstrapConfig {
|
|
siteUrl: string;
|
|
clientId: string;
|
|
clientSecret: string;
|
|
projectId: string;
|
|
}
|
|
|
|
@Injectable()
|
|
export class SecretService {
|
|
private logger = new Logger(SecretService.name);
|
|
|
|
private secrets: SecretMap | null = null; // null = 아직 로드 전
|
|
private loading?: Promise<void>; // 진행 중인 로드(중복 호출 방지)
|
|
|
|
constructor(private readonly config: ConfigService) {}
|
|
|
|
/** 한 번만 로그인/페치. 동시에 여러 번 호출돼도 같은 Promise를 공유 */
|
|
private async fetchSecrets(): Promise<void> {
|
|
if (this.secrets) return; // 이미 로드됨
|
|
if (this.loading) return this.loading; // 로드 중이면 그거 기다리기
|
|
|
|
this.loading = (async () => {
|
|
const secretSource = this.resolveSecretSource();
|
|
if (secretSource === 'env') {
|
|
this.loadEnvironmentSecrets();
|
|
return;
|
|
}
|
|
|
|
await this.fetchInfisicalSecrets();
|
|
})();
|
|
|
|
try {
|
|
await this.loading;
|
|
} finally {
|
|
this.loading = undefined; // 실패/성공 모두 끝나면 해제(실패 시 재시도 가능)
|
|
}
|
|
}
|
|
|
|
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 res = await loadInfisicalSecrets({
|
|
...bootstrapConfig,
|
|
environment:
|
|
process.env.NODE_ENV === 'prod'
|
|
? 'prod'
|
|
: process.env.NODE_ENV === 'staging'
|
|
? 'staging'
|
|
: 'dev',
|
|
});
|
|
|
|
// 임시 객체에 채운 뒤 한 번에 교체(일관성 보장)
|
|
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'),
|
|
this.resolveBootstrapValue('INFISICAL_CLIENT_SECRET'),
|
|
this.resolveBootstrapValue('INFISICAL_PROJECT_ID'),
|
|
]);
|
|
const siteUrl =
|
|
(await this.resolveBootstrapValue('INFISICAL_SITE_URL', false)) ??
|
|
DEFAULT_INFISICAL_SITE_URL;
|
|
|
|
const missing = [
|
|
!siteUrl && 'INFISICAL_SITE_URL',
|
|
!clientId && 'INFISICAL_CLIENT_ID',
|
|
!clientSecret && 'INFISICAL_CLIENT_SECRET',
|
|
!projectId && 'INFISICAL_PROJECT_ID',
|
|
].filter(Boolean);
|
|
if (missing.length > 0) {
|
|
throw new Error(
|
|
`Missing required Infisical bootstrap configuration: ${missing.join(', ')}`,
|
|
);
|
|
}
|
|
if (!clientId || !clientSecret || !projectId) {
|
|
throw new Error('Missing required Infisical bootstrap configuration.');
|
|
}
|
|
|
|
return {
|
|
siteUrl,
|
|
clientId,
|
|
clientSecret,
|
|
projectId,
|
|
};
|
|
}
|
|
|
|
private async resolveBootstrapValue(
|
|
key: string,
|
|
required = true,
|
|
): Promise<string | undefined> {
|
|
const configured = this.config.get<string>(key)?.trim();
|
|
if (configured) return configured;
|
|
|
|
const fromImds = await this.getImdsSecret(key);
|
|
if (fromImds) {
|
|
process.env[key] = fromImds;
|
|
return fromImds;
|
|
}
|
|
|
|
if (required) {
|
|
throw new Error(`Missing required bootstrap secret: ${key}`);
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
private async getImdsSecret(key: string): Promise<string | undefined> {
|
|
let lastError: Error | undefined;
|
|
for (const baseUrl of this.resolveImdsBaseUrls()) {
|
|
try {
|
|
const token = await this.issueImdsToken(baseUrl);
|
|
const secret = await this.fetchImdsText(
|
|
`${baseUrl.replace(/\/$/u, '')}/latest/meta-data/secrets/${encodeURIComponent(key)}`,
|
|
{
|
|
'X-aws-ec2-metadata-token': token,
|
|
},
|
|
);
|
|
return secret.trim() || undefined;
|
|
} catch (error) {
|
|
lastError = error instanceof Error ? error : new Error(String(error));
|
|
}
|
|
}
|
|
|
|
if (lastError) {
|
|
this.logger.debug(
|
|
`IMDS secret lookup failed for ${key}: ${lastError.message}`,
|
|
);
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
private resolveImdsBaseUrls(): string[] {
|
|
return [
|
|
this.config.get<string>('IMDS_BASE_URL'),
|
|
this.config.get<string>('MACHINE_METADATA_BASE_URL'),
|
|
...FALLBACK_IMDS_BASE_URLS,
|
|
]
|
|
.map((value) => value?.trim())
|
|
.filter((value): value is string => Boolean(value));
|
|
}
|
|
|
|
private async issueImdsToken(baseUrl: string): Promise<string> {
|
|
return this.fetchImdsText(
|
|
`${baseUrl.replace(/\/$/u, '')}/latest/api/token`,
|
|
{
|
|
'X-aws-ec2-metadata-token-ttl-seconds': String(IMDS_TOKEN_TTL_SECONDS),
|
|
},
|
|
'PUT',
|
|
);
|
|
}
|
|
|
|
private async fetchImdsText(
|
|
url: string,
|
|
headers: Record<string, string>,
|
|
method = 'GET',
|
|
): Promise<string> {
|
|
const controller = new AbortController();
|
|
const timeout = setTimeout(
|
|
() => controller.abort(),
|
|
IMDS_REQUEST_TIMEOUT_MS,
|
|
);
|
|
try {
|
|
const response = await fetch(url, {
|
|
method,
|
|
headers,
|
|
signal: controller.signal,
|
|
});
|
|
if (!response.ok) {
|
|
throw new Error(`IMDS ${method} ${url} failed with ${response.status}`);
|
|
}
|
|
return response.text();
|
|
} finally {
|
|
clearTimeout(timeout);
|
|
}
|
|
}
|
|
|
|
/** lazy get: 필요할 때 처음 한번만 로드 */
|
|
public async get<T = string>(key: string, fallback?: T): Promise<T> {
|
|
if (!this.secrets) {
|
|
await this.fetchSecrets();
|
|
}
|
|
// console.log('Secrets loaded:', this.secrets);
|
|
const val = this.secrets![key];
|
|
if (val === undefined) {
|
|
const cfg = this.config.get<T>(key);
|
|
if (cfg !== undefined) return cfg;
|
|
if (fallback !== undefined) return fallback;
|
|
throw new Error(`Secret not found for key="${key}"`);
|
|
}
|
|
return val as T;
|
|
}
|
|
|
|
/** 필요 시: 동기 접근(초기화 안됐으면 에러). constructor 등에서 강제 사용 금지 */
|
|
public getSync<T = string>(key: string, fallback?: T): T {
|
|
if (!this.secrets) {
|
|
const cfg = this.config.get<T>(key);
|
|
if (cfg !== undefined) return cfg;
|
|
if (fallback !== undefined) return fallback;
|
|
throw new Error(`SecretService not initialized yet (key="${key}")`);
|
|
}
|
|
const val = this.secrets[key];
|
|
if (val === undefined) {
|
|
const cfg = this.config.get<T>(key);
|
|
if (cfg !== undefined) return cfg;
|
|
if (fallback !== undefined) return fallback;
|
|
throw new Error(`Secret not found for key="${key}"`);
|
|
}
|
|
return val as T;
|
|
}
|
|
|
|
/** 선택: 사전에 강제로 로드하고 싶을 때 호출 */
|
|
public async ready(): Promise<void> {
|
|
await this.fetchSecrets();
|
|
}
|
|
}
|