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