shohei 2.4.1

Infrastructure diagnostics library: DNS, DNSSEC, TLS certificate inspection, email security, DNS propagation, and MCP-integrated AI agent support
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
//! HTTP(S) connectivity checker — verify web endpoint reachability and SSL/TLS.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use crate::error::{Result, ShoheError};

/// Check HTTP(S) connectivity and headers.
pub async fn check_http(req: &HttpCheckRequest) -> Result<HttpCheckResult> {
    use std::str::FromStr;
    use std::time::Instant;

    crate::api::helpers::validate_url_safety(&req.url)
        .map_err(ShoheError::Parse)?;

    let url = url::Url::from_str(&req.url)
        .map_err(|e| ShoheError::Parse(format!("invalid URL: {}", e)))?;

    let total_start = Instant::now();

    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(req.timeout_secs))
        .redirect(if req.follow_redirects {
            reqwest::redirect::Policy::limited(10)
        } else {
            reqwest::redirect::Policy::none()
        })
        .build()
        .map_err(|e| ShoheError::Transport(format!("client creation failed: {}", e)))?;

    let request_start = Instant::now();
    let response = match client.get(req.url.clone()).send().await {
        Ok(r) => r,
        Err(e) => {
            let total_ms = total_start.elapsed().as_millis() as u64;
            return Ok(HttpCheckResult {
                url: req.url.clone(),
                status_code: None,
                status_text: None,
                headers: HashMap::new(),
                hsts_present: false,
                hsts_max_age: None,
                redirect_chain: vec![],
                server_header: None,
                tls_info: None,
                security_headers: None,
                http_version: None,
                timing: Some(HttpTiming {
                    dns_ms: None,
                    connect_ms: None,
                    ttfb_ms: None,
                    total_ms,
                }),
                error: Some(e.to_string()),
            });
        }
    };
    let ttfb_ms = request_start.elapsed().as_millis() as u64;

    let status_code = Some(response.status().as_u16());
    let status_text = Some(response.status().canonical_reason().unwrap_or("").to_string());
    let final_url = response.url().to_string();
    let http_version = Some(format!("{:?}", response.version()).replace("HTTP_", "HTTP/"));

    // Extract headers
    let mut headers = HashMap::new();
    let mut hsts_max_age = None;
    let mut server_header = None;

    for (key, val) in response.headers().iter() {
        let key_str = key.to_string();
        let val_str = std::str::from_utf8(val.as_bytes())
            .unwrap_or("<invalid-utf8>")
            .to_string();

        headers.insert(key_str.clone(), val_str.clone());

        // Check for HSTS
        if key_str.to_lowercase() == "strict-transport-security" {
            if let Some(max_age_str) = val_str.split("max-age=").nth(1) {
                let age_part = max_age_str.split(';').next().unwrap_or("0").trim();
                match age_part.parse::<u64>() {
                    Ok(age) => hsts_max_age = Some(age),
                    Err(_) => {
                        // Malformed max-age value; log but don't fail
                        hsts_max_age = None;
                    }
                }
            }
        }

        // Check for Server
        if key_str.to_lowercase() == "server" {
            server_header = Some(val_str);
        }
    }

    let hsts_present = response.headers().contains_key("strict-transport-security");

    // Redirect chain: build from initial URL to final URL
    let redirect_chain = if final_url != req.url {
        let mut chain = vec![req.url.clone(), final_url.clone()];

        // Check for HTTPS -> HTTP downgrade (security issue)
        if req.url.starts_with("https://") && final_url.starts_with("http://") {
            chain.push("WARNING: HTTPS-to-HTTP downgrade detected".to_string());
        }

        chain
    } else {
        vec![]
    };

    // Extract TLS info if HTTPS
    let tls_info = if url.scheme() == "https" {
        if let Some(host) = url.host_str() {
            match crate::api::check_tls_chain(&crate::api::TlsCheckRequest {
                hostname: host.to_string(),
                port: url.port().unwrap_or(443),
                check_dane: false,
                timeout_secs: req.timeout_secs,
            })
            .await
            {
                Ok(tls_result) => Some(HttpTlsInfo {
                    protocol_version: tls_result.tls_version,
                    cipher_suite: tls_result.cipher_suite,
                    cert_valid: tls_result.valid,
                    days_until_expiry: tls_result.days_until_expiry.map(|d| d as i32),
                }),
                Err(_) => Some(HttpTlsInfo {
                    protocol_version: None,
                    cipher_suite: None,
                    cert_valid: false,
                    days_until_expiry: None,
                }),
            }
        } else {
            None
        }
    } else {
        None
    };

    // Audit security headers
    let security_headers = audit_security_headers(&headers);

    let total_ms = total_start.elapsed().as_millis() as u64;

    Ok(HttpCheckResult {
        url: req.url.clone(),
        status_code,
        status_text,
        headers,
        hsts_present,
        hsts_max_age,
        redirect_chain,
        server_header,
        tls_info,
        security_headers: Some(security_headers),
        http_version,
        timing: Some(HttpTiming {
            dns_ms: None, // DNS time is hard to measure with reqwest
            connect_ms: None, // Connection time is abstracted by reqwest
            ttfb_ms: Some(ttfb_ms),
            total_ms,
        }),
        error: None,
    })
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpCheckRequest {
    pub url: String,
    #[serde(default = "default_true")]
    pub follow_redirects: bool,
    #[serde(default = "default_timeout")]
    pub timeout_secs: u64,
}

fn default_true() -> bool { true }
fn default_timeout() -> u64 { 10 }

fn audit_security_headers(headers: &HashMap<String, String>) -> SecurityHeadersAudit {
    let mut headers_audit = HashMap::new();
    let mut score = 100u8;
    let mut improvements = Vec::new();

    // Check HSTS
    let hsts_key = headers
        .keys()
        .find(|k| k.to_lowercase() == "strict-transport-security")
        .cloned();

    if let Some(key) = hsts_key {
        let hsts_value = &headers[&key];
        let (hsts_status, hsts_good) = evaluate_hsts(hsts_value);
        headers_audit.insert(
            "Strict-Transport-Security".to_string(),
            HeaderStatus {
                present: true,
                value: Some(hsts_value.clone()),
                status: hsts_status,
            },
        );
        if !hsts_good {
            score = score.saturating_sub(15);
            improvements.push("HSTS: Increase max-age to ≥ 31536000 (1 year), add includeSubDomains and preload".to_string());
        }
    } else {
        headers_audit.insert(
            "Strict-Transport-Security".to_string(),
            HeaderStatus {
                present: false,
                value: None,
                status: "missing".to_string(),
            },
        );
        score = score.saturating_sub(20);
        improvements.push("Add Strict-Transport-Security header for HTTPS sites".to_string());
    }

    // Check CSP
    let csp_key = headers
        .keys()
        .find(|k| k.to_lowercase() == "content-security-policy")
        .cloned();

    if let Some(key) = csp_key {
        let csp_value = &headers[&key];
        let (csp_status, csp_good) = evaluate_csp(csp_value);
        headers_audit.insert(
            "Content-Security-Policy".to_string(),
            HeaderStatus {
                present: true,
                value: Some(csp_value.clone()),
                status: csp_status,
            },
        );
        if !csp_good {
            score = score.saturating_sub(10);
            improvements.push("CSP: Remove unsafe-inline and unsafe-eval".to_string());
        }
    } else {
        headers_audit.insert(
            "Content-Security-Policy".to_string(),
            HeaderStatus {
                present: false,
                value: None,
                status: "missing".to_string(),
            },
        );
        score = score.saturating_sub(15);
        improvements.push("Add Content-Security-Policy header".to_string());
    }

    // Check X-Frame-Options
    let xfo_key = headers
        .keys()
        .find(|k| k.to_lowercase() == "x-frame-options")
        .cloned();

    if let Some(key) = xfo_key {
        let xfo_value = &headers[&key];
        let xfo_good = xfo_value.to_uppercase().contains("DENY") || xfo_value.to_uppercase().contains("SAMEORIGIN");
        headers_audit.insert(
            "X-Frame-Options".to_string(),
            HeaderStatus {
                present: true,
                value: Some(xfo_value.clone()),
                status: if xfo_good { "good".to_string() } else { "weak".to_string() },
            },
        );
        if !xfo_good {
            score = score.saturating_sub(10);
        }
    } else {
        headers_audit.insert(
            "X-Frame-Options".to_string(),
            HeaderStatus {
                present: false,
                value: None,
                status: "missing".to_string(),
            },
        );
        score = score.saturating_sub(10);
        improvements.push("Add X-Frame-Options: DENY or SAMEORIGIN".to_string());
    }

    // Check X-Content-Type-Options
    let xcto_key = headers
        .keys()
        .find(|k| k.to_lowercase() == "x-content-type-options")
        .cloned();

    if let Some(key) = xcto_key {
        let xcto_value = &headers[&key];
        let xcto_good = xcto_value.to_lowercase().contains("nosniff");
        headers_audit.insert(
            "X-Content-Type-Options".to_string(),
            HeaderStatus {
                present: true,
                value: Some(xcto_value.clone()),
                status: if xcto_good { "good".to_string() } else { "weak".to_string() },
            },
        );
    } else {
        headers_audit.insert(
            "X-Content-Type-Options".to_string(),
            HeaderStatus {
                present: false,
                value: None,
                status: "missing".to_string(),
            },
        );
        score = score.saturating_sub(5);
        improvements.push("Add X-Content-Type-Options: nosniff".to_string());
    }

    // Check Referrer-Policy
    let rp_key = headers
        .keys()
        .find(|k| k.to_lowercase() == "referrer-policy")
        .cloned();

    if let Some(key) = rp_key {
        let rp_value = &headers[&key];
        let rp_good = rp_value.to_lowercase().contains("strict-origin-when-cross-origin");
        headers_audit.insert(
            "Referrer-Policy".to_string(),
            HeaderStatus {
                present: true,
                value: Some(rp_value.clone()),
                status: if rp_good { "good".to_string() } else { "weak".to_string() },
            },
        );
    } else {
        headers_audit.insert(
            "Referrer-Policy".to_string(),
            HeaderStatus {
                present: false,
                value: None,
                status: "missing".to_string(),
            },
        );
    }

    // Check Permissions-Policy
    let pp_key = headers
        .keys()
        .find(|k| k.to_lowercase() == "permissions-policy")
        .cloned();

    if pp_key.is_some() {
        headers_audit.insert(
            "Permissions-Policy".to_string(),
            HeaderStatus {
                present: true,
                value: pp_key.and_then(|k| headers.get(&k).cloned()),
                status: "good".to_string(),
            },
        );
    } else {
        headers_audit.insert(
            "Permissions-Policy".to_string(),
            HeaderStatus {
                present: false,
                value: None,
                status: "missing".to_string(),
            },
        );
    }

    SecurityHeadersAudit {
        score,
        headers: headers_audit,
        improvements,
    }
}

fn evaluate_hsts(hsts_value: &str) -> (String, bool) {
    let max_age_ok = hsts_value
        .split(';')
        .any(|part| {
            let part = part.trim();
            if let Some(age_str) = part.strip_prefix("max-age=") {
                age_str.parse::<u64>().map(|age| age >= 31536000).unwrap_or(false)
            } else {
                false
            }
        });

    let has_subdomain = hsts_value.to_lowercase().contains("includesubdomains");
    let has_preload = hsts_value.to_lowercase().contains("preload");

    let is_good = max_age_ok && has_subdomain && has_preload;
    let status = if is_good {
        "good".to_string()
    } else if max_age_ok {
        "weak".to_string()
    } else {
        "weak".to_string()
    };

    (status, is_good)
}

fn evaluate_csp(csp_value: &str) -> (String, bool) {
    let has_unsafe_inline = csp_value.to_lowercase().contains("unsafe-inline");
    let has_unsafe_eval = csp_value.to_lowercase().contains("unsafe-eval");

    let is_good = !has_unsafe_inline && !has_unsafe_eval;
    let status = if is_good { "good".to_string() } else { "weak".to_string() };

    (status, is_good)
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpCheckResult {
    pub url: String,
    pub status_code: Option<u16>,
    pub status_text: Option<String>,
    pub headers: HashMap<String, String>,
    pub hsts_present: bool,
    pub hsts_max_age: Option<u64>,
    pub redirect_chain: Vec<String>,
    pub server_header: Option<String>,
    pub tls_info: Option<HttpTlsInfo>,
    #[serde(default)]
    pub security_headers: Option<SecurityHeadersAudit>,
    #[serde(default)]
    pub http_version: Option<String>,
    #[serde(default)]
    pub timing: Option<HttpTiming>,
    pub error: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpTiming {
    /// DNS resolution time in milliseconds
    pub dns_ms: Option<u64>,
    /// TCP connection time in milliseconds (TLS included for HTTPS)
    pub connect_ms: Option<u64>,
    /// Time to first byte (TTFB) in milliseconds
    pub ttfb_ms: Option<u64>,
    /// Total request time in milliseconds
    pub total_ms: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpTlsInfo {
    pub protocol_version: Option<String>,
    pub cipher_suite: Option<String>,
    pub cert_valid: bool,
    pub days_until_expiry: Option<i32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityHeadersAudit {
    pub score: u8,  // 0-100
    pub headers: HashMap<String, HeaderStatus>,
    pub improvements: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HeaderStatus {
    pub present: bool,
    pub value: Option<String>,
    pub status: String,  // "good", "missing", "weak", etc.
}