Apply AWS Signature Version 4 signing to a raw HTTP request buffer. Strips existing AWS auth headers, computes a new signature using the `aws-sigv4` crate, and returns the rewritten request bytes including body.
(
raw: &[u8],
host: &str,
region: &str,
service: &str,
access_key: &str,
secret_key: &str,
session_token: Option<&str>,
)
| 253 | /// Strips existing AWS auth headers, computes a new signature using the |
| 254 | /// `aws-sigv4` crate, and returns the rewritten request bytes including body. |
| 255 | pub fn apply_sigv4_to_request( |
| 256 | raw: &[u8], |
| 257 | host: &str, |
| 258 | region: &str, |
| 259 | service: &str, |
| 260 | access_key: &str, |
| 261 | secret_key: &str, |
| 262 | session_token: Option<&str>, |
| 263 | ) -> Result<Vec<u8>> { |
| 264 | let header_end = raw |
| 265 | .windows(4) |
| 266 | .position(|w| w == b"\r\n\r\n") |
| 267 | .map_or(raw.len(), |p| p + 4); |
| 268 | |
| 269 | let body = if header_end < raw.len() { |
| 270 | &raw[header_end..] |
| 271 | } else { |
| 272 | &[] |
| 273 | }; |
| 274 | |
| 275 | let header_str = std::str::from_utf8(&raw[..header_end]) |
| 276 | .map_err(|e| miette!("SigV4 signing: request headers are not valid UTF-8: {e}"))?; |
| 277 | let parts = parse_request_parts(header_str); |
| 278 | let uri = format!("https://{host}{}", parts.path); |
| 279 | let identity = build_identity(access_key, secret_key, session_token); |
| 280 | let signing_params = build_signing_params(&identity, region, service)?; |
| 281 | |
| 282 | let signable_request = SignableRequest::new( |
| 283 | parts.method, |
| 284 | &uri, |
| 285 | parts |
| 286 | .headers_to_sign |
| 287 | .iter() |
| 288 | .map(|(k, v)| (k.as_str(), v.as_str())), |
| 289 | SignableBody::Bytes(body), |
| 290 | ) |
| 291 | .map_err(|e| miette!("SigV4 signable request: {e}"))?; |
| 292 | |
| 293 | let (instructions, _signature) = sign(signable_request, &signing_params) |
| 294 | .map_err(|e| miette!("SigV4 signing failed: {e}"))? |
| 295 | .into_parts(); |
| 296 | |
| 297 | Ok(rebuild_request(&parts, &instructions, body)) |
| 298 | } |
| 299 | |
| 300 | /// Apply AWS `SigV4` signing to HTTP headers only, using UNSIGNED-PAYLOAD. |
| 301 | /// |