qitops 0.1.0

Software Quality Assurance CLI for API, Performance, Security, and Web Testing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
use crate::api::ApiTestRunner;
use crate::common::{TestResult, TestRunner};
use crate::error::{Error, Result};
use chrono::Utc;
use log::{info, warn};
use reqwest::{Client, Method};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::path::Path;
use std::time::{Duration, Instant};
use jsonpath_lib as jsonpath;

/// Authentication configuration for API collections
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollectionAuth {
    /// Authentication type (basic, bearer, api_key)
    #[serde(rename = "type")]
    pub auth_type: String,
    /// Username for basic auth
    pub username: Option<String>,
    /// Password for basic auth
    pub password: Option<String>,
    /// Token for bearer auth
    pub token: Option<String>,
    /// Key name for API key auth
    pub key_name: Option<String>,
    /// Key value for API key auth
    pub key_value: Option<String>,
    /// Header or query parameter for API key
    pub key_in: Option<String>,
}

/// Default request configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollectionDefaults {
    /// Default headers for all requests
    pub headers: Option<HashMap<String, String>>,
    /// Default timeout in seconds
    pub timeout: Option<u64>,
    /// Default number of retries
    pub retries: Option<u32>,
}

/// Run options for the collection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollectionRunOptions {
    /// Run requests sequentially (true) or in parallel (false)
    pub sequential: Option<bool>,
    /// Stop on first failure
    pub stop_on_failure: Option<bool>,
    /// Delay between requests in milliseconds
    pub delay_between_requests_ms: Option<u64>,
}

/// A single request in a collection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollectionRequest {
    /// Request name
    pub name: String,
    /// Request description
    pub description: Option<String>,
    /// Request ID (used for dependencies)
    pub id: Option<String>,
    /// Request URL
    pub url: String,
    /// HTTP method
    pub method: String,
    /// Request headers
    pub headers: Option<HashMap<String, String>>,
    /// Request body
    pub body: Option<Value>,
    /// Expected HTTP status code
    pub expected_status: Option<u16>,
    /// Expected response body
    pub expected_body: Option<Value>,
    /// Expected response body type (object, array, etc.)
    pub expected_body_type: Option<String>,
    /// Request dependencies (IDs of requests that must be executed before this one)
    pub depends_on: Option<Vec<String>>,
    /// Variables to capture from the response
    pub capture: Option<HashMap<String, String>>,
}

impl CollectionRequest {
    /// Check if this is a simple request that could be handled by the ApiTestRunner
    /// A simple request has no dependencies, no variable captures, and no complex validation
    pub fn is_simple_request(&self) -> bool {
        self.depends_on.is_none() && self.capture.is_none()
    }
}

/// API collection configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiCollection {
    /// Collection name
    pub name: String,
    /// Collection description
    pub description: Option<String>,
    /// Collection version
    pub version: Option<String>,
    /// Collection variables
    pub variables: Option<HashMap<String, String>>,
    /// Collection authentication
    pub auth: Option<CollectionAuth>,
    /// Default request configuration
    pub defaults: Option<CollectionDefaults>,
    /// Collection requests
    pub requests: Vec<CollectionRequest>,
    /// Environment-specific variables
    pub environments: Option<HashMap<String, HashMap<String, String>>>,
    /// Run options
    pub run_options: Option<CollectionRunOptions>,
}

/// Result of a collection run
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollectionResult {
    /// Collection name
    pub name: String,
    /// Collection status (passed, failed, error)
    pub status: String,
    /// Total duration in seconds
    pub duration: f64,
    /// Results of individual requests
    pub request_results: Vec<TestResult>,
    /// Timestamp
    pub timestamp: String,
    /// Captured variables
    pub variables: HashMap<String, String>,
}

/// API collection runner
pub struct ApiCollectionRunner {
    client: Client,
    api_runner: ApiTestRunner,
}

impl ApiCollectionRunner {
    /// Create a new API collection runner
    pub fn new() -> Self {
        Self {
            client: Client::builder()
                .timeout(Duration::from_secs(30))
                .build()
                .unwrap_or_else(|_| Client::new()),
            api_runner: ApiTestRunner::new(),
        }
    }

    /// Load an API collection from a file
    pub fn load_collection(path: &Path) -> Result<ApiCollection> {
        let content = std::fs::read_to_string(path)?;
        let collection: ApiCollection = serde_json::from_str(&content)?;
        Ok(collection)
    }

    /// Run an API collection
    pub async fn run_collection(&self, collection: &ApiCollection, environment: &str) -> Result<CollectionResult> {
        let start = Instant::now();

        // Initialize variables with collection variables and environment variables
        let mut variables = HashMap::new();
        if let Some(collection_vars) = &collection.variables {
            variables.extend(collection_vars.clone());
        }

        // Add environment-specific variables
        if let Some(environments) = &collection.environments {
            if let Some(env_vars) = environments.get(environment) {
                variables.extend(env_vars.clone());
            }
        }

        // Add environment variables from the system
        for (key, value) in std::env::vars() {
            variables.insert(key, value);
        }

        info!("Running collection: {} with {} requests", collection.name, collection.requests.len());
        info!("Using environment: {}", environment);

        // Determine run options
        let sequential = collection.run_options.as_ref()
            .and_then(|opts| opts.sequential)
            .unwrap_or(true);

        let stop_on_failure = collection.run_options.as_ref()
            .and_then(|opts| opts.stop_on_failure)
            .unwrap_or(true);

        let delay = collection.run_options.as_ref()
            .and_then(|opts| opts.delay_between_requests_ms)
            .unwrap_or(0);

        // Track completed requests and their results
        let mut completed_requests = HashMap::new();
        let mut request_results = Vec::new();

        // Run requests
        if sequential {
            // Sequential execution
            for request in &collection.requests {
                // Check dependencies
                if let Some(dependencies) = &request.depends_on {
                    for dep_id in dependencies {
                        if !completed_requests.contains_key(dep_id) {
                            return Err(Error::ValidationError(format!(
                                "Request '{}' depends on '{}', which has not been executed",
                                request.name, dep_id
                            )));
                        }
                    }
                }

                // Execute request
                let result = self.execute_request(request, &collection, &variables).await?;

                // Store result
                if let Some(id) = &request.id {
                    completed_requests.insert(id.clone(), result.clone());
                }
                request_results.push(result.clone());

                // Update variables with captured values
                if let Some(captures) = &request.capture {
                    if let Some(details) = &result.details {
                        if let Some(response_body) = details.get("response_body") {
                            for (var_name, json_path) in captures {
                                if let Ok(values) = jsonpath::select(response_body, json_path) {
                                    if !values.is_empty() {
                                        let value = &values[0];
                                        let value_str = match value {
                                            Value::String(s) => s.clone(),
                                            Value::Number(n) => n.to_string(),
                                            Value::Bool(b) => b.to_string(),
                                            Value::Null => "null".to_string(),
                                            Value::Object(_) | Value::Array(_) => serde_json::to_string(value).unwrap_or_else(|_| "{}".to_string()),
                                        };

                                        info!("Captured variable '{}' with value: {}", var_name, value_str);
                                        variables.insert(var_name.clone(), value_str);
                                    } else {
                                        warn!("JSONPath '{}' matched no values in response", json_path);
                                    }
                                } else {
                                    warn!("Failed to evaluate JSONPath '{}' on response", json_path);
                                }
                            }
                        } else {
                            warn!("No response body found in result details");
                        }
                    } else {
                        warn!("No details found in result");
                    }
                }

                // Check if we should stop on failure
                if stop_on_failure && result.status != "passed" {
                    break;
                }

                // Delay between requests if specified
                if delay > 0 {
                    tokio::time::sleep(Duration::from_millis(delay)).await;
                }
            }
        } else {
            // Parallel execution (not implemented yet)
            return Err(Error::ValidationError("Parallel execution not yet implemented".to_string()));
        }

        // Calculate overall status
        let status = if request_results.iter().all(|r| r.status == "passed") {
            "passed"
        } else {
            "failed"
        };

        let duration = start.elapsed().as_secs_f64();

        Ok(CollectionResult {
            name: collection.name.clone(),
            status: status.to_string(),
            duration,
            request_results,
            timestamp: Utc::now().to_rfc3339(),
            variables,
        })
    }

    /// Execute a single request from the collection
    async fn execute_request(&self, request: &CollectionRequest, collection: &ApiCollection, variables: &HashMap<String, String>) -> Result<TestResult> {
        let start = Instant::now();

        // Interpolate variables in URL
        let url = self.interpolate_variables(&request.url, variables)?;

        // For simple requests, delegate to the ApiTestRunner
        // This reuses validation logic and reduces code duplication
        if request.is_simple_request() {
            // Create a simplified API test config for the ApiTestRunner
            let mut headers = HashMap::new();

            // Add headers from collection defaults
            if let Some(defaults) = &collection.defaults {
                if let Some(default_headers) = &defaults.headers {
                    for (key, value) in default_headers {
                        let interpolated_value = self.interpolate_variables(value, variables)?;
                        headers.insert(key.clone(), interpolated_value);
                    }
                }
            }

            // Add headers from request (overriding defaults)
            if let Some(req_headers) = &request.headers {
                for (key, value) in req_headers {
                    let interpolated_value = self.interpolate_variables(value, variables)?;
                    headers.insert(key.clone(), interpolated_value);
                }
            }

            // Create a simplified test config
            let test_config = serde_json::json!({
                "name": request.name,
                "description": request.description,
                "url": url,
                "method": request.method,
                "headers": headers,
                "expected_status": request.expected_status,
                "expected_body": request.expected_body,
                "timeout": collection.defaults.as_ref().and_then(|d| d.timeout).unwrap_or(30),
                "retries": collection.defaults.as_ref().and_then(|d| d.retries).unwrap_or(3)
            });

            // Use the ApiTestRunner to execute the request
            return self.api_runner.run(&test_config).await;
        }

        // Determine HTTP method
        let method = Method::from_bytes(request.method.as_bytes())
            .map_err(|e| Error::ValidationError(format!("Invalid HTTP method: {}", e)))?;

        // Build request with default timeout from collection or default value
        let timeout = collection.defaults.as_ref()
            .and_then(|d| d.timeout)
            .unwrap_or(30);

        let mut req_builder = self.client.request(method, &url)
            .timeout(Duration::from_secs(timeout));

        // Add headers from collection defaults
        if let Some(defaults) = &collection.defaults {
            if let Some(default_headers) = &defaults.headers {
                for (key, value) in default_headers {
                    let interpolated_value = self.interpolate_variables(value, variables)?;
                    req_builder = req_builder.header(key, interpolated_value);
                }
            }
        }

        // Add headers from request (overriding defaults)
        if let Some(headers) = &request.headers {
            for (key, value) in headers {
                let interpolated_value = self.interpolate_variables(value, variables)?;
                req_builder = req_builder.header(key, interpolated_value);
            }
        }

        // Add authentication if specified at collection level
        if let Some(auth) = &collection.auth {
            req_builder = self.add_authentication(req_builder, auth, variables)?;
        }

        // Add request body if specified
        if let Some(body) = &request.body {
            // Interpolate variables in the body
            let body_str = serde_json::to_string(body)?;
            let interpolated_body_str = self.interpolate_variables(&body_str, variables)?;
            let interpolated_body: Value = serde_json::from_str(&interpolated_body_str)?;
            req_builder = req_builder.json(&interpolated_body);
        }

        // Send the request
        info!("Sending {} request to {}", request.method, url);
        let response = req_builder.send().await?;

        // Process response
        let status = response.status();
        let headers = response.headers().clone();
        let response_body_text = response.text().await?;
        let response_body: Value = serde_json::from_str(&response_body_text).unwrap_or_else(|_| {
            // If not valid JSON, return as string
            Value::String(response_body_text.clone())
        });

        // Validate response
        let duration = start.elapsed().as_secs_f64();
        let validation_result = self.validate_response(
            &status,
            &headers,
            &response_body,
            request,
            duration
        )?;

        // Create response details
        let mut details = json!({
            "status_code": status.as_u16(),
            "response_time": duration,
            "response_body": response_body,
            "headers": headers
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
                .collect::<std::collections::HashMap<_, _>>()
        });

        // Add validation results if any
        let has_validation_issues = if let Some(ref issues) = validation_result {
            details["validation_issues"] = json!(issues);
            true
        } else {
            false
        };

        // Determine test status
        let test_status = if status.is_success() && !has_validation_issues {
            "passed"
        } else {
            "failed"
        };

        Ok(TestResult {
            name: request.name.clone(),
            status: test_status.to_string(),
            duration,
            details: Some(details),
            timestamp: Utc::now().to_rfc3339(),
        })
    }

    /// Add authentication to the request
    fn add_authentication(&self, mut req_builder: reqwest::RequestBuilder, auth: &CollectionAuth, variables: &HashMap<String, String>) -> Result<reqwest::RequestBuilder> {
        match auth.auth_type.as_str() {
            "basic" => {
                let username = auth.username.as_ref()
                    .ok_or_else(|| Error::ValidationError("Username required for basic auth".to_string()))?;
                let password = auth.password.as_ref()
                    .ok_or_else(|| Error::ValidationError("Password required for basic auth".to_string()))?;

                let interpolated_username = self.interpolate_variables(username, variables)?;
                let interpolated_password = self.interpolate_variables(password, variables)?;

                req_builder = req_builder.basic_auth(interpolated_username, Some(interpolated_password));
            },
            "bearer" => {
                let token = auth.token.as_ref()
                    .ok_or_else(|| Error::ValidationError("Token required for bearer auth".to_string()))?;

                let interpolated_token = self.interpolate_variables(token, variables)?;
                req_builder = req_builder.bearer_auth(interpolated_token);
            },
            "api_key" => {
                let key_name = auth.key_name.as_ref()
                    .ok_or_else(|| Error::ValidationError("Key name required for API key auth".to_string()))?;
                let key_value = auth.key_value.as_ref()
                    .ok_or_else(|| Error::ValidationError("Key value required for API key auth".to_string()))?;

                let interpolated_key_value = self.interpolate_variables(key_value, variables)?;

                // Determine if the key should be in header or query parameter
                match auth.key_in.as_deref() {
                    Some("query") => {
                        // Add as query parameter
                        req_builder = req_builder.query(&[(key_name, interpolated_key_value)]);
                    },
                    _ => {
                        // Default to header
                        req_builder = req_builder.header(key_name, interpolated_key_value);
                    }
                }
            },
            _ => {
                return Err(Error::ValidationError(format!("Unsupported authentication type: {}", auth.auth_type)));
            }
        }

        Ok(req_builder)
    }

    /// Interpolate variables in a string
    fn interpolate_variables(&self, input: &str, variables: &HashMap<String, String>) -> Result<String> {
        let mut result = input.to_string();

        // Find all variable references in the format {{variable_name}}
        let re = regex::Regex::new(r"\{\{([^{}]+)\}\}").unwrap();

        // Replace each variable reference with its value
        for capture in re.captures_iter(input) {
            let var_name = &capture[1];
            let var_placeholder = &capture[0]; // The full {{variable_name}}

            if let Some(value) = variables.get(var_name) {
                result = result.replace(var_placeholder, value);
            } else {
                // Variable not found - could either error or leave as is
                warn!("Variable '{}' not found during interpolation", var_name);
            }
        }

        Ok(result)
    }

    /// Validate response against expected values
    fn validate_response(
        &self,
        status: &reqwest::StatusCode,
        _headers: &reqwest::header::HeaderMap,
        body: &Value,
        request: &CollectionRequest,
        _duration: f64
    ) -> Result<Option<Vec<String>>> {
        let mut validation_issues = Vec::new();

        // Validate status code if expected
        if let Some(expected_status) = request.expected_status {
            if status.as_u16() != expected_status {
                validation_issues.push(format!(
                    "Status code mismatch. Expected: {}, Got: {}",
                    expected_status,
                    status.as_u16()
                ));
            }
        }

        // Validate body type if expected
        if let Some(expected_type) = &request.expected_body_type {
            let actual_type = match body {
                Value::Object(_) => "object",
                Value::Array(_) => "array",
                Value::String(_) => "string",
                Value::Number(_) => "number",
                Value::Bool(_) => "boolean",
                Value::Null => "null",
            };

            if actual_type != expected_type {
                validation_issues.push(format!(
                    "Body type mismatch. Expected: {}, Got: {}",
                    expected_type,
                    actual_type
                ));
            }
        }

        // Validate specific body fields if expected
        if let Some(expected_body) = &request.expected_body {
            if let Some(expected_obj) = expected_body.as_object() {
                for (key, expected_value) in expected_obj {
                    if let Some(actual_value) = body.get(key) {
                        if actual_value != expected_value {
                            validation_issues.push(format!(
                                "Field '{}' mismatch. Expected: {:?}, Got: {:?}",
                                key, expected_value, actual_value
                            ));
                        }
                    } else {
                        validation_issues.push(format!(
                            "Expected field '{}' not found in response body",
                            key
                        ));
                    }
                }
            }
        }

        if validation_issues.is_empty() {
            Ok(None)
        } else {
            Ok(Some(validation_issues))
        }
    }
}