Files
wehub-resource-sync 23f7624596
ADR-166 MCP Bridge Security Lock / Static-source security lock (push) Failing after 0s
ADR-166 MCP Bridge Security Lock / Compose default binds loopback + Mongo has auth (push) Failing after 2s
CodeQL Advanced / Analyze (rust) (push) Failing after 0s
ADR-166 MCP Bridge Security Lock / plugin-agent-federation bindHost default (push) Failing after 1s
ADR-166 MCP Bridge Security Lock / Runtime behavior — 401 + terminal gate + fail-closed (push) Failing after 4s
business-pods-smoke / smoke (push) Failing after 1s
all-plugins-smoke / smoke-all (push) Failing after 2s
CI/CD Pipeline / Security & Code Quality (push) Failing after 1s
CI/CD Pipeline / Test Suite (ubuntu-latest) (push) Failing after 1s
CI/CD Pipeline / Build & Package (macos-latest) (push) Has been skipped
CI/CD Pipeline / Build & Package (ubuntu-latest) (push) Has been skipped
CI/CD Pipeline / Build & Package (windows-latest) (push) Has been skipped
CI/CD Pipeline / Documentation & Examples (push) Failing after 1s
Clone Tracker (14-day rolling) / Snapshot clones for ruflo ecosystem (push) Failing after 1s
CodeQL Advanced / Analyze (actions) (push) Failing after 1s
CodeQL Advanced / Analyze (javascript-typescript) (push) Failing after 1s
federation-peer-rust / stable-noop (push) Failing after 1s
metaharness-ci / score (push) Failing after 1s
metaharness-ci / router-compat (push) Failing after 0s
metaharness-ci / similarity-tests (push) Failing after 0s
no-agentbbs-smoke / smoke-without-agentbbs (push) Failing after 1s
V3 CI/CD Pipeline / Build V3 (windows-latest) (push) Has been skipped
codex-integration-audit / Codex integration audit (push) Failing after 1s
helpers-manifest-guard / guard (push) Failing after 1s
🔗 Cross-Agent Integration Tests / 🤝 Agent Coordination Tests (push) Has been skipped
🔗 Cross-Agent Integration Tests / 🧠 Memory Sharing Integration (push) Has been skipped
🔗 Cross-Agent Integration Tests / 🛡️ Fault Tolerance Tests (push) Has been skipped
🔗 Cross-Agent Integration Tests / ⚡ Performance Integration Tests (push) Has been skipped
metaharness-ci / mcp-scan (push) Failing after 1s
metaharness-ci / eject-dryrun (push) Failing after 1s
metaharness-ci / metaharness-real-data (push) Failing after 0s
no-cli-optdep-bloat-2561 / guard (push) Failing after 1s
no-metaharness-smoke / smoke-without-metaharness (push) Failing after 1s
no-phantom-agentic-flow-subpath / guard (push) Failing after 1s
🔄 Automated Rollback Manager / 🚨 Failure Detection (push) Failing after 1s
V3 CI/CD Pipeline / Plugin hooks smoke / ubuntu-latest / Node 22 (push) Failing after 1s
V3 CI/CD Pipeline / ruflo-graph-intelligence build + test smoke (#2044, ADR-123) (push) Failing after 1s
CVE Audit Gate / Audit root (critical-blocking) (push) Failing after 2s
cost-tracker-smoke / smoke (push) Failing after 3s
oia-audit-weekly / audit (push) Failing after 2s
ruflo-agent-smoke / ruflo-agent structural smoke (push) Failing after 1s
📊 Status Badges Update / 📊 Update Status Badges (push) Failing after 1s
V3 CI/CD Pipeline / Static regression guards (#2267 YAML + (push) Failing after 1s
V3 CI/CD Pipeline / Test V3 Packages (push) Failing after 0s
V3 CI/CD Pipeline / agent_execute provider routing smoke (#2042) (push) Failing after 0s
CVE Audit Gate / Audit v3 (critical-blocking) (push) Failing after 1s
federation-peer-rust / stable-native (push) Failing after 2s
🔗 Cross-Agent Integration Tests / 🚀 Integration Test Setup (push) Failing after 2s
neural-trader-smoke / runtime-smoke (push) Failing after 1s
V3 CI/CD Pipeline / Build V3 (macos-latest) (push) Has been skipped
V3 CI/CD Pipeline / Build V3 (ubuntu-latest) (push) Has been skipped
V3 CI/CD Pipeline / Type Check V3 (push) Failing after 1s
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / ubuntu-latest / Node 24 (push) Failing after 1s
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / ubuntu-latest / Node 22 (push) Failing after 2s
V3 CI/CD Pipeline / browser rvf create flag smoke (#2015) (push) Failing after 0s
V3 CI/CD Pipeline / Dependency review (#2046) (push) Has been skipped
V3 CI/CD Pipeline / Supply-chain audit (#2046) (push) Failing after 0s
V3 CI/CD Pipeline / witness marker drift smoke (#2021) (push) Failing after 1s
V3 CI/CD Pipeline / neural-trader portfolio CG smoke (#2068, ADR-126 Phase 3) (push) Failing after 1s
V3 CI/CD Pipeline / neural-trader backtest signing smoke (#2068, ADR-126 Phase 4) (push) Failing after 1s
V3 CI/CD Pipeline / kg-extract type-import classification smoke (#2049) (push) Failing after 0s
V3 CI/CD Pipeline / witness verify precondition smoke (#1880) (push) Failing after 2s
V3 CI/CD Pipeline / neural-trader pipeline risk-gate smoke (#2068, ADR-126 Phase 5) (push) Failing after 0s
V3 CI/CD Pipeline / neural-trader feature attribution smoke (#2068, ADR-126 Phase 6) (push) Failing after 0s
V3 CI/CD Pipeline / plugin-registry signature verification smoke (#1922, CWE-347) (push) Failing after 4s
V3 CI/CD Pipeline / memory stats legacy-DB smoke (#2120) (push) Failing after 4s
V3 CI/CD Pipeline / github deprecated actions smoke (#2089, ADR-127 Phase 3) (push) Failing after 1s
V3 CI/CD Pipeline / graph query + pathfinder smoke (ADR-130 P2+P5) (push) Has been skipped
V3 CI/CD Pipeline / graph trajectory hooks smoke (ADR-130 P3) (push) Has been skipped
V3 CI/CD Pipeline / graph plugin adapter smoke (ADR-130 P4) (push) Has been skipped
V3 CI/CD Pipeline / graph benchmark (ADR-130 P6) (push) Has been skipped
V3 CI/CD Pipeline / statusline generator delegation smoke (#2195) (push) Failing after 1s
V3 CI/CD Pipeline / wizard init regression guard (#2206 (push) Failing after 1s
V3 CI/CD Pipeline / memory no-stray-db smoke (ADR-125 P7) (push) Failing after 1s
V3 CI/CD Pipeline / github-safe injection smoke (#2089, ADR-127 Phase 1) (push) Failing after 1s
V3 CI/CD Pipeline / github actions pin smoke (#2089, ADR-127 Phase 1) (push) Failing after 1s
V3 CI/CD Pipeline / github attribution opt-in smoke (#2089, ADR-127 Phase 4) (push) Failing after 1s
V3 CI/CD Pipeline / pre-bash hook safety smoke (#2017) (push) Failing after 1s
V3 CI/CD Pipeline / Memory import smoke / ubuntu-latest (push) Failing after 0s
V3 CI/CD Pipeline / MCP protocol smoke / ubuntu-latest (push) Failing after 2s
V3 CI/CD Pipeline / ruvllm WASM auto-init smoke (#2086) (push) Failing after 4s
V3 CI/CD Pipeline / MCP paired-tool round-trip smoke (#1889) (push) Failing after 1s
V3 CI/CD Pipeline / Plugin package install-safety (#1902/#1903/#1904) (push) Failing after 1s
V3 CI/CD Pipeline / Tool description discoverability (ADR-112) (push) Failing after 3s
V3 CI/CD Pipeline / CLI npx-install smoke (#1147 / (22) (push) Failing after 1s
V3 CI/CD Pipeline / CLI npx-install smoke (#1147 / (24) (push) Failing after 1s
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / ubuntu-latest (push) Failing after 2s
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / ubuntu-latest (push) Failing after 1s
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / ubuntu-latest (push) Failing after 1s
V3 CI/CD Pipeline / Vector-index dimension audit (#1947) (push) Failing after 0s
V3 CI/CD Pipeline / Hook-command install safety (#1921) (push) Failing after 1s
V3 CI/CD Pipeline / ToolOutputGuardrail smoke (ADR-131, (push) Failing after 1s
V3 CI/CD Pipeline / init-bundle invariants smoke (#2095, ADR-128 Phase 5) (push) Failing after 1s
V3 CI/CD Pipeline / wasm provider bridge smoke (ADR-129 P1) (push) Failing after 2s
V3 CI/CD Pipeline / wasm gallery CRUD smoke (ADR-129 P3) (push) Failing after 1s
V3 CI/CD Pipeline / wasm plugin bridge smoke (ADR-129 P4) (push) Failing after 0s
V3 CI/CD Pipeline / wasm compose smoke (ADR-129 P2) (push) Failing after 4s
V3 CI/CD Pipeline / graph schema smoke (ADR-130 P1) (push) Failing after 0s
Validate Marketplace / validate (push) Failing after 1s
🔍 Verification Pipeline / 🚀 Setup Verification (push) Failing after 1s
🔍 Verification Pipeline / 🛡️ Security Verification (push) Has been skipped
🔍 Verification Pipeline / 📝 Code Quality (push) Has been skipped
🔍 Verification Pipeline / 🧪 Test Verification (${{ matrix.os }}, Node ${{ matrix.node }}) (push) Has been skipped
🔍 Verification Pipeline / 🏗️ Build Verification (push) Has been skipped
🔍 Verification Pipeline / 📚 Documentation Verification (push) Has been skipped
CVE Audit Gate / High-severity report (warn only) (push) Has been cancelled
🔄 Automated Rollback Manager / 🔄 Execute Rollback (push) Has been cancelled
🔄 Automated Rollback Manager / ✅ Post-Rollback Verification (push) Has been cancelled
🔄 Automated Rollback Manager / 📊 Rollback Monitoring (push) Has been cancelled
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / windows-latest (push) Has been cancelled
🔄 Automated Rollback Manager / ⏳ Manual Rollback Approval (push) Has been cancelled
V3 CI/CD Pipeline / MCP protocol smoke / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Memory import smoke / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / ubuntu-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Publish to npm (alpha) (push) Has been cancelled
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / macos-latest / Node 22 (push) Has been cancelled
V3 CI/CD Pipeline / Plugin hooks smoke / macos-latest / Node 22 (push) Has been cancelled
CI/CD Pipeline / Deploy & Release (push) Has been cancelled
CI/CD Pipeline / CI Status (push) Has been cancelled
🔗 Cross-Agent Integration Tests / 📊 Integration Test Report (push) Has been cancelled
🔄 Automated Rollback Manager / 🔍 Pre-Rollback Validation (push) Has been cancelled
🔍 Verification Pipeline / ⚡ Performance Verification (push) Has been cancelled
🔍 Verification Pipeline / 📊 Verification Report (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:02:19 +08:00

693 lines
20 KiB
TypeScript

/**
* Security Scan Tool Tests
*
* Tests for the aqe/security-scan MCP tool that provides
* SAST/DAST security scanning with compliance checking.
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
// ============================================================================
// Mock Types
// ============================================================================
interface SecurityScanInput {
targetPath: string;
scanType?: 'sast' | 'dast' | 'both';
compliance?: string[];
options?: {
severity?: 'low' | 'medium' | 'high' | 'critical';
maxFindings?: number;
includeRemediation?: boolean;
timeout?: number;
};
}
interface SecurityFinding {
id: string;
title: string;
description: string;
severity: 'low' | 'medium' | 'high' | 'critical';
type: string;
cwe?: string;
owasp?: string;
file?: string;
line?: number;
code?: string;
remediation?: string;
confidence: number;
}
interface ComplianceResult {
standard: string;
passed: number;
failed: number;
notApplicable: number;
findings: string[];
}
interface SecurityScanOutput {
success: boolean;
findings: SecurityFinding[];
compliance: ComplianceResult[];
summary: {
totalFindings: number;
criticalCount: number;
highCount: number;
mediumCount: number;
lowCount: number;
scanDuration: number;
filesScanned: number;
passedCompliance: boolean;
};
errors?: string[];
}
// ============================================================================
// Mock Implementation
// ============================================================================
class MockSecurityScanTool {
private knownVulnerabilities: SecurityFinding[] = [
{
id: 'SEC-001',
title: 'SQL Injection',
description: 'Potential SQL injection vulnerability detected',
severity: 'critical',
type: 'injection',
cwe: 'CWE-89',
owasp: 'A03:2021',
file: 'src/db/queries.ts',
line: 45,
code: 'db.query(`SELECT * FROM users WHERE id = ${userId}`)',
remediation: 'Use parameterized queries instead of string interpolation',
confidence: 0.95,
},
{
id: 'SEC-002',
title: 'Cross-Site Scripting (XSS)',
description: 'Potential XSS vulnerability in user input rendering',
severity: 'high',
type: 'xss',
cwe: 'CWE-79',
owasp: 'A03:2021',
file: 'src/components/UserProfile.tsx',
line: 23,
code: '<div dangerouslySetInnerHTML={{ __html: userInput }} />',
remediation: 'Sanitize user input before rendering or avoid dangerouslySetInnerHTML',
confidence: 0.9,
},
{
id: 'SEC-003',
title: 'Hardcoded Secret',
description: 'Hardcoded API key detected',
severity: 'high',
type: 'secrets',
cwe: 'CWE-798',
owasp: 'A02:2021',
file: 'src/config.ts',
line: 12,
code: 'const API_KEY = "sk-1234567890abcdef"',
remediation: 'Move secrets to environment variables',
confidence: 0.99,
},
{
id: 'SEC-004',
title: 'Insecure Direct Object Reference',
description: 'Potential IDOR vulnerability',
severity: 'medium',
type: 'access-control',
cwe: 'CWE-639',
owasp: 'A01:2021',
file: 'src/api/users.ts',
line: 67,
code: 'getUser(req.params.id)',
remediation: 'Verify user authorization before accessing resources',
confidence: 0.7,
},
{
id: 'SEC-005',
title: 'Missing Rate Limiting',
description: 'API endpoint without rate limiting',
severity: 'low',
type: 'dos',
cwe: 'CWE-770',
owasp: 'A04:2021',
file: 'src/api/auth.ts',
line: 15,
remediation: 'Implement rate limiting middleware',
confidence: 0.6,
},
];
async execute(input: SecurityScanInput): Promise<SecurityScanOutput> {
const startTime = Date.now();
// Validate input
const errors = this.validateInput(input);
if (errors.length > 0) {
return this.createErrorResponse(errors);
}
// Filter findings based on options
let findings = this.filterFindings(input);
// Add remediation if requested
if (input.options?.includeRemediation === false) {
findings = findings.map((f) => {
const { remediation, ...rest } = f;
return rest as SecurityFinding;
});
}
// Limit findings
if (input.options?.maxFindings) {
findings = findings.slice(0, input.options.maxFindings);
}
// Check compliance
const compliance = this.checkCompliance(findings, input.compliance ?? []);
const duration = Date.now() - startTime;
return {
success: true,
findings,
compliance,
summary: this.generateSummary(findings, compliance, duration),
};
}
private validateInput(input: SecurityScanInput): string[] {
const errors: string[] = [];
if (!input.targetPath) {
errors.push('targetPath is required');
}
if (input.targetPath && !input.targetPath.match(/^[./]/)) {
errors.push('targetPath must be a valid path');
}
if (input.options?.timeout && input.options.timeout < 1000) {
errors.push('timeout must be at least 1000ms');
}
if (input.options?.maxFindings !== undefined && input.options.maxFindings < 1) {
errors.push('maxFindings must be at least 1');
}
return errors;
}
private filterFindings(input: SecurityScanInput): SecurityFinding[] {
let findings = [...this.knownVulnerabilities];
// Filter by scan type
if (input.scanType === 'sast') {
findings = findings.filter((f) => f.file !== undefined);
} else if (input.scanType === 'dast') {
// DAST focuses on runtime vulnerabilities
findings = findings.filter((f) => ['injection', 'xss', 'access-control'].includes(f.type));
}
// Filter by severity
if (input.options?.severity) {
const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
const minSeverity = severityOrder[input.options.severity];
findings = findings.filter((f) => severityOrder[f.severity] <= minSeverity);
}
return findings;
}
private checkCompliance(
findings: SecurityFinding[],
standards: string[]
): ComplianceResult[] {
const results: ComplianceResult[] = [];
for (const standard of standards) {
const result = this.checkStandard(standard, findings);
results.push(result);
}
return results;
}
private checkStandard(standard: string, findings: SecurityFinding[]): ComplianceResult {
const standardLower = standard.toLowerCase();
if (standardLower.includes('owasp')) {
const owaspFindings = findings.filter((f) => f.owasp);
return {
standard,
passed: 10 - owaspFindings.length,
failed: owaspFindings.length,
notApplicable: 0,
findings: owaspFindings.map((f) => f.id),
};
}
if (standardLower.includes('sans')) {
const criticalFindings = findings.filter(
(f) => f.severity === 'critical' || f.severity === 'high'
);
return {
standard,
passed: 25 - criticalFindings.length,
failed: criticalFindings.length,
notApplicable: 0,
findings: criticalFindings.map((f) => f.id),
};
}
// Generic compliance check
return {
standard,
passed: 20 - findings.length,
failed: findings.length,
notApplicable: 0,
findings: findings.map((f) => f.id),
};
}
private generateSummary(
findings: SecurityFinding[],
compliance: ComplianceResult[],
duration: number
): SecurityScanOutput['summary'] {
const criticalCount = findings.filter((f) => f.severity === 'critical').length;
const highCount = findings.filter((f) => f.severity === 'high').length;
const mediumCount = findings.filter((f) => f.severity === 'medium').length;
const lowCount = findings.filter((f) => f.severity === 'low').length;
const passedCompliance = compliance.every((c) => c.failed === 0);
return {
totalFindings: findings.length,
criticalCount,
highCount,
mediumCount,
lowCount,
scanDuration: duration,
filesScanned: 42, // Mock value
passedCompliance,
};
}
private createErrorResponse(errors: string[]): SecurityScanOutput {
return {
success: false,
findings: [],
compliance: [],
summary: {
totalFindings: 0,
criticalCount: 0,
highCount: 0,
mediumCount: 0,
lowCount: 0,
scanDuration: 0,
filesScanned: 0,
passedCompliance: false,
},
errors,
};
}
}
// ============================================================================
// Tests
// ============================================================================
describe('SecurityScanTool', () => {
let tool: MockSecurityScanTool;
beforeEach(() => {
tool = new MockSecurityScanTool();
});
describe('input validation', () => {
it('should require targetPath', async () => {
const result = await tool.execute({ targetPath: '' });
expect(result.success).toBe(false);
expect(result.errors).toContain('targetPath is required');
});
it('should validate targetPath format', async () => {
const result = await tool.execute({ targetPath: 'invalid' });
expect(result.success).toBe(false);
expect(result.errors.some(e => e.includes('valid path'))).toBe(true);
});
it('should accept valid paths', async () => {
const relativeResult = await tool.execute({ targetPath: './src' });
const absoluteResult = await tool.execute({ targetPath: '/workspace/src' });
expect(relativeResult.success).toBe(true);
expect(absoluteResult.success).toBe(true);
});
it('should validate timeout minimum', async () => {
const result = await tool.execute({
targetPath: './src',
options: { timeout: 500 },
});
expect(result.success).toBe(false);
expect(result.errors.some(e => e.includes('timeout'))).toBe(true);
});
it('should validate maxFindings minimum', async () => {
const result = await tool.execute({
targetPath: './src',
options: { maxFindings: 0 },
});
expect(result.success).toBe(false);
expect(result.errors.some(e => e.includes('maxFindings'))).toBe(true);
});
});
describe('finding detection', () => {
it('should detect security findings', async () => {
const result = await tool.execute({ targetPath: './src' });
expect(result.success).toBe(true);
expect(result.findings.length).toBeGreaterThan(0);
});
it('should include finding ID', async () => {
const result = await tool.execute({ targetPath: './src' });
for (const finding of result.findings) {
expect(finding.id).toBeTruthy();
expect(finding.id).toMatch(/^SEC-/);
}
});
it('should include finding title and description', async () => {
const result = await tool.execute({ targetPath: './src' });
for (const finding of result.findings) {
expect(finding.title).toBeTruthy();
expect(finding.description).toBeTruthy();
}
});
it('should include severity level', async () => {
const result = await tool.execute({ targetPath: './src' });
for (const finding of result.findings) {
expect(['low', 'medium', 'high', 'critical']).toContain(finding.severity);
}
});
it('should include CWE reference when available', async () => {
const result = await tool.execute({ targetPath: './src' });
const findingsWithCwe = result.findings.filter((f) => f.cwe);
expect(findingsWithCwe.length).toBeGreaterThan(0);
for (const finding of findingsWithCwe) {
expect(finding.cwe).toMatch(/^CWE-\d+$/);
}
});
it('should include OWASP reference when available', async () => {
const result = await tool.execute({ targetPath: './src' });
const findingsWithOwasp = result.findings.filter((f) => f.owasp);
expect(findingsWithOwasp.length).toBeGreaterThan(0);
});
it('should include file and line for SAST findings', async () => {
const result = await tool.execute({
targetPath: './src',
scanType: 'sast',
});
for (const finding of result.findings) {
expect(finding.file).toBeTruthy();
expect(finding.line).toBeGreaterThan(0);
}
});
it('should include confidence score', async () => {
const result = await tool.execute({ targetPath: './src' });
for (const finding of result.findings) {
expect(finding.confidence).toBeGreaterThan(0);
expect(finding.confidence).toBeLessThanOrEqual(1);
}
});
it('should include remediation by default', async () => {
const result = await tool.execute({ targetPath: './src' });
const findingsWithRemediation = result.findings.filter((f) => f.remediation);
expect(findingsWithRemediation.length).toBeGreaterThan(0);
});
it('should exclude remediation when disabled', async () => {
const result = await tool.execute({
targetPath: './src',
options: { includeRemediation: false },
});
const findingsWithRemediation = result.findings.filter((f) => f.remediation);
expect(findingsWithRemediation.length).toBe(0);
});
});
describe('scan type filtering', () => {
it('should default to both scan types', async () => {
const result = await tool.execute({ targetPath: './src' });
expect(result.findings.length).toBeGreaterThan(0);
});
it('should filter for SAST only', async () => {
const result = await tool.execute({
targetPath: './src',
scanType: 'sast',
});
// All findings should have file references
expect(result.findings.every((f) => f.file !== undefined)).toBe(true);
});
it('should filter for DAST only', async () => {
const result = await tool.execute({
targetPath: './src',
scanType: 'dast',
});
// DAST focuses on runtime vulnerabilities
const dastTypes = ['injection', 'xss', 'access-control'];
expect(result.findings.every((f) => dastTypes.includes(f.type))).toBe(true);
});
});
describe('severity filtering', () => {
it('should filter by severity threshold', async () => {
const criticalResult = await tool.execute({
targetPath: './src',
options: { severity: 'critical' },
});
const highResult = await tool.execute({
targetPath: './src',
options: { severity: 'high' },
});
expect(criticalResult.findings.length).toBeLessThanOrEqual(highResult.findings.length);
expect(criticalResult.findings.every((f) => f.severity === 'critical')).toBe(true);
});
it('should include critical and high for high threshold', async () => {
const result = await tool.execute({
targetPath: './src',
options: { severity: 'high' },
});
expect(result.findings.every((f) => f.severity === 'critical' || f.severity === 'high')).toBe(
true
);
});
});
describe('compliance checking', () => {
it('should check OWASP compliance', async () => {
const result = await tool.execute({
targetPath: './src',
compliance: ['owasp-top-10'],
});
expect(result.compliance.length).toBe(1);
expect(result.compliance[0].standard).toBe('owasp-top-10');
expect(result.compliance[0].passed).toBeDefined();
expect(result.compliance[0].failed).toBeDefined();
});
it('should check SANS compliance', async () => {
const result = await tool.execute({
targetPath: './src',
compliance: ['sans-25'],
});
expect(result.compliance.length).toBe(1);
expect(result.compliance[0].standard).toBe('sans-25');
});
it('should check multiple standards', async () => {
const result = await tool.execute({
targetPath: './src',
compliance: ['owasp-top-10', 'sans-25'],
});
expect(result.compliance.length).toBe(2);
});
it('should link findings to compliance failures', async () => {
const result = await tool.execute({
targetPath: './src',
compliance: ['owasp-top-10'],
});
expect(result.compliance[0].findings).toBeDefined();
expect(Array.isArray(result.compliance[0].findings)).toBe(true);
});
});
describe('summary generation', () => {
it('should include total finding count', async () => {
const result = await tool.execute({ targetPath: './src' });
expect(result.summary.totalFindings).toBe(result.findings.length);
});
it('should count findings by severity', async () => {
const result = await tool.execute({ targetPath: './src' });
const critical = result.findings.filter((f) => f.severity === 'critical').length;
const high = result.findings.filter((f) => f.severity === 'high').length;
const medium = result.findings.filter((f) => f.severity === 'medium').length;
const low = result.findings.filter((f) => f.severity === 'low').length;
expect(result.summary.criticalCount).toBe(critical);
expect(result.summary.highCount).toBe(high);
expect(result.summary.mediumCount).toBe(medium);
expect(result.summary.lowCount).toBe(low);
});
it('should report scan duration', async () => {
const result = await tool.execute({ targetPath: './src' });
expect(result.summary.scanDuration).toBeGreaterThanOrEqual(0);
});
it('should report files scanned', async () => {
const result = await tool.execute({ targetPath: './src' });
expect(result.summary.filesScanned).toBeGreaterThan(0);
});
it('should report compliance status', async () => {
const result = await tool.execute({
targetPath: './src',
compliance: ['owasp-top-10'],
});
expect(typeof result.summary.passedCompliance).toBe('boolean');
});
});
describe('finding limits', () => {
it('should respect maxFindings limit', async () => {
const result = await tool.execute({
targetPath: './src',
options: { maxFindings: 2 },
});
expect(result.findings.length).toBeLessThanOrEqual(2);
});
it('should return all findings when no limit', async () => {
const result = await tool.execute({ targetPath: './src' });
expect(result.findings.length).toBeGreaterThan(2);
});
});
});
describe('SecurityScanTool Common Vulnerabilities', () => {
let tool: MockSecurityScanTool;
beforeEach(() => {
tool = new MockSecurityScanTool();
});
it('should detect SQL injection', async () => {
const result = await tool.execute({ targetPath: './src' });
const sqlInjection = result.findings.find(
(f) => f.type === 'injection' && f.title.includes('SQL')
);
expect(sqlInjection).toBeDefined();
expect(sqlInjection?.severity).toBe('critical');
expect(sqlInjection?.cwe).toBe('CWE-89');
});
it('should detect XSS vulnerabilities', async () => {
const result = await tool.execute({ targetPath: './src' });
const xss = result.findings.find((f) => f.type === 'xss');
expect(xss).toBeDefined();
expect(xss?.cwe).toBe('CWE-79');
});
it('should detect hardcoded secrets', async () => {
const result = await tool.execute({ targetPath: './src' });
const secrets = result.findings.find((f) => f.type === 'secrets');
expect(secrets).toBeDefined();
expect(secrets?.confidence).toBeGreaterThan(0.9);
});
it('should detect access control issues', async () => {
const result = await tool.execute({ targetPath: './src' });
const accessControl = result.findings.find((f) => f.type === 'access-control');
expect(accessControl).toBeDefined();
});
});
describe('SecurityScanTool Performance', () => {
let tool: MockSecurityScanTool;
beforeEach(() => {
tool = new MockSecurityScanTool();
});
it('should complete scan in reasonable time', async () => {
const startTime = performance.now();
const result = await tool.execute({ targetPath: './src' });
const duration = performance.now() - startTime;
expect(result.success).toBe(true);
// Should complete in under 100ms for mock
expect(duration).toBeLessThan(100);
});
it('should report scan duration in summary', async () => {
const result = await tool.execute({ targetPath: './src' });
expect(result.summary.scanDuration).toBeGreaterThanOrEqual(0);
});
});