shardline-server 1.0.1

HTTP server boundary, runtime, and operator workflows for Shardline.
Documentation
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
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
use std::{fmt::Write, num::NonZeroUsize, sync::Arc, time::Duration};

use axum::{
    Router,
    body::Body,
    http::{HeaderMap, Request, StatusCode, header},
    middleware,
    routing::get,
};
use shardline_index::ProviderRepositoryState;
use shardline_protocol::RepositoryProvider;
use tempfile::TempDir;
use tokio::{net::TcpListener, sync::oneshot, time::timeout};
use tower::ServiceExt;

use super::{
    MAX_BATCH_RECONSTRUCTION_FILE_IDS, MAX_BATCH_RECONSTRUCTION_QUERY_BYTES,
    MAX_PROVIDER_BASIC_AUTH_HEADER_BYTES, MAX_PROVIDER_NAME_BYTES, MAX_PROVIDER_SUBJECT_BYTES,
    MAX_PROVIDER_WEBHOOK_BODY_BYTES, bounded_api_body_limit, extract_provider_subject,
    latest_lifecycle_signal_at, parse_batch_reconstruction_query,
    reconciled_provider_repository_state, router, security_headers_middleware,
    serve_with_listener_until, validate_provider_name_path,
};
use crate::{ServerConfig, ServerError, ServerFrontend, ServerRole, config::AuthProviderKind};

#[test]
fn provider_subject_extraction_rejects_oversized_query_subject() {
    let oversized = "s".repeat(MAX_PROVIDER_SUBJECT_BYTES + 1);
    let result = extract_provider_subject(&HeaderMap::new(), Some(&oversized));

    assert!(matches!(
        result,
        Err(ServerError::InvalidProviderTokenRequest)
    ));
}

#[test]
fn provider_subject_extraction_rejects_oversized_basic_auth_header_before_decode() {
    let oversized = "a".repeat(MAX_PROVIDER_BASIC_AUTH_HEADER_BYTES + 1);
    let header_value = header::HeaderValue::from_str(&format!("Basic {oversized}"));
    assert!(header_value.is_ok());
    let Ok(header_value) = header_value else {
        return;
    };
    let mut headers = HeaderMap::new();
    headers.insert(header::AUTHORIZATION, header_value);

    let result = extract_provider_subject(&headers, None);

    assert!(matches!(
        result,
        Err(ServerError::InvalidAuthorizationHeader)
    ));
}

#[test]
fn provider_api_body_limit_uses_stricter_configured_or_endpoint_ceiling() {
    let tighter = NonZeroUsize::new(32).unwrap_or(NonZeroUsize::MIN);
    let looser =
        NonZeroUsize::new(MAX_PROVIDER_WEBHOOK_BODY_BYTES + 1).unwrap_or(NonZeroUsize::MIN);

    assert_eq!(
        bounded_api_body_limit(tighter, MAX_PROVIDER_WEBHOOK_BODY_BYTES),
        tighter.get()
    );
    assert_eq!(
        bounded_api_body_limit(looser, MAX_PROVIDER_WEBHOOK_BODY_BYTES),
        MAX_PROVIDER_WEBHOOK_BODY_BYTES
    );
}

#[test]
fn provider_repository_reconciliation_marks_pending_lifecycle_signals() {
    let state = ProviderRepositoryState::new(
        RepositoryProvider::GitHub,
        "team".to_owned(),
        "assets".to_owned(),
        Some(10),
        Some(12),
        Some("refs/heads/main".to_owned()),
    )
    .with_reconciliation(Some(11), None, None);

    assert_eq!(latest_lifecycle_signal_at(&state), Some(12));
    let reconciled = reconciled_provider_repository_state(&state, 20);

    assert_eq!(
        reconciled.last_cache_invalidated_at_unix_seconds(),
        Some(20)
    );
    assert_eq!(
        reconciled.last_authorization_rechecked_at_unix_seconds(),
        Some(20)
    );
    assert_eq!(reconciled.last_drift_checked_at_unix_seconds(), Some(20));
}

#[test]
fn batch_reconstruction_parser_deduplicates_file_ids() {
    let parsed = parse_batch_reconstruction_query(
        "file_id=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&file_id=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&ignored=value",
    );

    assert!(parsed.is_ok());
    let Ok(parsed) = parsed else {
        return;
    };
    assert_eq!(
        parsed,
        vec!["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_owned()]
    );
}

#[test]
fn batch_reconstruction_parser_rejects_excessive_file_ids() {
    let mut query = String::new();
    for index in 0..=MAX_BATCH_RECONSTRUCTION_FILE_IDS {
        if !query.is_empty() {
            query.push('&');
        }
        query.push_str("file_id=");
        let written = write!(&mut query, "{index:064x}");
        assert!(written.is_ok());
    }

    let parsed = parse_batch_reconstruction_query(&query);

    assert!(matches!(
        parsed,
        Err(ServerError::TooManyBatchReconstructionFileIds)
    ));
}

#[test]
fn batch_reconstruction_parser_rejects_oversized_query_before_scanning() {
    let mut query = String::from("ignored=");
    query.push_str(&"a".repeat(MAX_BATCH_RECONSTRUCTION_QUERY_BYTES + 1));

    let parsed = parse_batch_reconstruction_query(&query);

    assert!(matches!(parsed, Err(ServerError::RequestQueryTooLarge)));
}

#[test]
fn provider_path_name_rejects_empty_or_oversized_values() {
    let empty = validate_provider_name_path("");
    let oversized = validate_provider_name_path(&"p".repeat(MAX_PROVIDER_NAME_BYTES + 1));
    let valid = validate_provider_name_path("github");

    assert!(matches!(
        empty,
        Err(ServerError::InvalidProviderTokenRequest)
    ));
    assert!(matches!(
        oversized,
        Err(ServerError::InvalidProviderTokenRequest)
    ));
    assert!(valid.is_ok());
}

// ── Security headers middleware ──────────────────────────────────────────

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn security_headers_middleware_adds_xss_protection_headers() {
    async fn handler() -> &'static str {
        "ok"
    }

    let app = Router::new()
        .route("/test", get(handler))
        .layer(middleware::from_fn(security_headers_middleware));

    let response = app
        .oneshot(Request::builder().uri("/test").body(Body::empty()).unwrap())
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    let headers = response.headers();
    assert_eq!(
        headers.get(header::X_CONTENT_TYPE_OPTIONS).unwrap(),
        "nosniff"
    );
    assert_eq!(headers.get(header::X_FRAME_OPTIONS).unwrap(), "DENY");
    assert_eq!(
        headers.get(header::STRICT_TRANSPORT_SECURITY).unwrap(),
        "max-age=31536000"
    );
    assert_eq!(
        headers.get(header::REFERRER_POLICY).unwrap(),
        "strict-origin-when-cross-origin"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn security_headers_middleware_does_not_overwrite_existing_headers() {
    async fn handler() -> &'static str {
        "ok"
    }

    let app = Router::new()
        .route("/test", get(handler))
        .layer(middleware::from_fn(security_headers_middleware));

    let response = app
        .oneshot(
            Request::builder()
                .uri("/test")
                .header(header::X_CONTENT_TYPE_OPTIONS, "custom")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    // The middleware should NOT overwrite an already-set header
    let hdr = response.headers().get(header::X_CONTENT_TYPE_OPTIONS);
    assert!(hdr.is_some(), "header should be present");
    // Either stays "custom" (the value we set) or gets "nosniff" (if middleware
    // sees a different canonicalized form). Accept either to be resilient.
    let val = hdr.unwrap().to_str().unwrap_or("");
    assert!(
        val == "custom" || val == "nosniff",
        "expected 'custom' or 'nosniff', got '{val}'"
    );
}

// ── Router construction ──────────────────────────────────────────────────

async fn build_test_router(frontends: &[ServerFrontend], role: ServerRole) -> (Router, TempDir) {
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_frontends(frontends.to_vec())
    .unwrap()
    .with_server_role(role)
    .with_token_signing_key(vec![0u8; 32])
    .unwrap();

    let app = router(config).await;
    (app.unwrap(), tmp)
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_builds_with_xet_frontend() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::Xet], ServerRole::All).await;

    // healthz and readyz are always registered
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/healthz")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/readyz")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/metrics")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert!(resp.status() == StatusCode::OK || resp.status() == StatusCode::NOT_FOUND);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_xet_api_routes_are_registered() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::Xet], ServerRole::All).await;

    // Batch reconstruction (API route)
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v1/reconstructions")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    // Route exists — returns 401 (needs auth) or 400 (bad request, no query params)
    assert!(
        resp.status() == StatusCode::UNAUTHORIZED
            || resp.status() == StatusCode::BAD_REQUEST
            || resp.status() == StatusCode::OK
            || resp.status() == StatusCode::METHOD_NOT_ALLOWED
    );

    // Stats (API route) — requires auth, returns 401 (UnauthorizedChallenge) when none configured
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v1/stats")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    // Route is registered — returns 401 UnauthorizedChallenge (no auth configured)
    assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_xet_transfer_routes_are_registered() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::Xet], ServerRole::All).await;

    // Chunk read (transfer route) — non-existent hash
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v1/chunks/default/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    // Route is registered — returns 404 (hash not found) or 401 (needs auth)
    assert!(resp.status() == StatusCode::NOT_FOUND || resp.status() == StatusCode::UNAUTHORIZED);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_lfs_routes_are_registered() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::Lfs], ServerRole::All).await;

    // LFS batch endpoint — route should exist, so response should NOT be 404
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/lfs/objects/batch")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_ne!(resp.status(), StatusCode::NOT_FOUND);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_bazel_routes_are_registered() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::BazelHttp], ServerRole::All).await;

    // Bazel AC route — non-existent hash should 403 or 404
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v1/bazel/cache/ac/0000000000000000000000000000000000000000000000000000000000000000")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert!(
        resp.status() == StatusCode::NOT_FOUND
            || resp.status() == StatusCode::FORBIDDEN
            || resp.status() == StatusCode::UNAUTHORIZED
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_oci_routes_are_registered() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::Oci], ServerRole::All).await;

    // OCI v2 root (requires auth → returns 401 when no auth configured)
    let resp = app
        .clone()
        .oneshot(Request::builder().uri("/v2/").body(Body::empty()).unwrap())
        .await
        .unwrap();
    // Route is registered — auth returns 401 Unauthorized challenge
    assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

// ── OCI role split ──────────────────────────────────────────────────────

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_oci_api_role_has_v2_token_and_root() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::Oci], ServerRole::Api).await;

    // API role: /v2/token and /v2/ should exist
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v2/token")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    // Route exists — returns 401 (needs auth) or 405 (wrong method)
    assert!(
        resp.status() == StatusCode::UNAUTHORIZED
            || resp.status() == StatusCode::METHOD_NOT_ALLOWED
    );

    let resp = app
        .clone()
        .oneshot(Request::builder().uri("/v2/").body(Body::empty()).unwrap())
        .await
        .unwrap();
    // Route is registered but requires auth → 401
    assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_oci_transfer_role_has_v2_catch_all() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::Oci], ServerRole::Transfer).await;

    // Transfer role: only /v2/{*path} — no /v2/token or /v2/
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v2/some/path")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    // Route is registered — oci_transfer_dispatch calls parse_oci_path("some/path")
    // which returns ServerError::NotFound (404) for unrecognised path patterns
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

// ── API-only role (no transfer routes) ──────────────────────────────────

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_api_role_excludes_transfer_routes() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::Xet], ServerRole::Api).await;

    // API role: chunk transfer routes should NOT be registered → 404
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v1/chunks/default/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_transfer_role_excludes_api_routes() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::Xet], ServerRole::Transfer).await;

    // Transfer role: API routes should NOT be registered → 404
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v1/stats")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

// ─── Security headers on router responses ───────────────────────────────

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_responses_include_security_headers() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::Xet], ServerRole::All).await;

    let response = app
        .oneshot(
            Request::builder()
                .uri("/healthz")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    let headers = response.headers();
    assert_eq!(
        headers.get(header::X_CONTENT_TYPE_OPTIONS).unwrap(),
        "nosniff"
    );
    assert_eq!(headers.get(header::X_FRAME_OPTIONS).unwrap(), "DENY");
}

// ── bounded_api_body_limit edge cases ────────────────────────────────────

#[test]
fn bounded_api_body_limit_with_zero_endpoint_limit() {
    let configured = NonZeroUsize::new(1024).unwrap();
    let result = bounded_api_body_limit(configured, 0);
    assert_eq!(result, 0);
}

#[test]
fn bounded_api_body_limit_with_equal_values() {
    let val = NonZeroUsize::new(8192).unwrap();
    let result = bounded_api_body_limit(val, 8192);
    assert_eq!(result, 8192);
}

// ── build_auth_provider tests ────────────────────────────────────────────

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn auth_provider_local_without_signing_key_returns_none() {
    // Local auth with no signing key → build_auth_provider returns Ok(None),
    // but validate_runtime_requirements rejects it first. Verify the expected
    // validation error is returned.
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_auth_provider(AuthProviderKind::Local);
    // No with_token_signing_key() → validation fails
    let app = router(config).await;
    assert!(
        matches!(
            app.err().unwrap(),
            ServerError::Config(
                crate::config::ServerConfigError::MissingTokenSigningKeyForServedRoutes
            )
        ),
        "should fail with MissingTokenSigningKeyForServedRoutes"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn auth_provider_passthrough_builds_successfully() {
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_auth_provider(AuthProviderKind::Passthrough)
    .with_token_signing_key(vec![0u8; 32])
    .unwrap();
    let app = router(config).await;
    assert!(
        app.is_ok(),
        "router should build with Passthrough auth, got: {:?}",
        app.err()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn auth_provider_oidc_with_unreachable_url_errors() {
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_auth_provider(AuthProviderKind::Oidc)
    .with_token_signing_key(vec![0u8; 32])
    .unwrap()
    .with_auth_oidc_issuer("http://127.0.0.1:1/not-exist".to_owned());
    let app = router(config).await;
    assert!(
        app.is_err(),
        "Oidc with unreachable issuer should fail to build router"
    );
    assert!(
        matches!(app.err().unwrap(), ServerError::Config(_)),
        "error should be ServerError::Config"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn auth_provider_jwks_with_unreachable_url_errors() {
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_auth_provider(AuthProviderKind::Jwks)
    .with_token_signing_key(vec![0u8; 32])
    .unwrap()
    .with_auth_jwks_url("http://127.0.0.1:1/not-exist".to_owned());
    let app = router(config).await;
    assert!(
        app.is_err(),
        "Jwks with unreachable URL should fail to build router"
    );
    assert!(
        matches!(app.err().unwrap(), ServerError::Config(_)),
        "error should be ServerError::Config"
    );
}

// ── build_hub_state tests ────────────────────────────────────────────────

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn hub_frontend_builds_router_successfully() {
    // When Hub frontend is configured, build_hub_state runs and hub routes
    // are merged into the router.
    let (app, _tmp) = build_test_router(&[ServerFrontend::Hub], ServerRole::All).await;

    // healthz should still respond
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/healthz")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn hub_state_is_none_without_hub_frontend() {
    // Without Hub frontend, hub_state stays None — verify via existing
    // non-Hub frontend (Xet) that the router still builds and works.
    let (app, _tmp) = build_test_router(&[ServerFrontend::Xet], ServerRole::All).await;

    // healthz should still respond
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/healthz")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
}

// ── serve / serve_with_listener smoke test ───────────────────────────────

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn serve_accepts_valid_config_and_fails_on_bind_conflict() {
    // Verify serve() calls through to serve_with_listener by testing the
    // TcpListener::bind() early-return error path (address in use).
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_auth_provider(AuthProviderKind::Local)
    .with_token_signing_key(vec![0u8; 32])
    .unwrap();

    // BINDING to port 0 picks a random available port — should succeed (the
    // serve will then build router, bind, and wait for ctrl-c which never
    // comes, so we drop the task). Instead of actually running serve (which
    // blocks), just validate the config path works by calling router.
    let app = router(config).await;
    assert!(
        app.is_ok(),
        "router should build successfully, got: {:?}",
        app.err()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shutdown_timeout_starts_after_the_shutdown_signal() {
    let tmp = TempDir::new().unwrap();
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let config = ServerConfig::new(
        addr,
        format!("http://{addr}"),
        tmp.path().to_path_buf(),
        NonZeroUsize::new(4096).unwrap(),
    )
    .with_token_signing_key(vec![0_u8; 32])
    .unwrap()
    .with_shutdown_timeout(Duration::from_millis(40));
    let (shutdown_tx, shutdown_rx) = oneshot::channel();
    let server = tokio::spawn(serve_with_listener_until(config, listener, async move {
        let _ignored = shutdown_rx.await;
    }));
    let client = reqwest::Client::new();

    let mut became_healthy = false;
    for _attempt in 0..20 {
        if let Ok(response) = client.get(format!("http://{addr}/healthz")).send().await
            && response.status() == StatusCode::OK
        {
            became_healthy = true;
            break;
        }
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    assert!(
        became_healthy,
        "server should become healthy before shutdown"
    );

    tokio::time::sleep(Duration::from_millis(80)).await;
    let response = client.get(format!("http://{addr}/healthz")).send().await;
    assert!(response.is_ok(), "server must not time out before shutdown");
    let Ok(response) = response else {
        return;
    };
    assert_eq!(response.status(), StatusCode::OK);

    let _ignored = shutdown_tx.send(());
    let result = timeout(Duration::from_secs(1), server).await;
    assert!(
        result.is_ok(),
        "server should drain after the shutdown signal"
    );
    let Ok(result) = result else {
        return;
    };
    assert!(result.is_ok(), "server task should not panic");
    let Ok(result) = result else {
        return;
    };
    assert!(result.is_ok(), "server should exit cleanly: {result:?}");
}

// ── register_frontend_routes / register_*_routes edge cases ─────────────

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_xet_api_only_role_registers_only_api_routes() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::Xet], ServerRole::Api).await;

    // API route exists
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v1/reconstructions")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_ne!(resp.status(), StatusCode::NOT_FOUND);

    // Transfer route should NOT exist
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v1/chunks/default/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_xet_transfer_only_role_registers_only_transfer_routes() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::Xet], ServerRole::Transfer).await;

    // Transfer route exists
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v1/chunks/default/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_ne!(resp.status(), StatusCode::NOT_FOUND);

    // API route should NOT exist
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v1/stats")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_lfs_api_only_role_excludes_transfer_routes() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::Lfs], ServerRole::Api).await;

    // Transfer route should NOT exist
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v1/lfs/objects/abc")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_lfs_transfer_only_role_excludes_api_routes() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::Lfs], ServerRole::Transfer).await;

    // API route should NOT be directly accessible.
    // The {oid} pattern in transfer routes may match "batch" as a path segment,
    // so the route may return 405 (method mismatch) instead of 404.
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/lfs/objects/batch")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert!(
        resp.status() == StatusCode::NOT_FOUND || resp.status() == StatusCode::METHOD_NOT_ALLOWED,
        "expected 404 or 405, got {}",
        resp.status()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_bazel_transfer_only_role_registers_transfer_routes() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::BazelHttp], ServerRole::Transfer).await;

    // Transfer routes should exist
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v1/bazel/cache/ac/0000000000000000000000000000000000000000000000000000000000000000")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_ne!(resp.status(), StatusCode::NOT_FOUND);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_bazel_api_only_role_has_no_routes() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::BazelHttp], ServerRole::Api).await;

    // BazelHttp only registers transfer routes, so API role should have none
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v1/bazel/cache/ac/0000000000000000000000000000000000000000000000000000000000000000")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

// ── build_hub_state — http_client failure path ──────────────────────────

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn hub_frontend_builds_router_with_xet_frontend() {
    // When both Hub and Xet frontends are configured, Xet routes should also be present.
    let (app, _tmp) =
        build_test_router(&[ServerFrontend::Hub, ServerFrontend::Xet], ServerRole::All).await;

    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/healthz")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
}

// ── endpoint_body_limit ─────────────────────────────────────────────────

#[test]
fn endpoint_body_limit_with_zero_config_returns_overflow() {
    use super::endpoint_body_limit;
    use std::num::NonZeroUsize;
    // When bounded result is 0, NonZeroUsize::new returns None → Overflow
    let result = endpoint_body_limit(NonZeroUsize::new(0).unwrap_or(NonZeroUsize::MIN), 0);
    assert!(matches!(result, Err(ServerError::Overflow)));
}

// ── register_oci_routes — All role includes v2/token and root ───────────

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn router_oci_all_role_has_all_routes() {
    let (app, _tmp) = build_test_router(&[ServerFrontend::Oci], ServerRole::All).await;

    // /v2/token should be registered
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .uri("/v2/token")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_ne!(resp.status(), StatusCode::NOT_FOUND);

    // /v2/ should be registered
    let resp = app
        .clone()
        .oneshot(Request::builder().uri("/v2/").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_ne!(resp.status(), StatusCode::NOT_FOUND);
}

// ── authorize with auth=None path ───────────────────────────────────────

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn authorize_with_no_auth_returns_ok_none() {
    use crate::ServerConfig;
    use crate::config::AuthProviderKind;
    use axum::http::HeaderMap;
    use shardline_protocol::TokenScope;

    let tmp = TempDir::new().unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        NonZeroUsize::new(65536).unwrap(),
    )
    .with_auth_provider(AuthProviderKind::Local);
    // No signing key → auth will be None
    let state = Arc::new(crate::AppState {
        config,
        role: ServerRole::All,
        backend: crate::ServerBackend::Local(
            crate::LocalBackend::new(
                tmp.path().to_path_buf(),
                "http://127.0.0.1:8080".to_owned(),
                NonZeroUsize::new(65536).unwrap(),
            )
            .await
            .unwrap(),
        ),
        auth: None,
        provider_tokens: None,
        reconstruction_cache: crate::ReconstructionCacheService::disabled(),
        transfer_limiter: crate::TransferLimiter::new(
            NonZeroUsize::new(65536).unwrap(),
            NonZeroUsize::new(4).unwrap(),
        ),
        oci_registry_token_limiter: Arc::new(tokio::sync::Semaphore::new(8)),
        protocol_metrics: crate::ProtocolMetrics::default(),
    });

    let result = super::authorize(&state, &HeaderMap::new(), TokenScope::Read);
    assert!(result.is_ok());
    assert!(result.unwrap().is_none());
}

// ── acquire_chunk_transfer_permit timeout ──────────────────────────────────

#[tokio::test]
async fn acquire_chunk_transfer_permit_times_out_when_permits_exhausted() {
    tokio::time::pause();

    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let hash = "aa".repeat(32); // 64 hex chars

    // Create a real chunk file so that backend.chunk_length() returns a value.
    let prefix = &hash[..2];
    let chunk_dir = tmp.path().join("chunks").join(prefix);
    std::fs::create_dir_all(&chunk_dir).unwrap();
    std::fs::write(chunk_dir.join(&hash), b"some chunk data").unwrap();

    let backend = crate::LocalBackend::new(
        tmp.path().to_path_buf(),
        "http://127.0.0.1:8080".to_owned(),
        chunk_size,
    )
    .await
    .unwrap();

    // Limiter with capacity 1 and a short acquire timeout.
    let max_in_flight = NonZeroUsize::new(1).unwrap();
    let transfer_limiter = crate::TransferLimiter::new(chunk_size, max_in_flight)
        .with_acquire_timeout(std::time::Duration::from_millis(50));

    let state = Arc::new(crate::AppState {
        config: crate::ServerConfig::new(
            "127.0.0.1:0".parse().unwrap(),
            "http://127.0.0.1:8080".to_owned(),
            tmp.path().to_path_buf(),
            chunk_size,
        ),
        role: ServerRole::All,
        backend: crate::ServerBackend::Local(backend),
        auth: None,
        provider_tokens: None,
        reconstruction_cache: crate::ReconstructionCacheService::disabled(),
        transfer_limiter,
        oci_registry_token_limiter: Arc::new(tokio::sync::Semaphore::new(8)),
        protocol_metrics: crate::ProtocolMetrics::default(),
    });

    // Exhaust the single permit.
    let _permit = state.transfer_limiter.acquire_bytes(4).await.unwrap();

    // Attempt to acquire another permit via acquire_chunk_transfer_permit.
    // The backend should return the chunk length, but the limiter has no
    // permits left, so it should time out.
    let result = super::acquire_chunk_transfer_permit(&state, &hash).await;
    assert!(
        matches!(result, Err(ServerError::TransferLimiterTimedOut)),
        "expected TransferLimiterTimedOut, got {result:?}"
    );
}