1use crate::crud_flow::{CrudFlowConfig, CrudFlowDetector};
4use crate::data_driven::{DataDistribution, DataDrivenConfig, DataDrivenGenerator, DataMapping};
5use crate::dynamic_params::{DynamicParamProcessor, DynamicPlaceholder};
6use crate::error::{BenchError, Result};
7use crate::executor::K6Executor;
8use crate::invalid_data::{InvalidDataConfig, InvalidDataGenerator};
9use crate::k6_gen::{K6Config, K6ScriptGenerator};
10use crate::mock_integration::{
11 MockIntegrationConfig, MockIntegrationGenerator, MockServerDetector,
12};
13use crate::owasp_api::{OwaspApiConfig, OwaspApiGenerator, OwaspCategory, ReportFormat};
14use crate::parallel_executor::{AggregatedResults, ParallelExecutor};
15use crate::parallel_requests::{ParallelConfig, ParallelRequestGenerator};
16use crate::param_overrides::ParameterOverrides;
17use crate::reporter::TerminalReporter;
18use crate::request_gen::RequestGenerator;
19use crate::scenarios::LoadScenario;
20use crate::security_payloads::{
21 SecurityCategory, SecurityPayload, SecurityPayloads, SecurityTestConfig, SecurityTestGenerator,
22};
23use crate::spec_dependencies::{
24 topological_sort, DependencyDetector, ExtractedValues, SpecDependencyConfig,
25};
26use crate::spec_parser::SpecParser;
27use crate::target_parser::parse_targets_file;
28use crate::wafbench::WafBenchLoader;
29use mockforge_openapi::multi_spec::{
30 load_specs_from_directory, load_specs_from_files, merge_specs, ConflictStrategy,
31};
32use mockforge_openapi::spec::OpenApiSpec;
33use std::collections::{HashMap, HashSet};
34use std::path::{Path, PathBuf};
35use std::str::FromStr;
36
37pub fn parse_header_string(inputs: &[String]) -> Result<HashMap<String, String>> {
45 let mut headers = HashMap::new();
46
47 for pair in inputs {
48 let pair = pair.trim();
49 if pair.is_empty() {
50 continue;
51 }
52 let parts: Vec<&str> = pair.splitn(2, ':').collect();
53 if parts.len() != 2 {
54 return Err(BenchError::Other(format!(
55 "Invalid header format: '{}'. Expected 'Key:Value'",
56 pair
57 )));
58 }
59 headers.insert(parts[0].trim().to_string(), parts[1].trim().to_string());
60 }
61
62 Ok(headers)
63}
64
65const CONFORMANCE_REPLACES_LOAD_ADVISORY: &str =
85 "Conformance mode REPLACES the load run: 1 VU, 1 iteration per endpoint. \
86 --vus, --rps and -d are ignored. Run bench a second time without \
87 --conformance if you also want a load test.";
88
89pub struct BenchCommand {
91 pub spec: Vec<PathBuf>,
93 pub spec_dir: Option<PathBuf>,
95 pub merge_conflicts: String,
97 pub spec_mode: String,
99 pub dependency_config: Option<PathBuf>,
101 pub target: String,
102 pub base_path: Option<String>,
105 pub duration: String,
106 pub vus: u32,
107 pub target_rps: Option<u32>,
113 pub no_keep_alive: bool,
118 pub scenario: String,
119 pub operations: Option<String>,
120 pub exclude_operations: Option<String>,
124 pub auth: Option<String>,
125 pub headers: Vec<String>,
128 pub output: PathBuf,
129 pub generate_only: bool,
130 pub script_output: Option<PathBuf>,
131 pub threshold_percentile: String,
132 pub threshold_ms: u64,
133 pub max_error_rate: f64,
134 pub abort_on_error: bool,
139 pub abort_on_error_rate: f64,
143 pub verbose: bool,
144 pub skip_tls_verify: bool,
145 pub chunked_request_bodies: bool,
150 pub targets_file: Option<PathBuf>,
152 pub max_concurrency: Option<u32>,
154 pub results_format: String,
156 pub params_file: Option<PathBuf>,
161
162 pub crud_flow: bool,
165 pub flow_config: Option<PathBuf>,
167 pub extract_fields: Option<String>,
169
170 pub parallel_create: Option<u32>,
173
174 pub data_file: Option<PathBuf>,
177 pub data_distribution: String,
179 pub data_mappings: Option<String>,
181 pub per_uri_control: bool,
183
184 pub error_rate: Option<f64>,
187 pub error_types: Option<String>,
189
190 pub security_test: bool,
193 pub security_payloads: Option<PathBuf>,
195 pub security_categories: Option<String>,
197 pub security_target_fields: Option<String>,
199
200 pub wafbench_dir: Option<String>,
203 pub wafbench_cycle_all: bool,
205 pub wafbench_verbatim: bool,
208
209 pub conformance: bool,
212 pub conformance_api_key: Option<String>,
214 pub conformance_basic_auth: Option<String>,
216 pub conformance_report: PathBuf,
218 pub conformance_categories: Option<String>,
220 pub conformance_report_format: String,
222 pub conformance_headers: Vec<String>,
225 pub conformance_all_operations: bool,
228 pub conformance_custom: Option<PathBuf>,
230 pub conformance_delay_ms: u64,
233 pub use_k6: bool,
235 pub conformance_custom_filter: Option<String>,
239 pub export_requests: bool,
242 pub validate_requests: bool,
245 pub conformance_self_test: bool,
252 pub conformance_self_test_capture: bool,
256 pub validate_response_schemas: bool,
262 pub conformance_self_test_iterations: u32,
267 pub conformance_self_test_duration: Option<String>,
272
273 pub source_ips: Vec<String>,
278 pub geo_source_ips: Vec<String>,
282 pub geo_source_headers: Vec<String>,
286
287 pub report_missed_cap: Option<u32>,
294
295 pub discard_response_bodies: bool,
302
303 pub dns_policy: Option<String>,
309
310 pub owasp_api_top10: bool,
313 pub owasp_categories: Option<String>,
315 pub owasp_auth_header: String,
317 pub owasp_auth_token: Option<String>,
319 pub owasp_admin_paths: Option<PathBuf>,
321 pub owasp_id_fields: Option<String>,
323 pub owasp_report: Option<PathBuf>,
325 pub owasp_report_format: String,
327 pub owasp_iterations: u32,
329}
330
331fn parse_ip_list(raw: &[String], flag_name: &str) -> Vec<std::net::IpAddr> {
345 use std::net::IpAddr;
346 const MAX_CIDR_EXPANSION: usize = 256;
347 let mut out = Vec::new();
348 for entry in raw {
349 for piece in entry.split(',') {
350 let s = piece.trim();
351 if s.is_empty() {
352 continue;
353 }
354 if let Some((addr_part, prefix_part)) = s.split_once('/') {
356 let prefix: u32 = match prefix_part.parse() {
357 Ok(p) => p,
358 Err(e) => {
359 tracing::warn!(target: "mockforge::bench", "ignoring --{flag_name} '{s}': bad CIDR prefix: {e}");
360 continue;
361 }
362 };
363 let net_addr: IpAddr = match addr_part.parse() {
364 Ok(a) => a,
365 Err(e) => {
366 tracing::warn!(target: "mockforge::bench", "ignoring --{flag_name} '{s}': bad CIDR address: {e}");
367 continue;
368 }
369 };
370 expand_cidr(net_addr, prefix, MAX_CIDR_EXPANSION, flag_name, s, &mut out);
371 continue;
372 }
373 if let Some((start_str, end_str)) = s.split_once('-') {
379 let start_s = start_str.trim();
380 let end_s = end_str.trim();
381 if start_s.contains(':') || end_s.contains(':') {
385 tracing::warn!(target: "mockforge::bench", "--{flag_name} '{s}': IPv6 range syntax not supported (use CIDR like 2001:db8::/126 instead)");
386 continue;
387 }
388 let start: IpAddr = match start_s.parse() {
389 Ok(a) => a,
390 Err(e) => {
391 tracing::warn!(target: "mockforge::bench", "ignoring --{flag_name} '{s}': bad range start: {e}");
392 continue;
393 }
394 };
395 let end: IpAddr = match end_s.parse() {
396 Ok(a) => a,
397 Err(e) => {
398 tracing::warn!(target: "mockforge::bench", "ignoring --{flag_name} '{s}': bad range end: {e}");
399 continue;
400 }
401 };
402 expand_range(start, end, MAX_CIDR_EXPANSION, flag_name, s, &mut out);
403 continue;
404 }
405 match s.parse::<IpAddr>() {
407 Ok(ip) => out.push(ip),
408 Err(e) => {
409 tracing::warn!(target: "mockforge::bench", "ignoring malformed --{flag_name} value '{s}': {e}");
410 }
411 }
412 }
413 }
414 out
415}
416
417fn expand_range(
421 start: std::net::IpAddr,
422 end: std::net::IpAddr,
423 cap: usize,
424 flag_name: &str,
425 raw: &str,
426 out: &mut Vec<std::net::IpAddr>,
427) {
428 use std::net::{IpAddr, Ipv4Addr};
429 let (start_v4, end_v4) = match (start, end) {
430 (IpAddr::V4(a), IpAddr::V4(b)) => (a, b),
431 _ => {
432 tracing::warn!(target: "mockforge::bench", "--{flag_name} '{raw}': range start/end must both be IPv4");
433 return;
434 }
435 };
436 let start_u32 = u32::from(start_v4);
437 let end_u32 = u32::from(end_v4);
438 if end_u32 < start_u32 {
439 tracing::warn!(target: "mockforge::bench", "--{flag_name} '{raw}': range end {end_v4} is before start {start_v4}");
440 return;
441 }
442 let total = (end_u32 - start_u32).saturating_add(1) as usize;
443 let take = total.min(cap);
444 if total > cap {
445 tracing::warn!(target: "mockforge::bench", "--{flag_name} '{raw}': range has {total} addresses, capping at {cap}");
446 }
447 for i in 0..take as u32 {
448 out.push(IpAddr::V4(Ipv4Addr::from(start_u32 + i)));
449 }
450}
451
452fn expand_cidr(
456 net: std::net::IpAddr,
457 prefix: u32,
458 cap: usize,
459 flag_name: &str,
460 raw: &str,
461 out: &mut Vec<std::net::IpAddr>,
462) {
463 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
464 match net {
465 IpAddr::V4(ipv4) => {
466 if prefix > 32 {
467 tracing::warn!(target: "mockforge::bench", "ignoring --{flag_name} '{raw}': IPv4 prefix must be <= 32");
468 return;
469 }
470 let total: u64 = 1u64 << (32 - prefix);
471 let take = total.min(cap as u64) as u32;
472 if total > cap as u64 {
473 tracing::warn!(target: "mockforge::bench", "--{flag_name} '{raw}': CIDR has {total} addresses, capping at {cap}");
474 }
475 let mask: u32 = if prefix == 0 {
476 0
477 } else {
478 !0u32 << (32 - prefix)
479 };
480 let net_u32 = u32::from(ipv4) & mask;
481 for i in 0..take {
482 out.push(IpAddr::V4(Ipv4Addr::from(net_u32.wrapping_add(i))));
483 }
484 }
485 IpAddr::V6(ipv6) => {
486 if prefix > 128 {
487 tracing::warn!(target: "mockforge::bench", "ignoring --{flag_name} '{raw}': IPv6 prefix must be <= 128");
488 return;
489 }
490 let mask: u128 = if prefix == 0 {
494 0
495 } else {
496 !0u128 << (128 - prefix)
497 };
498 let net_u128 = u128::from(ipv6) & mask;
499 let remaining_bits = 128 - prefix;
500 let total_capped = if remaining_bits >= 64 {
503 cap as u128
504 } else {
505 (1u128 << remaining_bits).min(cap as u128)
506 };
507 if remaining_bits < 128 && (1u128 << remaining_bits) > cap as u128 {
508 tracing::warn!(target: "mockforge::bench", "--{flag_name} '{raw}': IPv6 CIDR exceeds {cap} addresses, capping");
509 }
510 for i in 0..total_capped {
511 out.push(IpAddr::V6(Ipv6Addr::from(net_u128.wrapping_add(i))));
512 }
513 }
514 }
515}
516
517impl BenchCommand {
518 pub fn security_testing_enabled(&self) -> bool {
534 if self.wafbench_verbatim {
535 return false;
536 }
537 self.security_test || self.wafbench_dir.is_some()
538 }
539
540 pub async fn load_and_merge_specs(&self) -> Result<OpenApiSpec> {
542 let mut all_specs: Vec<(PathBuf, OpenApiSpec)> = Vec::new();
543
544 if !self.spec.is_empty() {
546 let specs = load_specs_from_files(self.spec.clone())
547 .await
548 .map_err(|e| BenchError::Other(format!("Failed to load spec files: {}", e)))?;
549 all_specs.extend(specs);
550 }
551
552 if let Some(spec_dir) = &self.spec_dir {
554 let dir_specs = load_specs_from_directory(spec_dir).await.map_err(|e| {
555 BenchError::Other(format!("Failed to load specs from directory: {}", e))
556 })?;
557 all_specs.extend(dir_specs);
558 }
559
560 if all_specs.is_empty() {
561 return Err(BenchError::Other(
562 "No spec files provided. Use --spec or --spec-dir.".to_string(),
563 ));
564 }
565
566 if all_specs.len() == 1 {
568 return Ok(all_specs.into_iter().next().expect("checked len() == 1 above").1);
570 }
571
572 let conflict_strategy = match self.merge_conflicts.as_str() {
574 "first" => ConflictStrategy::First,
575 "last" => ConflictStrategy::Last,
576 _ => ConflictStrategy::Error,
577 };
578
579 merge_specs(all_specs, conflict_strategy)
580 .map_err(|e| BenchError::Other(format!("Failed to merge specs: {}", e)))
581 }
582
583 fn get_spec_display_name(&self) -> String {
585 if self.spec.len() == 1 {
586 self.spec[0].to_string_lossy().to_string()
587 } else if !self.spec.is_empty() {
588 format!("{} spec files", self.spec.len())
589 } else if let Some(dir) = &self.spec_dir {
590 format!("specs from {}", dir.display())
591 } else {
592 "no specs".to_string()
593 }
594 }
595
596 fn advise_capacity(&self) {
603 let target_count = self
604 .targets_file
605 .as_ref()
606 .and_then(|p| std::fs::read_to_string(p).ok())
607 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
608 .and_then(|v| v.as_array().map(|a| a.len()))
609 .unwrap_or(1);
610 let vus = self.vus.max(1);
611 let rps_total = self.target_rps.unwrap_or(0) as usize * target_count.max(1);
612 let load_product = target_count * vus as usize;
616 if load_product >= 150 {
617 let est_ram_gb =
618 (vus as usize * 50) / 1024 + (target_count * 10 * 2) / 1024 + target_count / 2;
619 let est_cores = ((vus as usize) / 50).max(2);
620 TerminalReporter::print_warning(&format!(
621 "Capacity advisory: targets={target_count}, VUs={vus}, RPS-total≈{rps_total}. \
622 Single-client estimate: ~{est_cores} CPU cores, ~{est_ram_gb} GB RAM. \
623 If your machine is below that, expect OOM hangs partway through the run. \
624 See https://docs.mockforge.dev/reference/bench-capacity-sizing.html \
625 for the sizing table and sharding guide."
626 ));
627 }
628 }
629
630 pub async fn execute(&self) -> Result<()> {
632 if self.conformance_self_test && self.use_k6 {
639 TerminalReporter::print_warning(
640 "--use-k6 has no effect with --conformance-self-test: the self-test driver runs and returns before k6 is invoked. Drop one or the other depending on whether you want the spec-driven self-test or a k6 bench run.",
641 );
642 }
643
644 self.advise_capacity();
650
651 if let Some(targets_file) = &self.targets_file {
653 if self.conformance && self.conformance_self_test {
662 return self.execute_multi_target_self_test(targets_file).await;
663 }
664 if self.conformance {
665 return self.execute_multi_target_conformance(targets_file).await;
666 }
667 return self.execute_multi_target(targets_file).await;
668 }
669
670 if self.spec_mode == "sequential" && (self.spec.len() > 1 || self.spec_dir.is_some()) {
672 return self.execute_sequential_specs().await;
673 }
674
675 TerminalReporter::print_header(
678 &self.get_spec_display_name(),
679 &self.target,
680 0, &self.scenario,
682 Self::parse_duration(&self.duration)?,
683 );
684
685 if !K6Executor::is_k6_installed() {
687 TerminalReporter::print_error("k6 is not installed");
688 TerminalReporter::print_warning(
689 "Install k6 from: https://k6.io/docs/get-started/installation/",
690 );
691 return Err(BenchError::K6NotFound);
692 }
693 K6Executor::warn_if_pre_v1().await;
694
695 if self.conformance {
697 return self.execute_conformance_test().await;
698 }
699
700 let spec_supplied = !self.spec.is_empty() || self.spec_dir.is_some();
707 let merged_spec = if self.wafbench_verbatim && !spec_supplied {
708 tracing::info!(
709 target: "mockforge::bench",
710 "--wafbench-verbatim without --spec: sending only the traffic file's requests"
711 );
712 OpenApiSpec {
713 spec: Default::default(),
714 file_path: None,
715 raw_document: None,
716 }
717 } else {
718 TerminalReporter::print_progress("Loading OpenAPI specification(s)...");
719 self.load_and_merge_specs().await?
720 };
721 let parser = SpecParser::from_spec(merged_spec);
722 if self.spec.len() > 1 || self.spec_dir.is_some() {
723 TerminalReporter::print_success(&format!(
724 "Loaded and merged {} specification(s)",
725 self.spec.len() + self.spec_dir.as_ref().map(|_| 1).unwrap_or(0)
726 ));
727 } else {
728 TerminalReporter::print_success("Specification loaded");
729 }
730
731 let mock_config = self.build_mock_config().await;
733 if mock_config.is_mock_server {
734 TerminalReporter::print_progress("Mock server integration enabled");
735 }
736
737 if self.crud_flow {
739 return self.execute_crud_flow(&parser).await;
740 }
741
742 if self.owasp_api_top10 {
744 return self.execute_owasp_test(&parser).await;
745 }
746
747 TerminalReporter::print_progress("Extracting API operations...");
749 let mut operations = if let Some(filter) = &self.operations {
750 parser.filter_operations(filter)?
751 } else {
752 parser.get_operations()
753 };
754
755 if let Some(exclude) = &self.exclude_operations {
757 let before_count = operations.len();
758 operations = parser.exclude_operations(operations, exclude)?;
759 let excluded_count = before_count - operations.len();
760 if excluded_count > 0 {
761 TerminalReporter::print_progress(&format!(
762 "Excluded {} operations matching '{}'",
763 excluded_count, exclude
764 ));
765 }
766 }
767
768 if operations.is_empty() && !self.wafbench_verbatim {
774 return Err(BenchError::Other("No operations found in spec".to_string()));
775 }
776
777 TerminalReporter::print_success(&format!("Found {} operations", operations.len()));
778
779 let param_overrides = if let Some(params_file) = &self.params_file {
781 TerminalReporter::print_progress("Loading parameter overrides...");
782 let overrides = ParameterOverrides::from_file(params_file)?;
783 TerminalReporter::print_success(&format!(
784 "Loaded parameter overrides ({} operation-specific, {} defaults)",
785 overrides.operations.len(),
786 if overrides.defaults.is_empty() { 0 } else { 1 }
787 ));
788 Some(overrides)
789 } else {
790 None
791 };
792
793 TerminalReporter::print_progress("Generating request templates...");
795 let templates: Vec<_> = operations
796 .iter()
797 .map(|op| {
798 let op_overrides = param_overrides.as_ref().map(|po| {
799 po.get_for_operation(op.operation_id.as_deref(), &op.method, &op.path)
800 });
801 RequestGenerator::generate_template_with_overrides(op, op_overrides.as_ref())
802 })
803 .collect::<Result<Vec<_>>>()?;
804 TerminalReporter::print_success("Request templates generated");
805
806 let templates = if self.wafbench_verbatim {
812 let verbatim = self.load_verbatim_templates()?;
813 if verbatim.is_empty() {
814 return Err(BenchError::Other(
815 "--wafbench-verbatim was set but no traffic cases were loaded. Check \
816 --wafbench-dir points at a file, directory or glob containing cases with \
817 a `request.uri`."
818 .to_string(),
819 ));
820 }
821 TerminalReporter::print_success(&format!(
822 "Verbatim mode: {} request(s) will be sent exactly as written (spec endpoints not used)",
823 verbatim.len()
824 ));
825 verbatim
826 } else {
827 templates
828 };
829
830 let custom_headers = self.parse_headers()?;
832
833 let base_path = self.resolve_base_path(&parser);
835 if let Some(ref bp) = base_path {
836 TerminalReporter::print_progress(&format!("Using base path: {}", bp));
837 }
838
839 TerminalReporter::print_progress("Generating k6 load test script...");
841 let scenario =
842 LoadScenario::from_str(&self.scenario).map_err(BenchError::InvalidScenario)?;
843
844 let security_testing_enabled = self.security_testing_enabled();
845
846 let num_ops = operations.len() as u32;
864 if let Some(rps) = self.target_rps {
865 let probe =
866 crate::preflight::probe_target_latency(&self.target, 3, self.skip_tls_verify).await;
867
868 let (required_vus, basis) = match probe {
869 Some(p) => (
870 p.required_vus(rps, num_ops),
871 format!("avg {:.1}ms (measured)", p.avg_latency.as_secs_f64() * 1000.0),
872 ),
873 None => {
874 let fallback = (rps as u64)
876 .saturating_mul(num_ops.max(1) as u64)
877 .div_ceil(10)
878 .min(u32::MAX as u64) as u32;
879 (fallback, "~100ms (default — probe failed)".to_string())
880 }
881 };
882
883 if self.vus < required_vus {
884 const VU_RECOMMENDATION_CAP: u32 = 1000;
890 let recommendation = required_vus.max(self.vus + 1);
891 if recommendation > VU_RECOMMENDATION_CAP {
892 TerminalReporter::print_warning(&format!(
893 "Workload is very large: --rps {} × {} ops/iteration × {} \
894 baseline ⇒ ~{} VUs needed end-to-end, far beyond what's \
895 practical to drive. Two ways to fix:\n 1. Reduce \
896 operations per iteration with `--operations 'pattern,…'` \
897 (or `--exclude-operations`) to focus the bench on a \
898 representative subset.\n 2. Drop `--rps` and use \
899 `--vus {}` alone — closed-model load runs as fast as \
900 the VU pool allows, bounded by latency, with no per-\
901 iteration deadline. Expect 1-iteration coverage of ~{} \
902 operations in {}s.",
903 rps,
904 num_ops,
905 basis,
906 recommendation,
907 self.vus.max(5),
908 num_ops,
909 Self::parse_duration(&self.duration).unwrap_or(0),
910 ));
911 } else {
912 TerminalReporter::print_warning(&format!(
913 "--vus {} may be insufficient for --rps {} × {} ops/iteration \
914 (baseline latency {}). k6's constant-arrival-rate counts ITERATIONS \
915 and each runs every operation in the spec — required ≈ rps × ops × \
916 latency_secs VUs. Bump --vus to ~{} if you see \"Insufficient VUs\" \
917 warnings.",
918 self.vus, rps, num_ops, basis, recommendation,
919 ));
920 }
921 } else if probe.is_some() {
922 TerminalReporter::print_progress(&format!(
923 "Pre-flight probe: target latency {}, {} ops/iteration — --vus {} \
924 is sufficient for --rps {}",
925 basis, num_ops, self.vus, rps,
926 ));
927 }
928 }
929
930 let k6_config = K6Config {
931 target_url: self.target.clone(),
932 base_path,
933 scenario,
934 duration_secs: Self::parse_duration(&self.duration)?,
935 max_vus: self.vus,
936 threshold_percentile: self.threshold_percentile.clone(),
937 threshold_ms: self.threshold_ms,
938 max_error_rate: self.max_error_rate,
939 auth_header: self.auth.clone(),
940 custom_headers,
941 skip_tls_verify: self.skip_tls_verify,
942 security_testing_enabled,
943 chunked_request_bodies: self.chunked_request_bodies,
944 target_rps: self.target_rps,
945 no_keep_alive: self.no_keep_alive,
946 geo_source_ips: parse_ip_list(&self.geo_source_ips, "geo-source-ip")
952 .into_iter()
953 .map(|ip| ip.to_string())
954 .collect(),
955 geo_source_headers: if self.geo_source_headers.is_empty()
956 && !self.geo_source_ips.is_empty()
957 {
958 crate::conformance::self_test::default_geo_source_headers()
959 } else {
960 self.geo_source_headers.clone()
961 },
962 };
963
964 let generator = K6ScriptGenerator::new(k6_config, templates)
965 .with_abort_valve(self.abort_on_error, self.abort_on_error_rate);
966 let mut script = generator.generate()?;
967 TerminalReporter::print_success("k6 script generated");
968
969 let has_advanced_features = self.data_file.is_some()
971 || self.error_rate.is_some()
972 || self.security_test
973 || self.parallel_create.is_some()
974 || self.wafbench_dir.is_some();
975
976 if has_advanced_features {
978 script = self.generate_enhanced_script(&script)?;
979 }
980
981 if mock_config.is_mock_server {
983 let setup_code = MockIntegrationGenerator::generate_setup(&mock_config);
984 let teardown_code = MockIntegrationGenerator::generate_teardown(&mock_config);
985 let helper_code = MockIntegrationGenerator::generate_vu_id_helper();
986
987 if let Some(import_end) = script.find("export const options") {
989 script.insert_str(
990 import_end,
991 &format!(
992 "\n// === Mock Server Integration ===\n{}\n{}\n{}\n",
993 helper_code, setup_code, teardown_code
994 ),
995 );
996 }
997 }
998
999 TerminalReporter::print_progress("Validating k6 script...");
1001 let validation_errors = K6ScriptGenerator::validate_script(&script);
1002 if !validation_errors.is_empty() {
1003 TerminalReporter::print_error("Script validation failed");
1004 for error in &validation_errors {
1005 eprintln!(" {}", error);
1006 }
1007 return Err(BenchError::Other(format!(
1008 "Generated k6 script has {} validation error(s). Please check the output above.",
1009 validation_errors.len()
1010 )));
1011 }
1012 TerminalReporter::print_success("Script validation passed");
1013
1014 let script_path = if let Some(output) = &self.script_output {
1016 output.clone()
1017 } else {
1018 self.output.join("k6-script.js")
1019 };
1020
1021 if let Some(parent) = script_path.parent() {
1022 std::fs::create_dir_all(parent)?;
1023 }
1024 std::fs::write(&script_path, &script)?;
1025 TerminalReporter::print_success(&format!("Script written to: {}", script_path.display()));
1026
1027 if self.generate_only {
1029 println!("\nScript generated successfully. Run it with:");
1030 println!(" k6 run {}", script_path.display());
1031 return Ok(());
1032 }
1033
1034 TerminalReporter::print_progress("Executing load test...");
1036 let executor = K6Executor::new()?
1040 .with_local_ips(self.source_ips.join(","))
1041 .with_dns_policy(self.dns_policy.clone().unwrap_or_default())
1042 .with_discard_response_bodies(self.discard_response_bodies);
1043
1044 std::fs::create_dir_all(&self.output)?;
1045
1046 let results = executor.execute(&script_path, Some(&self.output), self.verbose).await?;
1047
1048 let duration_secs = Self::parse_duration(&self.duration)?;
1050 TerminalReporter::print_summary_full(
1051 &results,
1052 duration_secs,
1053 self.no_keep_alive,
1054 Some(num_ops),
1055 );
1056
1057 println!("\nResults saved to: {}", self.output.display());
1058
1059 Ok(())
1060 }
1061
1062 async fn execute_multi_target(&self, targets_file: &Path) -> Result<()> {
1064 TerminalReporter::print_progress("Parsing targets file...");
1065 let targets = parse_targets_file(targets_file)?;
1066 let num_targets = targets.len();
1067 TerminalReporter::print_success(&format!("Loaded {} targets", num_targets));
1068
1069 if targets.is_empty() {
1070 return Err(BenchError::Other("No targets found in file".to_string()));
1071 }
1072
1073 let max_concurrency = self.max_concurrency.unwrap_or(10) as usize;
1075 let max_concurrency = max_concurrency.min(num_targets); TerminalReporter::print_header(
1079 &self.get_spec_display_name(),
1080 &format!("{} targets", num_targets),
1081 0,
1082 &self.scenario,
1083 Self::parse_duration(&self.duration)?,
1084 );
1085
1086 let executor = ParallelExecutor::new(
1088 BenchCommand {
1089 spec: self.spec.clone(),
1091 spec_dir: self.spec_dir.clone(),
1092 merge_conflicts: self.merge_conflicts.clone(),
1093 spec_mode: self.spec_mode.clone(),
1094 dependency_config: self.dependency_config.clone(),
1095 target: self.target.clone(), base_path: self.base_path.clone(),
1097 duration: self.duration.clone(),
1098 vus: self.vus,
1099 target_rps: self.target_rps,
1100 no_keep_alive: self.no_keep_alive,
1101 scenario: self.scenario.clone(),
1102 operations: self.operations.clone(),
1103 exclude_operations: self.exclude_operations.clone(),
1104 auth: self.auth.clone(),
1105 headers: self.headers.clone(),
1106 output: self.output.clone(),
1107 generate_only: self.generate_only,
1108 script_output: self.script_output.clone(),
1109 threshold_percentile: self.threshold_percentile.clone(),
1110 threshold_ms: self.threshold_ms,
1111 max_error_rate: self.max_error_rate,
1112 abort_on_error: self.abort_on_error,
1113 abort_on_error_rate: self.abort_on_error_rate,
1114 verbose: self.verbose,
1115 skip_tls_verify: self.skip_tls_verify,
1116 chunked_request_bodies: self.chunked_request_bodies,
1117 targets_file: None,
1118 max_concurrency: None,
1119 results_format: self.results_format.clone(),
1120 params_file: self.params_file.clone(),
1121 crud_flow: self.crud_flow,
1122 flow_config: self.flow_config.clone(),
1123 extract_fields: self.extract_fields.clone(),
1124 parallel_create: self.parallel_create,
1125 data_file: self.data_file.clone(),
1126 data_distribution: self.data_distribution.clone(),
1127 data_mappings: self.data_mappings.clone(),
1128 per_uri_control: self.per_uri_control,
1129 error_rate: self.error_rate,
1130 error_types: self.error_types.clone(),
1131 security_test: self.security_test,
1132 security_payloads: self.security_payloads.clone(),
1133 security_categories: self.security_categories.clone(),
1134 security_target_fields: self.security_target_fields.clone(),
1135 wafbench_dir: self.wafbench_dir.clone(),
1136 wafbench_cycle_all: self.wafbench_cycle_all,
1137 wafbench_verbatim: self.wafbench_verbatim,
1138 owasp_api_top10: self.owasp_api_top10,
1139 owasp_categories: self.owasp_categories.clone(),
1140 owasp_auth_header: self.owasp_auth_header.clone(),
1141 owasp_auth_token: self.owasp_auth_token.clone(),
1142 owasp_admin_paths: self.owasp_admin_paths.clone(),
1143 owasp_id_fields: self.owasp_id_fields.clone(),
1144 owasp_report: self.owasp_report.clone(),
1145 owasp_report_format: self.owasp_report_format.clone(),
1146 owasp_iterations: self.owasp_iterations,
1147 conformance: false,
1148 conformance_api_key: self.conformance_api_key.clone(),
1164 conformance_basic_auth: self.conformance_basic_auth.clone(),
1165 conformance_report: PathBuf::from("conformance-report.json"),
1166 conformance_categories: None,
1167 conformance_report_format: "json".to_string(),
1168 conformance_headers: self.conformance_headers.clone(),
1172 conformance_all_operations: false,
1173 conformance_custom: None,
1174 conformance_delay_ms: 0,
1175 use_k6: false,
1176 conformance_custom_filter: None,
1177 export_requests: false,
1178 validate_requests: false,
1179 conformance_self_test: false,
1180 conformance_self_test_capture: false,
1181 conformance_self_test_iterations: 1,
1182 conformance_self_test_duration: None,
1183 validate_response_schemas: false,
1184 source_ips: self.source_ips.clone(),
1189 geo_source_ips: self.geo_source_ips.clone(),
1190 geo_source_headers: self.geo_source_headers.clone(),
1191 report_missed_cap: None,
1192 discard_response_bodies: self.discard_response_bodies,
1196 dns_policy: self.dns_policy.clone(),
1199 },
1200 targets,
1201 max_concurrency,
1202 );
1203
1204 let start_time = std::time::Instant::now();
1206 let aggregated_results = executor.execute_all().await?;
1207 let elapsed = start_time.elapsed();
1208
1209 self.report_multi_target_results(&aggregated_results, elapsed)?;
1211
1212 Ok(())
1213 }
1214
1215 fn report_multi_target_results(
1217 &self,
1218 results: &AggregatedResults,
1219 elapsed: std::time::Duration,
1220 ) -> Result<()> {
1221 TerminalReporter::print_multi_target_summary(results);
1223
1224 let total_secs = elapsed.as_secs();
1226 let hours = total_secs / 3600;
1227 let minutes = (total_secs % 3600) / 60;
1228 let seconds = total_secs % 60;
1229 if hours > 0 {
1230 println!("\n Total Elapsed Time: {}h {}m {}s", hours, minutes, seconds);
1231 } else if minutes > 0 {
1232 println!("\n Total Elapsed Time: {}m {}s", minutes, seconds);
1233 } else {
1234 println!("\n Total Elapsed Time: {}s", seconds);
1235 }
1236
1237 if self.results_format == "aggregated" || self.results_format == "both" {
1239 let summary_path = self.output.join("aggregated_summary.json");
1240 let summary_json = serde_json::json!({
1241 "total_elapsed_seconds": elapsed.as_secs(),
1242 "total_targets": results.total_targets,
1243 "successful_targets": results.successful_targets,
1244 "failed_targets": results.failed_targets,
1245 "aggregated_metrics": {
1246 "total_requests": results.aggregated_metrics.total_requests,
1247 "total_failed_requests": results.aggregated_metrics.total_failed_requests,
1248 "avg_duration_ms": results.aggregated_metrics.avg_duration_ms,
1249 "p95_duration_ms": results.aggregated_metrics.p95_duration_ms,
1250 "p99_duration_ms": results.aggregated_metrics.p99_duration_ms,
1251 "error_rate": results.aggregated_metrics.error_rate,
1252 "total_rps": results.aggregated_metrics.total_rps,
1253 "avg_rps": results.aggregated_metrics.avg_rps,
1254 "total_vus_max": results.aggregated_metrics.total_vus_max,
1255 },
1256 "target_results": results.target_results.iter().map(|r| {
1257 serde_json::json!({
1258 "target_url": r.target_url,
1259 "target_index": r.target_index,
1260 "success": r.success,
1261 "error": r.error,
1262 "total_requests": r.results.total_requests,
1263 "failed_requests": r.results.failed_requests,
1264 "avg_duration_ms": r.results.avg_duration_ms,
1265 "min_duration_ms": r.results.min_duration_ms,
1266 "med_duration_ms": r.results.med_duration_ms,
1267 "p90_duration_ms": r.results.p90_duration_ms,
1268 "p95_duration_ms": r.results.p95_duration_ms,
1269 "p99_duration_ms": r.results.p99_duration_ms,
1270 "max_duration_ms": r.results.max_duration_ms,
1271 "rps": r.results.rps,
1272 "vus_max": r.results.vus_max,
1273 "output_dir": r.output_dir.to_string_lossy(),
1274 })
1275 }).collect::<Vec<_>>(),
1276 });
1277
1278 std::fs::write(&summary_path, serde_json::to_string_pretty(&summary_json)?)?;
1279 TerminalReporter::print_success(&format!(
1280 "Aggregated summary saved to: {}",
1281 summary_path.display()
1282 ));
1283 }
1284
1285 let csv_path = self.output.join("all_targets.csv");
1287 let mut csv = String::from(
1288 "target_url,success,requests,failed,rps,vus,min_ms,avg_ms,med_ms,p90_ms,p95_ms,p99_ms,max_ms,error\n",
1289 );
1290 for r in &results.target_results {
1291 csv.push_str(&format!(
1292 "{},{},{},{},{:.1},{},{:.1},{:.1},{:.1},{:.1},{:.1},{:.1},{:.1},{}\n",
1293 r.target_url,
1294 r.success,
1295 r.results.total_requests,
1296 r.results.failed_requests,
1297 r.results.rps,
1298 r.results.vus_max,
1299 r.results.min_duration_ms,
1300 r.results.avg_duration_ms,
1301 r.results.med_duration_ms,
1302 r.results.p90_duration_ms,
1303 r.results.p95_duration_ms,
1304 r.results.p99_duration_ms,
1305 r.results.max_duration_ms,
1306 r.error.as_deref().unwrap_or(""),
1307 ));
1308 }
1309 let _ = std::fs::write(&csv_path, &csv);
1310
1311 println!("\nResults saved to: {}", self.output.display());
1312 println!(" - Per-target results: {}", self.output.join("target_*").display());
1313 println!(" - All targets CSV: {}", csv_path.display());
1314 if self.results_format == "aggregated" || self.results_format == "both" {
1315 println!(
1316 " - Aggregated summary: {}",
1317 self.output.join("aggregated_summary.json").display()
1318 );
1319 }
1320
1321 Ok(())
1322 }
1323
1324 pub fn parse_duration(duration: &str) -> Result<u64> {
1326 let duration = duration.trim();
1327
1328 if let Some(secs) = duration.strip_suffix('s') {
1329 secs.parse::<u64>()
1330 .map_err(|_| BenchError::Other(format!("Invalid duration: {}", duration)))
1331 } else if let Some(mins) = duration.strip_suffix('m') {
1332 mins.parse::<u64>()
1333 .map(|m| m * 60)
1334 .map_err(|_| BenchError::Other(format!("Invalid duration: {}", duration)))
1335 } else if let Some(hours) = duration.strip_suffix('h') {
1336 hours
1337 .parse::<u64>()
1338 .map(|h| h * 3600)
1339 .map_err(|_| BenchError::Other(format!("Invalid duration: {}", duration)))
1340 } else {
1341 duration
1343 .parse::<u64>()
1344 .map_err(|_| BenchError::Other(format!("Invalid duration: {}", duration)))
1345 }
1346 }
1347
1348 pub(crate) fn load_verbatim_templates(
1355 &self,
1356 ) -> Result<Vec<crate::request_gen::RequestTemplate>> {
1357 let Some(pattern) = self.wafbench_dir.as_ref() else {
1358 return Err(BenchError::Other(
1359 "--wafbench-verbatim requires --wafbench-dir pointing at your traffic file(s)"
1360 .to_string(),
1361 ));
1362 };
1363
1364 let mut loader = WafBenchLoader::new();
1365 loader.load_from_pattern(pattern)?;
1366
1367 Ok(crate::wafbench::traffic_cases_to_templates(loader.test_cases()))
1368 }
1369
1370 pub fn parse_headers(&self) -> Result<HashMap<String, String>> {
1372 let mut headers = parse_header_string(&self.headers)?;
1373
1374 let already_has = |hs: &HashMap<String, String>, name: &str| -> bool {
1385 hs.keys().any(|k| k.eq_ignore_ascii_case(name))
1386 };
1387
1388 if !already_has(&headers, "Authorization") {
1389 if let Some(b) = self.conformance_basic_auth.as_ref().filter(|s| !s.is_empty()) {
1390 use base64::Engine as _;
1391 let encoded = base64::engine::general_purpose::STANDARD.encode(b.as_bytes());
1392 headers.insert("Authorization".to_string(), format!("Basic {}", encoded));
1393 }
1394 }
1395
1396 for line in &self.conformance_headers {
1402 let Some((name, value)) = line.split_once(':') else {
1403 continue;
1404 };
1405 let name = name.trim();
1406 let value = value.trim();
1407 if name.is_empty() || already_has(&headers, name) {
1408 continue;
1409 }
1410 headers.insert(name.to_string(), value.to_string());
1411 }
1412
1413 if !self.conformance && self.conformance_api_key.is_some() {
1419 TerminalReporter::print_warning(
1420 "--conformance-api-key only fires under --conformance. For plain bench use --header 'X-API-Key: ...'.",
1421 );
1422 }
1423
1424 Ok(headers)
1425 }
1426
1427 fn parse_extracted_values(output_dir: &Path) -> Result<ExtractedValues> {
1428 let extracted_path = output_dir.join("extracted_values.json");
1429 if !extracted_path.exists() {
1430 return Ok(ExtractedValues::new());
1431 }
1432
1433 let content = std::fs::read_to_string(&extracted_path)
1434 .map_err(|e| BenchError::ResultsParseError(e.to_string()))?;
1435 let parsed: serde_json::Value = serde_json::from_str(&content)
1436 .map_err(|e| BenchError::ResultsParseError(e.to_string()))?;
1437
1438 let mut extracted = ExtractedValues::new();
1439 if let Some(values) = parsed.as_object() {
1440 for (key, value) in values {
1441 extracted.set(key.clone(), value.clone());
1442 }
1443 }
1444
1445 Ok(extracted)
1446 }
1447
1448 fn resolve_base_path(&self, parser: &SpecParser) -> Option<String> {
1457 if let Some(cli_base_path) = &self.base_path {
1459 if cli_base_path.is_empty() {
1460 return None;
1462 }
1463 return Some(cli_base_path.clone());
1464 }
1465
1466 parser.get_base_path()
1468 }
1469
1470 async fn build_mock_config(&self) -> MockIntegrationConfig {
1472 if MockServerDetector::looks_like_mock_server(&self.target) {
1474 if let Ok(info) = MockServerDetector::detect(&self.target).await {
1476 if info.is_mockforge {
1477 TerminalReporter::print_success(&format!(
1478 "Detected MockForge server (version: {})",
1479 info.version.as_deref().unwrap_or("unknown")
1480 ));
1481 return MockIntegrationConfig::mock_server();
1482 }
1483 }
1484 }
1485 MockIntegrationConfig::real_api()
1486 }
1487
1488 fn build_crud_flow_config(&self) -> Option<CrudFlowConfig> {
1490 if !self.crud_flow {
1491 return None;
1492 }
1493
1494 if let Some(config_path) = &self.flow_config {
1496 match CrudFlowConfig::from_file(config_path) {
1497 Ok(config) => return Some(config),
1498 Err(e) => {
1499 TerminalReporter::print_warning(&format!(
1500 "Failed to load flow config: {}. Using auto-detection.",
1501 e
1502 ));
1503 }
1504 }
1505 }
1506
1507 let extract_fields = self
1509 .extract_fields
1510 .as_ref()
1511 .map(|f| f.split(',').map(|s| s.trim().to_string()).collect())
1512 .unwrap_or_else(|| vec!["id".to_string(), "uuid".to_string()]);
1513
1514 Some(CrudFlowConfig {
1515 flows: Vec::new(), default_extract_fields: extract_fields,
1517 })
1518 }
1519
1520 fn build_data_driven_config(&self) -> Option<DataDrivenConfig> {
1522 let data_file = self.data_file.as_ref()?;
1523
1524 let distribution = DataDistribution::from_str(&self.data_distribution)
1525 .unwrap_or(DataDistribution::UniquePerVu);
1526
1527 let mappings = self
1528 .data_mappings
1529 .as_ref()
1530 .map(|m| DataMapping::parse_mappings(m).unwrap_or_default())
1531 .unwrap_or_default();
1532
1533 Some(DataDrivenConfig {
1534 file_path: data_file.to_string_lossy().to_string(),
1535 distribution,
1536 mappings,
1537 csv_has_header: true,
1538 per_uri_control: self.per_uri_control,
1539 per_uri_columns: crate::data_driven::PerUriColumns::default(),
1540 })
1541 }
1542
1543 fn build_invalid_data_config(&self) -> Option<InvalidDataConfig> {
1545 let error_rate = self.error_rate?;
1546
1547 let error_types = self
1548 .error_types
1549 .as_ref()
1550 .map(|types| InvalidDataConfig::parse_error_types(types).unwrap_or_default())
1551 .unwrap_or_default();
1552
1553 Some(InvalidDataConfig {
1554 error_rate,
1555 error_types,
1556 target_fields: Vec::new(),
1557 })
1558 }
1559
1560 fn build_security_config(&self) -> Option<SecurityTestConfig> {
1562 if !self.security_test {
1563 return None;
1564 }
1565
1566 let categories = self
1567 .security_categories
1568 .as_ref()
1569 .map(|cats| SecurityTestConfig::parse_categories(cats).unwrap_or_default())
1570 .unwrap_or_else(|| {
1571 let mut default = HashSet::new();
1572 default.insert(SecurityCategory::SqlInjection);
1573 default.insert(SecurityCategory::Xss);
1574 default
1575 });
1576
1577 let target_fields = self
1578 .security_target_fields
1579 .as_ref()
1580 .map(|fields| fields.split(',').map(|f| f.trim().to_string()).collect())
1581 .unwrap_or_default();
1582
1583 let custom_payloads_file =
1584 self.security_payloads.as_ref().map(|p| p.to_string_lossy().to_string());
1585
1586 Some(SecurityTestConfig {
1587 enabled: true,
1588 categories,
1589 target_fields,
1590 custom_payloads_file,
1591 include_high_risk: false,
1592 })
1593 }
1594
1595 fn build_parallel_config(&self) -> Option<ParallelConfig> {
1597 let count = self.parallel_create?;
1598
1599 Some(ParallelConfig::new(count))
1600 }
1601
1602 fn load_wafbench_payloads(&self) -> Vec<SecurityPayload> {
1604 let Some(ref wafbench_dir) = self.wafbench_dir else {
1605 return Vec::new();
1606 };
1607
1608 let mut loader = WafBenchLoader::new();
1609
1610 if let Err(e) = loader.load_from_pattern(wafbench_dir) {
1611 TerminalReporter::print_warning(&format!("Failed to load WAFBench tests: {}", e));
1612 return Vec::new();
1613 }
1614
1615 let stats = loader.stats();
1616
1617 if stats.files_processed == 0 {
1618 TerminalReporter::print_warning(&format!(
1619 "No WAFBench YAML files found matching '{}'",
1620 wafbench_dir
1621 ));
1622 if !stats.parse_errors.is_empty() {
1624 TerminalReporter::print_warning("Some files were found but failed to parse:");
1625 for error in &stats.parse_errors {
1626 TerminalReporter::print_warning(&format!(" - {}", error));
1627 }
1628 }
1629 return Vec::new();
1630 }
1631
1632 TerminalReporter::print_progress(&format!(
1633 "Loaded {} WAFBench files, {} test cases, {} payloads",
1634 stats.files_processed, stats.test_cases_loaded, stats.payloads_extracted
1635 ));
1636
1637 for (category, count) in &stats.by_category {
1639 TerminalReporter::print_progress(&format!(" - {}: {} tests", category, count));
1640 }
1641
1642 for error in &stats.parse_errors {
1644 TerminalReporter::print_warning(&format!(" Parse error: {}", error));
1645 }
1646
1647 loader.to_security_payloads()
1648 }
1649
1650 pub(crate) fn generate_enhanced_script(&self, base_script: &str) -> Result<String> {
1652 let mut enhanced_script = base_script.to_string();
1653 let mut additional_code = String::new();
1654
1655 if let Some(config) = self.build_data_driven_config() {
1657 TerminalReporter::print_progress("Adding data-driven testing support...");
1658 additional_code.push_str(&DataDrivenGenerator::generate_setup(&config));
1659 additional_code.push('\n');
1660 TerminalReporter::print_success("Data-driven testing enabled");
1661 }
1662
1663 if let Some(config) = self.build_invalid_data_config() {
1665 TerminalReporter::print_progress("Adding invalid data testing support...");
1666 additional_code.push_str(&InvalidDataGenerator::generate_invalidation_logic());
1667 additional_code.push('\n');
1668 additional_code
1669 .push_str(&InvalidDataGenerator::generate_should_invalidate(config.error_rate));
1670 additional_code.push('\n');
1671 additional_code
1672 .push_str(&InvalidDataGenerator::generate_type_selection(&config.error_types));
1673 additional_code.push('\n');
1674 TerminalReporter::print_success(&format!(
1675 "Invalid data testing enabled ({}% error rate)",
1676 (self.error_rate.unwrap_or(0.0) * 100.0) as u32
1677 ));
1678 }
1679
1680 let verbatim = self.wafbench_verbatim;
1687 if verbatim && self.security_test {
1688 TerminalReporter::print_warning(
1689 "--security-test is ignored under --wafbench-verbatim: verbatim mode sends your \
1690 traffic cases exactly as written and will not append attack payloads to them. \
1691 Drop --wafbench-verbatim if you want payload injection.",
1692 );
1693 }
1694 let security_config = if verbatim {
1695 None
1696 } else {
1697 self.build_security_config()
1698 };
1699 let wafbench_payloads = if verbatim {
1700 Vec::new()
1701 } else {
1702 self.load_wafbench_payloads()
1703 };
1704 let security_requested =
1705 !verbatim && (security_config.is_some() || self.wafbench_dir.is_some());
1706
1707 if security_config.is_some() || !wafbench_payloads.is_empty() {
1708 TerminalReporter::print_progress("Adding security testing support...");
1709
1710 let mut payload_list: Vec<SecurityPayload> = Vec::new();
1712
1713 if let Some(ref config) = security_config {
1714 payload_list.extend(SecurityPayloads::get_payloads(config));
1715 }
1716
1717 if !wafbench_payloads.is_empty() {
1719 TerminalReporter::print_progress(&format!(
1720 "Loading {} WAFBench attack patterns...",
1721 wafbench_payloads.len()
1722 ));
1723 payload_list.extend(wafbench_payloads);
1724 }
1725
1726 let target_fields =
1727 security_config.as_ref().map(|c| c.target_fields.clone()).unwrap_or_default();
1728
1729 additional_code.push_str(&SecurityTestGenerator::generate_payload_selection(
1730 &payload_list,
1731 self.wafbench_cycle_all,
1732 ));
1733 additional_code.push('\n');
1734 additional_code
1735 .push_str(&SecurityTestGenerator::generate_apply_payload(&target_fields));
1736 additional_code.push('\n');
1737 additional_code.push_str(&SecurityTestGenerator::generate_security_checks());
1738 additional_code.push('\n');
1739
1740 let mode = if self.wafbench_cycle_all {
1741 "cycle-all"
1742 } else {
1743 "random"
1744 };
1745 TerminalReporter::print_success(&format!(
1746 "Security testing enabled ({} payloads, {} mode)",
1747 payload_list.len(),
1748 mode
1749 ));
1750 } else if security_requested {
1751 TerminalReporter::print_warning(
1755 "Security testing was requested but no payloads were loaded. \
1756 Ensure --wafbench-dir points to valid CRS YAML files or add --security-test.",
1757 );
1758 additional_code
1759 .push_str(&SecurityTestGenerator::generate_payload_selection(&[], false));
1760 additional_code.push('\n');
1761 additional_code.push_str(&SecurityTestGenerator::generate_apply_payload(&[]));
1762 additional_code.push('\n');
1763 }
1764
1765 if let Some(config) = self.build_parallel_config() {
1767 TerminalReporter::print_progress("Adding parallel execution support...");
1768 additional_code.push_str(&ParallelRequestGenerator::generate_batch_helper(&config));
1769 additional_code.push('\n');
1770 TerminalReporter::print_success(&format!(
1771 "Parallel execution enabled (count: {})",
1772 config.count
1773 ));
1774 }
1775
1776 if !additional_code.is_empty() {
1778 if let Some(import_end) = enhanced_script.find("export const options") {
1780 enhanced_script.insert_str(
1781 import_end,
1782 &format!("\n// === Advanced Testing Features ===\n{}\n", additional_code),
1783 );
1784 }
1785 }
1786
1787 Ok(enhanced_script)
1788 }
1789
1790 async fn execute_sequential_specs(&self) -> Result<()> {
1792 TerminalReporter::print_progress("Sequential spec mode: Loading specs individually...");
1793
1794 let mut all_specs: Vec<(PathBuf, OpenApiSpec)> = Vec::new();
1796
1797 if !self.spec.is_empty() {
1798 let specs = load_specs_from_files(self.spec.clone())
1799 .await
1800 .map_err(|e| BenchError::Other(format!("Failed to load spec files: {}", e)))?;
1801 all_specs.extend(specs);
1802 }
1803
1804 if let Some(spec_dir) = &self.spec_dir {
1805 let dir_specs = load_specs_from_directory(spec_dir).await.map_err(|e| {
1806 BenchError::Other(format!("Failed to load specs from directory: {}", e))
1807 })?;
1808 all_specs.extend(dir_specs);
1809 }
1810
1811 if all_specs.is_empty() {
1812 return Err(BenchError::Other(
1813 "No spec files found for sequential execution".to_string(),
1814 ));
1815 }
1816
1817 TerminalReporter::print_success(&format!("Loaded {} spec(s)", all_specs.len()));
1818
1819 let execution_order = if let Some(config_path) = &self.dependency_config {
1821 TerminalReporter::print_progress("Loading dependency configuration...");
1822 let config = SpecDependencyConfig::from_file(config_path)?;
1823
1824 if !config.disable_auto_detect && config.execution_order.is_empty() {
1825 self.detect_and_sort_specs(&all_specs)?
1827 } else {
1828 config.execution_order.iter().flat_map(|g| g.specs.clone()).collect()
1830 }
1831 } else {
1832 self.detect_and_sort_specs(&all_specs)?
1834 };
1835
1836 TerminalReporter::print_success(&format!(
1837 "Execution order: {}",
1838 execution_order
1839 .iter()
1840 .map(|p| p.file_name().unwrap_or_default().to_string_lossy().to_string())
1841 .collect::<Vec<_>>()
1842 .join(" → ")
1843 ));
1844
1845 let mut extracted_values = ExtractedValues::new();
1847 let total_specs = execution_order.len();
1848
1849 for (index, spec_path) in execution_order.iter().enumerate() {
1850 let spec_name = spec_path.file_name().unwrap_or_default().to_string_lossy().to_string();
1851
1852 TerminalReporter::print_progress(&format!(
1853 "[{}/{}] Executing spec: {}",
1854 index + 1,
1855 total_specs,
1856 spec_name
1857 ));
1858
1859 let spec = all_specs
1861 .iter()
1862 .find(|(p, _)| {
1863 p == spec_path
1864 || p.file_name() == spec_path.file_name()
1865 || p.file_name() == Some(spec_path.as_os_str())
1866 })
1867 .map(|(_, s)| s.clone())
1868 .ok_or_else(|| {
1869 BenchError::Other(format!("Spec not found: {}", spec_path.display()))
1870 })?;
1871
1872 let new_values = self.execute_single_spec(&spec, &spec_name, &extracted_values).await?;
1874
1875 extracted_values.merge(&new_values);
1877
1878 TerminalReporter::print_success(&format!(
1879 "[{}/{}] Completed: {} (extracted {} values)",
1880 index + 1,
1881 total_specs,
1882 spec_name,
1883 new_values.values.len()
1884 ));
1885 }
1886
1887 TerminalReporter::print_success(&format!(
1888 "Sequential execution complete: {} specs executed",
1889 total_specs
1890 ));
1891
1892 Ok(())
1893 }
1894
1895 fn detect_and_sort_specs(&self, specs: &[(PathBuf, OpenApiSpec)]) -> Result<Vec<PathBuf>> {
1897 TerminalReporter::print_progress("Auto-detecting spec dependencies...");
1898
1899 let mut detector = DependencyDetector::new();
1900 let dependencies = detector.detect_dependencies(specs);
1901
1902 if dependencies.is_empty() {
1903 TerminalReporter::print_progress("No dependencies detected, using file order");
1904 return Ok(specs.iter().map(|(p, _)| p.clone()).collect());
1905 }
1906
1907 TerminalReporter::print_progress(&format!(
1908 "Detected {} cross-spec dependencies",
1909 dependencies.len()
1910 ));
1911
1912 for dep in &dependencies {
1913 TerminalReporter::print_progress(&format!(
1914 " {} → {} (via field '{}')",
1915 dep.dependency_spec.file_name().unwrap_or_default().to_string_lossy(),
1916 dep.dependent_spec.file_name().unwrap_or_default().to_string_lossy(),
1917 dep.field_name
1918 ));
1919 }
1920
1921 topological_sort(specs, &dependencies)
1922 }
1923
1924 async fn execute_single_spec(
1926 &self,
1927 spec: &OpenApiSpec,
1928 spec_name: &str,
1929 _external_values: &ExtractedValues,
1930 ) -> Result<ExtractedValues> {
1931 let parser = SpecParser::from_spec(spec.clone());
1932
1933 if self.crud_flow {
1935 self.execute_crud_flow_with_extraction(&parser, spec_name).await
1937 } else {
1938 self.execute_standard_spec(&parser, spec_name).await?;
1940 Ok(ExtractedValues::new())
1941 }
1942 }
1943
1944 async fn execute_crud_flow_with_extraction(
1946 &self,
1947 parser: &SpecParser,
1948 spec_name: &str,
1949 ) -> Result<ExtractedValues> {
1950 let operations = parser.get_operations();
1951 let flows = CrudFlowDetector::detect_flows(&operations);
1952
1953 if flows.is_empty() {
1954 TerminalReporter::print_warning(&format!("No CRUD flows detected in {}", spec_name));
1955 return Ok(ExtractedValues::new());
1956 }
1957
1958 TerminalReporter::print_progress(&format!(
1959 " {} CRUD flow(s) in {}",
1960 flows.len(),
1961 spec_name
1962 ));
1963
1964 let mut handlebars = handlebars::Handlebars::new();
1966 handlebars.register_helper(
1968 "json",
1969 Box::new(
1970 |h: &handlebars::Helper,
1971 _: &handlebars::Handlebars,
1972 _: &handlebars::Context,
1973 _: &mut handlebars::RenderContext,
1974 out: &mut dyn handlebars::Output|
1975 -> handlebars::HelperResult {
1976 let param = h.param(0).map(|v| v.value()).unwrap_or(&serde_json::Value::Null);
1977 out.write(&serde_json::to_string(param).unwrap_or_else(|_| "[]".to_string()))?;
1978 Ok(())
1979 },
1980 ),
1981 );
1982 let template = include_str!("templates/k6_crud_flow.hbs");
1983 let output_dir = self.output.join(format!("{}_results", spec_name.replace('.', "_")));
1984
1985 let custom_headers = self.parse_headers()?;
1986 let config = self.build_crud_flow_config().unwrap_or_default();
1987
1988 let param_overrides = if let Some(params_file) = &self.params_file {
1990 let overrides = ParameterOverrides::from_file(params_file)?;
1991 Some(overrides)
1992 } else {
1993 None
1994 };
1995
1996 let duration_secs = Self::parse_duration(&self.duration)?;
1998 let scenario =
1999 LoadScenario::from_str(&self.scenario).map_err(BenchError::InvalidScenario)?;
2000 let stages = scenario.generate_stages(duration_secs, self.vus);
2001
2002 let api_base_path = self.resolve_base_path(parser);
2004
2005 let mut all_headers = custom_headers.clone();
2007 if let Some(auth) = &self.auth {
2008 all_headers.insert("Authorization".to_string(), auth.clone());
2009 }
2010 let headers_json = serde_json::to_string(&all_headers).unwrap_or_else(|_| "{}".to_string());
2011
2012 let mut all_placeholders: HashSet<DynamicPlaceholder> = HashSet::new();
2014
2015 let flows_data: Vec<serde_json::Value> = flows.iter().map(|f| {
2016 let sanitized_name = K6ScriptGenerator::sanitize_k6_metric_name(&f.name);
2020 serde_json::json!({
2021 "name": sanitized_name.clone(),
2022 "display_name": f.name,
2023 "base_path": f.base_path,
2024 "steps": f.steps.iter().enumerate().map(|(idx, s)| {
2025 let parts: Vec<&str> = s.operation.splitn(2, ' ').collect();
2027 let method_raw = if !parts.is_empty() {
2028 parts[0].to_uppercase()
2029 } else {
2030 "GET".to_string()
2031 };
2032 let method = if !parts.is_empty() {
2033 let m = parts[0].to_lowercase();
2034 if m == "delete" { "del".to_string() } else { m }
2036 } else {
2037 "get".to_string()
2038 };
2039 let raw_path = if parts.len() >= 2 { parts[1] } else { "/" };
2040 let path = if let Some(ref bp) = api_base_path {
2042 format!("{}{}", bp, raw_path)
2043 } else {
2044 raw_path.to_string()
2045 };
2046 let is_get_or_head = method == "get" || method == "head";
2047 let has_body = matches!(method.as_str(), "post" | "put" | "patch");
2049
2050 let body_value = if has_body {
2052 param_overrides.as_ref()
2053 .map(|po| po.get_for_operation(None, &method_raw, raw_path))
2054 .and_then(|oo| oo.body)
2055 .unwrap_or_else(|| serde_json::json!({}))
2056 } else {
2057 serde_json::json!({})
2058 };
2059
2060 let processed_body = DynamicParamProcessor::process_json_body(&body_value);
2062
2063 let body_has_extracted_placeholders = processed_body.value.contains("${extracted.");
2065 let body_is_dynamic = processed_body.is_dynamic || body_has_extracted_placeholders;
2066
2067 serde_json::json!({
2068 "operation": s.operation,
2069 "method": method,
2070 "path": path,
2071 "extract": s.extract,
2072 "use_values": s.use_values,
2073 "use_body": s.use_body,
2074 "merge_body": if s.merge_body.is_empty() { None } else { Some(&s.merge_body) },
2075 "inject_attacks": s.inject_attacks,
2076 "attack_types": s.attack_types,
2077 "description": s.description,
2078 "display_name": s.description.clone().unwrap_or_else(|| format!("Step {}", idx)),
2079 "is_get_or_head": is_get_or_head,
2080 "has_body": has_body,
2081 "body": processed_body.value,
2082 "body_is_dynamic": body_is_dynamic,
2083 "_placeholders": processed_body.placeholders.iter().map(|p| format!("{:?}", p)).collect::<Vec<_>>(),
2084 })
2085 }).collect::<Vec<_>>(),
2086 })
2087 }).collect();
2088
2089 for flow_data in &flows_data {
2091 if let Some(steps) = flow_data.get("steps").and_then(|s| s.as_array()) {
2092 for step in steps {
2093 if let Some(placeholders_arr) =
2094 step.get("_placeholders").and_then(|p| p.as_array())
2095 {
2096 for p_str in placeholders_arr {
2097 if let Some(p_name) = p_str.as_str() {
2098 match p_name {
2099 "VU" => {
2100 all_placeholders.insert(DynamicPlaceholder::VU);
2101 }
2102 "Iteration" => {
2103 all_placeholders.insert(DynamicPlaceholder::Iteration);
2104 }
2105 "Timestamp" => {
2106 all_placeholders.insert(DynamicPlaceholder::Timestamp);
2107 }
2108 "UUID" => {
2109 all_placeholders.insert(DynamicPlaceholder::UUID);
2110 }
2111 "Random" => {
2112 all_placeholders.insert(DynamicPlaceholder::Random);
2113 }
2114 "Counter" => {
2115 all_placeholders.insert(DynamicPlaceholder::Counter);
2116 }
2117 "Date" => {
2118 all_placeholders.insert(DynamicPlaceholder::Date);
2119 }
2120 "VuIter" => {
2121 all_placeholders.insert(DynamicPlaceholder::VuIter);
2122 }
2123 _ => {}
2124 }
2125 }
2126 }
2127 }
2128 }
2129 }
2130 }
2131
2132 let required_imports = DynamicParamProcessor::get_required_imports(&all_placeholders);
2134 let required_globals = DynamicParamProcessor::get_required_globals(&all_placeholders);
2135
2136 let security_testing_enabled = self.security_testing_enabled();
2138
2139 let data = serde_json::json!({
2140 "base_url": self.target,
2141 "flows": flows_data,
2142 "extract_fields": config.default_extract_fields,
2143 "duration_secs": duration_secs,
2144 "max_vus": self.vus,
2145 "auth_header": self.auth,
2146 "custom_headers": custom_headers,
2147 "skip_tls_verify": self.skip_tls_verify,
2148 "stages": stages.iter().map(|s| serde_json::json!({
2150 "duration": s.duration,
2151 "target": s.target,
2152 })).collect::<Vec<_>>(),
2153 "threshold_percentile": self.threshold_percentile,
2154 "threshold_ms": self.threshold_ms,
2155 "max_error_rate": self.max_error_rate,
2156 "abort_on_error": self.abort_on_error,
2157 "abort_on_error_rate": self.abort_on_error_rate,
2158 "headers": headers_json,
2159 "dynamic_imports": required_imports,
2160 "dynamic_globals": required_globals,
2161 "extracted_values_output_path": output_dir.join("extracted_values.json").to_string_lossy(),
2162 "security_testing_enabled": security_testing_enabled,
2164 "has_custom_headers": !custom_headers.is_empty(),
2165 });
2166
2167 let mut script = handlebars
2168 .render_template(template, &data)
2169 .map_err(|e| BenchError::ScriptGenerationFailed(e.to_string()))?;
2170
2171 if security_testing_enabled {
2173 script = self.generate_enhanced_script(&script)?;
2174 }
2175
2176 let script_path =
2178 self.output.join(format!("k6-{}-crud-flow.js", spec_name.replace('.', "_")));
2179
2180 std::fs::create_dir_all(self.output.clone())?;
2181 std::fs::write(&script_path, &script)?;
2182
2183 if !self.generate_only {
2184 let executor = K6Executor::new()?
2185 .with_local_ips(self.source_ips.join(","))
2186 .with_dns_policy(self.dns_policy.clone().unwrap_or_default());
2187 std::fs::create_dir_all(&output_dir)?;
2188
2189 executor.execute(&script_path, Some(&output_dir), self.verbose).await?;
2190
2191 let extracted = Self::parse_extracted_values(&output_dir)?;
2192 TerminalReporter::print_progress(&format!(
2193 " Extracted {} value(s) from {}",
2194 extracted.values.len(),
2195 spec_name
2196 ));
2197 return Ok(extracted);
2198 }
2199
2200 Ok(ExtractedValues::new())
2201 }
2202
2203 async fn execute_standard_spec(&self, parser: &SpecParser, spec_name: &str) -> Result<()> {
2205 let mut operations = if let Some(filter) = &self.operations {
2206 parser.filter_operations(filter)?
2207 } else {
2208 parser.get_operations()
2209 };
2210
2211 if let Some(exclude) = &self.exclude_operations {
2212 operations = parser.exclude_operations(operations, exclude)?;
2213 }
2214
2215 if operations.is_empty() {
2216 TerminalReporter::print_warning(&format!("No operations found in {}", spec_name));
2217 return Ok(());
2218 }
2219
2220 TerminalReporter::print_progress(&format!(
2221 " {} operations in {}",
2222 operations.len(),
2223 spec_name
2224 ));
2225
2226 let templates: Vec<_> = operations
2228 .iter()
2229 .map(RequestGenerator::generate_template)
2230 .collect::<Result<Vec<_>>>()?;
2231
2232 let custom_headers = self.parse_headers()?;
2234
2235 let base_path = self.resolve_base_path(parser);
2237
2238 let scenario =
2240 LoadScenario::from_str(&self.scenario).map_err(BenchError::InvalidScenario)?;
2241
2242 let security_testing_enabled = self.security_testing_enabled();
2243
2244 let k6_config = K6Config {
2245 target_url: self.target.clone(),
2246 base_path,
2247 scenario,
2248 duration_secs: Self::parse_duration(&self.duration)?,
2249 max_vus: self.vus,
2250 threshold_percentile: self.threshold_percentile.clone(),
2251 threshold_ms: self.threshold_ms,
2252 max_error_rate: self.max_error_rate,
2253 auth_header: self.auth.clone(),
2254 custom_headers,
2255 skip_tls_verify: self.skip_tls_verify,
2256 security_testing_enabled,
2257 chunked_request_bodies: self.chunked_request_bodies,
2258 target_rps: self.target_rps,
2259 no_keep_alive: self.no_keep_alive,
2260 geo_source_ips: parse_ip_list(&self.geo_source_ips, "geo-source-ip")
2262 .into_iter()
2263 .map(|ip| ip.to_string())
2264 .collect(),
2265 geo_source_headers: if self.geo_source_headers.is_empty()
2266 && !self.geo_source_ips.is_empty()
2267 {
2268 crate::conformance::self_test::default_geo_source_headers()
2269 } else {
2270 self.geo_source_headers.clone()
2271 },
2272 };
2273
2274 let generator = K6ScriptGenerator::new(k6_config, templates)
2275 .with_abort_valve(self.abort_on_error, self.abort_on_error_rate);
2276 let mut script = generator.generate()?;
2277
2278 let has_advanced_features = self.data_file.is_some()
2280 || self.error_rate.is_some()
2281 || self.security_test
2282 || self.parallel_create.is_some()
2283 || self.wafbench_dir.is_some();
2284
2285 if has_advanced_features {
2286 script = self.generate_enhanced_script(&script)?;
2287 }
2288
2289 let script_path = self.output.join(format!("k6-{}.js", spec_name.replace('.', "_")));
2291
2292 std::fs::create_dir_all(self.output.clone())?;
2293 std::fs::write(&script_path, &script)?;
2294
2295 if !self.generate_only {
2296 let executor = K6Executor::new()?
2299 .with_local_ips(self.source_ips.join(","))
2300 .with_dns_policy(self.dns_policy.clone().unwrap_or_default())
2301 .with_discard_response_bodies(self.discard_response_bodies);
2302 let output_dir = self.output.join(format!("{}_results", spec_name.replace('.', "_")));
2303 std::fs::create_dir_all(&output_dir)?;
2304
2305 executor.execute(&script_path, Some(&output_dir), self.verbose).await?;
2306 }
2307
2308 Ok(())
2309 }
2310
2311 async fn execute_crud_flow(&self, parser: &SpecParser) -> Result<()> {
2313 let config = self.build_crud_flow_config().unwrap_or_default();
2315
2316 let flows = if !config.flows.is_empty() {
2318 TerminalReporter::print_progress("Using custom flow configuration...");
2319 config.flows.clone()
2320 } else {
2321 TerminalReporter::print_progress("Detecting CRUD operations...");
2322 let operations = parser.get_operations();
2323 CrudFlowDetector::detect_flows(&operations)
2324 };
2325
2326 if flows.is_empty() {
2327 return Err(BenchError::Other(
2328 "No CRUD flows detected in spec. Ensure spec has POST/GET/PUT/DELETE operations on related paths.".to_string(),
2329 ));
2330 }
2331
2332 if config.flows.is_empty() {
2333 TerminalReporter::print_success(&format!("Detected {} CRUD flow(s)", flows.len()));
2334 } else {
2335 TerminalReporter::print_success(&format!("Loaded {} custom flow(s)", flows.len()));
2336 }
2337
2338 for flow in &flows {
2339 TerminalReporter::print_progress(&format!(
2340 " - {}: {} steps",
2341 flow.name,
2342 flow.steps.len()
2343 ));
2344 }
2345
2346 let mut handlebars = handlebars::Handlebars::new();
2348 handlebars.register_helper(
2350 "json",
2351 Box::new(
2352 |h: &handlebars::Helper,
2353 _: &handlebars::Handlebars,
2354 _: &handlebars::Context,
2355 _: &mut handlebars::RenderContext,
2356 out: &mut dyn handlebars::Output|
2357 -> handlebars::HelperResult {
2358 let param = h.param(0).map(|v| v.value()).unwrap_or(&serde_json::Value::Null);
2359 out.write(&serde_json::to_string(param).unwrap_or_else(|_| "[]".to_string()))?;
2360 Ok(())
2361 },
2362 ),
2363 );
2364 let template = include_str!("templates/k6_crud_flow.hbs");
2365
2366 let custom_headers = self.parse_headers()?;
2367
2368 let param_overrides = if let Some(params_file) = &self.params_file {
2370 TerminalReporter::print_progress("Loading parameter overrides...");
2371 let overrides = ParameterOverrides::from_file(params_file)?;
2372 TerminalReporter::print_success(&format!(
2373 "Loaded parameter overrides ({} operation-specific, {} defaults)",
2374 overrides.operations.len(),
2375 if overrides.defaults.is_empty() { 0 } else { 1 }
2376 ));
2377 Some(overrides)
2378 } else {
2379 None
2380 };
2381
2382 let duration_secs = Self::parse_duration(&self.duration)?;
2384 let scenario =
2385 LoadScenario::from_str(&self.scenario).map_err(BenchError::InvalidScenario)?;
2386 let stages = scenario.generate_stages(duration_secs, self.vus);
2387
2388 let api_base_path = self.resolve_base_path(parser);
2390 if let Some(ref bp) = api_base_path {
2391 TerminalReporter::print_progress(&format!("Using base path: {}", bp));
2392 }
2393
2394 let mut all_headers = custom_headers.clone();
2396 if let Some(auth) = &self.auth {
2397 all_headers.insert("Authorization".to_string(), auth.clone());
2398 }
2399 let headers_json = serde_json::to_string(&all_headers).unwrap_or_else(|_| "{}".to_string());
2400
2401 let mut all_placeholders: HashSet<DynamicPlaceholder> = HashSet::new();
2403
2404 let flows_data: Vec<serde_json::Value> = flows.iter().map(|f| {
2405 let sanitized_name = K6ScriptGenerator::sanitize_k6_metric_name(&f.name);
2410 serde_json::json!({
2411 "name": sanitized_name.clone(), "display_name": f.name, "base_path": f.base_path,
2414 "steps": f.steps.iter().enumerate().map(|(idx, s)| {
2415 let parts: Vec<&str> = s.operation.splitn(2, ' ').collect();
2417 let method_raw = if !parts.is_empty() {
2418 parts[0].to_uppercase()
2419 } else {
2420 "GET".to_string()
2421 };
2422 let method = if !parts.is_empty() {
2423 let m = parts[0].to_lowercase();
2424 if m == "delete" { "del".to_string() } else { m }
2426 } else {
2427 "get".to_string()
2428 };
2429 let raw_path = if parts.len() >= 2 { parts[1] } else { "/" };
2430 let path = if let Some(ref bp) = api_base_path {
2432 format!("{}{}", bp, raw_path)
2433 } else {
2434 raw_path.to_string()
2435 };
2436 let is_get_or_head = method == "get" || method == "head";
2437 let has_body = matches!(method.as_str(), "post" | "put" | "patch");
2439
2440 let body_value = if has_body {
2442 param_overrides.as_ref()
2443 .map(|po| po.get_for_operation(None, &method_raw, raw_path))
2444 .and_then(|oo| oo.body)
2445 .unwrap_or_else(|| serde_json::json!({}))
2446 } else {
2447 serde_json::json!({})
2448 };
2449
2450 let processed_body = DynamicParamProcessor::process_json_body(&body_value);
2452 let body_has_extracted_placeholders = processed_body.value.contains("${extracted.");
2457 let body_is_dynamic = processed_body.is_dynamic || body_has_extracted_placeholders;
2458
2459 serde_json::json!({
2460 "operation": s.operation,
2461 "method": method,
2462 "path": path,
2463 "extract": s.extract,
2464 "use_values": s.use_values,
2465 "use_body": s.use_body,
2466 "merge_body": if s.merge_body.is_empty() { None } else { Some(&s.merge_body) },
2467 "inject_attacks": s.inject_attacks,
2468 "attack_types": s.attack_types,
2469 "description": s.description,
2470 "display_name": s.description.clone().unwrap_or_else(|| format!("Step {}", idx)),
2471 "is_get_or_head": is_get_or_head,
2472 "has_body": has_body,
2473 "body": processed_body.value,
2474 "body_is_dynamic": body_is_dynamic,
2475 "_placeholders": processed_body.placeholders.iter().map(|p| format!("{:?}", p)).collect::<Vec<_>>(),
2476 })
2477 }).collect::<Vec<_>>(),
2478 })
2479 }).collect();
2480
2481 for flow_data in &flows_data {
2483 if let Some(steps) = flow_data.get("steps").and_then(|s| s.as_array()) {
2484 for step in steps {
2485 if let Some(placeholders_arr) =
2486 step.get("_placeholders").and_then(|p| p.as_array())
2487 {
2488 for p_str in placeholders_arr {
2489 if let Some(p_name) = p_str.as_str() {
2490 match p_name {
2492 "VU" => {
2493 all_placeholders.insert(DynamicPlaceholder::VU);
2494 }
2495 "Iteration" => {
2496 all_placeholders.insert(DynamicPlaceholder::Iteration);
2497 }
2498 "Timestamp" => {
2499 all_placeholders.insert(DynamicPlaceholder::Timestamp);
2500 }
2501 "UUID" => {
2502 all_placeholders.insert(DynamicPlaceholder::UUID);
2503 }
2504 "Random" => {
2505 all_placeholders.insert(DynamicPlaceholder::Random);
2506 }
2507 "Counter" => {
2508 all_placeholders.insert(DynamicPlaceholder::Counter);
2509 }
2510 "Date" => {
2511 all_placeholders.insert(DynamicPlaceholder::Date);
2512 }
2513 "VuIter" => {
2514 all_placeholders.insert(DynamicPlaceholder::VuIter);
2515 }
2516 _ => {}
2517 }
2518 }
2519 }
2520 }
2521 }
2522 }
2523 }
2524
2525 let required_imports = DynamicParamProcessor::get_required_imports(&all_placeholders);
2527 let required_globals = DynamicParamProcessor::get_required_globals(&all_placeholders);
2528
2529 let invalid_data_config = self.build_invalid_data_config();
2531 let error_injection_enabled = invalid_data_config.is_some();
2532 let error_rate = self.error_rate.unwrap_or(0.0);
2533 let error_types: Vec<String> = invalid_data_config
2534 .as_ref()
2535 .map(|c| c.error_types.iter().map(|t| format!("{:?}", t)).collect())
2536 .unwrap_or_default();
2537
2538 if error_injection_enabled {
2539 TerminalReporter::print_progress(&format!(
2540 "Error injection enabled ({}% rate)",
2541 (error_rate * 100.0) as u32
2542 ));
2543 }
2544
2545 let security_testing_enabled = self.security_testing_enabled();
2547
2548 let data = serde_json::json!({
2549 "base_url": self.target,
2550 "flows": flows_data,
2551 "extract_fields": config.default_extract_fields,
2552 "duration_secs": duration_secs,
2553 "max_vus": self.vus,
2554 "auth_header": self.auth,
2555 "custom_headers": custom_headers,
2556 "skip_tls_verify": self.skip_tls_verify,
2557 "stages": stages.iter().map(|s| serde_json::json!({
2559 "duration": s.duration,
2560 "target": s.target,
2561 })).collect::<Vec<_>>(),
2562 "threshold_percentile": self.threshold_percentile,
2563 "threshold_ms": self.threshold_ms,
2564 "max_error_rate": self.max_error_rate,
2565 "abort_on_error": self.abort_on_error,
2566 "abort_on_error_rate": self.abort_on_error_rate,
2567 "headers": headers_json,
2568 "dynamic_imports": required_imports,
2569 "dynamic_globals": required_globals,
2570 "extracted_values_output_path": self
2571 .output
2572 .join("crud_flow_extracted_values.json")
2573 .to_string_lossy(),
2574 "error_injection_enabled": error_injection_enabled,
2576 "error_rate": error_rate,
2577 "error_types": error_types,
2578 "security_testing_enabled": security_testing_enabled,
2580 "has_custom_headers": !custom_headers.is_empty(),
2581 });
2582
2583 let mut script = handlebars
2584 .render_template(template, &data)
2585 .map_err(|e| BenchError::ScriptGenerationFailed(e.to_string()))?;
2586
2587 if security_testing_enabled {
2589 script = self.generate_enhanced_script(&script)?;
2590 }
2591
2592 TerminalReporter::print_progress("Validating CRUD flow script...");
2594 let validation_errors = K6ScriptGenerator::validate_script(&script);
2595 if !validation_errors.is_empty() {
2596 TerminalReporter::print_error("CRUD flow script validation failed");
2597 for error in &validation_errors {
2598 eprintln!(" {}", error);
2599 }
2600 return Err(BenchError::Other(format!(
2601 "CRUD flow script validation failed with {} error(s)",
2602 validation_errors.len()
2603 )));
2604 }
2605
2606 TerminalReporter::print_success("CRUD flow script generated");
2607
2608 let script_path = if let Some(output) = &self.script_output {
2610 output.clone()
2611 } else {
2612 self.output.join("k6-crud-flow-script.js")
2613 };
2614
2615 if let Some(parent) = script_path.parent() {
2616 std::fs::create_dir_all(parent)?;
2617 }
2618 std::fs::write(&script_path, &script)?;
2619 TerminalReporter::print_success(&format!("Script written to: {}", script_path.display()));
2620
2621 if self.generate_only {
2622 println!("\nScript generated successfully. Run it with:");
2623 println!(" k6 run {}", script_path.display());
2624 return Ok(());
2625 }
2626
2627 TerminalReporter::print_progress("Executing CRUD flow test...");
2629 let executor = K6Executor::new()?
2630 .with_local_ips(self.source_ips.join(","))
2631 .with_dns_policy(self.dns_policy.clone().unwrap_or_default());
2632 std::fs::create_dir_all(&self.output)?;
2633
2634 let results = executor.execute(&script_path, Some(&self.output), self.verbose).await?;
2635
2636 let duration_secs = Self::parse_duration(&self.duration)?;
2637 TerminalReporter::print_summary_with_mode(&results, duration_secs, self.no_keep_alive);
2638
2639 Ok(())
2640 }
2641
2642 async fn execute_conformance_test(&self) -> Result<()> {
2644 use crate::conformance::generator::{ConformanceConfig, ConformanceGenerator};
2645 use crate::conformance::report::ConformanceReport;
2646 use crate::conformance::spec::ConformanceFeature;
2647
2648 TerminalReporter::print_progress("OpenAPI 3.0.0 Conformance Testing Mode");
2649
2650 TerminalReporter::print_progress(CONFORMANCE_REPLACES_LOAD_ADVISORY);
2651
2652 let categories = self.conformance_categories.as_ref().map(|cats_str| {
2654 cats_str
2655 .split(',')
2656 .filter_map(|s| {
2657 let trimmed = s.trim();
2658 if let Some(canonical) = ConformanceFeature::category_from_cli_name(trimmed) {
2659 Some(canonical.to_string())
2660 } else {
2661 TerminalReporter::print_warning(&format!(
2662 "Unknown conformance category: '{}'. Valid categories: {}",
2663 trimmed,
2664 ConformanceFeature::cli_category_names()
2665 .iter()
2666 .map(|(cli, _)| *cli)
2667 .collect::<Vec<_>>()
2668 .join(", ")
2669 ));
2670 None
2671 }
2672 })
2673 .collect::<Vec<String>>()
2674 });
2675
2676 let custom_headers: Vec<(String, String)> = self
2678 .conformance_headers
2679 .iter()
2680 .filter_map(|h| {
2681 let (name, value) = h.split_once(':')?;
2682 Some((name.trim().to_string(), value.trim().to_string()))
2683 })
2684 .collect();
2685
2686 if !custom_headers.is_empty() {
2687 TerminalReporter::print_progress(&format!(
2688 "Using {} custom header(s) for authentication",
2689 custom_headers.len()
2690 ));
2691 }
2692
2693 if self.conformance_delay_ms > 0 {
2694 TerminalReporter::print_progress(&format!(
2695 "Using {}ms delay between conformance requests",
2696 self.conformance_delay_ms
2697 ));
2698 }
2699
2700 std::fs::create_dir_all(&self.output)?;
2702
2703 let config = ConformanceConfig {
2704 target_url: self.target.clone(),
2705 api_key: self.conformance_api_key.clone(),
2706 basic_auth: self.conformance_basic_auth.clone(),
2707 skip_tls_verify: self.skip_tls_verify,
2708 categories,
2709 base_path: self.base_path.clone(),
2710 custom_headers,
2711 output_dir: Some(self.output.clone()),
2712 all_operations: self.conformance_all_operations,
2713 custom_checks_file: self.conformance_custom.clone(),
2714 request_delay_ms: self.conformance_delay_ms,
2715 custom_filter: self.conformance_custom_filter.clone(),
2716 export_requests: self.export_requests,
2717 validate_requests: self.validate_requests,
2718 };
2719
2720 let mut resolved_base_path: Option<String> = None;
2728 let annotated_ops = if !self.spec.is_empty() {
2729 TerminalReporter::print_progress("Spec-driven conformance mode: analyzing spec...");
2730 let parser = SpecParser::from_file(&self.spec[0]).await?;
2731 resolved_base_path = self.resolve_base_path(&parser);
2732
2733 let mut operations = if let Some(filter) = &self.operations {
2738 parser.filter_operations(filter)?
2739 } else {
2740 parser.get_operations()
2741 };
2742 if let Some(exclude) = &self.exclude_operations {
2743 let before_count = operations.len();
2744 operations = parser.exclude_operations(operations, exclude)?;
2745 let excluded_count = before_count - operations.len();
2746 if excluded_count > 0 {
2747 TerminalReporter::print_progress(&format!(
2748 "Excluded {} operations matching '{}'",
2749 excluded_count, exclude
2750 ));
2751 }
2752 }
2753
2754 let annotated =
2755 crate::conformance::spec_driven::SpecDrivenConformanceGenerator::annotate_operations(
2756 &operations,
2757 parser.spec(),
2758 );
2759 TerminalReporter::print_success(&format!(
2760 "Analyzed {} operations, found {} feature annotations",
2761 operations.len(),
2762 annotated.iter().map(|a| a.features.len()).sum::<usize>()
2763 ));
2764 Some(annotated)
2765 } else {
2766 None
2767 };
2768
2769 if self.conformance_self_test {
2776 let Some(ops) = annotated_ops else {
2777 TerminalReporter::print_error(
2778 "--conformance-self-test requires --spec; no operations to test",
2779 );
2780 return Ok(());
2781 };
2782 let cfg = crate::conformance::self_test::SelfTestConfig {
2783 target_url: self.target.clone(),
2784 skip_tls_verify: self.skip_tls_verify,
2785 timeout: std::time::Duration::from_secs(30),
2786 extra_headers: self
2790 .conformance_headers
2791 .iter()
2792 .filter_map(|h| {
2793 let (n, v) = h.split_once(':')?;
2794 Some((n.trim().to_string(), v.trim().to_string()))
2795 })
2796 .collect(),
2797 delay_between_requests: std::time::Duration::from_millis(self.conformance_delay_ms),
2798 base_path: resolved_base_path.clone(),
2802 source_ips: parse_ip_list(&self.source_ips, "source-ip"),
2806 geo_source_ips: parse_ip_list(&self.geo_source_ips, "geo-source-ip"),
2807 geo_source_headers: if self.geo_source_headers.is_empty() {
2808 crate::conformance::self_test::default_geo_source_headers()
2809 } else {
2810 self.geo_source_headers.clone()
2811 },
2812 capture: if self.conformance_self_test_capture
2816 || self.validate_response_schemas
2817 || self.validate_requests
2818 {
2819 Some(std::sync::Arc::new(std::sync::Mutex::new(Vec::new())))
2830 } else {
2831 None
2832 },
2833 validate_response_schemas: self.validate_response_schemas,
2834 spec_label: self.spec.first().map(|p| {
2840 p.file_name()
2841 .map(|s| s.to_string_lossy().into_owned())
2842 .unwrap_or_else(|| p.to_string_lossy().into_owned())
2843 }),
2844 network_events: Some(std::sync::Arc::new(std::sync::Mutex::new(Vec::new()))),
2851 current_iteration: 1,
2852 };
2853 let capture_sink = cfg.capture.clone();
2854 let network_events_sink = cfg.network_events.clone();
2855 TerminalReporter::print_progress(&format!(
2856 "Self-test mode: driving {} operations with positive + per-category negative cases",
2857 ops.len()
2858 ));
2859 let target_iterations = self.conformance_self_test_iterations.max(1);
2866 let duration_budget = self
2867 .conformance_self_test_duration
2868 .as_ref()
2869 .map(|s| Self::parse_duration(s))
2870 .transpose()?
2871 .map(std::time::Duration::from_secs);
2872 let start = std::time::Instant::now();
2873 let deadline = duration_budget.map(|d| start + d);
2882 let mut cfg = cfg;
2886 cfg.current_iteration = 1;
2887 let mut report =
2888 crate::conformance::self_test::run_self_test_with_deadline(&ops, &cfg, deadline)
2889 .await
2890 .map_err(|e| BenchError::Other(format!("self-test client error: {e}")))?;
2891 let mut iter_done: u32 = 1;
2892 loop {
2893 let by_iter = iter_done >= target_iterations;
2894 let by_dur = duration_budget.map(|d| start.elapsed() >= d).unwrap_or(true);
2895 if by_iter && by_dur {
2896 break;
2897 }
2898 cfg.current_iteration = iter_done.saturating_add(1);
2899 let next = crate::conformance::self_test::run_self_test_with_deadline(
2900 &ops, &cfg, deadline,
2901 )
2902 .await
2903 .map_err(|e| BenchError::Other(format!("self-test client error: {e}")))?;
2904 report.merge_iteration(next);
2905 iter_done = iter_done.saturating_add(1);
2906 }
2907 if iter_done > 1 {
2908 TerminalReporter::print_progress(&format!(
2909 "Self-test repeated {} iteration(s) ({:.1?} elapsed)",
2910 iter_done,
2911 start.elapsed(),
2912 ));
2913 }
2914 let per_endpoint_summary: Vec<
2924 crate::conformance::per_endpoint_summary::PerEndpointSummary,
2925 >;
2926 if let Some(sink) = capture_sink {
2927 if let Ok(guard) = sink.lock() {
2928 let jsonl_path = self.output.join("conformance-self-test-requests.jsonl");
2929 let mut lines = String::with_capacity(guard.len() * 256);
2930 for entry in guard.iter() {
2931 if let Ok(line) = serde_json::to_string(entry) {
2932 lines.push_str(&line);
2933 lines.push('\n');
2934 }
2935 }
2936 let _ = std::fs::write(&jsonl_path, lines);
2937 let html_path = self.output.join("conformance-self-test-requests.html");
2938 let html =
2939 crate::conformance::capture_html::render_capture_html(guard.as_slice());
2940 let _ = std::fs::write(&html_path, html);
2941
2942 per_endpoint_summary =
2946 crate::conformance::per_endpoint_summary::build_summary(guard.as_slice());
2947 let summary_path = self.output.join("conformance-per-endpoint.json");
2948 if let Ok(json) = serde_json::to_string_pretty(&per_endpoint_summary) {
2949 let _ = std::fs::write(&summary_path, json);
2950 TerminalReporter::print_progress(&format!(
2951 "Self-test request/response capture written to {} ({} entries) + {} + {}",
2952 jsonl_path.display(),
2953 guard.len(),
2954 html_path.display(),
2955 summary_path.display(),
2956 ));
2957 } else {
2958 TerminalReporter::print_progress(&format!(
2959 "Self-test request/response capture written to {} ({} entries) + {}",
2960 jsonl_path.display(),
2961 guard.len(),
2962 html_path.display(),
2963 ));
2964 }
2965 } else {
2966 per_endpoint_summary = Vec::new();
2967 }
2968 } else {
2969 per_endpoint_summary = Vec::new();
2970 }
2971 TerminalReporter::print_progress(&report.render_summary());
2972 if let Some(sink) = network_events_sink {
2979 if let Ok(guard) = sink.lock() {
2980 let path = self.output.join("conformance-network-events.json");
2981 if let Ok(json) = serde_json::to_string_pretty(&*guard) {
2982 let _ = std::fs::write(&path, json);
2983 if guard.is_empty() {
2984 TerminalReporter::print_progress(
2985 "No wire-level network failures during self-test (file written empty)",
2986 );
2987 } else {
2988 TerminalReporter::print_warning(&format!(
2989 "Recorded {} wire-level network event(s) to {}",
2990 guard.len(),
2991 path.display()
2992 ));
2993 }
2994 }
2995 }
2996 }
2997 let json_path = self.output.join("conformance-self-test.json");
3001 if let Ok(json) = serde_json::to_string_pretty(&report) {
3002 let _ = std::fs::write(&json_path, json);
3003 TerminalReporter::print_progress(&format!(
3004 "Self-test report written to {}",
3005 json_path.display()
3006 ));
3007 }
3008 let issues = report.definite_issues();
3012 let issues_path = self.output.join("conformance-definite-issues.json");
3013 if let Ok(json) = serde_json::to_string_pretty(&issues) {
3014 if std::fs::write(&issues_path, json).is_ok() && !issues.is_empty() {
3015 TerminalReporter::print_warning(&format!(
3016 "{} definite issue(s) — see {}",
3017 issues.len(),
3018 issues_path.display()
3019 ));
3020 }
3021 }
3022 let owasp_accepted = report.owasp_accepted_probes();
3025 if !owasp_accepted.is_empty() {
3026 let owasp_path = self.output.join("conformance-owasp-accepted.json");
3027 if let Ok(json) = serde_json::to_string_pretty(&owasp_accepted) {
3028 if std::fs::write(&owasp_path, json).is_ok() {
3029 TerminalReporter::print_warning(&format!(
3030 "{} owasp injection probe(s) accepted by the target — see {}",
3031 owasp_accepted.len(),
3032 owasp_path.display()
3033 ));
3034 }
3035 }
3036 }
3037 if let Some(status) = report.detect_target_misconfiguration() {
3046 let hint = match status {
3047 404 => " Likely cause: spec paths don't match deployed routes — check --base-path and the spec's `servers` block.",
3048 401 | 403 => " Likely cause: authentication header is missing or invalid — check --conformance-header.",
3049 _ => "",
3050 };
3051 TerminalReporter::print_warning(&format!(
3052 "Self-test misconfiguration: every positive case returned {status}.{hint} Negative results below are meaningless under this condition."
3053 ));
3054 } else if !report.all_passed() {
3055 TerminalReporter::print_warning(
3056 "Self-test detected gaps — server let through at least one request that should have been a 4xx",
3057 );
3058 } else {
3059 TerminalReporter::print_success(
3060 "Self-test passed — all positive cases accepted and all negative cases rejected",
3061 );
3062 }
3063 let html_path = self.output.join("conformance-report.html");
3070 let audit_path = self.output.join("conformance-spec-audit.json");
3071 let audit_value = std::fs::read_to_string(&audit_path)
3072 .ok()
3073 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok());
3074 let render_opts = crate::conformance::report_html::RenderOptions {
3079 missed_cap: match self.report_missed_cap {
3080 Some(0) => None,
3081 Some(n) => Some(n as usize),
3082 None => Some(200),
3083 },
3084 };
3085 let mut html = crate::conformance::report_html::render_html_with_options(
3086 &report,
3087 audit_value.as_ref(),
3088 &render_opts,
3089 );
3090 let summary_section = crate::conformance::per_endpoint_summary::render_html_section(
3096 &per_endpoint_summary,
3097 );
3098 if !summary_section.is_empty() {
3099 if let Some(idx) = html.rfind("</body>") {
3100 html.insert_str(idx, &summary_section);
3101 } else {
3102 html.push_str(&summary_section);
3103 }
3104 }
3105 if std::fs::write(&html_path, html).is_ok() {
3106 TerminalReporter::print_progress(&format!(
3107 "HTML report written to {}",
3108 html_path.display()
3109 ));
3110 }
3111
3112 if self.validate_requests && !self.spec.is_empty() {
3124 let n = crate::conformance::request_validator::validate_emitted_requests_with_base_path(
3125 &self.spec,
3126 &self.output,
3127 self.base_path.as_deref(),
3128 )
3129 .await?;
3130 if n > 0 {
3131 TerminalReporter::print_warning(&format!(
3132 "{} emitted request(s) recorded against the spec — see conformance-request-violations.json",
3133 n
3134 ));
3135 }
3136 }
3137 return Ok(());
3138 }
3139
3140 if self.validate_requests && !self.spec.is_empty() {
3142 TerminalReporter::print_progress("Validating requests against OpenAPI spec...");
3143 let violation_count = crate::conformance::request_validator::run_request_validation(
3144 &self.spec,
3145 self.conformance_custom.as_deref(),
3146 self.base_path.as_deref(),
3147 &self.output,
3148 )
3149 .await?;
3150 if violation_count > 0 {
3151 TerminalReporter::print_warning(&format!(
3152 "{} request validation violation(s) found — see conformance-request-violations.json",
3153 violation_count
3154 ));
3155 } else {
3156 TerminalReporter::print_success("All requests conform to the OpenAPI spec");
3157 }
3158 }
3159
3160 if self.generate_only || self.use_k6 {
3162 let script = if let Some(annotated) = &annotated_ops {
3163 let gen = crate::conformance::spec_driven::SpecDrivenConformanceGenerator::new(
3164 config,
3165 annotated.clone(),
3166 );
3167 let op_count = gen.operation_count();
3168 let (script, check_count) = gen.generate()?;
3169 TerminalReporter::print_success(&format!(
3170 "Conformance: {} operations analyzed, {} unique checks generated",
3171 op_count, check_count
3172 ));
3173 script
3174 } else {
3175 let generator = ConformanceGenerator::new(config);
3176 generator.generate()?
3177 };
3178
3179 let script_path = self.output.join("k6-conformance.js");
3180 std::fs::write(&script_path, &script).map_err(|e| {
3181 BenchError::Other(format!("Failed to write conformance script: {}", e))
3182 })?;
3183 TerminalReporter::print_success(&format!(
3184 "Conformance script generated: {}",
3185 script_path.display()
3186 ));
3187
3188 if self.generate_only {
3189 println!("\nScript generated. Run with:");
3190 println!(" k6 run {}", script_path.display());
3191 return Ok(());
3192 }
3193
3194 if !K6Executor::is_k6_installed() {
3196 TerminalReporter::print_error("k6 is not installed");
3197 TerminalReporter::print_warning(
3198 "Install k6 from: https://k6.io/docs/get-started/installation/",
3199 );
3200 return Err(BenchError::K6NotFound);
3201 }
3202
3203 K6Executor::warn_if_pre_v1().await;
3204 TerminalReporter::print_progress("Running conformance tests via k6...");
3205 let executor = K6Executor::new()?
3206 .with_local_ips(self.source_ips.join(","))
3207 .with_dns_policy(self.dns_policy.clone().unwrap_or_default());
3208 executor.execute(&script_path, Some(&self.output), self.verbose).await?;
3209
3210 let report_path = self.output.join("conformance-report.json");
3211 if report_path.exists() {
3212 let report = ConformanceReport::from_file(&report_path)?;
3213 report.print_report_with_options(self.conformance_all_operations);
3214 self.save_conformance_report(&report, &report_path)?;
3215 } else {
3216 TerminalReporter::print_warning(
3217 "Conformance report not generated (k6 handleSummary may not have run)",
3218 );
3219 }
3220
3221 if self.validate_requests && self.export_requests && !self.spec.is_empty() {
3233 let n = crate::conformance::request_validator::validate_emitted_requests_with_base_path(
3234 &self.spec,
3235 &self.output,
3236 self.base_path.as_deref(),
3237 )
3238 .await?;
3239 if n > 0 {
3240 TerminalReporter::print_warning(&format!(
3241 "{} emitted request(s) violated the spec — see conformance-request-violations.json",
3242 n
3243 ));
3244 }
3245 }
3246
3247 return Ok(());
3248 }
3249
3250 TerminalReporter::print_progress("Running conformance tests (native executor)...");
3252
3253 let mut executor = crate::conformance::executor::NativeConformanceExecutor::new(config)?;
3254
3255 let custom_only = annotated_ops.is_none() && self.conformance_custom.is_some();
3265 executor = if let Some(annotated) = &annotated_ops {
3266 executor.with_spec_driven_checks(annotated)
3267 } else if custom_only {
3268 executor
3269 } else {
3270 executor.with_reference_checks()
3271 };
3272 executor = executor.with_custom_checks()?;
3273
3274 TerminalReporter::print_success(&format!(
3275 "Executing {} conformance checks...",
3276 executor.check_count()
3277 ));
3278
3279 let report = executor.execute().await?;
3280 report.print_report_with_options(self.conformance_all_operations);
3281
3282 let failure_details = report.failure_details();
3284 if !failure_details.is_empty() {
3285 let details_path = self.output.join("conformance-failure-details.json");
3286 if let Ok(json) = serde_json::to_string_pretty(&failure_details) {
3287 let _ = std::fs::write(&details_path, json);
3288 TerminalReporter::print_success(&format!(
3289 "Failure details saved to: {}",
3290 details_path.display()
3291 ));
3292 }
3293 }
3294
3295 let report_path = self.output.join("conformance-report.json");
3297 let report_json = serde_json::to_string_pretty(&report.to_json())
3298 .map_err(|e| BenchError::Other(format!("Failed to serialize report: {}", e)))?;
3299 std::fs::write(&report_path, &report_json)
3300 .map_err(|e| BenchError::Other(format!("Failed to write report: {}", e)))?;
3301 TerminalReporter::print_success(&format!("Report saved to: {}", report_path.display()));
3302
3303 self.save_conformance_report(&report, &report_path)?;
3304
3305 if self.validate_requests && self.export_requests && !self.spec.is_empty() {
3316 let n =
3317 crate::conformance::request_validator::validate_emitted_requests_with_base_path(
3318 &self.spec,
3319 &self.output,
3320 self.base_path.as_deref(),
3321 )
3322 .await?;
3323 if n > 0 {
3324 TerminalReporter::print_warning(&format!(
3325 "{} emitted request(s) violated the spec — see conformance-request-violations.json",
3326 n
3327 ));
3328 }
3329 }
3330
3331 Ok(())
3332 }
3333
3334 fn save_conformance_report(
3336 &self,
3337 report: &crate::conformance::report::ConformanceReport,
3338 report_path: &Path,
3339 ) -> Result<()> {
3340 if self.conformance_report_format == "sarif" {
3341 use crate::conformance::sarif::ConformanceSarifReport;
3342 ConformanceSarifReport::write(report, &self.target, &self.conformance_report)?;
3343 TerminalReporter::print_success(&format!(
3344 "SARIF report saved to: {}",
3345 self.conformance_report.display()
3346 ));
3347 } else if self.conformance_report != *report_path {
3348 std::fs::copy(report_path, &self.conformance_report)?;
3349 TerminalReporter::print_success(&format!(
3350 "Report saved to: {}",
3351 self.conformance_report.display()
3352 ));
3353 }
3354 Ok(())
3355 }
3356
3357 async fn execute_multi_target_self_test(&self, targets_file: &Path) -> Result<()> {
3369 use crate::conformance::self_test::SelfTestConfig;
3370
3371 TerminalReporter::print_progress("Multi-target conformance self-test mode");
3372 let targets = parse_targets_file(targets_file)?;
3373 if targets.is_empty() {
3374 return Err(BenchError::Other("No targets found in file".to_string()));
3375 }
3376 TerminalReporter::print_success(&format!("Loaded {} target(s)", targets.len()));
3377
3378 let annotated_ops = if !self.spec.is_empty() {
3380 let parser = SpecParser::from_file(&self.spec[0]).await?;
3381 let operations = parser.get_operations();
3382 Some(
3383 crate::conformance::spec_driven::SpecDrivenConformanceGenerator::annotate_operations(
3384 &operations,
3385 parser.spec(),
3386 ),
3387 )
3388 } else {
3389 return Err(BenchError::Other("--conformance-self-test requires --spec".to_string()));
3390 };
3391 let Some(ops) = annotated_ops else {
3392 unreachable!()
3393 };
3394
3395 std::fs::create_dir_all(&self.output)?;
3396 let resolved_base_path = self.base_path.clone();
3397 let target_iterations = self.conformance_self_test_iterations.max(1);
3398 let duration_budget = self
3399 .conformance_self_test_duration
3400 .as_ref()
3401 .map(|s| Self::parse_duration(s))
3402 .transpose()?
3403 .map(std::time::Duration::from_secs);
3404
3405 for (idx, target) in targets.iter().enumerate() {
3406 let target_dir = self.output.join(format!("target_{}", idx));
3407 std::fs::create_dir_all(&target_dir)?;
3408 TerminalReporter::print_progress(&format!(
3409 "[target {}/{}] {}",
3410 idx + 1,
3411 targets.len(),
3412 target.url
3413 ));
3414
3415 let merged_headers: Vec<(String, String)> = self
3416 .conformance_headers
3417 .iter()
3418 .filter_map(|h| {
3419 let (n, v) = h.split_once(':')?;
3420 Some((n.trim().to_string(), v.trim().to_string()))
3421 })
3422 .collect();
3423
3424 let cfg = SelfTestConfig {
3425 target_url: target.url.clone(),
3426 skip_tls_verify: self.skip_tls_verify,
3427 timeout: std::time::Duration::from_secs(30),
3428 extra_headers: merged_headers,
3429 delay_between_requests: std::time::Duration::from_millis(self.conformance_delay_ms),
3430 base_path: resolved_base_path.clone(),
3431 source_ips: parse_ip_list(&self.source_ips, "source-ip"),
3432 geo_source_ips: parse_ip_list(&self.geo_source_ips, "geo-source-ip"),
3433 geo_source_headers: if self.geo_source_headers.is_empty() {
3434 crate::conformance::self_test::default_geo_source_headers()
3435 } else {
3436 self.geo_source_headers.clone()
3437 },
3438 capture: if self.conformance_self_test_capture
3439 || self.validate_response_schemas
3440 || self.validate_requests
3441 {
3442 Some(std::sync::Arc::new(std::sync::Mutex::new(Vec::new())))
3446 } else {
3447 None
3448 },
3449 validate_response_schemas: self.validate_response_schemas,
3450 spec_label: self.spec.first().map(|p| {
3451 p.file_name()
3452 .map(|s| s.to_string_lossy().into_owned())
3453 .unwrap_or_else(|| p.to_string_lossy().into_owned())
3454 }),
3455 network_events: Some(std::sync::Arc::new(std::sync::Mutex::new(Vec::new()))),
3456 current_iteration: 1,
3457 };
3458 let capture_sink = cfg.capture.clone();
3459 let network_events_sink = cfg.network_events.clone();
3460
3461 let start = std::time::Instant::now();
3462 let deadline = duration_budget.map(|d| start + d);
3466 let mut cfg = cfg;
3470 cfg.current_iteration = 1;
3471 let mut report =
3472 crate::conformance::self_test::run_self_test_with_deadline(&ops, &cfg, deadline)
3473 .await
3474 .map_err(|e| BenchError::Other(format!("self-test client error: {e}")))?;
3475 let mut iter_done: u32 = 1;
3476 loop {
3477 let by_iter = iter_done >= target_iterations;
3478 let by_dur = duration_budget.map(|d| start.elapsed() >= d).unwrap_or(true);
3479 if by_iter && by_dur {
3480 break;
3481 }
3482 cfg.current_iteration = iter_done.saturating_add(1);
3483 let next = crate::conformance::self_test::run_self_test_with_deadline(
3484 &ops, &cfg, deadline,
3485 )
3486 .await
3487 .map_err(|e| BenchError::Other(format!("self-test client error: {e}")))?;
3488 report.merge_iteration(next);
3489 iter_done = iter_done.saturating_add(1);
3490 }
3491 if iter_done > 1 {
3492 TerminalReporter::print_progress(&format!(
3493 " ran {} iteration(s) in {:.1?}",
3494 iter_done,
3495 start.elapsed(),
3496 ));
3497 }
3498
3499 if let Some(sink) = capture_sink {
3501 if let Ok(guard) = sink.lock() {
3502 let jsonl = target_dir.join("conformance-self-test-requests.jsonl");
3503 let mut lines = String::with_capacity(guard.len() * 256);
3504 for entry in guard.iter() {
3505 if let Ok(line) = serde_json::to_string(entry) {
3506 lines.push_str(&line);
3507 lines.push('\n');
3508 }
3509 }
3510 let _ = std::fs::write(&jsonl, lines);
3511 }
3512 }
3513 if let Some(sink) = network_events_sink {
3514 if let Ok(guard) = sink.lock() {
3515 let path = target_dir.join("conformance-network-events.json");
3516 if let Ok(json) = serde_json::to_string_pretty(&*guard) {
3517 let _ = std::fs::write(&path, json);
3518 if !guard.is_empty() {
3519 TerminalReporter::print_warning(&format!(
3520 " recorded {} wire-level network event(s)",
3521 guard.len()
3522 ));
3523 }
3524 }
3525 }
3526 }
3527
3528 let json_path = target_dir.join("conformance-self-test.json");
3529 if let Ok(json) = serde_json::to_string_pretty(&report) {
3530 let _ = std::fs::write(&json_path, json);
3531 }
3532 let issues = report.definite_issues();
3535 if let Ok(json) = serde_json::to_string_pretty(&issues) {
3536 let issues_path = target_dir.join("conformance-definite-issues.json");
3537 if std::fs::write(&issues_path, json).is_ok() && !issues.is_empty() {
3538 TerminalReporter::print_warning(&format!(
3539 " {} definite issue(s) — see {}",
3540 issues.len(),
3541 issues_path.display()
3542 ));
3543 }
3544 }
3545 let owasp_accepted = report.owasp_accepted_probes();
3547 if !owasp_accepted.is_empty() {
3548 if let Ok(json) = serde_json::to_string_pretty(&owasp_accepted) {
3549 let owasp_path = target_dir.join("conformance-owasp-accepted.json");
3550 if std::fs::write(&owasp_path, json).is_ok() {
3551 TerminalReporter::print_warning(&format!(
3552 " {} owasp injection probe(s) accepted by the target — see {}",
3553 owasp_accepted.len(),
3554 owasp_path.display()
3555 ));
3556 }
3557 }
3558 }
3559 TerminalReporter::print_progress(&report.render_summary());
3560
3561 if self.validate_requests {
3570 let n = crate::conformance::request_validator::validate_emitted_requests_with_base_path(
3571 &self.spec,
3572 &target_dir,
3573 self.base_path.as_deref(),
3574 )
3575 .await?;
3576 if n > 0 {
3577 TerminalReporter::print_warning(&format!(
3578 " {} emitted request(s) violated the spec — see {}/conformance-request-violations.json",
3579 n,
3580 target_dir.display(),
3581 ));
3582 }
3583 }
3584 }
3585
3586 Ok(())
3587 }
3588
3589 async fn execute_multi_target_conformance(&self, targets_file: &Path) -> Result<()> {
3595 use crate::conformance::generator::{ConformanceConfig, ConformanceGenerator};
3596 use crate::conformance::report::ConformanceReport;
3597 use crate::conformance::spec::ConformanceFeature;
3598
3599 TerminalReporter::print_progress("Multi-target OpenAPI 3.0.0 Conformance Testing Mode");
3600
3601 TerminalReporter::print_progress("Parsing targets file...");
3603 let targets = parse_targets_file(targets_file)?;
3604 let num_targets = targets.len();
3605 TerminalReporter::print_success(&format!("Loaded {} targets", num_targets));
3606
3607 if targets.is_empty() {
3608 return Err(BenchError::Other("No targets found in file".to_string()));
3609 }
3610
3611 TerminalReporter::print_progress(CONFORMANCE_REPLACES_LOAD_ADVISORY);
3612
3613 let categories = self.conformance_categories.as_ref().map(|cats_str| {
3615 cats_str
3616 .split(',')
3617 .filter_map(|s| {
3618 let trimmed = s.trim();
3619 if let Some(canonical) = ConformanceFeature::category_from_cli_name(trimmed) {
3620 Some(canonical.to_string())
3621 } else {
3622 TerminalReporter::print_warning(&format!(
3623 "Unknown conformance category: '{}'. Valid categories: {}",
3624 trimmed,
3625 ConformanceFeature::cli_category_names()
3626 .iter()
3627 .map(|(cli, _)| *cli)
3628 .collect::<Vec<_>>()
3629 .join(", ")
3630 ));
3631 None
3632 }
3633 })
3634 .collect::<Vec<String>>()
3635 });
3636
3637 let base_custom_headers: Vec<(String, String)> = self
3639 .conformance_headers
3640 .iter()
3641 .filter_map(|h| {
3642 let (name, value) = h.split_once(':')?;
3643 Some((name.trim().to_string(), value.trim().to_string()))
3644 })
3645 .collect();
3646
3647 if !base_custom_headers.is_empty() {
3648 TerminalReporter::print_progress(&format!(
3649 "Using {} base custom header(s) for authentication",
3650 base_custom_headers.len()
3651 ));
3652 }
3653
3654 let annotated_ops = if !self.spec.is_empty() {
3656 TerminalReporter::print_progress("Spec-driven conformance mode: analyzing spec...");
3657 let parser = SpecParser::from_file(&self.spec[0]).await?;
3658 let operations = parser.get_operations();
3659 let annotated =
3660 crate::conformance::spec_driven::SpecDrivenConformanceGenerator::annotate_operations(
3661 &operations,
3662 parser.spec(),
3663 );
3664 TerminalReporter::print_success(&format!(
3665 "Analyzed {} operations, found {} feature annotations",
3666 operations.len(),
3667 annotated.iter().map(|a| a.features.len()).sum::<usize>()
3668 ));
3669 Some(annotated)
3670 } else {
3671 None
3672 };
3673
3674 std::fs::create_dir_all(&self.output)?;
3676
3677 struct TargetResult {
3679 url: String,
3680 passed: usize,
3681 failed: usize,
3682 elapsed: std::time::Duration,
3683 report_json: serde_json::Value,
3684 owasp_coverage: Vec<crate::conformance::report::OwaspCoverageEntry>,
3685 }
3686
3687 let mut target_results: Vec<TargetResult> = Vec::with_capacity(num_targets);
3688 let total_start = std::time::Instant::now();
3689
3690 for (idx, target) in targets.iter().enumerate() {
3691 tracing::info!(
3692 "Running conformance tests against target {}/{}: {}",
3693 idx + 1,
3694 num_targets,
3695 target.url
3696 );
3697 TerminalReporter::print_progress(&format!(
3698 "\n--- Target {}/{}: {} ---",
3699 idx + 1,
3700 num_targets,
3701 target.url
3702 ));
3703
3704 let mut merged_headers = base_custom_headers.clone();
3706 if let Some(ref target_headers) = target.headers {
3707 for (name, value) in target_headers {
3708 if let Some(existing) = merged_headers.iter_mut().find(|(n, _)| n == name) {
3710 existing.1 = value.clone();
3711 } else {
3712 merged_headers.push((name.clone(), value.clone()));
3713 }
3714 }
3715 }
3716 if let Some(ref auth) = target.auth {
3718 if let Some(existing) =
3719 merged_headers.iter_mut().find(|(n, _)| n.eq_ignore_ascii_case("Authorization"))
3720 {
3721 existing.1 = auth.clone();
3722 } else {
3723 merged_headers.push(("Authorization".to_string(), auth.clone()));
3724 }
3725 }
3726
3727 let target_dir = self.output.join(format!("target_{}", idx));
3733 std::fs::create_dir_all(&target_dir)?;
3734
3735 let config = ConformanceConfig {
3736 target_url: target.url.clone(),
3737 api_key: self.conformance_api_key.clone(),
3738 basic_auth: self.conformance_basic_auth.clone(),
3739 skip_tls_verify: self.skip_tls_verify,
3740 categories: categories.clone(),
3741 base_path: self.base_path.clone(),
3742 custom_headers: merged_headers,
3743 output_dir: Some(target_dir.clone()),
3744 all_operations: self.conformance_all_operations,
3745 custom_checks_file: self.conformance_custom.clone(),
3746 request_delay_ms: self.conformance_delay_ms,
3747 custom_filter: self.conformance_custom_filter.clone(),
3748 export_requests: self.export_requests,
3749 validate_requests: self.validate_requests,
3750 };
3751
3752 let target_start = std::time::Instant::now();
3753 let report = if self.use_k6 {
3754 if !K6Executor::is_k6_installed() {
3755 TerminalReporter::print_error("k6 is not installed");
3756 TerminalReporter::print_warning(
3757 "Install k6 from: https://k6.io/docs/get-started/installation/",
3758 );
3759 return Err(BenchError::K6NotFound);
3760 }
3761 K6Executor::warn_if_pre_v1().await;
3762
3763 let script = if let Some(ref annotated) = annotated_ops {
3764 let gen = crate::conformance::spec_driven::SpecDrivenConformanceGenerator::new(
3765 config.clone(),
3766 annotated.clone(),
3767 );
3768 let (script, _check_count) = gen.generate()?;
3769 script
3770 } else {
3771 let generator = ConformanceGenerator::new(config.clone());
3772 generator.generate()?
3773 };
3774
3775 let script_path = target_dir.join("k6-conformance.js");
3776 std::fs::write(&script_path, &script).map_err(|e| {
3777 BenchError::Other(format!("Failed to write conformance script: {}", e))
3778 })?;
3779 TerminalReporter::print_success(&format!(
3780 "Conformance script generated: {}",
3781 script_path.display()
3782 ));
3783
3784 TerminalReporter::print_progress(&format!(
3785 "Running conformance tests via k6 against {}...",
3786 target.url
3787 ));
3788 let k6 = K6Executor::new()?
3789 .with_local_ips(self.source_ips.join(","))
3790 .with_dns_policy(self.dns_policy.clone().unwrap_or_default());
3791 let api_port = 6565u16.saturating_add(idx as u16);
3793 k6.execute_with_port(&script_path, Some(&target_dir), self.verbose, Some(api_port))
3794 .await?;
3795
3796 let report_path = target_dir.join("conformance-report.json");
3797 if report_path.exists() {
3798 ConformanceReport::from_file(&report_path)?
3799 } else {
3800 TerminalReporter::print_warning(&format!(
3801 "Conformance report not generated for target {} (k6 handleSummary may not have run)",
3802 target.url
3803 ));
3804 continue;
3805 }
3806 } else {
3807 let mut executor =
3808 crate::conformance::executor::NativeConformanceExecutor::new(config)?;
3809
3810 let custom_only = annotated_ops.is_none() && self.conformance_custom.is_some();
3813 executor = if let Some(ref annotated) = annotated_ops {
3814 executor.with_spec_driven_checks(annotated)
3815 } else if custom_only {
3816 executor
3817 } else {
3818 executor.with_reference_checks()
3819 };
3820 executor = executor.with_custom_checks()?;
3821
3822 TerminalReporter::print_success(&format!(
3823 "Executing {} conformance checks against {}...",
3824 executor.check_count(),
3825 target.url
3826 ));
3827
3828 executor.execute().await?
3829 };
3830 let target_elapsed = target_start.elapsed();
3831
3832 let report_json = report.to_json();
3833
3834 let passed = report_json["summary"]["passed"].as_u64().unwrap_or(0) as usize;
3836 let failed = report_json["summary"]["failed"].as_u64().unwrap_or(0) as usize;
3837 let total_checks = passed + failed;
3838 let rate = if total_checks == 0 {
3839 0.0
3840 } else {
3841 (passed as f64 / total_checks as f64) * 100.0
3842 };
3843
3844 TerminalReporter::print_success(&format!(
3845 "Target {}: {}/{} passed ({:.1}%) in {:.1}s",
3846 target.url,
3847 passed,
3848 total_checks,
3849 rate,
3850 target_elapsed.as_secs_f64()
3851 ));
3852
3853 let target_report_path = target_dir.join("conformance-report.json");
3855 let report_str = serde_json::to_string_pretty(&report_json)
3856 .map_err(|e| BenchError::Other(format!("Failed to serialize report: {}", e)))?;
3857 std::fs::write(&target_report_path, &report_str)
3858 .map_err(|e| BenchError::Other(format!("Failed to write report: {}", e)))?;
3859
3860 let failure_details = report.failure_details();
3862 if !failure_details.is_empty() {
3863 let details_path = target_dir.join("conformance-failure-details.json");
3864 if let Ok(json) = serde_json::to_string_pretty(&failure_details) {
3865 let _ = std::fs::write(&details_path, json);
3866 }
3867 }
3868
3869 if self.validate_requests && self.export_requests && !self.spec.is_empty() {
3876 let n = crate::conformance::request_validator::validate_emitted_requests_with_base_path(
3877 &self.spec,
3878 &target_dir,
3879 self.base_path.as_deref(),
3880 )
3881 .await?;
3882 if n > 0 {
3883 TerminalReporter::print_warning(&format!(
3884 "Target {}: {} emitted request(s) violated the spec — see {}/conformance-request-violations.json",
3885 target.url,
3886 n,
3887 target_dir.display()
3888 ));
3889 }
3890 }
3891
3892 let owasp_coverage = report.owasp_coverage_data();
3894
3895 target_results.push(TargetResult {
3896 url: target.url.clone(),
3897 passed,
3898 failed,
3899 elapsed: target_elapsed,
3900 report_json,
3901 owasp_coverage,
3902 });
3903 }
3904
3905 let total_elapsed = total_start.elapsed();
3906
3907 println!("\n{}", "=".repeat(80));
3909 println!(" Multi-Target Conformance Summary");
3910 println!("{}", "=".repeat(80));
3911 println!(
3912 " {:<40} {:>8} {:>8} {:>8} {:>8}",
3913 "Target URL", "Passed", "Failed", "Rate", "Time"
3914 );
3915 println!(" {}", "-".repeat(76));
3916
3917 let mut total_passed = 0usize;
3918 let mut total_failed = 0usize;
3919
3920 for result in &target_results {
3921 let total_checks = result.passed + result.failed;
3922 let rate = if total_checks == 0 {
3923 0.0
3924 } else {
3925 (result.passed as f64 / total_checks as f64) * 100.0
3926 };
3927
3928 let display_url = if result.url.len() > 38 {
3930 format!("{}...", &result.url[..35])
3931 } else {
3932 result.url.clone()
3933 };
3934
3935 println!(
3936 " {:<40} {:>8} {:>8} {:>7.1}% {:>6.1}s",
3937 display_url,
3938 result.passed,
3939 result.failed,
3940 rate,
3941 result.elapsed.as_secs_f64()
3942 );
3943
3944 total_passed += result.passed;
3945 total_failed += result.failed;
3946 }
3947
3948 let grand_total = total_passed + total_failed;
3949 let overall_rate = if grand_total == 0 {
3950 0.0
3951 } else {
3952 (total_passed as f64 / grand_total as f64) * 100.0
3953 };
3954
3955 println!(" {}", "-".repeat(76));
3956 println!(
3957 " {:<40} {:>8} {:>8} {:>7.1}% {:>6.1}s",
3958 format!("TOTAL ({} targets)", num_targets),
3959 total_passed,
3960 total_failed,
3961 overall_rate,
3962 total_elapsed.as_secs_f64()
3963 );
3964 println!("{}", "=".repeat(80));
3965
3966 for result in &target_results {
3968 println!("\n OWASP API Security Top 10 Coverage for {}:", result.url);
3969 for entry in &result.owasp_coverage {
3970 let status = if !entry.tested {
3971 "-"
3972 } else if entry.all_passed {
3973 "pass"
3974 } else {
3975 "FAIL"
3976 };
3977 let via = if entry.via_categories.is_empty() {
3978 String::new()
3979 } else {
3980 format!(" (via {})", entry.via_categories.join(", "))
3981 };
3982 println!(" {:<12} {:<40} {}{}", entry.id, entry.name, status, via);
3983 }
3984 }
3985
3986 let per_target_summaries: Vec<serde_json::Value> = target_results
3988 .iter()
3989 .enumerate()
3990 .map(|(idx, r)| {
3991 let total_checks = r.passed + r.failed;
3992 let rate = if total_checks == 0 {
3993 0.0
3994 } else {
3995 (r.passed as f64 / total_checks as f64) * 100.0
3996 };
3997 let owasp_json: Vec<serde_json::Value> = r
3998 .owasp_coverage
3999 .iter()
4000 .map(|e| {
4001 serde_json::json!({
4002 "id": e.id,
4003 "name": e.name,
4004 "tested": e.tested,
4005 "all_passed": e.all_passed,
4006 "via_categories": e.via_categories,
4007 })
4008 })
4009 .collect();
4010 serde_json::json!({
4011 "target_url": r.url,
4012 "target_index": idx,
4013 "checks_passed": r.passed,
4014 "checks_failed": r.failed,
4015 "total_checks": total_checks,
4016 "pass_rate": rate,
4017 "elapsed_seconds": r.elapsed.as_secs_f64(),
4018 "report": r.report_json,
4019 "owasp_coverage": owasp_json,
4020 })
4021 })
4022 .collect();
4023
4024 let combined_summary = serde_json::json!({
4025 "total_targets": num_targets,
4026 "total_checks_passed": total_passed,
4027 "total_checks_failed": total_failed,
4028 "overall_pass_rate": overall_rate,
4029 "total_elapsed_seconds": total_elapsed.as_secs_f64(),
4030 "targets": per_target_summaries,
4031 });
4032
4033 let summary_path = self.output.join("multi-target-conformance-summary.json");
4034 let summary_str = serde_json::to_string_pretty(&combined_summary)
4035 .map_err(|e| BenchError::Other(format!("Failed to serialize summary: {}", e)))?;
4036 std::fs::write(&summary_path, &summary_str)
4037 .map_err(|e| BenchError::Other(format!("Failed to write summary: {}", e)))?;
4038 TerminalReporter::print_success(&format!(
4039 "Combined summary saved to: {}",
4040 summary_path.display()
4041 ));
4042
4043 Ok(())
4044 }
4045
4046 async fn execute_owasp_test(&self, parser: &SpecParser) -> Result<()> {
4048 TerminalReporter::print_progress("OWASP API Security Top 10 Testing Mode");
4049
4050 let custom_headers = self.parse_headers()?;
4052
4053 let mut config = OwaspApiConfig::new()
4055 .with_auth_header(&self.owasp_auth_header)
4056 .with_verbose(self.verbose)
4057 .with_insecure(self.skip_tls_verify)
4058 .with_concurrency(self.vus as usize)
4059 .with_iterations(self.owasp_iterations as usize)
4060 .with_base_path(self.base_path.clone())
4061 .with_custom_headers(custom_headers);
4062
4063 if let Some(ref token) = self.owasp_auth_token {
4065 config = config.with_valid_auth_token(token);
4066 }
4067
4068 if let Some(ref cats_str) = self.owasp_categories {
4070 let categories: Vec<OwaspCategory> = cats_str
4071 .split(',')
4072 .filter_map(|s| {
4073 let trimmed = s.trim();
4074 match trimmed.parse::<OwaspCategory>() {
4075 Ok(cat) => Some(cat),
4076 Err(e) => {
4077 TerminalReporter::print_warning(&e);
4078 None
4079 }
4080 }
4081 })
4082 .collect();
4083
4084 if !categories.is_empty() {
4085 config = config.with_categories(categories);
4086 }
4087 }
4088
4089 if let Some(ref admin_paths_file) = self.owasp_admin_paths {
4091 config.admin_paths_file = Some(admin_paths_file.clone());
4092 if let Err(e) = config.load_admin_paths() {
4093 TerminalReporter::print_warning(&format!("Failed to load admin paths file: {}", e));
4094 }
4095 }
4096
4097 if let Some(ref id_fields_str) = self.owasp_id_fields {
4099 let id_fields: Vec<String> = id_fields_str
4100 .split(',')
4101 .map(|s| s.trim().to_string())
4102 .filter(|s| !s.is_empty())
4103 .collect();
4104 if !id_fields.is_empty() {
4105 config = config.with_id_fields(id_fields);
4106 }
4107 }
4108
4109 if let Some(ref report_path) = self.owasp_report {
4111 config = config.with_report_path(report_path);
4112 }
4113 if let Ok(format) = self.owasp_report_format.parse::<ReportFormat>() {
4114 config = config.with_report_format(format);
4115 }
4116
4117 let categories = config.categories_to_test();
4119 TerminalReporter::print_success(&format!(
4120 "Testing {} OWASP categories: {}",
4121 categories.len(),
4122 categories.iter().map(|c| c.cli_name()).collect::<Vec<_>>().join(", ")
4123 ));
4124
4125 if config.valid_auth_token.is_some() {
4126 TerminalReporter::print_progress("Using provided auth token for baseline requests");
4127 }
4128
4129 TerminalReporter::print_progress("Generating OWASP security test script...");
4131 let generator = OwaspApiGenerator::new(config, self.target.clone(), parser);
4132
4133 let script = generator.generate()?;
4135 TerminalReporter::print_success("OWASP security test script generated");
4136
4137 let script_path = if let Some(output) = &self.script_output {
4139 output.clone()
4140 } else {
4141 self.output.join("k6-owasp-security-test.js")
4142 };
4143
4144 if let Some(parent) = script_path.parent() {
4145 std::fs::create_dir_all(parent)?;
4146 }
4147 std::fs::write(&script_path, &script)?;
4148 TerminalReporter::print_success(&format!("Script written to: {}", script_path.display()));
4149
4150 if self.generate_only {
4152 println!("\nOWASP security test script generated. Run it with:");
4153 println!(" k6 run {}", script_path.display());
4154 return Ok(());
4155 }
4156
4157 TerminalReporter::print_progress("Executing OWASP security tests...");
4159 let executor = K6Executor::new()?
4160 .with_local_ips(self.source_ips.join(","))
4161 .with_dns_policy(self.dns_policy.clone().unwrap_or_default());
4162 std::fs::create_dir_all(&self.output)?;
4163
4164 let results = executor.execute(&script_path, Some(&self.output), self.verbose).await?;
4165
4166 let duration_secs = Self::parse_duration(&self.duration)?;
4167 TerminalReporter::print_summary_with_mode(&results, duration_secs, self.no_keep_alive);
4168
4169 println!("\nOWASP security test results saved to: {}", self.output.display());
4170
4171 Ok(())
4172 }
4173}
4174
4175#[cfg(test)]
4176mod tests {
4177 use super::*;
4178 use tempfile::tempdir;
4179
4180 #[test]
4181 fn test_parse_duration() {
4182 assert_eq!(BenchCommand::parse_duration("30s").unwrap(), 30);
4183 assert_eq!(BenchCommand::parse_duration("5m").unwrap(), 300);
4184 assert_eq!(BenchCommand::parse_duration("1h").unwrap(), 3600);
4185 assert_eq!(BenchCommand::parse_duration("60").unwrap(), 60);
4186 }
4187
4188 #[test]
4192 fn parse_ip_list_ipv4_range_inclusive() {
4193 let v = parse_ip_list(&["10.0.0.5-10.0.0.27".into()], "source-ip");
4194 assert_eq!(v.len(), 23);
4195 assert_eq!(v.first().unwrap().to_string(), "10.0.0.5");
4196 assert_eq!(v.last().unwrap().to_string(), "10.0.0.27");
4197 }
4198
4199 #[test]
4202 fn parse_ip_list_range_rejects_backwards() {
4203 let v = parse_ip_list(&["10.0.0.10-10.0.0.5".into()], "source-ip");
4204 assert!(v.is_empty(), "backwards range should produce no IPs; got {v:?}");
4205 }
4206
4207 #[test]
4211 fn parse_ip_list_rejects_ipv6_range_syntax() {
4212 let v = parse_ip_list(&["2001:db8::1-2001:db8::5".into()], "geo-source-ip");
4213 assert!(v.is_empty(), "IPv6 range should be rejected; got {v:?}");
4214 }
4215
4216 #[test]
4218 fn parse_ip_list_range_capped_at_256() {
4219 let v = parse_ip_list(&["10.0.0.0-10.0.5.0".into()], "source-ip");
4220 assert_eq!(v.len(), 256);
4221 assert_eq!(v.first().unwrap().to_string(), "10.0.0.0");
4222 }
4223
4224 #[test]
4227 fn parse_ip_list_plain_and_comma() {
4228 let v = parse_ip_list(&["10.0.0.5".into(), "10.0.0.6,10.0.0.7".into()], "source-ip");
4229 assert_eq!(v.len(), 3);
4230 assert_eq!(v[0].to_string(), "10.0.0.5");
4231 assert_eq!(v[2].to_string(), "10.0.0.7");
4232 }
4233
4234 #[test]
4237 fn parse_ip_list_ipv4_cidr_29_expands_to_8() {
4238 let v = parse_ip_list(&["10.0.0.0/29".into()], "source-ip");
4239 assert_eq!(v.len(), 8);
4240 assert_eq!(v[0].to_string(), "10.0.0.0");
4241 assert_eq!(v[7].to_string(), "10.0.0.7");
4242 }
4243
4244 #[test]
4247 fn parse_ip_list_ipv4_cidr_8_capped_at_256() {
4248 let v = parse_ip_list(&["10.0.0.0/8".into()], "source-ip");
4249 assert_eq!(v.len(), 256);
4250 assert_eq!(v[0].to_string(), "10.0.0.0");
4251 assert_eq!(v[255].to_string(), "10.0.0.255");
4252 }
4253
4254 #[test]
4256 fn parse_ip_list_ipv6_cidr_126_expands_to_4() {
4257 let v = parse_ip_list(&["2001:db8::/126".into()], "geo-source-ip");
4258 assert_eq!(v.len(), 4);
4259 assert!(v[0].is_ipv6());
4260 assert_eq!(v[0].to_string(), "2001:db8::");
4261 assert_eq!(v[3].to_string(), "2001:db8::3");
4262 }
4263
4264 #[test]
4266 fn parse_ip_list_mixed_v4_v6_cidr() {
4267 let v = parse_ip_list(&["10.0.0.0/30,2001:db8::1,203.0.113.42".into()], "geo-source-ip");
4268 assert_eq!(v.len(), 6); assert!(v.iter().any(|ip| ip.to_string() == "2001:db8::1"));
4270 assert!(v.iter().any(|ip| ip.to_string() == "203.0.113.42"));
4271 }
4272
4273 #[test]
4276 fn parse_ip_list_skips_malformed() {
4277 let v = parse_ip_list(
4278 &[
4279 "10.0.0.5".into(),
4280 "not-an-ip".into(),
4281 "10.0.0.6".into(),
4282 "/24".into(),
4283 "1.2.3.4/200".into(),
4284 ],
4285 "source-ip",
4286 );
4287 assert_eq!(v.len(), 2);
4288 assert_eq!(v[0].to_string(), "10.0.0.5");
4289 assert_eq!(v[1].to_string(), "10.0.0.6");
4290 }
4291
4292 #[test]
4293 fn test_parse_duration_invalid() {
4294 assert!(BenchCommand::parse_duration("invalid").is_err());
4295 assert!(BenchCommand::parse_duration("30x").is_err());
4296 }
4297
4298 #[test]
4299 fn test_parse_headers() {
4300 let cmd = BenchCommand {
4301 spec: vec![PathBuf::from("test.yaml")],
4302 spec_dir: None,
4303 merge_conflicts: "error".to_string(),
4304 spec_mode: "merge".to_string(),
4305 dependency_config: None,
4306 target: "http://localhost".to_string(),
4307 base_path: None,
4308 duration: "1m".to_string(),
4309 vus: 10,
4310 scenario: "ramp-up".to_string(),
4311 operations: None,
4312 exclude_operations: None,
4313 auth: None,
4314 headers: vec![
4315 "X-API-Key:test123".to_string(),
4316 "X-Client-ID:client456".to_string(),
4317 ],
4318 output: PathBuf::from("output"),
4319 generate_only: false,
4320 script_output: None,
4321 threshold_percentile: "p(95)".to_string(),
4322 threshold_ms: 500,
4323 max_error_rate: 0.05,
4324 abort_on_error: true,
4325 abort_on_error_rate: 0.95,
4326 verbose: false,
4327 skip_tls_verify: false,
4328 chunked_request_bodies: false,
4329 target_rps: None,
4330 no_keep_alive: false,
4331 targets_file: None,
4332 max_concurrency: None,
4333 results_format: "both".to_string(),
4334 params_file: None,
4335 crud_flow: false,
4336 flow_config: None,
4337 extract_fields: None,
4338 parallel_create: None,
4339 data_file: None,
4340 data_distribution: "unique-per-vu".to_string(),
4341 data_mappings: None,
4342 per_uri_control: false,
4343 error_rate: None,
4344 error_types: None,
4345 security_test: false,
4346 security_payloads: None,
4347 security_categories: None,
4348 security_target_fields: None,
4349 wafbench_dir: None,
4350 wafbench_cycle_all: false,
4351 wafbench_verbatim: false,
4352 owasp_api_top10: false,
4353 owasp_categories: None,
4354 owasp_auth_header: "Authorization".to_string(),
4355 owasp_auth_token: None,
4356 owasp_admin_paths: None,
4357 owasp_id_fields: None,
4358 owasp_report: None,
4359 owasp_report_format: "json".to_string(),
4360 owasp_iterations: 1,
4361 conformance: false,
4362 conformance_api_key: None,
4363 conformance_basic_auth: None,
4364 conformance_report: PathBuf::from("conformance-report.json"),
4365 conformance_categories: None,
4366 conformance_report_format: "json".to_string(),
4367 conformance_headers: vec![],
4368 conformance_all_operations: false,
4369 conformance_custom: None,
4370 conformance_delay_ms: 0,
4371 use_k6: false,
4372 conformance_custom_filter: None,
4373 export_requests: false,
4374 validate_requests: false,
4375 conformance_self_test: false,
4376 conformance_self_test_capture: false,
4377 conformance_self_test_iterations: 1,
4378 conformance_self_test_duration: None,
4379 validate_response_schemas: false,
4380 source_ips: Vec::new(),
4381 geo_source_ips: Vec::new(),
4382 geo_source_headers: Vec::new(),
4383 report_missed_cap: None,
4384 discard_response_bodies: false,
4385 dns_policy: None,
4386 };
4387
4388 let headers = cmd.parse_headers().unwrap();
4389 assert_eq!(headers.get("X-API-Key"), Some(&"test123".to_string()));
4390 assert_eq!(headers.get("X-Client-ID"), Some(&"client456".to_string()));
4391 }
4392
4393 #[test]
4394 fn test_parse_header_string_preserves_comma_in_value() {
4395 let inputs = vec![
4398 "Cookie:session=abc; expires=Thu, 01 Jan 2099 00:00:00 GMT".to_string(),
4399 "X-Trace:1".to_string(),
4400 ];
4401 let headers = parse_header_string(&inputs).unwrap();
4402 assert_eq!(
4403 headers.get("Cookie"),
4404 Some(&"session=abc; expires=Thu, 01 Jan 2099 00:00:00 GMT".to_string())
4405 );
4406 assert_eq!(headers.get("X-Trace"), Some(&"1".to_string()));
4407 }
4408
4409 #[test]
4417 fn conformance_advisory_names_every_discarded_flag() {
4418 let msg = CONFORMANCE_REPLACES_LOAD_ADVISORY;
4419 for flag in ["--vus", "--rps", "-d"] {
4420 assert!(
4421 msg.contains(flag),
4422 "conformance advisory must name `{flag}` as ignored; it is discarded on that \
4423 path and silently dropping it is how users end up tuning a knob that does \
4424 nothing (#980). Message was: {msg}"
4425 );
4426 }
4427 assert!(
4428 msg.contains("REPLACES"),
4429 "conformance advisory must say the load run is REPLACED, not merely that some \
4430 flags are ignored — `--conformance` returns before the load path runs, so no \
4431 load traffic is generated at all (#980). Message was: {msg}"
4432 );
4433 }
4434
4435 #[test]
4449 fn multi_target_clone_preserves_fields_parse_headers_reads() {
4450 let src = include_str!("command.rs");
4451
4452 let fn_start = src
4453 .find("async fn execute_multi_target(")
4454 .expect("execute_multi_target should exist");
4455 let block_start = src[fn_start..]
4456 .find("ParallelExecutor::new(")
4457 .map(|i| i + fn_start)
4458 .expect("multi-target path should build a ParallelExecutor");
4459 let block_end = src[block_start..]
4461 .find("\n );")
4462 .map(|i| i + block_start)
4463 .expect("ParallelExecutor::new(..) should be closed");
4464 let block = &src[block_start..block_end];
4465
4466 for field in ["conformance_basic_auth", "conformance_headers"] {
4469 for zeroed in [format!("{field}: None"), format!("{field}: vec![]")] {
4470 assert!(
4471 !block.contains(&zeroed),
4472 "execute_multi_target zeroes `{zeroed}`. parse_headers() folds `{field}` \
4473 into the header map, so zeroing it here strips auth from every \
4474 multi-target run while single-target keeps working (#79 round 64)."
4475 );
4476 }
4477 let passthrough = format!("{field}: self.{field}.clone()");
4478 assert!(
4479 block.contains(&passthrough),
4480 "execute_multi_target must carry `{field}` through as `{passthrough}` so \
4481 parse_headers() can fold it (#79 round 64)."
4482 );
4483 }
4484 }
4485
4486 #[test]
4487 fn test_get_spec_display_name() {
4488 let cmd = BenchCommand {
4489 spec: vec![PathBuf::from("test.yaml")],
4490 spec_dir: None,
4491 merge_conflicts: "error".to_string(),
4492 spec_mode: "merge".to_string(),
4493 dependency_config: None,
4494 target: "http://localhost".to_string(),
4495 base_path: None,
4496 duration: "1m".to_string(),
4497 vus: 10,
4498 scenario: "ramp-up".to_string(),
4499 operations: None,
4500 exclude_operations: None,
4501 auth: None,
4502 headers: Vec::new(),
4503 output: PathBuf::from("output"),
4504 generate_only: false,
4505 script_output: None,
4506 threshold_percentile: "p(95)".to_string(),
4507 threshold_ms: 500,
4508 max_error_rate: 0.05,
4509 abort_on_error: true,
4510 abort_on_error_rate: 0.95,
4511 verbose: false,
4512 skip_tls_verify: false,
4513 chunked_request_bodies: false,
4514 target_rps: None,
4515 no_keep_alive: false,
4516 targets_file: None,
4517 max_concurrency: None,
4518 results_format: "both".to_string(),
4519 params_file: None,
4520 crud_flow: false,
4521 flow_config: None,
4522 extract_fields: None,
4523 parallel_create: None,
4524 data_file: None,
4525 data_distribution: "unique-per-vu".to_string(),
4526 data_mappings: None,
4527 per_uri_control: false,
4528 error_rate: None,
4529 error_types: None,
4530 security_test: false,
4531 security_payloads: None,
4532 security_categories: None,
4533 security_target_fields: None,
4534 wafbench_dir: None,
4535 wafbench_cycle_all: false,
4536 wafbench_verbatim: false,
4537 owasp_api_top10: false,
4538 owasp_categories: None,
4539 owasp_auth_header: "Authorization".to_string(),
4540 owasp_auth_token: None,
4541 owasp_admin_paths: None,
4542 owasp_id_fields: None,
4543 owasp_report: None,
4544 owasp_report_format: "json".to_string(),
4545 owasp_iterations: 1,
4546 conformance: false,
4547 conformance_api_key: None,
4548 conformance_basic_auth: None,
4549 conformance_report: PathBuf::from("conformance-report.json"),
4550 conformance_categories: None,
4551 conformance_report_format: "json".to_string(),
4552 conformance_headers: vec![],
4553 conformance_all_operations: false,
4554 conformance_custom: None,
4555 conformance_delay_ms: 0,
4556 use_k6: false,
4557 conformance_custom_filter: None,
4558 export_requests: false,
4559 validate_requests: false,
4560 conformance_self_test: false,
4561 conformance_self_test_capture: false,
4562 conformance_self_test_iterations: 1,
4563 conformance_self_test_duration: None,
4564 validate_response_schemas: false,
4565 source_ips: Vec::new(),
4566 geo_source_ips: Vec::new(),
4567 geo_source_headers: Vec::new(),
4568 report_missed_cap: None,
4569 discard_response_bodies: false,
4570 dns_policy: None,
4571 };
4572
4573 assert_eq!(cmd.get_spec_display_name(), "test.yaml");
4574
4575 let cmd_multi = BenchCommand {
4577 spec: vec![PathBuf::from("a.yaml"), PathBuf::from("b.yaml")],
4578 spec_dir: None,
4579 merge_conflicts: "error".to_string(),
4580 spec_mode: "merge".to_string(),
4581 dependency_config: None,
4582 target: "http://localhost".to_string(),
4583 base_path: None,
4584 duration: "1m".to_string(),
4585 vus: 10,
4586 scenario: "ramp-up".to_string(),
4587 operations: None,
4588 exclude_operations: None,
4589 auth: None,
4590 headers: Vec::new(),
4591 output: PathBuf::from("output"),
4592 generate_only: false,
4593 script_output: None,
4594 threshold_percentile: "p(95)".to_string(),
4595 threshold_ms: 500,
4596 max_error_rate: 0.05,
4597 abort_on_error: true,
4598 abort_on_error_rate: 0.95,
4599 verbose: false,
4600 skip_tls_verify: false,
4601 chunked_request_bodies: false,
4602 target_rps: None,
4603 no_keep_alive: false,
4604 targets_file: None,
4605 max_concurrency: None,
4606 results_format: "both".to_string(),
4607 params_file: None,
4608 crud_flow: false,
4609 flow_config: None,
4610 extract_fields: None,
4611 parallel_create: None,
4612 data_file: None,
4613 data_distribution: "unique-per-vu".to_string(),
4614 data_mappings: None,
4615 per_uri_control: false,
4616 error_rate: None,
4617 error_types: None,
4618 security_test: false,
4619 security_payloads: None,
4620 security_categories: None,
4621 security_target_fields: None,
4622 wafbench_dir: None,
4623 wafbench_cycle_all: false,
4624 wafbench_verbatim: false,
4625 owasp_api_top10: false,
4626 owasp_categories: None,
4627 owasp_auth_header: "Authorization".to_string(),
4628 owasp_auth_token: None,
4629 owasp_admin_paths: None,
4630 owasp_id_fields: None,
4631 owasp_report: None,
4632 owasp_report_format: "json".to_string(),
4633 owasp_iterations: 1,
4634 conformance: false,
4635 conformance_api_key: None,
4636 conformance_basic_auth: None,
4637 conformance_report: PathBuf::from("conformance-report.json"),
4638 conformance_categories: None,
4639 conformance_report_format: "json".to_string(),
4640 conformance_headers: vec![],
4641 conformance_all_operations: false,
4642 conformance_custom: None,
4643 conformance_delay_ms: 0,
4644 use_k6: false,
4645 conformance_custom_filter: None,
4646 export_requests: false,
4647 validate_requests: false,
4648 conformance_self_test: false,
4649 conformance_self_test_capture: false,
4650 conformance_self_test_iterations: 1,
4651 conformance_self_test_duration: None,
4652 validate_response_schemas: false,
4653 source_ips: Vec::new(),
4654 geo_source_ips: Vec::new(),
4655 geo_source_headers: Vec::new(),
4656 report_missed_cap: None,
4657 discard_response_bodies: false,
4658 dns_policy: None,
4659 };
4660
4661 assert_eq!(cmd_multi.get_spec_display_name(), "2 spec files");
4662 }
4663
4664 #[test]
4665 fn test_parse_extracted_values_from_output_dir() {
4666 let dir = tempdir().unwrap();
4667 let path = dir.path().join("extracted_values.json");
4668 std::fs::write(
4669 &path,
4670 r#"{
4671 "pool_id": "abc123",
4672 "count": 0,
4673 "enabled": false,
4674 "metadata": { "owner": "team-a" }
4675}"#,
4676 )
4677 .unwrap();
4678
4679 let extracted = BenchCommand::parse_extracted_values(dir.path()).unwrap();
4680 assert_eq!(extracted.get("pool_id"), Some(&serde_json::json!("abc123")));
4681 assert_eq!(extracted.get("count"), Some(&serde_json::json!(0)));
4682 assert_eq!(extracted.get("enabled"), Some(&serde_json::json!(false)));
4683 assert_eq!(extracted.get("metadata"), Some(&serde_json::json!({"owner": "team-a"})));
4684 }
4685
4686 #[test]
4687 fn test_parse_extracted_values_missing_file() {
4688 let dir = tempdir().unwrap();
4689 let extracted = BenchCommand::parse_extracted_values(dir.path()).unwrap();
4690 assert!(extracted.values.is_empty());
4691 }
4692
4693 fn sample_bench_command() -> BenchCommand {
4696 BenchCommand {
4697 spec: vec![PathBuf::from("test.yaml")],
4698 spec_dir: None,
4699 merge_conflicts: "error".to_string(),
4700 spec_mode: "merge".to_string(),
4701 dependency_config: None,
4702 target: "http://localhost".to_string(),
4703 base_path: None,
4704 duration: "1m".to_string(),
4705 vus: 10,
4706 scenario: "ramp-up".to_string(),
4707 operations: None,
4708 exclude_operations: None,
4709 auth: None,
4710 headers: vec![
4711 "X-API-Key:test123".to_string(),
4712 "X-Client-ID:client456".to_string(),
4713 ],
4714 output: PathBuf::from("output"),
4715 generate_only: false,
4716 script_output: None,
4717 threshold_percentile: "p(95)".to_string(),
4718 threshold_ms: 500,
4719 max_error_rate: 0.05,
4720 abort_on_error: true,
4721 abort_on_error_rate: 0.95,
4722 verbose: false,
4723 skip_tls_verify: false,
4724 chunked_request_bodies: false,
4725 target_rps: None,
4726 no_keep_alive: false,
4727 targets_file: None,
4728 max_concurrency: None,
4729 results_format: "both".to_string(),
4730 params_file: None,
4731 crud_flow: false,
4732 flow_config: None,
4733 extract_fields: None,
4734 parallel_create: None,
4735 data_file: None,
4736 data_distribution: "unique-per-vu".to_string(),
4737 data_mappings: None,
4738 per_uri_control: false,
4739 error_rate: None,
4740 error_types: None,
4741 security_test: false,
4742 security_payloads: None,
4743 security_categories: None,
4744 security_target_fields: None,
4745 wafbench_dir: None,
4746 wafbench_cycle_all: false,
4747 wafbench_verbatim: false,
4748 owasp_api_top10: false,
4749 owasp_categories: None,
4750 owasp_auth_header: "Authorization".to_string(),
4751 owasp_auth_token: None,
4752 owasp_admin_paths: None,
4753 owasp_id_fields: None,
4754 owasp_report: None,
4755 owasp_report_format: "json".to_string(),
4756 owasp_iterations: 1,
4757 conformance: false,
4758 conformance_api_key: None,
4759 conformance_basic_auth: None,
4760 conformance_report: PathBuf::from("conformance-report.json"),
4761 conformance_categories: None,
4762 conformance_report_format: "json".to_string(),
4763 conformance_headers: vec![],
4764 conformance_all_operations: false,
4765 conformance_custom: None,
4766 conformance_delay_ms: 0,
4767 use_k6: false,
4768 conformance_custom_filter: None,
4769 export_requests: false,
4770 validate_requests: false,
4771 conformance_self_test: false,
4772 conformance_self_test_capture: false,
4773 conformance_self_test_iterations: 1,
4774 conformance_self_test_duration: None,
4775 validate_response_schemas: false,
4776 source_ips: Vec::new(),
4777 geo_source_ips: Vec::new(),
4778 geo_source_headers: Vec::new(),
4779 report_missed_cap: None,
4780 discard_response_bodies: false,
4781 dns_policy: None,
4782 }
4783 }
4784
4785 #[test]
4793 fn verbatim_disables_security_payload_injection() {
4794 let mut cmd = sample_bench_command();
4795 cmd.wafbench_dir = Some("traffic.yaml".to_string());
4796
4797 assert!(
4798 cmd.security_testing_enabled(),
4799 "--wafbench-dir alone must still enable payload injection"
4800 );
4801
4802 cmd.wafbench_verbatim = true;
4803 assert!(
4804 !cmd.security_testing_enabled(),
4805 "verbatim mode must not inject payloads into requests sent as written"
4806 );
4807
4808 cmd.security_test = true;
4811 assert!(
4812 !cmd.security_testing_enabled(),
4813 "--security-test must not re-enable injection under --wafbench-verbatim"
4814 );
4815 }
4816
4817 #[test]
4822 fn security_testing_enabled_has_a_single_definition() {
4823 let src = include_str!("command.rs");
4824 let parallel = include_str!("parallel_executor.rs");
4825 let a = format!("self.{} || self.{}.is_some()", "security_test", "wafbench_dir");
4827 let b = format!("self.{}.is_some() || self.{}", "wafbench_dir", "security_test");
4828 let inline = src.matches(a.as_str()).count() + src.matches(b.as_str()).count();
4829 assert_eq!(
4830 inline, 1,
4831 "expected the security_testing_enabled() method to be the only place this is \
4832 computed, found {inline} inline copies -- collapse them or the render paths drift"
4833 );
4834
4835 let parallel_inline = format!(
4840 "{}.{} || {}.{}.is_some()",
4841 "base_command", "security_test", "self.base_command", "wafbench_dir"
4842 );
4843 assert!(
4844 !parallel.contains(¶llel_inline),
4845 "ParallelExecutor must not recompute the security flag inline"
4846 );
4847 assert!(
4848 parallel.contains("security_testing_enabled()"),
4849 "ParallelExecutor must call security_testing_enabled() so --wafbench-verbatim \
4850 turns injection off on --targets-file runs too"
4851 );
4852 }
4853
4854 #[test]
4859 fn multi_target_path_honors_verbatim_templates() {
4860 let src = include_str!("parallel_executor.rs");
4861 assert!(
4862 src.contains("load_verbatim_templates"),
4863 "ParallelExecutor must load traffic-file requests under --wafbench-verbatim. \
4864 Requiring a spec and generating templates from its operations is how \
4865 --targets-file ignored the flag and fuzzed spec URLs (#79)."
4866 );
4867 }
4868}