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
use std::fmt::{Display, Write};

use schemars::JsonSchema;
use serde::{de::Error, Deserialize, Serialize};
use thiserror::Error;

use crate::{segment::DomainSegment, FullyQualifiedDomainName};

#[derive(Error, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum PatternError {}

#[derive(Default, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Pattern(Vec<PatternSegment>);

impl Pattern {
    /// Returns a pattern that only matches the origin of the parent
    /// FQDN.
    pub fn origin() -> Self {
        Pattern::default()
    }

    /// Iterates over the [`PatternSegment`]s of the pattern.
    pub fn iter(&self) -> impl Iterator<Item = &PatternSegment> + '_ {
        self.0.iter()
    }

    /// Returns a new pattern with the origin appended.
    pub fn with_origin(&self, origin: &FullyQualifiedDomainName) -> Pattern {
        let mut cloned = self.clone();
        cloned.0.extend(origin.iter().map(PatternSegment::from));
        cloned
    }

    /// Returns true if the papttern matches the given domain.
    pub fn matches(&self, domain: &FullyQualifiedDomainName) -> bool {
        let domain_segments = domain.as_ref().iter().rev();
        let pattern_segments = self.0[..].iter().rev();

        if domain_segments.len() < pattern_segments.len() {
            // Patterns longer than the domain segment cannot possibly match.
            return false;
        }

        if domain_segments.len() > pattern_segments.len()
            // Domains longer than patterns can never match, unless the first
            // segment of the pattern is a standalone wildcard (*)
            && !self.0.first().is_some_and(|pattern| pattern.as_ref() == "*")
        {
            return false;
        }

        for (pattern, domain) in pattern_segments.zip(domain_segments) {
            // If we have hit a pattern segment containing only a wildcard, the rest of the
            // domain segments are automatically matched.
            if pattern.as_ref() == "*" {
                return true;
            }

            if !pattern.matches(domain) {
                return false;
            }
        }

        true
    }
}

impl FromIterator<PatternSegment> for Pattern {
    fn from_iter<T: IntoIterator<Item = PatternSegment>>(iter: T) -> Self {
        Pattern(iter.into_iter().collect())
    }
}

impl TryFrom<&str> for Pattern {
    type Error = PatternSegmentError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let segments = Result::from_iter(
            value
                .trim_end_matches('.')
                .split('.')
                .map(PatternSegment::try_from),
        )?;
        Ok(Pattern(segments))
    }
}

impl TryFrom<String> for Pattern {
    type Error = PatternSegmentError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::try_from(value.as_ref())
    }
}

impl Display for Pattern {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for segment in &self.0 {
            write!(f, "{}", segment)?;
            f.write_char('.')?;
        }

        Ok(())
    }
}

impl JsonSchema for Pattern {
    fn schema_name() -> String {
        <String as schemars::JsonSchema>::schema_name()
    }

    fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
        <String as schemars::JsonSchema>::json_schema(gen)
    }
}

impl<'de> Deserialize<'de> for Pattern {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;

        Self::try_from(value).map_err(D::Error::custom)
    }
}

impl Serialize for Pattern {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.to_string().serialize(serializer)
    }
}

/// Segment of a pattern.
///
/// Used for matching against a single [`DomainSegment`].
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PatternSegment(String);

impl PatternSegment {
    /// Returns true if the pattern segment matches the provided domain segment.
    pub fn matches(&self, domain_segment: &DomainSegment) -> bool {
        if self.0 == domain_segment.as_ref() {
            return true;
        }

        if let Some((head, tail)) = self.0.split_once('*') {
            return domain_segment.as_ref().starts_with(head)
                && domain_segment.as_ref().ends_with(tail);
        }

        false
    }

    // Segments cannot be empty.
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        self.0.len()
    }
}

/// Produced when attempting to construct a [`PatternSegment`]
/// from an invalid string.
#[derive(Error, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum PatternSegmentError {
    /// Domain name segments (and therefore pattern segments)
    /// can contain hyphens, but crucially:
    ///
    /// * Not at the beginning of a segment.
    /// * Not at the end of a segment.
    /// * Not at the 3rd and 4th position *simultaneously* (used for [Punycode encoding](https://en.wikipedia.org/wiki/Punycode))
    #[error("illegal hyphen at position {0}")]
    IllegalHyphen(usize),
    /// Segment contains invalid character.
    #[error("invalid character {0}")]
    InvalidCharacter(char),
    /// Domain segment is longer than the permitted 63 characters.
    #[error("pattern too long {0} > 63")]
    TooLong(usize),
    /// Domain segment is empty.
    #[error("pattern is an empty string")]
    EmptyString,
    /// Pattern contains more than one wildcard (*) character.
    #[error("patterns can only have one wildcard")]
    MultipleWildcards,
}

const VALID_CHARACTERS: &str = "_-0123456789abcdefghijklmnopqrstuvwxyz*";

impl TryFrom<&str> for PatternSegment {
    type Error = PatternSegmentError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let value = value.to_ascii_lowercase();

        if value.is_empty() {
            return Err(PatternSegmentError::EmptyString);
        }

        if value.len() > 63 {
            return Err(PatternSegmentError::TooLong(value.len()));
        }

        if let Some(character) = value.chars().find(|c| !VALID_CHARACTERS.contains(*c)) {
            return Err(PatternSegmentError::InvalidCharacter(character));
        }

        if value.starts_with('-') {
            return Err(PatternSegmentError::IllegalHyphen(1));
        }

        if value.ends_with('-') {
            return Err(PatternSegmentError::IllegalHyphen(value.len()));
        }

        if value.get(2..4) == Some("--") {
            return Err(PatternSegmentError::IllegalHyphen(3));
        }

        if value.chars().filter(|c| *c == '*').count() > 1 {
            return Err(PatternSegmentError::MultipleWildcards);
        }

        Ok(PatternSegment(value))
    }
}

impl From<DomainSegment> for PatternSegment {
    fn from(value: DomainSegment) -> Self {
        PatternSegment(value.to_string())
    }
}

impl From<&DomainSegment> for PatternSegment {
    fn from(value: &DomainSegment) -> Self {
        PatternSegment(value.to_string())
    }
}

impl TryFrom<String> for PatternSegment {
    type Error = PatternSegmentError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::try_from(value.as_str())
    }
}

impl Display for PatternSegment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for PatternSegment {
    fn as_ref(&self) -> &str {
        self.0.as_str()
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        error::PatternSegmentError, pattern::PatternSegment, segment::DomainSegment,
        FullyQualifiedDomainName, Pattern,
    };

    #[test]
    fn literal_matches() {
        assert!(PatternSegment::try_from("example")
            .unwrap()
            .matches(&DomainSegment::try_from("example").unwrap()))
    }

    #[test]
    fn wildcard() {
        assert!(PatternSegment::try_from("*")
            .unwrap()
            .matches(&DomainSegment::try_from("example").unwrap()))
    }

    #[test]
    fn leading_wildcard() {
        assert!(PatternSegment::try_from("*ample")
            .unwrap()
            .matches(&DomainSegment::try_from("example").unwrap()))
    }

    #[test]
    fn trailing_wildcard() {
        assert!(PatternSegment::try_from("examp*")
            .unwrap()
            .matches(&DomainSegment::try_from("example").unwrap()))
    }

    #[test]
    fn splitting_wildcard() {
        assert!(PatternSegment::try_from("ex*le")
            .unwrap()
            .matches(&DomainSegment::try_from("example").unwrap()))
    }

    #[test]
    fn multiple_wildcards() {
        assert_eq!(
            PatternSegment::try_from("*amp*"),
            Err(PatternSegmentError::MultipleWildcards)
        );
    }

    #[test]
    fn simple_pattern_match() {
        assert!(Pattern::try_from("*.example.org")
            .unwrap()
            .matches(&FullyQualifiedDomainName::try_from("www.example.org.").unwrap()));
    }

    #[test]
    fn longer_pattern_than_domain() {
        assert!(!Pattern::try_from("*.*.example.org")
            .unwrap()
            .matches(&FullyQualifiedDomainName::try_from("www.example.org.").unwrap()));
    }

    #[test]
    fn longer_domain_than_pattern() {
        assert!(Pattern::try_from("*.example.org").unwrap().matches(
            &FullyQualifiedDomainName::try_from("www.sub.test.dev.example.org.").unwrap()
        ));
    }

    #[test]
    fn wildcard_segments() {
        let pattern = Pattern::try_from("dev*.example.org").unwrap();

        assert!(pattern.matches(&FullyQualifiedDomainName::try_from("dev.example.org.").unwrap()));
        assert!(pattern.matches(&FullyQualifiedDomainName::try_from("dev-1.example.org.").unwrap()));
        assert!(
            pattern.matches(&FullyQualifiedDomainName::try_from("dev-hello.example.org.").unwrap())
        );
        assert!(!pattern.matches(&FullyQualifiedDomainName::try_from("de.example.org.").unwrap()));
        assert!(!pattern
            .matches(&FullyQualifiedDomainName::try_from("www.dev-1.example.org.").unwrap()));
    }

    #[test]
    fn patterns_assumed_wildcard() {
        let fqdn = Pattern::try_from("example.org.").unwrap();
        let pqdn = Pattern::try_from("example.org").unwrap();
        assert_eq!(fqdn, pqdn);

        assert_eq!(
            fqdn.matches(&FullyQualifiedDomainName::try_from("example.org.").unwrap()),
            pqdn.matches(&FullyQualifiedDomainName::try_from("example.org.").unwrap())
        );
    }

    #[test]
    fn origin_insertion() {
        let pattern = Pattern::try_from("example").unwrap();

        let domain = FullyQualifiedDomainName::try_from("example.org.").unwrap();

        assert!(!pattern.matches(&domain));

        assert!(pattern
            .with_origin(&FullyQualifiedDomainName::try_from("org.").unwrap())
            .matches(&FullyQualifiedDomainName::try_from("example.org.").unwrap()));
    }
}