nitr-std 0.0.0-beta.7

The built-in `nitr.*` standard library for Nitr: dbg, fetch, template, json, http, log, crypto, and the SQLite driver.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
// SPDX-License-Identifier: MIT OR Apache-2.0
// This file is part of Nitr.
// See https://nitrweb.com/ for more information
// Copyright (C) 2024-present Jose Quintana <joseluisq.net>

//! `nitr.env`: read-only access to environment variables.
//!
//! Opt-in and deliberately narrow: getters only, no setter, and no way to
//! enumerate the environment — a script can ask for a name it knows, never
//! discover what else is there. `NITR_*` variables are hidden
//! unconditionally (they configure the server, not the application), and
//! the operator can narrow the readable set further with `[env] allow`.
//!
//! An empty value reads as unset everywhere: a Compose file or a unit file
//! passes an optional variable through as `""`, and `NITR_*` already
//! treats that as absent.

use mlua::{Lua, Table, Value};

use crate::config::{EnvOptions, RunMode};

/// The shortest secret `nitr.env.secret` accepts without a `min_len`: the
/// session and CSRF keys need 16 bytes, and 32 leaves room for a hex or
/// base64 spelling of that.
const DEFAULT_SECRET_MIN_LEN: usize = 32;

/// Builds the `nitr.env` table.
pub(crate) fn create_env_table(lua: &Lua, opts: &EnvOptions) -> mlua::Result<Table> {
    let env = lua.create_table()?;

    let policy = opts.clone();
    env.set(
        "get",
        lua.create_function(move |lua, (name, default): (String, Option<Value>)| {
            match read(lua, &policy, &name) {
                Some(v) => Ok(Value::String(lua.create_string(&v)?)),
                None => Ok(default.unwrap_or(Value::Nil)),
            }
        })?,
    )?;

    let policy = opts.clone();
    env.set(
        "has",
        // Existence without the value; a name the policy hides reports
        // `false` rather than leaking that it is set.
        lua.create_function(move |lua, name: String| Ok(read(lua, &policy, &name).is_some()))?,
    )?;

    let policy = opts.clone();
    env.set(
        "number",
        lua.create_function(move |lua, (name, default): (String, Option<Value>)| {
            let parsed = read(lua, &policy, &name)
                .and_then(|v| v.trim().parse::<f64>().ok())
                .filter(|n| n.is_finite());
            match parsed {
                Some(n) => Ok(Value::Number(n)),
                None => Ok(default.unwrap_or(Value::Nil)),
            }
        })?,
    )?;

    let policy = opts.clone();
    env.set(
        "bool",
        lua.create_function(move |lua, (name, default): (String, Option<Value>)| {
            match read(lua, &policy, &name).as_deref().and_then(parse_bool) {
                Some(b) => Ok(Value::Boolean(b)),
                None => Ok(default.unwrap_or(Value::Nil)),
            }
        })?,
    )?;

    let policy = opts.clone();
    env.set(
        "secret",
        lua.create_function(move |lua, (name, opts): (String, Option<Table>)| {
            let (min_len, dev) = match opts {
                Some(opts) => (
                    opts.get::<Option<usize>>("min_len")?,
                    opts.get::<Option<String>>("dev")?,
                ),
                None => (None, None),
            };
            let min_len = min_len.unwrap_or(DEFAULT_SECRET_MIN_LEN);
            let value = match read(lua, &policy, &name) {
                Some(value) => value,
                // The fallback is for a laptop, never for a service: under
                // `run` a missing secret stays an error, or a deployment
                // that forgot the variable would sign with a known key.
                None if run_mode(lua, &policy) != RunMode::Run => match dev {
                    Some(fallback) => fallback,
                    None => return Err(missing_secret(&name)),
                },
                None => return Err(missing_secret(&name)),
            };
            if value.len() < min_len {
                return Err(mlua::Error::RuntimeError(format!(
                    "the secret in {name} is {} bytes long, at least {min_len} are required",
                    value.len()
                )));
            }
            lua.create_string(value)
        })?,
    )?;

    env.set("mode", opts.mode.as_str())?;

    Ok(env)
}

/// The mode this state runs under: what [`set_run_mode`] installed, else
/// the policy's.
fn run_mode(lua: &Lua, opts: &EnvOptions) -> RunMode {
    lua.app_data_ref::<RunMode>()
        .map_or(opts.mode, |mode| *mode)
}

/// Overrides the mode of a state whose builtins are already registered:
/// the test runner boots a real server from the same configuration, and
/// its states must answer `test` too, or a config script's `dev` fallback
/// would not apply under `nitr test`.
///
/// # Errors
///
/// Only when the `nitr` namespace table cannot be read.
pub fn set_run_mode(lua: &Lua, mode: RunMode) -> mlua::Result<()> {
    lua.set_app_data(mode);
    let nitr = nitr_core::nitr_table(lua).map_err(mlua::Error::external)?;
    if let Some(env) = nitr.get::<Option<Table>>("env")? {
        env.set("mode", mode.as_str())?;
    }
    Ok(())
}

fn missing_secret(name: &str) -> mlua::Error {
    mlua::Error::RuntimeError(format!(
        "the environment variable {name} is required and has no value"
    ))
}

/// Reads one variable under the policy; `None` for unset *and* for hidden,
/// so callers cannot distinguish the two, and for an empty value.
///
/// A test's override (`nitr.test.env`, installed as
/// [`Doubles`](crate::testing::Doubles) app data) is consulted only
/// *after* the policy: an override of a hidden name stays hidden, so a
/// test exercises the real `[env]` rules rather than a way around them.
fn read(lua: &Lua, opts: &EnvOptions, name: &str) -> Option<String> {
    if !visible(opts, name) {
        return None;
    }
    let value = match crate::testing::installed(lua).and_then(|d| d.env_override(name)) {
        Some(overridden) => overridden,
        None => std::env::var(name).ok(),
    };
    value.filter(|value| !value.is_empty())
}

/// Whether the policy lets scripts see this name.
fn visible(opts: &EnvOptions, name: &str) -> bool {
    if name.starts_with("NITR_") {
        return false;
    }
    match &opts.allow {
        None => true,
        Some(allow) => allow.iter().any(|entry| {
            // A trailing `_` marks a prefix, anything else an exact name —
            // so `"APP_"` cannot accidentally admit `"APP_SECRET"`'s
            // sibling `"APPLE"`.
            match entry.strip_suffix('_') {
                Some(_) => name.starts_with(entry.as_str()),
                None => name == entry,
            }
        }),
    }
}

/// Conventional truthiness for environment flags. Unrecognized text is
/// `None` — the caller's default answers, not a guess.
fn parse_bool(value: &str) -> Option<bool> {
    match value.trim().to_ascii_lowercase().as_str() {
        "1" | "true" | "yes" | "on" => Some(true),
        "0" | "false" | "no" | "off" | "" => Some(false),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn nitr_internals_are_always_hidden() {
        let open = EnvOptions::default();
        assert!(!visible(&open, "NITR_DATABASE_PATH"));
        assert!(!visible(&open, "NITR_ANYTHING"));
        assert!(visible(&open, "HOME"));
    }

    #[test]
    fn the_allow_list_matches_prefixes_and_exact_names() {
        let opts = EnvOptions {
            allow: Some(vec!["APP_".into(), "API_TOKEN".into()]),
            mode: RunMode::Run,
        };
        assert!(visible(&opts, "APP_NAME"));
        assert!(visible(&opts, "API_TOKEN"));
        assert!(!visible(&opts, "API_TOKEN_2"), "exact means exact");
        assert!(!visible(&opts, "APPLE"), "prefix requires the underscore");
        assert!(!visible(&opts, "HOME"));
        // The unconditional rule wins over any allow entry.
        let opts = EnvOptions {
            allow: Some(vec!["NITR_".into()]),
            mode: RunMode::Run,
        };
        assert!(!visible(&opts, "NITR_LISTEN"));
    }

    #[test]
    fn env_flags_parse_conventionally() {
        for yes in ["1", "true", "YES", "On", " true "] {
            assert_eq!(parse_bool(yes), Some(true), "{yes}");
        }
        for no in ["0", "false", "NO", "off", ""] {
            assert_eq!(parse_bool(no), Some(false), "{no}");
        }
        assert_eq!(parse_bool("maybe"), None);
    }

    #[test]
    fn lua_getters_answer_defaults_for_unset_names() {
        let lua = mlua::Lua::new();
        let table = create_env_table(&lua, &EnvOptions::default()).expect("table");
        lua.globals().set("env", table).expect("set");
        // Certainly-unset names take the default (or nil); no process
        // environment is mutated — `set_var` is unsafe in edition 2024.
        let (a, b, c, d): (Value, String, f64, bool) = lua
            .load(
                r#"return env.get("NITR_STD_SURELY_UNSET"),
                          env.get("NITR_STD_SURELY_UNSET", "fallback"),
                          env.number("NITR_STD_SURELY_UNSET", 42),
                          env.bool("NITR_STD_SURELY_UNSET", true)"#,
            )
            .eval()
            .expect("eval");
        assert!(a.is_nil());
        assert_eq!(b, "fallback");
        assert_eq!(c, 42.0);
        assert!(d);
    }

    /// An empty variable is an unset one, everywhere: Compose passes an
    /// optional variable through as `""`, and `NITR_*` already reads it
    /// as absent.
    #[test]
    fn an_empty_variable_reads_as_unset() {
        let lua = mlua::Lua::new();
        let doubles = crate::testing::Doubles::new();
        lua.set_app_data(doubles.clone());
        let table = create_env_table(&lua, &EnvOptions::default()).expect("table");
        lua.globals().set("env", table).expect("set");
        doubles.set_env("APP_EMPTY", Some(String::new()));
        let (value, has, number, flag): (String, bool, f64, bool) = lua
            .load(
                r#"return env.get("APP_EMPTY", "d"), env.has("APP_EMPTY"),
                          env.number("APP_EMPTY", 7), env.bool("APP_EMPTY", true)"#,
            )
            .eval()
            .expect("eval");
        assert_eq!((value.as_str(), has, number, flag), ("d", false, 7.0, true));
    }

    /// `secret` fails closed: unset, empty or short is an error naming the
    /// variable, and a development fallback applies only under `dev` or
    /// `test`. `mode` says which of the three the process is.
    #[test]
    fn secret_fails_closed_and_the_fallback_is_for_development_only() {
        for (mode, fallback_ok) in [
            (RunMode::Run, false),
            (RunMode::Dev, true),
            (RunMode::Test, true),
        ] {
            let lua = mlua::Lua::new();
            let doubles = crate::testing::Doubles::new();
            lua.set_app_data(doubles.clone());
            let opts = EnvOptions { allow: None, mode };
            let table = create_env_table(&lua, &opts).expect("table");
            lua.globals().set("env", table).expect("set");
            let got: String = lua.load("return env.mode").eval().expect("mode");
            assert_eq!(got, mode.as_str());
            let mode = mode.as_str();

            let err = lua
                .load(r#"return env.secret("APP_KEY")"#)
                .eval::<String>()
                .expect_err("unset")
                .to_string();
            assert!(
                err.contains("APP_KEY") && err.contains("required"),
                "{mode}: {err}"
            );

            let fallback = lua
                .load(
                    r#"return env.secret("APP_KEY", { dev = "dev-only-key-0123456789abcdef012" })"#,
                )
                .eval::<String>();
            if fallback_ok {
                assert_eq!(fallback.expect(mode), "dev-only-key-0123456789abcdef012");
            } else {
                let err = fallback.expect_err(mode).to_string();
                assert!(err.contains("APP_KEY"), "{mode}: {err}");
            }

            doubles.set_env("APP_KEY", Some("short".into()));
            let err = lua
                .load(r#"return env.secret("APP_KEY")"#)
                .eval::<String>()
                .expect_err("short")
                .to_string();
            assert!(
                err.contains("32") && err.contains("APP_KEY"),
                "{mode}: {err}"
            );
            let ok: String = lua
                .load(r#"return env.secret("APP_KEY", { min_len = 5 })"#)
                .eval()
                .expect("min_len");
            assert_eq!(ok, "short");
            doubles.set_env("APP_KEY", Some("x".repeat(32)));
            let ok: String = lua
                .load(r#"return env.secret("APP_KEY")"#)
                .eval()
                .expect("set");
            assert_eq!(ok.len(), 32);
        }
    }

    /// The runner flips a registered state to `test`: the field and the
    /// fallback follow.
    #[test]
    fn the_run_mode_can_be_set_after_registration() {
        let lua = mlua::Lua::new();
        let doubles = crate::testing::Doubles::new();
        lua.set_app_data(doubles);
        let nitr = nitr_core::nitr_table(&lua).expect("nitr");
        let table = create_env_table(&lua, &EnvOptions::default()).expect("table");
        nitr.set("env", table).expect("set");
        lua.globals().set("nitr", nitr).expect("set");
        let run =
            r#"return nitr.env.mode, pcall(nitr.env.secret, "APP_KEY", { dev = ("k"):rep(32) })"#;
        let (mode, ok): (String, bool) = lua.load(run).eval().expect("run");
        assert_eq!((mode.as_str(), ok), ("run", false));
        set_run_mode(&lua, RunMode::Test).expect("set mode");
        let (mode, ok): (String, bool) = lua.load(run).eval().expect("test");
        assert_eq!((mode.as_str(), ok), ("test", true));
    }

    /// `nan` and `inf` parse as floats but are not numbers a setting can
    /// mean: they read as unparseable, so the default answers.
    #[test]
    fn number_refuses_non_finite_values() {
        let lua = mlua::Lua::new();
        let doubles = crate::testing::Doubles::new();
        lua.set_app_data(doubles.clone());
        let table = create_env_table(&lua, &EnvOptions::default()).expect("table");
        lua.globals().set("env", table).expect("set");
        for value in ["nan", "inf", "-inf", "NaN"] {
            doubles.set_env("APP_LIMIT", Some(value.into()));
            let n: f64 = lua
                .load(r#"return env.number("APP_LIMIT", 7)"#)
                .eval()
                .expect("eval");
            assert_eq!(n, 7.0, "{value}");
        }
        doubles.set_env("APP_LIMIT", Some("2.5".into()));
        let n: f64 = lua
            .load(r#"return env.number("APP_LIMIT", 7)"#)
            .eval()
            .expect("eval");
        assert_eq!(n, 2.5);
    }

    /// A test's override answers only for names the policy lets scripts
    /// see: overriding a hidden name must not become a way to read it,
    /// and an explicit unset reads as unset even when the process has it.
    #[test]
    fn overrides_obey_the_policy() {
        let lua = mlua::Lua::new();
        let doubles = crate::testing::Doubles::new();
        lua.set_app_data(doubles.clone());
        let opts = EnvOptions {
            allow: Some(vec!["APP_".into(), "PATH".into()]),
            mode: RunMode::Run,
        };
        let table = create_env_table(&lua, &opts).expect("table");
        lua.globals().set("env", table).expect("set");

        doubles.set_env("APP_KEY", Some("sk_test_1".into()));
        doubles.set_env("SECRET", Some("leaked".into()));
        doubles.set_env("NITR_LISTEN", Some("leaked".into()));
        // PATH is set in every test environment; the override unsets it.
        doubles.set_env("PATH", None);
        let (key, secret, internal, path, has_path): (String, Value, Value, Value, bool) = lua
            .load(
                r#"return env.get("APP_KEY"), env.get("SECRET"), env.get("NITR_LISTEN"),
                          env.get("PATH"), env.has("PATH")"#,
            )
            .eval()
            .expect("eval");
        assert_eq!(key, "sk_test_1");
        assert!(secret.is_nil(), "outside the allow list stays hidden");
        assert!(internal.is_nil(), "NITR_* stays hidden");
        assert!(path.is_nil() && !has_path, "an explicit unset wins");

        doubles.reset();
        let path: Value = lua.load(r#"return env.get("PATH")"#).eval().expect("eval");
        assert!(!path.is_nil(), "reset restores the process environment");
    }
}