Skip to main content

ic_bn_lib/http/server/
cli.rs

1use std::time::Duration;
2
3use humantime::parse_duration;
4
5use crate::{
6    http::server::{ProxyProtocolMode, ServerOptions},
7    parse_size,
8    tls::TlsOptions,
9};
10
11/// HTTP Server CLI
12#[derive(clap::Args, Clone, Debug, Eq, PartialEq)]
13pub struct HttpServerCli {
14    /// Backlog of incoming connections to set on the listening socket
15    #[clap(env, long, default_value = "2048")]
16    pub http_server_backlog: u32,
17
18    /// Maximum number of HTTP requests to serve over a single connection.
19    /// After this number is reached the connection is gracefully closed.
20    #[clap(env, long)]
21    pub http_server_max_requests_per_conn: Option<u64>,
22
23    /// Timeout for network read calls.
24    /// If the read call takes longer than that - the connection is closed.
25    /// This effectively closes idle HTTP/1.1 connections.
26    #[clap(env, long, default_value = "30s", value_parser = parse_duration)]
27    pub http_server_read_timeout: Duration,
28
29    /// Timeout for network write calls.
30    /// If the write call takes longer than that - the connection is closed.
31    #[clap(env, long, default_value = "30s", value_parser = parse_duration)]
32    pub http_server_write_timeout: Duration,
33
34    /// Idle timeout for connections.
35    /// If no requests are executed during this period - the connections is closed.
36    /// Mostly needed for HTTP/2 where the read timeout sometimes cannot kick in
37    /// due to PING frames and other non-request activity.
38    #[clap(env, long, value_parser = parse_duration)]
39    pub http_server_idle_timeout: Option<Duration>,
40
41    /// TLS handshake timeout
42    #[clap(env, long, default_value = "15s", value_parser = parse_duration)]
43    pub http_server_tls_handshake_timeout: Duration,
44
45    /// For how long to wait for the client to send headers.
46    /// Applies only to HTTP1 connections.
47    /// Should be set lower than the global `http_server_read_timeout`.
48    #[clap(env, long, default_value = "10s", value_parser = parse_duration)]
49    pub http_server_http1_header_read_timeout: Duration,
50
51    /// For how long to wait for the client to send full request body.
52    #[clap(env, long, default_value = "60s", value_parser = parse_duration)]
53    pub http_server_body_read_timeout: Duration,
54
55    /// Maximum number of HTTP2 streams that the client is allowed to create inside a single connection
56    #[clap(env, long, default_value = "128")]
57    pub http_server_http2_max_streams: u32,
58
59    /// Keepalive interval for HTTP2 connections
60    #[clap(env, long, value_parser = parse_duration)]
61    pub http_server_http2_keepalive_interval: Option<Duration>,
62
63    /// Keepalive timeout for HTTP2 connections
64    #[clap(env, long, default_value = "10s", value_parser = parse_duration)]
65    pub http_server_http2_keepalive_timeout: Duration,
66
67    /// TCP Keepalive delay.
68    /// It's the time between when the connection became idle and when the keepalive packet is sent.
69    /// If not specified - keepalives are disabled.
70    #[clap(env, long, value_parser = parse_duration)]
71    pub http_server_tcp_keepalive_delay: Option<Duration>,
72
73    /// TCP Keepalive interval.
74    /// If the acknowledgement for the 1st keepalive wasn't received - retry after this time.
75    /// If not specified - use system default.
76    #[clap(env, long, value_parser = parse_duration)]
77    pub http_server_tcp_keepalive_interval: Option<Duration>,
78
79    /// TCP Keepalive retries.
80    /// If this many keepalives in a row weren't acknowledged - close the connection.
81    /// If not specified - use system default.
82    #[clap(env, long)]
83    pub http_server_tcp_keepalive_retries: Option<u32>,
84
85    /// TCP MSS option.
86    /// Limits the TCP segment size, can be used to work around PMTU issues.
87    #[clap(env, long)]
88    pub http_server_tcp_mss: Option<u32>,
89
90    /// Maximum size of cache to store TLS sessions in memory
91    #[clap(env, long, default_value = "256MB", value_parser = parse_size)]
92    pub http_server_tls_session_cache_size: u64,
93
94    /// Maximum time that a TLS session key can stay in cache without being requested (Time-to-Idle)
95    #[clap(env, long, default_value = "18h", value_parser = parse_duration)]
96    pub http_server_tls_session_cache_tti: Duration,
97
98    /// Lifetime of a TLS1.3 ticket, due to key rotation the actual lifetime will be twice than this
99    #[clap(env, long, default_value = "9h", value_parser = parse_duration)]
100    pub http_server_tls_ticket_lifetime: Duration,
101
102    /// How long to wait for the existing connections to finish before shutting down.
103    /// Also applies to the recycling of connections with `http_server_max_requests_per_conn` option.
104    #[clap(env, long, default_value = "60s", value_parser = parse_duration)]
105    pub http_server_grace_period: Duration,
106
107    /// Whether to expect connections with Proxy Protocol v2.
108    /// If the connection contains the Proxy Protocol v2 header - then we will use the client's IP
109    /// from it instead of TCP endpoint.
110    /// Can be "off", "enabled" or "forced".
111    /// If "enabled" - we'll support connections with or without Proxy Protocol.
112    /// If "forced" then connections without a Proxy Protocol header will not be accepted.
113    #[clap(env, long, default_value = "off")]
114    pub http_server_proxy_protocol_mode: ProxyProtocolMode,
115}
116
117impl From<&HttpServerCli> for ServerOptions {
118    fn from(c: &HttpServerCli) -> Self {
119        Self {
120            backlog: c.http_server_backlog,
121            read_timeout: Some(c.http_server_read_timeout),
122            write_timeout: Some(c.http_server_write_timeout),
123            idle_timeout: c.http_server_idle_timeout,
124            tls_handshake_timeout: c.http_server_tls_handshake_timeout,
125            tcp_keepalive_delay: c.http_server_tcp_keepalive_delay,
126            tcp_keepalive_interval: c.http_server_tcp_keepalive_interval,
127            tcp_keepalive_retries: c.http_server_tcp_keepalive_retries,
128            tcp_mss: c.http_server_tcp_mss,
129            http1_header_read_timeout: c.http_server_http1_header_read_timeout,
130            http2_keepalive_interval: c.http_server_http2_keepalive_interval,
131            http2_keepalive_timeout: c.http_server_http2_keepalive_timeout,
132            http2_max_streams: c.http_server_http2_max_streams,
133            grace_period: c.http_server_grace_period,
134            max_requests_per_conn: c.http_server_max_requests_per_conn,
135            proxy_protocol_mode: c.http_server_proxy_protocol_mode,
136        }
137    }
138}
139
140impl From<&HttpServerCli> for TlsOptions {
141    fn from(c: &HttpServerCli) -> Self {
142        Self {
143            additional_alpn: vec![],
144            sessions_count: c.http_server_tls_session_cache_size,
145            sessions_tti: c.http_server_tls_session_cache_tti,
146            ticket_lifetime: c.http_server_tls_ticket_lifetime,
147            tls_versions: vec![],
148        }
149    }
150}
151
152#[cfg(test)]
153mod test {
154    use clap::Parser;
155
156    use super::*;
157
158    /// Wrapper needed to be able to use `try_parse_from` on `clap::Args`
159    #[derive(Parser)]
160    struct Cli {
161        #[clap(flatten)]
162        srv: HttpServerCli,
163    }
164
165    fn parse(args: &[&str]) -> HttpServerCli {
166        let mut v = vec!["test"];
167        v.extend_from_slice(args);
168        Cli::try_parse_from(v).unwrap().srv
169    }
170
171    fn try_parse(args: &[&str]) -> Result<HttpServerCli, clap::Error> {
172        let mut v = vec!["test"];
173        v.extend_from_slice(args);
174        Cli::try_parse_from(v).map(|x| x.srv)
175    }
176
177    const ALL_ARGS: &[&str] = &[
178        "--http-server-backlog=4096",
179        "--http-server-max-requests-per-conn=1000",
180        "--http-server-read-timeout=1m",
181        "--http-server-write-timeout=2m",
182        "--http-server-idle-timeout=3m",
183        "--http-server-tls-handshake-timeout=4s",
184        "--http-server-http1-header-read-timeout=5s",
185        "--http-server-body-read-timeout=6s",
186        "--http-server-http2-max-streams=256",
187        "--http-server-http2-keepalive-interval=7s",
188        "--http-server-http2-keepalive-timeout=8s",
189        "--http-server-tcp-keepalive-delay=9s",
190        "--http-server-tcp-keepalive-interval=10s",
191        "--http-server-tcp-keepalive-retries=11",
192        "--http-server-tcp-mss=1400",
193        "--http-server-tls-session-cache-size=1MB",
194        "--http-server-tls-session-cache-tti=12h",
195        "--http-server-tls-ticket-lifetime=13h",
196        "--http-server-grace-period=14s",
197        "--http-server-proxy-protocol-mode=forced",
198    ];
199
200    #[test]
201    fn test_cli_defaults() {
202        let c = parse(&[]);
203
204        assert_eq!(c.http_server_backlog, 2048);
205        assert_eq!(c.http_server_max_requests_per_conn, None);
206        assert_eq!(c.http_server_read_timeout, Duration::from_secs(30));
207        assert_eq!(c.http_server_write_timeout, Duration::from_secs(30));
208        assert_eq!(c.http_server_idle_timeout, None);
209        assert_eq!(c.http_server_tls_handshake_timeout, Duration::from_secs(15));
210        assert_eq!(
211            c.http_server_http1_header_read_timeout,
212            Duration::from_secs(10)
213        );
214        assert_eq!(c.http_server_body_read_timeout, Duration::from_secs(60));
215        assert_eq!(c.http_server_http2_max_streams, 128);
216        assert_eq!(c.http_server_http2_keepalive_interval, None);
217        assert_eq!(
218            c.http_server_http2_keepalive_timeout,
219            Duration::from_secs(10)
220        );
221        assert_eq!(c.http_server_tcp_keepalive_delay, None);
222        assert_eq!(c.http_server_tcp_keepalive_interval, None);
223        assert_eq!(c.http_server_tcp_keepalive_retries, None);
224        assert_eq!(c.http_server_tcp_mss, None);
225        // `parse_size` is binary, so MB == MiB
226        assert_eq!(c.http_server_tls_session_cache_size, 256 * 1024 * 1024);
227        assert_eq!(
228            c.http_server_tls_session_cache_tti,
229            Duration::from_secs(18 * 3600)
230        );
231        assert_eq!(
232            c.http_server_tls_ticket_lifetime,
233            Duration::from_secs(9 * 3600)
234        );
235        assert_eq!(c.http_server_grace_period, Duration::from_secs(60));
236        assert_eq!(c.http_server_proxy_protocol_mode, ProxyProtocolMode::Off);
237    }
238
239    #[test]
240    fn test_cli_explicit_values() {
241        let c = parse(ALL_ARGS);
242
243        assert_eq!(c.http_server_backlog, 4096);
244        assert_eq!(c.http_server_max_requests_per_conn, Some(1000));
245        assert_eq!(c.http_server_read_timeout, Duration::from_secs(60));
246        assert_eq!(c.http_server_write_timeout, Duration::from_secs(120));
247        assert_eq!(c.http_server_idle_timeout, Some(Duration::from_secs(180)));
248        assert_eq!(c.http_server_tls_handshake_timeout, Duration::from_secs(4));
249        assert_eq!(
250            c.http_server_http1_header_read_timeout,
251            Duration::from_secs(5)
252        );
253        assert_eq!(c.http_server_body_read_timeout, Duration::from_secs(6));
254        assert_eq!(c.http_server_http2_max_streams, 256);
255        assert_eq!(
256            c.http_server_http2_keepalive_interval,
257            Some(Duration::from_secs(7))
258        );
259        assert_eq!(
260            c.http_server_http2_keepalive_timeout,
261            Duration::from_secs(8)
262        );
263        assert_eq!(
264            c.http_server_tcp_keepalive_delay,
265            Some(Duration::from_secs(9))
266        );
267        assert_eq!(
268            c.http_server_tcp_keepalive_interval,
269            Some(Duration::from_secs(10))
270        );
271        assert_eq!(c.http_server_tcp_keepalive_retries, Some(11));
272        assert_eq!(c.http_server_tcp_mss, Some(1400));
273        assert_eq!(c.http_server_tls_session_cache_size, 1024 * 1024);
274        assert_eq!(
275            c.http_server_tls_session_cache_tti,
276            Duration::from_secs(12 * 3600)
277        );
278        assert_eq!(
279            c.http_server_tls_ticket_lifetime,
280            Duration::from_secs(13 * 3600)
281        );
282        assert_eq!(c.http_server_grace_period, Duration::from_secs(14));
283        assert_eq!(c.http_server_proxy_protocol_mode, ProxyProtocolMode::Forced);
284    }
285
286    #[test]
287    fn test_cli_humantime_compound_duration() {
288        let c = parse(&["--http-server-read-timeout=1h30m10s"]);
289        assert_eq!(c.http_server_read_timeout, Duration::from_secs(5410));
290
291        // Sub-second precision must survive
292        let c = parse(&["--http-server-grace-period=1500ms"]);
293        assert_eq!(c.http_server_grace_period, Duration::from_millis(1500));
294    }
295
296    #[test]
297    fn test_cli_proxy_protocol_modes() {
298        assert_eq!(
299            parse(&["--http-server-proxy-protocol-mode=off"]).http_server_proxy_protocol_mode,
300            ProxyProtocolMode::Off
301        );
302        assert_eq!(
303            parse(&["--http-server-proxy-protocol-mode=enabled"]).http_server_proxy_protocol_mode,
304            ProxyProtocolMode::Enabled
305        );
306        assert_eq!(
307            parse(&["--http-server-proxy-protocol-mode=forced"]).http_server_proxy_protocol_mode,
308            ProxyProtocolMode::Forced
309        );
310
311        // Not snake_case / unknown values must be rejected
312        assert!(try_parse(&["--http-server-proxy-protocol-mode=Enabled"]).is_err());
313        assert!(try_parse(&["--http-server-proxy-protocol-mode=bogus"]).is_err());
314        assert!(try_parse(&["--http-server-proxy-protocol-mode="]).is_err());
315    }
316
317    #[test]
318    fn test_cli_invalid_durations() {
319        assert!(try_parse(&["--http-server-read-timeout=abc"]).is_err());
320        // No unit -> humantime refuses it
321        assert!(try_parse(&["--http-server-write-timeout=30"]).is_err());
322        assert!(try_parse(&["--http-server-idle-timeout=-5s"]).is_err());
323        assert!(try_parse(&["--http-server-grace-period="]).is_err());
324    }
325
326    #[test]
327    fn test_cli_invalid_sizes() {
328        assert!(try_parse(&["--http-server-tls-session-cache-size=abc"]).is_err());
329        assert!(try_parse(&["--http-server-tls-session-cache-size=1QB"]).is_err());
330        assert!(try_parse(&["--http-server-tls-session-cache-size=-1"]).is_err());
331        // Bare numbers are bytes
332        assert_eq!(
333            parse(&["--http-server-tls-session-cache-size=1234"])
334                .http_server_tls_session_cache_size,
335            1234
336        );
337    }
338
339    #[test]
340    fn test_cli_invalid_numbers() {
341        assert!(try_parse(&["--http-server-backlog=-1"]).is_err());
342        // u32 overflow
343        assert!(try_parse(&["--http-server-backlog=4294967296"]).is_err());
344        assert!(try_parse(&["--http-server-http2-max-streams=foo"]).is_err());
345        assert!(try_parse(&["--http-server-max-requests-per-conn=-1"]).is_err());
346        assert!(try_parse(&["--http-server-unknown-option=1"]).is_err());
347    }
348
349    /// Catches clap definition problems (duplicate ids, bad default values that
350    /// don't round-trip through the value parser, etc.)
351    #[test]
352    fn test_cli_definition_is_valid() {
353        use clap::CommandFactory;
354        Cli::command().debug_assert();
355    }
356
357    #[test]
358    fn test_cli_size_units_are_binary() {
359        let size = |s: &str| {
360            parse(&[&format!("--http-server-tls-session-cache-size={s}")])
361                .http_server_tls_session_cache_size
362        };
363
364        assert_eq!(size("0"), 0);
365        assert_eq!(size("1KB"), 1024);
366        assert_eq!(size("512KB"), 512 * 1024);
367        assert_eq!(size("2GB"), 2 * 1024 * 1024 * 1024);
368        // Decimal semantics would give 1_000_000 here
369        assert_eq!(size("1MB"), 1_048_576);
370    }
371
372    #[test]
373    fn test_cli_numeric_boundaries() {
374        assert_eq!(parse(&["--http-server-backlog=0"]).http_server_backlog, 0);
375        assert_eq!(
376            parse(&["--http-server-backlog=4294967295"]).http_server_backlog,
377            u32::MAX
378        );
379        assert_eq!(
380            parse(&["--http-server-http2-max-streams=0"]).http_server_http2_max_streams,
381            0
382        );
383        assert_eq!(
384            parse(&["--http-server-max-requests-per-conn=0"]).http_server_max_requests_per_conn,
385            Some(0)
386        );
387        assert_eq!(
388            parse(&["--http-server-max-requests-per-conn=18446744073709551615"])
389                .http_server_max_requests_per_conn,
390            Some(u64::MAX)
391        );
392        // One past u64
393        assert!(try_parse(&["--http-server-max-requests-per-conn=18446744073709551616"]).is_err());
394    }
395
396    /// Zero durations are accepted by humantime and must be carried over verbatim
397    /// rather than being turned into `None`.
398    #[test]
399    fn test_cli_zero_durations() {
400        let c = parse(&[
401            "--http-server-read-timeout=0s",
402            "--http-server-grace-period=0s",
403            "--http-server-idle-timeout=0s",
404        ]);
405        assert_eq!(c.http_server_read_timeout, Duration::ZERO);
406        assert_eq!(c.http_server_grace_period, Duration::ZERO);
407        assert_eq!(c.http_server_idle_timeout, Some(Duration::ZERO));
408
409        let o = ServerOptions::from(&c);
410        assert_eq!(o.read_timeout, Some(Duration::ZERO));
411        assert_eq!(o.grace_period, Duration::ZERO);
412        assert_eq!(o.idle_timeout, Some(Duration::ZERO));
413    }
414
415    #[test]
416    fn test_cli_clone_and_debug() {
417        let c = parse(ALL_ARGS);
418        assert_eq!(c.clone(), c);
419        // The Debug output is used in startup logs - make sure the fields are in it
420        let d = format!("{c:?}");
421        assert!(d.contains("http_server_backlog: 4096"), "{d}");
422        assert!(d.contains("Forced"), "{d}");
423    }
424
425    #[test]
426    fn test_cli_eq() {
427        assert_eq!(parse(&[]), parse(&["--http-server-read-timeout=30s"]));
428        assert_ne!(parse(&[]), parse(&["--http-server-read-timeout=31s"]));
429        assert_eq!(parse(ALL_ARGS), parse(ALL_ARGS));
430    }
431
432    #[test]
433    fn test_server_options_from_cli() {
434        let c = parse(ALL_ARGS);
435        let o = ServerOptions::from(&c);
436
437        assert_eq!(o.backlog, 4096);
438        // Non-optional CLI timeouts are wrapped into `Some`
439        assert_eq!(o.read_timeout, Some(Duration::from_secs(60)));
440        assert_eq!(o.write_timeout, Some(Duration::from_secs(120)));
441        assert_eq!(o.idle_timeout, Some(Duration::from_secs(180)));
442        assert_eq!(o.tls_handshake_timeout, Duration::from_secs(4));
443        assert_eq!(o.tcp_keepalive_delay, Some(Duration::from_secs(9)));
444        assert_eq!(o.tcp_keepalive_interval, Some(Duration::from_secs(10)));
445        assert_eq!(o.tcp_keepalive_retries, Some(11));
446        assert_eq!(o.tcp_mss, Some(1400));
447        assert_eq!(o.http1_header_read_timeout, Duration::from_secs(5));
448        assert_eq!(o.http2_keepalive_interval, Some(Duration::from_secs(7)));
449        assert_eq!(o.http2_keepalive_timeout, Duration::from_secs(8));
450        assert_eq!(o.http2_max_streams, 256);
451        assert_eq!(o.grace_period, Duration::from_secs(14));
452        assert_eq!(o.max_requests_per_conn, Some(1000));
453        assert_eq!(o.proxy_protocol_mode, ProxyProtocolMode::Forced);
454    }
455
456    #[test]
457    fn test_server_options_from_cli_defaults_keep_optionals_none() {
458        let o = ServerOptions::from(&parse(&[]));
459
460        assert_eq!(o.idle_timeout, None);
461        assert_eq!(o.max_requests_per_conn, None);
462        assert_eq!(o.tcp_keepalive_delay, None);
463        assert_eq!(o.tcp_keepalive_interval, None);
464        assert_eq!(o.tcp_keepalive_retries, None);
465        assert_eq!(o.tcp_mss, None);
466        assert_eq!(o.http2_keepalive_interval, None);
467        // ...while the mandatory ones are always set
468        assert_eq!(o.read_timeout, Some(Duration::from_secs(30)));
469        assert_eq!(o.write_timeout, Some(Duration::from_secs(30)));
470        assert_eq!(o.proxy_protocol_mode, ProxyProtocolMode::Off);
471    }
472
473    #[test]
474    fn test_tls_options_from_cli() {
475        let c = parse(ALL_ARGS);
476        let o = TlsOptions::from(&c);
477
478        assert_eq!(o.sessions_count, 1024 * 1024);
479        assert_eq!(o.sessions_tti, Duration::from_secs(12 * 3600));
480        assert_eq!(o.ticket_lifetime, Duration::from_secs(13 * 3600));
481        // These are not driven by the CLI and are left empty
482        assert!(o.additional_alpn.is_empty());
483        assert!(o.tls_versions.is_empty());
484
485        // The CLI conversion must not inherit `TlsOptions::default()`
486        let d = TlsOptions::default();
487        assert_ne!(o.sessions_count, d.sessions_count);
488        assert_ne!(o.sessions_tti, d.sessions_tti);
489        assert_ne!(o.ticket_lifetime, d.ticket_lifetime);
490    }
491}