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
// 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: refusals, warnings, and their wording.

use super::*;

/// Legal-but-suspicious combinations are reported as values rather than
/// logged in place, so they can be asserted without a capturing
/// subscriber.
#[test]
fn suspicious_settings_are_reported_as_warnings() {
    // The default configuration carries exactly one warning, and it is
    // load-bearing rather than noise: no TLS and `[cookies] secure =
    // "auto"` means auth cookies really will ship without `Secure`,
    // which is correct for local development and wrong behind a
    // terminating proxy — the case nothing here can detect. Asserted
    // as a set rather than as "empty" so a *new* warning on the
    // default path is still a visible failure.
    // Whether a cookie ships without `Secure` is decided by the cookie,
    // when one is built: the default configuration itself warns of nothing
    // (a service that never sets a cookie used to be told about them).
    let clean = valid_base();
    let warnings = clean.warnings();
    assert!(warnings.is_empty(), "got: {warnings:?}");

    // …and it goes away the moment the deployment says how it
    // terminates TLS, in either direction.
    let mut secure = valid_base();
    secure.cookies.secure = CookieSecure::Always;
    assert!(
        secure.warnings().is_empty(),
        "`always` is an explicit answer: {:?}",
        secure.warnings()
    );
    let mut tls = valid_base();
    tls.tls.enabled = true;
    assert!(
        !tls.warnings().iter().any(|w| w.contains("Secure")),
        "TLS on satisfies `auto`: {:?}",
        tls.warnings()
    );
    // `dev_mode` is an explicit "I am developing" switch, so it
    // suppresses both warnings; a loopback bind deliberately does not.
    let mut dev = valid_base();
    dev.dev_mode = true;
    assert!(dev.warnings().is_empty(), "got: {:?}", dev.warnings());
    assert_eq!(dev.cookie_insecure_warning(), None);

    // The full policy table, row by row: what boot says, and what the
    // first cookie built without `Secure` says. `"never"` on a plaintext
    // listener is a consistent answer and stays silent; `"never"` *with*
    // TLS is the contradiction worth naming at boot; `"auto"` without
    // TLS cannot see a terminating proxy, so the cookie that ships that
    // way carries the warning.
    for (secure, tls, want_boot, want_issuance) in [
        (CookieSecure::Auto, true, false, false),
        (CookieSecure::Auto, false, false, true),
        (CookieSecure::Always, true, false, false),
        (CookieSecure::Always, false, false, false),
        (CookieSecure::Never, true, true, false),
        (CookieSecure::Never, false, false, false),
    ] {
        let mut cfg = valid_base();
        cfg.cookies.secure = secure;
        cfg.tls.enabled = tls;
        let warned = cfg
            .warnings()
            .iter()
            .any(|w| w.contains("without the `Secure` attribute"));
        assert_eq!(
            warned, want_boot,
            "[cookies] secure = {secure:?} with [tls] enabled = {tls}"
        );
        assert_eq!(
            cfg.cookie_insecure_warning().is_some(),
            want_issuance,
            "[cookies] secure = {secure:?} with [tls] enabled = {tls}"
        );
    }

    // Above the execution budget, but the pool wait stays under it — the
    // pool-wait contradiction is a hard refusal and would mask this.
    let mut cfg = valid_base();
    cfg.lua.exec_timeout_ms = 5_000;
    cfg.limits.pool_wait_ms = 4_000;
    cfg.limits.body_read_ms = 9_000;
    let warnings = cfg.warnings();
    assert!(
        warnings.iter().any(|w| w.contains("body_read_ms")),
        "the body-read/exec-budget warning must survive the move: {warnings:?}"
    );
    cfg.validate().expect("a warning is never a refusal");
}

/// `"debug"` parses as a name but can never produce a state: mlua's safe
/// constructor refuses `StdLib::DEBUG` outright, so accepting it only
/// defers the failure to boot and reports it in terms of an internal
/// Rust constructor. It is refused where the names are mapped, with a
/// message an operator editing `nitr.toml` can act on.
#[test]
fn the_debug_library_is_refused_by_name() {
    let mut lua = LuaConfig::default();
    lua.stdlib.push("debug".into());
    let err = lua
        .parse_stdlib()
        .expect_err("`debug` must not map to a StdLib flag");
    let msg = err.to_string();
    assert!(
        msg.contains("[lua] stdlib") && msg.contains("debug"),
        "the refusal must name the setting and the library: {msg}"
    );
}

/// A config laid out the way a deployment is: the handler script in
/// its own `scripts/` directory, with `uploads/` a sibling rather than
/// a child.
///
/// [`valid_base`] cannot serve here — it writes the handler straight
/// into the system temp directory, which would make `require`'s root
/// `/tmp` and every upload directory on the machine "inside" it. The
/// layout is load-bearing, not incidental.
fn upload_base(label: &str) -> (Config, PathBuf, PathBuf) {
    let base = std::env::temp_dir().join(format!("nitr-up-{label}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&base);
    let scripts = base.join("scripts");
    let uploads = base.join("uploads");
    std::fs::create_dir_all(&scripts).expect("mkdir scripts");
    std::fs::create_dir_all(&uploads).expect("mkdir uploads");
    std::fs::write(scripts.join("app.lua"), "-- test handler").expect("write handler");
    let cfg = Config {
        handler_script: scripts.join("app.lua"),
        ..Config::default()
    };
    (cfg, base, uploads)
}

/// `[multipart] upload_dir` must exist, be a directory, and be
/// writable — checked at startup, because the alternative is a 500 on
/// the first upload that nobody can reproduce.
#[test]
fn the_upload_directory_is_validated_at_startup() {
    let (mut cfg, base, uploads) = upload_base("validated");

    // The sibling layout validates.
    cfg.multipart.upload_dir = Some(uploads.clone());
    cfg.validate().expect("a writable upload dir validates");

    // Missing entirely.
    cfg.multipart.upload_dir = Some(base.join("nope"));
    let err = cfg.validate().expect_err("a missing upload dir");
    let msg = err.to_string();
    assert!(msg.contains("[multipart] upload_dir"), "got: {msg}");
    assert!(msg.contains("does not exist"), "got: {msg}");

    // A file where a directory belongs.
    cfg.multipart.upload_dir = Some(cfg.handler_script.clone());
    let err = cfg.validate().expect_err("a file, not a directory");
    assert!(
        err.to_string().contains("must be a directory"),
        "got: {err}"
    );

    // Present but unwritable: existence is not writability, and the
    // refusal has to name the setting.
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        let locked = base.join("locked");
        std::fs::create_dir_all(&locked).expect("mkdir locked");
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o500)).expect("chmod");
        cfg.multipart.upload_dir = Some(locked.clone());
        // Running as root defeats the permission bits entirely, so the
        // assertion only holds where the mode is actually enforced.
        if std::fs::File::create(locked.join(".probe")).is_err() {
            let err = cfg.validate().expect_err("an unwritable upload dir");
            let msg = err.to_string();
            assert!(msg.contains("[multipart] upload_dir"), "got: {msg}");
            assert!(msg.contains("cannot be written to"), "got: {msg}");
        }
        let _ = std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o700));
    }

    let _ = std::fs::remove_dir_all(&base);
}

/// An upload root under the handler script's directory is the
/// upload-to-RCE chain spelled out in TOML: `require` is pinned there,
/// so an uploaded `.lua` file becomes a loadable module. It refuses to
/// boot rather than warning.
#[test]
fn an_upload_directory_inside_the_require_root_refuses_to_boot() {
    let (mut cfg, base, _) = upload_base("rce-chain");
    // Inside `scripts/`, where `require` is pinned — an uploaded
    // `evil.lua` here is `require("evil")`.
    let inside = base.join("scripts").join("uploads");
    std::fs::create_dir_all(&inside).expect("mkdir");
    cfg.multipart.upload_dir = Some(inside);

    let err = cfg
        .validate()
        .expect_err("an upload dir inside package_dir");
    let msg = err.to_string();
    assert!(msg.contains("[multipart] upload_dir"), "got: {msg}");
    assert!(
        msg.contains("loadable Lua module"),
        "the refusal must say why it matters: {msg}"
    );
    let _ = std::fs::remove_dir_all(&base);
}

/// The same refusal, for a handler script named without any
/// directory at all.
///
/// This is the shape that once slipped through: `"app.lua".parent()`
/// is `Some("")`, which fails to canonicalize, so a guard that
/// canonicalized the raw parent silently skipped itself — while
/// `runtime_opts` resolved the same empty parent to `.` and pinned
/// `require` to the working directory. The check and the runtime
/// disagreed about where modules load from, and the disagreement
/// favoured the attacker. Both now go through
/// [`Config::package_dir`].
#[test]
fn a_bare_handler_script_still_refuses_an_upload_dir_beside_it() {
    let base = std::env::temp_dir().join(format!("nitr-up-bare-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&base);
    std::fs::create_dir_all(base.join("uploads")).expect("mkdir uploads");
    std::fs::write(base.join("app.lua"), "-- handler").expect("write handler");

    // The working directory *is* the require root for a bare name, so
    // the test has to run from `base` for the layout to be the real
    // one rather than a path-string coincidence.
    let previous = std::env::current_dir().expect("cwd");
    std::env::set_current_dir(&base).expect("chdir");

    let cfg = Config {
        handler_script: PathBuf::from("app.lua"),
        multipart: MultipartConfig {
            upload_dir: Some(PathBuf::from("uploads")),
        },
        ..Config::default()
    };
    let result = cfg.validate();

    std::env::set_current_dir(&previous).expect("restore cwd");
    let _ = std::fs::remove_dir_all(&base);

    let err = result.expect_err("a bare handler name must not skip the check");
    assert!(
        err.to_string().contains("loadable Lua module"),
        "got: {err}"
    );
}

/// [`Config::package_dir`] is the single source of the `require` root,
/// and it must agree with what `runtime_opts` actually hands the
/// runtime for every way a handler path can be spelled.
#[test]
fn the_require_root_is_derived_identically_everywhere() {
    for (script, expected) in [
        ("app.lua", "."),
        ("./app.lua", "."),
        ("scripts/app.lua", "scripts"),
        ("/srv/app/scripts/app.lua", "/srv/app/scripts"),
    ] {
        let cfg = Config {
            handler_script: PathBuf::from(script),
            ..Config::default()
        };
        assert_eq!(
            cfg.package_dir(),
            Path::new(expected),
            "package_dir for {script}"
        );
        let opts = cfg.runtime_opts().expect("runtime opts");
        assert_eq!(
            opts.package_dir.as_deref(),
            Some(Path::new(expected)),
            "runtime_opts must pin `require` to the same root for {script}"
        );
    }
}

/// An upload root under `[static] dir` serves uploaded bytes back to
/// browsers. A real deployment shape, so it warns and still boots —
/// the contrast with the `package_dir` case, which refuses.
#[test]
fn an_upload_directory_inside_the_static_root_only_warns() {
    let (mut cfg, base, _) = upload_base("static-overlap");
    // `public/uploads` — served, and written by uploads.
    let public = base.join("public");
    let uploads = public.join("uploads");
    std::fs::create_dir_all(&uploads).expect("mkdir");
    cfg.static_files.dir = Some(public);
    cfg.multipart.upload_dir = Some(uploads);

    let warnings = cfg.warnings();
    assert!(
        warnings.iter().any(|w| w.contains("served back over HTTP")),
        "the overlap must be reported: {warnings:?}"
    );
    cfg.validate().expect("a warning is never a refusal");
    let _ = std::fs::remove_dir_all(&base);
}

/// The `[multipart]` section parses in every build, including one
/// without the `multipart` feature — a config file that stops being
/// readable depending on compilation flags is not portable. Plain
/// `cargo test -p nitr-http` *is* that build (`default = []`).
#[test]
fn the_multipart_section_parses_without_the_multipart_feature() {
    let toml = r#"
        handler_script = "app.lua"
        [multipart]
        upload_dir = "uploads"
    "#;
    let cfg: Config = toml::from_str(toml).expect("[multipart] must always parse");
    assert_eq!(
        cfg.multipart.upload_dir,
        Some(PathBuf::from("uploads")),
        "the value must survive the parse, not just the section"
    );
}

/// A stream holds its state for its whole life: when streams can take
/// every state, open streams make every other request wait
/// `pool_wait_ms` and then 503. The default on one worker is that case.
#[test]
fn stream_slots_for_every_state_warn() {
    for (workers, max_streams) in [(1, None), (1, Some(1)), (4, Some(4))] {
        let mut cfg = valid_base();
        cfg.workers = workers;
        cfg.max_streams = max_streams;
        assert!(
            cfg.streams_warning().is_some(),
            "workers = {workers}, max_streams = {max_streams:?}"
        );
    }
    let mut cfg = valid_base();
    cfg.workers = 4;
    assert_eq!(
        cfg.streams_warning(),
        None,
        "the default keeps a state free"
    );
}

/// `[headers]` values reach every response verbatim, so a name or value
/// that is not a header is refused at boot, naming the entry.
#[test]
fn response_headers_are_validated_at_startup() {
    let mut cfg = valid_base();
    cfg.headers.insert("X-Frame-Options".into(), "DENY".into());
    cfg.validate().expect("a plain header");
    for (name, value) in [("bad name", "x"), ("X-Ok", "line\nbreak")] {
        let mut cfg = valid_base();
        cfg.headers.insert(name.into(), value.into());
        let err = cfg.validate().expect_err(name).to_string();
        assert!(err.contains("[headers]") && err.contains(name), "{err}");
    }
}

/// `[fetch] private_hosts` names hosts, nothing else.
#[test]
fn private_hosts_are_host_names() {
    let mut cfg = valid_base();
    cfg.fetch.private_hosts = vec!["payments".into(), "db.internal".into()];
    cfg.validate().expect("host names");
    for bad in ["http://payments", "payments/charges", ""] {
        let mut cfg = valid_base();
        cfg.fetch.private_hosts = vec![bad.into()];
        let err = cfg.validate().expect_err(bad).to_string();
        assert!(err.contains("[fetch] private_hosts"), "{bad}: {err}");
    }
}

/// The settings a deployment behind a TLS proxy needs are reachable from
/// the environment, and a blank value is unset like every other variable.
#[test]
fn proxy_settings_have_environment_overrides() {
    let mut cfg = valid_base();
    cfg.apply_env_with(&|name| match name {
        "NITR_COOKIES_SECURE" => Some("always".into()),
        "NITR_TRUST_REQUEST_ID" => Some("true".into()),
        "NITR_RATE_LIMIT_TRUST_FORWARDED_FOR" => Some("true".into()),
        _ => None,
    })
    .expect("apply");
    assert_eq!(cfg.cookies.secure, CookieSecure::Always);
    assert!(cfg.trust_request_id);
    assert!(cfg.rate_limit.trust_forwarded_for);
    let mut cfg = valid_base();
    let err = cfg
        .apply_env_with(&|name| (name == "NITR_COOKIES_SECURE").then(|| "maybe".to_string()))
        .expect_err("not a policy")
        .to_string();
    assert!(err.contains("NITR_COOKIES_SECURE"), "{err}");
}

#[test]
fn contradictions_are_startup_errors() {
    let ok = valid_base();
    ok.validate().expect("a sane config validates");

    let mut cfg = valid_base();
    cfg.workers = 2;
    cfg.max_streams = Some(5);
    let err = cfg.validate().expect_err("max_streams > workers");
    assert!(err.to_string().contains("max_streams"), "got: {err}");

    // mlua enforces the allocator limit only when it is above zero.
    let mut cfg = valid_base();
    cfg.lua.memory_limit = 0;
    let err = cfg.validate().expect_err("memory_limit = 0");
    assert!(err.to_string().contains("[lua] memory_limit"), "got: {err}");

    // Hyper's header buffer refuses a longer request line first (431), so
    // a `max_uri_bytes` at or above it can never give its 414.
    let mut cfg = valid_base();
    cfg.limits.max_header_bytes = 16 * 1024;
    cfg.limits.max_uri_bytes = 16 * 1024;
    let err = cfg
        .validate()
        .expect_err("max_uri_bytes >= max_header_bytes");
    assert!(
        err.to_string().contains("[limits] max_uri_bytes"),
        "got: {err}"
    );

    // A limit of zero requests or a zero-second window is not a limit.
    for (requests, window) in [(0, 60), (100, 0)] {
        let mut cfg = valid_base();
        cfg.rate_limit.enabled = true;
        cfg.rate_limit.requests = requests;
        cfg.rate_limit.window = window;
        let err = cfg.validate().expect_err("rate limit of zero");
        assert!(err.to_string().contains("[rate_limit]"), "got: {err}");
    }

    // An origin is a scheme and a host: a path or a trailing slash never
    // matches the browser's `Origin` header.
    for origin in [
        "https://app.example/",
        "https://app.example/app",
        "app.example",
    ] {
        let mut cfg = valid_base();
        cfg.cors.origins = Some(vec![origin.into()]);
        let err = cfg.validate().expect_err(origin);
        assert!(
            err.to_string().contains("[cors] origins"),
            "{origin}: {err}"
        );
    }
    let mut cfg = valid_base();
    cfg.cors.origins = Some(vec!["https://app.example:8443".into(), "*".into()]);
    cfg.validate().expect("well-formed origins");

    // Zero slots answers every stream 503, after its handler already ran.
    let mut cfg = valid_base();
    cfg.max_streams = Some(0);
    let err = cfg.validate().expect_err("max_streams = 0");
    assert!(err.to_string().contains("max_streams = 0"), "got: {err}");

    let mut cfg = valid_base();
    cfg.limits.pool_wait_ms = 60_000;
    cfg.lua.exec_timeout_ms = 5_000;
    let err = cfg.validate().expect_err("pool_wait > exec budget");
    assert!(err.to_string().contains("pool_wait_ms"), "got: {err}");

    let mut cfg = valid_base();
    cfg.health.readiness = cfg.health.liveness.clone();
    let err = cfg.validate().expect_err("identical probe paths");
    assert!(err.to_string().contains("liveness"), "got: {err}");

    let mut cfg = valid_base();
    cfg.health.liveness = "healthz".into();
    let err = cfg.validate().expect_err("path without slash");
    assert!(err.to_string().contains("must start with"), "got: {err}");

    // Disabled health skips its checks entirely.
    let mut cfg = valid_base();
    cfg.health.enabled = false;
    cfg.health.liveness = "not-a-path".into();
    cfg.validate().expect("disabled health is not validated");
}

/// An unknown `[compression]` algorithm is a startup refusal naming
/// the offending value, not a silently un-negotiable encoding.
#[test]
fn unknown_compression_algorithms_are_startup_errors() {
    let mut cfg = valid_base();
    cfg.compression.algorithms = vec!["br".into(), "zstd".into()];
    let err = cfg.validate().expect_err("unknown algorithm");
    let msg = err.to_string();
    assert!(msg.contains("zstd"), "got: {msg}");
    assert!(msg.contains("[compression]"), "got: {msg}");

    // The two supported names still validate, in either order.
    let mut cfg = valid_base();
    cfg.compression.algorithms = vec!["gzip".into(), "br".into()];
    cfg.validate().expect("br and gzip are the supported set");
}

/// `[lua] stdlib` is strict: a misspelled library name refuses to
/// start, naming the string, instead of silently loading nothing.
#[test]
fn unknown_lua_stdlib_names_are_startup_errors() {
    let mut lua = LuaConfig::default();
    lua.stdlib.push("iio".into());
    let err = lua.parse_stdlib().expect_err("unknown stdlib name");
    assert!(err.to_string().contains("`iio`"), "got: {err}");

    // Every documented name parses, including the dangerous opt-ins.
    let all = LuaConfig {
        stdlib: [
            "coroutine",
            "table",
            "io",
            "os",
            "string",
            "utf8",
            "math",
            "package",
        ]
        .map(String::from)
        .to_vec(),
        ..LuaConfig::default()
    };
    let libs = all.parse_stdlib().expect("all loadable names");
    assert!(libs.contains(mlua::StdLib::IO));
    assert!(libs.contains(mlua::StdLib::PACKAGE));
}

#[test]
fn missing_paths_are_named_at_startup() {
    let mut cfg = valid_base();
    cfg.handler_script = PathBuf::from("/nonexistent/app.lua");
    let err = cfg.validate().expect_err("missing handler");
    assert!(err.to_string().contains("handler_script"), "got: {err}");

    let mut cfg = valid_base();
    cfg.templating.dir = Some(PathBuf::from("/nonexistent/templates"));
    let err = cfg.validate().expect_err("missing templates");
    assert!(err.to_string().contains("[templating] dir"), "got: {err}");

    // A file where a directory belongs is as wrong as nothing at all.
    let mut cfg = valid_base();
    cfg.templating.dir = Some(cfg.handler_script.clone());
    let err = cfg.validate().expect_err("file as the templating dir");
    assert!(err.to_string().contains("directory"), "got: {err}");

    // The database file may not exist yet, but its directory must.
    let mut cfg = valid_base();
    cfg.database = Some(DatabaseConfig::new("/nonexistent/dir/app.db"));
    let err = cfg.validate().expect_err("missing db dir");
    assert!(err.to_string().contains("database directory"), "got: {err}");
}

#[test]
fn unknown_keys_are_rejected_not_ignored() {
    let path = write_temp_config("typo.toml", "max_body_byte = 1\n");
    let err = Config::from_file(&path).expect_err("unknown key");
    assert!(err.to_string().contains("max_body_byte"), "got: {err}");

    // Inside a section too.
    let path = write_temp_config("typo2.toml", "[limits]\nmax_body_byte = 1\n");
    let err = Config::from_file(&path).expect_err("unknown section key");
    assert!(err.to_string().contains("max_body_byte"), "got: {err}");
    std::fs::remove_file(&path).ok();
}

proptest::proptest! {
    /// Property: over arbitrary numeric limit combinations, validation
    /// is total — it accepts, or refuses with an error naming a
    /// setting; it never panics — and the pool-wait/exec-budget
    /// contradiction is always the refusal it promises.
    #[test]
    fn prop_limit_validation_is_total_and_names_the_setting(
        workers in 1usize..8,
        max_streams in proptest::option::of(0usize..8),
        pool_wait_ms in 0u64..100_000,
        exec_timeout_ms in 0u64..100_000,
        body_read_ms in 0u64..100_000,
        header_read_ms in 0u64..100_000,
    ) {
        let mut cfg = valid_base();
        cfg.workers = workers;
        cfg.max_streams = max_streams;
        cfg.limits.pool_wait_ms = pool_wait_ms;
        cfg.limits.body_read_ms = body_read_ms;
        cfg.limits.header_read_ms = header_read_ms;
        cfg.lua.exec_timeout_ms = exec_timeout_ms;

        match cfg.validate() {
            Ok(()) => {
                proptest::prop_assert!(
                    !(pool_wait_ms > exec_timeout_ms
                        && pool_wait_ms != 0
                        && exec_timeout_ms != 0),
                    "the pool-wait contradiction must refuse"
                );
            }
            Err(err) => {
                let msg = err.to_string();
                proptest::prop_assert!(
                    msg.contains("pool_wait_ms") || msg.contains("max_streams"),
                    "a refusal must name the offending setting: {msg}"
                );
            }
        }
    }
}

/// A proxy resolves the target itself, which sidesteps the resolver guard:
/// with `fetch` enabled, a proxy needs an allow-list or an explicit
/// private-networks decision before the server starts.
#[test]
fn a_proxy_without_an_allow_list_is_refused_when_fetch_is_enabled() {
    let mut cfg = valid_base();
    cfg.std.features = Some(vec!["fetch".into()]);
    cfg.fetch.proxy = Some("http://proxy.internal:3128".into());
    let err = cfg.validate().expect_err("proxy without an allow-list");
    assert!(err.to_string().contains("allowed_hosts"), "got: {err}");

    // Either remedy is accepted.
    cfg.fetch.allowed_hosts = Some(vec!["api.example".into()]);
    cfg.validate().expect("an allow-list satisfies the rule");
    cfg.fetch.allowed_hosts = None;
    cfg.fetch.allow_private_networks = true;
    cfg.validate()
        .expect("an explicit trust decision satisfies the rule");

    // And without the fetch builtin a proxy setting proxies nothing.
    cfg.fetch.allow_private_networks = false;
    cfg.std.features = None;
    cfg.validate().expect("no fetch, no rule");
}