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 let is_fully_anonymous = auth_header.is_empty()
339 && !query_params.contains_key("X-Amz-Credential")
340 && sigv2_presigned_access_key(&query_params).is_none();
341 if config.verify_sigv4
342 && !is_fully_anonymous
343 && !is_root_bypass(caller_akid)
344 && config.credential_resolver.is_some()
345 {
346 let amz_date = parts
347 .headers
348 .get("x-amz-date")
349 .and_then(|v| v.to_str().ok());
350 let parsed = fakecloud_aws::sigv4::parse_sigv4_header(auth_header, amz_date)
351 .or_else(|| fakecloud_aws::sigv4::parse_sigv4_presigned(&query_params));
352 let parsed = match parsed {
353 Some(p) => p,
354 None => {
355 return build_error_response(
356 StatusCode::FORBIDDEN,
357 "IncompleteSignature",
358 "Request is missing or has a malformed AWS Signature",
359 &request_id,
360 detected.protocol,
361 );
362 }
363 };
364 let resolved_for_verify = match resolved.as_ref() {
365 Some(r) => r,
366 None => {
367 return build_error_response(
368 StatusCode::FORBIDDEN,
369 "InvalidClientTokenId",
370 "The security token included in the request is invalid",
371 &request_id,
372 detected.protocol,
373 );
374 }
375 };
376 let headers_vec = fakecloud_aws::sigv4::headers_from_http(&parts.headers);
377 let raw_query_for_verify = parts.uri.query().unwrap_or("").to_string();
378 let verify_req = fakecloud_aws::sigv4::VerifyRequest {
379 method: parts.method.as_str(),
380 path: parts.uri.path(),
381 query: &raw_query_for_verify,
382 headers: &headers_vec,
383 body: &body_bytes,
384 };
385 match fakecloud_aws::sigv4::verify(
386 &parsed,
387 &verify_req,
388 &resolved_for_verify.secret_access_key,
389 chrono::Utc::now(),
390 ) {
391 Ok(()) => {
392 if !parsed.is_presigned && detected.service != "s3" {
408 if let Some(signed_hash) = parts
409 .headers
410 .get("x-amz-content-sha256")
411 .and_then(|v| v.to_str().ok())
412 .filter(|h| is_hex_sha256(h))
413 {
414 if sha256_hex_lower(&body_bytes) != signed_hash {
415 return build_error_response(
416 StatusCode::FORBIDDEN,
417 "SignatureDoesNotMatch",
418 "The request signature we calculated does not match the signature you provided",
419 &request_id,
420 detected.protocol,
421 );
422 }
423 }
424 }
425 }
426 Err(fakecloud_aws::sigv4::SigV4Error::RequestTimeTooSkewed { .. }) => {
427 return build_error_response(
428 StatusCode::FORBIDDEN,
429 "RequestTimeTooSkewed",
430 "The difference between the request time and the current time is too large",
431 &request_id,
432 detected.protocol,
433 );
434 }
435 Err(fakecloud_aws::sigv4::SigV4Error::InvalidDate(msg)) => {
436 return build_error_response(
437 StatusCode::FORBIDDEN,
438 "IncompleteSignature",
439 &format!("Invalid x-amz-date: {msg}"),
440 &request_id,
441 detected.protocol,
442 );
443 }
444 Err(fakecloud_aws::sigv4::SigV4Error::Malformed(msg)) => {
445 return build_error_response(
446 StatusCode::FORBIDDEN,
447 "IncompleteSignature",
448 &format!("Malformed SigV4 signature: {msg}"),
449 &request_id,
450 detected.protocol,
451 );
452 }
453 Err(fakecloud_aws::sigv4::SigV4Error::SignatureMismatch) => {
454 return build_error_response(
455 StatusCode::FORBIDDEN,
456 "SignatureDoesNotMatch",
457 "The request signature we calculated does not match the signature you provided",
458 &request_id,
459 detected.protocol,
460 );
461 }
462 Err(fakecloud_aws::sigv4::SigV4Error::PresignedUrlExpired { .. }) => {
463 return build_error_response(
464 StatusCode::FORBIDDEN,
465 "AccessDenied",
466 "Request has expired",
467 &request_id,
468 detected.protocol,
469 );
470 }
471 Err(fakecloud_aws::sigv4::SigV4Error::InvalidPresignExpires(_)) => {
472 return build_error_response(
473 StatusCode::BAD_REQUEST,
474 "AuthorizationQueryParametersError",
475 "X-Amz-Expires must be a number between 1 and 604800 seconds",
476 &request_id,
477 detected.protocol,
478 );
479 }
480 }
481 }
482
483 let wire_path = parts.uri.path();
488 let path = if detected.service == "s3" {
489 if let Some(bucket) = host_info.as_ref().and_then(|h| h.bucket.as_deref()) {
490 let prefix_with_slash = format!("/{bucket}/");
491 let is_bucket_root = wire_path.trim_end_matches('/') == format!("/{bucket}");
492 if wire_path.starts_with(&prefix_with_slash) || is_bucket_root {
493 wire_path.to_string()
494 } else if wire_path == "/" || wire_path.is_empty() {
495 format!("/{bucket}")
496 } else {
497 format!("/{bucket}{wire_path}")
498 }
499 } else {
500 wire_path.to_string()
501 }
502 } else {
503 wire_path.to_string()
504 };
505 let raw_query = parts.uri.query().unwrap_or("").to_string();
506 let path_segments: Vec<String> = path
507 .split('/')
508 .filter(|s| !s.is_empty())
509 .map(|s| s.to_string())
510 .collect();
511
512 if detected.protocol == AwsProtocol::Json
514 && !body_bytes.is_empty()
515 && serde_json::from_slice::<serde_json::Value>(&body_bytes).is_err()
516 {
517 return build_error_response(
518 StatusCode::BAD_REQUEST,
519 "SerializationException",
520 "Start of structure or map found where not expected",
521 &request_id,
522 AwsProtocol::Json,
523 );
524 }
525
526 let mut all_params = query_params;
529 if matches!(
530 detected.protocol,
531 AwsProtocol::Query | AwsProtocol::Ec2Query
532 ) {
533 let body_params = protocol::parse_query_body(&body_bytes);
534 for (k, v) in body_params {
535 all_params.entry(k).or_insert(v);
536 }
537 }
538
539 if detected.protocol == AwsProtocol::Json && detected.service == "monitoring" {
544 let body_params = protocol::flatten_json_to_query(&body_bytes);
545 for (k, v) in body_params {
546 all_params.entry(k).or_insert(v);
547 }
548 }
549
550 let aws_request = AwsRequest {
551 service: detected.service.clone(),
552 action: detected.action.clone(),
553 region,
554 account_id: caller_principal
555 .as_ref()
556 .map(|p| p.account_id.clone())
557 .unwrap_or_else(|| config.account_id.clone()),
558 request_id: request_id.clone(),
559 headers: parts.headers,
560 query_params: all_params,
561 body: body_bytes,
562 body_stream: parking_lot::Mutex::new(body_stream),
563 path_segments,
564 raw_path: path,
565 raw_query,
566 method: parts.method,
567 is_query_protocol: matches!(
568 detected.protocol,
569 AwsProtocol::Query | AwsProtocol::Ec2Query
570 ),
571 access_key_id,
572 principal: caller_principal,
573 };
574
575 tracing::info!(
576 service = %aws_request.service,
577 action = %aws_request.action,
578 request_id = %aws_request.request_id,
579 "handling request"
580 );
581
582 if config.iam_mode.is_enabled()
589 && service.iam_enforceable()
590 && !is_root_bypass(aws_request.access_key_id.as_deref().unwrap_or(""))
591 {
592 if let Some(evaluator) = config.policy_evaluator.as_ref() {
593 if let Some(principal) = aws_request.principal.as_ref() {
594 if !principal.is_root() {
595 let iam_actions = service.iam_actions_for(&aws_request);
598 if !iam_actions.is_empty() {
599 for iam_action in &iam_actions {
600 let mut condition_context = build_condition_context(
601 principal,
602 remote_addr,
603 &aws_request.region,
604 is_secure_transport(&aws_request.headers),
605 );
606 if let Some(rc) = resolved.as_ref() {
614 condition_context.aws_mfa_present = Some(rc.mfa_present);
615 condition_context.aws_token_issue_time = rc.token_issued_at;
616 condition_context.aws_federated_provider =
617 rc.federated_provider.clone();
618 if rc.mfa_present {
626 if let Some(issued) = rc.token_issued_at {
627 let age = chrono::Utc::now()
628 .signed_duration_since(issued)
629 .num_seconds()
630 .max(0);
631 condition_context.aws_mfa_age_seconds = Some(age);
632 }
633 }
634 }
635 condition_context.service_keys =
636 service.iam_condition_keys_for(&aws_request, iam_action);
637
638 match service.resource_tags_for(&iam_action.resource) {
641 Some(tags) => condition_context.resource_tags = Some(tags),
642 None => tracing::debug!(
643 target: "fakecloud::iam::audit",
644 service = %detected.service,
645 resource = %iam_action.resource,
646 "service does not expose resource tags for ABAC; skipping aws:ResourceTag/* evaluation"
647 ),
648 }
649 match service.request_tags_from(&aws_request, iam_action.action) {
651 Some(tags) => condition_context.request_tags = Some(tags),
652 None => tracing::debug!(
653 target: "fakecloud::iam::audit",
654 service = %detected.service,
655 action = %iam_action.action_string(),
656 "service does not expose request tags for ABAC; skipping aws:RequestTag/* / aws:TagKeys evaluation"
657 ),
658 }
659 condition_context.principal_tags = principal.tags.clone();
661
662 let resource_policy_json =
671 config.resource_policy_provider.as_ref().and_then(|p| {
672 p.resource_policy(&detected.service, &iam_action.resource)
673 });
674 let resource_account_id = config
684 .resource_policy_provider
685 .as_ref()
686 .and_then(|p| {
687 p.resource_owner_account(
688 &detected.service,
689 &iam_action.resource,
690 )
691 })
692 .or_else(|| parse_account_from_arn(&iam_action.resource))
693 .unwrap_or_else(|| principal.account_id.clone());
694 let scps = config
701 .scp_resolver
702 .as_ref()
703 .and_then(|r| r.scps_for(principal));
704 let decision = evaluator.evaluate_with_resource_policy(
705 principal,
706 iam_action,
707 &condition_context,
708 resource_policy_json.as_deref(),
709 &resource_account_id,
710 &caller_session_policies,
711 scps.as_deref(),
712 );
713 if !decision.is_allow() {
714 tracing::warn!(
715 target: "fakecloud::iam::audit",
716 service = %detected.service,
717 action = %iam_action.action_string(),
718 resource = %iam_action.resource,
719 principal = %principal.arn,
720 resource_policy_present = resource_policy_json.is_some(),
721 decision = ?decision,
722 mode = %config.iam_mode,
723 request_id = %request_id,
724 "IAM policy evaluation denied request"
725 );
726 if config.iam_mode.is_strict() {
727 let context_summary = serde_json::json!({
740 "aws:PrincipalArn": principal.arn,
741 "aws:PrincipalAccount": principal.account_id,
742 "aws:RequestedRegion": condition_context
743 .aws_requested_region
744 .clone()
745 .unwrap_or_default(),
746 "aws:SecureTransport": condition_context
747 .aws_secure_transport
748 .unwrap_or(false),
749 "aws:Action": iam_action.action_string(),
750 "aws:Resource": iam_action.resource,
751 "decision": format!("{:?}", decision),
752 });
753 let action_string = iam_action.action_string();
754 let encoded = crate::auth_message::encode_deny(
755 matches!(decision, crate::auth::IamDecision::ExplicitDeny),
756 Some(&action_string),
757 Some(&principal.arn),
758 Vec::new(),
759 Some(context_summary),
760 );
761 return build_error_response(
762 StatusCode::FORBIDDEN,
763 "AccessDeniedException",
764 &format!(
765 "User: {} is not authorized to perform: {} on resource: {} Encoded authorization failure message: {}",
766 principal.arn,
767 iam_action.action_string(),
768 iam_action.resource,
769 encoded,
770 ),
771 &request_id,
772 detected.protocol,
773 );
774 }
775 }
778 }
779 } else {
780 tracing::warn!(
792 target: "fakecloud::iam::audit",
793 service = %detected.service,
794 action = %aws_request.action,
795 mode = %config.iam_mode,
796 request_id = %request_id,
797 "service is iam_enforceable but has no IamAction mapping for this action; denying under strict, allowing under soft"
798 );
799 if config.iam_mode.is_strict() {
800 return build_error_response(
801 StatusCode::FORBIDDEN,
802 "AccessDeniedException",
803 &format!(
804 "User: {} is not authorized to perform: {}: no IAM action mapping exists for this operation, so it cannot be authorized under strict IAM enforcement",
805 principal.arn, aws_request.action,
806 ),
807 &request_id,
808 detected.protocol,
809 );
810 }
811 }
814 }
815 } else if aws_request.access_key_id.is_none() {
816 let iam_actions = service.iam_actions_for(&aws_request);
832 if !iam_actions.is_empty() {
833 for iam_action in &iam_actions {
834 let now = chrono::Utc::now();
835 let mut condition_context = ConditionContext {
836 aws_source_ip: remote_addr.map(|sa| sa.ip()),
837 aws_current_time: Some(now),
838 aws_epoch_time: Some(now.timestamp()),
839 aws_secure_transport: Some(is_secure_transport(&aws_request.headers)),
840 aws_requested_region: Some(aws_request.region.clone()),
841 ..Default::default()
842 };
843 condition_context.service_keys =
844 service.iam_condition_keys_for(&aws_request, iam_action);
845 let resource_policy_json =
846 config.resource_policy_provider.as_ref().and_then(|p| {
847 p.resource_policy(&detected.service, &iam_action.resource)
848 });
849 let policy_decision = evaluator.evaluate_anonymous(
850 iam_action,
851 &condition_context,
852 resource_policy_json.as_deref(),
853 );
854 let policy_allows = policy_decision.is_allow();
855 let policy_explicit_deny =
860 matches!(policy_decision, crate::auth::IamDecision::ExplicitDeny);
861 let acl_allows = !policy_explicit_deny
862 && config.resource_policy_provider.as_ref().is_some_and(|p| {
863 p.public_acl_allows(
864 &detected.service,
865 &iam_action.resource,
866 iam_action.action,
867 )
868 });
869 if !policy_allows && !acl_allows {
870 tracing::warn!(
871 target: "fakecloud::iam::audit",
872 service = %detected.service,
873 action = %iam_action.action_string(),
874 resource = %iam_action.resource,
875 resource_policy_present = resource_policy_json.is_some(),
876 mode = %config.iam_mode,
877 request_id = %request_id,
878 "anonymous request denied: no public bucket policy or ACL grants the action"
879 );
880 if config.iam_mode.is_strict() {
881 return build_error_response(
882 StatusCode::FORBIDDEN,
883 "AccessDenied",
884 "Access Denied",
885 &request_id,
886 detected.protocol,
887 );
888 }
889 }
891 }
892 } else {
893 tracing::warn!(
900 target: "fakecloud::iam::audit",
901 service = %detected.service,
902 action = %aws_request.action,
903 mode = %config.iam_mode,
904 request_id = %request_id,
905 "anonymous request to iam_enforceable service has no IamAction mapping; denying under strict, allowing under soft"
906 );
907 if config.iam_mode.is_strict() {
908 return build_error_response(
909 StatusCode::FORBIDDEN,
910 "AccessDenied",
911 "Access Denied",
912 &request_id,
913 detected.protocol,
914 );
915 }
916 }
917 }
918 }
919 }
920
921 match service.handle(aws_request).await {
922 Ok(resp) => {
923 let mut builder = Response::builder()
924 .status(resp.status)
925 .header("x-amzn-requestid", &request_id)
926 .header("x-amz-request-id", &request_id);
927
928 if !resp.content_type.is_empty() {
929 builder = builder.header("content-type", &resp.content_type);
930 }
931
932 let has_content_length = resp
933 .headers
934 .iter()
935 .any(|(k, _)| k.as_str().eq_ignore_ascii_case("content-length"));
936
937 for (k, v) in &resp.headers {
938 builder = builder.header(k, v);
939 }
940
941 match resp.body {
942 ResponseBody::Bytes(b) => builder.body(Body::from(b)).unwrap(),
943 ResponseBody::File { file, size } => {
944 let stream = tokio_util::io::ReaderStream::new(file);
945 let body = Body::from_stream(stream);
946 if !has_content_length {
947 builder = builder.header("content-length", size.to_string());
948 }
949 builder.body(body).unwrap()
950 }
951 }
952 }
953 Err(err) => {
954 tracing::warn!(
955 service = %detected.service,
956 action = %detected.action,
957 error = %err,
958 "request failed"
959 );
960 let error_headers = err.response_headers().to_vec();
961 let mut resp = build_error_response_with_fields(
962 err.status(),
963 err.code(),
964 &err.message(),
965 &request_id,
966 detected.protocol,
967 err.extra_fields(),
968 );
969 for (k, v) in &error_headers {
970 if let (Ok(name), Ok(val)) = (
971 k.parse::<http::header::HeaderName>(),
972 v.parse::<http::header::HeaderValue>(),
973 ) {
974 resp.headers_mut().insert(name, val);
975 }
976 }
977 resp
978 }
979 }
980}
981
982#[derive(Clone)]
984pub struct DispatchConfig {
985 pub region: String,
986 pub account_id: String,
987 pub verify_sigv4: bool,
991 pub iam_mode: IamMode,
996 pub credential_resolver: Option<Arc<dyn CredentialResolver>>,
1000 pub policy_evaluator: Option<Arc<dyn IamPolicyEvaluator>>,
1004 pub resource_policy_provider: Option<Arc<dyn ResourcePolicyProvider>>,
1011 pub scp_resolver: Option<Arc<dyn crate::auth::ScpResolver>>,
1018}
1019
1020impl std::fmt::Debug for DispatchConfig {
1021 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1022 f.debug_struct("DispatchConfig")
1023 .field("region", &self.region)
1024 .field("account_id", &self.account_id)
1025 .field("verify_sigv4", &self.verify_sigv4)
1026 .field("iam_mode", &self.iam_mode)
1027 .field(
1028 "credential_resolver",
1029 &self
1030 .credential_resolver
1031 .as_ref()
1032 .map(|_| "<CredentialResolver>"),
1033 )
1034 .field(
1035 "policy_evaluator",
1036 &self
1037 .policy_evaluator
1038 .as_ref()
1039 .map(|_| "<IamPolicyEvaluator>"),
1040 )
1041 .field(
1042 "resource_policy_provider",
1043 &self
1044 .resource_policy_provider
1045 .as_ref()
1046 .map(|_| "<ResourcePolicyProvider>"),
1047 )
1048 .field(
1049 "scp_resolver",
1050 &self.scp_resolver.as_ref().map(|_| "<ScpResolver>"),
1051 )
1052 .finish()
1053 }
1054}
1055
1056impl DispatchConfig {
1057 pub fn new(region: impl Into<String>, account_id: impl Into<String>) -> Self {
1060 Self {
1061 region: region.into(),
1062 account_id: account_id.into(),
1063 verify_sigv4: false,
1064 iam_mode: IamMode::Off,
1065 credential_resolver: None,
1066 policy_evaluator: None,
1067 resource_policy_provider: None,
1068 scp_resolver: None,
1069 }
1070 }
1071}
1072
1073fn streaming_route(
1093 method: &http::Method,
1094 path: &str,
1095 headers: &http::HeaderMap,
1096 query_params: &HashMap<String, String>,
1097) -> Option<(&'static str, &'static str)> {
1098 if (method == http::Method::PATCH || method == http::Method::PUT)
1100 && path.starts_with("/v2/")
1101 && path.contains("/blobs/uploads/")
1102 {
1103 return Some(("ecr", ""));
1104 }
1105
1106 if method == http::Method::PUT {
1111 let after = path.trim_start_matches('/');
1112 let virtual_hosted_s3 = protocol::parse_routing_host_from_headers(headers)
1118 .filter(|h| h.service == "s3" && h.bucket.is_some())
1119 .is_some();
1120 if after.is_empty() || (!virtual_hosted_s3 && !after.contains('/')) {
1121 return None;
1122 }
1123 let header_s3 = headers
1124 .get("authorization")
1125 .and_then(|v| v.to_str().ok())
1126 .and_then(fakecloud_aws::sigv4::parse_sigv4)
1127 .map(|info| info.service == "s3")
1128 .unwrap_or(false);
1129 let presigned_v4_s3 = query_params
1130 .get("X-Amz-Credential")
1131 .and_then(|c| c.split('/').nth(3).map(|s| s.to_string()))
1132 .map(|service| service == "s3")
1133 .unwrap_or(false);
1134 let presigned_v2 = query_params.contains_key("AWSAccessKeyId")
1135 && query_params.contains_key("Signature")
1136 && query_params.contains_key("Expires");
1137 if header_s3 || presigned_v4_s3 || presigned_v2 {
1138 return Some(("s3", ""));
1139 }
1140 }
1141
1142 None
1143}
1144
1145const DEFAULT_MAX_REQUEST_BODY_BYTES: usize = 1024 * 1024 * 1024;
1155
1156pub fn max_request_body_bytes() -> usize {
1161 static CACHED: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1162 *CACHED.get_or_init(|| {
1163 std::env::var("FAKECLOUD_MAX_REQUEST_BODY_BYTES")
1164 .ok()
1165 .and_then(|s| s.parse::<usize>().ok())
1166 .filter(|&n| n > 0)
1167 .unwrap_or(DEFAULT_MAX_REQUEST_BODY_BYTES)
1168 })
1169}
1170
1171fn parse_account_from_arn(arn: &str) -> Option<String> {
1177 let mut parts = arn.splitn(6, ':');
1178 if parts.next()? != "arn" {
1179 return None;
1180 }
1181 let _partition = parts.next()?;
1182 let _service = parts.next()?;
1183 let _region = parts.next()?;
1184 let account = parts.next()?;
1185 parts.next()?;
1188 if account.is_empty() {
1189 None
1190 } else {
1191 Some(account.to_string())
1192 }
1193}
1194
1195fn user_agent_indicates_neptune(headers: &http::HeaderMap) -> bool {
1201 for name in ["user-agent", "x-amz-user-agent"] {
1202 if let Some(ua) = headers.get(name).and_then(|v| v.to_str().ok()) {
1203 for part in ua.split_whitespace() {
1204 if let Some(rest) = part.strip_prefix("api/neptune") {
1205 if rest.is_empty() || rest.starts_with('#') || rest.starts_with('/') {
1206 return true;
1207 }
1208 }
1209 }
1210 }
1211 }
1212 false
1213}
1214
1215fn user_agent_indicates_docdb(headers: &http::HeaderMap) -> bool {
1222 for name in ["user-agent", "x-amz-user-agent"] {
1223 if let Some(ua) = headers.get(name).and_then(|v| v.to_str().ok()) {
1224 for part in ua.split_whitespace() {
1225 if let Some(rest) = part.strip_prefix("api/docdb") {
1226 if rest.is_empty() || rest.starts_with('#') || rest.starts_with('/') {
1227 return true;
1228 }
1229 }
1230 }
1231 }
1232 }
1233 false
1234}
1235
1236fn extract_region_from_user_agent(headers: &http::HeaderMap) -> Option<String> {
1237 let ua = headers.get("user-agent")?.to_str().ok()?;
1238 for part in ua.split_whitespace() {
1239 if let Some(region) = part.strip_prefix("region/") {
1240 if !region.is_empty() {
1241 return Some(region.to_string());
1242 }
1243 }
1244 }
1245 None
1246}
1247
1248fn build_error_response(
1249 status: StatusCode,
1250 code: &str,
1251 message: &str,
1252 request_id: &str,
1253 protocol: AwsProtocol,
1254) -> Response<Body> {
1255 build_error_response_with_fields(status, code, message, request_id, protocol, &[])
1256}
1257
1258fn build_error_response_with_fields(
1259 status: StatusCode,
1260 code: &str,
1261 message: &str,
1262 request_id: &str,
1263 protocol: AwsProtocol,
1264 extra_fields: &[(String, String)],
1265) -> Response<Body> {
1266 let (status, content_type, body) = match protocol {
1267 AwsProtocol::Query => {
1270 fakecloud_aws::error::xml_error_response(status, code, message, request_id)
1271 }
1272 AwsProtocol::Ec2Query => {
1277 fakecloud_aws::ec2query::ec2_error_response(status, code, message, request_id)
1278 }
1279 AwsProtocol::Rest => fakecloud_aws::error::s3_xml_error_response_with_fields(
1280 status,
1281 code,
1282 message,
1283 request_id,
1284 extra_fields,
1285 ),
1286 AwsProtocol::Json | AwsProtocol::RestJson => {
1287 fakecloud_aws::error::json_error_response_with_fields(
1288 status,
1289 code,
1290 message,
1291 extra_fields,
1292 )
1293 }
1294 };
1295
1296 let safe_code = sanitize_header_value(code);
1306 let safe_message = sanitize_header_value(message);
1307 let mut builder = Response::builder()
1308 .status(status)
1309 .header("content-type", content_type)
1310 .header("x-amzn-requestid", request_id)
1311 .header("x-amz-request-id", request_id);
1312 if let Ok(v) = http::HeaderValue::from_str(&safe_code) {
1313 builder = builder.header("x-amz-error-code", v);
1314 }
1315 if let Ok(v) = http::HeaderValue::from_str(&safe_message) {
1316 builder = builder.header("x-amz-error-message", v);
1317 }
1318 builder.body(Body::from(body)).unwrap_or_else(|_| {
1319 Response::new(Body::empty())
1323 })
1324}
1325
1326fn sanitize_header_value(s: &str) -> String {
1331 const MAX_LEN: usize = 1024;
1332 let mut out = String::with_capacity(s.len().min(MAX_LEN));
1333 for ch in s.chars() {
1334 if out.len() >= MAX_LEN {
1335 break;
1336 }
1337 if ch.is_control() {
1340 if !out.ends_with(' ') {
1341 out.push(' ');
1342 }
1343 } else {
1344 out.push(ch);
1345 }
1346 }
1347 out.trim().to_string()
1348}
1349
1350fn sigv2_presigned_access_key(query_params: &HashMap<String, String>) -> Option<String> {
1370 if query_params.contains_key("Signature") && query_params.contains_key("Expires") {
1371 query_params.get("AWSAccessKeyId").cloned()
1372 } else {
1373 None
1374 }
1375}
1376
1377fn is_hex_sha256(s: &str) -> bool {
1383 s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
1384}
1385
1386fn sha256_hex_lower(bytes: &[u8]) -> String {
1389 use sha2::{Digest, Sha256};
1390 let digest = Sha256::digest(bytes);
1391 const HEX: &[u8] = b"0123456789abcdef";
1392 let mut out = String::with_capacity(64);
1393 for b in digest {
1394 out.push(HEX[(b >> 4) as usize] as char);
1395 out.push(HEX[(b & 0x0f) as usize] as char);
1396 }
1397 out
1398}
1399
1400fn anonymous_s3_bucket(uri: &http::Uri, config: &DispatchConfig) -> Option<String> {
1401 let provider = config.resource_policy_provider.as_ref()?;
1402 let segment = uri.path().split('/').find(|s| !s.is_empty())?.to_string();
1403 let arn = format!("arn:aws:s3:::{segment}");
1404 provider.resource_owner_account("s3", &arn).map(|_| segment)
1405}
1406
1407fn build_condition_context(
1408 principal: &Principal,
1409 remote_addr: Option<SocketAddr>,
1410 region: &str,
1411 secure_transport: bool,
1412) -> ConditionContext {
1413 let now = chrono::Utc::now();
1414 ConditionContext {
1415 aws_username: aws_username_from_principal(principal),
1416 aws_userid: Some(principal.user_id.clone()),
1417 aws_principal_arn: Some(principal.arn.clone()),
1418 aws_principal_account: Some(principal.account_id.clone()),
1419 aws_principal_type: Some(principal_type_label(principal.principal_type).to_string()),
1420 aws_source_ip: remote_addr.map(|sa| sa.ip()),
1421 aws_current_time: Some(now),
1422 aws_epoch_time: Some(now.timestamp()),
1423 aws_secure_transport: Some(secure_transport),
1424 aws_requested_region: Some(region.to_string()),
1425 aws_mfa_present: None,
1431 aws_mfa_age_seconds: None,
1432 aws_called_via: Vec::new(),
1433 aws_source_vpce: None,
1434 aws_source_vpc: None,
1435 aws_vpc_source_ip: None,
1436 aws_federated_provider: None,
1437 aws_token_issue_time: None,
1438 service_keys: Default::default(),
1439 resource_tags: None,
1440 request_tags: None,
1441 principal_tags: None,
1442 }
1443}
1444
1445fn aws_username_from_principal(principal: &Principal) -> Option<String> {
1449 if principal.principal_type != PrincipalType::User {
1450 return None;
1451 }
1452 let after = principal.arn.rsplit_once(":user/").map(|(_, s)| s)?;
1453 Some(after.rsplit('/').next().unwrap_or(after).to_string())
1455}
1456
1457fn principal_type_label(t: PrincipalType) -> &'static str {
1460 match t {
1461 PrincipalType::User => "User",
1462 PrincipalType::AssumedRole => "AssumedRole",
1463 PrincipalType::FederatedUser => "FederatedUser",
1464 PrincipalType::Root => "Account",
1465 PrincipalType::Unknown => "Unknown",
1466 }
1467}
1468
1469fn is_secure_transport(headers: &http::HeaderMap) -> bool {
1475 headers
1476 .get("x-forwarded-proto")
1477 .and_then(|v| v.to_str().ok())
1478 .map(|s| s.eq_ignore_ascii_case("https"))
1479 .unwrap_or(false)
1480}
1481
1482trait ProtocolExt {
1483 fn error_status(&self) -> StatusCode;
1484}
1485
1486impl ProtocolExt for AwsProtocol {
1487 fn error_status(&self) -> StatusCode {
1488 StatusCode::BAD_REQUEST
1489 }
1490}
1491
1492#[cfg(test)]
1493mod tests {
1494 use super::*;
1495
1496 #[test]
1497 fn default_max_request_body_bytes_is_one_gib() {
1498 assert_eq!(DEFAULT_MAX_REQUEST_BODY_BYTES, 1024 * 1024 * 1024);
1502 }
1503
1504 #[test]
1505 fn sigv2_presigned_access_key_extracted_with_signature_and_expires() {
1506 let mut q = HashMap::new();
1507 q.insert("AWSAccessKeyId".to_string(), "AKIAEXAMPLE".to_string());
1508 q.insert("Signature".to_string(), "abc%2Bdef".to_string());
1509 q.insert("Expires".to_string(), "1700000000".to_string());
1510 assert_eq!(
1511 sigv2_presigned_access_key(&q).as_deref(),
1512 Some("AKIAEXAMPLE")
1513 );
1514 }
1515
1516 #[test]
1517 fn sigv2_presigned_access_key_none_without_signature_or_expires() {
1518 let mut q = HashMap::new();
1521 q.insert("AWSAccessKeyId".to_string(), "AKIAEXAMPLE".to_string());
1522 assert_eq!(sigv2_presigned_access_key(&q), None);
1523
1524 q.insert("Expires".to_string(), "1700000000".to_string());
1525 assert_eq!(
1526 sigv2_presigned_access_key(&q),
1527 None,
1528 "missing Signature must not qualify"
1529 );
1530 }
1531
1532 #[test]
1533 fn sigv2_presigned_access_key_none_for_unsigned_request() {
1534 assert_eq!(sigv2_presigned_access_key(&HashMap::new()), None);
1535 }
1536
1537 #[test]
1538 fn is_hex_sha256_accepts_real_digest_rejects_markers() {
1539 assert!(is_hex_sha256(&sha256_hex_lower(b"hello")));
1541 assert!(is_hex_sha256(
1542 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
1543 ));
1544 assert!(!is_hex_sha256("UNSIGNED-PAYLOAD"));
1546 assert!(!is_hex_sha256("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"));
1547 assert!(!is_hex_sha256("STREAMING-UNSIGNED-PAYLOAD-TRAILER"));
1548 assert!(!is_hex_sha256("abc123"));
1550 assert!(!is_hex_sha256(
1551 "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855"
1552 ));
1553 }
1554
1555 #[test]
1556 fn sha256_hex_lower_matches_known_vectors() {
1557 assert_eq!(
1559 sha256_hex_lower(b""),
1560 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
1561 );
1562 assert_eq!(
1563 sha256_hex_lower(b"abc"),
1564 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
1565 );
1566 assert_eq!(sha256_hex_lower(b"abc").len(), 64);
1567 }
1568
1569 #[test]
1570 fn dispatch_config_new_defaults_to_off() {
1571 let cfg = DispatchConfig::new("us-east-1", "123456789012");
1572 assert_eq!(cfg.region, "us-east-1");
1573 assert_eq!(cfg.account_id, "123456789012");
1574 assert!(!cfg.verify_sigv4);
1575 assert_eq!(cfg.iam_mode, IamMode::Off);
1576 }
1577
1578 #[test]
1579 fn aws_username_strips_iam_path_for_users() {
1580 let p = Principal {
1581 arn: "arn:aws:iam::123456789012:user/engineering/alice".into(),
1582 user_id: "AIDAALICE".into(),
1583 account_id: "123456789012".into(),
1584 principal_type: PrincipalType::User,
1585 source_identity: None,
1586 tags: None,
1587 };
1588 assert_eq!(aws_username_from_principal(&p), Some("alice".into()));
1589 }
1590
1591 #[test]
1592 fn aws_username_unset_for_assumed_role() {
1593 let p = Principal {
1594 arn: "arn:aws:sts::123456789012:assumed-role/ops/session".into(),
1595 user_id: "AROAOPS:session".into(),
1596 account_id: "123456789012".into(),
1597 principal_type: PrincipalType::AssumedRole,
1598 source_identity: None,
1599 tags: None,
1600 };
1601 assert_eq!(aws_username_from_principal(&p), None);
1602 }
1603
1604 #[test]
1605 fn principal_type_label_matches_aws_casing() {
1606 assert_eq!(principal_type_label(PrincipalType::User), "User");
1607 assert_eq!(
1608 principal_type_label(PrincipalType::AssumedRole),
1609 "AssumedRole"
1610 );
1611 assert_eq!(principal_type_label(PrincipalType::Root), "Account");
1612 }
1613
1614 #[test]
1615 fn build_condition_context_populates_global_keys() {
1616 let p = Principal {
1617 arn: "arn:aws:iam::123456789012:user/alice".into(),
1618 user_id: "AIDAALICE".into(),
1619 account_id: "123456789012".into(),
1620 principal_type: PrincipalType::User,
1621 source_identity: None,
1622 tags: None,
1623 };
1624 let addr: SocketAddr = "10.0.0.1:54321".parse().unwrap();
1625 let ctx = build_condition_context(&p, Some(addr), "us-east-1", false);
1626 assert_eq!(ctx.aws_username.as_deref(), Some("alice"));
1627 assert_eq!(ctx.aws_userid.as_deref(), Some("AIDAALICE"));
1628 assert_eq!(
1629 ctx.aws_principal_arn.as_deref(),
1630 Some("arn:aws:iam::123456789012:user/alice")
1631 );
1632 assert_eq!(ctx.aws_principal_account.as_deref(), Some("123456789012"));
1633 assert_eq!(ctx.aws_principal_type.as_deref(), Some("User"));
1634 assert_eq!(
1635 ctx.aws_source_ip.map(|i| i.to_string()).as_deref(),
1636 Some("10.0.0.1")
1637 );
1638 assert_eq!(ctx.aws_requested_region.as_deref(), Some("us-east-1"));
1639 assert_eq!(ctx.aws_secure_transport, Some(false));
1640 assert!(ctx.aws_current_time.is_some());
1641 assert!(ctx.aws_epoch_time.is_some());
1642 }
1643
1644 #[test]
1645 fn is_secure_transport_reads_x_forwarded_proto() {
1646 let mut headers = http::HeaderMap::new();
1647 headers.insert("x-forwarded-proto", "https".parse().unwrap());
1648 assert!(is_secure_transport(&headers));
1649 headers.insert("x-forwarded-proto", "http".parse().unwrap());
1650 assert!(!is_secure_transport(&headers));
1651 let empty = http::HeaderMap::new();
1652 assert!(!is_secure_transport(&empty));
1653 }
1654
1655 #[test]
1656 fn parse_account_from_arn_extracts_standard_shapes() {
1657 assert_eq!(
1658 parse_account_from_arn("arn:aws:sqs:us-east-1:123456789012:queue"),
1659 Some("123456789012".to_string())
1660 );
1661 assert_eq!(
1662 parse_account_from_arn("arn:aws:iam::123456789012:user/alice"),
1663 Some("123456789012".to_string())
1664 );
1665 }
1666
1667 #[test]
1668 fn parse_account_from_arn_returns_none_for_s3_empty_account() {
1669 assert_eq!(parse_account_from_arn("arn:aws:s3:::my-bucket"), None);
1671 assert_eq!(
1672 parse_account_from_arn("arn:aws:s3:::my-bucket/path/to/key"),
1673 None
1674 );
1675 }
1676
1677 #[test]
1678 fn parse_account_from_arn_returns_none_for_malformed() {
1679 assert_eq!(parse_account_from_arn(""), None);
1680 assert_eq!(parse_account_from_arn("not-an-arn"), None);
1681 assert_eq!(parse_account_from_arn("arn:aws:sqs:us-east-1"), None);
1682 assert_eq!(parse_account_from_arn("arn:aws:sqs"), None);
1683 }
1684
1685 #[test]
1686 fn extract_region_from_user_agent_finds_region_segment() {
1687 let mut headers = http::HeaderMap::new();
1688 headers.insert(
1689 "user-agent",
1690 "aws-sdk-rust/1.0 os/linux region/eu-central-1"
1691 .parse()
1692 .unwrap(),
1693 );
1694 assert_eq!(
1695 extract_region_from_user_agent(&headers),
1696 Some("eu-central-1".to_string())
1697 );
1698 }
1699
1700 #[test]
1701 fn extract_region_from_user_agent_none_without_header() {
1702 let headers = http::HeaderMap::new();
1703 assert_eq!(extract_region_from_user_agent(&headers), None);
1704 }
1705
1706 #[test]
1707 fn extract_region_from_user_agent_ignores_empty_region() {
1708 let mut headers = http::HeaderMap::new();
1709 headers.insert("user-agent", "aws-sdk-java region/".parse().unwrap());
1710 assert_eq!(extract_region_from_user_agent(&headers), None);
1711 }
1712
1713 #[test]
1714 fn extract_region_from_user_agent_none_when_no_region_marker() {
1715 let mut headers = http::HeaderMap::new();
1716 headers.insert("user-agent", "curl/7.79.1".parse().unwrap());
1717 assert_eq!(extract_region_from_user_agent(&headers), None);
1718 }
1719
1720 #[test]
1721 fn aws_username_none_for_root() {
1722 let p = Principal {
1723 arn: "arn:aws:iam::123456789012:root".into(),
1724 user_id: "123456789012".into(),
1725 account_id: "123456789012".into(),
1726 principal_type: PrincipalType::Root,
1727 source_identity: None,
1728 tags: None,
1729 };
1730 assert_eq!(aws_username_from_principal(&p), None);
1731 }
1732
1733 #[test]
1734 fn aws_username_bare_no_path() {
1735 let p = Principal {
1736 arn: "arn:aws:iam::123456789012:user/bob".into(),
1737 user_id: "AIDABOB".into(),
1738 account_id: "123456789012".into(),
1739 principal_type: PrincipalType::User,
1740 source_identity: None,
1741 tags: None,
1742 };
1743 assert_eq!(aws_username_from_principal(&p), Some("bob".into()));
1744 }
1745
1746 #[test]
1747 fn principal_type_label_covers_federated_and_unknown() {
1748 assert_eq!(
1749 principal_type_label(PrincipalType::FederatedUser),
1750 "FederatedUser"
1751 );
1752 assert_eq!(principal_type_label(PrincipalType::Unknown), "Unknown");
1753 }
1754
1755 #[test]
1756 fn build_condition_context_marks_secure_when_flag_set() {
1757 let p = Principal {
1758 arn: "arn:aws:iam::123456789012:user/alice".into(),
1759 user_id: "AIDAALICE".into(),
1760 account_id: "123456789012".into(),
1761 principal_type: PrincipalType::User,
1762 source_identity: None,
1763 tags: None,
1764 };
1765 let ctx = build_condition_context(&p, None, "us-west-2", true);
1766 assert_eq!(ctx.aws_secure_transport, Some(true));
1767 assert!(ctx.aws_source_ip.is_none());
1768 assert_eq!(ctx.aws_requested_region.as_deref(), Some("us-west-2"));
1769 }
1770
1771 #[test]
1772 fn is_secure_transport_case_insensitive() {
1773 let mut headers = http::HeaderMap::new();
1774 headers.insert("x-forwarded-proto", "HTTPS".parse().unwrap());
1775 assert!(is_secure_transport(&headers));
1776 }
1777
1778 #[test]
1779 fn is_secure_transport_non_ascii_bytes_false() {
1780 let mut headers = http::HeaderMap::new();
1781 headers.insert(
1782 "x-forwarded-proto",
1783 http::HeaderValue::from_bytes(&[0xFF, 0xFE]).unwrap(),
1784 );
1785 assert!(!is_secure_transport(&headers));
1786 }
1787
1788 #[test]
1789 fn protocol_ext_error_status_is_bad_request() {
1790 assert_eq!(AwsProtocol::Query.error_status(), StatusCode::BAD_REQUEST);
1791 assert_eq!(AwsProtocol::Json.error_status(), StatusCode::BAD_REQUEST);
1792 assert_eq!(AwsProtocol::Rest.error_status(), StatusCode::BAD_REQUEST);
1793 assert_eq!(
1794 AwsProtocol::RestJson.error_status(),
1795 StatusCode::BAD_REQUEST
1796 );
1797 }
1798
1799 #[test]
1800 fn build_error_response_json_has_json_content_type() {
1801 let resp = build_error_response(
1802 StatusCode::BAD_REQUEST,
1803 "TestCode",
1804 "test msg",
1805 "req-1",
1806 AwsProtocol::Json,
1807 );
1808 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1809 let ct = resp
1810 .headers()
1811 .get("content-type")
1812 .unwrap()
1813 .to_str()
1814 .unwrap();
1815 assert!(ct.contains("json"));
1816 let rid = resp
1817 .headers()
1818 .get("x-amzn-requestid")
1819 .unwrap()
1820 .to_str()
1821 .unwrap();
1822 assert_eq!(rid, "req-1");
1823 }
1824
1825 #[test]
1826 fn build_error_response_rest_returns_xml_content_type() {
1827 let resp = build_error_response(
1828 StatusCode::NOT_FOUND,
1829 "NoSuchBucket",
1830 "bucket missing",
1831 "req-2",
1832 AwsProtocol::Rest,
1833 );
1834 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1835 let ct = resp
1836 .headers()
1837 .get("content-type")
1838 .unwrap()
1839 .to_str()
1840 .unwrap();
1841 assert!(ct.contains("xml"));
1842 }
1843
1844 #[test]
1845 fn build_error_response_query_returns_xml() {
1846 let resp = build_error_response(
1847 StatusCode::BAD_REQUEST,
1848 "InvalidParameter",
1849 "bad param",
1850 "req-3",
1851 AwsProtocol::Query,
1852 );
1853 let ct = resp
1854 .headers()
1855 .get("content-type")
1856 .unwrap()
1857 .to_str()
1858 .unwrap();
1859 assert!(ct.contains("xml"));
1860 }
1861
1862 #[test]
1867 fn build_error_response_with_multiline_message_does_not_panic() {
1868 let resp = build_error_response(
1869 StatusCode::INTERNAL_SERVER_ERROR,
1870 "ServiceException",
1871 "Lambda execution failed: container failed to start: docker start failed: \
1872 Error: unable to start container \"abc\": \
1873 failed to create new hosts file:\nhost-gateway is empty\n",
1874 "req-multi",
1875 AwsProtocol::Json,
1876 );
1877 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1878 let msg = resp
1879 .headers()
1880 .get("x-amz-error-message")
1881 .expect("x-amz-error-message must be set even when input contains newlines")
1882 .to_str()
1883 .unwrap();
1884 assert!(!msg.contains('\n'));
1885 assert!(!msg.contains('\r'));
1886 assert!(msg.contains("Lambda execution failed"));
1887 assert!(msg.contains("host-gateway is empty"));
1888 }
1889
1890 #[test]
1891 fn build_error_response_with_control_chars_strips_them() {
1892 let resp = build_error_response(
1893 StatusCode::BAD_REQUEST,
1894 "Code\twith\ttabs",
1895 "msg\x00with\x01nulls",
1896 "req-ctrl",
1897 AwsProtocol::Json,
1898 );
1899 let code = resp
1900 .headers()
1901 .get("x-amz-error-code")
1902 .unwrap()
1903 .to_str()
1904 .unwrap();
1905 let msg = resp
1906 .headers()
1907 .get("x-amz-error-message")
1908 .unwrap()
1909 .to_str()
1910 .unwrap();
1911 assert!(!code.contains('\t'));
1912 assert!(!msg.contains('\x00'));
1913 assert!(!msg.contains('\x01'));
1914 }
1915
1916 #[test]
1917 fn sanitize_header_value_truncates_long_input() {
1918 let huge = "x".repeat(5_000);
1919 let out = sanitize_header_value(&huge);
1920 assert!(out.len() <= 1024);
1921 }
1922
1923 #[test]
1924 fn sanitize_header_value_collapses_consecutive_control_runs() {
1925 let out = sanitize_header_value("a\n\n\n\rb");
1926 assert_eq!(out, "a b");
1927 }
1928
1929 #[test]
1930 fn dispatch_config_carries_opt_in_flags() {
1931 let cfg = DispatchConfig {
1932 region: "eu-west-1".to_string(),
1933 account_id: "000000000000".to_string(),
1934 verify_sigv4: true,
1935 iam_mode: IamMode::Strict,
1936 credential_resolver: None,
1937 policy_evaluator: None,
1938 resource_policy_provider: None,
1939 scp_resolver: None,
1940 };
1941 assert!(cfg.verify_sigv4);
1942 assert!(cfg.iam_mode.is_strict());
1943 assert!(cfg.resource_policy_provider.is_none());
1944 assert!(cfg.scp_resolver.is_none());
1945 }
1946
1947 fn s3_sigv4_headers() -> http::HeaderMap {
1948 let mut headers = http::HeaderMap::new();
1949 headers.insert(
1950 "authorization",
1951 "AWS4-HMAC-SHA256 Credential=test/20240101/us-east-1/s3/aws4_request, \
1952 SignedHeaders=host, Signature=fake"
1953 .parse()
1954 .unwrap(),
1955 );
1956 headers
1957 }
1958
1959 #[test]
1960 fn streaming_route_path_style_s3_put_object() {
1961 let headers = s3_sigv4_headers();
1962 assert_eq!(
1963 streaming_route(
1964 &http::Method::PUT,
1965 "/my-bucket/key.txt",
1966 &headers,
1967 &HashMap::new(),
1968 ),
1969 Some(("s3", "")),
1970 );
1971 }
1972
1973 #[test]
1974 fn streaming_route_path_style_create_bucket_skipped() {
1975 let headers = s3_sigv4_headers();
1978 assert_eq!(
1979 streaming_route(&http::Method::PUT, "/my-bucket", &headers, &HashMap::new(),),
1980 None,
1981 );
1982 }
1983
1984 #[test]
1985 fn streaming_route_virtual_hosted_s3_put_object() {
1986 let mut headers = s3_sigv4_headers();
1987 headers.insert(
1988 "host",
1989 "vhost-bucket.s3.us-east-1.localhost.localstack.cloud:4566"
1990 .parse()
1991 .unwrap(),
1992 );
1993 assert_eq!(
1998 streaming_route(&http::Method::PUT, "/hello.txt", &headers, &HashMap::new(),),
1999 Some(("s3", "")),
2000 );
2001 }
2002
2003 #[test]
2004 fn streaming_route_virtual_hosted_s3_root_skipped() {
2005 let mut headers = s3_sigv4_headers();
2008 headers.insert(
2009 "host",
2010 "vhost-bucket.s3.us-east-1.localhost.localstack.cloud:4566"
2011 .parse()
2012 .unwrap(),
2013 );
2014 assert_eq!(
2015 streaming_route(&http::Method::PUT, "/", &headers, &HashMap::new()),
2016 None,
2017 );
2018 }
2019
2020 #[test]
2021 fn streaming_route_ecr_blob_upload() {
2022 let headers = http::HeaderMap::new();
2023 assert_eq!(
2024 streaming_route(
2025 &http::Method::PATCH,
2026 "/v2/my-repo/blobs/uploads/abcd1234",
2027 &headers,
2028 &HashMap::new(),
2029 ),
2030 Some(("ecr", "")),
2031 );
2032 assert_eq!(
2033 streaming_route(
2034 &http::Method::PUT,
2035 "/v2/my-repo/blobs/uploads/abcd1234",
2036 &headers,
2037 &HashMap::new(),
2038 ),
2039 Some(("ecr", "")),
2040 );
2041 }
2042
2043 #[test]
2044 fn streaming_route_presigned_v4_s3_put() {
2045 let headers = http::HeaderMap::new();
2046 let mut query_params = HashMap::new();
2047 query_params.insert(
2048 "X-Amz-Credential".to_string(),
2049 "test/20240101/us-east-1/s3/aws4_request".to_string(),
2050 );
2051 assert_eq!(
2052 streaming_route(
2053 &http::Method::PUT,
2054 "/my-bucket/key.txt",
2055 &headers,
2056 &query_params,
2057 ),
2058 Some(("s3", "")),
2059 );
2060 }
2061
2062 #[test]
2063 fn streaming_route_non_s3_auth_header_skipped() {
2064 let mut headers = http::HeaderMap::new();
2067 headers.insert(
2068 "authorization",
2069 "AWS4-HMAC-SHA256 Credential=test/20240101/us-east-1/lambda/aws4_request, \
2070 SignedHeaders=host, Signature=fake"
2071 .parse()
2072 .unwrap(),
2073 );
2074 assert_eq!(
2075 streaming_route(
2076 &http::Method::PUT,
2077 "/my-bucket/key.txt",
2078 &headers,
2079 &HashMap::new(),
2080 ),
2081 None,
2082 );
2083 }
2084
2085 #[test]
2086 fn streaming_route_get_skipped() {
2087 let headers = s3_sigv4_headers();
2088 assert_eq!(
2089 streaming_route(
2090 &http::Method::GET,
2091 "/my-bucket/key.txt",
2092 &headers,
2093 &HashMap::new(),
2094 ),
2095 None,
2096 );
2097 }
2098}