rama-net 0.3.0

rama network types and utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! [`DomainBuilder`] — incrementally construct a [`Domain`] from labels,
//! enforcing per-label and total-length invariants at push time.

use core::fmt;

use super::label::validate_label_bytes;
use super::{Domain, DomainLabels, Label, LabelError, MAX_NAME_LEN};

use rama_core::bytes::BytesMut;

/// Builder for a [`Domain`].
///
/// Labels are pushed in DNS-natural order: leftmost (most specific) first,
/// rightmost (TLD) last. The builder maintains the [`Domain`] invariant
/// after every successful push.
///
/// Backed by [`BytesMut`], producing a [`Bytes`](rama_core::bytes::Bytes)-backed
/// [`Domain`] on [`finish`](Self::finish).
///
/// # Example
///
/// ```
/// use rama_net::address::domain::DomainBuilder;
///
/// let mut b = DomainBuilder::new();
/// b.push_label("www").unwrap();
/// b.push_label("example").unwrap();
/// b.push_label("com").unwrap();
/// let d = b.finish().unwrap();
/// assert_eq!(d.as_str(), "www.example.com");
/// ```
#[derive(Debug, Default)]
pub struct DomainBuilder {
    buf: BytesMut,
    label_count: usize,
    starts_with_wildcard: bool,
}

impl DomainBuilder {
    /// Creates an empty builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the number of labels currently in the builder.
    #[must_use]
    pub fn label_count(&self) -> usize {
        self.label_count
    }

    /// Returns `true` if no labels have been pushed yet.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.buf.is_empty()
    }

    /// Returns the current length in bytes (including separating dots).
    #[must_use]
    pub fn len(&self) -> usize {
        self.buf.len()
    }

    /// Push a single label.
    ///
    /// `label` must satisfy [`Label`]'s invariants. The total name length
    /// after the push (including the joining dot) must not exceed
    /// `MAX_NAME_LEN` (253).
    ///
    /// # Errors
    ///
    /// Returns [`PushError`] if the label or resulting name length is invalid.
    pub fn push_label(&mut self, label: &str) -> Result<&mut Self, PushError> {
        validate_label_bytes(label.as_bytes()).map_err(PushError::from_label)?;
        self.push_validated_label(label)
    }

    /// Push an already-validated [`Label`] reference.
    ///
    /// Still enforces the total name length cap.
    ///
    /// # Errors
    ///
    /// Returns a too-long [`PushError`] if the resulting name length would
    /// exceed `MAX_NAME_LEN`.
    pub fn push(&mut self, label: &Label) -> Result<&mut Self, PushError> {
        self.push_validated_label(label.as_str())
    }

    fn push_validated_label(&mut self, label: &str) -> Result<&mut Self, PushError> {
        // Wildcard `*` is only valid as the leftmost label. The label-level
        // validator accepts `"*"` standalone, so the positional rule lives
        // here in the builder.
        let is_wildcard = label == "*";
        if is_wildcard && !self.is_empty() {
            return Err(PushError::misplaced_wildcard());
        }

        let added = if self.is_empty() {
            label.len()
        } else {
            label.len() + 1
        };
        let new_len = self.buf.len() + added;
        if new_len > MAX_NAME_LEN {
            return Err(PushError::too_long(new_len));
        }
        if !self.is_empty() {
            self.buf.extend_from_slice(b".");
        } else {
            self.starts_with_wildcard = is_wildcard;
        }
        self.buf.extend_from_slice(label.as_bytes());
        self.label_count += 1;
        Ok(self)
    }

    /// Push every label from `it` in iteration order.
    ///
    /// # Errors
    ///
    /// Returns the first [`PushError`] encountered. On error, the builder
    /// retains the labels that pushed successfully — the caller may still
    /// inspect or discard it.
    pub fn push_labels<'a, I: IntoIterator<Item = &'a Label>>(
        &mut self,
        it: I,
    ) -> Result<&mut Self, PushError> {
        for l in it {
            self.push(l)?;
        }
        Ok(self)
    }

    /// Append every label from another label-aware value (e.g. a [`Domain`]
    /// or [`Host`](super::super::Host)).
    ///
    /// # Errors
    ///
    /// Returns the first [`PushError`] encountered.
    pub fn append<D: DomainLabels + ?Sized>(&mut self, other: &D) -> Result<&mut Self, PushError> {
        self.push_labels(other.labels())
    }

    /// Parse `dotted` as a sequence of labels separated by `.`, ignoring
    /// empty segments (i.e. leading and trailing FQDN dots are accepted).
    ///
    /// # Errors
    ///
    /// Returns [`PushError`] on the first invalid label or length overflow.
    pub fn push_label_segments(&mut self, dotted: &str) -> Result<&mut Self, PushError> {
        for part in dotted.split('.') {
            if part.is_empty() {
                continue;
            }
            self.push_label(part)?;
        }
        Ok(self)
    }

    /// Consume the builder and produce a [`Domain`].
    ///
    /// # Errors
    ///
    /// Returns a [`PushError`] if the builder is empty, or if the only pushed
    /// label is the bare wildcard `"*"` (which is never a valid standalone
    /// domain).
    pub fn finish(self) -> Result<Domain, PushError> {
        if self.label_count == 0 {
            return Err(PushError::empty());
        }
        if self.label_count == 1 && self.starts_with_wildcard {
            return Err(PushError::misplaced_wildcard());
        }
        // Safety: builder maintained the Domain invariant at every push.
        Ok(unsafe { Domain::from_maybe_borrowed_unchecked(self.buf.freeze()) })
    }
}

/// Error returned by [`DomainBuilder`] when a push would violate the
/// [`Domain`] invariant.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PushError(PushErrorKind);

#[derive(Debug, Clone, PartialEq, Eq)]
enum PushErrorKind {
    Empty,
    Label(LabelError),
    TooLong { len: usize },
    MisplacedWildcard,
}

impl PushError {
    #[inline]
    fn empty() -> Self {
        Self(PushErrorKind::Empty)
    }
    #[inline]
    fn from_label(e: LabelError) -> Self {
        Self(PushErrorKind::Label(e))
    }
    #[inline]
    fn too_long(len: usize) -> Self {
        Self(PushErrorKind::TooLong { len })
    }
    #[inline]
    fn misplaced_wildcard() -> Self {
        Self(PushErrorKind::MisplacedWildcard)
    }

    /// Returns the underlying [`LabelError`] if this is a label-validation
    /// failure.
    #[must_use]
    pub fn as_label_error(&self) -> Option<&LabelError> {
        match &self.0 {
            PushErrorKind::Label(e) => Some(e),
            _ => None,
        }
    }
}

impl fmt::Display for PushError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.0 {
            PushErrorKind::Empty => f.write_str("no labels pushed to domain builder"),
            PushErrorKind::Label(e) => write!(f, "invalid label: {e}"),
            PushErrorKind::TooLong { len } => write!(
                f,
                "domain name would be {len} bytes long, max is {MAX_NAME_LEN}"
            ),
            PushErrorKind::MisplacedWildcard => f.write_str(
                "wildcard label '*' is only valid as the leftmost label and never alone",
            ),
        }
    }
}

impl core::error::Error for PushError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match &self.0 {
            PushErrorKind::Label(e) => Some(e),
            _ => None,
        }
    }
}

impl From<LabelError> for PushError {
    fn from(e: LabelError) -> Self {
        Self::from_label(e)
    }
}

#[cfg(test)]
mod tests {
    use super::super::Domain;
    use super::*;

    #[test]
    fn build_single_label() {
        let mut b = DomainBuilder::new();
        b.push_label("com").unwrap();
        assert_eq!(b.label_count(), 1);
        let d = b.finish().unwrap();
        assert_eq!(d.as_str(), "com");
    }

    #[test]
    fn build_multi_label() {
        let mut b = DomainBuilder::new();
        b.push_label("www").unwrap();
        b.push_label("example").unwrap();
        b.push_label("com").unwrap();
        assert_eq!(b.label_count(), 3);
        let d = b.finish().unwrap();
        assert_eq!(d.as_str(), "www.example.com");
    }

    #[test]
    fn build_wildcard() {
        let mut b = DomainBuilder::new();
        b.push_label("*").unwrap();
        b.push_label("example").unwrap();
        b.push_label("com").unwrap();
        let d = b.finish().unwrap();
        assert_eq!(d.as_str(), "*.example.com");
        assert!(d.is_wildcard());
    }

    #[test]
    fn append_domain() {
        let parent = Domain::from_static("example.com");
        let mut b = DomainBuilder::new();
        b.push_label("www").unwrap();
        b.append(&parent).unwrap();
        assert_eq!(b.finish().unwrap().as_str(), "www.example.com");
    }

    #[test]
    fn push_label_segments_handles_dots() {
        let mut b = DomainBuilder::new();
        b.push_label_segments("a.b.c").unwrap();
        assert_eq!(b.finish().unwrap().as_str(), "a.b.c");

        // leading/trailing/duplicate dots are squashed (split + filter empty)
        let mut b = DomainBuilder::new();
        b.push_label_segments(".a.b.").unwrap();
        assert_eq!(b.finish().unwrap().as_str(), "a.b");
    }

    #[test]
    fn rejects_invalid_label() {
        let mut b = DomainBuilder::new();
        let err = b.push_label("-bad").unwrap_err();
        assert!(err.as_label_error().is_some());
        assert!(b.is_empty(), "builder is unchanged after failed push");
    }

    #[test]
    fn rejects_total_length_overflow() {
        // 63 + 1 + 63 + 1 + 63 + 1 + 63 = 255 > 253. Three 63-byte labels fit
        // (191), a fourth doesn't.
        let label63 = "a".repeat(63);
        let mut b = DomainBuilder::new();
        b.push_label(&label63).unwrap();
        b.push_label(&label63).unwrap();
        b.push_label(&label63).unwrap();
        let err = b.push_label(&label63).unwrap_err();
        assert!(format!("{err}").contains("max is 253"));
    }

    #[test]
    fn finish_empty_returns_err() {
        let b = DomainBuilder::new();
        let err = b.finish().unwrap_err();
        assert!(format!("{err}").contains("no labels"));
    }

    #[test]
    fn push_already_validated_label() {
        let l = Label::from_str("example").unwrap();
        let mut b = DomainBuilder::new();
        b.push(l).unwrap();
        b.push_label("com").unwrap();
        assert_eq!(b.finish().unwrap().as_str(), "example.com");
    }

    #[test]
    fn rejects_wildcard_at_non_leftmost_position() {
        // Pushed after a regular label.
        let mut b = DomainBuilder::new();
        b.push_label("example").unwrap();
        let err = b.push_label("*").unwrap_err();
        assert!(
            format!("{err}").contains("wildcard"),
            "expected wildcard mention, got: {err}"
        );

        // Pushed via push_label_segments.
        let mut b = DomainBuilder::new();
        let err = b.push_label_segments("x.*.com").unwrap_err();
        assert!(format!("{err}").contains("wildcard"), "got: {err}");

        // Pushed via append (Domain whose first label is `*`).
        let parent = Domain::from_static("*.example.com");
        let mut b = DomainBuilder::new();
        b.push_label("foo").unwrap();
        let err = b.append(&parent).unwrap_err();
        assert!(format!("{err}").contains("wildcard"), "got: {err}");
    }

    #[test]
    fn accepts_wildcard_as_leftmost_label() {
        let mut b = DomainBuilder::new();
        b.push_label("*").unwrap();
        b.push_label("example").unwrap();
        b.push_label("com").unwrap();
        let d = b.finish().unwrap();
        assert_eq!(d.as_str(), "*.example.com");
        // And the output reparses (no broken invariant).
        Domain::try_from(d.as_str().to_owned()).expect("builder output reparses");
    }

    #[test]
    fn rejects_bare_wildcard_on_finish() {
        let mut b = DomainBuilder::new();
        b.push_label("*").unwrap();
        // Only one label, and it's `*` — not a valid domain on its own.
        let err = b.finish().unwrap_err();
        assert!(format!("{err}").contains("wildcard"), "got: {err}");
    }

    #[test]
    fn build_matches_validating_parser() {
        // The buffer the builder produces is parseable as a Domain — i.e. the
        // builder's invariant matches the parser's.
        let mut b = DomainBuilder::new();
        b.push_label("a").unwrap();
        b.push_label("_acme-challenge").unwrap();
        b.push_label("example").unwrap();
        b.push_label("com").unwrap();
        let s = b.finish().unwrap().as_str().to_owned();
        Domain::try_from(s).expect("builder output must reparse");
    }
}