microclaw-engine 0.2.0

Channel-independent Agent Engine and default services for MicroClaw
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
use std::collections::{HashMap, HashSet};
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};

use microclaw_core::text::floor_char_boundary;
use reqwest::Url;
use tracing::warn;

use crate::internal::tool_runtime::web_content_validation::{
    validate_web_content_with_config, WebContentValidationConfig,
};
use crate::internal::tool_runtime::web_html::{extract_primary_html, html_to_text};

fn http_client(timeout_secs: u64) -> reqwest::Client {
    static CLIENTS: OnceLock<Mutex<HashMap<u64, reqwest::Client>>> = OnceLock::new();
    let cache = CLIENTS.get_or_init(|| Mutex::new(HashMap::new()));
    let mut cache = cache.lock().unwrap_or_else(|e| e.into_inner());
    if let Some(client) = cache.get(&timeout_secs) {
        return client.clone();
    }
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(timeout_secs))
        .redirect(reqwest::redirect::Policy::limited(5))
        .user_agent("MicroClaw/1.0")
        .build()
        .expect("failed to build HTTP client");
    cache.insert(timeout_secs, client.clone());
    client
}

fn http_client_no_redirect(timeout_secs: u64) -> reqwest::Client {
    static CLIENTS: OnceLock<Mutex<HashMap<u64, reqwest::Client>>> = OnceLock::new();
    let cache = CLIENTS.get_or_init(|| Mutex::new(HashMap::new()));
    let mut cache = cache.lock().unwrap_or_else(|e| e.into_inner());
    if let Some(client) = cache.get(&timeout_secs) {
        return client.clone();
    }
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(timeout_secs))
        .redirect(reqwest::redirect::Policy::none())
        .user_agent("MicroClaw/1.0")
        .build()
        .expect("failed to build HTTP client");
    cache.insert(timeout_secs, client.clone());
    client
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WebFetchFeedMode {
    Allowlist,
    Denylist,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WebFetchFeedFormat {
    Lines,
    CsvFirstColumn,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct WebFetchFeedSource {
    #[serde(default = "default_enabled")]
    pub enabled: bool,
    #[serde(default = "default_feed_mode")]
    pub mode: WebFetchFeedMode,
    pub url: String,
    #[serde(default = "default_feed_format")]
    pub format: WebFetchFeedFormat,
    #[serde(default = "default_feed_refresh_interval_secs")]
    pub refresh_interval_secs: u64,
    #[serde(default = "default_feed_timeout_secs")]
    pub timeout_secs: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct WebFetchFeedSyncConfig {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default = "default_feed_fail_open")]
    pub fail_open: bool,
    #[serde(default = "default_feed_max_entries_per_source")]
    pub max_entries_per_source: usize,
    #[serde(default)]
    pub sources: Vec<WebFetchFeedSource>,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct WebFetchUrlValidationConfig {
    #[serde(default = "default_enabled")]
    pub enabled: bool,
    #[serde(default = "default_allowed_schemes")]
    pub allowed_schemes: Vec<String>,
    #[serde(default)]
    pub allowlist_hosts: Vec<String>,
    #[serde(default)]
    pub denylist_hosts: Vec<String>,
    #[serde(default = "default_block_private_ips")]
    pub block_private_ips: bool,
    #[serde(default)]
    pub feed_sync: WebFetchFeedSyncConfig,
}

struct FeedCacheEntry {
    fetched_at: Instant,
    entries: Vec<String>,
}

const fn default_enabled() -> bool {
    true
}

const fn default_feed_mode() -> WebFetchFeedMode {
    WebFetchFeedMode::Denylist
}

const fn default_feed_format() -> WebFetchFeedFormat {
    WebFetchFeedFormat::Lines
}

const fn default_feed_refresh_interval_secs() -> u64 {
    3600
}

const fn default_feed_timeout_secs() -> u64 {
    10
}

const fn default_feed_fail_open() -> bool {
    true
}

const fn default_feed_max_entries_per_source() -> usize {
    10_000
}

const fn default_block_private_ips() -> bool {
    true
}

fn default_allowed_schemes() -> Vec<String> {
    vec!["https".to_string(), "http".to_string()]
}

impl Default for WebFetchFeedSyncConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            fail_open: default_feed_fail_open(),
            max_entries_per_source: default_feed_max_entries_per_source(),
            sources: Vec::new(),
        }
    }
}

impl WebFetchFeedSyncConfig {
    pub fn normalize(&mut self) {
        if self.max_entries_per_source == 0 {
            self.max_entries_per_source = default_feed_max_entries_per_source();
        }

        for source in &mut self.sources {
            source.url = source.url.trim().to_string();
            if source.refresh_interval_secs == 0 {
                source.refresh_interval_secs = default_feed_refresh_interval_secs();
            }
            if source.timeout_secs == 0 {
                source.timeout_secs = default_feed_timeout_secs();
            }
        }

        self.sources.retain(|s| !s.url.is_empty());
    }
}

impl Default for WebFetchUrlValidationConfig {
    fn default() -> Self {
        Self {
            enabled: default_enabled(),
            allowed_schemes: default_allowed_schemes(),
            allowlist_hosts: Vec::new(),
            denylist_hosts: Vec::new(),
            block_private_ips: default_block_private_ips(),
            feed_sync: WebFetchFeedSyncConfig::default(),
        }
    }
}

impl WebFetchUrlValidationConfig {
    pub fn normalize(&mut self) {
        self.allowed_schemes = self
            .allowed_schemes
            .drain(..)
            .map(|v| v.trim().to_ascii_lowercase())
            .filter(|v| !v.is_empty())
            .collect();
        if self.allowed_schemes.is_empty() {
            self.allowed_schemes = default_allowed_schemes();
        }

        normalize_host_list(&mut self.allowlist_hosts);
        normalize_host_list(&mut self.denylist_hosts);
        self.feed_sync.normalize();
    }
}

fn normalize_host_list(hosts: &mut Vec<String>) {
    let mut seen = HashSet::new();
    let mut normalized = Vec::new();

    for host in hosts.drain(..) {
        let Some(host) = normalize_host_candidate(&host) else {
            continue;
        };
        if seen.insert(host.clone()) {
            normalized.push(host);
        }
    }

    *hosts = normalized;
}

fn normalize_host_candidate(input: &str) -> Option<String> {
    let mut token = input.trim().to_string();
    if token.is_empty() {
        return None;
    }

    // Support feeds that include full URLs.
    if let Ok(parsed) = Url::parse(&token) {
        token = parsed.host_str()?.to_string();
    }

    // Support CSV and path-like entries.
    if let Some((head, _)) = token.split_once('/') {
        token = head.to_string();
    }

    token = token
        .trim()
        .trim_start_matches("*.")
        .trim_start_matches('.')
        .to_string();

    // Drop :port for domain and IPv4 host entries.
    if token.matches(':').count() == 1 {
        if let Some((head, _)) = token.split_once(':') {
            token = head.to_string();
        }
    }

    token = token.trim_end_matches('.').to_ascii_lowercase();
    if token.is_empty() {
        None
    } else {
        Some(token)
    }
}

fn host_matches_rule(host: &str, rule: &str) -> bool {
    host == rule || host.ends_with(&format!(".{rule}"))
}

fn resolve_and_validate_redirect_target(
    current_url: &Url,
    location: &str,
    url_validation: &WebFetchUrlValidationConfig,
) -> Result<Url, String> {
    let next = current_url
        .join(location)
        .map_err(|e| format!("invalid redirect target '{location}': {e}"))?;
    validate_web_fetch_url(next.as_str(), url_validation.clone())?;
    Ok(next)
}

fn feed_cache() -> &'static Mutex<HashMap<String, FeedCacheEntry>> {
    static CACHE: OnceLock<Mutex<HashMap<String, FeedCacheEntry>>> = OnceLock::new();
    CACHE.get_or_init(|| Mutex::new(HashMap::new()))
}

fn parse_feed_entries(raw: &str, format: &WebFetchFeedFormat, max_entries: usize) -> Vec<String> {
    let mut seen = HashSet::new();
    let mut out = Vec::new();

    for line in raw.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        let candidate = match format {
            WebFetchFeedFormat::Lines => line,
            WebFetchFeedFormat::CsvFirstColumn => line.split(',').next().unwrap_or(""),
        };

        let Some(host) = normalize_host_candidate(candidate) else {
            continue;
        };

        if seen.insert(host.clone()) {
            out.push(host);
            if out.len() >= max_entries {
                break;
            }
        }
    }

    out
}

async fn fetch_feed_entries(
    source: &WebFetchFeedSource,
    fail_open: bool,
    max_entries_per_source: usize,
) -> Result<Vec<String>, String> {
    if let Some(inline) = source.url.strip_prefix("inline:") {
        return Ok(parse_feed_entries(
            inline,
            &source.format,
            max_entries_per_source,
        ));
    }

    let cache_key = format!("{}::{:?}", source.url, source.format);
    let ttl = Duration::from_secs(source.refresh_interval_secs.max(1));

    let stale_entries = {
        let cache = feed_cache().lock().unwrap_or_else(|e| e.into_inner());
        if let Some(entry) = cache.get(&cache_key) {
            if entry.fetched_at.elapsed() < ttl {
                return Ok(entry.entries.clone());
            }
            Some(entry.entries.clone())
        } else {
            None
        }
    };

    let request_result = async {
        let client = http_client(source.timeout_secs.max(1));
        let resp = client
            .get(&source.url)
            .send()
            .await
            .map_err(|e| e.to_string())?;
        if !resp.status().is_success() {
            return Err(format!("feed returned HTTP {}", resp.status()));
        }
        let body = resp.text().await.map_err(|e| e.to_string())?;
        Ok(parse_feed_entries(
            &body,
            &source.format,
            max_entries_per_source,
        ))
    }
    .await;

    match request_result {
        Ok(entries) => {
            let mut cache = feed_cache().lock().unwrap_or_else(|e| e.into_inner());
            cache.insert(
                cache_key,
                FeedCacheEntry {
                    fetched_at: Instant::now(),
                    entries: entries.clone(),
                },
            );
            Ok(entries)
        }
        Err(err) => {
            if let Some(stale) = stale_entries {
                warn!(
                    url = source.url,
                    error = err,
                    "Using stale feed cache after refresh error"
                );
                return Ok(stale);
            }
            if fail_open {
                warn!(
                    url = source.url,
                    error = err,
                    "Skipping feed due to fail_open=true"
                );
                Ok(Vec::new())
            } else {
                Err(format!("feed fetch failed for '{}': {err}", source.url))
            }
        }
    }
}

pub async fn resolve_url_validation_config(
    mut config: WebFetchUrlValidationConfig,
) -> Result<WebFetchUrlValidationConfig, String> {
    config.normalize();
    if !config.enabled || !config.feed_sync.enabled || config.feed_sync.sources.is_empty() {
        return Ok(config);
    }

    let fail_open = config.feed_sync.fail_open;
    let max_entries_per_source = config.feed_sync.max_entries_per_source;
    for source in config.feed_sync.sources.iter().filter(|s| s.enabled) {
        let entries = fetch_feed_entries(source, fail_open, max_entries_per_source).await?;
        match source.mode {
            WebFetchFeedMode::Allowlist => config.allowlist_hosts.extend(entries),
            WebFetchFeedMode::Denylist => config.denylist_hosts.extend(entries),
        }
    }

    normalize_host_list(&mut config.allowlist_hosts);
    normalize_host_list(&mut config.denylist_hosts);
    Ok(config)
}

pub fn validate_web_fetch_url(
    raw_url: &str,
    mut config: WebFetchUrlValidationConfig,
) -> Result<(), String> {
    if !config.enabled {
        return Ok(());
    }
    config.normalize();

    let parsed = Url::parse(raw_url).map_err(|e| format!("invalid URL: {e}"))?;
    let scheme = parsed.scheme().to_ascii_lowercase();
    if !config.allowed_schemes.iter().any(|s| s == &scheme) {
        return Err(format!(
            "URL scheme '{}' is not allowed (allowed: {})",
            scheme,
            config.allowed_schemes.join(", ")
        ));
    }

    let host = parsed
        .host_str()
        .ok_or_else(|| "URL must include a host".to_string())?
        .to_ascii_lowercase();

    if config
        .denylist_hosts
        .iter()
        .any(|rule| host_matches_rule(&host, rule))
    {
        return Err(format!("URL host '{}' is denylisted", host));
    }

    if !config.allowlist_hosts.is_empty()
        && !config
            .allowlist_hosts
            .iter()
            .any(|rule| host_matches_rule(&host, rule))
    {
        return Err(format!("URL host '{}' is not in allowlist", host));
    }

    // SSRF guard: resolve hostname and reject private/internal targets unless
    // the host is explicitly on the allowlist (operator opt-out).
    if config.block_private_ips {
        let allowlisted = config
            .allowlist_hosts
            .iter()
            .any(|rule| host_matches_rule(&host, rule));
        if !allowlisted {
            crate::internal::tool_runtime::url_safety::check_url_private_ip(&parsed)?;
        }
    }

    Ok(())
}

pub async fn fetch_url_with_timeout(url: &str, timeout_secs: u64) -> Result<String, String> {
    fetch_url_with_timeout_and_validation(
        url,
        timeout_secs,
        WebContentValidationConfig::default(),
        WebFetchUrlValidationConfig::default(),
    )
    .await
}

pub async fn fetch_url_with_timeout_and_validation(
    url: &str,
    timeout_secs: u64,
    validation: WebContentValidationConfig,
    url_validation: WebFetchUrlValidationConfig,
) -> Result<String, String> {
    let effective_url_validation = resolve_url_validation_config(url_validation).await?;
    validate_web_fetch_url(url, effective_url_validation.clone())?;

    let client = http_client_no_redirect(timeout_secs.max(1));
    let mut current_url = Url::parse(url).map_err(|e| format!("invalid URL: {e}"))?;
    let mut redirects = 0usize;

    let resp = loop {
        let resp = client
            .get(current_url.clone())
            .send()
            .await
            .map_err(|e| e.to_string())?;

        if !resp.status().is_redirection() {
            break resp;
        }

        if redirects >= 5 {
            return Err("too many redirects (max 5)".to_string());
        }
        redirects += 1;

        let location = resp
            .headers()
            .get(reqwest::header::LOCATION)
            .ok_or_else(|| "redirect response missing Location header".to_string())?
            .to_str()
            .map_err(|e| format!("invalid redirect Location header: {e}"))?;
        current_url = resolve_and_validate_redirect_target(
            &current_url,
            location,
            &effective_url_validation,
        )?;
    };

    if !resp.status().is_success() {
        return Err(format!("HTTP {}", resp.status()));
    }

    let body = resp.text().await.map_err(|e| e.to_string())?;
    let primary = extract_primary_html(&body);
    let text = html_to_text(primary);

    if let Err(failure) = validate_web_content_with_config(&text, validation) {
        warn!(
            matched_rules = failure.rule_names.join(","),
            "Blocked web_fetch content by validation"
        );
        return Err(failure.message());
    }

    const MAX_BYTES: usize = 20_000;
    if text.len() > MAX_BYTES {
        let truncated = &text[..floor_char_boundary(&text, MAX_BYTES)];
        Ok(format!("{truncated}\n\n[Truncated at 20KB]"))
    } else {
        Ok(text)
    }
}

pub async fn fetch_url(url: &str) -> Result<String, String> {
    fetch_url_with_timeout(url, 15).await
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;

    use reqwest::Url;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;
    use tokio::time::{timeout, Duration};

    use super::{
        fetch_url_with_timeout_and_validation, resolve_and_validate_redirect_target,
        resolve_url_validation_config, validate_web_fetch_url, WebFetchFeedFormat,
        WebFetchFeedMode, WebFetchFeedSource, WebFetchFeedSyncConfig, WebFetchUrlValidationConfig,
    };
    use crate::internal::tool_runtime::web_content_validation::WebContentValidationConfig;

    #[test]
    fn url_validation_allows_default_http_https() {
        assert!(validate_web_fetch_url(
            "https://example.com",
            WebFetchUrlValidationConfig::default()
        )
        .is_ok());
        assert!(validate_web_fetch_url(
            "http://example.com/docs",
            WebFetchUrlValidationConfig::default()
        )
        .is_ok());
    }

    #[test]
    fn url_validation_blocks_scheme() {
        let err =
            validate_web_fetch_url("ftp://example.com", WebFetchUrlValidationConfig::default())
                .unwrap_err();
        assert!(err.contains("not allowed"));
    }

    #[test]
    fn url_validation_blocks_denylist() {
        let cfg = WebFetchUrlValidationConfig {
            denylist_hosts: vec!["example.com".into()],
            ..WebFetchUrlValidationConfig::default()
        };
        let err = validate_web_fetch_url("https://sub.example.com", cfg).unwrap_err();
        assert!(err.contains("denylisted"));
    }

    #[test]
    fn url_validation_enforces_allowlist() {
        let cfg = WebFetchUrlValidationConfig {
            allowlist_hosts: vec!["allowed.com".into()],
            ..WebFetchUrlValidationConfig::default()
        };
        assert!(validate_web_fetch_url("https://api.allowed.com/v1", cfg.clone()).is_ok());
        let err = validate_web_fetch_url("https://other.com", cfg).unwrap_err();
        assert!(err.contains("allowlist"));
    }

    #[test]
    fn url_validation_denylist_precedes_allowlist() {
        let cfg = WebFetchUrlValidationConfig {
            allowlist_hosts: vec!["example.com".into()],
            denylist_hosts: vec!["example.com".into()],
            ..WebFetchUrlValidationConfig::default()
        };
        let err = validate_web_fetch_url("https://api.example.com", cfg).unwrap_err();
        assert!(err.contains("denylisted"));
    }

    #[test]
    fn url_validation_can_be_disabled() {
        let cfg = WebFetchUrlValidationConfig {
            enabled: false,
            allowed_schemes: vec!["https".into()],
            allowlist_hosts: vec!["allowed.com".into()],
            denylist_hosts: vec!["allowed.com".into()],
            block_private_ips: true,
            feed_sync: WebFetchFeedSyncConfig::default(),
        };
        assert!(validate_web_fetch_url("ftp://bad", cfg).is_ok());
    }

    #[tokio::test]
    async fn feed_sync_merges_denylist_entries() {
        let cfg = WebFetchUrlValidationConfig {
            feed_sync: WebFetchFeedSyncConfig {
                enabled: true,
                fail_open: false,
                max_entries_per_source: 100,
                sources: vec![WebFetchFeedSource {
                    enabled: true,
                    mode: WebFetchFeedMode::Denylist,
                    url: "inline:#comment\nblocked.example\n".to_string(),
                    format: WebFetchFeedFormat::Lines,
                    refresh_interval_secs: 3600,
                    timeout_secs: 5,
                }],
            },
            ..WebFetchUrlValidationConfig::default()
        };

        let resolved = resolve_url_validation_config(cfg).await.unwrap();
        assert!(resolved
            .denylist_hosts
            .iter()
            .any(|h| h == "blocked.example"));
    }

    #[tokio::test]
    async fn feed_sync_supports_csv_first_column() {
        let cfg = WebFetchUrlValidationConfig {
            feed_sync: WebFetchFeedSyncConfig {
                enabled: true,
                fail_open: false,
                max_entries_per_source: 100,
                sources: vec![WebFetchFeedSource {
                    enabled: true,
                    mode: WebFetchFeedMode::Denylist,
                    url: "inline:host,score\nfoo.example,99\nbar.example,88\n".to_string(),
                    format: WebFetchFeedFormat::CsvFirstColumn,
                    refresh_interval_secs: 3600,
                    timeout_secs: 5,
                }],
            },
            ..WebFetchUrlValidationConfig::default()
        };

        let resolved = resolve_url_validation_config(cfg).await.unwrap();
        assert!(resolved.denylist_hosts.iter().any(|h| h == "foo.example"));
        assert!(resolved.denylist_hosts.iter().any(|h| h == "bar.example"));
    }

    #[tokio::test]
    async fn feed_sync_merges_allowlist_and_denylist_sources() {
        let cfg = WebFetchUrlValidationConfig {
            feed_sync: WebFetchFeedSyncConfig {
                enabled: true,
                fail_open: false,
                max_entries_per_source: 100,
                sources: vec![
                    WebFetchFeedSource {
                        enabled: true,
                        mode: WebFetchFeedMode::Allowlist,
                        url: "inline:https://allowed.example/path\n".to_string(),
                        format: WebFetchFeedFormat::Lines,
                        refresh_interval_secs: 3600,
                        timeout_secs: 5,
                    },
                    WebFetchFeedSource {
                        enabled: true,
                        mode: WebFetchFeedMode::Denylist,
                        url: "inline:blocked.example\n".to_string(),
                        format: WebFetchFeedFormat::Lines,
                        refresh_interval_secs: 3600,
                        timeout_secs: 5,
                    },
                ],
            },
            ..WebFetchUrlValidationConfig::default()
        };

        let resolved = resolve_url_validation_config(cfg).await.unwrap();
        assert!(resolved
            .allowlist_hosts
            .iter()
            .any(|h| h == "allowed.example"));
        assert!(resolved
            .denylist_hosts
            .iter()
            .any(|h| h == "blocked.example"));
    }

    #[tokio::test]
    async fn feed_sync_skips_disabled_sources() {
        let cfg = WebFetchUrlValidationConfig {
            feed_sync: WebFetchFeedSyncConfig {
                enabled: true,
                fail_open: false,
                max_entries_per_source: 100,
                sources: vec![WebFetchFeedSource {
                    enabled: false,
                    mode: WebFetchFeedMode::Denylist,
                    url: "inline:blocked.example\n".to_string(),
                    format: WebFetchFeedFormat::Lines,
                    refresh_interval_secs: 3600,
                    timeout_secs: 5,
                }],
            },
            ..WebFetchUrlValidationConfig::default()
        };

        let resolved = resolve_url_validation_config(cfg).await.unwrap();
        assert!(resolved.denylist_hosts.is_empty());
    }

    #[tokio::test]
    async fn feed_sync_fail_closed_returns_error() {
        let cfg = WebFetchUrlValidationConfig {
            feed_sync: WebFetchFeedSyncConfig {
                enabled: true,
                fail_open: false,
                max_entries_per_source: 100,
                sources: vec![WebFetchFeedSource {
                    enabled: true,
                    mode: WebFetchFeedMode::Denylist,
                    url: "http://127.0.0.1:9/unreachable".to_string(),
                    format: WebFetchFeedFormat::Lines,
                    refresh_interval_secs: 3600,
                    timeout_secs: 1,
                }],
            },
            ..WebFetchUrlValidationConfig::default()
        };

        let err = resolve_url_validation_config(cfg).await.unwrap_err();
        assert!(err.contains("feed fetch failed"));
    }

    #[tokio::test]
    async fn feed_sync_fail_open_skips_error() {
        let cfg = WebFetchUrlValidationConfig {
            feed_sync: WebFetchFeedSyncConfig {
                enabled: true,
                fail_open: true,
                max_entries_per_source: 100,
                sources: vec![WebFetchFeedSource {
                    enabled: true,
                    mode: WebFetchFeedMode::Denylist,
                    url: "http://127.0.0.1:9/unreachable".to_string(),
                    format: WebFetchFeedFormat::Lines,
                    refresh_interval_secs: 3600,
                    timeout_secs: 1,
                }],
            },
            ..WebFetchUrlValidationConfig::default()
        };

        let resolved = resolve_url_validation_config(cfg).await.unwrap();
        assert!(resolved.denylist_hosts.is_empty());
    }

    #[test]
    fn redirect_validation_blocks_denylisted_target() {
        let current = Url::parse("https://safe.example/start").unwrap();
        let cfg = WebFetchUrlValidationConfig {
            denylist_hosts: vec!["blocked.example".to_string()],
            ..WebFetchUrlValidationConfig::default()
        };
        let err =
            resolve_and_validate_redirect_target(&current, "https://blocked.example/path", &cfg)
                .unwrap_err();
        assert!(err.contains("denylisted"));
    }

    #[test]
    fn redirect_validation_allows_relative_target() {
        let current = Url::parse("https://safe.example/start").unwrap();
        // Disable SSRF check for a hostname that doesn't resolve publicly.
        let cfg = WebFetchUrlValidationConfig {
            block_private_ips: false,
            ..WebFetchUrlValidationConfig::default()
        };
        let next = resolve_and_validate_redirect_target(&current, "/next", &cfg).unwrap();
        assert_eq!(next.as_str(), "https://safe.example/next");
    }

    #[tokio::test]
    async fn fetch_blocks_redirect_to_denylisted_host() {
        let final_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let final_addr = final_listener.local_addr().unwrap();
        let final_hit = Arc::new(AtomicBool::new(false));
        let final_hit_clone = final_hit.clone();
        let final_server = tokio::spawn(async move {
            if let Ok(Ok((mut stream, _))) =
                timeout(Duration::from_secs(2), final_listener.accept()).await
            {
                final_hit_clone.store(true, Ordering::SeqCst);
                let mut buf = [0u8; 1024];
                let _ = stream.read(&mut buf).await;
                let _ = stream
                    .write_all(
                        b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok",
                    )
                    .await;
            }
        });

        let redirect_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let redirect_addr = redirect_listener.local_addr().unwrap();
        let redirect_server = tokio::spawn(async move {
            let (mut stream, _) = redirect_listener.accept().await.unwrap();
            let mut buf = [0u8; 1024];
            let _ = stream.read(&mut buf).await;
            let response = format!(
                "HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:{}/final\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
                final_addr.port()
            );
            let _ = stream.write_all(response.as_bytes()).await;
        });

        let start_url = format!("http://localhost:{}/start", redirect_addr.port());
        let url_cfg = WebFetchUrlValidationConfig {
            allowlist_hosts: vec!["localhost".to_string()],
            denylist_hosts: vec!["127.0.0.1".to_string()],
            ..WebFetchUrlValidationConfig::default()
        };
        let err = fetch_url_with_timeout_and_validation(
            &start_url,
            5,
            WebContentValidationConfig::default(),
            url_cfg,
        )
        .await
        .unwrap_err();

        redirect_server.await.unwrap();
        final_server.await.unwrap();

        assert!(err.contains("denylisted"));
        assert!(
            !final_hit.load(Ordering::SeqCst),
            "should not request redirect target after URL policy rejection"
        );
    }
}