zapreq 0.1.6

A fast, friendly HTTP client for the terminal
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
use anyhow::Result;
use chrono::Utc;
use regex::Regex;
use serde::Serialize;
use serde_json::Value;

use crate::cli::{SeverityLevel, SourceSelector};
use crate::config::Config;
use crate::localdb::{open_connection, record_report};
use crate::sources::{execute_record, resolve_records, RequestRecord};

#[derive(Clone, Debug, Serialize)]
pub struct SecurityFinding {
    pub endpoint: String,
    pub severity: String,
    pub title: String,
    pub impact: String,
    pub remediation: String,
    pub risk_score: u8,
    pub evidence: String,
}

#[derive(Clone, Debug, Serialize)]
pub struct SecurityReport {
    pub source: String,
    pub generated_at: String,
    pub live_scan: bool,
    pub findings: Vec<SecurityFinding>,
    pub report_id: i64,
}

pub fn run_scan(
    selector: &SourceSelector,
    threshold: SeverityLevel,
    live_scan: bool,
    config: &Config,
) -> Result<SecurityReport> {
    let records = resolve_records(selector)?;
    let source = source_name(selector);
    let mut findings = Vec::new();
    for record in &records {
        findings.extend(scan_record(record));
        if live_scan {
            findings.extend(scan_live(record, config));
        }
    }
    findings.retain(|finding| meets_threshold(&finding.severity, threshold));
    findings.sort_by_key(|finding| severity_rank(&finding.severity));
    findings.reverse();

    let summary = format!(
        "{} finding(s) across {} request(s)",
        findings.len(),
        records.len()
    );
    let payload = SecurityReport {
        source: source.clone(),
        generated_at: Utc::now().to_rfc3339(),
        live_scan,
        findings,
        report_id: 0,
    };
    let payload_json = serde_json::to_string_pretty(&payload)?;
    let conn = open_connection()?;
    let report_id = record_report(&conn, "security", &source, &summary, &payload_json)?;

    Ok(SecurityReport {
        report_id,
        ..payload
    })
}

pub fn render_report(report: &SecurityReport) -> String {
    let mut out = String::new();
    out.push_str(&format!(
        "Security scan for {} [{}] report_id={}\n",
        report.source, report.generated_at, report.report_id
    ));
    if report.findings.is_empty() {
        out.push_str("No findings matched the selected threshold.\n");
        return out;
    }
    for finding in &report.findings {
        out.push_str(&format!(
            "- [{}] {} :: {} (risk {})\n  Impact: {}\n  Remediation: {}\n  Evidence: {}\n",
            finding.severity,
            finding.endpoint,
            finding.title,
            finding.risk_score,
            finding.impact,
            finding.remediation,
            finding.evidence
        ));
    }
    out
}

fn scan_record(record: &RequestRecord) -> Vec<SecurityFinding> {
    let mut findings = Vec::new();
    let url_lower = record.url.to_ascii_lowercase();
    let joined_items = record.items.join("\n");
    let joined_headers = record
        .headers
        .iter()
        .map(|(k, v)| format!("{k}:{v}"))
        .collect::<Vec<_>>()
        .join("\n");
    let auth_header = record
        .headers
        .iter()
        .find(|(k, _)| k.eq_ignore_ascii_case("authorization"))
        .map(|(_, v)| v.clone())
        .unwrap_or_default();

    if url_lower.starts_with("http://") {
        findings.push(finding(
            record,
            "high",
            "Transport security disabled",
            "Requests over plain HTTP can expose credentials and payloads in transit.",
            "Use HTTPS endpoints and enforce TLS for all environments.",
            82,
            &record.url,
        ));
    }

    if auth_header.is_empty()
        && !joined_items.to_ascii_lowercase().contains("authorization:")
        && !joined_items.to_ascii_lowercase().contains("token")
        && !joined_items.to_ascii_lowercase().contains("apikey")
    {
        findings.push(finding(
            record,
            "medium",
            "No authentication detected",
            "Unauthenticated endpoints are more exposed to unauthorized access and BOLA-style abuse.",
            "Document the intended auth model and require auth where the endpoint is not explicitly public.",
            58,
            "No auth header, bearer token, or api key found in the saved request.",
        ));
    }

    if auth_header.to_ascii_lowercase().starts_with("basic ") {
        findings.push(finding(
            record,
            "high",
            "Basic authentication configured",
            "Basic auth is easy to mishandle and often relies on long-lived credentials.",
            "Prefer short-lived bearer tokens or signed requests with secret rotation.",
            76,
            &auth_header,
        ));
    }

    if contains_secret(&record.url)
        || contains_secret(&joined_items)
        || contains_secret(&joined_headers)
        || contains_aws_key(&record.url)
        || contains_aws_key(&joined_items)
        || contains_jwt(&record.url)
        || contains_jwt(&joined_items)
    {
        findings.push(finding(
            record,
            "critical",
            "Potential secret exposure",
            "Hardcoded credentials or tokens can be extracted from local request definitions and copied into logs or exports.",
            "Move credentials to the local secret store or environment profiles and scrub them from saved collections.",
            95,
            "Detected token-, key-, or credential-like content in URL, headers, or request items.",
        ));
    }

    if has_sensitive_query(&record.url) {
        findings.push(finding(
            record,
            "high",
            "Sensitive data appears in query parameters",
            "Secrets in URLs leak into logs, analytics systems, browser history, and proxies.",
            "Send secrets in headers or request bodies instead of query parameters.",
            84,
            &record.url,
        ));
    }

    if record.url.contains('{')
        || record.url.contains("}/")
        || Regex::new(r"/\d+(/|$)")
            .expect("regex")
            .is_match(&record.url)
    {
        findings.push(finding(
            record,
            "medium",
            "Potential object-level authorization risk",
            "Endpoints with path identifiers commonly require strong authorization checks to prevent BOLA-style access.",
            "Verify resource ownership and authorization checks for every identifier-based lookup.",
            61,
            &record.url,
        ));
    }

    if joined_items.to_ascii_lowercase().contains("callback")
        || joined_items.to_ascii_lowercase().contains("webhook")
        || joined_items.to_ascii_lowercase().contains("redirect_uri")
    {
        findings.push(finding(
            record,
            "low",
            "Potential SSRF-sensitive input",
            "Callback and redirect-style fields can be abused if upstream services fetch attacker-controlled URLs.",
            "Validate destinations against an allowlist and reject internal/private network targets.",
            38,
            "callback/webhook/redirect style field found in request items.",
        ));
    }

    findings
}

fn scan_live(record: &RequestRecord, config: &Config) -> Vec<SecurityFinding> {
    let method = record.method.trim().to_ascii_uppercase();
    if method != "GET" && method != "HEAD" {
        return Vec::new();
    }
    if !record.url.starts_with("http://") && !record.url.starts_with("https://") {
        return Vec::new();
    }

    let mut findings = Vec::new();
    let Ok((_trace, response, _elapsed_ms)) = execute_record(record, config) else {
        return vec![finding(
            record,
            "low",
            "Live scan skipped",
            "The response could not be fetched, so header-level checks were not completed.",
            "Re-run the security scan when the endpoint is reachable from this machine.",
            24,
            "request execution failed during live scan",
        )];
    };

    let mut headers = std::collections::HashMap::new();
    for (key, value) in &response.headers {
        headers.insert(key.to_ascii_lowercase(), value.clone());
    }

    if record.url.starts_with("https://") && !headers.contains_key("strict-transport-security") {
        findings.push(finding(
            record,
            "medium",
            "Missing HSTS header",
            "Without HSTS, browsers may downgrade or reattempt insecure transport.",
            "Add Strict-Transport-Security with a long max-age and includeSubDomains where appropriate.",
            55,
            "strict-transport-security header not present",
        ));
    }

    for (header, title) in [
        ("content-security-policy", "Missing CSP header"),
        ("x-frame-options", "Missing X-Frame-Options header"),
        (
            "x-content-type-options",
            "Missing X-Content-Type-Options header",
        ),
    ] {
        if !headers.contains_key(header) {
            findings.push(finding(
                record,
                "low",
                title,
                "Missing defensive headers can weaken browser-side protection for API consoles or HTML error pages.",
                "Return the recommended security headers consistently from the gateway or service.",
                29,
                header,
            ));
        }
    }

    if !headers.contains_key("x-ratelimit-limit")
        && !headers.contains_key("ratelimit-limit")
        && !headers.contains_key("retry-after")
    {
        findings.push(finding(
            record,
            "low",
            "No rate-limiting indicators observed",
            "Missing rate-limit headers can make client-side backoff and abuse monitoring harder.",
            "Expose standard rate-limit headers or document the throttling model for this API.",
            31,
            "x-ratelimit-limit/ratelimit-limit/retry-after not present",
        ));
    }

    if let Ok(json) = serde_json::from_slice::<Value>(&response.body) {
        let mut sensitive_paths = Vec::new();
        collect_sensitive_json_paths("", &json, &mut sensitive_paths);
        if !sensitive_paths.is_empty() {
            findings.push(finding(
                record,
                "high",
                "Potential excessive data exposure",
                "The live response contained sensitive-looking fields that may not belong in routine client payloads.",
                "Review response filtering, serializer policies, and least-data principles for this endpoint.",
                79,
                &sensitive_paths.join(", "),
            ));
        }
    }

    findings
}

fn finding(
    record: &RequestRecord,
    severity: &str,
    title: &str,
    impact: &str,
    remediation: &str,
    risk_score: u8,
    evidence: &str,
) -> SecurityFinding {
    SecurityFinding {
        endpoint: record.source_label.clone(),
        severity: severity.to_string(),
        title: title.to_string(),
        impact: impact.to_string(),
        remediation: remediation.to_string(),
        risk_score,
        evidence: evidence.to_string(),
    }
}

fn source_name(selector: &SourceSelector) -> String {
    if let Some(alias) = selector.alias.as_deref() {
        return format!("alias:{alias}");
    }
    if let Some(workspace) = selector.workspace.as_deref() {
        if let Some(request) = selector.request.as_deref() {
            return format!("request:{workspace}/{request}");
        }
        return format!("workspace:{workspace}");
    }
    selector
        .file
        .as_deref()
        .map(|path| format!("file:{path}"))
        .unwrap_or_else(|| "unknown".to_string())
}

fn meets_threshold(severity: &str, threshold: SeverityLevel) -> bool {
    severity_rank(severity) >= threshold_rank(threshold)
}

fn threshold_rank(level: SeverityLevel) -> u8 {
    match level {
        SeverityLevel::Low => 1,
        SeverityLevel::Medium => 2,
        SeverityLevel::High => 3,
        SeverityLevel::Critical => 4,
    }
}

fn severity_rank(level: &str) -> u8 {
    match level.to_ascii_lowercase().as_str() {
        "critical" => 4,
        "high" => 3,
        "medium" => 2,
        _ => 1,
    }
}

fn contains_secret(value: &str) -> bool {
    let lower = value.to_ascii_lowercase();
    [
        "password=",
        "secret=",
        "token=",
        "apikey=",
        "api_key=",
        "client_secret",
    ]
    .iter()
    .any(|needle| lower.contains(needle))
}

fn contains_aws_key(value: &str) -> bool {
    Regex::new(r"AKIA[0-9A-Z]{16}")
        .expect("regex")
        .is_match(value)
}

fn contains_jwt(value: &str) -> bool {
    Regex::new(r"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9._-]+\.[A-Za-z0-9._-]+")
        .expect("regex")
        .is_match(value)
}

fn has_sensitive_query(url: &str) -> bool {
    let lower = url.to_ascii_lowercase();
    [
        "access_token=",
        "token=",
        "password=",
        "apikey=",
        "api_key=",
    ]
    .iter()
    .any(|needle| lower.contains(needle))
}

fn collect_sensitive_json_paths(path: &str, value: &Value, output: &mut Vec<String>) {
    match value {
        Value::Object(map) => {
            for (key, child) in map {
                let next = if path.is_empty() {
                    key.to_string()
                } else {
                    format!("{path}.{key}")
                };
                let lowered = key.to_ascii_lowercase();
                if matches!(
                    lowered.as_str(),
                    "password"
                        | "secret"
                        | "token"
                        | "access_token"
                        | "refresh_token"
                        | "api_key"
                        | "apikey"
                ) {
                    output.push(next.clone());
                }
                collect_sensitive_json_paths(&next, child, output);
            }
        }
        Value::Array(items) => {
            for (idx, child) in items.iter().enumerate() {
                let next = format!("{path}[{idx}]");
                collect_sensitive_json_paths(&next, child, output);
            }
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use super::{contains_aws_key, contains_jwt, has_sensitive_query};

    #[test]
    fn aws_key_detection_works() {
        assert!(contains_aws_key("AKIAIOSFODNN7EXAMPLE"));
    }

    #[test]
    fn jwt_detection_works() {
        assert!(contains_jwt(
            "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjMifQ.signature"
        ));
    }

    #[test]
    fn sensitive_query_detection_works() {
        assert!(has_sensitive_query(
            "https://example.com?a=1&access_token=secret"
        ));
    }
}