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
405
use std;

use cookie::Cookie as RawCookie;
use idna;
use publicsuffix::{List, Psl, Suffix};
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use url::{Host, Url};

use crate::utils::is_host_name;
use crate::CookieError;

pub fn is_match(domain: &str, request_url: &Url) -> bool {
    CookieDomain::try_from(domain)
        .map(|domain| domain.matches(request_url))
        .unwrap_or(false)
}

/// The domain of a `Cookie`
#[derive(PartialEq, Eq, Clone, Debug, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum CookieDomain {
    /// No Domain attribute in Set-Cookie header
    HostOnly(String),
    /// Domain attribute from Set-Cookie header
    Suffix(String),
    /// Domain attribute was not present in the Set-Cookie header
    NotPresent,
    /// Domain attribute-value was empty; technically undefined behavior, but suggested that this
    /// be treated as invalid
    Empty,
}

// 5.1.3.  Domain Matching
// A string domain-matches a given domain string if at least one of the
// following conditions hold:
//
// o  The domain string and the string are identical.  (Note that both
//    the domain string and the string will have been canonicalized to
//    lower case at this point.)
//
// o  All of the following conditions hold:
//
//    *  The domain string is a suffix of the string.
//
//    *  The last character of the string that is not included in the
//       domain string is a %x2E (".") character.
//
//    *  The string is a host name (i.e., not an IP address).
/// The concept of a domain match per [IETF RFC6265 Section
/// 5.1.3](https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3)
impl CookieDomain {
    /// Get the CookieDomain::HostOnly variant based on `request_url`. This is the effective behavior of
    /// setting the domain-attribute to empty
    pub fn host_only(request_url: &Url) -> Result<CookieDomain, CookieError> {
        request_url
            .host()
            .ok_or(CookieError::NonRelativeScheme)
            .map(|h| match h {
                Host::Domain(d) => CookieDomain::HostOnly(d.into()),
                Host::Ipv4(addr) => CookieDomain::HostOnly(format!("{}", addr)),
                Host::Ipv6(addr) => CookieDomain::HostOnly(format!("[{}]", addr)),
            })
    }

    /// Tests if the given `url::Url` meets the domain-match criteria
    pub fn matches(&self, request_url: &Url) -> bool {
        if let Some(url_host) = request_url.host_str() {
            match *self {
                CookieDomain::HostOnly(ref host) => host == url_host,
                CookieDomain::Suffix(ref suffix) => {
                    suffix == url_host
                        || (is_host_name(url_host)
                            && url_host.ends_with(suffix)
                            && url_host[(url_host.len() - suffix.len() - 1)..].starts_with('.'))
                }
                CookieDomain::NotPresent | CookieDomain::Empty => false, // nothing can match the Empty case
            }
        } else {
            false // not a matchable scheme
        }
    }

    /// Tests if the given `url::Url` has a request-host identical to the domain attribute
    pub fn host_is_identical(&self, request_url: &Url) -> bool {
        if let Some(url_host) = request_url.host_str() {
            match *self {
                CookieDomain::HostOnly(ref host) => host == url_host,
                CookieDomain::Suffix(ref suffix) => suffix == url_host,
                CookieDomain::NotPresent | CookieDomain::Empty => false, // nothing can match the Empty case
            }
        } else {
            false // not a matchable scheme
        }
    }

    /// Tests if the domain-attribute is a public suffix as indicated by the provided
    /// `publicsuffix::List`.
    pub fn is_public_suffix(&self, psl: &List) -> bool {
        if let Some(domain) = self.as_cow().as_ref().map(|d| d.as_bytes()) {
            psl.suffix(domain)
                // Only consider suffixes explicitly listed in the public suffix list
                // to avoid issues like https://github.com/curl/curl/issues/658
                .filter(Suffix::is_known)
                .filter(|suffix| suffix == &domain)
                .is_some()
        } else {
            false
        }
    }

    /// Get a borrowed string representation of the domain. For `Empty` and `NotPresent` variants,
    /// `None` shall be returned;
    pub fn as_cow(&self) -> Option<std::borrow::Cow<'_, str>> {
        match *self {
            CookieDomain::HostOnly(ref s) | CookieDomain::Suffix(ref s) => {
                Some(std::borrow::Cow::Borrowed(s))
            }
            CookieDomain::Empty | CookieDomain::NotPresent => None,
        }
    }
}

/// Construct a `CookieDomain::Suffix` from a string, stripping a single leading '.' if present.
/// If the source string is empty, returns the `CookieDomain::Empty` variant.
impl<'a> TryFrom<&'a str> for CookieDomain {
    type Error = crate::Error;
    fn try_from(value: &str) -> Result<CookieDomain, Self::Error> {
        idna::domain_to_ascii(value.trim())
            .map_err(super::IdnaErrors::from)
            .map_err(Into::into)
            .map(|domain| {
                if domain.is_empty() || "." == domain {
                    CookieDomain::Empty
                } else if domain.starts_with('.') {
                    CookieDomain::Suffix(String::from(&domain[1..]))
                } else {
                    CookieDomain::Suffix(domain)
                }
            })
    }
}

/// Construct a `CookieDomain::Suffix` from a `cookie::Cookie`, which handles stripping a leading
/// '.' for us. If the cookie.domain is None or an empty string, the `CookieDomain::Empty` variant
/// is returned.
/// __NOTE__: `cookie::Cookie` domain values already have the leading '.' stripped. To avoid
/// performing this step twice, the `From<&cookie::Cookie>` impl should be used,
/// instead of passing `cookie.domain` to the `From<&str>` impl.
impl<'a, 'c> TryFrom<&'a RawCookie<'c>> for CookieDomain {
    type Error = crate::Error;
    fn try_from(cookie: &'a RawCookie<'c>) -> Result<CookieDomain, Self::Error> {
        if let Some(domain) = cookie.domain() {
            idna::domain_to_ascii(domain.trim())
                .map_err(super::IdnaErrors::from)
                .map_err(Into::into)
                .map(|domain| {
                    if domain.is_empty() {
                        CookieDomain::Empty
                    } else {
                        CookieDomain::Suffix(domain)
                    }
                })
        } else {
            Ok(CookieDomain::NotPresent)
        }
    }
}

impl<'a> From<&'a CookieDomain> for String {
    fn from(c: &'a CookieDomain) -> String {
        match *c {
            CookieDomain::HostOnly(ref h) => h.to_owned(),
            CookieDomain::Suffix(ref s) => s.to_owned(),
            CookieDomain::Empty | CookieDomain::NotPresent => "".to_owned(),
        }
    }
}

#[cfg(test)]
mod tests {
    use cookie::Cookie as RawCookie;
    use std::convert::TryFrom;
    use url::Url;

    use super::CookieDomain;
    use crate::utils::test::*;

    #[inline]
    fn matches(expected: bool, cookie_domain: &CookieDomain, url: &str) {
        let url = Url::parse(url).unwrap();
        assert!(
            expected == cookie_domain.matches(&url),
            "cookie_domain: {:?} url: {:?}, url.host_str(): {:?}",
            cookie_domain,
            url,
            url.host_str()
        );
    }

    #[inline]
    fn variants(expected: bool, cookie_domain: &CookieDomain, url: &str) {
        matches(expected, cookie_domain, url);
        matches(expected, cookie_domain, &format!("{}/", url));
        matches(expected, cookie_domain, &format!("{}:8080", url));
        matches(expected, cookie_domain, &format!("{}/foo/bar", url));
        matches(expected, cookie_domain, &format!("{}:8080/foo/bar", url));
    }

    #[test]
    fn matches_hostonly() {
        {
            let url = url("http://example.com");
            // HostOnly must be an identical string match, and may be an IP address
            // or a hostname
            let host_name = CookieDomain::host_only(&url).expect("unable to parse domain");
            matches(false, &host_name, "data:nonrelative");
            variants(true, &host_name, "http://example.com");
            variants(false, &host_name, "http://example.org");
            // per RFC6265:
            //    WARNING: Some existing user agents treat an absent Domain
            //      attribute as if the Domain attribute were present and contained
            //      the current host name.  For example, if example.com returns a Set-
            //      Cookie header without a Domain attribute, these user agents will
            //      erroneously send the cookie to www.example.com as well.
            variants(false, &host_name, "http://foo.example.com");
            variants(false, &host_name, "http://127.0.0.1");
            variants(false, &host_name, "http://[::1]");
        }

        {
            let url = url("http://127.0.0.1");
            let ip4 = CookieDomain::host_only(&url).expect("unable to parse Ipv4");
            matches(false, &ip4, "data:nonrelative");
            variants(true, &ip4, "http://127.0.0.1");
            variants(false, &ip4, "http://[::1]");
        }

        {
            let url = url("http://[::1]");
            let ip6 = CookieDomain::host_only(&url).expect("unable to parse Ipv6");
            matches(false, &ip6, "data:nonrelative");
            variants(false, &ip6, "http://127.0.0.1");
            variants(true, &ip6, "http://[::1]");
        }
    }

    #[test]
    fn from_strs() {
        assert_eq!(
            CookieDomain::Empty,
            CookieDomain::try_from("").expect("unable to parse domain")
        );
        assert_eq!(
            CookieDomain::Empty,
            CookieDomain::try_from(".").expect("unable to parse domain")
        );
        // per [IETF RFC6265 Section 5.2.3](https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.3)
        //If the first character of the attribute-value string is %x2E ("."):
        //
        //Let cookie-domain be the attribute-value without the leading %x2E
        //(".") character.
        assert_eq!(
            CookieDomain::Suffix(String::from(".")),
            CookieDomain::try_from("..").expect("unable to parse domain")
        );
        assert_eq!(
            CookieDomain::Suffix(String::from("example.com")),
            CookieDomain::try_from("example.com").expect("unable to parse domain")
        );
        assert_eq!(
            CookieDomain::Suffix(String::from("example.com")),
            CookieDomain::try_from(".example.com").expect("unable to parse domain")
        );
        assert_eq!(
            CookieDomain::Suffix(String::from(".example.com")),
            CookieDomain::try_from("..example.com").expect("unable to parse domain")
        );
    }

    #[test]
    fn from_raw_cookie() {
        fn raw_cookie(s: &str) -> RawCookie<'_> {
            RawCookie::parse(s).unwrap()
        }
        assert_eq!(
            CookieDomain::NotPresent,
            CookieDomain::try_from(&raw_cookie("cookie=value")).expect("unable to parse domain")
        );
        // cookie::Cookie handles this (cookie.domain == None)
        assert_eq!(
            CookieDomain::NotPresent,
            CookieDomain::try_from(&raw_cookie("cookie=value; Domain="))
                .expect("unable to parse domain")
        );
        // cookie::Cookie does not handle this (empty after stripping leading dot)
        assert_eq!(
            CookieDomain::Empty,
            CookieDomain::try_from(&raw_cookie("cookie=value; Domain=."))
                .expect("unable to parse domain")
        );
        assert_eq!(
            CookieDomain::Suffix(String::from("example.com")),
            CookieDomain::try_from(&raw_cookie("cookie=value; Domain=.example.com"))
                .expect("unable to parse domain")
        );
        assert_eq!(
            CookieDomain::Suffix(String::from("example.com")),
            CookieDomain::try_from(&raw_cookie("cookie=value; Domain=example.com"))
                .expect("unable to parse domain")
        );
    }

    #[test]
    fn matches_suffix() {
        {
            let suffix = CookieDomain::try_from("example.com").expect("unable to parse domain");
            variants(true, &suffix, "http://example.com"); //  exact match
            variants(true, &suffix, "http://foo.example.com"); //  suffix match
            variants(false, &suffix, "http://example.org"); //  no match
            variants(false, &suffix, "http://xample.com"); //  request is the suffix, no match
            variants(false, &suffix, "http://fooexample.com"); //  suffix, but no "." b/w foo and example, no match
        }

        {
            // strip leading dot
            let suffix = CookieDomain::try_from(".example.com").expect("unable to parse domain");
            variants(true, &suffix, "http://example.com");
            variants(true, &suffix, "http://foo.example.com");
            variants(false, &suffix, "http://example.org");
            variants(false, &suffix, "http://xample.com");
            variants(false, &suffix, "http://fooexample.com");
        }

        {
            // only first leading dot is stripped
            let suffix = CookieDomain::try_from("..example.com").expect("unable to parse domain");
            variants(true, &suffix, "http://.example.com");
            variants(true, &suffix, "http://foo..example.com");
            variants(false, &suffix, "http://example.com");
            variants(false, &suffix, "http://foo.example.com");
            variants(false, &suffix, "http://example.org");
            variants(false, &suffix, "http://xample.com");
            variants(false, &suffix, "http://fooexample.com");
        }

        {
            // an exact string match, although an IP is specified
            let suffix = CookieDomain::try_from("127.0.0.1").expect("unable to parse Ipv4");
            variants(true, &suffix, "http://127.0.0.1");
        }

        {
            // an exact string match, although an IP is specified
            let suffix = CookieDomain::try_from("[::1]").expect("unable to parse Ipv6");
            variants(true, &suffix, "http://[::1]");
        }

        {
            // non-identical suffix match only works for host names (i.e. not IPs)
            let suffix = CookieDomain::try_from("0.0.1").expect("unable to parse Ipv4");
            variants(false, &suffix, "http://127.0.0.1");
        }
    }
}

#[cfg(test)]
mod serde_tests {
    use serde_json;
    use std::convert::TryFrom;

    use crate::cookie_domain::CookieDomain;
    use crate::utils::test::*;

    fn encode_decode(cd: &CookieDomain, exp_json: &str) {
        let encoded = serde_json::to_string(cd).unwrap();
        assert!(
            exp_json == encoded,
            "expected: '{}'\n encoded: '{}'",
            exp_json,
            encoded
        );
        let decoded: CookieDomain = serde_json::from_str(&encoded).unwrap();
        assert!(
            *cd == decoded,
            "expected: '{:?}'\n decoded: '{:?}'",
            cd,
            decoded
        );
    }

    #[test]
    fn serde() {
        let url = url("http://example.com");
        encode_decode(
            &CookieDomain::host_only(&url).expect("cannot parse domain"),
            "{\"HostOnly\":\"example.com\"}",
        );
        encode_decode(
            &CookieDomain::try_from(".example.com").expect("cannot parse domain"),
            "{\"Suffix\":\"example.com\"}",
        );
        encode_decode(&CookieDomain::NotPresent, "\"NotPresent\"");
        encode_decode(&CookieDomain::Empty, "\"Empty\"");
    }
}