1use 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
13const 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 ("whatif", &[], false),
30];
31
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub enum Retrieval<'a> {
35 Response {
37 status: u16,
39 body: Option<&'a [u8]>,
41 },
42 Failed,
45}
46
47#[derive(Clone, Debug, PartialEq, Eq, Hash)]
50#[non_exhaustive]
51pub struct MeshDoc {
52 pub host: String,
54 pub bindings: String,
56 pub endpoints: BTreeMap<String, String>,
59}
60
61impl MeshDoc {
62 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 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#[derive(Clone, Debug, PartialEq, Eq, Hash)]
101#[non_exhaustive]
102pub struct ResolvedMesh {
103 pub keys: KeyDoc,
105 pub mesh: MeshDoc,
107 pub declarations: Option<Declarations>,
110}
111
112pub fn resolve_mesh(host: &str, key_doc_got: Retrieval<'_>, mesh_doc_got: Retrieval<'_>) -> Result<ResolvedMesh> {
128 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 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 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 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 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 let doc = key_doc(host, &kv)?;
166 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
179fn 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 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 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}