.
This commit is contained in:
1 parent
b152a5b0fa
commit
2379051196
32 files changed
+1682
-383
No files matched your search
@@ -2,7 +2,22 @@ import { Injectable, Logger } from '@nestjs/common';
|
||||
import { InfisicalSDK } from '@infisical/sdk';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
type SecretMap = Record<string, string | boolean | undefined>;
|
||||
type SecretMap = Record<string, string | undefined>;
|
||||
|
||||
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 {
|
||||
@@ -10,57 +25,8 @@ export class SecretService {
|
||||
|
||||
private secrets: SecretMap | null = null; // null = 아직 로드 전
|
||||
private loading?: Promise<void>; // 진행 중인 로드(중복 호출 방지)
|
||||
private infisicalClient: InfisicalSDK;
|
||||
|
||||
private readonly siteUrl: string;
|
||||
private readonly clientSecret: string;
|
||||
private readonly clientId: string;
|
||||
private readonly projectId: string;
|
||||
|
||||
private readonly PROCESS_ENVS = [
|
||||
'COSMOSDB_ENDPOINT',
|
||||
'COSMOSDB_KEY',
|
||||
'NATS_ENDPOINT',
|
||||
'NATS_TOKEN',
|
||||
'NATS_URL',
|
||||
'DAKAO_INBOUND_SUBJECT',
|
||||
'DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT',
|
||||
'DAKAO_REPLY_SUBJECT_PREFIX',
|
||||
'DAKAO_COMMAND_SOURCE',
|
||||
'DAKAO_BOT_USER_ID',
|
||||
'DAKAO_INSTANCE_ID',
|
||||
'JWT_CLAIM_AUDIENCE',
|
||||
'MICROSOFT_ENTRAID_TENANT_ID',
|
||||
'MICROSOFT_ENTRAID_ALLOWED_ALGS',
|
||||
'AUTH_DEV_HEADER_ENABLED',
|
||||
// 필요시 추가
|
||||
] as const;
|
||||
|
||||
constructor(private readonly config: ConfigService) {
|
||||
this.siteUrl =
|
||||
this.config.get<string>('INFISICAL_SITE_URL') ??
|
||||
'https://secret-manager.dahyeon.us/';
|
||||
this.clientSecret = this.config.get<string>(
|
||||
'INFISICAL_CLIENT_SECRET',
|
||||
) as string;
|
||||
this.clientId = this.config.get<string>('INFISICAL_CLIENT_ID') as string;
|
||||
this.projectId = this.config.get<string>('INFISICAL_PROJECT_ID') as string;
|
||||
// console.log(this.siteUrl, this.clientSecret, this.clientId, this.projectId)
|
||||
|
||||
const missing = [
|
||||
!this.siteUrl && 'INFISICAL_SITE_URL',
|
||||
!this.clientId && 'INFISICAL_CLIENT_ID',
|
||||
!this.clientSecret && 'INFISICAL_CLIENT_SECRET',
|
||||
!this.projectId && 'INFISICAL_PROJECT_ID',
|
||||
].filter(Boolean);
|
||||
if (missing.length > 0) {
|
||||
throw new Error(
|
||||
`Missing required Infisical configuration: ${missing.join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
this.infisicalClient = new InfisicalSDK({ siteUrl: this.siteUrl });
|
||||
}
|
||||
constructor(private readonly config: ConfigService) {}
|
||||
|
||||
/** 한 번만 로그인/페치. 동시에 여러 번 호출돼도 같은 Promise를 공유 */
|
||||
private async fetchSecrets(): Promise<void> {
|
||||
@@ -68,20 +34,24 @@ export class SecretService {
|
||||
if (this.loading) return this.loading; // 로드 중이면 그거 기다리기
|
||||
|
||||
this.loading = (async () => {
|
||||
await this.infisicalClient.auth().universalAuth.login({
|
||||
clientId: this.clientId,
|
||||
clientSecret: this.clientSecret,
|
||||
const bootstrapConfig = await this.resolveInfisicalBootstrapConfig();
|
||||
const infisicalClient = new InfisicalSDK({
|
||||
siteUrl: bootstrapConfig.siteUrl,
|
||||
});
|
||||
// console.log(this.infisicalClient)
|
||||
|
||||
const res = await this.infisicalClient.secrets().listSecrets({
|
||||
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: this.projectId,
|
||||
projectId: bootstrapConfig.projectId,
|
||||
});
|
||||
|
||||
// 임시 객체에 채운 뒤 한 번에 교체(일관성 보장)
|
||||
@@ -90,11 +60,10 @@ export class SecretService {
|
||||
map[s.secretKey] = s.secretValue;
|
||||
}
|
||||
|
||||
// 필요한 값은 process.env에 반영
|
||||
for (const k of this.PROCESS_ENVS) {
|
||||
const v = map[k as string];
|
||||
// 앱 생명주기에서 필요한 env는 모두 SecretService가 process.env에 반영한다.
|
||||
for (const [k, v] of Object.entries(map)) {
|
||||
if (typeof v === 'string' && v.length > 0) {
|
||||
process.env[k as string] = v;
|
||||
process.env[k] = v;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,6 +80,128 @@ export class SecretService {
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
Reference in new issue
Block a user