UNPKG

@iota-big3/sdk-security

Version:

Advanced security features including zero trust, quantum-safe crypto, and ML threat detection

320 lines 13.4 kB
"use strict"; /** * @iota-big3/sdk-security - Production Readiness * Orchestrates chaos engineering, monitoring, tracing, and validation */ Object.defineProperty(exports, "__esModule", { value: true }); exports.ProductionReadinessManager = void 0; const events_1 = require("events"); const production_smoke_test_1 = require("../tests/smoke/production-smoke.test"); const chaos_engine_1 = require("./chaos/chaos-engine"); const distributed_tracing_1 = require("./observability/distributed-tracing"); const performance_monitor_1 = require("./observability/performance-monitor"); class ProductionReadinessManager extends events_1.EventEmitter { constructor(config) { super(); this.isActive = false; this.config = config; } async initialize() { if (this.isActive) return; console.info(`Initializing production readiness for ${this.config.environment} environment`); // Initialize chaos engineering if (this.config.chaos?.enabled && this.config.environment !== 'production') { await this.initializeChaos(); } // Initialize performance monitoring if (this.config.monitoring?.enabled) { await this.initializeMonitoring(); } // Initialize distributed tracing if (this.config.tracing?.enabled) { await this.initializeTracing(); } // Initialize smoke tests if (this.config.smokeTests?.enabled) { await this.initializeSmokeTests(); } this.isActive = true; this.emit('production:ready'); } async initializeChaos() { const chaosConfig = { enabled: true, probability: this.config.environment === 'staging' ? 0.1 : 0.01, targets: [], safeguards: [ { name: 'cpu-threshold', condition: async () => { const snapshot = this.performanceMonitor?.getSnapshot(); return !snapshot || snapshot.metrics.cpuUsage < 80; }, action: 'pause' }, { name: 'error-rate-threshold', condition: async () => { const snapshot = this.performanceMonitor?.getSnapshot(); return !snapshot || snapshot.metrics.authFailureRate < 20; }, action: 'abort' } ] }; // Add selected scenarios const scenarios = this.config.chaos?.scenarios || ['AUTHENTICATION_STORM']; for (const scenarioName of scenarios) { const scenario = chaos_engine_1.CHAOS_SCENARIOS[scenarioName]; if (scenario) { chaosConfig.targets.push(...scenario.targets); chaosConfig.probability = Math.max(chaosConfig.probability, scenario.probability); chaosConfig.maxDuration = scenario.maxDuration; } } this.chaosEngine = new chaos_engine_1.ChaosEngine(chaosConfig); // Listen to chaos events this.chaosEngine.on('chaos:failure:injected', (event) => { this.emit('chaos:failure', event); this.performanceMonitor?.recordMetric({ name: 'chaos.failure.injected', value: 1, unit: 'count', timestamp: Date.now(), tags: { type: event.failureType } }); }); this.chaosEngine.on('chaos:failure:recovered', (event) => { this.emit('chaos:recovery', event); this.performanceMonitor?.recordMetric({ name: 'chaos.recovery.time', value: event.duration || 0, unit: 'ms', timestamp: Date.now() }); }); await this.chaosEngine.start(); console.info('Chaos engineering initialized'); } async initializeMonitoring() { this.performanceMonitor = new performance_monitor_1.PerformanceMonitor({ collectionIntervalMs: this.config.monitoring?.metricsInterval || 10000, historySize: 1000, enableCircuitBreakers: true }); // Listen to monitoring events this.performanceMonitor.on('performance:alert', (alert) => { this.emit('monitoring:alert', alert); // Integrate with chaos engine if (alert.severity === 'critical' && this.chaosEngine) { this.chaosEngine.pause(); } }); this.performanceMonitor.on('circuit:opened', (data) => { this.emit('circuit:opened', data); // Record in tracing if (this.distributedTracer) { const span = this.distributedTracer.startSpan('circuit_breaker_opened'); span.attributes['operation'] = data.operation; span.attributes['reason'] = data.reason; this.distributedTracer.endSpan(span.spanId, 'ERROR'); } }); await this.performanceMonitor.start(); console.info('Performance monitoring initialized'); } async initializeTracing() { const tracingConfig = { enabled: true, serviceName: `iota-security-${this.config.environment}`, endpoint: this.config.tracing?.endpoint || 'http://localhost:14268/api/traces', samplingRate: this.config.tracing?.samplingRate || 0.1, propagators: ['w3c', 'b3'], exportInterval: 5000, maxQueueSize: 1000 }; this.distributedTracer = new distributed_tracing_1.DistributedTracer(tracingConfig); // Listen to tracing events this.distributedTracer.on('span:ended', (span) => { // Record span metrics if (span.duration && this.performanceMonitor) { this.performanceMonitor.recordMetric({ name: `${span.operationName}.latency`, value: span.duration, unit: 'ms', timestamp: Date.now(), tags: { status: span.status } }); } }); await this.distributedTracer.initialize(); console.info('Distributed tracing initialized'); } async initializeSmokeTests() { const interval = this.config.smokeTests?.interval || 300000; // 5 minutes // Run initial smoke test await this.runSmokeTests(); // Schedule periodic smoke tests this.smokeTestInterval = setInterval(async () => { await this.runSmokeTests(); }, interval); console.info(`Smoke tests scheduled every ${interval / 1000} seconds`); } async runSmokeTests() { const startSpan = this.distributedTracer?.startSpan('smoke_tests'); try { const results = await (0, production_smoke_test_1.runProductionSmokeTests)(); // Record results if (this.performanceMonitor) { this.performanceMonitor.recordMetric({ name: 'smoke_tests.success_rate', value: (results.results.filter(r => r.passed).length / results.results.length) * 100, unit: 'percent', timestamp: Date.now() }); this.performanceMonitor.recordMetric({ name: 'smoke_tests.duration', value: results.totalDuration, unit: 'ms', timestamp: Date.now() }); } // Emit results this.emit('smoke:results', results); // Handle failures if (!results.success) { const failedTests = results.results.filter(r => !r.passed); if (this.config.smokeTests?.criticalOnly) { const criticalFailures = failedTests.filter(r => ['SecurityManager Initialization', 'Health Check'].includes(r.test)); if (criticalFailures.length > 0) { this.emit('smoke:critical:failure', criticalFailures); } } else { this.emit('smoke:failure', failedTests); } } if (startSpan) { this.distributedTracer.setAttributes(startSpan.spanId, { 'smoke.success': results.success, 'smoke.tests_count': results.results.length, 'smoke.failures_count': results.results.filter(r => !r.passed).length }); this.distributedTracer.endSpan(startSpan.spanId, results.success ? 'OK' : 'ERROR'); } } catch (error) { console.error('Smoke test error:', error); this.emit('smoke:error', error); if (startSpan) { this.distributedTracer.recordException(startSpan.spanId, error); this.distributedTracer.endSpan(startSpan.spanId, 'ERROR'); } } } async shutdown() { if (!this.isActive) return; console.info('Shutting down production readiness components'); // Stop smoke tests if (this.smokeTestInterval) { clearInterval(this.smokeTestInterval); } // Shutdown components await Promise.all([ this.chaosEngine?.stop(), this.performanceMonitor?.stop(), this.distributedTracer?.shutdown() ]); this.isActive = false; this.emit('production:shutdown'); } // Get production status getStatus() { const perfSnapshot = this.performanceMonitor?.getSnapshot(); const tracingMetrics = this.distributedTracer?.getTracingMetrics(); const chaosMetrics = this.chaosEngine?.getMetrics(); return { healthy: this.isHealthy(), components: { chaos: { active: this.chaosEngine?.getActiveFailures().length || 0 > 0, failures: chaosMetrics?.totalFailures || 0 }, monitoring: { active: !!this.performanceMonitor, alerts: perfSnapshot?.alerts.length || 0 }, tracing: { active: !!this.distributedTracer, errorRate: tracingMetrics?.errorRate || 0 }, smokeTests: { lastRun: Date.now(), // Would track actual last run success: true // Would track actual status } }, metrics: { availability: chaosMetrics?.systemAvailability || 100, latencyP99: perfSnapshot?.metrics.authLatencyP99 || 0, errorRate: perfSnapshot?.metrics.authFailureRate || 0, throughput: perfSnapshot?.metrics.scanThroughput || 0 } }; } isHealthy() { const perfSnapshot = this.performanceMonitor?.getSnapshot(); const chaosMetrics = this.chaosEngine?.getMetrics(); // Health criteria const criteria = [ !perfSnapshot || perfSnapshot.alerts.filter(a => a.severity === 'critical').length === 0, !chaosMetrics || chaosMetrics.systemAvailability > 95, !perfSnapshot || perfSnapshot.metrics.authSuccessRate > 90, !perfSnapshot || perfSnapshot.metrics.cpuUsage < 90 ]; return criteria.every(c => c); } // Trigger manual chaos async triggerChaos(scenario) { if (!this.chaosEngine) { throw new Error('Chaos engine not initialized'); } const scenarioConfig = chaos_engine_1.CHAOS_SCENARIOS[scenario]; if (!scenarioConfig) { throw new Error(`Unknown chaos scenario: ${scenario}`); } // Temporarily increase chaos probability const originalConfig = this.chaosEngine['config']; this.chaosEngine['config'] = { ...originalConfig, ...scenarioConfig, probability: 1.0 // Force immediate injection }; // Wait for injection await new Promise(resolve => setTimeout(resolve, 1000)); // Restore original config this.chaosEngine['config'] = originalConfig; } // Export dashboard data exportDashboard() { return { chaos: this.chaosEngine ? { metrics: this.chaosEngine.getMetrics(), activeFailures: this.chaosEngine.getActiveFailures(), history: this.chaosEngine.getFailureHistory(50) } : null, monitoring: this.performanceMonitor ? { snapshot: this.performanceMonitor.getSnapshot(), history: this.performanceMonitor.getHistory(3600000), // Last hour alerts: this.performanceMonitor.getAlerts() } : null, tracing: this.distributedTracer ? { metrics: this.distributedTracer.getTracingMetrics() } : null, status: this.getStatus() }; } } exports.ProductionReadinessManager = ProductionReadinessManager; //# sourceMappingURL=production-readiness.js.map