postrust-proxy 2.0.0

Reverse proxy for Postrust with load balancing and automatic TLS certificates
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
//! Configuration types for the proxy.

use http::HeaderMap;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{LazyLock, RwLock};
use uuid::Uuid;

/// Main proxy configuration.
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
#[non_exhaustive]
pub struct ProxyConfig {
    /// Server settings
    #[serde(default)]
    pub server: ServerConfig,

    /// TLS/ACME settings
    #[serde(default)]
    pub tls: TlsConfig,

    /// Default rate limiting settings
    #[serde(default)]
    pub rate_limit: RateLimitDefaults,

    /// Routes (for file-based config)
    #[serde(default)]
    pub routes: Vec<Route>,

    /// Upstreams (for file-based config)
    #[serde(default)]
    pub upstreams: Vec<Upstream>,
}

/// Server configuration.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ServerConfig {
    /// Listen address for HTTP
    #[serde(default = "default_http_host")]
    pub http_host: String,

    /// Listen port for HTTP
    #[serde(default = "default_http_port")]
    pub http_port: u16,

    /// Dedicated HTTP/2-only listen port.
    ///
    /// Optional and additive: the main port keeps serving HTTP/1.1 and h2c by
    /// sniffing. That sniffing is why a corrupted HTTP/2 preface gets an
    /// HTTP/1 400 rather than GOAWAY(PROTOCOL_ERROR) -- it is indistinguishable
    /// from a malformed HTTP/1 request. A port that only ever speaks HTTP/2 has
    /// no such ambiguity.
    #[serde(default)]
    pub http2_port: Option<u16>,

    /// Listen address for HTTPS
    #[serde(default = "default_https_host")]
    pub https_host: String,

    /// Listen port for HTTPS
    #[serde(default = "default_https_port")]
    pub https_port: u16,

    /// Enable HTTPS listener
    #[serde(default)]
    pub https_enabled: bool,

    /// Database-backed config enabled
    #[serde(default = "default_true")]
    pub database_config: bool,

    /// Config file path (for file-based bootstrap)
    pub config_file: Option<String>,

    /// Most client connections served at once, across every listener.
    ///
    /// Each connection costs a socket, a task and buffers, and an upstream
    /// socket besides; without a cap, a client that opens connections faster
    /// than they close runs the process out of file descriptors and everyone
    /// else is refused along with it. At the cap the proxy stops accepting, so
    /// further connections wait in the kernel's backlog instead of failing.
    /// An upgraded tunnel holds its slot for as long as it is open.
    #[serde(default = "default_max_connections")]
    pub max_connections: usize,

    /// How long a client has to send a complete HTTP/1 request head.
    ///
    /// Counted from when the proxy starts waiting for a request, so it also
    /// bounds the wait for the next request on a kept-alive connection. This
    /// is what stops a client trickling one header line at a time from holding
    /// a connection open indefinitely.
    #[serde(default = "default_header_read_timeout_secs")]
    pub header_read_timeout_secs: u64,

    /// How long a connection may sit with no request in flight before it is
    /// closed, for every protocol.
    ///
    /// Covers what the header timeout cannot: a connection that sends nothing
    /// at all (the cleartext port has to read the first bytes before it knows
    /// whether to speak HTTP/1 or HTTP/2), a TLS handshake that never
    /// finishes, and an HTTP/2 connection with no open streams.
    #[serde(default = "default_idle_timeout_secs")]
    pub idle_timeout_secs: u64,

    /// Interval between HTTP/2 keep-alive PINGs. `0` disables them.
    ///
    /// A peer that vanishes without closing leaves an HTTP/2 connection, and
    /// every stream on it, open until something notices; the PING is what
    /// notices.
    #[serde(default = "default_http2_keepalive_interval_secs")]
    pub http2_keepalive_interval_secs: u64,

    /// How long to wait for a PING to be acknowledged before closing the
    /// connection.
    #[serde(default = "default_http2_keepalive_timeout_secs")]
    pub http2_keepalive_timeout_secs: u64,

    /// How long an upgraded tunnel (WebSocket) may pass no bytes in either
    /// direction before it is closed.
    ///
    /// Longer than the connection idle timeout because a WebSocket is
    /// expected to sit quiet between messages; most clients and servers ping
    /// well within this.
    #[serde(default = "default_tunnel_idle_timeout_secs")]
    pub tunnel_idle_timeout_secs: u64,

    /// Protocols a client may upgrade to, by HTTP/1.1 `Upgrade` or HTTP/2
    /// extended CONNECT (`:protocol`). Compared case-insensitively.
    ///
    /// An upgrade turns the connection into an opaque tunnel to the backend,
    /// and a tunnel is not subject to routing: once `Upgrade: h2c` had been
    /// tunnelled, the client could send the backend any request on any path,
    /// past every route's method and path rules. So only protocols that are
    /// known to be safe to splice are allowed. A request asking for anything
    /// else is forwarded as an ordinary request with the upgrade removed,
    /// which RFC 9110 section 7.8 permits a server to do.
    #[serde(default = "default_allowed_upgrade_protocols")]
    pub allowed_upgrade_protocols: Vec<String>,

    /// Trust the `X-Forwarded-*` and `Forwarded` headers a client sends.
    ///
    /// Off by default: the proxy is then the first hop, anything a client says
    /// about where it came from is a claim it made up, and the headers are
    /// overwritten with what the proxy itself saw. Turn it on only when every
    /// connection reaches this proxy through another proxy you control, which
    /// sets those headers itself; the client's chain is then kept and this
    /// hop appended to it.
    #[serde(default)]
    pub trust_forwarded_headers: bool,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            http_host: default_http_host(),
            http_port: default_http_port(),
            http2_port: None,
            https_host: default_https_host(),
            https_port: default_https_port(),
            https_enabled: false,
            database_config: true,
            config_file: None,
            max_connections: default_max_connections(),
            header_read_timeout_secs: default_header_read_timeout_secs(),
            idle_timeout_secs: default_idle_timeout_secs(),
            http2_keepalive_interval_secs: default_http2_keepalive_interval_secs(),
            http2_keepalive_timeout_secs: default_http2_keepalive_timeout_secs(),
            tunnel_idle_timeout_secs: default_tunnel_idle_timeout_secs(),
            allowed_upgrade_protocols: default_allowed_upgrade_protocols(),
            trust_forwarded_headers: false,
        }
    }
}

/// TLS configuration.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TlsConfig {
    /// Enable ACME (Let's Encrypt)
    #[serde(default)]
    pub acme_enabled: bool,

    /// ACME directory URL
    #[serde(default = "default_acme_directory")]
    pub acme_directory: String,

    /// ACME contact email
    pub acme_email: Option<String>,

    /// Certificate storage directory
    #[serde(default = "default_cert_dir")]
    pub cert_dir: String,

    /// Use staging ACME server
    #[serde(default)]
    pub acme_staging: bool,

    /// PEM certificate chain for the HTTPS listener.
    ///
    /// Set this and `key_file` to serve TLS from a certificate on disk. Without
    /// them there is no HTTPS listener at all, which means HTTP/2 is only
    /// reachable as cleartext h2c and WebSocket only as `ws://`.
    #[serde(default)]
    pub cert_file: Option<String>,

    /// PEM private key matching `cert_file`.
    #[serde(default)]
    pub key_file: Option<String>,

    /// ACME directory URL.
    ///
    /// Defaults to Let's Encrypt production. `acme_staging = true` switches to
    /// staging, which issues untrusted certificates against far looser rate
    /// limits -- use it until the whole flow works, because production's limits
    /// are per-domain-per-week and are easy to exhaust while debugging.
    #[serde(default)]
    pub acme_directory_url: Option<String>,

    /// A PEM root to trust for the ACME directory's own TLS.
    ///
    /// Only for a CA with a private root, which in practice means a test CA
    /// such as Pebble. Never needed for Let's Encrypt.
    #[serde(default)]
    pub acme_root_pem: Option<String>,
}

impl Default for TlsConfig {
    fn default() -> Self {
        Self {
            acme_enabled: false,
            acme_directory: default_acme_directory(),
            acme_email: None,
            cert_dir: default_cert_dir(),
            acme_staging: false,
            cert_file: None,
            key_file: None,
            acme_directory_url: None,
            acme_root_pem: None,
        }
    }
}

/// Default rate limiting settings.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RateLimitDefaults {
    /// Default requests per window
    #[serde(default = "default_rate_limit_requests")]
    pub requests: u32,

    /// Default window size in seconds
    #[serde(default = "default_rate_limit_window")]
    pub window_secs: u32,

    /// Burst allowance
    #[serde(default = "default_burst")]
    pub burst: u32,

    /// Most clients (keys) tracked at once across every rate limit.
    ///
    /// Each distinct client costs an entry, and clients are cheap to invent --
    /// an IPv6 attacker has more addresses than the proxy has memory. At the
    /// cap, entries that have refilled completely are dropped (they say
    /// nothing a fresh entry would not), and if that frees nothing, a new
    /// client is refused rather than let through untracked.
    #[serde(default = "default_max_tracked_keys")]
    pub max_tracked_keys: usize,
}

impl Default for RateLimitDefaults {
    fn default() -> Self {
        Self {
            requests: default_rate_limit_requests(),
            window_secs: default_rate_limit_window(),
            burst: default_burst(),
            max_tracked_keys: default_max_tracked_keys(),
        }
    }
}

/// A proxy route configuration.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Route {
    /// Route ID (database)
    pub id: Option<Uuid>,

    /// Route name
    pub name: String,

    /// Description
    pub description: Option<String>,

    /// Matching criteria
    #[serde(default, rename = "match")]
    pub match_: RouteMatch,

    /// Priority (higher = matched first)
    #[serde(default = "default_priority")]
    pub priority: i32,

    /// Upstream name or ID
    pub upstream: String,

    /// Strip matched path prefix
    #[serde(default)]
    pub strip_path: bool,

    /// Headers to add to proxied requests
    #[serde(default)]
    pub add_headers: HashMap<String, String>,

    /// Headers to remove from proxied requests
    #[serde(default)]
    pub remove_headers: Vec<String>,

    /// Rate limiting for this route
    pub rate_limit: Option<RouteRateLimit>,

    /// Request timeout in seconds
    #[serde(default = "default_timeout")]
    pub timeout_secs: u32,

    /// Retry count on failure
    #[serde(default)]
    pub retry_count: u32,

    /// Route enabled
    #[serde(default = "default_true")]
    pub enabled: bool,
}

/// Route matching criteria.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct RouteMatch {
    /// Host pattern (supports wildcards)
    pub host: Option<String>,

    /// Path pattern
    pub path: Option<String>,

    /// Path matching type
    #[serde(default)]
    pub path_type: PathMatchType,

    /// Headers to match
    #[serde(default)]
    pub headers: HashMap<String, String>,

    /// HTTP methods to match
    pub methods: Option<Vec<String>>,
}

/// Compiled route regexes, keyed by their pattern.
///
/// `Regex::new` is not cheap, and route matching runs on every request against
/// every candidate route -- compiling inside the match, as this first did, put a
/// regex compilation on the hot path for each regex route a request was
/// compared against.
///
/// The cache is unbounded, which is safe because the keys come from the
/// configuration: routes are loaded from a TOML file or the proxy's own tables,
/// both of which an operator controls, and the set changes only when the
/// configuration does.
///
/// A pattern that does not compile is cached as `None`, so a typo costs one
/// failed compilation rather than one per request.
static REGEX_CACHE: LazyLock<RwLock<HashMap<String, Option<Regex>>>> =
    LazyLock::new(|| RwLock::new(HashMap::new()));

/// The compiled form of `pattern`, or `None` if it does not compile.
///
/// Warns once per pattern rather than once per request.
fn compiled_regex(pattern: &str) -> Option<Regex> {
    if let Ok(cache) = REGEX_CACHE.read() {
        if let Some(entry) = cache.get(pattern) {
            return entry.clone();
        }
    }

    let compiled = match Regex::new(pattern) {
        Ok(re) => Some(re),
        Err(error) => {
            tracing::warn!(
                %pattern, %error,
                "route path regex does not compile; the route matches nothing"
            );
            None
        }
    };

    if let Ok(mut cache) = REGEX_CACHE.write() {
        cache.insert(pattern.to_owned(), compiled.clone());
    }
    compiled
}

impl RouteMatch {
    /// Whether a request matches these criteria.
    ///
    /// Every field that is set has to match; a field left unset matches
    /// anything. That is the only reading under which adding a criterion can
    /// never widen a route.
    ///
    /// `path_type`, `methods` and `headers` were all declarable and all ignored
    /// before this existed -- the route filter compared host and path prefix and
    /// nothing else. Each of those silent no-ops widened a route past what its
    /// author wrote: `path_type = "exact"` on `/health` also matched
    /// `/health-internal`, and a route restricted to `methods = ["GET"]`
    /// accepted `DELETE`.
    pub fn matches(&self, host: &str, path: &str, method: &str, headers: &HeaderMap) -> bool {
        self.host_matches(host)
            && self.path_matches(path)
            && self.method_matches(method)
            && self.headers_match(headers)
    }

    /// Host, exactly or by a leading `*.` wildcard.
    ///
    /// `*` alone means any host, which is what an absent host also means.
    fn host_matches(&self, host: &str) -> bool {
        let Some(pattern) = self.host.as_deref() else {
            return true;
        };
        let pattern = pattern.trim().to_ascii_lowercase();
        let host = host.trim().to_ascii_lowercase();

        if pattern == "*" || pattern.is_empty() {
            return true;
        }
        if pattern == host {
            return true;
        }
        // `*.example.com` covers one label, not the apex and not two labels --
        // the same rule certificates use.
        match pattern.strip_prefix("*.") {
            Some(suffix) if !suffix.is_empty() => host
                .strip_suffix(&format!(".{suffix}"))
                .is_some_and(|label| !label.is_empty() && !label.contains('.')),
            _ => false,
        }
    }

    /// Path, by the declared [`PathMatchType`].
    ///
    /// A regex that does not compile matches nothing, and says so once. The
    /// alternative -- treating it as a prefix, or matching everything -- turns a
    /// typo into a route that catches traffic it was never meant to.
    fn path_matches(&self, path: &str) -> bool {
        let Some(pattern) = self.path.as_deref() else {
            return true;
        };
        match self.path_type {
            PathMatchType::Prefix => path_has_prefix(path, pattern),
            PathMatchType::Exact => path == pattern,
            PathMatchType::Regex => match compiled_regex(pattern) {
                Some(re) => re.is_match(path),
                None => false,
            },
        }
    }

    /// Method, case-insensitively. An empty list means any.
    fn method_matches(&self, method: &str) -> bool {
        match self.methods.as_deref() {
            None | Some([]) => true,
            Some(allowed) => allowed.iter().any(|m| m.eq_ignore_ascii_case(method)),
        }
    }

    /// Every named header must be present with that value, case-insensitively
    /// on the name and exactly on the value.
    fn headers_match(&self, headers: &HeaderMap) -> bool {
        self.headers.iter().all(|(name, expected)| {
            headers
                .get(name.as_str())
                .and_then(|value| value.to_str().ok())
                .is_some_and(|value| value == expected)
        })
    }
}

/// Whether `path` is `prefix` or lies beneath it, on a segment boundary.
///
/// A raw `starts_with` let `/public` catch `/publicity` and `/public-admin`,
/// which are different resources that merely share letters. So `/public`
/// matches `/public` and `/public/...` and nothing else. A prefix written with
/// a trailing slash already ends on a boundary and keeps its literal meaning:
/// `/public/` matches `/public/x` but not `/public`.
pub fn path_has_prefix(path: &str, prefix: &str) -> bool {
    if prefix.is_empty() || prefix.ends_with('/') {
        return path.starts_with(prefix);
    }
    match path.strip_prefix(prefix) {
        Some(rest) => rest.is_empty() || rest.starts_with('/'),
        None => false,
    }
}

/// Path matching type.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum PathMatchType {
    /// Prefix matching (default)
    #[default]
    Prefix,
    /// Exact matching
    Exact,
    /// Regex matching
    Regex,
}

/// Per-route rate limiting.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RouteRateLimit {
    /// Requests per window
    pub requests: u32,
    /// Window size in seconds
    pub window_secs: u32,
    /// Rate limit key
    #[serde(default)]
    pub key: RateLimitKey,
}

/// Rate limit key type.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RateLimitKey {
    /// Rate limit by client IP
    #[default]
    ClientIp,
    /// Rate limit by header value
    Header(String),
    /// Rate limit by route (global for route)
    Route,
}

/// An upstream (group of backend servers).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Upstream {
    /// Upstream ID (database)
    pub id: Option<Uuid>,

    /// Upstream name
    pub name: String,

    /// Description
    pub description: Option<String>,

    /// Load balancing strategy
    #[serde(default)]
    pub lb_strategy: LoadBalanceStrategy,

    /// Backend servers
    #[serde(default)]
    pub backends: Vec<Backend>,

    /// Health check configuration
    #[serde(default)]
    pub health_check: HealthCheckConfig,

    /// Upstream enabled
    #[serde(default = "default_true")]
    pub enabled: bool,
}

impl Upstream {
    /// The identifier this upstream is keyed by in the routing tables.
    ///
    /// `id` is only set for upstreams loaded from the database. A TOML config
    /// leaves it `None`, and both registration sites used to skip any upstream
    /// without one -- so a file-configured proxy logged "Loaded N routes and N
    /// upstreams" and then answered every request with 503 "Upstream not
    /// found". Names are unique within a config, so deriving a stable UUID
    /// from the name is enough to key the tables consistently.
    pub fn resolved_id(&self) -> Uuid {
        self.id
            .unwrap_or_else(|| Uuid::new_v5(&Uuid::NAMESPACE_OID, self.name.as_bytes()))
    }
}

/// Load balancing strategy.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum LoadBalanceStrategy {
    /// Round-robin (default)
    #[default]
    RoundRobin,
    /// Least connections
    LeastConnections,
    /// Weighted
    Weighted,
    /// Random
    Random,
    /// Sticky (cookie-based)
    Sticky,
}

/// A backend server.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Backend {
    /// Backend ID (database)
    pub id: Option<Uuid>,

    /// Server address (host:port)
    pub address: String,

    /// HTTP or HTTPS
    #[serde(default = "default_scheme")]
    pub scheme: String,

    /// Weight for weighted load balancing
    #[serde(default = "default_weight")]
    pub weight: u32,

    /// Backend enabled
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Protocol to speak on the upstream connection.
    ///
    /// Defaults to HTTP/1.1 regardless of how the client arrived, because
    /// HTTP/2 is a per-hop protocol. Set `http_version = "h2c"` for a backend
    /// that speaks cleartext HTTP/2 with prior knowledge. There is no
    /// negotiation: h2c has no ALPN to fall back on, so this has to be declared.
    #[serde(default)]
    pub http_version: UpstreamHttpVersion,
}

/// Which HTTP version to speak to an upstream.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum UpstreamHttpVersion {
    /// HTTP/1.1. The default, and correct for almost every backend.
    #[default]
    #[serde(alias = "http1", alias = "http/1.1")]
    Http11,
    /// Cleartext HTTP/2 with prior knowledge.
    #[serde(alias = "http2", alias = "h2")]
    H2c,
}

/// Health check configuration.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub struct HealthCheckConfig {
    /// Health check enabled
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Health check path
    #[serde(default = "default_health_path")]
    pub path: String,

    /// Check interval in seconds
    #[serde(default = "default_health_interval")]
    pub interval_secs: u32,

    /// Check timeout in seconds
    #[serde(default = "default_health_timeout")]
    pub timeout_secs: u32,

    /// Healthy threshold (consecutive successes)
    #[serde(default = "default_healthy_threshold")]
    pub healthy_threshold: u32,

    /// Unhealthy threshold (consecutive failures)
    #[serde(default = "default_unhealthy_threshold")]
    pub unhealthy_threshold: u32,
}

impl Default for HealthCheckConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            path: default_health_path(),
            interval_secs: default_health_interval(),
            timeout_secs: default_health_timeout(),
            healthy_threshold: default_healthy_threshold(),
            unhealthy_threshold: default_unhealthy_threshold(),
        }
    }
}

// Default value functions
fn default_http_host() -> String {
    "0.0.0.0".into()
}
fn default_http_port() -> u16 {
    8080
}
fn default_https_host() -> String {
    "0.0.0.0".into()
}
fn default_https_port() -> u16 {
    8443
}
fn default_true() -> bool {
    true
}
fn default_acme_directory() -> String {
    "https://acme-v02.api.letsencrypt.org/directory".into()
}
fn default_cert_dir() -> String {
    "./certs".into()
}
fn default_rate_limit_requests() -> u32 {
    1000
}
fn default_rate_limit_window() -> u32 {
    60
}
fn default_burst() -> u32 {
    50
}
fn default_max_tracked_keys() -> usize {
    100_000
}
fn default_max_connections() -> usize {
    10_000
}
fn default_header_read_timeout_secs() -> u64 {
    30
}
fn default_idle_timeout_secs() -> u64 {
    60
}
fn default_http2_keepalive_interval_secs() -> u64 {
    20
}
fn default_http2_keepalive_timeout_secs() -> u64 {
    20
}
fn default_tunnel_idle_timeout_secs() -> u64 {
    300
}
fn default_allowed_upgrade_protocols() -> Vec<String> {
    vec!["websocket".into()]
}
fn default_priority() -> i32 {
    100
}
fn default_timeout() -> u32 {
    30
}
fn default_scheme() -> String {
    "http".into()
}
fn default_weight() -> u32 {
    100
}
fn default_health_path() -> String {
    "/health".into()
}
fn default_health_interval() -> u32 {
    10
}
fn default_health_timeout() -> u32 {
    5
}
fn default_healthy_threshold() -> u32 {
    2
}
fn default_unhealthy_threshold() -> u32 {
    3
}

/// ACME configuration for automatic certificate management.
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct AcmeConfig {
    /// ACME enabled
    #[serde(default)]
    pub enabled: bool,

    /// Contact email
    pub email: Option<String>,

    /// Use staging server
    #[serde(default)]
    pub staging: bool,

    /// Domains to request certificates for
    #[serde(default)]
    pub domains: Vec<String>,
}

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

    fn header_map(pairs: &[(&str, &str)]) -> HeaderMap {
        let mut map = HeaderMap::new();
        for (name, value) in pairs {
            map.insert(
                http::header::HeaderName::from_bytes(name.as_bytes()).unwrap(),
                http::HeaderValue::from_str(value).unwrap(),
            );
        }
        map
    }

    /// A match with nothing set, so each test can set only what it is about.
    fn any() -> RouteMatch {
        RouteMatch::default()
    }

    #[test]
    fn an_empty_match_matches_anything() {
        let m = any();
        assert!(m.matches("example.com", "/anything", "GET", &HeaderMap::new()));
        assert!(m.matches("", "/", "DELETE", &HeaderMap::new()));
    }

    #[test]
    fn a_prefix_path_matches_by_prefix() {
        let m = RouteMatch {
            path: Some("/v1".into()),
            ..any()
        };
        assert!(m.matches("h", "/v1", "GET", &HeaderMap::new()));
        assert!(m.matches("h", "/v1/users", "GET", &HeaderMap::new()));
        assert!(!m.matches("h", "/v2", "GET", &HeaderMap::new()));
    }

    #[test]
    fn a_prefix_matches_on_segment_boundaries_only() {
        // `/public` used to catch `/publicity`: a different resource that
        // happens to share its first letters.
        let m = RouteMatch {
            path: Some("/public".into()),
            ..any()
        };
        assert!(m.matches("h", "/public", "GET", &HeaderMap::new()));
        assert!(m.matches("h", "/public/", "GET", &HeaderMap::new()));
        assert!(m.matches("h", "/public/a/b", "GET", &HeaderMap::new()));
        assert!(!m.matches("h", "/publicity", "GET", &HeaderMap::new()));
        assert!(!m.matches("h", "/public-admin", "GET", &HeaderMap::new()));
        assert!(!m.matches("h", "/publi", "GET", &HeaderMap::new()));
    }

    #[test]
    fn a_prefix_with_a_trailing_slash_keeps_its_meaning() {
        let m = RouteMatch {
            path: Some("/public/".into()),
            ..any()
        };
        assert!(m.matches("h", "/public/", "GET", &HeaderMap::new()));
        assert!(m.matches("h", "/public/x", "GET", &HeaderMap::new()));
        assert!(!m.matches("h", "/public", "GET", &HeaderMap::new()));

        let root = RouteMatch {
            path: Some("/".into()),
            ..any()
        };
        assert!(root.matches("h", "/", "GET", &HeaderMap::new()));
        assert!(root.matches("h", "/anything/at/all", "GET", &HeaderMap::new()));
    }

    #[test]
    fn the_new_server_settings_have_defaults() {
        // An existing config file names none of them and must keep loading.
        let server: ServerConfig = toml::from_str("http_port = 8080").unwrap();
        assert_eq!(server.max_connections, 10_000);
        assert_eq!(server.header_read_timeout_secs, 30);
        assert_eq!(server.idle_timeout_secs, 60);
        assert_eq!(server.tunnel_idle_timeout_secs, 300);
        assert_eq!(server.allowed_upgrade_protocols, vec!["websocket"]);
        assert!(!server.trust_forwarded_headers);

        let limits: RateLimitDefaults = toml::from_str("requests = 10").unwrap();
        assert_eq!(limits.max_tracked_keys, 100_000);
    }

    #[test]
    fn an_exact_path_does_not_match_a_longer_one() {
        // The widening this guards against: before `path_type` was honoured,
        // an "exact" route on /health also caught /health-internal.
        let m = RouteMatch {
            path: Some("/health".into()),
            path_type: PathMatchType::Exact,
            ..any()
        };
        assert!(m.matches("h", "/health", "GET", &HeaderMap::new()));
        assert!(!m.matches("h", "/health-internal", "GET", &HeaderMap::new()));
        assert!(!m.matches("h", "/health/deep", "GET", &HeaderMap::new()));
    }

    #[test]
    fn a_regex_path_matches_the_pattern() {
        let m = RouteMatch {
            path: Some(r"^/v[0-9]+/users$".into()),
            path_type: PathMatchType::Regex,
            ..any()
        };
        assert!(m.matches("h", "/v1/users", "GET", &HeaderMap::new()));
        assert!(m.matches("h", "/v22/users", "GET", &HeaderMap::new()));
        assert!(!m.matches("h", "/v1/users/1", "GET", &HeaderMap::new()));
        assert!(!m.matches("h", "/users", "GET", &HeaderMap::new()));
    }

    #[test]
    fn a_regex_is_compiled_once_and_reused() {
        // The bug: `Regex::new` inside the match put a compilation on the hot
        // path for every request compared against a regex route. Asserted via
        // the cache rather than by timing, which would be flaky.
        let pattern = format!("^/cache-probe-{}/[0-9]+$", uuid::Uuid::new_v4());
        let m = RouteMatch {
            path: Some(pattern.clone()),
            path_type: PathMatchType::Regex,
            ..any()
        };

        assert!(!REGEX_CACHE.read().unwrap().contains_key(&pattern));
        assert!(m.matches("h", "/nope", "GET", &HeaderMap::new()) || true);
        assert!(
            REGEX_CACHE.read().unwrap().contains_key(&pattern),
            "the compiled regex was not cached"
        );

        // And the cached one still matches correctly.
        let path = pattern
            .trim_start_matches('^')
            .trim_end_matches("/[0-9]+$")
            .to_string();
        assert!(m.matches("h", &format!("{path}/42"), "GET", &HeaderMap::new()));
    }

    #[test]
    fn a_broken_regex_is_cached_as_a_failure() {
        // So a typo costs one failed compilation, not one per request.
        let pattern = format!("/broken-{}/(unclosed", uuid::Uuid::new_v4());
        let m = RouteMatch {
            path: Some(pattern.clone()),
            path_type: PathMatchType::Regex,
            ..any()
        };
        assert!(!m.matches("h", "/anything", "GET", &HeaderMap::new()));
        let cache = REGEX_CACHE.read().unwrap();
        let entry = cache
            .get(&pattern)
            .expect("a pattern that does not compile should still be cached");
        assert!(
            entry.is_none(),
            "it should be cached as a failure, not as a compiled regex"
        );
    }

    #[test]
    fn a_regex_that_does_not_compile_matches_nothing() {
        // Not "everything", and not "treat it as a prefix". Either would turn a
        // typo into a route that catches traffic it was never meant to.
        let m = RouteMatch {
            path: Some("/v1/(unclosed".into()),
            path_type: PathMatchType::Regex,
            ..any()
        };
        assert!(!m.matches("h", "/v1/anything", "GET", &HeaderMap::new()));
        assert!(!m.matches("h", "/v1/(unclosed", "GET", &HeaderMap::new()));
    }

    #[test]
    fn methods_are_honoured_case_insensitively() {
        let m = RouteMatch {
            methods: Some(vec!["GET".into(), "head".into()]),
            ..any()
        };
        assert!(m.matches("h", "/", "GET", &HeaderMap::new()));
        assert!(m.matches("h", "/", "get", &HeaderMap::new()));
        assert!(m.matches("h", "/", "HEAD", &HeaderMap::new()));
        // The widening this guards against: a read-only route accepting writes.
        assert!(!m.matches("h", "/", "DELETE", &HeaderMap::new()));
        assert!(!m.matches("h", "/", "POST", &HeaderMap::new()));
    }

    #[test]
    fn an_empty_method_list_means_any() {
        let m = RouteMatch {
            methods: Some(vec![]),
            ..any()
        };
        assert!(m.matches("h", "/", "PATCH", &HeaderMap::new()));
    }

    #[test]
    fn every_named_header_must_be_present_with_that_value() {
        let m = RouteMatch {
            headers: HashMap::from([
                ("x-tenant".to_string(), "acme".to_string()),
                ("x-env".to_string(), "prod".to_string()),
            ]),
            ..any()
        };

        assert!(m.matches(
            "h",
            "/",
            "GET",
            &header_map(&[("x-tenant", "acme"), ("x-env", "prod")])
        ));
        // All of them, not any of them.
        assert!(!m.matches("h", "/", "GET", &header_map(&[("x-tenant", "acme")])));
        // The value has to match too.
        assert!(!m.matches(
            "h",
            "/",
            "GET",
            &header_map(&[("x-tenant", "other"), ("x-env", "prod")])
        ));
        assert!(!m.matches("h", "/", "GET", &HeaderMap::new()));
    }

    #[test]
    fn header_names_are_case_insensitive() {
        let m = RouteMatch {
            headers: HashMap::from([("X-Tenant".to_string(), "acme".to_string())]),
            ..any()
        };
        assert!(m.matches("h", "/", "GET", &header_map(&[("x-tenant", "acme")])));
    }

    #[test]
    fn a_host_matches_exactly_or_by_a_single_label_wildcard() {
        let exact = RouteMatch {
            host: Some("api.example.com".into()),
            ..any()
        };
        assert!(exact.matches("api.example.com", "/", "GET", &HeaderMap::new()));
        assert!(!exact.matches("www.example.com", "/", "GET", &HeaderMap::new()));

        let wild = RouteMatch {
            host: Some("*.example.com".into()),
            ..any()
        };
        assert!(wild.matches("api.example.com", "/", "GET", &HeaderMap::new()));
        // Not the apex, and not two labels.
        assert!(!wild.matches("example.com", "/", "GET", &HeaderMap::new()));
        assert!(!wild.matches("a.b.example.com", "/", "GET", &HeaderMap::new()));
        // And not a suffix match, which would catch an attacker's domain.
        assert!(!wild.matches("api.example.com.evil.test", "/", "GET", &HeaderMap::new()));
    }

    #[test]
    fn a_star_host_matches_anything() {
        let m = RouteMatch {
            host: Some("*".into()),
            ..any()
        };
        assert!(m.matches("anything.test", "/", "GET", &HeaderMap::new()));
        assert!(m.matches("", "/", "GET", &HeaderMap::new()));
    }

    #[test]
    fn host_matching_is_case_insensitive() {
        let m = RouteMatch {
            host: Some("API.Example.COM".into()),
            ..any()
        };
        assert!(m.matches("api.example.com", "/", "GET", &HeaderMap::new()));
    }

    #[test]
    fn every_set_criterion_has_to_hold() {
        // Adding a criterion must never widen a route.
        let m = RouteMatch {
            host: Some("api.example.com".into()),
            path: Some("/v1".into()),
            path_type: PathMatchType::Prefix,
            methods: Some(vec!["POST".into()]),
            headers: HashMap::from([("x-key".to_string(), "k".to_string())]),
        };
        let headers = header_map(&[("x-key", "k")]);

        assert!(m.matches("api.example.com", "/v1/x", "POST", &headers));
        assert!(!m.matches("other.example.com", "/v1/x", "POST", &headers));
        assert!(!m.matches("api.example.com", "/v2/x", "POST", &headers));
        assert!(!m.matches("api.example.com", "/v1/x", "GET", &headers));
        assert!(!m.matches("api.example.com", "/v1/x", "POST", &HeaderMap::new()));
    }

    #[test]
    fn test_backend_defaults_to_http11() {
        // HTTP/2 is per-hop: a backend says nothing, it gets HTTP/1.1.
        let backend: Backend = toml::from_str(r#"address = "127.0.0.1:8080""#).unwrap();
        assert_eq!(backend.http_version, UpstreamHttpVersion::Http11);
    }

    #[test]
    fn test_backend_h2c_aliases() {
        // h2c has no ALPN, so it must be declared; accept the spellings someone
        // would reasonably reach for.
        for spelling in ["h2c", "h2", "http2"] {
            let toml_src = format!("address = \"127.0.0.1:8080\"\nhttp_version = \"{spelling}\"");
            let backend: Backend = toml::from_str(&toml_src).unwrap();
            assert_eq!(
                backend.http_version,
                UpstreamHttpVersion::H2c,
                "spelling {spelling} should select h2c"
            );
        }
    }

    #[test]
    fn test_backend_http11_aliases() {
        for spelling in ["http11", "http1"] {
            let toml_src = format!("address = \"127.0.0.1:8080\"\nhttp_version = \"{spelling}\"");
            let backend: Backend = toml::from_str(&toml_src).unwrap();
            assert_eq!(backend.http_version, UpstreamHttpVersion::Http11);
        }
    }

    #[test]
    fn test_http2_port_is_optional_and_off_by_default() {
        let server: ServerConfig = toml::from_str("").unwrap();
        assert_eq!(server.http2_port, None);

        let server: ServerConfig = toml::from_str("http2_port = 19081").unwrap();
        assert_eq!(server.http2_port, Some(19081));
    }
}