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/// v0.8.18 P3: AWS SigV4 canonical-request test vectors. These
1024/// exercise [`canonical_uri_path`] and [`canonical_query_string`]
1025/// (the v0.8.16 #150 byte-level helpers) against the published
1026/// AWS test suite. Each vector's `request` field is the raw HTTP
1027/// request the suite ships; `expected_canonical_uri` and
1028/// `expected_canonical_query` are the canonical strings the
1029/// reference implementation produces. We compare byte-for-byte.
1030///
1031/// Sources are tagged with their AWS suite name so an auditor can
1032/// cross-check against the public docs. The vectors were chosen
1033/// to cover the edge cases the v0.8.16 #150 fix targeted
1034/// (non-UTF-8 bytes, mixed-case percent encoding, query duplicates,
1035/// path-segment encoding).
1036#[cfg(test)]
1037mod aws_sigv4_canonical_vectors {
1038 use super::{canonical_query_string, canonical_uri_path};
1039
1040 /// AWS `get-vanilla` — path `/`, no query. Canonical URI is `/`,
1041 /// canonical query is empty.
1042 #[test]
1043 fn get_vanilla() {
1044 assert_eq!(canonical_uri_path("/"), "/");
1045 assert_eq!(canonical_query_string(""), "");
1046 }
1047
1048 /// AWS `get-vanilla-query-order-key-case` — query keys must
1049 /// sort by encoded form. `Param2=value2&Param1=value1` →
1050 /// `Param1=value1&Param2=value2`. Case-sensitive comparison
1051 /// per the spec.
1052 #[test]
1053 fn get_vanilla_query_order_key_case() {
1054 let canon = canonical_query_string("Param2=value2&Param1=value1");
1055 assert_eq!(canon, "Param1=value1&Param2=value2");
1056 }
1057
1058 /// AWS `get-vanilla-query-order-value` — same key with
1059 /// different values must sort by encoded value as tiebreaker.
1060 #[test]
1061 fn get_vanilla_query_order_value() {
1062 let canon = canonical_query_string("Param1=value2&Param1=Value1");
1063 // `V` (0x56) sorts before `v` (0x76) in byte order; the
1064 // canonical form preserves the encoded value sort.
1065 assert_eq!(canon, "Param1=Value1&Param1=value2");
1066 }
1067
1068 /// AWS `get-utf8` — UTF-8 characters in the path must be
1069 /// percent-encoded with uppercase hex.
1070 #[test]
1071 fn get_utf8_path() {
1072 // Japanese for "Hello": "こんにちは" (5 chars, 15 bytes
1073 // UTF-8). Encoded per AWS canonical:
1074 // %E3%81%93 %E3%82%93 %E3%81%AB %E3%81%A1 %E3%81%AF
1075 let canon = canonical_uri_path("/こんにちは");
1076 assert_eq!(canon, "/%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF");
1077 }
1078
1079 /// v0.8.16 #150 motivation — non-UTF-8 percent-encoded bytes
1080 /// must round-trip byte-identically. Pre-#150 `decode_utf8_lossy`
1081 /// turned `%FF` into U+FFFD (`%EF%BF%BD`).
1082 #[test]
1083 fn non_utf8_path_byte_roundtrip() {
1084 // Raw `%FF` in a path. AWS-canonical re-encoding must
1085 // produce `%FF` again, not `%EF%BF%BD`.
1086 let canon = canonical_uri_path("/foo/%FF");
1087 assert_eq!(canon, "/foo/%FF");
1088 }
1089
1090 /// AWS canonical query: keys / values that contain reserved
1091 /// chars get re-encoded with uppercase hex.
1092 #[test]
1093 fn query_reserved_chars_uppercase_hex() {
1094 // `key with space=value/with%2Fslash` after canonical
1095 // encoding:
1096 let canon = canonical_query_string("key%20with%20space=value%2Fwith%2Fslash");
1097 assert_eq!(canon, "key%20with%20space=value%2Fwith%2Fslash");
1098 }
1099
1100 /// AWS canonical path: existing percent-encoded uppercase
1101 /// stays uppercase; lowercase `%2f` from a normalising
1102 /// terminator gets re-canonicalised to `%2F`.
1103 #[test]
1104 fn path_mixed_case_percent_encoding_normalised() {
1105 assert_eq!(canonical_uri_path("/a/%2Fb"), "/a/%2Fb");
1106 assert_eq!(canonical_uri_path("/a/%2fb"), "/a/%2Fb");
1107 }
1108
1109 /// AWS canonical: query key without value (e.g. `?delete`).
1110 /// Canonical form is `delete=`.
1111 #[test]
1112 fn query_bare_key_canonicalises_with_empty_value() {
1113 assert_eq!(canonical_query_string("delete"), "delete=");
1114 }
1115
1116 /// Reserved set per RFC 3986 unreserved: A-Z a-z 0-9 - _ . ~
1117 /// Everything else must be %-encoded.
1118 #[test]
1119 fn unreserved_set_kept_literal() {
1120 assert_eq!(
1121 canonical_uri_path("/-_.~ABCDEabcde012-_.~"),
1122 "/-_.~ABCDEabcde012-_.~"
1123 );
1124 }
1125
1126 /// Common AWS S3 query: `?list-type=2&prefix=foo%2F` — verify
1127 /// the canonical form matches what aws-sdk-rust signs.
1128 #[test]
1129 fn s3_listobjects_v2_canonical_query() {
1130 let canon = canonical_query_string("list-type=2&prefix=foo%2F");
1131 assert_eq!(canon, "list-type=2&prefix=foo%2F");
1132 }
1133
1134 /// S3 canonical URI: `/bucket/path with space/file` →
1135 /// `/bucket/path%20with%20space/file`.
1136 #[test]
1137 fn s3_path_with_spaces() {
1138 let canon = canonical_uri_path("/bucket/path with space/file");
1139 assert_eq!(canon, "/bucket/path%20with%20space/file");
1140 }
1141}
1142
1143#[cfg(test)]
1144mod sigv4a_gate_tests {
1145 //! v0.7 #47: unit tests for the SigV4a verify gate middleware.
1146 //!
1147 //! These exercise [`try_sigv4a_verify`] directly — no hyper
1148 //! `Incoming` body is needed because the function is generic over
1149 //! the body type. The canonical-request bytes computed by the
1150 //! middleware are the same bytes the test signs over (we use the
1151 //! `build_canonical_request_bytes` helper for both sides), so the
1152 //! happy-path verify is end-to-end byte-exact.
1153 //!
1154 //! Behavioural matrix:
1155 //!
1156 //! 1. no `AWS4-ECDSA-P256-SHA256` prefix and no region-set header
1157 //! → `None` (caller forwards to s3s SigV4 path)
1158 //! 2. SigV4a Authorization + valid signature → `Some(Ok(()))`
1159 //! 3. SigV4a Authorization + tampered signature → `Some(Err(403))`
1160 //! with `SignatureDoesNotMatch` body
1161 //! 4. SigV4a Authorization + region-set mismatch → `Some(Err(403))`
1162 //! 5. gate is `None` (no credential store) → `None` even when the
1163 //! request looks SigV4a-shaped (caller forwards, and s3s will
1164 //! surface its own "unknown algorithm" error — operator sees the
1165 //! misconfiguration rather than a silent pass)
1166 //! 6. unknown access-key-id → `Some(Err(403))` with
1167 //! `InvalidAccessKeyId` body
1168 //! 7. SigV4a-shaped (region-set header only, no SigV4a auth header)
1169 //! → `Some(Err(403))` (we cannot verify without a parseable
1170 //! Authorization, fail closed)
1171
1172 use super::*;
1173
1174 use std::collections::HashMap;
1175
1176 use http_body_util::BodyExt;
1177 use p256::ecdsa::SigningKey;
1178 use p256::ecdsa::signature::Signer;
1179 use rand::rngs::OsRng;
1180
1181 use crate::service::SigV4aGate;
1182 use crate::sigv4a::{REGION_SET_HEADER, SigV4aCredentialStore};
1183
1184 fn lower_hex(bytes: &[u8]) -> String {
1185 let mut s = String::with_capacity(bytes.len() * 2);
1186 for b in bytes {
1187 s.push_str(&format!("{b:02x}"));
1188 }
1189 s
1190 }
1191
1192 /// Build a `Request<()>` with the given method, path, and headers.
1193 fn req(method: Method, path: &str, headers: &[(&str, &str)]) -> Request<()> {
1194 let mut b = Request::builder().method(method).uri(path);
1195 for (k, v) in headers {
1196 b = b.header(*k, *v);
1197 }
1198 b.body(()).expect("request builder")
1199 }
1200
1201 /// Build the SigV4a Authorization header for the given access-key,
1202 /// signed-headers list, and signature (lowercase hex DER).
1203 fn build_auth_header(access_key: &str, signed_headers: &[&str], sig_hex: &str) -> String {
1204 format!(
1205 "AWS4-ECDSA-P256-SHA256 \
1206 Credential={access_key}/20260513/s3/aws4_request, \
1207 SignedHeaders={}, \
1208 Signature={sig_hex}",
1209 signed_headers.join(";")
1210 )
1211 }
1212
1213 /// Build a fully-signed SigV4a `Request<()>` ready for the gate to
1214 /// verify. Returns the request and the verifying key it should be
1215 /// loaded against.
1216 fn make_signed_request(
1217 access_key: &str,
1218 method: Method,
1219 path: &str,
1220 region_set: &str,
1221 ) -> (Request<()>, p256::ecdsa::VerifyingKey) {
1222 let signing = SigningKey::random(&mut OsRng);
1223 let verifying = p256::ecdsa::VerifyingKey::from(&signing);
1224 let signed_headers_list = [
1225 "host",
1226 "x-amz-content-sha256",
1227 "x-amz-date",
1228 REGION_SET_HEADER,
1229 ];
1230 // Build the request first WITHOUT the Authorization header so we
1231 // can compute canonical bytes and sign them; then re-build the
1232 // request with the Authorization header attached.
1233 let pre = Request::builder()
1234 .method(method.clone())
1235 .uri(path)
1236 .header("host", "s3.example.com")
1237 .header(
1238 "x-amz-content-sha256",
1239 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
1240 )
1241 .header("x-amz-date", "20260513T120000Z")
1242 .header(REGION_SET_HEADER, region_set)
1243 .body(())
1244 .expect("pre-request");
1245 let signed_headers: Vec<String> = signed_headers_list
1246 .iter()
1247 .map(|s| (*s).to_string())
1248 .collect();
1249 let canonical =
1250 build_canonical_request_bytes(&pre, &signed_headers).expect("test fixture canonical");
1251 // v0.8.12 #126 (MED-A): sign the AWS-spec string-to-sign so
1252 // the routing-layer SigV4a fixture matches the new
1253 // `verify_request` body (which hashes the canonical request
1254 // and signs the algo / date / scope / hash concatenation).
1255 let canonical_hash = {
1256 use sha2::{Digest, Sha256};
1257 let mut h = Sha256::new();
1258 h.update(&canonical);
1259 let out = h.finalize();
1260 let mut s = String::with_capacity(out.len() * 2);
1261 for b in out {
1262 use std::fmt::Write as _;
1263 let _ = write!(s, "{b:02x}");
1264 }
1265 s
1266 };
1267 let sts = format!(
1268 "AWS4-ECDSA-P256-SHA256\n20260513T120000Z\n20260513/s3/aws4_request\n{canonical_hash}"
1269 );
1270 let sig: p256::ecdsa::Signature = signing.sign(sts.as_bytes());
1271 let sig_hex = lower_hex(sig.to_der().as_bytes());
1272 let auth = build_auth_header(access_key, &signed_headers_list, &sig_hex);
1273
1274 // Rebuild with the Authorization header — every other header
1275 // value is identical so the canonical bytes the gate computes
1276 // match what we signed.
1277 let r = Request::builder()
1278 .method(method)
1279 .uri(path)
1280 .header("host", "s3.example.com")
1281 .header(
1282 "x-amz-content-sha256",
1283 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
1284 )
1285 .header("x-amz-date", "20260513T120000Z")
1286 .header(REGION_SET_HEADER, region_set)
1287 .header("authorization", auth)
1288 .body(())
1289 .expect("signed request");
1290 (r, verifying)
1291 }
1292
1293 fn make_gate_with(access_key: &str, vk: p256::ecdsa::VerifyingKey) -> Arc<SigV4aGate> {
1294 let mut m = HashMap::new();
1295 m.insert(access_key.to_string(), vk);
1296 let store = Arc::new(SigV4aCredentialStore::from_map(m));
1297 Arc::new(SigV4aGate::new(store))
1298 }
1299
1300 /// Drain a `s3s::Body` into bytes for body-content assertions.
1301 async fn body_to_bytes(resp: Response<s3s::Body>) -> Vec<u8> {
1302 resp.into_body()
1303 .collect()
1304 .await
1305 .expect("body collect")
1306 .to_bytes()
1307 .to_vec()
1308 }
1309
1310 /// v0.8.4 #76: pinned `now` matching the `x-amz-date: 20260513T120000Z`
1311 /// the test fixtures stamp. Without this the freshness check would
1312 /// reject every gate test (the timestamp would be days/weeks old by
1313 /// the time CI runs). Production callers use `try_sigv4a_verify`
1314 /// (which calls `Utc::now()`).
1315 fn fixture_now() -> chrono::DateTime<chrono::Utc> {
1316 chrono::DateTime::parse_from_rfc3339("2026-05-13T12:00:00Z")
1317 .unwrap()
1318 .with_timezone(&chrono::Utc)
1319 }
1320
1321 #[test]
1322 fn no_sigv4a_prefix_returns_none() {
1323 // Plain SigV4 (HMAC-SHA256) request — gate must defer to s3s.
1324 let (_, vk) = (
1325 (),
1326 p256::ecdsa::VerifyingKey::from(&SigningKey::random(&mut OsRng)),
1327 );
1328 let gate = make_gate_with("AKIAOK", vk);
1329 let r = req(
1330 Method::GET,
1331 "/bucket/key",
1332 &[(
1333 "authorization",
1334 "AWS4-HMAC-SHA256 Credential=AKIA/20260513/us-east-1/s3/aws4_request, \
1335 SignedHeaders=host, Signature=deadbeef",
1336 )],
1337 );
1338 assert!(
1339 try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", fixture_now()).is_none(),
1340 "plain SigV4 request must fall through to the inner service"
1341 );
1342 }
1343
1344 #[test]
1345 fn sigv4a_valid_signature_returns_ok() {
1346 let (r, vk) =
1347 make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1,us-west-2");
1348 let gate = make_gate_with("AKIAOK", vk);
1349 let result = try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", fixture_now())
1350 .expect("must intercept SigV4a request");
1351 assert!(
1352 result.is_ok(),
1353 "valid SigV4a signature must verify: {result:?}"
1354 );
1355 }
1356
1357 #[tokio::test]
1358 async fn sigv4a_tampered_signature_returns_403() {
1359 let (r, vk) = make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1");
1360 let gate = make_gate_with("AKIAOK", vk);
1361
1362 // Tamper one byte of the signature hex inside the Authorization
1363 // header — the DER decode may still succeed, but ECDSA verify
1364 // will fail (or the DER decode itself will fail; both surface
1365 // as `SignatureDoesNotMatch`).
1366 let auth = r
1367 .headers()
1368 .get("authorization")
1369 .and_then(|v| v.to_str().ok())
1370 .expect("auth header")
1371 .to_string();
1372 // Flip the last hex char to corrupt the signature.
1373 let mut chars: Vec<char> = auth.chars().collect();
1374 let last = chars.len() - 1;
1375 chars[last] = if chars[last] == '0' { '1' } else { '0' };
1376 let tampered_auth: String = chars.into_iter().collect();
1377 let tampered = req(
1378 Method::GET,
1379 "/bucket/key",
1380 &[
1381 ("host", "s3.example.com"),
1382 (
1383 "x-amz-content-sha256",
1384 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
1385 ),
1386 ("x-amz-date", "20260513T120000Z"),
1387 (REGION_SET_HEADER, "us-east-1"),
1388 ("authorization", &tampered_auth),
1389 ],
1390 );
1391 let result = try_sigv4a_verify_at(&tampered, Some(&gate), "us-east-1", fixture_now())
1392 .expect("must intercept SigV4a request");
1393 let resp = result.expect_err("tampered signature must surface a 403 response");
1394 assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1395 let body = body_to_bytes(resp).await;
1396 let body_str = String::from_utf8(body).expect("xml utf-8");
1397 assert!(
1398 body_str.contains("<Code>SignatureDoesNotMatch</Code>"),
1399 "403 body must surface SignatureDoesNotMatch: {body_str}"
1400 );
1401 }
1402
1403 #[tokio::test]
1404 async fn sigv4a_region_set_mismatch_returns_403() {
1405 // Sign for `us-east-1` only, then verify with the listener
1406 // region claiming `eu-west-1` — must fail with
1407 // SignatureDoesNotMatch (the region-set check sits inside the
1408 // gate's verify path, and any failure there folds to
1409 // SignatureDoesNotMatch).
1410 let (r, vk) = make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1");
1411 let gate = make_gate_with("AKIAOK", vk);
1412 let result = try_sigv4a_verify_at(&r, Some(&gate), "eu-west-1", fixture_now())
1413 .expect("must intercept SigV4a request");
1414 let resp = result.expect_err("region mismatch must produce 403");
1415 assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1416 let body = body_to_bytes(resp).await;
1417 let body_str = String::from_utf8(body).expect("xml utf-8");
1418 assert!(
1419 body_str.contains("<Code>SignatureDoesNotMatch</Code>"),
1420 "region-set mismatch must surface SignatureDoesNotMatch: {body_str}"
1421 );
1422 }
1423
1424 #[test]
1425 fn no_gate_attached_returns_none() {
1426 // Even a SigV4a-shaped request returns None when no gate is
1427 // installed — the listener will hand it to s3s, which surfaces
1428 // its own "unknown algorithm" error so the misconfiguration is
1429 // visible to the operator.
1430 let (r, _vk) = make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1");
1431 assert!(
1432 try_sigv4a_verify_at(&r, None, "us-east-1", fixture_now()).is_none(),
1433 "missing gate must defer to inner service"
1434 );
1435 }
1436
1437 #[tokio::test]
1438 async fn unknown_access_key_returns_403_invalid_access_key_id() {
1439 // Sign with one key but load the credential store with a
1440 // different access-key-id → InvalidAccessKeyId.
1441 let (r, _vk_unused) =
1442 make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1");
1443 let other_signing = SigningKey::random(&mut OsRng);
1444 let other_vk = p256::ecdsa::VerifyingKey::from(&other_signing);
1445 let gate = make_gate_with("AKIASOMEONEELSE", other_vk);
1446 let result = try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", fixture_now())
1447 .expect("must intercept SigV4a request");
1448 let resp = result.expect_err("unknown key must produce 403");
1449 assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1450 let body = body_to_bytes(resp).await;
1451 let body_str = String::from_utf8(body).expect("xml utf-8");
1452 assert!(
1453 body_str.contains("<Code>InvalidAccessKeyId</Code>"),
1454 "unknown access-key must surface InvalidAccessKeyId: {body_str}"
1455 );
1456 }
1457
1458 #[tokio::test]
1459 async fn region_set_header_only_without_sigv4a_auth_returns_403() {
1460 // Some legacy clients stamp the `X-Amz-Region-Set` header
1461 // before swapping the algorithm string. `detect` flags this as
1462 // SigV4a-shaped but we cannot verify without a parseable
1463 // Authorization → fail closed (SignatureDoesNotMatch).
1464 let signing = SigningKey::random(&mut OsRng);
1465 let vk = p256::ecdsa::VerifyingKey::from(&signing);
1466 let gate = make_gate_with("AKIAOK", vk);
1467 let r = req(
1468 Method::GET,
1469 "/bucket/key",
1470 &[
1471 // SigV4 algorithm + region-set header → detected, but
1472 // the Authorization is plain SigV4 so `parse_authorization_header`
1473 // returns None.
1474 (
1475 "authorization",
1476 "AWS4-HMAC-SHA256 Credential=AKIA/20260513/us-east-1/s3/aws4_request, \
1477 SignedHeaders=host, Signature=deadbeef",
1478 ),
1479 (REGION_SET_HEADER, "us-east-1"),
1480 ],
1481 );
1482 let result = try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", fixture_now())
1483 .expect("must intercept SigV4a-shaped request");
1484 let resp = result.expect_err("region-set without sigv4a auth must produce 403");
1485 assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1486 let body = body_to_bytes(resp).await;
1487 let body_str = String::from_utf8(body).expect("xml utf-8");
1488 assert!(
1489 body_str.contains("<Code>SignatureDoesNotMatch</Code>"),
1490 "missing/malformed Authorization for SigV4a-shaped request must fail closed: {body_str}"
1491 );
1492 }
1493
1494 /// v0.8.4 #76 (audit H-6): captured-request replay outside the
1495 /// 15-min window → 403 RequestTimeTooSkewed (not
1496 /// SignatureDoesNotMatch). This is the headline gate-level
1497 /// behaviour change; pre-#76 the same captured request would have
1498 /// reached the inner service, allowing destructive replay (DELETE
1499 /// included).
1500 #[tokio::test]
1501 async fn sigv4a_replay_outside_window_returns_403_request_time_too_skewed() {
1502 let (r, vk) = make_signed_request("AKIAOK", Method::GET, "/bucket/key", "us-east-1");
1503 let gate = make_gate_with("AKIAOK", vk);
1504 // Request stamped 20260513T120000Z; "now" is 30 min later → drift
1505 // 1800s, beyond the 900s default tolerance.
1506 let now = chrono::DateTime::parse_from_rfc3339("2026-05-13T12:30:00Z")
1507 .unwrap()
1508 .with_timezone(&chrono::Utc);
1509 let result = try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", now)
1510 .expect("must intercept SigV4a request");
1511 let resp = result.expect_err("replay outside window must reject");
1512 assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1513 let body = body_to_bytes(resp).await;
1514 let body_str = String::from_utf8(body).expect("xml utf-8");
1515 assert!(
1516 body_str.contains("<Code>RequestTimeTooSkewed</Code>"),
1517 "replay outside window must surface RequestTimeTooSkewed: {body_str}"
1518 );
1519 }
1520
1521 /// Cover the canonical-request builder directly: empty query
1522 /// string, sorted multi-pair query, and header value collapsed
1523 /// whitespace all hit the right code paths.
1524 #[test]
1525 fn canonical_request_bytes_format() {
1526 let r = req(
1527 Method::PUT,
1528 "/bucket/key?z=1&a=2",
1529 &[
1530 ("host", "s3.example.com"),
1531 ("x-amz-content-sha256", "UNSIGNED-PAYLOAD"),
1532 ("x-amz-date", " 20260513T120000Z "),
1533 ],
1534 );
1535 let signed: Vec<String> = ["host", "x-amz-content-sha256", "x-amz-date"]
1536 .iter()
1537 .map(|s| (*s).into())
1538 .collect();
1539 let bytes =
1540 build_canonical_request_bytes(&r, &signed).expect("canonical request bytes must build");
1541 let s = std::str::from_utf8(&bytes).expect("utf-8");
1542 let expected = "PUT\n\
1543 /bucket/key\n\
1544 a=2&z=1\n\
1545 host:s3.example.com\n\
1546 x-amz-content-sha256:UNSIGNED-PAYLOAD\n\
1547 x-amz-date:20260513T120000Z\n\
1548 \n\
1549 host;x-amz-content-sha256;x-amz-date\n\
1550 UNSIGNED-PAYLOAD";
1551 assert_eq!(s, expected, "canonical request bytes mismatch:\n{s}");
1552 }
1553
1554 /// v0.8.5 #84 H-4: duplicate `x-amz-date` headers must be rejected
1555 /// at canonical-request build time (not silently coalesced to the
1556 /// first value). HTTP/1.1 spec already forbids duplicates of
1557 /// `host` / `x-amz-date`; AWS SDKs never emit them; so any
1558 /// duplicate must be malicious or broken — single-value reject is
1559 /// the safe choice (see [`build_canonical_request_bytes`] doc).
1560 #[test]
1561 fn sigv4a_duplicate_x_amz_date_rejected() {
1562 // Two x-amz-date headers — first one matches the signature the
1563 // gate expects, second one is what a downstream parser might
1564 // pick up. This is the textbook auth-confusion vector.
1565 let r = Request::builder()
1566 .method(Method::GET)
1567 .uri("/b/k")
1568 .header("host", "s3.example.com")
1569 .header("x-amz-content-sha256", "UNSIGNED-PAYLOAD")
1570 .header("x-amz-date", "20260513T120000Z")
1571 .header("x-amz-date", "20260513T130000Z")
1572 .body(())
1573 .expect("dup-header request");
1574 let signed: Vec<String> = ["host", "x-amz-content-sha256", "x-amz-date"]
1575 .iter()
1576 .map(|s| (*s).into())
1577 .collect();
1578 let err = build_canonical_request_bytes(&r, &signed)
1579 .expect_err("duplicate x-amz-date must reject");
1580 match err {
1581 crate::sigv4a::SigV4aError::DuplicateSignedHeader { header } => {
1582 assert_eq!(header, "x-amz-date");
1583 }
1584 other => panic!("expected DuplicateSignedHeader, got {other:?}"),
1585 }
1586 }
1587
1588 /// v0.8.5 #84 H-4: counterpart to the duplicate-reject test —
1589 /// single-occurrence headers on the same path stay accepted.
1590 /// Guards against a regression where the duplicate-detect logic
1591 /// is over-eager and trips on a normally-formed request.
1592 #[test]
1593 fn sigv4a_canonicalization_single_header_passes() {
1594 let r = req(
1595 Method::GET,
1596 "/b/k",
1597 &[
1598 ("host", "s3.example.com"),
1599 ("x-amz-content-sha256", "UNSIGNED-PAYLOAD"),
1600 ("x-amz-date", "20260513T120000Z"),
1601 ],
1602 );
1603 let signed: Vec<String> = ["host", "x-amz-content-sha256", "x-amz-date"]
1604 .iter()
1605 .map(|s| (*s).into())
1606 .collect();
1607 let bytes =
1608 build_canonical_request_bytes(&r, &signed).expect("single-occurrence must accept");
1609 // Body content not asserted in detail (covered by
1610 // canonical_request_bytes_format); just confirm the bytes
1611 // parse as utf-8 and contain the date verbatim.
1612 let s = std::str::from_utf8(&bytes).expect("utf-8");
1613 assert!(
1614 s.contains("x-amz-date:20260513T120000Z"),
1615 "canonical bytes must echo the single x-amz-date verbatim:\n{s}"
1616 );
1617 }
1618
1619 /// v0.8.5 #84 H-4: end-to-end through the
1620 /// [`try_sigv4a_verify_at`] gate — duplicate `x-amz-date` on a
1621 /// SigV4a-shaped request must surface 403 SignatureDoesNotMatch
1622 /// (not silently authenticate against the first value).
1623 #[tokio::test]
1624 async fn sigv4a_pre_route_rejects_duplicate_signed_header() {
1625 let signing = SigningKey::random(&mut OsRng);
1626 let vk = p256::ecdsa::VerifyingKey::from(&signing);
1627 let gate = make_gate_with("AKIAOK", vk);
1628 // Authorization header lists x-amz-date in SignedHeaders —
1629 // signature value itself can be garbage; the duplicate-detect
1630 // path runs strictly before any ECDSA math.
1631 let auth = build_auth_header(
1632 "AKIAOK",
1633 &[
1634 "host",
1635 "x-amz-content-sha256",
1636 "x-amz-date",
1637 REGION_SET_HEADER,
1638 ],
1639 "deadbeef",
1640 );
1641 let r = Request::builder()
1642 .method(Method::GET)
1643 .uri("/bucket/key")
1644 .header("host", "s3.example.com")
1645 .header(
1646 "x-amz-content-sha256",
1647 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
1648 )
1649 .header("x-amz-date", "20260513T120000Z")
1650 .header("x-amz-date", "20260513T130000Z")
1651 .header(REGION_SET_HEADER, "us-east-1")
1652 .header("authorization", auth)
1653 .body(())
1654 .expect("dup-header sigv4a request");
1655 let result = try_sigv4a_verify_at(&r, Some(&gate), "us-east-1", fixture_now())
1656 .expect("must intercept SigV4a request");
1657 let resp = result.expect_err("duplicate signed header must reject at the gate");
1658 assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1659 let body = body_to_bytes(resp).await;
1660 let body_str = String::from_utf8(body).expect("xml utf-8");
1661 assert!(
1662 body_str.contains("<Code>SignatureDoesNotMatch</Code>"),
1663 "duplicate signed header must surface SignatureDoesNotMatch: {body_str}"
1664 );
1665 assert!(
1666 body_str.contains("duplicate signed header"),
1667 "diagnostic must mention duplicate header: {body_str}"
1668 );
1669 }
1670}