holger-server-lib 0.6.9

Holger server library: config, wiring, gRPC service, Rust API
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
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
//! HTTP/OCI gateway: the one non-gRPC ingress, letting HTTP-only clients (helm,
//! pip, cargo, OCI registry pushes via `oci://…`) reach the same repository
//! backends the tonic service in `grpc.rs` serves — each request is routed to a
//! backend and dispatched through its `handle_http2_request`. [`GatewaySettings`]
//! carries the shared [`FastRoutes`], auth config, optional TLS, body cap, and
//! the audit sink into every connection.
//!
//! Security-app rules, deliberately kept in lockstep with the gRPC path:
//! TLS terminates here and mTLS CN is lifted from the handshake once per
//! connection; reads (GET/HEAD) stay open and audit as `anonymous`, while writes
//! must pass `auth::validate_request` then `authorize_http_write` (RBAC mirror of
//! `grpc::authorize_write`, DELETE = admin, other writes = writer-or-admin,
//! fail-closed under a configured policy). Only `/healthz`, `/readyz`, and the
//! `/v2` OCI version probe are unauthenticated and unaudited. Routing keys off
//! the first path segment (`/v2/{name}/…` for OCI, else `/{repo}/…`) via
//! [`route_key`]; backends strip their own prefix from the passed-through path.
//!
//! Gotcha: the read-only write-gate (`backend.is_writable()`) and the body-size
//! cap both fire BEFORE the body is collected, so a rejected write never buffers
//! the upload — this is intentional, closing the DoS surface the pre-gate HTTP
//! path left open (it used to hand writes to a read-only backend that silently
//! swallowed them).
//
// HTTP/OCI gateway: bridges HTTP clients (helm, pip, cargo, OCI registry) to
// the repository backends' `handle_http2_request` handlers. Helm and friends
// speak HTTP, not gRPC, so this listener is required for any ecosystem interop;
// the modern Helm flow (`helm push/pull oci://…`) rides the OCI Distribution
// API served here.
//
// Security posture (this is a security application):
//   * TLS is terminated here when the endpoint has `ron_tls`; client certs are
//     requested but optional, so anonymous pulls and Kubernetes probes work
//     while writes are gated on identity at the application layer.
//   * mTLS identity (client-cert CN) is extracted once per connection and fed
//     into auth alongside any Bearer token.
//   * Request bodies are size-capped to bound memory use (upload DoS guard).
//   * Reserved unauthenticated paths: GET /healthz, GET /readyz, GET /v2/.
//
// Routing: `/v2/{name}/…` → repo named by the first OCI name segment (OCI);
// `/{repo}/…` → repo named by the first path segment (classic). The full
// path+query is passed through; backends strip their own prefix.

use std::sync::Arc;

/// Per-repo listing cap for the `/metrics` artifact-count gauge. The gauge is an
/// operability signal, not an inventory, so a very large repo is counted up to
/// this bound rather than paying an unbounded scan on every scrape.
const METRICS_LIST_CAP: usize = 100_000;

use http_body_util::{BodyExt, Full, Limited};
use hyper::body::{Bytes, Incoming};
use hyper::service::service_fn;
use hyper::{Request, Response};
use hyper_util::rt::{TokioExecutor, TokioIo};
use hyper_util::server::conn::auto::Builder as ConnBuilder;
use rustls::ServerConfig;
use tokio_rustls::TlsAcceptor;

use crate::audit::{AuditAction, AuditEvent, AuditLog};
use crate::auth::{self, AuthConfig};
use crate::exposed::fast_routes::FastRoutes;
use crate::exposed::tls::leaf_common_name;

/// Everything a gateway connection needs, shared behind an `Arc`.
pub struct GatewaySettings {
    pub routes: FastRoutes,
    pub auth_config: Arc<AuthConfig>,
    pub tls: Option<Arc<ServerConfig>>,
    pub max_body_bytes: usize,
    /// Append-only audit sink, shared with the gRPC services. Reads
    /// (GET/HEAD) record as anonymous downloads; gated writes record the
    /// resolved identity (Bearer sub / mTLS CN).
    pub audit: Arc<dyn AuditLog>,
    /// Hosted-SBOM store, shared with the `SbomService` gRPC RPCs. Backs the
    /// read-only `GET /-/sbom` door (attach is gRPC/CLI-only). `None` ⇒ the door
    /// answers 404 (SBOM hosting not configured on this server).
    pub sboms: Option<crate::sbom::SharedSbomStore>,
    /// Custom-property store, shared with the gRPC `Search` property axis. Backs
    /// the read-only `GET /-/properties` door AND the `property=` filter on
    /// `GET /-/search` (property WRITES are CLI/in-process for now). `None` ⇒ the
    /// door answers 404 and a `property=` filter matches nothing (fail-closed).
    pub properties: Option<crate::properties::SharedPropertyStore>,
    /// Serve-time **quarantine** predicate `(key, value)`, shared with the gRPC
    /// fetch gate. `Some` ⇒ a GET whose coordinate (via
    /// [`RepositoryBackendTrait::coordinate_for_path`]) has matching properties is
    /// refused with 404 before the backend serves it. `None` ⇒ no serve gate.
    pub quarantine: Option<(String, String)>,
}

pub fn start_http_gateway(
    addr: std::net::SocketAddr,
    settings: Arc<GatewaySettings>,
) -> anyhow::Result<()> {
    tokio::spawn(async move {
        let listener = match tokio::net::TcpListener::bind(addr).await {
            Ok(l) => l,
            Err(e) => {
                eprintln!("HTTP/OCI gateway failed to bind {}: {}", addr, e);
                return;
            }
        };
        let scheme = if settings.tls.is_some() { "https" } else { "http (cleartext)" };
        println!("HTTP/OCI gateway listening on {} [{}]", addr, scheme);
        if settings.tls.is_none() {
            log::warn!(
                "SECURITY: HTTP/OCI gateway on {} runs WITHOUT TLS — credentials and \
                 artifacts travel in cleartext. Set ron_tls for any non-loopback use.",
                addr
            );
        }

        let acceptor = settings.tls.clone().map(TlsAcceptor::from);

        loop {
            let (stream, peer) = match listener.accept().await {
                Ok(conn) => conn,
                Err(e) => {
                    log::debug!("gateway accept error: {}", e);
                    continue;
                }
            };
            let peer = peer.to_string();
            let settings = settings.clone();
            let acceptor = acceptor.clone();
            tokio::spawn(async move {
                match acceptor {
                    Some(acceptor) => {
                        let tls_stream = match acceptor.accept(stream).await {
                            Ok(s) => s,
                            Err(e) => {
                                log::debug!("TLS handshake failed: {}", e);
                                return;
                            }
                        };
                        // Pull the mTLS identity (if any) out of the handshake.
                        let client_cn = tls_stream
                            .get_ref()
                            .1
                            .peer_certificates()
                            .and_then(leaf_common_name);
                        serve(TokioIo::new(tls_stream), settings, client_cn, peer).await;
                    }
                    None => serve(TokioIo::new(stream), settings, None, peer).await,
                }
            });
        }
    });
    Ok(())
}

async fn serve<I>(
    io: TokioIo<I>,
    settings: Arc<GatewaySettings>,
    client_cn: Option<String>,
    peer: String,
) where
    I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + 'static,
{
    let svc = service_fn(move |req| {
        let settings = settings.clone();
        let client_cn = client_cn.clone();
        let peer = peer.clone();
        async move { handle(req, settings, client_cn, peer).await }
    });
    if let Err(e) = ConnBuilder::new(TokioExecutor::new())
        .serve_connection(io, svc)
        .await
    {
        log::debug!("gateway connection error: {}", e);
    }
}

async fn handle(
    req: Request<Incoming>,
    settings: Arc<GatewaySettings>,
    client_cn: Option<String>,
    peer: String,
) -> Result<Response<Full<Bytes>>, std::convert::Infallible> {
    // Request-handling clock: observed into the `holger_request_duration_seconds`
    // histogram at each door's exit, right where the request counter is bumped, so
    // latency is measured over the same handled-request population.
    let started = std::time::Instant::now();
    let method = req.method().as_str().to_owned();
    let path = req.uri().path().to_owned();
    let path_and_query = req
        .uri()
        .path_and_query()
        .map(|pq| pq.as_str().to_owned())
        .unwrap_or_else(|| path.clone());

    // Checksum-verify-on-deploy (Artifactory `X-Checksum-*` convention): a client
    // may advertise the digest of the bytes it is uploading. Capture the strong
    // digests NOW — before `req.into_body()` consumes the request — so the write
    // path can recompute and reject a corrupted upload before it reaches a
    // backend. Header lookups are case-insensitive (canonical lowercase names).
    let want_sha256 = req
        .headers()
        .get("x-checksum-sha256")
        .and_then(|v| v.to_str().ok())
        .map(str::to_owned);
    let want_sha512 = req
        .headers()
        .get("x-checksum-sha512")
        .and_then(|v| v.to_str().ok())
        .map(str::to_owned);

    // Unauthenticated, backend-less endpoints. Probes are not artifact
    // operations, so they are not audited.
    if method == "GET" {
        if path == "/healthz" || path == "/readyz" {
            return Ok(text(200, "ok"));
        }
        if path == "/v2" || path == "/v2/" {
            // OCI version probe — clients hit this before auth.
            return Ok(Response::builder()
                .status(200)
                .header("Docker-Distribution-Api-Version", "registry/2.0")
                .body(Full::new(Bytes::from_static(b"{}")))
                .expect("static response"));
        }
        // Read-only cross-repo SEARCH door (parity §H). Reserved under `/-/` so it
        // never collides with a repository name; open read (anonymous), audited as
        // a List. Query axes come from the query string:
        //   /-/search?name=&namespace=&version=&checksum=&path=&repo=&repo=&limit=
        // Returns the same JSON shape the engine produces (artifacts + paths +
        // truncated). This is the read-only HTTP twin of the `SearchService` RPC.
        if path == "/-/search" {
            let query = parse_search_query(req.uri().query().unwrap_or(""));
            let repos = settings.routes.all_repos();
            let props = settings.properties.clone();
            let results = tokio::task::spawn_blocking(move || {
                crate::search::search_repos_with_properties(
                    &repos,
                    &query,
                    props.as_deref().map(|p| p as &dyn crate::search::PropertyLookup),
                )
            })
            .await;
            let hit_count = results
                .as_ref()
                .map(|r| (r.artifacts.len() + r.paths.len()) as u64)
                .unwrap_or(0);
            let (status, body) = match results {
                Ok(r) => match serde_json::to_vec(&r) {
                    Ok(json) => (200u16, json),
                    Err(e) => (500, format!("serialize error: {e}").into_bytes()),
                },
                Err(e) => (500, format!("search task failed: {e}").into_bytes()),
            };
            // Audit the read (path column carries the raw query string).
            let ev = AuditEvent::new(
                "anonymous",
                AuditAction::List,
                "",
                &path_and_query,
                &peer,
                status,
                hit_count,
            );
            if let Err(e) = settings.audit.record(ev) {
                log::warn!("audit record failed: {e}");
            }
            crate::grpc::functional_status(
                "holger-http/search",
                "search_served",
                status == 200,
                &format!("{hit_count} hits"),
            );
            crate::metrics::global().record_request(
                crate::metrics::Verb::Search,
                status,
                body.len() as u64,
            );
            crate::metrics::global().observe_request_duration(started.elapsed().as_secs_f64());
            let ct = if status == 200 { "application/json" } else { "text/plain" };
            return Ok(Response::builder()
                .status(status)
                .header("Content-Type", ct)
                .body(Full::new(Bytes::from(body)))
                .unwrap_or_else(|_| text(500, "Internal error")));
        }
        // Read-only hosted-SBOM door (parity §6/§11). The read twin of the
        // `SbomService.FetchSbom` RPC — attach stays gRPC/CLI-only. Coordinate
        // comes from the query string:
        //   /-/sbom?repo=&namespace=&name=&version=
        // Serves the hosted CycloneDX document byte-identical (200), or 404 when
        // no SBOM is attached to that coordinate. Open read, audited as a Download.
        if path == "/-/sbom" {
            let (status, ct, body, repo, label) =
                serve_sbom_door(settings.sboms.as_ref(), req.uri().query().unwrap_or(""));
            let ev = AuditEvent::new(
                "anonymous",
                AuditAction::Download,
                &repo,
                &label,
                &peer,
                status,
                if status == 200 { body.len() as u64 } else { 0 },
            );
            if let Err(e) = settings.audit.record(ev) {
                log::warn!("audit record failed: {e}");
            }
            crate::grpc::functional_status(
                "holger-http/sbom",
                "sbom_served",
                status == 200,
                &format!("{status} {label}"),
            );
            crate::metrics::global().record_request(
                crate::metrics::Verb::Sbom,
                status,
                if status == 200 { body.len() as u64 } else { 0 },
            );
            crate::metrics::global().observe_request_duration(started.elapsed().as_secs_f64());
            return Ok(Response::builder()
                .status(status)
                .header("Content-Type", ct)
                .body(Full::new(Bytes::from(body)))
                .unwrap_or_else(|_| text(500, "Internal error")));
        }
        // Read-only custom-PROPERTIES door (parity §8). The read twin of the
        // `property` search axis — property WRITES are CLI/in-process for now.
        //   /-/properties?repo=&namespace=&name=&version=
        // Serves the coordinate's `{ key: [values] }` map as JSON (200, `{}` when
        // none), or 400 when the coordinate is incomplete. Open read, audited.
        if path == "/-/properties" {
            let (status, body, repo, label) =
                serve_properties_door(settings.properties.as_ref(), req.uri().query().unwrap_or(""));
            let ev = AuditEvent::new(
                "anonymous",
                AuditAction::List,
                &repo,
                &label,
                &peer,
                status,
                0,
            );
            if let Err(e) = settings.audit.record(ev) {
                log::warn!("audit record failed: {e}");
            }
            crate::grpc::functional_status(
                "holger-http/properties",
                "properties_served",
                status == 200,
                &format!("{status} {label}"),
            );
            let ct = if status == 200 { "application/json" } else { "text/plain" };
            return Ok(Response::builder()
                .status(status)
                .header("Content-Type", ct)
                .body(Full::new(Bytes::from(body)))
                .unwrap_or_else(|_| text(500, "Internal error")));
        }
        // Read-only Prometheus scrape door (parity §K). Reserved (no `/-/` prefix
        // — Prometheus scrapes the conventional `/metrics`), unauthenticated and
        // unaudited (it exposes only aggregate registry counters, not artifacts).
        // Counters come from the process-global registry every verb bumps; the
        // per-repo artifact gauge lists each backend at scrape time, so it runs
        // under `spawn_blocking` off the async reactor.
        if path == "/metrics" {
            let repos = settings.routes.all_repos();
            let body = tokio::task::spawn_blocking(move || {
                let repo_counts: Vec<(String, usize)> = repos
                    .iter()
                    .map(|(name, backend)| {
                        // Bounded listing: the gauge is a health signal, not a
                        // census, so a huge repo caps at METRICS_LIST_CAP and an
                        // errored backend reports 0 rather than failing the scrape.
                        let n = backend
                            .list(None, METRICS_LIST_CAP)
                            .map(|v| v.len())
                            .unwrap_or(0);
                        (name.clone(), n)
                    })
                    .collect();
                crate::metrics::global().render_prometheus(&repo_counts)
            })
            .await;
            let (status, body) = match body {
                Ok(text) => (200u16, text.into_bytes()),
                Err(e) => (500u16, format!("metrics task failed: {e}").into_bytes()),
            };
            crate::grpc::functional_status(
                "holger-http/metrics",
                "metrics_served",
                status == 200,
                &format!("{} bytes", body.len()),
            );
            return Ok(Response::builder()
                .status(status)
                // Prometheus text exposition format 0.0.4.
                .header("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
                .body(Full::new(Bytes::from(body)))
                .unwrap_or_else(|_| text(500, "Internal error")));
        }
    }

    // Custom-PROPERTIES WRITE door (parity §8): set/remove a property remotely —
    // the write twin of the read door above + the gRPC `PropertyService.SetProperty`
    // RPC (property write was CLI/in-process only before this).
    //   PUT|POST /-/properties?repo=&namespace=&name=&version=&key=&value=&value=…
    //   DELETE   /-/properties?repo=&…&key=                       (remove the key)
    // Write-gated (writer/admin), SCOPED to the TARGET repo from the query string
    // (not the `-` path segment), mirroring the gRPC write gate. Values ride in
    // repeatable `value=` params, so there is no artifact body / checksum gate.
    if path == "/-/properties" && matches!(method.as_str(), "PUT" | "POST" | "DELETE") {
        let raw_q = req.uri().query().unwrap_or("").to_owned();
        let coord = parse_sbom_coord(&raw_q);
        // AuthN: resolve identity (OIDC sub / mTLS CN), or `None` when auth is open.
        let bearer = req
            .headers()
            .get("authorization")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.strip_prefix("Bearer "));
        let identity =
            match auth::validate_request(&settings.auth_config, bearer, client_cn.as_deref()).await {
                Ok(id) => id,
                Err(_) => return Ok(text(401, "Unauthorized")),
            };
        // AuthZ (writer/admin), scoped to the coordinate's repository.
        if let Err((status, detail)) =
            authorize_http_write(&settings.auth_config, identity.as_ref(), &method, &coord.repository)
        {
            let who = identity.as_ref().map(|i| i.subject.as_str()).unwrap_or("anonymous");
            let ev = AuditEvent::new(who, AuditAction::Upload, &coord.repository, &path, &peer, status, 0)
                .with_detail(detail.to_string());
            if let Err(e) = settings.audit.record(ev) {
                log::warn!("audit record failed: {e}");
            }
            let msg = if status == 403 { "Forbidden" } else { "Unauthorized" };
            return Ok(text(status, msg));
        }
        let who = identity.map(|i| i.subject).unwrap_or_else(|| "anonymous".to_string());
        let (status, body, repo, label) =
            serve_properties_write(settings.properties.as_ref(), &method, &raw_q);
        let action = if method == "DELETE" { AuditAction::Delete } else { AuditAction::Upload };
        let ev = AuditEvent::new(&who, action, &repo, &label, &peer, status, 0);
        if let Err(e) = settings.audit.record(ev) {
            log::warn!("audit record failed: {e}");
        }
        crate::grpc::functional_status(
            "holger-http/properties_write",
            "property_written",
            status == 200,
            &format!("{status} {label}"),
        );
        crate::metrics::global().record_request(
            if method == "DELETE" { crate::metrics::Verb::Delete } else { crate::metrics::Verb::Put },
            status,
            0,
        );
        crate::metrics::global().observe_request_duration(started.elapsed().as_secs_f64());
        let ct = if status == 200 { "application/json" } else { "text/plain" };
        return Ok(Response::builder()
            .status(status)
            .header("Content-Type", ct)
            .body(Full::new(Bytes::from(body)))
            .unwrap_or_else(|_| text(500, "Internal error")));
    }

    // Map the HTTP verb to an audit action: reads (GET/HEAD) are downloads,
    // DELETE removes, everything else (PUT/POST/PATCH) stores.
    let is_read = method == "GET" || method == "HEAD";
    let action = if is_read {
        AuditAction::Download
    } else if method == "DELETE" {
        AuditAction::Delete
    } else {
        AuditAction::Upload
    };
    // Repository name for the audit record: the first OCI/classic path segment.
    let repo_key = route_key(&path).unwrap_or_default().to_owned();
    // Prometheus verb for this request, via the ONE shared audit-action→verb
    // classifier (Law #5 — same mapping the gRPC `record_audit` choke point uses).
    // The artifact door only ever produces Download/Upload/Delete here, all of
    // which classify; `Get` is a safe default that can't be reached.
    let metric_verb = crate::metrics::Verb::from_audit_action(action).unwrap_or(crate::metrics::Verb::Get);
    // Best-effort audit append, mirroring the gRPC `record_audit` helper. Every
    // outcome also bumps the process-global metrics registry (`/metrics`), so a
    // verb, its bytes served, and any 5xx are counted at the one exit point.
    let record = |ident: &str, status: u16, bytes: u64, detail: &str| {
        crate::metrics::global().record_request(metric_verb, status, bytes);
        crate::metrics::global().observe_request_duration(started.elapsed().as_secs_f64());
        let mut ev =
            AuditEvent::new(ident, action, &repo_key, &path, &peer, status, bytes);
        if !detail.is_empty() {
            ev = ev.with_detail(detail);
        }
        if let Err(e) = settings.audit.record(ev) {
            log::warn!("audit record failed: {e}");
        }
    };

    // Writes require a valid identity (Bearer or mTLS CN) and, when role policy
    // is configured, authorization. Reads stay open and record as the anonymous
    // principal.
    let ident = if is_read {
        "anonymous".to_string()
    } else {
        let bearer = req
            .headers()
            .get("authorization")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.strip_prefix("Bearer "));
        // AuthN: resolve the identity (OIDC sub / mTLS CN), or `None` when auth is
        // open (no methods configured).
        let identity =
            match auth::validate_request(&settings.auth_config, bearer, client_cn.as_deref()).await
            {
                Ok(id) => id,
                Err(_) => {
                    record("anonymous", 401, 0, "unauthorized");
                    return Ok(text(401, "Unauthorized"));
                }
            };

        // AuthZ (RBAC) — mirrors `grpc::authorize_write`, scoped to the target repo
        // so a per-repo ACL (`repo_roles`) governs this write.
        if let Err((status, detail)) =
            authorize_http_write(&settings.auth_config, identity.as_ref(), &method, &repo_key)
        {
            let who = identity
                .as_ref()
                .map(|i| i.subject.as_str())
                .unwrap_or("anonymous");
            record(who, status, 0, detail);
            let msg = if status == 403 { "Forbidden" } else { "Unauthorized" };
            return Ok(text(status, msg));
        }

        identity
            .map(|i| i.subject)
            .unwrap_or_else(|| "anonymous".to_string())
    };

    let backend = match routes_lookup(&settings.routes, &path) {
        Some(b) => b,
        None => {
            record(&ident, 404, 0, "unknown repository");
            return Ok(text(404, "Unknown repository"));
        }
    };

    // Serve-time quarantine gate (property-policy §): on a READ, if the backend can
    // map this path to a coordinate and that coordinate's properties match the
    // configured quarantine predicate (e.g. quarantine=true), refuse with 404 —
    // served as absent so a bad/unverified blob is blocked without deleting it. Off
    // unless configured, so the default serve path pays nothing.
    if is_read
        && serve_quarantined(
            settings.quarantine.as_ref(),
            settings.properties.as_ref(),
            backend.as_ref(),
            &path,
            &repo_key,
        )
    {
        record(&ident, 404, 0, "quarantined — refused at serve boundary");
        crate::grpc::functional_status("holger-http/quarantine", "quarantine_blocked", true, &path);
        return Ok(text(404, "Not found"));
    }

    // Read-only repository write-gate, mirroring grpc.rs: reject writes to a
    // non-writable backend BEFORE collecting the body (fail closed, no upload
    // DoS surface). The gRPC path returns 403 here; the HTTP path used to defer
    // to the backend, which silently accepted/ignored the write.
    if !is_read && !backend.is_writable() {
        record(&ident, 403, 0, "repository is read-only");
        return Ok(text(403, "Forbidden"));
    }

    // Cap the body to bound memory (upload DoS guard).
    let body = match Limited::new(req.into_body(), settings.max_body_bytes)
        .collect()
        .await
    {
        Ok(collected) => collected.to_bytes(),
        Err(_) => {
            record(&ident, 413, 0, "payload too large");
            return Ok(text(413, "Payload too large"));
        }
    };

    // Integrity gate: if the client advertised a digest, it MUST match the bytes
    // we received or the write is rejected (400) before any backend sees it —
    // holger's "the bytes are what you think they are" guarantee at the door.
    if !is_read {
        if let Err((status, detail)) =
            verify_upload_checksum(want_sha256.as_deref(), want_sha512.as_deref(), &body)
        {
            record(&ident, status, body.len() as u64, detail);
            return Ok(text(status, detail));
        }
    }

    let dispatch = tokio::task::spawn_blocking(move || {
        backend.handle_http2_request(&method, &path_and_query, &body)
    })
    .await;

    match dispatch {
        Ok(Ok((status, headers, body))) => {
            record(&ident, status, body.len() as u64, "");
            let mut builder = Response::builder().status(status);
            for (k, v) in headers {
                builder = builder.header(k, v);
            }
            Ok(builder
                .body(Full::new(Bytes::from(body)))
                .unwrap_or_else(|_| text(500, "Internal error")))
        }
        // Generic message to the client; detail stays in the server log.
        Ok(Err(e)) => {
            record(&ident, 500, 0, &e.to_string());
            log::warn!("backend error for {}: {:#}", path, e);
            Ok(text(500, "Internal error"))
        }
        Err(_) => {
            record(&ident, 500, 0, "dispatch task failed");
            Ok(text(500, "Internal error"))
        }
    }
}

/// Checksum-verify-on-deploy. Recomputes the strong digest(s) the client
/// advertised (`X-Checksum-Sha256` / `X-Checksum-Sha512`, Artifactory's
/// checksum-deploy convention) over the received bytes and returns
/// `Err((400, detail))` on any mismatch. Verification is **opt-in**: a missing
/// or empty header is `Ok(())` (the write proceeds unverified, as before). Only
/// strong digests are honoured — legacy `sha1`/`md5` are intentionally
/// unsupported (too weak to be an integrity guarantee). Hex compare is
/// case-insensitive.
fn verify_upload_checksum(
    want_sha256: Option<&str>,
    want_sha512: Option<&str>,
    body: &[u8],
) -> Result<(), (u16, &'static str)> {
    use sha2::{Digest, Sha256, Sha512};
    if let Some(expected) = want_sha256 {
        let expected = expected.trim();
        if !expected.is_empty() {
            let got = hex::encode(Sha256::digest(body));
            if !got.eq_ignore_ascii_case(expected) {
                return Err((400, "sha256 checksum mismatch"));
            }
        }
    }
    if let Some(expected) = want_sha512 {
        let expected = expected.trim();
        if !expected.is_empty() {
            let got = hex::encode(Sha512::digest(body));
            if !got.eq_ignore_ascii_case(expected) {
                return Err((400, "sha512 checksum mismatch"));
            }
        }
    }
    Ok(())
}

/// Percent-decode an `application/x-www-form-urlencoded` component: `+` → space
/// and `%XX` → the byte. Invalid escapes are passed through verbatim (a search
/// term is best-effort, never a hard error). Kept tiny + dependency-free.
fn form_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'+' => {
                out.push(b' ');
                i += 1;
            }
            b'%' if i + 2 < bytes.len() => {
                let hex = |c: u8| -> Option<u8> {
                    match c {
                        b'0'..=b'9' => Some(c - b'0'),
                        b'a'..=b'f' => Some(c - b'a' + 10),
                        b'A'..=b'F' => Some(c - b'A' + 10),
                        _ => None,
                    }
                };
                match (hex(bytes[i + 1]), hex(bytes[i + 2])) {
                    (Some(h), Some(l)) => {
                        out.push(h << 4 | l);
                        i += 3;
                    }
                    _ => {
                        out.push(b'%');
                        i += 1;
                    }
                }
            }
            b => {
                out.push(b);
                i += 1;
            }
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Build a [`search::SearchQuery`](crate::search::SearchQuery) from a raw URL
/// query string (`name=serde&version=1.0.0&repo=rust-dev&repo=maven-dev&limit=50`).
/// Recognised keys: `name`, `namespace` (alias `group`), `version`, `checksum`
/// (alias `sha256`), `path`, `repo`/`repository` (repeatable), `limit`. Empty
/// values are treated as unset; unknown keys are ignored.
fn parse_search_query(raw: &str) -> crate::search::SearchQuery {
    let mut q = crate::search::SearchQuery::default();
    for pair in raw.split('&').filter(|s| !s.is_empty()) {
        let (key, val) = match pair.split_once('=') {
            Some((k, v)) => (k, form_decode(v)),
            None => (pair, String::new()),
        };
        let set = |slot: &mut Option<String>, v: String| {
            if !v.is_empty() {
                *slot = Some(v);
            }
        };
        match key {
            "name" => set(&mut q.name, val),
            "namespace" | "group" => set(&mut q.namespace, val),
            "version" => set(&mut q.version, val),
            "checksum" | "sha256" => set(&mut q.checksum, val),
            "path" => set(&mut q.path, val),
            // `property=key:value` (repeatable) — a custom-property filter. The
            // key/value split is on the FIRST ':' so a value may itself contain
            // ':'; `property=key` (no ':') means "key present, any value".
            "property" | "prop" => {
                if !val.is_empty() {
                    let (k, v) = match val.split_once(':') {
                        Some((k, v)) => (k.to_string(), v.to_string()),
                        None => (val, String::new()),
                    };
                    if !k.is_empty() {
                        q.properties.push((k, v));
                    }
                }
            }
            "repo" | "repository" => {
                if !val.is_empty() {
                    q.repositories.push(val);
                }
            }
            "limit" => {
                if let Ok(n) = val.parse::<usize>() {
                    q.limit = n;
                }
            }
            _ => {}
        }
    }
    q
}

/// The parsed coordinate for the `GET /-/sbom` door: which repository +
/// artifact `(namespace/name/version)` an SBOM is requested for. Missing pieces
/// are empty strings (the handler rejects a query lacking `repo`/`name`/`version`).
pub(crate) struct SbomCoordQuery {
    pub repository: String,
    pub id: traits::ArtifactId,
}

/// Build an [`SbomCoordQuery`] from a raw URL query string
/// (`repo=rust-dev&name=serde&version=1.0.0[&namespace=…]`). Keys: `repo`
/// (alias `repository`), `namespace` (alias `group`), `name`, `version`. Empty
/// values are unset; an empty namespace ⇒ `None` (a namespace-less coordinate).
fn parse_sbom_coord(raw: &str) -> SbomCoordQuery {
    let (mut repository, mut namespace, mut name, mut version) =
        (String::new(), String::new(), String::new(), String::new());
    for pair in raw.split('&').filter(|s| !s.is_empty()) {
        let (key, val) = match pair.split_once('=') {
            Some((k, v)) => (k, form_decode(v)),
            None => (pair, String::new()),
        };
        match key {
            "repo" | "repository" => repository = val,
            "namespace" | "group" => namespace = val,
            "name" => name = val,
            "version" => version = val,
            _ => {}
        }
    }
    SbomCoordQuery {
        repository,
        id: traits::ArtifactId {
            namespace: if namespace.is_empty() { None } else { Some(namespace) },
            name,
            version,
        },
    }
}

/// Serve the read-only `GET /-/sbom` door: resolve the coordinate from
/// `raw_query`, fetch the hosted SBOM from `sboms`, and return
/// `(status, content_type, body, repository, label)`. **Pure** over the store it
/// is given, so the HTTP handler and its test share exactly one code path — the
/// byte-identical serving is asserted directly, not through a live socket.
///
/// * 400 when `repo`/`name`/`version` are not all present.
/// * 200 + the byte-identical CycloneDX document when an SBOM is attached.
/// * 404 when no SBOM is attached (or hosting is not configured on this server).
/// * 500 on a store read error.
pub(crate) fn serve_sbom_door(
    sboms: Option<&crate::sbom::SharedSbomStore>,
    raw_query: &str,
) -> (u16, &'static str, Vec<u8>, String, String) {
    let coord = parse_sbom_coord(raw_query);
    let label = format!(
        "{}/{}@{}",
        coord.id.namespace.as_deref().unwrap_or("-"),
        coord.id.name,
        coord.id.version,
    );
    let (status, ct, body): (u16, &'static str, Vec<u8>) = if coord.repository.is_empty()
        || coord.id.name.is_empty()
        || coord.id.version.is_empty()
    {
        (400, "text/plain", b"sbom query needs repo, name and version".to_vec())
    } else {
        match sboms.map(|s| s.fetch(&coord.repository, &coord.id)) {
            Some(Ok(Some(doc))) => (200, "application/json", doc),
            // No SBOM attached, or hosting not configured on this server.
            Some(Ok(None)) | None => {
                (404, "text/plain", b"no SBOM hosted for that coordinate".to_vec())
            }
            Some(Err(e)) => (500, "text/plain", format!("sbom read error: {e}").into_bytes()),
        }
    };
    (status, ct, body, coord.repository, label)
}

/// Serve the read-only `GET /-/properties` door: resolve the coordinate from
/// `raw_query` (reusing the SBOM coordinate parser), read its property map from
/// `props`, and return `(status, json_body, repository, label)`. **Pure** over
/// the store it is given, so the handler and its test share one code path.
///
/// * 400 when `repo`/`name`/`version` are not all present.
/// * 200 + the coordinate's `{ key: [values] }` JSON (`{}` when none, or when the
///   store is not configured — an unset coordinate has no properties either way).
pub(crate) fn serve_properties_door(
    props: Option<&crate::properties::SharedPropertyStore>,
    raw_query: &str,
) -> (u16, Vec<u8>, String, String) {
    let coord = parse_sbom_coord(raw_query);
    let label = format!(
        "{}/{}@{}",
        coord.id.namespace.as_deref().unwrap_or("-"),
        coord.id.name,
        coord.id.version,
    );
    if coord.repository.is_empty() || coord.id.name.is_empty() || coord.id.version.is_empty() {
        return (
            400,
            b"properties query needs repo, name and version".to_vec(),
            coord.repository,
            label,
        );
    }
    let map = props
        .map(|p| p.get(&coord.repository, &coord.id))
        .unwrap_or_default();
    let body = serde_json::to_vec(&map).unwrap_or_else(|_| b"{}".to_vec());
    (200, body, coord.repository, label)
}

/// Serve a `PUT`/`POST`/`DELETE /-/properties` WRITE: parse the coordinate + `key`
/// (+ repeatable `value=` for a set) from `raw_query`, apply it to `props`, and
/// return `(status, json_body, repository, label)`. **Pure** over the store, so
/// the handler and its test share one code path (the auth gate runs in the
/// handler, before this).
///
/// * 400 when `repo`/`name`/`version`/`key` are not all present.
/// * `DELETE`, or `PUT`/`POST` with no `value=`, **removes** the key.
/// * `PUT`/`POST` with values **sets** them (last-wins, deduped).
/// * 200 + the coordinate's resulting `{ key: [values] }` JSON.
/// * 503 when no property store is configured on this server.
pub(crate) fn serve_properties_write(
    props: Option<&crate::properties::SharedPropertyStore>,
    method: &str,
    raw_query: &str,
) -> (u16, Vec<u8>, String, String) {
    let coord = parse_sbom_coord(raw_query);
    // Pull `key` + repeatable `value=` from the same query string.
    let (mut key, mut values) = (String::new(), Vec::<String>::new());
    for pair in raw_query.split('&').filter(|s| !s.is_empty()) {
        let (k, v) = match pair.split_once('=') {
            Some((k, v)) => (k, form_decode(v)),
            None => (pair, String::new()),
        };
        match k {
            "key" => key = v,
            "value" => {
                if !v.is_empty() {
                    values.push(v);
                }
            }
            _ => {}
        }
    }
    let label = format!(
        "{}/{}@{}",
        coord.id.namespace.as_deref().unwrap_or("-"),
        coord.id.name,
        coord.id.version,
    );
    if coord.repository.is_empty()
        || coord.id.name.is_empty()
        || coord.id.version.is_empty()
        || key.is_empty()
    {
        return (
            400,
            b"properties write needs repo, name, version and key".to_vec(),
            coord.repository,
            label,
        );
    }
    let store = match props {
        Some(s) => s,
        None => {
            return (503, b"property store not configured".to_vec(), coord.repository, label)
        }
    };
    // DELETE (or a set with no values) removes the key; otherwise set the values.
    let effective = if method == "DELETE" { Vec::new() } else { values };
    match store.set(&coord.repository, &coord.id, &key, effective) {
        Ok(map) => {
            let body = serde_json::to_vec(&map).unwrap_or_else(|_| b"{}".to_vec());
            (200, body, coord.repository, label)
        }
        Err(e) => (500, format!("property write error: {e}").into_bytes(), coord.repository, label),
    }
}

/// The repository key a request path resolves to. `/v2/{name}/…` keys by the
/// first OCI name segment; everything else by the first path segment. `None`
/// when the path has no segments.
fn route_key(path: &str) -> Option<&str> {
    let segs: Vec<&str> = path.trim_start_matches('/').split('/').filter(|s| !s.is_empty()).collect();
    match segs.as_slice() {
        ["v2", name, ..] => Some(*name),
        [first, ..] => Some(*first),
        [] => None,
    }
}

/// Authorization decision for an HTTP write/delete, mirroring
/// [`grpc::authorize_write`](crate::grpc). `identity` is the resolved principal
/// (`None` = no auth methods configured / open access). RBAC is inactive unless
/// role policy is configured; when active, the resolved role must permit the
/// action — DELETE requires admin (per the role model: admin = promote/delete),
/// other writes (PUT/POST/PATCH) require writer-or-admin — and a configured
/// policy with no authenticated identity fails closed. Returns `Ok(())` to
/// proceed, or `Err((status, detail))` to reject.
fn authorize_http_write(
    auth_config: &AuthConfig,
    identity: Option<&auth::AuthIdentity>,
    method: &str,
    repo: &str,
) -> Result<(), (u16, &'static str)> {
    if !auth_config.rbac_enabled() {
        return Ok(());
    }
    match identity {
        Some(id) => {
            let role = auth_config.role_for_repo(repo, &id.subject);
            let permitted = if method == "DELETE" {
                role.can_admin()
            } else {
                role.can_write()
            };
            crate::grpc::functional_status(
                "holger-http/authorize_http_write",
                "rbac_write_permitted",
                permitted,
                method,
            );
            if permitted {
                Ok(())
            } else {
                Err((403, "insufficient role"))
            }
        }
        None => {
            crate::grpc::functional_status(
                "holger-http/authorize_http_write",
                "rbac_write_permitted",
                false,
                "rbac configured but no authenticated identity",
            );
            Err((401, "authentication required"))
        }
    }
}

/// Resolve the backend for a request path. `/v2/{name}/…` routes by the first
/// OCI name segment; everything else by the first path segment.
fn routes_lookup(
    routes: &FastRoutes,
    path: &str,
) -> Option<std::sync::Arc<dyn traits::RepositoryBackendTrait>> {
    routes.lookup(route_key(path)?).cloned()
}

/// Serve-time quarantine predicate for the HTTP read path: does the artifact this
/// `path` addresses carry the configured quarantine property (so it must be refused
/// with 404)? `false` — never gated — unless BOTH a quarantine predicate and a
/// property store are configured AND `backend` can map `path` back to a coordinate
/// (see [`RepositoryBackendTrait::coordinate_for_path`]). Uses the same
/// [`properties::map_matches`](crate::properties::map_matches) rule as the gRPC
/// [`HolgerGrpc::is_quarantined`](crate::grpc::HolgerGrpc) gate, so `quarantine=true`
/// means the same thing on both doors (Law #5, no twin).
fn serve_quarantined(
    quarantine: Option<&(String, String)>,
    properties: Option<&crate::properties::SharedPropertyStore>,
    backend: &dyn traits::RepositoryBackendTrait,
    path: &str,
    repo_key: &str,
) -> bool {
    match (quarantine, properties) {
        (Some((key, value)), Some(store)) => match backend.coordinate_for_path(path) {
            Some(id) => crate::properties::map_matches(&store.get(repo_key, &id), key, value),
            None => false,
        },
        _ => false,
    }
}

fn text(status: u16, msg: &str) -> Response<Full<Bytes>> {
    Response::builder()
        .status(status)
        .header("Content-Type", "text/plain")
        .body(Full::new(Bytes::from(msg.to_owned())))
        .expect("static response")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::{AuthConfig, AuthIdentity, Role};
    use std::collections::HashMap;

    fn ident(sub: &str) -> AuthIdentity {
        AuthIdentity { subject: sub.to_string(), method: "mtls".into() }
    }

    fn cfg_with_roles(pairs: &[(&str, Role)], default_role: Option<Role>) -> AuthConfig {
        let mut roles = HashMap::new();
        for (s, r) in pairs {
            roles.insert((*s).to_string(), *r);
        }
        AuthConfig { methods: vec![], roles, default_role, ..Default::default() }
    }

    // A repo with no per-repo ACL → the global policy governs (unchanged behaviour).
    const R: &str = "any-repo";

    /// RBAC off (no role policy): the HTTP gateway stays authN-only — any
    /// resolved identity, and even an open-auth `None`, may write. Preserves the
    /// pre-RBAC behaviour, matching `grpc::authorize_write`.
    #[test]
    fn rbac_off_allows_all_writes() {
        let cfg = AuthConfig::default();
        assert!(authorize_http_write(&cfg, Some(&ident("alice")), "PUT", R).is_ok());
        assert!(authorize_http_write(&cfg, None, "PUT", R).is_ok());
        assert!(authorize_http_write(&cfg, None, "DELETE", R).is_ok());
    }

    /// With RBAC on, a `reader` must NOT be able to PUT/POST/DELETE through the
    /// HTTP gateway (the bug: writes were authenticated but never authorized).
    #[test]
    fn rbac_on_reader_cannot_write_or_delete() {
        let cfg = cfg_with_roles(&[("bob", Role::Reader)], None);
        assert_eq!(
            authorize_http_write(&cfg, Some(&ident("bob")), "PUT", R),
            Err((403, "insufficient role"))
        );
        assert_eq!(
            authorize_http_write(&cfg, Some(&ident("bob")), "POST", R),
            Err((403, "insufficient role"))
        );
        assert_eq!(
            authorize_http_write(&cfg, Some(&ident("bob")), "DELETE", R),
            Err((403, "insufficient role"))
        );
    }

    /// A `writer` may upload but NOT delete (delete is an admin action); an
    /// `admin` may do both.
    #[test]
    fn rbac_on_writer_uploads_admin_deletes() {
        let cfg = cfg_with_roles(&[("wendy", Role::Writer), ("alice", Role::Admin)], None);
        assert!(authorize_http_write(&cfg, Some(&ident("wendy")), "PUT", R).is_ok());
        assert_eq!(
            authorize_http_write(&cfg, Some(&ident("wendy")), "DELETE", R),
            Err((403, "insufficient role")),
            "writer must not delete"
        );
        assert!(authorize_http_write(&cfg, Some(&ident("alice")), "PUT", R).is_ok());
        assert!(authorize_http_write(&cfg, Some(&ident("alice")), "DELETE", R).is_ok());
    }

    /// RBAC configured but the write arrived with no authenticated identity:
    /// fail closed (401), never fall open.
    #[test]
    fn rbac_on_anonymous_write_fails_closed() {
        let cfg = cfg_with_roles(&[("alice", Role::Admin)], None);
        assert_eq!(
            authorize_http_write(&cfg, None, "PUT", R),
            Err((401, "authentication required"))
        );
        // An unmapped identity falls back to the least-privilege Reader → denied.
        assert_eq!(
            authorize_http_write(&cfg, Some(&ident("stranger")), "PUT", R),
            Err((403, "insufficient role"))
        );
    }

    /// `default_role: Writer` lets unmapped identities upload but still not
    /// delete — confirms the default-role path is honoured.
    #[test]
    fn rbac_default_role_writer() {
        let cfg = cfg_with_roles(&[], Some(Role::Writer));
        assert!(cfg.rbac_enabled());
        assert!(authorize_http_write(&cfg, Some(&ident("anyone")), "PUT", R).is_ok());
        assert_eq!(
            authorize_http_write(&cfg, Some(&ident("anyone")), "DELETE", R),
            Err((403, "insufficient role"))
        );
    }

    /// Per-repo ACL: a subject the GLOBAL policy makes a Reader is a Writer on the
    /// repo its ACL names — and only there. The HTTP write-gate honours the
    /// repo-scoped role.
    #[test]
    fn rbac_per_repo_acl_scopes_the_write_gate() {
        let mut cfg = cfg_with_roles(&[("carol", Role::Reader)], None);
        cfg.repo_roles.insert(
            "team-a-dev".to_string(),
            HashMap::from([("carol".to_string(), Role::Writer)]),
        );
        // On the ACL'd repo carol may upload…
        assert!(authorize_http_write(&cfg, Some(&ident("carol")), "PUT", "team-a-dev").is_ok());
        // …but not delete (that's admin, and her per-repo role is only Writer)…
        assert_eq!(
            authorize_http_write(&cfg, Some(&ident("carol")), "DELETE", "team-a-dev"),
            Err((403, "insufficient role"))
        );
        // …and on any other repo she is back to the global Reader → denied.
        assert_eq!(
            authorize_http_write(&cfg, Some(&ident("carol")), "PUT", "other-repo"),
            Err((403, "insufficient role"))
        );
    }

    // ── checksum-verify-on-deploy (X-Checksum-*) ────────────────────────────
    use sha2::{Digest as _, Sha512};

    // LAW #5 dedup: SHA-256 comes from the shared `nornir-hash` leaf (edda); only
    // the SHA-512 variant (not in the leaf) still hand-rolls sha2 here.
    fn sha256_hex(b: &[u8]) -> String {
        nornir_hash::sha256_hex(b)
    }
    fn sha512_hex(b: &[u8]) -> String {
        hex::encode(Sha512::digest(b))
    }

    /// No checksum header ⇒ verification is a no-op (opt-in): the write proceeds.
    #[test]
    fn checksum_absent_is_ok() {
        assert!(verify_upload_checksum(None, None, b"anything").is_ok());
    }

    /// An empty header value is treated as "not supplied" (opt-in), not a mismatch.
    #[test]
    fn checksum_empty_header_is_ok() {
        assert!(verify_upload_checksum(Some(""), Some("  "), b"payload").is_ok());
    }

    /// The correct sha256 for the body verifies.
    #[test]
    fn checksum_sha256_match_ok() {
        let body = b"the artifact bytes";
        assert!(verify_upload_checksum(Some(&sha256_hex(body)), None, body).is_ok());
    }

    /// Uppercase hex still matches (case-insensitive compare).
    #[test]
    fn checksum_sha256_uppercase_ok() {
        let body = b"MiXeD case digest";
        let up = sha256_hex(body).to_uppercase();
        assert!(verify_upload_checksum(Some(&up), None, body).is_ok());
    }

    /// A wrong sha256 is rejected (400) — the write never reaches a backend.
    #[test]
    fn checksum_sha256_mismatch_rejected() {
        let body = b"the artifact bytes";
        let wrong = sha256_hex(b"different bytes entirely");
        assert_eq!(
            verify_upload_checksum(Some(&wrong), None, body),
            Err((400, "sha256 checksum mismatch"))
        );
    }

    /// A garbage / wrong-length digest never accidentally matches.
    #[test]
    fn checksum_sha256_garbage_rejected() {
        assert_eq!(
            verify_upload_checksum(Some("deadbeef"), None, b"x"),
            Err((400, "sha256 checksum mismatch"))
        );
    }

    /// The correct sha512 verifies; a wrong one is rejected.
    #[test]
    fn checksum_sha512_match_and_mismatch() {
        let body = b"sha512 covered payload";
        assert!(verify_upload_checksum(None, Some(&sha512_hex(body)), body).is_ok());
        let wrong = sha512_hex(b"nope");
        assert_eq!(
            verify_upload_checksum(None, Some(&wrong), body),
            Err((400, "sha512 checksum mismatch"))
        );
    }

    /// Both digests supplied and both correct ⇒ Ok.
    #[test]
    fn checksum_both_digests_match_ok() {
        let body = b"double-checked artifact";
        assert!(verify_upload_checksum(
            Some(&sha256_hex(body)),
            Some(&sha512_hex(body)),
            body
        )
        .is_ok());
    }

    // ── /-/search query-string parsing ──────────────────────────────────────

    /// Every recognised axis parses; empty values map to `None`; repeatable
    /// `repo` accumulates; `limit` parses.
    #[test]
    fn search_query_parses_every_axis() {
        let q = parse_search_query(
            "name=serde&group=org.example&version=1.0.0&sha256=ABC&path=%2Ftmp%2Fx&repo=a&repo=b&limit=25",
        );
        assert_eq!(q.name.as_deref(), Some("serde"));
        assert_eq!(q.namespace.as_deref(), Some("org.example"));
        assert_eq!(q.version.as_deref(), Some("1.0.0"));
        assert_eq!(q.checksum.as_deref(), Some("ABC"));
        assert_eq!(q.path.as_deref(), Some("/tmp/x"), "percent-decode applied");
        assert_eq!(q.repositories, vec!["a".to_string(), "b".to_string()]);
        assert_eq!(q.limit, 25);
    }

    /// An empty query string is an all-empty (match-everything) query, and empty
    /// values / unknown keys never fabricate a criterion.
    #[test]
    fn search_query_empty_and_unknown_keys() {
        assert!(parse_search_query("").is_empty());
        let q = parse_search_query("name=&bogus=x&version=");
        assert!(q.is_empty(), "empty values + unknown keys ⇒ no criteria set");
    }

    /// `+` decodes to a space in a search term.
    #[test]
    fn search_query_plus_is_space() {
        let q = parse_search_query("name=hello+world");
        assert_eq!(q.name.as_deref(), Some("hello world"));
    }

    // ── /-/sbom door ────────────────────────────────────────────────────────

    /// Every coordinate axis parses; an empty namespace ⇒ `None`; unknown keys
    /// are ignored.
    #[test]
    fn sbom_coord_parses_axes() {
        let c = parse_sbom_coord("repo=rust-dev&group=org.example&name=serde&version=1.0.0&x=y");
        assert_eq!(c.repository, "rust-dev");
        assert_eq!(c.id.namespace.as_deref(), Some("org.example"));
        assert_eq!(c.id.name, "serde");
        assert_eq!(c.id.version, "1.0.0");
        // No namespace given ⇒ a namespace-less coordinate.
        let c2 = parse_sbom_coord("repo=r&name=n&version=1");
        assert!(c2.id.namespace.is_none());
    }

    /// The HTTP door serves an attached SBOM byte-identical (200) and answers 404
    /// for an unattached / wrong coordinate — the read twin of the RPC round-trip.
    /// The 404 branch is the RED-when-broken guard (a broken key would 200 with
    /// the wrong document).
    #[test]
    fn sbom_door_serves_byte_identical_and_404s_missing() {
        let tmp = tempfile::tempdir().unwrap();
        let store: crate::sbom::SharedSbomStore = Arc::new(crate::sbom::SbomStore::new(tmp.path()));
        let coord = traits::ArtifactId {
            namespace: None,
            name: "serde".into(),
            version: "1.0.0".into(),
        };
        let doc = crate::sbom::build_cyclonedx(&crate::sbom::SbomInput {
            subject: "rust-dev".into(),
            components: vec![],
            vulns: vec![],
        });
        store.attach("rust-dev", &coord, &doc).unwrap();

        // Hit → 200 application/json, byte-identical body.
        let (status, ct, body, repo, _label) =
            serve_sbom_door(Some(&store), "repo=rust-dev&name=serde&version=1.0.0");
        assert_eq!(status, 200);
        assert_eq!(ct, "application/json");
        assert_eq!(body, doc, "the door serves the exact attached SBOM bytes");
        assert_eq!(repo, "rust-dev");

        // Wrong version → 404, never the wrong document.
        let (miss, _, _, _, _) =
            serve_sbom_door(Some(&store), "repo=rust-dev&name=serde&version=2.0.0");
        assert_eq!(miss, 404);

        // Missing repo/name/version → 400.
        let (bad, _, _, _, _) = serve_sbom_door(Some(&store), "name=serde");
        assert_eq!(bad, 400);

        // Hosting not configured (no store) → 404.
        let (none, _, _, _, _) =
            serve_sbom_door(None, "repo=rust-dev&name=serde&version=1.0.0");
        assert_eq!(none, 404);
    }

    // ── /-/properties door + property search axis (§8) ───────────────────────

    /// `property=key:value` (and bare `property=key`) parse into `(key, value)`
    /// filters; the split is on the first ':' so a value may contain ':'.
    #[test]
    fn search_query_parses_property_filters() {
        let q = parse_search_query("name=serde&property=env:prod&prop=team:core&property=reviewed");
        assert_eq!(q.name.as_deref(), Some("serde"));
        assert_eq!(
            q.properties,
            vec![
                ("env".to_string(), "prod".to_string()),
                ("team".to_string(), "core".to_string()),
                ("reviewed".to_string(), String::new()), // bare key = any value
            ]
        );
        // A value containing ':' survives (split on FIRST ':').
        let q2 = parse_search_query("property=url:https://x.y/z");
        assert_eq!(q2.properties, vec![("url".to_string(), "https://x.y/z".to_string())]);
    }

    /// The `/-/properties` door serves a coordinate's property map as JSON, 400s
    /// an incomplete coordinate, and returns `{}` for an unset one (the empty-map
    /// branch is the RED-when-broken guard — a broken key would leak another
    /// coordinate's props).
    #[test]
    fn properties_door_serves_map_and_validates_coordinate() {
        let tmp = tempfile::tempdir().unwrap();
        let store: crate::properties::SharedPropertyStore =
            Arc::new(crate::properties::PropertyStore::new(tmp.path()));
        let coord = traits::ArtifactId { namespace: None, name: "serde".into(), version: "1.0.0".into() };
        store.set("rust-dev", &coord, "env", vec!["prod".into()]).unwrap();

        // Set coordinate → 200 with a JSON object containing the property.
        let (status, body, repo, _label) =
            serve_properties_door(Some(&store), "repo=rust-dev&name=serde&version=1.0.0");
        assert_eq!(status, 200);
        assert_eq!(repo, "rust-dev");
        let json = String::from_utf8(body).unwrap();
        assert!(json.contains("\"env\"") && json.contains("\"prod\""), "map serialized: {json}");

        // Unset coordinate → 200 with an empty object (never another coord's data).
        let (s2, b2, _, _) =
            serve_properties_door(Some(&store), "repo=rust-dev&name=serde&version=2.0.0");
        assert_eq!(s2, 200);
        assert_eq!(String::from_utf8(b2).unwrap(), "{}", "unset coord ⇒ empty map, no leak");

        // Incomplete coordinate → 400.
        let (bad, _, _, _) = serve_properties_door(Some(&store), "name=serde");
        assert_eq!(bad, 400);

        // No store configured → still a valid empty map (never an error).
        let (none, nb, _, _) =
            serve_properties_door(None, "repo=rust-dev&name=serde&version=1.0.0");
        assert_eq!(none, 200);
        assert_eq!(String::from_utf8(nb).unwrap(), "{}");
    }

    /// The `PUT /-/properties` write door sets values, `DELETE` removes, and both
    /// validate the coordinate + key. The set-then-read-back and the remove are
    /// the RED-when-broken guards (a broken write path would 200 but persist
    /// nothing / the wrong thing).
    #[test]
    fn properties_write_door_sets_and_removes() {
        let tmp = tempfile::tempdir().unwrap();
        let store: crate::properties::SharedPropertyStore =
            Arc::new(crate::properties::PropertyStore::new(tmp.path()));

        // PUT with two values → 200, stored.
        let (s, body, repo, _l) = serve_properties_write(
            Some(&store),
            "PUT",
            "repo=rust-dev&name=serde&version=1.0.0&key=env&value=prod&value=staging",
        );
        assert_eq!(s, 200);
        assert_eq!(repo, "rust-dev");
        assert!(String::from_utf8(body).unwrap().contains("staging"), "response echoes the map");
        // Read back through the store: the values persisted.
        let coord = traits::ArtifactId { namespace: None, name: "serde".into(), version: "1.0.0".into() };
        assert_eq!(
            store.get("rust-dev", &coord).get("env").unwrap(),
            &vec!["prod".to_string(), "staging".to_string()]
        );

        // DELETE removes the key.
        let (sd, _b, _r, _l) =
            serve_properties_write(Some(&store), "DELETE", "repo=rust-dev&name=serde&version=1.0.0&key=env");
        assert_eq!(sd, 200);
        assert!(store.get("rust-dev", &coord).is_empty(), "DELETE removed the key");

        // Missing key → 400.
        let (bad, _b, _r, _l) =
            serve_properties_write(Some(&store), "PUT", "repo=rust-dev&name=serde&version=1.0.0");
        assert_eq!(bad, 400);

        // No store configured → 503, never a silent success.
        let (unavail, _b, _r, _l) =
            serve_properties_write(None, "PUT", "repo=r&name=n&version=1&key=k&value=v");
        assert_eq!(unavail, 503);
    }
}