-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathauth.rs
More file actions
268 lines (230 loc) · 9.83 KB
/
auth.rs
File metadata and controls
268 lines (230 loc) · 9.83 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
use base64::{engine::general_purpose::STANDARD, Engine as _};
use edgezero_core::body::Body as EdgeBody;
use error_stack::Report;
use http::header;
use http::{Request, Response, StatusCode};
use sha2::{Digest as _, Sha256};
use subtle::ConstantTimeEq as _;
use crate::error::TrustedServerError;
use crate::settings::Settings;
const BASIC_AUTH_REALM: &str = r#"Basic realm="Trusted Server""#;
/// Enforces HTTP Basic authentication for configured handler paths.
///
/// Returns `Ok(None)` when the request does not target a protected handler or
/// when the supplied credentials are valid. Returns `Ok(Some(Response))` with
/// the auth challenge when credentials are missing or invalid.
///
/// Admin endpoints are protected by requiring a handler at build time; see
/// [`Settings::from_toml_and_env`]. Credential checks use constant-time
/// comparison for both username and password, and evaluate both regardless of
/// individual match results to avoid timing oracles.
///
/// # Errors
///
/// Returns an error when handler configuration is invalid, such as an
/// un-compilable path regex.
pub fn enforce_basic_auth(
settings: &Settings,
req: &Request<EdgeBody>,
) -> Result<Option<Response<EdgeBody>>, Report<TrustedServerError>> {
let Some(handler) = settings.handler_for_path(req.uri().path())? else {
return Ok(None);
};
let (username, password) = match extract_credentials(req) {
Some(credentials) => credentials,
None => return Ok(Some(unauthorized_response())),
};
// Hash before comparing to normalise lengths — `ct_eq` on raw byte slices
// short-circuits when lengths differ, which would leak credential length.
// SHA-256 produces fixed-size digests so the comparison is truly constant-time.
//
// Note: constant-time guarantees are best-effort on WASM targets because the
// runtime optimiser/JIT may re-introduce variable-time paths. This is an
// inherent limitation of all constant-time code in managed runtimes.
let username_match = Sha256::digest(handler.username.expose().as_bytes())
.ct_eq(&Sha256::digest(username.as_bytes()));
let password_match = Sha256::digest(handler.password.expose().as_bytes())
.ct_eq(&Sha256::digest(password.as_bytes()));
if bool::from(username_match & password_match) {
Ok(None)
} else {
log::warn!("Basic auth failed for path: {}", req.uri().path());
Ok(Some(unauthorized_response()))
}
}
fn extract_credentials(req: &Request<EdgeBody>) -> Option<(String, String)> {
let header_value = req
.headers()
.get(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<EdgeBody> {
Response::builder()
.status(StatusCode::UNAUTHORIZED)
.header(header::WWW_AUTHENTICATE, BASIC_AUTH_REALM)
.header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
.body(EdgeBody::from(b"Unauthorized".as_ref()))
.expect("should build unauthorized response")
}
#[cfg(test)]
mod tests {
use super::*;
use base64::engine::general_purpose::STANDARD;
use http::{header, HeaderValue, Method};
use crate::test_support::tests::{crate_test_settings_str, create_test_settings};
fn build_request(method: Method, uri: &str) -> Request<EdgeBody> {
Request::builder()
.method(method)
.uri(uri)
.body(EdgeBody::empty())
.expect("should build request")
}
fn set_authorization(req: &mut Request<EdgeBody>, value: &str) {
req.headers_mut().insert(
header::AUTHORIZATION,
HeaderValue::from_str(value).expect("should build authorization header"),
);
}
#[test]
fn no_challenge_for_non_protected_path() {
let settings = create_test_settings();
let req = build_request(Method::GET, "https://example.com/open");
assert!(enforce_basic_auth(&settings, &req)
.expect("should evaluate auth")
.is_none());
}
#[test]
fn challenge_when_missing_credentials() {
let settings = create_test_settings();
let req = build_request(Method::GET, "https://example.com/secure");
let response = enforce_basic_auth(&settings, &req)
.expect("should evaluate auth")
.expect("should challenge");
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
let realm = response
.headers()
.get(header::WWW_AUTHENTICATE)
.expect("should have WWW-Authenticate header");
assert_eq!(realm, BASIC_AUTH_REALM);
}
#[test]
fn allow_when_credentials_match() {
let settings = create_test_settings();
let mut req = build_request(Method::GET, "https://example.com/secure/data");
let token = STANDARD.encode("user:pass");
set_authorization(&mut req, &format!("Basic {token}"));
assert!(enforce_basic_auth(&settings, &req)
.expect("should evaluate auth")
.is_none());
}
#[test]
fn challenge_when_both_credentials_wrong() {
let settings = create_test_settings();
let mut req = build_request(Method::GET, "https://example.com/secure/data");
let token = STANDARD.encode("wrong:wrong");
set_authorization(&mut req, &format!("Basic {token}"));
let response = enforce_basic_auth(&settings, &req)
.expect("should evaluate auth")
.expect("should challenge");
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[test]
fn challenge_when_username_wrong_password_correct() {
// Validates that both fields are always evaluated — no short-circuit username oracle.
let settings = create_test_settings();
let mut req = build_request(Method::GET, "https://example.com/secure/data");
let token = STANDARD.encode("wrong-user:pass");
set_authorization(&mut req, &format!("Basic {token}"));
let response = enforce_basic_auth(&settings, &req)
.expect("should evaluate auth")
.expect("should challenge");
assert_eq!(
response.status(),
StatusCode::UNAUTHORIZED,
"should reject wrong username even with correct password"
);
}
#[test]
fn challenge_when_username_correct_password_wrong() {
let settings = create_test_settings();
let mut req = build_request(Method::GET, "https://example.com/secure/data");
let token = STANDARD.encode("user:wrong-pass");
set_authorization(&mut req, &format!("Basic {token}"));
let response = enforce_basic_auth(&settings, &req)
.expect("should evaluate auth")
.expect("should challenge");
assert_eq!(
response.status(),
StatusCode::UNAUTHORIZED,
"should reject correct username with wrong password"
);
}
#[test]
fn challenge_when_scheme_is_not_basic() {
let settings = create_test_settings();
let mut req = build_request(Method::GET, "https://example.com/secure");
set_authorization(&mut req, "Bearer token");
let response = enforce_basic_auth(&settings, &req)
.expect("should evaluate auth")
.expect("should challenge");
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[test]
fn returns_error_for_invalid_handler_regex_without_panicking() {
let config = crate_test_settings_str().replace(r#"path = "^/secure""#, r#"path = "(""#);
let err = Settings::from_toml(&config).expect_err("should reject invalid handler regex");
assert!(
err.to_string()
.contains("Handler path regex `(` failed to compile"),
"should describe the invalid handler regex"
);
}
#[test]
fn allow_admin_path_with_valid_credentials() {
let settings = create_test_settings();
let mut req = build_request(Method::POST, "https://example.com/admin/keys/rotate");
let token = STANDARD.encode("admin:admin-pass");
set_authorization(&mut req, &format!("Basic {token}"));
assert!(
enforce_basic_auth(&settings, &req)
.expect("should evaluate auth")
.is_none(),
"should allow admin path with correct credentials"
);
}
#[test]
fn challenge_admin_path_with_wrong_credentials() {
let settings = create_test_settings();
let mut req = build_request(Method::POST, "https://example.com/admin/keys/rotate");
let token = STANDARD.encode("admin:wrong");
set_authorization(&mut req, &format!("Basic {token}"));
let response = enforce_basic_auth(&settings, &req)
.expect("should evaluate auth")
.expect("should challenge admin path with wrong credentials");
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[test]
fn challenge_admin_path_with_missing_credentials() {
let settings = create_test_settings();
let req = build_request(Method::POST, "https://example.com/admin/keys/rotate");
let response = enforce_basic_auth(&settings, &req)
.expect("should evaluate auth")
.expect("should challenge admin path with missing credentials");
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
}