ferro-oci-server 1.0.0

OCI Distribution Specification v1.1 server-side primitives — manifest / blob / tag / referrers handlers, chunked uploads, in-memory metadata plane. Backed by ferro-blob-store. Extracted from the Ferro ecosystem.
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
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
// SPDX-License-Identifier: Apache-2.0
//! In-process edge-case coverage for the OCI handlers.
//!
//! These tests drive the full [`router`] (plus probe routes) through
//! `tower::oneshot`, exercising the error / pagination / method-not-
//! allowed / empty-descriptor / cancellation paths that the happy-path
//! conformance smoke test does not reach.

#![allow(clippy::too_many_lines)]

use std::sync::Arc;

use axum::Router;
use axum::body::{Body, to_bytes};
use axum::http::{Method, Request, StatusCode, header};
use ferro_blob_store::{Digest, InMemoryBlobStore, SharedBlobStore};
use ferro_oci_server::{AppState, InMemoryRegistryMeta, probe_routes, router};
use serde_json::{Value, json};
use tower::ServiceExt;

/// Well-known OCI empty descriptor digest (`{}`).
const EMPTY_DIGEST: &str = "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a";

fn app() -> Router {
    let blob_store: SharedBlobStore = Arc::new(InMemoryBlobStore::new());
    let registry = Arc::new(InMemoryRegistryMeta::new());
    let state = AppState::new(blob_store, registry);
    router(state).merge(probe_routes())
}

async fn send(app: &Router, req: Request<Body>) -> (StatusCode, axum::http::HeaderMap, Vec<u8>) {
    let resp = app.clone().oneshot(req).await.expect("response");
    let status = resp.status();
    let headers = resp.headers().clone();
    let body = to_bytes(resp.into_body(), 1 << 20).await.expect("body");
    (status, headers, body.to_vec())
}

fn get(uri: &str) -> Request<Body> {
    Request::builder()
        .method(Method::GET)
        .uri(uri)
        .body(Body::empty())
        .expect("req")
}

fn method(m: Method, uri: &str, body: Body) -> Request<Body> {
    Request::builder()
        .method(m)
        .uri(uri)
        .body(body)
        .expect("req")
}

fn assert_error_code(body: &[u8], expected: &str) {
    let v: Value = serde_json::from_slice(body).expect("error json");
    assert_eq!(v["errors"][0]["code"], expected, "body={v}");
}

// ---- blob.rs ------------------------------------------------------------

#[tokio::test]
async fn blob_get_missing_returns_404_blob_unknown() {
    let app = app();
    let digest = Digest::sha256_of(b"absent").to_string();
    let (status, _h, body) = send(&app, get(&format!("/v2/repo/blobs/{digest}"))).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_error_code(&body, "BLOB_UNKNOWN");
}

#[tokio::test]
async fn blob_get_invalid_digest_returns_400() {
    let app = app();
    let (status, _h, body) = send(&app, get("/v2/repo/blobs/not-a-digest")).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_error_code(&body, "DIGEST_INVALID");
}

#[tokio::test]
async fn blob_get_empty_descriptor_served_synthetically() {
    let app = app();
    let (status, headers, body) = send(&app, get(&format!("/v2/repo/blobs/{EMPTY_DIGEST}"))).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, b"{}");
    assert_eq!(headers[header::CONTENT_LENGTH], "2");
    assert!(headers.contains_key("docker-content-digest"));
}

#[tokio::test]
async fn blob_head_empty_descriptor_ok_no_body() {
    let app = app();
    let (status, headers, body) = send(
        &app,
        method(Method::HEAD, &format!("/v2/repo/blobs/{EMPTY_DIGEST}"), Body::empty()),
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.is_empty());
    assert_eq!(headers[header::CONTENT_LENGTH], "2");
}

#[tokio::test]
async fn blob_head_missing_returns_404() {
    let app = app();
    let digest = Digest::sha256_of(b"absent-head").to_string();
    let (status, _h, _b) = send(
        &app,
        method(Method::HEAD, &format!("/v2/repo/blobs/{digest}"), Body::empty()),
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn blob_delete_existing_then_missing() {
    let app = app();
    // Upload a blob monolithically so it exists.
    let payload = b"deletable-bytes";
    let digest = Digest::sha256_of(payload).to_string();
    let (status, _h, _b) = send(
        &app,
        method(
            Method::POST,
            &format!("/v2/repo/blobs/uploads/?digest={digest}"),
            Body::from(&payload[..]),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    // Delete it → 202.
    let (status, _h, _b) = send(
        &app,
        method(Method::DELETE, &format!("/v2/repo/blobs/{digest}"), Body::empty()),
    )
    .await;
    assert_eq!(status, StatusCode::ACCEPTED);

    // Deleting again → 404 BLOB_UNKNOWN.
    let (status, _h, body) = send(
        &app,
        method(Method::DELETE, &format!("/v2/repo/blobs/{digest}"), Body::empty()),
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_error_code(&body, "BLOB_UNKNOWN");
}

#[tokio::test]
async fn blob_get_invalid_name_returns_400() {
    let app = app();
    // Upper-case repository name is invalid per OCI name grammar.
    let (status, _h, body) = send(&app, get(&format!("/v2/Bad_NAME/blobs/{EMPTY_DIGEST}"))).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_error_code(&body, "NAME_INVALID");
}

// ---- blob_upload.rs -----------------------------------------------------

#[tokio::test]
async fn monolithic_upload_digest_mismatch_returns_400() {
    let app = app();
    let wrong = Digest::sha256_of(b"something-else").to_string();
    let (status, _h, body) = send(
        &app,
        method(
            Method::POST,
            &format!("/v2/repo/blobs/uploads/?digest={wrong}"),
            Body::from(&b"actual-bytes"[..]),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_error_code(&body, "DIGEST_INVALID");
}

#[tokio::test]
async fn monolithic_upload_bad_digest_string_returns_400() {
    let app = app();
    let (status, _h, body) = send(
        &app,
        method(
            Method::POST,
            "/v2/repo/blobs/uploads/?digest=not-a-digest",
            Body::from(&b"x"[..]),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_error_code(&body, "DIGEST_INVALID");
}

#[tokio::test]
async fn start_upload_then_get_status_then_cancel() {
    let app = app();
    // Start a session.
    let (status, headers, _b) =
        send(&app, method(Method::POST, "/v2/repo/blobs/uploads/", Body::empty())).await;
    assert_eq!(status, StatusCode::ACCEPTED);
    let location = headers[header::LOCATION].to_str().unwrap().to_owned();
    assert!(location.contains("/blobs/uploads/"));

    // GET upload status → 204 with Range header.
    let (status, headers, _b) = send(&app, get(&location)).await;
    assert_eq!(status, StatusCode::NO_CONTENT);
    assert!(headers.contains_key(header::RANGE));

    // Cancel → 204.
    let (status, _h, _b) =
        send(&app, method(Method::DELETE, &location, Body::empty())).await;
    assert_eq!(status, StatusCode::NO_CONTENT);

    // Cancel again → unknown upload (404).
    let (status, _h, body) =
        send(&app, method(Method::DELETE, &location, Body::empty())).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_error_code(&body, "BLOB_UPLOAD_UNKNOWN");
}

#[tokio::test]
async fn get_status_for_unknown_upload_returns_404() {
    let app = app();
    let (status, _h, body) = send(&app, get("/v2/repo/blobs/uploads/does-not-exist")).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_error_code(&body, "BLOB_UPLOAD_UNKNOWN");
}

#[tokio::test]
async fn patch_unknown_upload_returns_404() {
    let app = app();
    let (status, _h, body) = send(
        &app,
        method(
            Method::PATCH,
            "/v2/repo/blobs/uploads/ghost",
            Body::from(&b"chunk"[..]),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_error_code(&body, "BLOB_UPLOAD_UNKNOWN");
}

#[tokio::test]
async fn patch_out_of_order_content_range_returns_416() {
    let app = app();
    let (_s, headers, _b) =
        send(&app, method(Method::POST, "/v2/repo/blobs/uploads/", Body::empty())).await;
    let location = headers[header::LOCATION].to_str().unwrap().to_owned();
    // Declare a chunk that starts at 50 even though offset is 0.
    let req = Request::builder()
        .method(Method::PATCH)
        .uri(&location)
        .header(header::CONTENT_RANGE, "50-99")
        .body(Body::from(&b"data"[..]))
        .expect("req");
    let (status, _h, body) = send(&app, req).await;
    assert_eq!(status, StatusCode::RANGE_NOT_SATISFIABLE);
    assert_error_code(&body, "BLOB_UPLOAD_INVALID");
}

#[tokio::test]
async fn patch_malformed_content_range_returns_400() {
    let app = app();
    let (_s, headers, _b) =
        send(&app, method(Method::POST, "/v2/repo/blobs/uploads/", Body::empty())).await;
    let location = headers[header::LOCATION].to_str().unwrap().to_owned();
    let req = Request::builder()
        .method(Method::PATCH)
        .uri(&location)
        .header(header::CONTENT_RANGE, "garbage")
        .body(Body::from(&b"data"[..]))
        .expect("req");
    let (status, _h, body) = send(&app, req).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_error_code(&body, "BLOB_UPLOAD_INVALID");
}

#[tokio::test]
async fn patch_full_u64_content_range_with_empty_body_rejected_no_panic() {
    // R2-2: `Content-Range: 0-18446744073709551615` (0-u64::MAX) makes the
    // inclusive length `end - start + 1` overflow. In a debug build the
    // naive arithmetic would panic; in release it wraps to 0, which would
    // spuriously match an empty body and let the chunk "succeed". The
    // handler must reject the range as BLOB_UPLOAD_INVALID without
    // panicking. (Run under debug to exercise the overflow-panic path.)
    let app = app();
    let (_s, headers, _b) =
        send(&app, method(Method::POST, "/v2/repo/blobs/uploads/", Body::empty())).await;
    let location = headers[header::LOCATION].to_str().unwrap().to_owned();
    let req = Request::builder()
        .method(Method::PATCH)
        .uri(&location)
        .header(header::CONTENT_RANGE, format!("0-{}", u64::MAX))
        .body(Body::empty())
        .expect("req");
    let (status, _h, body) = send(&app, req).await;
    assert_eq!(status, StatusCode::RANGE_NOT_SATISFIABLE);
    assert_error_code(&body, "BLOB_UPLOAD_INVALID");
}

#[tokio::test]
async fn finish_upload_missing_digest_param_returns_400() {
    let app = app();
    let (_s, headers, _b) =
        send(&app, method(Method::POST, "/v2/repo/blobs/uploads/", Body::empty())).await;
    let location = headers[header::LOCATION].to_str().unwrap().to_owned();
    // PUT with no ?digest=.
    let (status, _h, body) =
        send(&app, method(Method::PUT, &location, Body::from(&b"final"[..]))).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_error_code(&body, "DIGEST_INVALID");
}

#[tokio::test]
async fn finish_unknown_upload_returns_404() {
    let app = app();
    let digest = Digest::sha256_of(b"whatever").to_string();
    let (status, _h, body) = send(
        &app,
        method(
            Method::PUT,
            &format!("/v2/repo/blobs/uploads/ghost?digest={digest}"),
            Body::empty(),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_error_code(&body, "BLOB_UPLOAD_UNKNOWN");
}

#[tokio::test]
async fn upload_invalid_name_returns_400() {
    let app = app();
    let (status, _h, body) =
        send(&app, method(Method::POST, "/v2/BAD/blobs/uploads/", Body::empty())).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_error_code(&body, "NAME_INVALID");
}

/// Start an upload session and return its `Location` URL.
async fn start_session(app: &Router, name: &str) -> String {
    let (status, headers, _b) = send(
        app,
        method(Method::POST, &format!("/v2/{name}/blobs/uploads/"), Body::empty()),
    )
    .await;
    assert_eq!(status, StatusCode::ACCEPTED, "start upload session");
    headers[header::LOCATION].to_str().unwrap().to_owned()
}

#[tokio::test]
async fn monolithic_upload_matching_digest_is_created() {
    // Positive boundary for the integrity check
    // `actual.algo() == digest.algo() && actual.hex() != digest.hex()`:
    // a CORRECT digest must yield 201 Created and the blob must then be
    // retrievable with exactly the bytes pushed. Paired with the
    // `monolithic_upload_digest_mismatch_returns_400` test, this pins the
    // `==`/`!=` algo comparison (mutating `==` to `!=` would accept a
    // mismatched digest, which the mismatch test catches).
    let app = app();
    let payload = b"correct-monolithic-bytes";
    let digest = Digest::sha256_of(payload).to_string();
    let (status, _h, _b) = send(
        &app,
        method(
            Method::POST,
            &format!("/v2/repo/blobs/uploads/?digest={digest}"),
            Body::from(&payload[..]),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED, "correct digest ⇒ 201");
    // Round-trip: the stored bytes are exactly what we pushed.
    let (status, _h, body) = send(&app, get(&format!("/v2/repo/blobs/{digest}"))).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, payload, "blob round-trips byte-for-byte");
}

#[tokio::test]
async fn chunked_finish_appends_final_chunk_body() {
    // `finish_upload` appends the PUT body when `!body.is_empty()`
    // (line ~320). Deleting the `!` would skip the real final chunk, so
    // the recomputed digest would not match and the PUT would fail.
    // Here the WHOLE blob is delivered as the final-PUT body (no prior
    // PATCH), so the append-on-finish path is load-bearing.
    let app = app();
    let location = start_session(&app, "repo").await;
    let payload = b"finalized-in-one-put";
    let digest = Digest::sha256_of(payload).to_string();
    let (status, _h, _b) = send(
        &app,
        method(
            Method::PUT,
            &format!("{location}?digest={digest}"),
            Body::from(&payload[..]),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED, "final-chunk PUT ⇒ 201");
    // The exact bytes must be retrievable.
    let (status, _h, body) = send(&app, get(&format!("/v2/repo/blobs/{digest}"))).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, payload, "final-chunk bytes were appended and stored");
}

#[tokio::test]
async fn chunked_finish_with_wrong_digest_returns_400() {
    // `finish_upload`'s digest check
    // `declared.algo() == actual.algo() && actual.hex() != declared.hex()`
    // (line ~350). A PUT declaring the wrong digest must be rejected with
    // 400 DIGEST_INVALID. Mutating `==` to `!=` would skip verification
    // (both sha256) and wrongly accept the mismatched bytes.
    let app = app();
    let location = start_session(&app, "repo").await;
    let wrong = Digest::sha256_of(b"some-other-content").to_string();
    let (status, _h, body) = send(
        &app,
        method(
            Method::PUT,
            &format!("{location}?digest={wrong}"),
            Body::from(&b"actually-these-bytes"[..]),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "wrong digest ⇒ 400");
    assert_error_code(&body, "DIGEST_INVALID");
}

#[tokio::test]
async fn chunked_finish_increments_blob_gauge_for_new_blob() {
    // `finish_upload` increments the distinct-blobs gauge only when the
    // blob is NOT already present: `if !already_present { inc }`
    // (line ~365). Deleting the `!` would increment only for duplicates,
    // so a brand-new blob completed via the chunked PUT path would leave
    // the gauge at 0. Drive the gauge through `/metrics` and assert it
    // reaches 1 after finishing a fresh blob.
    let blob_store: SharedBlobStore = Arc::new(InMemoryBlobStore::new());
    let registry = Arc::new(InMemoryRegistryMeta::new());
    let state = AppState::new(blob_store, registry);
    let blob_count = state.blob_count_handle();
    let app = ferro_oci_server::instrument(router(state), ferro_oci_server::Metrics::new(), blob_count);

    let location = start_session(&app, "repo").await;
    let payload = b"freshly-chunk-finished-blob";
    let digest = Digest::sha256_of(payload).to_string();
    let (status, _h, _b) = send(
        &app,
        method(
            Method::PUT,
            &format!("{location}?digest={digest}"),
            Body::from(&payload[..]),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED);

    let (_s, _h, body) = send(&app, get("/metrics")).await;
    let text = String::from_utf8(body).expect("utf8");
    let counted = text
        .lines()
        .any(|l| l == "ferrooci_storage_blobs 1");
    assert!(
        counted,
        "a new blob finished via chunked PUT must increment the gauge to 1:\n{text}"
    );
}

// ---- catalog.rs + tags.rs ----------------------------------------------

#[tokio::test]
async fn catalog_empty_is_ok_with_no_repositories() {
    let app = app();
    let (status, _h, body) = send(&app, get("/v2/_catalog")).await;
    assert_eq!(status, StatusCode::OK);
    let v: Value = serde_json::from_slice(&body).expect("json");
    assert_eq!(v["repositories"].as_array().expect("arr").len(), 0);
}

#[tokio::test]
async fn catalog_pagination_emits_link_header() {
    let app = app();
    // Push three tiny manifests in distinct repos so the catalog has
    // entries; paginate with n=1 to force the Link header.
    for repo in ["a-repo", "b-repo", "c-repo"] {
        push_min_manifest(&app, repo, "latest").await;
    }
    let (status, headers, body) = send(&app, get("/v2/_catalog?n=1")).await;
    assert_eq!(status, StatusCode::OK);
    let v: Value = serde_json::from_slice(&body).expect("json");
    assert_eq!(v["repositories"].as_array().unwrap().len(), 1);
    assert!(
        headers.contains_key(header::LINK),
        "n=1 over 3 repos must emit a next Link"
    );
}

#[tokio::test]
async fn tags_list_pagination_emits_link_header() {
    let app = app();
    for tag in ["v1", "v2", "v3"] {
        push_min_manifest(&app, "tagrepo", tag).await;
    }
    let (status, headers, body) = send(&app, get("/v2/tagrepo/tags/list?n=1")).await;
    assert_eq!(status, StatusCode::OK);
    let v: Value = serde_json::from_slice(&body).expect("json");
    assert_eq!(v["name"], "tagrepo");
    assert_eq!(v["tags"].as_array().unwrap().len(), 1);
    assert!(headers.contains_key(header::LINK));
}

#[tokio::test]
async fn tags_list_invalid_name_returns_400() {
    let app = app();
    let (status, _h, body) = send(&app, get("/v2/BAD/tags/list")).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_error_code(&body, "NAME_INVALID");
}

// ---- manifest.rs --------------------------------------------------------

/// Push a minimal image manifest referencing only the empty descriptor.
async fn push_min_manifest(app: &Router, name: &str, reference: &str) -> Digest {
    let manifest = json!({
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.manifest.v1+json",
        "config": {
            "mediaType": "application/vnd.oci.image.config.v1+json",
            "digest": EMPTY_DIGEST,
            "size": 2
        },
        "layers": []
    });
    let body = serde_json::to_vec(&manifest).expect("ser");
    let digest = Digest::sha256_of(&body);
    let req = Request::builder()
        .method(Method::PUT)
        .uri(format!("/v2/{name}/manifests/{reference}"))
        .header(
            header::CONTENT_TYPE,
            "application/vnd.oci.image.manifest.v1+json",
        )
        .body(Body::from(body))
        .expect("req");
    let (status, _h, _b) = send(app, req).await;
    assert_eq!(status, StatusCode::CREATED, "manifest push for {name}:{reference}");
    digest
}

#[tokio::test]
async fn manifest_put_missing_content_type_returns_400() {
    let app = app();
    let req = Request::builder()
        .method(Method::PUT)
        .uri("/v2/repo/manifests/latest")
        .body(Body::from(&b"{}"[..]))
        .expect("req");
    let (status, _h, body) = send(&app, req).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_error_code(&body, "MANIFEST_INVALID");
}

#[tokio::test]
async fn manifest_put_unsupported_media_type_returns_400() {
    let app = app();
    let req = Request::builder()
        .method(Method::PUT)
        .uri("/v2/repo/manifests/latest")
        .header(header::CONTENT_TYPE, "text/plain")
        .body(Body::from(&b"{}"[..]))
        .expect("req");
    let (status, _h, body) = send(&app, req).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_error_code(&body, "MANIFEST_INVALID");
}

#[tokio::test]
async fn manifest_put_invalid_json_returns_400() {
    let app = app();
    let req = Request::builder()
        .method(Method::PUT)
        .uri("/v2/repo/manifests/latest")
        .header(
            header::CONTENT_TYPE,
            "application/vnd.oci.image.manifest.v1+json",
        )
        .body(Body::from(&b"{not json"[..]))
        .expect("req");
    let (status, _h, body) = send(&app, req).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert_error_code(&body, "MANIFEST_INVALID");
}

#[tokio::test]
async fn manifest_put_missing_referenced_layer_blob_returns_404() {
    let app = app();
    // Manifest references a layer blob that was never uploaded.
    let missing = Digest::sha256_of(b"never-uploaded-layer").to_string();
    let manifest = json!({
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.manifest.v1+json",
        "config": { "mediaType": "application/vnd.oci.image.config.v1+json", "digest": EMPTY_DIGEST, "size": 2 },
        "layers": [ { "mediaType": "application/vnd.oci.image.layer.v1.tar", "digest": missing, "size": 10 } ]
    });
    let req = Request::builder()
        .method(Method::PUT)
        .uri("/v2/repo/manifests/latest")
        .header(
            header::CONTENT_TYPE,
            "application/vnd.oci.image.manifest.v1+json",
        )
        .body(Body::from(serde_json::to_vec(&manifest).unwrap()))
        .expect("req");
    let (status, _h, body) = send(&app, req).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_error_code(&body, "MANIFEST_BLOB_UNKNOWN");
}

#[tokio::test]
async fn image_index_missing_child_returns_404() {
    let app = app();
    let missing = Digest::sha256_of(b"absent-child-manifest").to_string();
    let index = json!({
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.index.v1+json",
        "manifests": [ { "mediaType": "application/vnd.oci.image.manifest.v1+json", "digest": missing, "size": 5 } ]
    });
    let req = Request::builder()
        .method(Method::PUT)
        .uri("/v2/repo/manifests/idx")
        .header(
            header::CONTENT_TYPE,
            "application/vnd.oci.image.index.v1+json",
        )
        .body(Body::from(serde_json::to_vec(&index).unwrap()))
        .expect("req");
    let (status, _h, body) = send(&app, req).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_error_code(&body, "MANIFEST_BLOB_UNKNOWN");
}

#[tokio::test]
async fn manifest_delete_by_tag_returns_405() {
    let app = app();
    push_min_manifest(&app, "repo", "latest").await;
    let (status, _h, body) = send(
        &app,
        method(Method::DELETE, "/v2/repo/manifests/latest", Body::empty()),
    )
    .await;
    assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
    assert_error_code(&body, "UNSUPPORTED");
}

#[tokio::test]
async fn manifest_delete_by_digest_then_missing() {
    let app = app();
    let digest = push_min_manifest(&app, "repo", "latest").await;
    let digest_str = digest.to_string();
    // Delete by digest → 202.
    let (status, _h, _b) = send(
        &app,
        method(Method::DELETE, &format!("/v2/repo/manifests/{digest_str}"), Body::empty()),
    )
    .await;
    assert_eq!(status, StatusCode::ACCEPTED);
    // Delete again by digest → 404.
    let (status, _h, body) = send(
        &app,
        method(Method::DELETE, &format!("/v2/repo/manifests/{digest_str}"), Body::empty()),
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_error_code(&body, "MANIFEST_UNKNOWN");
}

#[tokio::test]
async fn manifest_delete_invalid_reference_returns_400() {
    let app = app();
    // `sha256:` prefix with non-hex content parses as a digest reference
    // but fails digest validation → 400 DIGEST_INVALID (a URI-legal but
    // semantically invalid reference, unlike a raw space).
    let (status, _h, _b) = send(
        &app,
        method(
            Method::DELETE,
            "/v2/repo/manifests/sha256:ZZZZ",
            Body::empty(),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn manifest_get_unparseable_range_serves_full_body_200() {
    let app = app();
    push_min_manifest(&app, "repo", "latest").await;
    let req = Request::builder()
        .method(Method::GET)
        .uri("/v2/repo/manifests/latest")
        .header(header::RANGE, "items=0-5")
        .body(Body::empty())
        .expect("req");
    let (status, headers, body) = send(&app, req).await;
    assert_eq!(status, StatusCode::OK);
    assert!(!body.is_empty());
    assert_eq!(headers[header::ACCEPT_RANGES], "bytes");
}

#[tokio::test]
async fn manifest_get_inverted_range_returns_416() {
    let app = app();
    push_min_manifest(&app, "repo", "latest").await;
    let req = Request::builder()
        .method(Method::GET)
        .uri("/v2/repo/manifests/latest")
        .header(header::RANGE, "bytes=80-10")
        .body(Body::empty())
        .expect("req");
    let (status, _h, _b) = send(&app, req).await;
    assert_eq!(status, StatusCode::RANGE_NOT_SATISFIABLE);
}

// ---- router.rs dispatch (method-not-allowed + unroutable) ---------------

#[tokio::test]
async fn tags_list_with_post_is_405() {
    let app = app();
    let (status, _h, body) = send(
        &app,
        method(Method::POST, "/v2/repo/tags/list", Body::empty()),
    )
    .await;
    assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
    assert_error_code(&body, "UNSUPPORTED");
}

#[tokio::test]
async fn unroutable_v2_suffix_returns_name_unknown() {
    let app = app();
    // A path that has no recognised keyword suffix.
    let (status, _h, body) = send(&app, get("/v2/repo/bogus/segment")).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_error_code(&body, "NAME_UNKNOWN");
}

#[tokio::test]
async fn referrers_with_post_is_405() {
    let app = app();
    let (status, _h, _b) = send(
        &app,
        method(
            Method::POST,
            &format!("/v2/repo/referrers/{EMPTY_DIGEST}"),
            Body::empty(),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
}

#[tokio::test]
async fn probe_routes_live_ready_healthz() {
    let app = app();
    for uri in ["/live", "/ready", "/healthz"] {
        let (status, _h, _b) = send(&app, get(uri)).await;
        assert_eq!(status, StatusCode::OK, "GET {uri}");
    }
}

// ---- F1: manifest PUT by digest must verify digest matches body --------

#[tokio::test]
async fn manifest_put_by_digest_mismatch_is_rejected() {
    let app = app();
    // A valid minimal manifest whose *real* digest is D2…
    let manifest = json!({
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.manifest.v1+json",
        "config": { "mediaType": "application/vnd.oci.image.config.v1+json", "digest": EMPTY_DIGEST, "size": 2 },
        "layers": []
    });
    let body = serde_json::to_vec(&manifest).expect("ser");
    // …but the client lies and pushes it under a *different* digest D1.
    let wrong_digest = Digest::sha256_of(b"a completely different payload").to_string();
    let req = Request::builder()
        .method(Method::PUT)
        .uri(format!("/v2/repo/manifests/{wrong_digest}"))
        .header(
            header::CONTENT_TYPE,
            "application/vnd.oci.image.manifest.v1+json",
        )
        .body(Body::from(body))
        .expect("req");
    let (status, _h, body) = send(&app, req).await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "mismatched by-digest PUT");
    assert_error_code(&body, "DIGEST_INVALID");
}

#[tokio::test]
async fn manifest_put_by_non_sha256_digest_reference_is_rejected() {
    // R2-1: the registry canonicalises manifests with SHA-256 only. A
    // PUT-by-digest using a non-sha256 algorithm (e.g. `sha512:<128 hex>`)
    // must NOT skip digest verification: previously the handler only
    // compared when the declared algo equalled the computed (sha256) algo,
    // so a `sha512:` reference fell through and returned 201 for arbitrary
    // bytes. The fix rejects the reference with DIGEST_INVALID.
    let app = app();
    let manifest = json!({
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.manifest.v1+json",
        "config": { "mediaType": "application/vnd.oci.image.config.v1+json", "digest": EMPTY_DIGEST, "size": 2 },
        "layers": []
    });
    let body = serde_json::to_vec(&manifest).expect("ser");
    // A syntactically valid sha512 digest reference (128 hex chars).
    let sha512_ref = format!("sha512:{}", "a".repeat(128));
    let req = Request::builder()
        .method(Method::PUT)
        .uri(format!("/v2/repo/manifests/{sha512_ref}"))
        .header(
            header::CONTENT_TYPE,
            "application/vnd.oci.image.manifest.v1+json",
        )
        .body(Body::from(body))
        .expect("req");
    let (status, _h, body) = send(&app, req).await;
    assert_eq!(
        status,
        StatusCode::BAD_REQUEST,
        "non-sha256 by-digest PUT must be rejected, not 201"
    );
    assert_error_code(&body, "DIGEST_INVALID");
}

#[tokio::test]
async fn manifest_put_by_matching_digest_succeeds() {
    let app = app();
    let manifest = json!({
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.manifest.v1+json",
        "config": { "mediaType": "application/vnd.oci.image.config.v1+json", "digest": EMPTY_DIGEST, "size": 2 },
        "layers": []
    });
    let body = serde_json::to_vec(&manifest).expect("ser");
    // Push under the *correct* digest → 201.
    let digest = Digest::sha256_of(&body).to_string();
    let req = Request::builder()
        .method(Method::PUT)
        .uri(format!("/v2/repo/manifests/{digest}"))
        .header(
            header::CONTENT_TYPE,
            "application/vnd.oci.image.manifest.v1+json",
        )
        .body(Body::from(body))
        .expect("req");
    let (status, headers, _b) = send(&app, req).await;
    assert_eq!(status, StatusCode::CREATED, "matching by-digest PUT");
    assert_eq!(headers["docker-content-digest"], digest);
}

// ---- F2: chunked uploads are bounded by a per-session size cap ----------

/// Build an app whose upload-session cap is forced to `cap` bytes so the
/// cap-exceeded path can be driven with a few bytes instead of gigabytes.
fn app_with_upload_cap(cap: u64) -> Router {
    let blob_store: SharedBlobStore = Arc::new(InMemoryBlobStore::new());
    let registry = Arc::new(InMemoryRegistryMeta::new());
    let state = AppState::with_max_upload_session_bytes(blob_store, registry, cap);
    router(state).merge(probe_routes())
}

#[tokio::test]
async fn chunked_upload_past_session_cap_is_rejected_and_buffer_dropped() {
    // Cap the session at 8 bytes.
    let app = app_with_upload_cap(8);
    let (_s, headers, _b) =
        send(&app, method(Method::POST, "/v2/repo/blobs/uploads/", Body::empty())).await;
    let location = headers[header::LOCATION].to_str().unwrap().to_owned();

    // First chunk (5 bytes) fits under the 8-byte cap → 202.
    let req = Request::builder()
        .method(Method::PATCH)
        .uri(&location)
        .header(header::CONTENT_RANGE, "0-4")
        .body(Body::from(&b"hello"[..]))
        .expect("req");
    let (status, _h, _b) = send(&app, req).await;
    assert_eq!(status, StatusCode::ACCEPTED, "first sub-cap chunk");

    // Second chunk (5 bytes) would bring the total to 10 > 8 → 413,
    // and the session is dropped.
    let req = Request::builder()
        .method(Method::PATCH)
        .uri(&location)
        .header(header::CONTENT_RANGE, "5-9")
        .body(Body::from(&b"world"[..]))
        .expect("req");
    let (status, _h, body) = send(&app, req).await;
    assert_eq!(
        status,
        StatusCode::PAYLOAD_TOO_LARGE,
        "over-cap chunk rejected"
    );
    assert_error_code(&body, "BLOB_UPLOAD_INVALID");

    // The session was dropped on overflow: a subsequent status GET 404s,
    // proving the buffered bytes are no longer retained (no unbounded
    // growth).
    let (status, _h, body) = send(&app, get(&location)).await;
    assert_eq!(status, StatusCode::NOT_FOUND, "session dropped after overflow");
    assert_error_code(&body, "BLOB_UPLOAD_UNKNOWN");

    // Sanity: the production default cap is the documented 4 GiB.
    assert_eq!(
        ferro_oci_server::MAX_UPLOAD_SESSION_BYTES,
        4 * 1024 * 1024 * 1024
    );
}

// ---- R2-7: concurrent upload-session count cap + idle TTL ---------------

#[tokio::test]
async fn opening_more_sessions_than_cap_returns_429() {
    use ferro_oci_server::SessionLimits;
    // Cap concurrent sessions at 2 (TTL well above the test runtime so the
    // sweep does not interfere).
    let blob_store: SharedBlobStore = Arc::new(InMemoryBlobStore::new());
    let registry = Arc::new(ferro_oci_server::InMemoryRegistryMeta::with_session_limits(
        SessionLimits {
            max_sessions: 2,
            idle_ttl: std::time::Duration::from_secs(3600),
        },
    ));
    let state = AppState::new(blob_store, registry);
    let app = router(state).merge(probe_routes());

    // First two POSTs succeed (202).
    for _ in 0..2 {
        let (status, _h, _b) =
            send(&app, method(Method::POST, "/v2/repo/blobs/uploads/", Body::empty())).await;
        assert_eq!(status, StatusCode::ACCEPTED, "session under the cap");
    }
    // The third exceeds the cap → 429 Too Many Requests.
    let (status, _h, body) =
        send(&app, method(Method::POST, "/v2/repo/blobs/uploads/", Body::empty())).await;
    assert_eq!(
        status,
        StatusCode::TOO_MANY_REQUESTS,
        "session over the cap must be rejected with 429"
    );
    assert_error_code(&body, "TOOMANYREQUESTS");
}

#[tokio::test]
async fn idle_session_is_evicted_and_reads_as_unknown() {
    use ferro_oci_server::SessionLimits;
    // Zero TTL: the session is idle the instant it is created, so the very
    // next access evicts it and the handler answers 404 BLOB_UPLOAD_UNKNOWN.
    let blob_store: SharedBlobStore = Arc::new(InMemoryBlobStore::new());
    let registry = Arc::new(ferro_oci_server::InMemoryRegistryMeta::with_session_limits(
        SessionLimits {
            max_sessions: 16,
            idle_ttl: std::time::Duration::from_secs(0),
        },
    ));
    let state = AppState::new(blob_store, registry);
    let app = router(state).merge(probe_routes());

    let (status, headers, _b) =
        send(&app, method(Method::POST, "/v2/repo/blobs/uploads/", Body::empty())).await;
    assert_eq!(status, StatusCode::ACCEPTED);
    let location = headers[header::LOCATION].to_str().unwrap().to_owned();

    // The expired session no longer resolves.
    let (status, _h, body) = send(&app, get(&location)).await;
    assert_eq!(status, StatusCode::NOT_FOUND, "expired session evicted");
    assert_error_code(&body, "BLOB_UPLOAD_UNKNOWN");
}

// ---- F3: body limit raised above Axum's 2 MiB default -------------------

#[tokio::test]
async fn manifest_put_3mib_succeeds_past_axum_default_limit() {
    let app = app();
    // Build a valid image manifest inflated to ~3 MiB via a large
    // annotation value. This exceeds Axum's 2 MiB DefaultBodyLimit and
    // would 413 without the explicit higher limit; OCI requires
    // registries to accept manifests of at least 4 MiB.
    let big = "x".repeat(3 * 1024 * 1024);
    let manifest = json!({
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.manifest.v1+json",
        "config": { "mediaType": "application/vnd.oci.image.config.v1+json", "digest": EMPTY_DIGEST, "size": 2 },
        "layers": [],
        "annotations": { "com.example.padding": big }
    });
    let body = serde_json::to_vec(&manifest).expect("ser");
    assert!(body.len() > 2 * 1024 * 1024, "manifest exceeds 2 MiB");
    let req = Request::builder()
        .method(Method::PUT)
        .uri("/v2/repo/manifests/latest")
        .header(
            header::CONTENT_TYPE,
            "application/vnd.oci.image.manifest.v1+json",
        )
        .body(Body::from(body))
        .expect("req");
    let (status, _h, _b) = send(&app, req).await;
    assert_eq!(
        status,
        StatusCode::CREATED,
        "3 MiB manifest accepted past the 2 MiB default"
    );
}

// ---- F6: PATCH Content-Range inclusive length must match body length ----

#[tokio::test]
async fn patch_content_range_length_mismatch_is_rejected() {
    let app = app();
    let (_s, headers, _b) =
        send(&app, method(Method::POST, "/v2/repo/blobs/uploads/", Body::empty())).await;
    let location = headers[header::LOCATION].to_str().unwrap().to_owned();

    // Content-Range claims 0-999999 (1_000_000 bytes) but the body is a
    // single byte → must be rejected, not silently accepted.
    let req = Request::builder()
        .method(Method::PATCH)
        .uri(&location)
        .header(header::CONTENT_RANGE, "0-999999")
        .body(Body::from(&b"x"[..]))
        .expect("req");
    let (status, _h, body) = send(&app, req).await;
    assert_eq!(
        status,
        StatusCode::RANGE_NOT_SATISFIABLE,
        "range/body length mismatch"
    );
    assert_error_code(&body, "BLOB_UPLOAD_INVALID");
}

#[tokio::test]
async fn patch_content_range_length_match_is_accepted() {
    let app = app();
    let (_s, headers, _b) =
        send(&app, method(Method::POST, "/v2/repo/blobs/uploads/", Body::empty())).await;
    let location = headers[header::LOCATION].to_str().unwrap().to_owned();

    // Content-Range 0-4 spans 5 bytes; body is exactly 5 bytes → 202.
    let req = Request::builder()
        .method(Method::PATCH)
        .uri(&location)
        .header(header::CONTENT_RANGE, "0-4")
        .body(Body::from(&b"hello"[..]))
        .expect("req");
    let (status, _h, _b) = send(&app, req).await;
    assert_eq!(status, StatusCode::ACCEPTED, "matching range/body length");
}

// ---- R4-1: atomic manifest+referrer PUT across persist failure ----------

/// Build a router backed by a persistence registry whose snapshot writes are
/// forced to FAIL: `metadata.json` is pre-placed as a non-empty directory so
/// the atomic rename can never clobber it. Returns the app plus the owning
/// temp dir (kept alive for the test's lifetime).
fn app_with_failing_persist() -> (Router, tempfile::TempDir) {
    let tmp = tempfile::TempDir::new().expect("tempdir");
    let meta = tmp.path().join(ferro_oci_server::METADATA_FILE_NAME);
    std::fs::create_dir(&meta).expect("metadata.json as dir");
    std::fs::write(meta.join("child"), b"x").expect("child");
    let blob_store: SharedBlobStore = Arc::new(InMemoryBlobStore::new());
    let registry = Arc::new(InMemoryRegistryMeta::with_persistence(tmp.path()));
    let state = AppState::new(blob_store, registry);
    (router(state).merge(probe_routes()), tmp)
}

#[tokio::test]
async fn manifest_put_with_subject_persist_failure_rolls_back_all_and_returns_500() {
    // R4-1: a manifest PUT declaring a `subject` couples the manifest/tag
    // persist with the referrer-index persist. If durability fails the handler
    // must surface 500 AND leave NOTHING behind — neither the manifest/tag nor
    // the referrer may survive, since the client was told it failed.
    let (app, _tmp) = app_with_failing_persist();
    let subject_digest = Digest::sha256_of(b"the-subject-manifest").to_string();
    let manifest = json!({
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.manifest.v1+json",
        "artifactType": "application/spdx+json",
        "config": {
            "mediaType": "application/vnd.oci.image.config.v1+json",
            "digest": EMPTY_DIGEST,
            "size": 2
        },
        "layers": [],
        "subject": {
            "mediaType": "application/vnd.oci.image.manifest.v1+json",
            "digest": subject_digest,
            "size": 7
        }
    });
    let body = serde_json::to_vec(&manifest).expect("ser");
    let digest = Digest::sha256_of(&body).to_string();
    let req = Request::builder()
        .method(Method::PUT)
        .uri("/v2/lib/withsub/manifests/latest")
        .header(
            header::CONTENT_TYPE,
            "application/vnd.oci.image.manifest.v1+json",
        )
        .body(Body::from(body))
        .expect("req");
    let (status, _h, _b) = send(&app, req).await;
    assert_eq!(
        status,
        StatusCode::INTERNAL_SERVER_ERROR,
        "persist failure on a subject PUT must be 500"
    );

    // The manifest must NOT resolve by tag.
    let (tag_status, _h, _b) = send(&app, get("/v2/lib/withsub/manifests/latest")).await;
    assert_eq!(
        tag_status,
        StatusCode::NOT_FOUND,
        "rolled-back manifest must not resolve by tag"
    );
    // Nor by digest.
    let (digest_status, _h, _b) =
        send(&app, get(&format!("/v2/lib/withsub/manifests/{digest}"))).await;
    assert_eq!(
        digest_status,
        StatusCode::NOT_FOUND,
        "rolled-back manifest must not resolve by digest"
    );
    // The referrer must NOT have been registered.
    let (ref_status, _h, ref_body) =
        send(&app, get(&format!("/v2/lib/withsub/referrers/{subject_digest}"))).await;
    assert_eq!(ref_status, StatusCode::OK, "referrers list is always 200");
    let v: Value = serde_json::from_slice(&ref_body).expect("referrers json");
    assert_eq!(
        v["manifests"].as_array().map_or(0, Vec::len),
        0,
        "no referrer may survive the rolled-back PUT: {v}"
    );
    // The brand-new repo must not linger in the catalog (R4-2 via R4-1).
    let (_cs, _h, cat_body) = send(&app, get("/v2/_catalog")).await;
    let cat: Value = serde_json::from_slice(&cat_body).expect("catalog json");
    assert_eq!(
        cat["repositories"].as_array().map_or(0, Vec::len),
        0,
        "failed first publish must leave catalog empty: {cat}"
    );
}

#[tokio::test]
async fn manifest_put_with_subject_success_registers_manifest_and_referrer() {
    // R4-1 success path through the full handler: a subject PUT that persists
    // cleanly registers BOTH the manifest/tag and its referrer.
    let app = app();
    let subject_digest = Digest::sha256_of(b"the-subject-manifest").to_string();
    let manifest = json!({
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.manifest.v1+json",
        "artifactType": "application/spdx+json",
        "config": {
            "mediaType": "application/vnd.oci.image.config.v1+json",
            "digest": EMPTY_DIGEST,
            "size": 2
        },
        "layers": [],
        "subject": {
            "mediaType": "application/vnd.oci.image.manifest.v1+json",
            "digest": subject_digest,
            "size": 7
        }
    });
    let body = serde_json::to_vec(&manifest).expect("ser");
    let digest = Digest::sha256_of(&body).to_string();
    let req = Request::builder()
        .method(Method::PUT)
        .uri("/v2/lib/withsub/manifests/latest")
        .header(
            header::CONTENT_TYPE,
            "application/vnd.oci.image.manifest.v1+json",
        )
        .body(Body::from(body))
        .expect("req");
    let (status, headers, _b) = send(&app, req).await;
    assert_eq!(status, StatusCode::CREATED, "subject PUT ⇒ 201");
    assert_eq!(
        headers["oci-subject"], subject_digest,
        "OCI-Subject header surfaces the subject"
    );

    // Manifest resolves by tag.
    let (tag_status, _h, _b) = send(&app, get("/v2/lib/withsub/manifests/latest")).await;
    assert_eq!(tag_status, StatusCode::OK, "manifest resolves by tag");
    // Referrer is registered and surfaces under the subject.
    let (ref_status, _h, ref_body) =
        send(&app, get(&format!("/v2/lib/withsub/referrers/{subject_digest}"))).await;
    assert_eq!(ref_status, StatusCode::OK);
    let v: Value = serde_json::from_slice(&ref_body).expect("referrers json");
    let list = v["manifests"].as_array().expect("manifests array");
    assert_eq!(list.len(), 1, "exactly one referrer registered: {v}");
    assert_eq!(list[0]["digest"], digest, "referrer points at the PUT manifest");
}