-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathauth.rs
More file actions
172 lines (140 loc) · 6.06 KB
/
auth.rs
File metadata and controls
172 lines (140 loc) · 6.06 KB
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
use base64::{engine::general_purpose::STANDARD, Engine as _};
use fastly::http::{header, StatusCode};
use fastly::{Request, Response};
use crate::settings::Settings;
const BASIC_AUTH_REALM: &str = r#"Basic realm="Trusted Server""#;
/// Enforces Basic-auth for incoming requests.
///
/// Authentication is required when a configured handler's `path` regex matches
/// the request path. Paths not covered by any handler pass through without
/// authentication.
///
/// Admin endpoints are protected by requiring a handler at build time — see
/// [`Settings::from_toml_and_env`].
///
/// # Returns
///
/// * `Some(Response)` — a `401 Unauthorized` response that should be sent back
/// to the client (credentials missing or incorrect).
/// * `None` — the request is allowed to proceed.
pub fn enforce_basic_auth(settings: &Settings, req: &Request) -> Option<Response> {
let path = req.get_path();
let handler = settings.handler_for_path(path)?;
let (username, password) = match extract_credentials(req) {
Some(credentials) => credentials,
None => return Some(unauthorized_response()),
};
if handler.username == username && handler.password == password {
None
} else {
Some(unauthorized_response())
}
}
fn extract_credentials(req: &Request) -> Option<(String, String)> {
let header_value = req
.get_header(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())?;
let mut parts = header_value.splitn(2, ' ');
let scheme = parts.next()?.trim();
if !scheme.eq_ignore_ascii_case("basic") {
return None;
}
let token = parts.next()?.trim();
if token.is_empty() {
return None;
}
let decoded = STANDARD.decode(token).ok()?;
let credentials = String::from_utf8(decoded).ok()?;
let mut credentials_parts = credentials.splitn(2, ':');
let username = credentials_parts.next()?.to_string();
let password = credentials_parts.next()?.to_string();
Some((username, password))
}
fn unauthorized_response() -> Response {
Response::from_status(StatusCode::UNAUTHORIZED)
.with_header(header::WWW_AUTHENTICATE, BASIC_AUTH_REALM)
.with_header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
.with_body_text_plain("Unauthorized")
}
#[cfg(test)]
mod tests {
use super::*;
use base64::engine::general_purpose::STANDARD;
use fastly::http::{header, Method};
use crate::test_support::tests::crate_test_settings_str;
fn settings_with_handlers() -> Settings {
let config = crate_test_settings_str();
Settings::from_toml(&config).expect("should parse settings with handlers")
}
#[test]
fn no_challenge_for_non_protected_path() {
let settings = settings_with_handlers();
let req = Request::new(Method::GET, "https://example.com/open");
assert!(enforce_basic_auth(&settings, &req).is_none());
}
#[test]
fn challenge_when_missing_credentials() {
let settings = settings_with_handlers();
let req = Request::new(Method::GET, "https://example.com/secure");
let response = enforce_basic_auth(&settings, &req).expect("should challenge");
assert_eq!(response.get_status(), StatusCode::UNAUTHORIZED);
let realm = response
.get_header(header::WWW_AUTHENTICATE)
.expect("should have WWW-Authenticate header");
assert_eq!(realm, BASIC_AUTH_REALM);
}
#[test]
fn allow_when_credentials_match() {
let settings = settings_with_handlers();
let mut req = Request::new(Method::GET, "https://example.com/secure/data");
let token = STANDARD.encode("user:pass");
req.set_header(header::AUTHORIZATION, format!("Basic {token}"));
assert!(enforce_basic_auth(&settings, &req).is_none());
}
#[test]
fn challenge_when_credentials_mismatch() {
let settings = settings_with_handlers();
let mut req = Request::new(Method::GET, "https://example.com/secure/data");
let token = STANDARD.encode("user:wrong");
req.set_header(header::AUTHORIZATION, format!("Basic {token}"));
let response = enforce_basic_auth(&settings, &req).expect("should challenge");
assert_eq!(response.get_status(), StatusCode::UNAUTHORIZED);
}
#[test]
fn challenge_when_scheme_is_not_basic() {
let settings = settings_with_handlers();
let mut req = Request::new(Method::GET, "https://example.com/secure");
req.set_header(header::AUTHORIZATION, "Bearer token");
let response = enforce_basic_auth(&settings, &req).expect("should challenge");
assert_eq!(response.get_status(), StatusCode::UNAUTHORIZED);
}
#[test]
fn allow_admin_path_with_valid_credentials() {
let settings = settings_with_handlers();
let mut req = Request::new(Method::POST, "https://example.com/admin/keys/rotate");
let token = STANDARD.encode("admin:admin-pass");
req.set_header(header::AUTHORIZATION, format!("Basic {token}"));
assert!(
enforce_basic_auth(&settings, &req).is_none(),
"should allow admin path with correct credentials"
);
}
#[test]
fn challenge_admin_path_with_wrong_credentials() {
let settings = settings_with_handlers();
let mut req = Request::new(Method::POST, "https://example.com/admin/keys/rotate");
let token = STANDARD.encode("admin:wrong");
req.set_header(header::AUTHORIZATION, format!("Basic {token}"));
let response = enforce_basic_auth(&settings, &req)
.expect("should challenge admin path with wrong credentials");
assert_eq!(response.get_status(), StatusCode::UNAUTHORIZED);
}
#[test]
fn challenge_admin_path_with_missing_credentials() {
let settings = settings_with_handlers();
let req = Request::new(Method::POST, "https://example.com/admin/keys/rotate");
let response = enforce_basic_auth(&settings, &req)
.expect("should challenge admin path with missing credentials");
assert_eq!(response.get_status(), StatusCode::UNAUTHORIZED);
}
}