Skip to main content

s4_server/
routing.rs

1//! `/health` と `/ready` の HTTP routing layer + CORS OPTIONS preflight
2//! interceptor + SigV4a verify gate。
3//!
4//! S3 server と同じポートで health probe に応答できると AWS ALB / NLB / k8s
5//! readiness probe との統合が単純になる。
6//!
7//! - `GET /health` → 常に `200 OK` (server プロセスが生きていれば返す)
8//! - `GET /ready` → `ready_check` future を await し、`Ok(())` なら 200、
9//!   それ以外 (backend 不通等) は 503。
10//! - `OPTIONS /<bucket>[/<key>]` (Origin + Access-Control-Request-Method 付き)
11//!   → v0.7 #44: `cors_manager` が attach されていれば、bucket の登録された
12//!   rule list に対して preflight match を実行し、200 + Allow-* header を
13//!   組み立てて返す (no match なら 403)。s3s framework は OPTIONS verb を
14//!   typed handler として持たないため、HTTP-level の interceptor で寄せる。
15//! - `Authorization: AWS4-ECDSA-P256-SHA256 ...` (SigV4a) を持つ request
16//!   → v0.7 #47: `sigv4a_gate` が attach されていれば、listener 側で署名を
17//!   verify し、success なら inner S3Service へ forward、failure なら 403
18//!   `SignatureDoesNotMatch` / `InvalidAccessKeyId` を直接返す。s3s 既存の
19//!   SigV4 verifier は `AWS4-ECDSA-P256-SHA256` を "unknown algorithm" として
20//!   reject するため、middleware を挟まないと SigV4a request は届かない。
21//! - その他のパス → inner S3Service へ委譲
22
23use std::convert::Infallible;
24use std::future::Future;
25use std::pin::Pin;
26use std::sync::Arc;
27
28use bytes::Bytes;
29use http_body_util::Full;
30use hyper::body::Incoming;
31use hyper::service::Service;
32use hyper::{Method, Request, Response, StatusCode};
33use metrics_exporter_prometheus::PrometheusHandle;
34
35use crate::cors::{CorsManager, CorsRule};
36use crate::service::SigV4aGate;
37
38/// readiness check 関数。bound is `Send + Sync` for cross-task use.
39pub type ReadyCheck =
40    Arc<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), String>> + Send>> + Send + Sync>;
41
42/// inner service と health/ready/metrics + CORS preflight handler +
43/// SigV4a verify gate を合成する hyper Service。
44#[derive(Clone)]
45pub struct HealthRouter<S> {
46    pub inner: S,
47    pub ready_check: Option<ReadyCheck>,
48    pub metrics_handle: Option<PrometheusHandle>,
49    /// v0.7 #44: optional CORS bucket-config manager. When attached,
50    /// OPTIONS requests carrying `Origin` + `Access-Control-Request-Method`
51    /// are intercepted before reaching the s3s service and answered
52    /// directly with Access-Control-Allow-* headers (or 403 if no rule
53    /// matches). When `None`, OPTIONS falls through to the inner service
54    /// (s3s typically returns 405 since no S3 handler maps to OPTIONS).
55    pub cors_manager: Option<Arc<CorsManager>>,
56    /// v0.7 #47: optional SigV4a verify gate. When attached, requests
57    /// whose `Authorization` header begins with `AWS4-ECDSA-P256-SHA256`
58    /// (or that carry `X-Amz-Region-Set`) are verified at the HTTP
59    /// layer using the configured ECDSA-P-256 credential store; on
60    /// failure the listener returns 403 directly. When `None`, the
61    /// gate is a no-op so plain SigV4 deployments are unaffected.
62    pub sigv4a_gate: Option<Arc<SigV4aGate>>,
63    /// v0.7 #47: region name used when checking
64    /// `X-Amz-Region-Set` membership during SigV4a verification. The
65    /// listener is single-region in this milestone — operators that
66    /// front S4 with a Multi-Region Access Point set this to the
67    /// canonical "this listener's region" string. Defaults to
68    /// `"us-east-1"` (the AWS-default region when none is configured).
69    pub region: String,
70}
71
72impl<S> HealthRouter<S> {
73    pub fn new(inner: S, ready_check: Option<ReadyCheck>) -> Self {
74        Self {
75            inner,
76            ready_check,
77            metrics_handle: None,
78            cors_manager: None,
79            sigv4a_gate: None,
80            region: "us-east-1".to_string(),
81        }
82    }
83
84    #[must_use]
85    pub fn with_metrics(mut self, handle: PrometheusHandle) -> Self {
86        self.metrics_handle = Some(handle);
87        self
88    }
89
90    /// v0.7 #44: attach an `Arc<CorsManager>` so OPTIONS preflight
91    /// requests are handled at the HTTP layer instead of falling through
92    /// to s3s.
93    #[must_use]
94    pub fn with_cors_manager(mut self, mgr: Arc<CorsManager>) -> Self {
95        self.cors_manager = Some(mgr);
96        self
97    }
98
99    /// v0.7 #47: attach an `Arc<SigV4aGate>` so `AWS4-ECDSA-P256-SHA256`
100    /// requests are verified at the HTTP layer instead of being
101    /// rejected by s3s' SigV4 verifier as "unknown algorithm".
102    #[must_use]
103    pub fn with_sigv4a_gate(mut self, gate: Arc<SigV4aGate>) -> Self {
104        self.sigv4a_gate = Some(gate);
105        self
106    }
107
108    /// v0.7 #47: override the listener's "served region" string used
109    /// to check `X-Amz-Region-Set` membership during SigV4a
110    /// verification. Defaults to `"us-east-1"`.
111    #[must_use]
112    pub fn with_region(mut self, region: impl Into<String>) -> Self {
113        self.region = region.into();
114        self
115    }
116}
117
118/// v0.7 #44: HTTP-level OPTIONS preflight interceptor.
119///
120/// Returns:
121/// - `Some(response)` if `req` is an OPTIONS preflight (Origin +
122///   Access-Control-Request-Method headers present) targeting a bucket
123///   with CORS configured. The response is 200 with Allow-* headers
124///   when a rule matches, or 403 when no rule matches the
125///   (origin, method, headers) triple.
126/// - `None` if the request is not a preflight, or no CORS config is
127///   registered for the target bucket — caller forwards to the s3s
128///   service.
129///
130/// `cors` is `Option<&Arc<CorsManager>>` so callers can pass through
131/// the inner service's optional manager without unwrapping first.
132///
133/// Generic over the request body type `B` so unit tests can drive the
134/// matcher with `Request<()>` without constructing a real `Incoming`
135/// stream (only headers, method, and URI are inspected).
136#[must_use]
137pub fn try_handle_preflight<B>(
138    req: &Request<B>,
139    cors: Option<&Arc<CorsManager>>,
140) -> Option<Response<s3s::Body>> {
141    if req.method() != Method::OPTIONS {
142        return None;
143    }
144    let mgr = cors?;
145    // Path is `/<bucket>` or `/<bucket>/<key>` — first segment is bucket.
146    // Empty path or a query-only request has no bucket and is not a
147    // preflight we can answer.
148    let path = req.uri().path();
149    let bucket = path.trim_start_matches('/').split('/').next()?;
150    if bucket.is_empty() {
151        return None;
152    }
153    let origin = req.headers().get("origin")?.to_str().ok()?;
154    let method = req
155        .headers()
156        .get("access-control-request-method")?
157        .to_str()
158        .ok()?;
159    // Access-Control-Request-Headers is a comma-separated list, optional
160    // (browsers omit it when no custom headers are being sent).
161    let req_headers: Vec<String> = req
162        .headers()
163        .get("access-control-request-headers")
164        .and_then(|h| h.to_str().ok())
165        .map(|s| {
166            s.split(',')
167                .map(|t| t.trim().to_string())
168                .filter(|t| !t.is_empty())
169                .collect()
170        })
171        .unwrap_or_default();
172    // No config for this bucket → not our problem (let s3s handle / 404).
173    // We need to distinguish "no config" from "config but no rule matches"
174    // to correctly fall through vs. return 403.
175    let _ = mgr.get(bucket)?;
176    match mgr.match_preflight(bucket, origin, method, &req_headers) {
177        Some(rule) => Some(build_preflight_allow_response(&rule, origin)),
178        None => Some(build_preflight_deny_response()),
179    }
180}
181
182/// 200 response with the matched rule's Allow-* headers.
183fn build_preflight_allow_response(rule: &CorsRule, origin: &str) -> Response<s3s::Body> {
184    let mut builder = Response::builder().status(StatusCode::OK);
185    // Echo the matched origin: literal "*" if the rule used a wildcard,
186    // otherwise the requesting origin verbatim (S3 spec).
187    let allow_origin: String = if rule.allowed_origins.iter().any(|o| o == "*") {
188        "*".into()
189    } else {
190        origin.to_owned()
191    };
192    builder = builder.header("Access-Control-Allow-Origin", allow_origin);
193    builder = builder.header(
194        "Access-Control-Allow-Methods",
195        rule.allowed_methods.join(", "),
196    );
197    if !rule.allowed_headers.is_empty() {
198        builder = builder.header(
199            "Access-Control-Allow-Headers",
200            rule.allowed_headers.join(", "),
201        );
202    }
203    if !rule.expose_headers.is_empty() {
204        builder = builder.header(
205            "Access-Control-Expose-Headers",
206            rule.expose_headers.join(", "),
207        );
208    }
209    if let Some(secs) = rule.max_age_seconds {
210        builder = builder.header("Access-Control-Max-Age", secs.to_string());
211    }
212    // Empty body, but set content-length explicitly for clarity.
213    let bytes = Bytes::new();
214    builder = builder.header("content-length", "0");
215    builder
216        .body(s3s::Body::http_body(
217            Full::new(bytes).map_err(|never| match never {}),
218        ))
219        .expect("preflight response builder")
220}
221
222/// 403 response when an OPTIONS preflight reaches a bucket with CORS
223/// configured but no rule matches the (origin, method, headers) triple.
224fn build_preflight_deny_response() -> Response<s3s::Body> {
225    let body = Bytes::from_static(b"CORSResponse: This CORS request is not allowed.");
226    Response::builder()
227        .status(StatusCode::FORBIDDEN)
228        .header("content-type", "text/plain; charset=utf-8")
229        .header("content-length", body.len().to_string())
230        .body(s3s::Body::http_body(
231            Full::new(body).map_err(|never| match never {}),
232        ))
233        .expect("preflight deny response builder")
234}
235
236// ===========================================================================
237// v0.7 #47 — SigV4a verify gate middleware.
238// ===========================================================================
239
240/// v0.7 #47: Try to verify the request as SigV4a-signed.
241///
242/// Returns:
243/// - `None` if the request is not SigV4a-signed (no `AWS4-ECDSA-P256-SHA256`
244///   `Authorization` prefix and no `X-Amz-Region-Set` header) — the
245///   caller forwards the request to s3s for the default SigV4 path.
246/// - `Some(Ok(()))` if SigV4a verify succeeded — the caller forwards to
247///   the inner service so the S3 handler runs.
248/// - `Some(Err(response))` if SigV4a verify failed — the caller returns
249///   the 403 response directly without ever invoking the inner service.
250///
251/// `gate` is `Option<&Arc<SigV4aGate>>` so callers can pass through the
252/// router's optional gate without unwrapping first; when `None`, this
253/// function always returns `None` (no SigV4a verification configured).
254///
255/// `requested_region` is the listener's served region (used to validate
256/// the request's `X-Amz-Region-Set` header membership).
257///
258/// Generic over the request body type `B` so unit tests can drive the
259/// matcher with `Request<()>` without constructing a real `Incoming`
260/// stream — only headers, method, and URI participate in the canonical
261/// request bytes built here.
262///
263/// # Canonical request bytes
264///
265/// We build a SigV4-shaped canonical request from the HTTP-layer
266/// signal alone (method, URI path, sorted query string, headers in the
267/// order listed by `SignedHeaders=`, and `x-amz-content-sha256` as the
268/// payload hash — the standard "client-supplied body hash" convention
269/// every AWS SDK uses). Reading the body would force a `Request<Bytes>`
270/// rebuild and break the s3s framework's streaming-body assumptions, so
271/// the payload-hash header is the only correct source for SigV4a.
272///
273/// Clients that want to sign over the body must include the actual
274/// SHA-256 of the body in `x-amz-content-sha256`; clients that don't
275/// (most S3 SDKs default to `UNSIGNED-PAYLOAD` for streaming PUTs) sign
276/// over that literal string instead. Either way the bytes the gate
277/// compares against are exactly what the client computed.
278pub fn try_sigv4a_verify<B>(
279    req: &Request<B>,
280    gate: Option<&Arc<SigV4aGate>>,
281    requested_region: &str,
282) -> Option<Result<(), Response<s3s::Body>>> {
283    try_sigv4a_verify_at(req, gate, requested_region, chrono::Utc::now())
284}
285
286/// v0.8.4 #76: like [`try_sigv4a_verify`] but takes an explicit `now`
287/// for tests that need to pin the freshness clock without time-warping
288/// the system clock. Production callers always reach this via
289/// `try_sigv4a_verify` (which calls `chrono::Utc::now()`).
290pub fn try_sigv4a_verify_at<B>(
291    req: &Request<B>,
292    gate: Option<&Arc<SigV4aGate>>,
293    requested_region: &str,
294    now: chrono::DateTime<chrono::Utc>,
295) -> Option<Result<(), Response<s3s::Body>>> {
296    // v0.8.17 G-1: presigned-URL detection runs BEFORE the
297    // `gate.is_none()` short-circuit. The v0.8.16 F-5 fix only
298    // emitted the 501 when a SigV4a verifier was already wired
299    // (`--sigv4a-credentials <DIR>`); operators who hadn't
300    // configured one had `?X-Amz-Algorithm=AWS4-ECDSA-P256-SHA256`
301    // requests silently fall through to the SigV4 path, which
302    // doesn't understand SigV4a query auth either — request
303    // effectively accepted as unsigned. We now surface the 501
304    // unconditionally for SigV4a-shaped query auth, so the
305    // "deterministic failure" the F-5 comment promised holds for
306    // every deployment.
307    if crate::sigv4a::detect_presigned(req) {
308        return Some(Err(build_sigv4a_error_response(
309            StatusCode::NOT_IMPLEMENTED,
310            "NotImplemented",
311            "SigV4a presigned URLs (query auth) are not yet supported on this gateway; \
312             use Authorization-header SigV4a instead",
313        )));
314    }
315    let gate = gate?;
316    if !crate::sigv4a::detect(req) {
317        // Not a SigV4a request — caller forwards to the SigV4 path.
318        return None;
319    }
320    // Pre-parse the Authorization header so we know which signed-headers
321    // list to canonicalise in. If the header is malformed, fail fast
322    // with 403 rather than building canonical bytes that can never
323    // verify.
324    //
325    // v0.8.4 #76: `parse_authorization_header` now returns `Result`
326    // (was `Option`) so the gate can surface scope-shape failures
327    // (`InvalidCredentialScope`, `WrongService`, etc.) as 400
328    // InvalidRequest. Any non-Ok parse falls through to the
329    // SignatureDoesNotMatch 403 the original code returned, since at
330    // this point we can't extract a `signed_headers` list to feed the
331    // canonical-request builder.
332    let auth_hdr = req
333        .headers()
334        .get(http::header::AUTHORIZATION)
335        .and_then(|v| v.to_str().ok());
336    let signed_headers: Vec<String> =
337        match auth_hdr.and_then(|hdr| crate::sigv4a::parse_authorization_header(hdr).ok()) {
338            Some(parsed) => parsed.signed_headers,
339            None => {
340                // No / unparseable Authorization header but `detect` flagged
341                // it as SigV4a-shaped (e.g. only the region-set header is
342                // present) — surface as SignatureDoesNotMatch directly.
343                return Some(Err(build_sigv4a_error_response(
344                    StatusCode::FORBIDDEN,
345                    "SignatureDoesNotMatch",
346                    "missing or malformed Authorization header for SigV4a request",
347                )));
348            }
349        };
350    let canonical = match build_canonical_request_bytes(req, &signed_headers) {
351        Ok(bytes) => bytes,
352        Err(err) => {
353            // v0.8.5 #84 H-4: duplicate signed header (only failure
354            // mode the canonical builder has today). Surface as
355            // `SignatureDoesNotMatch` 403 — the AWS SDKs treat that
356            // as the catch-all auth-failure code, and the diagnostic
357            // is in the response body / server log.
358            tracing::warn!(error = %err, "SigV4a canonical-request build rejected request");
359            return Some(Err(build_sigv4a_error_response(
360                StatusCode::FORBIDDEN,
361                "SignatureDoesNotMatch",
362                &err.to_string(),
363            )));
364        }
365    };
366    match gate.pre_route_at(req, requested_region, &canonical, now) {
367        Ok(()) => Some(Ok(())),
368        Err(err) => {
369            tracing::warn!(error = %err, "SigV4a verify rejected request");
370            Some(Err(build_sigv4a_error_response(
371                err.http_status(),
372                err.s3_error_code(),
373                &err.to_string(),
374            )))
375        }
376    }
377}
378
379/// v0.7 #47: build a SigV4-shaped canonical request from the HTTP
380/// surface alone (no body access). Returns the bytes that the
381/// SigV4a gate will check the ECDSA signature against.
382///
383/// Format (one element per line, joined with `\n`):
384/// 1. HTTP method (uppercase)
385/// 2. canonical URI (path; we leave it untouched since AWS SDKs
386///    pre-encode it the same way s3s receives it)
387/// 3. canonical query string (sorted by name, name=value pairs joined
388///    by `&`; empty when no query string)
389/// 4. canonical headers (one `name:trimmed-value\n` per signed header,
390///    in the **order** they appear in `SignedHeaders=`)
391/// 5. signed headers list (lowercase names joined by `;`)
392/// 6. payload hash (value of `x-amz-content-sha256`, or `UNSIGNED-PAYLOAD`
393///    if absent)
394///
395/// v0.8.5 #84 (audit H-4): every signed header is checked for being
396/// sent **exactly once** on the request. If a header in
397/// `SignedHeaders=` appears more than once we'd have to choose between
398/// the first value (`HeaderMap::get` semantics) and the comma-joined
399/// AWS-canonical form — and any S3 SDK / WAF / sidecar in front of us
400/// would make a different choice, opening "auth confusion" attacks
401/// (sign over the benign first `x-amz-date`, smuggle a second one for
402/// the inner parser). HTTP/1.1 spec already forbids duplicates of
403/// `host` / `x-amz-date` and the AWS SDKs never emit them, so any
404/// duplicate is a malicious or broken request — reject upfront with
405/// [`SigV4aError::DuplicateSignedHeader`].
406fn build_canonical_request_bytes<B>(
407    req: &Request<B>,
408    signed_headers: &[String],
409) -> Result<Vec<u8>, crate::sigv4a::SigV4aError> {
410    let mut buf = String::with_capacity(512);
411    buf.push_str(req.method().as_str());
412    buf.push('\n');
413    // v0.8.15 H-d: canonical URI per RFC 3986 unreserved set. Real
414    // AWS SDKs decode + re-encode (uppercase hex, only unreserved
415    // chars left literal) before hashing, so receiving the same
416    // request through a normalising TLS terminator that lowercases
417    // `%2f` to `%2F` (or vice versa) would otherwise produce a
418    // different canonical form than what the SDK signed. `/`
419    // path-segment separators stay literal — S3 doesn't escape them
420    // in the canonical path.
421    buf.push_str(&canonical_uri_path(req.uri().path()));
422    buf.push('\n');
423    buf.push_str(&canonical_query_string(req.uri().query().unwrap_or("")));
424    buf.push('\n');
425    for name in signed_headers {
426        // v0.8.5 #84 H-4: count occurrences via `get_all` rather than
427        // `get`, which only ever returns the first value. Two
428        // `x-amz-date` headers with `get` would canonicalise to the
429        // first value while a downstream HTTP/1.1 parser might pick
430        // the second — auth confusion. Single-value reject is the
431        // safe choice; comma-join would be the AWS-canonical form
432        // for legitimately multi-valued signed headers, but the AWS
433        // SDKs never sign over comma-joined values for any header
434        // S3 cares about, so refusing duplicates outright matches
435        // every real-world client.
436        let occurrences = req.headers().get_all(name.as_str()).iter().count();
437        if occurrences > 1 {
438            return Err(crate::sigv4a::SigV4aError::DuplicateSignedHeader {
439                header: name.clone(),
440            });
441        }
442        // v0.8.16 F-4: presence is required. A signed header that's
443        // missing from the request used to canonicalise as `name:\n`
444        // (empty value) — a client could sign over a placeholder
445        // value, then drop the actual header on the wire. The gate
446        // would happily verify because both sides agreed on the
447        // empty-string canonical form. AWS S3 returns
448        // SignatureDoesNotMatch; we surface a typed variant so the
449        // gate can map to 403 with a clear message.
450        let value = match req
451            .headers()
452            .get(name.as_str())
453            .and_then(|v| v.to_str().ok())
454        {
455            Some(v) => v,
456            None => {
457                return Err(crate::sigv4a::SigV4aError::SignedHeaderMissing {
458                    header: name.clone(),
459                });
460            }
461        };
462        buf.push_str(name);
463        buf.push(':');
464        // Trim whitespace and collapse repeated inner whitespace per
465        // SigV4 canonicalisation rules. This is the same trimming AWS
466        // SDKs do when they sign.
467        buf.push_str(&trim_collapse_ws(value));
468        buf.push('\n');
469    }
470    buf.push('\n');
471    buf.push_str(&signed_headers.join(";"));
472    buf.push('\n');
473    let payload_hash = req
474        .headers()
475        .get("x-amz-content-sha256")
476        .and_then(|v| v.to_str().ok())
477        .unwrap_or("UNSIGNED-PAYLOAD");
478    buf.push_str(payload_hash);
479    Ok(buf.into_bytes())
480}
481
482/// SigV4 canonical query string: split on `&`, parse each `k=v` (or
483/// `k`), sort lexicographically by name (then by value), re-join with
484/// `&`. Empty input → empty string. We do **not** re-encode the values
485/// — they already arrived URL-encoded over the wire, and AWS SDKs
486/// expect the server to compare the bytes verbatim.
487fn canonical_query_string(query: &str) -> String {
488    if query.is_empty() {
489        return String::new();
490    }
491    // v0.8.15 H-d: AWS SigV4 / SigV4a spec — decode each key/value to
492    // raw bytes, then re-encode with the AWS canonical form (RFC
493    // 3986 unreserved set, uppercase hex), then sort by the encoded
494    // key (and value as tiebreaker). The pre-H-d code took the raw
495    // wire bytes and sorted those, which produced a different
496    // canonical string than the SDK's output for any of these
497    // mismatches:
498    //
499    // 1. Lowercase `%2f` in the wire vs. SDK-canonical uppercase
500    //    `%2F` (some TLS terminators normalise).
501    // 2. Mixed encoding choices (one side encodes `=` as `%3D`, the
502    //    other leaves it bare).
503    // 3. Sort order on raw bytes vs. encoded bytes differs when one
504    //    side encodes a char the other left literal.
505    //
506    // Real AWS SDKs always emit fully-encoded canonical form, so the
507    // pre-H-d "verbatim sort" only matched signatures the gate itself
508    // produced, not signatures real clients ship.
509    // v0.8.16 F-6: byte-level decode + re-encode. The pre-F-6
510    // helpers ran `decode_utf8_lossy()` which silently replaced
511    // any non-UTF8 percent-encoded byte (e.g. `%FF`) with the
512    // U+FFFD replacement character (`%EF%BF%BD` after re-encode),
513    // mismatching every signer that operates on raw bytes (most
514    // AWS SDKs do). Now we work with `Vec<u8>` end-to-end so the
515    // canonical form is bit-for-bit identical to what AWS SDKs
516    // emit, including for non-UTF8 path / query content.
517    let mut pairs: Vec<(String, String)> = query
518        .split('&')
519        .filter(|s| !s.is_empty())
520        .map(|kv| match kv.split_once('=') {
521            Some((k, v)) => (percent_decode_bytes(k), percent_decode_bytes(v)),
522            None => (percent_decode_bytes(kv), Vec::new()),
523        })
524        .map(|(k, v)| {
525            (
526                aws_canonical_encode_bytes(&k),
527                aws_canonical_encode_bytes(&v),
528            )
529        })
530        .collect();
531    pairs.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
532    let mut out = String::with_capacity(query.len());
533    for (i, (k, v)) in pairs.iter().enumerate() {
534        if i > 0 {
535            out.push('&');
536        }
537        out.push_str(k);
538        out.push('=');
539        out.push_str(v);
540    }
541    out
542}
543
544/// v0.8.15 H-d: AWS canonical URI path encoding. Pulls each segment
545/// out of the slash-separated path, decodes any percent-encoded
546/// bytes, then re-encodes with the canonical form. Slashes are
547/// preserved literal (S3 doesn't escape segment separators in the
548/// canonical path).
549fn canonical_uri_path(path: &str) -> String {
550    if path.is_empty() {
551        return "/".to_owned();
552    }
553    // v0.8.16 F-6: byte-level. See `canonical_query_string` for
554    // the rationale — `decode_utf8_lossy` mangled non-UTF8 paths
555    // into U+FFFD before re-encoding, mismatching the signer.
556    let mut out = String::with_capacity(path.len());
557    let mut first = true;
558    for segment in path.split('/') {
559        if !first {
560            out.push('/');
561        }
562        first = false;
563        let decoded = percent_decode_bytes(segment);
564        out.push_str(&aws_canonical_encode_bytes(&decoded));
565    }
566    out
567}
568
569/// v0.8.16 F-6: decode a percent-encoded string to its raw bytes
570/// (`Vec<u8>`). Preserves non-UTF8 sequences verbatim so the
571/// downstream re-encode produces the same bytes a byte-level signer
572/// (e.g. `aws-crt-cpp`, `aws-sigv4` Rust crate) would compute.
573fn percent_decode_bytes(s: &str) -> Vec<u8> {
574    percent_encoding::percent_decode_str(s).collect()
575}
576
577/// v0.8.16 F-6: encode a raw byte sequence per AWS SigV4 canonical
578/// form. AWS canonical set = RFC 3986 unreserved (`A-Z a-z 0-9 - _
579/// . ~`); every other byte becomes `%XX` with uppercase hex.
580/// Operates on `&[u8]` so it never panics on non-UTF8 input.
581fn aws_canonical_encode_bytes(bytes: &[u8]) -> String {
582    let mut out = String::with_capacity(bytes.len());
583    for &b in bytes {
584        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
585            out.push(b as char);
586        } else {
587            use std::fmt::Write as _;
588            let _ = write!(out, "%{b:02X}");
589        }
590    }
591    out
592}
593
594#[allow(dead_code)]
595/// v0.8.15 H-d (kept for any UTF-8-only call site): encode a UTF-8
596/// string per AWS SigV4 canonical form. Prefer
597/// [`aws_canonical_encode_bytes`] which doesn't lossy-decode.
598fn aws_canonical_encode(s: &str) -> String {
599    /// AWS canonical set per SigV4 spec — equivalent to RFC 3986
600    /// unreserved. Everything else gets `%XX`.
601    const AWS_CANONICAL_SET: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC
602        .remove(b'-')
603        .remove(b'_')
604        .remove(b'.')
605        .remove(b'~');
606    percent_encoding::utf8_percent_encode(s, AWS_CANONICAL_SET).to_string()
607}
608
609/// SigV4 header-value canonicalisation: trim leading + trailing
610/// whitespace and collapse runs of internal whitespace to a single
611/// space. This mirrors what AWS SDKs do client-side when computing the
612/// canonical request — without it, a header value with extra spaces
613/// would canonicalise differently on each side.
614fn trim_collapse_ws(s: &str) -> String {
615    let trimmed = s.trim();
616    let mut out = String::with_capacity(trimmed.len());
617    let mut prev_ws = false;
618    for c in trimmed.chars() {
619        if c.is_whitespace() {
620            if !prev_ws {
621                out.push(' ');
622            }
623            prev_ws = true;
624        } else {
625            out.push(c);
626            prev_ws = false;
627        }
628    }
629    out
630}
631
632/// v0.7 #47: build an AWS-shaped XML response for a SigV4a verify
633/// failure. The response body matches the wire format AWS S3 emits for
634/// the same conditions so SDKs surface the right exception class to the
635/// caller.
636///
637/// v0.8.4 #76: now takes `status` so the gate can return 400
638/// InvalidRequest for malformed-input failures (missing x-amz-date,
639/// wrong service scope, etc.) and 403 for actual auth failures.
640fn build_sigv4a_error_response(
641    status: StatusCode,
642    code: &str,
643    message: &str,
644) -> Response<s3s::Body> {
645    let body_str = format!(
646        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
647         <Error>\n  <Code>{code}</Code>\n  <Message>{message}</Message>\n</Error>"
648    );
649    let bytes = Bytes::from(body_str.into_bytes());
650    Response::builder()
651        .status(status)
652        .header("content-type", "application/xml")
653        .header("content-length", bytes.len().to_string())
654        .body(s3s::Body::http_body(
655            Full::new(bytes).map_err(|never| match never {}),
656        ))
657        .expect("sigv4a error response builder")
658}
659
660/// `/health` と `/ready` のレスポンス Body。
661/// inner S3Service の Body と互換する形にするために `s3s::Body` でラップ可能な
662/// `Full<Bytes>` を `s3s::Body::http_body` 経由で構築する。
663type RespBody = s3s::Body;
664
665fn make_text_response(status: StatusCode, body: &'static str) -> Response<RespBody> {
666    let bytes = Bytes::from_static(body.as_bytes());
667    Response::builder()
668        .status(status)
669        .header("content-type", "text/plain; charset=utf-8")
670        .header("content-length", bytes.len().to_string())
671        .body(s3s::Body::http_body(
672            Full::new(bytes).map_err(|never| match never {}),
673        ))
674        .expect("static response")
675}
676
677fn make_owned_text_response(
678    status: StatusCode,
679    content_type: &'static str,
680    body: String,
681) -> Response<RespBody> {
682    let bytes = Bytes::from(body.into_bytes());
683    Response::builder()
684        .status(status)
685        .header("content-type", content_type)
686        .header("content-length", bytes.len().to_string())
687        .body(s3s::Body::http_body(
688            Full::new(bytes).map_err(|never| match never {}),
689        ))
690        .expect("owned response")
691}
692
693impl<S> Service<Request<Incoming>> for HealthRouter<S>
694where
695    S: Service<Request<Incoming>, Response = Response<s3s::Body>, Error = s3s::HttpError>
696        + Clone
697        + Send
698        + 'static,
699    S::Future: Send + 'static,
700{
701    type Response = Response<RespBody>;
702    type Error = s3s::HttpError;
703    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
704
705    fn call(&self, req: Request<Incoming>) -> Self::Future {
706        // v0.7 #44: short-circuit CORS OPTIONS preflight at the HTTP layer
707        // before health/metrics dispatch. Preflight must run only for
708        // OPTIONS requests, and only when a CORS manager is attached and
709        // a config exists for the requested bucket; otherwise fall
710        // through to the existing routing logic.
711        if let Some(resp) = try_handle_preflight(&req, self.cors_manager.as_ref()) {
712            return Box::pin(async move { Ok(resp) });
713        }
714        // v0.7 #47: SigV4a verify gate. When the request is signed with
715        // `AWS4-ECDSA-P256-SHA256` and a credential store is configured,
716        // verify here at the HTTP layer (s3s' SigV4 verifier would
717        // otherwise reject the request as "unknown algorithm" before
718        // any handler ran). Plain SigV4 (HMAC) requests return `None`
719        // and fall through to the inner service untouched.
720        if let Some(result) = try_sigv4a_verify(&req, self.sigv4a_gate.as_ref(), &self.region) {
721            match result {
722                Ok(()) => {
723                    // verified — fall through to the path-routing logic
724                    // below (the health/metrics/inner-service dispatch).
725                }
726                Err(resp) => return Box::pin(async move { Ok(resp) }),
727            }
728        }
729        let path = req.uri().path();
730        match (req.method(), path) {
731            (&hyper::Method::GET, "/health") | (&hyper::Method::HEAD, "/health") => {
732                Box::pin(async { Ok(make_text_response(StatusCode::OK, "ok\n")) })
733            }
734            (&hyper::Method::GET, "/metrics") | (&hyper::Method::HEAD, "/metrics") => {
735                let handle = self.metrics_handle.clone();
736                Box::pin(async move {
737                    match handle {
738                        Some(h) => {
739                            let body = h.render();
740                            Ok(make_owned_text_response(
741                                StatusCode::OK,
742                                "text/plain; version=0.0.4; charset=utf-8",
743                                body,
744                            ))
745                        }
746                        None => Ok(make_text_response(
747                            StatusCode::SERVICE_UNAVAILABLE,
748                            "metrics not configured\n",
749                        )),
750                    }
751                })
752            }
753            (&hyper::Method::GET, "/ready") | (&hyper::Method::HEAD, "/ready") => {
754                let check = self.ready_check.clone();
755                Box::pin(async move {
756                    match check {
757                        Some(f) => match f().await {
758                            Ok(()) => Ok(make_text_response(StatusCode::OK, "ready\n")),
759                            Err(reason) => {
760                                tracing::warn!(%reason, "readiness check failed");
761                                Ok(make_text_response(
762                                    StatusCode::SERVICE_UNAVAILABLE,
763                                    "not ready\n",
764                                ))
765                            }
766                        },
767                        None => Ok(make_text_response(StatusCode::OK, "ready (no check)\n")),
768                    }
769                })
770            }
771            _ => {
772                let inner = self.inner.clone();
773                Box::pin(async move { inner.call(req).await })
774            }
775        }
776    }
777}
778
779/// `Infallible` を anything に変換するためのトリック (`Full::map_err` 用)
780trait FullExt<B> {
781    fn map_err<E, F: FnMut(Infallible) -> E>(
782        self,
783        f: F,
784    ) -> http_body_util::combinators::MapErr<Self, F>
785    where
786        Self: Sized;
787}
788impl<B> FullExt<B> for Full<B>
789where
790    B: bytes::Buf,
791{
792    fn map_err<E, F: FnMut(Infallible) -> E>(
793        self,
794        f: F,
795    ) -> http_body_util::combinators::MapErr<Self, F>
796    where
797        Self: Sized,
798    {
799        http_body_util::BodyExt::map_err(self, f)
800    }
801}
802
803#[cfg(test)]
804mod preflight_tests {
805    //! v0.7 #44: unit tests for the OPTIONS preflight interceptor.
806    //!
807    //! These exercise [`try_handle_preflight`] directly — no hyper
808    //! `Incoming` body is needed because the function is generic over
809    //! the body type. Behavioural matrix:
810    //!
811    //! 1. matching preflight → 200 + Allow-* headers
812    //! 2. no matching rule (config exists, but origin/method/headers fail)
813    //!    → 403
814    //! 3. missing `Origin` header → `None` (not a CORS preflight)
815    //! 4. non-OPTIONS verb → `None`
816    //! 5. no CORS config registered for the bucket → `None`
817    //! 6. no manager attached → `None`
818
819    use super::*;
820    use crate::cors::{CorsConfig, CorsManager, CorsRule};
821
822    fn rule(origins: &[&str], methods: &[&str], headers: &[&str]) -> CorsRule {
823        CorsRule {
824            allowed_origins: origins.iter().map(|s| (*s).to_owned()).collect(),
825            allowed_methods: methods.iter().map(|s| (*s).to_owned()).collect(),
826            allowed_headers: headers.iter().map(|s| (*s).to_owned()).collect(),
827            expose_headers: vec!["ETag".into()],
828            max_age_seconds: Some(600),
829            id: Some("test".into()),
830        }
831    }
832
833    /// Helper: build a `Request<()>` with the given method, path, and
834    /// headers — body is ignored by the matcher.
835    fn req(method: Method, path: &str, headers: &[(&str, &str)]) -> Request<()> {
836        let mut b = Request::builder().method(method).uri(path);
837        for (k, v) in headers {
838            b = b.header(*k, *v);
839        }
840        b.body(()).expect("request builder")
841    }
842
843    fn manager_with_rule() -> Arc<CorsManager> {
844        let mgr = CorsManager::new();
845        mgr.put(
846            "b",
847            CorsConfig {
848                rules: vec![rule(
849                    &["https://app.example.com"],
850                    &["GET", "PUT", "DELETE"],
851                    &["Content-Type", "X-Amz-Date"],
852                )],
853            },
854        );
855        Arc::new(mgr)
856    }
857
858    #[test]
859    fn preflight_match_returns_allow_response() {
860        let mgr = manager_with_rule();
861        let r = req(
862            Method::OPTIONS,
863            "/b/key.txt",
864            &[
865                ("origin", "https://app.example.com"),
866                ("access-control-request-method", "PUT"),
867                ("access-control-request-headers", "content-type, x-amz-date"),
868            ],
869        );
870        let resp = try_handle_preflight(&r, Some(&mgr)).expect("must intercept");
871        assert_eq!(resp.status(), StatusCode::OK);
872        let h = resp.headers();
873        assert_eq!(
874            h.get("access-control-allow-origin")
875                .and_then(|v| v.to_str().ok()),
876            Some("https://app.example.com")
877        );
878        assert_eq!(
879            h.get("access-control-allow-methods")
880                .and_then(|v| v.to_str().ok()),
881            Some("GET, PUT, DELETE")
882        );
883        assert_eq!(
884            h.get("access-control-allow-headers")
885                .and_then(|v| v.to_str().ok()),
886            Some("Content-Type, X-Amz-Date")
887        );
888        assert_eq!(
889            h.get("access-control-max-age")
890                .and_then(|v| v.to_str().ok()),
891            Some("600")
892        );
893        assert_eq!(
894            h.get("access-control-expose-headers")
895                .and_then(|v| v.to_str().ok()),
896            Some("ETag")
897        );
898    }
899
900    #[test]
901    fn preflight_no_match_returns_403() {
902        let mgr = manager_with_rule();
903        // Origin not in allow-list → no rule matches but bucket has CORS
904        // config, so we must answer 403 directly (not fall through to
905        // s3s, which would otherwise leak the bucket existence via 405).
906        let r = req(
907            Method::OPTIONS,
908            "/b/key.txt",
909            &[
910                ("origin", "https://evil.example.com"),
911                ("access-control-request-method", "PUT"),
912            ],
913        );
914        let resp = try_handle_preflight(&r, Some(&mgr)).expect("must intercept");
915        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
916        // 403 deny response must NOT carry Allow-Origin (RFC 7234 + S3 wire compat).
917        assert!(resp.headers().get("access-control-allow-origin").is_none());
918    }
919
920    #[test]
921    fn preflight_no_origin_falls_through() {
922        // OPTIONS without Origin is a generic OPTIONS (e.g. `OPTIONS *`)
923        // — not a CORS preflight, must not be intercepted.
924        let mgr = manager_with_rule();
925        let r = req(
926            Method::OPTIONS,
927            "/b/key.txt",
928            &[("access-control-request-method", "PUT")],
929        );
930        assert!(try_handle_preflight(&r, Some(&mgr)).is_none());
931    }
932
933    #[test]
934    fn non_options_falls_through() {
935        let mgr = manager_with_rule();
936        // Even with Origin + ACRM headers, GET is not a preflight.
937        let r = req(
938            Method::GET,
939            "/b/key.txt",
940            &[
941                ("origin", "https://app.example.com"),
942                ("access-control-request-method", "PUT"),
943            ],
944        );
945        assert!(try_handle_preflight(&r, Some(&mgr)).is_none());
946    }
947
948    #[test]
949    fn no_cors_config_for_bucket_falls_through() {
950        // Manager attached but no rule registered for "ghost" → fall
951        // through to inner service so backend can respond naturally.
952        let mgr = manager_with_rule();
953        let r = req(
954            Method::OPTIONS,
955            "/ghost/key.txt",
956            &[
957                ("origin", "https://app.example.com"),
958                ("access-control-request-method", "PUT"),
959            ],
960        );
961        assert!(try_handle_preflight(&r, Some(&mgr)).is_none());
962    }
963
964    #[test]
965    fn no_manager_attached_falls_through() {
966        let r = req(
967            Method::OPTIONS,
968            "/b/key.txt",
969            &[
970                ("origin", "https://app.example.com"),
971                ("access-control-request-method", "PUT"),
972            ],
973        );
974        assert!(try_handle_preflight(&r, None).is_none());
975    }
976
977    #[test]
978    fn preflight_wildcard_origin_echoes_star() {
979        // Rule with `*` origin → response echoes literal "*" (S3 spec).
980        let mgr = CorsManager::new();
981        mgr.put(
982            "b",
983            CorsConfig {
984                rules: vec![rule(&["*"], &["GET", "PUT"], &["*"])],
985            },
986        );
987        let mgr = Arc::new(mgr);
988        let r = req(
989            Method::OPTIONS,
990            "/b/key",
991            &[
992                ("origin", "https://anywhere.example"),
993                ("access-control-request-method", "PUT"),
994                ("access-control-request-headers", "x-custom-header"),
995            ],
996        );
997        let resp = try_handle_preflight(&r, Some(&mgr)).expect("must intercept");
998        assert_eq!(resp.status(), StatusCode::OK);
999        assert_eq!(
1000            resp.headers()
1001                .get("access-control-allow-origin")
1002                .and_then(|v| v.to_str().ok()),
1003            Some("*"),
1004            "wildcard rule must echo literal '*' instead of requesting origin"
1005        );
1006    }
1007
1008    #[test]
1009    fn preflight_empty_path_falls_through() {
1010        let mgr = manager_with_rule();
1011        let r = req(
1012            Method::OPTIONS,
1013            "/",
1014            &[
1015                ("origin", "https://app.example.com"),
1016                ("access-control-request-method", "PUT"),
1017            ],
1018        );
1019        assert!(try_handle_preflight(&r, Some(&mgr)).is_none());
1020    }
1021}
1022
1023#[cfg(test)]
1024mod sigv4a_gate_tests {
1025    //! v0.7 #47: unit tests for the SigV4a verify gate middleware.
1026    //!
1027    //! These exercise [`try_sigv4a_verify`] directly — no hyper
1028    //! `Incoming` body is needed because the function is generic over
1029    //! the body type. The canonical-request bytes computed by the
1030    //! middleware are the same bytes the test signs over (we use the
1031    //! `build_canonical_request_bytes` helper for both sides), so the
1032    //! happy-path verify is end-to-end byte-exact.
1033    //!
1034    //! Behavioural matrix:
1035    //!
1036    //! 1. no `AWS4-ECDSA-P256-SHA256` prefix and no region-set header
1037    //!    → `None` (caller forwards to s3s SigV4 path)
1038    //! 2. SigV4a Authorization + valid signature → `Some(Ok(()))`
1039    //! 3. SigV4a Authorization + tampered signature → `Some(Err(403))`
1040    //!    with `SignatureDoesNotMatch` body
1041    //! 4. SigV4a Authorization + region-set mismatch → `Some(Err(403))`
1042    //! 5. gate is `None` (no credential store) → `None` even when the
1043    //!    request looks SigV4a-shaped (caller forwards, and s3s will
1044    //!    surface its own "unknown algorithm" error — operator sees the
1045    //!    misconfiguration rather than a silent pass)
1046    //! 6. unknown access-key-id → `Some(Err(403))` with
1047    //!    `InvalidAccessKeyId` body
1048    //! 7. SigV4a-shaped (region-set header only, no SigV4a auth header)
1049    //!    → `Some(Err(403))` (we cannot verify without a parseable
1050    //!    Authorization, fail closed)
1051
1052    use super::*;
1053
1054    use std::collections::HashMap;
1055
1056    use http_body_util::BodyExt;
1057    use p256::ecdsa::SigningKey;
1058    use p256::ecdsa::signature::Signer;
1059    use rand::rngs::OsRng;
1060
1061    use crate::service::SigV4aGate;
1062    use crate::sigv4a::{REGION_SET_HEADER, SigV4aCredentialStore};
1063
1064    fn lower_hex(bytes: &[u8]) -> String {
1065        let mut s = String::with_capacity(bytes.len() * 2);
1066        for b in bytes {
1067            s.push_str(&format!("{b:02x}"));
1068        }
1069        s
1070    }
1071
1072    /// Build a `Request<()>` with the given method, path, and headers.
1073    fn req(method: Method, path: &str, headers: &[(&str, &str)]) -> Request<()> {
1074        let mut b = Request::builder().method(method).uri(path);
1075        for (k, v) in headers {
1076            b = b.header(*k, *v);
1077        }
1078        b.body(()).expect("request builder")
1079    }
1080
1081    /// Build the SigV4a Authorization header for the given access-key,
1082    /// signed-headers list, and signature (lowercase hex DER).
1083    fn build_auth_header(access_key: &str, signed_headers: &[&str], sig_hex: &str) -> String {
1084        format!(
1085            "AWS4-ECDSA-P256-SHA256 \
1086             Credential={access_key}/20260513/s3/aws4_request, \
1087             SignedHeaders={}, \
1088             Signature={sig_hex}",
1089            signed_headers.join(";")
1090        )
1091    }
1092
1093    /// Build a fully-signed SigV4a `Request<()>` ready for the gate to
1094    /// verify. Returns the request and the verifying key it should be
1095    /// loaded against.
1096    fn make_signed_request(
1097        access_key: &str,
1098        method: Method,
1099        path: &str,
1100        region_set: &str,
1101    ) -> (Request<()>, p256::ecdsa::VerifyingKey) {
1102        let signing = SigningKey::random(&mut OsRng);
1103        let verifying = p256::ecdsa::VerifyingKey::from(&signing);
1104        let signed_headers_list = [
1105            "host",
1106            "x-amz-content-sha256",
1107            "x-amz-date",
1108            REGION_SET_HEADER,
1109        ];
1110        // Build the request first WITHOUT the Authorization header so we
1111        // can compute canonical bytes and sign them; then re-build the
1112        // request with the Authorization header attached.
1113        let pre = Request::builder()
1114            .method(method.clone())
1115            .uri(path)
1116            .header("host", "s3.example.com")
1117            .header(
1118                "x-amz-content-sha256",
1119                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
1120            )
1121            .header("x-amz-date", "20260513T120000Z")
1122            .header(REGION_SET_HEADER, region_set)
1123            .body(())
1124            .expect("pre-request");
1125        let signed_headers: Vec<String> = signed_headers_list
1126            .iter()
1127            .map(|s| (*s).to_string())
1128            .collect();
1129        let canonical =
1130            build_canonical_request_bytes(&pre, &signed_headers).expect("test fixture canonical");
1131        // v0.8.12 #126 (MED-A): sign the AWS-spec string-to-sign so
1132        // the routing-layer SigV4a fixture matches the new
1133        // `verify_request` body (which hashes the canonical request
1134        // and signs the algo / date / scope / hash concatenation).
1135        let canonical_hash = {
1136            use sha2::{Digest, Sha256};
1137            let mut h = Sha256::new();
1138            h.update(&canonical);
1139            let out = h.finalize();
1140            let mut s = String::with_capacity(out.len() * 2);
1141            for b in out {
1142                use std::fmt::Write as _;
1143                let _ = write!(s, "{b:02x}");
1144            }
1145            s
1146        };
1147        let sts = format!(
1148            "AWS4-ECDSA-P256-SHA256\n20260513T120000Z\n20260513/s3/aws4_request\n{canonical_hash}"
1149        );
1150        let sig: p256::ecdsa::Signature = signing.sign(sts.as_bytes());
1151        let sig_hex = lower_hex(sig.to_der().as_bytes());
1152        let auth = build_auth_header(access_key, &signed_headers_list, &sig_hex);
1153
1154        // Rebuild with the Authorization header — every other header
1155        // value is identical so the canonical bytes the gate computes
1156        // match what we signed.
1157        let r = Request::builder()
1158            .method(method)
1159            .uri(path)
1160            .header("host", "s3.example.com")
1161            .header(
1162                "x-amz-content-sha256",
1163                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
1164            )
1165            .header("x-amz-date", "20260513T120000Z")
1166            .header(REGION_SET_HEADER, region_set)
1167            .header("authorization", auth)
1168            .body(())
1169            .expect("signed request");
1170        (r, verifying)
1171    }
1172
1173    fn make_gate_with(access_key: &str, vk: p256::ecdsa::VerifyingKey) -> Arc<SigV4aGate> {
1174        let mut m = HashMap::new();
1175        m.insert(access_key.to_string(), vk);
1176        let store = Arc::new(SigV4aCredentialStore::from_map(m));
1177        Arc::new(SigV4aGate::new(store))
1178    }
1179
1180    /// Drain a `s3s::Body` into bytes for body-content assertions.
1181    async fn body_to_bytes(resp: Response<s3s::Body>) -> Vec<u8> {
1182        resp.into_body()
1183            .collect()
1184            .await
1185            .expect("body collect")
1186            .to_bytes()
1187            .to_vec()
1188    }
1189
1190    /// v0.8.4 #76: pinned `now` matching the `x-amz-date: 20260513T120000Z`
1191    /// the test fixtures stamp. Without this the freshness check would
1192    /// reject every gate test (the timestamp would be days/weeks old by
1193    /// the time CI runs). Production callers use `try_sigv4a_verify`
1194    /// (which calls `Utc::now()`).
1195    fn fixture_now() -> chrono::DateTime<chrono::Utc> {
1196        chrono::DateTime::parse_from_rfc3339("2026-05-13T12:00:00Z")
1197            .unwrap()
1198            .with_timezone(&chrono::Utc)
1199    }
1200
1201    #[test]
1202    fn no_sigv4a_prefix_returns_none() {
1203        // Plain SigV4 (HMAC-SHA256) request — gate must defer to s3s.
1204        let (_, vk) = (
1205            (),
1206            p256::ecdsa::VerifyingKey::from(&SigningKey::random(&mut OsRng)),
1207        );
1208        let gate = make_gate_with("AKIAOK", vk);
1209        let r = req(
1210            Method::GET,
1211            "/bucket/key",
1212            &[(
1213                "authorization",
1214                "AWS4-HMAC-SHA256 Credential=AKIA/20260513/us-east-1/s3/aws4_request, \
1215                 SignedHeaders=host, Signature=deadbeef",
1216            )],
1217        );
1218        assert!(
1219            try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", fixture_now()).is_none(),
1220            "plain SigV4 request must fall through to the inner service"
1221        );
1222    }
1223
1224    #[test]
1225    fn sigv4a_valid_signature_returns_ok() {
1226        let (r, vk) =
1227            make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1,us-west-2");
1228        let gate = make_gate_with("AKIAOK", vk);
1229        let result = try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", fixture_now())
1230            .expect("must intercept SigV4a request");
1231        assert!(
1232            result.is_ok(),
1233            "valid SigV4a signature must verify: {result:?}"
1234        );
1235    }
1236
1237    #[tokio::test]
1238    async fn sigv4a_tampered_signature_returns_403() {
1239        let (r, vk) = make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1");
1240        let gate = make_gate_with("AKIAOK", vk);
1241
1242        // Tamper one byte of the signature hex inside the Authorization
1243        // header — the DER decode may still succeed, but ECDSA verify
1244        // will fail (or the DER decode itself will fail; both surface
1245        // as `SignatureDoesNotMatch`).
1246        let auth = r
1247            .headers()
1248            .get("authorization")
1249            .and_then(|v| v.to_str().ok())
1250            .expect("auth header")
1251            .to_string();
1252        // Flip the last hex char to corrupt the signature.
1253        let mut chars: Vec<char> = auth.chars().collect();
1254        let last = chars.len() - 1;
1255        chars[last] = if chars[last] == '0' { '1' } else { '0' };
1256        let tampered_auth: String = chars.into_iter().collect();
1257        let tampered = req(
1258            Method::GET,
1259            "/bucket/key",
1260            &[
1261                ("host", "s3.example.com"),
1262                (
1263                    "x-amz-content-sha256",
1264                    "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
1265                ),
1266                ("x-amz-date", "20260513T120000Z"),
1267                (REGION_SET_HEADER, "us-east-1"),
1268                ("authorization", &tampered_auth),
1269            ],
1270        );
1271        let result = try_sigv4a_verify_at(&tampered, Some(&gate), "us-east-1", fixture_now())
1272            .expect("must intercept SigV4a request");
1273        let resp = result.expect_err("tampered signature must surface a 403 response");
1274        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1275        let body = body_to_bytes(resp).await;
1276        let body_str = String::from_utf8(body).expect("xml utf-8");
1277        assert!(
1278            body_str.contains("<Code>SignatureDoesNotMatch</Code>"),
1279            "403 body must surface SignatureDoesNotMatch: {body_str}"
1280        );
1281    }
1282
1283    #[tokio::test]
1284    async fn sigv4a_region_set_mismatch_returns_403() {
1285        // Sign for `us-east-1` only, then verify with the listener
1286        // region claiming `eu-west-1` — must fail with
1287        // SignatureDoesNotMatch (the region-set check sits inside the
1288        // gate's verify path, and any failure there folds to
1289        // SignatureDoesNotMatch).
1290        let (r, vk) = make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1");
1291        let gate = make_gate_with("AKIAOK", vk);
1292        let result = try_sigv4a_verify_at(&r, Some(&gate), "eu-west-1", fixture_now())
1293            .expect("must intercept SigV4a request");
1294        let resp = result.expect_err("region mismatch must produce 403");
1295        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1296        let body = body_to_bytes(resp).await;
1297        let body_str = String::from_utf8(body).expect("xml utf-8");
1298        assert!(
1299            body_str.contains("<Code>SignatureDoesNotMatch</Code>"),
1300            "region-set mismatch must surface SignatureDoesNotMatch: {body_str}"
1301        );
1302    }
1303
1304    #[test]
1305    fn no_gate_attached_returns_none() {
1306        // Even a SigV4a-shaped request returns None when no gate is
1307        // installed — the listener will hand it to s3s, which surfaces
1308        // its own "unknown algorithm" error so the misconfiguration is
1309        // visible to the operator.
1310        let (r, _vk) = make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1");
1311        assert!(
1312            try_sigv4a_verify_at(&r, None, "us-east-1", fixture_now()).is_none(),
1313            "missing gate must defer to inner service"
1314        );
1315    }
1316
1317    #[tokio::test]
1318    async fn unknown_access_key_returns_403_invalid_access_key_id() {
1319        // Sign with one key but load the credential store with a
1320        // different access-key-id → InvalidAccessKeyId.
1321        let (r, _vk_unused) =
1322            make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1");
1323        let other_signing = SigningKey::random(&mut OsRng);
1324        let other_vk = p256::ecdsa::VerifyingKey::from(&other_signing);
1325        let gate = make_gate_with("AKIASOMEONEELSE", other_vk);
1326        let result = try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", fixture_now())
1327            .expect("must intercept SigV4a request");
1328        let resp = result.expect_err("unknown key must produce 403");
1329        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1330        let body = body_to_bytes(resp).await;
1331        let body_str = String::from_utf8(body).expect("xml utf-8");
1332        assert!(
1333            body_str.contains("<Code>InvalidAccessKeyId</Code>"),
1334            "unknown access-key must surface InvalidAccessKeyId: {body_str}"
1335        );
1336    }
1337
1338    #[tokio::test]
1339    async fn region_set_header_only_without_sigv4a_auth_returns_403() {
1340        // Some legacy clients stamp the `X-Amz-Region-Set` header
1341        // before swapping the algorithm string. `detect` flags this as
1342        // SigV4a-shaped but we cannot verify without a parseable
1343        // Authorization → fail closed (SignatureDoesNotMatch).
1344        let signing = SigningKey::random(&mut OsRng);
1345        let vk = p256::ecdsa::VerifyingKey::from(&signing);
1346        let gate = make_gate_with("AKIAOK", vk);
1347        let r = req(
1348            Method::GET,
1349            "/bucket/key",
1350            &[
1351                // SigV4 algorithm + region-set header → detected, but
1352                // the Authorization is plain SigV4 so `parse_authorization_header`
1353                // returns None.
1354                (
1355                    "authorization",
1356                    "AWS4-HMAC-SHA256 Credential=AKIA/20260513/us-east-1/s3/aws4_request, \
1357                     SignedHeaders=host, Signature=deadbeef",
1358                ),
1359                (REGION_SET_HEADER, "us-east-1"),
1360            ],
1361        );
1362        let result = try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", fixture_now())
1363            .expect("must intercept SigV4a-shaped request");
1364        let resp = result.expect_err("region-set without sigv4a auth must produce 403");
1365        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1366        let body = body_to_bytes(resp).await;
1367        let body_str = String::from_utf8(body).expect("xml utf-8");
1368        assert!(
1369            body_str.contains("<Code>SignatureDoesNotMatch</Code>"),
1370            "missing/malformed Authorization for SigV4a-shaped request must fail closed: {body_str}"
1371        );
1372    }
1373
1374    /// v0.8.4 #76 (audit H-6): captured-request replay outside the
1375    /// 15-min window → 403 RequestTimeTooSkewed (not
1376    /// SignatureDoesNotMatch). This is the headline gate-level
1377    /// behaviour change; pre-#76 the same captured request would have
1378    /// reached the inner service, allowing destructive replay (DELETE
1379    /// included).
1380    #[tokio::test]
1381    async fn sigv4a_replay_outside_window_returns_403_request_time_too_skewed() {
1382        let (r, vk) = make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1");
1383        let gate = make_gate_with("AKIAOK", vk);
1384        // Request stamped 20260513T120000Z; "now" is 30 min later → drift
1385        // 1800s, beyond the 900s default tolerance.
1386        let now = chrono::DateTime::parse_from_rfc3339("2026-05-13T12:30:00Z")
1387            .unwrap()
1388            .with_timezone(&chrono::Utc);
1389        let result = try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", now)
1390            .expect("must intercept SigV4a request");
1391        let resp = result.expect_err("replay outside window must reject");
1392        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1393        let body = body_to_bytes(resp).await;
1394        let body_str = String::from_utf8(body).expect("xml utf-8");
1395        assert!(
1396            body_str.contains("<Code>RequestTimeTooSkewed</Code>"),
1397            "replay outside window must surface RequestTimeTooSkewed: {body_str}"
1398        );
1399    }
1400
1401    /// Cover the canonical-request builder directly: empty query
1402    /// string, sorted multi-pair query, and header value collapsed
1403    /// whitespace all hit the right code paths.
1404    #[test]
1405    fn canonical_request_bytes_format() {
1406        let r = req(
1407            Method::PUT,
1408            "/bucket/key?z=1&a=2",
1409            &[
1410                ("host", "s3.example.com"),
1411                ("x-amz-content-sha256", "UNSIGNED-PAYLOAD"),
1412                ("x-amz-date", "  20260513T120000Z  "),
1413            ],
1414        );
1415        let signed: Vec<String> = ["host", "x-amz-content-sha256", "x-amz-date"]
1416            .iter()
1417            .map(|s| (*s).into())
1418            .collect();
1419        let bytes =
1420            build_canonical_request_bytes(&r, &signed).expect("canonical request bytes must build");
1421        let s = std::str::from_utf8(&bytes).expect("utf-8");
1422        let expected = "PUT\n\
1423                        /bucket/key\n\
1424                        a=2&z=1\n\
1425                        host:s3.example.com\n\
1426                        x-amz-content-sha256:UNSIGNED-PAYLOAD\n\
1427                        x-amz-date:20260513T120000Z\n\
1428                        \n\
1429                        host;x-amz-content-sha256;x-amz-date\n\
1430                        UNSIGNED-PAYLOAD";
1431        assert_eq!(s, expected, "canonical request bytes mismatch:\n{s}");
1432    }
1433
1434    /// v0.8.5 #84 H-4: duplicate `x-amz-date` headers must be rejected
1435    /// at canonical-request build time (not silently coalesced to the
1436    /// first value). HTTP/1.1 spec already forbids duplicates of
1437    /// `host` / `x-amz-date`; AWS SDKs never emit them; so any
1438    /// duplicate must be malicious or broken — single-value reject is
1439    /// the safe choice (see [`build_canonical_request_bytes`] doc).
1440    #[test]
1441    fn sigv4a_duplicate_x_amz_date_rejected() {
1442        // Two x-amz-date headers — first one matches the signature the
1443        // gate expects, second one is what a downstream parser might
1444        // pick up. This is the textbook auth-confusion vector.
1445        let r = Request::builder()
1446            .method(Method::GET)
1447            .uri("/b/k")
1448            .header("host", "s3.example.com")
1449            .header("x-amz-content-sha256", "UNSIGNED-PAYLOAD")
1450            .header("x-amz-date", "20260513T120000Z")
1451            .header("x-amz-date", "20260513T130000Z")
1452            .body(())
1453            .expect("dup-header request");
1454        let signed: Vec<String> = ["host", "x-amz-content-sha256", "x-amz-date"]
1455            .iter()
1456            .map(|s| (*s).into())
1457            .collect();
1458        let err = build_canonical_request_bytes(&r, &signed)
1459            .expect_err("duplicate x-amz-date must reject");
1460        match err {
1461            crate::sigv4a::SigV4aError::DuplicateSignedHeader { header } => {
1462                assert_eq!(header, "x-amz-date");
1463            }
1464            other => panic!("expected DuplicateSignedHeader, got {other:?}"),
1465        }
1466    }
1467
1468    /// v0.8.5 #84 H-4: counterpart to the duplicate-reject test —
1469    /// single-occurrence headers on the same path stay accepted.
1470    /// Guards against a regression where the duplicate-detect logic
1471    /// is over-eager and trips on a normally-formed request.
1472    #[test]
1473    fn sigv4a_canonicalization_single_header_passes() {
1474        let r = req(
1475            Method::GET,
1476            "/b/k",
1477            &[
1478                ("host", "s3.example.com"),
1479                ("x-amz-content-sha256", "UNSIGNED-PAYLOAD"),
1480                ("x-amz-date", "20260513T120000Z"),
1481            ],
1482        );
1483        let signed: Vec<String> = ["host", "x-amz-content-sha256", "x-amz-date"]
1484            .iter()
1485            .map(|s| (*s).into())
1486            .collect();
1487        let bytes =
1488            build_canonical_request_bytes(&r, &signed).expect("single-occurrence must accept");
1489        // Body content not asserted in detail (covered by
1490        // canonical_request_bytes_format); just confirm the bytes
1491        // parse as utf-8 and contain the date verbatim.
1492        let s = std::str::from_utf8(&bytes).expect("utf-8");
1493        assert!(
1494            s.contains("x-amz-date:20260513T120000Z"),
1495            "canonical bytes must echo the single x-amz-date verbatim:\n{s}"
1496        );
1497    }
1498
1499    /// v0.8.5 #84 H-4: end-to-end through the
1500    /// [`try_sigv4a_verify_at`] gate — duplicate `x-amz-date` on a
1501    /// SigV4a-shaped request must surface 403 SignatureDoesNotMatch
1502    /// (not silently authenticate against the first value).
1503    #[tokio::test]
1504    async fn sigv4a_pre_route_rejects_duplicate_signed_header() {
1505        let signing = SigningKey::random(&mut OsRng);
1506        let vk = p256::ecdsa::VerifyingKey::from(&signing);
1507        let gate = make_gate_with("AKIAOK", vk);
1508        // Authorization header lists x-amz-date in SignedHeaders —
1509        // signature value itself can be garbage; the duplicate-detect
1510        // path runs strictly before any ECDSA math.
1511        let auth = build_auth_header(
1512            "AKIAOK",
1513            &[
1514                "host",
1515                "x-amz-content-sha256",
1516                "x-amz-date",
1517                REGION_SET_HEADER,
1518            ],
1519            "deadbeef",
1520        );
1521        let r = Request::builder()
1522            .method(Method::GET)
1523            .uri("/bucket/key")
1524            .header("host", "s3.example.com")
1525            .header(
1526                "x-amz-content-sha256",
1527                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
1528            )
1529            .header("x-amz-date", "20260513T120000Z")
1530            .header("x-amz-date", "20260513T130000Z")
1531            .header(REGION_SET_HEADER, "us-east-1")
1532            .header("authorization", auth)
1533            .body(())
1534            .expect("dup-header sigv4a request");
1535        let result = try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", fixture_now())
1536            .expect("must intercept SigV4a request");
1537        let resp = result.expect_err("duplicate signed header must reject at the gate");
1538        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1539        let body = body_to_bytes(resp).await;
1540        let body_str = String::from_utf8(body).expect("xml utf-8");
1541        assert!(
1542            body_str.contains("<Code>SignatureDoesNotMatch</Code>"),
1543            "duplicate signed header must surface SignatureDoesNotMatch: {body_str}"
1544        );
1545        assert!(
1546            body_str.contains("duplicate signed header"),
1547            "diagnostic must mention duplicate header: {body_str}"
1548        );
1549    }
1550}