Skip to main content

nitr_http/config/sections/
server.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! Sections for the listener and its protections: `[health]`, `[log]`,
7//! `[limits]`, `[shutdown]`, `[cors]`, `[rate_limit]`, `[tls]`.
8
9use std::net::SocketAddr;
10use std::path::PathBuf;
11
12use serde::{Deserialize, Serialize};
13
14/// Health and readiness endpoints (`[health]` section), answered entirely
15/// in Rust.
16///
17/// Two deliberately separate questions: liveness ("is the process alive?")
18/// never touches a Lua state; a probe that queued behind a saturated pool
19/// would cause the restart it exists to prevent; and readiness ("should
20/// it receive traffic?") flips to `503` the moment a graceful drain
21/// starts, so a rolling deploy shifts traffic before requests can fail.
22/// An application cannot influence either answer.
23#[derive(Debug, Clone, Deserialize, Serialize)]
24#[serde(default, deny_unknown_fields)]
25pub struct HealthConfig {
26    /// Whether the endpoints are served at all.
27    pub enabled: bool,
28    /// Liveness path: `200 ok` while the process runs.
29    pub liveness: String,
30    /// Readiness path: `200 ok` while accepting traffic, `503 draining`
31    /// once a graceful shutdown begins.
32    pub readiness: String,
33    /// A separate address to serve the endpoints on, keeping them off the
34    /// public port. When unset they answer on the main listener.
35    pub bind: Option<SocketAddr>,
36    /// Connection cap for the separate probe listener (`bind`), deliberately
37    /// far below `[limits] max_connections`: a prober opens one connection,
38    /// not a thousand, and inheriting the main cap would let the probe port
39    /// consume the process's whole file-descriptor budget on its own.
40    /// Ignored when the probes answer on the main listener, which has its
41    /// own cap.
42    pub max_connections: usize,
43}
44
45impl Default for HealthConfig {
46    fn default() -> Self {
47        Self {
48            enabled: true,
49            liveness: "/healthz".into(),
50            readiness: "/readyz".into(),
51            bind: None,
52            max_connections: 64,
53        }
54    }
55}
56
57/// Log output (`[log]` section).
58#[derive(Debug, Clone, Default, Deserialize, Serialize)]
59#[serde(default, deny_unknown_fields)]
60pub struct LogConfig {
61    /// Output format.
62    pub format: LogFormat,
63    /// Minimum level (`trace`/`debug`/`info`/`warn`/`error`), or any
64    /// `tracing` filter directive. The `RUST_LOG` environment variable
65    /// wins over this; without either, `info` (`debug` in dev mode).
66    pub level: Option<String>,
67}
68
69/// How log lines are rendered.
70#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
71#[serde(rename_all = "lowercase")]
72pub enum LogFormat {
73    /// Human-readable single-line text (the default).
74    #[default]
75    Text,
76    /// One JSON object per line, with the request/error fields as real
77    /// keys — what makes the structured fields usable by a log shipper.
78    Json,
79}
80
81/// Request-size and connection limits (`[limits]` section), enforced in
82/// Rust before a request reaches Lua.
83#[derive(Debug, Clone, Deserialize, Serialize)]
84#[serde(default, deny_unknown_fields)]
85pub struct LimitsConfig {
86    /// Maximum declared request body size in bytes (413 beyond it).
87    pub max_body_bytes: u64,
88    /// Maximum request header buffer in bytes (hyper enforces a floor of
89    /// 8 KiB).
90    pub max_header_bytes: usize,
91    /// Maximum request URI length in bytes (414 beyond it).
92    pub max_uri_bytes: usize,
93    /// Maximum concurrent TCP connections; the listener stops accepting
94    /// while at the cap.
95    pub max_connections: usize,
96    /// How long a request may wait for a free Lua state before it is shed
97    /// with `503` and a `Retry-After`, in milliseconds. `0` waits forever
98    /// (the pre-phase-10 behavior). Shedding happens before any Lua runs,
99    /// so an overloaded server answers quickly instead of queueing work
100    /// nobody is still waiting for.
101    pub pool_wait_ms: u64,
102    /// How long a client may take to send its complete request headers,
103    /// in milliseconds; the connection is closed past it. `0` disables
104    /// the deadline.
105    pub header_read_ms: u64,
106    /// How long each read of the request body may wait for the next
107    /// bytes, in milliseconds (`408` past it, and the connection is
108    /// closed). A progress bound, not a total-transfer one: a body that
109    /// keeps arriving is fine at any size the byte limits allow; one
110    /// that stalls fails deterministically instead of holding a
111    /// connection slot and a pooled Lua state. `0` disables the bound.
112    pub body_read_ms: u64,
113    /// Maximum number of parts in a `multipart/form-data` body.
114    pub max_form_parts: usize,
115    /// Maximum size of a single non-file form field, in bytes. Fields
116    /// become Lua strings, so this bounds what a request can push into a
117    /// state's heap.
118    pub max_field_bytes: u64,
119    /// Maximum size of a single uploaded file, in bytes. Files stream to
120    /// disk in Rust and never enter the Lua heap, so this is far larger
121    /// than [`max_field_bytes`](Self::max_field_bytes).
122    pub max_file_bytes: u64,
123}
124
125impl Default for LimitsConfig {
126    fn default() -> Self {
127        Self {
128            max_body_bytes: 1024 * 1024, // 1 MiB
129            max_header_bytes: 16 * 1024, // 16 KiB
130            max_uri_bytes: 8 * 1024,     // 8 KiB
131            max_connections: 1024,
132            // Generous by default: long enough that a brief burst queues
133            // rather than sheds, short enough that a saturated server fails
134            // fast instead of accumulating doomed requests.
135            pool_wait_ms: 5_000,
136            // 30 s each: far beyond any honest client or network hiccup,
137            // far short of forever. The header value matches what was a
138            // hardcoded constant before it became configurable.
139            header_read_ms: 30_000,
140            body_read_ms: 30_000,
141            max_form_parts: 64,
142            max_field_bytes: 64 * 1024,       // 64 KiB
143            max_file_bytes: 10 * 1024 * 1024, // 10 MiB
144        }
145    }
146}
147
148/// Graceful-shutdown timing (`[shutdown]` section).
149///
150/// On `SIGTERM`/`SIGINT` the server stops accepting, lets in-flight
151/// requests finish, and only then exits. These bound how long it waits.
152#[derive(Debug, Clone, Deserialize, Serialize)]
153#[serde(default, deny_unknown_fields)]
154pub struct ShutdownConfig {
155    /// Seconds to let ordinary in-flight requests finish.
156    pub grace: u64,
157    /// Extra seconds granted to streaming and SSE bodies, which can
158    /// legitimately outlive a normal request. They are cut at
159    /// `grace + stream_grace`.
160    pub stream_grace: u64,
161    /// Seconds the main listener keeps serving after the signal, with
162    /// readiness already answering 503, so a balancer probing that port
163    /// sees "draining" and moves traffic before the port closes. Unset:
164    /// 5 when the probes share the main listener, else 0 (a separate
165    /// `[health] bind` stays up through the drain, and dev mode stops at
166    /// once).
167    pub readiness_delay: Option<u64>,
168}
169
170impl Default for ShutdownConfig {
171    fn default() -> Self {
172        Self {
173            grace: 30,
174            stream_grace: 5,
175            readiness_delay: None,
176        }
177    }
178}
179
180impl ShutdownConfig {
181    /// Deadline for ordinary in-flight requests.
182    pub fn grace(&self) -> std::time::Duration {
183        std::time::Duration::from_secs(self.grace)
184    }
185
186    /// Total deadline including the extra budget for long-lived bodies.
187    pub fn total_grace(&self) -> std::time::Duration {
188        std::time::Duration::from_secs(self.grace + self.stream_grace)
189    }
190}
191
192/// Cross-origin resource sharing (`[cors]` section).
193///
194/// Enforced in Rust: a preflight never reaches a Lua state, and the policy
195/// is auditable in one place instead of spread across middleware.
196/// Disabled until `origins` is set.
197#[derive(Debug, Clone, Default, Deserialize, Serialize)]
198#[serde(default, deny_unknown_fields)]
199pub struct CorsConfig {
200    /// Allowed origins, or `["*"]` for any. Unset disables CORS entirely.
201    pub origins: Option<Vec<String>>,
202    /// Methods allowed on cross-origin requests.
203    pub methods: Option<Vec<String>>,
204    /// Request headers a preflight may approve.
205    pub headers: Option<Vec<String>>,
206    /// Response headers scripts on other origins may read.
207    pub expose_headers: Option<Vec<String>>,
208    /// Allow credentialed requests (cookies, `Authorization`). Cannot be
209    /// combined with `origins = ["*"]`.
210    pub credentials: bool,
211    /// How long (seconds) a browser may cache a preflight result.
212    pub max_age: Option<u64>,
213}
214
215/// Per-client-IP fixed-window rate limiting (`[rate_limit]` section).
216/// Disabled by default; rejections answer 429 with a `Retry-After` header.
217#[derive(Debug, Clone, Deserialize, Serialize)]
218#[serde(default, deny_unknown_fields)]
219pub struct RateLimitConfig {
220    /// Whether rate limiting is enforced.
221    pub enabled: bool,
222    /// Allowed requests per window and client IP.
223    pub requests: u32,
224    /// Window length in seconds.
225    pub window: u64,
226    /// Key the budget by the **last** `X-Forwarded-For` entry — the
227    /// address the proxy in front appended, i.e. the client it accepted
228    /// the connection from — instead of the peer address. Enable only
229    /// behind a trusted proxy. The last entry is the right one whether
230    /// the proxy overwrites the header or (as nginx, Caddy, Traefik and
231    /// HAProxy do by default) appends to whatever the client sent; the
232    /// first entry is client-written and would hand every request a
233    /// fresh budget. With more than one proxy hop the budget keys by the
234    /// nearest hop's client, not the origin client.
235    pub trust_forwarded_for: bool,
236}
237
238impl Default for RateLimitConfig {
239    fn default() -> Self {
240        Self {
241            enabled: false,
242            requests: 100,
243            window: 60,
244            trust_forwarded_for: false,
245        }
246    }
247}
248
249/// Inbound TLS termination (`[tls]` section), served by rustls over the
250/// `ring` crypto provider.
251///
252/// Off by default, and deliberately not inferred from the presence of a
253/// certificate: turning a port from plaintext to TLS is a decision an
254/// operator makes, not one a stray file makes for them. When it *is* on,
255/// both paths are required — a half-configured `[tls]` fails at startup
256/// rather than at the first connection, where the failure would look like
257/// a network problem.
258#[derive(Debug, Clone, Default, Deserialize, Serialize)]
259#[serde(default, deny_unknown_fields)]
260pub struct TlsConfig {
261    /// Whether the listener speaks TLS.
262    pub enabled: bool,
263    /// PEM file holding the server certificate, leaf first, followed by
264    /// any intermediates a client needs to build the chain.
265    pub cert: Option<PathBuf>,
266    /// PEM file holding the matching private key (PKCS#8, PKCS#1 or
267    /// SEC1). Read at startup and again on each reload (`SIGHUP`), which
268    /// swaps in renewed material only when the pair validates.
269    pub key: Option<PathBuf>,
270    /// Oldest protocol version accepted: `"1.2"` or `"1.3"`. Unset means
271    /// the floor, TLS 1.2, which is what a public endpoint wants;
272    /// `"1.3"` is for a closed set of clients known to speak it.
273    ///
274    /// The floor cannot be lowered. TLS 1.0 and 1.1 are deprecated
275    /// (RFC 8996) and are not settings this server offers under any
276    /// spelling — see [`TLS_MIN_VERSIONS`].
277    pub min_version: Option<String>,
278    /// Deadline for the TLS handshake itself, in milliseconds. Unset
279    /// means `min(header_read_ms, 10s)` — and when `[limits]
280    /// header_read_ms` is `0` (disabled), simply 10 s. `0` here is a
281    /// startup error, never "unbounded": the handshake happens before
282    /// hyper's header machinery exists, so a stalled `ClientHello` holds
283    /// a connection slot the header deadline can never reclaim, and 1024
284    /// of them close the listener. The header read and the handshake are
285    /// different waits on different protocol phases; a streaming
286    /// deployment that relaxes the first says nothing about the second.
287    pub handshake_ms: Option<u64>,
288}
289
290/// Every protocol version `[tls] min_version` may name, weakest first.
291///
292/// `"1.2"` is the floor and the default: TLS 1.0 and 1.1 are deprecated
293/// by RFC 8996, rustls implements neither, and accepting the spelling
294/// would promise a downgrade no build here can — or should — keep. This
295/// list is the whole vocabulary; a name outside it is a startup refusal,
296/// not a silent fallback.
297pub(crate) const TLS_MIN_VERSIONS: [&str; 2] = ["1.2", "1.3"];