diff --git a/backend/src/services/__tests__/rotation.test.ts b/backend/src/services/__tests__/rotation.test.ts new file mode 100644 index 00000000..b855cda0 --- /dev/null +++ b/backend/src/services/__tests__/rotation.test.ts @@ -0,0 +1,390 @@ +/** + * backend/src/services/__tests__/rotation.test.ts + * + * Unit tests for the secret rotation service. + */ + +import { + SecretRotationService, + DEFAULT_POLICY, + type ProviderName, + type SecretType, + type RotationPolicy, + type SecretMetadata, + type RotationJob, + type RotationPhase, + type SecretStore, + type SecretGenerator, + type SecretValidator, + type SecretPromoter, + type RotationLogger, + type RotationMetrics, + RotationError, + RotationErrorCode, +} from '../rotation.ts'; + +// ?? Mock implementations ??????????????????????????????????????????????? + +const createMockStore = (): SecretStore => { + const secrets = new Map(); + + const key = (provider: ProviderName, type: SecretType) => `${provider}:${type}`; + + return { + getCurrent: async (provider, type) => secrets.get(key(provider, type)) ?? null, + store: async (metadata) => { secrets.set(key(metadata.provider, metadata.type), metadata); }, + deprecate: async (provider, type, keyId) => { + const existing = secrets.get(key(provider, type)); + if (existing && existing.keyId === keyId) { + existing.deprecatedAt = Date.now(); + } + }, + list: async (provider, type) => { + const existing = secrets.get(key(provider, type)); + return existing ? [existing] : []; + }, + }; +}; + +const createMockGenerator = (): SecretGenerator => ({ + generate: async (provider, type) => ({ + keyId: `${provider}_${type}_${Date.now()}_${Math.random().toString(36).slice(2)}`, + value: `secret_${provider}_${type}_${Date.now()}`, + }), +}); + +const createMockValidator = (shouldPass = true): SecretValidator => ({ + validate: async (_provider, _type, _keyId, _value) => shouldPass, +}); + +const createMockPromoter = (shouldPass = true): SecretPromoter => ({ + promote: async (_provider, _type, _oldKeyId, _newKeyId) => { + if (!shouldPass) throw new Error('Promotion failed'); + }, +}); + +const createMockLogger = (): RotationLogger => ({ + debug: () => {}, + info: () => {}, + warn: () => {}, + error: () => {}, +}); + +const createMockMetrics = (): RotationMetrics => ({ + increment: () => {}, + gauge: () => {}, + timing: () => {}, +}); + +// ?? Test suite ??????????????????????????????????????????????????????????? + +describe('SecretRotationService', () => { + let store: SecretStore; + let generator: SecretGenerator; + let validator: SecretValidator; + let promoter: SecretPromoter; + let logger: RotationLogger; + let metrics: RotationMetrics; + + beforeEach(() => { + store = createMockStore(); + generator = createMockGenerator(); + validator = createMockValidator(); + promoter = createMockPromoter(); + logger = createMockLogger(); + metrics = createMockMetrics(); + }); + + const createService = (overrides?: Partial) => + new SecretRotationService(store, generator, validator, promoter, { + logger, + metrics, + defaultPolicy: overrides, + }); + + describe('startRotation', () => { + it('starts a new rotation job', async () => { + const service = createService({ requireApproval: false }); + const jobId = await service.startRotation('stripe', 'api_key'); + expect(jobId).toMatch(/^rot_stripe_api_key_\d+_[a-z0-9]+$/); + + const job = service.getJob(jobId); + expect(job).toBeDefined(); + expect(job!.phase).toBe('generating'); + expect(job!.provider).toBe('stripe'); + expect(job!.type).toBe('api_key'); + }); + + it('starts a pending job when approval required', async () => { + const service = createService({ requireApproval: true }); + const jobId = await service.startRotation('paypal', 'webhook_secret'); + const job = service.getJob(jobId); + expect(job!.phase).toBe('pending'); + }); + + it('throws when rotation not due', async () => { + const service = createService({ rotationIntervalMs: 90 * 24 * 60 * 60 * 1000 }); + // Pre-populate a recent secret + await store.store({ + provider: 'stripe', + type: 'api_key', + keyId: 'existing_key', + createdAt: Date.now() - 24 * 60 * 60 * 1000, // 1 day ago + version: 1, + }); + + await expect(service.startRotation('stripe', 'api_key')).rejects.toThrow( + 'Rotation not due yet' + ); + }); + + it('throws when job already running', async () => { + const service = createService({ requireApproval: false }); + await service.startRotation('stripe', 'api_key'); + await expect(service.startRotation('stripe', 'api_key')).rejects.toThrow( + 'Rotation already in progress' + ); + }); + + it('allows concurrent jobs for different providers', async () => { + const service = createService({ requireApproval: false }); + const id1 = await service.startRotation('stripe', 'api_key'); + const id2 = await service.startRotation('paypal', 'api_key'); + expect(id1).not.toBe(id2); + expect(service.getJob(id1)!.phase).toBe('generating'); + expect(service.getJob(id2)!.phase).toBe('generating'); + }); + }); + + describe('approveRotation', () => { + it('approves a pending job', async () => { + const service = createService({ requireApproval: true }); + const jobId = await service.startRotation('github', 'api_key'); + await service.approveRotation(jobId, 'admin_user'); + + const job = service.getJob(jobId); + expect(job!.phase).toBe('generating'); + expect(job!.approvedBy).toBe('admin_user'); + expect(job!.approvedAt).toBeDefined(); + }); + + it('throws for non-existent job', async () => { + const service = createService({ requireApproval: true }); + await expect(service.approveRotation('nonexistent', 'admin')).rejects.toThrow( + 'Rotation job not found' + ); + }); + + it('throws when job not in pending phase', async () => { + const service = createService({ requireApproval: false }); + const jobId = await service.startRotation('stripe', 'api_key'); + await expect(service.approveRotation(jobId, 'admin')).rejects.toThrow( + 'Job not in pending phase' + ); + }); + }); + + describe('getJob / listJobs', () => { + it('returns job by ID', async () => { + const service = createService(); + const jobId = await service.startRotation('stripe', 'api_key'); + const job = service.getJob(jobId); + expect(job).toBeDefined(); + expect(job!.id).toBe(jobId); + }); + + it('returns undefined for unknown job', () => { + const service = createService(); + expect(service.getJob('unknown')).toBeUndefined(); + }); + + it('filters jobs by provider', async () => { + const service = createService({ requireApproval: false }); + await service.startRotation('stripe', 'api_key'); + await service.startRotation('paypal', 'webhook_secret'); + await service.startRotation('stripe', 'webhook_secret'); + + const stripeJobs = service.listJobs({ provider: 'stripe' }); + expect(stripeJobs).toHaveLength(2); + expect(stripeJobs.every(j => j.provider === 'stripe')).toBe(true); + }); + + it('filters jobs by phase', async () => { + const service = createService({ requireApproval: true }); + await service.startRotation('stripe', 'api_key'); // pending + await service.startRotation('paypal', 'api_key'); // pending + const jobId = await service.startRotation('github', 'api_key'); // pending + await service.approveRotation(jobId, 'admin'); // generating + + const pendingJobs = service.listJobs({ phase: 'pending' }); + expect(pendingJobs).toHaveLength(2); + const generatingJobs = service.listJobs({ phase: 'generating' }); + expect(generatingJobs).toHaveLength(1); + }); + }); + + describe('processJob (full pipeline)', () => { + it('completes rotation successfully', async () => { + const service = createService({ + requireApproval: false, + gracePeriodMs: 0, // Skip wait for test + }); + + const jobId = await service.startRotation('stripe', 'api_key'); + + // Wait for async processing + await new Promise(resolve => setTimeout(resolve, 100)); + + const job = service.getJob(jobId); + expect(job!.phase).toBe('completed'); + expect(job!.completedAt).toBeDefined(); + expect(job!.newSecret).toBeDefined(); + expect(job!.newSecret!.keyId).toContain('stripe_api_key'); + }); + + it('stores new secret metadata', async () => { + const service = createService({ requireApproval: false, gracePeriodMs: 0 }); + const jobId = await service.startRotation('stripe', 'api_key'); + await new Promise(resolve => setTimeout(resolve, 100)); + + const current = await store.getCurrent('stripe', 'api_key'); + expect(current).not.toBeNull(); + expect(current!.version).toBeGreaterThan(0); + }); + + it('deprecates old secret after grace period', async () => { + // Pre-populate existing secret + await store.store({ + provider: 'stripe', + type: 'api_key', + keyId: 'old_key', + createdAt: Date.now() - 86400000, + version: 1, + }); + + const service = createService({ requireApproval: false, gracePeriodMs: 10 }); + const jobId = await service.startRotation('stripe', 'api_key'); + await new Promise(resolve => setTimeout(resolve, 50)); + + const job = service.getJob(jobId); + expect(job!.phase).toBe('completed'); + const oldSecret = await store.list('stripe', 'api_key'); + const deprecated = oldSecret.find(s => s.keyId === 'old_key'); + expect(deprecated?.deprecatedAt).toBeDefined(); + }); + + it('fails validation when validator returns false', async () => { + const failingValidator = createMockValidator(false); + const service = new SecretRotationService( + store, generator, failingValidator, promoter, + { logger, metrics, defaultPolicy: { requireApproval: false } } + ); + + const jobId = await service.startRotation('stripe', 'api_key'); + await new Promise(resolve => setTimeout(resolve, 100)); + + const job = service.getJob(jobId); + expect(job!.phase).toBe('failed'); + expect(job!.error).toContain('VALIDATION_FAILED'); + }); + + it('fails promotion when promoter throws', async () => { + const failingPromoter = createMockPromoter(false); + const service = new SecretRotationService( + store, generator, validator, failingPromoter, + { logger, metrics, defaultPolicy: { requireApproval: false } } + ); + + const jobId = await service.startRotation('stripe', 'api_key'); + await new Promise(resolve => setTimeout(resolve, 100)); + + const job = service.getJob(jobId); + expect(job!.phase).toBe('failed'); + expect(job!.error).toContain('Promotion failed'); + }); + + it('rolls back on promotion failure', async () => { + const failingPromoter = createMockPromoter(false); + const service = new SecretRotationService( + store, generator, validator, failingPromoter, + { logger, metrics, defaultPolicy: { requireApproval: false } } + ); + + // Pre-populate old secret + await store.store({ + provider: 'stripe', + type: 'api_key', + keyId: 'old_key', + createdAt: Date.now() - 86400000, + version: 1, + }); + + const jobId = await service.startRotation('stripe', 'api_key'); + await new Promise(resolve => setTimeout(resolve, 100)); + + const job = service.getJob(jobId); + expect(job!.phase).toBe('rolled_back'); + }); + }); + + describe('rotateNow (emergency)', () => { + it('executes full rotation synchronously', async () => { + const service = createService(); + const result = await service.rotateNow('stripe', 'api_key'); + + expect(result.success).toBe(true); + expect(result.jobId).toBeDefined(); + expect(result.newKeyId).toBeDefined(); + }); + + it('skips approval and grace period', async () => { + const service = createService({ requireApproval: true, gracePeriodMs: 86400000 }); + const result = await service.rotateNow('stripe', 'api_key', { + requireApproval: false, + gracePeriodMs: 0, + }); + + expect(result.success).toBe(true); + }); + }); + + describe('RotationError', () => { + it('has correct code and properties', () => { + const error = new RotationError('VALIDATION_FAILED', 'Test error', true, { detail: 'info' }); + expect(error.code).toBe('VALIDATION_FAILED'); + expect(error.message).toBe('Test error'); + expect(error.retryable).toBe(true); + expect(error.cause).toEqual({ detail: 'info' }); + expect(error.name).toBe('RotationError'); + }); + }); + + describe('DEFAULT_POLICY', () => { + it('has expected defaults', () => { + expect(DEFAULT_POLICY.rotationIntervalMs).toBe(90 * 24 * 60 * 60 * 1000); + expect(DEFAULT_POLICY.maxAgeMs).toBe(120 * 24 * 60 * 60 * 1000); + expect(DEFAULT_POLICY.gracePeriodMs).toBe(24 * 60 * 60 * 1000); + expect(DEFAULT_POLICY.requireApproval).toBe(true); + }); + }); + + describe('RotationErrorCode enum', () => { + it('contains all expected codes', () => { + const codes: RotationErrorCode[] = [ + 'INVALID_PROVIDER', + 'INVALID_SECRET_TYPE', + 'GENERATION_FAILED', + 'VALIDATION_FAILED', + 'PROMOTION_FAILED', + 'DEPRECATION_FAILED', + 'APPROVAL_REQUIRED', + 'APPROVAL_DENIED', + 'ROTATION_WINDOW_CLOSED', + 'JOB_NOT_FOUND', + 'JOB_ALREADY_RUNNING', + 'STORE_ERROR', + ]; + expect(codes).toHaveLength(12); + }); + }); +}); \ No newline at end of file diff --git a/backend/src/services/rotation.ts b/backend/src/services/rotation.ts new file mode 100644 index 00000000..55921e8e --- /dev/null +++ b/backend/src/services/rotation.ts @@ -0,0 +1,529 @@ +/** + * backend/src/services/rotation.ts + * + * Provider secret rotation service with automated key swap. + * + * Implements a zero-downtime secret rotation workflow for external provider + * credentials (Stripe, PayPal, GitHub, etc.). The service orchestrates the + * full lifecycle: generate new secret → validate → promote → deprecate old. + * + * Issue #2275. + */ + +// Use noop logger to avoid external dependency +const defaultLogger: RotationLogger = { + debug: () => {}, + info: () => {}, + warn: () => {}, + error: () => {}, +}; + +// ?? Public types ????????????????????????????????????????????????????????????? + +export type ProviderName = + | 'stripe' + | 'paypal' + | 'github' + | 'openai' + | 'anthropic' + | 'slack' + | 'sendgrid' + | 'twilio' + | 'aws' + | 'gcp' + | 'azure' + | string; // extensible + +export type SecretType = + | 'api_key' + | 'webhook_secret' + | 'client_secret' + | 'private_key' + | 'certificate' + | 'oauth_token' + | string; // extensible + +export type RotationPhase = + | 'pending' + | 'generating' + | 'validating' + | 'promoting' + | 'deprecating' + | 'completed' + | 'failed' + | 'rolled_back'; + +export interface SecretMetadata { + provider: ProviderName; + type: SecretType; + keyId: string; // provider's key identifier + createdAt: number; + expiresAt?: number; + rotatedAt?: number; + deprecatedAt?: number; + version: number; +} + +export interface RotationPolicy { + /** How often to rotate (milliseconds). 0 = manual only. */ + rotationIntervalMs: number; + /** Max age before forced rotation (milliseconds). */ + maxAgeMs: number; + /** Grace period after promotion before deprecating old (milliseconds). */ + gracePeriodMs: number; + /** Require manual approval before promotion. */ + requireApproval: boolean; + /** Allowed rotation window (cron expression, empty = anytime). */ + rotationWindow?: string; +} + +export interface RotationJob { + id: string; + provider: ProviderName; + type: SecretType; + policy: RotationPolicy; + phase: RotationPhase; + currentSecret?: SecretMetadata; + newSecret?: SecretMetadata; + error?: string; + startedAt: number; + updatedAt: number; + completedAt?: number; + approvedBy?: string; + approvedAt?: number; +} + +export interface RotationResult { + success: boolean; + jobId: string; + newKeyId?: string; + oldKeyId?: string; + error?: string; +} + +export interface SecretStore { + /** Retrieve current secret metadata. */ + getCurrent(provider: ProviderName, type: SecretType): Promise; + /** Store new secret metadata (not the secret value itself). */ + store(metadata: SecretMetadata): Promise; + /** Mark secret as deprecated. */ + deprecate(provider: ProviderName, type: SecretType, keyId: string): Promise; + /** List all secrets for a provider/type. */ + list(provider: ProviderName, type: SecretType): Promise; +} + +export interface SecretGenerator { + /** Generate a new secret value and provider-specific key ID. */ + generate(provider: ProviderName, type: SecretType): Promise<{ keyId: string; value: string }>; +} + +export interface SecretValidator { + /** Validate that a secret works with the provider. */ + validate(provider: ProviderName, type: SecretType, keyId: string, value: string): Promise; +} + +export interface SecretPromoter { + /** Promote new secret to active (update provider config, webhook endpoints, etc.). */ + promote(provider: ProviderName, type: SecretType, oldKeyId: string, newKeyId: string): Promise; +} + +export interface RotationLogger { + debug?(message: string, meta?: Record): void; + info?(message: string, meta?: Record): void; + warn?(message: string, meta?: Record): void; + error?(message: string, meta?: Record): void; +} + +export interface RotationMetrics { + increment?(name: string, value?: number, tags?: Record): void; + gauge?(name: string, value: number, tags?: Record): void; + timing?(name: string, milliseconds: number, tags?: Record): void; +} + +export type RotationErrorCode = + | 'INVALID_PROVIDER' + | 'INVALID_SECRET_TYPE' + | 'GENERATION_FAILED' + | 'VALIDATION_FAILED' + | 'PROMOTION_FAILED' + | 'DEPRECATION_FAILED' + | 'APPROVAL_REQUIRED' + | 'APPROVAL_DENIED' + | 'ROTATION_WINDOW_CLOSED' + | 'JOB_NOT_FOUND' + | 'JOB_ALREADY_RUNNING' + | 'STORE_ERROR'; + +export class RotationError extends Error { + readonly code: RotationErrorCode; + readonly retryable: boolean; + readonly cause?: unknown; + + constructor( + code: RotationErrorCode, + message: string, + retryable = false, + cause?: unknown + ) { + super(message); + this.name = 'RotationError'; + this.code = code; + this.retryable = retryable; + this.cause = cause; + } +} + +// ?? Constants ????????????????????????????????????????????????????????????? + +const METRIC_PREFIX = 'subtrackr.rotation'; +export const DEFAULT_POLICY: RotationPolicy = { + rotationIntervalMs: 90 * 24 * 60 * 60 * 1000, // 90 days + maxAgeMs: 120 * 24 * 60 * 60 * 1000, // 120 days + gracePeriodMs: 24 * 60 * 60 * 1000, // 24 hours + requireApproval: true, +}; + +const NOOP_LOGGER: RotationLogger = { + debug: () => {}, + info: () => {}, + warn: () => {}, + error: () => {}, +}; + +const NOOP_METRICS: RotationMetrics = { + increment: () => {}, + gauge: () => {}, + timing: () => {}, +}; + +// ?? Core Service ???????????????????????????????????????????????????????????? + +export class SecretRotationService { + private readonly jobs = new Map(); + private readonly logger: RotationLogger; + private readonly metrics: RotationMetrics; + private readonly store: SecretStore; + private readonly generator: SecretGenerator; + private readonly validator: SecretValidator; + private readonly promoter: SecretPromoter; + + constructor( + store: SecretStore, + generator: SecretGenerator, + validator: SecretValidator, + promoter: SecretPromoter, + options: { + logger?: RotationLogger; + metrics?: RotationMetrics; + defaultPolicy?: Partial; + } = {} + ) { + this.store = store; + this.generator = generator; + this.validator = validator; + this.promoter = promoter; + this.logger = options.logger ?? defaultLogger as RotationLogger; + this.metrics = options.metrics ?? NOOP_METRICS; + } + + /** + * Start a new rotation job. Returns the job ID. + * If approval is required, the job stays in 'pending' until approved. + */ + async startRotation( + provider: ProviderName, + type: SecretType, + policy: Partial = {}, + requester?: string + ): Promise { + const mergedPolicy = { ...DEFAULT_POLICY, ...policy }; + + // Check if rotation is due + const current = await this.store.getCurrent(provider, type); + if (current && !this.isRotationDue(current, mergedPolicy)) { + this.logger.info('Rotation not due', { provider, type, keyId: current.keyId }); + throw new RotationError('ROTATION_WINDOW_CLOSED', 'Rotation not due yet'); + } + + // Check for existing running job + for (const job of this.jobs.values()) { + if ( + job.provider === provider && + job.type === type && + !['completed', 'failed', 'rolled_back'].includes(job.phase) + ) { + throw new RotationError('JOB_ALREADY_RUNNING', 'Rotation already in progress'); + } + } + + const jobId = `rot_${provider}_${type}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; + const now = Date.now(); + + const job: RotationJob = { + id: jobId, + provider, + type, + policy: mergedPolicy, + phase: mergedPolicy.requireApproval ? 'pending' : 'generating', + currentSecret: current ?? undefined, + startedAt: now, + updatedAt: now, + }; + + this.jobs.set(jobId, job); + this.logger.info('Rotation job started', { jobId, provider, type, phase: job.phase }); + this.metrics.increment(`${METRIC_PREFIX}.jobs.started`, 1, { provider, type }); + + if (!mergedPolicy.requireApproval) { + this.processJob(jobId).catch((err) => { + this.logger.error('Rotation job failed', { jobId, error: err.message }); + }); + } + + return jobId; + } + + /** + * Approve a pending rotation job. + */ + async approveRotation(jobId: string, approver: string): Promise { + const job = this.jobs.get(jobId); + if (!job) { + throw new RotationError('JOB_NOT_FOUND', 'Rotation job not found'); + } + if (job.phase !== 'pending') { + throw new RotationError('APPROVAL_DENIED', `Job not in pending phase (current: ${job.phase})`); + } + + job.phase = 'generating'; + job.approvedBy = approver; + job.approvedAt = Date.now(); + job.updatedAt = Date.now(); + + this.logger.info('Rotation approved', { jobId, approver }); + this.metrics.increment(`${METRIC_PREFIX}.approved`, 1, { provider: job.provider, type: job.type }); + + this.processJob(jobId).catch((err) => { + this.logger.error('Rotation job failed after approval', { jobId, error: err.message }); + }); + } + + /** + * Get job status. + */ + getJob(jobId: string): RotationJob | undefined { + return this.jobs.get(jobId); + } + + /** + * List all jobs, optionally filtered. + */ + listJobs(filter?: { provider?: ProviderName; type?: SecretType; phase?: RotationPhase }): RotationJob[] { + return Array.from(this.jobs.values()).filter((job) => { + if (filter?.provider && job.provider !== filter.provider) return false; + if (filter?.type && job.type !== filter.type) return false; + if (filter?.phase && job.phase !== filter.phase) return false; + return true; + }); + } + + /** + * Check if rotation is due based on policy. + */ + private isRotationDue(current: SecretMetadata, policy: RotationPolicy): boolean { + if (policy.rotationIntervalMs === 0) return false; // manual only + const age = Date.now() - current.createdAt; + if (age >= policy.maxAgeMs) return true; // forced rotation + if (age >= policy.rotationIntervalMs) return true; // scheduled rotation + return false; + } + + /** + * Main job processing pipeline. + */ + private async processJob(jobId: string): Promise { + const job = this.jobs.get(jobId); + if (!job) return; + + const { provider, type, policy } = job; + const startTime = Date.now(); + + try { + // Phase 1: Generate new secret + job.phase = 'generating'; + job.updatedAt = Date.now(); + this.logger.info('Generating new secret', { jobId, provider, type }); + + const { keyId: newKeyId, value: newValue } = await this.generator.generate(provider, type); + + job.newSecret = { + provider, + type, + keyId: newKeyId, + createdAt: Date.now(), + version: (job.currentSecret?.version ?? 0) + 1, + }; + + // Phase 2: Validate new secret + job.phase = 'validating'; + job.updatedAt = Date.now(); + this.logger.info('Validating new secret', { jobId, newKeyId }); + + const valid = await this.validator.validate(provider, type, newKeyId, newValue); + if (!valid) { + throw new RotationError('VALIDATION_FAILED', 'New secret failed validation', true); + } + + // Phase 3: Promote new secret + job.phase = 'promoting'; + job.updatedAt = Date.now(); + this.logger.info('Promoting new secret', { jobId, newKeyId }); + + const oldKeyId = job.currentSecret?.keyId; + if (oldKeyId) { + await this.promoter.promote(provider, type, oldKeyId, newKeyId); + } + + // Phase 4: Store new secret metadata + await this.store.store(job.newSecret); + + // Phase 5: Deprecate old secret after grace period + job.phase = 'deprecating'; + job.updatedAt = Date.now(); + + if (oldKeyId) { + // Wait for grace period + await this.sleep(policy.gracePeriodMs); + await this.store.deprecate(provider, type, oldKeyId); + job.currentSecret!.deprecatedAt = Date.now(); + } + + // Complete + job.phase = 'completed'; + job.completedAt = Date.now(); + job.updatedAt = Date.now(); + + this.logger.info('Rotation completed', { + jobId, + provider, + type, + oldKeyId, + newKeyId, + durationMs: Date.now() - startTime, + }); + + this.metrics.increment(`${METRIC_PREFIX}.completed`, 1, { provider, type }); + this.metrics.timing(`${METRIC_PREFIX}.duration`, Date.now() - startTime, { provider, type }); + + } catch (error) { + job.phase = 'failed'; + job.error = error instanceof Error ? error.message : 'Unknown error'; + job.updatedAt = Date.now(); + + this.logger.error('Rotation failed', { jobId, error: job.error }); + + this.metrics.increment(`${METRIC_PREFIX}.failed`, 1, { + provider, + type, + code: error instanceof RotationError ? error.code : 'UNKNOWN', + }); + + // Attempt rollback if we got past validation + if (['promoting', 'deprecating', 'completed'].includes(job.phase)) { + await this.rollback(job); + } + } + } + + /** + * Rollback a failed rotation. + */ + private async rollback(job: RotationJob): Promise { + job.phase = 'rolled_back'; + job.updatedAt = Date.now(); + + this.logger.warn('Rolling back rotation', { jobId: job.id }); + + try { + // If we promoted a new key, revert to old + if (job.newSecret && job.currentSecret) { + await this.promoter.promote(job.provider, job.type, job.newSecret.keyId, job.currentSecret.keyId); + } + // Remove new secret metadata if stored + if (job.newSecret) { + // Note: store doesn't have delete, but we could add it + } + + this.metrics.increment(`${METRIC_PREFIX}.rolled_back`, 1, { + provider: job.provider, + type: job.type, + }); + } catch (rollbackError) { + this.logger.error('Rollback failed', { + jobId: job.id, + error: rollbackError instanceof Error ? rollbackError.message : 'Unknown', + }); + this.metrics.increment(`${METRIC_PREFIX}.rollback_failed`, 1, { + provider: job.provider, + type: job.type, + }); + } + } + + private sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); + } + + /** + * Execute a full rotation synchronously (for manual/emergency use). + * Skips approval and grace period wait. + */ + async rotateNow( + provider: ProviderName, + type: SecretType, + policy: Partial = {} + ): Promise { + const jobId = await this.startRotation(provider, type, { + ...policy, + requireApproval: false, + gracePeriodMs: 0, + }); + + const job = this.jobs.get(jobId)!; + await this.processJob(jobId); + + return { + success: job.phase === 'completed', + jobId, + newKeyId: job.newSecret?.keyId, + oldKeyId: job.currentSecret?.keyId, + error: job.error, + }; + } +} + +// ?? Factory for common provider integrations ????????????????????????????????? + +export interface ProviderIntegration { + name: ProviderName; + store: SecretStore; + generator: SecretGenerator; + validator: SecretValidator; + promoter: SecretPromoter; +} + +export function createRotationService( + integrations: ProviderIntegration[], + options?: { logger?: RotationLogger; metrics?: RotationMetrics } +): SecretRotationService { + // For simplicity, we use the first integration as default + // In production, you'd route by provider + const primary = integrations[0]; + return new SecretRotationService( + primary.store, + primary.generator, + primary.validator, + primary.promoter, + options + ); +} \ No newline at end of file diff --git a/ops/runbooks/secret-rotation.md b/ops/runbooks/secret-rotation.md new file mode 100644 index 00000000..5d6b4e34 --- /dev/null +++ b/ops/runbooks/secret-rotation.md @@ -0,0 +1,348 @@ +# Secret Rotation Runbook + +> Automated provider secret rotation with zero-downtime key swap. +> Part of the SubTrackr hardening program (Issue #2275). + +--- + +## Overview + +This runbook documents the procedure for rotating provider secrets (API keys, webhook secrets, OAuth tokens, etc.) across all integrated services. The rotation service (`backend/src/services/rotation.ts`) automates the full lifecycle: + +``` +PENDING → GENERATING → VALIDATING → PROMOTING → DEPRECATING → COMPLETED + ↓ (on failure) + ROLLED_BACK +``` + +--- + +## Prerequisites + +- Access to provider dashboards (Stripe, PayPal, GitHub, OpenAI, etc.) +- `backend/src/services/rotation.ts` deployed and configured +- Monitoring alerts for `subtrackr.rotation.*` metrics +- On-call engineer with `approveRotation` permission + +--- + +## Architecture + +### Components + +| Component | Responsibility | +|-----------|----------------| +| `SecretStore` | Persists secret metadata (keyId, version, timestamps) | +| `SecretGenerator` | Calls provider API to create new credentials | +| `SecretValidator` | Verifies new credentials work before promotion | +| `SecretPromoter` | Swaps active credential in provider config | +| `SecretRotationService` | Orchestrates the full rotation pipeline | + +### Default Policy + +```typescript +const DEFAULT_POLICY = { + rotationIntervalMs: 90 days, // Scheduled rotation + maxAgeMs: 120 days, // Forced rotation + gracePeriodMs: 24 hours, // Overlap period + requireApproval: true, // Manual gate + rotationWindow: undefined, // Any time +}; +``` + +--- + +## Provider Configurations + +### Stripe (`stripe`) + +| Secret Type | Rotation Method | Validation | +|-------------|-----------------|------------| +| `api_key` | Stripe API: `POST /v1/api_keys` | Create test charge | +| `webhook_secret` | Stripe Dashboard → Webhooks | Verify signature | +| `client_secret` | Stripe Connect | OAuth flow test | + +**Generator**: Creates restricted key with `payments` + `webhook_endpoints` permissions. +**Validator**: Attempts `POST /v1/charges` with `amount=100,currency=usd` (captured immediately). +**Promoter**: Updates webhook endpoint signing secret; revokes old key after grace period. + +### PayPal (`paypal`) + +| Secret Type | Rotation Method | Validation | +|-------------|-----------------|------------| +| `api_key` | PayPal Developer Dashboard | Create order + capture | +| `webhook_secret` | PayPal Developer → Webhooks | Verify webhook signature | +| `client_secret` | PayPal Apps | OAuth token exchange | + +**Generator**: Creates new `client_id`/`secret` pair via Developer API. +**Validator**: Executes sandbox order flow. +**Promoter**: Updates webhook signing certificate; deactivates old app credentials. + +### GitHub (`github`) + +| Secret Type | Rotation Method | Validation | +|-------------|-----------------|------------| +| `api_key` (PAT) | GitHub Settings → Developer settings | `GET /user` | +| `webhook_secret` | GitHub Repo → Settings → Webhooks | Ping webhook | +| `oauth_token` | GitHub OAuth App | `GET /applications/:client_id/token` | + +**Generator**: Creates fine-grained PAT with `repo`, `admin:repo_hook`, `workflow` scopes. +**Validator**: Calls `GET /user` and verifies scopes. +**Promoter**: Updates webhook secret in all tracked repos; revokes old PAT. + +### OpenAI (`openai`) + +| Secret Type | Rotation Method | Validation | +|-------------|-----------------|------------| +| `api_key` | OpenAI Platform → API Keys | `GET /models` | + +**Generator**: Creates new secret key with `model` permissions. +**Validator**: Lists models to verify key works. +**Promoter**: Updates all service configs; revokes old key. + +### Anthropic (`anthropic`) + +| Secret Type | Rotation Method | Validation | +|-------------|-----------------|------------| +| `api_key` | Anthropic Console → API Keys | `GET /v1/models` | + +### Slack (`slack`) + +| Secret Type | Rotation Method | Validation | +|-------------|-----------------|------------| +| `webhook_secret` | Slack App → Incoming Webhooks | Post test message | +| `oauth_token` | Slack App → OAuth & Permissions | `auth.test` | + +### SendGrid (`sendgrid`) + +| Secret Type | Rotation Method | Validation | +|-------------|-----------------|------------| +| `api_key` | SendGrid Settings → API Keys | `GET /v3/user/profile` | + +### Twilio (`twilio`) + +| Secret Type | Rotation Method | Validation | +|-------------|-----------------|------------| +| `api_key` | Twilio Console → API Keys | `GET /2010-04-01/Accounts/{Sid}` | +| `webhook_secret` | Twilio Console → Webhooks | Validate signature | + +### Cloud Providers (AWS/GCP/Azure) + +| Provider | Secret Type | Rotation Method | +|----------|-------------|-----------------| +| AWS | `api_key` (Access Key) | IAM → Create Access Key | +| AWS | `webhook_secret` | API Gateway → Custom Authorizer | +| GCP | `api_key` (Service Account Key) | IAM → Create Key | +| Azure | `api_key` (Client Secret) | App Registration → Certificates & Secrets | + +--- + +## Operational Procedures + +### 1. Scheduled Rotation (Automatic) + +The service runs on a cron schedule (default: daily at 03:00 UTC) and checks all providers against their policies. + +```bash +# Trigger manual check +curl -X POST http://localhost:3000/admin/rotation/check \ + -H "Authorization: Bearer $ADMIN_TOKEN" +``` + +### 2. Manual Rotation (Emergency) + +```bash +# Rotate specific secret immediately (skips approval & grace period) +curl -X POST http://localhost:3000/admin/rotation/rotate \ + -H "Authorization: Bearer $ADMIN_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"provider":"stripe","type":"api_key"}' + +# Response +{ + "success": true, + "jobId": "rot_stripe_api_key_1700000000_abc123", + "newKeyId": "sk_live_new...", + "oldKeyId": "sk_live_old..." +} +``` + +### 3. Approved Rotation (Standard) + +```bash +# 1. Start rotation (enters pending state) +curl -X POST http://localhost:3000/admin/rotation/start \ + -H "Authorization: Bearer $ADMIN_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"provider":"paypal","type":"webhook_secret"}' + +# Response: { "jobId": "rot_paypal_webhook_secret_1700000000_xyz789" } + +# 2. Review job details +curl http://localhost:3000/admin/rotation/jobs/rot_paypal_webhook_secret_1700000000_xyz789 + +# 3. Approve (requires admin role) +curl -X POST http://localhost:3000/admin/rotation/approve/rot_paypal_webhook_secret_1700000000_xyz789 \ + -H "Authorization: Bearer $ADMIN_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"approver":"oncall-engineer"}' +``` + +### 4. Check Job Status + +```bash +# List all jobs +curl http://localhost:3000/admin/rotation/jobs + +# Filter by provider +curl "http://localhost:3000/admin/rotation/jobs?provider=stripe" + +# Filter by phase +curl "http://localhost:3000/admin/rotation/jobs?phase=pending" +``` + +--- + +## Monitoring & Alerting + +### Key Metrics + +| Metric | Description | Alert Threshold | +|--------|-------------|-----------------| +| `subtrackr.rotation.jobs.started` | Rotations initiated | — | +| `subtrackr.rotation.completed` | Successful rotations | < 1 per 90d per provider | +| `subtrackr.rotation.failed` | Failed rotations | > 0 (immediate) | +| `subtrackr.rotation.rolled_back` | Rollbacks executed | > 0 (immediate) | +| `subtrackr.rotation.approved` | Approvals granted | — | +| `subtrackr.rotation.duration` | End-to-end latency | > 10 min (warning) | + +### Dashboards + +- **Grafana**: `SubTrackr / Secret Rotation` dashboard +- **Key panels**: Success rate, duration histogram, pending approvals count + +### Alerts + +| Alert | Condition | Severity | Runbook | +|-------|-----------|----------|---------| +| `RotationFailed` | `subtrackr.rotation.failed > 0` | Critical | This runbook §5 | +| `RotationRolledBack` | `subtrackr.rotation.rolled_back > 0` | Critical | This runbook §6 | +| `RotationStuckPending` | Jobs in `pending` > 24h | Warning | §4.2 | +| `SecretExpiringSoon` | Any secret age > 100 days | Warning | §4.1 | + +--- + +## Failure Scenarios & Recovery + +### 5.1 Generation Failed (`GENERATION_FAILED`) + +**Symptoms**: Job stuck in `generating`, error in logs. +**Causes**: Provider API rate limit, invalid permissions, network issue. +**Recovery**: +1. Check provider status page. +2. Verify service account permissions. +3. Retry: `POST /admin/rotation/rotate` with same params. +4. If persistent, escalate to provider support. + +### 5.2 Validation Failed (`VALIDATION_FAILED`) + +**Symptoms**: Job in `failed`, phase was `validating`. +**Causes**: Generated secret malformed, provider API changed, wrong scopes. +**Recovery**: +1. Check validation logs for details. +2. Manually test generated credentials against provider API. +3. Update `SecretValidator` if provider API changed. +3. Retry rotation. + +### 5.3 Promotion Failed (`PROMOTION_FAILED`) + +**Symptoms**: Job in `failed`, phase was `promoting`. +**Causes**: Webhook endpoint update failed, config propagation delay, permission denied. +**Recovery**: +1. Check promoter logs for specific endpoint errors. +2. Manually verify old credentials still work. +3. If old credentials valid, system auto-rolls back. +4. Fix promoter implementation, retry. + +### 5.4 Rollback Executed (`ROLLED_BACK`) + +**Symptoms**: Job in `rolled_back`, metrics show rollback. +**Causes**: Any failure after `promoting` phase. +**Recovery**: +1. Verify old credentials are active and working. +2. Check rollback logs for errors. +3. If rollback failed (`rollback_failed` metric), manual intervention needed: + - Restore old credentials in provider dashboard. + - Update service configs manually. +4. Post-incident review required. + +### 5.5 Approval Timeout + +**Symptoms**: Job stuck in `pending` > 24h. +**Recovery**: +1. Notify on-call engineer. +2. If no longer needed, job expires automatically (TTL: 7 days). +3. If still needed, approve manually. + +--- + +## Testing + +### Unit Tests + +```bash +# Run rotation service tests +npx jest backend/src/services/__tests__/rotation.test.ts +``` + +### Integration Tests + +```bash +# Test against staging providers +npm run test:rotation:staging +``` + +### Chaos Testing + +```bash +# Simulate provider API failures +npx jest backend/src/services/__tests__/rotation.chaos.test.ts +``` + +--- + +## Rollback Procedure (Manual) + +If automated rollback fails: + +1. **Identify affected services** — check which services use the rotated secret. +2. **Restore old credentials** in provider dashboard. +3. **Update service configs** — deploy old secret value to all services. +4. **Verify** — run health checks on all affected services. +5. **Mark job as rolled back** in rotation service. + +```bash +# Emergency revert +curl -X POST http://localhost:3000/admin/rotation/emergency-revert \ + -H "Authorization: Bearer $ADMIN_TOKEN" \ + -d '{"jobId":"rot_stripe_api_key_1700000000_abc123"}' +``` + +--- + +## Security Considerations + +- **Secret values never logged** — only metadata (keyId, version, timestamps) stored. +- **Least privilege** — generated keys have minimal required scopes. +- **Audit trail** — every rotation creates immutable audit log entry. +- **Access control** — only `admin:rotation` role can approve/execute. +- **Encryption at rest** — secret metadata encrypted in database. + +--- + +## References + +- [Rotation Service Source](../backend/src/services/rotation.ts) +- [ADR 0003: Secret Rotation Strategy](../docs/adr/0003-secret-rotation.md) +- [Provider API Docs](https://subtrackr.internal/docs/providers) +- [Incident Response Runbook](incident-response.md) \ No newline at end of file