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

use bytes::Bytes;
use http::uri::{self, Authority, Scheme, Uri};

use util::{IterExt, TryFromValues};
use ::{HeaderValue};

/// The `Origin` header.
///
/// The `Origin` header is a version of the `Referer` header that is used for all HTTP fetches and `POST`s whose CORS flag is set.
/// This header is often used to inform recipients of the security context of where the request was initiated.
///
/// Following the spec, [https://fetch.spec.whatwg.org/#origin-header][url], the value of this header is composed of
/// a String (scheme), Host (host/port)
///
/// [url]: https://fetch.spec.whatwg.org/#origin-header
///
/// # Examples
///
/// ```
/// # extern crate headers;
/// use headers::Origin;
///
/// let origin = Origin::NULL;
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash, Header)]
pub struct Origin(OriginOrNull);

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum OriginOrNull {
    Origin(Scheme, Authority),
    Null,
}

impl Origin {
    /// The literal `null` Origin header.
    pub const NULL: Origin = Origin(OriginOrNull::Null);

    /// Checks if `Origin` is `null`.
    #[inline]
    pub fn is_null(&self) -> bool {
        match self.0 {
            OriginOrNull::Null => true,
            _ => false,
        }
    }

    /// Get the "scheme" part of this origin.
    #[inline]
    pub fn scheme(&self) -> &str {
        match self.0 {
            OriginOrNull::Origin(ref scheme, _) => scheme.as_str(),
            OriginOrNull::Null => "",
        }
    }

    /// Get the "hostname" part of this origin.
    #[inline]
    pub fn hostname(&self) -> &str {
        match self.0 {
            OriginOrNull::Origin(_, ref auth) => auth.host(),
            OriginOrNull::Null => "",
        }
    }

    /// Get the "port" part of this origin.
    #[inline]
    pub fn port(&self) -> Option<u16> {
        match self.0 {
            OriginOrNull::Origin(_, ref auth) => auth.port_part().map(|p| p.as_u16()),
            OriginOrNull::Null => None,
        }
    }

    /// Tries to build a `Origin` from three parts, the scheme, the host and an optional port.
    pub fn try_from_parts(scheme: &str, host: &str, port: impl Into<Option<u16>>) -> Result<Self, InvalidOrigin> {

        struct MaybePort(Option<u16>);

        impl fmt::Display for MaybePort {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                if let Some(port) = self.0 {
                    write!(f, ":{}", port)
                } else {
                    Ok(())
                }
            }
        }

        let bytes = Bytes::from(format!("{}://{}{}", scheme, host, MaybePort(port.into())));
        HeaderValue::from_shared(bytes)
            .ok()
            .and_then(|val| Self::try_from_value(&val))
            .ok_or_else(|| InvalidOrigin { _inner: () })
    }

    // Used in AccessControlAllowOrigin
    pub(super) fn try_from_value(value: &HeaderValue) -> Option<Self> {
        OriginOrNull::try_from_value(value)
            .map(Origin)
    }

    pub(super) fn into_value(&self) -> HeaderValue {
        (&self.0).into()
    }
}

impl fmt::Display for Origin {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.0 {
            OriginOrNull::Origin(ref scheme, ref auth) => {
                write!(f, "{}://{}", scheme, auth)
            },
            OriginOrNull::Null => f.write_str("null"),
        }
    }
}

error_type!(InvalidOrigin);

impl OriginOrNull {
    fn try_from_value(value: &HeaderValue) -> Option<Self> {
        if value == "null" {
            return Some(OriginOrNull::Null);
        }

        let bytes = Bytes::from(value.clone());

        let uri = Uri::from_shared(bytes).ok()?;

        let (scheme, auth) = match uri.into_parts() {
            uri::Parts {
                scheme: Some(scheme),
                authority: Some(auth),
                path_and_query: None,
                ..
            } => (scheme, auth),
            uri::Parts {
                scheme: Some(ref scheme),
                authority: Some(ref auth),
                path_and_query: Some(ref p),
                ..
            } if p == "/" => (scheme.clone(), auth.clone()),
            _ => {
                return None;
            }
        };

        Some(OriginOrNull::Origin(scheme, auth))
    }
}

impl TryFromValues for OriginOrNull {
    fn try_from_values<'i, I>(values: &mut I) -> Result<Self, ::Error>
    where
        I: Iterator<Item = &'i HeaderValue>,
    {
        values
            .just_one()
            .and_then(OriginOrNull::try_from_value)
            .ok_or_else(::Error::invalid)
    }
}

impl<'a> From<&'a OriginOrNull> for HeaderValue {
    fn from(origin: &'a OriginOrNull) -> HeaderValue {
        match origin {
            OriginOrNull::Origin(ref scheme, ref auth) => {
                let s = format!("{}://{}", scheme, auth);
                let bytes = Bytes::from(s);
                HeaderValue::from_shared(bytes)
                    .expect("Scheme and Authority are valid header values")
            },
            // Serialized as "null" per ASCII serialization of an origin
            // https://html.spec.whatwg.org/multipage/browsers.html#ascii-serialisation-of-an-origin
            OriginOrNull::Null => HeaderValue::from_static("null"),
        }
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use super::super::{test_decode, test_encode};


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

        let headers = test_encode(origin);
        assert_eq!(headers["origin"], s);
    }

    #[test]
    fn null() {
        assert_eq!(
            test_decode::<Origin>(&["null"]),
            Some(Origin::NULL),
        );

        let headers = test_encode(Origin::NULL);
        assert_eq!(headers["origin"], "null");
    }
}