s4-server 0.8.6

S4 — Squished S3 — GPU-accelerated transparent compression S3-compatible storage gateway (cargo install s4-server installs the `s4` binary).
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
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
//! `/health` と `/ready` の HTTP routing layer + CORS OPTIONS preflight
//! interceptor + SigV4a verify gate。
//!
//! S3 server と同じポートで health probe に応答できると AWS ALB / NLB / k8s
//! readiness probe との統合が単純になる。
//!
//! - `GET /health` → 常に `200 OK` (server プロセスが生きていれば返す)
//! - `GET /ready` → `ready_check` future を await し、`Ok(())` なら 200、
//!   それ以外 (backend 不通等) は 503。
//! - `OPTIONS /<bucket>[/<key>]` (Origin + Access-Control-Request-Method 付き)
//!   → v0.7 #44: `cors_manager` が attach されていれば、bucket の登録された
//!   rule list に対して preflight match を実行し、200 + Allow-* header を
//!   組み立てて返す (no match なら 403)。s3s framework は OPTIONS verb を
//!   typed handler として持たないため、HTTP-level の interceptor で寄せる。
//! - `Authorization: AWS4-ECDSA-P256-SHA256 ...` (SigV4a) を持つ request
//!   → v0.7 #47: `sigv4a_gate` が attach されていれば、listener 側で署名を
//!   verify し、success なら inner S3Service へ forward、failure なら 403
//!   `SignatureDoesNotMatch` / `InvalidAccessKeyId` を直接返す。s3s 既存の
//!   SigV4 verifier は `AWS4-ECDSA-P256-SHA256` を "unknown algorithm" として
//!   reject するため、middleware を挟まないと SigV4a request は届かない。
//! - その他のパス → inner S3Service へ委譲

use std::convert::Infallible;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use bytes::Bytes;
use http_body_util::Full;
use hyper::body::Incoming;
use hyper::service::Service;
use hyper::{Method, Request, Response, StatusCode};
use metrics_exporter_prometheus::PrometheusHandle;

use crate::cors::{CorsManager, CorsRule};
use crate::service::SigV4aGate;

/// readiness check 関数。bound is `Send + Sync` for cross-task use.
pub type ReadyCheck =
    Arc<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), String>> + Send>> + Send + Sync>;

/// inner service と health/ready/metrics + CORS preflight handler +
/// SigV4a verify gate を合成する hyper Service。
#[derive(Clone)]
pub struct HealthRouter<S> {
    pub inner: S,
    pub ready_check: Option<ReadyCheck>,
    pub metrics_handle: Option<PrometheusHandle>,
    /// v0.7 #44: optional CORS bucket-config manager. When attached,
    /// OPTIONS requests carrying `Origin` + `Access-Control-Request-Method`
    /// are intercepted before reaching the s3s service and answered
    /// directly with Access-Control-Allow-* headers (or 403 if no rule
    /// matches). When `None`, OPTIONS falls through to the inner service
    /// (s3s typically returns 405 since no S3 handler maps to OPTIONS).
    pub cors_manager: Option<Arc<CorsManager>>,
    /// v0.7 #47: optional SigV4a verify gate. When attached, requests
    /// whose `Authorization` header begins with `AWS4-ECDSA-P256-SHA256`
    /// (or that carry `X-Amz-Region-Set`) are verified at the HTTP
    /// layer using the configured ECDSA-P-256 credential store; on
    /// failure the listener returns 403 directly. When `None`, the
    /// gate is a no-op so plain SigV4 deployments are unaffected.
    pub sigv4a_gate: Option<Arc<SigV4aGate>>,
    /// v0.7 #47: region name used when checking
    /// `X-Amz-Region-Set` membership during SigV4a verification. The
    /// listener is single-region in this milestone — operators that
    /// front S4 with a Multi-Region Access Point set this to the
    /// canonical "this listener's region" string. Defaults to
    /// `"us-east-1"` (the AWS-default region when none is configured).
    pub region: String,
}

impl<S> HealthRouter<S> {
    pub fn new(inner: S, ready_check: Option<ReadyCheck>) -> Self {
        Self {
            inner,
            ready_check,
            metrics_handle: None,
            cors_manager: None,
            sigv4a_gate: None,
            region: "us-east-1".to_string(),
        }
    }

    #[must_use]
    pub fn with_metrics(mut self, handle: PrometheusHandle) -> Self {
        self.metrics_handle = Some(handle);
        self
    }

    /// v0.7 #44: attach an `Arc<CorsManager>` so OPTIONS preflight
    /// requests are handled at the HTTP layer instead of falling through
    /// to s3s.
    #[must_use]
    pub fn with_cors_manager(mut self, mgr: Arc<CorsManager>) -> Self {
        self.cors_manager = Some(mgr);
        self
    }

    /// v0.7 #47: attach an `Arc<SigV4aGate>` so `AWS4-ECDSA-P256-SHA256`
    /// requests are verified at the HTTP layer instead of being
    /// rejected by s3s' SigV4 verifier as "unknown algorithm".
    #[must_use]
    pub fn with_sigv4a_gate(mut self, gate: Arc<SigV4aGate>) -> Self {
        self.sigv4a_gate = Some(gate);
        self
    }

    /// v0.7 #47: override the listener's "served region" string used
    /// to check `X-Amz-Region-Set` membership during SigV4a
    /// verification. Defaults to `"us-east-1"`.
    #[must_use]
    pub fn with_region(mut self, region: impl Into<String>) -> Self {
        self.region = region.into();
        self
    }
}

/// v0.7 #44: HTTP-level OPTIONS preflight interceptor.
///
/// Returns:
/// - `Some(response)` if `req` is an OPTIONS preflight (Origin +
///   Access-Control-Request-Method headers present) targeting a bucket
///   with CORS configured. The response is 200 with Allow-* headers
///   when a rule matches, or 403 when no rule matches the
///   (origin, method, headers) triple.
/// - `None` if the request is not a preflight, or no CORS config is
///   registered for the target bucket — caller forwards to the s3s
///   service.
///
/// `cors` is `Option<&Arc<CorsManager>>` so callers can pass through
/// the inner service's optional manager without unwrapping first.
///
/// Generic over the request body type `B` so unit tests can drive the
/// matcher with `Request<()>` without constructing a real `Incoming`
/// stream (only headers, method, and URI are inspected).
#[must_use]
pub fn try_handle_preflight<B>(
    req: &Request<B>,
    cors: Option<&Arc<CorsManager>>,
) -> Option<Response<s3s::Body>> {
    if req.method() != Method::OPTIONS {
        return None;
    }
    let mgr = cors?;
    // Path is `/<bucket>` or `/<bucket>/<key>` — first segment is bucket.
    // Empty path or a query-only request has no bucket and is not a
    // preflight we can answer.
    let path = req.uri().path();
    let bucket = path.trim_start_matches('/').split('/').next()?;
    if bucket.is_empty() {
        return None;
    }
    let origin = req.headers().get("origin")?.to_str().ok()?;
    let method = req
        .headers()
        .get("access-control-request-method")?
        .to_str()
        .ok()?;
    // Access-Control-Request-Headers is a comma-separated list, optional
    // (browsers omit it when no custom headers are being sent).
    let req_headers: Vec<String> = req
        .headers()
        .get("access-control-request-headers")
        .and_then(|h| h.to_str().ok())
        .map(|s| {
            s.split(',')
                .map(|t| t.trim().to_string())
                .filter(|t| !t.is_empty())
                .collect()
        })
        .unwrap_or_default();
    // No config for this bucket → not our problem (let s3s handle / 404).
    // We need to distinguish "no config" from "config but no rule matches"
    // to correctly fall through vs. return 403.
    let _ = mgr.get(bucket)?;
    match mgr.match_preflight(bucket, origin, method, &req_headers) {
        Some(rule) => Some(build_preflight_allow_response(&rule, origin)),
        None => Some(build_preflight_deny_response()),
    }
}

/// 200 response with the matched rule's Allow-* headers.
fn build_preflight_allow_response(rule: &CorsRule, origin: &str) -> Response<s3s::Body> {
    let mut builder = Response::builder().status(StatusCode::OK);
    // Echo the matched origin: literal "*" if the rule used a wildcard,
    // otherwise the requesting origin verbatim (S3 spec).
    let allow_origin: String = if rule.allowed_origins.iter().any(|o| o == "*") {
        "*".into()
    } else {
        origin.to_owned()
    };
    builder = builder.header("Access-Control-Allow-Origin", allow_origin);
    builder = builder.header(
        "Access-Control-Allow-Methods",
        rule.allowed_methods.join(", "),
    );
    if !rule.allowed_headers.is_empty() {
        builder = builder.header(
            "Access-Control-Allow-Headers",
            rule.allowed_headers.join(", "),
        );
    }
    if !rule.expose_headers.is_empty() {
        builder = builder.header(
            "Access-Control-Expose-Headers",
            rule.expose_headers.join(", "),
        );
    }
    if let Some(secs) = rule.max_age_seconds {
        builder = builder.header("Access-Control-Max-Age", secs.to_string());
    }
    // Empty body, but set content-length explicitly for clarity.
    let bytes = Bytes::new();
    builder = builder.header("content-length", "0");
    builder
        .body(s3s::Body::http_body(
            Full::new(bytes).map_err(|never| match never {}),
        ))
        .expect("preflight response builder")
}

/// 403 response when an OPTIONS preflight reaches a bucket with CORS
/// configured but no rule matches the (origin, method, headers) triple.
fn build_preflight_deny_response() -> Response<s3s::Body> {
    let body = Bytes::from_static(b"CORSResponse: This CORS request is not allowed.");
    Response::builder()
        .status(StatusCode::FORBIDDEN)
        .header("content-type", "text/plain; charset=utf-8")
        .header("content-length", body.len().to_string())
        .body(s3s::Body::http_body(
            Full::new(body).map_err(|never| match never {}),
        ))
        .expect("preflight deny response builder")
}

// ===========================================================================
// v0.7 #47 — SigV4a verify gate middleware.
// ===========================================================================

/// v0.7 #47: Try to verify the request as SigV4a-signed.
///
/// Returns:
/// - `None` if the request is not SigV4a-signed (no `AWS4-ECDSA-P256-SHA256`
///   `Authorization` prefix and no `X-Amz-Region-Set` header) — the
///   caller forwards the request to s3s for the default SigV4 path.
/// - `Some(Ok(()))` if SigV4a verify succeeded — the caller forwards to
///   the inner service so the S3 handler runs.
/// - `Some(Err(response))` if SigV4a verify failed — the caller returns
///   the 403 response directly without ever invoking the inner service.
///
/// `gate` is `Option<&Arc<SigV4aGate>>` so callers can pass through the
/// router's optional gate without unwrapping first; when `None`, this
/// function always returns `None` (no SigV4a verification configured).
///
/// `requested_region` is the listener's served region (used to validate
/// the request's `X-Amz-Region-Set` header membership).
///
/// Generic over the request body type `B` so unit tests can drive the
/// matcher with `Request<()>` without constructing a real `Incoming`
/// stream — only headers, method, and URI participate in the canonical
/// request bytes built here.
///
/// # Canonical request bytes
///
/// We build a SigV4-shaped canonical request from the HTTP-layer
/// signal alone (method, URI path, sorted query string, headers in the
/// order listed by `SignedHeaders=`, and `x-amz-content-sha256` as the
/// payload hash — the standard "client-supplied body hash" convention
/// every AWS SDK uses). Reading the body would force a `Request<Bytes>`
/// rebuild and break the s3s framework's streaming-body assumptions, so
/// the payload-hash header is the only correct source for SigV4a.
///
/// Clients that want to sign over the body must include the actual
/// SHA-256 of the body in `x-amz-content-sha256`; clients that don't
/// (most S3 SDKs default to `UNSIGNED-PAYLOAD` for streaming PUTs) sign
/// over that literal string instead. Either way the bytes the gate
/// compares against are exactly what the client computed.
pub fn try_sigv4a_verify<B>(
    req: &Request<B>,
    gate: Option<&Arc<SigV4aGate>>,
    requested_region: &str,
) -> Option<Result<(), Response<s3s::Body>>> {
    try_sigv4a_verify_at(req, gate, requested_region, chrono::Utc::now())
}

/// v0.8.4 #76: like [`try_sigv4a_verify`] but takes an explicit `now`
/// for tests that need to pin the freshness clock without time-warping
/// the system clock. Production callers always reach this via
/// `try_sigv4a_verify` (which calls `chrono::Utc::now()`).
pub fn try_sigv4a_verify_at<B>(
    req: &Request<B>,
    gate: Option<&Arc<SigV4aGate>>,
    requested_region: &str,
    now: chrono::DateTime<chrono::Utc>,
) -> Option<Result<(), Response<s3s::Body>>> {
    let gate = gate?;
    if !crate::sigv4a::detect(req) {
        // Not a SigV4a request — caller forwards to the SigV4 path.
        return None;
    }
    // Pre-parse the Authorization header so we know which signed-headers
    // list to canonicalise in. If the header is malformed, fail fast
    // with 403 rather than building canonical bytes that can never
    // verify.
    //
    // v0.8.4 #76: `parse_authorization_header` now returns `Result`
    // (was `Option`) so the gate can surface scope-shape failures
    // (`InvalidCredentialScope`, `WrongService`, etc.) as 400
    // InvalidRequest. Any non-Ok parse falls through to the
    // SignatureDoesNotMatch 403 the original code returned, since at
    // this point we can't extract a `signed_headers` list to feed the
    // canonical-request builder.
    let auth_hdr = req
        .headers()
        .get(http::header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok());
    let signed_headers: Vec<String> =
        match auth_hdr.and_then(|hdr| crate::sigv4a::parse_authorization_header(hdr).ok()) {
            Some(parsed) => parsed.signed_headers,
            None => {
                // No / unparseable Authorization header but `detect` flagged
                // it as SigV4a-shaped (e.g. only the region-set header is
                // present) — surface as SignatureDoesNotMatch directly.
                return Some(Err(build_sigv4a_error_response(
                    StatusCode::FORBIDDEN,
                    "SignatureDoesNotMatch",
                    "missing or malformed Authorization header for SigV4a request",
                )));
            }
        };
    let canonical = match build_canonical_request_bytes(req, &signed_headers) {
        Ok(bytes) => bytes,
        Err(err) => {
            // v0.8.5 #84 H-4: duplicate signed header (only failure
            // mode the canonical builder has today). Surface as
            // `SignatureDoesNotMatch` 403 — the AWS SDKs treat that
            // as the catch-all auth-failure code, and the diagnostic
            // is in the response body / server log.
            tracing::warn!(error = %err, "SigV4a canonical-request build rejected request");
            return Some(Err(build_sigv4a_error_response(
                StatusCode::FORBIDDEN,
                "SignatureDoesNotMatch",
                &err.to_string(),
            )));
        }
    };
    match gate.pre_route_at(req, requested_region, &canonical, now) {
        Ok(()) => Some(Ok(())),
        Err(err) => {
            tracing::warn!(error = %err, "SigV4a verify rejected request");
            Some(Err(build_sigv4a_error_response(
                err.http_status(),
                err.s3_error_code(),
                &err.to_string(),
            )))
        }
    }
}

/// v0.7 #47: build a SigV4-shaped canonical request from the HTTP
/// surface alone (no body access). Returns the bytes that the
/// SigV4a gate will check the ECDSA signature against.
///
/// Format (one element per line, joined with `\n`):
/// 1. HTTP method (uppercase)
/// 2. canonical URI (path; we leave it untouched since AWS SDKs
///    pre-encode it the same way s3s receives it)
/// 3. canonical query string (sorted by name, name=value pairs joined
///    by `&`; empty when no query string)
/// 4. canonical headers (one `name:trimmed-value\n` per signed header,
///    in the **order** they appear in `SignedHeaders=`)
/// 5. signed headers list (lowercase names joined by `;`)
/// 6. payload hash (value of `x-amz-content-sha256`, or `UNSIGNED-PAYLOAD`
///    if absent)
///
/// v0.8.5 #84 (audit H-4): every signed header is checked for being
/// sent **exactly once** on the request. If a header in
/// `SignedHeaders=` appears more than once we'd have to choose between
/// the first value (`HeaderMap::get` semantics) and the comma-joined
/// AWS-canonical form — and any S3 SDK / WAF / sidecar in front of us
/// would make a different choice, opening "auth confusion" attacks
/// (sign over the benign first `x-amz-date`, smuggle a second one for
/// the inner parser). HTTP/1.1 spec already forbids duplicates of
/// `host` / `x-amz-date` and the AWS SDKs never emit them, so any
/// duplicate is a malicious or broken request — reject upfront with
/// [`SigV4aError::DuplicateSignedHeader`].
fn build_canonical_request_bytes<B>(
    req: &Request<B>,
    signed_headers: &[String],
) -> Result<Vec<u8>, crate::sigv4a::SigV4aError> {
    let mut buf = String::with_capacity(512);
    buf.push_str(req.method().as_str());
    buf.push('\n');
    buf.push_str(req.uri().path());
    buf.push('\n');
    buf.push_str(&canonical_query_string(req.uri().query().unwrap_or("")));
    buf.push('\n');
    for name in signed_headers {
        // v0.8.5 #84 H-4: count occurrences via `get_all` rather than
        // `get`, which only ever returns the first value. Two
        // `x-amz-date` headers with `get` would canonicalise to the
        // first value while a downstream HTTP/1.1 parser might pick
        // the second — auth confusion. Single-value reject is the
        // safe choice; comma-join would be the AWS-canonical form
        // for legitimately multi-valued signed headers, but the AWS
        // SDKs never sign over comma-joined values for any header
        // S3 cares about, so refusing duplicates outright matches
        // every real-world client.
        let occurrences = req.headers().get_all(name.as_str()).iter().count();
        if occurrences > 1 {
            return Err(crate::sigv4a::SigV4aError::DuplicateSignedHeader {
                header: name.clone(),
            });
        }
        let value = req
            .headers()
            .get(name.as_str())
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
        buf.push_str(name);
        buf.push(':');
        // Trim whitespace and collapse repeated inner whitespace per
        // SigV4 canonicalisation rules. This is the same trimming AWS
        // SDKs do when they sign.
        buf.push_str(&trim_collapse_ws(value));
        buf.push('\n');
    }
    buf.push('\n');
    buf.push_str(&signed_headers.join(";"));
    buf.push('\n');
    let payload_hash = req
        .headers()
        .get("x-amz-content-sha256")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("UNSIGNED-PAYLOAD");
    buf.push_str(payload_hash);
    Ok(buf.into_bytes())
}

/// SigV4 canonical query string: split on `&`, parse each `k=v` (or
/// `k`), sort lexicographically by name (then by value), re-join with
/// `&`. Empty input → empty string. We do **not** re-encode the values
/// — they already arrived URL-encoded over the wire, and AWS SDKs
/// expect the server to compare the bytes verbatim.
fn canonical_query_string(query: &str) -> String {
    if query.is_empty() {
        return String::new();
    }
    let mut pairs: Vec<(&str, &str)> = query
        .split('&')
        .filter(|s| !s.is_empty())
        .map(|kv| match kv.split_once('=') {
            Some((k, v)) => (k, v),
            None => (kv, ""),
        })
        .collect();
    pairs.sort_by(|a, b| a.0.cmp(b.0).then_with(|| a.1.cmp(b.1)));
    let mut out = String::with_capacity(query.len());
    for (i, (k, v)) in pairs.iter().enumerate() {
        if i > 0 {
            out.push('&');
        }
        out.push_str(k);
        out.push('=');
        out.push_str(v);
    }
    out
}

/// SigV4 header-value canonicalisation: trim leading + trailing
/// whitespace and collapse runs of internal whitespace to a single
/// space. This mirrors what AWS SDKs do client-side when computing the
/// canonical request — without it, a header value with extra spaces
/// would canonicalise differently on each side.
fn trim_collapse_ws(s: &str) -> String {
    let trimmed = s.trim();
    let mut out = String::with_capacity(trimmed.len());
    let mut prev_ws = false;
    for c in trimmed.chars() {
        if c.is_whitespace() {
            if !prev_ws {
                out.push(' ');
            }
            prev_ws = true;
        } else {
            out.push(c);
            prev_ws = false;
        }
    }
    out
}

/// v0.7 #47: build an AWS-shaped XML response for a SigV4a verify
/// failure. The response body matches the wire format AWS S3 emits for
/// the same conditions so SDKs surface the right exception class to the
/// caller.
///
/// v0.8.4 #76: now takes `status` so the gate can return 400
/// InvalidRequest for malformed-input failures (missing x-amz-date,
/// wrong service scope, etc.) and 403 for actual auth failures.
fn build_sigv4a_error_response(
    status: StatusCode,
    code: &str,
    message: &str,
) -> Response<s3s::Body> {
    let body_str = format!(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
         <Error>\n  <Code>{code}</Code>\n  <Message>{message}</Message>\n</Error>"
    );
    let bytes = Bytes::from(body_str.into_bytes());
    Response::builder()
        .status(status)
        .header("content-type", "application/xml")
        .header("content-length", bytes.len().to_string())
        .body(s3s::Body::http_body(
            Full::new(bytes).map_err(|never| match never {}),
        ))
        .expect("sigv4a error response builder")
}

/// `/health` と `/ready` のレスポンス Body。
/// inner S3Service の Body と互換する形にするために `s3s::Body` でラップ可能な
/// `Full<Bytes>` を `s3s::Body::http_body` 経由で構築する。
type RespBody = s3s::Body;

fn make_text_response(status: StatusCode, body: &'static str) -> Response<RespBody> {
    let bytes = Bytes::from_static(body.as_bytes());
    Response::builder()
        .status(status)
        .header("content-type", "text/plain; charset=utf-8")
        .header("content-length", bytes.len().to_string())
        .body(s3s::Body::http_body(
            Full::new(bytes).map_err(|never| match never {}),
        ))
        .expect("static response")
}

fn make_owned_text_response(
    status: StatusCode,
    content_type: &'static str,
    body: String,
) -> Response<RespBody> {
    let bytes = Bytes::from(body.into_bytes());
    Response::builder()
        .status(status)
        .header("content-type", content_type)
        .header("content-length", bytes.len().to_string())
        .body(s3s::Body::http_body(
            Full::new(bytes).map_err(|never| match never {}),
        ))
        .expect("owned response")
}

impl<S> Service<Request<Incoming>> for HealthRouter<S>
where
    S: Service<Request<Incoming>, Response = Response<s3s::Body>, Error = s3s::HttpError>
        + Clone
        + Send
        + 'static,
    S::Future: Send + 'static,
{
    type Response = Response<RespBody>;
    type Error = s3s::HttpError;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn call(&self, req: Request<Incoming>) -> Self::Future {
        // v0.7 #44: short-circuit CORS OPTIONS preflight at the HTTP layer
        // before health/metrics dispatch. Preflight must run only for
        // OPTIONS requests, and only when a CORS manager is attached and
        // a config exists for the requested bucket; otherwise fall
        // through to the existing routing logic.
        if let Some(resp) = try_handle_preflight(&req, self.cors_manager.as_ref()) {
            return Box::pin(async move { Ok(resp) });
        }
        // v0.7 #47: SigV4a verify gate. When the request is signed with
        // `AWS4-ECDSA-P256-SHA256` and a credential store is configured,
        // verify here at the HTTP layer (s3s' SigV4 verifier would
        // otherwise reject the request as "unknown algorithm" before
        // any handler ran). Plain SigV4 (HMAC) requests return `None`
        // and fall through to the inner service untouched.
        if let Some(result) = try_sigv4a_verify(&req, self.sigv4a_gate.as_ref(), &self.region) {
            match result {
                Ok(()) => {
                    // verified — fall through to the path-routing logic
                    // below (the health/metrics/inner-service dispatch).
                }
                Err(resp) => return Box::pin(async move { Ok(resp) }),
            }
        }
        let path = req.uri().path();
        match (req.method(), path) {
            (&hyper::Method::GET, "/health") | (&hyper::Method::HEAD, "/health") => {
                Box::pin(async { Ok(make_text_response(StatusCode::OK, "ok\n")) })
            }
            (&hyper::Method::GET, "/metrics") | (&hyper::Method::HEAD, "/metrics") => {
                let handle = self.metrics_handle.clone();
                Box::pin(async move {
                    match handle {
                        Some(h) => {
                            let body = h.render();
                            Ok(make_owned_text_response(
                                StatusCode::OK,
                                "text/plain; version=0.0.4; charset=utf-8",
                                body,
                            ))
                        }
                        None => Ok(make_text_response(
                            StatusCode::SERVICE_UNAVAILABLE,
                            "metrics not configured\n",
                        )),
                    }
                })
            }
            (&hyper::Method::GET, "/ready") | (&hyper::Method::HEAD, "/ready") => {
                let check = self.ready_check.clone();
                Box::pin(async move {
                    match check {
                        Some(f) => match f().await {
                            Ok(()) => Ok(make_text_response(StatusCode::OK, "ready\n")),
                            Err(reason) => {
                                tracing::warn!(%reason, "readiness check failed");
                                Ok(make_text_response(
                                    StatusCode::SERVICE_UNAVAILABLE,
                                    "not ready\n",
                                ))
                            }
                        },
                        None => Ok(make_text_response(StatusCode::OK, "ready (no check)\n")),
                    }
                })
            }
            _ => {
                let inner = self.inner.clone();
                Box::pin(async move { inner.call(req).await })
            }
        }
    }
}

/// `Infallible` を anything に変換するためのトリック (`Full::map_err` 用)
trait FullExt<B> {
    fn map_err<E, F: FnMut(Infallible) -> E>(
        self,
        f: F,
    ) -> http_body_util::combinators::MapErr<Self, F>
    where
        Self: Sized;
}
impl<B> FullExt<B> for Full<B>
where
    B: bytes::Buf,
{
    fn map_err<E, F: FnMut(Infallible) -> E>(
        self,
        f: F,
    ) -> http_body_util::combinators::MapErr<Self, F>
    where
        Self: Sized,
    {
        http_body_util::BodyExt::map_err(self, f)
    }
}

#[cfg(test)]
mod preflight_tests {
    //! v0.7 #44: unit tests for the OPTIONS preflight interceptor.
    //!
    //! These exercise [`try_handle_preflight`] directly — no hyper
    //! `Incoming` body is needed because the function is generic over
    //! the body type. Behavioural matrix:
    //!
    //! 1. matching preflight → 200 + Allow-* headers
    //! 2. no matching rule (config exists, but origin/method/headers fail)
    //!    → 403
    //! 3. missing `Origin` header → `None` (not a CORS preflight)
    //! 4. non-OPTIONS verb → `None`
    //! 5. no CORS config registered for the bucket → `None`
    //! 6. no manager attached → `None`

    use super::*;
    use crate::cors::{CorsConfig, CorsManager, CorsRule};

    fn rule(origins: &[&str], methods: &[&str], headers: &[&str]) -> CorsRule {
        CorsRule {
            allowed_origins: origins.iter().map(|s| (*s).to_owned()).collect(),
            allowed_methods: methods.iter().map(|s| (*s).to_owned()).collect(),
            allowed_headers: headers.iter().map(|s| (*s).to_owned()).collect(),
            expose_headers: vec!["ETag".into()],
            max_age_seconds: Some(600),
            id: Some("test".into()),
        }
    }

    /// Helper: build a `Request<()>` with the given method, path, and
    /// headers — body is ignored by the matcher.
    fn req(method: Method, path: &str, headers: &[(&str, &str)]) -> Request<()> {
        let mut b = Request::builder().method(method).uri(path);
        for (k, v) in headers {
            b = b.header(*k, *v);
        }
        b.body(()).expect("request builder")
    }

    fn manager_with_rule() -> Arc<CorsManager> {
        let mgr = CorsManager::new();
        mgr.put(
            "b",
            CorsConfig {
                rules: vec![rule(
                    &["https://app.example.com"],
                    &["GET", "PUT", "DELETE"],
                    &["Content-Type", "X-Amz-Date"],
                )],
            },
        );
        Arc::new(mgr)
    }

    #[test]
    fn preflight_match_returns_allow_response() {
        let mgr = manager_with_rule();
        let r = req(
            Method::OPTIONS,
            "/b/key.txt",
            &[
                ("origin", "https://app.example.com"),
                ("access-control-request-method", "PUT"),
                ("access-control-request-headers", "content-type, x-amz-date"),
            ],
        );
        let resp = try_handle_preflight(&r, Some(&mgr)).expect("must intercept");
        assert_eq!(resp.status(), StatusCode::OK);
        let h = resp.headers();
        assert_eq!(
            h.get("access-control-allow-origin")
                .and_then(|v| v.to_str().ok()),
            Some("https://app.example.com")
        );
        assert_eq!(
            h.get("access-control-allow-methods")
                .and_then(|v| v.to_str().ok()),
            Some("GET, PUT, DELETE")
        );
        assert_eq!(
            h.get("access-control-allow-headers")
                .and_then(|v| v.to_str().ok()),
            Some("Content-Type, X-Amz-Date")
        );
        assert_eq!(
            h.get("access-control-max-age")
                .and_then(|v| v.to_str().ok()),
            Some("600")
        );
        assert_eq!(
            h.get("access-control-expose-headers")
                .and_then(|v| v.to_str().ok()),
            Some("ETag")
        );
    }

    #[test]
    fn preflight_no_match_returns_403() {
        let mgr = manager_with_rule();
        // Origin not in allow-list → no rule matches but bucket has CORS
        // config, so we must answer 403 directly (not fall through to
        // s3s, which would otherwise leak the bucket existence via 405).
        let r = req(
            Method::OPTIONS,
            "/b/key.txt",
            &[
                ("origin", "https://evil.example.com"),
                ("access-control-request-method", "PUT"),
            ],
        );
        let resp = try_handle_preflight(&r, Some(&mgr)).expect("must intercept");
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        // 403 deny response must NOT carry Allow-Origin (RFC 7234 + S3 wire compat).
        assert!(resp.headers().get("access-control-allow-origin").is_none());
    }

    #[test]
    fn preflight_no_origin_falls_through() {
        // OPTIONS without Origin is a generic OPTIONS (e.g. `OPTIONS *`)
        // — not a CORS preflight, must not be intercepted.
        let mgr = manager_with_rule();
        let r = req(
            Method::OPTIONS,
            "/b/key.txt",
            &[("access-control-request-method", "PUT")],
        );
        assert!(try_handle_preflight(&r, Some(&mgr)).is_none());
    }

    #[test]
    fn non_options_falls_through() {
        let mgr = manager_with_rule();
        // Even with Origin + ACRM headers, GET is not a preflight.
        let r = req(
            Method::GET,
            "/b/key.txt",
            &[
                ("origin", "https://app.example.com"),
                ("access-control-request-method", "PUT"),
            ],
        );
        assert!(try_handle_preflight(&r, Some(&mgr)).is_none());
    }

    #[test]
    fn no_cors_config_for_bucket_falls_through() {
        // Manager attached but no rule registered for "ghost" → fall
        // through to inner service so backend can respond naturally.
        let mgr = manager_with_rule();
        let r = req(
            Method::OPTIONS,
            "/ghost/key.txt",
            &[
                ("origin", "https://app.example.com"),
                ("access-control-request-method", "PUT"),
            ],
        );
        assert!(try_handle_preflight(&r, Some(&mgr)).is_none());
    }

    #[test]
    fn no_manager_attached_falls_through() {
        let r = req(
            Method::OPTIONS,
            "/b/key.txt",
            &[
                ("origin", "https://app.example.com"),
                ("access-control-request-method", "PUT"),
            ],
        );
        assert!(try_handle_preflight(&r, None).is_none());
    }

    #[test]
    fn preflight_wildcard_origin_echoes_star() {
        // Rule with `*` origin → response echoes literal "*" (S3 spec).
        let mgr = CorsManager::new();
        mgr.put(
            "b",
            CorsConfig {
                rules: vec![rule(&["*"], &["GET", "PUT"], &["*"])],
            },
        );
        let mgr = Arc::new(mgr);
        let r = req(
            Method::OPTIONS,
            "/b/key",
            &[
                ("origin", "https://anywhere.example"),
                ("access-control-request-method", "PUT"),
                ("access-control-request-headers", "x-custom-header"),
            ],
        );
        let resp = try_handle_preflight(&r, Some(&mgr)).expect("must intercept");
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(
            resp.headers()
                .get("access-control-allow-origin")
                .and_then(|v| v.to_str().ok()),
            Some("*"),
            "wildcard rule must echo literal '*' instead of requesting origin"
        );
    }

    #[test]
    fn preflight_empty_path_falls_through() {
        let mgr = manager_with_rule();
        let r = req(
            Method::OPTIONS,
            "/",
            &[
                ("origin", "https://app.example.com"),
                ("access-control-request-method", "PUT"),
            ],
        );
        assert!(try_handle_preflight(&r, Some(&mgr)).is_none());
    }
}

#[cfg(test)]
mod sigv4a_gate_tests {
    //! v0.7 #47: unit tests for the SigV4a verify gate middleware.
    //!
    //! These exercise [`try_sigv4a_verify`] directly — no hyper
    //! `Incoming` body is needed because the function is generic over
    //! the body type. The canonical-request bytes computed by the
    //! middleware are the same bytes the test signs over (we use the
    //! `build_canonical_request_bytes` helper for both sides), so the
    //! happy-path verify is end-to-end byte-exact.
    //!
    //! Behavioural matrix:
    //!
    //! 1. no `AWS4-ECDSA-P256-SHA256` prefix and no region-set header
    //!    → `None` (caller forwards to s3s SigV4 path)
    //! 2. SigV4a Authorization + valid signature → `Some(Ok(()))`
    //! 3. SigV4a Authorization + tampered signature → `Some(Err(403))`
    //!    with `SignatureDoesNotMatch` body
    //! 4. SigV4a Authorization + region-set mismatch → `Some(Err(403))`
    //! 5. gate is `None` (no credential store) → `None` even when the
    //!    request looks SigV4a-shaped (caller forwards, and s3s will
    //!    surface its own "unknown algorithm" error — operator sees the
    //!    misconfiguration rather than a silent pass)
    //! 6. unknown access-key-id → `Some(Err(403))` with
    //!    `InvalidAccessKeyId` body
    //! 7. SigV4a-shaped (region-set header only, no SigV4a auth header)
    //!    → `Some(Err(403))` (we cannot verify without a parseable
    //!    Authorization, fail closed)

    use super::*;

    use std::collections::HashMap;

    use http_body_util::BodyExt;
    use p256::ecdsa::SigningKey;
    use p256::ecdsa::signature::Signer;
    use rand::rngs::OsRng;

    use crate::service::SigV4aGate;
    use crate::sigv4a::{REGION_SET_HEADER, SigV4aCredentialStore};

    fn lower_hex(bytes: &[u8]) -> String {
        let mut s = String::with_capacity(bytes.len() * 2);
        for b in bytes {
            s.push_str(&format!("{b:02x}"));
        }
        s
    }

    /// Build a `Request<()>` with the given method, path, and headers.
    fn req(method: Method, path: &str, headers: &[(&str, &str)]) -> Request<()> {
        let mut b = Request::builder().method(method).uri(path);
        for (k, v) in headers {
            b = b.header(*k, *v);
        }
        b.body(()).expect("request builder")
    }

    /// Build the SigV4a Authorization header for the given access-key,
    /// signed-headers list, and signature (lowercase hex DER).
    fn build_auth_header(access_key: &str, signed_headers: &[&str], sig_hex: &str) -> String {
        format!(
            "AWS4-ECDSA-P256-SHA256 \
             Credential={access_key}/20260513/s3/aws4_request, \
             SignedHeaders={}, \
             Signature={sig_hex}",
            signed_headers.join(";")
        )
    }

    /// Build a fully-signed SigV4a `Request<()>` ready for the gate to
    /// verify. Returns the request and the verifying key it should be
    /// loaded against.
    fn make_signed_request(
        access_key: &str,
        method: Method,
        path: &str,
        region_set: &str,
    ) -> (Request<()>, p256::ecdsa::VerifyingKey) {
        let signing = SigningKey::random(&mut OsRng);
        let verifying = p256::ecdsa::VerifyingKey::from(&signing);
        let signed_headers_list = [
            "host",
            "x-amz-content-sha256",
            "x-amz-date",
            REGION_SET_HEADER,
        ];
        // Build the request first WITHOUT the Authorization header so we
        // can compute canonical bytes and sign them; then re-build the
        // request with the Authorization header attached.
        let pre = Request::builder()
            .method(method.clone())
            .uri(path)
            .header("host", "s3.example.com")
            .header(
                "x-amz-content-sha256",
                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
            )
            .header("x-amz-date", "20260513T120000Z")
            .header(REGION_SET_HEADER, region_set)
            .body(())
            .expect("pre-request");
        let signed_headers: Vec<String> = signed_headers_list
            .iter()
            .map(|s| (*s).to_string())
            .collect();
        let canonical =
            build_canonical_request_bytes(&pre, &signed_headers).expect("test fixture canonical");
        let sig: p256::ecdsa::Signature = signing.sign(&canonical);
        let sig_hex = lower_hex(sig.to_der().as_bytes());
        let auth = build_auth_header(access_key, &signed_headers_list, &sig_hex);

        // Rebuild with the Authorization header — every other header
        // value is identical so the canonical bytes the gate computes
        // match what we signed.
        let r = Request::builder()
            .method(method)
            .uri(path)
            .header("host", "s3.example.com")
            .header(
                "x-amz-content-sha256",
                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
            )
            .header("x-amz-date", "20260513T120000Z")
            .header(REGION_SET_HEADER, region_set)
            .header("authorization", auth)
            .body(())
            .expect("signed request");
        (r, verifying)
    }

    fn make_gate_with(access_key: &str, vk: p256::ecdsa::VerifyingKey) -> Arc<SigV4aGate> {
        let mut m = HashMap::new();
        m.insert(access_key.to_string(), vk);
        let store = Arc::new(SigV4aCredentialStore::from_map(m));
        Arc::new(SigV4aGate::new(store))
    }

    /// Drain a `s3s::Body` into bytes for body-content assertions.
    async fn body_to_bytes(resp: Response<s3s::Body>) -> Vec<u8> {
        resp.into_body()
            .collect()
            .await
            .expect("body collect")
            .to_bytes()
            .to_vec()
    }

    /// v0.8.4 #76: pinned `now` matching the `x-amz-date: 20260513T120000Z`
    /// the test fixtures stamp. Without this the freshness check would
    /// reject every gate test (the timestamp would be days/weeks old by
    /// the time CI runs). Production callers use `try_sigv4a_verify`
    /// (which calls `Utc::now()`).
    fn fixture_now() -> chrono::DateTime<chrono::Utc> {
        chrono::DateTime::parse_from_rfc3339("2026-05-13T12:00:00Z")
            .unwrap()
            .with_timezone(&chrono::Utc)
    }

    #[test]
    fn no_sigv4a_prefix_returns_none() {
        // Plain SigV4 (HMAC-SHA256) request — gate must defer to s3s.
        let (_, vk) = (
            (),
            p256::ecdsa::VerifyingKey::from(&SigningKey::random(&mut OsRng)),
        );
        let gate = make_gate_with("AKIAOK", vk);
        let r = req(
            Method::GET,
            "/bucket/key",
            &[(
                "authorization",
                "AWS4-HMAC-SHA256 Credential=AKIA/20260513/us-east-1/s3/aws4_request, \
                 SignedHeaders=host, Signature=deadbeef",
            )],
        );
        assert!(
            try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", fixture_now()).is_none(),
            "plain SigV4 request must fall through to the inner service"
        );
    }

    #[test]
    fn sigv4a_valid_signature_returns_ok() {
        let (r, vk) =
            make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1,us-west-2");
        let gate = make_gate_with("AKIAOK", vk);
        let result = try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", fixture_now())
            .expect("must intercept SigV4a request");
        assert!(
            result.is_ok(),
            "valid SigV4a signature must verify: {result:?}"
        );
    }

    #[tokio::test]
    async fn sigv4a_tampered_signature_returns_403() {
        let (r, vk) = make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1");
        let gate = make_gate_with("AKIAOK", vk);

        // Tamper one byte of the signature hex inside the Authorization
        // header — the DER decode may still succeed, but ECDSA verify
        // will fail (or the DER decode itself will fail; both surface
        // as `SignatureDoesNotMatch`).
        let auth = r
            .headers()
            .get("authorization")
            .and_then(|v| v.to_str().ok())
            .expect("auth header")
            .to_string();
        // Flip the last hex char to corrupt the signature.
        let mut chars: Vec<char> = auth.chars().collect();
        let last = chars.len() - 1;
        chars[last] = if chars[last] == '0' { '1' } else { '0' };
        let tampered_auth: String = chars.into_iter().collect();
        let tampered = req(
            Method::GET,
            "/bucket/key",
            &[
                ("host", "s3.example.com"),
                (
                    "x-amz-content-sha256",
                    "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
                ),
                ("x-amz-date", "20260513T120000Z"),
                (REGION_SET_HEADER, "us-east-1"),
                ("authorization", &tampered_auth),
            ],
        );
        let result = try_sigv4a_verify_at(&tampered, Some(&gate), "us-east-1", fixture_now())
            .expect("must intercept SigV4a request");
        let resp = result.expect_err("tampered signature must surface a 403 response");
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        let body = body_to_bytes(resp).await;
        let body_str = String::from_utf8(body).expect("xml utf-8");
        assert!(
            body_str.contains("<Code>SignatureDoesNotMatch</Code>"),
            "403 body must surface SignatureDoesNotMatch: {body_str}"
        );
    }

    #[tokio::test]
    async fn sigv4a_region_set_mismatch_returns_403() {
        // Sign for `us-east-1` only, then verify with the listener
        // region claiming `eu-west-1` — must fail with
        // SignatureDoesNotMatch (the region-set check sits inside the
        // gate's verify path, and any failure there folds to
        // SignatureDoesNotMatch).
        let (r, vk) = make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1");
        let gate = make_gate_with("AKIAOK", vk);
        let result = try_sigv4a_verify_at(&r, Some(&gate), "eu-west-1", fixture_now())
            .expect("must intercept SigV4a request");
        let resp = result.expect_err("region mismatch must produce 403");
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        let body = body_to_bytes(resp).await;
        let body_str = String::from_utf8(body).expect("xml utf-8");
        assert!(
            body_str.contains("<Code>SignatureDoesNotMatch</Code>"),
            "region-set mismatch must surface SignatureDoesNotMatch: {body_str}"
        );
    }

    #[test]
    fn no_gate_attached_returns_none() {
        // Even a SigV4a-shaped request returns None when no gate is
        // installed — the listener will hand it to s3s, which surfaces
        // its own "unknown algorithm" error so the misconfiguration is
        // visible to the operator.
        let (r, _vk) = make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1");
        assert!(
            try_sigv4a_verify_at(&r, None, "us-east-1", fixture_now()).is_none(),
            "missing gate must defer to inner service"
        );
    }

    #[tokio::test]
    async fn unknown_access_key_returns_403_invalid_access_key_id() {
        // Sign with one key but load the credential store with a
        // different access-key-id → InvalidAccessKeyId.
        let (r, _vk_unused) =
            make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1");
        let other_signing = SigningKey::random(&mut OsRng);
        let other_vk = p256::ecdsa::VerifyingKey::from(&other_signing);
        let gate = make_gate_with("AKIASOMEONEELSE", other_vk);
        let result = try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", fixture_now())
            .expect("must intercept SigV4a request");
        let resp = result.expect_err("unknown key must produce 403");
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        let body = body_to_bytes(resp).await;
        let body_str = String::from_utf8(body).expect("xml utf-8");
        assert!(
            body_str.contains("<Code>InvalidAccessKeyId</Code>"),
            "unknown access-key must surface InvalidAccessKeyId: {body_str}"
        );
    }

    #[tokio::test]
    async fn region_set_header_only_without_sigv4a_auth_returns_403() {
        // Some legacy clients stamp the `X-Amz-Region-Set` header
        // before swapping the algorithm string. `detect` flags this as
        // SigV4a-shaped but we cannot verify without a parseable
        // Authorization → fail closed (SignatureDoesNotMatch).
        let signing = SigningKey::random(&mut OsRng);
        let vk = p256::ecdsa::VerifyingKey::from(&signing);
        let gate = make_gate_with("AKIAOK", vk);
        let r = req(
            Method::GET,
            "/bucket/key",
            &[
                // SigV4 algorithm + region-set header → detected, but
                // the Authorization is plain SigV4 so `parse_authorization_header`
                // returns None.
                (
                    "authorization",
                    "AWS4-HMAC-SHA256 Credential=AKIA/20260513/us-east-1/s3/aws4_request, \
                     SignedHeaders=host, Signature=deadbeef",
                ),
                (REGION_SET_HEADER, "us-east-1"),
            ],
        );
        let result = try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", fixture_now())
            .expect("must intercept SigV4a-shaped request");
        let resp = result.expect_err("region-set without sigv4a auth must produce 403");
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        let body = body_to_bytes(resp).await;
        let body_str = String::from_utf8(body).expect("xml utf-8");
        assert!(
            body_str.contains("<Code>SignatureDoesNotMatch</Code>"),
            "missing/malformed Authorization for SigV4a-shaped request must fail closed: {body_str}"
        );
    }

    /// v0.8.4 #76 (audit H-6): captured-request replay outside the
    /// 15-min window → 403 RequestTimeTooSkewed (not
    /// SignatureDoesNotMatch). This is the headline gate-level
    /// behaviour change; pre-#76 the same captured request would have
    /// reached the inner service, allowing destructive replay (DELETE
    /// included).
    #[tokio::test]
    async fn sigv4a_replay_outside_window_returns_403_request_time_too_skewed() {
        let (r, vk) = make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1");
        let gate = make_gate_with("AKIAOK", vk);
        // Request stamped 20260513T120000Z; "now" is 30 min later → drift
        // 1800s, beyond the 900s default tolerance.
        let now = chrono::DateTime::parse_from_rfc3339("2026-05-13T12:30:00Z")
            .unwrap()
            .with_timezone(&chrono::Utc);
        let result = try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", now)
            .expect("must intercept SigV4a request");
        let resp = result.expect_err("replay outside window must reject");
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        let body = body_to_bytes(resp).await;
        let body_str = String::from_utf8(body).expect("xml utf-8");
        assert!(
            body_str.contains("<Code>RequestTimeTooSkewed</Code>"),
            "replay outside window must surface RequestTimeTooSkewed: {body_str}"
        );
    }

    /// Cover the canonical-request builder directly: empty query
    /// string, sorted multi-pair query, and header value collapsed
    /// whitespace all hit the right code paths.
    #[test]
    fn canonical_request_bytes_format() {
        let r = req(
            Method::PUT,
            "/bucket/key?z=1&a=2",
            &[
                ("host", "s3.example.com"),
                ("x-amz-content-sha256", "UNSIGNED-PAYLOAD"),
                ("x-amz-date", "  20260513T120000Z  "),
            ],
        );
        let signed: Vec<String> = ["host", "x-amz-content-sha256", "x-amz-date"]
            .iter()
            .map(|s| (*s).into())
            .collect();
        let bytes =
            build_canonical_request_bytes(&r, &signed).expect("canonical request bytes must build");
        let s = std::str::from_utf8(&bytes).expect("utf-8");
        let expected = "PUT\n\
                        /bucket/key\n\
                        a=2&z=1\n\
                        host:s3.example.com\n\
                        x-amz-content-sha256:UNSIGNED-PAYLOAD\n\
                        x-amz-date:20260513T120000Z\n\
                        \n\
                        host;x-amz-content-sha256;x-amz-date\n\
                        UNSIGNED-PAYLOAD";
        assert_eq!(s, expected, "canonical request bytes mismatch:\n{s}");
    }

    /// v0.8.5 #84 H-4: duplicate `x-amz-date` headers must be rejected
    /// at canonical-request build time (not silently coalesced to the
    /// first value). HTTP/1.1 spec already forbids duplicates of
    /// `host` / `x-amz-date`; AWS SDKs never emit them; so any
    /// duplicate must be malicious or broken — single-value reject is
    /// the safe choice (see [`build_canonical_request_bytes`] doc).
    #[test]
    fn sigv4a_duplicate_x_amz_date_rejected() {
        // Two x-amz-date headers — first one matches the signature the
        // gate expects, second one is what a downstream parser might
        // pick up. This is the textbook auth-confusion vector.
        let r = Request::builder()
            .method(Method::GET)
            .uri("/b/k")
            .header("host", "s3.example.com")
            .header("x-amz-content-sha256", "UNSIGNED-PAYLOAD")
            .header("x-amz-date", "20260513T120000Z")
            .header("x-amz-date", "20260513T130000Z")
            .body(())
            .expect("dup-header request");
        let signed: Vec<String> = ["host", "x-amz-content-sha256", "x-amz-date"]
            .iter()
            .map(|s| (*s).into())
            .collect();
        let err = build_canonical_request_bytes(&r, &signed)
            .expect_err("duplicate x-amz-date must reject");
        match err {
            crate::sigv4a::SigV4aError::DuplicateSignedHeader { header } => {
                assert_eq!(header, "x-amz-date");
            }
            other => panic!("expected DuplicateSignedHeader, got {other:?}"),
        }
    }

    /// v0.8.5 #84 H-4: counterpart to the duplicate-reject test —
    /// single-occurrence headers on the same path stay accepted.
    /// Guards against a regression where the duplicate-detect logic
    /// is over-eager and trips on a normally-formed request.
    #[test]
    fn sigv4a_canonicalization_single_header_passes() {
        let r = req(
            Method::GET,
            "/b/k",
            &[
                ("host", "s3.example.com"),
                ("x-amz-content-sha256", "UNSIGNED-PAYLOAD"),
                ("x-amz-date", "20260513T120000Z"),
            ],
        );
        let signed: Vec<String> = ["host", "x-amz-content-sha256", "x-amz-date"]
            .iter()
            .map(|s| (*s).into())
            .collect();
        let bytes =
            build_canonical_request_bytes(&r, &signed).expect("single-occurrence must accept");
        // Body content not asserted in detail (covered by
        // canonical_request_bytes_format); just confirm the bytes
        // parse as utf-8 and contain the date verbatim.
        let s = std::str::from_utf8(&bytes).expect("utf-8");
        assert!(
            s.contains("x-amz-date:20260513T120000Z"),
            "canonical bytes must echo the single x-amz-date verbatim:\n{s}"
        );
    }

    /// v0.8.5 #84 H-4: end-to-end through the
    /// [`try_sigv4a_verify_at`] gate — duplicate `x-amz-date` on a
    /// SigV4a-shaped request must surface 403 SignatureDoesNotMatch
    /// (not silently authenticate against the first value).
    #[tokio::test]
    async fn sigv4a_pre_route_rejects_duplicate_signed_header() {
        let signing = SigningKey::random(&mut OsRng);
        let vk = p256::ecdsa::VerifyingKey::from(&signing);
        let gate = make_gate_with("AKIAOK", vk);
        // Authorization header lists x-amz-date in SignedHeaders —
        // signature value itself can be garbage; the duplicate-detect
        // path runs strictly before any ECDSA math.
        let auth = build_auth_header(
            "AKIAOK",
            &[
                "host",
                "x-amz-content-sha256",
                "x-amz-date",
                REGION_SET_HEADER,
            ],
            "deadbeef",
        );
        let r = Request::builder()
            .method(Method::GET)
            .uri("/bucket/key")
            .header("host", "s3.example.com")
            .header(
                "x-amz-content-sha256",
                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
            )
            .header("x-amz-date", "20260513T120000Z")
            .header("x-amz-date", "20260513T130000Z")
            .header(REGION_SET_HEADER, "us-east-1")
            .header("authorization", auth)
            .body(())
            .expect("dup-header sigv4a request");
        let result = try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", fixture_now())
            .expect("must intercept SigV4a request");
        let resp = result.expect_err("duplicate signed header must reject at the gate");
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        let body = body_to_bytes(resp).await;
        let body_str = String::from_utf8(body).expect("xml utf-8");
        assert!(
            body_str.contains("<Code>SignatureDoesNotMatch</Code>"),
            "duplicate signed header must surface SignatureDoesNotMatch: {body_str}"
        );
        assert!(
            body_str.contains("duplicate signed header"),
            "diagnostic must mention duplicate header: {body_str}"
        );
    }
}