Skip to main content

nitr_http/config/
validate.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//! Startup validation (`validate`/`validate_paths`), bundle path
7//! re-anchoring (`rebase`), and the effective-config rendering.
8
9use std::path::{Path, PathBuf};
10
11use nitr_core::{Error, Result};
12
13use super::Config;
14
15/// Whether the environment names an outbound proxy reqwest would honor.
16fn proxy_env_present() -> bool {
17    [
18        "HTTP_PROXY",
19        "HTTPS_PROXY",
20        "ALL_PROXY",
21        "http_proxy",
22        "https_proxy",
23        "all_proxy",
24    ]
25    .iter()
26    .any(|name| std::env::var_os(name).is_some_and(|value| !value.is_empty()))
27}
28
29/// Most Lua states one process will build; each is a full VM with its
30/// own memory budget.
31const MAX_WORKERS: usize = 4096;
32
33/// Most connection slots a listener will reserve. Far under
34/// `tokio::sync::Semaphore::MAX_PERMITS`, which is where a larger value
35/// panics.
36const MAX_CONNECTIONS: usize = 1 << 20;
37
38impl Config {
39    /// Rejects configurations that parse but cannot be honored.
40    ///
41    /// Called once at startup so a contradiction is a loud failure rather
42    /// than a subtle runtime surprise, a browser silently ignoring a
43    /// header combination is much harder to debug than a refused boot.
44    pub(crate) fn validate(&self) -> Result {
45        let any_origin = self
46            .cors
47            .origins
48            .as_ref()
49            .is_some_and(|o| o.iter().any(|o| o == "*"));
50        if any_origin && self.cors.credentials {
51            return Err(Error::Config(
52                "[cors] origins = [\"*\"] cannot be combined with credentials = true: \
53                 browsers reject `Access-Control-Allow-Origin: *` on a credentialed \
54                 request. List the allowed origins explicitly."
55                    .into(),
56            ));
57        }
58        for name in &self.compression.algorithms {
59            if !matches!(name.as_str(), "br" | "gzip") {
60                return Err(Error::Config(format!(
61                    "unknown [compression] algorithm `{name}`: expected \"br\" or \"gzip\""
62                )));
63            }
64        }
65        // Ceilings on the counts that size kernel or runtime objects: a
66        // stray zero in `max_connections = 10000000000` would otherwise
67        // bind the port and then panic inside `Semaphore::new`, and a
68        // `workers` typo would try to build that many Lua states.
69        for (name, value, ceiling) in [
70            ("workers", self.workers, MAX_WORKERS),
71            (
72                "[limits] max_connections",
73                self.limits.max_connections,
74                MAX_CONNECTIONS,
75            ),
76            (
77                "[health] max_connections",
78                self.health.max_connections,
79                MAX_CONNECTIONS,
80            ),
81        ] {
82            if value > ceiling {
83                return Err(Error::Config(format!(
84                    "{name} = {value} is above the supported maximum of {ceiling}"
85                )));
86            }
87        }
88        // hyper reads the request line into a buffer of `max_header_bytes`
89        // (8 KiB at least) and answers a longer one 431 itself, so a URI
90        // bound at or past that buffer could never give its 414.
91        let header_buffer = self.limits.max_header_bytes.max(8 * 1024);
92        if self.limits.max_uri_bytes >= header_buffer {
93            return Err(Error::Config(format!(
94                "[limits] max_uri_bytes = {} is not below the header buffer of {header_buffer} \
95                 bytes ([limits] max_header_bytes, at least 8192): a longer request line is \
96                 refused with 431 before it could be refused with 414",
97                self.limits.max_uri_bytes
98            )));
99        }
100        if self.rate_limit.enabled && (self.rate_limit.requests == 0 || self.rate_limit.window == 0)
101        {
102            return Err(Error::Config(format!(
103                "[rate_limit] requests = {} and window = {} must both be at least 1",
104                self.rate_limit.requests, self.rate_limit.window
105            )));
106        }
107        for origin in self.cors.origins.iter().flatten() {
108            let well_formed = origin == "*"
109                || origin.split_once("://").is_some_and(|(scheme, rest)| {
110                    !scheme.is_empty() && !rest.is_empty() && !rest.contains('/')
111                });
112            if !well_formed {
113                return Err(Error::Config(format!(
114                    "[cors] origins entry `{origin}` is not an origin: a browser sends \
115                     `scheme://host[:port]`, with no path and no trailing slash"
116                )));
117            }
118        }
119        for (name, value) in &self.headers {
120            if hyper::header::HeaderName::from_bytes(name.as_bytes()).is_err() {
121                return Err(Error::Config(format!(
122                    "[headers] `{name}` is not a header name"
123                )));
124            }
125            if hyper::header::HeaderValue::from_str(value).is_err() {
126                return Err(Error::Config(format!(
127                    "[headers] the value of `{name}` is not a header value: \
128                     visible ASCII only, no line breaks"
129                )));
130            }
131        }
132        for host in &self.fetch.private_hosts {
133            let well_formed =
134                !host.is_empty() && !host.contains(['/', ':', '@', '?', '#']) && host.is_ascii();
135            if !well_formed {
136                return Err(Error::Config(format!(
137                    "[fetch] private_hosts entry `{host}` is not a host name: a bare name \
138                     such as \"payments\" or \"db.internal\", without scheme, port or path"
139                )));
140            }
141        }
142        // mlua enforces the allocator limit only above zero (memory.rs),
143        // so 0 would silently lift the cap on every state.
144        if self.lua.memory_limit == 0 {
145            return Err(Error::Config(
146                "[lua] memory_limit = 0 removes the per-state memory cap: set a size in \
147                 bytes (default 8388608)"
148                    .into(),
149            ));
150        }
151        if self.max_streams == Some(0) {
152            return Err(Error::Config(
153                "max_streams = 0 refuses every streaming response, after its handler has \
154                 already run: remove it for the default (workers - 1), or set it to 1 or more"
155                    .into(),
156            ));
157        }
158        if let Some(max_streams) = self.max_streams
159            && max_streams > self.workers.max(1)
160        {
161            return Err(Error::Config(format!(
162                "max_streams = {max_streams} exceeds workers = {}: every streaming \
163                 response holds a pooled Lua state, so the extra slots could never \
164                 be used",
165                self.workers.max(1)
166            )));
167        }
168        // Waiting for a state longer than a handler is allowed to run means
169        // the queue can only ever grow: work is admitted slower than it can
170        // possibly be retired.
171        if self.limits.pool_wait_ms > self.lua.exec_timeout_ms
172            && self.limits.pool_wait_ms != 0
173            && self.lua.exec_timeout_ms != 0
174        {
175            return Err(Error::Config(format!(
176                "[limits] pool_wait_ms = {} exceeds [lua] exec_timeout_ms = {}: a \
177                 request would wait for a state longer than any handler may run",
178                self.limits.pool_wait_ms, self.lua.exec_timeout_ms
179            )));
180        }
181        // Behind an outbound proxy the *proxy* resolves the target, so the
182        // guarded resolver — the thing that makes the SSRF policy hold
183        // against DNS rebinding — never runs; only the pre-flight name
184        // check does, and a name can answer that check with one address
185        // and the proxy's lookup with another. Without private networks
186        // allowed (the operator saying "I trust what this proxy reaches")
187        // the policy then needs an allow-list that does not depend on
188        // DNS at all. Only enforced when `fetch` is enabled: a proxy in
189        // the file with no fetch builtin proxies nothing.
190        if self
191            .builtins()
192            .is_ok_and(|b| b.contains(nitr_std::Builtins::FETCH))
193            && (self.fetch.proxy.is_some() || (!self.fetch.no_proxy && proxy_env_present()))
194            && !self.fetch.allow_private_networks
195            && self.fetch.allowed_hosts.is_none()
196        {
197            let source = if self.fetch.proxy.is_some() {
198                "[fetch] proxy is set"
199            } else {
200                "a proxy environment variable (HTTP_PROXY/HTTPS_PROXY/ALL_PROXY) is set"
201            };
202            return Err(Error::Config(format!(
203                "{source}, so outbound targets are resolved by the proxy and the SSRF resolver \
204                 guard cannot apply. Set [fetch] allowed_hosts to the hosts scripts may reach, \
205                 or allow_private_networks = true if the proxy is trusted to reach anything, \
206                 or no_proxy = true to ignore the environment"
207            )));
208        }
209        // Drained before the remaining hard checks, where the old inline
210        // `warn!` sat: a config refused by a TLS or health error below still
211        // logs its warnings, so the operator sees every problem in one boot.
212        for warning in self.warnings() {
213            tracing::warn!("{warning}");
214        }
215        self.validate_tls()?;
216        self.validate_docs()?;
217        if self.health.enabled {
218            for (name, path) in [
219                ("liveness", &self.health.liveness),
220                ("readiness", &self.health.readiness),
221            ] {
222                if !path.starts_with('/') {
223                    return Err(Error::Config(format!(
224                        "[health] {name} = `{path}` must start with `/`"
225                    )));
226                }
227            }
228            if self.health.liveness == self.health.readiness {
229                return Err(Error::Config(
230                    "[health] liveness and readiness must be different paths: they \
231                     answer different questions (see the [health] docs)"
232                        .into(),
233                ));
234            }
235        }
236        self.validate_paths()
237    }
238
239    /// The warning for streams that can hold every state, when they can.
240    ///
241    /// A stream keeps its state until it ends: with a slot for every
242    /// state, open streams leave none for anything else, and every other
243    /// request waits `pool_wait_ms` and gets a 503. The default is that
244    /// case on a single worker. Given when the server starts serving, not
245    /// in [`warnings`](Self::warnings): `nitr openapi` builds on one worker
246    /// and never serves.
247    pub(crate) fn streams_warning(&self) -> Option<String> {
248        (self.effective_max_streams() >= self.workers.max(1)).then(|| {
249            format!(
250                "max_streams = {} allows a streaming response on every one of the {} Lua \
251                 state(s): while that many streams are open, every other request waits \
252                 [limits] pool_wait_ms and gets a 503; raise workers or lower max_streams",
253                self.effective_max_streams(),
254                self.workers.max(1)
255            )
256        })
257    }
258
259    /// Configurations that are legal but suspicious, as values.
260    ///
261    /// Collected rather than logged in place so each one can be asserted in
262    /// an ordinary unit test — a `tracing::warn!` is invisible to the
263    /// `Result`-shaped assertions the rest of this module is tested with,
264    /// and capturing it would cost a subscriber in `[dev-dependencies]`
265    /// purely to read back log text. [`Config::validate`] drains this list
266    /// through `tracing::warn!` at startup, so the boot output is unchanged.
267    pub(crate) fn warnings(&self) -> Vec<String> {
268        let mut out = Vec::new();
269        // The stall bound still protects handlers that read the body
270        // incrementally past the compute budget — but for the common
271        // buffered read (`req:text()`, `req:form()`) the execution timeout
272        // fires first, turning what should be a clear 408 into a
273        // timeout-kind 500 that blames the handler.
274        if self.limits.body_read_ms > self.lua.exec_timeout_ms
275            && self.limits.body_read_ms != 0
276            && self.lua.exec_timeout_ms != 0
277        {
278            out.push(format!(
279                "[limits] body_read_ms = {} exceeds [lua] exec_timeout_ms = {}: a stalled \
280                 buffered body read will surface as a handler timeout instead of a 408",
281                self.limits.body_read_ms, self.lua.exec_timeout_ms
282            ));
283        }
284        // An upload root under the static root means uploaded bytes are
285        // served straight back to browsers. That is a real deployment
286        // shape (user avatars), so it warns rather than refuses — but it
287        // turns every upload into hosted content, which the operator has
288        // to have chosen on purpose. Contrast the `package_dir` overlap,
289        // which `validate_paths` refuses outright: there is no version of
290        // that one an operator wants.
291        if let (Some(upload), Some(static_dir)) =
292            (&self.multipart.upload_dir, &self.static_files.dir)
293            && let (Ok(upload), Ok(static_dir)) = (upload.canonicalize(), static_dir.canonicalize())
294            && upload.starts_with(&static_dir)
295        {
296            out.push(format!(
297                "[multipart] upload_dir {} is inside [static] dir {}: every uploaded file \
298                 is served back over HTTP",
299                upload.display(),
300                static_dir.display()
301            ));
302        }
303        // A server that terminates TLS and then opts its cookies out of it.
304        // The other way round, `"auto"` on a plaintext listener, is said
305        // by the first cookie that ships that way (`cookie_insecure_warning`):
306        // a service that sets no cookie has nothing to be warned about.
307        if self.cookies.secure == super::CookieSecure::Never && self.tls.enabled && !self.dev_mode {
308            out.push(
309                "cookies will be sent without the `Secure` attribute: [cookies] secure = \
310                 \"never\" is set even though [tls] enabled = true"
311                    .into(),
312            );
313        }
314        // A private key other users on the box can read. A warning and
315        // never a refusal: containers legitimately run as root with a
316        // mounted secret, and a security check whose failure mode is "the
317        // deployment does not come up" gets disabled. Ownership is
318        // deliberately not examined — the operator's uid arrangement is
319        // not the server's to police; the mode bits are merely mentioned.
320        // Non-Unix has no comparable mode and skips the check.
321        #[cfg(unix)]
322        if self.tls.enabled
323            && let Some(key) = &self.tls.key
324            && let Ok(meta) = std::fs::metadata(key)
325        {
326            use std::os::unix::fs::PermissionsExt as _;
327            let mode = meta.permissions().mode();
328            if !key_mode_is_private(mode) {
329                out.push(format!(
330                    "[tls] key = {} is mode {:03o}: readable beyond its owner. The server \
331                     reads it regardless — protecting the file is the operator's job — \
332                     but a private key usually wants 0600",
333                    key.display(),
334                    mode & 0o7777
335                ));
336            }
337        }
338        // `"debug"` is deliberately *not* warned about here: it is refused
339        // outright by `LuaConfig::parse_stdlib`, because mlua's safe
340        // constructor cannot load it at all. A warning would only precede a
341        // failure.
342        out
343    }
344
345    /// Rejects a `[tls]` section that cannot terminate a connection.
346    ///
347    /// Every check here fires at startup rather than at the first
348    /// handshake: a listener that accepts TCP and then fails every
349    /// connection is indistinguishable, from the outside, from a network
350    /// fault, and it fails *after* a deployment has already shifted
351    /// traffic onto it.
352    fn validate_tls(&self) -> Result {
353        if !self.tls.enabled {
354            // An unused section is not held to its own rules — the same
355            // way `[health]` skips its path checks when disabled — so a
356            // half-written `[tls]` block can sit in a file until the day
357            // somebody turns it on.
358            return Ok(());
359        }
360        // `cfg!` rather than `#[cfg]` so the checks below are compiled —
361        // and tested — in both feature configurations; only the refusal
362        // is conditional.
363        if cfg!(not(feature = "tls")) {
364            return Err(Error::Config(
365                "[tls] enabled = true, but this binary was built without the `tls` \
366                 feature: rebuild with `--features tls` (or `all`)"
367                    .into(),
368            ));
369        }
370        for (key, what) in [("cert", "certificate chain"), ("key", "private key")] {
371            let path = match key {
372                "cert" => &self.tls.cert,
373                _ => &self.tls.key,
374            };
375            let Some(path) = path else {
376                return Err(Error::Config(format!(
377                    "[tls] enabled = true requires `{key}`: set [tls] {key} to the PEM \
378                     file holding the server {what}"
379                )));
380            };
381            if !path.is_file() {
382                return Err(Error::Config(format!(
383                    "[tls] {key} points at {}, which is not a readable file",
384                    path.display()
385                )));
386            }
387        }
388        // `0` is how `[limits]` spells "disabled", and it is exactly the
389        // spelling this key must refuse: the handshake precedes hyper's
390        // header machinery, so an unbounded accept would hold a
391        // connection slot nothing else can reclaim. Unset (the default)
392        // already means a bounded `min(header_read_ms, 10s)`.
393        if self.tls.handshake_ms == Some(0) {
394            return Err(Error::Config(
395                "[tls] handshake_ms = 0 would leave the TLS handshake unbounded, and a \
396                 stalled ClientHello holds a connection slot forever: set a positive \
397                 deadline, or leave it unset for min(header_read_ms, 10s)"
398                    .into(),
399            ));
400        }
401        if let Some(version) = &self.tls.min_version
402            && !super::sections::TLS_MIN_VERSIONS.contains(&version.as_str())
403        {
404            return Err(Error::Config(format!(
405                "unknown [tls] min_version `{version}`: expected {}",
406                super::sections::TLS_MIN_VERSIONS
407                    .map(|v| format!("\"{v}\""))
408                    .join(" or ")
409            )));
410        }
411        Ok(())
412    }
413
414    /// The `[openapi]` and `[swagger]` sections: feature presence, the
415    /// paths they claim (distinct from each other and from the health
416    /// probes), the page's option table, and the dev-mode output file.
417    fn validate_docs(&self) -> Result {
418        let openapi = &self.openapi;
419        let swagger = &self.swagger;
420        if openapi.enabled && cfg!(not(feature = "openapi")) {
421            return Err(Error::Config(
422                "[openapi] enabled = true, but this binary was built without the `openapi` \
423                 feature: rebuild with `--features openapi` (or `all`)"
424                    .into(),
425            ));
426        }
427        if swagger.enabled && cfg!(not(feature = "swagger")) {
428            return Err(Error::Config(
429                "[swagger] enabled = true, but this binary was built without the `swagger` \
430                 feature: rebuild with `--features swagger` (or `all`)"
431                    .into(),
432            ));
433        }
434        for (key, path) in [
435            ("[openapi] path", &openapi.path),
436            ("[swagger] path", &swagger.path),
437        ] {
438            if !path.starts_with('/') || path.len() < 2 || path.ends_with('/') {
439                return Err(Error::Config(format!(
440                    "{key} must be an absolute URL path below `/` without a trailing slash, got `{path}`"
441                )));
442            }
443        }
444        if swagger.enabled {
445            if !openapi.enabled && swagger.spec_url.is_none() {
446                return Err(Error::Config(
447                    "[swagger] enabled = true needs the document it renders: set [openapi] \
448                     enabled = true, or point `spec_url` at a document served elsewhere"
449                        .into(),
450                ));
451            }
452            if let Some(url) = &swagger.spec_url
453                && !url.starts_with('/')
454                && !swagger.allow_external_spec
455            {
456                return Err(Error::Config(format!(
457                    "[swagger] spec_url `{url}` is on another origin: set allow_external_spec = \
458                     true to let the page load it (this widens its connect-src to that origin)"
459                )));
460            }
461            if !super::sections::DOC_EXPANSIONS.contains(&swagger.doc_expansion.as_str()) {
462                return Err(Error::Config(format!(
463                    "[swagger] doc_expansion must be \"list\", \"full\" or \"none\", got `{}`",
464                    swagger.doc_expansion
465                )));
466            }
467            for key in swagger.options.keys() {
468                if super::sections::SWAGGER_RESERVED_OPTIONS.contains(&key.as_str()) {
469                    return Err(Error::Config(format!(
470                        "[swagger.options] may not set `{key}`: the page owns it"
471                    )));
472                }
473                if let Some((typed, _)) = super::sections::SWAGGER_TYPED_OPTIONS
474                    .iter()
475                    .find(|(_, camel)| camel == key)
476                {
477                    return Err(Error::Config(format!(
478                        "[swagger.options] `{key}` is the typed setting [swagger] {typed}: set it \
479                         there, once"
480                    )));
481                }
482            }
483        }
484        if openapi.enabled && swagger.enabled {
485            let (a, b) = (openapi.path.as_str(), swagger.path.as_str());
486            if a == b || a.starts_with(&format!("{b}/")) || b.starts_with(&format!("{a}/")) {
487                return Err(Error::Config(format!(
488                    "[openapi] path `{a}` and [swagger] path `{b}` overlap: the page's assets live \
489                     under its path, so the two must be distinct and neither below the other"
490                )));
491            }
492        }
493        if self.health.enabled && self.health.bind.is_none() {
494            for (key, enabled, path) in [
495                ("[openapi] path", openapi.enabled, &openapi.path),
496                ("[swagger] path", swagger.enabled, &swagger.path),
497            ] {
498                if enabled && (path == &self.health.liveness || path == &self.health.readiness) {
499                    return Err(Error::Config(format!(
500                        "{key} `{path}` is a [health] probe path: the probes answer first, so \
501                         the document could never be served there"
502                    )));
503                }
504            }
505        }
506        if let Some(output) = &openapi.output {
507            if output.extension().is_some_and(|e| e == "lua") {
508                return Err(Error::Config(format!(
509                    "[openapi] output {} has a `.lua` extension: the dev-mode watcher would \
510                     reload on every write, so the document may not be a script",
511                    output.display()
512                )));
513            }
514            if let Some(dir) = &self.templating.dir
515                && output.starts_with(dir)
516            {
517                return Err(Error::Config(format!(
518                    "[openapi] output {} is inside [templating] dir: the watcher would reload \
519                     on every write",
520                    output.display()
521                )));
522            }
523            match output.parent() {
524                Some(parent) if parent.as_os_str().is_empty() || parent.is_dir() => {}
525                Some(parent) => {
526                    return Err(Error::Config(format!(
527                        "[openapi] output {}: the directory {} does not exist",
528                        output.display(),
529                        parent.display()
530                    )));
531                }
532                None => {
533                    return Err(Error::Config(
534                        "[openapi] output must name a file, not a directory".into(),
535                    ));
536                }
537            }
538            if let Some(dir) = &self.static_files.dir
539                && output.starts_with(dir)
540            {
541                tracing::warn!(
542                    "[openapi] output {} is inside [static] dir: the file is served statically, \
543                     which bypasses `[openapi] enabled`",
544                    output.display()
545                );
546            }
547        }
548        Ok(())
549    }
550
551    /// Rejects paths that cannot work before any of them is opened, so a
552    /// typo'd path is a startup error naming the setting, not a confusing
553    /// failure minutes later.
554    fn validate_paths(&self) -> Result {
555        let checks: [(&str, Option<&PathBuf>, bool); 5] = [
556            ("handler_script", Some(&self.handler_script), false),
557            ("config_script", self.config_script.as_ref(), false),
558            ("[templating] dir", self.templating.dir.as_ref(), true),
559            ("[static] dir", self.static_files.dir.as_ref(), true),
560            (
561                "[multipart] upload_dir",
562                self.multipart.upload_dir.as_ref(),
563                true,
564            ),
565        ];
566        for (name, path, want_dir) in checks {
567            let Some(path) = path else { continue };
568            if !path.exists() {
569                return Err(Error::Config(format!(
570                    "{name} points at {}, which does not exist",
571                    path.display()
572                )));
573            }
574            if want_dir != path.is_dir() {
575                let (wanted, got) = if want_dir {
576                    ("a directory", "a file")
577                } else {
578                    ("a file", "a directory")
579                };
580                return Err(Error::Config(format!(
581                    "{name} must be {wanted}, but {} is {got}",
582                    path.display()
583                )));
584            }
585        }
586        // Existence is not readability: a mis-owned static root would
587        // otherwise answer every request 404 with nothing explaining why.
588        // Probing with read_dir surfaces PermissionDenied at startup.
589        if let Some(dir) = &self.static_files.dir
590            && let Err(err) = std::fs::read_dir(dir)
591        {
592            return Err(Error::Config(format!(
593                "[static] dir {} exists but cannot be read: {err}",
594                dir.display()
595            )));
596        }
597        // Uploads are the one thing Lua can write, so the root has to be
598        // writable *now* rather than at the first upload, when the only
599        // symptom is a 500 on a request nobody can reproduce. Existence
600        // is not writability: a mis-owned or read-only-mounted directory
601        // passes every check above.
602        //
603        // `create_new`, never `create`: the upload root may be shared with
604        // other local users, and a pre-planted symlink named like the
605        // probe would have been *truncated through* by a plain create.
606        // The name carries a random component for the same reason — a pid
607        // is guessable — and an `AlreadyExists` is retried, not trusted.
608        if let Some(dir) = &self.multipart.upload_dir {
609            let mut attempts = 0;
610            loop {
611                let probe = dir.join(format!(
612                    ".nitr-write-probe-{}-{}",
613                    std::process::id(),
614                    uuid::Uuid::now_v7().simple()
615                ));
616                match std::fs::File::create_new(&probe) {
617                    Ok(file) => {
618                        drop(file);
619                        let _ = std::fs::remove_file(&probe);
620                        break;
621                    }
622                    Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists && attempts < 3 => {
623                        attempts += 1;
624                    }
625                    Err(err) => {
626                        return Err(Error::Config(format!(
627                            "[multipart] upload_dir {} exists but cannot be written to: {err}",
628                            dir.display()
629                        )));
630                    }
631                }
632            }
633        }
634        // An upload root inside the handler's own directory is the
635        // upload-to-RCE chain written in configuration: `require`'s search
636        // path is pinned there, so an uploaded `.lua` file becomes a
637        // module the handler can load — and in dev mode the watcher may
638        // reload it without being asked.
639        if let Some(dir) = &self.multipart.upload_dir
640            && let (Ok(upload), Ok(package)) =
641                (dir.canonicalize(), self.package_dir().canonicalize())
642            && upload.starts_with(&package)
643        {
644            return Err(Error::Config(format!(
645                "[multipart] upload_dir {} is inside the handler script's directory {}: \
646                 `require` is pinned there, so an uploaded file would be a loadable Lua \
647                 module. Put the upload root outside it.",
648                upload.display(),
649                package.display()
650            )));
651        }
652        // An upload root inside the templates directory: an upload whose
653        // name matches a template replaces it — stored script injection
654        // through the renderer, and in dev mode a reload per upload.
655        if let (Some(upload), Some(templates)) = (&self.multipart.upload_dir, &self.templating.dir)
656            && let (Ok(upload), Ok(templates)) = (upload.canonicalize(), templates.canonicalize())
657            && upload.starts_with(&templates)
658        {
659            return Err(Error::Config(format!(
660                "[multipart] upload_dir {} is inside [templating] dir {}: an uploaded \
661                 file could replace a template. Put the upload root outside it.",
662                upload.display(),
663                templates.display()
664            )));
665        }
666        // A static root that encloses the scripts or the templates serves
667        // them: `[static] dir = "."` with `mount = "/"` answers
668        // `GET /app.lua` and `GET /nitr.toml` (the env file beside them is
669        // covered by the dotfile rule, these two are not).
670        if let Some(static_dir) = &self.static_files.dir
671            && let Ok(static_dir) = static_dir.canonicalize()
672        {
673            let enclosed: [(&str, Option<PathBuf>); 2] = [
674                (
675                    "the handler script's directory",
676                    self.package_dir().canonicalize().ok(),
677                ),
678                (
679                    "[templating] dir",
680                    self.templating
681                        .dir
682                        .as_ref()
683                        .and_then(|p| p.canonicalize().ok()),
684                ),
685            ];
686            for (what, dir) in enclosed {
687                if let Some(dir) = dir
688                    && dir.starts_with(&static_dir)
689                {
690                    return Err(Error::Config(format!(
691                        "[static] dir {} encloses {what} ({}): the scripts and configuration \
692                         would be served as static files. Point [static] dir at a directory \
693                         that holds only public assets.",
694                        static_dir.display(),
695                        dir.display()
696                    )));
697                }
698            }
699        }
700        // The database file itself may not exist yet (SQLite creates it),
701        // but its parent directory must, SQLite will not create that.
702        if let Some(db) = &self.database
703            && let Some(parent) = db.path.parent()
704            && !parent.as_os_str().is_empty()
705            && !parent.is_dir()
706        {
707            return Err(Error::Config(format!(
708                "the database directory {} does not exist (SQLite creates the \
709                 file, not its directory)",
710                parent.display()
711            )));
712        }
713        Ok(())
714    }
715
716    /// Re-anchors the application's relative paths under `root`.
717    ///
718    /// Used when running from a `nitr build` bundle: the scripts, templates
719    /// and static files live in the extraction directory, while the
720    /// database path is deliberately left alone, it is mutable state and
721    /// stays external to the artifact, resolving against the working
722    /// directory as usual. `[multipart] upload_dir` is left alone for the
723    /// same reason — uploads outlive the bundle they were received by, and
724    /// re-anchoring them inside a `nitr build` extraction directory would
725    /// make them vanish on the next deploy. `[tls] cert`/`key` are left
726    /// alone for the stronger version of the same reason: a private key
727    /// inside a copyable one-file artifact is a private key that leaks
728    /// with it.
729    pub fn rebase(&mut self, root: &Path) {
730        let anchor = |path: &mut PathBuf| {
731            if path.is_relative() {
732                *path = root.join(&path);
733            }
734        };
735        anchor(&mut self.handler_script);
736        if let Some(path) = &mut self.config_script {
737            anchor(path);
738        }
739        if let Some(path) = &mut self.templating.dir {
740            anchor(path);
741        }
742        if let Some(path) = &mut self.static_files.dir {
743            anchor(path);
744        }
745        if let Some(db) = &mut self.database
746            && let Some(dir) = &mut db.migrations_dir
747        {
748            anchor(dir);
749        }
750        anchor(&mut self.testing.dir);
751        if let Some(path) = &mut self.testing.seed {
752            anchor(path);
753        }
754    }
755
756    /// What `nitr test` checks on top of the boot validation: its tests
757    /// directory becomes a second `require` root in test states, so it
758    /// gets the rule the handler's directory has — an upload root inside
759    /// it would make an uploaded `.lua` file a loadable module.
760    pub fn validate_testing(&self) -> Result {
761        // `nitr test` truncates, seeds and restores its database; pointed
762        // at the live one, one `t.db.truncate()` empties production data.
763        if let (Some(db), Some(test_db)) = (&self.database, &self.testing.database)
764            && resolved_file(&db.path) == resolved_file(test_db)
765        {
766            return Err(Error::Config(format!(
767                "[testing] database {} is [database] path: tests reset, truncate and seed \
768                 their database. Name a separate file, or leave [testing] database unset for \
769                 a private one per run.",
770                test_db.display()
771            )));
772        }
773        if let Some(dir) = &self.multipart.upload_dir
774            && let (Ok(upload), Ok(tests)) = (dir.canonicalize(), self.testing.dir.canonicalize())
775            && upload.starts_with(&tests)
776        {
777            return Err(Error::Config(format!(
778                "[multipart] upload_dir {} is inside [testing] dir {}: `nitr test` lets test \
779                 files `require` from there, so an uploaded file would be a loadable Lua \
780                 module. Put the upload root outside it.",
781                upload.display(),
782                tests.display()
783            )));
784        }
785        Ok(())
786    }
787
788    /// The effective configuration after file, environment, and flag
789    /// layering, rendered as TOML, the answer to "which value actually
790    /// won?".
791    pub fn effective_toml(&self) -> Result<String> {
792        // Route through JSON first to drop the `None`s: TOML has no null,
793        // and an absent key is exactly what an unset option means.
794        let json = serde_json::to_value(self)
795            .map_err(|err| Error::Config(format!("cannot serialize the configuration: {err}")))?;
796        let json = strip_nulls(json);
797        toml::to_string_pretty(&json)
798            .map_err(|err| Error::Config(format!("cannot render the configuration: {err}")))
799    }
800}
801
802/// A file's path with its directory canonicalized, so two spellings of one
803/// file compare equal even before the file exists.
804fn resolved_file(path: &Path) -> PathBuf {
805    if let Ok(canonical) = path.canonicalize() {
806        return canonical;
807    }
808    match (path.parent(), path.file_name()) {
809        (Some(parent), Some(name)) => {
810            let parent = if parent.as_os_str().is_empty() {
811                Path::new(".")
812            } else {
813                parent
814            };
815            parent
816                .canonicalize()
817                .map(|dir| dir.join(name))
818                .unwrap_or_else(|_| path.to_path_buf())
819        }
820        _ => path.to_path_buf(),
821    }
822}
823
824/// Removes `null`s (and the entries they were) from a JSON tree, so the
825/// result can render as TOML, which has no null.
826fn strip_nulls(value: serde_json::Value) -> serde_json::Value {
827    match value {
828        serde_json::Value::Object(map) => serde_json::Value::Object(
829            map.into_iter()
830                .filter(|(_, v)| !v.is_null())
831                .map(|(k, v)| (k, strip_nulls(v)))
832                .collect(),
833        ),
834        serde_json::Value::Array(items) => {
835            serde_json::Value::Array(items.into_iter().map(strip_nulls).collect())
836        }
837        other => other,
838    }
839}
840
841/// Whether a key file's mode keeps it to its owner: no group or other
842/// bits at all. `0600`/`0400` pass; `0640`, `0644` and wider do not.
843/// The predicate the `[tls] key` permission warning fires on, split out
844/// so the mask is pinned by a unit test rather than implied by a log
845/// line.
846#[cfg(unix)]
847pub(crate) fn key_mode_is_private(mode: u32) -> bool {
848    mode & 0o077 == 0
849}