Skip to main content

nitr_std/
lib.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//! The built-in `nitr.*` standard library for Nitr and its registration.
7//!
8//! Every builtin mounts as a field of the global `nitr` namespace table
9//! (`nitr.json`, `nitr.fetch`, `nitr.db`, …) — Nitr registers no other
10//! globals, so scripts always read `nitr.*` and nothing is intermixed with
11//! the Lua standard library.
12
13// Lint policy comes from `[workspace.lints]` in the root Cargo.toml.
14// `unwrap_used`/`expect_used` are denied here (not in the workspace table,
15// which would also hit test and bench targets); unit tests are exempt, and
16// the few documented-invariant `expect()`s carry targeted allows.
17#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]
18#![cfg_attr(docsrs, feature(doc_cfg))]
19
20use std::path::PathBuf;
21
22use nitr_core::Result;
23
24pub(crate) mod base64;
25pub mod cache;
26pub(crate) mod config;
27#[cfg(feature = "crypto")]
28pub(crate) mod crypto;
29pub(crate) mod csrf;
30#[cfg(feature = "db")]
31pub(crate) mod db;
32pub(crate) mod env;
33#[cfg(feature = "fetch")]
34pub(crate) mod fetch;
35pub(crate) mod http;
36pub(crate) mod json;
37pub(crate) mod log;
38pub(crate) mod path;
39pub(crate) mod session;
40#[cfg(feature = "template")]
41pub(crate) mod template;
42pub(crate) mod time;
43pub(crate) mod url;
44pub(crate) mod utils;
45pub(crate) mod validate;
46
47pub use cache::{Cache, CacheOptions};
48// The configuration types are always available: `nitr.toml` has one shape
49// regardless of which builtins this build compiled in.
50pub use config::{EnvOptions, FetchOptions, SqlitePragmas};
51pub use http::{RequestCookies, ResponseCookies, best_match};
52pub use utils::error_lua_value;
53
54/// Internal functions exposed for the fuzz targets in `fuzz/` only.
55/// Not part of the public API; no stability promise applies here.
56#[doc(hidden)]
57pub mod fuzzing {
58    pub use crate::http::{sign, verify};
59    pub use crate::json::create_json_fn;
60    pub use crate::path::{
61        basename, dirname, is_absolute, is_windows_style, join, normalize, split_root,
62    };
63}
64
65#[cfg(feature = "db")]
66pub use db::migrate;
67#[cfg(feature = "db")]
68pub use db::pragmas::open as db_open;
69#[cfg(feature = "fetch")]
70pub use fetch::{reset_outbound_budget, set_trace_context};
71
72/// Resets the per-request outbound budget. A no-op without the `fetch`
73/// feature, so the server can call it unconditionally.
74#[cfg(not(feature = "fetch"))]
75pub fn reset_outbound_budget(_lua: &mlua::Lua) {}
76
77/// Records the inbound request id for `traceparent` propagation. A no-op
78/// without the `fetch` feature.
79#[cfg(not(feature = "fetch"))]
80pub fn set_trace_context(_lua: &mlua::Lua, _request_id: &str) {}
81
82bitflags::bitflags! {
83    /// Built-in `nitr.*` standard library modules that can be exposed to
84    /// Lua scripts.
85    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
86    pub struct Builtins: u32 {
87        /// `nitr.dbg(value)` debug-print function.
88        const DEBUG = 1;
89        /// `nitr.fetch(method, url, opts?)` HTTP client plus
90        /// `nitr.await_all` for concurrent requests.
91        const FETCH = 1 << 1;
92        /// `nitr.template:render(name, data?)` template engine (minijinja).
93        const TEMPLATE = 1 << 2;
94        /// `nitr.json` JSON codec (`:encode`/`:decode`) and, called as a
95        /// function, the JSON response helper.
96        const JSON = 1 << 3;
97        /// `nitr.db:execute/query/query_row/query_one/transaction` SQLite
98        /// driver.
99        const DATABASE = 1 << 4;
100        /// HTTP ergonomics: the `nitr.text`/`html`/`redirect`/`status`/
101        /// `negotiate`/`sse` response helpers and `nitr.error`.
102        const HTTP = 1 << 5;
103        /// `nitr.log.debug/info/warn/error(msg, fields?)` structured logging.
104        const LOG = 1 << 6;
105        /// `nitr.crypto` primitives (hashing, HMAC, passwords, AEAD, JWT)
106        /// and the `nitr.auth` header parsers.
107        const CRYPTO = 1 << 7;
108        /// `nitr.cache`: the bounded cache shared by every pooled state.
109        const CACHE = 1 << 8;
110        /// `nitr.time`: safe clocks and time formatting/parsing, so
111        /// scripts never need the `os` Lua standard library for a date.
112        const TIME = 1 << 9;
113        /// `nitr.validate`: declarative request validation, compiled once
114        /// and checked in Rust.
115        const VALIDATE = 1 << 10;
116        /// `nitr.base64`: base64 encoding/decoding (standard and
117        /// URL-safe alphabets).
118        const BASE64 = 1 << 11;
119        /// `nitr.path`: lexical `/`-path manipulation — pure text, no
120        /// filesystem access.
121        const PATH = 1 << 12;
122        /// `nitr.url`: percent-encoding, query strings, and a lexical
123        /// URL splitter.
124        const URL = 1 << 13;
125        /// `nitr.env`: read-only environment variable access
126        /// (`get`/`has`/`number`/`bool`), filtered by `[env] allow` and
127        /// never exposing `NITR_*` internals.
128        const ENV = 1 << 14;
129    }
130}
131
132impl Builtins {
133    /// The minimal default feature set enabled when the configuration has
134    /// no explicit `[std] features` list: the JSON codec, the HTTP response
135    /// helpers, structured logging, safe time, and validation. These need
136    /// no external resources (templates directory, database file, outbound
137    /// network) and keep the standard library lightweight; everything else
138    /// is opt-in. `time` and `validate` are here because they replace the
139    /// dangerous alternatives (`os.date`, hand-rolled input checks) — a
140    /// default that omitted them would push scripts toward widening the
141    /// sandbox instead.
142    pub const fn minimal() -> Self {
143        Self::JSON
144            .union(Self::HTTP)
145            .union(Self::LOG)
146            .union(Self::TIME)
147            .union(Self::VALIDATE)
148            .union(Self::BASE64)
149            .union(Self::PATH)
150            .union(Self::URL)
151    }
152
153    /// The field name a builtin mounts under on the `nitr` namespace table.
154    ///
155    /// Returns `None` for combined flags and for builtins that register
156    /// several fields ([`HTTP`](Self::HTTP) and [`CRYPTO`](Self::CRYPTO)).
157    pub fn nitr_name(self) -> Option<&'static str> {
158        match self {
159            Builtins::DEBUG => Some("dbg"),
160            Builtins::FETCH => Some("fetch"),
161            Builtins::TEMPLATE => Some("template"),
162            Builtins::JSON => Some("json"),
163            Builtins::DATABASE => Some("db"),
164            Builtins::LOG => Some("log"),
165            Builtins::TIME => Some("time"),
166            Builtins::VALIDATE => Some("validate"),
167            Builtins::BASE64 => Some("base64"),
168            Builtins::PATH => Some("path"),
169            Builtins::URL => Some("url"),
170            Builtins::ENV => Some("env"),
171            _ => None,
172        }
173    }
174
175    /// Resolves a configuration name (e.g. `"dbg"`, `"fetch"`, `"db"`) into
176    /// its builtin flag.
177    pub fn from_config_name(name: &str) -> Option<Self> {
178        match name {
179            "dbg" => Some(Builtins::DEBUG),
180            "fetch" => Some(Builtins::FETCH),
181            "template" => Some(Builtins::TEMPLATE),
182            "json" => Some(Builtins::JSON),
183            "db" => Some(Builtins::DATABASE),
184            "http" => Some(Builtins::HTTP),
185            "log" => Some(Builtins::LOG),
186            "crypto" => Some(Builtins::CRYPTO),
187            "cache" => Some(Builtins::CACHE),
188            "time" => Some(Builtins::TIME),
189            "validate" => Some(Builtins::VALIDATE),
190            "base64" => Some(Builtins::BASE64),
191            "path" => Some(Builtins::PATH),
192            "url" => Some(Builtins::URL),
193            "env" => Some(Builtins::ENV),
194            _ => None,
195        }
196    }
197}
198
199/// External resources required by some builtins: `template` needs a
200/// templates directory and `db` a SQLite database file.
201#[derive(Debug, Clone, Default)]
202pub struct BuiltinsEnv {
203    /// Directory the `template` builtin loads templates from.
204    pub templates_dir: Option<PathBuf>,
205    /// SQLite database file the `db` builtin connects to.
206    pub database: Option<PathBuf>,
207    /// Connection pragmas applied to that database.
208    pub sqlite: SqlitePragmas,
209    /// The shared cache backing `nitr.cache`. Built once by the server and
210    /// handed to every state, so it survives a pool rebuild — a cache that
211    /// empties on every reload is a cache that never warms.
212    pub cache: Option<Cache>,
213    /// Outbound-request policy for the `fetch` builtin.
214    pub fetch: FetchOptions,
215    /// Read policy for the `nitr.env` builtin.
216    pub env: EnvOptions,
217}
218
219/// Registers the selected builtins as fields of the global `nitr`
220/// namespace table (`nitr.dbg`, `nitr.fetch`, `nitr.json`, `nitr.db`, …).
221///
222/// Builtins that need a setting from the [`BuiltinsEnv`] (`template` needs
223/// `templates_dir`, `db` needs `database`) are skipped with a warning when
224/// that setting is absent; callers that take an explicit builtins list
225/// should reject such combinations upfront.
226/// Only reachable when at least one gated builtin was left out.
227#[cfg(not(all(
228    feature = "crypto",
229    feature = "db",
230    feature = "fetch",
231    feature = "template"
232)))]
233fn not_compiled_in(name: &str) -> nitr_core::Error {
234    nitr_core::Error::Config(format!(
235        "the `{name}` builtin is configured but was not compiled into this \
236         binary: rebuild with the `{name}` Cargo feature (or `all`), or drop \
237         it from `[std] features`"
238    ))
239}
240
241/// Registers the selected builtins on the global `nitr` namespace table,
242/// using the [`BuiltinsEnv`] for the resources some of them need.
243pub fn register_builtins(lua: &mlua::Lua, builtins: Builtins, env: &BuiltinsEnv) -> Result {
244    let nitr = nitr_core::nitr_table(lua)?;
245    for builtin in builtins.iter() {
246        match builtin {
247            Builtins::DEBUG => nitr.set("dbg", utils::create_debug_fn(lua)?)?,
248            // Also registers `nitr.await_all` for concurrent requests.
249            #[cfg(feature = "fetch")]
250            Builtins::FETCH => {
251                let opts = std::sync::Arc::new(env.fetch.clone());
252                nitr.set("fetch", fetch::create_fetch_fn(lua, opts.clone())?)?;
253                nitr.set("await_all", fetch::create_await_all_fn(lua, opts)?)?;
254            }
255            #[cfg(not(feature = "fetch"))]
256            Builtins::FETCH => return Err(not_compiled_in("fetch")),
257
258            #[cfg(feature = "template")]
259            Builtins::TEMPLATE => match &env.templates_dir {
260                Some(dir) => nitr.set("template", template::create_template_fn(lua, dir)?)?,
261                None => {
262                    tracing::warn!(
263                        "skipping builtin `template`: `[templating] dir` is not configured"
264                    );
265                }
266            },
267            #[cfg(not(feature = "template"))]
268            Builtins::TEMPLATE => return Err(not_compiled_in("template")),
269            Builtins::JSON => nitr.set("json", json::create_json_fn(lua)?)?,
270            // Registers the response helpers (`nitr.text`, `nitr.html`,
271            // `nitr.redirect`, `nitr.status`, `nitr.negotiate`, `nitr.sse`),
272            // `nitr.error`, and the signed-cookie ergonomics built on them:
273            // `nitr.csrf` and `nitr.session`.
274            Builtins::HTTP => {
275                http::register(lua, &nitr)?;
276                nitr.set("csrf", csrf::create_csrf_table(lua)?)?;
277                nitr.set("session", session::create_session_fn(lua)?)?;
278            }
279            Builtins::LOG => nitr.set("log", log::create_log_table(lua)?)?,
280            Builtins::TIME => nitr.set("time", time::create_time_table(lua)?)?,
281            Builtins::VALIDATE => nitr.set("validate", validate::create_validate_table(lua)?)?,
282            Builtins::BASE64 => nitr.set("base64", base64::create_base64_table(lua)?)?,
283            Builtins::PATH => nitr.set("path", path::create_path_table(lua)?)?,
284            Builtins::URL => nitr.set("url", url::create_url_table(lua)?)?,
285            Builtins::ENV => nitr.set("env", env::create_env_table(lua, &env.env)?)?,
286            // Registers both `nitr.crypto` and `nitr.auth`.
287            #[cfg(feature = "crypto")]
288            Builtins::CRYPTO => {
289                nitr.set("crypto", crypto::create_crypto_table(lua)?)?;
290                nitr.set("auth", crypto::create_auth_table(lua)?)?;
291            }
292            #[cfg(not(feature = "crypto"))]
293            Builtins::CRYPTO => return Err(not_compiled_in("crypto")),
294
295            #[cfg(feature = "db")]
296            Builtins::DATABASE => match &env.database {
297                Some(path) => nitr.set("db", db::create_database_fn(lua, path, &env.sqlite)?)?,
298                None => {
299                    tracing::warn!("skipping builtin `db`: `database` is not configured");
300                }
301            },
302            #[cfg(not(feature = "db"))]
303            Builtins::DATABASE => return Err(not_compiled_in("db")),
304            Builtins::CACHE => match &env.cache {
305                Some(cache) => nitr.set("cache", cache::create_cache(lua, cache.clone())?)?,
306                None => {
307                    tracing::warn!("skipping builtin `cache`: no shared cache was provided");
308                }
309            },
310            _ => continue,
311        };
312    }
313    // Always registered, independent of the configured builtins: turning a
314    // caught error into its structured form is part of the error model,
315    // not an optional capability.
316    nitr.set("errinfo", utils::create_errinfo_fn(lua)?)?;
317    Ok(())
318}
319
320#[cfg(test)]
321mod tests {
322    use super::Builtins;
323
324    #[test]
325    fn config_names_round_trip() {
326        for (name, flag) in [
327            ("dbg", Builtins::DEBUG),
328            ("fetch", Builtins::FETCH),
329            ("template", Builtins::TEMPLATE),
330            ("json", Builtins::JSON),
331            ("db", Builtins::DATABASE),
332            ("http", Builtins::HTTP),
333            ("log", Builtins::LOG),
334            ("crypto", Builtins::CRYPTO),
335            ("time", Builtins::TIME),
336            ("validate", Builtins::VALIDATE),
337            ("base64", Builtins::BASE64),
338            ("path", Builtins::PATH),
339            ("url", Builtins::URL),
340            ("env", Builtins::ENV),
341        ] {
342            assert_eq!(Builtins::from_config_name(name), Some(flag));
343        }
344        assert_eq!(Builtins::from_config_name("nope"), None);
345        // Combined flags and multi-field builtins have no single name.
346        assert_eq!((Builtins::DEBUG | Builtins::JSON).nitr_name(), None);
347        assert_eq!(Builtins::HTTP.nitr_name(), None);
348        assert_eq!(Builtins::DATABASE.nitr_name(), Some("db"));
349    }
350}