fix: apply api-key updates during token regeneration

This commit is contained in:
Tam Nhu Tran
2026-04-13 22:57:27 -04:00
parent c7e60974ac
commit f067f39245
2 changed files with 116 additions and 42 deletions
+31 -42
View File
@@ -71,25 +71,19 @@ async function showAuthStatus(showUnmasked: boolean): Promise<void> {
export async function handleTokensCommand(args: string[]): Promise<number> {
await initUI();
// Parse flags
const showFlag = args.includes('--show');
const resetFlag = args.includes('--reset');
const regenerateSecretFlag = args.includes('--regenerate-secret');
const helpFlag = args.includes('--help') || args.includes('-h');
// Find --api-key value
const apiKeyIndex = args.indexOf('--api-key');
const hasApiKeyFlag = apiKeyIndex !== -1;
const apiKeyValue = apiKeyIndex !== -1 ? args[apiKeyIndex + 1] : undefined;
// Find --secret value
const secretIndex = args.indexOf('--secret');
const hasSecretFlag = secretIndex !== -1;
const secretValue = secretIndex !== -1 ? args[secretIndex + 1] : undefined;
// Find --variant value
const variantIndex = args.indexOf('--variant');
const variantValue = variantIndex !== -1 ? args[variantIndex + 1] : undefined;
// Help
if (helpFlag) {
console.log(header('CCS Tokens Management'));
console.log('');
@@ -124,40 +118,45 @@ export async function handleTokensCommand(args: string[]): Promise<number> {
return 0;
}
// Reset to defaults
if (resetFlag) {
resetAuthToDefaults();
// Regenerate CLIProxy config to apply changes
regenerateConfig();
console.log(ok('Auth tokens reset to defaults'));
console.log(info('CLIProxy config regenerated'));
return 0;
}
// Regenerate management secret
if (regenerateSecretFlag && hasSecretFlag) {
console.error(fail('Cannot combine --secret with --regenerate-secret'));
return 1;
}
if (hasApiKeyFlag && (!apiKeyValue || apiKeyValue.startsWith('-'))) {
console.error(fail('Missing value for --api-key'));
return 1;
}
if (hasSecretFlag && (!secretValue || secretValue.startsWith('-'))) {
console.error(fail('Missing value for --secret'));
return 1;
}
let updated = false;
if (regenerateSecretFlag) {
const newSecret = generateSecureToken(32);
setGlobalManagementSecret(newSecret);
// Regenerate CLIProxy config to apply changes
regenerateConfig();
console.log(ok('New management secret generated'));
console.log(` Secret: ${maskToken(newSecret)}`);
console.log(info('CLIProxy config regenerated'));
console.log(warn('Restart CLIProxy to apply: ccs cliproxy restart'));
return 0;
updated = true;
}
// Set API key
if (apiKeyValue !== undefined) {
if (!apiKeyValue || apiKeyValue.startsWith('-')) {
console.error(fail('Missing value for --api-key'));
return 1;
}
if (hasApiKeyFlag) {
const resolvedApiKey = apiKeyValue;
if (variantValue) {
// Per-variant API key
try {
setVariantApiKey(variantValue, apiKeyValue);
setVariantApiKey(variantValue, resolvedApiKey);
console.log(ok(`API key set for variant '${variantValue}'`));
} catch (err) {
const error = err instanceof Error ? err.message : 'Unknown error';
@@ -165,35 +164,25 @@ export async function handleTokensCommand(args: string[]): Promise<number> {
return 1;
}
} else {
// Global API key
setGlobalApiKey(apiKeyValue);
setGlobalApiKey(resolvedApiKey);
console.log(ok('Global API key updated'));
}
// Regenerate CLIProxy config to apply changes
regenerateConfig();
console.log(info('CLIProxy config regenerated'));
console.log(warn('Restart CLIProxy to apply: ccs cliproxy restart'));
return 0;
updated = true;
}
// Set management secret
if (secretValue !== undefined) {
if (!secretValue || secretValue.startsWith('-')) {
console.error(fail('Missing value for --secret'));
return 1;
}
if (hasSecretFlag) {
setGlobalManagementSecret(secretValue);
// Regenerate CLIProxy config to apply changes
regenerateConfig();
console.log(ok('Management secret updated'));
updated = true;
}
if (updated) {
regenerateConfig();
console.log(info('CLIProxy config regenerated'));
console.log(warn('Restart CLIProxy to apply: ccs cliproxy restart'));
return 0;
}
// Default: show status
await showAuthStatus(showFlag);
return 0;
}
@@ -0,0 +1,85 @@
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { getCliproxyConfigPath } from '../../../src/cliproxy';
import { handleTokensCommand } from '../../../src/commands/tokens-command';
import { getConfigYamlPath, loadUnifiedConfig } from '../../../src/config/unified-config-loader';
describe('tokens command auth rotation', () => {
let tempHome = '';
let logLines: string[] = [];
let errorLines: string[] = [];
let originalCcsHome: string | undefined;
let originalNoColor: string | undefined;
let originalConsoleLog: typeof console.log;
let originalConsoleError: typeof console.error;
beforeEach(() => {
tempHome = fs.mkdtempSync(path.join(os.tmpdir(), 'ccs-tokens-rotation-'));
logLines = [];
errorLines = [];
originalCcsHome = process.env.CCS_HOME;
originalNoColor = process.env.NO_COLOR;
originalConsoleLog = console.log;
originalConsoleError = console.error;
process.env.CCS_HOME = tempHome;
process.env.NO_COLOR = '1';
console.log = (...args: unknown[]) => {
logLines.push(args.map(String).join(' '));
};
console.error = (...args: unknown[]) => {
errorLines.push(args.map(String).join(' '));
};
});
afterEach(() => {
if (originalCcsHome !== undefined) process.env.CCS_HOME = originalCcsHome;
else delete process.env.CCS_HOME;
if (originalNoColor !== undefined) process.env.NO_COLOR = originalNoColor;
else delete process.env.NO_COLOR;
console.log = originalConsoleLog;
console.error = originalConsoleError;
fs.rmSync(tempHome, { recursive: true, force: true });
});
it('applies api-key and regenerated secret in a single invocation', async () => {
const exitCode = await handleTokensCommand([
'--api-key',
'ccs-custom-key-123',
'--regenerate-secret',
]);
expect(exitCode).toBe(0);
expect(errorLines).toHaveLength(0);
expect(logLines.some((line) => line.includes('New management secret generated'))).toBe(true);
expect(logLines.some((line) => line.includes('Global API key updated'))).toBe(true);
expect(logLines.filter((line) => line.includes('CLIProxy config regenerated'))).toHaveLength(1);
const config = loadUnifiedConfig();
const managementSecret = config?.cliproxy.auth?.management_secret;
expect(config?.cliproxy.auth?.api_key).toBe('ccs-custom-key-123');
expect(typeof managementSecret).toBe('string');
expect((managementSecret ?? '').length).toBeGreaterThan(20);
const cliproxyConfig = fs.readFileSync(getCliproxyConfigPath(), 'utf8');
expect(cliproxyConfig).toContain('"ccs-custom-key-123"');
});
it('rejects conflicting manual and generated secret flags', async () => {
const exitCode = await handleTokensCommand([
'--secret',
'manual-secret',
'--regenerate-secret',
]);
expect(exitCode).toBe(1);
expect(
errorLines.some((line) => line.includes('Cannot combine --secret with --regenerate-secret'))
).toBe(true);
expect(fs.existsSync(getConfigYamlPath())).toBe(false);
});
});