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