Skip to main content

bytepeel_core/
edit.rs

1//! Re-encoding: change, add or remove one protobuf field, CBOR/MessagePack
2//! value or DER element, and re-serialize every layer.
3//!
4//! Edits are byte-exact splices. Only the target item's bytes change; the
5//! lengths and item counts of enclosing containers are rewritten, and each
6//! outer layer is re-encoded in its original style (see `reencode.rs`). Every
7//! other byte is preserved, including field order, unknown fields and
8//! non-canonical encodings elsewhere. The result is decoded again and checked before it is
9//! returned.
10
11use crate::get::{self, Crossing, Holder, Pick};
12use crate::node::{AltKind, Asn1, Asn1Value, Codec, Detail, Field, FieldValue, Node, TagClass};
13use crate::path::{
14    bundle_parts, der_items, field_children, jwt_parts, map_index, message_fields, parse_path,
15    values_items,
16};
17use crate::value::{Value, ValueKind};
18use std::cell::RefCell;
19
20use crate::{Diag, Options, cbor, compress, der, encode_value, msgpack, reencode, text, varint};
21
22/// A new value for a field, parsed from the CLI syntax (see [`parse_value`]).
23#[derive(Debug, Clone, PartialEq)]
24pub enum NewValue {
25    /// A decimal integer: `42`, `-2`.
26    Int(i128),
27    /// A zigzag (sint32/sint64) integer: `sint:-2`.
28    Sint(i64),
29    /// A floating-point number: `1.5`, `float:1e-3`, `float:NaN`.
30    Float(f64),
31    Bool(bool),
32    /// `null` (CBOR and MessagePack only).
33    Null,
34    /// A UTF-8 string: `"text"` (JSON escapes) or `str:text`.
35    Str(String),
36    /// Raw bytes: `hex:0a0b`, `b64:CgM=`.
37    Bytes(Vec<u8>),
38}
39
40fn bad_value(s: &str) -> Diag {
41    Diag::new(
42        "BAD_VALUE",
43        format!(
44            "cannot parse value '{s}'; use an integer (42, -2), sint:N, a float (1.5, float:NaN), \
45             true/false, null, \"text\" or str:text, hex:.. or b64:.."
46        ),
47        None,
48    )
49}
50
51/// Parse a value in the CLI syntax.
52pub fn parse_value(s: &str) -> Result<NewValue, Diag> {
53    if let Some(r) = s.strip_prefix("str:") {
54        return Ok(NewValue::Str(r.to_string()));
55    }
56    if let Some(r) = s.strip_prefix("hex:") {
57        return crate::decode_hex(r).map(NewValue::Bytes).or_else(|_| {
58            if r.is_empty() {
59                Ok(NewValue::Bytes(vec![]))
60            } else {
61                Err(bad_value(s))
62            }
63        });
64    }
65    if let Some(r) = s.strip_prefix("b64:") {
66        if r.is_empty() {
67            return Ok(NewValue::Bytes(vec![]));
68        }
69        return crate::decode_b64(r)
70            .map(|b| NewValue::Bytes(b.bytes))
71            .map_err(|_| bad_value(s));
72    }
73    if let Some(r) = s.strip_prefix("sint:") {
74        return r
75            .parse::<i64>()
76            .map(NewValue::Sint)
77            .map_err(|_| bad_value(s));
78    }
79    if let Some(r) = s.strip_prefix("float:") {
80        return parse_float(r)
81            .map(NewValue::Float)
82            .ok_or_else(|| bad_value(s));
83    }
84    match s {
85        "true" => return Ok(NewValue::Bool(true)),
86        "false" => return Ok(NewValue::Bool(false)),
87        "null" => return Ok(NewValue::Null),
88        _ => {}
89    }
90    if s.starts_with('"') {
91        return json_string(s)
92            .map(NewValue::Str)
93            .ok_or_else(|| bad_value(s));
94    }
95    let digits = s
96        .strip_prefix('-')
97        .or_else(|| s.strip_prefix('+'))
98        .unwrap_or(s);
99    if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) {
100        return s
101            .parse::<i128>()
102            .map(NewValue::Int)
103            .map_err(|_| bad_value(s));
104    }
105    if s.bytes().any(|b| b.is_ascii_digit()) {
106        if let Some(f) = parse_float(s) {
107            return Ok(NewValue::Float(f));
108        }
109    }
110    Err(bad_value(s))
111}
112
113fn parse_float(s: &str) -> Option<f64> {
114    match s {
115        "NaN" | "nan" => Some(f64::NAN),
116        "Infinity" | "inf" => Some(f64::INFINITY),
117        "-Infinity" | "-inf" => Some(f64::NEG_INFINITY),
118        _ if s
119            .bytes()
120            .all(|b| b.is_ascii_digit() || b"+-.eE".contains(&b)) =>
121        {
122            s.parse().ok()
123        }
124        _ => None,
125    }
126}
127
128/// A JSON string literal (with escapes) to its value.
129fn json_string(s: &str) -> Option<String> {
130    let inner = s.strip_prefix('"')?.strip_suffix('"')?;
131    let mut out = String::new();
132    let mut it = inner.chars();
133    while let Some(c) = it.next() {
134        match c {
135            '"' => return None,
136            '\\' => out.push(match it.next()? {
137                '"' => '"',
138                '\\' => '\\',
139                '/' => '/',
140                'n' => '\n',
141                'r' => '\r',
142                't' => '\t',
143                'b' => '\u{8}',
144                'f' => '\u{c}',
145                'u' => {
146                    let h: String = it.by_ref().take(4).collect();
147                    let cp = u32::from_str_radix(&h, 16).ok()?;
148                    char::from_u32(cp)?
149                }
150                _ => return None,
151            }),
152            c => out.push(c),
153        }
154    }
155    Some(out)
156}
157
158/// One edit for [`edit`]. Paths are the `--get` paths of the decoded tree.
159#[derive(Debug, Clone, PartialEq)]
160pub enum Op {
161    /// Change the protobuf field, CBOR/MessagePack value or DER element at
162    /// the path.
163    Set(String, NewValue),
164    /// Add: a protobuf field `PARENT.N` (appended to the parent message, or
165    /// the top-level message for `N`), a CBOR/MessagePack map key or array
166    /// index (inserted there; an index equal to the length appends), or a DER
167    /// element index (inserted; the value is one complete element as
168    /// `hex:`/`b64:`).
169    Add(String, NewValue),
170    /// Remove the field, value or element at the path.
171    Del(String),
172}
173
174/// Set the field at `path` to `value`: `edit(input, opts, &Op::Set(..))`.
175pub fn set(input: &[u8], opts: &Options, path: &str, value: &NewValue) -> Result<Vec<u8>, Diag> {
176    edit(input, opts, &Op::Set(path.to_string(), value.clone()))
177}
178
179/// Apply one edit and re-encode every enclosing layer in its original style.
180/// The output is decoded again with the same options and checked; the result
181/// is returned only if it holds exactly the requested change.
182pub fn edit(input: &[u8], opts: &Options, op: &Op) -> Result<Vec<u8>, Diag> {
183    let root = crate::peel(input, opts)?;
184    let rp = |out: &[u8]| crate::peel(out, opts).map_err(vf);
185    Ok(edit_at(&root, input, op, &rp)?.0)
186}
187
188/// Decodes re-encoded bytes for verification, giving the node the edit's
189/// path is relative to.
190type Reparse<'r> = dyn Fn(&[u8]) -> Result<Node, Diag> + 'r;
191
192/// Apply `op` to `root` (decoded from `input`); returns the new bytes and
193/// their verified decoding.
194fn edit_at(root: &Node, input: &[u8], op: &Op, rp: &Reparse<'_>) -> Result<(Vec<u8>, Node), Diag> {
195    if let Some(c) = crossing(root, op)? {
196        return edit_across(root, input, op, c, rp);
197    }
198    if jwt_parts(root).is_some() {
199        return Err(jwt_unsupported());
200    }
201    if crate::is_values(root) {
202        return values_op(root, input, op, rp);
203    }
204    if crate::is_der(root) {
205        return der_op(root, input, op, rp);
206    }
207    protobuf_op(root, input, op, rp)
208}
209
210impl Op {
211    fn path(&self) -> &str {
212        match self {
213            Op::Set(p, _) | Op::Add(p, _) | Op::Del(p) => p,
214        }
215    }
216
217    fn with_path(&self, path: String) -> Op {
218        match self {
219            Op::Set(_, v) => Op::Set(path, v.clone()),
220            Op::Add(_, v) => Op::Add(path, v.clone()),
221            Op::Del(_) => Op::Del(path),
222        }
223    }
224}
225
226/// Where `op`'s path last crosses into a decoded node, as `--get` walks it.
227/// An add or delete is located by its parent, which may itself be a string
228/// or byte string holding the decoded data (`2.0` adds element 0 to the DER
229/// in protobuf string field 2).
230fn crossing<'a>(root: &'a Node, op: &Op) -> Result<Option<Crossing<'a>>, Diag> {
231    let path = op.path();
232    if let Op::Set(..) = op {
233        let (pick, cx) = get::locate(root, path)?;
234        if let Pick::Json(_) = pick {
235            return Err(json_unsupported());
236        }
237        return Ok(cx);
238    }
239    let Some((parent, _)) = path.rsplit_once('.') else {
240        return Ok(None);
241    };
242    // A bad parent is reported by the single-format op, with its own errors.
243    let Ok((pick, cx)) = get::locate(root, parent) else {
244        return Ok(None);
245    };
246    if let Pick::Json(_) = pick {
247        return Err(json_unsupported());
248    }
249    Ok(get::leaf_crossing(&pick, parent.split('.').count()).or(cx))
250}
251
252/// An edit inside decoded data: edit the inner bytes, then set the item that
253/// holds them (which may itself be inside decoded data) to the new bytes.
254/// Verification decodes the whole output and follows the path back into the
255/// decoded node, so the inner edit is checked as `--get` will see it.
256fn edit_across(
257    root: &Node,
258    input: &[u8],
259    op: &Op,
260    c: Crossing<'_>,
261    rp: &Reparse<'_>,
262) -> Result<(Vec<u8>, Node), Diag> {
263    let payload = match c.holder {
264        Holder::Field(f) => f.payload(),
265        Holder::Value(v) => v.untagged().payload(),
266        Holder::Jwt => return Err(jwt_unsupported()),
267    }
268    .ok_or_else(|| unsupported("the decoded data's holder has no payload"))?;
269    let segs: Vec<&str> = op.path().split('.').collect();
270    let prefix = segs[..c.at].join(".");
271    let inner_op = op.with_path(segs[c.at..].join("."));
272    let done: RefCell<Option<(Vec<u8>, Node)>> = RefCell::new(None);
273    let inner_rp = |inner: &[u8]| -> Result<Node, Diag> {
274        let set = Op::Set(prefix.clone(), NewValue::Bytes(inner.to_vec()));
275        let (out, again) = edit_at(root, input, &set, rp)?;
276        let node = match crossing(&again, op) {
277            Ok(Some(c2)) if c2.at == c.at => c2.node.clone(),
278            Ok(_) => {
279                return Err(verify_failed(&format!(
280                    "'{prefix}' no longer holds decoded data"
281                )));
282            }
283            Err(e) => return Err(vf(e)),
284        };
285        *done.borrow_mut() = Some((out, again));
286        Ok(node)
287    };
288    edit_at(c.node, &payload, &inner_op, &inner_rp)?;
289    done.into_inner()
290        .ok_or_else(|| verify_failed("the outer layers were not re-encoded"))
291}
292
293/// A selection error on the re-encoded output is a verification failure.
294fn vf(e: Diag) -> Diag {
295    verify_failed(&format!("{}: {}", e.code, e.message))
296}
297
298fn json_unsupported() -> Diag {
299    unsupported("editing values inside JSON text is not supported; set the whole text instead")
300}
301
302fn jwt_unsupported() -> Diag {
303    unsupported(
304        "editing a JWT would invalidate its signature; decode the part, edit it, and re-sign it",
305    )
306}
307
308// ---------------------------------------------------------------- protobuf ops
309
310fn protobuf_op(
311    root: &Node,
312    input: &[u8],
313    op: &Op,
314    rp: &Reparse<'_>,
315) -> Result<(Vec<u8>, Node), Diag> {
316    match op {
317        Op::Set(path, value) => {
318            // Validates the path and gives the same errors as --get.
319            let target = crate::select(root, path)?;
320            let expected = encode_payload(target, value)?;
321            let segs = parse_path(path)?;
322            let out = rebuild(
323                root,
324                input,
325                &Edit::Field(&segs, &FieldAction::Replace(value)),
326            )?;
327            let again = rp(&out)?;
328            let f = crate::select(&again, path).map_err(vf)?;
329            if f.payload().as_deref() != Some(&expected[..])
330                || f.value.wire_name() != target.value.wire_name()
331            {
332                return Err(verify_failed("the field does not hold the new value"));
333            }
334            Ok((out, again))
335        }
336        Op::Del(path) => {
337            crate::select(root, path)?;
338            let segs = parse_path(path)?;
339            let (prefix, (num, _)) = (&segs[..segs.len() - 1], segs[segs.len() - 1]);
340            let before = pb_count(root, prefix, num)?;
341            let out = rebuild(root, input, &Edit::Field(&segs, &FieldAction::Delete))?;
342            let again = rp(&out)?;
343            if pb_count(&again, prefix, num).map_err(vf)? + 1 != before {
344                return Err(verify_failed("the field was not removed"));
345            }
346            Ok((out, again))
347        }
348        Op::Add(path, value) => {
349            if path.trim_end().ends_with(']') {
350                return Err(Diag::new(
351                    "BAD_PATH",
352                    "an added field's path ends in its field number (e.g. 1.3), not an index",
353                    None,
354                ));
355            }
356            let segs = parse_path(path)?;
357            let (prefix, (num, _)) = (&segs[..segs.len() - 1], segs[segs.len() - 1]);
358            if num == 0 {
359                return Err(Diag::new(
360                    "FIELD_NUMBER_ZERO",
361                    "field number 0 is invalid",
362                    None,
363                ));
364            }
365            if num > (1 << 29) - 1 {
366                return Err(Diag::new(
367                    "FIELD_NUMBER_TOO_LARGE",
368                    "field numbers go up to 536870911",
369                    None,
370                ));
371            }
372            let before = pb_count(root, prefix, num)?;
373            let (wire, payload) = new_field_payload(num, value)?;
374            let mut bytes = varint::encode(u64::from(num) << 3 | wire);
375            if wire == 2 {
376                bytes.extend_from_slice(&varint::encode(payload.len() as u64));
377            }
378            bytes.extend_from_slice(&payload);
379            let out = rebuild(
380                root,
381                input,
382                &Edit::Field(prefix, &FieldAction::Append(&bytes)),
383            )?;
384            let again = rp(&out)?;
385            let f = crate::select(&again, &format!("{path}[{before}]")).map_err(vf)?;
386            let wire_name = ["VARINT", "I64", "LEN"][wire as usize];
387            if f.payload().as_deref() != Some(&payload[..]) || f.value.wire_name() != wire_name {
388                return Err(verify_failed("the new field does not hold the value"));
389            }
390            Ok((out, again))
391        }
392    }
393}
394
395/// The fields of the message at `prefix` (the top-level message when empty).
396fn pb_children<'a>(root: &'a Node, prefix: &[(u32, usize)]) -> Result<&'a [Field], Diag> {
397    if prefix.is_empty() {
398        return message_fields(root).ok_or_else(|| {
399            Diag::new(
400                "PATH_NOT_MESSAGE",
401                "the input did not decode to a protobuf message",
402                None,
403            )
404        });
405    }
406    let p = prefix
407        .iter()
408        .map(|(n, i)| {
409            if *i == 0 {
410                n.to_string()
411            } else {
412                format!("{n}[{i}]")
413            }
414        })
415        .collect::<Vec<_>>()
416        .join(".");
417    let f = crate::select(root, &p)?;
418    field_children(f).ok_or_else(|| {
419        Diag::new(
420            "PATH_NOT_MESSAGE",
421            format!("field at '{p}' is not a message"),
422            None,
423        )
424    })
425}
426
427fn pb_count(root: &Node, prefix: &[(u32, usize)], num: u32) -> Result<usize, Diag> {
428    Ok(pb_children(root, prefix)?
429        .iter()
430        .filter(|f| f.number == num)
431        .count())
432}
433
434/// Wire type and payload of a new field: integers and bools are VARINT,
435/// floats are I64 (double), strings and bytes are LEN.
436fn new_field_payload(num: u32, v: &NewValue) -> Result<(u64, Vec<u8>), Diag> {
437    Ok(match v {
438        NewValue::Int(n) => {
439            if *n < i128::from(i64::MIN) || *n > i128::from(u64::MAX) {
440                return Err(Diag::new(
441                    "VALUE_OUT_OF_RANGE",
442                    "a VARINT must be in [-2^63, 2^64)",
443                    None,
444                ));
445            }
446            (
447                0,
448                varint::encode(if *n < 0 { *n as i64 as u64 } else { *n as u64 }),
449            )
450        }
451        NewValue::Sint(n) => (0, varint::encode(((*n << 1) ^ (*n >> 63)) as u64)),
452        NewValue::Bool(b) => (0, vec![u8::from(*b)]),
453        NewValue::Float(x) => (1, x.to_bits().to_le_bytes().to_vec()),
454        NewValue::Str(s) => (2, s.as_bytes().to_vec()),
455        NewValue::Bytes(b) => (2, b.clone()),
456        NewValue::Null => {
457            return Err(Diag::new(
458                "TYPE_MISMATCH",
459                format!("field {num}: protobuf has no null; use --del to remove a field"),
460                None,
461            ));
462        }
463    })
464}
465
466// ---------------------------------------------------------------- CBOR/MessagePack ops
467
468fn values_op(
469    root: &Node,
470    input: &[u8],
471    op: &Op,
472    rp: &Reparse<'_>,
473) -> Result<(Vec<u8>, Node), Diag> {
474    let codec = innermost(root).codec.clone();
475    let vbuf = innermost_buf(root, input);
476    let encode = |v: &NewValue, like: &ValueKind| match codec {
477        Codec::Cbor => encode_value::cbor_scalar(v, like),
478        _ => encode_value::msgpack_scalar(v, like),
479    };
480    let check_codec = |again: &Node| {
481        if innermost(again).codec == codec {
482            Ok(())
483        } else {
484            Err(verify_failed(&format!(
485                "the data now decodes as {} instead of {}",
486                innermost(again).codec.name(),
487                codec.name()
488            )))
489        }
490    };
491    match op {
492        Op::Set(path, value) => {
493            // Validates the path with the same errors as --get.
494            let target = crate::select_value(root, path)?.untagged();
495            let item = encode(value, &target.kind)?;
496            let expected = parse_one(&codec, &item)?;
497            let out = rebuild(root, input, &Edit::Splices(&[(target.range, item)]))?;
498            let again = rp(&out)?;
499            check_codec(&again)?;
500            let got = crate::select_value(&again, path).map_err(vf)?.untagged();
501            if structural(got) != structural(&expected) {
502                return Err(verify_failed("the value does not hold the new item"));
503            }
504            Ok((out, again))
505        }
506        Op::Del(path) => {
507            crate::select_value(root, path)?;
508            let (parent, last) = split_last(path);
509            let c = container(root, parent)?;
510            let (range, count) = match &c.kind {
511                ValueKind::Array(items) => {
512                    let i: usize = last.parse().expect("validated by select_value");
513                    (items[i].range, items.len())
514                }
515                ValueKind::Map(entries) => {
516                    let i = map_index(entries, last).expect("validated by select_value");
517                    (
518                        [entries[i].0.range[0], entries[i].1.range[1]],
519                        entries.len(),
520                    )
521                }
522                _ => unreachable!("container() returns maps and arrays"),
523            };
524            let mut splices: Vec<([usize; 2], Vec<u8>)> = header_splice(&codec, vbuf, c, count - 1)
525                .into_iter()
526                .collect();
527            splices.push((range, vec![]));
528            let out = rebuild(root, input, &Edit::Splices(&splices))?;
529            let again = rp(&out)?;
530            check_codec(&again)?;
531            if container_len(container(&again, parent).map_err(vf)?) + 1 != count {
532                return Err(verify_failed("the item was not removed"));
533            }
534            Ok((out, again))
535        }
536        Op::Add(path, value) => {
537            let (parent, last) = split_last(path);
538            let c = container(root, parent)?;
539            let item = encode(value, &ValueKind::Null)?;
540            let expected = parse_one(&codec, &item)?;
541            let (pos, bytes, count) = match &c.kind {
542                ValueKind::Map(entries) => {
543                    if map_index(entries, last).is_some() {
544                        return Err(Diag::new(
545                            "ALREADY_EXISTS",
546                            format!("key '{last}' already exists; use PATH=VALUE to change it"),
547                            None,
548                        ));
549                    }
550                    let mut bytes = encode(&NewValue::Str(last.to_string()), &ValueKind::Null)?;
551                    bytes.extend_from_slice(&item);
552                    let end = end_pos(c, entries.last().map(|e| e.1.range[1]));
553                    (end, bytes, entries.len())
554                }
555                ValueKind::Array(items) => {
556                    let i: usize = last.parse().map_err(|_| {
557                        Diag::new("BAD_PATH", format!("'{last}' is not an array index"), None)
558                    })?;
559                    if i > items.len() {
560                        return Err(Diag::new(
561                            "PATH_NOT_FOUND",
562                            format!(
563                                "index {i} is past the end (the array has {} items)",
564                                items.len()
565                            ),
566                            None,
567                        ));
568                    }
569                    let pos = match items.get(i) {
570                        Some(v) => v.range[0],
571                        None => end_pos(c, items.last().map(|v| v.range[1])),
572                    };
573                    (pos, item.clone(), items.len())
574                }
575                _ => unreachable!("container() returns maps and arrays"),
576            };
577            let mut splices: Vec<([usize; 2], Vec<u8>)> = header_splice(&codec, vbuf, c, count + 1)
578                .into_iter()
579                .collect();
580            splices.push(([pos, pos], bytes));
581            let out = rebuild(root, input, &Edit::Splices(&splices))?;
582            let again = rp(&out)?;
583            check_codec(&again)?;
584            let got = crate::select_value(&again, path).map_err(vf)?.untagged();
585            if structural(got) != structural(&expected)
586                || container_len(container(&again, parent).map_err(vf)?) != count + 1
587            {
588                return Err(verify_failed("the new item is not where it should be"));
589            }
590            Ok((out, again))
591        }
592    }
593}
594
595/// `a.b.c` -> (`a.b`, `c`); `c` -> (``, `c`).
596fn split_last(path: &str) -> (&str, &str) {
597    path.rsplit_once('.').unwrap_or(("", path))
598}
599
600/// The map or array at `parent` (the single top-level item when empty),
601/// with tags followed.
602fn container<'a>(root: &'a Node, parent: &str) -> Result<&'a Value, Diag> {
603    let v = if parent.is_empty() {
604        match values_items(root) {
605            Some([only]) => only,
606            _ => {
607                return Err(unsupported(
608                    "adding or removing top-level items of a multi-item sequence is not supported",
609                ));
610            }
611        }
612    } else {
613        crate::select_value(root, parent)?
614    }
615    .untagged();
616    match v.kind {
617        ValueKind::Array(_) | ValueKind::Map(_) => Ok(v),
618        _ => Err(Diag::new(
619            "PATH_NOT_MESSAGE",
620            format!("'{parent}' is not a map or array"),
621            None,
622        )),
623    }
624}
625
626fn container_len(c: &Value) -> usize {
627    match &c.kind {
628        ValueKind::Array(items) => items.len(),
629        ValueKind::Map(entries) => entries.len(),
630        _ => 0,
631    }
632}
633
634/// Where a new item goes after the last one: after `last_end`, or for an
635/// empty container right after the header (definite) / before the break
636/// byte (indefinite).
637fn end_pos(c: &Value, last_end: Option<usize>) -> usize {
638    match last_end {
639        Some(e) => e,
640        None if c.indefinite => c.range[1] - 1,
641        None => c.range[1],
642    }
643}
644
645/// Rewrite a definite container's header for `n` items. Indefinite (CBOR)
646/// containers have no count.
647fn header_splice(codec: &Codec, buf: &[u8], c: &Value, n: usize) -> Option<([usize; 2], Vec<u8>)> {
648    if c.indefinite {
649        return None;
650    }
651    let s = c.range[0];
652    let map = matches!(c.kind, ValueKind::Map(_));
653    let (len, head) = match codec {
654        Codec::Cbor => {
655            let len = match buf[s] & 0x1f {
656                24 => 2,
657                25 => 3,
658                26 => 5,
659                27 => 9,
660                _ => 1,
661            };
662            let mut head = Vec::new();
663            encode_value::cbor_head(if map { 5 } else { 4 }, n as u64, &mut head);
664            (len, head)
665        }
666        _ => {
667            let len = match buf[s] {
668                0xdc | 0xde => 3,
669                0xdd | 0xdf => 5,
670                _ => 1,
671            };
672            (len, encode_value::msgpack_container_head(map, n as u64))
673        }
674    };
675    Some(([s, s + len], head))
676}
677
678/// The decoded buffer of the innermost layer (what value ranges index).
679pub(crate) fn innermost_buf<'a>(node: &'a Node, buf: &'a [u8]) -> &'a [u8] {
680    match &node.detail {
681        Detail::Layer { decoded, child } => innermost_buf(child, decoded),
682        _ => buf,
683    }
684}
685
686/// The node at the end of the layer chain.
687fn innermost(node: &Node) -> &Node {
688    match &node.detail {
689        Detail::Layer { child, .. } => innermost(child),
690        _ => node,
691    }
692}
693
694/// Decode exactly one item of `codec` from `bytes`.
695fn parse_one(codec: &Codec, bytes: &[u8]) -> Result<Value, Diag> {
696    let items = match codec {
697        Codec::Cbor => cbor::parse_sequence(bytes)?,
698        _ => msgpack::parse_sequence(bytes)?,
699    };
700    items
701        .into_iter()
702        .next()
703        .ok_or_else(|| verify_failed("the encoder produced no item"))
704}
705
706/// A value's kind with ranges and nested detection stripped, for comparison.
707fn structural(v: &Value) -> ValueKind {
708    match &v.kind {
709        ValueKind::Bytes { data, .. } => ValueKind::Bytes {
710            data: data.clone(),
711            decoded: None,
712        },
713        ValueKind::Float { value, width } => ValueKind::Float {
714            // Compare bit patterns so NaN equals NaN.
715            value: f64::from_bits(value.to_bits()),
716            width: *width,
717        },
718        k => k.clone(),
719    }
720}
721
722// ---------------------------------------------------------------- rebuilding
723
724/// What to change, carried down through the layers.
725enum Edit<'a> {
726    /// A protobuf edit: the path to the field (replace/delete) or to the
727    /// parent message (append; empty = top level).
728    Field(&'a [(u32, usize)], &'a FieldAction<'a>),
729    /// CBOR/MessagePack: sorted, non-overlapping byte replacements in the
730    /// value buffer.
731    Splices(&'a [([usize; 2], Vec<u8>)]),
732    /// DER: a child-index path (the first index picks a PEM bundle's block).
733    Der(&'a [usize], &'a DerAction<'a>),
734}
735
736enum FieldAction<'a> {
737    Replace(&'a NewValue),
738    Delete,
739    /// Encoded field bytes (tag included) to append.
740    Append(&'a [u8]),
741}
742
743enum DerAction<'a> {
744    /// A complete new element.
745    Replace(&'a [u8]),
746    Delete,
747    /// A complete element, inserted before the index (or appended at the end).
748    Insert(&'a [u8]),
749}
750
751fn verify_failed(why: &str) -> Diag {
752    Diag::new(
753        "REENCODE_VERIFY_FAILED",
754        format!(
755            "the re-encoded output does not decode back as expected ({why}); \
756             pin the layers with --in/--as and try again"
757        ),
758        None,
759    )
760}
761
762fn unsupported(what: impl Into<String>) -> Diag {
763    Diag::new("REENCODE_UNSUPPORTED", what, None)
764}
765
766/// Re-encode `node` (parsed from `buf`) with `edit` applied.
767fn rebuild(node: &Node, buf: &[u8], edit: &Edit<'_>) -> Result<Vec<u8>, Diag> {
768    match (&node.detail, edit) {
769        (Detail::Message { fields }, Edit::Field(segs, action)) => {
770            let mut out = Vec::with_capacity(buf.len());
771            edit_fields(buf, [0, buf.len()], fields, segs, action, &mut out)?;
772            Ok(out)
773        }
774        (Detail::Values { .. }, Edit::Splices(splices)) => {
775            let mut out = Vec::with_capacity(buf.len());
776            let mut at = 0;
777            for ([s, e], bytes) in splices.iter() {
778                out.extend_from_slice(&buf[at..*s]);
779                out.extend_from_slice(bytes);
780                at = *e;
781            }
782            out.extend_from_slice(&buf[at..]);
783            Ok(out)
784        }
785        (Detail::Der { items }, Edit::Der(segs, action)) => {
786            let mut out = Vec::with_capacity(buf.len());
787            der_splice(buf, [0, buf.len()], items, segs, action, &mut out);
788            Ok(out)
789        }
790        (Detail::Parts { parts, .. }, Edit::Der(segs, action)) if node.codec == Codec::Bundle => {
791            // The first index picks the block; only that block is re-encoded.
792            let part = &parts[segs[0]];
793            let (Codec::Pem { label }, Detail::Layer { decoded, child }) =
794                (&part.codec, &part.detail)
795            else {
796                return Err(unsupported("a bundle part is not a PEM block"));
797            };
798            let der = rebuild(child, decoded, &Edit::Der(&segs[1..], action))?;
799            let t = std::str::from_utf8(buf)
800                .map_err(|_| unsupported("the bundle's original text is not UTF-8"))?;
801            Ok(reencode::pem_like(t, part.range, label, &der)?.into_bytes())
802        }
803        (Detail::Layer { decoded, child }, _) => {
804            let inner = rebuild(child, decoded, edit)?;
805            encode_layer(&node.codec, buf, &inner)
806        }
807        (Detail::Parts { .. }, _) if matches!(node.codec, Codec::Jwt { .. }) => {
808            Err(jwt_unsupported())
809        }
810        _ => Err(unsupported(format!(
811            "re-encoding a {} layer is not supported yet",
812            node.codec.name()
813        ))),
814    }
815}
816
817/// Re-encode a text or compression layer around its new decoded bytes.
818fn encode_layer(codec: &Codec, orig: &[u8], inner: &[u8]) -> Result<Vec<u8>, Diag> {
819    let text = || {
820        std::str::from_utf8(orig).map_err(|_| unsupported("the layer's original text is not UTF-8"))
821    };
822    Ok(match codec {
823        Codec::Hex => reencode::hex_like(text()?, inner).into_bytes(),
824        Codec::Dump { style, start } => {
825            reencode::dump_like(text()?, style, *start, inner).into_bytes()
826        }
827        Codec::Base64 { alphabet, padded } => {
828            reencode::base64_like(text()?, *alphabet, *padded, inner).into_bytes()
829        }
830        Codec::Pem { label } => {
831            let t = text()?;
832            let range = match text::decode_pem(t) {
833                Some(Ok(b)) if b.blocks.len() == 1 => b.blocks[0].range,
834                _ => return Err(unsupported("could not locate the PEM block again")),
835            };
836            reencode::pem_like(t, range, label, inner)?.into_bytes()
837        }
838        Codec::Gzip { .. } => compress::recompress("gzip", orig, inner)?,
839        Codec::Zlib => compress::recompress("zlib", orig, inner)?,
840        Codec::Zstd => compress::recompress("zstd", orig, inner)?,
841        c => {
842            return Err(unsupported(format!(
843                "re-encoding a {} layer is not supported yet",
844                c.name()
845            )));
846        }
847    })
848}
849
850/// Copy `buf[region]` to `out`, applying `action` at `segs`. Field ranges
851/// are absolute in `buf` (nested messages share the buffer). For an append,
852/// `segs` is the parent message's path and may be empty.
853fn edit_fields(
854    buf: &[u8],
855    region: [usize; 2],
856    fields: &[Field],
857    segs: &[(u32, usize)],
858    action: &FieldAction<'_>,
859    out: &mut Vec<u8>,
860) -> Result<(), Diag> {
861    let Some(&(num, idx)) = segs.first() else {
862        // The target message itself: only reached for an append.
863        out.extend_from_slice(&buf[region[0]..region[1]]);
864        if let FieldAction::Append(bytes) = action {
865            out.extend_from_slice(bytes);
866        }
867        return Ok(());
868    };
869    let f = fields
870        .iter()
871        .filter(|f| f.number == num)
872        .nth(idx)
873        .expect("path was validated by select");
874    let [fs, fe] = f.range;
875    let (_, tag_len) = varint::decode(&buf[fs..fe]).expect("parsed tag");
876    let tag = &buf[fs..fs + tag_len];
877    out.extend_from_slice(&buf[region[0]..fs]);
878    let rest = &segs[1..];
879    match (&f.value, action) {
880        (_, FieldAction::Delete) if rest.is_empty() => {}
881        (_, FieldAction::Replace(v)) if rest.is_empty() => {
882            let payload = encode_payload(f, v)?;
883            out.extend_from_slice(tag);
884            if matches!(f.value, FieldValue::Len { .. }) {
885                out.extend_from_slice(&varint::encode(payload.len() as u64));
886            }
887            out.extend_from_slice(&payload);
888        }
889        (FieldValue::Group { fields: inner }, _) => {
890            // Start tag, fields, end tag: only the fields change. The end tag
891            // starts where the last inner field ends (it may be an overlong
892            // varint, so its length cannot be derived from the number).
893            let start = fs + tag_len;
894            let end = inner.last().map_or(start, |f| f.range[1]);
895            out.extend_from_slice(tag);
896            edit_fields(buf, [start, end], inner, rest, action, out)?;
897            out.extend_from_slice(&buf[end..fe]);
898        }
899        (
900            FieldValue::Len {
901                data_range, alts, ..
902            },
903            _,
904        ) => {
905            let [ds, de] = *data_range;
906            // Enter the same interpretation as `select`: the first message
907            // alt, or a string whose decoded layers end in a message.
908            let mut inner = Vec::new();
909            let mut entered = false;
910            for a in alts {
911                match &a.kind {
912                    AltKind::Message(sub) => {
913                        edit_fields(buf, [ds, de], sub, rest, action, &mut inner)?;
914                        entered = true;
915                    }
916                    AltKind::String {
917                        decoded: Some(n), ..
918                    } if message_fields(n).is_some() => {
919                        inner = rebuild(n, &buf[ds..de], &Edit::Field(rest, action))?;
920                        entered = true;
921                    }
922                    // An empty LEN field is an empty message: fields can be
923                    // added to it.
924                    AltKind::Empty => {
925                        edit_fields(buf, [ds, de], &[], rest, action, &mut inner)?;
926                        entered = true;
927                    }
928                    _ => continue,
929                }
930                break;
931            }
932            if !entered {
933                unreachable!("path was validated by select");
934            }
935            out.extend_from_slice(tag);
936            out.extend_from_slice(&varint::encode(inner.len() as u64));
937            out.extend_from_slice(&inner);
938        }
939        _ => unreachable!("select only descends into LEN fields and groups"),
940    }
941    out.extend_from_slice(&buf[fe..region[1]]);
942    Ok(())
943}
944
945fn mismatch(f: &Field, hint: &str) -> Diag {
946    Diag::new(
947        "TYPE_MISMATCH",
948        format!("field {} is {}; {hint}", f.number, f.value.wire_name()),
949        None,
950    )
951}
952
953fn out_of_range(f: &Field, range: &str) -> Diag {
954    Diag::new(
955        "VALUE_OUT_OF_RANGE",
956        format!(
957            "field {} is {}: the value must be in {range}",
958            f.number,
959            f.value.wire_name()
960        ),
961        None,
962    )
963}
964
965/// The new payload bytes for `f` (tag and LEN prefix excluded), in the
966/// field's existing wire type.
967fn encode_payload(f: &Field, v: &NewValue) -> Result<Vec<u8>, Diag> {
968    match (&f.value, v) {
969        (FieldValue::Varint { .. }, NewValue::Int(n)) => {
970            if *n < i128::from(i64::MIN) || *n > i128::from(u64::MAX) {
971                return Err(out_of_range(f, "[-2^63, 2^64)"));
972            }
973            // Negative values use the 10-byte two's complement form (int32/int64).
974            Ok(varint::encode(if *n < 0 {
975                *n as i64 as u64
976            } else {
977                *n as u64
978            }))
979        }
980        (FieldValue::Varint { .. }, NewValue::Sint(n)) => {
981            Ok(varint::encode(((*n << 1) ^ (*n >> 63)) as u64))
982        }
983        (FieldValue::Varint { .. }, NewValue::Bool(b)) => Ok(vec![u8::from(*b)]),
984        (FieldValue::Varint { .. }, _) => Err(mismatch(f, "use an integer, sint:N or true/false")),
985        (FieldValue::I64 { .. }, NewValue::Int(n)) => {
986            if *n < i128::from(i64::MIN) || *n > i128::from(u64::MAX) {
987                return Err(out_of_range(f, "[-2^63, 2^64)"));
988            }
989            Ok((*n as u64).to_le_bytes().to_vec())
990        }
991        (FieldValue::I64 { .. }, NewValue::Float(x)) => Ok(x.to_bits().to_le_bytes().to_vec()),
992        (FieldValue::I32 { .. }, NewValue::Int(n)) => {
993            if *n < i128::from(i32::MIN) || *n > i128::from(u32::MAX) {
994                return Err(out_of_range(f, "[-2^31, 2^32)"));
995            }
996            Ok((*n as u32).to_le_bytes().to_vec())
997        }
998        (FieldValue::I32 { .. }, NewValue::Float(x)) => {
999            let y = *x as f32;
1000            if x.is_finite() && !y.is_finite() {
1001                return Err(out_of_range(f, "the float32 range"));
1002            }
1003            Ok(y.to_bits().to_le_bytes().to_vec())
1004        }
1005        (FieldValue::I64 { .. } | FieldValue::I32 { .. }, _) => {
1006            Err(mismatch(f, "use an integer or a float"))
1007        }
1008        (FieldValue::Len { .. }, NewValue::Str(s)) => Ok(s.as_bytes().to_vec()),
1009        (FieldValue::Len { .. }, NewValue::Bytes(b)) => Ok(b.clone()),
1010        (FieldValue::Len { .. }, _) => Err(mismatch(
1011            f,
1012            "use \"text\", str:text, hex:.. or b64:.. (or a path into its message)",
1013        )),
1014        (FieldValue::Group { .. }, _) => Err(mismatch(f, "set one of its fields instead")),
1015    }
1016}
1017
1018// ---------------------------------------------------------------- DER
1019
1020/// Edits on DER. A changed element keeps its tag and its content is encoded
1021/// for its type; an added element is one complete element given as bytes.
1022/// The length of every enclosing element (including encapsulating BIT/OCTET
1023/// STRINGs) is rewritten.
1024fn der_op(root: &Node, input: &[u8], op: &Op, rp: &Reparse<'_>) -> Result<(Vec<u8>, Node), Diag> {
1025    let path = match op {
1026        Op::Set(p, _) | Op::Add(p, _) | Op::Del(p) => p,
1027    };
1028    let segs: Vec<usize> = path
1029        .split('.')
1030        .map(|p| {
1031            p.parse().map_err(|_| {
1032                Diag::new(
1033                    "BAD_PATH",
1034                    format!("invalid path segment '{p}' (DER paths are child indices, e.g. 0.0.6)"),
1035                    None,
1036                )
1037            })
1038        })
1039        .collect::<Result<_, _>>()?;
1040    let prefix = &segs[..segs.len() - 1];
1041    let need_der = |again: &Node| {
1042        if crate::is_der(again) {
1043            Ok(())
1044        } else {
1045            Err(verify_failed("the data no longer decodes as DER"))
1046        }
1047    };
1048    match op {
1049        Op::Set(_, value) => {
1050            let target = crate::select_der(root, path)?;
1051            let content = der_content(target, value)?;
1052            let mut elem = der_tag_bytes(target, input_for(root, input, target)).to_vec();
1053            elem.extend_from_slice(&der_length(content.len()));
1054            elem.extend_from_slice(&content);
1055            let out = rebuild(root, input, &Edit::Der(&segs, &DerAction::Replace(&elem)))?;
1056            let again = rp(&out)?;
1057            need_der(&again)?;
1058            let got = crate::select_der(&again, path).map_err(vf)?;
1059            let bit_string = target.class == TagClass::Universal && target.number == 3;
1060            let expected = if bit_string {
1061                &content[1..]
1062            } else {
1063                &content[..]
1064            };
1065            if (got.class, got.number, got.constructed) != (target.class, target.number, false)
1066                || got.payload().as_deref() != Some(expected)
1067            {
1068                return Err(verify_failed("the element does not hold the new value"));
1069            }
1070            Ok((out, again))
1071        }
1072        Op::Del(_) => {
1073            crate::select_der(root, path)?;
1074            let before = der_children(root, prefix)?.len();
1075            let out = rebuild(root, input, &Edit::Der(&segs, &DerAction::Delete))?;
1076            let again = rp(&out)?;
1077            need_der(&again)?;
1078            if der_children(&again, prefix).map_err(vf)?.len() + 1 != before {
1079                return Err(verify_failed("the element was not removed"));
1080            }
1081            Ok((out, again))
1082        }
1083        Op::Add(_, value) => {
1084            let before = der_children(root, prefix)?.len();
1085            let idx = segs[segs.len() - 1];
1086            if idx > before {
1087                return Err(Diag::new(
1088                    "PATH_NOT_FOUND",
1089                    format!("index {idx} is past the end (there are {before} elements)"),
1090                    None,
1091                ));
1092            }
1093            let NewValue::Bytes(elem) = value else {
1094                return Err(Diag::new(
1095                    "TYPE_MISMATCH",
1096                    "an added DER element is one complete element as hex:.. or b64:.. (e.g. hex:020105)",
1097                    None,
1098                ));
1099            };
1100            let mut st = der::Stats::default();
1101            let parsed = match der::parse(elem, &mut st) {
1102                Ok(items) if items.len() == 1 => items.into_iter().next().expect("one item"),
1103                _ => {
1104                    return Err(Diag::new(
1105                        "BAD_VALUE",
1106                        "the added bytes are not exactly one complete DER element",
1107                        None,
1108                    ));
1109                }
1110            };
1111            let out = rebuild(root, input, &Edit::Der(&segs, &DerAction::Insert(elem)))?;
1112            let again = rp(&out)?;
1113            need_der(&again)?;
1114            let got = crate::select_der(&again, path).map_err(vf)?;
1115            if (got.class, got.number, got.constructed, got.payload())
1116                != (
1117                    parsed.class,
1118                    parsed.number,
1119                    parsed.constructed,
1120                    parsed.payload(),
1121                )
1122                || der_children(&again, prefix).map_err(vf)?.len() != before + 1
1123            {
1124                return Err(verify_failed("the new element is not where it should be"));
1125            }
1126            Ok((out, again))
1127        }
1128    }
1129}
1130
1131/// The elements under `prefix`: the top-level elements when it is empty (for
1132/// a PEM bundle, the first index picks the block).
1133fn der_children<'a>(root: &'a Node, prefix: &[usize]) -> Result<&'a [Asn1], Diag> {
1134    let (mut items, rest) = match bundle_parts(root) {
1135        Some(parts) => {
1136            let Some((&block, rest)) = prefix.split_first() else {
1137                return Err(unsupported(
1138                    "adding or removing whole PEM blocks is not supported",
1139                ));
1140            };
1141            let part = parts.get(block).ok_or_else(|| {
1142                Diag::new("PATH_NOT_FOUND", format!("no bundle block {block}"), None)
1143            })?;
1144            let items = der_items(part).ok_or_else(|| {
1145                Diag::new(
1146                    "PATH_NOT_MESSAGE",
1147                    format!("bundle block {block} is not DER"),
1148                    None,
1149                )
1150            })?;
1151            (items, rest)
1152        }
1153        None => (
1154            der_items(root).ok_or_else(|| {
1155                Diag::new("PATH_NOT_MESSAGE", "the input did not decode to DER", None)
1156            })?,
1157            prefix,
1158        ),
1159    };
1160    for &i in rest {
1161        let e = items
1162            .get(i)
1163            .ok_or_else(|| Diag::new("PATH_NOT_FOUND", format!("no element at index {i}"), None))?;
1164        items = e.children().ok_or_else(|| {
1165            Diag::new(
1166                "PATH_NOT_MESSAGE",
1167                format!("element {} has no children", e.tag_name()),
1168                None,
1169            )
1170        })?;
1171    }
1172    Ok(items)
1173}
1174
1175/// The DER buffer `target` was parsed from: the decoded bytes of the layer
1176/// (or bundle block) that holds it. Element ranges index into this buffer.
1177fn input_for<'a>(node: &'a Node, buf: &'a [u8], target: &Asn1) -> &'a [u8] {
1178    match &node.detail {
1179        Detail::Der { .. } => buf,
1180        Detail::Layer { decoded, child } => input_for(child, decoded, target),
1181        Detail::Parts { parts, .. } => {
1182            // The block whose DER contains `target` (by identity).
1183            for p in parts {
1184                if let Detail::Layer { decoded, child } = &p.detail {
1185                    if contains(child, target) {
1186                        return input_for(child, decoded, target);
1187                    }
1188                }
1189            }
1190            buf
1191        }
1192        _ => buf,
1193    }
1194}
1195
1196fn contains(node: &Node, target: &Asn1) -> bool {
1197    fn walk(items: &[Asn1], t: &Asn1) -> bool {
1198        items
1199            .iter()
1200            .any(|e| std::ptr::eq(e, t) || e.children().is_some_and(|c| walk(c, t)))
1201    }
1202    match &node.detail {
1203        Detail::Der { items } => walk(items, target),
1204        Detail::Layer { child, .. } => contains(child, target),
1205        _ => false,
1206    }
1207}
1208
1209/// The identifier octets of `e` (its tag, including high-tag-number form).
1210fn der_tag_bytes<'a>(e: &Asn1, buf: &'a [u8]) -> &'a [u8] {
1211    let s = e.range[0];
1212    let mut n = 1;
1213    if buf[s] & 0x1f == 0x1f {
1214        while buf[s + n] & 0x80 != 0 {
1215            n += 1;
1216        }
1217        n += 1;
1218    }
1219    &buf[s..s + n]
1220}
1221
1222/// A minimal DER length.
1223fn der_length(n: usize) -> Vec<u8> {
1224    if n < 0x80 {
1225        return vec![n as u8];
1226    }
1227    let bytes = (n as u64).to_be_bytes();
1228    let skip = bytes.iter().take_while(|&&b| b == 0).count();
1229    let mut out = vec![0x80 | (8 - skip) as u8];
1230    out.extend_from_slice(&bytes[skip..]);
1231    out
1232}
1233
1234/// Copy `buf[region]` to `out`, applying `action` at `segs` and re-encoding
1235/// the length of every element on the way down.
1236fn der_splice(
1237    buf: &[u8],
1238    region: [usize; 2],
1239    items: &[Asn1],
1240    segs: &[usize],
1241    action: &DerAction<'_>,
1242    out: &mut Vec<u8>,
1243) {
1244    let idx = segs[0];
1245    if segs.len() == 1 {
1246        if let DerAction::Insert(elem) = action {
1247            if idx == items.len() {
1248                out.extend_from_slice(&buf[region[0]..region[1]]);
1249                out.extend_from_slice(elem);
1250                return;
1251            }
1252        }
1253        let e = &items[idx];
1254        out.extend_from_slice(&buf[region[0]..e.range[0]]);
1255        match action {
1256            DerAction::Replace(elem) => out.extend_from_slice(elem),
1257            DerAction::Delete => {}
1258            DerAction::Insert(elem) => {
1259                out.extend_from_slice(elem);
1260                out.extend_from_slice(&buf[e.range[0]..e.range[1]]);
1261            }
1262        }
1263        out.extend_from_slice(&buf[e.range[1]..region[1]]);
1264        return;
1265    }
1266    let e = &items[idx];
1267    out.extend_from_slice(&buf[region[0]..e.range[0]]);
1268    let children = e.children().expect("validated by the caller");
1269    let [cs, ce] = e.content;
1270    // An encapsulating BIT STRING keeps its unused-bits byte.
1271    let prefix = matches!(
1272        e.value,
1273        Asn1Value::Encapsulated {
1274            unused_bits: Some(_),
1275            ..
1276        }
1277    );
1278    let mut content = Vec::new();
1279    if prefix {
1280        content.push(buf[cs]);
1281    }
1282    let start = if prefix { cs + 1 } else { cs };
1283    der_splice(buf, [start, ce], children, &segs[1..], action, &mut content);
1284    out.extend_from_slice(der_tag_bytes(e, buf));
1285    out.extend_from_slice(&der_length(content.len()));
1286    out.extend_from_slice(&content);
1287    out.extend_from_slice(&buf[e.range[1]..region[1]]);
1288}
1289
1290fn der_mismatch(e: &Asn1, hint: &str) -> Diag {
1291    Diag::new(
1292        "TYPE_MISMATCH",
1293        format!("element is {}; {hint}", e.tag_name()),
1294        None,
1295    )
1296}
1297
1298/// The new content octets for `e`, encoded for its type. `hex:`/`b64:` set
1299/// the content verbatim (for a BIT STRING: the bits, with 0 unused bits).
1300fn der_content(e: &Asn1, v: &NewValue) -> Result<Vec<u8>, Diag> {
1301    if e.constructed {
1302        return Err(der_mismatch(e, "set one of its children instead"));
1303    }
1304    let universal = e.class == TagClass::Universal;
1305    if let NewValue::Bytes(b) = v {
1306        return Ok(if universal && e.number == 3 {
1307            let mut c = vec![0];
1308            c.extend_from_slice(b);
1309            c
1310        } else {
1311            b.clone()
1312        });
1313    }
1314    if !universal {
1315        // Context/application/private primitives are untyped: text only.
1316        return match v {
1317            NewValue::Str(s) => Ok(s.as_bytes().to_vec()),
1318            _ => Err(der_mismatch(e, "use \"text\", hex:.. or b64:..")),
1319        };
1320    }
1321    let text_only = |check: fn(char) -> bool, what: &str| -> Result<Vec<u8>, Diag> {
1322        match v {
1323            NewValue::Str(s) => match s.chars().find(|&c| !check(c)) {
1324                None => Ok(s.as_bytes().to_vec()),
1325                Some(c) => Err(Diag::new(
1326                    "VALUE_OUT_OF_RANGE",
1327                    format!("{c:?} is not allowed in a {what}"),
1328                    None,
1329                )),
1330            },
1331            _ => Err(der_mismatch(e, "use \"text\"")),
1332        }
1333    };
1334    match (e.number, v) {
1335        (1, NewValue::Bool(b)) => Ok(vec![if *b { 0xff } else { 0 }]),
1336        (1, _) => Err(der_mismatch(e, "use true or false")),
1337        (2 | 10, NewValue::Int(n)) => Ok(der_int(*n)),
1338        (2 | 10, _) => Err(der_mismatch(
1339            e,
1340            "use an integer, or hex:.. for wider values",
1341        )),
1342        (5, NewValue::Null) => Ok(vec![]),
1343        (5, _) => Err(der_mismatch(e, "use null")),
1344        (6, NewValue::Str(s)) => der_oid(s).ok_or_else(|| {
1345            Diag::new(
1346                "BAD_VALUE",
1347                format!("'{s}' is not a dotted OID (e.g. \"2.5.4.3\")"),
1348                None,
1349            )
1350        }),
1351        (6, _) => Err(der_mismatch(e, "use a dotted OID string, e.g. \"2.5.4.3\"")),
1352        (23 | 24, NewValue::Str(s)) => der_time(s, e.number == 23),
1353        (23 | 24, _) => Err(der_mismatch(
1354            e,
1355            "use a time string, e.g. \"2030-01-01T00:00:00Z\"",
1356        )),
1357        (4 | 12, NewValue::Str(s)) => Ok(s.as_bytes().to_vec()),
1358        (18, _) => text_only(|c| c.is_ascii_digit() || c == ' ', "NumericString"),
1359        (19, _) => text_only(
1360            |c| c.is_ascii_alphanumeric() || " '()+,-./:=?".contains(c),
1361            "PrintableString",
1362        ),
1363        (22, _) => text_only(|c| c.is_ascii(), "IA5String"),
1364        (26, _) => text_only(|c| (' '..='~').contains(&c), "VisibleString"),
1365        (25 | 27, _) => text_only(|_| true, "string"),
1366        (20 | 21, NewValue::Str(s)) => s
1367            .chars()
1368            .map(|c| u8::try_from(u32::from(c)).ok())
1369            .collect::<Option<Vec<u8>>>()
1370            .ok_or_else(|| {
1371                Diag::new(
1372                    "VALUE_OUT_OF_RANGE",
1373                    "T61/Videotex strings hold Latin-1 only",
1374                    None,
1375                )
1376            }),
1377        (30, NewValue::Str(s)) => {
1378            if s.chars().any(|c| u32::from(c) > 0xffff) {
1379                return Err(Diag::new(
1380                    "VALUE_OUT_OF_RANGE",
1381                    "a BMPString holds only U+0000..U+FFFF",
1382                    None,
1383                ));
1384            }
1385            Ok(s.encode_utf16().flat_map(u16::to_be_bytes).collect())
1386        }
1387        (28, NewValue::Str(s)) => Ok(s.chars().flat_map(|c| u32::from(c).to_be_bytes()).collect()),
1388        _ => Err(der_mismatch(
1389            e,
1390            "use hex:.. or b64:.. to set its content bytes",
1391        )),
1392    }
1393}
1394
1395/// Minimal two's complement, big-endian.
1396fn der_int(n: i128) -> Vec<u8> {
1397    let b = n.to_be_bytes();
1398    let mut i = 0;
1399    while i < 15 && ((b[i] == 0 && b[i + 1] & 0x80 == 0) || (b[i] == 0xff && b[i + 1] & 0x80 != 0))
1400    {
1401        i += 1;
1402    }
1403    b[i..].to_vec()
1404}
1405
1406fn der_oid(s: &str) -> Option<Vec<u8>> {
1407    let arcs: Vec<u128> = s
1408        .split('.')
1409        .map(|a| a.parse().ok())
1410        .collect::<Option<_>>()?;
1411    if arcs.len() < 2 || arcs[0] > 2 || (arcs[0] < 2 && arcs[1] >= 40) {
1412        return None;
1413    }
1414    let mut out = Vec::new();
1415    let first = arcs[0].checked_mul(40)?.checked_add(arcs[1])?;
1416    for a in std::iter::once(first).chain(arcs[2..].iter().copied()) {
1417        let mut chunk = vec![(a & 0x7f) as u8];
1418        let mut v = a >> 7;
1419        while v > 0 {
1420            chunk.push(0x80 | (v & 0x7f) as u8);
1421            v >>= 7;
1422        }
1423        chunk.reverse();
1424        out.extend_from_slice(&chunk);
1425    }
1426    Some(out)
1427}
1428
1429/// A UTCTime/GeneralizedTime from its own form or from ISO 8601
1430/// (`2030-01-01T00:00:00Z`, `...T00:00:00.5+02:00`).
1431fn der_time(s: &str, utc: bool) -> Result<Vec<u8>, Diag> {
1432    if der::time_iso(s, utc).is_some() {
1433        return Ok(s.as_bytes().to_vec());
1434    }
1435    let bad = || {
1436        Diag::new(
1437            "BAD_VALUE",
1438            format!("'{s}' is not a time; use e.g. \"2030-01-01T00:00:00Z\""),
1439            None,
1440        )
1441    };
1442    let b = s.as_bytes();
1443    if !s.is_ascii()
1444        || b.len() < 20
1445        || b[4] != b'-'
1446        || b[7] != b'-'
1447        || b[10] != b'T'
1448        || b[13] != b':'
1449        || b[16] != b':'
1450    {
1451        return Err(bad());
1452    }
1453    let (date, time) = (&s[..10], &s[11..19]);
1454    let mut rest = &s[19..];
1455    let mut frac = "";
1456    if let Some(r) = rest.strip_prefix('.') {
1457        let n = r.bytes().take_while(u8::is_ascii_digit).count();
1458        frac = &rest[..1 + n];
1459        rest = &r[n..];
1460    }
1461    let zone = match rest {
1462        "Z" => "Z".to_string(),
1463        z if z.len() == 6 && (z.starts_with('+') || z.starts_with('-')) && &z[3..4] == ":" => {
1464            format!("{}{}", &z[..3], &z[4..])
1465        }
1466        _ => return Err(bad()),
1467    };
1468    let digits: String = format!("{date}{time}")
1469        .chars()
1470        .filter(char::is_ascii_digit)
1471        .collect();
1472    let raw = if utc {
1473        if !frac.is_empty() {
1474            return Err(Diag::new(
1475                "VALUE_OUT_OF_RANGE",
1476                "UTCTime has no fractional seconds",
1477                None,
1478            ));
1479        }
1480        let year: u32 = digits[..4].parse().map_err(|_| bad())?;
1481        if !(1950..=2049).contains(&year) {
1482            return Err(Diag::new(
1483                "VALUE_OUT_OF_RANGE",
1484                "UTCTime covers the years 1950-2049",
1485                None,
1486            ));
1487        }
1488        format!("{}{zone}", &digits[2..])
1489    } else {
1490        format!("{digits}{frac}{zone}")
1491    };
1492    if der::time_iso(&raw, utc).is_none() {
1493        return Err(bad());
1494    }
1495    Ok(raw.into_bytes())
1496}
1497
1498#[cfg(test)]
1499mod tests {
1500    use super::*;
1501
1502    #[test]
1503    fn value_syntax() {
1504        assert_eq!(parse_value("42").unwrap(), NewValue::Int(42));
1505        assert_eq!(parse_value("-2").unwrap(), NewValue::Int(-2));
1506        assert_eq!(parse_value("sint:-2").unwrap(), NewValue::Sint(-2));
1507        assert_eq!(parse_value("1.5").unwrap(), NewValue::Float(1.5));
1508        assert_eq!(parse_value("float:1").unwrap(), NewValue::Float(1.0));
1509        assert!(matches!(parse_value("float:NaN").unwrap(), NewValue::Float(x) if x.is_nan()));
1510        assert_eq!(parse_value("true").unwrap(), NewValue::Bool(true));
1511        assert_eq!(parse_value("null").unwrap(), NewValue::Null);
1512        assert_eq!(
1513            parse_value(r#""a\"bé""#).unwrap(),
1514            NewValue::Str("a\"bé".into())
1515        );
1516        assert_eq!(
1517            parse_value("str:hi there").unwrap(),
1518            NewValue::Str("hi there".into())
1519        );
1520        assert_eq!(
1521            parse_value("hex:0a0b").unwrap(),
1522            NewValue::Bytes(vec![10, 11])
1523        );
1524        assert_eq!(parse_value("hex:").unwrap(), NewValue::Bytes(vec![]));
1525        assert_eq!(
1526            parse_value("b64:CgM=").unwrap(),
1527            NewValue::Bytes(vec![10, 3])
1528        );
1529        for bad in ["", "hello", "\"unterminated", "hex:0g", "sint:x", "1.2.3x"] {
1530            assert_eq!(parse_value(bad).unwrap_err().code, "BAD_VALUE", "{bad}");
1531        }
1532    }
1533}