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.
10
11use crate::Diag;
12use crate::json;
13use crate::node::{AltKind, Asn1, Field, FieldValue, Node};
14use crate::path::{
15    self, JwtPick, bundle_parts, der_items, field_children, jwt_parts, map_index, message_fields,
16    values_items,
17};
18use crate::tree;
19use crate::value::{Value, ValueKind};
20
21/// What a path selected.
22#[derive(Debug)]
23pub enum Pick<'a> {
24    Field(&'a Field),
25    Element(&'a Asn1),
26    Value(&'a Value),
27    Jwt(JwtPick<'a>),
28}
29
30impl Pick<'_> {
31    /// The selection as JSON, in its own format's schema.
32    pub fn to_json(&self) -> String {
33        match self {
34            Pick::Field(f) => json::field_to_json(f),
35            Pick::Element(e) => json::asn1_to_json(e),
36            Pick::Value(v) => json::value_to_json(v),
37            Pick::Jwt(p) => p.to_json(),
38        }
39    }
40
41    /// The selection as an indented outline.
42    pub fn to_tree(&self) -> String {
43        match self {
44            Pick::Field(f) => tree::field_to_tree(f),
45            Pick::Element(e) => tree::asn1_to_tree(e),
46            Pick::Value(v) => tree::value_to_tree(v),
47            Pick::Jwt(p) => p.to_tree(),
48        }
49    }
50
51    /// The selection's payload bytes, or `NO_PAYLOAD` for a group, a
52    /// constructed element or a map/array value.
53    pub fn payload(&self) -> Result<Vec<u8>, Diag> {
54        let none = |what: &str| {
55            Diag::new(
56                "NO_PAYLOAD",
57                format!("{what} has no single payload; use the JSON output"),
58                None,
59            )
60        };
61        match self {
62            Pick::Field(f) => f.payload().ok_or_else(|| none("a group")),
63            Pick::Element(e) => e.payload().ok_or_else(|| none("a constructed element")),
64            Pick::Value(v) => v.payload().ok_or_else(|| none("this value")),
65            Pick::Jwt(p) => Ok(p.payload()),
66        }
67    }
68}
69
70/// Select by a path that may cross formats, e.g. `2.0.0.5` for the subject
71/// of a base64 certificate in protobuf string field 2, or `token.payload.sub`
72/// for a JWT in a CBOR byte string.
73pub fn get<'a>(root: &'a Node, path: &str) -> Result<Pick<'a>, Diag> {
74    walk(root, &segments(path)?, 0, &mut None)
75}
76
77fn segments(path: &str) -> Result<Vec<&str>, Diag> {
78    if path.trim().is_empty() {
79        return Err(Diag::new("BAD_PATH", "empty path", None));
80    }
81    let segs: Vec<&str> = path.split('.').collect();
82    if segs.iter().any(|s| s.is_empty()) {
83        return Err(Diag::new(
84            "BAD_PATH",
85            "paths do not allow empty segments",
86            None,
87        ));
88    }
89    Ok(segs)
90}
91
92/// What holds a decoded node that a path crossed into.
93#[derive(Debug, Clone, Copy)]
94pub(crate) enum Holder<'a> {
95    Field(&'a Field),
96    Value(&'a Value),
97    /// A JWT part that is not JSON.
98    Jwt,
99}
100
101/// Where a path crosses into a decoded node: `segs[at..]` continue in `node`.
102#[derive(Debug, Clone, Copy)]
103pub(crate) struct Crossing<'a> {
104    pub at: usize,
105    pub holder: Holder<'a>,
106    pub node: &'a Node,
107}
108
109/// [`get`], plus the last place the path crossed formats.
110pub(crate) fn locate<'a>(
111    root: &'a Node,
112    path: &str,
113) -> Result<(Pick<'a>, Option<Crossing<'a>>), Diag> {
114    let mut cx = None;
115    let pick = walk(root, &segments(path)?, 0, &mut cx)?;
116    Ok((pick, cx))
117}
118
119/// The decoded node of a selection that has no children in its own format
120/// (a string or bytes field, a byte string), as a crossing at `at`.
121pub(crate) fn leaf_crossing<'a>(pick: &Pick<'a>, at: usize) -> Option<Crossing<'a>> {
122    match pick {
123        Pick::Field(f) if field_children(f).is_none() => decoded_alt(f).map(|node| Crossing {
124            at,
125            holder: Holder::Field(f),
126            node,
127        }),
128        Pick::Value(v) => match &v.untagged().kind {
129            ValueKind::Bytes {
130                decoded: Some(n), ..
131            } => Some(Crossing {
132                at,
133                holder: Holder::Value(v),
134                node: n,
135            }),
136            _ => None,
137        },
138        _ => None,
139    }
140}
141
142fn at(segs: &[&str], n: usize) -> String {
143    segs[..n].join(".")
144}
145
146fn not_found(msg: String) -> Diag {
147    Diag::new("PATH_NOT_FOUND", msg, None)
148}
149
150fn no_children(segs: &[&str], n: usize, what: &str) -> Diag {
151    Diag::new(
152        "PATH_NOT_MESSAGE",
153        format!("{what} at '{}' has nothing to descend into", at(segs, n)),
154        None,
155    )
156}
157
158/// Walk `segs[i..]` starting in `node` (text layers are skipped).
159fn walk<'a>(
160    node: &'a Node,
161    segs: &[&str],
162    i: usize,
163    cx: &mut Option<Crossing<'a>>,
164) -> Result<Pick<'a>, Diag> {
165    if let Some(parts) = bundle_parts(node) {
166        let block: usize = segs[i]
167            .parse()
168            .map_err(|_| bad_index(segs[i], "a PEM bundle block"))?;
169        let part = parts
170            .get(block)
171            .ok_or_else(|| not_found(format!("no bundle block '{}'", at(segs, i + 1))))?;
172        if i + 1 == segs.len() {
173            return Err(not_found(
174                "a bundle path needs an element index after the block".into(),
175            ));
176        }
177        return walk(part, segs, i + 1, cx);
178    }
179    if let Some(items) = der_items(node) {
180        return walk_der(items, segs, i);
181    }
182    if let Some(items) = values_items(node) {
183        return walk_values(items, segs, i, cx);
184    }
185    if jwt_parts(node).is_some() {
186        return walk_jwt(node, segs, i, cx);
187    }
188    if let Some(fields) = message_fields(node) {
189        return walk_fields(fields, segs, i, cx);
190    }
191    Err(Diag::new(
192        "PATH_NOT_MESSAGE",
193        if i == 0 {
194            "the input did not decode to protobuf, DER, CBOR/MessagePack or a JWT".to_string()
195        } else {
196            format!(
197                "the data decoded at '{}' is not protobuf, DER, CBOR/MessagePack or a JWT",
198                at(segs, i)
199            )
200        },
201        None,
202    ))
203}
204
205fn bad_index(seg: &str, what: &str) -> Diag {
206    Diag::new(
207        "BAD_PATH",
208        format!("'{seg}' is not an index into {what}"),
209        None,
210    )
211}
212
213fn walk_fields<'a>(
214    mut fields: &'a [Field],
215    segs: &[&str],
216    mut i: usize,
217    cx: &mut Option<Crossing<'a>>,
218) -> Result<Pick<'a>, Diag> {
219    loop {
220        let (num, idx) = path::parse_path(segs[i])?[0];
221        let f = fields
222            .iter()
223            .filter(|f| f.number == num)
224            .nth(idx)
225            .ok_or_else(|| not_found(format!("no field '{}'", at(segs, i + 1))))?;
226        i += 1;
227        if i == segs.len() {
228            return Ok(Pick::Field(f));
229        }
230        if let Some(children) = field_children(f) {
231            fields = children;
232            continue;
233        }
234        // A string or bytes field whose content decodes to another format.
235        return match decoded_alt(f) {
236            Some(node) => {
237                *cx = Some(Crossing {
238                    at: i,
239                    holder: Holder::Field(f),
240                    node,
241                });
242                walk(node, segs, i, cx)
243            }
244            None => Err(no_children(segs, i, "the field")),
245        };
246    }
247}
248
249/// The decoded node of a LEN field's best-ranked string or bytes alt that
250/// has one.
251fn decoded_alt(f: &Field) -> Option<&Node> {
252    match &f.value {
253        FieldValue::Len { alts, .. } => alts.iter().find_map(|a| match &a.kind {
254            AltKind::String {
255                decoded: Some(n), ..
256            }
257            | AltKind::Bytes { decoded: Some(n) } => Some(&**n),
258            _ => None,
259        }),
260        _ => None,
261    }
262}
263
264fn walk_der<'a>(mut items: &'a [Asn1], segs: &[&str], mut i: usize) -> Result<Pick<'a>, Diag> {
265    loop {
266        let idx: usize = segs[i].parse().map_err(|_| {
267            Diag::new(
268                "BAD_PATH",
269                format!(
270                    "invalid path segment '{}' (DER paths are child indices, e.g. 0.0.6)",
271                    segs[i]
272                ),
273                None,
274            )
275        })?;
276        let e = items
277            .get(idx)
278            .ok_or_else(|| not_found(format!("no element '{}'", at(segs, i + 1))))?;
279        i += 1;
280        if i == segs.len() {
281            return Ok(Pick::Element(e));
282        }
283        items = e
284            .children()
285            .ok_or_else(|| no_children(segs, i, "the element"))?;
286    }
287}
288
289fn walk_values<'a>(
290    items: &'a [Value],
291    segs: &[&str],
292    mut i: usize,
293    cx: &mut Option<Crossing<'a>>,
294) -> Result<Pick<'a>, Diag> {
295    let mut cur = if items.len() == 1 {
296        &items[0]
297    } else {
298        let idx: usize = segs[i]
299            .parse()
300            .map_err(|_| bad_index(segs[i], "the CBOR/MessagePack sequence"))?;
301        i += 1;
302        items
303            .get(idx)
304            .ok_or_else(|| not_found(format!("no element '{}'", at(segs, i))))?
305    };
306    while i < segs.len() {
307        let seg = segs[i];
308        cur = match &cur.untagged().kind {
309            ValueKind::Map(entries) => {
310                let k = map_index(entries, seg)
311                    .ok_or_else(|| not_found(format!("no key '{seg}' at '{}'", at(segs, i))))?;
312                &entries[k].1
313            }
314            ValueKind::Array(arr) => {
315                let idx: usize = seg
316                    .parse()
317                    .map_err(|_| not_found(format!("'{seg}' is not an array index")))?;
318                arr.get(idx)
319                    .ok_or_else(|| not_found(format!("no index '{idx}' at '{}'", at(segs, i))))?
320            }
321            // A byte string that decodes to another format.
322            ValueKind::Bytes {
323                decoded: Some(node),
324                ..
325            } => {
326                *cx = Some(Crossing {
327                    at: i,
328                    holder: Holder::Value(cur),
329                    node,
330                });
331                return walk(node, segs, i, cx);
332            }
333            _ => return Err(no_children(segs, i, "the value")),
334        };
335        i += 1;
336    }
337    Ok(Pick::Value(cur))
338}
339
340fn walk_jwt<'a>(
341    node: &'a Node,
342    segs: &[&str],
343    i: usize,
344    cx: &mut Option<Crossing<'a>>,
345) -> Result<Pick<'a>, Diag> {
346    let rest = segs[i..].join(".");
347    if i + 1 < segs.len() {
348        let part = path::select_jwt(node, segs[i])?;
349        if !part_is_json(&part) {
350            // Not JSON (e.g. a JWE part, or a binary payload): continue in
351            // whatever the part decodes to.
352            *cx = Some(Crossing {
353                at: i + 1,
354                holder: Holder::Jwt,
355                node: part.node,
356            });
357            return walk(part.node, segs, i + 1, cx);
358        }
359    }
360    path::select_jwt(node, &rest).map(Pick::Jwt)
361}
362
363fn part_is_json(p: &JwtPick) -> bool {
364    match &p.node.detail {
365        crate::node::Detail::Layer { decoded, .. } => std::str::from_utf8(decoded)
366            .is_ok_and(|t| crate::jsonpath::find(t, &[], p.part).is_ok()),
367        _ => false,
368    }
369}