| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
use axum::{ |
| 9 |
extract::{FromRequestParts, Request}, |
| 10 |
handler::Handler, |
| 11 |
http::{header::HeaderMap, request::Parts, StatusCode}, |
| 12 |
middleware::{from_fn, Next}, |
| 13 |
response::{IntoResponse, Response}, |
| 14 |
routing::{delete, patch, post, put, MethodRouter}, |
| 15 |
Router, |
| 16 |
}; |
| 17 |
use rand::RngCore; |
| 18 |
use tower_sessions::Session; |
| 19 |
|
| 20 |
use crate::error::{AppError, ResultExt}; |
| 21 |
|
| 22 |
|
| 23 |
pub const CSRF_SESSION_KEY: &str = "csrf_token"; |
| 24 |
|
| 25 |
|
| 26 |
const CSRF_TOKEN_LENGTH: usize = 32; |
| 27 |
|
| 28 |
|
| 29 |
pub fn generate_token() -> String { |
| 30 |
let mut token = [0u8; CSRF_TOKEN_LENGTH]; |
| 31 |
rand::rng().fill_bytes(&mut token); |
| 32 |
hex::encode(token) |
| 33 |
} |
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
pub async fn get_or_create_token(session: &Session) -> Result<String, AppError> { |
| 48 |
if let Some(token) = session |
| 49 |
.get::<String>(CSRF_SESSION_KEY) |
| 50 |
.await |
| 51 |
.context("session error")? |
| 52 |
{ |
| 53 |
return Ok(token); |
| 54 |
} |
| 55 |
|
| 56 |
let candidate = generate_token(); |
| 57 |
session |
| 58 |
.insert(CSRF_SESSION_KEY, &candidate) |
| 59 |
.await |
| 60 |
.context("session insert")?; |
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
let final_token: String = session |
| 66 |
.get(CSRF_SESSION_KEY) |
| 67 |
.await |
| 68 |
.context("session error")? |
| 69 |
.unwrap_or(candidate); |
| 70 |
|
| 71 |
Ok(final_token) |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
pub async fn validate_token(session: &Session, provided_token: &str) -> Result<bool, AppError> { |
| 76 |
let session_token: Option<String> = session |
| 77 |
.get(CSRF_SESSION_KEY) |
| 78 |
.await |
| 79 |
.context("session error")?; |
| 80 |
|
| 81 |
match session_token { |
| 82 |
Some(token) => Ok(crate::helpers::constant_time_compare(&token, provided_token)), |
| 83 |
None => Ok(false), |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
|
| 88 |
pub fn extract_token_from_request(headers: &HeaderMap, body: Option<&str>) -> Option<String> { |
| 89 |
|
| 90 |
if let Some(token) = headers |
| 91 |
.get("X-CSRF-Token") |
| 92 |
.and_then(|v| v.to_str().ok()) |
| 93 |
.map(|s| s.to_string()) |
| 94 |
{ |
| 95 |
return Some(token); |
| 96 |
} |
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
if let Some(body_str) = body { |
| 105 |
for (key, value) in url::form_urlencoded::parse(body_str.as_bytes()) { |
| 106 |
if key == "_csrf" { |
| 107 |
return Some(value.into_owned()); |
| 108 |
} |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
None |
| 113 |
} |
| 114 |
|
| 115 |
|
| 116 |
pub struct CsrfToken(pub String); |
| 117 |
|
| 118 |
impl<S> FromRequestParts<S> for CsrfToken |
| 119 |
where |
| 120 |
S: Send + Sync, |
| 121 |
{ |
| 122 |
type Rejection = AppError; |
| 123 |
|
| 124 |
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { |
| 125 |
let session = parts |
| 126 |
.extensions |
| 127 |
.get::<Session>() |
| 128 |
.ok_or(AppError::Internal(anyhow::anyhow!("Session not found")))?; |
| 129 |
|
| 130 |
let token = get_or_create_token(session).await?; |
| 131 |
Ok(CsrfToken(token)) |
| 132 |
} |
| 133 |
} |
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
#[derive(Clone, Copy, Debug)] |
| 142 |
pub enum CsrfPosture { |
| 143 |
|
| 144 |
Auto, |
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
Manual(&'static str), |
| 149 |
|
| 150 |
|
| 151 |
Skip(&'static str), |
| 152 |
} |
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
pub use sealed::CsrfManuallyValidated; |
| 160 |
|
| 161 |
mod sealed { |
| 162 |
pub struct CsrfManuallyValidated { |
| 163 |
_private: (), |
| 164 |
} |
| 165 |
|
| 166 |
pub(super) fn make_validated() -> CsrfManuallyValidated { |
| 167 |
CsrfManuallyValidated { _private: () } |
| 168 |
} |
| 169 |
} |
| 170 |
|
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
pub async fn validate_token_consuming( |
| 177 |
session: &Session, |
| 178 |
provided_token: &str, |
| 179 |
) -> Result<CsrfManuallyValidated, AppError> { |
| 180 |
if validate_token(session, provided_token).await? { |
| 181 |
Ok(sealed::make_validated()) |
| 182 |
} else { |
| 183 |
Err(AppError::Forbidden) |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
fn attach_auto_layer<S>(method_router: MethodRouter<S>) -> MethodRouter<S> |
| 199 |
where |
| 200 |
S: Clone + Send + Sync + 'static, |
| 201 |
{ |
| 202 |
method_router.layer(from_fn(|req: Request, next: Next| async move { |
| 203 |
let path = req.uri().path().to_string(); |
| 204 |
validate_auto(req, next, &path).await |
| 205 |
})) |
| 206 |
} |
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
pub use posture_router::PostureMethodRouter; |
| 213 |
|
| 214 |
mod posture_router { |
| 215 |
use super::*; |
| 216 |
|
| 217 |
pub struct PostureMethodRouter<S = ()>(pub(super) MethodRouter<S>); |
| 218 |
|
| 219 |
impl<S> PostureMethodRouter<S> |
| 220 |
where |
| 221 |
S: Clone + Send + Sync + 'static, |
| 222 |
{ |
| 223 |
pub(super) fn new(inner: MethodRouter<S>) -> Self { |
| 224 |
Self(inner) |
| 225 |
} |
| 226 |
|
| 227 |
pub(super) fn into_inner(self) -> MethodRouter<S> { |
| 228 |
self.0 |
| 229 |
} |
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
pub fn layer<L>(self, layer: L) -> Self |
| 235 |
where |
| 236 |
L: tower::Layer<axum::routing::Route> + Clone + Send + Sync + 'static, |
| 237 |
L::Service: |
| 238 |
tower::Service<axum::extract::Request> + Clone + Send + Sync + 'static, |
| 239 |
<L::Service as tower::Service<axum::extract::Request>>::Response: |
| 240 |
axum::response::IntoResponse + 'static, |
| 241 |
<L::Service as tower::Service<axum::extract::Request>>::Error: |
| 242 |
Into<std::convert::Infallible> + 'static, |
| 243 |
<L::Service as tower::Service<axum::extract::Request>>::Future: |
| 244 |
Send + 'static, |
| 245 |
{ |
| 246 |
Self(self.0.layer(layer)) |
| 247 |
} |
| 248 |
} |
| 249 |
} |
| 250 |
|
| 251 |
macro_rules! csrf_auto_helper { |
| 252 |
($name:ident, $axum_fn:ident) => { |
| 253 |
pub fn $name<H, T, S>(handler: H) -> PostureMethodRouter<S> |
| 254 |
where |
| 255 |
H: Handler<T, S>, |
| 256 |
T: 'static, |
| 257 |
S: Clone + Send + Sync + 'static, |
| 258 |
{ |
| 259 |
posture_router::PostureMethodRouter::new(attach_auto_layer($axum_fn(handler))) |
| 260 |
} |
| 261 |
}; |
| 262 |
} |
| 263 |
|
| 264 |
macro_rules! csrf_passthrough_helper { |
| 265 |
($name:ident, $axum_fn:ident, $variant:ident) => { |
| 266 |
pub fn $name<H, T, S>(reason: &'static str, handler: H) -> PostureMethodRouter<S> |
| 267 |
where |
| 268 |
H: Handler<T, S>, |
| 269 |
T: 'static, |
| 270 |
S: Clone + Send + Sync + 'static, |
| 271 |
{ |
| 272 |
let _ = CsrfPosture::$variant(reason); |
| 273 |
posture_router::PostureMethodRouter::new($axum_fn(handler)) |
| 274 |
} |
| 275 |
}; |
| 276 |
} |
| 277 |
|
| 278 |
|
| 279 |
csrf_auto_helper!(post_csrf, post); |
| 280 |
csrf_auto_helper!(put_csrf, put); |
| 281 |
csrf_auto_helper!(patch_csrf, patch); |
| 282 |
csrf_auto_helper!(delete_csrf, delete); |
| 283 |
|
| 284 |
|
| 285 |
csrf_passthrough_helper!(post_csrf_manual, post, Manual); |
| 286 |
csrf_passthrough_helper!(put_csrf_manual, put, Manual); |
| 287 |
csrf_passthrough_helper!(patch_csrf_manual, patch, Manual); |
| 288 |
csrf_passthrough_helper!(delete_csrf_manual, delete, Manual); |
| 289 |
|
| 290 |
|
| 291 |
csrf_passthrough_helper!(post_csrf_skip, post, Skip); |
| 292 |
csrf_passthrough_helper!(put_csrf_skip, put, Skip); |
| 293 |
csrf_passthrough_helper!(patch_csrf_skip, patch, Skip); |
| 294 |
csrf_passthrough_helper!(delete_csrf_skip, delete, Skip); |
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
|
| 300 |
|
| 301 |
|
| 302 |
|
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
|
| 307 |
pub fn with_csrf<S>(method_router: MethodRouter<S>) -> PostureMethodRouter<S> |
| 308 |
where |
| 309 |
S: Clone + Send + Sync + 'static, |
| 310 |
{ |
| 311 |
posture_router::PostureMethodRouter::new(attach_auto_layer(method_router)) |
| 312 |
} |
| 313 |
|
| 314 |
|
| 315 |
|
| 316 |
pub fn with_csrf_manual<S>( |
| 317 |
reason: &'static str, |
| 318 |
method_router: MethodRouter<S>, |
| 319 |
) -> PostureMethodRouter<S> |
| 320 |
where |
| 321 |
S: Clone + Send + Sync + 'static, |
| 322 |
{ |
| 323 |
let _ = CsrfPosture::Manual(reason); |
| 324 |
posture_router::PostureMethodRouter::new(method_router) |
| 325 |
} |
| 326 |
|
| 327 |
|
| 328 |
pub fn with_csrf_skip<S>( |
| 329 |
reason: &'static str, |
| 330 |
method_router: MethodRouter<S>, |
| 331 |
) -> PostureMethodRouter<S> |
| 332 |
where |
| 333 |
S: Clone + Send + Sync + 'static, |
| 334 |
{ |
| 335 |
let _ = CsrfPosture::Skip(reason); |
| 336 |
posture_router::PostureMethodRouter::new(method_router) |
| 337 |
} |
| 338 |
|
| 339 |
|
| 340 |
|
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
pub struct CsrfRouter<S = ()>(Router<S>); |
| 349 |
|
| 350 |
impl<S> Default for CsrfRouter<S> |
| 351 |
where |
| 352 |
S: Clone + Send + Sync + 'static, |
| 353 |
{ |
| 354 |
fn default() -> Self { |
| 355 |
Self::new() |
| 356 |
} |
| 357 |
} |
| 358 |
|
| 359 |
impl<S> CsrfRouter<S> |
| 360 |
where |
| 361 |
S: Clone + Send + Sync + 'static, |
| 362 |
{ |
| 363 |
pub fn new() -> Self { |
| 364 |
Self(Router::new()) |
| 365 |
} |
| 366 |
|
| 367 |
pub fn route(self, path: &str, posture: PostureMethodRouter<S>) -> Self { |
| 368 |
Self(self.0.route(path, posture.into_inner())) |
| 369 |
} |
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
|
| 375 |
|
| 376 |
|
| 377 |
pub fn route_get(self, path: &str, method_router: MethodRouter<S>) -> Self { |
| 378 |
Self(self.0.route(path, method_router)) |
| 379 |
} |
| 380 |
|
| 381 |
pub fn merge(self, other: Self) -> Self { |
| 382 |
Self(self.0.merge(other.0)) |
| 383 |
} |
| 384 |
|
| 385 |
pub fn nest(self, path: &str, other: Self) -> Self { |
| 386 |
Self(self.0.nest(path, other.0)) |
| 387 |
} |
| 388 |
|
| 389 |
pub fn layer<L>(self, layer: L) -> Self |
| 390 |
where |
| 391 |
L: tower::Layer<axum::routing::Route> + Clone + Send + Sync + 'static, |
| 392 |
L::Service: |
| 393 |
tower::Service<axum::extract::Request> + Clone + Send + Sync + 'static, |
| 394 |
<L::Service as tower::Service<axum::extract::Request>>::Response: |
| 395 |
IntoResponse + 'static, |
| 396 |
<L::Service as tower::Service<axum::extract::Request>>::Error: |
| 397 |
Into<std::convert::Infallible> + 'static, |
| 398 |
<L::Service as tower::Service<axum::extract::Request>>::Future: Send + 'static, |
| 399 |
{ |
| 400 |
Self(self.0.layer(layer)) |
| 401 |
} |
| 402 |
|
| 403 |
pub fn route_layer<L>(self, layer: L) -> Self |
| 404 |
where |
| 405 |
L: tower::Layer<axum::routing::Route> + Clone + Send + Sync + 'static, |
| 406 |
L::Service: |
| 407 |
tower::Service<axum::extract::Request> + Clone + Send + Sync + 'static, |
| 408 |
<L::Service as tower::Service<axum::extract::Request>>::Response: |
| 409 |
IntoResponse + 'static, |
| 410 |
<L::Service as tower::Service<axum::extract::Request>>::Error: |
| 411 |
Into<std::convert::Infallible> + 'static, |
| 412 |
<L::Service as tower::Service<axum::extract::Request>>::Future: Send + 'static, |
| 413 |
{ |
| 414 |
Self(self.0.route_layer(layer)) |
| 415 |
} |
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
pub fn finalize(self) -> Router<S> { |
| 422 |
self.0 |
| 423 |
} |
| 424 |
} |
| 425 |
|
| 426 |
|
| 427 |
|
| 428 |
|
| 429 |
async fn validate_auto(request: Request, next: Next, path: &str) -> Response { |
| 430 |
|
| 431 |
|
| 432 |
|
| 433 |
|
| 434 |
if !matches!(*request.method(), axum::http::Method::POST |
| 435 |
| axum::http::Method::PUT |
| 436 |
| axum::http::Method::PATCH |
| 437 |
| axum::http::Method::DELETE) |
| 438 |
{ |
| 439 |
return next.run(request).await; |
| 440 |
} |
| 441 |
|
| 442 |
|
| 443 |
let session = match request.extensions().get::<Session>() { |
| 444 |
Some(s) => s.clone(), |
| 445 |
None => { |
| 446 |
tracing::warn!("CSRF check failed: no session"); |
| 447 |
return (StatusCode::FORBIDDEN, "CSRF validation failed").into_response(); |
| 448 |
} |
| 449 |
}; |
| 450 |
|
| 451 |
|
| 452 |
let header_token = request |
| 453 |
.headers() |
| 454 |
.get("X-CSRF-Token") |
| 455 |
.and_then(|v| v.to_str().ok()) |
| 456 |
.map(|s| s.to_string()); |
| 457 |
|
| 458 |
if let Some(ref token) = header_token { |
| 459 |
return match validate_token(&session, token).await { |
| 460 |
Ok(true) => next.run(request).await, |
| 461 |
Ok(false) => { |
| 462 |
tracing::warn!(path = %path, "CSRF token mismatch"); |
| 463 |
crate::error::AppError::Forbidden.into_response() |
| 464 |
} |
| 465 |
Err(e) => { |
| 466 |
tracing::error!(error = ?e, "CSRF validation error"); |
| 467 |
crate::error::AppError::Internal(anyhow::anyhow!("CSRF validation error")).into_response() |
| 468 |
} |
| 469 |
}; |
| 470 |
} |
| 471 |
|
| 472 |
|
| 473 |
let has_user: bool = session |
| 474 |
.get::<crate::auth::SessionUser>("user") |
| 475 |
.await |
| 476 |
.ok() |
| 477 |
.flatten() |
| 478 |
.is_some(); |
| 479 |
|
| 480 |
if !has_user { |
| 481 |
return next.run(request).await; |
| 482 |
} |
| 483 |
|
| 484 |
|
| 485 |
|
| 486 |
|
| 487 |
|
| 488 |
|
| 489 |
|
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
|
| 494 |
|
| 495 |
|
| 496 |
|
| 497 |
|
| 498 |
|
| 499 |
let content_type = request |
| 500 |
.headers() |
| 501 |
.get("content-type") |
| 502 |
.and_then(|v| v.to_str().ok()) |
| 503 |
.unwrap_or(""); |
| 504 |
let is_form = content_type.starts_with("application/x-www-form-urlencoded"); |
| 505 |
|
| 506 |
if !is_form { |
| 507 |
let is_multipart = content_type.starts_with("multipart/form-data"); |
| 508 |
tracing::warn!( |
| 509 |
path = %path, |
| 510 |
content_type, |
| 511 |
is_multipart, |
| 512 |
"CSRF token missing for authenticated non-form request" |
| 513 |
); |
| 514 |
return crate::error::AppError::Forbidden.into_response(); |
| 515 |
} |
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
let (parts, body) = request.into_parts(); |
| 521 |
let bytes = match axum::body::to_bytes(body, 1024 * 1024).await { |
| 522 |
Ok(b) => b, |
| 523 |
Err(_) => { |
| 524 |
return (StatusCode::BAD_REQUEST, "Request body too large").into_response(); |
| 525 |
} |
| 526 |
}; |
| 527 |
|
| 528 |
let body_str = String::from_utf8_lossy(&bytes); |
| 529 |
let body_token = extract_token_from_request(&HeaderMap::new(), Some(&body_str)); |
| 530 |
|
| 531 |
let token = match body_token { |
| 532 |
Some(t) => t, |
| 533 |
None => { |
| 534 |
tracing::warn!(path = %path, "CSRF token missing from form body"); |
| 535 |
return crate::error::AppError::Forbidden.into_response(); |
| 536 |
} |
| 537 |
}; |
| 538 |
|
| 539 |
match validate_token(&session, &token).await { |
| 540 |
Ok(true) => { |
| 541 |
|
| 542 |
let request = Request::from_parts(parts, axum::body::Body::from(bytes)); |
| 543 |
next.run(request).await |
| 544 |
} |
| 545 |
Ok(false) => { |
| 546 |
tracing::warn!(path = %path, "CSRF token mismatch"); |
| 547 |
(StatusCode::FORBIDDEN, "Invalid CSRF token").into_response() |
| 548 |
} |
| 549 |
Err(e) => { |
| 550 |
tracing::error!(error = ?e, "CSRF validation error"); |
| 551 |
(StatusCode::INTERNAL_SERVER_ERROR, "CSRF validation error").into_response() |
| 552 |
} |
| 553 |
} |
| 554 |
} |
| 555 |
|
| 556 |
#[cfg(test)] |
| 557 |
mod tests { |
| 558 |
use super::*; |
| 559 |
|
| 560 |
#[test] |
| 561 |
fn test_generate_token() { |
| 562 |
let token1 = generate_token(); |
| 563 |
let token2 = generate_token(); |
| 564 |
|
| 565 |
|
| 566 |
assert_eq!(token1.len(), 64); |
| 567 |
assert_eq!(token2.len(), 64); |
| 568 |
|
| 569 |
|
| 570 |
assert_ne!(token1, token2); |
| 571 |
} |
| 572 |
|
| 573 |
#[test] |
| 574 |
fn test_constant_time_compare() { |
| 575 |
use crate::helpers::constant_time_compare; |
| 576 |
assert!(constant_time_compare("abc", "abc")); |
| 577 |
assert!(!constant_time_compare("abc", "abd")); |
| 578 |
assert!(!constant_time_compare("abc", "abcd")); |
| 579 |
assert!(!constant_time_compare("", "a")); |
| 580 |
} |
| 581 |
|
| 582 |
#[test] |
| 583 |
fn test_generate_token_is_hex() { |
| 584 |
let token = generate_token(); |
| 585 |
|
| 586 |
assert!(token.chars().all(|c| c.is_ascii_hexdigit())); |
| 587 |
} |
| 588 |
|
| 589 |
#[test] |
| 590 |
fn test_extract_token_from_header() { |
| 591 |
let mut headers = HeaderMap::new(); |
| 592 |
headers.insert("X-CSRF-Token", "abc123".parse().unwrap()); |
| 593 |
let token = extract_token_from_request(&headers, None); |
| 594 |
assert_eq!(token.as_deref(), Some("abc123")); |
| 595 |
} |
| 596 |
|
| 597 |
#[test] |
| 598 |
fn test_extract_token_from_form_body() { |
| 599 |
let headers = HeaderMap::new(); |
| 600 |
let body = "name=value&_csrf=mytoken123&other=data"; |
| 601 |
let token = extract_token_from_request(&headers, Some(body)); |
| 602 |
assert_eq!(token.as_deref(), Some("mytoken123")); |
| 603 |
} |
| 604 |
|
| 605 |
#[test] |
| 606 |
fn test_extract_token_missing() { |
| 607 |
let headers = HeaderMap::new(); |
| 608 |
let token = extract_token_from_request(&headers, None); |
| 609 |
assert!(token.is_none()); |
| 610 |
} |
| 611 |
|
| 612 |
#[test] |
| 613 |
fn test_generate_token_unique_across_many() { |
| 614 |
let tokens: Vec<String> = (0..100).map(|_| generate_token()).collect(); |
| 615 |
let unique: std::collections::HashSet<&String> = tokens.iter().collect(); |
| 616 |
assert_eq!(unique.len(), 100, "all 100 tokens should be unique"); |
| 617 |
} |
| 618 |
|
| 619 |
#[test] |
| 620 |
fn test_generate_token_correct_byte_length() { |
| 621 |
let token = generate_token(); |
| 622 |
let bytes = hex::decode(&token).expect("token should be valid hex"); |
| 623 |
assert_eq!(bytes.len(), CSRF_TOKEN_LENGTH); |
| 624 |
} |
| 625 |
|
| 626 |
#[test] |
| 627 |
fn test_extract_token_header_takes_priority_over_body() { |
| 628 |
let mut headers = HeaderMap::new(); |
| 629 |
headers.insert("X-CSRF-Token", "header_token".parse().unwrap()); |
| 630 |
let body = "_csrf=body_token"; |
| 631 |
let token = extract_token_from_request(&headers, Some(body)); |
| 632 |
assert_eq!(token.as_deref(), Some("header_token")); |
| 633 |
} |
| 634 |
|
| 635 |
#[test] |
| 636 |
fn test_extract_token_from_body_url_encoded() { |
| 637 |
let headers = HeaderMap::new(); |
| 638 |
let body = "_csrf=token%20with%20spaces&other=val"; |
| 639 |
let token = extract_token_from_request(&headers, Some(body)); |
| 640 |
assert_eq!(token.as_deref(), Some("token with spaces")); |
| 641 |
} |
| 642 |
|
| 643 |
#[test] |
| 644 |
fn test_extract_token_csrf_at_start_of_body() { |
| 645 |
let headers = HeaderMap::new(); |
| 646 |
let body = "_csrf=firstfield&name=value"; |
| 647 |
let token = extract_token_from_request(&headers, Some(body)); |
| 648 |
assert_eq!(token.as_deref(), Some("firstfield")); |
| 649 |
} |
| 650 |
|
| 651 |
#[test] |
| 652 |
fn test_extract_token_csrf_at_end_of_body() { |
| 653 |
let headers = HeaderMap::new(); |
| 654 |
let body = "name=value&_csrf=lastfield"; |
| 655 |
let token = extract_token_from_request(&headers, Some(body)); |
| 656 |
assert_eq!(token.as_deref(), Some("lastfield")); |
| 657 |
} |
| 658 |
|
| 659 |
#[test] |
| 660 |
fn test_extract_token_empty_body() { |
| 661 |
let headers = HeaderMap::new(); |
| 662 |
let token = extract_token_from_request(&headers, Some("")); |
| 663 |
assert!(token.is_none()); |
| 664 |
} |
| 665 |
|
| 666 |
#[test] |
| 667 |
fn test_extract_token_body_without_csrf_field() { |
| 668 |
let headers = HeaderMap::new(); |
| 669 |
let body = "name=value&other=data"; |
| 670 |
let token = extract_token_from_request(&headers, Some(body)); |
| 671 |
assert!(token.is_none()); |
| 672 |
} |
| 673 |
|
| 674 |
#[test] |
| 675 |
fn test_extract_token_csrf_prefix_mismatch() { |
| 676 |
let headers = HeaderMap::new(); |
| 677 |
|
| 678 |
let body = "_csrfx=notreal"; |
| 679 |
let token = extract_token_from_request(&headers, Some(body)); |
| 680 |
assert!(token.is_none()); |
| 681 |
} |
| 682 |
|
| 683 |
#[test] |
| 684 |
fn test_extract_token_empty_csrf_value() { |
| 685 |
let headers = HeaderMap::new(); |
| 686 |
let body = "_csrf=&other=val"; |
| 687 |
let token = extract_token_from_request(&headers, Some(body)); |
| 688 |
assert_eq!(token.as_deref(), Some("")); |
| 689 |
} |
| 690 |
|
| 691 |
#[test] |
| 692 |
fn test_constant_time_compare_empty_strings() { |
| 693 |
use crate::helpers::constant_time_compare; |
| 694 |
assert!(constant_time_compare("", "")); |
| 695 |
} |
| 696 |
|
| 697 |
#[test] |
| 698 |
fn test_constant_time_compare_near_miss() { |
| 699 |
use crate::helpers::constant_time_compare; |
| 700 |
let token = generate_token(); |
| 701 |
|
| 702 |
let mut tampered = token.clone(); |
| 703 |
let last = tampered.pop().unwrap(); |
| 704 |
tampered.push(if last == '0' { '1' } else { '0' }); |
| 705 |
assert!(!constant_time_compare(&token, &tampered)); |
| 706 |
} |
| 707 |
|
| 708 |
#[test] |
| 709 |
fn csrf_manually_validated_marker_is_zero_sized() { |
| 710 |
assert_eq!(std::mem::size_of::<CsrfManuallyValidated>(), 0); |
| 711 |
} |
| 712 |
|
| 713 |
#[test] |
| 714 |
fn csrf_posture_is_copyable_and_carries_reason() { |
| 715 |
let p = CsrfPosture::Skip("webhook: stripe signature"); |
| 716 |
let copy = p; |
| 717 |
match copy { |
| 718 |
CsrfPosture::Skip(r) => assert_eq!(r, "webhook: stripe signature"), |
| 719 |
_ => panic!("variant mismatch"), |
| 720 |
} |
| 721 |
} |
| 722 |
|
| 723 |
#[test] |
| 724 |
fn test_constant_time_compare_truncated() { |
| 725 |
use crate::helpers::constant_time_compare; |
| 726 |
let token = generate_token(); |
| 727 |
let truncated = &token[..token.len() - 1]; |
| 728 |
assert!(!constant_time_compare(&token, truncated)); |
| 729 |
} |
| 730 |
} |
| 731 |
|