-
Notifications
You must be signed in to change notification settings - Fork 378
/
Copy pathhttp_basic.rs
83 lines (66 loc) · 2.23 KB
/
http_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
use crate::auth::{AuthError, Authenticated};
use super::{UserAuthContext, UserAuthStrategy};
pub struct HttpBasic {
credential: String,
}
impl UserAuthStrategy for HttpBasic {
fn authenticate(&self, ctx: UserAuthContext) -> Result<Authenticated, AuthError> {
tracing::trace!("executing http basic auth");
let auth_str = None
.or_else(|| ctx.custom_fields.get("authorization"))
.or_else(|| ctx.custom_fields.get("x-authorization"));
let (_, token) = auth_str
.ok_or(AuthError::AuthHeaderNotFound)
.map(|s| s.split_once(' ').ok_or(AuthError::AuthStringMalformed))
.and_then(|o| o)?;
// NOTE: this naive comparison may leak information about the `expected_value`
// using a timing attack
let expected_value = self.credential.trim_end_matches('=');
let creds_match = token.contains(expected_value);
if creds_match {
return Ok(Authenticated::FullAccess);
}
Err(AuthError::BasicRejected)
}
fn required_fields(&self) -> Vec<String> {
vec!["authorization".to_string(), "x-authorization".to_string()]
}
}
impl HttpBasic {
pub fn new(credential: String) -> Self {
Self { credential }
}
}
#[cfg(test)]
mod tests {
use super::*;
const CREDENTIAL: &str = "d29qdGVrOnRoZWJlYXI=";
fn strategy() -> HttpBasic {
HttpBasic::new(CREDENTIAL.into())
}
#[test]
fn authenticates_with_valid_credential() {
let context = UserAuthContext::basic(CREDENTIAL);
assert!(matches!(
strategy().authenticate(context).unwrap(),
Authenticated::FullAccess
))
}
#[test]
fn authenticates_with_valid_trimmed_credential() {
let credential = CREDENTIAL.trim_end_matches('=');
let context = UserAuthContext::basic(credential);
assert!(matches!(
strategy().authenticate(context).unwrap(),
Authenticated::FullAccess
))
}
#[test]
fn errors_when_credentials_do_not_match() {
let context = UserAuthContext::basic("abc");
assert_eq!(
strategy().authenticate(context).unwrap_err(),
AuthError::BasicRejected
)
}
}