100 lines
4.3 KiB
TypeScript
100 lines
4.3 KiB
TypeScript
import { X509Certificate } from 'node:crypto';
|
|
import { readFileSync } from 'node:fs';
|
|
import { Agent, request } from 'node:https';
|
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
|
|
export function serviceTls() {
|
|
return {
|
|
ca: readFileSync(process.env.TLS_CA_FILE ?? '/run/tls/ca.crt'),
|
|
cert: readFileSync('/run/identity/tls.crt'),
|
|
key: readFileSync('/run/identity/tls.key'),
|
|
minVersion: 'TLSv1.2' as const,
|
|
rejectUnauthorized: true,
|
|
};
|
|
}
|
|
|
|
const keys = ['DATABASE_URL', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY'] as const;
|
|
type Credentials = Record<(typeof keys)[number], string>;
|
|
|
|
let baoAgent: Agent | undefined;
|
|
|
|
export async function baoRequest(path: string, data?: object, token?: string): Promise<any> {
|
|
const url = new URL(path, process.env.BAO_ADDR ?? 'https://openbao:8200');
|
|
if (url.protocol !== 'https:') throw new Error('OpenBao требует HTTPS');
|
|
return new Promise((resolve, reject) => {
|
|
const body = data === undefined ? undefined : JSON.stringify(data);
|
|
const req = request(url, {
|
|
agent: baoAgent ??= new Agent({ ...serviceTls(), keepAlive: true, maxSockets: 1 }), method: body === undefined ? 'GET' : 'POST',
|
|
headers: {
|
|
...(body && { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }),
|
|
...(token && { 'X-Vault-Token': token }),
|
|
},
|
|
signal: AbortSignal.timeout(8000),
|
|
}, (res) => {
|
|
let content = '';
|
|
res.setEncoding('utf8');
|
|
res.on('data', (part: string) => {
|
|
content += part;
|
|
if (content.length > 65536) req.destroy(new Error('OpenBao: ответ превышает лимит'));
|
|
});
|
|
res.on('error', reject);
|
|
res.on('end', () => {
|
|
if (res.statusCode !== 200 && res.statusCode !== 204) return reject(new Error(`OpenBao HTTP ${res.statusCode}`));
|
|
try { resolve(content ? JSON.parse(content) : null); } catch { reject(new Error('OpenBao: неверный JSON')); }
|
|
});
|
|
});
|
|
req.on('error', reject);
|
|
req.end(body);
|
|
});
|
|
}
|
|
|
|
export function serviceSecretName(role: string): string {
|
|
if (role !== 'worker') return role;
|
|
const name = new X509Certificate(serviceTls().cert).subject;
|
|
if (!/^CN=worker-[0-9a-f]{8}$/.test(name)) throw new Error('Неверная identity worker');
|
|
return name.slice(3);
|
|
}
|
|
|
|
export async function loadServiceSecrets(role: string) {
|
|
const path = serviceSecretName(role);
|
|
async function acquire(): Promise<{ values: Credentials; ttl: number }> {
|
|
const { auth } = await baoRequest('/v1/auth/cert/login', { name: role });
|
|
const { data } = await baoRequest(`/v1/messenger/data/${path}`, undefined, auth.client_token);
|
|
if (!keys.every((key) => typeof data.data[key] === 'string' && data.data[key])) throw new Error('OpenBao: неполный secret');
|
|
if (!Number.isFinite(auth.lease_duration) || auth.lease_duration < 10 || auth.lease_duration > 300) {
|
|
throw new Error('OpenBao: неверный TTL');
|
|
}
|
|
const values = Object.fromEntries(keys.map((key) => [key, data.data[key]])) as Credentials;
|
|
return { values, ttl: auth.lease_duration };
|
|
}
|
|
|
|
const { log } = await import('./otel.ts');
|
|
const initial = await acquire();
|
|
Object.assign(process.env, initial.values);
|
|
// Re-auth вместо продления токена: замена/отзыв leaf проверяются при каждом цикле.
|
|
let expiresAt = performance.now() + initial.ttl * 1000;
|
|
const expire = () => {
|
|
log('error', 'secrets.expired', 'OpenBao недоступен или identity отозвана; срок использования credentials истёк');
|
|
process.exit(1);
|
|
};
|
|
let deadline = setTimeout(expire, initial.ttl * 1000).unref();
|
|
void (async () => {
|
|
for (;;) {
|
|
await sleep(5000, undefined, { ref: false });
|
|
try {
|
|
const next = await acquire();
|
|
if (keys.some((key) => next.values[key] !== initial.values[key])) {
|
|
log('info', 'secrets.rotated', 'Получены новые credentials; процесс перезапускается');
|
|
process.kill(process.pid, 'SIGTERM');
|
|
return;
|
|
}
|
|
expiresAt = performance.now() + next.ttl * 1000;
|
|
clearTimeout(deadline);
|
|
deadline = setTimeout(expire, next.ttl * 1000).unref();
|
|
} catch {
|
|
if (performance.now() >= expiresAt) expire();
|
|
}
|
|
}
|
|
})();
|
|
}
|