Skip to main content

datumesh_core/
mesh.rs

1//! Mesh documents (9.6) and cross-mesh resolution, `spec-0.4.1`. A verifier never needs them.
2
3use std::collections::BTreeMap;
4
5use crate::error::{err, member, ErrorCode, Result};
6use crate::json::{self, Value};
7use crate::keys::{key_doc, KeyDoc};
8use crate::lexical;
9use crate::lexical::limits;
10use crate::licence::Declarations;
11use crate::schema;
12
13/// The endpoints of 9.6: name, placeholders, whether required.
14const ENDPOINTS: [(&str, &[&str], bool); 14] = [
15    ("blob", &["sha256"], false),
16    ("cell", &["cell"], true),
17    ("cells", &[], false),
18    ("describe", &["id"], false),
19    ("descriptor", &["hash"], true),
20    ("explain", &["cell"], false),
21    ("find", &[], false),
22    ("jobs", &["job"], true),
23    ("manifest", &["slice_id", "members_hash"], true),
24    ("receipt", &["hash"], true),
25    ("slice", &["cell"], false),
26    ("verify", &[], false),
27    ("versions", &["cell"], false),
28    // spec-0.6.0: a read with overrides (5.9); no placeholders, and optional.
29    ("whatif", &[], false),
30];
31
32/// What one HTTPS `GET` of a document gave, as the caller's HTTP client saw it.
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub enum Retrieval<'a> {
35    /// A response: its status and body (`None` when there was none).
36    Response {
37        /// The integer HTTP status.
38        status: u16,
39        /// The body.
40        body: Option<&'a [u8]>,
41    },
42    /// No response: a network, DNS, TLS or timeout failure, a redirect, or a retrieval the
43    /// client abandoned.
44    Failed,
45}
46
47/// A checked mesh document (9.6): the host's bindings URL and its known endpoint templates.
48/// Unknown members are dropped.
49#[derive(Clone, Debug, PartialEq, Eq, Hash)]
50#[non_exhaustive]
51pub struct MeshDoc {
52    /// The host it was fetched from (and names).
53    pub host: String,
54    /// The URL of the bindings resource (9.7).
55    pub bindings: String,
56    /// The known endpoints present, by name (`cell`, `receipt`, `jobs`, ...): URL templates
57    /// with their placeholders, such as `https://<host>/cell/{cell}`.
58    pub endpoints: BTreeMap<String, String>,
59}
60
61impl MeshDoc {
62    /// Parses and checks a mesh document fetched from `host`, on its own (without the key
63    /// document): strict JSON, an object, `host` equal to `host`, `proto` `"datumesh/1"`, then
64    /// `bindings`, `endpoints` (an object holding every required endpoint) and each known
65    /// endpoint in ascending name order (9.6): on this host (beginning `https://<host>/`), with
66    /// its placeholders each once and no other brace. Unknown members are not checked. Every
67    /// failure is `E_MESH_DOC`. Cross-mesh resolution also needs the key document to agree:
68    /// see [`resolve_mesh`].
69    pub fn from_json(host: &str, body: &[u8]) -> Result<MeshDoc> {
70        let v = parse_mesh(body)?;
71        let m = v.as_object().unwrap_or(&[]);
72        if schema::get(m, "host").as_str() != Some(host) {
73            return err(ErrorCode::MeshDoc, "$.host", "the mesh document names another host");
74        }
75        if schema::get(m, "proto").as_str() != Some("datumesh/1") {
76            return err(ErrorCode::MeshDoc, "$.proto", "proto must be datumesh/1");
77        }
78        mesh_members(host, m)
79    }
80
81    /// The URL of endpoint `name` with its placeholders replaced: `values` must give each of
82    /// the template's placeholders exactly once and nothing else (by name, without braces).
83    /// Values are inserted as given: percent-encode them first where 5.1 says. `None` for an
84    /// endpoint the document does not have, or values that do not match its placeholders.
85    pub fn url(&self, name: &str, values: &[(&str, &str)]) -> Option<String> {
86        let template = self.endpoints.get(name)?;
87        let (_, placeholders, _) = ENDPOINTS.iter().find(|(n, _, _)| *n == name)?;
88        if values.len() != placeholders.len() || !placeholders.iter().all(|p| values.iter().any(|(k, _)| k == p)) {
89            return None;
90        }
91        let mut out = template.clone();
92        for (k, v) in values {
93            out = out.replacen(&format!("{{{k}}}"), v, 1);
94        }
95        Some(out)
96    }
97}
98
99/// A host accepted by cross-mesh resolution: its key document and its mesh document.
100#[derive(Clone, Debug, PartialEq, Eq, Hash)]
101#[non_exhaustive]
102pub struct ResolvedMesh {
103    /// The key document (9.2).
104    pub keys: KeyDoc,
105    /// The mesh document (9.6).
106    pub mesh: MeshDoc,
107    /// The key document's `declarations` (9.2, `spec-0.4.3`), checked with it in step 5; `None`
108    /// when it has none.
109    pub declarations: Option<Declarations>,
110}
111
112/// Cross-mesh resolution of `host` (9.6, `spec-0.4.1`), from what `GET
113/// https://<host>/.well-known/datumesh.json` and `GET
114/// https://<host>/.well-known/datumesh-mesh.json` gave. Separate from verification, which never
115/// needs it; it fetches nothing. In the order of 9.6, the first failure is reported:
116///
117/// 1. the key document retrieved as in 9.3 (`E_KEY_UNAVAILABLE`; a 200 without a body is
118///    `E_KEY_DOC`);
119/// 2. the mesh document retrieved: the integer status 200 with a body (`E_MESH_DOC`);
120/// 3. both parsed strictly: the key document (`E_KEY_DOC`), then the mesh document, an object
121///    (`E_MESH_DOC`);
122/// 4. the two describe the same mesh (`E_MESH_DOC`): the mesh document's `host` is `host` and its
123///    `proto` `"datumesh/1"`; the key document's `host` and `proto`, each where it is a string in
124///    an object, too (anything else about the key document is left to step 5);
125/// 5. the key document by 9.2 (`E_KEY_DOC`);
126/// 6. the mesh document's members (`E_MESH_DOC`, see [`MeshDoc::from_json`]).
127pub fn resolve_mesh(host: &str, key_doc_got: Retrieval<'_>, mesh_doc_got: Retrieval<'_>) -> Result<ResolvedMesh> {
128    // 1.
129    let key_body = match key_doc_got {
130        Retrieval::Response { status: 200, body: Some(b) } => b,
131        Retrieval::Response { status: 200, body: None } => {
132            return err(ErrorCode::KeyDoc, "$", "a 200 response without a key document");
133        }
134        _ => return err(ErrorCode::KeyUnavailable, "$", "the key document could not be retrieved"),
135    };
136    // 2.
137    let Retrieval::Response { status: 200, body: Some(mesh_body) } = mesh_doc_got else {
138        return err(ErrorCode::MeshDoc, "$", "the mesh document could not be retrieved");
139    };
140    // 3.
141    let kv = json::parse(key_body).map_err(|e| e.recode(ErrorCode::KeyDoc))?;
142    let mv = parse_mesh(mesh_body)?;
143    let mm = mv.as_object().unwrap_or(&[]);
144    // 4.
145    if schema::get(mm, "host").as_str() != Some(host) {
146        return err(ErrorCode::MeshDoc, "$.host", "the mesh document names another host than the one fetched");
147    }
148    if schema::get(mm, "proto").as_str() != Some("datumesh/1") {
149        return err(ErrorCode::MeshDoc, "$.proto", "the mesh document's proto is not datumesh/1");
150    }
151    if let Value::Object(km) = &kv {
152        if let Some(Value::String(h)) = schema::opt(km, "host") {
153            if h != host {
154                return err(ErrorCode::MeshDoc, "$.host", "the key document names another host");
155            }
156        }
157        // Compared only where it is a string (3f79313); otherwise step 5 gives E_KEY_DOC.
158        if let Some(Value::String(p)) = schema::opt(km, "proto") {
159            if p != "datumesh/1" {
160                return err(ErrorCode::MeshDoc, "$.proto", "the key document names another protocol");
161            }
162        }
163    }
164    // 5.
165    let doc = key_doc(host, &kv)?;
166    // 6.
167    let mesh = mesh_members(host, mm)?;
168    Ok(ResolvedMesh { keys: doc.keys, mesh, declarations: doc.declarations })
169}
170
171fn parse_mesh(body: &[u8]) -> Result<Value> {
172    let v = json::parse(body).map_err(|e| e.recode(ErrorCode::MeshDoc))?;
173    if !matches!(v, Value::Object(_)) {
174        return err(ErrorCode::MeshDoc, "$", "a mesh document is a JSON object");
175    }
176    Ok(v)
177}
178
179/// The origin of a URL of a mesh document of `host` (9.6): `https://`, printable ASCII, at most
180/// 512 characters, its authority exactly `host`, followed by a path; for an unrooted host, also
181/// a loopback URL (`spec-0.5.0`, [`lexical::loopback_origin`]). `None` when it is neither.
182fn url_origin(u: &str, host: &str) -> Option<String> {
183    if let Some(rest) = u.strip_prefix("https://") {
184        let on_host = u.len() <= limits::LICENCE_URL
185            && rest.bytes().all(|c| (0x21..=0x7E).contains(&c))
186            && rest.strip_prefix(host).is_some_and(|path| path.starts_with('/'));
187        return on_host.then(|| format!("https://{host}"));
188    }
189    if lexical::is_unrooted(host) {
190        return lexical::loopback_origin(u).map(String::from);
191    }
192    None
193}
194
195fn mesh_members(host: &str, m: &[(String, Value)]) -> Result<MeshDoc> {
196    let md = ErrorCode::MeshDoc;
197    // One origin for the whole document (9.6): all on https://<host>, or all on one loopback origin.
198    let mut origin: Option<String> = None;
199    let mut same_origin = |u: &str, p: &str| -> Result<()> {
200        match url_origin(u, host) {
201            Some(o) if origin.as_ref().is_none_or(|first| *first == o) => {
202                origin = Some(o);
203                Ok(())
204            }
205            _ => err(md, p, "a URL is on the host, or on one loopback origin for an unrooted host"),
206        }
207    };
208    let bindings = match schema::get(m, "bindings") {
209        Value::String(b) => {
210            same_origin(b, "$.bindings")?;
211            b.clone()
212        }
213        _ => return err(md, "$.bindings", "bindings is a URL on this host"),
214    };
215    let Value::Object(em) = schema::get(m, "endpoints") else {
216        return err(md, "$.endpoints", "endpoints is an object");
217    };
218    for (name, _, required) in ENDPOINTS {
219        if required && schema::opt(em, name).is_none() {
220            return err(md, "$.endpoints", format!("the required endpoint {name} is missing"));
221        }
222    }
223    let mut endpoints = BTreeMap::new();
224    for (name, placeholders, _) in ENDPOINTS {
225        let Some(v) = schema::opt(em, name) else { continue };
226        let p = member("$.endpoints", name);
227        let Value::String(t) = v else { return err(md, &p, "an endpoint is a URL template") };
228        same_origin(t, &p)?;
229        let mut rest = t.clone();
230        for ph in placeholders {
231            let token = format!("{{{ph}}}");
232            if rest.matches(&token).count() != 1 {
233                return err(md, &p, format!("the template has {token} exactly once"));
234            }
235            rest = rest.replacen(&token, "", 1);
236        }
237        // Every brace belongs to a placeholder (3f79313).
238        if rest.contains('{') || rest.contains('}') {
239            return err(md, &p, "every brace of the template belongs to one of its placeholders");
240        }
241        endpoints.insert(name.to_string(), t.clone());
242    }
243    Ok(MeshDoc { host: host.into(), bindings, endpoints })
244}