Skip to main content

datumesh_http/
config.rs

1//! The mesh's configuration: [`Config`], from code or from the environment
2//! ([`Config::from_env`]).
3//!
4//! Secrets never come from here directly: the signing key and the API keys are read from
5//! files that must have mode 0600 ([`read_secret_file`]).
6
7use 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
17/// The default wall-clock budget of a request before it is answered `pending` (SPEC 5.5).
18pub const DEFAULT_BUDGET: Duration = Duration::from_secs(1);
19
20/// The store barrier's default timeout (`DATUMESH_BARRIER_TIMEOUT_MS`, second review B3).
21pub const DEFAULT_BARRIER_TIMEOUT: Duration = Duration::from_secs(5);
22
23/// `DATUMESH_BARRIER_TIMEOUT_MS`: a positive number of milliseconds (default 5,000).
24pub 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}
33/// The default size of the blocking pool, which is the concurrency limit of evaluation and
34/// store access (see the crate documentation for why).
35pub const DEFAULT_POOL_SIZE: usize = 32;
36/// The default bound on a `POST /cells` batch.
37pub const DEFAULT_BATCH_MAX: usize = 1000;
38/// The default number of members in one JSON page of `GET /slice`.
39pub const DEFAULT_SLICE_PAGE: usize = 1000;
40
41/// The most subjects the catalogue lists (`DATUMESH_CATALOG_MAX`, default 100,000; CONTRACT-0.5.1 H2). Read by the catalogue
42/// job and by the mesh alike.
43pub 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}
52/// The bound on a JSON page of `GET /slice` (`limit=`).
53pub const MAX_SLICE_PAGE: usize = 10_000;
54/// The bound on the members of a slice served (SPEC 10.1: a manifest has at most 1,048,576).
55pub const MAX_SLICE_MEMBERS: usize = 1_048_576;
56
57/// Rate limits (token buckets), per minute. Refused requests are answered `rate_limited`
58/// with `retry_after_seconds` and `Retry-After`; nothing is ever queued.
59#[non_exhaustive]
60#[derive(Clone, Debug, PartialEq, Eq)]
61pub struct RateLimits {
62    /// Whether limits apply at all (default true).
63    pub enabled: bool,
64    /// Requests per minute per client IP without an API key (default 60).
65    pub per_ip: u32,
66    /// The burst per IP: the bucket's capacity (default 120).
67    pub ip_burst: u32,
68    /// Requests per minute per API key, unless the key's own line says otherwise (default
69    /// 600; the burst is the same number).
70    pub per_key: u32,
71    /// `POST /verify` per minute per IP, with or without a key (default 60; burst the same).
72    pub verify_per_ip: u32,
73    /// `POST /x/calc` per minute per IP, with or without a key (default 30; burst the same). Its
74    /// own bucket, taken after the per-IP limit (Build 2 Part 3, `calc`).
75    pub calc_per_ip: u32,
76    /// Cells per request token in a `POST /cells` batch (default 50: a batch of 1,000 cells
77    /// counts as 20 requests).
78    pub batch_cells_per_token: u32,
79    /// `/series` pages per minute per IP, besides the per-IP limit (`DATUMESH_RATE_SERIES_PER_IP`,
80    /// default 30; burst the same), so that a crawler that misses the cache cannot load the mesh.
81    pub series_per_ip: u32,
82    /// `POST /x/keys` per minute per IP, besides the per-IP limit (`DATUMESH_RATE_KEYS_PER_IP`, default 5;
83    /// burst the same). Every `POST` counts, whatever its outcome (QUESTIONS-build2 D39).
84    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/// Cache lifetimes. Content-addressed objects (descriptors, receipts, manifests, blobs) never
104/// expire: their bytes are fixed by their hash.
105#[non_exhaustive]
106#[derive(Clone, Debug, PartialEq, Eq)]
107pub struct Ttls {
108    /// A foreign host's key document (default 300 s). A receipt signed with a key id the
109    /// cached document lacks refetches it at once (at most every `key_refetch`).
110    pub key_doc: Duration,
111    /// The shortest interval between two fetches of one host's key document (default 10 s).
112    pub key_refetch: Duration,
113    /// A foreign host's mesh document (default 300 s).
114    pub mesh_doc: Duration,
115    /// How long a foreign name's binding, confirmed with its mesh, stands for requests
116    /// without an asof or with a later one (default 60 s).
117    pub binding: Duration,
118    /// How long a foreign cell's latest version, confirmed with its mesh, stands for requests
119    /// without an asof or with a later one (default 60 s).
120    pub current: Duration,
121    /// `max-age` of answers to requests without an asof (default 10 s).
122    pub latest_max_age: Duration,
123    /// How long a completed job's result is kept after it is first served, and after it
124    /// completes when it is never served, while the mesh runs (default and minimum 300 s, SPEC 5.5).
125    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/// What a function's cells need (the licence and payment stubs of step 1.4).
143#[non_exhaustive]
144#[derive(Clone, Debug, PartialEq, Eq)]
145pub enum Rule {
146    /// Only these principals (API key owners) may receive the function's cells; anyone
147    /// else is answered `unlicensed`.
148    Principals(Vec<String>),
149    /// The function's cells are sold: `payment_required` with this quote (a stub until
150    /// prepaid balances, 3.3).
151    Price {
152        /// The amount (SPEC 3.1, greater than zero).
153        amount: String,
154        /// A currency code of `units.md`.
155        currency: String,
156    },
157}
158
159/// Per-function rules, by fully qualified function name. Functions without one are free.
160#[non_exhaustive]
161#[derive(Clone, Debug, Default, PartialEq, Eq)]
162pub struct Policy {
163    /// The rules.
164    pub rules: BTreeMap<String, Rule>,
165}
166
167impl Policy {
168    /// The rule of a function, if any.
169    pub fn rule(&self, fn_name: &str) -> Option<&Rule> {
170        self.rules.get(fn_name)
171    }
172
173    /// From JSON: `{"<function>": {"principals": ["..."]} | {"price": {"amount", "currency"}}}`.
174    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/// The mesh's configuration.
205#[non_exhaustive]
206#[derive(Clone, Debug)]
207pub struct Config {
208    /// The DNS name the mesh signs as (`computed_by`) and serves on: `https://<host>/...`
209    /// (e.g. `mesh-test.datumesh.com`), unless [`Config::base_url`] says otherwise.
210    pub host: String,
211    /// Where the mesh is served when not at `https://<host>`, e.g. `http://127.0.0.1:8787`
212    /// for a mesh on this machine (default: none): the base of every URL in the mesh
213    /// document (`bindings` and the endpoints, [`crate::Mesh::mesh_document`]). `https://`
214    /// with any host; `http://` only when the mesh's `host` is unrooted (its last label is
215    /// `invalid`, SPEC 2.5, e.g. `local.invalid`) and only with `127.0.0.1`, `[::1]` or
216    /// `localhost`; an optional port; no path, query, fragment or trailing slash
217    /// ([`check_base_url`]; [`crate::MeshBuilder::build`] refuses another with
218    /// [`crate::BuildError::BaseUrl`]).
219    ///
220    /// An `http://` mesh document is for local use only: it is not valid under spec-0.4.3
221    /// (9.6 wants `https://` URLs on the host), and core 0.3.6's `resolve_mesh` refuses it.
222    /// spec-0.4.4 will allow exactly this: for an unrooted host, mesh-document URLs and
223    /// `poll` may be `http://` on a loopback address only (`127.0.0.1`, `[::1]`,
224    /// `localhost`); rooted hosts stay `https://`-only. datumesh-core 0.3.8 will accept it.
225    /// The key document and `host` do not change, nor do the URLs in envelopes and headers
226    /// (a `pending` envelope's `poll`, a page's `next`, the `canonical` link), which stay
227    /// [`Config::origin`]: SPEC 5.5 makes `poll` an `https://` URL, and a client maps
228    /// `https://<host>/` onto where it reaches the mesh (its peers).
229    pub base_url: Option<String>,
230    /// The hosts whose names this mesh owns (default: `host`). A name under any other host
231    /// is resolved across meshes.
232    pub namespaces: Vec<String>,
233    /// The wall-clock budget of a request before it is answered `pending` (default 1 s).
234    pub budget: Duration,
235    /// The blocking pool's size: the concurrency limit (default 32).
236    pub pool_size: usize,
237    /// The most cells in one `POST /cells` (default 1,000).
238    pub batch_max: usize,
239    /// Whether each held test is a signed cell (trust `primary`) `<host>/test_case(function_hash, case)` (E5:
240    /// `DATUMESH_TEST_CELLS=1`, mesh-test). Off on production: no test cells until named.
241    pub test_cells: bool,
242    /// The default JSON page of `GET /slice` (default 1,000; at most 10,000 with `limit=`).
243    pub slice_page: usize,
244    /// The most members one slice read serves (default 1,048,576).
245    pub slice_max: usize,
246    /// The most subjects the catalogue lists (default 100,000; `DATUMESH_CATALOG_MAX`).
247    pub catalog_max: usize,
248    /// The depth of `GET /explain` by default (default 4; at most 16 with `depth=`).
249    pub explain_depth: usize,
250    /// The most jobs held at once, running or done (default 10,000).
251    pub max_jobs: usize,
252    /// The most members an evaluation started by a request may store as a manifest (default 0:
253    /// none; `DATUMESH_MANIFEST_STORE_MAX`). At 0 the engine keeps only member-set rows, and a
254    /// manifest is rebuilt on demand (guard patch G4).
255    pub manifest_store_max: usize,
256    /// How long a request waits for the writers in flight (the store's barrier) before it fails 503
257    /// `E_INPUT_UNAVAILABLE` (default 5 s; `DATUMESH_BARRIER_TIMEOUT_MS`; second review B3).
258    pub barrier_timeout: Duration,
259    /// Rate limits.
260    pub rate: RateLimits,
261    /// Cache lifetimes.
262    pub ttl: Ttls,
263    /// Take the client IP from the last `X-Forwarded-For` entry (behind Caddy) instead of
264    /// the peer address (default false).
265    pub trust_proxy: bool,
266    /// Resolve names under hosts this mesh does not own (default true).
267    pub cross_mesh: bool,
268    /// When set, the only other hosts whose names are resolved across meshes; names under
269    /// any other host are not served (`not_covered`). Default: every host.
270    pub cross_mesh_hosts: Option<Vec<String>>,
271    /// Origins to use instead of `https://<host>` for some hosts, e.g. `mesh-b.example` ->
272    /// `http://127.0.0.1:8081` (tests and private networks only; the default is none).
273    pub peers: BTreeMap<String, String>,
274    /// The time limit of one request to another mesh (default 10 s; SPEC 9.3's bound).
275    pub peer_timeout: Duration,
276    /// Short names of the call syntax: `@alias` -> fully qualified name.
277    pub aliases: BTreeMap<String, String>,
278    /// Licence and payment rules.
279    pub policy: Policy,
280    /// Descriptions of the functions `GET /find` searches (name -> description).
281    pub catalog: BTreeMap<String, String>,
282    /// The embedding service's base URL (`DATUMESH_EMBED_URL`, e.g. `http://embed:8080`): vector
283    /// `find` is on when it is set and the store has vectors (default none). Since 0.4.0.
284    pub embed_url: Option<String>,
285    /// API keys (`Authorization: Bearer dm_...`).
286    pub api_keys: ApiKeys,
287    /// The hosts that may publish with `POST /bundles` besides the mesh's own namespaces
288    /// (`DATUMESH_PUBLISH_DOMAINS`; Build 2 Part 4, D11). Default: none.
289    pub publish_domains: PublishDomains,
290    /// Where the operator's log of `POST /bundles` goes (`DATUMESH_LOG_DIR`, the file
291    /// `bundles.log` in it); default none, no log.
292    pub log_dir: Option<std::path::PathBuf>,
293    /// The series with month or year pages (`DATUMESH_SERIES_FILE`, Build 2 Part 6); none: no pages.
294    pub(crate) series: Vec<crate::series::SeriesPage>,
295    /// Whether a key of a publisher can be registered for a namespace of its own: `DATUMESH_KEY_NAMES=1`
296    /// turns `GET /x/keys/challenge` and `POST /x/keys` on (QUESTIONS-build2 D39). Default off; any other
297    /// value is off too.
298    pub key_names: bool,
299    /// How long a registration challenge is valid (`DATUMESH_KEY_CHALLENGE_TTL_SECS`; default 300 s).
300    pub key_challenge_ttl: Duration,
301    /// The address the takeover page names for a source that wants to take over (`DATUMESH_CONTACT`,
302    /// D40). Default none: the page names no address.
303    pub contact: Option<String>,
304    /// How long the first build of the series overview waits after start (`DATUMESH_SERIES_FIRST_BUILD_DELAY_SECS`;
305    /// default 0). Until that build is done the sitemap and the index answer `503`.
306    pub series_first_build_delay: Duration,
307    /// How often the series overview is rebuilt (`DATUMESH_SERIES_REFRESH_SECS`; default 300 s, at least 1 s).
308    pub series_refresh: Duration,
309    /// How long the first build of the catalogue pages waits after start (`DATUMESH_CATALOG_FIRST_BUILD_DELAY_SECS`;
310    /// default 0). Until that build is done the catalogue's pages and the root of its `describe` answer `503`.
311    pub catalog_first_build_delay: Duration,
312    /// How often the catalogue pages are rebuilt (`DATUMESH_CATALOG_REFRESH_SECS`; default 300 s, at least 1 s).
313    pub catalog_refresh: Duration,
314    /// How long the first build of the object index (`describe` of an object id) waits after start
315    /// (`DATUMESH_INDEX_FIRST_BUILD_DELAY_SECS`; default 0). Until it is built, such a request is `503`.
316    pub index_first_build_delay: Duration,
317    /// How often the object index is built again (`DATUMESH_INDEX_SECS`; default 300 s, at least 1 s). A full build
318    /// reads each heard-of class's declared list in pages (CONTRACT-round-0.7-P HP2, HP3); nothing else rebuilds it.
319    pub index_secs: Duration,
320    /// The most objects one class holds in the object index (`DATUMESH_INDEX_CLASS_MAX`; default 50,000, at least 1).
321    /// A class past it keeps its first objects in cell-id order and is counted in
322    /// `datumesh_object_index_truncated_total`.
323    pub index_class_max: usize,
324    /// The most objects the object index holds in all (`DATUMESH_INDEX_MAX`; default 200,000, at least 1).
325    pub index_max: usize,
326    /// How long the first build of the `find` summary and the empty query waits after start
327    /// (`DATUMESH_FIND_FIRST_BUILD_DELAY_SECS`; default 0). Until it is built, those requests are `503`.
328    pub find_first_build_delay: Duration,
329    /// How often the value counts of the catalogue are refreshed (`DATUMESH_VALUE_COUNTS_SECS`; default 3600 s,
330    /// at least 1 s; and once at start).
331    pub value_counts_refresh: Duration,
332    /// The most distinct values a string key takes from the cells of a function before it is open
333    /// (`DATUMESH_DICTIONARY_MAX`; default 1000, at least 1; CONTRACT-0.4.9 H7).
334    pub dictionary_max: usize,
335}
336
337/// Which hosts may publish with `POST /bundles` (`DATUMESH_PUBLISH_DOMAINS`): the mesh's own
338/// namespaces always; then none (the default), named hosts, or any host with a valid key
339/// document (`*`).
340#[non_exhaustive]
341#[derive(Clone, Debug, PartialEq, Eq, Default)]
342pub enum PublishDomains {
343    /// The mesh's own namespaces only.
344    #[default]
345    Own,
346    /// These hosts, besides the mesh's own namespaces.
347    Hosts(Vec<String>),
348    /// Any host whose key document the mesh can check.
349    Any,
350}
351
352impl PublishDomains {
353    /// Parses the variable's value: empty is `Own`, `*` is `Any`, else a comma-separated list of
354    /// hosts (spaces allowed).
355    pub fn parse(v: &str) -> Result<PublishDomains, ConfigError> {
356        let v = v.trim();
357        if v.is_empty() {
358            return Ok(PublishDomains::Own);
359        }
360        if v == "*" {
361            return Ok(PublishDomains::Any);
362        }
363        let mut hosts = Vec::new();
364        for h in v.split(',').map(str::trim).filter(|h| !h.is_empty()) {
365            lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("DATUMESH_PUBLISH_DOMAINS", e.to_string()))?;
366            hosts.push(h.to_string());
367        }
368        Ok(if hosts.is_empty() { PublishDomains::Own } else { PublishDomains::Hosts(hosts) })
369    }
370
371    /// Whether a bundle of `host` (not one of the mesh's own namespaces) may be published.
372    pub fn allows(&self, host: &str) -> bool {
373        match self {
374            PublishDomains::Own => false,
375            PublishDomains::Hosts(h) => h.iter().any(|x| x == host),
376            PublishDomains::Any => true,
377        }
378    }
379}
380
381impl Config {
382    /// The defaults for a mesh signing as `host`.
383    pub fn new(host: impl Into<String>) -> Config {
384        let host = host.into();
385        Config {
386            namespaces: vec![host.clone()],
387            host,
388            base_url: None,
389            budget: DEFAULT_BUDGET,
390            pool_size: DEFAULT_POOL_SIZE,
391            batch_max: DEFAULT_BATCH_MAX,
392            test_cells: false,
393            slice_page: DEFAULT_SLICE_PAGE,
394            slice_max: MAX_SLICE_MEMBERS,
395            catalog_max: crate::catalog_build::DEFAULT_CATALOG_MAX,
396            explain_depth: 4,
397            max_jobs: 10_000,
398            manifest_store_max: 0,
399            barrier_timeout: DEFAULT_BARRIER_TIMEOUT,
400            rate: RateLimits::default(),
401            ttl: Ttls::default(),
402            trust_proxy: false,
403            cross_mesh: true,
404            cross_mesh_hosts: None,
405            peers: BTreeMap::new(),
406            peer_timeout: Duration::from_secs(10),
407            aliases: BTreeMap::new(),
408            policy: Policy::default(),
409            catalog: BTreeMap::new(),
410            embed_url: None,
411            api_keys: ApiKeys::default(),
412            publish_domains: PublishDomains::Own,
413            key_names: false,
414            key_challenge_ttl: Duration::from_secs(300),
415            contact: None,
416            series_first_build_delay: Duration::ZERO,
417            series_refresh: Duration::from_secs(300),
418            catalog_first_build_delay: Duration::ZERO,
419            catalog_refresh: Duration::from_secs(300),
420            index_first_build_delay: Duration::ZERO,
421            index_secs: Duration::from_secs(300),
422            index_class_max: 50_000,
423            index_max: 200_000,
424            find_first_build_delay: Duration::ZERO,
425            value_counts_refresh: Duration::from_secs(3600),
426            dictionary_max: 1000,
427            log_dir: None,
428            series: Vec::new(),
429        }
430    }
431
432    /// The configuration with this base URL ([`Config::base_url`]); it is checked when the
433    /// mesh is built.
434    pub fn with_base_url(mut self, url: impl Into<String>) -> Config {
435        self.base_url = Some(url.into());
436        self
437    }
438
439    /// The configuration from the environment (`DATUMESH_*`; the README lists them). The
440    /// files named (`DATUMESH_API_KEYS_FILE`, and the others) are read here; the API keys
441    /// file must have mode 0600.
442    pub fn from_env() -> Result<Config, ConfigError> {
443        Config::from_vars(|k| std::env::var(k).ok())
444    }
445
446    /// The configuration from variables `get` answers, as [`Config::from_env`] reads them.
447    pub fn from_vars(get: impl Fn(&str) -> Option<String>) -> Result<Config, ConfigError> {
448        let host = get("DATUMESH_HOST").ok_or_else(|| ConfigError::new("DATUMESH_HOST", "not set"))?;
449        let mut c = Config::new(host);
450        if let Some(v) = get("DATUMESH_BASE_URL").filter(|v| !v.is_empty()) {
451            c.base_url = Some(v);
452        }
453        if let Some(v) = get("DATUMESH_NAMESPACES") {
454            c.namespaces = v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
455        }
456        let ms = |k: &str, d: Duration| -> Result<Duration, ConfigError> {
457            match get(k) {
458                Some(v) => v.parse::<u64>().map(Duration::from_millis).map_err(|e| ConfigError::new(k, e.to_string())),
459                None => Ok(d),
460            }
461        };
462        let secs = |k: &str, d: Duration| -> Result<Duration, ConfigError> {
463            match get(k) {
464                Some(v) => v.parse::<u64>().map(Duration::from_secs).map_err(|e| ConfigError::new(k, e.to_string())),
465                None => Ok(d),
466            }
467        };
468        let num = |k: &str, d: usize| -> Result<usize, ConfigError> {
469            match get(k) {
470                Some(v) => v.parse::<usize>().map_err(|e| ConfigError::new(k, e.to_string())),
471                None => Ok(d),
472            }
473        };
474        let flag = |k: &str, d: bool| -> Result<bool, ConfigError> {
475            match get(k).as_deref() {
476                None => Ok(d),
477                Some("1" | "true" | "yes") => Ok(true),
478                Some("0" | "false" | "no") => Ok(false),
479                Some(v) => Err(ConfigError::new(k, format!("not a boolean: {v}"))),
480            }
481        };
482        c.budget = ms("DATUMESH_BUDGET_MS", c.budget)?;
483        c.pool_size = num("DATUMESH_POOL_SIZE", c.pool_size)?;
484        c.batch_max = num("DATUMESH_BATCH_MAX", c.batch_max)?;
485        c.test_cells = flag("DATUMESH_TEST_CELLS", c.test_cells)?;
486        c.slice_page = num("DATUMESH_SLICE_PAGE", c.slice_page)?;
487        c.slice_max = num("DATUMESH_SLICE_MAX", c.slice_max)?;
488        c.catalog_max = catalog_max_of(get("DATUMESH_CATALOG_MAX"))?;
489        c.explain_depth = num("DATUMESH_EXPLAIN_DEPTH", c.explain_depth)?;
490        c.max_jobs = num("DATUMESH_MAX_JOBS", c.max_jobs)?;
491        c.manifest_store_max = num("DATUMESH_MANIFEST_STORE_MAX", c.manifest_store_max)?;
492        c.barrier_timeout = barrier_timeout_of(get("DATUMESH_BARRIER_TIMEOUT_MS"))?;
493        c.trust_proxy = flag("DATUMESH_TRUST_PROXY", c.trust_proxy)?;
494        c.cross_mesh = flag("DATUMESH_CROSS_MESH", c.cross_mesh)?;
495        c.rate.enabled = flag("DATUMESH_RATE_LIMITS", c.rate.enabled)?;
496        c.rate.per_ip = num("DATUMESH_RATE_PER_IP", c.rate.per_ip as usize)? as u32;
497        c.rate.ip_burst = num("DATUMESH_RATE_IP_BURST", c.rate.ip_burst as usize)? as u32;
498        c.rate.per_key = num("DATUMESH_RATE_PER_KEY", c.rate.per_key as usize)? as u32;
499        c.rate.verify_per_ip = num("DATUMESH_RATE_VERIFY_PER_IP", c.rate.verify_per_ip as usize)? as u32;
500        c.rate.series_per_ip = num("DATUMESH_RATE_SERIES_PER_IP", c.rate.series_per_ip as usize)? as u32;
501        c.rate.calc_per_ip = num("DATUMESH_RATE_CALC_PER_IP", c.rate.calc_per_ip as usize)? as u32;
502        c.rate.keys_per_ip = num("DATUMESH_RATE_KEYS_PER_IP", c.rate.keys_per_ip as usize)? as u32;
503        // Off unless exactly `1` (an empty or other value is off too, not an error).
504        c.key_names = get("DATUMESH_KEY_NAMES").as_deref() == Some("1");
505        c.key_challenge_ttl = secs("DATUMESH_KEY_CHALLENGE_TTL_SECS", c.key_challenge_ttl)?;
506        c.contact = get("DATUMESH_CONTACT").map(|v| v.trim().to_string()).filter(|v| !v.is_empty());
507        c.series_first_build_delay = secs("DATUMESH_SERIES_FIRST_BUILD_DELAY_SECS", c.series_first_build_delay)?;
508        c.series_refresh = secs("DATUMESH_SERIES_REFRESH_SECS", c.series_refresh)?;
509        c.catalog_first_build_delay = secs("DATUMESH_CATALOG_FIRST_BUILD_DELAY_SECS", c.catalog_first_build_delay)?;
510        c.catalog_refresh = secs("DATUMESH_CATALOG_REFRESH_SECS", c.catalog_refresh)?;
511        c.index_first_build_delay = secs("DATUMESH_INDEX_FIRST_BUILD_DELAY_SECS", c.index_first_build_delay)?;
512        c.index_secs = secs("DATUMESH_INDEX_SECS", c.index_secs)?;
513        c.index_class_max = num("DATUMESH_INDEX_CLASS_MAX", c.index_class_max)?.max(1);
514        c.index_max = num("DATUMESH_INDEX_MAX", c.index_max)?.max(1);
515        c.find_first_build_delay = secs("DATUMESH_FIND_FIRST_BUILD_DELAY_SECS", c.find_first_build_delay)?;
516        c.value_counts_refresh = secs("DATUMESH_VALUE_COUNTS_SECS", c.value_counts_refresh)?;
517        c.dictionary_max = num("DATUMESH_DICTIONARY_MAX", c.dictionary_max)?;
518        c.ttl.key_doc = secs("DATUMESH_TTL_KEY_DOC", c.ttl.key_doc)?;
519        c.ttl.mesh_doc = secs("DATUMESH_TTL_MESH_DOC", c.ttl.mesh_doc)?;
520        c.ttl.binding = secs("DATUMESH_TTL_BINDING", c.ttl.binding)?;
521        c.ttl.current = secs("DATUMESH_TTL_CURRENT", c.ttl.current)?;
522        c.ttl.latest_max_age = secs("DATUMESH_LATEST_MAX_AGE", c.ttl.latest_max_age)?;
523        c.ttl.job = secs("DATUMESH_JOB_TTL", c.ttl.job)?;
524        c.peer_timeout = ms("DATUMESH_PEER_TIMEOUT_MS", c.peer_timeout)?;
525        if let Some(v) = get("DATUMESH_CROSS_MESH_HOSTS") {
526            c.cross_mesh_hosts = Some(v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect());
527        }
528        if let Some(v) = get("DATUMESH_PEERS") {
529            for pair in v.split(',').map(str::trim).filter(|s| !s.is_empty()) {
530                let (h, o) =
531                    pair.split_once('=').ok_or_else(|| ConfigError::new("DATUMESH_PEERS", "host=origin pairs"))?;
532                c.peers.insert(h.trim().to_string(), o.trim().trim_end_matches('/').to_string());
533            }
534        }
535        if let Some(p) = get("DATUMESH_ALIASES_FILE") {
536            c.aliases = string_map(&read_file(&p)?, "DATUMESH_ALIASES_FILE")?;
537        }
538        if let Some(p) = get("DATUMESH_CATALOG_FILE") {
539            c.catalog = string_map(&read_file(&p)?, "DATUMESH_CATALOG_FILE")?;
540        }
541        if let Some(v) = get("DATUMESH_EMBED_URL").filter(|v| !v.trim().is_empty()) {
542            c.embed_url = Some(v.trim().trim_end_matches('/').to_string());
543        }
544        if let Some(p) = get("DATUMESH_POLICY_FILE") {
545            c.policy = Policy::from_json(&read_file(&p)?)?;
546        }
547        if let Some(p) = get("DATUMESH_API_KEYS_FILE") {
548            c.api_keys = ApiKeys::parse(&read_secret_file(Path::new(&p))?)?;
549        }
550        c.publish_domains = PublishDomains::parse(&get("DATUMESH_PUBLISH_DOMAINS").unwrap_or_default())?;
551        if let Some(p) = get("DATUMESH_SERIES_FILE").filter(|p| !p.trim().is_empty()) {
552            c.series = crate::series::parse(&read_file(&p)?)?;
553        }
554        if let Some(d) = get("DATUMESH_LOG_DIR").filter(|d| !d.trim().is_empty()) {
555            c.log_dir = Some(std::path::PathBuf::from(d));
556        }
557        c.check()?;
558        Ok(c)
559    }
560
561    /// Checks the configuration: names are DNS names and function names, the base URL is
562    /// one ([`check_base_url`]), numbers in range.
563    pub fn check(&self) -> Result<(), ConfigError> {
564        lexical::check_dns_name(&self.host, "$").map_err(|e| ConfigError::new("host", e.to_string()))?;
565        if self.series_refresh < Duration::from_secs(1) {
566            return Err(ConfigError::new("DATUMESH_SERIES_REFRESH_SECS", "at least 1 second"));
567        }
568        if self.catalog_refresh < Duration::from_secs(1) {
569            return Err(ConfigError::new("DATUMESH_CATALOG_REFRESH_SECS", "at least 1 second"));
570        }
571        if self.value_counts_refresh < Duration::from_secs(1) {
572            return Err(ConfigError::new("DATUMESH_VALUE_COUNTS_SECS", "at least 1 second"));
573        }
574        if self.dictionary_max == 0 {
575            return Err(ConfigError::new("DATUMESH_DICTIONARY_MAX", "at least 1"));
576        }
577        if let Some(c) = &self.contact {
578            if c.chars().any(|ch| ch.is_whitespace() || ch.is_control()) {
579                return Err(ConfigError::new("DATUMESH_CONTACT", "an address without spaces"));
580            }
581        }
582        if let Some(u) = &self.base_url {
583            check_base_url(&self.host, u).map_err(|e| ConfigError::new("base URL", format!("{u}: {e}")))?;
584        }
585        for h in &self.namespaces {
586            lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("namespaces", e.to_string()))?;
587        }
588        for (h, o) in &self.peers {
589            lexical::check_dns_name(h, "$").map_err(|e| ConfigError::new("peers", e.to_string()))?;
590            if !(o.starts_with("http://") || o.starts_with("https://")) {
591                return Err(ConfigError::new("peers", format!("{o}: not an http(s) origin")));
592            }
593        }
594        for (a, n) in &self.aliases {
595            lexical::check_function_name(n, "$").map_err(|e| ConfigError::new("aliases", format!("{a}: {e}")))?;
596        }
597        if self.pool_size == 0 || self.batch_max == 0 || self.slice_page == 0 || self.slice_max == 0 {
598            return Err(ConfigError::new("sizes", "the pool, batch and slice bounds must be positive"));
599        }
600        if self.ttl.job < Duration::from_secs(300) {
601            return Err(ConfigError::new("job TTL", "at least 300 s (SPEC 5.5)"));
602        }
603        if self.budget.is_zero() {
604            return Err(ConfigError::new("budget", "must be positive"));
605        }
606        Ok(())
607    }
608
609    /// Whether this mesh owns the names under `host`.
610    pub fn owns(&self, host: &str) -> bool {
611        self.namespaces.iter().any(|h| h == host)
612    }
613
614    /// `https://<host>`: where this mesh is served, the base of the URLs in its envelopes.
615    pub fn origin(&self) -> String {
616        format!("https://{}", self.host)
617    }
618
619    /// The base of the URLs in the mesh document: the base URL when set, else
620    /// [`Config::origin`].
621    pub fn mesh_document_base(&self) -> String {
622        self.base_url.clone().unwrap_or_else(|| self.origin())
623    }
624}
625
626/// Why a base URL ([`Config::base_url`]) is refused.
627#[non_exhaustive]
628#[derive(Clone, Copy, Debug, PartialEq, Eq)]
629pub enum BaseUrlError {
630    /// Neither `https://` nor `http://` (lower case).
631    Scheme,
632    /// `http://` for a mesh whose host is rooted (not under `.invalid`, SPEC 2.5): rooted
633    /// hosts are served over `https://` only, whatever the base URL's host.
634    HttpRootedHost,
635    /// `http://` (for an unrooted host) with a host other than `127.0.0.1`, `[::1]` and
636    /// `localhost`.
637    HttpNotLoopback,
638    /// No host, userinfo, or a host that is neither a DNS name (lower case), an IPv4 address
639    /// nor an IPv6 address in brackets.
640    Host,
641    /// A port that is not a decimal number from 1 to 65535 (`:` with nothing after it too).
642    Port,
643    /// A path after the host and port.
644    Path,
645    /// A slash alone after the host and port.
646    TrailingSlash,
647    /// A query.
648    Query,
649    /// A fragment.
650    Fragment,
651}
652
653impl fmt::Display for BaseUrlError {
654    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
655        f.write_str(match self {
656            BaseUrlError::Scheme => "not an https:// or http:// URL",
657            BaseUrlError::HttpRootedHost => "http:// is for an unrooted host (under .invalid) only",
658            BaseUrlError::HttpNotLoopback => "http:// is for 127.0.0.1, [::1] and localhost only",
659            BaseUrlError::Host => "not a host name, IPv4 address or bracketed IPv6 address",
660            BaseUrlError::Port => "not a port from 1 to 65535",
661            BaseUrlError::Path => "a path (the base URL is a scheme, a host and a port)",
662            BaseUrlError::TrailingSlash => "a trailing slash",
663            BaseUrlError::Query => "a query",
664            BaseUrlError::Fragment => "a fragment",
665        })
666    }
667}
668
669impl std::error::Error for BaseUrlError {}
670
671/// Checks a base URL ([`Config::base_url`]) for a mesh signing as `host`: `https://` with any
672/// host, or, when `host` is unrooted ([`is_unrooted`]), `http://` with `127.0.0.1`, `[::1]`
673/// or `localhost`; then an optional `:<port>` (1 to 65535) and nothing else: no path, query,
674/// fragment, trailing slash or userinfo. The form is checked first, then the scheme's rule:
675/// `http://` for a rooted host is [`BaseUrlError::HttpRootedHost`] before anything about the
676/// URL's host.
677pub fn check_base_url(host: &str, url: &str) -> Result<(), BaseUrlError> {
678    let mesh_host = host;
679    let (http, rest) = if let Some(r) = url.strip_prefix("https://") {
680        (false, r)
681    } else if let Some(r) = url.strip_prefix("http://") {
682        (true, r)
683    } else {
684        return Err(BaseUrlError::Scheme);
685    };
686    if rest.contains('#') {
687        return Err(BaseUrlError::Fragment);
688    }
689    if rest.contains('?') {
690        return Err(BaseUrlError::Query);
691    }
692    let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
693    match path {
694        "" => {}
695        "/" => return Err(BaseUrlError::TrailingSlash),
696        _ => return Err(BaseUrlError::Path),
697    }
698    if authority.contains('@') {
699        return Err(BaseUrlError::Host);
700    }
701    let (host, port) = if let Some(r) = authority.strip_prefix('[') {
702        let (inside, after) = r.split_once(']').ok_or(BaseUrlError::Host)?;
703        inside.parse::<std::net::Ipv6Addr>().map_err(|_| BaseUrlError::Host)?;
704        let port = match after {
705            "" => None,
706            p => Some(p.strip_prefix(':').ok_or(BaseUrlError::Host)?),
707        };
708        (&authority[..inside.len() + 2], port)
709    } else {
710        let (host, port) = match authority.split_once(':') {
711            Some((h, p)) => (h, Some(p)),
712            None => (authority, None),
713        };
714        if host.parse::<std::net::Ipv4Addr>().is_err() && !is_dns_name(host) {
715            return Err(BaseUrlError::Host);
716        }
717        (host, port)
718    };
719    if let Some(p) = port {
720        let ok = !p.is_empty() && p.len() <= 5 && p.bytes().all(|b| b.is_ascii_digit());
721        if !ok || !(1..=65535).contains(&p.parse::<u32>().unwrap_or(0)) {
722            return Err(BaseUrlError::Port);
723        }
724    }
725    if http && !is_unrooted(mesh_host) {
726        return Err(BaseUrlError::HttpRootedHost);
727    }
728    if http && !matches!(host, "127.0.0.1" | "[::1]" | "localhost") {
729        return Err(BaseUrlError::HttpNotLoopback);
730    }
731    Ok(())
732}
733
734/// Whether a host is unrooted (SPEC 2.5, spec-0.4.3): its last label is `invalid`
735/// (`local.invalid`, `agent-7.local.invalid`). Every other host is rooted.
736pub fn is_unrooted(host: &str) -> bool {
737    host.rsplit('.').next() == Some("invalid")
738}
739
740/// A DNS name in lower case: labels of 1 to 63 of `a-z`, `0-9` and `-`, not starting or
741/// ending with `-`, at most 253 characters.
742fn is_dns_name(h: &str) -> bool {
743    !h.is_empty()
744        && h.len() <= 253
745        && h.split('.').all(|l| {
746            !l.is_empty()
747                && l.len() <= 63
748                && !l.starts_with('-')
749                && !l.ends_with('-')
750                && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
751        })
752}
753
754fn string_map(bytes: &[u8], what: &str) -> Result<BTreeMap<String, String>, ConfigError> {
755    let v = json::parse(bytes).map_err(|e| ConfigError::new(what, e.to_string()))?;
756    let mut out = BTreeMap::new();
757    for (k, x) in v.as_object().ok_or_else(|| ConfigError::new(what, "not an object"))? {
758        let s = x.as_str().ok_or_else(|| ConfigError::new(what, format!("{k}: not a string")))?;
759        out.insert(k.clone(), s.to_string());
760    }
761    Ok(out)
762}
763
764fn read_file(path: &str) -> Result<Vec<u8>, ConfigError> {
765    std::fs::read(path).map_err(|e| ConfigError::new(path, e.to_string()))
766}
767
768/// Reads a file holding a secret, refusing it unless only its owner may read or write it
769/// (mode 0600 or stricter, on Unix).
770pub fn read_secret_file(path: &Path) -> Result<Vec<u8>, ConfigError> {
771    let what = path.display().to_string();
772    let meta = std::fs::metadata(path).map_err(|e| ConfigError::new(&what, e.to_string()))?;
773    #[cfg(unix)]
774    {
775        use std::os::unix::fs::PermissionsExt;
776        let mode = meta.permissions().mode() & 0o777;
777        if mode & 0o077 != 0 {
778            return Err(ConfigError::new(&what, format!("mode {mode:o}: a secret file must be 0600")));
779        }
780    }
781    #[cfg(not(unix))]
782    let _ = meta;
783    std::fs::read(path).map_err(|e| ConfigError::new(&what, e.to_string()))
784}
785
786/// A configuration error: what and why.
787#[derive(Clone, Debug, PartialEq, Eq)]
788pub struct ConfigError {
789    what: String,
790    detail: String,
791}
792
793impl ConfigError {
794    pub(crate) fn new(what: &str, detail: impl Into<String>) -> ConfigError {
795        ConfigError { what: what.to_string(), detail: detail.into() }
796    }
797}
798
799impl fmt::Display for ConfigError {
800    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
801        write!(f, "configuration: {}: {}", self.what, self.detail)
802    }
803}
804
805impl std::error::Error for ConfigError {}