1use std::collections::BTreeMap;
8use std::fmt;
9use std::path::Path;
10use std::time::Duration;
11
12use datumesh_core::json::{self, Value};
13use datumesh_core::lexical;
14
15use crate::apikeys::ApiKeys;
16
17pub const DEFAULT_BUDGET: Duration = Duration::from_secs(1);
19
20pub const DEFAULT_BARRIER_TIMEOUT: Duration = Duration::from_secs(5);
22
23pub fn barrier_timeout_of(v: Option<String>) -> Result<Duration, ConfigError> {
25 match v {
26 None => Ok(DEFAULT_BARRIER_TIMEOUT),
27 Some(v) => match v.parse::<u64>() {
28 Ok(n) if n > 0 => Ok(Duration::from_millis(n)),
29 _ => Err(ConfigError::new("DATUMESH_BARRIER_TIMEOUT_MS", format!("not a positive number: {v}"))),
30 },
31 }
32}
33pub const DEFAULT_POOL_SIZE: usize = 32;
36pub const DEFAULT_BATCH_MAX: usize = 1000;
38pub const DEFAULT_SLICE_PAGE: usize = 1000;
40
41pub fn catalog_max_of(v: Option<String>) -> Result<usize, ConfigError> {
44 match v {
45 None => Ok(crate::catalog_build::DEFAULT_CATALOG_MAX),
46 Some(v) => match v.parse::<usize>() {
47 Ok(n) if n > 0 => Ok(n),
48 _ => Err(ConfigError::new("DATUMESH_CATALOG_MAX", format!("not a positive number: {v}"))),
49 },
50 }
51}
52pub const MAX_SLICE_PAGE: usize = 10_000;
54pub const MAX_SLICE_MEMBERS: usize = 1_048_576;
56
57#[non_exhaustive]
60#[derive(Clone, Debug, PartialEq, Eq)]
61pub struct RateLimits {
62 pub enabled: bool,
64 pub per_ip: u32,
66 pub ip_burst: u32,
68 pub per_key: u32,
71 pub verify_per_ip: u32,
73 pub calc_per_ip: u32,
76 pub batch_cells_per_token: u32,
79 pub series_per_ip: u32,
82 pub keys_per_ip: u32,
85}
86
87impl Default for RateLimits {
88 fn default() -> Self {
89 RateLimits {
90 enabled: true,
91 per_ip: 60,
92 ip_burst: 120,
93 per_key: 600,
94 verify_per_ip: 60,
95 calc_per_ip: 30,
96 batch_cells_per_token: 50,
97 series_per_ip: 30,
98 keys_per_ip: 5,
99 }
100 }
101}
102
103#[non_exhaustive]
106#[derive(Clone, Debug, PartialEq, Eq)]
107pub struct Ttls {
108 pub key_doc: Duration,
111 pub key_refetch: Duration,
113 pub mesh_doc: Duration,
115 pub binding: Duration,
118 pub current: Duration,
121 pub latest_max_age: Duration,
123 pub job: Duration,
126}
127
128impl Default for Ttls {
129 fn default() -> Self {
130 Ttls {
131 key_doc: Duration::from_secs(300),
132 key_refetch: Duration::from_secs(10),
133 mesh_doc: Duration::from_secs(300),
134 binding: Duration::from_secs(60),
135 current: Duration::from_secs(60),
136 latest_max_age: Duration::from_secs(10),
137 job: Duration::from_secs(300),
138 }
139 }
140}
141
142#[non_exhaustive]
144#[derive(Clone, Debug, PartialEq, Eq)]
145pub enum Rule {
146 Principals(Vec<String>),
149 Price {
152 amount: String,
154 currency: String,
156 },
157}
158
159#[non_exhaustive]
161#[derive(Clone, Debug, Default, PartialEq, Eq)]
162pub struct Policy {
163 pub rules: BTreeMap<String, Rule>,
165}
166
167impl Policy {
168 pub fn rule(&self, fn_name: &str) -> Option<&Rule> {
170 self.rules.get(fn_name)
171 }
172
173 pub fn from_json(bytes: &[u8]) -> Result<Policy, ConfigError> {
175 let v = json::parse(bytes).map_err(|e| ConfigError::new("policy", e.to_string()))?;
176 let mut rules = BTreeMap::new();
177 for (name, r) in v.as_object().ok_or_else(|| ConfigError::new("policy", "not an object"))? {
178 lexical::check_function_name(name, "$").map_err(|e| ConfigError::new("policy", e.to_string()))?;
179 let rule = if let Some(Value::Array(ps)) = r.get("principals") {
180 Rule::Principals(
181 ps.iter()
182 .map(|p| p.as_str().map(str::to_string).ok_or_else(|| ConfigError::new("policy", "principal")))
183 .collect::<Result<_, _>>()?,
184 )
185 } else if let Some(p) = r.get("price") {
186 let amount =
187 p.get("amount").and_then(Value::as_str).ok_or_else(|| ConfigError::new("policy", "amount"))?;
188 let currency =
189 p.get("currency").and_then(Value::as_str).ok_or_else(|| ConfigError::new("policy", "currency"))?;
190 lexical::check_number(amount, "$").map_err(|e| ConfigError::new("policy", e.to_string()))?;
191 if amount.starts_with('-') || amount == "0" || !lexical::is_currency(currency) {
192 return Err(ConfigError::new("policy", format!("price of {name}")));
193 }
194 Rule::Price { amount: amount.to_string(), currency: currency.to_string() }
195 } else {
196 return Err(ConfigError::new("policy", format!("rule of {name}")));
197 };
198 rules.insert(name.clone(), rule);
199 }
200 Ok(Policy { rules })
201 }
202}
203
204#[non_exhaustive]
206#[derive(Clone, Debug)]
207pub struct Config {
208 pub host: String,
211 pub base_url: Option<String>,
230 pub namespaces: Vec<String>,
233 pub budget: Duration,
235 pub pool_size: usize,
237 pub batch_max: usize,
239 pub test_cells: bool,
242 pub slice_page: usize,
244 pub slice_max: usize,
246 pub catalog_max: usize,
248 pub explain_depth: usize,
250 pub max_jobs: usize,
252 pub manifest_store_max: usize,
256 pub barrier_timeout: Duration,
259 pub rate: RateLimits,
261 pub ttl: Ttls,
263 pub trust_proxy: bool,
266 pub cross_mesh: bool,
268 pub cross_mesh_hosts: Option<Vec<String>>,
271 pub peers: BTreeMap<String, String>,
274 pub peer_timeout: Duration,
276 pub aliases: BTreeMap<String, String>,
278 pub policy: Policy,
280 pub catalog: BTreeMap<String, String>,
282 pub embed_url: Option<String>,
285 pub api_keys: ApiKeys,
287 pub publish_domains: PublishDomains,
290 pub log_dir: Option<std::path::PathBuf>,
293 pub(crate) series: Vec<crate::series::SeriesPage>,
295 pub key_names: bool,
299 pub key_challenge_ttl: Duration,
301 pub contact: Option<String>,
304 pub series_first_build_delay: Duration,
307 pub series_refresh: Duration,
309 pub catalog_first_build_delay: Duration,
312 pub catalog_refresh: Duration,
314 pub index_first_build_delay: Duration,
317 pub index_secs: Duration,
320 pub index_class_max: usize,
324 pub index_max: usize,
326 pub find_first_build_delay: Duration,
329 pub value_counts_refresh: Duration,
332 pub dictionary_max: usize,
335 pub listed_meshes: Vec<String>,
339 pub listing_interval: Duration,
341 pub listing_first_delay: Duration,
343}
344
345#[non_exhaustive]
349#[derive(Clone, Debug, PartialEq, Eq, Default)]
350pub enum PublishDomains {
351 #[default]
353 Own,
354 Hosts(Vec<String>),
356 Any,
358}
359
360impl PublishDomains {
361 pub fn parse(v: &str) -> Result<PublishDomains, ConfigError> {
364 let v = v.trim();
365 if v.is_empty() {
366 return Ok(PublishDomains::Own);
367 }
368 if v == "*" {
369 return Ok(PublishDomains::Any);
370 }
371 let mut hosts = Vec::new();
372 for h in v.split(',').map(str::trim).filter(|h| !h.is_empty()) {
373 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("DATUMESH_PUBLISH_DOMAINS", e.to_string()))?;
374 hosts.push(h.to_string());
375 }
376 Ok(if hosts.is_empty() { PublishDomains::Own } else { PublishDomains::Hosts(hosts) })
377 }
378
379 pub fn allows(&self, host: &str) -> bool {
381 match self {
382 PublishDomains::Own => false,
383 PublishDomains::Hosts(h) => h.iter().any(|x| x == host),
384 PublishDomains::Any => true,
385 }
386 }
387}
388
389impl Config {
390 pub fn new(host: impl Into<String>) -> Config {
392 let host = host.into();
393 Config {
394 namespaces: vec![host.clone()],
395 host,
396 base_url: None,
397 budget: DEFAULT_BUDGET,
398 pool_size: DEFAULT_POOL_SIZE,
399 batch_max: DEFAULT_BATCH_MAX,
400 test_cells: false,
401 slice_page: DEFAULT_SLICE_PAGE,
402 slice_max: MAX_SLICE_MEMBERS,
403 catalog_max: crate::catalog_build::DEFAULT_CATALOG_MAX,
404 explain_depth: 4,
405 max_jobs: 10_000,
406 manifest_store_max: 0,
407 barrier_timeout: DEFAULT_BARRIER_TIMEOUT,
408 rate: RateLimits::default(),
409 ttl: Ttls::default(),
410 trust_proxy: false,
411 cross_mesh: true,
412 cross_mesh_hosts: None,
413 peers: BTreeMap::new(),
414 peer_timeout: Duration::from_secs(10),
415 aliases: BTreeMap::new(),
416 policy: Policy::default(),
417 catalog: BTreeMap::new(),
418 embed_url: None,
419 api_keys: ApiKeys::default(),
420 publish_domains: PublishDomains::Own,
421 key_names: false,
422 key_challenge_ttl: Duration::from_secs(300),
423 contact: None,
424 series_first_build_delay: Duration::ZERO,
425 series_refresh: Duration::from_secs(300),
426 catalog_first_build_delay: Duration::ZERO,
427 catalog_refresh: Duration::from_secs(300),
428 index_first_build_delay: Duration::ZERO,
429 index_secs: Duration::from_secs(300),
430 index_class_max: 50_000,
431 index_max: 200_000,
432 find_first_build_delay: Duration::ZERO,
433 value_counts_refresh: Duration::from_secs(3600),
434 dictionary_max: 1000,
435 listed_meshes: Vec::new(),
436 listing_interval: crate::listing::DEFAULT_INTERVAL,
437 listing_first_delay: Duration::ZERO,
438 log_dir: None,
439 series: Vec::new(),
440 }
441 }
442
443 pub fn with_base_url(mut self, url: impl Into<String>) -> Config {
446 self.base_url = Some(url.into());
447 self
448 }
449
450 pub fn from_env() -> Result<Config, ConfigError> {
454 Config::from_vars(|k| std::env::var(k).ok())
455 }
456
457 pub fn from_vars(get: impl Fn(&str) -> Option<String>) -> Result<Config, ConfigError> {
459 let host = get("DATUMESH_HOST").ok_or_else(|| ConfigError::new("DATUMESH_HOST", "not set"))?;
460 let mut c = Config::new(host);
461 if let Some(v) = get("DATUMESH_BASE_URL").filter(|v| !v.is_empty()) {
462 c.base_url = Some(v);
463 }
464 if let Some(v) = get("DATUMESH_NAMESPACES") {
465 c.namespaces = v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
466 }
467 let ms = |k: &str, d: Duration| -> Result<Duration, ConfigError> {
468 match get(k) {
469 Some(v) => v.parse::<u64>().map(Duration::from_millis).map_err(|e| ConfigError::new(k, e.to_string())),
470 None => Ok(d),
471 }
472 };
473 let secs = |k: &str, d: Duration| -> Result<Duration, ConfigError> {
474 match get(k) {
475 Some(v) => v.parse::<u64>().map(Duration::from_secs).map_err(|e| ConfigError::new(k, e.to_string())),
476 None => Ok(d),
477 }
478 };
479 let num = |k: &str, d: usize| -> Result<usize, ConfigError> {
480 match get(k) {
481 Some(v) => v.parse::<usize>().map_err(|e| ConfigError::new(k, e.to_string())),
482 None => Ok(d),
483 }
484 };
485 let flag = |k: &str, d: bool| -> Result<bool, ConfigError> {
486 match get(k).as_deref() {
487 None => Ok(d),
488 Some("1" | "true" | "yes") => Ok(true),
489 Some("0" | "false" | "no") => Ok(false),
490 Some(v) => Err(ConfigError::new(k, format!("not a boolean: {v}"))),
491 }
492 };
493 c.budget = ms("DATUMESH_BUDGET_MS", c.budget)?;
494 c.pool_size = num("DATUMESH_POOL_SIZE", c.pool_size)?;
495 c.batch_max = num("DATUMESH_BATCH_MAX", c.batch_max)?;
496 c.test_cells = flag("DATUMESH_TEST_CELLS", c.test_cells)?;
497 c.slice_page = num("DATUMESH_SLICE_PAGE", c.slice_page)?;
498 c.slice_max = num("DATUMESH_SLICE_MAX", c.slice_max)?;
499 c.catalog_max = catalog_max_of(get("DATUMESH_CATALOG_MAX"))?;
500 c.explain_depth = num("DATUMESH_EXPLAIN_DEPTH", c.explain_depth)?;
501 c.max_jobs = num("DATUMESH_MAX_JOBS", c.max_jobs)?;
502 c.manifest_store_max = num("DATUMESH_MANIFEST_STORE_MAX", c.manifest_store_max)?;
503 c.barrier_timeout = barrier_timeout_of(get("DATUMESH_BARRIER_TIMEOUT_MS"))?;
504 c.trust_proxy = flag("DATUMESH_TRUST_PROXY", c.trust_proxy)?;
505 c.cross_mesh = flag("DATUMESH_CROSS_MESH", c.cross_mesh)?;
506 c.rate.enabled = flag("DATUMESH_RATE_LIMITS", c.rate.enabled)?;
507 c.rate.per_ip = num("DATUMESH_RATE_PER_IP", c.rate.per_ip as usize)? as u32;
508 c.rate.ip_burst = num("DATUMESH_RATE_IP_BURST", c.rate.ip_burst as usize)? as u32;
509 c.rate.per_key = num("DATUMESH_RATE_PER_KEY", c.rate.per_key as usize)? as u32;
510 c.rate.verify_per_ip = num("DATUMESH_RATE_VERIFY_PER_IP", c.rate.verify_per_ip as usize)? as u32;
511 c.rate.series_per_ip = num("DATUMESH_RATE_SERIES_PER_IP", c.rate.series_per_ip as usize)? as u32;
512 c.rate.calc_per_ip = num("DATUMESH_RATE_CALC_PER_IP", c.rate.calc_per_ip as usize)? as u32;
513 c.rate.keys_per_ip = num("DATUMESH_RATE_KEYS_PER_IP", c.rate.keys_per_ip as usize)? as u32;
514 c.key_names = get("DATUMESH_KEY_NAMES").as_deref() == Some("1");
516 c.key_challenge_ttl = secs("DATUMESH_KEY_CHALLENGE_TTL_SECS", c.key_challenge_ttl)?;
517 c.contact = get("DATUMESH_CONTACT").map(|v| v.trim().to_string()).filter(|v| !v.is_empty());
518 c.series_first_build_delay = secs("DATUMESH_SERIES_FIRST_BUILD_DELAY_SECS", c.series_first_build_delay)?;
519 c.series_refresh = secs("DATUMESH_SERIES_REFRESH_SECS", c.series_refresh)?;
520 c.catalog_first_build_delay = secs("DATUMESH_CATALOG_FIRST_BUILD_DELAY_SECS", c.catalog_first_build_delay)?;
521 c.catalog_refresh = secs("DATUMESH_CATALOG_REFRESH_SECS", c.catalog_refresh)?;
522 c.index_first_build_delay = secs("DATUMESH_INDEX_FIRST_BUILD_DELAY_SECS", c.index_first_build_delay)?;
523 c.index_secs = secs("DATUMESH_INDEX_SECS", c.index_secs)?;
524 c.index_class_max = num("DATUMESH_INDEX_CLASS_MAX", c.index_class_max)?.max(1);
525 c.index_max = num("DATUMESH_INDEX_MAX", c.index_max)?.max(1);
526 c.find_first_build_delay = secs("DATUMESH_FIND_FIRST_BUILD_DELAY_SECS", c.find_first_build_delay)?;
527 c.value_counts_refresh = secs("DATUMESH_VALUE_COUNTS_SECS", c.value_counts_refresh)?;
528 c.dictionary_max = num("DATUMESH_DICTIONARY_MAX", c.dictionary_max)?;
529 c.ttl.key_doc = secs("DATUMESH_TTL_KEY_DOC", c.ttl.key_doc)?;
530 c.ttl.mesh_doc = secs("DATUMESH_TTL_MESH_DOC", c.ttl.mesh_doc)?;
531 c.ttl.binding = secs("DATUMESH_TTL_BINDING", c.ttl.binding)?;
532 c.ttl.current = secs("DATUMESH_TTL_CURRENT", c.ttl.current)?;
533 c.ttl.latest_max_age = secs("DATUMESH_LATEST_MAX_AGE", c.ttl.latest_max_age)?;
534 c.ttl.job = secs("DATUMESH_JOB_TTL", c.ttl.job)?;
535 c.peer_timeout = ms("DATUMESH_PEER_TIMEOUT_MS", c.peer_timeout)?;
536 if let Some(v) = get("DATUMESH_CROSS_MESH_HOSTS") {
537 c.cross_mesh_hosts = Some(v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect());
538 }
539 if let Some(v) = get("DATUMESH_PEERS") {
540 for pair in v.split(',').map(str::trim).filter(|s| !s.is_empty()) {
541 let (h, o) =
542 pair.split_once('=').ok_or_else(|| ConfigError::new("DATUMESH_PEERS", "host=origin pairs"))?;
543 c.peers.insert(h.trim().to_string(), o.trim().trim_end_matches('/').to_string());
544 }
545 }
546 if let Some(v) = get("DATUMESH_LISTED_MESHES") {
547 for h in v.split(',').map(str::trim).filter(|s| !s.is_empty()) {
549 if !c.listed_meshes.iter().any(|x| x == h) {
550 c.listed_meshes.push(h.to_string());
551 }
552 }
553 }
554 c.listing_interval = secs("DATUMESH_LISTING_INTERVAL_SECS", c.listing_interval)?;
555 c.listing_first_delay = secs("DATUMESH_LISTING_FIRST_DELAY_SECS", c.listing_first_delay)?;
556 if let Some(p) = get("DATUMESH_ALIASES_FILE") {
557 c.aliases = string_map(&read_file(&p)?, "DATUMESH_ALIASES_FILE")?;
558 }
559 if let Some(p) = get("DATUMESH_CATALOG_FILE") {
560 c.catalog = string_map(&read_file(&p)?, "DATUMESH_CATALOG_FILE")?;
561 }
562 if let Some(v) = get("DATUMESH_EMBED_URL").filter(|v| !v.trim().is_empty()) {
563 c.embed_url = Some(v.trim().trim_end_matches('/').to_string());
564 }
565 if let Some(p) = get("DATUMESH_POLICY_FILE") {
566 c.policy = Policy::from_json(&read_file(&p)?)?;
567 }
568 if let Some(p) = get("DATUMESH_API_KEYS_FILE") {
569 c.api_keys = ApiKeys::parse(&read_secret_file(Path::new(&p))?)?;
570 }
571 c.publish_domains = PublishDomains::parse(&get("DATUMESH_PUBLISH_DOMAINS").unwrap_or_default())?;
572 if let Some(p) = get("DATUMESH_SERIES_FILE").filter(|p| !p.trim().is_empty()) {
573 c.series = crate::series::parse(&read_file(&p)?)?;
574 }
575 if let Some(d) = get("DATUMESH_LOG_DIR").filter(|d| !d.trim().is_empty()) {
576 c.log_dir = Some(std::path::PathBuf::from(d));
577 }
578 c.check()?;
579 Ok(c)
580 }
581
582 pub fn check(&self) -> Result<(), ConfigError> {
585 lexical::check_dns_name(&self.host, "$").map_err(|e| ConfigError::new("host", e.to_string()))?;
586 if self.series_refresh < Duration::from_secs(1) {
587 return Err(ConfigError::new("DATUMESH_SERIES_REFRESH_SECS", "at least 1 second"));
588 }
589 if self.catalog_refresh < Duration::from_secs(1) {
590 return Err(ConfigError::new("DATUMESH_CATALOG_REFRESH_SECS", "at least 1 second"));
591 }
592 if self.value_counts_refresh < Duration::from_secs(1) {
593 return Err(ConfigError::new("DATUMESH_VALUE_COUNTS_SECS", "at least 1 second"));
594 }
595 if self.dictionary_max == 0 {
596 return Err(ConfigError::new("DATUMESH_DICTIONARY_MAX", "at least 1"));
597 }
598 if let Some(c) = &self.contact {
599 if c.chars().any(|ch| ch.is_whitespace() || ch.is_control()) {
600 return Err(ConfigError::new("DATUMESH_CONTACT", "an address without spaces"));
601 }
602 }
603 if let Some(u) = &self.base_url {
604 check_base_url(&self.host, u).map_err(|e| ConfigError::new("base URL", format!("{u}: {e}")))?;
605 }
606 for h in &self.namespaces {
607 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("namespaces", e.to_string()))?;
608 }
609 for (h, o) in &self.peers {
610 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("peers", e.to_string()))?;
611 if !(o.starts_with("http://") || o.starts_with("https://")) {
612 return Err(ConfigError::new("peers", format!("{o}: not an http(s) origin")));
613 }
614 }
615 for (a, n) in &self.aliases {
616 lexical::check_function_name(n, "$").map_err(|e| ConfigError::new("aliases", format!("{a}: {e}")))?;
617 }
618 if self.pool_size == 0 || self.batch_max == 0 || self.slice_page == 0 || self.slice_max == 0 {
619 return Err(ConfigError::new("sizes", "the pool, batch and slice bounds must be positive"));
620 }
621 if self.ttl.job < Duration::from_secs(300) {
622 return Err(ConfigError::new("job TTL", "at least 300 s (SPEC 5.5)"));
623 }
624 if self.budget.is_zero() {
625 return Err(ConfigError::new("budget", "must be positive"));
626 }
627 if self.listing_interval < Duration::from_secs(1) {
628 return Err(ConfigError::new("DATUMESH_LISTING_INTERVAL_SECS", "at least 1 second"));
629 }
630 if self.listed_meshes.len() > crate::listing::MAX_HOSTS {
631 return Err(ConfigError::new(
632 "DATUMESH_LISTED_MESHES",
633 format!("at most {} hosts", crate::listing::MAX_HOSTS),
634 ));
635 }
636 for h in &self.listed_meshes {
637 lexical::check_dns_name(h, "$")
638 .map_err(|e| ConfigError::new("DATUMESH_LISTED_MESHES", format!("{h}: {e}")))?;
639 if self.namespaces.contains(h) {
640 return Err(ConfigError::new("DATUMESH_LISTED_MESHES", format!("{h} is hosted here (a namespace)")));
641 }
642 if self.publish_domains.allows(h) {
644 return Err(ConfigError::new(
645 "DATUMESH_LISTED_MESHES",
646 format!("{h} may publish here (DATUMESH_PUBLISH_DOMAINS): a listed host publishes elsewhere"),
647 ));
648 }
649 if self.cross_mesh_hosts.as_ref().is_some_and(|hosts| hosts.iter().any(|x| x == h)) {
650 return Err(ConfigError::new(
651 "DATUMESH_LISTED_MESHES",
652 format!("{h} is resolved here (DATUMESH_CROSS_MESH_HOSTS): a listed host is not one"),
653 ));
654 }
655 }
656 Ok(())
657 }
658
659 pub fn owns(&self, host: &str) -> bool {
661 self.namespaces.iter().any(|h| h == host)
662 }
663
664 pub fn origin(&self) -> String {
666 format!("https://{}", self.host)
667 }
668
669 pub fn mesh_document_base(&self) -> String {
672 self.base_url.clone().unwrap_or_else(|| self.origin())
673 }
674}
675
676#[non_exhaustive]
678#[derive(Clone, Copy, Debug, PartialEq, Eq)]
679pub enum BaseUrlError {
680 Scheme,
682 HttpRootedHost,
685 HttpNotLoopback,
688 Host,
691 Port,
693 Path,
695 TrailingSlash,
697 Query,
699 Fragment,
701}
702
703impl fmt::Display for BaseUrlError {
704 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
705 f.write_str(match self {
706 BaseUrlError::Scheme => "not an https:// or http:// URL",
707 BaseUrlError::HttpRootedHost => "http:// is for an unrooted host (under .invalid) only",
708 BaseUrlError::HttpNotLoopback => "http:// is for 127.0.0.1, [::1] and localhost only",
709 BaseUrlError::Host => "not a host name, IPv4 address or bracketed IPv6 address",
710 BaseUrlError::Port => "not a port from 1 to 65535",
711 BaseUrlError::Path => "a path (the base URL is a scheme, a host and a port)",
712 BaseUrlError::TrailingSlash => "a trailing slash",
713 BaseUrlError::Query => "a query",
714 BaseUrlError::Fragment => "a fragment",
715 })
716 }
717}
718
719impl std::error::Error for BaseUrlError {}
720
721pub fn check_base_url(host: &str, url: &str) -> Result<(), BaseUrlError> {
728 let mesh_host = host;
729 let (http, rest) = if let Some(r) = url.strip_prefix("https://") {
730 (false, r)
731 } else if let Some(r) = url.strip_prefix("http://") {
732 (true, r)
733 } else {
734 return Err(BaseUrlError::Scheme);
735 };
736 if rest.contains('#') {
737 return Err(BaseUrlError::Fragment);
738 }
739 if rest.contains('?') {
740 return Err(BaseUrlError::Query);
741 }
742 let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
743 match path {
744 "" => {}
745 "/" => return Err(BaseUrlError::TrailingSlash),
746 _ => return Err(BaseUrlError::Path),
747 }
748 if authority.contains('@') {
749 return Err(BaseUrlError::Host);
750 }
751 let (host, port) = if let Some(r) = authority.strip_prefix('[') {
752 let (inside, after) = r.split_once(']').ok_or(BaseUrlError::Host)?;
753 inside.parse::<std::net::Ipv6Addr>().map_err(|_| BaseUrlError::Host)?;
754 let port = match after {
755 "" => None,
756 p => Some(p.strip_prefix(':').ok_or(BaseUrlError::Host)?),
757 };
758 (&authority[..inside.len() + 2], port)
759 } else {
760 let (host, port) = match authority.split_once(':') {
761 Some((h, p)) => (h, Some(p)),
762 None => (authority, None),
763 };
764 if host.parse::<std::net::Ipv4Addr>().is_err() && !is_dns_name(host) {
765 return Err(BaseUrlError::Host);
766 }
767 (host, port)
768 };
769 if let Some(p) = port {
770 let ok = !p.is_empty() && p.len() <= 5 && p.bytes().all(|b| b.is_ascii_digit());
771 if !ok || !(1..=65535).contains(&p.parse::<u32>().unwrap_or(0)) {
772 return Err(BaseUrlError::Port);
773 }
774 }
775 if http && !is_unrooted(mesh_host) {
776 return Err(BaseUrlError::HttpRootedHost);
777 }
778 if http && !matches!(host, "127.0.0.1" | "[::1]" | "localhost") {
779 return Err(BaseUrlError::HttpNotLoopback);
780 }
781 Ok(())
782}
783
784pub fn is_unrooted(host: &str) -> bool {
787 host.rsplit('.').next() == Some("invalid")
788}
789
790fn is_dns_name(h: &str) -> bool {
793 !h.is_empty()
794 && h.len() <= 253
795 && h.split('.').all(|l| {
796 !l.is_empty()
797 && l.len() <= 63
798 && !l.starts_with('-')
799 && !l.ends_with('-')
800 && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
801 })
802}
803
804fn string_map(bytes: &[u8], what: &str) -> Result<BTreeMap<String, String>, ConfigError> {
805 let v = json::parse(bytes).map_err(|e| ConfigError::new(what, e.to_string()))?;
806 let mut out = BTreeMap::new();
807 for (k, x) in v.as_object().ok_or_else(|| ConfigError::new(what, "not an object"))? {
808 let s = x.as_str().ok_or_else(|| ConfigError::new(what, format!("{k}: not a string")))?;
809 out.insert(k.clone(), s.to_string());
810 }
811 Ok(out)
812}
813
814fn read_file(path: &str) -> Result<Vec<u8>, ConfigError> {
815 std::fs::read(path).map_err(|e| ConfigError::new(path, e.to_string()))
816}
817
818pub fn read_secret_file(path: &Path) -> Result<Vec<u8>, ConfigError> {
821 let what = path.display().to_string();
822 let meta = std::fs::metadata(path).map_err(|e| ConfigError::new(&what, e.to_string()))?;
823 #[cfg(unix)]
824 {
825 use std::os::unix::fs::PermissionsExt;
826 let mode = meta.permissions().mode() & 0o777;
827 if mode & 0o077 != 0 {
828 return Err(ConfigError::new(&what, format!("mode {mode:o}: a secret file must be 0600")));
829 }
830 }
831 #[cfg(not(unix))]
832 let _ = meta;
833 std::fs::read(path).map_err(|e| ConfigError::new(&what, e.to_string()))
834}
835
836#[derive(Clone, Debug, PartialEq, Eq)]
838pub struct ConfigError {
839 what: String,
840 detail: String,
841}
842
843impl ConfigError {
844 pub(crate) fn new(what: &str, detail: impl Into<String>) -> ConfigError {
845 ConfigError { what: what.to_string(), detail: detail.into() }
846 }
847}
848
849impl fmt::Display for ConfigError {
850 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
851 write!(f, "configuration: {}: {}", self.what, self.detail)
852 }
853}
854
855impl std::error::Error for ConfigError {}