http_types/auth/
www_authenticate.rs

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

/// Define the authentication method that should be used to gain access to a
/// resource.
///
/// # Specifications
///
/// - [RFC 7235, section 4.1: WWW-Authenticate](https://tools.ietf.org/html/rfc7235#section-4.1)
///
/// # Implementation Notes
///
/// This implementation only encodes and parses a single authentication method,
/// further authorization methods are ignored. It also always passes the utf-8 encoding flag.
///
/// # Examples
///
/// ```
/// # fn main() -> http_types::Result<()> {
/// #
/// use http_types::Response;
/// use http_types::auth::{AuthenticationScheme, WwwAuthenticate};
///
/// let scheme = AuthenticationScheme::Basic;
/// let realm = "Access to the staging site";
/// let authz = WwwAuthenticate::new(scheme, realm.into());
///
/// let mut res = Response::new(200);
/// authz.apply(&mut res);
///
/// let authz = WwwAuthenticate::from_headers(res)?.unwrap();
///
/// assert_eq!(authz.scheme(), AuthenticationScheme::Basic);
/// assert_eq!(authz.realm(), realm);
/// #
/// # Ok(()) }
/// ```
#[derive(Debug)]
pub struct WwwAuthenticate {
    scheme: AuthenticationScheme,
    realm: String,
}

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

    /// 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(WWW_AUTHENTICATE) {
            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, realm) = match (scheme, credential) {
            (None, _) => bail!(400, "Could not find scheme"),
            (Some(_), None) => bail!(400, "Could not find realm"),
            (Some(scheme), Some(realm)) => (scheme.parse()?, realm.to_owned()),
        };

        let realm = realm.trim_start();
        let realm = match realm.strip_prefix(r#"realm=""#) {
            Some(realm) => realm,
            None => bail!(400, "realm not found"),
        };

        let mut chars = realm.chars();
        let mut closing_quote = false;
        let realm = (&mut chars)
            .take_while(|c| {
                if c == &'"' {
                    closing_quote = true;
                    false
                } else {
                    true
                }
            })
            .collect();
        if !closing_quote {
            bail!(400, r"Expected a closing quote");
        }

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

    /// 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 {
        WWW_AUTHENTICATE
    }

    /// Get the `HeaderValue`.
    pub fn value(&self) -> HeaderValue {
        let output = format!(r#"{} realm="{}", charset="UTF-8""#, self.scheme, self.realm);

        // 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 realm.
    pub fn realm(&self) -> &str {
        self.realm.as_str()
    }

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

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

    #[test]
    fn smoke() -> crate::Result<()> {
        let scheme = AuthenticationScheme::Basic;
        let realm = "Access to the staging site";
        let authz = WwwAuthenticate::new(scheme, realm.into());

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

        assert_eq!(
            headers["WWW-Authenticate"],
            r#"Basic realm="Access to the staging site", charset="UTF-8""#
        );

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

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

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