Skip to main content

bytepeel_core/
path.rs

1//! Field selection by path, e.g. `1.3[2].4`.
2
3use crate::Diag;
4use crate::node::{AltKind, Asn1, Codec, Detail, Field, FieldValue, Node};
5use crate::value::{Value, ValueKind};
6
7/// Select a protobuf field by path.
8///
9/// Segments are field numbers separated by `.`; `N[i]` picks the i-th
10/// occurrence of a repeated field (default 0). Text layers (hex/base64/PEM,
11/// including base64 inside string fields) are descended automatically, and a
12/// LEN field is entered through its best-ranked `message` interpretation.
13pub fn select<'a>(root: &'a Node, path: &str) -> Result<&'a Field, Diag> {
14    let segs = parse_path(path)?;
15    let mut fields = message_fields(root).ok_or_else(|| {
16        Diag::new(
17            "PATH_NOT_MESSAGE",
18            "the input did not decode to a protobuf message",
19            None,
20        )
21    })?;
22    let mut cur: Option<&Field> = None;
23    for (i, &(num, idx)) in segs.iter().enumerate() {
24        if let Some(parent) = cur {
25            fields = field_children(parent).ok_or_else(|| {
26                Diag::new(
27                    "PATH_NOT_MESSAGE",
28                    format!(
29                        "field at '{}' has no message interpretation",
30                        prefix(&segs, i)
31                    ),
32                    None,
33                )
34            })?;
35        }
36        let found = fields
37            .iter()
38            .filter(|f| f.number == num)
39            .nth(idx)
40            .ok_or_else(|| {
41                Diag::new(
42                    "PATH_NOT_FOUND",
43                    format!("no field '{}'", prefix(&segs, i + 1)),
44                    None,
45                )
46            })?;
47        cur = Some(found);
48    }
49    Ok(cur.expect("path has at least one segment"))
50}
51
52fn prefix(segs: &[(u32, usize)], n: usize) -> String {
53    segs[..n]
54        .iter()
55        .map(|(f, i)| {
56            if *i == 0 {
57                f.to_string()
58            } else {
59                format!("{f}[{i}]")
60            }
61        })
62        .collect::<Vec<_>>()
63        .join(".")
64}
65
66pub(crate) fn parse_path(p: &str) -> Result<Vec<(u32, usize)>, Diag> {
67    if p.trim().is_empty() {
68        return Err(Diag::new("BAD_PATH", "empty path", None));
69    }
70    p.split('.')
71        .map(|seg| {
72            let bad = || {
73                Diag::new(
74                    "BAD_PATH",
75                    format!("invalid path segment '{seg}' (expected N or N[i])"),
76                    None,
77                )
78            };
79            let (num, idx) = match seg.split_once('[') {
80                Some((n, rest)) => {
81                    let i = rest.strip_suffix(']').ok_or_else(bad)?;
82                    (n, i.parse::<usize>().map_err(|_| bad())?)
83                }
84                None => (seg, 0),
85            };
86            Ok((num.parse::<u32>().map_err(|_| bad())?, idx))
87        })
88        .collect()
89}
90
91pub(crate) fn message_fields(node: &Node) -> Option<&[Field]> {
92    match &node.detail {
93        Detail::Message { fields } => Some(fields),
94        Detail::Layer { child, .. } => message_fields(child),
95        _ => None,
96    }
97}
98
99pub(crate) fn field_children(f: &Field) -> Option<&[Field]> {
100    match &f.value {
101        FieldValue::Group { fields } => Some(fields),
102        FieldValue::Len { alts, .. } => alts.iter().find_map(|a| match &a.kind {
103            AltKind::Message(fs) => Some(&fs[..]),
104            AltKind::String {
105                decoded: Some(n), ..
106            } => message_fields(n),
107            // An empty LEN field is an empty message (so `set` can add to it
108            // and a deleted last field verifies).
109            AltKind::Empty => Some(&[][..]),
110            _ => None,
111        }),
112        _ => None,
113    }
114}
115
116/// Select a DER element by path.
117///
118/// Segments are 0-based child indices separated by `.`: the first indexes the
119/// top-level elements, so `0.0.6` is the subjectPublicKeyInfo of a certificate.
120/// For a PEM bundle, the first segment picks the block and the rest is the DER
121/// path within it, so `1.0.0.5` is the second certificate's subject. Text
122/// layers are descended automatically, and BIT STRING / OCTET STRING elements
123/// with encapsulated DER are entered like constructed ones.
124pub fn select_der<'a>(root: &'a Node, path: &str) -> Result<&'a Asn1, Diag> {
125    let segs = parse_indices(path)?;
126    let (mut items, start) = match bundle_parts(root) {
127        Some(parts) => {
128            let block = segs[0];
129            let part = parts.get(block).ok_or_else(|| {
130                Diag::new("PATH_NOT_FOUND", format!("no bundle block {block}"), None)
131            })?;
132            let items = der_items(part).ok_or_else(|| {
133                Diag::new(
134                    "PATH_NOT_MESSAGE",
135                    format!("bundle block {block} is not DER"),
136                    None,
137                )
138            })?;
139            if segs.len() == 1 {
140                return Err(Diag::new(
141                    "PATH_NOT_FOUND",
142                    "a bundle path needs an element index after the block",
143                    None,
144                ));
145            }
146            (items, 1)
147        }
148        None => (
149            der_items(root).ok_or_else(|| {
150                Diag::new("PATH_NOT_MESSAGE", "the input did not decode to DER", None)
151            })?,
152            0,
153        ),
154    };
155    let mut cur: Option<&'a Asn1> = None;
156    for (i, &idx) in segs[start..].iter().enumerate() {
157        if let Some(parent) = cur {
158            items = parent.children().ok_or_else(|| {
159                Diag::new(
160                    "PATH_NOT_MESSAGE",
161                    format!("element at '{}' has no children", join(&segs[..start + i])),
162                    None,
163                )
164            })?;
165        }
166        cur = Some(items.get(idx).ok_or_else(|| {
167            Diag::new(
168                "PATH_NOT_FOUND",
169                format!("no element '{}'", join(&segs[..=start + i])),
170                None,
171            )
172        })?);
173    }
174    Ok(cur.expect("path has at least one segment"))
175}
176
177/// Select a CBOR or MessagePack value by path.
178///
179/// Each segment is a map key or an array index (`users.0.name`). A segment
180/// matches a text key exactly; a numeric segment indexes an array, or matches
181/// an integer map key. If the top level has several items (a forced
182/// CBOR/MessagePack sequence), the first segment indexes them. CBOR tags are
183/// followed transparently.
184pub fn select_value<'a>(root: &'a Node, path: &str) -> Result<&'a Value, Diag> {
185    let segs = parse_value_path(path)?;
186    let items = values_items(root).ok_or_else(|| {
187        Diag::new(
188            "PATH_NOT_MESSAGE",
189            "the input did not decode to CBOR/MessagePack",
190            None,
191        )
192    })?;
193    let (mut cur, start) = if items.len() == 1 {
194        (&items[0], 0)
195    } else {
196        let idx: usize = segs[0].parse().map_err(|_| {
197            Diag::new(
198                "PATH_NOT_FOUND",
199                format!(
200                    "'{}' is not an index into the CBOR/MessagePack sequence",
201                    segs[0]
202                ),
203                None,
204            )
205        })?;
206        let v = items.get(idx).ok_or_else(|| {
207            Diag::new("PATH_NOT_FOUND", format!("no element '{}'", segs[0]), None)
208        })?;
209        (v, 1)
210    };
211    for (i, seg) in segs.iter().enumerate().skip(start) {
212        let v = cur.untagged();
213        cur = match &v.kind {
214            ValueKind::Map(entries) => map_lookup(entries, seg).ok_or_else(|| {
215                Diag::new(
216                    "PATH_NOT_FOUND",
217                    format!("no key '{}' at '{}'", seg, prefix_str(&segs, i)),
218                    None,
219                )
220            })?,
221            ValueKind::Array(arr) => {
222                let idx: usize = seg.parse().map_err(|_| {
223                    Diag::new(
224                        "PATH_NOT_FOUND",
225                        format!("'{}' is not an array index", seg),
226                        None,
227                    )
228                })?;
229                arr.get(idx).ok_or_else(|| {
230                    Diag::new(
231                        "PATH_NOT_FOUND",
232                        format!("no index '{idx}' at '{}'", prefix_str(&segs, i)),
233                        None,
234                    )
235                })?
236            }
237            _ => {
238                return Err(Diag::new(
239                    "PATH_NOT_MESSAGE",
240                    format!("'{}' is not a map or array", prefix_str(&segs, i)),
241                    None,
242                ));
243            }
244        };
245    }
246    Ok(cur)
247}
248
249fn map_lookup<'a>(entries: &'a [(Value, Value)], seg: &str) -> Option<&'a Value> {
250    map_index(entries, seg).map(|i| &entries[i].1)
251}
252
253/// The entry a path segment selects: a text key equal to it, else an integer
254/// key equal to it.
255pub(crate) fn map_index(entries: &[(Value, Value)], seg: &str) -> Option<usize> {
256    let text = entries
257        .iter()
258        .position(|(k, _)| matches!(&k.untagged().kind, ValueKind::Text(t) if t == seg));
259    if text.is_some() {
260        return text;
261    }
262    let want = seg.parse::<i128>().ok()?;
263    entries.iter().position(|(k, _)| {
264        let key = match &k.untagged().kind {
265            ValueKind::Uint(n) => Some(*n as i128),
266            ValueKind::Nint(n) => Some(-(*n as i128) - 1),
267            _ => None,
268        };
269        key == Some(want)
270    })
271}
272
273fn prefix_str(segs: &[&str], n: usize) -> String {
274    segs[..n].join(".")
275}
276
277fn parse_value_path(p: &str) -> Result<Vec<&str>, Diag> {
278    if p.trim().is_empty() {
279        return Err(Diag::new("BAD_PATH", "empty path", None));
280    }
281    let segs: Vec<&str> = p.split('.').collect();
282    if segs.iter().any(|s| s.is_empty()) {
283        return Err(Diag::new(
284            "BAD_PATH",
285            "CBOR/MessagePack paths do not allow empty segments",
286            None,
287        ));
288    }
289    Ok(segs)
290}
291
292/// True when `node` (after any text layers) is CBOR or MessagePack.
293pub fn is_values(node: &Node) -> bool {
294    values_items(node).is_some()
295}
296
297pub(crate) fn values_items(node: &Node) -> Option<&[Value]> {
298    match &node.detail {
299        Detail::Values { items } => Some(items),
300        Detail::Layer { child, .. } => values_items(child),
301        _ => None,
302    }
303}
304
305/// True when `node` (after any text layers) is DER, so paths are element
306/// indices. A PEM bundle counts when every block is DER.
307pub fn is_der(node: &Node) -> bool {
308    if let Some(parts) = bundle_parts(node) {
309        return !parts.is_empty() && parts.iter().all(|p| der_items(p).is_some());
310    }
311    der_items(node).is_some()
312}
313
314/// The parts of a PEM bundle node, if `node` (after text layers) is one.
315pub(crate) fn bundle_parts(node: &Node) -> Option<&[Node]> {
316    match &node.detail {
317        Detail::Parts { parts, .. } if matches!(node.codec, Codec::Bundle) => Some(parts),
318        Detail::Layer { child, .. } => bundle_parts(child),
319        _ => None,
320    }
321}
322
323pub(crate) fn der_items(node: &Node) -> Option<&[Asn1]> {
324    match &node.detail {
325        Detail::Der { items } => Some(items),
326        Detail::Layer { child, .. } => der_items(child),
327        _ => None,
328    }
329}
330
331fn join(segs: &[usize]) -> String {
332    segs.iter()
333        .map(usize::to_string)
334        .collect::<Vec<_>>()
335        .join(".")
336}
337
338fn parse_indices(p: &str) -> Result<Vec<usize>, Diag> {
339    if p.trim().is_empty() {
340        return Err(Diag::new("BAD_PATH", "empty path", None));
341    }
342    p.split('.')
343        .map(|seg| {
344            seg.parse::<usize>().map_err(|_| {
345                Diag::new(
346                    "BAD_PATH",
347                    format!(
348                        "invalid path segment '{seg}' (DER paths are child indices, e.g. 0.0.6)"
349                    ),
350                    None,
351                )
352            })
353        })
354        .collect()
355}
356
357/// A JWT part picked by [`select_jwt`], optionally narrowed to one JSON value
358/// inside the header or payload.
359#[derive(Debug)]
360pub struct JwtPick<'a> {
361    /// `header`, `payload`, `signature` (JWS) or `header`, `encrypted_key`,
362    /// `iv`, `ciphertext`, `tag` (JWE).
363    pub part: &'static str,
364    /// The part's position in the token.
365    pub index: usize,
366    /// The part's base64url layer node.
367    pub node: &'a Node,
368    /// The JSON path within the part (empty when the whole part is picked).
369    pub path: String,
370    /// The selected value's byte range in the part's decoded text, and that
371    /// text (validated JSON), when `path` is non-empty.
372    pub json: Option<([usize; 2], &'a str)>,
373}
374
375const JWS_PARTS: [&str; 3] = ["header", "payload", "signature"];
376const JWE_PARTS: [&str; 5] = ["header", "encrypted_key", "iv", "ciphertext", "tag"];
377
378/// True when `node` (after any text layers) is a JWT.
379pub fn is_jwt(node: &Node) -> bool {
380    jwt_parts(node).is_some()
381}
382
383pub(crate) fn jwt_parts(node: &Node) -> Option<(&'static [&'static str], &[Node])> {
384    match &node.detail {
385        Detail::Parts { parts, .. } => match node.codec {
386            Codec::Jwt { kind: "jws" } => Some((&JWS_PARTS[..], parts)),
387            Codec::Jwt { .. } => Some((&JWE_PARTS[..], parts)),
388            _ => None,
389        },
390        Detail::Layer { child, .. } => jwt_parts(child),
391        _ => None,
392    }
393}
394
395/// Select a JWT part by name (`payload`) or index (`1`), then optionally a
396/// value inside its JSON (`payload.sub`, `header.alg`, `payload.roles.0`).
397/// JSON segments are object keys (matched exactly; the first of duplicate
398/// keys wins) or array indices. Keys containing `.` cannot be addressed.
399pub fn select_jwt<'a>(root: &'a Node, path: &str) -> Result<JwtPick<'a>, Diag> {
400    if path.trim().is_empty() {
401        return Err(Diag::new("BAD_PATH", "empty path", None));
402    }
403    let (names, parts) = jwt_parts(root).ok_or_else(|| {
404        Diag::new(
405            "PATH_NOT_MESSAGE",
406            "the input did not decode to a JWT",
407            None,
408        )
409    })?;
410    let segs: Vec<&str> = path.split('.').collect();
411    if segs.iter().any(|s| s.is_empty()) {
412        return Err(Diag::new(
413            "BAD_PATH",
414            "JWT paths do not allow empty segments",
415            None,
416        ));
417    }
418    let index = names
419        .iter()
420        .position(|n| *n == segs[0])
421        .or_else(|| segs[0].parse().ok().filter(|&i: &usize| i < names.len()))
422        .ok_or_else(|| {
423            Diag::new(
424                "PATH_NOT_FOUND",
425                format!(
426                    "no JWT part '{}' (expected one of {} or an index)",
427                    segs[0],
428                    names.join(", ")
429                ),
430                None,
431            )
432        })?;
433    let part = names[index];
434    let node = &parts[index];
435    let mut pick = JwtPick {
436        part,
437        index,
438        node,
439        path: segs[1..].join("."),
440        json: None,
441    };
442    if segs.len() > 1 {
443        let decoded = match &node.detail {
444            Detail::Layer { decoded, .. } => decoded,
445            _ => unreachable!("JWT parts are base64 layers"),
446        };
447        let text = std::str::from_utf8(decoded).map_err(|_| {
448            Diag::new(
449                "PATH_NOT_MESSAGE",
450                format!("JWT part '{part}' is not JSON text"),
451                None,
452            )
453        })?;
454        let range = crate::jsonpath::find(text, &segs[1..], part)?;
455        pick.json = Some((range, &text[range[0]..range[1]]));
456    }
457    Ok(pick)
458}
459
460impl JwtPick<'_> {
461    /// Serialize as `{"part":..,"index":..,"node":Node}` for a whole part, or
462    /// `{"part":..,"index":..,"path":..,"range":[s,e],"value":<JSON>}`.
463    pub fn to_json(&self) -> String {
464        let mut o = format!("{{\"part\":\"{}\",\"index\":{}", self.part, self.index);
465        match self.json {
466            None => {
467                o.push_str(",\"node\":");
468                o.push_str(&crate::json::node_to_json(self.node));
469            }
470            Some((range, text)) => {
471                o.push_str(",\"path\":");
472                crate::json::esc(&mut o, &self.path);
473                o.push_str(&format!(
474                    ",\"range\":[{},{}],\"value\":",
475                    range[0], range[1]
476                ));
477                o.push_str(text);
478            }
479        }
480        o.push('}');
481        o
482    }
483
484    /// Render as an outline: the part's node tree, or `payload.sub = "…"`.
485    pub fn to_tree(&self) -> String {
486        match self.json {
487            None => crate::tree::node_to_tree(self.node),
488            Some((_, text)) => format!("{}.{} = {}\n", self.part, self.path, text),
489        }
490    }
491
492    /// The selection's bytes for `--format raw`: a JSON string's unescaped
493    /// text, any other JSON value verbatim, or a whole part's decoded bytes.
494    pub fn payload(&self) -> Vec<u8> {
495        match self.json {
496            Some((_, text)) => crate::jsonpath::string_value(text)
497                .map_or_else(|| text.as_bytes().to_vec(), String::into_bytes),
498            None => match &self.node.detail {
499                Detail::Layer { decoded, .. } => decoded.clone(),
500                _ => Vec::new(),
501            },
502        }
503    }
504}