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    /// The hosts whose meshes this mesh lists (`DATUMESH_LISTED_MESHES`, comma-separated; default none; CONTRACT-http-listing
336    /// L1, since 0.6.0): their functions as descriptions only, no cells. Refused by [`Config::check`]: a host that is one
337    /// of [`Config::namespaces`], a host that is not a DNS name, more than 64 hosts. Empty: nothing is fetched.
338    pub listed_meshes: Vec<String>,
339    /// How often each listed host is fetched (`DATUMESH_LISTING_INTERVAL_SECS`; default 21,600 s; at least 1 s).
340    pub listing_interval: Duration,
341    /// How long the listing thread waits after start before its first run (`DATUMESH_LISTING_FIRST_DELAY_SECS`; default 0).
342    pub listing_first_delay: Duration,
343}
344
345/// Which hosts may publish with `POST /bundles` (`DATUMESH_PUBLISH_DOMAINS`): the mesh's own
346/// namespaces always; then none (the default), named hosts, or any host with a valid key
347/// document (`*`).
348#[non_exhaustive]
349#[derive(Clone, Debug, PartialEq, Eq, Default)]
350pub enum PublishDomains {
351    /// The mesh's own namespaces only.
352    #[default]
353    Own,
354    /// These hosts, besides the mesh's own namespaces.
355    Hosts(Vec<String>),
356    /// Any host whose key document the mesh can check.
357    Any,
358}
359
360impl PublishDomains {
361    /// Parses the variable's value: empty is `Own`, `*` is `Any`, else a comma-separated list of
362    /// hosts (spaces allowed).
363    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    /// Whether a bundle of `host` (not one of the mesh's own namespaces) may be published.
380    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    /// The defaults for a mesh signing as `host`.
391    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    /// The configuration with this base URL ([`Config::base_url`]); it is checked when the
444    /// mesh is built.
445    pub fn with_base_url(mut self, url: impl Into<String>) -> Config {
446        self.base_url = Some(url.into());
447        self
448    }
449
450    /// The configuration from the environment (`DATUMESH_*`; the README lists them). The
451    /// files named (`DATUMESH_API_KEYS_FILE`, and the others) are read here; the API keys
452    /// file must have mode 0600.
453    pub fn from_env() -> Result<Config, ConfigError> {
454        Config::from_vars(|k| std::env::var(k).ok())
455    }
456
457    /// The configuration from variables `get` answers, as [`Config::from_env`] reads them.
458    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        // Off unless exactly `1` (an empty or other value is off too, not an error).
515        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            // A host named twice counts once (smaller 4), in the order it is first named.
548            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    /// Checks the configuration: names are DNS names and function names, the base URL is
583    /// one ([`check_base_url`]), numbers in range.
584    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            // C3 (re-review, decided 27 Nov): a listed host may not also publish here or be resolved here.
643            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    /// Whether this mesh owns the names under `host`.
660    pub fn owns(&self, host: &str) -> bool {
661        self.namespaces.iter().any(|h| h == host)
662    }
663
664    /// `https://<host>`: where this mesh is served, the base of the URLs in its envelopes.
665    pub fn origin(&self) -> String {
666        format!("https://{}", self.host)
667    }
668
669    /// The base of the URLs in the mesh document: the base URL when set, else
670    /// [`Config::origin`].
671    pub fn mesh_document_base(&self) -> String {
672        self.base_url.clone().unwrap_or_else(|| self.origin())
673    }
674}
675
676/// Why a base URL ([`Config::base_url`]) is refused.
677#[non_exhaustive]
678#[derive(Clone, Copy, Debug, PartialEq, Eq)]
679pub enum BaseUrlError {
680    /// Neither `https://` nor `http://` (lower case).
681    Scheme,
682    /// `http://` for a mesh whose host is rooted (not under `.invalid`, SPEC 2.5): rooted
683    /// hosts are served over `https://` only, whatever the base URL's host.
684    HttpRootedHost,
685    /// `http://` (for an unrooted host) with a host other than `127.0.0.1`, `[::1]` and
686    /// `localhost`.
687    HttpNotLoopback,
688    /// No host, userinfo, or a host that is neither a DNS name (lower case), an IPv4 address
689    /// nor an IPv6 address in brackets.
690    Host,
691    /// A port that is not a decimal number from 1 to 65535 (`:` with nothing after it too).
692    Port,
693    /// A path after the host and port.
694    Path,
695    /// A slash alone after the host and port.
696    TrailingSlash,
697    /// A query.
698    Query,
699    /// A fragment.
700    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
721/// Checks a base URL ([`Config::base_url`]) for a mesh signing as `host`: `https://` with any
722/// host, or, when `host` is unrooted ([`is_unrooted`]), `http://` with `127.0.0.1`, `[::1]`
723/// or `localhost`; then an optional `:<port>` (1 to 65535) and nothing else: no path, query,
724/// fragment, trailing slash or userinfo. The form is checked first, then the scheme's rule:
725/// `http://` for a rooted host is [`BaseUrlError::HttpRootedHost`] before anything about the
726/// URL's host.
727pub 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
784/// Whether a host is unrooted (SPEC 2.5, spec-0.4.3): its last label is `invalid`
785/// (`local.invalid`, `agent-7.local.invalid`). Every other host is rooted.
786pub fn is_unrooted(host: &str) -> bool {
787    host.rsplit('.').next() == Some("invalid")
788}
789
790/// A DNS name in lower case: labels of 1 to 63 of `a-z`, `0-9` and `-`, not starting or
791/// ending with `-`, at most 253 characters.
792fn 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
818/// Reads a file holding a secret, refusing it unless only its owner may read or write it
819/// (mode 0600 or stricter, on Unix).
820pub 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/// A configuration error: what and why.
837#[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 {}