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