1use std::collections::HashSet;
2use std::path::Path;
3
4use reqwest::header::HeaderMap;
5use reqwest::Method;
6use scraper::{Html, Selector};
7use serde::{Deserialize, Serialize};
8use url::Url;
9
10use crate::models::{Category, CheckOutcome, ExecutionStatus, Finding, Severity, Verdict};
11use crate::transport::{AuthMode, HttpTransport, TransportError};
12
13#[derive(Debug, Clone, Deserialize, Serialize)]
14pub struct CustomRulePack {
15 #[serde(default)]
16 pub name: String,
17 #[serde(default = "default_pack_version")]
18 pub version: String,
19 #[serde(default)]
20 pub rules: Vec<CustomRule>,
21}
22
23fn default_pack_version() -> String {
24 "1.0".to_string()
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Default)]
28#[serde(rename_all = "snake_case")]
29pub enum MatchMode {
30 #[default]
31 Substring,
32 Exact,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
36#[serde(rename_all = "snake_case")]
37pub enum CustomRuleKind {
38 HeaderMissing,
39 HeaderMatches,
40 BodyContains,
41 PathSignature,
42 ScriptVersion,
43}
44
45#[derive(Debug, Clone, Deserialize, Serialize)]
46pub struct CustomRule {
47 pub id: String,
48 pub kind: CustomRuleKind,
49 pub severity: Severity,
50 #[serde(default = "default_category")]
51 pub category: Category,
52 pub title: String,
53 pub summary: String,
54 #[serde(default)]
55 pub remediation: String,
56 #[serde(default)]
57 pub standard_ref: Option<String>,
58
59 #[serde(default)]
60 pub header: Option<String>,
61 #[serde(default)]
62 pub pattern: Option<String>,
63 #[serde(default)]
64 pub match_mode: MatchMode,
65 #[serde(default)]
66 pub case_sensitive: bool,
67 #[serde(default)]
68 pub path: Option<String>,
69 #[serde(default)]
70 pub body_contains: Option<String>,
71 #[serde(default = "default_true")]
72 pub ignore_html: bool,
73 #[serde(default)]
74 pub library: Option<String>,
75 #[serde(default)]
76 pub below_version: Option<String>,
77}
78
79fn default_category() -> Category {
80 Category::SecurityHeaders
81}
82
83fn default_true() -> bool {
84 true
85}
86
87pub fn validate_rule_pack(pack: &CustomRulePack) -> anyhow::Result<()> {
88 let ver = pack.version.trim();
89 if !ver.is_empty() && ver != "1" && ver != "1.0" && ver != "1.1" {
90 anyhow::bail!("Unsupported custom rule pack version '{ver}' (supported: 1, 1.0, 1.1)");
91 }
92
93 let mut seen_ids = HashSet::new();
94 for (idx, rule) in pack.rules.iter().enumerate() {
95 let id = rule.id.trim();
96 if id.is_empty() {
97 anyhow::bail!("Rule at index {idx} has an empty 'id'");
98 }
99 if !seen_ids.insert(id.to_string()) {
100 anyhow::bail!("Duplicate rule id '{id}' in rule pack '{}'", pack.name);
101 }
102 if rule.title.trim().is_empty() {
103 anyhow::bail!("Rule '{id}': 'title' must not be empty");
104 }
105 match rule.kind {
106 CustomRuleKind::HeaderMissing => {
107 if rule
108 .header
109 .as_deref()
110 .map(str::trim)
111 .unwrap_or("")
112 .is_empty()
113 {
114 anyhow::bail!("Rule '{id}' (header_missing) requires non-empty 'header'");
115 }
116 }
117 CustomRuleKind::HeaderMatches => {
118 if rule
119 .header
120 .as_deref()
121 .map(str::trim)
122 .unwrap_or("")
123 .is_empty()
124 {
125 anyhow::bail!("Rule '{id}' (header_matches) requires non-empty 'header'");
126 }
127 }
128 CustomRuleKind::BodyContains => {
129 if rule
130 .pattern
131 .as_deref()
132 .map(str::trim)
133 .unwrap_or("")
134 .is_empty()
135 {
136 anyhow::bail!("Rule '{id}' (body_contains) requires non-empty 'pattern'");
137 }
138 }
139 CustomRuleKind::PathSignature => {
140 let p = rule.path.as_deref().map(str::trim).unwrap_or("");
141 if p.is_empty() {
142 anyhow::bail!("Rule '{id}' (path_signature) requires non-empty 'path'");
143 }
144 if p.starts_with("http://") || p.starts_with("https://") || p.starts_with("//") {
145 anyhow::bail!(
146 "Rule '{id}' (path_signature) must use a relative path, not external URL '{p}'"
147 );
148 }
149 }
150 CustomRuleKind::ScriptVersion => {
151 if rule
152 .library
153 .as_deref()
154 .map(str::trim)
155 .unwrap_or("")
156 .is_empty()
157 {
158 anyhow::bail!("Rule '{id}' (script_version) requires non-empty 'library'");
159 }
160 let bv = rule.below_version.as_deref().map(str::trim).unwrap_or("");
161 if bv.is_empty() || parse_semver(bv).is_none() {
162 anyhow::bail!(
163 "Rule '{id}' (script_version) requires valid semver 'below_version', got '{bv}'"
164 );
165 }
166 }
167 }
168 }
169
170 Ok(())
171}
172
173pub fn load_rule_pack(path: &Path) -> anyhow::Result<CustomRulePack> {
174 let raw = std::fs::read_to_string(path)?;
175 let pack: CustomRulePack = serde_json::from_str(&raw)?;
176 validate_rule_pack(&pack)?;
177 Ok(pack)
178}
179
180pub fn load_rules_from_paths(paths: &[impl AsRef<Path>]) -> anyhow::Result<Vec<CustomRule>> {
181 let mut all = Vec::new();
182 let mut global_ids = HashSet::new();
183 for p in paths {
184 let pack = load_rule_pack(p.as_ref())?;
185 for r in pack.rules {
186 if !global_ids.insert(r.id.clone()) {
187 anyhow::bail!("Duplicate rule id '{}' across loaded rule packs", r.id);
188 }
189 all.push(r);
190 }
191 }
192 Ok(all)
193}
194
195fn match_text(haystack: &str, needle: &str, mode: MatchMode, case_sensitive: bool) -> bool {
196 match (mode, case_sensitive) {
197 (MatchMode::Substring, true) => haystack.contains(needle),
198 (MatchMode::Substring, false) => haystack
199 .to_ascii_lowercase()
200 .contains(&needle.to_ascii_lowercase()),
201 (MatchMode::Exact, true) => haystack.trim() == needle.trim(),
202 (MatchMode::Exact, false) => haystack.trim().eq_ignore_ascii_case(needle.trim()),
203 }
204}
205
206pub fn evaluate_page_rules(
207 rules: &[CustomRule],
208 headers: &HeaderMap,
209 body: Option<&str>,
210 page_url: &Url,
211) -> Vec<Finding> {
212 let mut findings = Vec::new();
213
214 for rule in rules {
215 match rule.kind {
216 CustomRuleKind::HeaderMissing => {
217 let Some(hdr_name) = &rule.header else {
218 continue;
219 };
220 if headers.get(hdr_name.as_str()).is_none() {
221 findings.push(Finding {
222 id: rule.id.clone(),
223 category: rule.category,
224 severity: rule.severity,
225 title: rule.title.clone(),
226 summary: rule.summary.clone(),
227 evidence: Some(format!("{} (missing header: {hdr_name})", page_url)),
228 remediation: rule.remediation.clone(),
229 standard_ref: rule.standard_ref.clone(),
230 confidence: crate::models::Confidence::High,
231 });
232 }
233 }
234 CustomRuleKind::HeaderMatches => {
235 let Some(hdr_name) = &rule.header else {
236 continue;
237 };
238 if let Some(val) = headers.get(hdr_name.as_str()).and_then(|v| v.to_str().ok()) {
239 let matched = match &rule.pattern {
240 None => true,
241 Some(pat) => match_text(val, pat, rule.match_mode, rule.case_sensitive),
242 };
243 if matched {
244 findings.push(Finding {
245 id: rule.id.clone(),
246 category: rule.category,
247 severity: rule.severity,
248 title: rule.title.clone(),
249 summary: rule.summary.clone(),
250 evidence: Some(format!("{hdr_name}: {val}")),
251 remediation: rule.remediation.clone(),
252 standard_ref: rule.standard_ref.clone(),
253 confidence: crate::models::Confidence::High,
254 });
255 }
256 }
257 }
258 CustomRuleKind::BodyContains => {
259 let (Some(text), Some(pat)) = (body, &rule.pattern) else {
260 continue;
261 };
262 if match_text(text, pat, rule.match_mode, rule.case_sensitive) {
263 findings.push(Finding {
264 id: rule.id.clone(),
265 category: rule.category,
266 severity: rule.severity,
267 title: rule.title.clone(),
268 summary: rule.summary.clone(),
269 evidence: Some(format!("{page_url} (matched: {pat})")),
270 remediation: rule.remediation.clone(),
271 standard_ref: rule.standard_ref.clone(),
272 confidence: crate::models::Confidence::High,
273 });
274 }
275 }
276 CustomRuleKind::ScriptVersion => {
277 let (Some(text), Some(lib), Some(min_ver)) =
278 (body, &rule.library, &rule.below_version)
279 else {
280 continue;
281 };
282 let Some(min_tuple) = parse_semver(min_ver) else {
283 continue;
284 };
285 let doc = Html::parse_document(text);
286 let Ok(sel) = Selector::parse("script[src]") else {
287 continue;
288 };
289 for el in doc.select(&sel) {
290 if let Some(src) = el.value().attr("src") {
291 let lower = src.to_ascii_lowercase();
292 if let Some(found_ver) =
293 extract_version_near(&lower, &lib.to_ascii_lowercase())
294 {
295 if let Some(found_tuple) = parse_semver(&found_ver) {
296 if found_tuple < min_tuple {
297 findings.push(Finding {
298 id: rule.id.clone(),
299 category: rule.category,
300 severity: rule.severity,
301 title: rule.title.clone(),
302 summary: rule.summary.clone(),
303 evidence: Some(format!(
304 "{src} (version {found_ver} < {min_ver})"
305 )),
306 remediation: rule.remediation.clone(),
307 standard_ref: rule.standard_ref.clone(),
308 confidence: crate::models::Confidence::Medium,
309 });
310 break;
311 }
312 }
313 }
314 }
315 }
316 }
317 CustomRuleKind::PathSignature => {}
318 }
319 }
320
321 findings
322}
323
324pub async fn evaluate_path_rules(
325 rules: &[CustomRule],
326 transport: &HttpTransport,
327 base_url: &Url,
328 auth_context: &str,
329) -> (Vec<Finding>, Vec<CheckOutcome>) {
330 let mut findings = Vec::new();
331 let mut outcomes = Vec::new();
332
333 for rule in rules {
334 if rule.kind != CustomRuleKind::PathSignature {
335 continue;
336 }
337 let Some(path) = &rule.path else {
338 continue;
339 };
340 let target_url = match transport.resolve_in_scope(base_url, path) {
341 Ok(u) => u,
342 Err(e) => {
343 outcomes.push(CheckOutcome {
344 check_id: rule.id.clone(),
345 category: rule.category,
346 location: path.clone(),
347 auth_context: auth_context.to_string(),
348 status: ExecutionStatus::Skipped,
349 verdict: Verdict::Inconclusive,
350 reason: Some(e.to_string()),
351 });
352 continue;
353 }
354 };
355
356 let resp = match transport
357 .send(
358 Method::GET,
359 &target_url,
360 AuthMode::Anonymous,
361 &[],
362 Some(65_536),
363 )
364 .await
365 {
366 Ok(r) => r,
367 Err(TransportError::Cancelled) => {
368 outcomes.push(CheckOutcome {
369 check_id: rule.id.clone(),
370 category: rule.category,
371 location: target_url.to_string(),
372 auth_context: auth_context.to_string(),
373 status: ExecutionStatus::Cancelled,
374 verdict: Verdict::Inconclusive,
375 reason: Some("cancelled".into()),
376 });
377 break;
378 }
379 Err(e) => {
380 outcomes.push(CheckOutcome {
381 check_id: rule.id.clone(),
382 category: rule.category,
383 location: target_url.to_string(),
384 auth_context: auth_context.to_string(),
385 status: ExecutionStatus::Error,
386 verdict: Verdict::Inconclusive,
387 reason: Some(e.to_string()),
388 });
389 continue;
390 }
391 };
392
393 if !(200..300).contains(&resp.status) {
394 outcomes.push(CheckOutcome {
395 check_id: rule.id.clone(),
396 category: rule.category,
397 location: target_url.to_string(),
398 auth_context: auth_context.to_string(),
399 status: ExecutionStatus::Completed,
400 verdict: Verdict::Pass,
401 reason: Some(format!("HTTP {}", resp.status)),
402 });
403 continue;
404 }
405
406 let ct = resp
407 .headers
408 .get(reqwest::header::CONTENT_TYPE)
409 .and_then(|v| v.to_str().ok())
410 .unwrap_or("")
411 .to_ascii_lowercase();
412 let text = std::str::from_utf8(&resp.body).unwrap_or("");
413 let trimmed = text.trim_start();
414 let is_html = ct.contains("text/html")
415 || trimmed.starts_with("<!DOCTYPE")
416 || trimmed.starts_with("<!doctype")
417 || trimmed.starts_with("<html");
418
419 if rule.ignore_html && is_html {
420 outcomes.push(CheckOutcome {
421 check_id: rule.id.clone(),
422 category: rule.category,
423 location: target_url.to_string(),
424 auth_context: auth_context.to_string(),
425 status: ExecutionStatus::Completed,
426 verdict: Verdict::Pass,
427 reason: Some("HTML fallback ignored".into()),
428 });
429 continue;
430 }
431
432 let body_ok = match &rule.body_contains {
433 None => true,
434 Some(pat) => match_text(text, pat, rule.match_mode, rule.case_sensitive),
435 };
436
437 if body_ok {
438 findings.push(Finding {
439 id: rule.id.clone(),
440 category: rule.category,
441 severity: rule.severity,
442 title: rule.title.clone(),
443 summary: rule.summary.clone(),
444 evidence: Some(transport.redactor.sanitize_url(&target_url)),
445 remediation: rule.remediation.clone(),
446 standard_ref: rule.standard_ref.clone(),
447 confidence: crate::models::Confidence::High,
448 });
449 outcomes.push(CheckOutcome {
450 check_id: rule.id.clone(),
451 category: rule.category,
452 location: target_url.to_string(),
453 auth_context: auth_context.to_string(),
454 status: ExecutionStatus::Completed,
455 verdict: Verdict::Fail,
456 reason: None,
457 });
458 } else {
459 outcomes.push(CheckOutcome {
460 check_id: rule.id.clone(),
461 category: rule.category,
462 location: target_url.to_string(),
463 auth_context: auth_context.to_string(),
464 status: ExecutionStatus::Completed,
465 verdict: Verdict::Pass,
466 reason: None,
467 });
468 }
469 }
470
471 (findings, outcomes)
472}
473
474fn parse_semver(raw: &str) -> Option<(u32, u32, u32)> {
475 let mut nums = raw.split('.').take(3).filter_map(|p| p.parse::<u32>().ok());
476 let maj = nums.next()?;
477 let min = nums.next().unwrap_or(0);
478 let pat = nums.next().unwrap_or(0);
479 Some((maj, min, pat))
480}
481
482fn extract_version_near(lower_src: &str, lib_name: &str) -> Option<String> {
483 let idx = lower_src.find(lib_name)?;
484 let tail = &lower_src[idx + lib_name.len()..];
485 let window: String = tail.chars().take(36).collect();
486 let bytes = window.as_bytes();
487 for start in 0..bytes.len() {
488 if bytes[start].is_ascii_digit() {
489 if start > 0 && bytes[start - 1].is_ascii_alphanumeric() {
490 continue;
491 }
492 let slice = &window[start..];
493 let ver: String = slice
494 .chars()
495 .take_while(|c| c.is_ascii_digit() || *c == '.')
496 .collect();
497 let ver = ver.trim_end_matches('.').to_string();
498 if ver.contains('.') && parse_semver(&ver).is_some() {
499 return Some(ver);
500 }
501 }
502 }
503 None
504}
505
506#[cfg(test)]
507mod tests {
508 use super::*;
509 use reqwest::header::{HeaderName, HeaderValue};
510
511 #[test]
512 fn evaluates_custom_header_body_and_script_rules() {
513 let json_pack = r#"{
514 "name": "Test Pack",
515 "version": "1.0",
516 "rules": [
517 {
518 "id": "CUST-HDR-MISS",
519 "kind": "header_missing",
520 "severity": "medium",
521 "category": "security_headers",
522 "title": "Missing X-Custom",
523 "summary": "Custom header missing",
524 "remediation": "Add X-Custom",
525 "header": "x-custom"
526 },
527 {
528 "id": "CUST-BODY",
529 "kind": "body_contains",
530 "severity": "low",
531 "category": "information_disclosure",
532 "title": "Debug marker",
533 "summary": "Marker found",
534 "remediation": "Remove marker",
535 "pattern": "INTERNAL_DEBUG"
536 },
537 {
538 "id": "CUST-LIB",
539 "kind": "script_version",
540 "severity": "high",
541 "category": "client_html",
542 "title": "Old lib",
543 "summary": "Upgrade lib",
544 "remediation": "Upgrade to 2.0",
545 "library": "mylib",
546 "below_version": "2.0.0"
547 }
548 ]
549 }"#;
550 let pack: CustomRulePack = serde_json::from_str(json_pack).unwrap();
551 validate_rule_pack(&pack).unwrap();
552
553 let mut headers = HeaderMap::new();
554 headers.insert(
555 HeaderName::from_static("server"),
556 HeaderValue::from_static("test"),
557 );
558 let html =
559 r#"<html><!-- INTERNAL_DEBUG --><script src="/js/mylib-1.4.2.min.js"></script></html>"#;
560 let url = Url::parse("https://example.test/").unwrap();
561
562 let found = evaluate_page_rules(&pack.rules, &headers, Some(html), &url);
563 let ids: Vec<&str> = found.iter().map(|f| f.id.as_str()).collect();
564 assert_eq!(ids, vec!["CUST-HDR-MISS", "CUST-BODY", "CUST-LIB"]);
565 }
566
567 #[test]
568 fn rejects_duplicate_ids_external_urls_and_unknown_version() {
569 let dup_json = r#"{
570 "name": "Dup",
571 "version": "1.0",
572 "rules": [
573 {"id":"R1","kind":"header_missing","severity":"low","title":"A","summary":"","header":"x-a"},
574 {"id":"R1","kind":"header_missing","severity":"low","title":"B","summary":"","header":"x-b"}
575 ]
576 }"#;
577 let dup_pack: CustomRulePack = serde_json::from_str(dup_json).unwrap();
578 assert!(validate_rule_pack(&dup_pack).is_err());
579
580 let ext_json = r#"{
581 "name": "Ext",
582 "version": "1.0",
583 "rules": [
584 {"id":"R-EXT","kind":"path_signature","severity":"low","title":"Ext","summary":"","path":"https://evil.test/a"}
585 ]
586 }"#;
587 let ext_pack: CustomRulePack = serde_json::from_str(ext_json).unwrap();
588 assert!(validate_rule_pack(&ext_pack).is_err());
589
590 let ver_json = r#"{"name":"Old","version":"99.0","rules":[]}"#;
591 let ver_pack: CustomRulePack = serde_json::from_str(ver_json).unwrap();
592 assert!(validate_rule_pack(&ver_pack).is_err());
593 }
594}