Skip to main content

mockforge_bench/conformance/
spec_driven.rs

1//! Spec-driven conformance testing
2//!
3//! Analyzes the user's OpenAPI spec to determine which features their API uses,
4//! then generates k6 conformance tests against their real endpoints.
5
6use super::generator::ConformanceConfig;
7use super::schema_validator::SchemaValidatorGenerator;
8use super::spec::ConformanceFeature;
9use crate::error::Result;
10use crate::request_gen::RequestGenerator;
11use crate::spec_parser::ApiOperation;
12use openapiv3::{
13    OpenAPI, Operation, Parameter, ParameterSchemaOrContent, ReferenceOr, RequestBody, Response,
14    Schema, SchemaKind, SecurityScheme, StringFormat, Type, VariantOrUnknownOrEmpty,
15};
16use std::collections::HashSet;
17
18/// Resolve `$ref` references against the OpenAPI components
19mod ref_resolver {
20    use super::*;
21
22    pub fn resolve_parameter<'a>(
23        param_ref: &'a ReferenceOr<Parameter>,
24        spec: &'a OpenAPI,
25    ) -> Option<&'a Parameter> {
26        match param_ref {
27            ReferenceOr::Item(param) => Some(param),
28            ReferenceOr::Reference { reference } => {
29                let name = reference.strip_prefix("#/components/parameters/")?;
30                let components = spec.components.as_ref()?;
31                match components.parameters.get(name)? {
32                    ReferenceOr::Item(param) => Some(param),
33                    ReferenceOr::Reference {
34                        reference: inner_ref,
35                    } => {
36                        // One level of recursive resolution
37                        let inner_name = inner_ref.strip_prefix("#/components/parameters/")?;
38                        match components.parameters.get(inner_name)? {
39                            ReferenceOr::Item(param) => Some(param),
40                            ReferenceOr::Reference { .. } => None,
41                        }
42                    }
43                }
44            }
45        }
46    }
47
48    pub fn resolve_request_body<'a>(
49        body_ref: &'a ReferenceOr<RequestBody>,
50        spec: &'a OpenAPI,
51    ) -> Option<&'a RequestBody> {
52        match body_ref {
53            ReferenceOr::Item(body) => Some(body),
54            ReferenceOr::Reference { reference } => {
55                let name = reference.strip_prefix("#/components/requestBodies/")?;
56                let components = spec.components.as_ref()?;
57                match components.request_bodies.get(name)? {
58                    ReferenceOr::Item(body) => Some(body),
59                    ReferenceOr::Reference {
60                        reference: inner_ref,
61                    } => {
62                        // One level of recursive resolution
63                        let inner_name = inner_ref.strip_prefix("#/components/requestBodies/")?;
64                        match components.request_bodies.get(inner_name)? {
65                            ReferenceOr::Item(body) => Some(body),
66                            ReferenceOr::Reference { .. } => None,
67                        }
68                    }
69                }
70            }
71        }
72    }
73
74    pub fn resolve_schema<'a>(
75        schema_ref: &'a ReferenceOr<Schema>,
76        spec: &'a OpenAPI,
77    ) -> Option<&'a Schema> {
78        resolve_schema_with_visited(schema_ref, spec, &mut HashSet::new())
79    }
80
81    fn resolve_schema_with_visited<'a>(
82        schema_ref: &'a ReferenceOr<Schema>,
83        spec: &'a OpenAPI,
84        visited: &mut HashSet<String>,
85    ) -> Option<&'a Schema> {
86        match schema_ref {
87            ReferenceOr::Item(schema) => Some(schema),
88            ReferenceOr::Reference { reference } => {
89                if !visited.insert(reference.clone()) {
90                    return None; // Cycle detected
91                }
92                let name = reference.strip_prefix("#/components/schemas/")?;
93                let components = spec.components.as_ref()?;
94                let nested = components.schemas.get(name)?;
95                resolve_schema_with_visited(nested, spec, visited)
96            }
97        }
98    }
99
100    /// Resolve a boxed schema reference (used by array items and object properties)
101    pub fn resolve_boxed_schema<'a>(
102        schema_ref: &'a ReferenceOr<Box<Schema>>,
103        spec: &'a OpenAPI,
104    ) -> Option<&'a Schema> {
105        match schema_ref {
106            ReferenceOr::Item(schema) => Some(schema.as_ref()),
107            ReferenceOr::Reference { reference } => {
108                // Delegate to the regular schema resolver
109                let name = reference.strip_prefix("#/components/schemas/")?;
110                let components = spec.components.as_ref()?;
111                let nested = components.schemas.get(name)?;
112                resolve_schema_with_visited(nested, spec, &mut HashSet::new())
113            }
114        }
115    }
116
117    pub fn resolve_response<'a>(
118        resp_ref: &'a ReferenceOr<Response>,
119        spec: &'a OpenAPI,
120    ) -> Option<&'a Response> {
121        match resp_ref {
122            ReferenceOr::Item(resp) => Some(resp),
123            ReferenceOr::Reference { reference } => {
124                let name = reference.strip_prefix("#/components/responses/")?;
125                let components = spec.components.as_ref()?;
126                match components.responses.get(name)? {
127                    ReferenceOr::Item(resp) => Some(resp),
128                    ReferenceOr::Reference {
129                        reference: inner_ref,
130                    } => {
131                        // One level of recursive resolution
132                        let inner_name = inner_ref.strip_prefix("#/components/responses/")?;
133                        match components.responses.get(inner_name)? {
134                            ReferenceOr::Item(resp) => Some(resp),
135                            ReferenceOr::Reference { .. } => None,
136                        }
137                    }
138                }
139            }
140        }
141    }
142}
143
144/// Resolved security scheme details for an operation
145#[derive(Debug, Clone)]
146pub enum SecuritySchemeInfo {
147    /// HTTP Bearer token
148    Bearer,
149    /// HTTP Basic auth
150    Basic,
151    /// API Key in header, query, or cookie
152    ApiKey {
153        location: ApiKeyLocation,
154        name: String,
155    },
156}
157
158/// Where an API key is transmitted
159#[derive(Debug, Clone, PartialEq)]
160pub enum ApiKeyLocation {
161    Header,
162    Query,
163    Cookie,
164}
165
166/// An API operation annotated with the conformance features it exercises
167#[derive(Debug, Clone)]
168pub struct AnnotatedOperation {
169    pub path: String,
170    pub method: String,
171    pub features: Vec<ConformanceFeature>,
172    pub request_body_content_type: Option<String>,
173    pub sample_body: Option<String>,
174    pub query_params: Vec<(String, String)>,
175    pub header_params: Vec<(String, String)>,
176    pub path_params: Vec<(String, String)>,
177    /// Response schema for validation (JSON string of the schema)
178    pub response_schema: Option<Schema>,
179    /// Round 25 — per-status response schemas (JSON values, pre-resolved
180    /// via $ref). Keyed by HTTP status code, populated for every
181    /// status declared in the spec that has an `application/json`
182    /// body. The self-test driver looks up the schema for each probe's
183    /// actual status and validates the response body against it
184    /// (closing round 21.3 / Srikanth's a2 / a3 ask). Empty when the
185    /// spec declares no JSON response bodies.
186    pub response_schemas: std::collections::BTreeMap<u16, serde_json::Value>,
187    /// Round 17.2 — the resolved request-body schema (application/json).
188    /// Used by the self-test driver to synthesise schema-aware
189    /// negative mutations (wrong type, min/max bounds, pattern, enum
190    /// out-of-range, required-field removal). Independent of
191    /// `sample_body`, which is the positive payload.
192    pub request_body_schema: Option<Schema>,
193    /// Security scheme details resolved from the OpenAPI spec
194    pub security_schemes: Vec<SecuritySchemeInfo>,
195}
196
197/// Generates spec-driven conformance k6 scripts
198pub struct SpecDrivenConformanceGenerator {
199    config: ConformanceConfig,
200    operations: Vec<AnnotatedOperation>,
201}
202
203impl SpecDrivenConformanceGenerator {
204    pub fn new(config: ConformanceConfig, operations: Vec<AnnotatedOperation>) -> Self {
205        Self { config, operations }
206    }
207
208    /// Annotate a list of API operations with conformance features
209    pub fn annotate_operations(
210        operations: &[ApiOperation],
211        spec: &OpenAPI,
212    ) -> Vec<AnnotatedOperation> {
213        operations.iter().map(|op| Self::annotate_operation(op, spec)).collect()
214    }
215
216    /// Analyze an operation and determine which conformance features it exercises
217    fn annotate_operation(op: &ApiOperation, spec: &OpenAPI) -> AnnotatedOperation {
218        let mut features = Vec::new();
219        let mut query_params = Vec::new();
220        let mut header_params = Vec::new();
221        let mut path_params = Vec::new();
222
223        // Detect HTTP method feature
224        match op.method.to_uppercase().as_str() {
225            "GET" => features.push(ConformanceFeature::MethodGet),
226            "POST" => features.push(ConformanceFeature::MethodPost),
227            "PUT" => features.push(ConformanceFeature::MethodPut),
228            "PATCH" => features.push(ConformanceFeature::MethodPatch),
229            "DELETE" => features.push(ConformanceFeature::MethodDelete),
230            "HEAD" => features.push(ConformanceFeature::MethodHead),
231            "OPTIONS" => features.push(ConformanceFeature::MethodOptions),
232            _ => {}
233        }
234
235        // Detect parameter features (resolves $ref)
236        for param_ref in &op.operation.parameters {
237            if let Some(param) = ref_resolver::resolve_parameter(param_ref, spec) {
238                Self::annotate_parameter(
239                    param,
240                    spec,
241                    &mut features,
242                    &mut query_params,
243                    &mut header_params,
244                    &mut path_params,
245                );
246            }
247        }
248
249        // Detect path parameters from the path template itself
250        for segment in op.path.split('/') {
251            if segment.starts_with('{') && segment.ends_with('}') {
252                let name = &segment[1..segment.len() - 1];
253                // Only add if not already found from parameters
254                if !path_params.iter().any(|(n, _)| n == name) {
255                    path_params.push((name.to_string(), "test-value".to_string()));
256                    // Determine type from path params we didn't already handle
257                    if !features.contains(&ConformanceFeature::PathParamString)
258                        && !features.contains(&ConformanceFeature::PathParamInteger)
259                    {
260                        features.push(ConformanceFeature::PathParamString);
261                    }
262                }
263            }
264        }
265
266        // Detect request body features (resolves $ref)
267        let mut request_body_content_type = None;
268        let mut sample_body = None;
269        let mut request_body_schema: Option<Schema> = None;
270
271        let resolved_body = op
272            .operation
273            .request_body
274            .as_ref()
275            .and_then(|b| ref_resolver::resolve_request_body(b, spec));
276
277        if let Some(body) = resolved_body {
278            for (content_type, _media) in &body.content {
279                match content_type.as_str() {
280                    "application/json" => {
281                        features.push(ConformanceFeature::BodyJson);
282                        request_body_content_type = Some("application/json".to_string());
283                        // Generate sample body from schema
284                        if let Ok(template) = RequestGenerator::generate_template(op) {
285                            if let Some(body_val) = &template.body {
286                                sample_body = Some(body_val.to_string());
287                            }
288                        }
289                    }
290                    "application/x-www-form-urlencoded" => {
291                        features.push(ConformanceFeature::BodyFormUrlencoded);
292                        request_body_content_type =
293                            Some("application/x-www-form-urlencoded".to_string());
294                    }
295                    "multipart/form-data" => {
296                        features.push(ConformanceFeature::BodyMultipart);
297                        request_body_content_type = Some("multipart/form-data".to_string());
298                    }
299                    _ => {}
300                }
301            }
302
303            // Detect schema features in request body (resolves $ref in schema)
304            if let Some(media) = body.content.get("application/json") {
305                if let Some(schema_ref) = &media.schema {
306                    if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
307                        Self::annotate_schema(schema, spec, &mut features);
308                        // Round 17.2 — keep a clone of the resolved
309                        // body schema so the self-test driver can walk
310                        // it to synthesise schema-aware negatives.
311                        request_body_schema = Some(schema.clone());
312                    }
313                }
314            }
315        }
316
317        // Detect response code features
318        Self::annotate_responses(&op.operation, spec, &mut features);
319
320        // Extract response schema for validation (resolves $ref)
321        let response_schema = Self::extract_response_schema(&op.operation, spec);
322        if response_schema.is_some() {
323            features.push(ConformanceFeature::ResponseValidation);
324        }
325        // Round 25 — per-status response schema map (closes round 21.3).
326        let response_schemas = Self::extract_response_schemas_per_status(&op.operation, spec);
327
328        // Detect content negotiation (response with multiple content types)
329        Self::annotate_content_negotiation(&op.operation, spec, &mut features);
330
331        // Detect security features and resolve scheme details
332        let mut security_schemes = Vec::new();
333        Self::annotate_security(&op.operation, spec, &mut features, &mut security_schemes);
334
335        // Deduplicate features
336        features.sort_by_key(|f| f.check_name());
337        features.dedup_by_key(|f| f.check_name());
338
339        AnnotatedOperation {
340            path: op.path.clone(),
341            method: op.method.to_uppercase(),
342            features,
343            request_body_content_type,
344            sample_body,
345            query_params,
346            header_params,
347            path_params,
348            response_schema,
349            response_schemas,
350            request_body_schema,
351            security_schemes,
352        }
353    }
354
355    /// Annotate parameter features
356    fn annotate_parameter(
357        param: &Parameter,
358        spec: &OpenAPI,
359        features: &mut Vec<ConformanceFeature>,
360        query_params: &mut Vec<(String, String)>,
361        header_params: &mut Vec<(String, String)>,
362        path_params: &mut Vec<(String, String)>,
363    ) {
364        let (location, data) = match param {
365            Parameter::Query { parameter_data, .. } => ("query", parameter_data),
366            Parameter::Path { parameter_data, .. } => ("path", parameter_data),
367            Parameter::Header { parameter_data, .. } => ("header", parameter_data),
368            Parameter::Cookie { .. } => {
369                features.push(ConformanceFeature::CookieParam);
370                return;
371            }
372        };
373
374        // Detect type from schema
375        let is_integer = Self::param_schema_is_integer(data, spec);
376        let is_array = Self::param_schema_is_array(data, spec);
377
378        // Round 51 (#79) — generate a spec-VALID sample so the baseline probe
379        // doesn't trip spurious query/path violations on every probe (Srikanth
380        // on 0.3.196: a `request-body:content-type-mismatch:multipart` probe
381        // reported `query_value_mismatch` on `alt`/`prettyPrint` because every
382        // param was filled with the invalid literal "test-value"). Enum ->
383        // first member; boolean -> "true"; integer/number -> a valid number;
384        // array -> "a,b"; string formats -> a plausible valid value. Negative
385        // probes still override the specific param they attack.
386        let sample = Self::param_sample_value(data, spec);
387
388        match location {
389            "path" => {
390                if is_integer {
391                    features.push(ConformanceFeature::PathParamInteger);
392                } else {
393                    features.push(ConformanceFeature::PathParamString);
394                }
395                path_params.push((data.name.clone(), sample));
396            }
397            "query" => {
398                if is_array {
399                    features.push(ConformanceFeature::QueryParamArray);
400                } else if is_integer {
401                    features.push(ConformanceFeature::QueryParamInteger);
402                } else {
403                    features.push(ConformanceFeature::QueryParamString);
404                }
405                query_params.push((data.name.clone(), sample));
406            }
407            "header" => {
408                features.push(ConformanceFeature::HeaderParam);
409                header_params.push((data.name.clone(), sample));
410            }
411            _ => {}
412        }
413
414        // Check for constraint features on the parameter (resolves $ref)
415        if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
416            if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
417                Self::annotate_schema(schema, spec, features);
418            }
419        }
420
421        // Required/optional
422        if data.required {
423            features.push(ConformanceFeature::ConstraintRequired);
424        } else {
425            features.push(ConformanceFeature::ConstraintOptional);
426        }
427    }
428
429    fn param_schema_is_integer(data: &openapiv3::ParameterData, spec: &OpenAPI) -> bool {
430        if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
431            if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
432                return matches!(&schema.schema_kind, SchemaKind::Type(Type::Integer(_)));
433            }
434        }
435        false
436    }
437
438    fn param_schema_is_array(data: &openapiv3::ParameterData, spec: &OpenAPI) -> bool {
439        if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
440            if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
441                return matches!(&schema.schema_kind, SchemaKind::Type(Type::Array(_)));
442            }
443        }
444        false
445    }
446
447    /// Round 51 (#79) — a spec-VALID sample value for a parameter, used as the
448    /// baseline (positive) filler so a probe that isn't attacking a given
449    /// param doesn't trip a spurious violation on it. Falls back to the generic
450    /// "test-value" only when the schema doesn't constrain the value.
451    fn param_sample_value(data: &openapiv3::ParameterData, spec: &OpenAPI) -> String {
452        if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
453            if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
454                return Self::schema_sample_value(schema);
455            }
456        }
457        "test-value".to_string()
458    }
459
460    /// Produce a value that satisfies `schema`'s type / enum / format so the
461    /// server-side (and client-side) validator accepts it.
462    fn schema_sample_value(schema: &Schema) -> String {
463        match &schema.schema_kind {
464            SchemaKind::Type(Type::String(s)) => {
465                if let Some(first) = s.enumeration.iter().flatten().next() {
466                    return first.clone();
467                }
468                match &s.format {
469                    VariantOrUnknownOrEmpty::Item(StringFormat::Date) => "2024-01-01".to_string(),
470                    VariantOrUnknownOrEmpty::Item(StringFormat::DateTime) => {
471                        "2024-01-01T00:00:00Z".to_string()
472                    }
473                    VariantOrUnknownOrEmpty::Unknown(fmt) => match fmt.as_str() {
474                        "email" => "user@example.com".to_string(),
475                        "uuid" => "00000000-0000-0000-0000-000000000000".to_string(),
476                        "uri" | "url" => "https://example.com".to_string(),
477                        "ipv4" => "192.0.2.1".to_string(),
478                        "ipv6" => "2001:db8::1".to_string(),
479                        "hostname" => "example.com".to_string(),
480                        "byte" => "dGVzdA==".to_string(),
481                        _ => "test-value".to_string(),
482                    },
483                    _ => "test-value".to_string(),
484                }
485            }
486            SchemaKind::Type(Type::Integer(i)) => i
487                .enumeration
488                .iter()
489                .flatten()
490                .next()
491                .map(|v| v.to_string())
492                .unwrap_or_else(|| "42".to_string()),
493            SchemaKind::Type(Type::Number(n)) => n
494                .enumeration
495                .iter()
496                .flatten()
497                .next()
498                .map(|v| v.to_string())
499                .unwrap_or_else(|| "42".to_string()),
500            SchemaKind::Type(Type::Boolean(_)) => "true".to_string(),
501            SchemaKind::Type(Type::Array(_)) => "a,b".to_string(),
502            _ => "test-value".to_string(),
503        }
504    }
505
506    /// Annotate schema-level features (types, composition, formats, constraints)
507    fn annotate_schema(schema: &Schema, spec: &OpenAPI, features: &mut Vec<ConformanceFeature>) {
508        match &schema.schema_kind {
509            SchemaKind::Type(Type::String(s)) => {
510                features.push(ConformanceFeature::SchemaString);
511                // Check format
512                match &s.format {
513                    VariantOrUnknownOrEmpty::Item(StringFormat::Date) => {
514                        features.push(ConformanceFeature::FormatDate);
515                    }
516                    VariantOrUnknownOrEmpty::Item(StringFormat::DateTime) => {
517                        features.push(ConformanceFeature::FormatDateTime);
518                    }
519                    VariantOrUnknownOrEmpty::Unknown(fmt) => match fmt.as_str() {
520                        "email" => features.push(ConformanceFeature::FormatEmail),
521                        "uuid" => features.push(ConformanceFeature::FormatUuid),
522                        "uri" | "url" => features.push(ConformanceFeature::FormatUri),
523                        "ipv4" => features.push(ConformanceFeature::FormatIpv4),
524                        "ipv6" => features.push(ConformanceFeature::FormatIpv6),
525                        _ => {}
526                    },
527                    _ => {}
528                }
529                // Check constraints
530                if s.pattern.is_some() {
531                    features.push(ConformanceFeature::ConstraintPattern);
532                }
533                if !s.enumeration.is_empty() {
534                    features.push(ConformanceFeature::ConstraintEnum);
535                }
536                if s.min_length.is_some() || s.max_length.is_some() {
537                    features.push(ConformanceFeature::ConstraintMinMax);
538                }
539            }
540            SchemaKind::Type(Type::Integer(i)) => {
541                features.push(ConformanceFeature::SchemaInteger);
542                if i.minimum.is_some() || i.maximum.is_some() {
543                    features.push(ConformanceFeature::ConstraintMinMax);
544                }
545                if !i.enumeration.is_empty() {
546                    features.push(ConformanceFeature::ConstraintEnum);
547                }
548            }
549            SchemaKind::Type(Type::Number(n)) => {
550                features.push(ConformanceFeature::SchemaNumber);
551                if n.minimum.is_some() || n.maximum.is_some() {
552                    features.push(ConformanceFeature::ConstraintMinMax);
553                }
554            }
555            SchemaKind::Type(Type::Boolean(_)) => {
556                features.push(ConformanceFeature::SchemaBoolean);
557            }
558            SchemaKind::Type(Type::Array(arr)) => {
559                features.push(ConformanceFeature::SchemaArray);
560                if let Some(item_ref) = &arr.items {
561                    if let Some(item_schema) = ref_resolver::resolve_boxed_schema(item_ref, spec) {
562                        Self::annotate_schema(item_schema, spec, features);
563                    }
564                }
565            }
566            SchemaKind::Type(Type::Object(obj)) => {
567                features.push(ConformanceFeature::SchemaObject);
568                // Check required fields
569                if !obj.required.is_empty() {
570                    features.push(ConformanceFeature::ConstraintRequired);
571                }
572                // Walk properties (resolves $ref)
573                for (_name, prop_ref) in &obj.properties {
574                    if let Some(prop_schema) = ref_resolver::resolve_boxed_schema(prop_ref, spec) {
575                        Self::annotate_schema(prop_schema, spec, features);
576                    }
577                }
578            }
579            SchemaKind::OneOf { .. } => {
580                features.push(ConformanceFeature::CompositionOneOf);
581            }
582            SchemaKind::AnyOf { .. } => {
583                features.push(ConformanceFeature::CompositionAnyOf);
584            }
585            SchemaKind::AllOf { .. } => {
586                features.push(ConformanceFeature::CompositionAllOf);
587            }
588            _ => {}
589        }
590    }
591
592    /// Detect response code features (resolves $ref in responses)
593    fn annotate_responses(
594        operation: &Operation,
595        spec: &OpenAPI,
596        features: &mut Vec<ConformanceFeature>,
597    ) {
598        for (status_code, resp_ref) in &operation.responses.responses {
599            // Only count features for responses that actually resolve
600            if ref_resolver::resolve_response(resp_ref, spec).is_some() {
601                match status_code {
602                    openapiv3::StatusCode::Code(200) => {
603                        features.push(ConformanceFeature::Response200)
604                    }
605                    openapiv3::StatusCode::Code(201) => {
606                        features.push(ConformanceFeature::Response201)
607                    }
608                    openapiv3::StatusCode::Code(204) => {
609                        features.push(ConformanceFeature::Response204)
610                    }
611                    openapiv3::StatusCode::Code(400) => {
612                        features.push(ConformanceFeature::Response400)
613                    }
614                    openapiv3::StatusCode::Code(404) => {
615                        features.push(ConformanceFeature::Response404)
616                    }
617                    _ => {}
618                }
619            }
620        }
621    }
622
623    /// Round 25 — extract every declared response schema, keyed by the
624    /// numeric HTTP status. Only `application/json` content types are
625    /// included (the only body shape the self-test validates against).
626    /// Used by the self-test driver to validate response bodies against
627    /// the schema for the ACTUAL status returned, not just 200.
628    fn extract_response_schemas_per_status(
629        operation: &Operation,
630        spec: &OpenAPI,
631    ) -> std::collections::BTreeMap<u16, serde_json::Value> {
632        let mut out = std::collections::BTreeMap::new();
633        for (code, resp_ref) in &operation.responses.responses {
634            let openapiv3::StatusCode::Code(n) = code else {
635                continue; // skip "default" / range responses for now
636            };
637            let Some(response) = ref_resolver::resolve_response(resp_ref, spec) else {
638                continue;
639            };
640            let Some(media) = response.content.get("application/json") else {
641                continue;
642            };
643            let Some(schema_ref) = &media.schema else {
644                continue;
645            };
646            let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) else {
647                continue;
648            };
649            // Convert openapiv3::Schema → serde_json::Value so the
650            // validation step can hand it straight to jsonschema.
651            if let Ok(value) = serde_json::to_value(schema) {
652                out.insert(*n, value);
653            }
654        }
655        out
656    }
657
658    /// Extract the response schema for the primary success response (200 or 201)
659    /// Resolves $ref for both the response and the schema within it.
660    fn extract_response_schema(operation: &Operation, spec: &OpenAPI) -> Option<Schema> {
661        // Try 200 first, then 201
662        for code in [200u16, 201] {
663            if let Some(resp_ref) =
664                operation.responses.responses.get(&openapiv3::StatusCode::Code(code))
665            {
666                if let Some(response) = ref_resolver::resolve_response(resp_ref, spec) {
667                    if let Some(media) = response.content.get("application/json") {
668                        if let Some(schema_ref) = &media.schema {
669                            if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
670                                return Some(schema.clone());
671                            }
672                        }
673                    }
674                }
675            }
676        }
677        None
678    }
679
680    /// Detect content negotiation: response supports multiple content types
681    fn annotate_content_negotiation(
682        operation: &Operation,
683        spec: &OpenAPI,
684        features: &mut Vec<ConformanceFeature>,
685    ) {
686        for (_status_code, resp_ref) in &operation.responses.responses {
687            if let Some(response) = ref_resolver::resolve_response(resp_ref, spec) {
688                if response.content.len() > 1 {
689                    features.push(ConformanceFeature::ContentNegotiation);
690                    return; // Only need to detect once per operation
691                }
692            }
693        }
694    }
695
696    /// Detect security scheme features.
697    /// Checks operation-level security first, falling back to global security requirements.
698    /// Resolves scheme names against SecurityScheme definitions in components.
699    fn annotate_security(
700        operation: &Operation,
701        spec: &OpenAPI,
702        features: &mut Vec<ConformanceFeature>,
703        security_schemes: &mut Vec<SecuritySchemeInfo>,
704    ) {
705        // Use operation-level security if present, otherwise fall back to global
706        let security_reqs = operation.security.as_ref().or(spec.security.as_ref());
707
708        if let Some(security) = security_reqs {
709            for security_req in security {
710                for scheme_name in security_req.keys() {
711                    // Try to resolve the scheme from components for accurate type detection
712                    if let Some(resolved) = Self::resolve_security_scheme(scheme_name, spec) {
713                        match resolved {
714                            SecurityScheme::HTTP { ref scheme, .. } => {
715                                if scheme.eq_ignore_ascii_case("bearer") {
716                                    features.push(ConformanceFeature::SecurityBearer);
717                                    security_schemes.push(SecuritySchemeInfo::Bearer);
718                                } else if scheme.eq_ignore_ascii_case("basic") {
719                                    features.push(ConformanceFeature::SecurityBasic);
720                                    security_schemes.push(SecuritySchemeInfo::Basic);
721                                }
722                            }
723                            SecurityScheme::APIKey { location, name, .. } => {
724                                features.push(ConformanceFeature::SecurityApiKey);
725                                let loc = match location {
726                                    openapiv3::APIKeyLocation::Query => ApiKeyLocation::Query,
727                                    openapiv3::APIKeyLocation::Header => ApiKeyLocation::Header,
728                                    openapiv3::APIKeyLocation::Cookie => ApiKeyLocation::Cookie,
729                                };
730                                security_schemes.push(SecuritySchemeInfo::ApiKey {
731                                    location: loc,
732                                    name: name.clone(),
733                                });
734                            }
735                            // OAuth2 and OpenIDConnect don't map to our current feature set
736                            _ => {}
737                        }
738                    } else {
739                        // Fallback: heuristic name matching for unresolvable schemes
740                        let name_lower = scheme_name.to_lowercase();
741                        if name_lower.contains("bearer") || name_lower.contains("jwt") {
742                            features.push(ConformanceFeature::SecurityBearer);
743                            security_schemes.push(SecuritySchemeInfo::Bearer);
744                        } else if name_lower.contains("api") && name_lower.contains("key") {
745                            features.push(ConformanceFeature::SecurityApiKey);
746                            security_schemes.push(SecuritySchemeInfo::ApiKey {
747                                location: ApiKeyLocation::Header,
748                                name: "X-API-Key".to_string(),
749                            });
750                        } else if name_lower.contains("basic") {
751                            features.push(ConformanceFeature::SecurityBasic);
752                            security_schemes.push(SecuritySchemeInfo::Basic);
753                        }
754                    }
755                }
756            }
757        }
758    }
759
760    /// Resolve a security scheme name to its SecurityScheme definition
761    fn resolve_security_scheme<'a>(name: &str, spec: &'a OpenAPI) -> Option<&'a SecurityScheme> {
762        let components = spec.components.as_ref()?;
763        match components.security_schemes.get(name)? {
764            ReferenceOr::Item(scheme) => Some(scheme),
765            ReferenceOr::Reference { .. } => None,
766        }
767    }
768
769    /// Returns the number of operations being tested
770    pub fn operation_count(&self) -> usize {
771        self.operations.len()
772    }
773
774    /// Generate the k6 conformance script.
775    /// Returns (script, check_count) where check_count is the number of unique checks emitted.
776    pub fn generate(&self) -> Result<(String, usize)> {
777        let mut script = String::with_capacity(16384);
778
779        // Imports
780        script.push_str("import http from 'k6/http';\n");
781        script.push_str("import { check, group } from 'k6';\n");
782        if self.config.request_delay_ms > 0 {
783            script.push_str("import { sleep } from 'k6';\n");
784        }
785        script.push('\n');
786
787        // Tell k6 that all HTTP status codes are "expected" in conformance mode.
788        // Without this, k6 counts 4xx responses (e.g. intentional 404 tests) as
789        // http_req_failed errors, producing a misleading error rate percentage.
790        script.push_str(
791            "http.setResponseCallback(http.expectedStatuses({ min: 100, max: 599 }));\n\n",
792        );
793
794        // Options
795        script.push_str("export const options = {\n");
796        script.push_str("  vus: 1,\n");
797        script.push_str("  iterations: 1,\n");
798        if self.config.skip_tls_verify {
799            script.push_str("  insecureSkipTLSVerify: true,\n");
800        }
801        script.push_str("  thresholds: {\n");
802        script.push_str("    checks: ['rate>0'],\n");
803        script.push_str("  },\n");
804        script.push_str("};\n\n");
805
806        // Base URL (includes base_path if configured)
807        script.push_str(&format!("const BASE_URL = '{}';\n\n", self.config.effective_base_url()));
808        script.push_str("const JSON_HEADERS = { 'Content-Type': 'application/json' };\n\n");
809
810        // Round 39 (#79) — emit init-scope code (e.g. `open()` calls
811        // for file uploads in custom checks) here, before any
812        // function declarations.
813        let custom_emit = self.config.generate_custom_group()?;
814        if let Some(emit) = &custom_emit {
815            if !emit.init_code.is_empty() {
816                script.push_str("// Round 39 (#79) — preloaded upload bytes for custom checks\n");
817                script.push_str(&emit.init_code);
818                script.push('\n');
819            }
820        }
821
822        // Failure detail collector — logs req/res info for failed checks via console.log
823        // (k6's handleSummary runs in a separate JS context, so we can't use module-level arrays)
824        script
825            .push_str("function __captureFailure(checkName, res, expected, schemaViolations) {\n");
826        script.push_str("  let bodyStr = '';\n");
827        script.push_str("  try { if (res.body) { const __n = res.body.length; bodyStr = res.body.substring(0, 65536); if (__n > 65536) bodyStr = bodyStr + ' <truncated at 65536 bytes; full body was ' + __n + ' bytes>'; } else { bodyStr = ''; } } catch(e) { bodyStr = '<unreadable>'; }\n");
828        script.push_str("  let reqHeaders = {};\n");
829        script.push_str(
830            "  if (res.request && res.request.headers) { reqHeaders = res.request.headers; }\n",
831        );
832        script.push_str("  let reqBody = '';\n");
833        script.push_str("  if (res.request && res.request.body) { try { const __m = res.request.body.length; reqBody = res.request.body.substring(0, 65536); if (__m > 65536) reqBody = reqBody + ' <truncated at 65536 bytes; full body was ' + __m + ' bytes>'; } catch(e) {} }\n");
834        script.push_str("  let payload = {\n");
835        script.push_str("    check: checkName,\n");
836        script.push_str("    request: {\n");
837        script.push_str("      method: res.request ? res.request.method : 'unknown',\n");
838        script.push_str("      url: res.request ? res.request.url : res.url || 'unknown',\n");
839        script.push_str("      headers: reqHeaders,\n");
840        script.push_str("      body: reqBody,\n");
841        script.push_str("    },\n");
842        script.push_str("    response: {\n");
843        script.push_str("      status: res.status,\n");
844        script.push_str("      headers: res.headers ? Object.fromEntries(Object.entries(res.headers).slice(0, 20)) : {},\n");
845        script.push_str("      body: bodyStr,\n");
846        script.push_str("    },\n");
847        script.push_str("    expected: expected,\n");
848        script.push_str("  };\n");
849        script.push_str("  if (schemaViolations && schemaViolations.length > 0) { payload.schema_violations = schemaViolations; }\n");
850        script.push_str("  console.log('MOCKFORGE_FAILURE:' + JSON.stringify(payload));\n");
851        script.push_str("}\n\n");
852
853        // Request/response capture for --export-requests
854        //
855        // Round 44 (#79) — mirror the resilience added in `generator.rs`:
856        // wrap the primary stringify in try/catch + fall back to a minimal
857        // entry + last-resort hand-rolled JSON so a multipart body that
858        // contains bytes JSON.stringify can't roundtrip never silently
859        // drops the row from the export. See `generator.rs` for the
860        // surfacing incident.
861        if self.config.export_requests {
862            script.push_str("function __captureExchange(checkName, res) {\n");
863            script.push_str("  try {\n");
864            script.push_str("    let bodyStr = '';\n");
865            script.push_str("    try { if (res.body) { const __n = res.body.length; bodyStr = res.body.substring(0, 65536); if (__n > 65536) bodyStr = bodyStr + ' <truncated at 65536 bytes; full body was ' + __n + ' bytes>'; } else { bodyStr = ''; } } catch(e) { bodyStr = '<unreadable>'; }\n");
866            script.push_str("    let reqHeaders = {};\n");
867            script.push_str(
868                "    if (res.request && res.request.headers) { reqHeaders = res.request.headers; }\n",
869            );
870            // Round 46 (#79) — mirror the structured multipart summary
871            // from `generator.rs`. See the long comment there; same
872            // rationale (k6 logfmt mangling on raw binary bytes).
873            script.push_str("    let reqBody = '';\n");
874            script.push_str("    {\n");
875            script.push_str(
876                "      const ct = (reqHeaders['Content-Type'] || reqHeaders['content-type'] || '').toString();\n",
877            );
878            script.push_str("      const isMultipart = ct.startsWith('multipart/');\n");
879            script.push_str(
880                "      if (isMultipart && res.request && res.request.body) {\n\
881                 \x20\x20\x20\x20\x20\x20\x20\x20try {\n\
882                 \x20\x20\x20\x20\x20\x20\x20\x20  const raw = res.request.body;\n\
883                 \x20\x20\x20\x20\x20\x20\x20\x20  let totalBytes = raw.length;\n\
884                 \x20\x20\x20\x20\x20\x20\x20\x20  let envelopeBytes = 0;\n\
885                 \x20\x20\x20\x20\x20\x20\x20\x20  const boundaryMatch = ct.match(/boundary=([^;]+)/);\n\
886                 \x20\x20\x20\x20\x20\x20\x20\x20  const boundary = boundaryMatch ? boundaryMatch[1].replace(/^\"|\"$/g, '') : '';\n\
887                 \x20\x20\x20\x20\x20\x20\x20\x20  const parts = [];\n\
888                 \x20\x20\x20\x20\x20\x20\x20\x20  if (boundary) {\n\
889                 \x20\x20\x20\x20\x20\x20\x20\x20    const sep = '--' + boundary;\n\
890                 \x20\x20\x20\x20\x20\x20\x20\x20    let cursor = raw.indexOf(sep);\n\
891                 \x20\x20\x20\x20\x20\x20\x20\x20    while (cursor !== -1 && parts.length < 100) {\n\
892                 \x20\x20\x20\x20\x20\x20\x20\x20      const next = raw.indexOf(sep, cursor + sep.length);\n\
893                 \x20\x20\x20\x20\x20\x20\x20\x20      if (next === -1) break;\n\
894                 \x20\x20\x20\x20\x20\x20\x20\x20      const slice = raw.substring(cursor + sep.length, next);\n\
895                 \x20\x20\x20\x20\x20\x20\x20\x20      const headerEnd = slice.indexOf('\\r\\n\\r\\n');\n\
896                 \x20\x20\x20\x20\x20\x20\x20\x20      const partHeaders = headerEnd === -1 ? slice : slice.substring(0, headerEnd);\n\
897                 \x20\x20\x20\x20\x20\x20\x20\x20      const partBody = headerEnd === -1 ? '' : slice.substring(headerEnd + 4);\n\
898                 \x20\x20\x20\x20\x20\x20\x20\x20      // Round 50 #79 — ASCII envelope is byte-accurate (see generator.rs).\n\
899                 \x20\x20\x20\x20\x20\x20\x20\x20      envelopeBytes += sep.length + partHeaders.length + 6;\n\
900                 \x20\x20\x20\x20\x20\x20\x20\x20      const nameMatch = partHeaders.match(/name=\"([^\"]+)\"/);\n\
901                 \x20\x20\x20\x20\x20\x20\x20\x20      const filenameMatch = partHeaders.match(/filename=\"([^\"]+)\"/);\n\
902                 \x20\x20\x20\x20\x20\x20\x20\x20      const partCtMatch = partHeaders.match(/Content-Type:\\s*([^\\r\\n]+)/i);\n\
903                 \x20\x20\x20\x20\x20\x20\x20\x20      parts.push({\n\
904                 \x20\x20\x20\x20\x20\x20\x20\x20        name: nameMatch ? nameMatch[1] : '',\n\
905                 \x20\x20\x20\x20\x20\x20\x20\x20        filename: filenameMatch ? filenameMatch[1] : '',\n\
906                 \x20\x20\x20\x20\x20\x20\x20\x20        contentType: partCtMatch ? partCtMatch[1].trim() : '',\n\
907                 \x20\x20\x20\x20\x20\x20\x20\x20        bytes: Math.max(0, partBody.length - 2),\n\
908                 \x20\x20\x20\x20\x20\x20\x20\x20      });\n\
909                 \x20\x20\x20\x20\x20\x20\x20\x20      cursor = next;\n\
910                 \x20\x20\x20\x20\x20\x20\x20\x20    }\n\
911                 \x20\x20\x20\x20\x20\x20\x20\x20    if (parts.length) { envelopeBytes += sep.length + 4; }\n\
912                 \x20\x20\x20\x20\x20\x20\x20\x20  }\n\
913                 \x20\x20\x20\x20\x20\x20\x20\x20  // Round 47 #79 — overlay on-disk byte counts (see generator.rs).\n\
914                 \x20\x20\x20\x20\x20\x20\x20\x20  const __mfSizes = (globalThis.__mfUploadSizes || {})[checkName] || {};\n\
915                 \x20\x20\x20\x20\x20\x20\x20\x20  let __allKnown = parts.length > 0;\n\
916                 \x20\x20\x20\x20\x20\x20\x20\x20  parts.forEach(function (p) { if (typeof __mfSizes[p.name] === 'number') { p.bytes = __mfSizes[p.name]; } else { __allKnown = false; } });\n\
917                 \x20\x20\x20\x20\x20\x20\x20\x20  const partsTotal = parts.reduce(function (acc, p) { return acc + p.bytes; }, 0);\n\
918                 \x20\x20\x20\x20\x20\x20\x20\x20  if (__allKnown) totalBytes = partsTotal;\n\
919                 \x20\x20\x20\x20\x20\x20\x20\x20  // Round 49/50 #79 — total = disk-sum payload; wire = total +\n\
920                 \x20\x20\x20\x20\x20\x20\x20\x20  // ASCII envelope. raw.length UNDERcounts binary bodies, so\n\
921                 \x20\x20\x20\x20\x20\x20\x20\x20  // never use it for wire when part sizes are known.\n\
922                 \x20\x20\x20\x20\x20\x20\x20\x20  // Round 51 #79 — prefer k6's Content-Length (exact wire body\n\
923                 \x20\x20\x20\x20\x20\x20\x20\x20  // size, matches the proxy) over the reconstructed envelope.\n\
924                 \x20\x20\x20\x20\x20\x20\x20\x20  const __clHdr = parseInt((reqHeaders['Content-Length'] || reqHeaders['content-length'] || ''), 10);\n\
925                 \x20\x20\x20\x20\x20\x20\x20\x20  const wireBytes = (!isNaN(__clHdr) && __clHdr > 0) ? __clHdr : (__allKnown ? (partsTotal + envelopeBytes) : ((typeof raw === 'string' && raw.length) ? raw.length : totalBytes));\n\
926                 \x20\x20\x20\x20\x20\x20\x20\x20  const summary = parts.map(function (p) { return '\\'' + p.name + '\\':\\'' + p.filename + '\\' (' + p.contentType + ', ' + p.bytes + ' bytes)'; }).join(', ');\n\
927                 \x20\x20\x20\x20\x20\x20\x20\x20  reqBody = '<multipart/form-data; boundary=' + boundary + '; ' + parts.length + ' part(s); total ' + totalBytes + ' bytes (wire ' + wireBytes + ' bytes w/ envelope): ' + summary + '>';\n\
928                 \x20\x20\x20\x20\x20\x20\x20\x20} catch (e) {\n\
929                 \x20\x20\x20\x20\x20\x20\x20\x20  reqBody = '<multipart upload; summary failed: ' + (e && e.message ? e.message : 'unknown') + '>';\n\
930                 \x20\x20\x20\x20\x20\x20\x20\x20}\n\
931                 \x20\x20\x20\x20\x20\x20} else if (isMultipart) {\n\
932                 \x20\x20\x20\x20\x20\x20\x20\x20reqBody = '<multipart upload; body bytes not surfaced by k6 res.request.body>';\n\
933                 \x20\x20\x20\x20\x20\x20} else if (res.request && res.request.body) {\n\
934                 \x20\x20\x20\x20\x20\x20\x20\x20try { const __m = res.request.body.length; reqBody = res.request.body.substring(0, 65536); if (__m > 65536) reqBody = reqBody + ' <truncated at 65536 bytes; full body was ' + __m + ' bytes>'; } catch (e) {}\n\
935                 \x20\x20\x20\x20\x20\x20}\n\
936                 \x20\x20\x20\x20}\n",
937            );
938            // Round 47 (#79) — mirror network-event emit from generator.rs.
939            script.push_str(
940                "    if (res && res.status === 0) {\n\
941                 \x20\x20\x20\x20\x20\x20const ec = (res.error_code != null) ? res.error_code : 0;\n\
942                 \x20\x20\x20\x20\x20\x20const em = (res.error != null) ? String(res.error) : '';\n\
943                 \x20\x20\x20\x20\x20\x20let kind = 'other';\n\
944                 \x20\x20\x20\x20\x20\x20if (ec >= 1200 && ec < 1300) kind = 'connect';\n\
945                 \x20\x20\x20\x20\x20\x20else if (ec >= 1300 && ec < 1400) kind = 'tls';\n\
946                 \x20\x20\x20\x20\x20\x20else if (ec >= 1400 && ec < 1500) kind = 'timeout';\n\
947                 \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('eof') !== -1) kind = 'connect';\n                 \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('timeout') !== -1) kind = 'timeout';\n\
948                 \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('tls') !== -1) kind = 'tls';\n\
949                 \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('connect') !== -1 || em.toLowerCase().indexOf('refused') !== -1) kind = 'connect';\n\
950                 \x20\x20\x20\x20\x20\x20console.log('MOCKFORGE_NETWORK_EVENT:' + JSON.stringify({\n\
951                 \x20\x20\x20\x20\x20\x20  timestamp: new Date().toISOString(),\n\
952                 \x20\x20\x20\x20\x20\x20  check: checkName,\n\
953                 \x20\x20\x20\x20\x20\x20  method: res.request ? res.request.method : 'unknown',\n\
954                 \x20\x20\x20\x20\x20\x20  url: res.request ? res.request.url : res.url || 'unknown',\n\
955                 \x20\x20\x20\x20\x20\x20  kind: kind,\n\
956                 \x20\x20\x20\x20\x20\x20  error_code: ec,\n\
957                 \x20\x20\x20\x20\x20\x20  message: em,\n\
958                 \x20\x20\x20\x20\x20\x20}));\n\
959                 \x20\x20\x20\x20}\n",
960            );
961            script.push_str("    console.log('MOCKFORGE_EXCHANGE:' + JSON.stringify({\n");
962            script.push_str("      check: checkName,\n");
963            script.push_str("      request: {\n");
964            script.push_str("        method: res.request ? res.request.method : 'unknown',\n");
965            script.push_str("        url: res.request ? res.request.url : res.url || 'unknown',\n");
966            script.push_str("        headers: reqHeaders,\n");
967            script.push_str("        body: reqBody,\n");
968            script.push_str("      },\n");
969            script.push_str("      response: {\n");
970            script.push_str("        status: res.status,\n");
971            script.push_str("        headers: res.headers ? Object.fromEntries(Object.entries(res.headers).slice(0, 30)) : {},\n");
972            script.push_str("        body: bodyStr,\n");
973            script.push_str("      },\n");
974            script.push_str("    }));\n");
975            script.push_str("  } catch (e) {\n");
976            script.push_str("    try {\n");
977            script.push_str("      console.log('MOCKFORGE_EXCHANGE:' + JSON.stringify({\n");
978            script.push_str("        check: checkName,\n");
979            script.push_str("        request: {\n");
980            script.push_str(
981                "          method: (res && res.request) ? res.request.method : 'unknown',\n",
982            );
983            script.push_str("          url: (res && res.request) ? res.request.url : (res && res.url) || 'unknown',\n");
984            script.push_str("          headers: {},\n");
985            script.push_str("          body: '<exchange capture failed: ' + (e && e.message ? e.message : 'unknown error') + '>',\n");
986            script.push_str("        },\n");
987            script.push_str("        response: {\n");
988            script.push_str("          status: (res && res.status) || 0,\n");
989            script.push_str("          headers: {},\n");
990            script.push_str("          body: '',\n");
991            script.push_str("        },\n");
992            script.push_str("        _export_error: (e && e.message) ? e.message : String(e),\n");
993            script.push_str("      }));\n");
994            script.push_str("    } catch (e2) {\n");
995            script.push_str("      console.log('MOCKFORGE_EXCHANGE:{\"check\":\"' + checkName + '\",\"request\":{\"method\":\"unknown\",\"url\":\"unknown\",\"headers\":{},\"body\":\"\"},\"response\":{\"status\":0,\"headers\":{},\"body\":\"\"},\"_export_error\":\"double-fault\"}');\n");
996            script.push_str("    }\n");
997            script.push_str("  }\n");
998            script.push_str("}\n\n");
999        }
1000
1001        // Default function
1002        script.push_str("export default function () {\n");
1003
1004        if self.config.has_cookie_header() {
1005            script.push_str(
1006                "  // Clear cookie jar to prevent server Set-Cookie from duplicating custom Cookie header\n",
1007            );
1008            script.push_str("  http.cookieJar().clear(BASE_URL);\n\n");
1009        }
1010
1011        // Group operations by category
1012        let mut category_ops: std::collections::BTreeMap<
1013            &'static str,
1014            Vec<(&AnnotatedOperation, &ConformanceFeature)>,
1015        > = std::collections::BTreeMap::new();
1016
1017        for op in &self.operations {
1018            for feature in &op.features {
1019                let category = feature.category();
1020                if self.config.should_include_category(category) {
1021                    category_ops.entry(category).or_default().push((op, feature));
1022                }
1023            }
1024        }
1025
1026        // Emit grouped tests
1027        let mut total_checks = 0usize;
1028        for (category, ops) in &category_ops {
1029            script.push_str(&format!("  group('{}', function () {{\n", category));
1030
1031            if self.config.all_operations {
1032                // All-operations mode: test every operation, using path-qualified check names
1033                let mut emitted_checks: HashSet<String> = HashSet::new();
1034                for (op, feature) in ops {
1035                    let qualified = format!("{}:{}", feature.check_name(), op.path);
1036                    if emitted_checks.insert(qualified.clone()) {
1037                        self.emit_check_named(&mut script, op, feature, &qualified);
1038                        total_checks += 1;
1039                    }
1040                }
1041            } else {
1042                // Default: one representative operation per feature, with path-qualified
1043                // check names so failures identify which endpoint was tested.
1044                let mut emitted_features: HashSet<&str> = HashSet::new();
1045                for (op, feature) in ops {
1046                    if emitted_features.insert(feature.check_name()) {
1047                        let qualified = format!("{}:{}", feature.check_name(), op.path);
1048                        self.emit_check_named(&mut script, op, feature, &qualified);
1049                        total_checks += 1;
1050                    }
1051                }
1052            }
1053
1054            script.push_str("  });\n\n");
1055        }
1056
1057        // Custom checks from YAML file — round 39: init-scope code
1058        // was already emitted above; here we just splice the group
1059        // body inside the default function.
1060        if let Some(emit) = custom_emit {
1061            script.push_str(&emit.group_body);
1062        }
1063
1064        script.push_str("}\n\n");
1065
1066        // handleSummary
1067        self.generate_handle_summary(&mut script);
1068
1069        Ok((script, total_checks))
1070    }
1071
1072    /// Emit a single k6 check for an operation + feature with a custom check name
1073    fn emit_check_named(
1074        &self,
1075        script: &mut String,
1076        op: &AnnotatedOperation,
1077        feature: &ConformanceFeature,
1078        check_name: &str,
1079    ) {
1080        // Escape single quotes in check name since it's embedded in JS single-quoted strings
1081        let check_name = check_name.replace('\'', "\\'");
1082        let check_name = check_name.as_str();
1083
1084        script.push_str("    {\n");
1085
1086        // Build the URL path with parameters substituted
1087        let mut url_path = op.path.clone();
1088        for (name, value) in &op.path_params {
1089            url_path = url_path.replace(&format!("{{{}}}", name), value);
1090        }
1091
1092        // Build query string
1093        if !op.query_params.is_empty() {
1094            let qs: Vec<String> =
1095                op.query_params.iter().map(|(k, v)| format!("{}={}", k, v)).collect();
1096            url_path = format!("{}?{}", url_path, qs.join("&"));
1097        }
1098
1099        let full_url = format!("${{BASE_URL}}{}", url_path);
1100
1101        // Build effective headers: merge spec-derived headers with custom headers.
1102        // Custom headers override spec-derived ones with the same name.
1103        let mut effective_headers = self.effective_headers(&op.header_params);
1104
1105        // For non-default response code checks, add header to tell the mock server
1106        // which status code to return (the server defaults to the first declared status)
1107        if matches!(feature, ConformanceFeature::Response400 | ConformanceFeature::Response404) {
1108            let expected_code = match feature {
1109                ConformanceFeature::Response400 => "400",
1110                ConformanceFeature::Response404 => "404",
1111                _ => unreachable!(),
1112            };
1113            effective_headers
1114                .push(("X-Mockforge-Response-Status".to_string(), expected_code.to_string()));
1115        }
1116
1117        // For security checks AND for all requests on endpoints with security requirements,
1118        // inject auth credentials so the server doesn't reject with 401.
1119        // Only inject if the user hasn't already provided the header via --custom-headers.
1120        let needs_auth = matches!(
1121            feature,
1122            ConformanceFeature::SecurityBearer
1123                | ConformanceFeature::SecurityBasic
1124                | ConformanceFeature::SecurityApiKey
1125        ) || !op.security_schemes.is_empty();
1126
1127        if needs_auth {
1128            self.inject_security_headers(&op.security_schemes, &mut effective_headers);
1129        }
1130
1131        let has_headers = !effective_headers.is_empty();
1132        let headers_obj = if has_headers {
1133            Self::format_headers(&effective_headers)
1134        } else {
1135            String::new()
1136        };
1137
1138        // Determine HTTP method and emit request
1139        match op.method.as_str() {
1140            "GET" => {
1141                if has_headers {
1142                    script.push_str(&format!(
1143                        "      let res = http.get(`{}`, {{ headers: {} }});\n",
1144                        full_url, headers_obj
1145                    ));
1146                } else {
1147                    script.push_str(&format!("      let res = http.get(`{}`);\n", full_url));
1148                }
1149            }
1150            "POST" => {
1151                self.emit_request_with_body(script, "post", &full_url, op, &effective_headers);
1152            }
1153            "PUT" => {
1154                self.emit_request_with_body(script, "put", &full_url, op, &effective_headers);
1155            }
1156            "PATCH" => {
1157                self.emit_request_with_body(script, "patch", &full_url, op, &effective_headers);
1158            }
1159            "DELETE" => {
1160                if has_headers {
1161                    script.push_str(&format!(
1162                        "      let res = http.del(`{}`, null, {{ headers: {} }});\n",
1163                        full_url, headers_obj
1164                    ));
1165                } else {
1166                    script.push_str(&format!("      let res = http.del(`{}`);\n", full_url));
1167                }
1168            }
1169            "HEAD" => {
1170                if has_headers {
1171                    script.push_str(&format!(
1172                        "      let res = http.head(`{}`, {{ headers: {} }});\n",
1173                        full_url, headers_obj
1174                    ));
1175                } else {
1176                    script.push_str(&format!("      let res = http.head(`{}`);\n", full_url));
1177                }
1178            }
1179            "OPTIONS" => {
1180                if has_headers {
1181                    script.push_str(&format!(
1182                        "      let res = http.options(`{}`, null, {{ headers: {} }});\n",
1183                        full_url, headers_obj
1184                    ));
1185                } else {
1186                    script.push_str(&format!("      let res = http.options(`{}`);\n", full_url));
1187                }
1188            }
1189            _ => {
1190                if has_headers {
1191                    script.push_str(&format!(
1192                        "      let res = http.get(`{}`, {{ headers: {} }});\n",
1193                        full_url, headers_obj
1194                    ));
1195                } else {
1196                    script.push_str(&format!("      let res = http.get(`{}`);\n", full_url));
1197                }
1198            }
1199        }
1200
1201        // Capture request/response for --export-requests
1202        // (check_name is already escaped at line 829 above — don't double-escape)
1203        if self.config.export_requests {
1204            script.push_str(&format!(
1205                "      if (typeof __captureExchange === 'function') __captureExchange('{}', res);\n",
1206                check_name
1207            ));
1208        }
1209
1210        // Check: emit assertion based on feature type, with failure detail capture
1211        if matches!(
1212            feature,
1213            ConformanceFeature::Response200
1214                | ConformanceFeature::Response201
1215                | ConformanceFeature::Response204
1216                | ConformanceFeature::Response400
1217                | ConformanceFeature::Response404
1218        ) {
1219            let expected_code = match feature {
1220                ConformanceFeature::Response200 => 200,
1221                ConformanceFeature::Response201 => 201,
1222                ConformanceFeature::Response204 => 204,
1223                ConformanceFeature::Response400 => 400,
1224                ConformanceFeature::Response404 => 404,
1225                _ => 200,
1226            };
1227            script.push_str(&format!(
1228                "      {{ let ok = check(res, {{ '{}': (r) => r.status === {} }}); if (!ok) __captureFailure('{}', res, 'status === {}'); }}\n",
1229                check_name, expected_code, check_name, expected_code
1230            ));
1231        } else if matches!(feature, ConformanceFeature::ResponseValidation) {
1232            // Response schema validation — validate the response body against the schema
1233            // Uses inline field-level error collection so failure details include
1234            // which specific fields violated the schema (field_path, violation_type,
1235            // expected, actual) — matching the Ajv `errors` array structure.
1236            if let Some(schema) = &op.response_schema {
1237                let validation_js = SchemaValidatorGenerator::generate_validation(schema);
1238                let schema_json = serde_json::to_string(schema).unwrap_or_default();
1239                // Escape backticks and backslashes for JS template literal safety
1240                let schema_json_escaped = schema_json.replace('\\', "\\\\").replace('`', "\\`");
1241                script.push_str(&format!(
1242                    concat!(
1243                        "      try {{\n",
1244                        "        let body = res.json();\n",
1245                        "        let ok = check(res, {{ '{check}': (r) => ( {validation} ) }});\n",
1246                        "        if (!ok) {{\n",
1247                        "          let __violations = [];\n",
1248                        "          try {{\n",
1249                        "            let __schema = JSON.parse(`{schema}`);\n",
1250                        "            function __collectErrors(schema, data, path) {{\n",
1251                        "              if (!schema || typeof schema !== 'object') return;\n",
1252                        "              let st = schema.type || (schema.schema_kind && schema.schema_kind.Type && Object.keys(schema.schema_kind.Type)[0]);\n",
1253                        "              if (st) {{ st = st.toLowerCase(); }}\n",
1254                        "              if (st === 'object') {{\n",
1255                        "                if (typeof data !== 'object' || data === null) {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'object', actual: typeof data }}); return; }}\n",
1256                        "                let props = schema.properties || (schema.schema_kind && schema.schema_kind.Type && schema.schema_kind.Type.Object && schema.schema_kind.Type.Object.properties) || {{}};\n",
1257                        "                let req = schema.required || (schema.schema_kind && schema.schema_kind.Type && schema.schema_kind.Type.Object && schema.schema_kind.Type.Object.required) || [];\n",
1258                        "                for (let f of req) {{ if (!(f in data)) {{ __violations.push({{ field_path: path + '/' + f, violation_type: 'required', expected: 'present', actual: 'missing' }}); }} }}\n",
1259                        "                for (let [k, v] of Object.entries(props)) {{ if (data[k] !== undefined) {{ let ps = v.Item || v; __collectErrors(ps, data[k], path + '/' + k); }} }}\n",
1260                        "              }} else if (st === 'array') {{\n",
1261                        "                if (!Array.isArray(data)) {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'array', actual: typeof data }}); return; }}\n",
1262                        "                let items = schema.items || (schema.schema_kind && schema.schema_kind.Type && schema.schema_kind.Type.Array && schema.schema_kind.Type.Array.items);\n",
1263                        "                if (items) {{ let is = items.Item || items; for (let i = 0; i < Math.min(data.length, 5); i++) {{ __collectErrors(is, data[i], path + '/' + i); }} }}\n",
1264                        "              }} else if (st === 'string') {{\n",
1265                        "                if (typeof data !== 'string') {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'string', actual: typeof data }}); }}\n",
1266                        "              }} else if (st === 'integer') {{\n",
1267                        "                if (typeof data !== 'number' || !Number.isInteger(data)) {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'integer', actual: typeof data }}); }}\n",
1268                        "              }} else if (st === 'number') {{\n",
1269                        "                if (typeof data !== 'number') {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'number', actual: typeof data }}); }}\n",
1270                        "              }} else if (st === 'boolean') {{\n",
1271                        "                if (typeof data !== 'boolean') {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'boolean', actual: typeof data }}); }}\n",
1272                        "              }}\n",
1273                        "            }}\n",
1274                        "            __collectErrors(__schema, body, '');\n",
1275                        "          }} catch(_e) {{}}\n",
1276                        "          __captureFailure('{check}', res, 'schema validation', __violations);\n",
1277                        "        }}\n",
1278                        "      }} catch(e) {{ check(res, {{ '{check}': () => false }}); __captureFailure('{check}', res, 'JSON parse failed: ' + e.message); }}\n",
1279                    ),
1280                    check = check_name,
1281                    validation = validation_js,
1282                    schema = schema_json_escaped,
1283                ));
1284            }
1285        } else if matches!(
1286            feature,
1287            ConformanceFeature::SecurityBearer
1288                | ConformanceFeature::SecurityBasic
1289                | ConformanceFeature::SecurityApiKey
1290        ) {
1291            // Security checks verify the server accepts the auth credentials (not 401/403)
1292            script.push_str(&format!(
1293                "      {{ let ok = check(res, {{ '{}': (r) => r.status >= 200 && r.status < 400 }}); if (!ok) __captureFailure('{}', res, 'status >= 200 && status < 400 (auth accepted)'); }}\n",
1294                check_name, check_name
1295            ));
1296        } else {
1297            script.push_str(&format!(
1298                "      {{ let ok = check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }}); if (!ok) __captureFailure('{}', res, 'status >= 200 && status < 500'); }}\n",
1299                check_name, check_name
1300            ));
1301        }
1302
1303        // Clear cookie jar after each request to prevent Set-Cookie leaking
1304        let has_cookie = self.config.has_cookie_header()
1305            || effective_headers.iter().any(|(h, _)| h.eq_ignore_ascii_case("Cookie"));
1306        if has_cookie {
1307            script.push_str("      http.cookieJar().clear(BASE_URL);\n");
1308        }
1309
1310        script.push_str("    }\n");
1311
1312        // Rate-limit delay between checks (to avoid 429 from target API)
1313        if self.config.request_delay_ms > 0 {
1314            script.push_str(&format!(
1315                "    sleep({:.3});\n",
1316                self.config.request_delay_ms as f64 / 1000.0
1317            ));
1318        }
1319    }
1320
1321    /// Emit an HTTP request with a body
1322    fn emit_request_with_body(
1323        &self,
1324        script: &mut String,
1325        method: &str,
1326        url: &str,
1327        op: &AnnotatedOperation,
1328        effective_headers: &[(String, String)],
1329    ) {
1330        if let Some(body) = &op.sample_body {
1331            let escaped_body = body.replace('\'', "\\'");
1332            let headers = if !effective_headers.is_empty() {
1333                format!(
1334                    "Object.assign({{}}, JSON_HEADERS, {})",
1335                    Self::format_headers(effective_headers)
1336                )
1337            } else {
1338                "JSON_HEADERS".to_string()
1339            };
1340            script.push_str(&format!(
1341                "      let res = http.{}(`{}`, '{}', {{ headers: {} }});\n",
1342                method, url, escaped_body, headers
1343            ));
1344        } else if !effective_headers.is_empty() {
1345            script.push_str(&format!(
1346                "      let res = http.{}(`{}`, null, {{ headers: {} }});\n",
1347                method,
1348                url,
1349                Self::format_headers(effective_headers)
1350            ));
1351        } else {
1352            script.push_str(&format!("      let res = http.{}(`{}`, null);\n", method, url));
1353        }
1354    }
1355
1356    /// Build effective headers by merging spec-derived headers with custom headers.
1357    /// Custom headers override spec-derived ones with the same name (case-insensitive).
1358    /// Custom headers not in the spec are appended.
1359    fn effective_headers(&self, spec_headers: &[(String, String)]) -> Vec<(String, String)> {
1360        let custom = &self.config.custom_headers;
1361        if custom.is_empty() {
1362            return spec_headers.to_vec();
1363        }
1364
1365        let mut result: Vec<(String, String)> = Vec::new();
1366
1367        // Start with spec headers, replacing values if a custom header matches
1368        for (name, value) in spec_headers {
1369            if let Some((_, custom_val)) =
1370                custom.iter().find(|(cn, _)| cn.eq_ignore_ascii_case(name))
1371            {
1372                result.push((name.clone(), custom_val.clone()));
1373            } else {
1374                result.push((name.clone(), value.clone()));
1375            }
1376        }
1377
1378        // Append custom headers that aren't already in spec headers
1379        for (name, value) in custom {
1380            if !spec_headers.iter().any(|(sn, _)| sn.eq_ignore_ascii_case(name)) {
1381                result.push((name.clone(), value.clone()));
1382            }
1383        }
1384
1385        result
1386    }
1387
1388    /// Inject security headers based on resolved security scheme details.
1389    /// Respects user-provided custom headers (won't overwrite if already set).
1390    fn inject_security_headers(
1391        &self,
1392        schemes: &[SecuritySchemeInfo],
1393        headers: &mut Vec<(String, String)>,
1394    ) {
1395        let mut to_add: Vec<(String, String)> = Vec::new();
1396
1397        let has_header = |name: &str, headers: &[(String, String)]| {
1398            headers.iter().any(|(h, _)| h.eq_ignore_ascii_case(name))
1399                || self.config.custom_headers.iter().any(|(h, _)| h.eq_ignore_ascii_case(name))
1400        };
1401
1402        // If user provides Cookie header, they're using session-based auth — skip auto auth
1403        let has_cookie_auth = has_header("Cookie", headers);
1404
1405        for scheme in schemes {
1406            match scheme {
1407                SecuritySchemeInfo::Bearer => {
1408                    if !has_cookie_auth && !has_header("Authorization", headers) {
1409                        // MockForge mock server accepts any Bearer token
1410                        to_add.push((
1411                            "Authorization".to_string(),
1412                            "Bearer mockforge-conformance-test-token".to_string(),
1413                        ));
1414                    }
1415                }
1416                SecuritySchemeInfo::Basic => {
1417                    if !has_cookie_auth && !has_header("Authorization", headers) {
1418                        let creds = self.config.basic_auth.as_deref().unwrap_or("test:test");
1419                        use base64::Engine;
1420                        let encoded =
1421                            base64::engine::general_purpose::STANDARD.encode(creds.as_bytes());
1422                        to_add.push(("Authorization".to_string(), format!("Basic {}", encoded)));
1423                    }
1424                }
1425                SecuritySchemeInfo::ApiKey { location, name } => match location {
1426                    ApiKeyLocation::Header => {
1427                        if !has_header(name, headers) {
1428                            let key = self
1429                                .config
1430                                .api_key
1431                                .as_deref()
1432                                .unwrap_or("mockforge-conformance-test-key");
1433                            to_add.push((name.clone(), key.to_string()));
1434                        }
1435                    }
1436                    ApiKeyLocation::Cookie => {
1437                        if !has_header("Cookie", headers) {
1438                            to_add.push((
1439                                "Cookie".to_string(),
1440                                format!("{}=mockforge-conformance-test-session", name),
1441                            ));
1442                        }
1443                    }
1444                    ApiKeyLocation::Query => {
1445                        // Query params are handled via URL, not headers — skip here
1446                    }
1447                },
1448            }
1449        }
1450
1451        headers.extend(to_add);
1452    }
1453
1454    /// Format header params as a JS object literal
1455    fn format_headers(headers: &[(String, String)]) -> String {
1456        let entries: Vec<String> = headers
1457            .iter()
1458            .map(|(k, v)| format!("'{}': '{}'", k, v.replace('\'', "\\'")))
1459            .collect();
1460        format!("{{ {} }}", entries.join(", "))
1461    }
1462
1463    /// handleSummary — same format as reference mode for report compatibility
1464    fn generate_handle_summary(&self, script: &mut String) {
1465        // Use absolute path for report output so k6 writes where the CLI expects
1466        let report_path = match &self.config.output_dir {
1467            Some(dir) => {
1468                let abs = std::fs::canonicalize(dir)
1469                    .unwrap_or_else(|_| dir.clone())
1470                    .join("conformance-report.json");
1471                abs.to_string_lossy().to_string()
1472            }
1473            None => "conformance-report.json".to_string(),
1474        };
1475
1476        script.push_str("export function handleSummary(data) {\n");
1477        script.push_str("  let checks = {};\n");
1478        script.push_str("  if (data.metrics && data.metrics.checks) {\n");
1479        script.push_str("    checks.overall_pass_rate = data.metrics.checks.values.rate;\n");
1480        script.push_str("  }\n");
1481        script.push_str("  let checkResults = {};\n");
1482        script.push_str("  function walkGroups(group) {\n");
1483        script.push_str("    if (group.checks) {\n");
1484        script.push_str("      for (let checkObj of group.checks) {\n");
1485        script.push_str("        checkResults[checkObj.name] = {\n");
1486        script.push_str("          passes: checkObj.passes,\n");
1487        script.push_str("          fails: checkObj.fails,\n");
1488        script.push_str("        };\n");
1489        script.push_str("      }\n");
1490        script.push_str("    }\n");
1491        script.push_str("    if (group.groups) {\n");
1492        script.push_str("      for (let subGroup of group.groups) {\n");
1493        script.push_str("        walkGroups(subGroup);\n");
1494        script.push_str("      }\n");
1495        script.push_str("    }\n");
1496        script.push_str("  }\n");
1497        script.push_str("  if (data.root_group) {\n");
1498        script.push_str("    walkGroups(data.root_group);\n");
1499        script.push_str("  }\n");
1500        script.push_str("  return {\n");
1501        script.push_str(&format!(
1502            "    '{}': JSON.stringify({{ checks: checkResults, overall: checks }}, null, 2),\n",
1503            report_path
1504        ));
1505        script.push_str("    'summary.json': JSON.stringify(data),\n");
1506        script.push_str("    stdout: textSummary(data, { indent: '  ', enableColors: true }),\n");
1507        script.push_str("  };\n");
1508        script.push_str("}\n\n");
1509        script.push_str("function textSummary(data, opts) {\n");
1510        script.push_str("  return JSON.stringify(data, null, 2);\n");
1511        script.push_str("}\n");
1512    }
1513}
1514
1515#[cfg(test)]
1516mod tests {
1517    use super::*;
1518    use openapiv3::{
1519        Operation, ParameterData, ParameterSchemaOrContent, PathStyle, Response, Schema,
1520        SchemaData, SchemaKind, StringType, Type,
1521    };
1522
1523    fn make_op(method: &str, path: &str, operation: Operation) -> ApiOperation {
1524        ApiOperation {
1525            method: method.to_string(),
1526            path: path.to_string(),
1527            operation,
1528            operation_id: None,
1529        }
1530    }
1531
1532    fn empty_spec() -> OpenAPI {
1533        OpenAPI::default()
1534    }
1535
1536    #[test]
1537    fn test_annotate_get_with_path_param() {
1538        let mut op = Operation::default();
1539        op.parameters.push(ReferenceOr::Item(Parameter::Path {
1540            parameter_data: ParameterData {
1541                name: "id".to_string(),
1542                description: None,
1543                required: true,
1544                deprecated: None,
1545                format: ParameterSchemaOrContent::Schema(ReferenceOr::Item(Schema {
1546                    schema_data: SchemaData::default(),
1547                    schema_kind: SchemaKind::Type(Type::String(StringType::default())),
1548                })),
1549                example: None,
1550                examples: Default::default(),
1551                explode: None,
1552                extensions: Default::default(),
1553            },
1554            style: PathStyle::Simple,
1555        }));
1556
1557        let api_op = make_op("get", "/users/{id}", op);
1558        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1559
1560        assert!(annotated.features.contains(&ConformanceFeature::MethodGet));
1561        assert!(annotated.features.contains(&ConformanceFeature::PathParamString));
1562        assert!(annotated.features.contains(&ConformanceFeature::ConstraintRequired));
1563        assert_eq!(annotated.path_params.len(), 1);
1564        assert_eq!(annotated.path_params[0].0, "id");
1565    }
1566
1567    #[test]
1568    fn test_annotate_post_with_json_body() {
1569        let mut op = Operation::default();
1570        let mut body = RequestBody {
1571            required: true,
1572            ..Default::default()
1573        };
1574        body.content
1575            .insert("application/json".to_string(), openapiv3::MediaType::default());
1576        op.request_body = Some(ReferenceOr::Item(body));
1577
1578        let api_op = make_op("post", "/items", op);
1579        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1580
1581        assert!(annotated.features.contains(&ConformanceFeature::MethodPost));
1582        assert!(annotated.features.contains(&ConformanceFeature::BodyJson));
1583    }
1584
1585    #[test]
1586    fn test_annotate_response_codes() {
1587        let mut op = Operation::default();
1588        op.responses
1589            .responses
1590            .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(Response::default()));
1591        op.responses
1592            .responses
1593            .insert(openapiv3::StatusCode::Code(404), ReferenceOr::Item(Response::default()));
1594
1595        let api_op = make_op("get", "/items", op);
1596        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1597
1598        assert!(annotated.features.contains(&ConformanceFeature::Response200));
1599        assert!(annotated.features.contains(&ConformanceFeature::Response404));
1600    }
1601
1602    #[test]
1603    fn test_generate_spec_driven_script() {
1604        let config = ConformanceConfig {
1605            target_url: "http://localhost:3000".to_string(),
1606            api_key: None,
1607            basic_auth: None,
1608            skip_tls_verify: false,
1609            categories: None,
1610            base_path: None,
1611            custom_headers: vec![],
1612            output_dir: None,
1613            all_operations: false,
1614            custom_checks_file: None,
1615            request_delay_ms: 0,
1616            custom_filter: None,
1617            export_requests: false,
1618            validate_requests: false,
1619        };
1620
1621        let operations = vec![AnnotatedOperation {
1622            path: "/users/{id}".to_string(),
1623            method: "GET".to_string(),
1624            features: vec![
1625                ConformanceFeature::MethodGet,
1626                ConformanceFeature::PathParamString,
1627            ],
1628            request_body_content_type: None,
1629            sample_body: None,
1630            query_params: vec![],
1631            header_params: vec![],
1632            path_params: vec![("id".to_string(), "test-value".to_string())],
1633            response_schema: None,
1634            response_schemas: std::collections::BTreeMap::new(),
1635            request_body_schema: None,
1636            security_schemes: vec![],
1637        }];
1638
1639        let gen = SpecDrivenConformanceGenerator::new(config, operations);
1640        let (script, _check_count) = gen.generate().unwrap();
1641
1642        assert!(script.contains("import http from 'k6/http'"));
1643        assert!(script.contains("/users/test-value"));
1644        assert!(script.contains("param:path:string"));
1645        assert!(script.contains("method:GET"));
1646        assert!(script.contains("handleSummary"));
1647    }
1648
1649    #[test]
1650    fn test_generate_with_category_filter() {
1651        let config = ConformanceConfig {
1652            target_url: "http://localhost:3000".to_string(),
1653            api_key: None,
1654            basic_auth: None,
1655            skip_tls_verify: false,
1656            categories: Some(vec!["Parameters".to_string()]),
1657            base_path: None,
1658            custom_headers: vec![],
1659            output_dir: None,
1660            all_operations: false,
1661            custom_checks_file: None,
1662            request_delay_ms: 0,
1663            custom_filter: None,
1664            export_requests: false,
1665            validate_requests: false,
1666        };
1667
1668        let operations = vec![AnnotatedOperation {
1669            path: "/users/{id}".to_string(),
1670            method: "GET".to_string(),
1671            features: vec![
1672                ConformanceFeature::MethodGet,
1673                ConformanceFeature::PathParamString,
1674            ],
1675            request_body_content_type: None,
1676            sample_body: None,
1677            query_params: vec![],
1678            header_params: vec![],
1679            path_params: vec![("id".to_string(), "1".to_string())],
1680            response_schema: None,
1681            response_schemas: std::collections::BTreeMap::new(),
1682            request_body_schema: None,
1683            security_schemes: vec![],
1684        }];
1685
1686        let gen = SpecDrivenConformanceGenerator::new(config, operations);
1687        let (script, _check_count) = gen.generate().unwrap();
1688
1689        assert!(script.contains("group('Parameters'"));
1690        assert!(!script.contains("group('HTTP Methods'"));
1691    }
1692
1693    #[test]
1694    fn test_annotate_response_validation() {
1695        use openapiv3::ObjectType;
1696
1697        // Operation with a 200 response that has a JSON schema
1698        let mut op = Operation::default();
1699        let mut response = Response::default();
1700        let mut media = openapiv3::MediaType::default();
1701        let mut obj_type = ObjectType::default();
1702        obj_type.properties.insert(
1703            "name".to_string(),
1704            ReferenceOr::Item(Box::new(Schema {
1705                schema_data: SchemaData::default(),
1706                schema_kind: SchemaKind::Type(Type::String(StringType::default())),
1707            })),
1708        );
1709        obj_type.required = vec!["name".to_string()];
1710        media.schema = Some(ReferenceOr::Item(Schema {
1711            schema_data: SchemaData::default(),
1712            schema_kind: SchemaKind::Type(Type::Object(obj_type)),
1713        }));
1714        response.content.insert("application/json".to_string(), media);
1715        op.responses
1716            .responses
1717            .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));
1718
1719        let api_op = make_op("get", "/users", op);
1720        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1721
1722        assert!(
1723            annotated.features.contains(&ConformanceFeature::ResponseValidation),
1724            "Should detect ResponseValidation when response has a JSON schema"
1725        );
1726        assert!(annotated.response_schema.is_some(), "Should extract the response schema");
1727
1728        // Verify generated script includes schema validation with try-catch
1729        let config = ConformanceConfig {
1730            target_url: "http://localhost:3000".to_string(),
1731            api_key: None,
1732            basic_auth: None,
1733            skip_tls_verify: false,
1734            categories: None,
1735            base_path: None,
1736            custom_headers: vec![],
1737            output_dir: None,
1738            all_operations: false,
1739            custom_checks_file: None,
1740            request_delay_ms: 0,
1741            custom_filter: None,
1742            export_requests: false,
1743            validate_requests: false,
1744        };
1745        let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
1746        let (script, _check_count) = gen.generate().unwrap();
1747
1748        assert!(
1749            script.contains("response:schema:validation"),
1750            "Script should contain the validation check name"
1751        );
1752        assert!(script.contains("try {"), "Script should wrap validation in try-catch");
1753        assert!(script.contains("res.json()"), "Script should parse response as JSON");
1754    }
1755
1756    #[test]
1757    fn test_annotate_global_security() {
1758        // Spec with global security requirement, operation without its own security
1759        let op = Operation::default();
1760        let mut spec = OpenAPI::default();
1761        let mut global_req = openapiv3::SecurityRequirement::new();
1762        global_req.insert("bearerAuth".to_string(), vec![]);
1763        spec.security = Some(vec![global_req]);
1764        // Define the security scheme in components
1765        let mut components = openapiv3::Components::default();
1766        components.security_schemes.insert(
1767            "bearerAuth".to_string(),
1768            ReferenceOr::Item(SecurityScheme::HTTP {
1769                scheme: "bearer".to_string(),
1770                bearer_format: Some("JWT".to_string()),
1771                description: None,
1772                extensions: Default::default(),
1773            }),
1774        );
1775        spec.components = Some(components);
1776
1777        let api_op = make_op("get", "/protected", op);
1778        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &spec);
1779
1780        assert!(
1781            annotated.features.contains(&ConformanceFeature::SecurityBearer),
1782            "Should detect SecurityBearer from global security + components"
1783        );
1784    }
1785
1786    #[test]
1787    fn test_annotate_security_scheme_resolution() {
1788        // Test that security scheme type is resolved from components, not just name heuristic
1789        let mut op = Operation::default();
1790        // Use a generic name that wouldn't match name heuristics
1791        let mut req = openapiv3::SecurityRequirement::new();
1792        req.insert("myAuth".to_string(), vec![]);
1793        op.security = Some(vec![req]);
1794
1795        let mut spec = OpenAPI::default();
1796        let mut components = openapiv3::Components::default();
1797        components.security_schemes.insert(
1798            "myAuth".to_string(),
1799            ReferenceOr::Item(SecurityScheme::APIKey {
1800                location: openapiv3::APIKeyLocation::Header,
1801                name: "X-API-Key".to_string(),
1802                description: None,
1803                extensions: Default::default(),
1804            }),
1805        );
1806        spec.components = Some(components);
1807
1808        let api_op = make_op("get", "/data", op);
1809        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &spec);
1810
1811        assert!(
1812            annotated.features.contains(&ConformanceFeature::SecurityApiKey),
1813            "Should detect SecurityApiKey from SecurityScheme::APIKey, not name heuristic"
1814        );
1815    }
1816
1817    #[test]
1818    fn test_annotate_content_negotiation() {
1819        let mut op = Operation::default();
1820        let mut response = Response::default();
1821        // Response with multiple content types
1822        response
1823            .content
1824            .insert("application/json".to_string(), openapiv3::MediaType::default());
1825        response
1826            .content
1827            .insert("application/xml".to_string(), openapiv3::MediaType::default());
1828        op.responses
1829            .responses
1830            .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));
1831
1832        let api_op = make_op("get", "/items", op);
1833        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1834
1835        assert!(
1836            annotated.features.contains(&ConformanceFeature::ContentNegotiation),
1837            "Should detect ContentNegotiation when response has multiple content types"
1838        );
1839    }
1840
1841    #[test]
1842    fn test_no_content_negotiation_for_single_type() {
1843        let mut op = Operation::default();
1844        let mut response = Response::default();
1845        response
1846            .content
1847            .insert("application/json".to_string(), openapiv3::MediaType::default());
1848        op.responses
1849            .responses
1850            .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));
1851
1852        let api_op = make_op("get", "/items", op);
1853        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1854
1855        assert!(
1856            !annotated.features.contains(&ConformanceFeature::ContentNegotiation),
1857            "Should NOT detect ContentNegotiation for a single content type"
1858        );
1859    }
1860
1861    #[test]
1862    fn test_spec_driven_with_base_path() {
1863        let annotated = AnnotatedOperation {
1864            path: "/users".to_string(),
1865            method: "GET".to_string(),
1866            features: vec![ConformanceFeature::MethodGet],
1867            path_params: vec![],
1868            query_params: vec![],
1869            header_params: vec![],
1870            request_body_content_type: None,
1871            sample_body: None,
1872            response_schema: None,
1873            response_schemas: std::collections::BTreeMap::new(),
1874            request_body_schema: None,
1875            security_schemes: vec![],
1876        };
1877        let config = ConformanceConfig {
1878            target_url: "https://192.168.2.86/".to_string(),
1879            api_key: None,
1880            basic_auth: None,
1881            skip_tls_verify: true,
1882            categories: None,
1883            base_path: Some("/api".to_string()),
1884            custom_headers: vec![],
1885            output_dir: None,
1886            all_operations: false,
1887            custom_checks_file: None,
1888            request_delay_ms: 0,
1889            custom_filter: None,
1890            export_requests: false,
1891            validate_requests: false,
1892        };
1893        let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
1894        let (script, _check_count) = gen.generate().unwrap();
1895
1896        assert!(
1897            script.contains("const BASE_URL = 'https://192.168.2.86/api'"),
1898            "BASE_URL should include the base_path. Got: {}",
1899            script.lines().find(|l| l.contains("BASE_URL")).unwrap_or("not found")
1900        );
1901    }
1902
1903    #[test]
1904    fn test_spec_driven_with_custom_headers() {
1905        let annotated = AnnotatedOperation {
1906            path: "/users".to_string(),
1907            method: "GET".to_string(),
1908            features: vec![ConformanceFeature::MethodGet],
1909            path_params: vec![],
1910            query_params: vec![],
1911            header_params: vec![
1912                ("X-Avi-Tenant".to_string(), "test-value".to_string()),
1913                ("X-CSRFToken".to_string(), "test-value".to_string()),
1914            ],
1915            request_body_content_type: None,
1916            sample_body: None,
1917            response_schema: None,
1918            response_schemas: std::collections::BTreeMap::new(),
1919            request_body_schema: None,
1920            security_schemes: vec![],
1921        };
1922        let config = ConformanceConfig {
1923            target_url: "https://192.168.2.86/".to_string(),
1924            api_key: None,
1925            basic_auth: None,
1926            skip_tls_verify: true,
1927            categories: None,
1928            base_path: Some("/api".to_string()),
1929            custom_headers: vec![
1930                ("X-Avi-Tenant".to_string(), "admin".to_string()),
1931                ("X-CSRFToken".to_string(), "real-csrf-token".to_string()),
1932                ("Cookie".to_string(), "sessionid=abc123".to_string()),
1933            ],
1934            output_dir: None,
1935            all_operations: false,
1936            custom_checks_file: None,
1937            request_delay_ms: 0,
1938            custom_filter: None,
1939            export_requests: false,
1940            validate_requests: false,
1941        };
1942        let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
1943        let (script, _check_count) = gen.generate().unwrap();
1944
1945        // Custom headers should override spec-derived test-value placeholders
1946        assert!(
1947            script.contains("'X-Avi-Tenant': 'admin'"),
1948            "Should use custom value for X-Avi-Tenant, not test-value"
1949        );
1950        assert!(
1951            script.contains("'X-CSRFToken': 'real-csrf-token'"),
1952            "Should use custom value for X-CSRFToken, not test-value"
1953        );
1954        // Custom headers not in spec should be appended
1955        assert!(
1956            script.contains("'Cookie': 'sessionid=abc123'"),
1957            "Should include Cookie header from custom_headers"
1958        );
1959        // test-value should NOT appear
1960        assert!(
1961            !script.contains("'test-value'"),
1962            "test-value placeholders should be replaced by custom values"
1963        );
1964    }
1965
1966    #[test]
1967    fn test_effective_headers_merging() {
1968        let config = ConformanceConfig {
1969            target_url: "http://localhost".to_string(),
1970            api_key: None,
1971            basic_auth: None,
1972            skip_tls_verify: false,
1973            categories: None,
1974            base_path: None,
1975            custom_headers: vec![
1976                ("X-Auth".to_string(), "real-token".to_string()),
1977                ("Cookie".to_string(), "session=abc".to_string()),
1978            ],
1979            output_dir: None,
1980            all_operations: false,
1981            custom_checks_file: None,
1982            request_delay_ms: 0,
1983            custom_filter: None,
1984            export_requests: false,
1985            validate_requests: false,
1986        };
1987        let gen = SpecDrivenConformanceGenerator::new(config, vec![]);
1988
1989        // Spec headers with a matching custom header
1990        let spec_headers = vec![
1991            ("X-Auth".to_string(), "test-value".to_string()),
1992            ("X-Other".to_string(), "keep-this".to_string()),
1993        ];
1994        let effective = gen.effective_headers(&spec_headers);
1995
1996        // X-Auth should be overridden
1997        assert_eq!(effective[0], ("X-Auth".to_string(), "real-token".to_string()));
1998        // X-Other should be kept as-is
1999        assert_eq!(effective[1], ("X-Other".to_string(), "keep-this".to_string()));
2000        // Cookie should be appended
2001        assert_eq!(effective[2], ("Cookie".to_string(), "session=abc".to_string()));
2002    }
2003
2004    // Round 51 (#79) — baseline param filler must be spec-VALID so a probe that
2005    // isn't attacking a given param doesn't trip a spurious violation on it.
2006    #[test]
2007    fn param_sample_value_respects_enum_boolean_and_type() {
2008        use openapiv3::{BooleanType, IntegerType, NumberType, VariantOrUnknownOrEmpty};
2009
2010        // Enum string (like Apigee's `alt`: json|media|proto) -> first member.
2011        let st = StringType {
2012            enumeration: vec![Some("json".into()), Some("media".into())],
2013            ..Default::default()
2014        };
2015        let enum_schema = Schema {
2016            schema_data: SchemaData::default(),
2017            schema_kind: SchemaKind::Type(Type::String(st)),
2018        };
2019        assert_eq!(SpecDrivenConformanceGenerator::schema_sample_value(&enum_schema), "json");
2020
2021        // Boolean (like `prettyPrint`) -> "true", not "test-value".
2022        let bool_schema = Schema {
2023            schema_data: SchemaData::default(),
2024            schema_kind: SchemaKind::Type(Type::Boolean(BooleanType::default())),
2025        };
2026        assert_eq!(SpecDrivenConformanceGenerator::schema_sample_value(&bool_schema), "true");
2027
2028        // Integer -> a number.
2029        let int_schema = Schema {
2030            schema_data: SchemaData::default(),
2031            schema_kind: SchemaKind::Type(Type::Integer(IntegerType::default())),
2032        };
2033        assert_eq!(SpecDrivenConformanceGenerator::schema_sample_value(&int_schema), "42");
2034
2035        // Number -> a number.
2036        let num_schema = Schema {
2037            schema_data: SchemaData::default(),
2038            schema_kind: SchemaKind::Type(Type::Number(NumberType::default())),
2039        };
2040        assert_eq!(SpecDrivenConformanceGenerator::schema_sample_value(&num_schema), "42");
2041
2042        // Plain string with no constraints -> the generic filler.
2043        let plain = Schema {
2044            schema_data: SchemaData::default(),
2045            schema_kind: SchemaKind::Type(Type::String(StringType::default())),
2046        };
2047        assert_eq!(SpecDrivenConformanceGenerator::schema_sample_value(&plain), "test-value");
2048
2049        // String with a known format -> a value valid for that format.
2050        let email = StringType {
2051            format: VariantOrUnknownOrEmpty::Unknown("email".into()),
2052            ..Default::default()
2053        };
2054        let email_schema = Schema {
2055            schema_data: SchemaData::default(),
2056            schema_kind: SchemaKind::Type(Type::String(email)),
2057        };
2058        assert_eq!(
2059            SpecDrivenConformanceGenerator::schema_sample_value(&email_schema),
2060            "user@example.com"
2061        );
2062    }
2063}