iroh_dns_server/
util.rs

1use core::fmt;
2use std::{
3    collections::{BTreeMap, btree_map},
4    str::FromStr,
5    sync::Arc,
6};
7
8use hickory_server::proto::{
9    ProtoError,
10    op::Message,
11    rr::{
12        Name, Record, RecordSet, RecordType, RrKey,
13        domain::{IntoLabel, Label},
14    },
15    serialize::binary::BinDecodable,
16};
17use iroh_base::PublicKey;
18use iroh_dns::pkarr::SignedPacket;
19use n0_error::{e, stack_error};
20
21/// A lightweight `[u8; 32]` wrapper used as a key for caches and database lookups.
22///
23/// Does not validate that the bytes are a valid public key on construction.
24/// If constructed from invalid bytes, methods like `Display` and `to_z32`
25/// will panic. In practice, bytes always originate from a validated `PublicKey`
26/// or a database that was written from one.
27#[derive(derive_more::Into, Eq, PartialEq, Ord, PartialOrd, Hash, Clone, Copy)]
28pub(crate) struct PublicKeyBytes([u8; 32]);
29
30#[stack_error(derive, add_meta, from_sources)]
31pub(crate) enum InvalidPublicKeyBytes {
32    #[error("invalid z-base-32 encoding")]
33    InvalidEncoding,
34    #[error("invalid length, must be 32 bytes")]
35    InvalidLength,
36}
37
38impl PublicKeyBytes {
39    /// Wraps raw bytes without validating they are a valid public key.
40    ///
41    /// # Safety (logical)
42    ///
43    /// The caller must ensure the bytes represent a valid Ed25519 public key.
44    /// Passing invalid bytes will cause panics in `Display`, `Debug`, and `to_z32`.
45    pub(crate) fn new_unchecked(bytes: [u8; 32]) -> Self {
46        Self(bytes)
47    }
48
49    pub(crate) fn from_z32(s: &str) -> Result<Self, InvalidPublicKeyBytes> {
50        let pk = PublicKey::from_z32(s).map_err(|_| e!(InvalidPublicKeyBytes::InvalidEncoding))?;
51        Ok(Self(*pk.as_bytes()))
52    }
53
54    pub(crate) fn to_z32(self) -> String {
55        PublicKey::from_bytes(&self.0).expect("valid key").to_z32()
56    }
57
58    pub(crate) fn as_bytes(&self) -> &[u8; 32] {
59        &self.0
60    }
61
62    pub(crate) fn from_signed_packet(packet: &SignedPacket) -> Self {
63        Self(*packet.public_key().as_bytes())
64    }
65}
66
67impl fmt::Display for PublicKeyBytes {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        write!(f, "{}", self.to_z32())
70    }
71}
72
73impl fmt::Debug for PublicKeyBytes {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        write!(f, "PublicKeyBytes({})", self.to_z32())
76    }
77}
78
79impl FromStr for PublicKeyBytes {
80    type Err = InvalidPublicKeyBytes;
81
82    fn from_str(s: &str) -> Result<Self, Self::Err> {
83        Self::from_z32(s)
84    }
85}
86
87impl AsRef<[u8; 32]> for PublicKeyBytes {
88    fn as_ref(&self) -> &[u8; 32] {
89        &self.0
90    }
91}
92
93pub(crate) fn signed_packet_to_hickory_message(
94    signed_packet: &SignedPacket,
95) -> Result<Message, ProtoError> {
96    let encoded = signed_packet.encoded_packet();
97    let message = Message::from_bytes(encoded)?;
98    Ok(message)
99}
100
101pub(crate) fn signed_packet_to_hickory_records_without_origin(
102    signed_packet: &SignedPacket,
103    filter: impl Fn(&Record) -> bool,
104) -> Result<(Label, BTreeMap<RrKey, Arc<RecordSet>>), ProtoError> {
105    let common_zone = Label::from_utf8(&signed_packet.public_key().to_z32())?;
106    let mut message = signed_packet_to_hickory_message(signed_packet)?;
107    let answers = std::mem::take(&mut message.answers);
108    let mut output: BTreeMap<RrKey, Arc<RecordSet>> = BTreeMap::new();
109    for mut record in answers.into_iter() {
110        // disallow SOA and NS records
111        if matches!(record.record_type(), RecordType::SOA | RecordType::NS) {
112            continue;
113        }
114        // expect the z32 encoded pubkey as root name
115        let name = &record.name;
116        if name.num_labels() < 1 {
117            continue;
118        }
119        let zone = name.iter().next_back().unwrap().into_label()?;
120        if zone != common_zone {
121            continue;
122        }
123        if !filter(&record) {
124            continue;
125        }
126
127        let name_without_zone =
128            Name::from_labels(name.iter().take(name.num_labels() as usize - 1))?;
129        record.name = name_without_zone;
130
131        let rrkey = RrKey::new(record.name.clone().into(), record.record_type());
132        match output.entry(rrkey) {
133            btree_map::Entry::Vacant(e) => {
134                let set: RecordSet = record.into();
135                e.insert(Arc::new(set));
136            }
137            btree_map::Entry::Occupied(mut e) => {
138                let set = e.get_mut();
139                let serial = set.serial();
140                // safe because we just created the arc and are sync iterating
141                Arc::get_mut(set).unwrap().insert(record, serial);
142            }
143        }
144    }
145    Ok((common_zone, output))
146}
147
148pub(crate) fn record_set_append_origin(
149    input: &RecordSet,
150    origin: &Name,
151    serial: u32,
152) -> Result<RecordSet, ProtoError> {
153    let new_name = input.name().clone().append_name(origin)?;
154    let mut output = RecordSet::new(new_name.clone(), input.record_type(), serial);
155    // TODO: less clones
156    for record in input.records_without_rrsigs() {
157        let mut record = record.clone();
158        record.name = new_name.clone();
159        output.insert(record, serial);
160    }
161    Ok(output)
162}