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
use std::convert::TryFrom;

use super::origin::Origin;
use util::{IterExt, TryFromValues};
use HeaderValue;

/// The `Access-Control-Allow-Origin` response header,
/// part of [CORS](http://www.w3.org/TR/cors/#access-control-allow-origin-response-header)
///
/// The `Access-Control-Allow-Origin` header indicates whether a resource
/// can be shared based by returning the value of the Origin request header,
/// `*`, or `null` in the response.
///
/// ## ABNF
///
/// ```text
/// Access-Control-Allow-Origin = "Access-Control-Allow-Origin" ":" origin-list-or-null | "*"
/// ```
///
/// ## Example values
/// * `null`
/// * `*`
/// * `http://google.com/`
///
/// # Examples
///
/// ```
/// # extern crate headers;
/// use headers::AccessControlAllowOrigin;
/// use std::convert::TryFrom;
///
/// let any_origin = AccessControlAllowOrigin::ANY;
/// let null_origin = AccessControlAllowOrigin::NULL;
/// let origin = AccessControlAllowOrigin::try_from("http://web-platform.test:8000");
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct AccessControlAllowOrigin(OriginOrAny);

derive_header! {
    AccessControlAllowOrigin(_),
    name: ACCESS_CONTROL_ALLOW_ORIGIN
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum OriginOrAny {
    Origin(Origin),
    /// Allow all origins
    Any,
}

impl AccessControlAllowOrigin {
    /// `Access-Control-Allow-Origin: *`
    pub const ANY: AccessControlAllowOrigin = AccessControlAllowOrigin(OriginOrAny::Any);
    /// `Access-Control-Allow-Origin: null`
    pub const NULL: AccessControlAllowOrigin =
        AccessControlAllowOrigin(OriginOrAny::Origin(Origin::NULL));

    /// Returns the origin if there's one specified.
    pub fn origin(&self) -> Option<&Origin> {
        match self.0 {
            OriginOrAny::Origin(ref origin) => Some(origin),
            _ => None,
        }
    }
}

impl TryFrom<&str> for AccessControlAllowOrigin {
    type Error = ::Error;

    fn try_from(s: &str) -> Result<Self, ::Error> {
        let header_value = HeaderValue::from_str(s).map_err(|_| ::Error::invalid())?;
        let origin = OriginOrAny::try_from(&header_value)?;
        Ok(Self(origin))
    }
}

impl TryFrom<&HeaderValue> for OriginOrAny {
    type Error = ::Error;

    fn try_from(header_value: &HeaderValue) -> Result<Self, ::Error> {
        Origin::try_from_value(header_value)
            .map(OriginOrAny::Origin)
            .ok_or_else(::Error::invalid)
    }
}

impl TryFromValues for OriginOrAny {
    fn try_from_values<'i, I>(values: &mut I) -> Result<Self, ::Error>
    where
        I: Iterator<Item = &'i HeaderValue>,
    {
        values
            .just_one()
            .and_then(|value| {
                if value == "*" {
                    return Some(OriginOrAny::Any);
                }

                Origin::try_from_value(value).map(OriginOrAny::Origin)
            })
            .ok_or_else(::Error::invalid)
    }
}

impl<'a> From<&'a OriginOrAny> for HeaderValue {
    fn from(origin: &'a OriginOrAny) -> HeaderValue {
        match origin {
            OriginOrAny::Origin(ref origin) => origin.into_value(),
            OriginOrAny::Any => HeaderValue::from_static("*"),
        }
    }
}

#[cfg(test)]
mod tests {

    use super::super::{test_decode, test_encode};
    use super::*;

    #[test]
    fn origin() {
        let s = "http://web-platform.test:8000";

        let allow_origin = test_decode::<AccessControlAllowOrigin>(&[s]).unwrap();
        {
            let origin = allow_origin.origin().unwrap();
            assert_eq!(origin.scheme(), "http");
            assert_eq!(origin.hostname(), "web-platform.test");
            assert_eq!(origin.port(), Some(8000));
        }

        let headers = test_encode(allow_origin);
        assert_eq!(headers["access-control-allow-origin"], s);
    }

    #[test]
    fn try_from_origin() {
        let s = "http://web-platform.test:8000";

        let allow_origin = AccessControlAllowOrigin::try_from(s).unwrap();
        {
            let origin = allow_origin.origin().unwrap();
            assert_eq!(origin.scheme(), "http");
            assert_eq!(origin.hostname(), "web-platform.test");
            assert_eq!(origin.port(), Some(8000));
        }

        let headers = test_encode(allow_origin);
        assert_eq!(headers["access-control-allow-origin"], s);
    }

    #[test]
    fn any() {
        let allow_origin = test_decode::<AccessControlAllowOrigin>(&["*"]).unwrap();
        assert_eq!(allow_origin, AccessControlAllowOrigin::ANY);

        let headers = test_encode(allow_origin);
        assert_eq!(headers["access-control-allow-origin"], "*");
    }

    #[test]
    fn null() {
        let allow_origin = test_decode::<AccessControlAllowOrigin>(&["null"]).unwrap();
        assert_eq!(allow_origin, AccessControlAllowOrigin::NULL);

        let headers = test_encode(allow_origin);
        assert_eq!(headers["access-control-allow-origin"], "null");
    }
}