ic-asset-router 0.1.1

File-based HTTP routing with IC response certification for Internet Computer canisters
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
use std::{collections::HashMap, time::Duration};

use ic_http_certification::HeaderField;

/// Global cache-control configuration for static and dynamic assets.
///
/// Static assets are files embedded via `include_dir` and served directly.
/// Dynamic assets are generated by route handlers at request time.
///
/// These values are used as defaults; per-route overrides can be applied via
/// handler response headers.
pub struct CacheControl {
    /// Cache-Control for static assets embedded via `include_dir`.
    /// Default: `"public, max-age=31536000, immutable"`
    pub static_assets: String,

    /// Cache-Control for dynamically generated assets.
    /// Default: `"public, no-cache, no-store"`
    pub dynamic_assets: String,
}

impl Default for CacheControl {
    fn default() -> Self {
        Self {
            static_assets: "public, max-age=31536000, immutable".into(),
            dynamic_assets: "public, no-cache, no-store".into(),
        }
    }
}

/// TTL-based cache configuration for dynamic assets.
///
/// Controls how long dynamically generated assets remain valid before
/// the library triggers re-generation via an update call.
#[derive(Default)]
pub struct CacheConfig {
    /// Default TTL applied to all dynamic assets that don't have an explicit TTL.
    /// `None` means dynamic assets are cached indefinitely (backwards-compatible).
    pub default_ttl: Option<Duration>,
    /// Per-route TTL overrides. Keys are exact path strings (e.g. `"/posts/1"`).
    /// A per-route TTL takes precedence over `default_ttl`.
    pub per_route_ttl: HashMap<String, Duration>,
}

impl CacheConfig {
    /// Resolve the effective TTL for a given path.
    ///
    /// Priority: per-route TTL > default TTL > None (cache forever).
    pub fn effective_ttl(&self, path: &str) -> Option<Duration> {
        self.per_route_ttl.get(path).copied().or(self.default_ttl)
    }
}

/// Typed fields for well-known security headers.
///
/// Based on the OWASP Secure Headers Project "active" list and Helmet.js defaults.
/// Each field is `Option<String>` -- `None` means the header is not emitted.
///
/// For headers not covered by this struct, use [`AssetConfig::custom_headers`].
///
/// `X-XSS-Protection` is intentionally excluded: it is deprecated and its filter
/// mechanism can be exploited. Modern guidance is to not set it at all.
pub struct SecurityHeaders {
    /// `Strict-Transport-Security` -- Forces HTTPS, prevents protocol downgrade (RFC 6797).
    /// Example: `"max-age=31536000; includeSubDomains"`
    pub hsts: Option<String>,

    /// `Content-Security-Policy` -- Controls which resources the browser can load.
    /// Primary defense against XSS. Complex to configure; `None` by default.
    /// Example: `"default-src 'self'; script-src 'self'"`
    pub csp: Option<String>,

    /// `X-Content-Type-Options` -- Prevents MIME-type sniffing.
    /// The only valid value is `"nosniff"`.
    pub content_type_options: Option<String>,

    /// `X-Frame-Options` -- Controls iframe embedding (legacy; superseded by CSP `frame-ancestors`).
    /// Values: `"DENY"`, `"SAMEORIGIN"`.
    pub frame_options: Option<String>,

    /// `Referrer-Policy` -- Controls referrer information sent with requests.
    /// Values: `"no-referrer"`, `"strict-origin-when-cross-origin"`, etc.
    pub referrer_policy: Option<String>,

    /// `Permissions-Policy` -- Controls which browser APIs are allowed (camera, geolocation, etc.).
    /// Replaces deprecated `Feature-Policy`. Still a W3C working draft but widely supported.
    /// Example: `"camera=(), microphone=(), geolocation=()"`
    pub permissions_policy: Option<String>,

    /// `Cross-Origin-Embedder-Policy` -- Controls loading of cross-origin resources.
    /// Values: `"require-corp"`, `"credentialless"`, `"unsafe-none"`.
    /// Warning: `"require-corp"` breaks Google Fonts, CDN images, analytics scripts.
    pub coep: Option<String>,

    /// `Cross-Origin-Opener-Policy` -- Process-isolates the document, prevents XS-Leaks.
    /// Values: `"same-origin"`, `"same-origin-allow-popups"`, `"unsafe-none"`.
    pub coop: Option<String>,

    /// `Cross-Origin-Resource-Policy` -- Controls which origins can load a resource.
    /// Mitigates Spectre side-channel attacks.
    /// Values: `"same-origin"`, `"same-site"`, `"cross-origin"`.
    pub corp: Option<String>,

    /// `X-DNS-Prefetch-Control` -- Controls DNS prefetching, which can leak browsing intent.
    /// Values: `"off"`, `"on"`.
    pub dns_prefetch_control: Option<String>,

    /// `X-Permitted-Cross-Domain-Policies` -- Controls cross-domain policy for Flash/PDF.
    /// Values: `"none"`, `"master-only"`, `"by-content-type"`, `"all"`.
    pub permitted_cross_domain_policies: Option<String>,
}

impl SecurityHeaders {
    /// Strict preset — mirrors the library's original hardcoded behavior plus
    /// `Cross-Origin-Resource-Policy`, `X-DNS-Prefetch-Control`, and
    /// `X-Permitted-Cross-Domain-Policies`.
    ///
    /// Suitable for apps that do not load cross-origin resources.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_asset_router::SecurityHeaders;
    ///
    /// let headers = SecurityHeaders::strict().to_headers();
    /// let names: Vec<&str> = headers.iter().map(|(k, _)| k.as_str()).collect();
    /// assert!(names.contains(&"strict-transport-security"));
    /// assert!(names.contains(&"x-content-type-options"));
    /// assert!(names.contains(&"x-frame-options"));
    /// assert!(names.contains(&"cross-origin-embedder-policy"));
    /// ```
    pub fn strict() -> Self {
        Self {
            hsts: Some("max-age=31536000; includeSubDomains".into()),
            csp: None,
            content_type_options: Some("nosniff".into()),
            frame_options: Some("DENY".into()),
            referrer_policy: Some("no-referrer".into()),
            permissions_policy: Some(
                "accelerometer=(), camera=(), geolocation=(), gyroscope=(), \
                 magnetometer=(), microphone=(), payment=(), usb=(), interest-cohort=()"
                    .into(),
            ),
            coep: Some("require-corp".into()),
            coop: Some("same-origin".into()),
            corp: Some("same-origin".into()),
            dns_prefetch_control: Some("off".into()),
            permitted_cross_domain_policies: Some("none".into()),
        }
    }

    /// Permissive preset — allows cross-origin resources, iframe embedding via
    /// `SAMEORIGIN`, and relaxed referrer policy.
    ///
    /// Suitable for SPAs loading external fonts, images, scripts. This is the
    /// default preset returned by [`SecurityHeaders::default()`].
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_asset_router::SecurityHeaders;
    ///
    /// let headers = SecurityHeaders::permissive().to_headers();
    /// let names: Vec<&str> = headers.iter().map(|(k, _)| k.as_str()).collect();
    /// // Permissive does not set COEP (which would break external resources)
    /// assert!(!names.contains(&"cross-origin-embedder-policy"));
    /// // But still sets HSTS and X-Content-Type-Options
    /// assert!(names.contains(&"strict-transport-security"));
    /// assert!(names.contains(&"x-content-type-options"));
    /// ```
    pub fn permissive() -> Self {
        Self {
            hsts: Some("max-age=31536000; includeSubDomains".into()),
            csp: None,
            content_type_options: Some("nosniff".into()),
            frame_options: Some("SAMEORIGIN".into()),
            referrer_policy: Some("strict-origin-when-cross-origin".into()),
            permissions_policy: None,
            coep: None,
            coop: Some("same-origin-allow-popups".into()),
            corp: Some("cross-origin".into()),
            dns_prefetch_control: None,
            permitted_cross_domain_policies: Some("none".into()),
        }
    }

    /// No security headers — the consumer takes full responsibility.
    ///
    /// # Examples
    ///
    /// ```
    /// use ic_asset_router::SecurityHeaders;
    ///
    /// let headers = SecurityHeaders::none().to_headers();
    /// assert!(headers.is_empty());
    /// ```
    pub fn none() -> Self {
        Self {
            hsts: None,
            csp: None,
            content_type_options: None,
            frame_options: None,
            referrer_policy: None,
            permissions_policy: None,
            coep: None,
            coop: None,
            corp: None,
            dns_prefetch_control: None,
            permitted_cross_domain_policies: None,
        }
    }

    /// Convert non-`None` fields into a list of HTTP header tuples.
    ///
    /// Fields that are `None` are omitted entirely (the header is not emitted).
    pub fn to_headers(&self) -> Vec<HeaderField> {
        let mut headers = Vec::new();

        if let Some(ref v) = self.hsts {
            headers.push(("strict-transport-security".to_string(), v.clone()));
        }
        if let Some(ref v) = self.csp {
            headers.push(("content-security-policy".to_string(), v.clone()));
        }
        if let Some(ref v) = self.content_type_options {
            headers.push(("x-content-type-options".to_string(), v.clone()));
        }
        if let Some(ref v) = self.frame_options {
            headers.push(("x-frame-options".to_string(), v.clone()));
        }
        if let Some(ref v) = self.referrer_policy {
            headers.push(("referrer-policy".to_string(), v.clone()));
        }
        if let Some(ref v) = self.permissions_policy {
            headers.push(("permissions-policy".to_string(), v.clone()));
        }
        if let Some(ref v) = self.coep {
            headers.push(("cross-origin-embedder-policy".to_string(), v.clone()));
        }
        if let Some(ref v) = self.coop {
            headers.push(("cross-origin-opener-policy".to_string(), v.clone()));
        }
        if let Some(ref v) = self.corp {
            headers.push(("cross-origin-resource-policy".to_string(), v.clone()));
        }
        if let Some(ref v) = self.dns_prefetch_control {
            headers.push(("x-dns-prefetch-control".to_string(), v.clone()));
        }
        if let Some(ref v) = self.permitted_cross_domain_policies {
            headers.push(("x-permitted-cross-domain-policies".to_string(), v.clone()));
        }

        headers
    }
}

impl Default for SecurityHeaders {
    /// Returns [`SecurityHeaders::permissive()`] to avoid breaking common use cases
    /// (external fonts, CDN images, analytics).
    fn default() -> Self {
        Self::permissive()
    }
}

/// Global configuration for the asset router.
///
/// Controls security headers, cache-control, custom headers, and TTL-based
/// caching applied to all responses.
///
/// # Examples
///
/// ```
/// use ic_asset_router::{AssetConfig, SecurityHeaders, CacheControl};
///
/// let config = AssetConfig {
///     security_headers: SecurityHeaders::strict(),
///     cache_control: CacheControl {
///         static_assets: "public, max-age=3600".into(),
///         ..CacheControl::default()
///     },
///     ..AssetConfig::default()
/// };
/// ```
#[derive(Default)]
pub struct AssetConfig {
    /// Typed security headers. Use a preset ([`SecurityHeaders::strict()`],
    /// [`SecurityHeaders::permissive()`], [`SecurityHeaders::none()`]) or
    /// configure individual fields.
    pub security_headers: SecurityHeaders,

    /// Cache-Control configuration for static and dynamic assets.
    pub cache_control: CacheControl,

    /// TTL-based cache configuration for dynamic assets.
    pub cache_config: CacheConfig,

    /// Arbitrary headers appended after security headers.
    ///
    /// If a custom header has the same name as a security header, the custom
    /// header wins (last-write-wins semantics during merging).
    pub custom_headers: Vec<HeaderField>,
}

impl AssetConfig {
    /// Merge security headers and custom headers into a single list, then layer
    /// `additional_headers` on top.
    ///
    /// Merge order (last-write-wins for duplicate header names):
    /// 1. Security headers (from [`SecurityHeaders`])
    /// 2. Custom headers (from [`AssetConfig::custom_headers`])
    /// 3. `additional_headers` (per-route / per-call overrides)
    ///
    /// The comparison is case-insensitive on header names.
    pub fn merged_headers(&self, additional_headers: Vec<HeaderField>) -> Vec<HeaderField> {
        let mut merged: Vec<HeaderField> = Vec::new();

        // Start with security headers
        for h in self.security_headers.to_headers() {
            merged.push(h);
        }

        // Layer custom_headers -- override any security header with the same name
        for h in &self.custom_headers {
            let name_lower = h.0.to_lowercase();
            merged.retain(|(k, _)| k.to_lowercase() != name_lower);
            merged.push(h.clone());
        }

        // Layer additional_headers (per-route overrides)
        for h in &additional_headers {
            let name_lower = h.0.to_lowercase();
            merged.retain(|(k, _)| k.to_lowercase() != name_lower);
            merged.push(h.clone());
        }

        merged
    }
}

// Test coverage audit (Session 7, Spec 5.5):
//
// Covered:
//   - SecurityHeaders presets: strict (all expected headers), permissive (subset), none (zero)
//   - Custom header override: custom_headers replaces security header of same name
//   - Additional headers override both custom and security headers
//   - Case-insensitive header name matching during merges
//   - X-XSS-Protection never set by any preset
//   - Default preset is permissive
//   - CacheControl defaults and custom values (static and dynamic)
//   - CacheConfig default (None TTL, empty per-route), per-route TTL overrides default
//
// No significant gaps identified for config.rs.
#[cfg(test)]
mod tests {
    use super::*;

    // ---- 1.1.15: strict() produces the expected set of headers ----

    #[test]
    fn strict_produces_expected_headers() {
        let headers = SecurityHeaders::strict().to_headers();
        let names: Vec<&str> = headers.iter().map(|(k, _)| k.as_str()).collect();

        assert!(names.contains(&"strict-transport-security"));
        assert!(names.contains(&"x-content-type-options"));
        assert!(names.contains(&"x-frame-options"));
        assert!(names.contains(&"referrer-policy"));
        assert!(names.contains(&"permissions-policy"));
        assert!(names.contains(&"cross-origin-embedder-policy"));
        assert!(names.contains(&"cross-origin-opener-policy"));
        assert!(names.contains(&"cross-origin-resource-policy"));
        assert!(names.contains(&"x-dns-prefetch-control"));
        assert!(names.contains(&"x-permitted-cross-domain-policies"));

        // CSP is None by default even in strict
        assert!(!names.contains(&"content-security-policy"));

        // Verify specific values
        let find =
            |name: &str| -> String { headers.iter().find(|(k, _)| k == name).unwrap().1.clone() };

        assert_eq!(find("x-frame-options"), "DENY");
        assert_eq!(find("referrer-policy"), "no-referrer");
        assert_eq!(find("cross-origin-embedder-policy"), "require-corp");
        assert_eq!(find("cross-origin-opener-policy"), "same-origin");
        assert_eq!(find("cross-origin-resource-policy"), "same-origin");
        assert_eq!(find("x-dns-prefetch-control"), "off");
        assert_eq!(find("x-permitted-cross-domain-policies"), "none");
    }

    // ---- 1.1.16: permissive() produces the expected set of headers ----

    #[test]
    fn permissive_produces_expected_headers() {
        let headers = SecurityHeaders::permissive().to_headers();
        let names: Vec<&str> = headers.iter().map(|(k, _)| k.as_str()).collect();

        assert!(names.contains(&"strict-transport-security"));
        assert!(names.contains(&"x-content-type-options"));
        assert!(names.contains(&"x-frame-options"));
        assert!(names.contains(&"referrer-policy"));
        assert!(names.contains(&"cross-origin-opener-policy"));
        assert!(names.contains(&"cross-origin-resource-policy"));
        assert!(names.contains(&"x-permitted-cross-domain-policies"));

        // These should NOT be set in permissive
        assert!(!names.contains(&"permissions-policy"));
        assert!(!names.contains(&"cross-origin-embedder-policy"));
        assert!(!names.contains(&"content-security-policy"));
        assert!(!names.contains(&"x-dns-prefetch-control"));

        let find =
            |name: &str| -> String { headers.iter().find(|(k, _)| k == name).unwrap().1.clone() };

        assert_eq!(find("x-frame-options"), "SAMEORIGIN");
        assert_eq!(find("referrer-policy"), "strict-origin-when-cross-origin");
        assert_eq!(
            find("cross-origin-opener-policy"),
            "same-origin-allow-popups"
        );
        assert_eq!(find("cross-origin-resource-policy"), "cross-origin");
    }

    // ---- 1.1.17: none() produces zero headers ----

    #[test]
    fn none_produces_zero_headers() {
        let headers = SecurityHeaders::none().to_headers();
        assert!(headers.is_empty());
    }

    // ---- 1.1.18: custom headers override security headers of same name ----

    #[test]
    fn custom_headers_override_security_headers() {
        let config = AssetConfig {
            security_headers: SecurityHeaders::strict(),
            cache_control: CacheControl::default(),
            cache_config: CacheConfig::default(),
            custom_headers: vec![("x-frame-options".to_string(), "SAMEORIGIN".to_string())],
        };
        let merged = config.merged_headers(vec![]);
        let frame_opts: Vec<_> = merged
            .iter()
            .filter(|(k, _)| k == "x-frame-options")
            .collect();
        assert_eq!(frame_opts.len(), 1);
        assert_eq!(frame_opts[0].1, "SAMEORIGIN");
    }

    #[test]
    fn additional_headers_override_custom_and_security() {
        let config = AssetConfig {
            security_headers: SecurityHeaders::strict(),
            cache_control: CacheControl::default(),
            cache_config: CacheConfig::default(),
            custom_headers: vec![("x-frame-options".to_string(), "SAMEORIGIN".to_string())],
        };
        let merged = config.merged_headers(vec![(
            "X-Frame-Options".to_string(),
            "ALLOW-FROM https://example.com".to_string(),
        )]);
        let frame_opts: Vec<_> = merged
            .iter()
            .filter(|(k, _)| k.to_lowercase() == "x-frame-options")
            .collect();
        assert_eq!(frame_opts.len(), 1);
        assert_eq!(frame_opts[0].1, "ALLOW-FROM https://example.com");
    }

    // ---- 1.1.19: X-XSS-Protection is never set by any preset ----

    #[test]
    fn xss_protection_never_set() {
        for headers in [
            SecurityHeaders::strict().to_headers(),
            SecurityHeaders::permissive().to_headers(),
            SecurityHeaders::none().to_headers(),
        ] {
            assert!(
                headers
                    .iter()
                    .all(|(k, _)| k.to_lowercase() != "x-xss-protection"),
                "X-XSS-Protection should never be set by any preset"
            );
        }
    }

    #[test]
    fn default_is_permissive() {
        let default_headers = SecurityHeaders::default().to_headers();
        let permissive_headers = SecurityHeaders::permissive().to_headers();
        assert_eq!(default_headers, permissive_headers);
    }

    // ---- 1.7.7: default CacheControl reproduces current behavior ----

    #[test]
    fn default_cache_control_reproduces_current_behavior() {
        let cc = CacheControl::default();
        assert_eq!(cc.static_assets, "public, max-age=31536000, immutable");
        assert_eq!(cc.dynamic_assets, "public, no-cache, no-store");
    }

    // ---- 1.7.8: custom static cache-control value is used ----

    #[test]
    fn custom_static_cache_control() {
        let cc = CacheControl {
            static_assets: "public, max-age=3600".into(),
            ..CacheControl::default()
        };
        assert_eq!(cc.static_assets, "public, max-age=3600");
        // dynamic_assets unchanged
        assert_eq!(cc.dynamic_assets, "public, no-cache, no-store");
    }

    // ---- 1.7.9: custom dynamic cache-control value is used ----

    #[test]
    fn custom_dynamic_cache_control() {
        let cc = CacheControl {
            dynamic_assets: "public, max-age=600".into(),
            ..CacheControl::default()
        };
        assert_eq!(cc.dynamic_assets, "public, max-age=600");
        // static_assets unchanged
        assert_eq!(cc.static_assets, "public, max-age=31536000, immutable");
    }

    #[test]
    fn asset_config_default_includes_default_cache_control() {
        let config = AssetConfig::default();
        assert_eq!(
            config.cache_control.static_assets,
            "public, max-age=31536000, immutable"
        );
        assert_eq!(
            config.cache_control.dynamic_assets,
            "public, no-cache, no-store"
        );
    }

    // ---- 4.1.16: CacheConfig::default() has default_ttl: None and empty per_route_ttl ----

    #[test]
    fn cache_config_default_has_none_and_empty() {
        let cc = CacheConfig::default();
        assert!(cc.default_ttl.is_none());
        assert!(cc.per_route_ttl.is_empty());
    }

    // ---- 4.1.20: per-route TTL overrides default TTL ----

    #[test]
    fn per_route_ttl_overrides_default_ttl() {
        let cc = CacheConfig {
            default_ttl: Some(Duration::from_secs(3600)),
            per_route_ttl: HashMap::from([("/posts/1".to_string(), Duration::from_secs(60))]),
        };
        // Per-route TTL should win
        assert_eq!(cc.effective_ttl("/posts/1"), Some(Duration::from_secs(60)));
        // Path without per-route override falls back to default
        assert_eq!(cc.effective_ttl("/about"), Some(Duration::from_secs(3600)));
        // With no default and no per-route, returns None
        let cc_no_default = CacheConfig {
            default_ttl: None,
            per_route_ttl: HashMap::from([("/posts/1".to_string(), Duration::from_secs(60))]),
        };
        assert_eq!(
            cc_no_default.effective_ttl("/posts/1"),
            Some(Duration::from_secs(60))
        );
        assert_eq!(cc_no_default.effective_ttl("/about"), None);
    }

    // ---- 8.6.4: Config header dedup tests ----

    /// Later header with the same key overrides the earlier one.
    #[test]
    fn merged_headers_later_overrides_earlier() {
        let config = AssetConfig {
            security_headers: SecurityHeaders::none(),
            cache_control: CacheControl::default(),
            cache_config: CacheConfig::default(),
            custom_headers: vec![
                ("x-custom".to_string(), "first".to_string()),
                ("x-custom".to_string(), "second".to_string()),
            ],
        };
        let merged = config.merged_headers(vec![]);
        let custom: Vec<_> = merged.iter().filter(|(k, _)| k == "x-custom").collect();
        assert_eq!(custom.len(), 1, "only one x-custom header should remain");
        assert_eq!(custom[0].1, "second", "later value should win");
    }

    /// Override is case-insensitive: "Content-Type" overrides "content-type".
    #[test]
    fn merged_headers_case_insensitive_override() {
        let config = AssetConfig {
            security_headers: SecurityHeaders::none(),
            cache_control: CacheControl::default(),
            cache_config: CacheConfig::default(),
            custom_headers: vec![("content-type".to_string(), "text/plain".to_string())],
        };
        // Additional header with different casing overrides custom.
        let merged = config.merged_headers(vec![(
            "Content-Type".to_string(),
            "application/json".to_string(),
        )]);
        let ct: Vec<_> = merged
            .iter()
            .filter(|(k, _)| k.to_lowercase() == "content-type")
            .collect();
        assert_eq!(ct.len(), 1, "only one content-type header should remain");
        assert_eq!(ct[0].1, "application/json", "additional header should win");
        // The surviving header preserves the casing from the additional layer.
        assert_eq!(ct[0].0, "Content-Type");
    }
}