vaultace-cli
Version:
AI-powered security scanner that detects vulnerabilities in AI-generated code. Proactive scanning, autonomous fixing, and emergency response for modern development teams.
492 lines (435 loc) • 16.2 kB
JavaScript
/**
* Integration Tests for SecureFlow Workflow Engine
* Tests end-to-end workflow execution with encryption and state management
*/
const { SecureFlowEngine } = require('../../src/workflows/engine/core');
const { WorkflowStateManager } = require('../../src/workflows/engine/state');
const { EventBus } = require('../../src/workflows/engine/events');
const crypto = require('crypto');
describe('SecureFlow Workflow Engine Integration Tests', () => {
let engine;
let stateManager;
let eventBus;
beforeEach(() => {
engine = new SecureFlowEngine();
stateManager = new WorkflowStateManager();
eventBus = new EventBus();
});
afterEach(async () => {
await engine.cleanup();
await stateManager.cleanup();
eventBus.removeAllListeners();
});
describe('Workflow Registration and Execution', () => {
test('should register and execute basic vulnerability workflow', async () => {
const workflowDef = {
id: 'test_vulnerability_response',
name: 'Test Vulnerability Response',
version: '1.0.0',
steps: [
{
id: 'assess_vulnerability',
type: 'analysis',
implementation: async (context) => {
return {
risk_level: 'high',
affected_components: ['lodash@4.17.0'],
fix_available: true
};
}
},
{
id: 'apply_fix',
type: 'action',
condition: 'fix_available === true',
implementation: async (context) => {
return {
fix_applied: true,
new_version: 'lodash@4.17.21'
};
}
}
]
};
// Register workflow
await engine.registerWorkflow(workflowDef);
// Execute workflow
const executionId = await engine.executeWorkflow('test_vulnerability_response', {
vulnerability_id: 'CVE-2021-23337',
package_name: 'lodash',
current_version: '4.17.0'
});
expect(executionId).toBeDefined();
// Wait for completion
const result = await engine.waitForCompletion(executionId, 30000);
expect(result.status).toBe('completed');
expect(result.steps).toHaveLength(2);
expect(result.steps[0].outputs.risk_level).toBe('high');
expect(result.steps[1].outputs.fix_applied).toBe(true);
});
test('should handle workflow failures with proper rollback', async () => {
const workflowDef = {
id: 'test_failure_workflow',
name: 'Test Failure Workflow',
version: '1.0.0',
steps: [
{
id: 'step1',
type: 'action',
implementation: async (context) => {
return { step1_completed: true };
}
},
{
id: 'step2_fail',
type: 'action',
implementation: async (context) => {
throw new Error('Simulated failure');
}
}
],
rollback_strategy: 'immediate'
};
await engine.registerWorkflow(workflowDef);
const executionId = await engine.executeWorkflow('test_failure_workflow', {});
const result = await engine.waitForCompletion(executionId, 30000);
expect(result.status).toBe('failed');
expect(result.error).toContain('Simulated failure');
expect(result.rollback_completed).toBe(true);
});
});
describe('State Management and Encryption', () => {
test('should encrypt and decrypt workflow state properly', async () => {
const sensitiveData = {
api_key: 'secret-api-key-12345',
database_password: 'super-secure-password',
workflow_context: {
user_id: 'user-123',
organization: 'test-org'
}
};
// Encrypt state
const encryptedState = await stateManager.encryptState(sensitiveData);
expect(encryptedState.encrypted_data).toBeDefined();
expect(encryptedState.iv).toBeDefined();
expect(encryptedState.auth_tag).toBeDefined();
// Verify original data is not visible
expect(encryptedState.encrypted_data).not.toContain('secret-api-key');
expect(encryptedState.encrypted_data).not.toContain('super-secure-password');
// Decrypt state
const decryptedState = await stateManager.decryptState(encryptedState);
expect(decryptedState).toEqual(sensitiveData);
});
test('should maintain state consistency across workflow steps', async () => {
const workflowDef = {
id: 'state_consistency_test',
name: 'State Consistency Test',
version: '1.0.0',
steps: [
{
id: 'set_state',
type: 'action',
implementation: async (context) => {
await context.setState('counter', 1);
await context.setState('data', { items: ['a', 'b', 'c'] });
return { state_set: true };
}
},
{
id: 'modify_state',
type: 'action',
implementation: async (context) => {
const counter = await context.getState('counter');
const data = await context.getState('data');
await context.setState('counter', counter + 1);
data.items.push('d');
await context.setState('data', data);
return {
counter_incremented: true,
items_count: data.items.length
};
}
},
{
id: 'verify_state',
type: 'analysis',
implementation: async (context) => {
const counter = await context.getState('counter');
const data = await context.getState('data');
return {
final_counter: counter,
final_items: data.items,
state_consistent: counter === 2 && data.items.length === 4
};
}
}
]
};
await engine.registerWorkflow(workflowDef);
const executionId = await engine.executeWorkflow('state_consistency_test', {});
const result = await engine.waitForCompletion(executionId, 30000);
expect(result.status).toBe('completed');
expect(result.steps[2].outputs.state_consistent).toBe(true);
expect(result.steps[2].outputs.final_counter).toBe(2);
expect(result.steps[2].outputs.final_items).toEqual(['a', 'b', 'c', 'd']);
});
});
describe('Event-Driven Architecture', () => {
test('should trigger workflows based on events', async () => {
const eventTriggeredResults = [];
const workflowDef = {
id: 'event_triggered_workflow',
name: 'Event Triggered Workflow',
version: '1.0.0',
triggers: ['vulnerability_detected', 'security_scan_completed'],
steps: [
{
id: 'process_event',
type: 'analysis',
implementation: async (context) => {
eventTriggeredResults.push({
event_type: context.trigger.type,
event_data: context.trigger.data,
timestamp: new Date().toISOString()
});
return { event_processed: true };
}
}
]
};
await engine.registerWorkflow(workflowDef);
// Emit events
await eventBus.emit('vulnerability_detected', {
vulnerability_id: 'CVE-2024-0001',
severity: 'critical'
});
await eventBus.emit('security_scan_completed', {
scan_id: 'scan-12345',
vulnerabilities_found: 5
});
// Wait for event processing
await new Promise(resolve => setTimeout(resolve, 1000));
expect(eventTriggeredResults).toHaveLength(2);
expect(eventTriggeredResults[0].event_type).toBe('vulnerability_detected');
expect(eventTriggeredResults[1].event_type).toBe('security_scan_completed');
});
test('should handle concurrent workflow executions', async () => {
const workflowDef = {
id: 'concurrent_test_workflow',
name: 'Concurrent Test Workflow',
version: '1.0.0',
steps: [
{
id: 'concurrent_step',
type: 'action',
implementation: async (context) => {
// Simulate some async work
await new Promise(resolve => setTimeout(resolve, 100));
return {
execution_id: context.executionId,
timestamp: Date.now()
};
}
}
]
};
await engine.registerWorkflow(workflowDef);
// Start multiple executions concurrently
const executionPromises = [];
for (let i = 0; i < 5; i++) {
executionPromises.push(
engine.executeWorkflow('concurrent_test_workflow', { batch: i })
);
}
const executionIds = await Promise.all(executionPromises);
expect(executionIds).toHaveLength(5);
// Wait for all to complete
const resultPromises = executionIds.map(id =>
engine.waitForCompletion(id, 30000)
);
const results = await Promise.all(resultPromises);
// Verify all completed successfully
results.forEach(result => {
expect(result.status).toBe('completed');
expect(result.steps[0].outputs.execution_id).toBeDefined();
});
// Verify they all have different execution IDs
const uniqueExecutionIds = new Set(
results.map(r => r.steps[0].outputs.execution_id)
);
expect(uniqueExecutionIds.size).toBe(5);
});
});
describe('Security and Compliance Features', () => {
test('should generate complete audit trails', async () => {
const workflowDef = {
id: 'audit_trail_workflow',
name: 'Audit Trail Workflow',
version: '1.0.0',
compliance_requirements: ['SOC2', 'HIPAA'],
steps: [
{
id: 'security_action',
type: 'action',
implementation: async (context) => {
await context.logSecurityEvent('VULNERABILITY_FIX_APPLIED', {
vulnerability_id: 'CVE-2024-0001',
fix_method: 'dependency_update'
});
return { security_action_completed: true };
}
}
]
};
await engine.registerWorkflow(workflowDef);
const executionId = await engine.executeWorkflow('audit_trail_workflow', {
user: 'test-user',
organization: 'test-org'
});
const result = await engine.waitForCompletion(executionId, 30000);
expect(result.status).toBe('completed');
// Verify audit trail
const auditTrail = await engine.getAuditTrail(executionId);
expect(auditTrail).toBeDefined();
expect(auditTrail.events).toContainEqual(
expect.objectContaining({
type: 'WORKFLOW_STARTED',
user: 'test-user',
timestamp: expect.any(String)
})
);
expect(auditTrail.events).toContainEqual(
expect.objectContaining({
type: 'SECURITY_EVENT',
event_type: 'VULNERABILITY_FIX_APPLIED'
})
);
expect(auditTrail.compliance_evidence).toContain('SOC2');
expect(auditTrail.compliance_evidence).toContain('HIPAA');
});
test('should enforce zero-trust authentication', async () => {
const restrictedWorkflowDef = {
id: 'restricted_workflow',
name: 'Restricted Workflow',
version: '1.0.0',
security_policy: {
require_authentication: true,
required_permissions: ['security.write', 'workflows.execute']
},
steps: [
{
id: 'restricted_action',
type: 'action',
implementation: async (context) => {
return { restricted_action_completed: true };
}
}
]
};
await engine.registerWorkflow(restrictedWorkflowDef);
// Try to execute without proper authentication
await expect(
engine.executeWorkflow('restricted_workflow', {}, {
skipAuthentication: false,
user: { permissions: ['read.only'] }
})
).rejects.toThrow('Insufficient permissions');
// Execute with proper authentication
const executionId = await engine.executeWorkflow('restricted_workflow', {}, {
skipAuthentication: false,
user: {
id: 'authorized-user',
permissions: ['security.write', 'workflows.execute']
}
});
const result = await engine.waitForCompletion(executionId, 30000);
expect(result.status).toBe('completed');
});
});
describe('Performance and Scalability', () => {
test('should handle large workflow payloads efficiently', async () => {
const largePayload = {
scan_results: Array.from({ length: 10000 }, (_, i) => ({
file: `file-${i}.js`,
vulnerabilities: Array.from({ length: 10 }, (_, j) => ({
id: `vuln-${i}-${j}`,
severity: ['low', 'medium', 'high', 'critical'][j % 4],
description: `Vulnerability ${j} in file ${i}`
}))
}))
};
const workflowDef = {
id: 'large_payload_workflow',
name: 'Large Payload Workflow',
version: '1.0.0',
steps: [
{
id: 'process_large_payload',
type: 'analysis',
implementation: async (context) => {
const results = context.inputs.scan_results;
const totalVulnerabilities = results.reduce(
(sum, file) => sum + file.vulnerabilities.length,
0
);
return {
files_processed: results.length,
total_vulnerabilities: totalVulnerabilities
};
}
}
]
};
const startTime = Date.now();
await engine.registerWorkflow(workflowDef);
const executionId = await engine.executeWorkflow('large_payload_workflow', largePayload);
const result = await engine.waitForCompletion(executionId, 60000);
const endTime = Date.now();
expect(result.status).toBe('completed');
expect(result.steps[0].outputs.files_processed).toBe(10000);
expect(result.steps[0].outputs.total_vulnerabilities).toBe(100000);
expect(endTime - startTime).toBeLessThan(10000); // Should complete within 10 seconds
});
test('should maintain performance under concurrent load', async () => {
const workflowDef = {
id: 'load_test_workflow',
name: 'Load Test Workflow',
version: '1.0.0',
steps: [
{
id: 'cpu_intensive_task',
type: 'analysis',
implementation: async (context) => {
// Simulate CPU-intensive work
let sum = 0;
for (let i = 0; i < 100000; i++) {
sum += Math.sqrt(i);
}
return { calculation_result: sum };
}
}
]
};
await engine.registerWorkflow(workflowDef);
// Execute 20 workflows concurrently
const startTime = Date.now();
const executionPromises = Array.from({ length: 20 }, (_, i) =>
engine.executeWorkflow('load_test_workflow', { batch_id: i })
);
const executionIds = await Promise.all(executionPromises);
const resultPromises = executionIds.map(id =>
engine.waitForCompletion(id, 30000)
);
const results = await Promise.all(resultPromises);
const endTime = Date.now();
// Verify all completed successfully
results.forEach(result => {
expect(result.status).toBe('completed');
expect(typeof result.steps[0].outputs.calculation_result).toBe('number');
});
// Performance expectation: should handle 20 concurrent workflows within reasonable time
expect(endTime - startTime).toBeLessThan(15000); // 15 seconds max
console.log(`Concurrent load test completed in ${endTime - startTime}ms`);
});
});
});