1use std::path::{Path, PathBuf};
10
11use nitr_core::{Error, Result};
12
13use super::Config;
14
15fn 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
29const MAX_WORKERS: usize = 4096;
32
33const MAX_CONNECTIONS: usize = 1 << 20;
37
38impl Config {
39 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 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 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 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 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 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 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 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 pub(crate) fn warnings(&self) -> Vec<String> {
268 let mut out = Vec::new();
269 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 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 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 #[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 out
343 }
344
345 fn validate_tls(&self) -> Result {
353 if !self.tls.enabled {
354 return Ok(());
359 }
360 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 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 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 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 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 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 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 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 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 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 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 pub fn validate_testing(&self) -> Result {
761 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 pub fn effective_toml(&self) -> Result<String> {
792 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
802fn 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
824fn 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#[cfg(unix)]
847pub(crate) fn key_mode_is_private(mode: u32) -> bool {
848 mode & 0o077 == 0
849}