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
use crate::auth::AuthenticationScheme;
use crate::bail_status as bail;
use crate::headers::{HeaderName, HeaderValue, Headers, AUTHORIZATION};

/// Credentials to authenticate a user agent with a server.
///
/// # Specifications
///
/// - [RFC 7235, section 4.2: Authorization](https://tools.ietf.org/html/rfc7235#section-4.2)
///
/// # Examples
///
/// ```
/// # fn main() -> http_types::Result<()> {
/// #
/// use http_types::Response;
/// use http_types::auth::{AuthenticationScheme, Authorization};
///
/// let scheme = AuthenticationScheme::Basic;
/// let credentials = "0xdeadbeef202020";
/// let authz = Authorization::new(scheme, credentials.into());
///
/// let mut res = Response::new(200);
/// authz.apply(&mut res);
///
/// let authz = Authorization::from_headers(res)?.unwrap();
///
/// assert_eq!(authz.scheme(), AuthenticationScheme::Basic);
/// assert_eq!(authz.credentials(), credentials);
/// #
/// # Ok(()) }
/// ```
#[derive(Debug)]
pub struct Authorization {
    scheme: AuthenticationScheme,
    credentials: String,
}

impl Authorization {
    /// Create a new instance of `Authorization`.
    pub fn new(scheme: AuthenticationScheme, credentials: String) -> Self {
        Self {
            scheme,
            credentials,
        }
    }

    /// Create a new instance from headers.
    pub fn from_headers(headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> {
        let headers = match headers.as_ref().get(AUTHORIZATION) {
            Some(headers) => headers,
            None => return Ok(None),
        };

        // If we successfully parsed the header then there's always at least one
        // entry. We want the last entry.
        let value = headers.iter().last().unwrap();

        let mut iter = value.as_str().splitn(2, ' ');
        let scheme = iter.next();
        let credential = iter.next();
        let (scheme, credentials) = match (scheme, credential) {
            (None, _) => bail!(400, "Could not find scheme"),
            (Some(_), None) => bail!(400, "Could not find credentials"),
            (Some(scheme), Some(credentials)) => (scheme.parse()?, credentials.to_owned()),
        };

        Ok(Some(Self {
            scheme,
            credentials,
        }))
    }

    /// Sets the header.
    pub fn apply(&self, mut headers: impl AsMut<Headers>) {
        headers.as_mut().insert(self.name(), self.value());
    }

    /// Get the `HeaderName`.
    pub fn name(&self) -> HeaderName {
        AUTHORIZATION
    }

    /// Get the `HeaderValue`.
    pub fn value(&self) -> HeaderValue {
        let output = format!("{} {}", self.scheme, self.credentials);

        // SAFETY: the internal string is validated to be ASCII.
        unsafe { HeaderValue::from_bytes_unchecked(output.into()) }
    }

    /// Get the authorization scheme.
    pub fn scheme(&self) -> AuthenticationScheme {
        self.scheme
    }

    /// Set the authorization scheme.
    pub fn set_scheme(&mut self, scheme: AuthenticationScheme) {
        self.scheme = scheme;
    }

    /// Get the authorization credentials.
    pub fn credentials(&self) -> &str {
        self.credentials.as_str()
    }

    /// Set the authorization credentials.
    pub fn set_credentials(&mut self, credentials: String) {
        self.credentials = credentials;
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::headers::Headers;

    #[test]
    fn smoke() -> crate::Result<()> {
        let scheme = AuthenticationScheme::Basic;
        let credentials = "0xdeadbeef202020";
        let authz = Authorization::new(scheme, credentials.into());

        let mut headers = Headers::new();
        authz.apply(&mut headers);

        let authz = Authorization::from_headers(headers)?.unwrap();

        assert_eq!(authz.scheme(), AuthenticationScheme::Basic);
        assert_eq!(authz.credentials(), credentials);
        Ok(())
    }

    #[test]
    fn bad_request_on_parse_error() {
        let mut headers = Headers::new();
        headers.insert(AUTHORIZATION, "<nori ate the tag. yum.>");
        let err = Authorization::from_headers(headers).unwrap_err();
        assert_eq!(err.status(), 400);
    }
}