csaf-crud 1.5.26

CSAF 2.0 / 2.1 advisory CRUD server with HATEOAS JSON API and HTML UI (TLS 1.3, HTTP/1.1 + HTTP/2 + HTTP/3)
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 Pierre Gronau, ndaal in Cologne

//! Lightweight HTTP router built on [`matchit`].
//!
//! Adapted from the vulnerability-lookup-rs router pattern.

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use bytes::Bytes;
use http::{Method, Response, StatusCode};
use http_body_util::Full;

use crate::app_state::AppState;

// ---------------------------------------------------------------------------
// Type aliases
// ---------------------------------------------------------------------------

/// The concrete body type used throughout the server.
pub type Body = Full<Bytes>;

/// The boxed future returned by route handlers.
pub type HandlerFuture = Pin<Box<dyn Future<Output = Response<Body>> + Send>>;

/// A route handler function signature.
pub type HandlerFn = Arc<
    dyn Fn(AppState, http::request::Parts, Vec<(String, String)>) -> HandlerFuture + Send + Sync,
>;

// ---------------------------------------------------------------------------
// Router
// ---------------------------------------------------------------------------

/// A lightweight, method-aware HTTP router.
pub struct Router {
    trees: HashMap<Method, matchit::Router<HandlerFn>>,
    state: AppState,
}

impl Router {
    /// Create a new router with the given application state.
    #[must_use]
    pub fn new(state: AppState) -> Self {
        Self {
            trees: HashMap::new(),
            state,
        }
    }

    /// Register a handler for a `(method, path)` pair.
    ///
    /// # Errors
    ///
    /// Returns `matchit::InsertError` if the path template is malformed
    /// or conflicts with a previously registered route under the same
    /// method.
    pub fn route(
        mut self,
        method: Method,
        path: &str,
        handler: HandlerFn,
    ) -> Result<Self, matchit::InsertError> {
        self.trees
            .entry(method)
            .or_default()
            .insert(path, handler)?;
        Ok(self)
    }

    /// Convenience: register a `GET` route.
    ///
    /// # Errors
    ///
    /// See [`Router::route`].
    pub fn get(self, path: &str, handler: HandlerFn) -> Result<Self, matchit::InsertError> {
        self.route(Method::GET, path, handler)
    }

    /// Convenience: register a `POST` route.
    ///
    /// # Errors
    ///
    /// See [`Router::route`].
    pub fn post(self, path: &str, handler: HandlerFn) -> Result<Self, matchit::InsertError> {
        self.route(Method::POST, path, handler)
    }

    /// Convenience: register a `PUT` route.
    ///
    /// # Errors
    ///
    /// See [`Router::route`].
    pub fn put(self, path: &str, handler: HandlerFn) -> Result<Self, matchit::InsertError> {
        self.route(Method::PUT, path, handler)
    }

    /// Convenience: register a `DELETE` route.
    ///
    /// # Errors
    ///
    /// See [`Router::route`].
    pub fn delete(self, path: &str, handler: HandlerFn) -> Result<Self, matchit::InsertError> {
        self.route(Method::DELETE, path, handler)
    }

    /// Convert the router into a shared, cloneable service handle.
    #[must_use]
    pub fn into_shared(self) -> SharedRouter {
        SharedRouter {
            inner: Arc::new(self),
        }
    }
}

// ---------------------------------------------------------------------------
// Security response headers
// ---------------------------------------------------------------------------

/// The security headers every response carries (`skills/security-headers`).
///
/// The Content-Security-Policy is stricter than that skill's example: no
/// `style-src 'unsafe-inline'`, and `img-src 'self'` only. The pages have no
/// inline styles or scripts (a layout test enforces it), and the UI must work
/// fully offline, so nothing may name a remote host.
///
/// HSTS is ignored by browsers on connections with certificate errors, so the
/// default self-signed certificate never activates it; with a trusted
/// certificate it covers the whole host, every port and its subdomains.
const SECURITY_HEADERS: &[(&str, &str)] = &[
    (
        "content-security-policy",
        "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; \
         font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; \
         form-action 'self'; frame-ancestors 'none'",
    ),
    (
        "strict-transport-security",
        "max-age=31536000; includeSubDomains; preload",
    ),
    ("x-content-type-options", "nosniff"),
    ("x-frame-options", "DENY"),
    ("referrer-policy", "strict-origin-when-cross-origin"),
    (
        "permissions-policy",
        "camera=(), microphone=(), geolocation=(), payment=()",
    ),
];

/// The six security headers as `(lowercase name, value)` pairs.
///
/// One source for the response wrapper, the tests and the documentation.
#[must_use]
pub const fn security_headers() -> &'static [(&'static str, &'static str)] {
    SECURITY_HEADERS
}

/// Add every security header the handler did not already set itself.
///
/// A handler may need a tighter value than the default (a file download, for
/// example), so an existing header is left alone.
#[must_use]
pub fn with_security_headers(mut response: Response<Body>) -> Response<Body> {
    for &(name, value) in SECURITY_HEADERS {
        let name = http::HeaderName::from_static(name);
        if !response.headers().contains_key(&name) {
            response
                .headers_mut()
                .insert(name, http::HeaderValue::from_static(value));
        }
    }
    response
}

// ---------------------------------------------------------------------------
// SharedRouter
// ---------------------------------------------------------------------------

/// A cheaply cloneable handle to a [`Router`].
#[derive(Clone)]
pub struct SharedRouter {
    inner: Arc<Router>,
}

impl SharedRouter {
    /// Dispatch an incoming hyper request.
    pub async fn handle(&self, req: http::Request<hyper::body::Incoming>) -> Response<Body> {
        let (mut parts, body) = req.into_parts();

        // Collect request body for methods that carry payloads.
        if matches!(
            parts.method,
            Method::POST | Method::PUT | Method::PATCH | Method::DELETE
        ) {
            use http_body_util::BodyExt;
            let body_bytes = body
                .collect()
                .await
                .map(|c| c.to_bytes())
                .unwrap_or_default();
            parts.extensions.insert(RequestBody(body_bytes));
        }

        self.handle_parts(parts).await
    }

    /// Dispatch a request from its parts and add the security headers.
    ///
    /// Both transports end up here (`handle` for HTTP/1.1 and HTTP/2, the
    /// HTTP/3 handler directly), so the headers apply to every response:
    /// matched routes, 404 and 405 alike.
    pub async fn handle_parts(&self, parts: http::request::Parts) -> Response<Body> {
        with_security_headers(self.route_parts(parts).await)
    }

    /// Match a request against the route trees and run its handler.
    async fn route_parts(&self, parts: http::request::Parts) -> Response<Body> {
        let method = parts.method.clone();
        let path = parts.uri.path().to_owned();

        // Try matching the request method tree.
        if let Some(tree) = self.inner.trees.get(&method)
            && let Ok(matched) = tree.at(&path)
        {
            let params: Vec<(String, String)> = matched
                .params
                .iter()
                .map(|(k, v)| (k.to_owned(), v.to_owned()))
                .collect();
            let handler = matched.value.clone();
            return handler(self.inner.state.clone(), parts, params).await;
        }

        // Check if any other method matches -- if so, 405.
        for (m, tree) in &self.inner.trees {
            if *m != method && tree.at(&path).is_ok() {
                return Response::builder()
                    .status(StatusCode::METHOD_NOT_ALLOWED)
                    .header("content-type", "text/plain; charset=utf-8")
                    .body(Body::from("Method Not Allowed"))
                    .unwrap_or_default();
            }
        }

        // No match -- 404.
        Response::builder()
            .status(StatusCode::NOT_FOUND)
            .header("content-type", "text/plain; charset=utf-8")
            .body(Body::from("Not Found"))
            .unwrap_or_default()
    }
}

// ---------------------------------------------------------------------------
// Handler helper
// ---------------------------------------------------------------------------

/// Wrap an async handler function into a boxed [`HandlerFn`].
#[must_use]
pub fn handler_fn<F, Fut>(f: F) -> HandlerFn
where
    F: Fn(AppState, http::request::Parts, Vec<(String, String)>) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Response<Body>> + Send + 'static,
{
    Arc::new(move |state, parts, params| Box::pin(f(state, parts, params)))
}

// ---------------------------------------------------------------------------
// Request helpers
// ---------------------------------------------------------------------------

/// Wrapper for the collected request body stored in `Parts.extensions`.
#[derive(Clone, Debug)]
pub struct RequestBody(pub Bytes);

/// Extract a named path parameter by key.
#[must_use]
pub fn path_param(params: &[(String, String)], name: &str) -> Option<String> {
    params
        .iter()
        .find(|(k, _)| k == name)
        .map(|(_, v)| v.clone())
}

/// Parse query string into a deserializable struct.
pub fn parse_query<T: serde::de::DeserializeOwned>(uri: &http::Uri) -> Result<T, String> {
    let query = uri.query().unwrap_or_default();
    let pairs: Vec<(String, String)> = query
        .split('&')
        .filter(|s| !s.is_empty())
        .filter_map(|pair| {
            let (k, v) = pair.split_once('=')?;
            Some((k.to_owned(), urlencoding_decode(v)))
        })
        .collect();

    let map: serde_json::Map<String, serde_json::Value> = pairs
        .into_iter()
        .map(|(k, v)| (k, serde_json::Value::String(v)))
        .collect();

    serde_json::from_value(serde_json::Value::Object(map))
        .map_err(|e| format!("query parse error: {e}"))
}

/// Extract and parse the JSON request body.
pub fn parse_json_body<T: serde::de::DeserializeOwned>(
    parts: &http::request::Parts,
) -> Result<T, String> {
    let body = parts
        .extensions
        .get::<RequestBody>()
        .ok_or_else(|| "No request body".to_owned())?;
    serde_json::from_slice(&body.0).map_err(|e| format!("Invalid JSON: {e}"))
}

/// Parse an `application/x-www-form-urlencoded` request body into a
/// `Vec<(key, value)>`. Multi-value fields are preserved in insertion order.
pub fn parse_form_body(parts: &http::request::Parts) -> Result<Vec<(String, String)>, String> {
    let body = parts
        .extensions
        .get::<RequestBody>()
        .ok_or_else(|| "No request body".to_owned())?;
    let s = std::str::from_utf8(&body.0).map_err(|e| format!("invalid UTF-8: {e}"))?;
    Ok(s.split('&')
        .filter(|p| !p.is_empty())
        .map(|pair| {
            let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
            (urlencoding_decode(k), urlencoding_decode(v))
        })
        .collect())
}

/// Look up a form field from a parsed form body. Returns the last value if
/// the same key appears multiple times.
#[must_use]
pub fn form_field<'a>(form: &'a [(String, String)], name: &str) -> Option<&'a str> {
    form.iter()
        .rev()
        .find(|(k, _)| k == name)
        .map(|(_, v)| v.as_str())
}

/// Check whether a form checkbox is set (HTML checkboxes only appear in the
/// submission when checked).
#[must_use]
pub fn form_checkbox(form: &[(String, String)], name: &str) -> bool {
    form.iter().any(|(k, _)| k == name)
}

/// Minimal percent-decoding for query parameter values.
///
/// Exposed as `pub` so fuzz targets can exercise it directly. Decodes
/// `%XX` escapes and treats `+` as space. Unknown escapes are silently
/// decoded to zero bytes rather than panicking, so the function is total
/// over any `&str` input.
#[must_use]
pub fn decode_percent(input: &str) -> String {
    urlencoding_decode(input)
}

/// Minimal percent-decoding for query parameter values.
///
/// Operates on raw UTF-8 bytes so that multi-byte sequences — whether
/// literal or assembled from several `%XX` escapes — survive the round
/// trip unchanged. Invalid UTF-8 sequences produced by malformed
/// percent-escapes are replaced with the Unicode replacement character
/// via `String::from_utf8_lossy`, ensuring the function is total.
fn urlencoding_decode(input: &str) -> String {
    let bytes = input.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut i = 0;

    while i < bytes.len() {
        let b = bytes[i];
        if b == b'%'
            && i + 2 < bytes.len()
            && let Some(hi) = hex_val(bytes[i + 1])
            && let Some(lo) = hex_val(bytes[i + 2])
        {
            out.push((hi << 4) | lo);
            i += 3;
        } else if b == b'+' {
            out.push(b' ');
            i += 1;
        } else {
            out.push(b);
            i += 1;
        }
    }

    String::from_utf8_lossy(&out).into_owned()
}

/// Value of one ASCII hex digit, or `None` if `b` is not a hex digit.
///
/// Returning `Option` rather than `0` is the whole point. The previous form
/// mapped every non-hex byte to zero, so `%ZZ` decoded to a NUL byte the caller
/// never sent -- see `invalid_hex_escape_is_left_literal_not_decoded_to_nul`.
/// With `None` the caller can decline the escape and fall through to copying
/// `%` literally, which is what RFC 3986 requires.
fn hex_val(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Response helpers
// ---------------------------------------------------------------------------

/// Build an HTML response.
#[must_use]
pub fn html_response(status: StatusCode, body: impl Into<Bytes>) -> Response<Body> {
    Response::builder()
        .status(status)
        .header("content-type", "text/html; charset=utf-8")
        .body(Body::from(body.into()))
        .unwrap_or_default()
}

/// Build a JSON response.
#[must_use]
pub fn json_response(status: StatusCode, value: &serde_json::Value) -> Response<Body> {
    let body = serde_json::to_string(value).unwrap_or_else(|_| "{}".to_owned());
    Response::builder()
        .status(status)
        .header("content-type", "application/json; charset=utf-8")
        .body(Body::from(Bytes::from(body)))
        .unwrap_or_default()
}

/// Build an RFC 9457 Problem Details error response.
#[must_use]
pub fn problem_response(
    status: StatusCode,
    error_type: &str,
    title: &str,
    detail: &str,
) -> Response<Body> {
    let body = serde_json::json!({
        "type": error_type,
        "title": title,
        "status": status.as_u16(),
        "detail": detail,
    });
    let json = serde_json::to_string(&body).unwrap_or_else(|_| "{}".to_owned());
    Response::builder()
        .status(status)
        .header("content-type", "application/problem+json; charset=utf-8")
        .body(Body::from(Bytes::from(json)))
        .unwrap_or_default()
}

/// Build a redirect response.
#[must_use]
pub fn redirect(location: &str) -> Response<Body> {
    Response::builder()
        .status(StatusCode::SEE_OTHER)
        .header("location", location)
        .body(Body::default())
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_path_param_found() {
        let params = vec![("id".to_owned(), "ndaal-sa-2026-001".to_owned())];
        assert_eq!(
            path_param(&params, "id"),
            Some("ndaal-sa-2026-001".to_owned())
        );
    }

    #[test]
    fn test_path_param_not_found() {
        let params: Vec<(String, String)> = vec![];
        assert_eq!(path_param(&params, "id"), None);
    }

    #[test]
    fn test_json_response_content_type() {
        let resp = json_response(StatusCode::OK, &serde_json::json!({"key": "value"}));
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(
            resp.headers().get("content-type").unwrap(),
            "application/json; charset=utf-8"
        );
    }

    #[test]
    fn test_problem_response_content_type() {
        let resp = problem_response(
            StatusCode::NOT_FOUND,
            "https://ndaal.eu/csaf/errors/not-found",
            "Not Found",
            "Document not found",
        );
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
        assert_eq!(
            resp.headers().get("content-type").unwrap(),
            "application/problem+json; charset=utf-8"
        );
    }

    #[test]
    fn test_html_response() {
        let resp = html_response(StatusCode::OK, "<h1>Test</h1>");
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(
            resp.headers().get("content-type").unwrap(),
            "text/html; charset=utf-8"
        );
    }

    #[test]
    fn test_redirect() {
        let resp = redirect("/csaf");
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        assert_eq!(resp.headers().get("location").unwrap(), "/csaf");
    }

    #[test]
    fn test_urlencoding_decode() {
        assert_eq!(urlencoding_decode("hello%20world"), "hello world");
        assert_eq!(urlencoding_decode("a+b"), "a b");
        assert_eq!(urlencoding_decode("%2F"), "/");
        assert_eq!(urlencoding_decode("plain"), "plain");
    }

    #[test]
    fn test_urlencoding_decode_literal_utf8_passthrough() {
        // Regression test for a bug found by `fuzz_url_decode`: previously
        // the decoder iterated raw bytes and cast each non-`%` byte to
        // `char`, corrupting multi-byte UTF-8 sequences. A literal "Ú"
        // (UTF-8 `C3 9A`) must survive the round trip byte-for-byte.
        assert_eq!(urlencoding_decode("Ú"), "Ú");
        assert_eq!(urlencoding_decode("Á&Ú"), "Á&Ú");
        assert_eq!(urlencoding_decode("ɉ"), "ɉ");
        assert_eq!(urlencoding_decode("カフェ"), "カフェ");
    }

    #[test]
    fn test_urlencoding_decode_percent_escaped_utf8() {
        // Assembled from `%XX` escapes: the German "Ü" is `C3 9C`, which
        // encodes as `%C3%9C`.
        assert_eq!(urlencoding_decode("Gr%C3%BC%C3%9F"), "Grüß");
        assert_eq!(urlencoding_decode("caf%C3%A9"), "café");
    }

    #[test]
    fn test_urlencoding_decode_mixed_literal_and_escaped() {
        assert_eq!(urlencoding_decode("Ü%2FÖ"), "Ü/Ö");
        assert_eq!(urlencoding_decode("a+b+%C3%B6"), "a b ö");
    }

    #[test]
    fn invalid_hex_escape_is_left_literal_not_decoded_to_nul() {
        // RFC 3986 §2.1: a `%` not followed by two HEXDIG is not a valid
        // percent-encoding. It must survive decoding as the literal characters
        // it is -- never be silently reinterpreted.
        //
        // WHY THIS MATTERS RATHER THAN BEING PEDANTRY: `hex_val` used to map
        // every non-hex byte to 0, so `%ZZ` decoded to a single NUL byte. That
        // is a value the caller never sent, injected into a query parameter
        // from input an attacker controls. The filesystem screens
        // (`is_safe_asset_name`, `safe_join`) do reject NUL, so this was not a
        // path-traversal hole -- but anything else consuming a decoded
        // parameter (a log line, a database column, a rendered page) inherits a
        // NUL it has no reason to expect, and NUL is exactly the byte that
        // truncates strings in C-adjacent consumers.
        assert_eq!(urlencoding_decode("%ZZ"), "%ZZ");
        assert_eq!(urlencoding_decode("%GG"), "%GG");
        assert_eq!(urlencoding_decode("a%ZZb"), "a%ZZb");
        // Half-valid is still invalid: one hex digit does not make an escape.
        assert_eq!(urlencoding_decode("%4Z"), "%4Z");
        assert_eq!(urlencoding_decode("%Z4"), "%Z4");
    }

    #[test]
    fn explicit_nul_escape_still_decodes() {
        // The fix must reject only INVALID escapes. `%00` is perfectly valid
        // and must keep decoding to NUL -- otherwise the change would silently
        // alter the meaning of well-formed input while fixing malformed input.
        assert_eq!(urlencoding_decode("%00"), "\0");
        assert_eq!(urlencoding_decode("a%00b"), "a\0b");
    }

    #[test]
    fn test_urlencoding_decode_total_on_truncated_escape() {
        // Malformed percent-escape at end of input must not panic.
        assert_eq!(urlencoding_decode("abc%"), "abc%");
        assert_eq!(urlencoding_decode("abc%2"), "abc%2");
        assert_eq!(urlencoding_decode("%"), "%");
    }
}

/// Security response headers (`skills/security-headers`): every outcome of
/// [`SharedRouter::handle_parts`] carries all six, on HTTP/1.1, HTTP/2 and
/// HTTP/3 alike, because both transports dispatch through that one function.
#[cfg(test)]
mod security_header_tests {
    use csaf_core::config::AppConfig;
    use csaf_core::storage::CsafStorage;
    use csaf_models::db::DbPool;
    use csaf_models::settings::Settings;

    use super::*;

    fn shared_router() -> SharedRouter {
        let state = AppState::new(
            CsafStorage::open_temp().expect("temp storage opens"),
            DbPool::open_in_memory().expect("in-memory pool opens"),
            AppConfig::default(),
            Settings::default(),
        );
        Router::new(state)
            .get(
                "/page",
                handler_fn(|_state, _parts, _params| async {
                    html_response(StatusCode::OK, "<p>x</p>")
                }),
            )
            .expect("route registers")
            .get(
                "/go",
                handler_fn(|_state, _parts, _params| async { redirect("/page") }),
            )
            .expect("route registers")
            .get(
                "/own-csp",
                handler_fn(|_state, _parts, _params| async {
                    let mut response = html_response(StatusCode::OK, "<p>x</p>");
                    response.headers_mut().insert(
                        "content-security-policy",
                        http::HeaderValue::from_static("default-src 'none'"),
                    );
                    response
                }),
            )
            .expect("route registers")
            .get(
                "/static/{*path}",
                handler_fn(crate::static_files::serve_static),
            )
            .expect("route registers")
            .into_shared()
    }

    async fn send(router: &SharedRouter, method: Method, path: &str) -> Response<Body> {
        let (parts, ()) = http::Request::builder()
            .method(method)
            .uri(path)
            .body(())
            .expect("request builds")
            .into_parts();
        router.handle_parts(parts).await
    }

    fn assert_carries_all_six(response: &Response<Body>, what: &str) {
        for &(name, value) in security_headers() {
            assert_eq!(
                response.headers().get(name).and_then(|v| v.to_str().ok()),
                Some(value),
                "{what}: header {name}"
            );
        }
    }

    mod properties {
        use std::collections::HashMap;

        use http::{HeaderName, HeaderValue, Response};
        use proptest::collection::vec;
        use proptest::prelude::*;

        use super::super::{Body, security_headers, with_security_headers};

        proptest! {
            /// WHY: the wrapper is the single place the six headers come
            /// from. For ANY mix of headers a handler already set it must add
            /// exactly what is missing, never duplicate or overwrite what the
            /// handler chose, leave unrelated headers alone, and be safe to
            /// apply twice.
            #[test]
            fn the_wrapper_adds_the_missing_and_keeps_the_handlers_own(
                preset in vec((0..security_headers().len(), "[!-~]{1,30}"), 0..8),
                extras in vec(("x-[a-z]{1,10}", "[!-~]{1,20}"), 0..4),
            ) {
                let mut response = Response::new(Body::default());
                let mut chosen: HashMap<&str, String> = HashMap::new();
                for (index, value) in &preset {
                    let name = security_headers()[*index].0;
                    response.headers_mut().insert(
                        HeaderName::from_static(name),
                        HeaderValue::from_str(value).expect("visible ASCII"),
                    );
                    chosen.insert(name, value.clone());
                }
                let mut kept: HashMap<String, String> = HashMap::new();
                for (name, value) in &extras {
                    response.headers_mut().insert(
                        HeaderName::from_bytes(name.as_bytes()).expect("valid name"),
                        HeaderValue::from_str(value).expect("visible ASCII"),
                    );
                    kept.insert(name.clone(), value.clone());
                }

                let wrapped = with_security_headers(response);

                for &(name, default) in security_headers() {
                    let values: Vec<_> = wrapped.headers().get_all(name).iter().collect();
                    prop_assert_eq!(values.len(), 1, "{} must appear exactly once", name);
                    let want = chosen.get(name).map_or(default, String::as_str);
                    prop_assert_eq!(values[0].to_str().expect("ASCII"), want);
                }
                for (name, value) in &kept {
                    let got = wrapped.headers().get(name.as_str()).and_then(|v| v.to_str().ok());
                    prop_assert_eq!(got, Some(value.as_str()), "{} was changed", name);
                }
                let again = with_security_headers(wrapped.clone());
                prop_assert_eq!(again.headers(), wrapped.headers());
            }
        }
    }

    #[tokio::test]
    async fn an_html_page_carries_all_six_headers() {
        let response = send(&shared_router(), Method::GET, "/page").await;
        assert_eq!(response.status(), StatusCode::OK);
        assert_carries_all_six(&response, "200 html");
    }

    #[tokio::test]
    async fn a_static_file_carries_all_six_headers() {
        let response = send(&shared_router(), Method::GET, "/static/css/csaf-ui.css").await;
        assert_eq!(response.status(), StatusCode::OK);
        assert_carries_all_six(&response, "static css");
    }

    #[tokio::test]
    async fn a_redirect_carries_all_six_headers() {
        let response = send(&shared_router(), Method::GET, "/go").await;
        assert_eq!(response.status(), StatusCode::SEE_OTHER);
        assert_carries_all_six(&response, "303 redirect");
    }

    #[tokio::test]
    async fn an_unknown_path_carries_all_six_headers() {
        let response = send(&shared_router(), Method::GET, "/nope").await;
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
        assert_carries_all_six(&response, "404");
    }

    #[tokio::test]
    async fn a_wrong_method_carries_all_six_headers() {
        let response = send(&shared_router(), Method::POST, "/page").await;
        assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
        assert_carries_all_six(&response, "405");
    }

    #[tokio::test]
    async fn a_header_the_handler_set_itself_is_not_overwritten() {
        // A handler may need a tighter policy than the default (for example a
        // file download); the wrapper must add what is missing, not replace.
        let response = send(&shared_router(), Method::GET, "/own-csp").await;
        assert_eq!(
            response.headers().get("content-security-policy").unwrap(),
            "default-src 'none'"
        );
        assert_eq!(
            response.headers().get("x-frame-options").unwrap(),
            "DENY",
            "the other five are still added"
        );
    }

    #[test]
    fn exactly_the_six_documented_headers_are_defined() {
        let mut names: Vec<&str> = security_headers().iter().map(|(name, _)| *name).collect();
        names.sort_unstable();
        assert_eq!(
            names,
            [
                "content-security-policy",
                "permissions-policy",
                "referrer-policy",
                "strict-transport-security",
                "x-content-type-options",
                "x-frame-options",
            ]
        );
    }

    #[test]
    fn the_content_security_policy_is_strict() {
        let csp = security_headers()
            .iter()
            .find(|(name, _)| *name == "content-security-policy")
            .map(|(_, value)| *value)
            .expect("CSP is defined");
        // The point of moving every inline style and script out of the pages.
        assert!(!csp.contains("unsafe-inline"), "{csp}");
        assert!(!csp.contains("unsafe-eval"), "{csp}");
        for directive in [
            "default-src 'self'",
            "script-src 'self'",
            "style-src 'self'",
            "img-src 'self'",
            "font-src 'self'",
            "connect-src 'self'",
            "object-src 'none'",
            "base-uri 'self'",
            "form-action 'self'",
            "frame-ancestors 'none'",
        ] {
            assert!(csp.contains(directive), "{directive} missing from {csp}");
        }
        // Nothing may name a remote host: the UI must work fully offline.
        assert!(!csp.contains("http"), "{csp}");
    }

    #[test]
    fn hsts_covers_at_least_one_year_and_subdomains() {
        let hsts = security_headers()
            .iter()
            .find(|(name, _)| *name == "strict-transport-security")
            .map(|(_, value)| *value)
            .expect("HSTS is defined");
        assert!(hsts.contains("max-age=31536000"), "{hsts}");
        assert!(hsts.contains("includeSubDomains"), "{hsts}");
    }
}