navree_http/options.rs
1//! [`HttpOptions`]: the `http` configuration section.
2
3use std::net::SocketAddr;
4use std::path::PathBuf;
5
6use http::HeaderValue;
7use navree_config::{ConfigSection, ConfigTable};
8use navree_contracts::Secret;
9use serde::Deserialize;
10
11use crate::extract::MultipartLimits;
12
13/// HTTP server settings (configuration section `http`; every key optional).
14///
15/// ```toml
16/// [http]
17/// addr = "0.0.0.0:8080"
18/// api_prefix = "/api"
19/// timeout_secs = 30
20/// cors = { allowed_origins = ["http://localhost:3000"] }
21/// errors = { code = true }
22/// server = { max_connections = 10000 }
23/// ```
24#[derive(Clone, Debug, Deserialize, ConfigSection)]
25#[config(key = "http", docs = "/docs/basics/routing/", validate = Self::check_values)]
26#[serde(default)]
27pub struct HttpOptions {
28 /// The address `serve` binds (default `127.0.0.1:8080`).
29 pub addr: String,
30 /// The prefix of every controller route (default `/api`); routes whose
31 /// path starts with `!` ignore it.
32 pub api_prefix: String,
33 /// Cross-origin settings.
34 #[config(table)]
35 pub cors: CorsOptions,
36 /// The request timeout (default 30 s); routes may override it.
37 pub timeout_secs: u64,
38 /// The default request body limit (default 2 MiB); routes may override it.
39 pub body_limit_bytes: usize,
40 /// Requests per minute per client IP (default `Some(600)`; `None` disables).
41 /// Counted in each process, and also in the store `http.rate_limit_store`
42 /// names when every process shares one (`"redis"` with RedisModule).
43 pub per_ip_rate_limit: Option<u32>,
44 /// Where the per-IP limit and route throttles also count: unset or
45 /// `"memory"`, only in each process; else in the `dyn RateLimitStore`
46 /// registered under this name (`"redis"` with RedisModule) too, so every
47 /// process counts them together. A name nothing registered stops the boot.
48 pub rate_limit_store: Option<String>,
49 /// How much of an IPv6 address names a client for every per-IP limit
50 /// (this one, route throttles for guests, the sign-in throttles, the
51 /// OAuth endpoint limits): the first `rate_limit_ipv6_prefix` bits, so
52 /// all addresses of one network share one budget (default 64: one /64,
53 /// the smallest allocation a provider normally gives a customer; 1 to
54 /// 128). IPv4 clients are counted per address, and IPv4-mapped IPv6
55 /// addresses (`::ffff:192.0.2.1`) as IPv4. See [`rate_limit_key`](crate::rate_limit_key).
56 pub rate_limit_ipv6_prefix: u8,
57 /// Send the default security headers (default `true`).
58 pub security_headers: bool,
59 /// Compress responses (default `true`): with gzip, and the pages and ops of
60 /// navree-ui with brotli. Off, no response is compressed by either. A route
61 /// opts out with [`no_compression`](crate::RouteDef::no_compression) and a
62 /// response with `Cache-Control: no-transform`, from both: see the BREACH
63 /// note on [`CompressionLayer`](crate::CompressionLayer).
64 pub compression: bool,
65 /// While this file exists the app answers 503 (default `storage/framework/down`).
66 pub maintenance_file: PathBuf,
67 /// Request paths still served during maintenance, matched exactly
68 /// (default `/health/live`, `/health/ready` and `/metrics`, so probes and
69 /// scrapes keep working and an orchestrator does not restart instances
70 /// that are only down for maintenance). From the environment, a
71 /// comma-separated list (`APP_HTTP__MAINTENANCE_EXCEPT=/health/live,/up`).
72 #[serde(deserialize_with = "navree_config::comma_list")]
73 pub maintenance_except: Vec<String>,
74 /// Take the client IP from `X-Forwarded-For` / `X-Real-IP` sent by any
75 /// peer (default `false`; enable only when every request comes through
76 /// a reverse proxy that sets them). Prefer `trusted_proxies`.
77 pub trust_proxy: bool,
78 /// The reverse proxies (and backends-for-frontends) whose
79 /// `X-Forwarded-For` / `X-Real-IP` name the client: IP addresses or
80 /// CIDR blocks (`127.0.0.1`, `::1`, `10.0.0.0/8`). A request from any
81 /// other peer is identified by its own address, so clients reaching the
82 /// app directly cannot choose theirs. In `X-Forwarded-For`, the client
83 /// is the first address from the right that is not a listed proxy.
84 /// When set, it replaces `trust_proxy`. From the environment, a
85 /// comma-separated list (`APP_HTTP__TRUSTED_PROXIES=127.0.0.1,::1`).
86 #[serde(deserialize_with = "navree_config::comma_list")]
87 pub trusted_proxies: Vec<String>,
88 /// The key for signed URLs. When unset, a key derived from the app key
89 /// (`app.key`, or `APP_KEY`) is used; with no app key either, a random
90 /// per-process key, so signed URLs do not survive a restart.
91 pub signing_key: Option<Secret<String>>,
92 /// How long `serve` waits for in-flight requests after a shutdown signal
93 /// (default 30 s).
94 pub shutdown_grace_secs: u64,
95 /// How error bodies are rendered (`http.errors`).
96 #[config(table)]
97 pub errors: ErrorOptions,
98 /// The limits on connections (`http.server`).
99 #[config(table)]
100 pub server: ServerOptions,
101 /// The limits on `multipart/form-data` forms (`http.multipart`).
102 #[config(table)]
103 pub multipart: MultipartLimits,
104}
105
106/// The limits on connections, enforced by [`serve`](crate::serve()) on every
107/// listener (configuration section `http.server`; every key optional). They
108/// bound what a client can hold without finishing anything, and the defaults
109/// are meant for production.
110///
111/// A key of type `Option` is turned off with `None`, which TOML cannot write
112/// (set it to `null` through `ConfigSources`, or in code, as for
113/// `http.per_ip_rate_limit`); `0` fails the boot.
114///
115/// ```toml
116/// [http.server]
117/// header_read_timeout_ms = 10000
118/// idle_timeout_ms = 75000
119/// body_read_timeout_ms = 20000
120/// body_min_bytes_per_sec = 256
121/// http2_keep_alive_interval_ms = 30000
122/// http2_keep_alive_timeout_ms = 20000
123/// http2_max_concurrent_streams = 200
124/// max_connections = 10000
125/// max_connections_per_ip = 256
126/// max_header_bytes = 32768
127/// max_headers = 100
128/// write_stall_timeout_ms = 60000
129/// ```
130#[derive(Clone, Debug, Deserialize, ConfigTable)]
131#[serde(default)]
132pub struct ServerOptions {
133 /// How long a client has to send a request head, from the moment it
134 /// connects (or from its first byte, between two requests of a
135 /// connection) to the end of the head (default 10 s). A client that
136 /// takes longer, however steadily it sends, is disconnected. On HTTP/2 a
137 /// new connection has this long to open its first stream. A head sent in
138 /// one read with a request that has no body is timed from the end of
139 /// that response; after a request with a body it has `idle_timeout_ms`.
140 pub header_read_timeout_ms: Option<u64>,
141 /// How long a connection may sit with no request in flight before the
142 /// server closes it (default 75 s, above the 60 s of common load
143 /// balancers, so they close first and never reuse a closing connection).
144 /// Nothing a client sends extends it on HTTP/2; on HTTP/1 its next byte
145 /// starts a request head, and with `header_read_timeout_ms` off this
146 /// deadline stays. A response still on its way to the client is not
147 /// idle: `write_stall_timeout_ms` is the limit then.
148 pub idle_timeout_ms: Option<u64>,
149 /// The longest the server waits for a request body while a handler reads
150 /// it (default 20 s): a stall this long ends the read with a 408, and
151 /// the connection closes (on HTTP/2 the stream ends and the connection
152 /// stays). Only time spent waiting on the client counts.
153 pub body_read_timeout_ms: Option<u64>,
154 /// The slowest a request body may arrive, averaged over time (default
155 /// 256 bytes per second): each byte earns back `1 / rate` seconds of
156 /// `body_read_timeout_ms`, so a client dripping bytes runs out of it even
157 /// though it never stalls for long. `None` makes any byte restore the
158 /// whole timeout. Does nothing without `body_read_timeout_ms`.
159 pub body_min_bytes_per_sec: Option<u64>,
160 /// How often an HTTP/2 connection that has gone quiet is pinged (default
161 /// 30 s), so dead peers are found while a request is in flight.
162 pub http2_keep_alive_interval_ms: Option<u64>,
163 /// How long a client has to answer an HTTP/2 ping before the connection
164 /// closes (default 20 s).
165 pub http2_keep_alive_timeout_ms: u64,
166 /// The most requests one HTTP/2 connection may have open at once
167 /// (default 200).
168 pub http2_max_concurrent_streams: u32,
169 /// The most connections open at once, WebSockets and TLS handshakes in
170 /// progress included (default 10 000). At the cap new connections wait
171 /// until one closes, nearly all of them in the listen backlog, and
172 /// nothing is read from or answered on them until then. For a client
173 /// that has sent something, the connection idle the longest closes, as at
174 /// its idle timeout, one for each such client, and a connection that has
175 /// only started its next request head counts as idle. A client that has
176 /// sent nothing closes nothing, and has `header_read_timeout_ms` to wait.
177 pub max_connections: Option<usize>,
178 /// The most connections open at once from one client address (default
179 /// 256), counted like `http.per_ip_rate_limit`: per IPv4 address, or per
180 /// IPv6 network of `http.rate_limit_ipv6_prefix` bits. At the limit a new
181 /// connection takes the place of the address's own connection idle the
182 /// longest, closed as at its idle timeout. That one counts until its
183 /// socket has closed, and at most 8 of an address's connections (no more
184 /// than the limit) close for newer ones at a time, so one address holds
185 /// at most the limit and those. When none of its connections is idle, or
186 /// that many are closing, the new one is closed at once; it cannot wait,
187 /// because the address is only known after the accept.
188 ///
189 /// This limits what one address can hold. It does not stop a client with
190 /// many addresses, which `max_connections` is then the limit for.
191 ///
192 /// Peers in `http.trusted_proxies`, or every peer with `http.trust_proxy`,
193 /// are not counted: each carries many clients. Behind a reverse proxy
194 /// list it there (`http.per_ip_rate_limit` needs that too) or raise this,
195 /// or a busy proxy runs into it. So can many clients sharing one address,
196 /// such as an office or a carrier.
197 ///
198 /// Counted per listener, like `max_connections`, and by the peer of the
199 /// socket, so a proxy's clients are never limited here: limit those at
200 /// the proxy.
201 pub max_connections_per_ip: Option<usize>,
202 /// The largest request head, in bytes (default 32 KiB, at least 8 KiB):
203 /// the request line and headers on HTTP/1, the header list on HTTP/2,
204 /// where each header also counts 32 bytes. Above it the answer is a 431.
205 pub max_header_bytes: usize,
206 /// The most headers a request may have (default 100, 431 above it). On
207 /// HTTP/2 a header can cost a client a single byte, so without this a
208 /// small request could carry a thousand into the app; a browser's cookies
209 /// can count one each there, as HTTP/2 allows sending them apart.
210 pub max_headers: usize,
211 /// How long a response may go without moving (default 60 s). When the
212 /// socket takes nothing for this long the connection closes; when an
213 /// HTTP/2 client's flow control holds one response back for this long,
214 /// that stream is reset and the connection stays. Each byte the socket
215 /// takes starts it over, and on HTTP/2 each 16 KiB the client takes from
216 /// a response, so only a client that has really stopped runs out. It
217 /// also applies to what a handler writes to an upgraded HTTP/1 socket,
218 /// but not to an HTTP/2 WebSocket held back by flow control: that is the
219 /// work of `upgraded_idle_timeout_ms`, or of a timeout on the handler's
220 /// own writes. A client pausing a large download for longer loses it and
221 /// has to ask for the rest.
222 pub write_stall_timeout_ms: Option<u64>,
223 /// How long an upgraded connection (a WebSocket) may go with no bytes
224 /// from its client before it closes (default `None`: never). A quiet
225 /// WebSocket is a healthy one to the server, so this is for apps that
226 /// know how their sockets talk: set it above the heartbeat of the
227 /// protocol, whose answers are what count. What the server writes does
228 /// not, so a heartbeat of its own cannot keep a silent client's socket
229 /// open. The connection closes with an error, so a handler sees its read
230 /// fail, and a handler must be reading for this to work. On HTTP/2 it
231 /// applies once nothing but upgraded streams is left on the connection,
232 /// and only `DATA` counts: the frames that look after the connection,
233 /// such as keep-alive pings, are silence.
234 pub upgraded_idle_timeout_ms: Option<u64>,
235}
236
237impl Default for ServerOptions {
238 fn default() -> Self {
239 Self {
240 header_read_timeout_ms: Some(10_000),
241 idle_timeout_ms: Some(75_000),
242 body_read_timeout_ms: Some(20_000),
243 body_min_bytes_per_sec: Some(256),
244 http2_keep_alive_interval_ms: Some(30_000),
245 http2_keep_alive_timeout_ms: 20_000,
246 http2_max_concurrent_streams: 200,
247 max_connections: Some(10_000),
248 max_connections_per_ip: Some(256),
249 max_header_bytes: 32 * 1024,
250 max_headers: 100,
251 write_stall_timeout_ms: Some(60_000),
252 upgraded_idle_timeout_ms: None,
253 }
254 }
255}
256
257impl ServerOptions {
258 /// Adds every problem with these options to `errors`.
259 fn check(&self, errors: &mut Vec<String>) {
260 let optional = [
261 ("header_read_timeout_ms", self.header_read_timeout_ms),
262 ("idle_timeout_ms", self.idle_timeout_ms),
263 ("body_read_timeout_ms", self.body_read_timeout_ms),
264 ("body_min_bytes_per_sec", self.body_min_bytes_per_sec),
265 (
266 "http2_keep_alive_interval_ms",
267 self.http2_keep_alive_interval_ms,
268 ),
269 (
270 "max_connections",
271 self.max_connections.map(|connections| connections as u64),
272 ),
273 (
274 "max_connections_per_ip",
275 self.max_connections_per_ip
276 .map(|connections| connections as u64),
277 ),
278 ("write_stall_timeout_ms", self.write_stall_timeout_ms),
279 ("upgraded_idle_timeout_ms", self.upgraded_idle_timeout_ms),
280 ];
281 for (key, value) in optional {
282 if value == Some(0) {
283 errors.push(format!("http.server.{key} must be at least 1 (or unset)"));
284 }
285 }
286 if self
287 .max_connections
288 .is_some_and(|connections| connections > tokio::sync::Semaphore::MAX_PERMITS)
289 {
290 errors.push("http.server.max_connections is too large".to_owned());
291 }
292 if self.http2_keep_alive_timeout_ms == 0 {
293 errors.push("http.server.http2_keep_alive_timeout_ms must be at least 1".to_owned());
294 }
295 if self.http2_max_concurrent_streams == 0 {
296 errors.push("http.server.http2_max_concurrent_streams must be at least 1".to_owned());
297 }
298 if self.max_header_bytes < crate::serve::MIN_HEADER_BYTES
299 || u32::try_from(self.max_header_bytes).is_err()
300 {
301 errors.push(format!(
302 "http.server.max_header_bytes must be between {} and {} (got {})",
303 crate::serve::MIN_HEADER_BYTES,
304 u32::MAX,
305 self.max_header_bytes
306 ));
307 }
308 if self.max_headers == 0 {
309 errors.push("http.server.max_headers must be at least 1".to_owned());
310 }
311 }
312}
313
314/// How error bodies are rendered (configuration section `http.errors`).
315///
316/// ```toml
317/// [http.errors]
318/// code = true
319/// ```
320#[derive(Clone, Debug, Deserialize, ConfigTable)]
321#[serde(default)]
322pub struct ErrorOptions {
323 /// Send the machine-readable `code` member in every error body (default
324 /// `true`). `false` leaves it out (`APP_HTTP__ERRORS__CODE=false`).
325 pub code: bool,
326}
327
328impl Default for ErrorOptions {
329 fn default() -> Self {
330 Self { code: true }
331 }
332}
333
334impl Default for HttpOptions {
335 fn default() -> Self {
336 Self {
337 addr: "127.0.0.1:8080".to_owned(),
338 api_prefix: "/api".to_owned(),
339 cors: CorsOptions::default(),
340 timeout_secs: 30,
341 body_limit_bytes: 2 * 1024 * 1024,
342 per_ip_rate_limit: Some(600),
343 rate_limit_store: None,
344 rate_limit_ipv6_prefix: crate::network::DEFAULT_IPV6_PREFIX,
345 security_headers: true,
346 compression: true,
347 maintenance_file: PathBuf::from("storage/framework/down"),
348 maintenance_except: ["/health/live", "/health/ready", "/metrics"]
349 .map(str::to_owned)
350 .to_vec(),
351 trust_proxy: false,
352 trusted_proxies: Vec::new(),
353 signing_key: None,
354 shutdown_grace_secs: 30,
355 errors: ErrorOptions::default(),
356 server: ServerOptions::default(),
357 multipart: MultipartLimits::default(),
358 }
359 }
360}
361
362/// Cross-origin resource sharing: only the listed origins, with credentials,
363/// and explicitly listed request and exposed headers (no wildcards). Applied
364/// by [`CorsLayer`](crate::CorsLayer); an origin that is not listed gets no
365/// CORS headers.
366#[derive(Clone, Debug, Deserialize, ConfigTable)]
367#[serde(default)]
368pub struct CorsOptions {
369 /// Exact origins allowed to call the API, e.g. `http://localhost:3000`.
370 /// Empty (the default) disables CORS. `*` is rejected. From the
371 /// environment, a comma-separated list
372 /// (`APP_HTTP__CORS__ALLOWED_ORIGINS=http://localhost:3000,https://app.example.com`).
373 #[serde(deserialize_with = "navree_config::comma_list")]
374 pub allowed_origins: Vec<String>,
375 /// Allow cookies on cross-origin requests (default `true`).
376 pub allow_credentials: bool,
377 /// How long browsers may cache a preflight answer (default 600 s).
378 pub max_age_secs: u64,
379}
380
381impl Default for CorsOptions {
382 fn default() -> Self {
383 Self {
384 allowed_origins: Vec::new(),
385 allow_credentials: true,
386 max_age_secs: 600,
387 }
388 }
389}
390
391impl HttpOptions {
392 /// Checks the values for the configuration section: every problem, in
393 /// one message (the boot calls this).
394 fn check_values(&self) -> Result<(), String> {
395 self.check().map_err(|errors| errors.join("; "))
396 }
397
398 /// The key a client's per-IP limits are counted under: its IPv4 address,
399 /// or the network of its IPv6 address (`rate_limit_ipv6_prefix`).
400 pub fn rate_limit_key(&self, ip: std::net::IpAddr) -> std::net::IpAddr {
401 crate::network::rate_limit_key(ip, self.rate_limit_ipv6_prefix)
402 }
403
404 /// Every problem with these options (empty when valid).
405 pub(crate) fn check(&self) -> Result<(), Vec<String>> {
406 let mut errors = Vec::new();
407 if self.addr.parse::<SocketAddr>().is_err() && !self.addr.contains(':') {
408 errors.push(format!(
409 "http.addr must be HOST:PORT, e.g. 127.0.0.1:8080 (got `{}`)",
410 self.addr
411 ));
412 }
413 if !self.api_prefix.is_empty() && !self.api_prefix.starts_with('/') {
414 errors.push("http.api_prefix must be empty or start with `/`".to_owned());
415 }
416 if self.timeout_secs == 0 {
417 errors.push("http.timeout_secs must be at least 1".to_owned());
418 }
419 if self.per_ip_rate_limit == Some(0) {
420 errors.push("http.per_ip_rate_limit must be at least 1 (or unset)".to_owned());
421 }
422 self.server.check(&mut errors);
423 self.multipart.check(&mut errors);
424 if !(1..=128).contains(&self.rate_limit_ipv6_prefix) {
425 errors.push(format!(
426 "http.rate_limit_ipv6_prefix must be between 1 and 128 (got {})",
427 self.rate_limit_ipv6_prefix
428 ));
429 }
430 for proxy in &self.trusted_proxies {
431 if crate::extract::IpNetwork::parse(proxy).is_none() {
432 errors.push(format!(
433 "http.trusted_proxies: `{proxy}` is not an IP address or CIDR block like 10.0.0.0/8"
434 ));
435 }
436 }
437 for origin in &self.cors.allowed_origins {
438 if origin.trim() == "*" {
439 errors.push(
440 "http.cors.allowed_origins must list exact origins; `*` is not allowed"
441 .to_owned(),
442 );
443 } else if HeaderValue::from_str(origin).is_err()
444 || !(origin.starts_with("http://") || origin.starts_with("https://"))
445 {
446 errors.push(format!(
447 "http.cors.allowed_origins: `{origin}` is not an origin like https://app.example.com"
448 ));
449 }
450 }
451 if errors.is_empty() {
452 Ok(())
453 } else {
454 Err(errors)
455 }
456 }
457}
458
459#[cfg(test)]
460mod tests {
461 use navree_config::FieldType;
462
463 use super::*;
464
465 #[test]
466 fn the_section_describes_itself() {
467 let schema = HttpOptions::schema().expect("schema");
468 assert_eq!(schema.key, "http");
469 assert_eq!(schema.docs.as_deref(), Some("/docs/basics/routing/"));
470 assert!(
471 schema.unmarked_secrets().is_empty(),
472 "{:?}",
473 schema.unmarked_secrets()
474 );
475 assert_eq!(schema.secret_paths(), ["http.signing_key"]);
476 let field = |name: &str| {
477 schema
478 .fields
479 .iter()
480 .find(|f| f.name == name)
481 .unwrap_or_else(|| panic!("{name}"))
482 };
483 for table in ["cors", "errors", "server"] {
484 assert_eq!(field(table).ty, FieldType::Table, "{table}");
485 }
486 assert_eq!(
487 field("trusted_proxies").ty,
488 FieldType::list(FieldType::String)
489 );
490 let leaves: Vec<String> = schema.leaves().into_iter().map(|(path, _)| path).collect();
491 for path in [
492 "http.cors.allowed_origins",
493 "http.errors.code",
494 "http.server.max_connections",
495 ] {
496 assert!(leaves.contains(&path.to_owned()), "{path}: {leaves:?}");
497 }
498 let defaults = HttpOptions::defaults().expect("defaults");
499 assert_eq!(defaults["addr"], "127.0.0.1:8080");
500 assert_eq!(defaults["per_ip_rate_limit"], 600);
501 assert_eq!(defaults["server"]["max_connections"], 10_000);
502 assert!(defaults["signing_key"].is_null());
503 }
504
505 #[test]
506 fn the_signing_key_never_shows_in_debug() {
507 let options = HttpOptions {
508 signing_key: Some(Secret::new("url-signing-key-value".to_owned())),
509 ..HttpOptions::default()
510 };
511 assert!(!format!("{options:?}").contains("url-signing-key-value"));
512 }
513
514 #[test]
515 fn defaults_match_the_plan() {
516 let options = HttpOptions::default();
517 assert_eq!(options.addr, "127.0.0.1:8080");
518 assert_eq!(options.api_prefix, "/api");
519 assert_eq!(options.timeout_secs, 30);
520 assert_eq!(options.body_limit_bytes, 2 * 1024 * 1024);
521 assert_eq!(options.per_ip_rate_limit, Some(600));
522 assert!(options.security_headers && options.compression && !options.trust_proxy);
523 assert!(options.cors.allow_credentials);
524 assert!(options.check().is_ok());
525 }
526
527 #[test]
528 fn error_codes_are_rendered_unless_the_environment_turns_them_off() {
529 assert!(HttpOptions::default().errors.code, "on by default");
530 let config = navree_config::Config::load(
531 &navree_config::ConfigSources::new()
532 .env_vars("APP_", [("APP_HTTP__ERRORS__CODE", "false")]),
533 )
534 .unwrap();
535 let options = config.typed::<HttpOptions>().unwrap();
536 assert!(!options.errors.code);
537 assert_eq!(options.api_prefix, "/api", "other keys keep defaults");
538 }
539
540 #[test]
541 fn missing_keys_deserialize_to_defaults() {
542 let options: HttpOptions = serde_json::from_value(
543 serde_json::json!({"cors": {"allowed_origins": ["https://a.example"]}}),
544 )
545 .unwrap();
546 assert_eq!(options.api_prefix, "/api");
547 assert!(options.cors.allow_credentials);
548 assert_eq!(options.cors.allowed_origins, ["https://a.example"]);
549 assert!(options.errors.code);
550 }
551
552 #[test]
553 fn trusted_proxies_come_from_a_list_or_the_environment_and_are_checked() {
554 let config = navree_config::Config::load(&navree_config::ConfigSources::new().env_vars(
555 "APP_",
556 [("APP_HTTP__TRUSTED_PROXIES", "127.0.0.1, ::1,10.0.0.0/8")],
557 ))
558 .unwrap();
559 let options = config.typed::<HttpOptions>().unwrap();
560 assert_eq!(options.trusted_proxies, ["127.0.0.1", "::1", "10.0.0.0/8"]);
561 assert!(HttpOptions::default().trusted_proxies.is_empty());
562
563 let options = HttpOptions {
564 trusted_proxies: vec![
565 "127.0.0.1".into(),
566 "proxy.internal".into(),
567 "10.0.0.0/40".into(),
568 ],
569 ..HttpOptions::default()
570 };
571 let errors = options.check().unwrap_err();
572 assert_eq!(errors.len(), 2, "{errors:?}");
573 assert!(errors[0].contains("proxy.internal"), "{errors:?}");
574 }
575
576 #[test]
577 fn the_ipv6_rate_limit_prefix_defaults_to_a_slash_64_and_is_checked() {
578 assert_eq!(HttpOptions::default().rate_limit_ipv6_prefix, 64);
579 let config = navree_config::Config::load(
580 &navree_config::ConfigSources::new()
581 .env_vars("APP_", [("APP_HTTP__RATE_LIMIT_IPV6_PREFIX", "56")]),
582 )
583 .unwrap();
584 let options = config.typed::<HttpOptions>().unwrap();
585 assert_eq!(options.rate_limit_ipv6_prefix, 56);
586 assert_eq!(
587 options.rate_limit_key("2001:db8:1:ff7f::1".parse().unwrap()),
588 "2001:db8:1:ff00::".parse::<std::net::IpAddr>().unwrap()
589 );
590 for bad in [0, 129] {
591 let options = HttpOptions {
592 rate_limit_ipv6_prefix: bad,
593 ..HttpOptions::default()
594 };
595 let errors = options.check().unwrap_err();
596 assert!(errors[0].contains("rate_limit_ipv6_prefix"), "{errors:?}");
597 }
598 }
599
600 #[test]
601 fn server_limits_default_to_safe_values_and_come_from_the_environment() {
602 let server = HttpOptions::default().server;
603 assert_eq!(server.header_read_timeout_ms, Some(10_000));
604 assert_eq!(server.idle_timeout_ms, Some(75_000));
605 assert_eq!(server.body_read_timeout_ms, Some(20_000));
606 assert_eq!(server.body_min_bytes_per_sec, Some(256));
607 assert_eq!(server.http2_keep_alive_interval_ms, Some(30_000));
608 assert_eq!(server.http2_keep_alive_timeout_ms, 20_000);
609 assert_eq!(server.http2_max_concurrent_streams, 200);
610 assert_eq!(server.max_connections, Some(10_000));
611 assert_eq!(server.max_connections_per_ip, Some(256));
612 assert_eq!(server.max_header_bytes, 32 * 1024);
613 assert_eq!(server.max_headers, 100);
614 assert_eq!(server.write_stall_timeout_ms, Some(60_000));
615 assert_eq!(server.upgraded_idle_timeout_ms, None);
616
617 let config = navree_config::Config::load(&navree_config::ConfigSources::new().env_vars(
618 "APP_",
619 [
620 ("APP_HTTP__SERVER__HEADER_READ_TIMEOUT_MS", "2500"),
621 ("APP_HTTP__SERVER__MAX_CONNECTIONS", "64"),
622 ],
623 ))
624 .unwrap();
625 let options = config.typed::<HttpOptions>().unwrap();
626 assert_eq!(options.server.header_read_timeout_ms, Some(2_500));
627 assert_eq!(options.server.max_connections, Some(64));
628 assert_eq!(
629 options.server.idle_timeout_ms,
630 Some(75_000),
631 "other keys keep defaults"
632 );
633 }
634
635 #[test]
636 fn server_limits_are_checked() {
637 let options = HttpOptions {
638 server: ServerOptions {
639 header_read_timeout_ms: Some(0),
640 idle_timeout_ms: Some(0),
641 body_read_timeout_ms: Some(0),
642 body_min_bytes_per_sec: Some(0),
643 http2_keep_alive_interval_ms: Some(0),
644 http2_keep_alive_timeout_ms: 0,
645 http2_max_concurrent_streams: 0,
646 max_connections: Some(0),
647 max_connections_per_ip: Some(0),
648 max_header_bytes: 1024,
649 max_headers: 0,
650 write_stall_timeout_ms: Some(0),
651 upgraded_idle_timeout_ms: Some(0),
652 },
653 ..HttpOptions::default()
654 };
655 let errors = options.check().unwrap_err();
656 assert_eq!(errors.len(), 13, "{errors:?}");
657 assert!(errors[0].contains("header_read_timeout_ms"), "{errors:?}");
658 for key in [
659 "max_connections_per_ip",
660 "write_stall_timeout_ms",
661 "upgraded_idle_timeout_ms",
662 ] {
663 assert!(errors.iter().any(|e| e.contains(key)), "{errors:?}");
664 }
665
666 // Off is `None`, never `0`.
667 let options = HttpOptions {
668 server: ServerOptions {
669 header_read_timeout_ms: None,
670 idle_timeout_ms: None,
671 body_read_timeout_ms: None,
672 body_min_bytes_per_sec: None,
673 http2_keep_alive_interval_ms: None,
674 max_connections: None,
675 max_connections_per_ip: None,
676 write_stall_timeout_ms: None,
677 upgraded_idle_timeout_ms: None,
678 ..ServerOptions::default()
679 },
680 ..HttpOptions::default()
681 };
682 assert!(options.check().is_ok());
683 }
684
685 #[test]
686 fn allowed_origins_can_come_from_one_environment_variable() {
687 let config = navree_config::Config::load(&navree_config::ConfigSources::new().env_vars(
688 "APP_",
689 [(
690 "APP_HTTP__CORS__ALLOWED_ORIGINS",
691 "http://localhost:3000, https://app.example.com,",
692 )],
693 ))
694 .unwrap();
695 let options = config.typed::<HttpOptions>().unwrap();
696 assert_eq!(
697 options.cors.allowed_origins,
698 ["http://localhost:3000", "https://app.example.com"]
699 );
700 assert!(options.cors.allow_credentials, "other keys keep defaults");
701 }
702
703 #[test]
704 fn wildcard_and_malformed_origins_are_rejected() {
705 let mut options = HttpOptions::default();
706 options.cors.allowed_origins = vec!["*".into(), "localhost:3000".into()];
707 let errors = options.check().unwrap_err();
708 assert_eq!(errors.len(), 2, "{errors:?}");
709 assert!(errors[0].contains('*'));
710 }
711}