Skip to main content

hns_dns_relay_protocol/
lib.rs

1#![doc = "Wire-compatible, allocation-bounded messages for draft HIP #76."]
2
3use hns_encoding::{DecodeError, Decoder, Encoder};
4use thiserror::Error;
5
6/// Maximum DNS message body carried by a HIP-76 request.
7pub const MAX_DNS_RELAY_QUERY_BODY_SIZE: usize = 4 * 1024;
8/// Maximum DNS message body carried by a successful HIP-76 response.
9pub const MAX_DNS_RELAY_RESPONSE_BODY_SIZE: usize = u16::MAX as usize;
10/// Maximum complete `getdnsrelay` payload: request ID, body length, and body.
11pub const MAX_DNS_RELAY_REQUEST_PAYLOAD_SIZE: usize = 8 + 2 + MAX_DNS_RELAY_QUERY_BODY_SIZE;
12/// Maximum complete `dnsrelay` payload: request ID, status, body length, and body.
13pub const MAX_DNS_RELAY_RESPONSE_PAYLOAD_SIZE: usize = 8 + 1 + 2 + MAX_DNS_RELAY_RESPONSE_BODY_SIZE;
14
15/// Compatibility alias for the maximum HIP-76 query body size.
16pub const MAX_DNS_RELAY_QUERY_SIZE: usize = MAX_DNS_RELAY_QUERY_BODY_SIZE;
17/// Compatibility alias for the maximum HIP-76 response body size.
18pub const MAX_DNS_RELAY_RESPONSE_SIZE: usize = MAX_DNS_RELAY_RESPONSE_BODY_SIZE;
19
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21#[repr(u8)]
22pub enum DnsRelayStatus {
23    Ok = 0,
24    Refused = 1,
25    Unsupported = 2,
26    Busy = 3,
27    InvalidQuery = 4,
28    ResolverUnavailable = 5,
29    Timeout = 6,
30    InternalError = 7,
31}
32
33impl TryFrom<u8> for DnsRelayStatus {
34    type Error = DnsRelayProtocolError;
35
36    fn try_from(value: u8) -> Result<Self, Self::Error> {
37        match value {
38            0 => Ok(Self::Ok),
39            1 => Ok(Self::Refused),
40            2 => Ok(Self::Unsupported),
41            3 => Ok(Self::Busy),
42            4 => Ok(Self::InvalidQuery),
43            5 => Ok(Self::ResolverUnavailable),
44            6 => Ok(Self::Timeout),
45            7 => Ok(Self::InternalError),
46            _ => Err(DnsRelayProtocolError::UnknownStatus(value)),
47        }
48    }
49}
50
51#[derive(Clone, Debug, Eq, PartialEq)]
52pub struct GetDnsRelay {
53    pub request_id: u64,
54    pub query: Vec<u8>,
55}
56
57impl GetDnsRelay {
58    pub fn new(request_id: u64, query: Vec<u8>) -> Result<Self, DnsRelayProtocolError> {
59        let message = Self { request_id, query };
60        message.validate()?;
61        Ok(message)
62    }
63
64    pub fn encode(&self) -> Result<Vec<u8>, DnsRelayProtocolError> {
65        self.validate()?;
66        let mut encoder = Encoder::with_capacity(10 + self.query.len());
67        encoder.put_u64_le(self.request_id);
68        encoder.put_u16_le(
69            u16::try_from(self.query.len())
70                .map_err(|_| DnsRelayProtocolError::QueryTooLarge(self.query.len()))?,
71        );
72        encoder.put_bytes(&self.query);
73        Ok(encoder.into_bytes())
74    }
75
76    pub fn decode(input: &[u8]) -> Result<Self, DnsRelayProtocolError> {
77        let mut decoder = Decoder::new(input);
78        let request_id = decoder.read_u64_le()?;
79        if request_id == 0 {
80            return Err(DnsRelayProtocolError::ZeroRequestId);
81        }
82        let query_length = decoder.read_u16_le()? as usize;
83        if query_length > MAX_DNS_RELAY_QUERY_BODY_SIZE {
84            return Err(DnsRelayProtocolError::QueryTooLarge(query_length));
85        }
86        let query = decoder.read_bounded_vec(query_length, MAX_DNS_RELAY_QUERY_BODY_SIZE)?;
87        decoder.finish()?;
88        Self::new(request_id, query)
89    }
90
91    fn validate(&self) -> Result<(), DnsRelayProtocolError> {
92        if self.request_id == 0 {
93            return Err(DnsRelayProtocolError::ZeroRequestId);
94        }
95        if self.query.is_empty() {
96            return Err(DnsRelayProtocolError::EmptyQuery);
97        }
98        if self.query.len() > MAX_DNS_RELAY_QUERY_BODY_SIZE {
99            return Err(DnsRelayProtocolError::QueryTooLarge(self.query.len()));
100        }
101        Ok(())
102    }
103}
104
105#[derive(Clone, Debug, Eq, PartialEq)]
106pub struct DnsRelay {
107    pub request_id: u64,
108    pub status: DnsRelayStatus,
109    pub response: Vec<u8>,
110}
111
112impl DnsRelay {
113    pub fn new(
114        request_id: u64,
115        status: DnsRelayStatus,
116        response: Vec<u8>,
117    ) -> Result<Self, DnsRelayProtocolError> {
118        let message = Self {
119            request_id,
120            status,
121            response,
122        };
123        message.validate()?;
124        Ok(message)
125    }
126
127    pub fn encode(&self) -> Result<Vec<u8>, DnsRelayProtocolError> {
128        self.validate()?;
129        let mut encoder = Encoder::with_capacity(11 + self.response.len());
130        encoder.put_u64_le(self.request_id);
131        encoder.put_u8(self.status as u8);
132        encoder.put_u16_le(
133            u16::try_from(self.response.len())
134                .map_err(|_| DnsRelayProtocolError::ResponseTooLarge(self.response.len()))?,
135        );
136        encoder.put_bytes(&self.response);
137        Ok(encoder.into_bytes())
138    }
139
140    pub fn decode(input: &[u8]) -> Result<Self, DnsRelayProtocolError> {
141        let mut decoder = Decoder::new(input);
142        let request_id = decoder.read_u64_le()?;
143        if request_id == 0 {
144            return Err(DnsRelayProtocolError::ZeroRequestId);
145        }
146        let status = DnsRelayStatus::try_from(decoder.read_u8()?)?;
147        let response_length = decoder.read_u16_le()? as usize;
148        if response_length > MAX_DNS_RELAY_RESPONSE_BODY_SIZE {
149            return Err(DnsRelayProtocolError::ResponseTooLarge(response_length));
150        }
151        let response =
152            decoder.read_bounded_vec(response_length, MAX_DNS_RELAY_RESPONSE_BODY_SIZE)?;
153        decoder.finish()?;
154        Self::new(request_id, status, response)
155    }
156
157    fn validate(&self) -> Result<(), DnsRelayProtocolError> {
158        if self.request_id == 0 {
159            return Err(DnsRelayProtocolError::ZeroRequestId);
160        }
161        if self.response.len() > MAX_DNS_RELAY_RESPONSE_BODY_SIZE {
162            return Err(DnsRelayProtocolError::ResponseTooLarge(self.response.len()));
163        }
164        match (self.status, self.response.is_empty()) {
165            (DnsRelayStatus::Ok, true) => Err(DnsRelayProtocolError::EmptySuccess),
166            (DnsRelayStatus::Ok, false) | (_, true) => Ok(()),
167            (_, false) => Err(DnsRelayProtocolError::ErrorHasBody),
168        }
169    }
170}
171
172#[derive(Clone, Debug, Eq, Error, PartialEq)]
173pub enum DnsRelayProtocolError {
174    #[error(transparent)]
175    Decode(#[from] DecodeError),
176    #[error("request ID must be nonzero")]
177    ZeroRequestId,
178    #[error("DNS relay query must not be empty")]
179    EmptyQuery,
180    #[error("DNS relay query length {0} exceeds 4096 bytes")]
181    QueryTooLarge(usize),
182    #[error("DNS relay response length {0} exceeds 65535 bytes")]
183    ResponseTooLarge(usize),
184    #[error("unknown DNS relay status {0}")]
185    UnknownStatus(u8),
186    #[error("successful DNS relay response has no DNS message")]
187    EmptySuccess,
188    #[error("DNS relay error status has a response body")]
189    ErrorHasBody,
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    const REQUEST_BASIC: &str = "08070605040302012a00123401100001000000000001037777770972656c617974657374000001000100002904d0000080000000";
197    const RESPONSE_OK: &str = "0807060504030201003a00123481b00001000100000001037777770972656c6179746573740000010001c00c000100010000003c0004c000020100002904d0000080000000";
198    const RESPONSE_ERROR: &str = "0807060504030201030000";
199
200    #[test]
201    fn exact_draft_vectors_round_trip() {
202        let request_wire = hex::decode(REQUEST_BASIC).expect("hex");
203        let request = GetDnsRelay::decode(&request_wire).expect("valid");
204        assert_eq!(request.request_id, 0x0102_0304_0506_0708);
205        assert_eq!(request.encode().expect("valid"), request_wire);
206
207        let response_wire = hex::decode(RESPONSE_OK).expect("hex");
208        let response = DnsRelay::decode(&response_wire).expect("valid");
209        assert_eq!(response.status, DnsRelayStatus::Ok);
210        assert_eq!(response.encode().expect("valid"), response_wire);
211
212        let error_wire = hex::decode(RESPONSE_ERROR).expect("hex");
213        let response = DnsRelay::decode(&error_wire).expect("valid");
214        assert_eq!(response.status, DnsRelayStatus::Busy);
215        assert!(response.response.is_empty());
216        assert_eq!(response.encode().expect("valid"), error_wire);
217    }
218
219    #[test]
220    fn request_parser_rejects_zero_id_lengths_and_trailing_bytes() {
221        let zero_id = hex::decode("0000000000000000030000").expect("hex");
222        assert_eq!(
223            GetDnsRelay::decode(&zero_id),
224            Err(DnsRelayProtocolError::ZeroRequestId)
225        );
226
227        let malformed = hex::decode(
228            "08070605040302012b00123401100001000000000001037777770972656c617974657374000001000100002904d0000080000000",
229        )
230        .expect("hex");
231        assert!(matches!(
232            GetDnsRelay::decode(&malformed),
233            Err(DnsRelayProtocolError::Decode(
234                DecodeError::UnexpectedEnd { .. }
235            ))
236        ));
237
238        let trailing = hex::decode(
239            "08070605040302012a00123401100001000000000001037777770972656c617974657374000001000100002904d0000080000000ff",
240        )
241        .expect("hex");
242        assert!(matches!(
243            GetDnsRelay::decode(&trailing),
244            Err(DnsRelayProtocolError::Decode(
245                DecodeError::TrailingBytes { .. }
246            ))
247        ));
248    }
249
250    #[test]
251    fn response_parser_rejects_unknown_status_and_body_mismatch() {
252        let unknown = hex::decode("0807060504030201ff0000").expect("hex");
253        assert_eq!(
254            DnsRelay::decode(&unknown),
255            Err(DnsRelayProtocolError::UnknownStatus(0xff))
256        );
257        assert_eq!(
258            DnsRelay::new(1, DnsRelayStatus::Ok, Vec::new()),
259            Err(DnsRelayProtocolError::EmptySuccess)
260        );
261        assert_eq!(
262            DnsRelay::new(1, DnsRelayStatus::Busy, vec![1]),
263            Err(DnsRelayProtocolError::ErrorHasBody)
264        );
265    }
266
267    #[test]
268    fn allocation_bounds_are_enforced_at_both_limits() {
269        let request =
270            GetDnsRelay::new(1, vec![0; MAX_DNS_RELAY_QUERY_BODY_SIZE]).expect("maximum request");
271        assert_eq!(
272            request.encode().expect("valid").len(),
273            MAX_DNS_RELAY_REQUEST_PAYLOAD_SIZE
274        );
275        assert_eq!(MAX_DNS_RELAY_REQUEST_PAYLOAD_SIZE, 4_106);
276        assert_eq!(
277            GetDnsRelay::new(1, vec![0; MAX_DNS_RELAY_QUERY_BODY_SIZE + 1]),
278            Err(DnsRelayProtocolError::QueryTooLarge(
279                MAX_DNS_RELAY_QUERY_BODY_SIZE + 1
280            ))
281        );
282
283        let response = DnsRelay::new(
284            1,
285            DnsRelayStatus::Ok,
286            vec![0; MAX_DNS_RELAY_RESPONSE_BODY_SIZE],
287        )
288        .expect("maximum response");
289        assert_eq!(
290            response.encode().expect("valid").len(),
291            MAX_DNS_RELAY_RESPONSE_PAYLOAD_SIZE
292        );
293        assert_eq!(MAX_DNS_RELAY_RESPONSE_PAYLOAD_SIZE, 65_546);
294        assert_eq!(MAX_DNS_RELAY_QUERY_SIZE, MAX_DNS_RELAY_QUERY_BODY_SIZE);
295        assert_eq!(
296            MAX_DNS_RELAY_RESPONSE_SIZE,
297            MAX_DNS_RELAY_RESPONSE_BODY_SIZE
298        );
299    }
300}