Spaces:
Paused
Paused
File size: 31,385 Bytes
2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae 2c8ae4e 5f0e2ae ad9e5dd 094c13f ad9e5dd | 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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 | mod common;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use http_body_util::BodyExt;
use sea_orm::ConnectionTrait;
use tower::ServiceExt;
fn json_body(json: serde_json::Value) -> Body {
Body::from(json.to_string())
}
// --- CORS origin enforcement (via preflight OPTIONS requests) ---
#[tokio::test]
async fn cors_preflight_without_origin_config_rejected() {
// No CORS origin configured — CorsLayer::new() rejects all cross-origin
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.method("OPTIONS")
.uri("/api/auth/setup")
.header("origin", "https://example.com")
.header("access-control-request-method", "POST")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
// No Access-Control-Allow-Origin header should be present
assert!(res.headers().get("access-control-allow-origin").is_none());
}
#[tokio::test]
async fn cors_preflight_with_correct_origin_allowed() {
let (app, _state) =
common::setup_test_app_with_cors(Some("https://example.com".into())).await;
let req = Request::builder()
.method("OPTIONS")
.uri("/api/auth/setup")
.header("origin", "https://example.com")
.header("access-control-request-method", "POST")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
let acao = res
.headers()
.get("access-control-allow-origin")
.and_then(|v| v.to_str().ok());
assert_eq!(acao, Some("https://example.com"));
}
#[tokio::test]
async fn cors_preflight_with_wrong_origin_rejected() {
let (app, _state) =
common::setup_test_app_with_cors(Some("https://example.com".into())).await;
let req = Request::builder()
.method("OPTIONS")
.uri("/api/auth/setup")
.header("origin", "https://evil.com")
.header("access-control-request-method", "POST")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
// CorsLayer echoes the configured origin, not the request origin.
// The browser compares and rejects when they don't match.
let acao = res
.headers()
.get("access-control-allow-origin")
.and_then(|v| v.to_str().ok());
assert_ne!(acao, Some("https://evil.com"), "should not allow wrong origin");
}
#[tokio::test]
async fn cors_get_allowed_even_with_cors_origin_set() {
let (app, _state) =
common::setup_test_app_with_cors(Some("https://example.com".into())).await;
let req = Request::builder()
.uri("/api/auth/status")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
}
#[tokio::test]
async fn cors_delete_without_origin_no_cors_headers() {
let (app, _state) =
common::setup_test_app_with_cors(Some("https://example.com".into())).await;
let req = Request::builder()
.method("DELETE")
.uri("/api/keys/1")
.header("authorization", "Bearer fake")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
// Without matching origin, browser will block the response
let acao = res
.headers()
.get("access-control-allow-origin")
.and_then(|v| v.to_str().ok());
assert_ne!(acao, Some("https://evil.com"));
}
// --- Refresh token expiry ---
#[tokio::test]
async fn refresh_with_expired_token_returns_401() {
let (app, state) = common::setup_test_app().await;
// Setup admin
let req = Request::builder()
.method("POST")
.uri("/api/auth/setup")
.header("content-type", "application/json")
.body(json_body(serde_json::json!({
"username": "admin",
"password": "testpassword123"
})))
.unwrap();
let res = app.clone().oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let set_cookie = common::extract_set_cookie(res.headers()).unwrap();
let refresh_token = common::extract_refresh_token(&set_cookie).unwrap();
// Manually expire all refresh tokens in the DB
state
.db
.execute_unprepared(
"UPDATE refresh_tokens SET expires_at = '2020-01-01 00:00:00'",
)
.await
.unwrap();
// Try to refresh with the expired token
let req = Request::builder()
.method("POST")
.uri("/api/auth/refresh")
.header("cookie", format!("refresh_token={refresh_token}"))
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
// --- Concurrent setup race condition ---
#[tokio::test]
async fn concurrent_setup_only_one_succeeds() {
let (app, _state) = common::setup_test_app().await;
let app1 = app.clone();
let app2 = app.clone();
let req1 = Request::builder()
.method("POST")
.uri("/api/auth/setup")
.header("content-type", "application/json")
.body(json_body(serde_json::json!({
"username": "admin1",
"password": "testpassword123"
})))
.unwrap();
let req2 = Request::builder()
.method("POST")
.uri("/api/auth/setup")
.header("content-type", "application/json")
.body(json_body(serde_json::json!({
"username": "admin2",
"password": "testpassword123"
})))
.unwrap();
let (res1, res2) = tokio::join!(app1.oneshot(req1), app2.oneshot(req2));
let status1 = res1.unwrap().status();
let status2 = res2.unwrap().status();
// Exactly one should succeed, one should fail
let successes = [status1, status2]
.iter()
.filter(|s| **s == StatusCode::OK)
.count();
let failures = [status1, status2]
.iter()
.filter(|s| **s == StatusCode::FORBIDDEN)
.count();
assert_eq!(successes, 1, "exactly one setup should succeed (got {status1}, {status2})");
assert_eq!(failures, 1, "exactly one setup should be forbidden (got {status1}, {status2})");
}
// --- API key negative caching ---
#[tokio::test]
async fn invalid_api_key_cached_returns_401_consistently() {
let (app, _state) = common::setup_test_app().await;
// First request with invalid key
let req = Request::builder()
.uri("/bogus-key/imdb/poster-default/tt0000001.jpg")
.body(Body::empty())
.unwrap();
let res = app.clone().oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
// Second request with same invalid key should also fail (from cache)
let req = Request::builder()
.uri("/bogus-key/imdb/poster-default/tt0000001.jpg")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
// --- Deleted API key is rejected after cache invalidation ---
#[tokio::test]
async fn deleted_api_key_rejected_after_cache_invalidation() {
let (app, state) = common::setup_test_app().await;
let token = common::setup_admin(&app).await;
// Create an API key
let req = Request::builder()
.method("POST")
.uri("/api/keys")
.header("content-type", "application/json")
.header("authorization", format!("Bearer {token}"))
.body(json_body(serde_json::json!({"name": "temp-key"})))
.unwrap();
let res = app.clone().oneshot(req).await.unwrap();
let body = res.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
let api_key = json["key"].as_str().unwrap().to_string();
let key_id = json["id"].as_i64().unwrap();
// Use the API key (populates cache)
let req = Request::builder()
.uri(format!("/{api_key}/imdb/poster-default/tt0000001.jpg"))
.body(Body::empty())
.unwrap();
let res = app.clone().oneshot(req).await.unwrap();
assert_ne!(res.status(), StatusCode::UNAUTHORIZED);
// Delete the API key via the endpoint (which calls invalidate_all)
let req = Request::builder()
.method("DELETE")
.uri(format!("/api/keys/{key_id}"))
.header("authorization", format!("Bearer {token}"))
.body(Body::empty())
.unwrap();
let res = app.clone().oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
// Ensure cache eviction completes
state.api_key_cache.run_pending_tasks().await;
// Now the API key should be rejected
let req = Request::builder()
.uri(format!("/{api_key}/imdb/poster-default/tt0000001.jpg"))
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
// --- Input validation on auth endpoints ---
#[tokio::test]
async fn setup_rejects_short_password() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.method("POST")
.uri("/api/auth/setup")
.header("content-type", "application/json")
.body(json_body(serde_json::json!({
"username": "admin",
"password": "short"
})))
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn setup_rejects_empty_username() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.method("POST")
.uri("/api/auth/setup")
.header("content-type", "application/json")
.body(json_body(serde_json::json!({
"username": "",
"password": "testpassword123"
})))
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn setup_rejects_username_with_whitespace() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.method("POST")
.uri("/api/auth/setup")
.header("content-type", "application/json")
.body(json_body(serde_json::json!({
"username": "admin user",
"password": "testpassword123"
})))
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
// --- Expired JWT token ---
#[tokio::test]
async fn expired_jwt_rejected() {
let (app, state) = common::setup_test_app().await;
let claims = serde_json::json!({
"sub": "admin",
"exp": 1000000000 // Way in the past (2001)
});
let token = jsonwebtoken::encode(
&jsonwebtoken::Header::default(),
&claims,
&jsonwebtoken::EncodingKey::from_secret(&state.jwt_secret),
)
.unwrap();
let req = Request::builder()
.uri("/api/keys")
.header("authorization", format!("Bearer {token}"))
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
// --- JWT signed with wrong secret ---
#[tokio::test]
async fn jwt_with_wrong_secret_rejected() {
let (app, _state) = common::setup_test_app().await;
let wrong_secret = vec![0xCD; 32];
let exp = (chrono::Utc::now() + chrono::Duration::hours(1)).timestamp() as usize;
let claims = serde_json::json!({
"sub": "admin",
"exp": exp
});
let token = jsonwebtoken::encode(
&jsonwebtoken::Header::default(),
&claims,
&jsonwebtoken::EncodingKey::from_secret(&wrong_secret),
)
.unwrap();
let req = Request::builder()
.uri("/api/keys")
.header("authorization", format!("Bearer {token}"))
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
// --- Poster endpoint with invalid id type ---
#[tokio::test]
async fn poster_endpoint_invalid_id_type() {
let (app, _state) = common::setup_test_app().await;
let token = common::setup_admin(&app).await;
// Create a valid API key
let req = Request::builder()
.method("POST")
.uri("/api/keys")
.header("content-type", "application/json")
.header("authorization", format!("Bearer {token}"))
.body(json_body(serde_json::json!({"name": "test"})))
.unwrap();
let res = app.clone().oneshot(req).await.unwrap();
let body = res.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
let api_key = json["key"].as_str().unwrap();
// Use invalid id type
let req = Request::builder()
.uri(format!("/{api_key}/invalid_type/poster-default/tt0000001.jpg"))
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
// --- Refresh with fabricated token (not in DB) ---
#[tokio::test]
async fn refresh_with_fabricated_token_returns_401() {
let (app, _state) = common::setup_test_app().await;
common::setup_admin(&app).await;
let req = Request::builder()
.method("POST")
.uri("/api/auth/refresh")
.header("cookie", "refresh_token=aabbccdd00112233fabricatedtoken")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
// --- Delete nonexistent API key ---
#[tokio::test]
async fn delete_nonexistent_api_key_succeeds() {
let (app, _state) = common::setup_test_app().await;
let token = common::setup_admin(&app).await;
let req = Request::builder()
.method("DELETE")
.uri("/api/keys/99999")
.header("authorization", format!("Bearer {token}"))
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
}
// --- Path traversal prevention ---
#[tokio::test]
async fn poster_endpoint_rejects_path_traversal() {
let (app, _state) = common::setup_test_app().await;
let token = common::setup_admin(&app).await;
// Create a valid API key
let req = Request::builder()
.method("POST")
.uri("/api/keys")
.header("content-type", "application/json")
.header("authorization", format!("Bearer {token}"))
.body(json_body(serde_json::json!({"name": "test"})))
.unwrap();
let res = app.clone().oneshot(req).await.unwrap();
let body = res.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
let api_key = json["key"].as_str().unwrap();
// Attempt path traversal in id_value
let req = Request::builder()
.uri(format!("/{api_key}/imdb/poster-default/..%2F..%2Fetc%2Fpasswd.jpg"))
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
// --- Error redaction (integration) ---
#[tokio::test]
async fn internal_error_response_is_redacted() {
let (app, _state) = common::setup_test_app().await;
let token = common::setup_admin(&app).await;
// Create a valid API key
let req = Request::builder()
.method("POST")
.uri("/api/keys")
.header("content-type", "application/json")
.header("authorization", format!("Bearer {token}"))
.body(json_body(serde_json::json!({"name": "test"})))
.unwrap();
let res = app.clone().oneshot(req).await.unwrap();
let body = res.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
let api_key = json["key"].as_str().unwrap();
// Request a poster that will fail internally (fake TMDB key)
let req = Request::builder()
.uri(format!("/{api_key}/imdb/poster-default/tt0000001.jpg"))
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
let body = res.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
let error_msg = json["error"].as_str().unwrap();
// Must not leak internal details like URLs, connection errors, etc.
assert_eq!(error_msg, "Internal server error");
}
// --- HSTS header ---
#[tokio::test]
async fn hsts_header_present_when_secure_cookies() {
let (app, _state) = common::setup_test_app_with_options(common::TestAppOptions {
secure_cookies: true,
..Default::default()
})
.await;
let req = Request::builder()
.uri("/api/auth/status")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let hsts = res
.headers()
.get("strict-transport-security")
.and_then(|v| v.to_str().ok());
assert_eq!(hsts, Some("max-age=63072000; includeSubDomains"));
}
#[tokio::test]
async fn hsts_header_absent_when_not_secure() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.uri("/api/auth/status")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert!(res.headers().get("strict-transport-security").is_none());
}
// --- Password max length (integration) ---
#[tokio::test]
async fn setup_rejects_too_long_password() {
let (app, _state) = common::setup_test_app().await;
let long_pw = "a".repeat(257);
let req = Request::builder()
.method("POST")
.uri("/api/auth/setup")
.header("content-type", "application/json")
.body(json_body(serde_json::json!({
"username": "admin",
"password": long_pw
})))
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
// --- Security headers ---
#[tokio::test]
async fn security_headers_present_on_all_responses() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.uri("/api/auth/status")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let xcto = res
.headers()
.get("x-content-type-options")
.and_then(|v| v.to_str().ok());
assert_eq!(xcto, Some("nosniff"), "X-Content-Type-Options should be nosniff");
let xfo = res
.headers()
.get("x-frame-options")
.and_then(|v| v.to_str().ok());
assert_eq!(xfo, Some("DENY"), "X-Frame-Options should be DENY");
}
#[tokio::test]
async fn security_headers_present_on_error_responses() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.uri("/api/keys")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
assert!(
res.headers().get("x-content-type-options").is_some(),
"X-Content-Type-Options should be present on error responses"
);
assert!(
res.headers().get("x-frame-options").is_some(),
"X-Frame-Options should be present on error responses"
);
}
// --- Username max length ---
#[tokio::test]
async fn setup_rejects_too_long_username() {
let (app, _state) = common::setup_test_app().await;
let long_name = "a".repeat(129);
let req = Request::builder()
.method("POST")
.uri("/api/auth/setup")
.header("content-type", "application/json")
.body(json_body(serde_json::json!({
"username": long_name,
"password": "testpassword123"
})))
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
// --- API key name validation ---
#[tokio::test]
async fn create_api_key_rejects_too_long_name() {
let (app, _state) = common::setup_test_app().await;
let token = common::setup_admin(&app).await;
let long_name = "a".repeat(129);
let req = Request::builder()
.method("POST")
.uri("/api/keys")
.header("content-type", "application/json")
.header("authorization", format!("Bearer {token}"))
.body(json_body(serde_json::json!({"name": long_name})))
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn create_api_key_rejects_control_chars_in_name() {
let (app, _state) = common::setup_test_app().await;
let token = common::setup_admin(&app).await;
let req = Request::builder()
.method("POST")
.uri("/api/keys")
.header("content-type", "application/json")
.header("authorization", format!("Bearer {token}"))
.body(json_body(serde_json::json!({"name": "key\u{0000}name"})))
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
// --- Malformed JWT handling ---
#[tokio::test]
async fn truncated_jwt_rejected() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.uri("/api/keys")
.header("authorization", "Bearer eyJhbGciOiJIUzI1NiJ9.truncated")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn jwt_with_none_algorithm_rejected() {
let (app, _state) = common::setup_test_app().await;
use base64::Engine;
let header = base64::engine::general_purpose::URL_SAFE_NO_PAD
.encode(r#"{"alg":"none","typ":"JWT"}"#);
let exp = (chrono::Utc::now() + chrono::Duration::hours(1)).timestamp();
let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
.encode(format!(r#"{{"sub":"admin","exp":{exp}}}"#));
let token = format!("{header}.{payload}.");
let req = Request::builder()
.uri("/api/keys")
.header("authorization", format!("Bearer {token}"))
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn jwt_with_empty_string_rejected() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.uri("/api/keys")
.header("authorization", "Bearer ")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn jwt_with_garbage_rejected() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.uri("/api/keys")
.header("authorization", "Bearer not-a-jwt-at-all")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
// --- Concurrent refresh token reuse ---
#[tokio::test]
async fn concurrent_refresh_token_reuse_at_most_one_succeeds() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.method("POST")
.uri("/api/auth/setup")
.header("content-type", "application/json")
.body(json_body(serde_json::json!({
"username": "admin",
"password": "testpassword123"
})))
.unwrap();
let res = app.clone().oneshot(req).await.unwrap();
let set_cookie = common::extract_set_cookie(res.headers()).unwrap();
let refresh_token = common::extract_refresh_token(&set_cookie).unwrap();
let app1 = app.clone();
let app2 = app.clone();
let rt1 = refresh_token.clone();
let rt2 = refresh_token.clone();
let req1 = Request::builder()
.method("POST")
.uri("/api/auth/refresh")
.header("cookie", format!("refresh_token={rt1}"))
.body(Body::empty())
.unwrap();
let req2 = Request::builder()
.method("POST")
.uri("/api/auth/refresh")
.header("cookie", format!("refresh_token={rt2}"))
.body(Body::empty())
.unwrap();
let (res1, res2) = tokio::join!(app1.oneshot(req1), app2.oneshot(req2));
let status1 = res1.unwrap().status();
let status2 = res2.unwrap().status();
let successes = [status1, status2]
.iter()
.filter(|s| **s == StatusCode::OK)
.count();
assert!(
successes <= 1,
"at most one concurrent refresh should succeed (got {status1}, {status2})"
);
}
// --- Empty/malformed body handling ---
#[tokio::test]
async fn setup_with_empty_body_returns_error() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.method("POST")
.uri("/api/auth/setup")
.header("content-type", "application/json")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert!(
res.status().is_client_error(),
"empty body should return 4xx, got {}",
res.status()
);
}
#[tokio::test]
async fn login_with_empty_body_returns_error() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.method("POST")
.uri("/api/auth/login")
.header("content-type", "application/json")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert!(
res.status().is_client_error(),
"empty body should return 4xx, got {}",
res.status()
);
}
#[tokio::test]
async fn setup_with_wrong_content_type_returns_error() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.method("POST")
.uri("/api/auth/setup")
.header("content-type", "text/plain")
.body(Body::from(r#"{"username":"admin","password":"testpassword123"}"#))
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert!(
res.status().is_client_error(),
"wrong content-type should return 4xx, got {}",
res.status()
);
}
#[tokio::test]
async fn key_login_with_empty_body_returns_error() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.method("POST")
.uri("/api/auth/key-login")
.header("content-type", "application/json")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert!(
res.status().is_client_error(),
"empty body should return 4xx, got {}",
res.status()
);
}
// --- Free API key cannot login ---
#[tokio::test]
async fn free_api_key_cannot_login_via_security() {
let (app, _state) = common::setup_test_app().await;
let token = common::setup_admin(&app).await;
// Enable free key
let req = Request::builder()
.method("PUT")
.uri("/api/admin/settings")
.header("content-type", "application/json")
.header("authorization", format!("Bearer {token}"))
.body(json_body(serde_json::json!({
"image_source": "t",
"free_api_key_enabled": true
})))
.unwrap();
app.clone().oneshot(req).await.unwrap();
let req = Request::builder()
.method("POST")
.uri("/api/auth/key-login")
.header("content-type", "application/json")
.body(json_body(serde_json::json!({"api_key": "t0-free-rpdb"})))
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
// --- Cookie Secure flag behavior ---
#[tokio::test]
async fn cookie_has_secure_flag_in_secure_mode() {
let (app, _state) = common::setup_test_app_with_options(common::TestAppOptions {
secure_cookies: true,
..Default::default()
})
.await;
let req = Request::builder()
.method("POST")
.uri("/api/auth/setup")
.header("content-type", "application/json")
.body(json_body(serde_json::json!({
"username": "admin",
"password": "testpassword123"
})))
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let set_cookie = common::extract_set_cookie(res.headers()).unwrap();
assert!(set_cookie.contains("; Secure"), "cookie should have Secure flag");
}
#[tokio::test]
async fn cookie_lacks_secure_flag_in_insecure_mode() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.method("POST")
.uri("/api/auth/setup")
.header("content-type", "application/json")
.body(json_body(serde_json::json!({
"username": "admin",
"password": "testpassword123"
})))
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let set_cookie = common::extract_set_cookie(res.headers()).unwrap();
assert!(!set_cookie.contains("; Secure"), "cookie should not have Secure flag");
}
// --- Authorization header edge cases ---
#[tokio::test]
async fn auth_without_bearer_prefix_rejected() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.uri("/api/keys")
.header("authorization", "Basic dXNlcjpwYXNz")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn auth_with_no_authorization_header_rejected() {
let (app, _state) = common::setup_test_app().await;
let req = Request::builder()
.uri("/api/keys")
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
// --- Poster endpoint with null byte injection ---
#[tokio::test]
async fn poster_endpoint_rejects_null_bytes_in_id() {
let (app, _state) = common::setup_test_app().await;
let token = common::setup_admin(&app).await;
let req = Request::builder()
.method("POST")
.uri("/api/keys")
.header("content-type", "application/json")
.header("authorization", format!("Bearer {token}"))
.body(json_body(serde_json::json!({"name": "test"})))
.unwrap();
let res = app.clone().oneshot(req).await.unwrap();
let body = res.into_body().collect().await.unwrap().to_bytes();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
let api_key = json["key"].as_str().unwrap();
let req = Request::builder()
.uri(format!("/{api_key}/imdb/poster-default/tt123%00.jpg"))
.body(Body::empty())
.unwrap();
let res = app.oneshot(req).await.unwrap();
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
|