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;
26pub const MAX_SLICE_PAGE: usize = 10_000;
28pub const MAX_SLICE_MEMBERS: usize = 1_048_576;
30
31#[non_exhaustive]
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub struct RateLimits {
36 pub enabled: bool,
38 pub per_ip: u32,
40 pub ip_burst: u32,
42 pub per_key: u32,
45 pub verify_per_ip: u32,
47 pub calc_per_ip: u32,
50 pub batch_cells_per_token: u32,
53 pub series_per_ip: u32,
56 pub keys_per_ip: u32,
59}
60
61impl Default for RateLimits {
62 fn default() -> Self {
63 RateLimits {
64 enabled: true,
65 per_ip: 60,
66 ip_burst: 120,
67 per_key: 600,
68 verify_per_ip: 60,
69 calc_per_ip: 30,
70 batch_cells_per_token: 50,
71 series_per_ip: 30,
72 keys_per_ip: 5,
73 }
74 }
75}
76
77#[non_exhaustive]
80#[derive(Clone, Debug, PartialEq, Eq)]
81pub struct Ttls {
82 pub key_doc: Duration,
85 pub key_refetch: Duration,
87 pub mesh_doc: Duration,
89 pub binding: Duration,
92 pub current: Duration,
95 pub latest_max_age: Duration,
97 pub job: Duration,
100}
101
102impl Default for Ttls {
103 fn default() -> Self {
104 Ttls {
105 key_doc: Duration::from_secs(300),
106 key_refetch: Duration::from_secs(10),
107 mesh_doc: Duration::from_secs(300),
108 binding: Duration::from_secs(60),
109 current: Duration::from_secs(60),
110 latest_max_age: Duration::from_secs(10),
111 job: Duration::from_secs(300),
112 }
113 }
114}
115
116#[non_exhaustive]
118#[derive(Clone, Debug, PartialEq, Eq)]
119pub enum Rule {
120 Principals(Vec<String>),
123 Price {
126 amount: String,
128 currency: String,
130 },
131}
132
133#[non_exhaustive]
135#[derive(Clone, Debug, Default, PartialEq, Eq)]
136pub struct Policy {
137 pub rules: BTreeMap<String, Rule>,
139}
140
141impl Policy {
142 pub fn rule(&self, fn_name: &str) -> Option<&Rule> {
144 self.rules.get(fn_name)
145 }
146
147 pub fn from_json(bytes: &[u8]) -> Result<Policy, ConfigError> {
149 let v = json::parse(bytes).map_err(|e| ConfigError::new("policy", e.to_string()))?;
150 let mut rules = BTreeMap::new();
151 for (name, r) in v.as_object().ok_or_else(|| ConfigError::new("policy", "not an object"))? {
152 lexical::check_function_name(name, "$").map_err(|e| ConfigError::new("policy", e.to_string()))?;
153 let rule = if let Some(Value::Array(ps)) = r.get("principals") {
154 Rule::Principals(
155 ps.iter()
156 .map(|p| p.as_str().map(str::to_string).ok_or_else(|| ConfigError::new("policy", "principal")))
157 .collect::<Result<_, _>>()?,
158 )
159 } else if let Some(p) = r.get("price") {
160 let amount =
161 p.get("amount").and_then(Value::as_str).ok_or_else(|| ConfigError::new("policy", "amount"))?;
162 let currency =
163 p.get("currency").and_then(Value::as_str).ok_or_else(|| ConfigError::new("policy", "currency"))?;
164 lexical::check_number(amount, "$").map_err(|e| ConfigError::new("policy", e.to_string()))?;
165 if amount.starts_with('-') || amount == "0" || !lexical::is_currency(currency) {
166 return Err(ConfigError::new("policy", format!("price of {name}")));
167 }
168 Rule::Price { amount: amount.to_string(), currency: currency.to_string() }
169 } else {
170 return Err(ConfigError::new("policy", format!("rule of {name}")));
171 };
172 rules.insert(name.clone(), rule);
173 }
174 Ok(Policy { rules })
175 }
176}
177
178#[non_exhaustive]
180#[derive(Clone, Debug)]
181pub struct Config {
182 pub host: String,
185 pub base_url: Option<String>,
204 pub namespaces: Vec<String>,
207 pub budget: Duration,
209 pub pool_size: usize,
211 pub batch_max: usize,
213 pub test_cells: bool,
216 pub slice_page: usize,
218 pub slice_max: usize,
220 pub explain_depth: usize,
222 pub max_jobs: usize,
224 pub rate: RateLimits,
226 pub ttl: Ttls,
228 pub trust_proxy: bool,
231 pub cross_mesh: bool,
233 pub cross_mesh_hosts: Option<Vec<String>>,
236 pub peers: BTreeMap<String, String>,
239 pub peer_timeout: Duration,
241 pub aliases: BTreeMap<String, String>,
243 pub policy: Policy,
245 pub catalog: BTreeMap<String, String>,
247 pub embed_url: Option<String>,
250 pub api_keys: ApiKeys,
252 pub publish_domains: PublishDomains,
255 pub log_dir: Option<std::path::PathBuf>,
258 pub(crate) series: Vec<crate::series::SeriesPage>,
260 pub key_names: bool,
264 pub key_challenge_ttl: Duration,
266 pub contact: Option<String>,
269 pub series_first_build_delay: Duration,
272 pub series_refresh: Duration,
274 pub index_first_build_delay: Duration,
277 pub index_secs: Duration,
280 pub index_class_max: usize,
284 pub index_max: usize,
286 pub find_first_build_delay: Duration,
289 pub value_counts_refresh: Duration,
292 pub dictionary_max: usize,
295}
296
297#[non_exhaustive]
301#[derive(Clone, Debug, PartialEq, Eq, Default)]
302pub enum PublishDomains {
303 #[default]
305 Own,
306 Hosts(Vec<String>),
308 Any,
310}
311
312impl PublishDomains {
313 pub fn parse(v: &str) -> Result<PublishDomains, ConfigError> {
316 let v = v.trim();
317 if v.is_empty() {
318 return Ok(PublishDomains::Own);
319 }
320 if v == "*" {
321 return Ok(PublishDomains::Any);
322 }
323 let mut hosts = Vec::new();
324 for h in v.split(',').map(str::trim).filter(|h| !h.is_empty()) {
325 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("DATUMESH_PUBLISH_DOMAINS", e.to_string()))?;
326 hosts.push(h.to_string());
327 }
328 Ok(if hosts.is_empty() { PublishDomains::Own } else { PublishDomains::Hosts(hosts) })
329 }
330
331 pub fn allows(&self, host: &str) -> bool {
333 match self {
334 PublishDomains::Own => false,
335 PublishDomains::Hosts(h) => h.iter().any(|x| x == host),
336 PublishDomains::Any => true,
337 }
338 }
339}
340
341impl Config {
342 pub fn new(host: impl Into<String>) -> Config {
344 let host = host.into();
345 Config {
346 namespaces: vec![host.clone()],
347 host,
348 base_url: None,
349 budget: DEFAULT_BUDGET,
350 pool_size: DEFAULT_POOL_SIZE,
351 batch_max: DEFAULT_BATCH_MAX,
352 test_cells: false,
353 slice_page: DEFAULT_SLICE_PAGE,
354 slice_max: MAX_SLICE_MEMBERS,
355 explain_depth: 4,
356 max_jobs: 10_000,
357 rate: RateLimits::default(),
358 ttl: Ttls::default(),
359 trust_proxy: false,
360 cross_mesh: true,
361 cross_mesh_hosts: None,
362 peers: BTreeMap::new(),
363 peer_timeout: Duration::from_secs(10),
364 aliases: BTreeMap::new(),
365 policy: Policy::default(),
366 catalog: BTreeMap::new(),
367 embed_url: None,
368 api_keys: ApiKeys::default(),
369 publish_domains: PublishDomains::Own,
370 key_names: false,
371 key_challenge_ttl: Duration::from_secs(300),
372 contact: None,
373 series_first_build_delay: Duration::ZERO,
374 series_refresh: Duration::from_secs(300),
375 index_first_build_delay: Duration::ZERO,
376 index_secs: Duration::from_secs(300),
377 index_class_max: 50_000,
378 index_max: 200_000,
379 find_first_build_delay: Duration::ZERO,
380 value_counts_refresh: Duration::from_secs(3600),
381 dictionary_max: 1000,
382 log_dir: None,
383 series: Vec::new(),
384 }
385 }
386
387 pub fn with_base_url(mut self, url: impl Into<String>) -> Config {
390 self.base_url = Some(url.into());
391 self
392 }
393
394 pub fn from_env() -> Result<Config, ConfigError> {
398 Config::from_vars(|k| std::env::var(k).ok())
399 }
400
401 pub fn from_vars(get: impl Fn(&str) -> Option<String>) -> Result<Config, ConfigError> {
403 let host = get("DATUMESH_HOST").ok_or_else(|| ConfigError::new("DATUMESH_HOST", "not set"))?;
404 let mut c = Config::new(host);
405 if let Some(v) = get("DATUMESH_BASE_URL").filter(|v| !v.is_empty()) {
406 c.base_url = Some(v);
407 }
408 if let Some(v) = get("DATUMESH_NAMESPACES") {
409 c.namespaces = v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
410 }
411 let ms = |k: &str, d: Duration| -> Result<Duration, ConfigError> {
412 match get(k) {
413 Some(v) => v.parse::<u64>().map(Duration::from_millis).map_err(|e| ConfigError::new(k, e.to_string())),
414 None => Ok(d),
415 }
416 };
417 let secs = |k: &str, d: Duration| -> Result<Duration, ConfigError> {
418 match get(k) {
419 Some(v) => v.parse::<u64>().map(Duration::from_secs).map_err(|e| ConfigError::new(k, e.to_string())),
420 None => Ok(d),
421 }
422 };
423 let num = |k: &str, d: usize| -> Result<usize, ConfigError> {
424 match get(k) {
425 Some(v) => v.parse::<usize>().map_err(|e| ConfigError::new(k, e.to_string())),
426 None => Ok(d),
427 }
428 };
429 let flag = |k: &str, d: bool| -> Result<bool, ConfigError> {
430 match get(k).as_deref() {
431 None => Ok(d),
432 Some("1" | "true" | "yes") => Ok(true),
433 Some("0" | "false" | "no") => Ok(false),
434 Some(v) => Err(ConfigError::new(k, format!("not a boolean: {v}"))),
435 }
436 };
437 c.budget = ms("DATUMESH_BUDGET_MS", c.budget)?;
438 c.pool_size = num("DATUMESH_POOL_SIZE", c.pool_size)?;
439 c.batch_max = num("DATUMESH_BATCH_MAX", c.batch_max)?;
440 c.test_cells = flag("DATUMESH_TEST_CELLS", c.test_cells)?;
441 c.slice_page = num("DATUMESH_SLICE_PAGE", c.slice_page)?;
442 c.slice_max = num("DATUMESH_SLICE_MAX", c.slice_max)?;
443 c.explain_depth = num("DATUMESH_EXPLAIN_DEPTH", c.explain_depth)?;
444 c.max_jobs = num("DATUMESH_MAX_JOBS", c.max_jobs)?;
445 c.trust_proxy = flag("DATUMESH_TRUST_PROXY", c.trust_proxy)?;
446 c.cross_mesh = flag("DATUMESH_CROSS_MESH", c.cross_mesh)?;
447 c.rate.enabled = flag("DATUMESH_RATE_LIMITS", c.rate.enabled)?;
448 c.rate.per_ip = num("DATUMESH_RATE_PER_IP", c.rate.per_ip as usize)? as u32;
449 c.rate.ip_burst = num("DATUMESH_RATE_IP_BURST", c.rate.ip_burst as usize)? as u32;
450 c.rate.per_key = num("DATUMESH_RATE_PER_KEY", c.rate.per_key as usize)? as u32;
451 c.rate.verify_per_ip = num("DATUMESH_RATE_VERIFY_PER_IP", c.rate.verify_per_ip as usize)? as u32;
452 c.rate.series_per_ip = num("DATUMESH_RATE_SERIES_PER_IP", c.rate.series_per_ip as usize)? as u32;
453 c.rate.calc_per_ip = num("DATUMESH_RATE_CALC_PER_IP", c.rate.calc_per_ip as usize)? as u32;
454 c.rate.keys_per_ip = num("DATUMESH_RATE_KEYS_PER_IP", c.rate.keys_per_ip as usize)? as u32;
455 c.key_names = get("DATUMESH_KEY_NAMES").as_deref() == Some("1");
457 c.key_challenge_ttl = secs("DATUMESH_KEY_CHALLENGE_TTL_SECS", c.key_challenge_ttl)?;
458 c.contact = get("DATUMESH_CONTACT").map(|v| v.trim().to_string()).filter(|v| !v.is_empty());
459 c.series_first_build_delay = secs("DATUMESH_SERIES_FIRST_BUILD_DELAY_SECS", c.series_first_build_delay)?;
460 c.series_refresh = secs("DATUMESH_SERIES_REFRESH_SECS", c.series_refresh)?;
461 c.index_first_build_delay = secs("DATUMESH_INDEX_FIRST_BUILD_DELAY_SECS", c.index_first_build_delay)?;
462 c.index_secs = secs("DATUMESH_INDEX_SECS", c.index_secs)?;
463 c.index_class_max = num("DATUMESH_INDEX_CLASS_MAX", c.index_class_max)?.max(1);
464 c.index_max = num("DATUMESH_INDEX_MAX", c.index_max)?.max(1);
465 c.find_first_build_delay = secs("DATUMESH_FIND_FIRST_BUILD_DELAY_SECS", c.find_first_build_delay)?;
466 c.value_counts_refresh = secs("DATUMESH_VALUE_COUNTS_SECS", c.value_counts_refresh)?;
467 c.dictionary_max = num("DATUMESH_DICTIONARY_MAX", c.dictionary_max)?;
468 c.ttl.key_doc = secs("DATUMESH_TTL_KEY_DOC", c.ttl.key_doc)?;
469 c.ttl.mesh_doc = secs("DATUMESH_TTL_MESH_DOC", c.ttl.mesh_doc)?;
470 c.ttl.binding = secs("DATUMESH_TTL_BINDING", c.ttl.binding)?;
471 c.ttl.current = secs("DATUMESH_TTL_CURRENT", c.ttl.current)?;
472 c.ttl.latest_max_age = secs("DATUMESH_LATEST_MAX_AGE", c.ttl.latest_max_age)?;
473 c.ttl.job = secs("DATUMESH_JOB_TTL", c.ttl.job)?;
474 c.peer_timeout = ms("DATUMESH_PEER_TIMEOUT_MS", c.peer_timeout)?;
475 if let Some(v) = get("DATUMESH_CROSS_MESH_HOSTS") {
476 c.cross_mesh_hosts = Some(v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect());
477 }
478 if let Some(v) = get("DATUMESH_PEERS") {
479 for pair in v.split(',').map(str::trim).filter(|s| !s.is_empty()) {
480 let (h, o) =
481 pair.split_once('=').ok_or_else(|| ConfigError::new("DATUMESH_PEERS", "host=origin pairs"))?;
482 c.peers.insert(h.trim().to_string(), o.trim().trim_end_matches('/').to_string());
483 }
484 }
485 if let Some(p) = get("DATUMESH_ALIASES_FILE") {
486 c.aliases = string_map(&read_file(&p)?, "DATUMESH_ALIASES_FILE")?;
487 }
488 if let Some(p) = get("DATUMESH_CATALOG_FILE") {
489 c.catalog = string_map(&read_file(&p)?, "DATUMESH_CATALOG_FILE")?;
490 }
491 if let Some(v) = get("DATUMESH_EMBED_URL").filter(|v| !v.trim().is_empty()) {
492 c.embed_url = Some(v.trim().trim_end_matches('/').to_string());
493 }
494 if let Some(p) = get("DATUMESH_POLICY_FILE") {
495 c.policy = Policy::from_json(&read_file(&p)?)?;
496 }
497 if let Some(p) = get("DATUMESH_API_KEYS_FILE") {
498 c.api_keys = ApiKeys::parse(&read_secret_file(Path::new(&p))?)?;
499 }
500 c.publish_domains = PublishDomains::parse(&get("DATUMESH_PUBLISH_DOMAINS").unwrap_or_default())?;
501 if let Some(p) = get("DATUMESH_SERIES_FILE").filter(|p| !p.trim().is_empty()) {
502 c.series = crate::series::parse(&read_file(&p)?)?;
503 }
504 if let Some(d) = get("DATUMESH_LOG_DIR").filter(|d| !d.trim().is_empty()) {
505 c.log_dir = Some(std::path::PathBuf::from(d));
506 }
507 c.check()?;
508 Ok(c)
509 }
510
511 pub fn check(&self) -> Result<(), ConfigError> {
514 lexical::check_dns_name(&self.host, "$").map_err(|e| ConfigError::new("host", e.to_string()))?;
515 if self.series_refresh < Duration::from_secs(1) {
516 return Err(ConfigError::new("DATUMESH_SERIES_REFRESH_SECS", "at least 1 second"));
517 }
518 if self.value_counts_refresh < Duration::from_secs(1) {
519 return Err(ConfigError::new("DATUMESH_VALUE_COUNTS_SECS", "at least 1 second"));
520 }
521 if self.dictionary_max == 0 {
522 return Err(ConfigError::new("DATUMESH_DICTIONARY_MAX", "at least 1"));
523 }
524 if let Some(c) = &self.contact {
525 if c.chars().any(|ch| ch.is_whitespace() || ch.is_control()) {
526 return Err(ConfigError::new("DATUMESH_CONTACT", "an address without spaces"));
527 }
528 }
529 if let Some(u) = &self.base_url {
530 check_base_url(&self.host, u).map_err(|e| ConfigError::new("base URL", format!("{u}: {e}")))?;
531 }
532 for h in &self.namespaces {
533 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("namespaces", e.to_string()))?;
534 }
535 for (h, o) in &self.peers {
536 lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("peers", e.to_string()))?;
537 if !(o.starts_with("http://") || o.starts_with("https://")) {
538 return Err(ConfigError::new("peers", format!("{o}: not an http(s) origin")));
539 }
540 }
541 for (a, n) in &self.aliases {
542 lexical::check_function_name(n, "$").map_err(|e| ConfigError::new("aliases", format!("{a}: {e}")))?;
543 }
544 if self.pool_size == 0 || self.batch_max == 0 || self.slice_page == 0 || self.slice_max == 0 {
545 return Err(ConfigError::new("sizes", "the pool, batch and slice bounds must be positive"));
546 }
547 if self.ttl.job < Duration::from_secs(300) {
548 return Err(ConfigError::new("job TTL", "at least 300 s (SPEC 5.5)"));
549 }
550 if self.budget.is_zero() {
551 return Err(ConfigError::new("budget", "must be positive"));
552 }
553 Ok(())
554 }
555
556 pub fn owns(&self, host: &str) -> bool {
558 self.namespaces.iter().any(|h| h == host)
559 }
560
561 pub fn origin(&self) -> String {
563 format!("https://{}", self.host)
564 }
565
566 pub fn mesh_document_base(&self) -> String {
569 self.base_url.clone().unwrap_or_else(|| self.origin())
570 }
571}
572
573#[non_exhaustive]
575#[derive(Clone, Copy, Debug, PartialEq, Eq)]
576pub enum BaseUrlError {
577 Scheme,
579 HttpRootedHost,
582 HttpNotLoopback,
585 Host,
588 Port,
590 Path,
592 TrailingSlash,
594 Query,
596 Fragment,
598}
599
600impl fmt::Display for BaseUrlError {
601 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
602 f.write_str(match self {
603 BaseUrlError::Scheme => "not an https:// or http:// URL",
604 BaseUrlError::HttpRootedHost => "http:// is for an unrooted host (under .invalid) only",
605 BaseUrlError::HttpNotLoopback => "http:// is for 127.0.0.1, [::1] and localhost only",
606 BaseUrlError::Host => "not a host name, IPv4 address or bracketed IPv6 address",
607 BaseUrlError::Port => "not a port from 1 to 65535",
608 BaseUrlError::Path => "a path (the base URL is a scheme, a host and a port)",
609 BaseUrlError::TrailingSlash => "a trailing slash",
610 BaseUrlError::Query => "a query",
611 BaseUrlError::Fragment => "a fragment",
612 })
613 }
614}
615
616impl std::error::Error for BaseUrlError {}
617
618pub fn check_base_url(host: &str, url: &str) -> Result<(), BaseUrlError> {
625 let mesh_host = host;
626 let (http, rest) = if let Some(r) = url.strip_prefix("https://") {
627 (false, r)
628 } else if let Some(r) = url.strip_prefix("http://") {
629 (true, r)
630 } else {
631 return Err(BaseUrlError::Scheme);
632 };
633 if rest.contains('#') {
634 return Err(BaseUrlError::Fragment);
635 }
636 if rest.contains('?') {
637 return Err(BaseUrlError::Query);
638 }
639 let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
640 match path {
641 "" => {}
642 "/" => return Err(BaseUrlError::TrailingSlash),
643 _ => return Err(BaseUrlError::Path),
644 }
645 if authority.contains('@') {
646 return Err(BaseUrlError::Host);
647 }
648 let (host, port) = if let Some(r) = authority.strip_prefix('[') {
649 let (inside, after) = r.split_once(']').ok_or(BaseUrlError::Host)?;
650 inside.parse::<std::net::Ipv6Addr>().map_err(|_| BaseUrlError::Host)?;
651 let port = match after {
652 "" => None,
653 p => Some(p.strip_prefix(':').ok_or(BaseUrlError::Host)?),
654 };
655 (&authority[..inside.len() + 2], port)
656 } else {
657 let (host, port) = match authority.split_once(':') {
658 Some((h, p)) => (h, Some(p)),
659 None => (authority, None),
660 };
661 if host.parse::<std::net::Ipv4Addr>().is_err() && !is_dns_name(host) {
662 return Err(BaseUrlError::Host);
663 }
664 (host, port)
665 };
666 if let Some(p) = port {
667 let ok = !p.is_empty() && p.len() <= 5 && p.bytes().all(|b| b.is_ascii_digit());
668 if !ok || !(1..=65535).contains(&p.parse::<u32>().unwrap_or(0)) {
669 return Err(BaseUrlError::Port);
670 }
671 }
672 if http && !is_unrooted(mesh_host) {
673 return Err(BaseUrlError::HttpRootedHost);
674 }
675 if http && !matches!(host, "127.0.0.1" | "[::1]" | "localhost") {
676 return Err(BaseUrlError::HttpNotLoopback);
677 }
678 Ok(())
679}
680
681pub fn is_unrooted(host: &str) -> bool {
684 host.rsplit('.').next() == Some("invalid")
685}
686
687fn is_dns_name(h: &str) -> bool {
690 !h.is_empty()
691 && h.len() <= 253
692 && h.split('.').all(|l| {
693 !l.is_empty()
694 && l.len() <= 63
695 && !l.starts_with('-')
696 && !l.ends_with('-')
697 && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
698 })
699}
700
701fn string_map(bytes: &[u8], what: &str) -> Result<BTreeMap<String, String>, ConfigError> {
702 let v = json::parse(bytes).map_err(|e| ConfigError::new(what, e.to_string()))?;
703 let mut out = BTreeMap::new();
704 for (k, x) in v.as_object().ok_or_else(|| ConfigError::new(what, "not an object"))? {
705 let s = x.as_str().ok_or_else(|| ConfigError::new(what, format!("{k}: not a string")))?;
706 out.insert(k.clone(), s.to_string());
707 }
708 Ok(out)
709}
710
711fn read_file(path: &str) -> Result<Vec<u8>, ConfigError> {
712 std::fs::read(path).map_err(|e| ConfigError::new(path, e.to_string()))
713}
714
715pub fn read_secret_file(path: &Path) -> Result<Vec<u8>, ConfigError> {
718 let what = path.display().to_string();
719 let meta = std::fs::metadata(path).map_err(|e| ConfigError::new(&what, e.to_string()))?;
720 #[cfg(unix)]
721 {
722 use std::os::unix::fs::PermissionsExt;
723 let mode = meta.permissions().mode() & 0o777;
724 if mode & 0o077 != 0 {
725 return Err(ConfigError::new(&what, format!("mode {mode:o}: a secret file must be 0600")));
726 }
727 }
728 #[cfg(not(unix))]
729 let _ = meta;
730 std::fs::read(path).map_err(|e| ConfigError::new(&what, e.to_string()))
731}
732
733#[derive(Clone, Debug, PartialEq, Eq)]
735pub struct ConfigError {
736 what: String,
737 detail: String,
738}
739
740impl ConfigError {
741 pub(crate) fn new(what: &str, detail: impl Into<String>) -> ConfigError {
742 ConfigError { what: what.to_string(), detail: detail.into() }
743 }
744}
745
746impl fmt::Display for ConfigError {
747 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
748 write!(f, "configuration: {}: {}", self.what, self.detail)
749 }
750}
751
752impl std::error::Error for ConfigError {}