1use axum::body::Body;
2use axum::extract::{ConnectInfo, Extension, Query};
3use axum::http::{Request, StatusCode};
4use axum::response::Response;
5use bytes::Bytes;
6use std::collections::HashMap;
7use std::net::SocketAddr;
8use std::sync::Arc;
9
10use crate::auth::{
11 is_root_bypass, ConditionContext, CredentialResolver, IamMode, IamPolicyEvaluator, Principal,
12 PrincipalType, ResourcePolicyProvider,
13};
14use crate::protocol::{self, AwsProtocol};
15use crate::registry::ServiceRegistry;
16use crate::service::{AwsRequest, ResponseBody};
17
18pub async fn dispatch(
20 ConnectInfo(remote_addr): ConnectInfo<SocketAddr>,
21 Extension(registry): Extension<Arc<ServiceRegistry>>,
22 Extension(config): Extension<Arc<DispatchConfig>>,
23 Query(query_params): Query<HashMap<String, String>>,
24 request: Request<Body>,
25) -> Response<Body> {
26 let remote_addr = Some(remote_addr);
27 let request_id = uuid::Uuid::new_v4().to_string();
28
29 let (parts, body) = request.into_parts();
30
31 let stream_route = streaming_route(
37 &parts.method,
38 parts.uri.path(),
39 &parts.headers,
40 &query_params,
41 );
42 let header_only = protocol::detect_service_headers_only(&parts.headers, &query_params);
43 let stream_dispatch = match (&stream_route, &header_only) {
44 (Some(sr), Some(detected)) if sr.0 == detected.service => Some(detected.clone()),
47 (Some((service, _)), None) if *service == "ecr" => Some(protocol::DetectedRequest {
53 service: "ecr".to_string(),
54 action: String::new(),
55 protocol: AwsProtocol::Rest,
56 }),
57 _ => None,
58 };
59
60 let (body_bytes, body_stream) = if stream_dispatch.is_some() {
61 (Bytes::new(), Some(body))
62 } else {
63 let max_body_bytes = max_request_body_bytes();
68 match axum::body::to_bytes(body, max_body_bytes).await {
69 Ok(b) => (b, None),
70 Err(_) => {
71 return build_error_response(
72 StatusCode::PAYLOAD_TOO_LARGE,
73 "RequestEntityTooLarge",
74 "Request body too large",
75 &request_id,
76 AwsProtocol::Query,
77 );
78 }
79 }
80 };
81
82 let detected = if let Some(d) = stream_dispatch {
84 d
85 } else {
86 match protocol::detect_service(&parts.headers, &query_params, &body_bytes) {
87 Some(d) => d,
88 None => {
89 if let Some(target) = parts
95 .headers
96 .get("x-amz-target")
97 .and_then(|v| v.to_str().ok())
98 {
99 return build_error_response(
100 StatusCode::BAD_REQUEST,
101 "UnknownOperationException",
102 &format!("The operation {target} is not recognized."),
103 &request_id,
104 AwsProtocol::Json,
105 );
106 }
107 if parts.method == http::Method::OPTIONS {
113 protocol::DetectedRequest {
114 service: "s3".to_string(),
115 action: String::new(),
116 protocol: AwsProtocol::Rest,
117 }
118 } else if parts.uri.path() == "/v2" || parts.uri.path().starts_with("/v2/") {
119 protocol::DetectedRequest {
123 service: "ecr".to_string(),
124 action: String::new(),
125 protocol: AwsProtocol::Rest,
126 }
127 } else if let Some(bucket) = anonymous_s3_bucket(&parts.uri, &config) {
128 tracing::debug!(bucket = %bucket, "routing unsigned request to S3 (existing bucket)");
135 protocol::DetectedRequest {
136 service: "s3".to_string(),
137 action: String::new(),
138 protocol: AwsProtocol::Rest,
139 }
140 } else if !parts.uri.path().starts_with("/_") {
141 protocol::DetectedRequest {
146 service: "apigateway".to_string(),
147 action: String::new(),
148 protocol: AwsProtocol::RestJson,
149 }
150 } else {
151 return build_error_response(
152 StatusCode::BAD_REQUEST,
153 "MissingAction",
154 "Could not determine target service or action from request",
155 &request_id,
156 AwsProtocol::Query,
157 );
158 }
159 }
160 }
161 };
162
163 let detected = if detected.service == "bedrock" {
167 let first_seg = parts.uri.path().split('/').nth(1);
168 if matches!(
169 first_seg,
170 Some(
171 "agents"
172 | "knowledgebases"
173 | "flows"
174 | "prompts"
175 | "tags"
176 | "retrieveAndGenerate"
177 | "retrieveAndGenerateStream"
178 | "optimize-prompt"
179 | "sessions"
180 | "invocations"
181 | "generate-query"
182 | "rerank"
183 )
184 ) {
185 let segs: Vec<&str> = parts.uri.path().split('/').collect();
187 let is_runtime = matches!(
188 segs.as_slice(),
189 ["", "agents", _, "agentAliases", _, ..] | ["", "flows", _, "aliases", _] | ["", "knowledgebases", _, "retrieve"] | ["", "retrieveAndGenerate"]
193 | ["", "retrieveAndGenerateStream"]
194 | ["", "optimize-prompt"]
195 | ["", "sessions", ..]
196 | ["", "invocations", ..]
197 | ["", "generate-query"]
198 | ["", "rerank"]
199 );
200 if is_runtime {
201 protocol::DetectedRequest {
202 service: "bedrock-agent-runtime".to_string(),
203 ..detected
204 }
205 } else {
206 protocol::DetectedRequest {
207 service: "bedrock-agent".to_string(),
208 ..detected
209 }
210 }
211 } else {
212 detected
213 }
214 } else {
215 detected
216 };
217
218 let detected = if detected.service == "rds" && user_agent_indicates_docdb(&parts.headers) {
227 protocol::DetectedRequest {
228 service: "docdb".to_string(),
229 ..detected
230 }
231 } else {
232 detected
233 };
234
235 let detected = if detected.service == "rds" && user_agent_indicates_neptune(&parts.headers) {
244 protocol::DetectedRequest {
245 service: "neptune".to_string(),
246 ..detected
247 }
248 } else {
249 detected
250 };
251
252 let service = match registry.get(&detected.service) {
254 Some(s) => s,
255 None => {
256 return build_error_response(
257 detected.protocol.error_status(),
258 "UnknownService",
259 &format!("Service '{}' is not available", detected.service),
260 &request_id,
261 detected.protocol,
262 );
263 }
264 };
265
266 let auth_header = parts
268 .headers
269 .get("authorization")
270 .and_then(|v| v.to_str().ok())
271 .unwrap_or("");
272 let header_info = fakecloud_aws::sigv4::parse_sigv4(auth_header);
273 let presigned_info = if header_info.is_none() {
274 fakecloud_aws::sigv4::parse_sigv4_presigned(&query_params).map(|p| p.as_info())
276 } else {
277 None
278 };
279 let sigv4_info = header_info.or(presigned_info);
280 let access_key_id = sigv4_info
286 .as_ref()
287 .map(|info| info.access_key.clone())
288 .or_else(|| sigv2_presigned_access_key(&query_params));
289
290 let host_info = protocol::parse_routing_host_from_headers(&parts.headers);
296
297 let region = sigv4_info
298 .map(|info| info.region)
299 .or_else(|| host_info.as_ref().map(|h| h.region.clone()))
300 .or_else(|| extract_region_from_user_agent(&parts.headers))
301 .unwrap_or_else(|| config.region.clone());
302
303 let caller_akid = access_key_id.as_deref().unwrap_or("");
309 let resolved = if !caller_akid.is_empty() && !is_root_bypass(caller_akid) {
310 config
311 .credential_resolver
312 .as_ref()
313 .and_then(|r| r.resolve(caller_akid))
314 } else {
315 None
316 };
317 let caller_principal = resolved.as_ref().map(|r| r.principal.clone());
318 let caller_session_policies = resolved
319 .as_ref()
320 .map(|r| r.session_policies.clone())
321 .unwrap_or_default();
322
323 if config.verify_sigv4 && !is_root_bypass(caller_akid) && config.credential_resolver.is_some() {
328 let amz_date = parts
329 .headers
330 .get("x-amz-date")
331 .and_then(|v| v.to_str().ok());
332 let parsed = fakecloud_aws::sigv4::parse_sigv4_header(auth_header, amz_date)
333 .or_else(|| fakecloud_aws::sigv4::parse_sigv4_presigned(&query_params));
334 let parsed = match parsed {
335 Some(p) => p,
336 None => {
337 return build_error_response(
338 StatusCode::FORBIDDEN,
339 "IncompleteSignature",
340 "Request is missing or has a malformed AWS Signature",
341 &request_id,
342 detected.protocol,
343 );
344 }
345 };
346 let resolved_for_verify = match resolved.as_ref() {
347 Some(r) => r,
348 None => {
349 return build_error_response(
350 StatusCode::FORBIDDEN,
351 "InvalidClientTokenId",
352 "The security token included in the request is invalid",
353 &request_id,
354 detected.protocol,
355 );
356 }
357 };
358 let headers_vec = fakecloud_aws::sigv4::headers_from_http(&parts.headers);
359 let raw_query_for_verify = parts.uri.query().unwrap_or("").to_string();
360 let verify_req = fakecloud_aws::sigv4::VerifyRequest {
361 method: parts.method.as_str(),
362 path: parts.uri.path(),
363 query: &raw_query_for_verify,
364 headers: &headers_vec,
365 body: &body_bytes,
366 };
367 match fakecloud_aws::sigv4::verify(
368 &parsed,
369 &verify_req,
370 &resolved_for_verify.secret_access_key,
371 chrono::Utc::now(),
372 ) {
373 Ok(()) => {}
374 Err(fakecloud_aws::sigv4::SigV4Error::RequestTimeTooSkewed { .. }) => {
375 return build_error_response(
376 StatusCode::FORBIDDEN,
377 "RequestTimeTooSkewed",
378 "The difference between the request time and the current time is too large",
379 &request_id,
380 detected.protocol,
381 );
382 }
383 Err(fakecloud_aws::sigv4::SigV4Error::InvalidDate(msg)) => {
384 return build_error_response(
385 StatusCode::FORBIDDEN,
386 "IncompleteSignature",
387 &format!("Invalid x-amz-date: {msg}"),
388 &request_id,
389 detected.protocol,
390 );
391 }
392 Err(fakecloud_aws::sigv4::SigV4Error::Malformed(msg)) => {
393 return build_error_response(
394 StatusCode::FORBIDDEN,
395 "IncompleteSignature",
396 &format!("Malformed SigV4 signature: {msg}"),
397 &request_id,
398 detected.protocol,
399 );
400 }
401 Err(fakecloud_aws::sigv4::SigV4Error::SignatureMismatch) => {
402 return build_error_response(
403 StatusCode::FORBIDDEN,
404 "SignatureDoesNotMatch",
405 "The request signature we calculated does not match the signature you provided",
406 &request_id,
407 detected.protocol,
408 );
409 }
410 Err(fakecloud_aws::sigv4::SigV4Error::PresignedUrlExpired { .. }) => {
411 return build_error_response(
412 StatusCode::FORBIDDEN,
413 "AccessDenied",
414 "Request has expired",
415 &request_id,
416 detected.protocol,
417 );
418 }
419 Err(fakecloud_aws::sigv4::SigV4Error::InvalidPresignExpires(_)) => {
420 return build_error_response(
421 StatusCode::BAD_REQUEST,
422 "AuthorizationQueryParametersError",
423 "X-Amz-Expires must be a number between 1 and 604800 seconds",
424 &request_id,
425 detected.protocol,
426 );
427 }
428 }
429 }
430
431 let wire_path = parts.uri.path();
436 let path = if detected.service == "s3" {
437 if let Some(bucket) = host_info.as_ref().and_then(|h| h.bucket.as_deref()) {
438 let prefix_with_slash = format!("/{bucket}/");
439 let is_bucket_root = wire_path.trim_end_matches('/') == format!("/{bucket}");
440 if wire_path.starts_with(&prefix_with_slash) || is_bucket_root {
441 wire_path.to_string()
442 } else if wire_path == "/" || wire_path.is_empty() {
443 format!("/{bucket}")
444 } else {
445 format!("/{bucket}{wire_path}")
446 }
447 } else {
448 wire_path.to_string()
449 }
450 } else {
451 wire_path.to_string()
452 };
453 let raw_query = parts.uri.query().unwrap_or("").to_string();
454 let path_segments: Vec<String> = path
455 .split('/')
456 .filter(|s| !s.is_empty())
457 .map(|s| s.to_string())
458 .collect();
459
460 if detected.protocol == AwsProtocol::Json
462 && !body_bytes.is_empty()
463 && serde_json::from_slice::<serde_json::Value>(&body_bytes).is_err()
464 {
465 return build_error_response(
466 StatusCode::BAD_REQUEST,
467 "SerializationException",
468 "Start of structure or map found where not expected",
469 &request_id,
470 AwsProtocol::Json,
471 );
472 }
473
474 let mut all_params = query_params;
476 if detected.protocol == AwsProtocol::Query {
477 let body_params = protocol::parse_query_body(&body_bytes);
478 for (k, v) in body_params {
479 all_params.entry(k).or_insert(v);
480 }
481 }
482
483 if detected.protocol == AwsProtocol::Json && detected.service == "monitoring" {
488 let body_params = protocol::flatten_json_to_query(&body_bytes);
489 for (k, v) in body_params {
490 all_params.entry(k).or_insert(v);
491 }
492 }
493
494 let aws_request = AwsRequest {
495 service: detected.service.clone(),
496 action: detected.action.clone(),
497 region,
498 account_id: caller_principal
499 .as_ref()
500 .map(|p| p.account_id.clone())
501 .unwrap_or_else(|| config.account_id.clone()),
502 request_id: request_id.clone(),
503 headers: parts.headers,
504 query_params: all_params,
505 body: body_bytes,
506 body_stream: parking_lot::Mutex::new(body_stream),
507 path_segments,
508 raw_path: path,
509 raw_query,
510 method: parts.method,
511 is_query_protocol: detected.protocol == AwsProtocol::Query,
512 access_key_id,
513 principal: caller_principal,
514 };
515
516 tracing::info!(
517 service = %aws_request.service,
518 action = %aws_request.action,
519 request_id = %aws_request.request_id,
520 "handling request"
521 );
522
523 if config.iam_mode.is_enabled()
530 && service.iam_enforceable()
531 && !is_root_bypass(aws_request.access_key_id.as_deref().unwrap_or(""))
532 {
533 if let Some(evaluator) = config.policy_evaluator.as_ref() {
534 if let Some(principal) = aws_request.principal.as_ref() {
535 if !principal.is_root() {
536 if let Some(iam_action) = service.iam_action_for(&aws_request) {
537 let mut condition_context = build_condition_context(
538 principal,
539 remote_addr,
540 &aws_request.region,
541 is_secure_transport(&aws_request.headers),
542 );
543 if let Some(rc) = resolved.as_ref() {
551 condition_context.aws_mfa_present = Some(rc.mfa_present);
552 condition_context.aws_token_issue_time = rc.token_issued_at;
553 condition_context.aws_federated_provider =
554 rc.federated_provider.clone();
555 if rc.mfa_present {
563 if let Some(issued) = rc.token_issued_at {
564 let age = chrono::Utc::now()
565 .signed_duration_since(issued)
566 .num_seconds()
567 .max(0);
568 condition_context.aws_mfa_age_seconds = Some(age);
569 }
570 }
571 }
572 condition_context.service_keys =
573 service.iam_condition_keys_for(&aws_request, &iam_action);
574
575 match service.resource_tags_for(&iam_action.resource) {
578 Some(tags) => condition_context.resource_tags = Some(tags),
579 None => tracing::debug!(
580 target: "fakecloud::iam::audit",
581 service = %detected.service,
582 resource = %iam_action.resource,
583 "service does not expose resource tags for ABAC; skipping aws:ResourceTag/* evaluation"
584 ),
585 }
586 match service.request_tags_from(&aws_request, iam_action.action) {
588 Some(tags) => condition_context.request_tags = Some(tags),
589 None => tracing::debug!(
590 target: "fakecloud::iam::audit",
591 service = %detected.service,
592 action = %iam_action.action_string(),
593 "service does not expose request tags for ABAC; skipping aws:RequestTag/* / aws:TagKeys evaluation"
594 ),
595 }
596 condition_context.principal_tags = principal.tags.clone();
598
599 let resource_policy_json =
608 config.resource_policy_provider.as_ref().and_then(|p| {
609 p.resource_policy(&detected.service, &iam_action.resource)
610 });
611 let resource_account_id = config
621 .resource_policy_provider
622 .as_ref()
623 .and_then(|p| {
624 p.resource_owner_account(&detected.service, &iam_action.resource)
625 })
626 .or_else(|| parse_account_from_arn(&iam_action.resource))
627 .unwrap_or_else(|| principal.account_id.clone());
628 let scps = config
635 .scp_resolver
636 .as_ref()
637 .and_then(|r| r.scps_for(principal));
638 let decision = evaluator.evaluate_with_resource_policy(
639 principal,
640 &iam_action,
641 &condition_context,
642 resource_policy_json.as_deref(),
643 &resource_account_id,
644 &caller_session_policies,
645 scps.as_deref(),
646 );
647 if !decision.is_allow() {
648 tracing::warn!(
649 target: "fakecloud::iam::audit",
650 service = %detected.service,
651 action = %iam_action.action_string(),
652 resource = %iam_action.resource,
653 principal = %principal.arn,
654 resource_policy_present = resource_policy_json.is_some(),
655 decision = ?decision,
656 mode = %config.iam_mode,
657 request_id = %request_id,
658 "IAM policy evaluation denied request"
659 );
660 if config.iam_mode.is_strict() {
661 let context_summary = serde_json::json!({
674 "aws:PrincipalArn": principal.arn,
675 "aws:PrincipalAccount": principal.account_id,
676 "aws:RequestedRegion": condition_context
677 .aws_requested_region
678 .clone()
679 .unwrap_or_default(),
680 "aws:SecureTransport": condition_context
681 .aws_secure_transport
682 .unwrap_or(false),
683 "aws:Action": iam_action.action_string(),
684 "aws:Resource": iam_action.resource,
685 "decision": format!("{:?}", decision),
686 });
687 let action_string = iam_action.action_string();
688 let encoded = crate::auth_message::encode_deny(
689 matches!(decision, crate::auth::IamDecision::ExplicitDeny),
690 Some(&action_string),
691 Some(&principal.arn),
692 Vec::new(),
693 Some(context_summary),
694 );
695 return build_error_response(
696 StatusCode::FORBIDDEN,
697 "AccessDeniedException",
698 &format!(
699 "User: {} is not authorized to perform: {} on resource: {} Encoded authorization failure message: {}",
700 principal.arn,
701 iam_action.action_string(),
702 iam_action.resource,
703 encoded,
704 ),
705 &request_id,
706 detected.protocol,
707 );
708 }
709 }
712 } else {
713 tracing::warn!(
725 target: "fakecloud::iam::audit",
726 service = %detected.service,
727 action = %aws_request.action,
728 mode = %config.iam_mode,
729 request_id = %request_id,
730 "service is iam_enforceable but has no IamAction mapping for this action; denying under strict, allowing under soft"
731 );
732 if config.iam_mode.is_strict() {
733 return build_error_response(
734 StatusCode::FORBIDDEN,
735 "AccessDeniedException",
736 &format!(
737 "User: {} is not authorized to perform: {}: no IAM action mapping exists for this operation, so it cannot be authorized under strict IAM enforcement",
738 principal.arn, aws_request.action,
739 ),
740 &request_id,
741 detected.protocol,
742 );
743 }
744 }
747 }
748 } else if aws_request.access_key_id.is_none() {
749 if let Some(iam_action) = service.iam_action_for(&aws_request) {
765 let now = chrono::Utc::now();
766 let mut condition_context = ConditionContext {
767 aws_source_ip: remote_addr.map(|sa| sa.ip()),
768 aws_current_time: Some(now),
769 aws_epoch_time: Some(now.timestamp()),
770 aws_secure_transport: Some(is_secure_transport(&aws_request.headers)),
771 aws_requested_region: Some(aws_request.region.clone()),
772 ..Default::default()
773 };
774 condition_context.service_keys =
775 service.iam_condition_keys_for(&aws_request, &iam_action);
776 let resource_policy_json = config
777 .resource_policy_provider
778 .as_ref()
779 .and_then(|p| p.resource_policy(&detected.service, &iam_action.resource));
780 let policy_decision = evaluator.evaluate_anonymous(
781 &iam_action,
782 &condition_context,
783 resource_policy_json.as_deref(),
784 );
785 let policy_allows = policy_decision.is_allow();
786 let policy_explicit_deny =
791 matches!(policy_decision, crate::auth::IamDecision::ExplicitDeny);
792 let acl_allows = !policy_explicit_deny
793 && config.resource_policy_provider.as_ref().is_some_and(|p| {
794 p.public_acl_allows(
795 &detected.service,
796 &iam_action.resource,
797 iam_action.action,
798 )
799 });
800 if !policy_allows && !acl_allows {
801 tracing::warn!(
802 target: "fakecloud::iam::audit",
803 service = %detected.service,
804 action = %iam_action.action_string(),
805 resource = %iam_action.resource,
806 resource_policy_present = resource_policy_json.is_some(),
807 mode = %config.iam_mode,
808 request_id = %request_id,
809 "anonymous request denied: no public bucket policy or ACL grants the action"
810 );
811 if config.iam_mode.is_strict() {
812 return build_error_response(
813 StatusCode::FORBIDDEN,
814 "AccessDenied",
815 "Access Denied",
816 &request_id,
817 detected.protocol,
818 );
819 }
820 }
822 }
823 }
824 }
825 }
826
827 match service.handle(aws_request).await {
828 Ok(resp) => {
829 let mut builder = Response::builder()
830 .status(resp.status)
831 .header("x-amzn-requestid", &request_id)
832 .header("x-amz-request-id", &request_id);
833
834 if !resp.content_type.is_empty() {
835 builder = builder.header("content-type", &resp.content_type);
836 }
837
838 let has_content_length = resp
839 .headers
840 .iter()
841 .any(|(k, _)| k.as_str().eq_ignore_ascii_case("content-length"));
842
843 for (k, v) in &resp.headers {
844 builder = builder.header(k, v);
845 }
846
847 match resp.body {
848 ResponseBody::Bytes(b) => builder.body(Body::from(b)).unwrap(),
849 ResponseBody::File { file, size } => {
850 let stream = tokio_util::io::ReaderStream::new(file);
851 let body = Body::from_stream(stream);
852 if !has_content_length {
853 builder = builder.header("content-length", size.to_string());
854 }
855 builder.body(body).unwrap()
856 }
857 }
858 }
859 Err(err) => {
860 tracing::warn!(
861 service = %detected.service,
862 action = %detected.action,
863 error = %err,
864 "request failed"
865 );
866 let error_headers = err.response_headers().to_vec();
867 let mut resp = build_error_response_with_fields(
868 err.status(),
869 err.code(),
870 &err.message(),
871 &request_id,
872 detected.protocol,
873 err.extra_fields(),
874 );
875 for (k, v) in &error_headers {
876 if let (Ok(name), Ok(val)) = (
877 k.parse::<http::header::HeaderName>(),
878 v.parse::<http::header::HeaderValue>(),
879 ) {
880 resp.headers_mut().insert(name, val);
881 }
882 }
883 resp
884 }
885 }
886}
887
888#[derive(Clone)]
890pub struct DispatchConfig {
891 pub region: String,
892 pub account_id: String,
893 pub verify_sigv4: bool,
897 pub iam_mode: IamMode,
902 pub credential_resolver: Option<Arc<dyn CredentialResolver>>,
906 pub policy_evaluator: Option<Arc<dyn IamPolicyEvaluator>>,
910 pub resource_policy_provider: Option<Arc<dyn ResourcePolicyProvider>>,
917 pub scp_resolver: Option<Arc<dyn crate::auth::ScpResolver>>,
924}
925
926impl std::fmt::Debug for DispatchConfig {
927 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
928 f.debug_struct("DispatchConfig")
929 .field("region", &self.region)
930 .field("account_id", &self.account_id)
931 .field("verify_sigv4", &self.verify_sigv4)
932 .field("iam_mode", &self.iam_mode)
933 .field(
934 "credential_resolver",
935 &self
936 .credential_resolver
937 .as_ref()
938 .map(|_| "<CredentialResolver>"),
939 )
940 .field(
941 "policy_evaluator",
942 &self
943 .policy_evaluator
944 .as_ref()
945 .map(|_| "<IamPolicyEvaluator>"),
946 )
947 .field(
948 "resource_policy_provider",
949 &self
950 .resource_policy_provider
951 .as_ref()
952 .map(|_| "<ResourcePolicyProvider>"),
953 )
954 .field(
955 "scp_resolver",
956 &self.scp_resolver.as_ref().map(|_| "<ScpResolver>"),
957 )
958 .finish()
959 }
960}
961
962impl DispatchConfig {
963 pub fn new(region: impl Into<String>, account_id: impl Into<String>) -> Self {
966 Self {
967 region: region.into(),
968 account_id: account_id.into(),
969 verify_sigv4: false,
970 iam_mode: IamMode::Off,
971 credential_resolver: None,
972 policy_evaluator: None,
973 resource_policy_provider: None,
974 scp_resolver: None,
975 }
976 }
977}
978
979fn streaming_route(
999 method: &http::Method,
1000 path: &str,
1001 headers: &http::HeaderMap,
1002 query_params: &HashMap<String, String>,
1003) -> Option<(&'static str, &'static str)> {
1004 if (method == http::Method::PATCH || method == http::Method::PUT)
1006 && path.starts_with("/v2/")
1007 && path.contains("/blobs/uploads/")
1008 {
1009 return Some(("ecr", ""));
1010 }
1011
1012 if method == http::Method::PUT {
1017 let after = path.trim_start_matches('/');
1018 let virtual_hosted_s3 = protocol::parse_routing_host_from_headers(headers)
1024 .filter(|h| h.service == "s3" && h.bucket.is_some())
1025 .is_some();
1026 if after.is_empty() || (!virtual_hosted_s3 && !after.contains('/')) {
1027 return None;
1028 }
1029 let header_s3 = headers
1030 .get("authorization")
1031 .and_then(|v| v.to_str().ok())
1032 .and_then(fakecloud_aws::sigv4::parse_sigv4)
1033 .map(|info| info.service == "s3")
1034 .unwrap_or(false);
1035 let presigned_v4_s3 = query_params
1036 .get("X-Amz-Credential")
1037 .and_then(|c| c.split('/').nth(3).map(|s| s.to_string()))
1038 .map(|service| service == "s3")
1039 .unwrap_or(false);
1040 let presigned_v2 = query_params.contains_key("AWSAccessKeyId")
1041 && query_params.contains_key("Signature")
1042 && query_params.contains_key("Expires");
1043 if header_s3 || presigned_v4_s3 || presigned_v2 {
1044 return Some(("s3", ""));
1045 }
1046 }
1047
1048 None
1049}
1050
1051const DEFAULT_MAX_REQUEST_BODY_BYTES: usize = 1024 * 1024 * 1024;
1061
1062pub fn max_request_body_bytes() -> usize {
1067 static CACHED: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1068 *CACHED.get_or_init(|| {
1069 std::env::var("FAKECLOUD_MAX_REQUEST_BODY_BYTES")
1070 .ok()
1071 .and_then(|s| s.parse::<usize>().ok())
1072 .filter(|&n| n > 0)
1073 .unwrap_or(DEFAULT_MAX_REQUEST_BODY_BYTES)
1074 })
1075}
1076
1077fn parse_account_from_arn(arn: &str) -> Option<String> {
1083 let mut parts = arn.splitn(6, ':');
1084 if parts.next()? != "arn" {
1085 return None;
1086 }
1087 let _partition = parts.next()?;
1088 let _service = parts.next()?;
1089 let _region = parts.next()?;
1090 let account = parts.next()?;
1091 parts.next()?;
1094 if account.is_empty() {
1095 None
1096 } else {
1097 Some(account.to_string())
1098 }
1099}
1100
1101fn user_agent_indicates_neptune(headers: &http::HeaderMap) -> bool {
1107 for name in ["user-agent", "x-amz-user-agent"] {
1108 if let Some(ua) = headers.get(name).and_then(|v| v.to_str().ok()) {
1109 for part in ua.split_whitespace() {
1110 if let Some(rest) = part.strip_prefix("api/neptune") {
1111 if rest.is_empty() || rest.starts_with('#') || rest.starts_with('/') {
1112 return true;
1113 }
1114 }
1115 }
1116 }
1117 }
1118 false
1119}
1120
1121fn user_agent_indicates_docdb(headers: &http::HeaderMap) -> bool {
1128 for name in ["user-agent", "x-amz-user-agent"] {
1129 if let Some(ua) = headers.get(name).and_then(|v| v.to_str().ok()) {
1130 for part in ua.split_whitespace() {
1131 if let Some(rest) = part.strip_prefix("api/docdb") {
1132 if rest.is_empty() || rest.starts_with('#') || rest.starts_with('/') {
1133 return true;
1134 }
1135 }
1136 }
1137 }
1138 }
1139 false
1140}
1141
1142fn extract_region_from_user_agent(headers: &http::HeaderMap) -> Option<String> {
1143 let ua = headers.get("user-agent")?.to_str().ok()?;
1144 for part in ua.split_whitespace() {
1145 if let Some(region) = part.strip_prefix("region/") {
1146 if !region.is_empty() {
1147 return Some(region.to_string());
1148 }
1149 }
1150 }
1151 None
1152}
1153
1154fn build_error_response(
1155 status: StatusCode,
1156 code: &str,
1157 message: &str,
1158 request_id: &str,
1159 protocol: AwsProtocol,
1160) -> Response<Body> {
1161 build_error_response_with_fields(status, code, message, request_id, protocol, &[])
1162}
1163
1164fn build_error_response_with_fields(
1165 status: StatusCode,
1166 code: &str,
1167 message: &str,
1168 request_id: &str,
1169 protocol: AwsProtocol,
1170 extra_fields: &[(String, String)],
1171) -> Response<Body> {
1172 let (status, content_type, body) = match protocol {
1173 AwsProtocol::Query => {
1174 fakecloud_aws::error::xml_error_response(status, code, message, request_id)
1175 }
1176 AwsProtocol::Rest => fakecloud_aws::error::s3_xml_error_response_with_fields(
1177 status,
1178 code,
1179 message,
1180 request_id,
1181 extra_fields,
1182 ),
1183 AwsProtocol::Json | AwsProtocol::RestJson => {
1184 fakecloud_aws::error::json_error_response_with_fields(
1185 status,
1186 code,
1187 message,
1188 extra_fields,
1189 )
1190 }
1191 };
1192
1193 let safe_code = sanitize_header_value(code);
1203 let safe_message = sanitize_header_value(message);
1204 let mut builder = Response::builder()
1205 .status(status)
1206 .header("content-type", content_type)
1207 .header("x-amzn-requestid", request_id)
1208 .header("x-amz-request-id", request_id);
1209 if let Ok(v) = http::HeaderValue::from_str(&safe_code) {
1210 builder = builder.header("x-amz-error-code", v);
1211 }
1212 if let Ok(v) = http::HeaderValue::from_str(&safe_message) {
1213 builder = builder.header("x-amz-error-message", v);
1214 }
1215 builder.body(Body::from(body)).unwrap_or_else(|_| {
1216 Response::new(Body::empty())
1220 })
1221}
1222
1223fn sanitize_header_value(s: &str) -> String {
1228 const MAX_LEN: usize = 1024;
1229 let mut out = String::with_capacity(s.len().min(MAX_LEN));
1230 for ch in s.chars() {
1231 if out.len() >= MAX_LEN {
1232 break;
1233 }
1234 if ch.is_control() {
1237 if !out.ends_with(' ') {
1238 out.push(' ');
1239 }
1240 } else {
1241 out.push(ch);
1242 }
1243 }
1244 out.trim().to_string()
1245}
1246
1247fn sigv2_presigned_access_key(query_params: &HashMap<String, String>) -> Option<String> {
1267 if query_params.contains_key("Signature") && query_params.contains_key("Expires") {
1268 query_params.get("AWSAccessKeyId").cloned()
1269 } else {
1270 None
1271 }
1272}
1273
1274fn anonymous_s3_bucket(uri: &http::Uri, config: &DispatchConfig) -> Option<String> {
1275 let provider = config.resource_policy_provider.as_ref()?;
1276 let segment = uri.path().split('/').find(|s| !s.is_empty())?.to_string();
1277 let arn = format!("arn:aws:s3:::{segment}");
1278 provider.resource_owner_account("s3", &arn).map(|_| segment)
1279}
1280
1281fn build_condition_context(
1282 principal: &Principal,
1283 remote_addr: Option<SocketAddr>,
1284 region: &str,
1285 secure_transport: bool,
1286) -> ConditionContext {
1287 let now = chrono::Utc::now();
1288 ConditionContext {
1289 aws_username: aws_username_from_principal(principal),
1290 aws_userid: Some(principal.user_id.clone()),
1291 aws_principal_arn: Some(principal.arn.clone()),
1292 aws_principal_account: Some(principal.account_id.clone()),
1293 aws_principal_type: Some(principal_type_label(principal.principal_type).to_string()),
1294 aws_source_ip: remote_addr.map(|sa| sa.ip()),
1295 aws_current_time: Some(now),
1296 aws_epoch_time: Some(now.timestamp()),
1297 aws_secure_transport: Some(secure_transport),
1298 aws_requested_region: Some(region.to_string()),
1299 aws_mfa_present: None,
1305 aws_mfa_age_seconds: None,
1306 aws_called_via: Vec::new(),
1307 aws_source_vpce: None,
1308 aws_source_vpc: None,
1309 aws_vpc_source_ip: None,
1310 aws_federated_provider: None,
1311 aws_token_issue_time: None,
1312 service_keys: Default::default(),
1313 resource_tags: None,
1314 request_tags: None,
1315 principal_tags: None,
1316 }
1317}
1318
1319fn aws_username_from_principal(principal: &Principal) -> Option<String> {
1323 if principal.principal_type != PrincipalType::User {
1324 return None;
1325 }
1326 let after = principal.arn.rsplit_once(":user/").map(|(_, s)| s)?;
1327 Some(after.rsplit('/').next().unwrap_or(after).to_string())
1329}
1330
1331fn principal_type_label(t: PrincipalType) -> &'static str {
1334 match t {
1335 PrincipalType::User => "User",
1336 PrincipalType::AssumedRole => "AssumedRole",
1337 PrincipalType::FederatedUser => "FederatedUser",
1338 PrincipalType::Root => "Account",
1339 PrincipalType::Unknown => "Unknown",
1340 }
1341}
1342
1343fn is_secure_transport(headers: &http::HeaderMap) -> bool {
1349 headers
1350 .get("x-forwarded-proto")
1351 .and_then(|v| v.to_str().ok())
1352 .map(|s| s.eq_ignore_ascii_case("https"))
1353 .unwrap_or(false)
1354}
1355
1356trait ProtocolExt {
1357 fn error_status(&self) -> StatusCode;
1358}
1359
1360impl ProtocolExt for AwsProtocol {
1361 fn error_status(&self) -> StatusCode {
1362 StatusCode::BAD_REQUEST
1363 }
1364}
1365
1366#[cfg(test)]
1367mod tests {
1368 use super::*;
1369
1370 #[test]
1371 fn default_max_request_body_bytes_is_one_gib() {
1372 assert_eq!(DEFAULT_MAX_REQUEST_BODY_BYTES, 1024 * 1024 * 1024);
1376 }
1377
1378 #[test]
1379 fn sigv2_presigned_access_key_extracted_with_signature_and_expires() {
1380 let mut q = HashMap::new();
1381 q.insert("AWSAccessKeyId".to_string(), "AKIAEXAMPLE".to_string());
1382 q.insert("Signature".to_string(), "abc%2Bdef".to_string());
1383 q.insert("Expires".to_string(), "1700000000".to_string());
1384 assert_eq!(
1385 sigv2_presigned_access_key(&q).as_deref(),
1386 Some("AKIAEXAMPLE")
1387 );
1388 }
1389
1390 #[test]
1391 fn sigv2_presigned_access_key_none_without_signature_or_expires() {
1392 let mut q = HashMap::new();
1395 q.insert("AWSAccessKeyId".to_string(), "AKIAEXAMPLE".to_string());
1396 assert_eq!(sigv2_presigned_access_key(&q), None);
1397
1398 q.insert("Expires".to_string(), "1700000000".to_string());
1399 assert_eq!(
1400 sigv2_presigned_access_key(&q),
1401 None,
1402 "missing Signature must not qualify"
1403 );
1404 }
1405
1406 #[test]
1407 fn sigv2_presigned_access_key_none_for_unsigned_request() {
1408 assert_eq!(sigv2_presigned_access_key(&HashMap::new()), None);
1409 }
1410
1411 #[test]
1412 fn dispatch_config_new_defaults_to_off() {
1413 let cfg = DispatchConfig::new("us-east-1", "123456789012");
1414 assert_eq!(cfg.region, "us-east-1");
1415 assert_eq!(cfg.account_id, "123456789012");
1416 assert!(!cfg.verify_sigv4);
1417 assert_eq!(cfg.iam_mode, IamMode::Off);
1418 }
1419
1420 #[test]
1421 fn aws_username_strips_iam_path_for_users() {
1422 let p = Principal {
1423 arn: "arn:aws:iam::123456789012:user/engineering/alice".into(),
1424 user_id: "AIDAALICE".into(),
1425 account_id: "123456789012".into(),
1426 principal_type: PrincipalType::User,
1427 source_identity: None,
1428 tags: None,
1429 };
1430 assert_eq!(aws_username_from_principal(&p), Some("alice".into()));
1431 }
1432
1433 #[test]
1434 fn aws_username_unset_for_assumed_role() {
1435 let p = Principal {
1436 arn: "arn:aws:sts::123456789012:assumed-role/ops/session".into(),
1437 user_id: "AROAOPS:session".into(),
1438 account_id: "123456789012".into(),
1439 principal_type: PrincipalType::AssumedRole,
1440 source_identity: None,
1441 tags: None,
1442 };
1443 assert_eq!(aws_username_from_principal(&p), None);
1444 }
1445
1446 #[test]
1447 fn principal_type_label_matches_aws_casing() {
1448 assert_eq!(principal_type_label(PrincipalType::User), "User");
1449 assert_eq!(
1450 principal_type_label(PrincipalType::AssumedRole),
1451 "AssumedRole"
1452 );
1453 assert_eq!(principal_type_label(PrincipalType::Root), "Account");
1454 }
1455
1456 #[test]
1457 fn build_condition_context_populates_global_keys() {
1458 let p = Principal {
1459 arn: "arn:aws:iam::123456789012:user/alice".into(),
1460 user_id: "AIDAALICE".into(),
1461 account_id: "123456789012".into(),
1462 principal_type: PrincipalType::User,
1463 source_identity: None,
1464 tags: None,
1465 };
1466 let addr: SocketAddr = "10.0.0.1:54321".parse().unwrap();
1467 let ctx = build_condition_context(&p, Some(addr), "us-east-1", false);
1468 assert_eq!(ctx.aws_username.as_deref(), Some("alice"));
1469 assert_eq!(ctx.aws_userid.as_deref(), Some("AIDAALICE"));
1470 assert_eq!(
1471 ctx.aws_principal_arn.as_deref(),
1472 Some("arn:aws:iam::123456789012:user/alice")
1473 );
1474 assert_eq!(ctx.aws_principal_account.as_deref(), Some("123456789012"));
1475 assert_eq!(ctx.aws_principal_type.as_deref(), Some("User"));
1476 assert_eq!(
1477 ctx.aws_source_ip.map(|i| i.to_string()).as_deref(),
1478 Some("10.0.0.1")
1479 );
1480 assert_eq!(ctx.aws_requested_region.as_deref(), Some("us-east-1"));
1481 assert_eq!(ctx.aws_secure_transport, Some(false));
1482 assert!(ctx.aws_current_time.is_some());
1483 assert!(ctx.aws_epoch_time.is_some());
1484 }
1485
1486 #[test]
1487 fn is_secure_transport_reads_x_forwarded_proto() {
1488 let mut headers = http::HeaderMap::new();
1489 headers.insert("x-forwarded-proto", "https".parse().unwrap());
1490 assert!(is_secure_transport(&headers));
1491 headers.insert("x-forwarded-proto", "http".parse().unwrap());
1492 assert!(!is_secure_transport(&headers));
1493 let empty = http::HeaderMap::new();
1494 assert!(!is_secure_transport(&empty));
1495 }
1496
1497 #[test]
1498 fn parse_account_from_arn_extracts_standard_shapes() {
1499 assert_eq!(
1500 parse_account_from_arn("arn:aws:sqs:us-east-1:123456789012:queue"),
1501 Some("123456789012".to_string())
1502 );
1503 assert_eq!(
1504 parse_account_from_arn("arn:aws:iam::123456789012:user/alice"),
1505 Some("123456789012".to_string())
1506 );
1507 }
1508
1509 #[test]
1510 fn parse_account_from_arn_returns_none_for_s3_empty_account() {
1511 assert_eq!(parse_account_from_arn("arn:aws:s3:::my-bucket"), None);
1513 assert_eq!(
1514 parse_account_from_arn("arn:aws:s3:::my-bucket/path/to/key"),
1515 None
1516 );
1517 }
1518
1519 #[test]
1520 fn parse_account_from_arn_returns_none_for_malformed() {
1521 assert_eq!(parse_account_from_arn(""), None);
1522 assert_eq!(parse_account_from_arn("not-an-arn"), None);
1523 assert_eq!(parse_account_from_arn("arn:aws:sqs:us-east-1"), None);
1524 assert_eq!(parse_account_from_arn("arn:aws:sqs"), None);
1525 }
1526
1527 #[test]
1528 fn extract_region_from_user_agent_finds_region_segment() {
1529 let mut headers = http::HeaderMap::new();
1530 headers.insert(
1531 "user-agent",
1532 "aws-sdk-rust/1.0 os/linux region/eu-central-1"
1533 .parse()
1534 .unwrap(),
1535 );
1536 assert_eq!(
1537 extract_region_from_user_agent(&headers),
1538 Some("eu-central-1".to_string())
1539 );
1540 }
1541
1542 #[test]
1543 fn extract_region_from_user_agent_none_without_header() {
1544 let headers = http::HeaderMap::new();
1545 assert_eq!(extract_region_from_user_agent(&headers), None);
1546 }
1547
1548 #[test]
1549 fn extract_region_from_user_agent_ignores_empty_region() {
1550 let mut headers = http::HeaderMap::new();
1551 headers.insert("user-agent", "aws-sdk-java region/".parse().unwrap());
1552 assert_eq!(extract_region_from_user_agent(&headers), None);
1553 }
1554
1555 #[test]
1556 fn extract_region_from_user_agent_none_when_no_region_marker() {
1557 let mut headers = http::HeaderMap::new();
1558 headers.insert("user-agent", "curl/7.79.1".parse().unwrap());
1559 assert_eq!(extract_region_from_user_agent(&headers), None);
1560 }
1561
1562 #[test]
1563 fn aws_username_none_for_root() {
1564 let p = Principal {
1565 arn: "arn:aws:iam::123456789012:root".into(),
1566 user_id: "123456789012".into(),
1567 account_id: "123456789012".into(),
1568 principal_type: PrincipalType::Root,
1569 source_identity: None,
1570 tags: None,
1571 };
1572 assert_eq!(aws_username_from_principal(&p), None);
1573 }
1574
1575 #[test]
1576 fn aws_username_bare_no_path() {
1577 let p = Principal {
1578 arn: "arn:aws:iam::123456789012:user/bob".into(),
1579 user_id: "AIDABOB".into(),
1580 account_id: "123456789012".into(),
1581 principal_type: PrincipalType::User,
1582 source_identity: None,
1583 tags: None,
1584 };
1585 assert_eq!(aws_username_from_principal(&p), Some("bob".into()));
1586 }
1587
1588 #[test]
1589 fn principal_type_label_covers_federated_and_unknown() {
1590 assert_eq!(
1591 principal_type_label(PrincipalType::FederatedUser),
1592 "FederatedUser"
1593 );
1594 assert_eq!(principal_type_label(PrincipalType::Unknown), "Unknown");
1595 }
1596
1597 #[test]
1598 fn build_condition_context_marks_secure_when_flag_set() {
1599 let p = Principal {
1600 arn: "arn:aws:iam::123456789012:user/alice".into(),
1601 user_id: "AIDAALICE".into(),
1602 account_id: "123456789012".into(),
1603 principal_type: PrincipalType::User,
1604 source_identity: None,
1605 tags: None,
1606 };
1607 let ctx = build_condition_context(&p, None, "us-west-2", true);
1608 assert_eq!(ctx.aws_secure_transport, Some(true));
1609 assert!(ctx.aws_source_ip.is_none());
1610 assert_eq!(ctx.aws_requested_region.as_deref(), Some("us-west-2"));
1611 }
1612
1613 #[test]
1614 fn is_secure_transport_case_insensitive() {
1615 let mut headers = http::HeaderMap::new();
1616 headers.insert("x-forwarded-proto", "HTTPS".parse().unwrap());
1617 assert!(is_secure_transport(&headers));
1618 }
1619
1620 #[test]
1621 fn is_secure_transport_non_ascii_bytes_false() {
1622 let mut headers = http::HeaderMap::new();
1623 headers.insert(
1624 "x-forwarded-proto",
1625 http::HeaderValue::from_bytes(&[0xFF, 0xFE]).unwrap(),
1626 );
1627 assert!(!is_secure_transport(&headers));
1628 }
1629
1630 #[test]
1631 fn protocol_ext_error_status_is_bad_request() {
1632 assert_eq!(AwsProtocol::Query.error_status(), StatusCode::BAD_REQUEST);
1633 assert_eq!(AwsProtocol::Json.error_status(), StatusCode::BAD_REQUEST);
1634 assert_eq!(AwsProtocol::Rest.error_status(), StatusCode::BAD_REQUEST);
1635 assert_eq!(
1636 AwsProtocol::RestJson.error_status(),
1637 StatusCode::BAD_REQUEST
1638 );
1639 }
1640
1641 #[test]
1642 fn build_error_response_json_has_json_content_type() {
1643 let resp = build_error_response(
1644 StatusCode::BAD_REQUEST,
1645 "TestCode",
1646 "test msg",
1647 "req-1",
1648 AwsProtocol::Json,
1649 );
1650 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1651 let ct = resp
1652 .headers()
1653 .get("content-type")
1654 .unwrap()
1655 .to_str()
1656 .unwrap();
1657 assert!(ct.contains("json"));
1658 let rid = resp
1659 .headers()
1660 .get("x-amzn-requestid")
1661 .unwrap()
1662 .to_str()
1663 .unwrap();
1664 assert_eq!(rid, "req-1");
1665 }
1666
1667 #[test]
1668 fn build_error_response_rest_returns_xml_content_type() {
1669 let resp = build_error_response(
1670 StatusCode::NOT_FOUND,
1671 "NoSuchBucket",
1672 "bucket missing",
1673 "req-2",
1674 AwsProtocol::Rest,
1675 );
1676 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1677 let ct = resp
1678 .headers()
1679 .get("content-type")
1680 .unwrap()
1681 .to_str()
1682 .unwrap();
1683 assert!(ct.contains("xml"));
1684 }
1685
1686 #[test]
1687 fn build_error_response_query_returns_xml() {
1688 let resp = build_error_response(
1689 StatusCode::BAD_REQUEST,
1690 "InvalidParameter",
1691 "bad param",
1692 "req-3",
1693 AwsProtocol::Query,
1694 );
1695 let ct = resp
1696 .headers()
1697 .get("content-type")
1698 .unwrap()
1699 .to_str()
1700 .unwrap();
1701 assert!(ct.contains("xml"));
1702 }
1703
1704 #[test]
1709 fn build_error_response_with_multiline_message_does_not_panic() {
1710 let resp = build_error_response(
1711 StatusCode::INTERNAL_SERVER_ERROR,
1712 "ServiceException",
1713 "Lambda execution failed: container failed to start: docker start failed: \
1714 Error: unable to start container \"abc\": \
1715 failed to create new hosts file:\nhost-gateway is empty\n",
1716 "req-multi",
1717 AwsProtocol::Json,
1718 );
1719 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1720 let msg = resp
1721 .headers()
1722 .get("x-amz-error-message")
1723 .expect("x-amz-error-message must be set even when input contains newlines")
1724 .to_str()
1725 .unwrap();
1726 assert!(!msg.contains('\n'));
1727 assert!(!msg.contains('\r'));
1728 assert!(msg.contains("Lambda execution failed"));
1729 assert!(msg.contains("host-gateway is empty"));
1730 }
1731
1732 #[test]
1733 fn build_error_response_with_control_chars_strips_them() {
1734 let resp = build_error_response(
1735 StatusCode::BAD_REQUEST,
1736 "Code\twith\ttabs",
1737 "msg\x00with\x01nulls",
1738 "req-ctrl",
1739 AwsProtocol::Json,
1740 );
1741 let code = resp
1742 .headers()
1743 .get("x-amz-error-code")
1744 .unwrap()
1745 .to_str()
1746 .unwrap();
1747 let msg = resp
1748 .headers()
1749 .get("x-amz-error-message")
1750 .unwrap()
1751 .to_str()
1752 .unwrap();
1753 assert!(!code.contains('\t'));
1754 assert!(!msg.contains('\x00'));
1755 assert!(!msg.contains('\x01'));
1756 }
1757
1758 #[test]
1759 fn sanitize_header_value_truncates_long_input() {
1760 let huge = "x".repeat(5_000);
1761 let out = sanitize_header_value(&huge);
1762 assert!(out.len() <= 1024);
1763 }
1764
1765 #[test]
1766 fn sanitize_header_value_collapses_consecutive_control_runs() {
1767 let out = sanitize_header_value("a\n\n\n\rb");
1768 assert_eq!(out, "a b");
1769 }
1770
1771 #[test]
1772 fn dispatch_config_carries_opt_in_flags() {
1773 let cfg = DispatchConfig {
1774 region: "eu-west-1".to_string(),
1775 account_id: "000000000000".to_string(),
1776 verify_sigv4: true,
1777 iam_mode: IamMode::Strict,
1778 credential_resolver: None,
1779 policy_evaluator: None,
1780 resource_policy_provider: None,
1781 scp_resolver: None,
1782 };
1783 assert!(cfg.verify_sigv4);
1784 assert!(cfg.iam_mode.is_strict());
1785 assert!(cfg.resource_policy_provider.is_none());
1786 assert!(cfg.scp_resolver.is_none());
1787 }
1788
1789 fn s3_sigv4_headers() -> http::HeaderMap {
1790 let mut headers = http::HeaderMap::new();
1791 headers.insert(
1792 "authorization",
1793 "AWS4-HMAC-SHA256 Credential=test/20240101/us-east-1/s3/aws4_request, \
1794 SignedHeaders=host, Signature=fake"
1795 .parse()
1796 .unwrap(),
1797 );
1798 headers
1799 }
1800
1801 #[test]
1802 fn streaming_route_path_style_s3_put_object() {
1803 let headers = s3_sigv4_headers();
1804 assert_eq!(
1805 streaming_route(
1806 &http::Method::PUT,
1807 "/my-bucket/key.txt",
1808 &headers,
1809 &HashMap::new(),
1810 ),
1811 Some(("s3", "")),
1812 );
1813 }
1814
1815 #[test]
1816 fn streaming_route_path_style_create_bucket_skipped() {
1817 let headers = s3_sigv4_headers();
1820 assert_eq!(
1821 streaming_route(&http::Method::PUT, "/my-bucket", &headers, &HashMap::new(),),
1822 None,
1823 );
1824 }
1825
1826 #[test]
1827 fn streaming_route_virtual_hosted_s3_put_object() {
1828 let mut headers = s3_sigv4_headers();
1829 headers.insert(
1830 "host",
1831 "vhost-bucket.s3.us-east-1.localhost.localstack.cloud:4566"
1832 .parse()
1833 .unwrap(),
1834 );
1835 assert_eq!(
1840 streaming_route(&http::Method::PUT, "/hello.txt", &headers, &HashMap::new(),),
1841 Some(("s3", "")),
1842 );
1843 }
1844
1845 #[test]
1846 fn streaming_route_virtual_hosted_s3_root_skipped() {
1847 let mut headers = s3_sigv4_headers();
1850 headers.insert(
1851 "host",
1852 "vhost-bucket.s3.us-east-1.localhost.localstack.cloud:4566"
1853 .parse()
1854 .unwrap(),
1855 );
1856 assert_eq!(
1857 streaming_route(&http::Method::PUT, "/", &headers, &HashMap::new()),
1858 None,
1859 );
1860 }
1861
1862 #[test]
1863 fn streaming_route_ecr_blob_upload() {
1864 let headers = http::HeaderMap::new();
1865 assert_eq!(
1866 streaming_route(
1867 &http::Method::PATCH,
1868 "/v2/my-repo/blobs/uploads/abcd1234",
1869 &headers,
1870 &HashMap::new(),
1871 ),
1872 Some(("ecr", "")),
1873 );
1874 assert_eq!(
1875 streaming_route(
1876 &http::Method::PUT,
1877 "/v2/my-repo/blobs/uploads/abcd1234",
1878 &headers,
1879 &HashMap::new(),
1880 ),
1881 Some(("ecr", "")),
1882 );
1883 }
1884
1885 #[test]
1886 fn streaming_route_presigned_v4_s3_put() {
1887 let headers = http::HeaderMap::new();
1888 let mut query_params = HashMap::new();
1889 query_params.insert(
1890 "X-Amz-Credential".to_string(),
1891 "test/20240101/us-east-1/s3/aws4_request".to_string(),
1892 );
1893 assert_eq!(
1894 streaming_route(
1895 &http::Method::PUT,
1896 "/my-bucket/key.txt",
1897 &headers,
1898 &query_params,
1899 ),
1900 Some(("s3", "")),
1901 );
1902 }
1903
1904 #[test]
1905 fn streaming_route_non_s3_auth_header_skipped() {
1906 let mut headers = http::HeaderMap::new();
1909 headers.insert(
1910 "authorization",
1911 "AWS4-HMAC-SHA256 Credential=test/20240101/us-east-1/lambda/aws4_request, \
1912 SignedHeaders=host, Signature=fake"
1913 .parse()
1914 .unwrap(),
1915 );
1916 assert_eq!(
1917 streaming_route(
1918 &http::Method::PUT,
1919 "/my-bucket/key.txt",
1920 &headers,
1921 &HashMap::new(),
1922 ),
1923 None,
1924 );
1925 }
1926
1927 #[test]
1928 fn streaming_route_get_skipped() {
1929 let headers = s3_sigv4_headers();
1930 assert_eq!(
1931 streaming_route(
1932 &http::Method::GET,
1933 "/my-bucket/key.txt",
1934 &headers,
1935 &HashMap::new(),
1936 ),
1937 None,
1938 );
1939 }
1940}