Skip to main content

nitr_http/config/sections/
features.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 configuring builtin features: `[fetch]`, `[static]`,
7//! `[templating]`, `[cookies]`, `[multipart]`, `[cache]`, `[compression]`.
8
9use std::path::PathBuf;
10
11use serde::{Deserialize, Serialize};
12
13/// Outbound-request policy for the `fetch` builtin (`[fetch]` section).
14/// By default, requests to loopback/private/link-local addresses are
15/// refused (SSRF protection) and every redirect hop is re-checked.
16#[derive(Debug, Clone, Deserialize, Serialize)]
17#[serde(default, deny_unknown_fields)]
18pub struct FetchConfig {
19    /// When set, only these exact host names may be fetched.
20    pub allowed_hosts: Option<Vec<String>>,
21    /// Allow requests to private/loopback/link-local addresses.
22    pub allow_private_networks: bool,
23    /// Host names that may resolve to a private address while
24    /// `allow_private_networks` stays off: the service next door, named,
25    /// rather than every address on the network.
26    pub private_hosts: Vec<String>,
27    /// Maximum response body accumulated by `resp:text()`/`resp:json()`.
28    pub max_response_bytes: u64,
29    /// Maximum concurrent requests per `await_all(...)` call.
30    pub max_concurrent: usize,
31    /// Maximum outbound requests one inbound request may make in total.
32    /// `max_concurrent` bounds a single `await_all`; this bounds the whole
33    /// handler, including a loop issuing calls one after another. `0`
34    /// removes the cap.
35    pub max_per_request: u32,
36    /// Seconds to wait for a TCP/TLS connection to an upstream.
37    pub connect_timeout: f64,
38    /// Default total budget per outbound request, in seconds. A per-call
39    /// `timeout` option overrides it.
40    pub timeout: f64,
41    /// Idle connections kept per upstream host.
42    pub pool_max_idle_per_host: usize,
43    /// Maximum retry attempts a call may ask for. Retries are opt-in per
44    /// call and only ever applied to idempotent methods.
45    pub max_retries: u32,
46    /// Proxy URL for outbound requests. Unset reads the conventional
47    /// `HTTPS_PROXY`/`HTTP_PROXY`/`ALL_PROXY` environment variables.
48    pub proxy: Option<String>,
49    /// Ignore the proxy environment variables entirely.
50    pub no_proxy: bool,
51    /// Forward a W3C `traceparent` header on outbound calls, derived from
52    /// the inbound request id, so a request crossing services can be
53    /// correlated. Pass-through only: this is not a tracing SDK.
54    pub propagate_trace_context: bool,
55}
56
57impl Default for FetchConfig {
58    fn default() -> Self {
59        let defaults = nitr_std::FetchOptions::default();
60        Self {
61            allowed_hosts: defaults.allowed_hosts,
62            allow_private_networks: defaults.allow_private_networks,
63            private_hosts: defaults.private_hosts,
64            max_response_bytes: defaults.max_response_bytes,
65            max_concurrent: defaults.max_concurrent,
66            max_per_request: defaults.max_per_request,
67            connect_timeout: defaults.connect_timeout.as_secs_f64(),
68            timeout: defaults.timeout.as_secs_f64(),
69            pool_max_idle_per_host: defaults.pool_max_idle_per_host,
70            max_retries: defaults.max_retries,
71            proxy: None,
72            no_proxy: false,
73            propagate_trace_context: false,
74        }
75    }
76}
77
78impl FetchConfig {
79    /// The runtime policy handed to the `fetch` builtin.
80    pub fn options(&self) -> nitr_std::FetchOptions {
81        nitr_std::FetchOptions {
82            allowed_hosts: self.allowed_hosts.clone(),
83            allow_private_networks: self.allow_private_networks,
84            private_hosts: self.private_hosts.clone(),
85            max_response_bytes: self.max_response_bytes,
86            max_concurrent: self.max_concurrent.max(1),
87            max_per_request: self.max_per_request,
88            connect_timeout: std::time::Duration::from_secs_f64(self.connect_timeout.max(0.1)),
89            timeout: std::time::Duration::from_secs_f64(self.timeout.max(0.1)),
90            pool_max_idle_per_host: self.pool_max_idle_per_host,
91            max_retries: self.max_retries,
92            proxy: self.proxy.clone(),
93            no_proxy: self.no_proxy,
94            propagate_trace_context: self.propagate_trace_context,
95        }
96    }
97}
98
99/// Static file serving (`[static]` section): a `GET` or `HEAD` under
100/// `mount` that no route serves with that method is answered from `dir`
101/// entirely in Rust, without a Lua state. Scripts can add further mounts
102/// with `app:static(mount, dir, opts?)`.
103#[derive(Debug, Clone, Default, Deserialize, Serialize)]
104#[serde(default, deny_unknown_fields)]
105pub struct StaticConfig {
106    /// Directory served as static files; unset disables the section.
107    pub dir: Option<PathBuf>,
108    /// URL prefix the directory is mounted at (default `/`).
109    pub mount: Option<String>,
110    /// Serve `index.html` for unknown paths (single-page applications).
111    pub spa: bool,
112    /// `Cache-Control` header value for served files.
113    pub cache_control: Option<String>,
114    /// Serve files and directories whose name starts with `.` (default
115    /// `false`). `.well-known/` is served regardless.
116    pub dotfiles: bool,
117}
118
119/// Template rendering (`[templating]` section) for the `template`
120/// builtin (`nitr.template`).
121#[derive(Debug, Clone, Default, Deserialize, Serialize)]
122#[serde(default, deny_unknown_fields)]
123pub struct TemplatingConfig {
124    /// Directory `nitr.template` loads templates from. Unset leaves the
125    /// builtin unavailable: there is no sensible default location to
126    /// guess, and silently rendering from the wrong directory is worse
127    /// than saying the builtin is not configured.
128    pub dir: Option<PathBuf>,
129}
130
131/// When cookies Nitr builds carry the `Secure` attribute
132/// (`[cookies] secure`).
133///
134/// Tri-state rather than a bool because the most common Nitr deployment —
135/// a loopback bind behind a terminating proxy — needs `Secure` cookies
136/// while `[tls] enabled = false` is the correct setting for this process.
137/// A bool cannot express that without reading as a contradiction.
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
139#[serde(rename_all = "lowercase")]
140pub enum CookieSecure {
141    /// `Secure` when `[tls] enabled = true`. The first cookie built
142    /// without `Secure` logs a warning, since this cannot see a proxy in
143    /// front.
144    #[default]
145    Auto,
146    /// Always `Secure`: TLS is terminated in front of this process.
147    Always,
148    /// Never `Secure`: plain-HTTP development.
149    Never,
150}
151
152impl std::str::FromStr for CookieSecure {
153    type Err = String;
154
155    fn from_str(s: &str) -> Result<Self, Self::Err> {
156        match s {
157            "auto" => Ok(Self::Auto),
158            "always" => Ok(Self::Always),
159            "never" => Ok(Self::Never),
160            other => Err(format!(
161                "`{other}` is not a cookie policy: expected \"auto\", \"always\" or \"never\""
162            )),
163        }
164    }
165}
166
167impl CookieSecure {
168    /// Resolves the policy against whether this process terminates TLS.
169    pub fn resolve(self, tls_enabled: bool) -> bool {
170        match self {
171            Self::Auto => tls_enabled,
172            Self::Always => true,
173            Self::Never => false,
174        }
175    }
176}
177
178/// Cookie defaults (`[cookies]` section).
179#[derive(Debug, Clone, Default, Deserialize, Serialize)]
180#[serde(default, deny_unknown_fields)]
181pub struct CookiesConfig {
182    /// Default `Secure` attribute for cookies Nitr builds — the session
183    /// and CSRF cookies, and anything through `res.cookies:set` /
184    /// `:set_signed` — when the caller's own options table does not set
185    /// `secure`. An explicit `secure` from Lua always wins, in both
186    /// directions.
187    ///
188    /// This reaches only cookies Nitr *builds*. A handler that writes the
189    /// header itself (`headers = { ["Set-Cookie"] = "a=1" }`) is converted
190    /// straight through and never passes the serializer, so that cookie's
191    /// attributes are the script's own responsibility.
192    ///
193    /// Deliberately not forced the way `HttpOnly` is: a `Secure` cookie
194    /// sent over plain `http` is dropped by the browser without a word, so
195    /// forcing it would break local development with a failure mode far
196    /// worse than a startup line.
197    pub secure: CookieSecure,
198}
199
200/// Filesystem policy for multipart uploads (`[multipart]` section).
201///
202/// The byte caps stay in [`LimitsConfig`] with every other byte cap; a
203/// directory belongs beside `[static] dir` and `[templating] dir`.
204///
205/// Parsed in every build, including one without the `multipart` feature —
206/// the same reason `FormLimits` carries its values there. A configuration
207/// file that stops being readable depending on how the binary was compiled
208/// is not portable.
209#[derive(Debug, Clone, Default, Deserialize, Serialize)]
210#[serde(default, deny_unknown_fields)]
211pub struct MultipartConfig {
212    /// Root directory that every `part:save(path)` resolves inside.
213    ///
214    /// Unset leaves `part:save` unavailable, the same call `[templating]
215    /// dir` makes: there is no safe directory to guess, and an upload
216    /// written somewhere nobody chose is worse than a startup error.
217    /// Relative paths resolve against the working directory. Must exist
218    /// and be writable at startup.
219    ///
220    /// Paths handed to `part:save` are relative to this directory;
221    /// absolute paths and anything climbing out with `..` are refused
222    /// rather than re-rooted, so the on-disk location always follows from
223    /// the source.
224    pub upload_dir: Option<PathBuf>,
225}
226
227/// The shared `nitr.cache` (`[cache]` section).
228///
229/// Bounded and owned by Rust, so it is shared *data* rather than shared
230/// *state*: entries are serialized on the way in, no Lua value crosses
231/// between states, and the memory cannot grow past these limits.
232#[derive(Debug, Clone, Deserialize, Serialize)]
233#[serde(default, deny_unknown_fields)]
234pub struct CacheConfig {
235    /// Maximum number of live entries; the least recently used is evicted
236    /// past this.
237    pub max_entries: usize,
238    /// Maximum total size of the stored values, in bytes.
239    pub max_bytes: u64,
240    /// Seconds an entry lives when `set` does not say. `0` means no
241    /// expiry, leaving eviction entirely to the size bounds.
242    pub default_ttl: u64,
243}
244
245impl Default for CacheConfig {
246    fn default() -> Self {
247        Self {
248            max_entries: 10_000,
249            max_bytes: 32 * 1024 * 1024, // 32 MiB
250            default_ttl: 300,
251        }
252    }
253}
254
255/// Response compression (`[compression]` section).
256///
257/// Off by default: compression turns a CPU-cheap server into a
258/// CPU-spending one, and that should be a decision, not a surprise. One
259/// line enables it. Precompressed sidecars (`app.js.br` next to `app.js`)
260/// are served regardless of this section — they cost nothing at runtime.
261#[derive(Debug, Clone, Deserialize, Serialize)]
262#[serde(default, deny_unknown_fields)]
263pub struct CompressionConfig {
264    /// Whether responses are compressed on the fly.
265    pub enabled: bool,
266    /// Algorithms offered, best first. Valid names: `"br"`, `"gzip"`.
267    pub algorithms: Vec<String>,
268    /// Responses smaller than this are sent uncompressed: below roughly a
269    /// packet, compression costs more than it saves.
270    pub min_size: u64,
271    /// Content types to compress. A trailing `*` matches a prefix, so
272    /// `"text/*"` covers every text subtype. Already-compressed types
273    /// (images, video, archives) are skipped even when listed.
274    pub types: Vec<String>,
275}
276
277impl Default for CompressionConfig {
278    fn default() -> Self {
279        Self {
280            enabled: false,
281            algorithms: vec!["br".into(), "gzip".into()],
282            min_size: 1024,
283            types: [
284                "text/*",
285                "application/json",
286                "application/javascript",
287                "application/xml",
288                "image/svg+xml",
289            ]
290            .map(String::from)
291            .to_vec(),
292        }
293    }
294}