nitr-http 0.0.0-beta.7

The Nitr HTTP server layer: hyper server, configuration, and the request/response Lua bridge.
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
// 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>

//! Startup validation (`validate`/`validate_paths`), bundle path
//! re-anchoring (`rebase`), and the effective-config rendering.

use std::path::{Path, PathBuf};

use nitr_core::{Error, Result};

use super::Config;

/// Whether the environment names an outbound proxy reqwest would honor.
fn proxy_env_present() -> bool {
    [
        "HTTP_PROXY",
        "HTTPS_PROXY",
        "ALL_PROXY",
        "http_proxy",
        "https_proxy",
        "all_proxy",
    ]
    .iter()
    .any(|name| std::env::var_os(name).is_some_and(|value| !value.is_empty()))
}

/// Most Lua states one process will build; each is a full VM with its
/// own memory budget.
const MAX_WORKERS: usize = 4096;

/// Most connection slots a listener will reserve. Far under
/// `tokio::sync::Semaphore::MAX_PERMITS`, which is where a larger value
/// panics.
const MAX_CONNECTIONS: usize = 1 << 20;

impl Config {
    /// Rejects configurations that parse but cannot be honored.
    ///
    /// Called once at startup so a contradiction is a loud failure rather
    /// than a subtle runtime surprise, a browser silently ignoring a
    /// header combination is much harder to debug than a refused boot.
    pub(crate) fn validate(&self) -> Result {
        let any_origin = self
            .cors
            .origins
            .as_ref()
            .is_some_and(|o| o.iter().any(|o| o == "*"));
        if any_origin && self.cors.credentials {
            return Err(Error::Config(
                "[cors] origins = [\"*\"] cannot be combined with credentials = true: \
                 browsers reject `Access-Control-Allow-Origin: *` on a credentialed \
                 request. List the allowed origins explicitly."
                    .into(),
            ));
        }
        for name in &self.compression.algorithms {
            if !matches!(name.as_str(), "br" | "gzip") {
                return Err(Error::Config(format!(
                    "unknown [compression] algorithm `{name}`: expected \"br\" or \"gzip\""
                )));
            }
        }
        // Ceilings on the counts that size kernel or runtime objects: a
        // stray zero in `max_connections = 10000000000` would otherwise
        // bind the port and then panic inside `Semaphore::new`, and a
        // `workers` typo would try to build that many Lua states.
        for (name, value, ceiling) in [
            ("workers", self.workers, MAX_WORKERS),
            (
                "[limits] max_connections",
                self.limits.max_connections,
                MAX_CONNECTIONS,
            ),
            (
                "[health] max_connections",
                self.health.max_connections,
                MAX_CONNECTIONS,
            ),
        ] {
            if value > ceiling {
                return Err(Error::Config(format!(
                    "{name} = {value} is above the supported maximum of {ceiling}"
                )));
            }
        }
        // hyper reads the request line into a buffer of `max_header_bytes`
        // (8 KiB at least) and answers a longer one 431 itself, so a URI
        // bound at or past that buffer could never give its 414.
        let header_buffer = self.limits.max_header_bytes.max(8 * 1024);
        if self.limits.max_uri_bytes >= header_buffer {
            return Err(Error::Config(format!(
                "[limits] max_uri_bytes = {} is not below the header buffer of {header_buffer} \
                 bytes ([limits] max_header_bytes, at least 8192): a longer request line is \
                 refused with 431 before it could be refused with 414",
                self.limits.max_uri_bytes
            )));
        }
        if self.rate_limit.enabled && (self.rate_limit.requests == 0 || self.rate_limit.window == 0)
        {
            return Err(Error::Config(format!(
                "[rate_limit] requests = {} and window = {} must both be at least 1",
                self.rate_limit.requests, self.rate_limit.window
            )));
        }
        for origin in self.cors.origins.iter().flatten() {
            let well_formed = origin == "*"
                || origin.split_once("://").is_some_and(|(scheme, rest)| {
                    !scheme.is_empty() && !rest.is_empty() && !rest.contains('/')
                });
            if !well_formed {
                return Err(Error::Config(format!(
                    "[cors] origins entry `{origin}` is not an origin: a browser sends \
                     `scheme://host[:port]`, with no path and no trailing slash"
                )));
            }
        }
        for (name, value) in &self.headers {
            if hyper::header::HeaderName::from_bytes(name.as_bytes()).is_err() {
                return Err(Error::Config(format!(
                    "[headers] `{name}` is not a header name"
                )));
            }
            if hyper::header::HeaderValue::from_str(value).is_err() {
                return Err(Error::Config(format!(
                    "[headers] the value of `{name}` is not a header value: \
                     visible ASCII only, no line breaks"
                )));
            }
        }
        for host in &self.fetch.private_hosts {
            let well_formed =
                !host.is_empty() && !host.contains(['/', ':', '@', '?', '#']) && host.is_ascii();
            if !well_formed {
                return Err(Error::Config(format!(
                    "[fetch] private_hosts entry `{host}` is not a host name: a bare name \
                     such as \"payments\" or \"db.internal\", without scheme, port or path"
                )));
            }
        }
        // mlua enforces the allocator limit only above zero (memory.rs),
        // so 0 would silently lift the cap on every state.
        if self.lua.memory_limit == 0 {
            return Err(Error::Config(
                "[lua] memory_limit = 0 removes the per-state memory cap: set a size in \
                 bytes (default 8388608)"
                    .into(),
            ));
        }
        if self.max_streams == Some(0) {
            return Err(Error::Config(
                "max_streams = 0 refuses every streaming response, after its handler has \
                 already run: remove it for the default (workers - 1), or set it to 1 or more"
                    .into(),
            ));
        }
        if let Some(max_streams) = self.max_streams
            && max_streams > self.workers.max(1)
        {
            return Err(Error::Config(format!(
                "max_streams = {max_streams} exceeds workers = {}: every streaming \
                 response holds a pooled Lua state, so the extra slots could never \
                 be used",
                self.workers.max(1)
            )));
        }
        // Waiting for a state longer than a handler is allowed to run means
        // the queue can only ever grow: work is admitted slower than it can
        // possibly be retired.
        if self.limits.pool_wait_ms > self.lua.exec_timeout_ms
            && self.limits.pool_wait_ms != 0
            && self.lua.exec_timeout_ms != 0
        {
            return Err(Error::Config(format!(
                "[limits] pool_wait_ms = {} exceeds [lua] exec_timeout_ms = {}: a \
                 request would wait for a state longer than any handler may run",
                self.limits.pool_wait_ms, self.lua.exec_timeout_ms
            )));
        }
        // Behind an outbound proxy the *proxy* resolves the target, so the
        // guarded resolver — the thing that makes the SSRF policy hold
        // against DNS rebinding — never runs; only the pre-flight name
        // check does, and a name can answer that check with one address
        // and the proxy's lookup with another. Without private networks
        // allowed (the operator saying "I trust what this proxy reaches")
        // the policy then needs an allow-list that does not depend on
        // DNS at all. Only enforced when `fetch` is enabled: a proxy in
        // the file with no fetch builtin proxies nothing.
        if self
            .builtins()
            .is_ok_and(|b| b.contains(nitr_std::Builtins::FETCH))
            && (self.fetch.proxy.is_some() || (!self.fetch.no_proxy && proxy_env_present()))
            && !self.fetch.allow_private_networks
            && self.fetch.allowed_hosts.is_none()
        {
            let source = if self.fetch.proxy.is_some() {
                "[fetch] proxy is set"
            } else {
                "a proxy environment variable (HTTP_PROXY/HTTPS_PROXY/ALL_PROXY) is set"
            };
            return Err(Error::Config(format!(
                "{source}, so outbound targets are resolved by the proxy and the SSRF resolver \
                 guard cannot apply. Set [fetch] allowed_hosts to the hosts scripts may reach, \
                 or allow_private_networks = true if the proxy is trusted to reach anything, \
                 or no_proxy = true to ignore the environment"
            )));
        }
        // Drained before the remaining hard checks, where the old inline
        // `warn!` sat: a config refused by a TLS or health error below still
        // logs its warnings, so the operator sees every problem in one boot.
        for warning in self.warnings() {
            tracing::warn!("{warning}");
        }
        self.validate_tls()?;
        self.validate_docs()?;
        if self.health.enabled {
            for (name, path) in [
                ("liveness", &self.health.liveness),
                ("readiness", &self.health.readiness),
            ] {
                if !path.starts_with('/') {
                    return Err(Error::Config(format!(
                        "[health] {name} = `{path}` must start with `/`"
                    )));
                }
            }
            if self.health.liveness == self.health.readiness {
                return Err(Error::Config(
                    "[health] liveness and readiness must be different paths: they \
                     answer different questions (see the [health] docs)"
                        .into(),
                ));
            }
        }
        self.validate_paths()
    }

    /// The warning for streams that can hold every state, when they can.
    ///
    /// A stream keeps its state until it ends: with a slot for every
    /// state, open streams leave none for anything else, and every other
    /// request waits `pool_wait_ms` and gets a 503. The default is that
    /// case on a single worker. Given when the server starts serving, not
    /// in [`warnings`](Self::warnings): `nitr openapi` builds on one worker
    /// and never serves.
    pub(crate) fn streams_warning(&self) -> Option<String> {
        (self.effective_max_streams() >= self.workers.max(1)).then(|| {
            format!(
                "max_streams = {} allows a streaming response on every one of the {} Lua \
                 state(s): while that many streams are open, every other request waits \
                 [limits] pool_wait_ms and gets a 503; raise workers or lower max_streams",
                self.effective_max_streams(),
                self.workers.max(1)
            )
        })
    }

    /// Configurations that are legal but suspicious, as values.
    ///
    /// Collected rather than logged in place so each one can be asserted in
    /// an ordinary unit test — a `tracing::warn!` is invisible to the
    /// `Result`-shaped assertions the rest of this module is tested with,
    /// and capturing it would cost a subscriber in `[dev-dependencies]`
    /// purely to read back log text. [`Config::validate`] drains this list
    /// through `tracing::warn!` at startup, so the boot output is unchanged.
    pub(crate) fn warnings(&self) -> Vec<String> {
        let mut out = Vec::new();
        // The stall bound still protects handlers that read the body
        // incrementally past the compute budget — but for the common
        // buffered read (`req:text()`, `req:form()`) the execution timeout
        // fires first, turning what should be a clear 408 into a
        // timeout-kind 500 that blames the handler.
        if self.limits.body_read_ms > self.lua.exec_timeout_ms
            && self.limits.body_read_ms != 0
            && self.lua.exec_timeout_ms != 0
        {
            out.push(format!(
                "[limits] body_read_ms = {} exceeds [lua] exec_timeout_ms = {}: a stalled \
                 buffered body read will surface as a handler timeout instead of a 408",
                self.limits.body_read_ms, self.lua.exec_timeout_ms
            ));
        }
        // An upload root under the static root means uploaded bytes are
        // served straight back to browsers. That is a real deployment
        // shape (user avatars), so it warns rather than refuses — but it
        // turns every upload into hosted content, which the operator has
        // to have chosen on purpose. Contrast the `package_dir` overlap,
        // which `validate_paths` refuses outright: there is no version of
        // that one an operator wants.
        if let (Some(upload), Some(static_dir)) =
            (&self.multipart.upload_dir, &self.static_files.dir)
            && let (Ok(upload), Ok(static_dir)) = (upload.canonicalize(), static_dir.canonicalize())
            && upload.starts_with(&static_dir)
        {
            out.push(format!(
                "[multipart] upload_dir {} is inside [static] dir {}: every uploaded file \
                 is served back over HTTP",
                upload.display(),
                static_dir.display()
            ));
        }
        // A server that terminates TLS and then opts its cookies out of it.
        // The other way round, `"auto"` on a plaintext listener, is said
        // by the first cookie that ships that way (`cookie_insecure_warning`):
        // a service that sets no cookie has nothing to be warned about.
        if self.cookies.secure == super::CookieSecure::Never && self.tls.enabled && !self.dev_mode {
            out.push(
                "cookies will be sent without the `Secure` attribute: [cookies] secure = \
                 \"never\" is set even though [tls] enabled = true"
                    .into(),
            );
        }
        // A private key other users on the box can read. A warning and
        // never a refusal: containers legitimately run as root with a
        // mounted secret, and a security check whose failure mode is "the
        // deployment does not come up" gets disabled. Ownership is
        // deliberately not examined — the operator's uid arrangement is
        // not the server's to police; the mode bits are merely mentioned.
        // Non-Unix has no comparable mode and skips the check.
        #[cfg(unix)]
        if self.tls.enabled
            && let Some(key) = &self.tls.key
            && let Ok(meta) = std::fs::metadata(key)
        {
            use std::os::unix::fs::PermissionsExt as _;
            let mode = meta.permissions().mode();
            if !key_mode_is_private(mode) {
                out.push(format!(
                    "[tls] key = {} is mode {:03o}: readable beyond its owner. The server \
                     reads it regardless — protecting the file is the operator's job — \
                     but a private key usually wants 0600",
                    key.display(),
                    mode & 0o7777
                ));
            }
        }
        // `"debug"` is deliberately *not* warned about here: it is refused
        // outright by `LuaConfig::parse_stdlib`, because mlua's safe
        // constructor cannot load it at all. A warning would only precede a
        // failure.
        out
    }

    /// Rejects a `[tls]` section that cannot terminate a connection.
    ///
    /// Every check here fires at startup rather than at the first
    /// handshake: a listener that accepts TCP and then fails every
    /// connection is indistinguishable, from the outside, from a network
    /// fault, and it fails *after* a deployment has already shifted
    /// traffic onto it.
    fn validate_tls(&self) -> Result {
        if !self.tls.enabled {
            // An unused section is not held to its own rules — the same
            // way `[health]` skips its path checks when disabled — so a
            // half-written `[tls]` block can sit in a file until the day
            // somebody turns it on.
            return Ok(());
        }
        // `cfg!` rather than `#[cfg]` so the checks below are compiled —
        // and tested — in both feature configurations; only the refusal
        // is conditional.
        if cfg!(not(feature = "tls")) {
            return Err(Error::Config(
                "[tls] enabled = true, but this binary was built without the `tls` \
                 feature: rebuild with `--features tls` (or `all`)"
                    .into(),
            ));
        }
        for (key, what) in [("cert", "certificate chain"), ("key", "private key")] {
            let path = match key {
                "cert" => &self.tls.cert,
                _ => &self.tls.key,
            };
            let Some(path) = path else {
                return Err(Error::Config(format!(
                    "[tls] enabled = true requires `{key}`: set [tls] {key} to the PEM \
                     file holding the server {what}"
                )));
            };
            if !path.is_file() {
                return Err(Error::Config(format!(
                    "[tls] {key} points at {}, which is not a readable file",
                    path.display()
                )));
            }
        }
        // `0` is how `[limits]` spells "disabled", and it is exactly the
        // spelling this key must refuse: the handshake precedes hyper's
        // header machinery, so an unbounded accept would hold a
        // connection slot nothing else can reclaim. Unset (the default)
        // already means a bounded `min(header_read_ms, 10s)`.
        if self.tls.handshake_ms == Some(0) {
            return Err(Error::Config(
                "[tls] handshake_ms = 0 would leave the TLS handshake unbounded, and a \
                 stalled ClientHello holds a connection slot forever: set a positive \
                 deadline, or leave it unset for min(header_read_ms, 10s)"
                    .into(),
            ));
        }
        if let Some(version) = &self.tls.min_version
            && !super::sections::TLS_MIN_VERSIONS.contains(&version.as_str())
        {
            return Err(Error::Config(format!(
                "unknown [tls] min_version `{version}`: expected {}",
                super::sections::TLS_MIN_VERSIONS
                    .map(|v| format!("\"{v}\""))
                    .join(" or ")
            )));
        }
        Ok(())
    }

    /// The `[openapi]` and `[swagger]` sections: feature presence, the
    /// paths they claim (distinct from each other and from the health
    /// probes), the page's option table, and the dev-mode output file.
    fn validate_docs(&self) -> Result {
        let openapi = &self.openapi;
        let swagger = &self.swagger;
        if openapi.enabled && cfg!(not(feature = "openapi")) {
            return Err(Error::Config(
                "[openapi] enabled = true, but this binary was built without the `openapi` \
                 feature: rebuild with `--features openapi` (or `all`)"
                    .into(),
            ));
        }
        if swagger.enabled && cfg!(not(feature = "swagger")) {
            return Err(Error::Config(
                "[swagger] enabled = true, but this binary was built without the `swagger` \
                 feature: rebuild with `--features swagger` (or `all`)"
                    .into(),
            ));
        }
        for (key, path) in [
            ("[openapi] path", &openapi.path),
            ("[swagger] path", &swagger.path),
        ] {
            if !path.starts_with('/') || path.len() < 2 || path.ends_with('/') {
                return Err(Error::Config(format!(
                    "{key} must be an absolute URL path below `/` without a trailing slash, got `{path}`"
                )));
            }
        }
        if swagger.enabled {
            if !openapi.enabled && swagger.spec_url.is_none() {
                return Err(Error::Config(
                    "[swagger] enabled = true needs the document it renders: set [openapi] \
                     enabled = true, or point `spec_url` at a document served elsewhere"
                        .into(),
                ));
            }
            if let Some(url) = &swagger.spec_url
                && !url.starts_with('/')
                && !swagger.allow_external_spec
            {
                return Err(Error::Config(format!(
                    "[swagger] spec_url `{url}` is on another origin: set allow_external_spec = \
                     true to let the page load it (this widens its connect-src to that origin)"
                )));
            }
            if !super::sections::DOC_EXPANSIONS.contains(&swagger.doc_expansion.as_str()) {
                return Err(Error::Config(format!(
                    "[swagger] doc_expansion must be \"list\", \"full\" or \"none\", got `{}`",
                    swagger.doc_expansion
                )));
            }
            for key in swagger.options.keys() {
                if super::sections::SWAGGER_RESERVED_OPTIONS.contains(&key.as_str()) {
                    return Err(Error::Config(format!(
                        "[swagger.options] may not set `{key}`: the page owns it"
                    )));
                }
                if let Some((typed, _)) = super::sections::SWAGGER_TYPED_OPTIONS
                    .iter()
                    .find(|(_, camel)| camel == key)
                {
                    return Err(Error::Config(format!(
                        "[swagger.options] `{key}` is the typed setting [swagger] {typed}: set it \
                         there, once"
                    )));
                }
            }
        }
        if openapi.enabled && swagger.enabled {
            let (a, b) = (openapi.path.as_str(), swagger.path.as_str());
            if a == b || a.starts_with(&format!("{b}/")) || b.starts_with(&format!("{a}/")) {
                return Err(Error::Config(format!(
                    "[openapi] path `{a}` and [swagger] path `{b}` overlap: the page's assets live \
                     under its path, so the two must be distinct and neither below the other"
                )));
            }
        }
        if self.health.enabled && self.health.bind.is_none() {
            for (key, enabled, path) in [
                ("[openapi] path", openapi.enabled, &openapi.path),
                ("[swagger] path", swagger.enabled, &swagger.path),
            ] {
                if enabled && (path == &self.health.liveness || path == &self.health.readiness) {
                    return Err(Error::Config(format!(
                        "{key} `{path}` is a [health] probe path: the probes answer first, so \
                         the document could never be served there"
                    )));
                }
            }
        }
        if let Some(output) = &openapi.output {
            if output.extension().is_some_and(|e| e == "lua") {
                return Err(Error::Config(format!(
                    "[openapi] output {} has a `.lua` extension: the dev-mode watcher would \
                     reload on every write, so the document may not be a script",
                    output.display()
                )));
            }
            if let Some(dir) = &self.templating.dir
                && output.starts_with(dir)
            {
                return Err(Error::Config(format!(
                    "[openapi] output {} is inside [templating] dir: the watcher would reload \
                     on every write",
                    output.display()
                )));
            }
            match output.parent() {
                Some(parent) if parent.as_os_str().is_empty() || parent.is_dir() => {}
                Some(parent) => {
                    return Err(Error::Config(format!(
                        "[openapi] output {}: the directory {} does not exist",
                        output.display(),
                        parent.display()
                    )));
                }
                None => {
                    return Err(Error::Config(
                        "[openapi] output must name a file, not a directory".into(),
                    ));
                }
            }
            if let Some(dir) = &self.static_files.dir
                && output.starts_with(dir)
            {
                tracing::warn!(
                    "[openapi] output {} is inside [static] dir: the file is served statically, \
                     which bypasses `[openapi] enabled`",
                    output.display()
                );
            }
        }
        Ok(())
    }

    /// Rejects paths that cannot work before any of them is opened, so a
    /// typo'd path is a startup error naming the setting, not a confusing
    /// failure minutes later.
    fn validate_paths(&self) -> Result {
        let checks: [(&str, Option<&PathBuf>, bool); 5] = [
            ("handler_script", Some(&self.handler_script), false),
            ("config_script", self.config_script.as_ref(), false),
            ("[templating] dir", self.templating.dir.as_ref(), true),
            ("[static] dir", self.static_files.dir.as_ref(), true),
            (
                "[multipart] upload_dir",
                self.multipart.upload_dir.as_ref(),
                true,
            ),
        ];
        for (name, path, want_dir) in checks {
            let Some(path) = path else { continue };
            if !path.exists() {
                return Err(Error::Config(format!(
                    "{name} points at {}, which does not exist",
                    path.display()
                )));
            }
            if want_dir != path.is_dir() {
                let (wanted, got) = if want_dir {
                    ("a directory", "a file")
                } else {
                    ("a file", "a directory")
                };
                return Err(Error::Config(format!(
                    "{name} must be {wanted}, but {} is {got}",
                    path.display()
                )));
            }
        }
        // Existence is not readability: a mis-owned static root would
        // otherwise answer every request 404 with nothing explaining why.
        // Probing with read_dir surfaces PermissionDenied at startup.
        if let Some(dir) = &self.static_files.dir
            && let Err(err) = std::fs::read_dir(dir)
        {
            return Err(Error::Config(format!(
                "[static] dir {} exists but cannot be read: {err}",
                dir.display()
            )));
        }
        // Uploads are the one thing Lua can write, so the root has to be
        // writable *now* rather than at the first upload, when the only
        // symptom is a 500 on a request nobody can reproduce. Existence
        // is not writability: a mis-owned or read-only-mounted directory
        // passes every check above.
        //
        // `create_new`, never `create`: the upload root may be shared with
        // other local users, and a pre-planted symlink named like the
        // probe would have been *truncated through* by a plain create.
        // The name carries a random component for the same reason — a pid
        // is guessable — and an `AlreadyExists` is retried, not trusted.
        if let Some(dir) = &self.multipart.upload_dir {
            let mut attempts = 0;
            loop {
                let probe = dir.join(format!(
                    ".nitr-write-probe-{}-{}",
                    std::process::id(),
                    uuid::Uuid::now_v7().simple()
                ));
                match std::fs::File::create_new(&probe) {
                    Ok(file) => {
                        drop(file);
                        let _ = std::fs::remove_file(&probe);
                        break;
                    }
                    Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists && attempts < 3 => {
                        attempts += 1;
                    }
                    Err(err) => {
                        return Err(Error::Config(format!(
                            "[multipart] upload_dir {} exists but cannot be written to: {err}",
                            dir.display()
                        )));
                    }
                }
            }
        }
        // An upload root inside the handler's own directory is the
        // upload-to-RCE chain written in configuration: `require`'s search
        // path is pinned there, so an uploaded `.lua` file becomes a
        // module the handler can load — and in dev mode the watcher may
        // reload it without being asked.
        if let Some(dir) = &self.multipart.upload_dir
            && let (Ok(upload), Ok(package)) =
                (dir.canonicalize(), self.package_dir().canonicalize())
            && upload.starts_with(&package)
        {
            return Err(Error::Config(format!(
                "[multipart] upload_dir {} is inside the handler script's directory {}: \
                 `require` is pinned there, so an uploaded file would be a loadable Lua \
                 module. Put the upload root outside it.",
                upload.display(),
                package.display()
            )));
        }
        // An upload root inside the templates directory: an upload whose
        // name matches a template replaces it — stored script injection
        // through the renderer, and in dev mode a reload per upload.
        if let (Some(upload), Some(templates)) = (&self.multipart.upload_dir, &self.templating.dir)
            && let (Ok(upload), Ok(templates)) = (upload.canonicalize(), templates.canonicalize())
            && upload.starts_with(&templates)
        {
            return Err(Error::Config(format!(
                "[multipart] upload_dir {} is inside [templating] dir {}: an uploaded \
                 file could replace a template. Put the upload root outside it.",
                upload.display(),
                templates.display()
            )));
        }
        // A static root that encloses the scripts or the templates serves
        // them: `[static] dir = "."` with `mount = "/"` answers
        // `GET /app.lua` and `GET /nitr.toml` (the env file beside them is
        // covered by the dotfile rule, these two are not).
        if let Some(static_dir) = &self.static_files.dir
            && let Ok(static_dir) = static_dir.canonicalize()
        {
            let enclosed: [(&str, Option<PathBuf>); 2] = [
                (
                    "the handler script's directory",
                    self.package_dir().canonicalize().ok(),
                ),
                (
                    "[templating] dir",
                    self.templating
                        .dir
                        .as_ref()
                        .and_then(|p| p.canonicalize().ok()),
                ),
            ];
            for (what, dir) in enclosed {
                if let Some(dir) = dir
                    && dir.starts_with(&static_dir)
                {
                    return Err(Error::Config(format!(
                        "[static] dir {} encloses {what} ({}): the scripts and configuration \
                         would be served as static files. Point [static] dir at a directory \
                         that holds only public assets.",
                        static_dir.display(),
                        dir.display()
                    )));
                }
            }
        }
        // The database file itself may not exist yet (SQLite creates it),
        // but its parent directory must, SQLite will not create that.
        if let Some(db) = &self.database
            && let Some(parent) = db.path.parent()
            && !parent.as_os_str().is_empty()
            && !parent.is_dir()
        {
            return Err(Error::Config(format!(
                "the database directory {} does not exist (SQLite creates the \
                 file, not its directory)",
                parent.display()
            )));
        }
        Ok(())
    }

    /// Re-anchors the application's relative paths under `root`.
    ///
    /// Used when running from a `nitr build` bundle: the scripts, templates
    /// and static files live in the extraction directory, while the
    /// database path is deliberately left alone, it is mutable state and
    /// stays external to the artifact, resolving against the working
    /// directory as usual. `[multipart] upload_dir` is left alone for the
    /// same reason — uploads outlive the bundle they were received by, and
    /// re-anchoring them inside a `nitr build` extraction directory would
    /// make them vanish on the next deploy. `[tls] cert`/`key` are left
    /// alone for the stronger version of the same reason: a private key
    /// inside a copyable one-file artifact is a private key that leaks
    /// with it.
    pub fn rebase(&mut self, root: &Path) {
        let anchor = |path: &mut PathBuf| {
            if path.is_relative() {
                *path = root.join(&path);
            }
        };
        anchor(&mut self.handler_script);
        if let Some(path) = &mut self.config_script {
            anchor(path);
        }
        if let Some(path) = &mut self.templating.dir {
            anchor(path);
        }
        if let Some(path) = &mut self.static_files.dir {
            anchor(path);
        }
        if let Some(db) = &mut self.database
            && let Some(dir) = &mut db.migrations_dir
        {
            anchor(dir);
        }
        anchor(&mut self.testing.dir);
        if let Some(path) = &mut self.testing.seed {
            anchor(path);
        }
    }

    /// What `nitr test` checks on top of the boot validation: its tests
    /// directory becomes a second `require` root in test states, so it
    /// gets the rule the handler's directory has — an upload root inside
    /// it would make an uploaded `.lua` file a loadable module.
    pub fn validate_testing(&self) -> Result {
        // `nitr test` truncates, seeds and restores its database; pointed
        // at the live one, one `t.db.truncate()` empties production data.
        if let (Some(db), Some(test_db)) = (&self.database, &self.testing.database)
            && resolved_file(&db.path) == resolved_file(test_db)
        {
            return Err(Error::Config(format!(
                "[testing] database {} is [database] path: tests reset, truncate and seed \
                 their database. Name a separate file, or leave [testing] database unset for \
                 a private one per run.",
                test_db.display()
            )));
        }
        if let Some(dir) = &self.multipart.upload_dir
            && let (Ok(upload), Ok(tests)) = (dir.canonicalize(), self.testing.dir.canonicalize())
            && upload.starts_with(&tests)
        {
            return Err(Error::Config(format!(
                "[multipart] upload_dir {} is inside [testing] dir {}: `nitr test` lets test \
                 files `require` from there, so an uploaded file would be a loadable Lua \
                 module. Put the upload root outside it.",
                upload.display(),
                tests.display()
            )));
        }
        Ok(())
    }

    /// The effective configuration after file, environment, and flag
    /// layering, rendered as TOML, the answer to "which value actually
    /// won?".
    pub fn effective_toml(&self) -> Result<String> {
        // Route through JSON first to drop the `None`s: TOML has no null,
        // and an absent key is exactly what an unset option means.
        let json = serde_json::to_value(self)
            .map_err(|err| Error::Config(format!("cannot serialize the configuration: {err}")))?;
        let json = strip_nulls(json);
        toml::to_string_pretty(&json)
            .map_err(|err| Error::Config(format!("cannot render the configuration: {err}")))
    }
}

/// A file's path with its directory canonicalized, so two spellings of one
/// file compare equal even before the file exists.
fn resolved_file(path: &Path) -> PathBuf {
    if let Ok(canonical) = path.canonicalize() {
        return canonical;
    }
    match (path.parent(), path.file_name()) {
        (Some(parent), Some(name)) => {
            let parent = if parent.as_os_str().is_empty() {
                Path::new(".")
            } else {
                parent
            };
            parent
                .canonicalize()
                .map(|dir| dir.join(name))
                .unwrap_or_else(|_| path.to_path_buf())
        }
        _ => path.to_path_buf(),
    }
}

/// Removes `null`s (and the entries they were) from a JSON tree, so the
/// result can render as TOML, which has no null.
fn strip_nulls(value: serde_json::Value) -> serde_json::Value {
    match value {
        serde_json::Value::Object(map) => serde_json::Value::Object(
            map.into_iter()
                .filter(|(_, v)| !v.is_null())
                .map(|(k, v)| (k, strip_nulls(v)))
                .collect(),
        ),
        serde_json::Value::Array(items) => {
            serde_json::Value::Array(items.into_iter().map(strip_nulls).collect())
        }
        other => other,
    }
}

/// Whether a key file's mode keeps it to its owner: no group or other
/// bits at all. `0600`/`0400` pass; `0640`, `0644` and wider do not.
/// The predicate the `[tls] key` permission warning fires on, split out
/// so the mask is pinned by a unit test rather than implied by a log
/// line.
#[cfg(unix)]
pub(crate) fn key_mode_is_private(mode: u32) -> bool {
    mode & 0o077 == 0
}