Skip to main content

bytepeel_core/
get.rs

1//! `--get` across formats: one path walks protobuf, DER, CBOR/MessagePack and
2//! JWT layers in turn.
3//!
4//! Each format's segments are walked natively (field numbers, child indices,
5//! map keys, JWT parts and JSON keys). When the next segment cannot descend
6//! natively but the current item holds a decoded node (a protobuf string that
7//! is base64 DER, a CBOR byte string that is protobuf, a JWT part that is not
8//! JSON), the rest of the path continues in that node's format. Native descent
9//! always wins, so every single-format path keeps its meaning. Text that is a
10//! JSON object or array (a decoded text layer, a protobuf string, a
11//! CBOR/MessagePack text string) is walked by JSON keys and array indices.
12
13use crate::Diag;
14use crate::json;
15use crate::jsonpath;
16use crate::node::{AltKind, Asn1, Detail, Field, FieldValue, Node};
17use crate::path::{
18    self, JwtPick, bundle_parts, der_items, field_children, jwt_parts, map_index, message_fields,
19    values_items,
20};
21use crate::tree;
22use crate::value::{Value, ValueKind};
23
24/// What a path selected.
25#[derive(Debug)]
26pub enum Pick<'a> {
27    Field(&'a Field),
28    Element(&'a Asn1),
29    Value(&'a Value),
30    Jwt(JwtPick<'a>),
31    Json(JsonPick<'a>),
32}
33
34/// A value inside JSON text.
35#[derive(Debug)]
36pub struct JsonPick<'a> {
37    /// The whole JSON document.
38    pub doc: &'a str,
39    /// The path within the document (the segments after the text's holder).
40    pub path: String,
41    /// The selected value's byte range in `doc`.
42    pub range: [usize; 2],
43}
44
45impl JsonPick<'_> {
46    /// The selected value as JSON text.
47    pub fn value(&self) -> &str {
48        &self.doc[self.range[0]..self.range[1]]
49    }
50
51    /// `{"path":..,"range":[s,e],"value":<JSON>}`.
52    pub fn to_json(&self) -> String {
53        let mut o = String::from("{\"path\":");
54        json::esc(&mut o, &self.path);
55        o.push_str(&format!(
56            ",\"range\":[{},{}],\"value\":{}}}",
57            self.range[0],
58            self.range[1],
59            self.value()
60        ));
61        o
62    }
63
64    /// A string's unescaped text, any other value verbatim.
65    pub fn payload(&self) -> Vec<u8> {
66        let v = self.value();
67        jsonpath::string_value(v).map_or_else(|| v.as_bytes().to_vec(), String::into_bytes)
68    }
69}
70
71impl Pick<'_> {
72    /// The selection as JSON, in its own format's schema.
73    pub fn to_json(&self) -> String {
74        match self {
75            Pick::Field(f) => json::field_to_json(f),
76            Pick::Element(e) => json::asn1_to_json(e),
77            Pick::Value(v) => json::value_to_json(v),
78            Pick::Jwt(p) => p.to_json(),
79            Pick::Json(p) => p.to_json(),
80        }
81    }
82
83    /// The selection as an indented outline.
84    pub fn to_tree(&self) -> String {
85        match self {
86            Pick::Field(f) => tree::field_to_tree(f),
87            Pick::Element(e) => tree::asn1_to_tree(e),
88            Pick::Value(v) => tree::value_to_tree(v),
89            Pick::Jwt(p) => p.to_tree(),
90            Pick::Json(p) => format!("{} = {}\n", p.path, p.value()),
91        }
92    }
93
94    /// The selection's payload bytes, or `NO_PAYLOAD` for a group, a
95    /// constructed element or a map/array value.
96    pub fn payload(&self) -> Result<Vec<u8>, Diag> {
97        let none = |what: &str| {
98            Diag::new(
99                "NO_PAYLOAD",
100                format!("{what} has no single payload; use the JSON output"),
101                None,
102            )
103        };
104        match self {
105            Pick::Field(f) => f.payload().ok_or_else(|| none("a group")),
106            Pick::Element(e) => e.payload().ok_or_else(|| none("a constructed element")),
107            Pick::Value(v) => v.payload().ok_or_else(|| none("this value")),
108            Pick::Jwt(p) => Ok(p.payload()),
109            Pick::Json(p) => Ok(p.payload()),
110        }
111    }
112}
113
114/// Select by a path that may cross formats, e.g. `2.0.0.5` for the subject
115/// of a base64 certificate in protobuf string field 2, or `token.payload.sub`
116/// for a JWT in a CBOR byte string.
117pub fn get<'a>(root: &'a Node, path: &str) -> Result<Pick<'a>, Diag> {
118    walk(root, &segments(path)?, 0, &mut None)
119}
120
121fn segments(path: &str) -> Result<Vec<&str>, Diag> {
122    if path.trim().is_empty() {
123        return Err(Diag::new("BAD_PATH", "empty path", None));
124    }
125    let segs: Vec<&str> = path.split('.').collect();
126    if segs.iter().any(|s| s.is_empty()) {
127        return Err(Diag::new(
128            "BAD_PATH",
129            "paths do not allow empty segments",
130            None,
131        ));
132    }
133    Ok(segs)
134}
135
136/// What holds a decoded node that a path crossed into.
137#[derive(Debug, Clone, Copy)]
138pub(crate) enum Holder<'a> {
139    Field(&'a Field),
140    Value(&'a Value),
141    /// A JWT part that is not JSON.
142    Jwt,
143}
144
145/// Where a path crosses into a decoded node: `segs[at..]` continue in `node`.
146#[derive(Debug, Clone, Copy)]
147pub(crate) struct Crossing<'a> {
148    pub at: usize,
149    pub holder: Holder<'a>,
150    pub node: &'a Node,
151}
152
153/// [`get`], plus the last place the path crossed formats.
154pub(crate) fn locate<'a>(
155    root: &'a Node,
156    path: &str,
157) -> Result<(Pick<'a>, Option<Crossing<'a>>), Diag> {
158    let mut cx = None;
159    let pick = walk(root, &segments(path)?, 0, &mut cx)?;
160    Ok((pick, cx))
161}
162
163/// The decoded node of a selection that has no children in its own format
164/// (a string or bytes field, a byte string), as a crossing at `at`.
165pub(crate) fn leaf_crossing<'a>(pick: &Pick<'a>, at: usize) -> Option<Crossing<'a>> {
166    match pick {
167        Pick::Field(f) if field_children(f).is_none() => decoded_alt(f).map(|node| Crossing {
168            at,
169            holder: Holder::Field(f),
170            node,
171        }),
172        Pick::Value(v) => match &v.untagged().kind {
173            ValueKind::Bytes {
174                decoded: Some(n), ..
175            } => Some(Crossing {
176                at,
177                holder: Holder::Value(v),
178                node: n,
179            }),
180            _ => None,
181        },
182        _ => None,
183    }
184}
185
186fn at(segs: &[&str], n: usize) -> String {
187    segs[..n].join(".")
188}
189
190fn not_found(msg: String) -> Diag {
191    Diag::new("PATH_NOT_FOUND", msg, None)
192}
193
194fn no_children(segs: &[&str], n: usize, what: &str) -> Diag {
195    Diag::new(
196        "PATH_NOT_MESSAGE",
197        format!("{what} at '{}' has nothing to descend into", at(segs, n)),
198        None,
199    )
200}
201
202/// Walk `segs[i..]` starting in `node` (text layers are skipped).
203fn walk<'a>(
204    node: &'a Node,
205    segs: &[&str],
206    i: usize,
207    cx: &mut Option<Crossing<'a>>,
208) -> Result<Pick<'a>, Diag> {
209    if let Some(parts) = bundle_parts(node) {
210        let block: usize = segs[i]
211            .parse()
212            .map_err(|_| bad_index(segs[i], "a PEM bundle block"))?;
213        let part = parts
214            .get(block)
215            .ok_or_else(|| not_found(format!("no bundle block '{}'", at(segs, i + 1))))?;
216        if i + 1 == segs.len() {
217            return Err(not_found(
218                "a bundle path needs an element index after the block".into(),
219            ));
220        }
221        return walk(part, segs, i + 1, cx);
222    }
223    if let Some(items) = der_items(node) {
224        return walk_der(items, segs, i);
225    }
226    if let Some(items) = values_items(node) {
227        return walk_values(items, segs, i, cx);
228    }
229    if jwt_parts(node).is_some() {
230        return walk_jwt(node, segs, i, cx);
231    }
232    if let Some(fields) = message_fields(node) {
233        return walk_fields(fields, segs, i, cx);
234    }
235    if let Some(doc) = text_doc(node) {
236        return walk_json(doc, segs, i);
237    }
238    Err(Diag::new(
239        "PATH_NOT_MESSAGE",
240        if i == 0 {
241            "the input did not decode to protobuf, DER, CBOR/MessagePack, a JWT or JSON".to_string()
242        } else {
243            format!(
244                "the data decoded at '{}' is not protobuf, DER, CBOR/MessagePack, a JWT or JSON",
245                at(segs, i)
246            )
247        },
248        None,
249    ))
250}
251
252fn bad_index(seg: &str, what: &str) -> Diag {
253    Diag::new(
254        "BAD_PATH",
255        format!("'{seg}' is not an index into {what}"),
256        None,
257    )
258}
259
260fn walk_fields<'a>(
261    mut fields: &'a [Field],
262    segs: &[&str],
263    mut i: usize,
264    cx: &mut Option<Crossing<'a>>,
265) -> Result<Pick<'a>, Diag> {
266    loop {
267        let (num, idx) = path::parse_path(segs[i])?[0];
268        let f = fields
269            .iter()
270            .filter(|f| f.number == num)
271            .nth(idx)
272            .ok_or_else(|| not_found(format!("no field '{}'", at(segs, i + 1))))?;
273        i += 1;
274        if i == segs.len() {
275            return Ok(Pick::Field(f));
276        }
277        if let Some(children) = field_children(f) {
278            fields = children;
279            continue;
280        }
281        // A string or bytes field whose content decodes to another format.
282        return match decoded_alt(f) {
283            Some(node) => {
284                *cx = Some(Crossing {
285                    at: i,
286                    holder: Holder::Field(f),
287                    node,
288                });
289                walk(node, segs, i, cx)
290            }
291            None => match json_alt(f) {
292                Some(doc) => walk_json(doc, segs, i),
293                None => Err(no_children(segs, i, "the field")),
294            },
295        };
296    }
297}
298
299/// The decoded node of a LEN field's best-ranked string or bytes alt that
300/// has one.
301fn decoded_alt(f: &Field) -> Option<&Node> {
302    match &f.value {
303        FieldValue::Len { alts, .. } => alts.iter().find_map(|a| match &a.kind {
304            AltKind::String {
305                decoded: Some(n), ..
306            }
307            | AltKind::Bytes { decoded: Some(n) } => Some(&**n),
308            _ => None,
309        }),
310        _ => None,
311    }
312}
313
314/// The text of a LEN field's string alt, when it is a JSON object or array.
315fn json_alt(f: &Field) -> Option<&str> {
316    match &f.value {
317        FieldValue::Len { alts, .. } => alts.iter().find_map(|a| match &a.kind {
318            AltKind::String { text, .. } if is_json_doc(text) => Some(text.as_str()),
319            _ => None,
320        }),
321        _ => None,
322    }
323}
324
325/// The whole text of a node that is (after any layers) JSON text. A layer's
326/// decoded bytes hold the full text; a root text node holds it only when it
327/// is short enough to be kept whole.
328fn text_doc(node: &Node) -> Option<&str> {
329    match &node.detail {
330        Detail::Layer { decoded, child } => match &child.detail {
331            Detail::Text { .. } => std::str::from_utf8(decoded).ok().filter(|t| is_json_doc(t)),
332            _ => text_doc(child),
333        },
334        Detail::Text { text, len } if *len == text.len() => {
335            Some(text.as_str()).filter(|t| is_json_doc(t))
336        }
337        _ => None,
338    }
339}
340
341/// A JSON object or array (not a bare scalar: a number or a quoted word is
342/// text, not a document to walk).
343fn is_json_doc(t: &str) -> bool {
344    matches!(t.trim_start().as_bytes().first(), Some(b'{' | b'['))
345        && jsonpath::find(t, &[], "").is_ok()
346}
347
348fn walk_json<'a>(doc: &'a str, segs: &[&str], i: usize) -> Result<Pick<'a>, Diag> {
349    let range = jsonpath::find(doc, &segs[i..], &at(segs, i))?;
350    Ok(Pick::Json(JsonPick {
351        doc,
352        path: segs[i..].join("."),
353        range,
354    }))
355}
356
357fn walk_der<'a>(mut items: &'a [Asn1], segs: &[&str], mut i: usize) -> Result<Pick<'a>, Diag> {
358    loop {
359        let idx: usize = segs[i].parse().map_err(|_| {
360            Diag::new(
361                "BAD_PATH",
362                format!(
363                    "invalid path segment '{}' (DER paths are child indices, e.g. 0.0.6)",
364                    segs[i]
365                ),
366                None,
367            )
368        })?;
369        let e = items
370            .get(idx)
371            .ok_or_else(|| not_found(format!("no element '{}'", at(segs, i + 1))))?;
372        i += 1;
373        if i == segs.len() {
374            return Ok(Pick::Element(e));
375        }
376        items = e
377            .children()
378            .ok_or_else(|| no_children(segs, i, "the element"))?;
379    }
380}
381
382fn walk_values<'a>(
383    items: &'a [Value],
384    segs: &[&str],
385    mut i: usize,
386    cx: &mut Option<Crossing<'a>>,
387) -> Result<Pick<'a>, Diag> {
388    let mut cur = if items.len() == 1 {
389        &items[0]
390    } else {
391        let idx: usize = segs[i]
392            .parse()
393            .map_err(|_| bad_index(segs[i], "the CBOR/MessagePack sequence"))?;
394        i += 1;
395        items
396            .get(idx)
397            .ok_or_else(|| not_found(format!("no element '{}'", at(segs, i))))?
398    };
399    while i < segs.len() {
400        let seg = segs[i];
401        cur = match &cur.untagged().kind {
402            ValueKind::Map(entries) => {
403                let k = map_index(entries, seg)
404                    .ok_or_else(|| not_found(format!("no key '{seg}' at '{}'", at(segs, i))))?;
405                &entries[k].1
406            }
407            ValueKind::Array(arr) => {
408                let idx: usize = seg
409                    .parse()
410                    .map_err(|_| not_found(format!("'{seg}' is not an array index")))?;
411                arr.get(idx)
412                    .ok_or_else(|| not_found(format!("no index '{idx}' at '{}'", at(segs, i))))?
413            }
414            // A byte string that decodes to another format.
415            ValueKind::Bytes {
416                decoded: Some(node),
417                ..
418            } => {
419                *cx = Some(Crossing {
420                    at: i,
421                    holder: Holder::Value(cur),
422                    node,
423                });
424                return walk(node, segs, i, cx);
425            }
426            ValueKind::Text(t) if is_json_doc(t) => return walk_json(t, segs, i),
427            _ => return Err(no_children(segs, i, "the value")),
428        };
429        i += 1;
430    }
431    Ok(Pick::Value(cur))
432}
433
434fn walk_jwt<'a>(
435    node: &'a Node,
436    segs: &[&str],
437    i: usize,
438    cx: &mut Option<Crossing<'a>>,
439) -> Result<Pick<'a>, Diag> {
440    let rest = segs[i..].join(".");
441    if i + 1 < segs.len() {
442        let part = path::select_jwt(node, segs[i])?;
443        if !part_is_json(&part) {
444            // Not JSON (e.g. a JWE part, or a binary payload): continue in
445            // whatever the part decodes to.
446            *cx = Some(Crossing {
447                at: i + 1,
448                holder: Holder::Jwt,
449                node: part.node,
450            });
451            return walk(part.node, segs, i + 1, cx);
452        }
453    }
454    path::select_jwt(node, &rest).map(Pick::Jwt)
455}
456
457fn part_is_json(p: &JwtPick) -> bool {
458    match &p.node.detail {
459        crate::node::Detail::Layer { decoded, .. } => std::str::from_utf8(decoded)
460            .is_ok_and(|t| crate::jsonpath::find(t, &[], p.part).is_ok()),
461        _ => false,
462    }
463}