Repository navigation
metrics-plugin: add authentication #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
84d5bfa
c0113e4
3a7c77b
cfc9c26
78fb5de
b5172f1
22de7a9
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,9 @@ | ||
| use crate::cache::CachedData; | ||
| use axum::{ | ||
| Router, | ||
| http::StatusCode, | ||
| extract::{Request, State}, | ||
| http::{StatusCode, header}, | ||
| middleware::{self, Next}, | ||
| response::{IntoResponse, Response}, | ||
| routing::get, | ||
| }; | ||
|
|
@@ -521,12 +523,120 @@ async fn metrics_handler() -> Response { | |
| .into_response() | ||
| } | ||
|
|
||
| pub async fn start_metrics_server(listener: TcpListener) -> anyhow::Result<()> { | ||
| let app = Router::new().route("/metrics", get(metrics_handler)); | ||
| /// Constant-time comparison to avoid leaking the configured token via response-timing side | ||
| /// channels. | ||
| fn tokens_match(provided: &[u8], expected: &[u8]) -> bool { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why do we work with bytes? token is already stored as a string, so we can just compare strings
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ohhh, than question opens a pandora box that I'm really happy to share 😈 The thing is related to so-called remote timing attacks against string comparisons. Let's consider a case where we compare strings rather than bytes. Rust comrpares string values character by character. This allows an attacker to brute-force a password based on response times. The guard checks the first character, then the second, then the third, and so on. As soon as it encounters an incorrect character, it immediately rejects the input and stops checking. For example, a guess that matches the first five characters takes slightly longer to reject than one that only matches the first character, simply because the guard has to check more characters before giving up. This creates an opportunity to gradually figure out the correct sequence of characters. In our case, the comparison function always takes a constant-time approach. It uses a combination of XOR and OR operations to check the result. Even if some characters are incorrect, it processes the entire provided string, making it much harder to determine whether a particular character is invalid based on execution time. And yes, I know the probability of successfully exploiting this is relatively low, and we also have to account for external noise (e.g. network jitter). However, by performing thousands or even millions of requests and averaging the response times, the actual timing difference (caused by comparing one additional byte) can still emerge statistically. |
||
| if provided.len() != expected.len() { | ||
| return false; | ||
| } | ||
|
|
||
| provided | ||
| .iter() | ||
| .zip(expected.iter()) | ||
| .fold(0u8, |acc, (a, b)| acc | (a ^ b)) | ||
| == 0 | ||
| } | ||
|
|
||
| fn is_authorized(request: &Request, token: &str) -> bool { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. also, not sure, but usually i think it may be preferred to fix the token encoding, like URL-compatible Base64. I understand that you may want to leave the decision to the plugin user, but we should be sure that it cant be a potential attack vector
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The encoding choice itself isn't really an attack vector in my opninion - the comparison is already byte-equal and constant-time regardless of what characters are in the token. The HTTP layer (the |
||
| let Some(header) = request.headers().get(header::AUTHORIZATION) else { | ||
| return false; | ||
| }; | ||
|
|
||
| let Ok(header) = header.to_str() else { | ||
| return false; | ||
| }; | ||
|
|
||
| let Some(provided) = header.strip_prefix("Bearer ") else { | ||
| return false; | ||
| }; | ||
|
|
||
| tokens_match(provided.as_bytes(), token.as_bytes()) | ||
| } | ||
|
|
||
| async fn require_bearer_token( | ||
| State(token): State<String>, | ||
| request: Request, | ||
| next: Next, | ||
| ) -> Response { | ||
| if is_authorized(&request, &token) { | ||
| return next.run(request).await; | ||
| } | ||
|
|
||
| (StatusCode::UNAUTHORIZED, "Unauthorized\n").into_response() | ||
| } | ||
|
|
||
| /// `auth_token` gates the `/metrics` route with bearer-token auth when set; `None` serves it | ||
| /// unauthenticated (only reachable via the explicit `metrics-disable-auth` opt-out). | ||
| pub async fn start_metrics_server( | ||
| listener: TcpListener, | ||
| auth_token: Option<String>, | ||
| ) -> anyhow::Result<()> { | ||
| let mut app = Router::new().route("/metrics", get(metrics_handler)); | ||
|
|
||
| if let Some(token) = auth_token { | ||
| app = app.route_layer(middleware::from_fn_with_state(token, require_bearer_token)); | ||
| } | ||
|
|
||
| tokio::spawn(async move { | ||
| if let Err(e) = axum::serve(listener, app).await { | ||
| error!("metrics server error: {}", e); | ||
| } | ||
| }); | ||
| Ok(()) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use axum::body::Body; | ||
| use axum::http::Request; | ||
| use tower::ServiceExt; | ||
|
|
||
| fn protected_app() -> Router { | ||
| Router::new() | ||
| .route("/metrics", get(metrics_handler)) | ||
| .route_layer(middleware::from_fn_with_state( | ||
| "secret".to_string(), | ||
| require_bearer_token, | ||
| )) | ||
| } | ||
|
|
||
| async fn get_metrics(app: Router, auth_header: Option<&str>) -> StatusCode { | ||
| let mut req = Request::builder().uri("/metrics"); | ||
| if let Some(value) = auth_header { | ||
| req = req.header(header::AUTHORIZATION, value); | ||
| } | ||
| let response = app.oneshot(req.body(Body::empty()).unwrap()).await.unwrap(); | ||
| response.status() | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn rejects_missing_authorization_header() { | ||
| assert_eq!( | ||
| get_metrics(protected_app(), None).await, | ||
| StatusCode::UNAUTHORIZED | ||
| ); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn rejects_wrong_token() { | ||
| assert_eq!( | ||
| get_metrics(protected_app(), Some("Bearer wrong")).await, | ||
| StatusCode::UNAUTHORIZED | ||
| ); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn accepts_correct_token() { | ||
| assert_eq!( | ||
| get_metrics(protected_app(), Some("Bearer secret")).await, | ||
| StatusCode::OK | ||
| ); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn unprotected_app_serves_without_authorization() { | ||
| let app = Router::new().route("/metrics", get(metrics_handler)); | ||
| assert_eq!(get_metrics(app, None).await, StatusCode::OK); | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.