chore: initial deploy bundle
This commit is contained in:
70
apps/api/src/services/key-rotation.service.ts
Normal file
70
apps/api/src/services/key-rotation.service.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { env, getVaultToken } from '../config/env';
|
||||
import { vaultAppRoleLogin } from '../config/vault';
|
||||
import { loadJwtKeysFromVault } from './jwt.service';
|
||||
import { loadCsrfSecret } from './csrf.service';
|
||||
import { logger } from '../lib/logger';
|
||||
|
||||
const DEFAULT_INTERVAL_MS = 60 * 60 * 1000; // 1 hour
|
||||
|
||||
let timer: NodeJS.Timeout | null = null;
|
||||
let currentVaultToken: string | null = null;
|
||||
|
||||
/**
|
||||
* Refresh JWT public keys (active + previous) and CSRF secret from Vault.
|
||||
* Errors are logged but do NOT throw — старые значения остаются в памяти,
|
||||
* сервис продолжает работать до следующего успешного refresh.
|
||||
*/
|
||||
export async function refreshAllKeys(): Promise<void> {
|
||||
const { addr, roleId, secretId, mount, jwtKidPath, jwtKidsPrefix, csrfPath } = env.vault;
|
||||
|
||||
if (!addr || !roleId || !secretId) {
|
||||
logger.warn('Vault not configured, skipping key refresh');
|
||||
return;
|
||||
}
|
||||
|
||||
// Use token from initEnv first call; re-login only if we don't have one yet.
|
||||
let token = currentVaultToken || getVaultToken();
|
||||
if (!token) {
|
||||
const fresh = await vaultAppRoleLogin(addr, roleId, secretId);
|
||||
if (!fresh) {
|
||||
logger.error('Key refresh: Vault AppRole login failed');
|
||||
return;
|
||||
}
|
||||
token = fresh;
|
||||
currentVaultToken = fresh;
|
||||
}
|
||||
|
||||
try {
|
||||
await loadJwtKeysFromVault(addr, token, mount, jwtKidPath, jwtKidsPrefix);
|
||||
} catch (err: any) {
|
||||
logger.error(`Failed to refresh JWT keys: ${err.message}`);
|
||||
}
|
||||
|
||||
try {
|
||||
await loadCsrfSecret(addr, token, mount, csrfPath);
|
||||
} catch (err: any) {
|
||||
logger.error(`Failed to refresh CSRF secret: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function startKeyRotation(intervalMs: number = DEFAULT_INTERVAL_MS): void {
|
||||
if (timer) return;
|
||||
timer = setInterval(() => {
|
||||
logger.info('Refreshing keys from Vault...');
|
||||
void refreshAllKeys().catch((err) =>
|
||||
logger.error(`Key rotation tick failed: ${err?.message || err}`)
|
||||
);
|
||||
// On token expiry Vault will return 403 — we need to re-login.
|
||||
// Reset cached token so refreshAllKeys re-logs in on next call.
|
||||
currentVaultToken = null;
|
||||
}, intervalMs);
|
||||
logger.info(`Key rotation scheduled (every ${intervalMs}ms)`);
|
||||
}
|
||||
|
||||
export function stopKeyRotation(): void {
|
||||
if (timer) {
|
||||
clearInterval(timer);
|
||||
timer = null;
|
||||
logger.info('Key rotation stopped');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user