Skip to main content

nitr_http/config/
mod.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//! Server configuration (`nitr.toml`), defaults, and environment overrides.
7
8use std::collections::BTreeMap;
9use std::net::SocketAddr;
10use std::path::{Path, PathBuf};
11
12use serde::{Deserialize, Serialize};
13
14use nitr_core::RuntimeOpts;
15use nitr_core::{Error, Result};
16use nitr_std::Builtins;
17
18mod database;
19mod env;
20mod sections;
21mod validate;
22
23pub use database::DatabaseConfig;
24pub use sections::*;
25
26/// Server configuration, typically loaded from a `nitr.toml` file.
27///
28/// Precedence (strongest first): CLI flags / builder setters, `NITR_*`
29/// environment variables (see [`apply_env()`](Self::apply_env)), the TOML
30/// file, and finally the built-in defaults.
31#[derive(Debug, Clone, Deserialize, Serialize)]
32#[serde(default, deny_unknown_fields)]
33pub struct Config {
34    /// Address the server binds to.
35    pub listen: SocketAddr,
36    /// The handler script, loaded once per Lua state at startup and on
37    /// every reload; its routes serve the requests.
38    pub handler_script: PathBuf,
39    /// Lua script executed once at startup; its returned table is passed to
40    /// the handler on every request.
41    pub config_script: Option<PathBuf>,
42    /// SQLite database for the `db` builtin (`[database]` section): the
43    /// file path plus the connection pragmas.
44    pub database: Option<DatabaseConfig>,
45    /// Number of pooled Lua states (the maximum concurrently executing)
46    /// handlers.
47    pub workers: usize,
48    /// Maximum concurrent streaming responses (each holds a pooled state
49    /// for its whole lifetime). Defaults to `workers - 1`, so idle streams
50    /// cannot pin the entire pool; with one worker that is still 1, and
51    /// startup warns that one stream then holds the only state.
52    pub max_streams: Option<usize>,
53    /// Development mode: hot-reload the handler script on change.
54    pub dev_mode: bool,
55    /// Standard library (`nitr.*`) selection (`[std]` section). When the
56    /// feature list is omitted, only the minimal set is enabled; an
57    /// explicit list is strict and fails at startup when a listed feature
58    /// is missing its configuration (e.g. `template` without
59    /// `[templating] dir`).
60    pub std: StdConfig,
61    /// Trust an inbound `X-Request-ID` header (well-formed, <= 64 ASCII
62    /// chars) instead of generating a fresh id. Enable only behind a proxy
63    /// that sets or sanitizes the header.
64    pub trust_request_id: bool,
65    /// Request-size and connection limits (`[limits]` section).
66    pub limits: LimitsConfig,
67    /// Per-client rate limiting (`[rate_limit]` section).
68    pub rate_limit: RateLimitConfig,
69    /// Outbound-request policy for the `fetch` builtin (`[fetch]` section).
70    pub fetch: FetchConfig,
71    /// Graceful-shutdown timing (`[shutdown]` section).
72    pub shutdown: ShutdownConfig,
73    /// Response compression (`[compression]` section).
74    pub compression: CompressionConfig,
75    /// Cross-origin resource sharing (`[cors]` section).
76    pub cors: CorsConfig,
77    /// Headers added to every response (`[headers]` section): the static
78    /// files, the built-in rejections and the SPA page included. A header
79    /// the handler itself set wins.
80    pub headers: BTreeMap<String, String>,
81    /// Inbound TLS termination (`[tls]` section).
82    pub tls: TlsConfig,
83    /// The shared `nitr.cache` (`[cache]` section).
84    pub cache: CacheConfig,
85    /// Static file serving (`[static]` section).
86    #[serde(rename = "static")]
87    pub static_files: StaticConfig,
88    /// Template rendering (`[templating]` section).
89    pub templating: TemplatingConfig,
90    /// Filesystem policy for multipart uploads (`[multipart]` section).
91    pub multipart: MultipartConfig,
92    /// Cookie defaults (`[cookies]` section).
93    pub cookies: CookiesConfig,
94    /// Test runner settings (`[testing]` section).
95    pub testing: TestingConfig,
96    /// Environment access for the `nitr.env` builtin (`[env]` section).
97    pub env: EnvConfig,
98    /// Lua runtime settings.
99    pub lua: LuaConfig,
100    /// Health and readiness endpoints (`[health]` section).
101    pub health: HealthConfig,
102    /// Set by a tool that proves the application without serving it
103    /// (`nitr check`, `nitr test`): a static directory that does not exist
104    /// yet is skipped with a warning rather than refused, because the
105    /// front-end build that fills it runs later. Never read from a file.
106    #[serde(skip)]
107    pub static_dirs_optional: bool,
108    /// The generated OpenAPI document (`[openapi]` section).
109    pub openapi: OpenApiConfig,
110    /// The Swagger UI page (`[swagger]` section).
111    pub swagger: SwaggerConfig,
112    /// Log output (`[log]` section).
113    pub log: LogConfig,
114    /// File the server writes its process id to at startup (and removes at
115    /// exit), so `nitr reload` and scripts can find the process without
116    /// grepping the process table.
117    pub pidfile: Option<PathBuf>,
118}
119
120impl Default for Config {
121    fn default() -> Self {
122        Self {
123            listen: SocketAddr::from(([127, 0, 0, 1], 3000)),
124            handler_script: PathBuf::from("scripts/handler.lua"),
125            config_script: None,
126            database: None,
127            workers: std::thread::available_parallelism().map_or(1, |n| n.get()),
128            max_streams: None,
129            dev_mode: false,
130            std: StdConfig::default(),
131            trust_request_id: false,
132            limits: LimitsConfig::default(),
133            rate_limit: RateLimitConfig::default(),
134            fetch: FetchConfig::default(),
135            shutdown: ShutdownConfig::default(),
136            compression: CompressionConfig::default(),
137            cors: CorsConfig::default(),
138            headers: BTreeMap::new(),
139            tls: TlsConfig::default(),
140            cache: CacheConfig::default(),
141            static_files: StaticConfig::default(),
142            templating: TemplatingConfig::default(),
143            multipart: MultipartConfig::default(),
144            cookies: CookiesConfig::default(),
145            testing: TestingConfig::default(),
146            env: EnvConfig::default(),
147            lua: LuaConfig::default(),
148            health: HealthConfig::default(),
149            static_dirs_optional: false,
150            openapi: OpenApiConfig::default(),
151            swagger: SwaggerConfig::default(),
152            log: LogConfig::default(),
153            pidfile: None,
154        }
155    }
156}
157
158impl Config {
159    /// `[shutdown] readiness_delay`, or its default (see there).
160    pub(crate) fn readiness_delay(&self) -> std::time::Duration {
161        let probes_on_main = self.health.enabled && self.health.bind.is_none();
162        let secs = match self.shutdown.readiness_delay {
163            Some(secs) => secs,
164            None if probes_on_main && !self.dev_mode => 5,
165            None => 0,
166        };
167        std::time::Duration::from_secs(secs)
168    }
169
170    /// `max_streams`, or its default: `workers - 1`, at least 1.
171    pub(crate) fn effective_max_streams(&self) -> usize {
172        self.max_streams
173            .unwrap_or_else(|| self.workers.max(1).saturating_sub(1).max(1))
174    }
175
176    /// Loads the configuration from a TOML file.
177    pub fn from_file(path: &Path) -> Result<Self> {
178        let data = std::fs::read_to_string(path).map_err(|err| {
179            Error::Config(format!(
180                "failed to read the config file {}: {err}",
181                path.display()
182            ))
183        })?;
184        // Deserialization alone would report the removed spellings as mere
185        // unknown/invalid fields; recognize them first so the error says
186        // what to write instead.
187        if let Ok(doc) = toml::from_str::<toml::Value>(&data) {
188            check_moved_keys(&doc)?;
189        }
190        toml::from_str(&data).map_err(|err| {
191            Error::Config(format!(
192                "failed to parse the config file {}: {err}",
193                path.display()
194            ))
195        })
196    }
197
198    /// The read policy handed to the `nitr.env` builtin.
199    pub fn env_options(&self) -> nitr_std::EnvOptions {
200        nitr_std::EnvOptions {
201            allow: self.env.allow.clone(),
202            mode: if self.dev_mode {
203                nitr_std::RunMode::Dev
204            } else {
205                nitr_std::RunMode::Run
206            },
207        }
208    }
209
210    /// Why a cookie built without `Secure` deserves a warning, for the
211    /// first such cookie to log. `"auto"` cannot see a proxy terminating
212    /// TLS in front of a plaintext bind, the most common deployment, so
213    /// it says so once a cookie actually ships that way; `dev_mode` and an
214    /// explicit `"never"` are the operator's answer and stay silent.
215    pub fn cookie_insecure_warning(&self) -> Option<String> {
216        let auto_insecure = self.cookies.secure == CookieSecure::Auto && !self.tls.enabled;
217        (auto_insecure && !self.dev_mode).then(|| {
218            "a cookie was sent without the `Secure` attribute: [tls] enabled = false, and \
219             [cookies] secure = \"auto\" follows it. If TLS is terminated by a proxy in front \
220             of this process, set [cookies] secure = \"always\"; nothing here can detect that \
221             proxy."
222                .into()
223        })
224    }
225
226    /// Limits for the shared `nitr.cache`.
227    pub fn cache_options(&self) -> nitr_std::CacheOptions {
228        nitr_std::CacheOptions {
229            max_entries: self.cache.max_entries.max(1),
230            max_bytes: self.cache.max_bytes,
231            default_ttl: self.cache.default_ttl,
232        }
233    }
234
235    /// Resolves the configured `[std] features` list into [`Builtins`] flags.
236    ///
237    /// With no explicit list, the minimal default set
238    /// ([`Builtins::minimal()`]: `json`, `http`, `log`, `time`,
239    /// `validate`, `base64`, `path`, `url`) is enabled to keep the
240    /// standard library lightweight. An explicit list is strict:
241    /// unknown names or a listed feature without its required setting fail
242    /// here.
243    pub fn builtins(&self) -> Result<Builtins> {
244        let Some(names) = &self.std.features else {
245            return Ok(Builtins::minimal());
246        };
247        let mut builtins = Builtins::empty();
248        for name in names {
249            let builtin = Builtins::from_config_name(name)
250                .ok_or_else(|| Error::Config(format!("unknown std feature `{name}`")))?;
251            if builtin == Builtins::TEMPLATE && self.templating.dir.is_none() {
252                return Err(Error::Config(
253                    "std feature `template` is enabled but `[templating] dir` is not set".into(),
254                ));
255            }
256            if builtin == Builtins::DATABASE && self.database.is_none() {
257                return Err(Error::Config(
258                    "std feature `db` is enabled but `database` is not set".into(),
259                ));
260            }
261            builtins |= builtin;
262        }
263        Ok(builtins)
264    }
265
266    /// The directory `require` is pinned to: the one containing the
267    /// handler script.
268    ///
269    /// A bare `handler_script = "app.lua"` has `parent()` of `Some("")`,
270    /// which names nothing — the script is in the working directory, so
271    /// that is what `require` gets. Every caller must derive the root
272    /// *here* rather than re-deriving it: `validate_paths` refuses an
273    /// upload directory inside this root, and a second copy of the
274    /// expression that disagreed with this one is exactly how that
275    /// refusal was once skipped for a bare filename while `require` was
276    /// still pinned to the working directory.
277    pub(crate) fn package_dir(&self) -> &Path {
278        self.handler_script
279            .parent()
280            .filter(|p| !p.as_os_str().is_empty())
281            .unwrap_or_else(|| Path::new("."))
282    }
283
284    /// Builds the [`RuntimeOpts`] derived from this configuration.
285    pub fn runtime_opts(&self) -> Result<RuntimeOpts> {
286        // Lua module loading (`require`) is confined to the directory
287        // containing the handler script.
288        let package_dir = self.package_dir().to_path_buf();
289        Ok(RuntimeOpts {
290            libs: self.lua.parse_stdlib()?,
291            memory_limit: self.lua.memory_limit,
292            dev_mode: self.dev_mode,
293            exec_timeout: match self.lua.exec_timeout_ms {
294                0 => None,
295                ms => Some(std::time::Duration::from_millis(ms)),
296            },
297            package_dir: Some(package_dir),
298            // Server states resolve `require` against the application
299            // alone; only `nitr test` adds a second root, and only to its
300            // own test states.
301            extra_package_dirs: Vec::new(),
302        })
303    }
304}
305
306/// Rejects superseded spellings of moved settings with an error that says
307/// what to write instead — `deny_unknown_fields` alone would report them
308/// as a bare unknown key or type mismatch.
309fn check_moved_keys(doc: &toml::Value) -> Result {
310    let Some(table) = doc.as_table() else {
311        return Ok(());
312    };
313    if table.get("database").is_some_and(toml::Value::is_str) {
314        return Err(Error::Config(
315            "`database` is now a table: replace `database = \"app.db\"` with a \
316             `[database]` section containing `path = \"app.db\"`"
317                .into(),
318        ));
319    }
320    if table.contains_key("tests_dir") {
321        return Err(Error::Config(
322            "`tests_dir` moved: replace it with a `[testing]` section \
323             containing `dir = \"...\"`"
324                .into(),
325        ));
326    }
327    if table.contains_key("templates_dir") {
328        return Err(Error::Config(
329            "`templates_dir` moved: replace it with a `[templating]` section \
330             containing `dir = \"...\"`"
331                .into(),
332        ));
333    }
334    Ok(())
335}
336
337#[cfg(test)]
338mod tests;