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);
19pub const DEFAULT_POOL_SIZE: usize = 32;
22pub const DEFAULT_BATCH_MAX: usize = 1000;
24pub const DEFAULT_SLICE_PAGE: usize = 1000;
26
27pub fn catalog_max_of(v: Option<String>) -> Result<usize, ConfigError> {
30 match v {
31 None => Ok(crate::catalog_build::DEFAULT_CATALOG_MAX),
32 Some(v) => match v.parse::<usize>() {
33 Ok(n) if n > 0 => Ok(n),
34 _ => Err(ConfigError::new("DATUMESH_CATALOG_MAX", format!("not a positive number: {v}"))),
35 },
36 }
37}
38pub const MAX_SLICE_PAGE: usize = 10_000;
40pub const MAX_SLICE_MEMBERS: usize = 1_048_576;
42
43#[non_exhaustive]
46#[derive(Clone, Debug, PartialEq, Eq)]
47pub struct RateLimits {
48 pub enabled: bool,
50 pub per_ip: u32,
52 pub ip_burst: u32,
54 pub per_key: u32,
57 pub verify_per_ip: u32,
59 pub calc_per_ip: u32,
62 pub batch_cells_per_token: u32,
65 pub series_per_ip: u32,
68 pub keys_per_ip: u32,
71}
72
73impl Default for RateLimits {
74 fn default() -> Self {
75 RateLimits {
76 enabled: true,
77 per_ip: 60,
78 ip_burst: 120,
79 per_key: 600,
80 verify_per_ip: 60,
81 calc_per_ip: 30,
82 batch_cells_per_token: 50,
83 series_per_ip: 30,
84 keys_per_ip: 5,
85 }
86 }
87}
88
89#[non_exhaustive]
92#[derive(Clone, Debug, PartialEq, Eq)]
93pub struct Ttls {
94 pub key_doc: Duration,
97 pub key_refetch: Duration,
99 pub mesh_doc: Duration,
101 pub binding: Duration,
104 pub current: Duration,
107 pub latest_max_age: Duration,
109 pub job: Duration,
112}
113
114impl Default for Ttls {
115 fn default() -> Self {
116 Ttls {
117 key_doc: Duration::from_secs(300),
118 key_refetch: Duration::from_secs(10),
119 mesh_doc: Duration::from_secs(300),
120 binding: Duration::from_secs(60),
121 current: Duration::from_secs(60),
122 latest_max_age: Duration::from_secs(10),
123 job: Duration::from_secs(300),
124 }
125 }
126}
127
128#[non_exhaustive]
130#[derive(Clone, Debug, PartialEq, Eq)]
131pub enum Rule {
132 Principals(Vec<String>),
135 Price {
138 amount: String,
140 currency: String,
142 },
143}
144
145#[non_exhaustive]
147#[derive(Clone, Debug, Default, PartialEq, Eq)]
148pub struct Policy {
149 pub rules: BTreeMap<String, Rule>,
151}
152
153impl Policy {
154 pub fn rule(&self, fn_name: &str) -> Option<&Rule> {
156 self.rules.get(fn_name)
157 }
158
159 pub fn from_json(bytes: &[u8]) -> Result<Policy, ConfigError> {
161 let v = json::parse(bytes).map_err(|e| ConfigError::new("policy", e.to_string()))?;
162 let mut rules = BTreeMap::new();
163 for (name, r) in v.as_object().ok_or_else(|| ConfigError::new("policy", "not an object"))? {
164 lexical::check_function_name(name, "$").map_err(|e| ConfigError::new("policy", e.to_string()))?;
165 let rule = if let Some(Value::Array(ps)) = r.get("principals") {
166 Rule::Principals(
167 ps.iter()
168 .map(|p| p.as_str().map(str::to_string).ok_or_else(|| ConfigError::new("policy", "principal")))
169 .collect::<Result<_, _>>()?,
170 )
171 } else if let Some(p) = r.get("price") {
172 let amount =
173 p.get("amount").and_then(Value::as_str).ok_or_else(|| ConfigError::new("policy", "amount"))?;
174 let currency =
175 p.get("currency").and_then(Value::as_str).ok_or_else(|| ConfigError::new("policy", "currency"))?;
176 lexical::check_number(amount, "$").map_err(|e| ConfigError::new("policy", e.to_string()))?;
177 if amount.starts_with('-') || amount == "0" || !lexical::is_currency(currency) {
178 return Err(ConfigError::new("policy", format!("price of {name}")));
179 }
180 Rule::Price { amount: amount.to_string(), currency: currency.to_string() }
181 } else {
182 return Err(ConfigError::new("policy", format!("rule of {name}")));
183 };
184 rules.insert(name.clone(), rule);
185 }
186 Ok(Policy { rules })
187 }
188}
189
190#[non_exhaustive]
192#[derive(Clone, Debug)]
193pub struct Config {
194 pub host: String,
197 pub base_url: Option<String>,
216 pub namespaces: Vec<String>,
219 pub budget: Duration,
221 pub pool_size: usize,
223 pub batch_max: usize,
225 pub test_cells: bool,
228 pub slice_page: usize,
230 pub slice_max: usize,
232 pub catalog_max: usize,
234 pub explain_depth: usize,
236 pub max_jobs: usize,
238 pub rate: RateLimits,
240 pub ttl: Ttls,
242 pub trust_proxy: bool,
245 pub cross_mesh: bool,
247 pub cross_mesh_hosts: Option<Vec<String>>,
250 pub peers: BTreeMap<String, String>,
253 pub peer_timeout: Duration,
255 pub aliases: BTreeMap<String, String>,
257 pub policy: Policy,
259 pub catalog: BTreeMap<String, String>,
261 pub embed_url: Option<String>,
264 pub api_keys: ApiKeys,
266 pub publish_domains: PublishDomains,
269 pub log_dir: Option<std::path::PathBuf>,
272 pub(crate) series: Vec<crate::series::SeriesPage>,
274 pub key_names: bool,
278 pub key_challenge_ttl: Duration,
280 pub contact: Option<String>,
283 pub series_first_build_delay: Duration,
286 pub series_refresh: Duration,
288 pub catalog_first_build_delay: Duration,
291 pub catalog_refresh: Duration,
293 pub index_first_build_delay: Duration,
296 pub index_secs: Duration,
299 pub index_class_max: usize,
303 pub index_max: usize,
305 pub find_first_build_delay: Duration,
308 pub value_counts_refresh: Duration,
311 pub dictionary_max: usize,
314}
315
316#[non_exhaustive]
320#[derive(Clone, Debug, PartialEq, Eq, Default)]
321pub enum PublishDomains {
322 #[default]
324 Own,
325 Hosts(Vec<String>),
327 Any,
329}
330
331impl PublishDomains {
332 pub fn parse(v: &str) -> Result<PublishDomains, ConfigError> {
335 let v = v.trim();
336 if v.is_empty() {
337 return Ok(PublishDomains::Own);
338 }
339 if v == "*" {
340 return Ok(PublishDomains::Any);
341 }
342 let mut hosts = Vec::new();
343 for h in v.split(',').map(str::trim).filter(|h| !h.is_empty()) {
344 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("DATUMESH_PUBLISH_DOMAINS", e.to_string()))?;
345 hosts.push(h.to_string());
346 }
347 Ok(if hosts.is_empty() { PublishDomains::Own } else { PublishDomains::Hosts(hosts) })
348 }
349
350 pub fn allows(&self, host: &str) -> bool {
352 match self {
353 PublishDomains::Own => false,
354 PublishDomains::Hosts(h) => h.iter().any(|x| x == host),
355 PublishDomains::Any => true,
356 }
357 }
358}
359
360impl Config {
361 pub fn new(host: impl Into<String>) -> Config {
363 let host = host.into();
364 Config {
365 namespaces: vec![host.clone()],
366 host,
367 base_url: None,
368 budget: DEFAULT_BUDGET,
369 pool_size: DEFAULT_POOL_SIZE,
370 batch_max: DEFAULT_BATCH_MAX,
371 test_cells: false,
372 slice_page: DEFAULT_SLICE_PAGE,
373 slice_max: MAX_SLICE_MEMBERS,
374 catalog_max: crate::catalog_build::DEFAULT_CATALOG_MAX,
375 explain_depth: 4,
376 max_jobs: 10_000,
377 rate: RateLimits::default(),
378 ttl: Ttls::default(),
379 trust_proxy: false,
380 cross_mesh: true,
381 cross_mesh_hosts: None,
382 peers: BTreeMap::new(),
383 peer_timeout: Duration::from_secs(10),
384 aliases: BTreeMap::new(),
385 policy: Policy::default(),
386 catalog: BTreeMap::new(),
387 embed_url: None,
388 api_keys: ApiKeys::default(),
389 publish_domains: PublishDomains::Own,
390 key_names: false,
391 key_challenge_ttl: Duration::from_secs(300),
392 contact: None,
393 series_first_build_delay: Duration::ZERO,
394 series_refresh: Duration::from_secs(300),
395 catalog_first_build_delay: Duration::ZERO,
396 catalog_refresh: Duration::from_secs(300),
397 index_first_build_delay: Duration::ZERO,
398 index_secs: Duration::from_secs(300),
399 index_class_max: 50_000,
400 index_max: 200_000,
401 find_first_build_delay: Duration::ZERO,
402 value_counts_refresh: Duration::from_secs(3600),
403 dictionary_max: 1000,
404 log_dir: None,
405 series: Vec::new(),
406 }
407 }
408
409 pub fn with_base_url(mut self, url: impl Into<String>) -> Config {
412 self.base_url = Some(url.into());
413 self
414 }
415
416 pub fn from_env() -> Result<Config, ConfigError> {
420 Config::from_vars(|k| std::env::var(k).ok())
421 }
422
423 pub fn from_vars(get: impl Fn(&str) -> Option<String>) -> Result<Config, ConfigError> {
425 let host = get("DATUMESH_HOST").ok_or_else(|| ConfigError::new("DATUMESH_HOST", "not set"))?;
426 let mut c = Config::new(host);
427 if let Some(v) = get("DATUMESH_BASE_URL").filter(|v| !v.is_empty()) {
428 c.base_url = Some(v);
429 }
430 if let Some(v) = get("DATUMESH_NAMESPACES") {
431 c.namespaces = v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
432 }
433 let ms = |k: &str, d: Duration| -> Result<Duration, ConfigError> {
434 match get(k) {
435 Some(v) => v.parse::<u64>().map(Duration::from_millis).map_err(|e| ConfigError::new(k, e.to_string())),
436 None => Ok(d),
437 }
438 };
439 let secs = |k: &str, d: Duration| -> Result<Duration, ConfigError> {
440 match get(k) {
441 Some(v) => v.parse::<u64>().map(Duration::from_secs).map_err(|e| ConfigError::new(k, e.to_string())),
442 None => Ok(d),
443 }
444 };
445 let num = |k: &str, d: usize| -> Result<usize, ConfigError> {
446 match get(k) {
447 Some(v) => v.parse::<usize>().map_err(|e| ConfigError::new(k, e.to_string())),
448 None => Ok(d),
449 }
450 };
451 let flag = |k: &str, d: bool| -> Result<bool, ConfigError> {
452 match get(k).as_deref() {
453 None => Ok(d),
454 Some("1" | "true" | "yes") => Ok(true),
455 Some("0" | "false" | "no") => Ok(false),
456 Some(v) => Err(ConfigError::new(k, format!("not a boolean: {v}"))),
457 }
458 };
459 c.budget = ms("DATUMESH_BUDGET_MS", c.budget)?;
460 c.pool_size = num("DATUMESH_POOL_SIZE", c.pool_size)?;
461 c.batch_max = num("DATUMESH_BATCH_MAX", c.batch_max)?;
462 c.test_cells = flag("DATUMESH_TEST_CELLS", c.test_cells)?;
463 c.slice_page = num("DATUMESH_SLICE_PAGE", c.slice_page)?;
464 c.slice_max = num("DATUMESH_SLICE_MAX", c.slice_max)?;
465 c.catalog_max = catalog_max_of(get("DATUMESH_CATALOG_MAX"))?;
466 c.explain_depth = num("DATUMESH_EXPLAIN_DEPTH", c.explain_depth)?;
467 c.max_jobs = num("DATUMESH_MAX_JOBS", c.max_jobs)?;
468 c.trust_proxy = flag("DATUMESH_TRUST_PROXY", c.trust_proxy)?;
469 c.cross_mesh = flag("DATUMESH_CROSS_MESH", c.cross_mesh)?;
470 c.rate.enabled = flag("DATUMESH_RATE_LIMITS", c.rate.enabled)?;
471 c.rate.per_ip = num("DATUMESH_RATE_PER_IP", c.rate.per_ip as usize)? as u32;
472 c.rate.ip_burst = num("DATUMESH_RATE_IP_BURST", c.rate.ip_burst as usize)? as u32;
473 c.rate.per_key = num("DATUMESH_RATE_PER_KEY", c.rate.per_key as usize)? as u32;
474 c.rate.verify_per_ip = num("DATUMESH_RATE_VERIFY_PER_IP", c.rate.verify_per_ip as usize)? as u32;
475 c.rate.series_per_ip = num("DATUMESH_RATE_SERIES_PER_IP", c.rate.series_per_ip as usize)? as u32;
476 c.rate.calc_per_ip = num("DATUMESH_RATE_CALC_PER_IP", c.rate.calc_per_ip as usize)? as u32;
477 c.rate.keys_per_ip = num("DATUMESH_RATE_KEYS_PER_IP", c.rate.keys_per_ip as usize)? as u32;
478 c.key_names = get("DATUMESH_KEY_NAMES").as_deref() == Some("1");
480 c.key_challenge_ttl = secs("DATUMESH_KEY_CHALLENGE_TTL_SECS", c.key_challenge_ttl)?;
481 c.contact = get("DATUMESH_CONTACT").map(|v| v.trim().to_string()).filter(|v| !v.is_empty());
482 c.series_first_build_delay = secs("DATUMESH_SERIES_FIRST_BUILD_DELAY_SECS", c.series_first_build_delay)?;
483 c.series_refresh = secs("DATUMESH_SERIES_REFRESH_SECS", c.series_refresh)?;
484 c.catalog_first_build_delay = secs("DATUMESH_CATALOG_FIRST_BUILD_DELAY_SECS", c.catalog_first_build_delay)?;
485 c.catalog_refresh = secs("DATUMESH_CATALOG_REFRESH_SECS", c.catalog_refresh)?;
486 c.index_first_build_delay = secs("DATUMESH_INDEX_FIRST_BUILD_DELAY_SECS", c.index_first_build_delay)?;
487 c.index_secs = secs("DATUMESH_INDEX_SECS", c.index_secs)?;
488 c.index_class_max = num("DATUMESH_INDEX_CLASS_MAX", c.index_class_max)?.max(1);
489 c.index_max = num("DATUMESH_INDEX_MAX", c.index_max)?.max(1);
490 c.find_first_build_delay = secs("DATUMESH_FIND_FIRST_BUILD_DELAY_SECS", c.find_first_build_delay)?;
491 c.value_counts_refresh = secs("DATUMESH_VALUE_COUNTS_SECS", c.value_counts_refresh)?;
492 c.dictionary_max = num("DATUMESH_DICTIONARY_MAX", c.dictionary_max)?;
493 c.ttl.key_doc = secs("DATUMESH_TTL_KEY_DOC", c.ttl.key_doc)?;
494 c.ttl.mesh_doc = secs("DATUMESH_TTL_MESH_DOC", c.ttl.mesh_doc)?;
495 c.ttl.binding = secs("DATUMESH_TTL_BINDING", c.ttl.binding)?;
496 c.ttl.current = secs("DATUMESH_TTL_CURRENT", c.ttl.current)?;
497 c.ttl.latest_max_age = secs("DATUMESH_LATEST_MAX_AGE", c.ttl.latest_max_age)?;
498 c.ttl.job = secs("DATUMESH_JOB_TTL", c.ttl.job)?;
499 c.peer_timeout = ms("DATUMESH_PEER_TIMEOUT_MS", c.peer_timeout)?;
500 if let Some(v) = get("DATUMESH_CROSS_MESH_HOSTS") {
501 c.cross_mesh_hosts = Some(v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect());
502 }
503 if let Some(v) = get("DATUMESH_PEERS") {
504 for pair in v.split(',').map(str::trim).filter(|s| !s.is_empty()) {
505 let (h, o) =
506 pair.split_once('=').ok_or_else(|| ConfigError::new("DATUMESH_PEERS", "host=origin pairs"))?;
507 c.peers.insert(h.trim().to_string(), o.trim().trim_end_matches('/').to_string());
508 }
509 }
510 if let Some(p) = get("DATUMESH_ALIASES_FILE") {
511 c.aliases = string_map(&read_file(&p)?, "DATUMESH_ALIASES_FILE")?;
512 }
513 if let Some(p) = get("DATUMESH_CATALOG_FILE") {
514 c.catalog = string_map(&read_file(&p)?, "DATUMESH_CATALOG_FILE")?;
515 }
516 if let Some(v) = get("DATUMESH_EMBED_URL").filter(|v| !v.trim().is_empty()) {
517 c.embed_url = Some(v.trim().trim_end_matches('/').to_string());
518 }
519 if let Some(p) = get("DATUMESH_POLICY_FILE") {
520 c.policy = Policy::from_json(&read_file(&p)?)?;
521 }
522 if let Some(p) = get("DATUMESH_API_KEYS_FILE") {
523 c.api_keys = ApiKeys::parse(&read_secret_file(Path::new(&p))?)?;
524 }
525 c.publish_domains = PublishDomains::parse(&get("DATUMESH_PUBLISH_DOMAINS").unwrap_or_default())?;
526 if let Some(p) = get("DATUMESH_SERIES_FILE").filter(|p| !p.trim().is_empty()) {
527 c.series = crate::series::parse(&read_file(&p)?)?;
528 }
529 if let Some(d) = get("DATUMESH_LOG_DIR").filter(|d| !d.trim().is_empty()) {
530 c.log_dir = Some(std::path::PathBuf::from(d));
531 }
532 c.check()?;
533 Ok(c)
534 }
535
536 pub fn check(&self) -> Result<(), ConfigError> {
539 lexical::check_dns_name(&self.host, "$").map_err(|e| ConfigError::new("host", e.to_string()))?;
540 if self.series_refresh < Duration::from_secs(1) {
541 return Err(ConfigError::new("DATUMESH_SERIES_REFRESH_SECS", "at least 1 second"));
542 }
543 if self.catalog_refresh < Duration::from_secs(1) {
544 return Err(ConfigError::new("DATUMESH_CATALOG_REFRESH_SECS", "at least 1 second"));
545 }
546 if self.value_counts_refresh < Duration::from_secs(1) {
547 return Err(ConfigError::new("DATUMESH_VALUE_COUNTS_SECS", "at least 1 second"));
548 }
549 if self.dictionary_max == 0 {
550 return Err(ConfigError::new("DATUMESH_DICTIONARY_MAX", "at least 1"));
551 }
552 if let Some(c) = &self.contact {
553 if c.chars().any(|ch| ch.is_whitespace() || ch.is_control()) {
554 return Err(ConfigError::new("DATUMESH_CONTACT", "an address without spaces"));
555 }
556 }
557 if let Some(u) = &self.base_url {
558 check_base_url(&self.host, u).map_err(|e| ConfigError::new("base URL", format!("{u}: {e}")))?;
559 }
560 for h in &self.namespaces {
561 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("namespaces", e.to_string()))?;
562 }
563 for (h, o) in &self.peers {
564 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("peers", e.to_string()))?;
565 if !(o.starts_with("http://") || o.starts_with("https://")) {
566 return Err(ConfigError::new("peers", format!("{o}: not an http(s) origin")));
567 }
568 }
569 for (a, n) in &self.aliases {
570 lexical::check_function_name(n, "$").map_err(|e| ConfigError::new("aliases", format!("{a}: {e}")))?;
571 }
572 if self.pool_size == 0 || self.batch_max == 0 || self.slice_page == 0 || self.slice_max == 0 {
573 return Err(ConfigError::new("sizes", "the pool, batch and slice bounds must be positive"));
574 }
575 if self.ttl.job < Duration::from_secs(300) {
576 return Err(ConfigError::new("job TTL", "at least 300 s (SPEC 5.5)"));
577 }
578 if self.budget.is_zero() {
579 return Err(ConfigError::new("budget", "must be positive"));
580 }
581 Ok(())
582 }
583
584 pub fn owns(&self, host: &str) -> bool {
586 self.namespaces.iter().any(|h| h == host)
587 }
588
589 pub fn origin(&self) -> String {
591 format!("https://{}", self.host)
592 }
593
594 pub fn mesh_document_base(&self) -> String {
597 self.base_url.clone().unwrap_or_else(|| self.origin())
598 }
599}
600
601#[non_exhaustive]
603#[derive(Clone, Copy, Debug, PartialEq, Eq)]
604pub enum BaseUrlError {
605 Scheme,
607 HttpRootedHost,
610 HttpNotLoopback,
613 Host,
616 Port,
618 Path,
620 TrailingSlash,
622 Query,
624 Fragment,
626}
627
628impl fmt::Display for BaseUrlError {
629 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
630 f.write_str(match self {
631 BaseUrlError::Scheme => "not an https:// or http:// URL",
632 BaseUrlError::HttpRootedHost => "http:// is for an unrooted host (under .invalid) only",
633 BaseUrlError::HttpNotLoopback => "http:// is for 127.0.0.1, [::1] and localhost only",
634 BaseUrlError::Host => "not a host name, IPv4 address or bracketed IPv6 address",
635 BaseUrlError::Port => "not a port from 1 to 65535",
636 BaseUrlError::Path => "a path (the base URL is a scheme, a host and a port)",
637 BaseUrlError::TrailingSlash => "a trailing slash",
638 BaseUrlError::Query => "a query",
639 BaseUrlError::Fragment => "a fragment",
640 })
641 }
642}
643
644impl std::error::Error for BaseUrlError {}
645
646pub fn check_base_url(host: &str, url: &str) -> Result<(), BaseUrlError> {
653 let mesh_host = host;
654 let (http, rest) = if let Some(r) = url.strip_prefix("https://") {
655 (false, r)
656 } else if let Some(r) = url.strip_prefix("http://") {
657 (true, r)
658 } else {
659 return Err(BaseUrlError::Scheme);
660 };
661 if rest.contains('#') {
662 return Err(BaseUrlError::Fragment);
663 }
664 if rest.contains('?') {
665 return Err(BaseUrlError::Query);
666 }
667 let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
668 match path {
669 "" => {}
670 "/" => return Err(BaseUrlError::TrailingSlash),
671 _ => return Err(BaseUrlError::Path),
672 }
673 if authority.contains('@') {
674 return Err(BaseUrlError::Host);
675 }
676 let (host, port) = if let Some(r) = authority.strip_prefix('[') {
677 let (inside, after) = r.split_once(']').ok_or(BaseUrlError::Host)?;
678 inside.parse::<std::net::Ipv6Addr>().map_err(|_| BaseUrlError::Host)?;
679 let port = match after {
680 "" => None,
681 p => Some(p.strip_prefix(':').ok_or(BaseUrlError::Host)?),
682 };
683 (&authority[..inside.len() + 2], port)
684 } else {
685 let (host, port) = match authority.split_once(':') {
686 Some((h, p)) => (h, Some(p)),
687 None => (authority, None),
688 };
689 if host.parse::<std::net::Ipv4Addr>().is_err() && !is_dns_name(host) {
690 return Err(BaseUrlError::Host);
691 }
692 (host, port)
693 };
694 if let Some(p) = port {
695 let ok = !p.is_empty() && p.len() <= 5 && p.bytes().all(|b| b.is_ascii_digit());
696 if !ok || !(1..=65535).contains(&p.parse::<u32>().unwrap_or(0)) {
697 return Err(BaseUrlError::Port);
698 }
699 }
700 if http && !is_unrooted(mesh_host) {
701 return Err(BaseUrlError::HttpRootedHost);
702 }
703 if http && !matches!(host, "127.0.0.1" | "[::1]" | "localhost") {
704 return Err(BaseUrlError::HttpNotLoopback);
705 }
706 Ok(())
707}
708
709pub fn is_unrooted(host: &str) -> bool {
712 host.rsplit('.').next() == Some("invalid")
713}
714
715fn is_dns_name(h: &str) -> bool {
718 !h.is_empty()
719 && h.len() <= 253
720 && h.split('.').all(|l| {
721 !l.is_empty()
722 && l.len() <= 63
723 && !l.starts_with('-')
724 && !l.ends_with('-')
725 && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
726 })
727}
728
729fn string_map(bytes: &[u8], what: &str) -> Result<BTreeMap<String, String>, ConfigError> {
730 let v = json::parse(bytes).map_err(|e| ConfigError::new(what, e.to_string()))?;
731 let mut out = BTreeMap::new();
732 for (k, x) in v.as_object().ok_or_else(|| ConfigError::new(what, "not an object"))? {
733 let s = x.as_str().ok_or_else(|| ConfigError::new(what, format!("{k}: not a string")))?;
734 out.insert(k.clone(), s.to_string());
735 }
736 Ok(out)
737}
738
739fn read_file(path: &str) -> Result<Vec<u8>, ConfigError> {
740 std::fs::read(path).map_err(|e| ConfigError::new(path, e.to_string()))
741}
742
743pub fn read_secret_file(path: &Path) -> Result<Vec<u8>, ConfigError> {
746 let what = path.display().to_string();
747 let meta = std::fs::metadata(path).map_err(|e| ConfigError::new(&what, e.to_string()))?;
748 #[cfg(unix)]
749 {
750 use std::os::unix::fs::PermissionsExt;
751 let mode = meta.permissions().mode() & 0o777;
752 if mode & 0o077 != 0 {
753 return Err(ConfigError::new(&what, format!("mode {mode:o}: a secret file must be 0600")));
754 }
755 }
756 #[cfg(not(unix))]
757 let _ = meta;
758 std::fs::read(path).map_err(|e| ConfigError::new(&what, e.to_string()))
759}
760
761#[derive(Clone, Debug, PartialEq, Eq)]
763pub struct ConfigError {
764 what: String,
765 detail: String,
766}
767
768impl ConfigError {
769 pub(crate) fn new(what: &str, detail: impl Into<String>) -> ConfigError {
770 ConfigError { what: what.to_string(), detail: detail.into() }
771 }
772}
773
774impl fmt::Display for ConfigError {
775 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
776 write!(f, "configuration: {}: {}", self.what, self.detail)
777 }
778}
779
780impl std::error::Error for ConfigError {}