actix_web_httpauth/headers/authorization/scheme/
basic.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
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
use std::{borrow::Cow, fmt, str};

use actix_web::{
    http::header::{HeaderValue, InvalidHeaderValue, TryIntoHeaderValue},
    web::{BufMut, BytesMut},
};
use base64::{prelude::BASE64_STANDARD, Engine};

use crate::headers::authorization::{errors::ParseError, Scheme};

/// Credentials for `Basic` authentication scheme, defined in [RFC 7617](https://tools.ietf.org/html/rfc7617)
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Basic {
    user_id: Cow<'static, str>,
    password: Option<Cow<'static, str>>,
}

impl Basic {
    /// Creates `Basic` credentials with provided `user_id` and optional
    /// `password`.
    ///
    /// # Examples
    /// ```
    /// # use actix_web_httpauth::headers::authorization::Basic;
    /// let credentials = Basic::new("Alladin", Some("open sesame"));
    /// ```
    pub fn new<U, P>(user_id: U, password: Option<P>) -> Basic
    where
        U: Into<Cow<'static, str>>,
        P: Into<Cow<'static, str>>,
    {
        Basic {
            user_id: user_id.into(),
            password: password.map(Into::into),
        }
    }

    /// Returns client's user-ID.
    pub fn user_id(&self) -> &str {
        self.user_id.as_ref()
    }

    /// Returns client's password if provided.
    pub fn password(&self) -> Option<&str> {
        self.password.as_deref()
    }
}

impl Scheme for Basic {
    fn parse(header: &HeaderValue) -> Result<Self, ParseError> {
        // "Basic *" length
        if header.len() < 7 {
            return Err(ParseError::Invalid);
        }

        let mut parts = header.to_str()?.splitn(2, ' ');
        match parts.next() {
            Some("Basic") => (),
            _ => return Err(ParseError::MissingScheme),
        }

        let decoded = BASE64_STANDARD.decode(parts.next().ok_or(ParseError::Invalid)?)?;
        let mut credentials = str::from_utf8(&decoded)?.splitn(2, ':');

        let user_id = credentials
            .next()
            .ok_or(ParseError::MissingField("user_id"))
            .map(|user_id| user_id.to_string().into())?;

        let password = credentials
            .next()
            .ok_or(ParseError::MissingField("password"))
            .map(|password| {
                if password.is_empty() {
                    None
                } else {
                    Some(password.to_string().into())
                }
            })?;

        Ok(Basic { user_id, password })
    }
}

impl fmt::Debug for Basic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!("Basic {}:******", self.user_id))
    }
}

impl fmt::Display for Basic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!("Basic {}:******", self.user_id))
    }
}

impl TryIntoHeaderValue for Basic {
    type Error = InvalidHeaderValue;

    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
        let credential_length =
            self.user_id.len() + 1 + self.password.as_ref().map_or(0, |pwd| pwd.len());
        // The length of BASE64 encoded bytes is `4 * credential_length.div_ceil(3)`
        // TODO: Use credential_length.div_ceil(3) when `int_roundings` becomes stable
        // https://github.com/rust-lang/rust/issues/88581
        let mut value = String::with_capacity(6 + 4 * (credential_length + 2) / 3);
        let mut credentials = BytesMut::with_capacity(credential_length);

        credentials.extend_from_slice(self.user_id.as_bytes());
        credentials.put_u8(b':');
        if let Some(ref password) = self.password {
            credentials.extend_from_slice(password.as_bytes());
        }

        value.push_str("Basic ");
        BASE64_STANDARD.encode_string(&credentials, &mut value);

        HeaderValue::from_maybe_shared(value)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_header() {
        let value = HeaderValue::from_static("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
        let scheme = Basic::parse(&value);

        assert!(scheme.is_ok());
        let scheme = scheme.unwrap();
        assert_eq!(scheme.user_id, "Aladdin");
        assert_eq!(scheme.password, Some("open sesame".into()));
    }

    #[test]
    fn test_empty_password() {
        let value = HeaderValue::from_static("Basic QWxhZGRpbjo=");
        let scheme = Basic::parse(&value);

        assert!(scheme.is_ok());
        let scheme = scheme.unwrap();
        assert_eq!(scheme.user_id, "Aladdin");
        assert_eq!(scheme.password, None);
    }

    #[test]
    fn test_empty_header() {
        let value = HeaderValue::from_static("");
        let scheme = Basic::parse(&value);

        assert!(scheme.is_err());
    }

    #[test]
    fn test_wrong_scheme() {
        let value = HeaderValue::from_static("THOUSHALLNOTPASS please?");
        let scheme = Basic::parse(&value);

        assert!(scheme.is_err());
    }

    #[test]
    fn test_missing_credentials() {
        let value = HeaderValue::from_static("Basic ");
        let scheme = Basic::parse(&value);

        assert!(scheme.is_err());
    }

    #[test]
    fn test_missing_credentials_colon() {
        let value = HeaderValue::from_static("Basic QWxsYWRpbg==");
        let scheme = Basic::parse(&value);

        assert!(scheme.is_err());
    }

    #[test]
    fn test_into_header_value() {
        let basic = Basic {
            user_id: "Aladdin".into(),
            password: Some("open sesame".into()),
        };

        let result = basic.try_into_value();
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            HeaderValue::from_static("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==")
        );
    }
}