Skip to main content

nitr_std/
config.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//! Plain-data configuration types shared with the server layer.
7//!
8//! These live outside the modules that implement them, and outside every
9//! Cargo feature, on purpose: the shape of `nitr.toml` must not depend on
10//! which builtins a particular build compiled in. A server built without
11//! the `db` feature still parses a `[database]` section — it just refuses
12//! to enable the builtin, with a message saying so, instead of failing to
13//! recognize the configuration at all.
14
15use std::time::Duration;
16
17/// Policy and limits applied to every outbound `fetch` request.
18///
19/// None of this is reachable from Lua: a script declares intent (a timeout,
20/// a retry count) but cannot widen its own policy or uncap its budget.
21#[derive(Debug, Clone)]
22pub struct FetchOptions {
23    /// When set, only these exact host names may be fetched (compared
24    /// case-insensitively; applies to every redirect hop).
25    pub allowed_hosts: Option<Vec<String>>,
26    /// Allow requests to loopback/private/link-local addresses. Off by
27    /// default; enable for trusted internal aggregation.
28    pub allow_private_networks: bool,
29    /// Host names that may resolve to a private address while
30    /// `allow_private_networks` stays off: the sidecar or the service next
31    /// door, compared case-insensitively against the URL's host and
32    /// applied to every redirect hop.
33    pub private_hosts: Vec<String>,
34    /// Maximum response body size accumulated by `resp:text()` /
35    /// `resp:json()`, in bytes.
36    pub max_response_bytes: u64,
37    /// Maximum concurrent requests per `await_all(...)` call.
38    pub max_concurrent: usize,
39    /// Maximum outbound requests one inbound request may make in total.
40    /// `0` removes the cap.
41    pub max_per_request: u32,
42    /// How long to wait for a TCP/TLS connection to an upstream.
43    pub connect_timeout: Duration,
44    /// Default total budget per outbound request.
45    pub timeout: Duration,
46    /// Idle connections kept per upstream host.
47    pub pool_max_idle_per_host: usize,
48    /// Ceiling on the `retry.attempts` a call may ask for.
49    pub max_retries: u32,
50    /// Explicit proxy URL; `None` uses the environment variables unless
51    /// [`no_proxy`](Self::no_proxy) is set.
52    pub proxy: Option<String>,
53    /// Ignore the proxy environment variables.
54    pub no_proxy: bool,
55    /// Forward a W3C `traceparent` derived from the inbound request id.
56    pub propagate_trace_context: bool,
57}
58
59impl Default for FetchOptions {
60    fn default() -> Self {
61        Self {
62            allowed_hosts: None,
63            allow_private_networks: false,
64            private_hosts: Vec::new(),
65            max_response_bytes: 8 * 1024 * 1024, // 8 MiB
66            max_concurrent: 8,
67            max_per_request: 32,
68            connect_timeout: Duration::from_secs(10),
69            timeout: Duration::from_secs(30),
70            pool_max_idle_per_host: 8,
71            max_retries: 5,
72            proxy: None,
73            no_proxy: false,
74            propagate_trace_context: false,
75        }
76    }
77}
78
79/// Read policy for the `nitr.env` builtin.
80///
81/// The builtin itself is opt-in (`[std] features`); this narrows what an
82/// enabled one may see. `NITR_*` variables are hidden from scripts
83/// unconditionally — they configure the server, not the application.
84#[derive(Debug, Clone, Default)]
85pub struct EnvOptions {
86    /// Names scripts may read: exact names, or prefixes written with a
87    /// trailing `_` (`"APP_"`). `None` allows every non-`NITR_*` variable.
88    pub allow: Option<Vec<String>>,
89    /// What the process is doing, as `nitr.env.mode` reports it and as
90    /// `nitr.env.secret` decides whether a development fallback applies.
91    pub mode: RunMode,
92}
93
94/// What a process is running as, decided by the server (`dev_mode`) or
95/// the test runner and never by a script.
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
97pub enum RunMode {
98    /// Serving, `dev_mode = false`: a secret without a value is an error.
99    #[default]
100    Run,
101    /// Serving with `dev_mode = true`.
102    Dev,
103    /// Under `nitr test`.
104    Test,
105}
106
107impl RunMode {
108    /// The word `nitr.env.mode` holds.
109    pub fn as_str(self) -> &'static str {
110        match self {
111            Self::Run => "run",
112            Self::Dev => "dev",
113            Self::Test => "test",
114        }
115    }
116}
117
118/// The pragma set applied to a connection when it is opened.
119#[derive(Debug, Clone)]
120pub struct SqlitePragmas {
121    /// `"wal"`, `"delete"`, any other SQLite journal mode, or `"keep"` to
122    /// leave whatever the database already uses.
123    pub journal_mode: String,
124    /// Milliseconds to wait on a locked database before failing.
125    pub busy_timeout: u64,
126    /// `synchronous` pragma (`"off"`, `"normal"`, `"full"`, `"extra"`).
127    pub synchronous: String,
128    /// Enforce foreign-key constraints.
129    pub foreign_keys: bool,
130    /// `cache_size` per connection; negative values are KiB.
131    pub cache_size: i64,
132    /// Most rows one `query` may return. A result past it is an error,
133    /// not a truncation: every row is materialized into memory on the
134    /// blocking thread and then copied into the Lua state, so an unbounded
135    /// `SELECT *` (or an attacker-chosen `LIMIT` a handler interpolated)
136    /// was a memory amplifier with no ceiling.
137    pub max_rows: usize,
138}
139
140impl Default for SqlitePragmas {
141    fn default() -> Self {
142        Self {
143            journal_mode: "wal".into(),
144            busy_timeout: 5_000,
145            synchronous: "normal".into(),
146            foreign_keys: true,
147            cache_size: -2_000,
148            max_rows: 10_000,
149        }
150    }
151}
152
153/// Upper bound on a password handed to `password_hash`/`password_verify`,
154/// in bytes — the argon2 input cap, checked before any hashing work.
155///
156/// Defined here, outside the `crypto` feature, for the same reason the
157/// configuration types are: the *shape* of the surface (the CLI's stdin
158/// cap, `nitr.crypto.max_password_bytes` as data) must not depend on
159/// which features a binary compiled in. The full rationale for the value
160/// lives on the `crypto::password` module that enforces it.
161pub const MAX_PASSWORD_BYTES: usize = 1024;