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