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 if let Some(iam_action) = service.iam_action_for(&aws_request) {
596 let mut condition_context = build_condition_context(
597 principal,
598 remote_addr,
599 &aws_request.region,
600 is_secure_transport(&aws_request.headers),
601 );
602 if let Some(rc) = resolved.as_ref() {
610 condition_context.aws_mfa_present = Some(rc.mfa_present);
611 condition_context.aws_token_issue_time = rc.token_issued_at;
612 condition_context.aws_federated_provider =
613 rc.federated_provider.clone();
614 if rc.mfa_present {
622 if let Some(issued) = rc.token_issued_at {
623 let age = chrono::Utc::now()
624 .signed_duration_since(issued)
625 .num_seconds()
626 .max(0);
627 condition_context.aws_mfa_age_seconds = Some(age);
628 }
629 }
630 }
631 condition_context.service_keys =
632 service.iam_condition_keys_for(&aws_request, &iam_action);
633
634 match service.resource_tags_for(&iam_action.resource) {
637 Some(tags) => condition_context.resource_tags = Some(tags),
638 None => tracing::debug!(
639 target: "fakecloud::iam::audit",
640 service = %detected.service,
641 resource = %iam_action.resource,
642 "service does not expose resource tags for ABAC; skipping aws:ResourceTag/* evaluation"
643 ),
644 }
645 match service.request_tags_from(&aws_request, iam_action.action) {
647 Some(tags) => condition_context.request_tags = Some(tags),
648 None => tracing::debug!(
649 target: "fakecloud::iam::audit",
650 service = %detected.service,
651 action = %iam_action.action_string(),
652 "service does not expose request tags for ABAC; skipping aws:RequestTag/* / aws:TagKeys evaluation"
653 ),
654 }
655 condition_context.principal_tags = principal.tags.clone();
657
658 let resource_policy_json =
667 config.resource_policy_provider.as_ref().and_then(|p| {
668 p.resource_policy(&detected.service, &iam_action.resource)
669 });
670 let resource_account_id = config
680 .resource_policy_provider
681 .as_ref()
682 .and_then(|p| {
683 p.resource_owner_account(&detected.service, &iam_action.resource)
684 })
685 .or_else(|| parse_account_from_arn(&iam_action.resource))
686 .unwrap_or_else(|| principal.account_id.clone());
687 let scps = config
694 .scp_resolver
695 .as_ref()
696 .and_then(|r| r.scps_for(principal));
697 let decision = evaluator.evaluate_with_resource_policy(
698 principal,
699 &iam_action,
700 &condition_context,
701 resource_policy_json.as_deref(),
702 &resource_account_id,
703 &caller_session_policies,
704 scps.as_deref(),
705 );
706 if !decision.is_allow() {
707 tracing::warn!(
708 target: "fakecloud::iam::audit",
709 service = %detected.service,
710 action = %iam_action.action_string(),
711 resource = %iam_action.resource,
712 principal = %principal.arn,
713 resource_policy_present = resource_policy_json.is_some(),
714 decision = ?decision,
715 mode = %config.iam_mode,
716 request_id = %request_id,
717 "IAM policy evaluation denied request"
718 );
719 if config.iam_mode.is_strict() {
720 let context_summary = serde_json::json!({
733 "aws:PrincipalArn": principal.arn,
734 "aws:PrincipalAccount": principal.account_id,
735 "aws:RequestedRegion": condition_context
736 .aws_requested_region
737 .clone()
738 .unwrap_or_default(),
739 "aws:SecureTransport": condition_context
740 .aws_secure_transport
741 .unwrap_or(false),
742 "aws:Action": iam_action.action_string(),
743 "aws:Resource": iam_action.resource,
744 "decision": format!("{:?}", decision),
745 });
746 let action_string = iam_action.action_string();
747 let encoded = crate::auth_message::encode_deny(
748 matches!(decision, crate::auth::IamDecision::ExplicitDeny),
749 Some(&action_string),
750 Some(&principal.arn),
751 Vec::new(),
752 Some(context_summary),
753 );
754 return build_error_response(
755 StatusCode::FORBIDDEN,
756 "AccessDeniedException",
757 &format!(
758 "User: {} is not authorized to perform: {} on resource: {} Encoded authorization failure message: {}",
759 principal.arn,
760 iam_action.action_string(),
761 iam_action.resource,
762 encoded,
763 ),
764 &request_id,
765 detected.protocol,
766 );
767 }
768 }
771 } else {
772 tracing::warn!(
784 target: "fakecloud::iam::audit",
785 service = %detected.service,
786 action = %aws_request.action,
787 mode = %config.iam_mode,
788 request_id = %request_id,
789 "service is iam_enforceable but has no IamAction mapping for this action; denying under strict, allowing under soft"
790 );
791 if config.iam_mode.is_strict() {
792 return build_error_response(
793 StatusCode::FORBIDDEN,
794 "AccessDeniedException",
795 &format!(
796 "User: {} is not authorized to perform: {}: no IAM action mapping exists for this operation, so it cannot be authorized under strict IAM enforcement",
797 principal.arn, aws_request.action,
798 ),
799 &request_id,
800 detected.protocol,
801 );
802 }
803 }
806 }
807 } else if aws_request.access_key_id.is_none() {
808 if let Some(iam_action) = service.iam_action_for(&aws_request) {
824 let now = chrono::Utc::now();
825 let mut condition_context = ConditionContext {
826 aws_source_ip: remote_addr.map(|sa| sa.ip()),
827 aws_current_time: Some(now),
828 aws_epoch_time: Some(now.timestamp()),
829 aws_secure_transport: Some(is_secure_transport(&aws_request.headers)),
830 aws_requested_region: Some(aws_request.region.clone()),
831 ..Default::default()
832 };
833 condition_context.service_keys =
834 service.iam_condition_keys_for(&aws_request, &iam_action);
835 let resource_policy_json = config
836 .resource_policy_provider
837 .as_ref()
838 .and_then(|p| p.resource_policy(&detected.service, &iam_action.resource));
839 let policy_decision = evaluator.evaluate_anonymous(
840 &iam_action,
841 &condition_context,
842 resource_policy_json.as_deref(),
843 );
844 let policy_allows = policy_decision.is_allow();
845 let policy_explicit_deny =
850 matches!(policy_decision, crate::auth::IamDecision::ExplicitDeny);
851 let acl_allows = !policy_explicit_deny
852 && config.resource_policy_provider.as_ref().is_some_and(|p| {
853 p.public_acl_allows(
854 &detected.service,
855 &iam_action.resource,
856 iam_action.action,
857 )
858 });
859 if !policy_allows && !acl_allows {
860 tracing::warn!(
861 target: "fakecloud::iam::audit",
862 service = %detected.service,
863 action = %iam_action.action_string(),
864 resource = %iam_action.resource,
865 resource_policy_present = resource_policy_json.is_some(),
866 mode = %config.iam_mode,
867 request_id = %request_id,
868 "anonymous request denied: no public bucket policy or ACL grants the action"
869 );
870 if config.iam_mode.is_strict() {
871 return build_error_response(
872 StatusCode::FORBIDDEN,
873 "AccessDenied",
874 "Access Denied",
875 &request_id,
876 detected.protocol,
877 );
878 }
879 }
881 } else {
882 tracing::warn!(
889 target: "fakecloud::iam::audit",
890 service = %detected.service,
891 action = %aws_request.action,
892 mode = %config.iam_mode,
893 request_id = %request_id,
894 "anonymous request to iam_enforceable service has no IamAction mapping; denying under strict, allowing under soft"
895 );
896 if config.iam_mode.is_strict() {
897 return build_error_response(
898 StatusCode::FORBIDDEN,
899 "AccessDenied",
900 "Access Denied",
901 &request_id,
902 detected.protocol,
903 );
904 }
905 }
906 }
907 }
908 }
909
910 match service.handle(aws_request).await {
911 Ok(resp) => {
912 let mut builder = Response::builder()
913 .status(resp.status)
914 .header("x-amzn-requestid", &request_id)
915 .header("x-amz-request-id", &request_id);
916
917 if !resp.content_type.is_empty() {
918 builder = builder.header("content-type", &resp.content_type);
919 }
920
921 let has_content_length = resp
922 .headers
923 .iter()
924 .any(|(k, _)| k.as_str().eq_ignore_ascii_case("content-length"));
925
926 for (k, v) in &resp.headers {
927 builder = builder.header(k, v);
928 }
929
930 match resp.body {
931 ResponseBody::Bytes(b) => builder.body(Body::from(b)).unwrap(),
932 ResponseBody::File { file, size } => {
933 let stream = tokio_util::io::ReaderStream::new(file);
934 let body = Body::from_stream(stream);
935 if !has_content_length {
936 builder = builder.header("content-length", size.to_string());
937 }
938 builder.body(body).unwrap()
939 }
940 }
941 }
942 Err(err) => {
943 tracing::warn!(
944 service = %detected.service,
945 action = %detected.action,
946 error = %err,
947 "request failed"
948 );
949 let error_headers = err.response_headers().to_vec();
950 let mut resp = build_error_response_with_fields(
951 err.status(),
952 err.code(),
953 &err.message(),
954 &request_id,
955 detected.protocol,
956 err.extra_fields(),
957 );
958 for (k, v) in &error_headers {
959 if let (Ok(name), Ok(val)) = (
960 k.parse::<http::header::HeaderName>(),
961 v.parse::<http::header::HeaderValue>(),
962 ) {
963 resp.headers_mut().insert(name, val);
964 }
965 }
966 resp
967 }
968 }
969}
970
971#[derive(Clone)]
973pub struct DispatchConfig {
974 pub region: String,
975 pub account_id: String,
976 pub verify_sigv4: bool,
980 pub iam_mode: IamMode,
985 pub credential_resolver: Option<Arc<dyn CredentialResolver>>,
989 pub policy_evaluator: Option<Arc<dyn IamPolicyEvaluator>>,
993 pub resource_policy_provider: Option<Arc<dyn ResourcePolicyProvider>>,
1000 pub scp_resolver: Option<Arc<dyn crate::auth::ScpResolver>>,
1007}
1008
1009impl std::fmt::Debug for DispatchConfig {
1010 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1011 f.debug_struct("DispatchConfig")
1012 .field("region", &self.region)
1013 .field("account_id", &self.account_id)
1014 .field("verify_sigv4", &self.verify_sigv4)
1015 .field("iam_mode", &self.iam_mode)
1016 .field(
1017 "credential_resolver",
1018 &self
1019 .credential_resolver
1020 .as_ref()
1021 .map(|_| "<CredentialResolver>"),
1022 )
1023 .field(
1024 "policy_evaluator",
1025 &self
1026 .policy_evaluator
1027 .as_ref()
1028 .map(|_| "<IamPolicyEvaluator>"),
1029 )
1030 .field(
1031 "resource_policy_provider",
1032 &self
1033 .resource_policy_provider
1034 .as_ref()
1035 .map(|_| "<ResourcePolicyProvider>"),
1036 )
1037 .field(
1038 "scp_resolver",
1039 &self.scp_resolver.as_ref().map(|_| "<ScpResolver>"),
1040 )
1041 .finish()
1042 }
1043}
1044
1045impl DispatchConfig {
1046 pub fn new(region: impl Into<String>, account_id: impl Into<String>) -> Self {
1049 Self {
1050 region: region.into(),
1051 account_id: account_id.into(),
1052 verify_sigv4: false,
1053 iam_mode: IamMode::Off,
1054 credential_resolver: None,
1055 policy_evaluator: None,
1056 resource_policy_provider: None,
1057 scp_resolver: None,
1058 }
1059 }
1060}
1061
1062fn streaming_route(
1082 method: &http::Method,
1083 path: &str,
1084 headers: &http::HeaderMap,
1085 query_params: &HashMap<String, String>,
1086) -> Option<(&'static str, &'static str)> {
1087 if (method == http::Method::PATCH || method == http::Method::PUT)
1089 && path.starts_with("/v2/")
1090 && path.contains("/blobs/uploads/")
1091 {
1092 return Some(("ecr", ""));
1093 }
1094
1095 if method == http::Method::PUT {
1100 let after = path.trim_start_matches('/');
1101 let virtual_hosted_s3 = protocol::parse_routing_host_from_headers(headers)
1107 .filter(|h| h.service == "s3" && h.bucket.is_some())
1108 .is_some();
1109 if after.is_empty() || (!virtual_hosted_s3 && !after.contains('/')) {
1110 return None;
1111 }
1112 let header_s3 = headers
1113 .get("authorization")
1114 .and_then(|v| v.to_str().ok())
1115 .and_then(fakecloud_aws::sigv4::parse_sigv4)
1116 .map(|info| info.service == "s3")
1117 .unwrap_or(false);
1118 let presigned_v4_s3 = query_params
1119 .get("X-Amz-Credential")
1120 .and_then(|c| c.split('/').nth(3).map(|s| s.to_string()))
1121 .map(|service| service == "s3")
1122 .unwrap_or(false);
1123 let presigned_v2 = query_params.contains_key("AWSAccessKeyId")
1124 && query_params.contains_key("Signature")
1125 && query_params.contains_key("Expires");
1126 if header_s3 || presigned_v4_s3 || presigned_v2 {
1127 return Some(("s3", ""));
1128 }
1129 }
1130
1131 None
1132}
1133
1134const DEFAULT_MAX_REQUEST_BODY_BYTES: usize = 1024 * 1024 * 1024;
1144
1145pub fn max_request_body_bytes() -> usize {
1150 static CACHED: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1151 *CACHED.get_or_init(|| {
1152 std::env::var("FAKECLOUD_MAX_REQUEST_BODY_BYTES")
1153 .ok()
1154 .and_then(|s| s.parse::<usize>().ok())
1155 .filter(|&n| n > 0)
1156 .unwrap_or(DEFAULT_MAX_REQUEST_BODY_BYTES)
1157 })
1158}
1159
1160fn parse_account_from_arn(arn: &str) -> Option<String> {
1166 let mut parts = arn.splitn(6, ':');
1167 if parts.next()? != "arn" {
1168 return None;
1169 }
1170 let _partition = parts.next()?;
1171 let _service = parts.next()?;
1172 let _region = parts.next()?;
1173 let account = parts.next()?;
1174 parts.next()?;
1177 if account.is_empty() {
1178 None
1179 } else {
1180 Some(account.to_string())
1181 }
1182}
1183
1184fn user_agent_indicates_neptune(headers: &http::HeaderMap) -> bool {
1190 for name in ["user-agent", "x-amz-user-agent"] {
1191 if let Some(ua) = headers.get(name).and_then(|v| v.to_str().ok()) {
1192 for part in ua.split_whitespace() {
1193 if let Some(rest) = part.strip_prefix("api/neptune") {
1194 if rest.is_empty() || rest.starts_with('#') || rest.starts_with('/') {
1195 return true;
1196 }
1197 }
1198 }
1199 }
1200 }
1201 false
1202}
1203
1204fn user_agent_indicates_docdb(headers: &http::HeaderMap) -> bool {
1211 for name in ["user-agent", "x-amz-user-agent"] {
1212 if let Some(ua) = headers.get(name).and_then(|v| v.to_str().ok()) {
1213 for part in ua.split_whitespace() {
1214 if let Some(rest) = part.strip_prefix("api/docdb") {
1215 if rest.is_empty() || rest.starts_with('#') || rest.starts_with('/') {
1216 return true;
1217 }
1218 }
1219 }
1220 }
1221 }
1222 false
1223}
1224
1225fn extract_region_from_user_agent(headers: &http::HeaderMap) -> Option<String> {
1226 let ua = headers.get("user-agent")?.to_str().ok()?;
1227 for part in ua.split_whitespace() {
1228 if let Some(region) = part.strip_prefix("region/") {
1229 if !region.is_empty() {
1230 return Some(region.to_string());
1231 }
1232 }
1233 }
1234 None
1235}
1236
1237fn build_error_response(
1238 status: StatusCode,
1239 code: &str,
1240 message: &str,
1241 request_id: &str,
1242 protocol: AwsProtocol,
1243) -> Response<Body> {
1244 build_error_response_with_fields(status, code, message, request_id, protocol, &[])
1245}
1246
1247fn build_error_response_with_fields(
1248 status: StatusCode,
1249 code: &str,
1250 message: &str,
1251 request_id: &str,
1252 protocol: AwsProtocol,
1253 extra_fields: &[(String, String)],
1254) -> Response<Body> {
1255 let (status, content_type, body) = match protocol {
1256 AwsProtocol::Query => {
1259 fakecloud_aws::error::xml_error_response(status, code, message, request_id)
1260 }
1261 AwsProtocol::Ec2Query => {
1266 fakecloud_aws::ec2query::ec2_error_response(status, code, message, request_id)
1267 }
1268 AwsProtocol::Rest => fakecloud_aws::error::s3_xml_error_response_with_fields(
1269 status,
1270 code,
1271 message,
1272 request_id,
1273 extra_fields,
1274 ),
1275 AwsProtocol::Json | AwsProtocol::RestJson => {
1276 fakecloud_aws::error::json_error_response_with_fields(
1277 status,
1278 code,
1279 message,
1280 extra_fields,
1281 )
1282 }
1283 };
1284
1285 let safe_code = sanitize_header_value(code);
1295 let safe_message = sanitize_header_value(message);
1296 let mut builder = Response::builder()
1297 .status(status)
1298 .header("content-type", content_type)
1299 .header("x-amzn-requestid", request_id)
1300 .header("x-amz-request-id", request_id);
1301 if let Ok(v) = http::HeaderValue::from_str(&safe_code) {
1302 builder = builder.header("x-amz-error-code", v);
1303 }
1304 if let Ok(v) = http::HeaderValue::from_str(&safe_message) {
1305 builder = builder.header("x-amz-error-message", v);
1306 }
1307 builder.body(Body::from(body)).unwrap_or_else(|_| {
1308 Response::new(Body::empty())
1312 })
1313}
1314
1315fn sanitize_header_value(s: &str) -> String {
1320 const MAX_LEN: usize = 1024;
1321 let mut out = String::with_capacity(s.len().min(MAX_LEN));
1322 for ch in s.chars() {
1323 if out.len() >= MAX_LEN {
1324 break;
1325 }
1326 if ch.is_control() {
1329 if !out.ends_with(' ') {
1330 out.push(' ');
1331 }
1332 } else {
1333 out.push(ch);
1334 }
1335 }
1336 out.trim().to_string()
1337}
1338
1339fn sigv2_presigned_access_key(query_params: &HashMap<String, String>) -> Option<String> {
1359 if query_params.contains_key("Signature") && query_params.contains_key("Expires") {
1360 query_params.get("AWSAccessKeyId").cloned()
1361 } else {
1362 None
1363 }
1364}
1365
1366fn is_hex_sha256(s: &str) -> bool {
1372 s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
1373}
1374
1375fn sha256_hex_lower(bytes: &[u8]) -> String {
1378 use sha2::{Digest, Sha256};
1379 let digest = Sha256::digest(bytes);
1380 const HEX: &[u8] = b"0123456789abcdef";
1381 let mut out = String::with_capacity(64);
1382 for b in digest {
1383 out.push(HEX[(b >> 4) as usize] as char);
1384 out.push(HEX[(b & 0x0f) as usize] as char);
1385 }
1386 out
1387}
1388
1389fn anonymous_s3_bucket(uri: &http::Uri, config: &DispatchConfig) -> Option<String> {
1390 let provider = config.resource_policy_provider.as_ref()?;
1391 let segment = uri.path().split('/').find(|s| !s.is_empty())?.to_string();
1392 let arn = format!("arn:aws:s3:::{segment}");
1393 provider.resource_owner_account("s3", &arn).map(|_| segment)
1394}
1395
1396fn build_condition_context(
1397 principal: &Principal,
1398 remote_addr: Option<SocketAddr>,
1399 region: &str,
1400 secure_transport: bool,
1401) -> ConditionContext {
1402 let now = chrono::Utc::now();
1403 ConditionContext {
1404 aws_username: aws_username_from_principal(principal),
1405 aws_userid: Some(principal.user_id.clone()),
1406 aws_principal_arn: Some(principal.arn.clone()),
1407 aws_principal_account: Some(principal.account_id.clone()),
1408 aws_principal_type: Some(principal_type_label(principal.principal_type).to_string()),
1409 aws_source_ip: remote_addr.map(|sa| sa.ip()),
1410 aws_current_time: Some(now),
1411 aws_epoch_time: Some(now.timestamp()),
1412 aws_secure_transport: Some(secure_transport),
1413 aws_requested_region: Some(region.to_string()),
1414 aws_mfa_present: None,
1420 aws_mfa_age_seconds: None,
1421 aws_called_via: Vec::new(),
1422 aws_source_vpce: None,
1423 aws_source_vpc: None,
1424 aws_vpc_source_ip: None,
1425 aws_federated_provider: None,
1426 aws_token_issue_time: None,
1427 service_keys: Default::default(),
1428 resource_tags: None,
1429 request_tags: None,
1430 principal_tags: None,
1431 }
1432}
1433
1434fn aws_username_from_principal(principal: &Principal) -> Option<String> {
1438 if principal.principal_type != PrincipalType::User {
1439 return None;
1440 }
1441 let after = principal.arn.rsplit_once(":user/").map(|(_, s)| s)?;
1442 Some(after.rsplit('/').next().unwrap_or(after).to_string())
1444}
1445
1446fn principal_type_label(t: PrincipalType) -> &'static str {
1449 match t {
1450 PrincipalType::User => "User",
1451 PrincipalType::AssumedRole => "AssumedRole",
1452 PrincipalType::FederatedUser => "FederatedUser",
1453 PrincipalType::Root => "Account",
1454 PrincipalType::Unknown => "Unknown",
1455 }
1456}
1457
1458fn is_secure_transport(headers: &http::HeaderMap) -> bool {
1464 headers
1465 .get("x-forwarded-proto")
1466 .and_then(|v| v.to_str().ok())
1467 .map(|s| s.eq_ignore_ascii_case("https"))
1468 .unwrap_or(false)
1469}
1470
1471trait ProtocolExt {
1472 fn error_status(&self) -> StatusCode;
1473}
1474
1475impl ProtocolExt for AwsProtocol {
1476 fn error_status(&self) -> StatusCode {
1477 StatusCode::BAD_REQUEST
1478 }
1479}
1480
1481#[cfg(test)]
1482mod tests {
1483 use super::*;
1484
1485 #[test]
1486 fn default_max_request_body_bytes_is_one_gib() {
1487 assert_eq!(DEFAULT_MAX_REQUEST_BODY_BYTES, 1024 * 1024 * 1024);
1491 }
1492
1493 #[test]
1494 fn sigv2_presigned_access_key_extracted_with_signature_and_expires() {
1495 let mut q = HashMap::new();
1496 q.insert("AWSAccessKeyId".to_string(), "AKIAEXAMPLE".to_string());
1497 q.insert("Signature".to_string(), "abc%2Bdef".to_string());
1498 q.insert("Expires".to_string(), "1700000000".to_string());
1499 assert_eq!(
1500 sigv2_presigned_access_key(&q).as_deref(),
1501 Some("AKIAEXAMPLE")
1502 );
1503 }
1504
1505 #[test]
1506 fn sigv2_presigned_access_key_none_without_signature_or_expires() {
1507 let mut q = HashMap::new();
1510 q.insert("AWSAccessKeyId".to_string(), "AKIAEXAMPLE".to_string());
1511 assert_eq!(sigv2_presigned_access_key(&q), None);
1512
1513 q.insert("Expires".to_string(), "1700000000".to_string());
1514 assert_eq!(
1515 sigv2_presigned_access_key(&q),
1516 None,
1517 "missing Signature must not qualify"
1518 );
1519 }
1520
1521 #[test]
1522 fn sigv2_presigned_access_key_none_for_unsigned_request() {
1523 assert_eq!(sigv2_presigned_access_key(&HashMap::new()), None);
1524 }
1525
1526 #[test]
1527 fn is_hex_sha256_accepts_real_digest_rejects_markers() {
1528 assert!(is_hex_sha256(&sha256_hex_lower(b"hello")));
1530 assert!(is_hex_sha256(
1531 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
1532 ));
1533 assert!(!is_hex_sha256("UNSIGNED-PAYLOAD"));
1535 assert!(!is_hex_sha256("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"));
1536 assert!(!is_hex_sha256("STREAMING-UNSIGNED-PAYLOAD-TRAILER"));
1537 assert!(!is_hex_sha256("abc123"));
1539 assert!(!is_hex_sha256(
1540 "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855"
1541 ));
1542 }
1543
1544 #[test]
1545 fn sha256_hex_lower_matches_known_vectors() {
1546 assert_eq!(
1548 sha256_hex_lower(b""),
1549 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
1550 );
1551 assert_eq!(
1552 sha256_hex_lower(b"abc"),
1553 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
1554 );
1555 assert_eq!(sha256_hex_lower(b"abc").len(), 64);
1556 }
1557
1558 #[test]
1559 fn dispatch_config_new_defaults_to_off() {
1560 let cfg = DispatchConfig::new("us-east-1", "123456789012");
1561 assert_eq!(cfg.region, "us-east-1");
1562 assert_eq!(cfg.account_id, "123456789012");
1563 assert!(!cfg.verify_sigv4);
1564 assert_eq!(cfg.iam_mode, IamMode::Off);
1565 }
1566
1567 #[test]
1568 fn aws_username_strips_iam_path_for_users() {
1569 let p = Principal {
1570 arn: "arn:aws:iam::123456789012:user/engineering/alice".into(),
1571 user_id: "AIDAALICE".into(),
1572 account_id: "123456789012".into(),
1573 principal_type: PrincipalType::User,
1574 source_identity: None,
1575 tags: None,
1576 };
1577 assert_eq!(aws_username_from_principal(&p), Some("alice".into()));
1578 }
1579
1580 #[test]
1581 fn aws_username_unset_for_assumed_role() {
1582 let p = Principal {
1583 arn: "arn:aws:sts::123456789012:assumed-role/ops/session".into(),
1584 user_id: "AROAOPS:session".into(),
1585 account_id: "123456789012".into(),
1586 principal_type: PrincipalType::AssumedRole,
1587 source_identity: None,
1588 tags: None,
1589 };
1590 assert_eq!(aws_username_from_principal(&p), None);
1591 }
1592
1593 #[test]
1594 fn principal_type_label_matches_aws_casing() {
1595 assert_eq!(principal_type_label(PrincipalType::User), "User");
1596 assert_eq!(
1597 principal_type_label(PrincipalType::AssumedRole),
1598 "AssumedRole"
1599 );
1600 assert_eq!(principal_type_label(PrincipalType::Root), "Account");
1601 }
1602
1603 #[test]
1604 fn build_condition_context_populates_global_keys() {
1605 let p = Principal {
1606 arn: "arn:aws:iam::123456789012:user/alice".into(),
1607 user_id: "AIDAALICE".into(),
1608 account_id: "123456789012".into(),
1609 principal_type: PrincipalType::User,
1610 source_identity: None,
1611 tags: None,
1612 };
1613 let addr: SocketAddr = "10.0.0.1:54321".parse().unwrap();
1614 let ctx = build_condition_context(&p, Some(addr), "us-east-1", false);
1615 assert_eq!(ctx.aws_username.as_deref(), Some("alice"));
1616 assert_eq!(ctx.aws_userid.as_deref(), Some("AIDAALICE"));
1617 assert_eq!(
1618 ctx.aws_principal_arn.as_deref(),
1619 Some("arn:aws:iam::123456789012:user/alice")
1620 );
1621 assert_eq!(ctx.aws_principal_account.as_deref(), Some("123456789012"));
1622 assert_eq!(ctx.aws_principal_type.as_deref(), Some("User"));
1623 assert_eq!(
1624 ctx.aws_source_ip.map(|i| i.to_string()).as_deref(),
1625 Some("10.0.0.1")
1626 );
1627 assert_eq!(ctx.aws_requested_region.as_deref(), Some("us-east-1"));
1628 assert_eq!(ctx.aws_secure_transport, Some(false));
1629 assert!(ctx.aws_current_time.is_some());
1630 assert!(ctx.aws_epoch_time.is_some());
1631 }
1632
1633 #[test]
1634 fn is_secure_transport_reads_x_forwarded_proto() {
1635 let mut headers = http::HeaderMap::new();
1636 headers.insert("x-forwarded-proto", "https".parse().unwrap());
1637 assert!(is_secure_transport(&headers));
1638 headers.insert("x-forwarded-proto", "http".parse().unwrap());
1639 assert!(!is_secure_transport(&headers));
1640 let empty = http::HeaderMap::new();
1641 assert!(!is_secure_transport(&empty));
1642 }
1643
1644 #[test]
1645 fn parse_account_from_arn_extracts_standard_shapes() {
1646 assert_eq!(
1647 parse_account_from_arn("arn:aws:sqs:us-east-1:123456789012:queue"),
1648 Some("123456789012".to_string())
1649 );
1650 assert_eq!(
1651 parse_account_from_arn("arn:aws:iam::123456789012:user/alice"),
1652 Some("123456789012".to_string())
1653 );
1654 }
1655
1656 #[test]
1657 fn parse_account_from_arn_returns_none_for_s3_empty_account() {
1658 assert_eq!(parse_account_from_arn("arn:aws:s3:::my-bucket"), None);
1660 assert_eq!(
1661 parse_account_from_arn("arn:aws:s3:::my-bucket/path/to/key"),
1662 None
1663 );
1664 }
1665
1666 #[test]
1667 fn parse_account_from_arn_returns_none_for_malformed() {
1668 assert_eq!(parse_account_from_arn(""), None);
1669 assert_eq!(parse_account_from_arn("not-an-arn"), None);
1670 assert_eq!(parse_account_from_arn("arn:aws:sqs:us-east-1"), None);
1671 assert_eq!(parse_account_from_arn("arn:aws:sqs"), None);
1672 }
1673
1674 #[test]
1675 fn extract_region_from_user_agent_finds_region_segment() {
1676 let mut headers = http::HeaderMap::new();
1677 headers.insert(
1678 "user-agent",
1679 "aws-sdk-rust/1.0 os/linux region/eu-central-1"
1680 .parse()
1681 .unwrap(),
1682 );
1683 assert_eq!(
1684 extract_region_from_user_agent(&headers),
1685 Some("eu-central-1".to_string())
1686 );
1687 }
1688
1689 #[test]
1690 fn extract_region_from_user_agent_none_without_header() {
1691 let headers = http::HeaderMap::new();
1692 assert_eq!(extract_region_from_user_agent(&headers), None);
1693 }
1694
1695 #[test]
1696 fn extract_region_from_user_agent_ignores_empty_region() {
1697 let mut headers = http::HeaderMap::new();
1698 headers.insert("user-agent", "aws-sdk-java region/".parse().unwrap());
1699 assert_eq!(extract_region_from_user_agent(&headers), None);
1700 }
1701
1702 #[test]
1703 fn extract_region_from_user_agent_none_when_no_region_marker() {
1704 let mut headers = http::HeaderMap::new();
1705 headers.insert("user-agent", "curl/7.79.1".parse().unwrap());
1706 assert_eq!(extract_region_from_user_agent(&headers), None);
1707 }
1708
1709 #[test]
1710 fn aws_username_none_for_root() {
1711 let p = Principal {
1712 arn: "arn:aws:iam::123456789012:root".into(),
1713 user_id: "123456789012".into(),
1714 account_id: "123456789012".into(),
1715 principal_type: PrincipalType::Root,
1716 source_identity: None,
1717 tags: None,
1718 };
1719 assert_eq!(aws_username_from_principal(&p), None);
1720 }
1721
1722 #[test]
1723 fn aws_username_bare_no_path() {
1724 let p = Principal {
1725 arn: "arn:aws:iam::123456789012:user/bob".into(),
1726 user_id: "AIDABOB".into(),
1727 account_id: "123456789012".into(),
1728 principal_type: PrincipalType::User,
1729 source_identity: None,
1730 tags: None,
1731 };
1732 assert_eq!(aws_username_from_principal(&p), Some("bob".into()));
1733 }
1734
1735 #[test]
1736 fn principal_type_label_covers_federated_and_unknown() {
1737 assert_eq!(
1738 principal_type_label(PrincipalType::FederatedUser),
1739 "FederatedUser"
1740 );
1741 assert_eq!(principal_type_label(PrincipalType::Unknown), "Unknown");
1742 }
1743
1744 #[test]
1745 fn build_condition_context_marks_secure_when_flag_set() {
1746 let p = Principal {
1747 arn: "arn:aws:iam::123456789012:user/alice".into(),
1748 user_id: "AIDAALICE".into(),
1749 account_id: "123456789012".into(),
1750 principal_type: PrincipalType::User,
1751 source_identity: None,
1752 tags: None,
1753 };
1754 let ctx = build_condition_context(&p, None, "us-west-2", true);
1755 assert_eq!(ctx.aws_secure_transport, Some(true));
1756 assert!(ctx.aws_source_ip.is_none());
1757 assert_eq!(ctx.aws_requested_region.as_deref(), Some("us-west-2"));
1758 }
1759
1760 #[test]
1761 fn is_secure_transport_case_insensitive() {
1762 let mut headers = http::HeaderMap::new();
1763 headers.insert("x-forwarded-proto", "HTTPS".parse().unwrap());
1764 assert!(is_secure_transport(&headers));
1765 }
1766
1767 #[test]
1768 fn is_secure_transport_non_ascii_bytes_false() {
1769 let mut headers = http::HeaderMap::new();
1770 headers.insert(
1771 "x-forwarded-proto",
1772 http::HeaderValue::from_bytes(&[0xFF, 0xFE]).unwrap(),
1773 );
1774 assert!(!is_secure_transport(&headers));
1775 }
1776
1777 #[test]
1778 fn protocol_ext_error_status_is_bad_request() {
1779 assert_eq!(AwsProtocol::Query.error_status(), StatusCode::BAD_REQUEST);
1780 assert_eq!(AwsProtocol::Json.error_status(), StatusCode::BAD_REQUEST);
1781 assert_eq!(AwsProtocol::Rest.error_status(), StatusCode::BAD_REQUEST);
1782 assert_eq!(
1783 AwsProtocol::RestJson.error_status(),
1784 StatusCode::BAD_REQUEST
1785 );
1786 }
1787
1788 #[test]
1789 fn build_error_response_json_has_json_content_type() {
1790 let resp = build_error_response(
1791 StatusCode::BAD_REQUEST,
1792 "TestCode",
1793 "test msg",
1794 "req-1",
1795 AwsProtocol::Json,
1796 );
1797 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1798 let ct = resp
1799 .headers()
1800 .get("content-type")
1801 .unwrap()
1802 .to_str()
1803 .unwrap();
1804 assert!(ct.contains("json"));
1805 let rid = resp
1806 .headers()
1807 .get("x-amzn-requestid")
1808 .unwrap()
1809 .to_str()
1810 .unwrap();
1811 assert_eq!(rid, "req-1");
1812 }
1813
1814 #[test]
1815 fn build_error_response_rest_returns_xml_content_type() {
1816 let resp = build_error_response(
1817 StatusCode::NOT_FOUND,
1818 "NoSuchBucket",
1819 "bucket missing",
1820 "req-2",
1821 AwsProtocol::Rest,
1822 );
1823 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1824 let ct = resp
1825 .headers()
1826 .get("content-type")
1827 .unwrap()
1828 .to_str()
1829 .unwrap();
1830 assert!(ct.contains("xml"));
1831 }
1832
1833 #[test]
1834 fn build_error_response_query_returns_xml() {
1835 let resp = build_error_response(
1836 StatusCode::BAD_REQUEST,
1837 "InvalidParameter",
1838 "bad param",
1839 "req-3",
1840 AwsProtocol::Query,
1841 );
1842 let ct = resp
1843 .headers()
1844 .get("content-type")
1845 .unwrap()
1846 .to_str()
1847 .unwrap();
1848 assert!(ct.contains("xml"));
1849 }
1850
1851 #[test]
1856 fn build_error_response_with_multiline_message_does_not_panic() {
1857 let resp = build_error_response(
1858 StatusCode::INTERNAL_SERVER_ERROR,
1859 "ServiceException",
1860 "Lambda execution failed: container failed to start: docker start failed: \
1861 Error: unable to start container \"abc\": \
1862 failed to create new hosts file:\nhost-gateway is empty\n",
1863 "req-multi",
1864 AwsProtocol::Json,
1865 );
1866 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1867 let msg = resp
1868 .headers()
1869 .get("x-amz-error-message")
1870 .expect("x-amz-error-message must be set even when input contains newlines")
1871 .to_str()
1872 .unwrap();
1873 assert!(!msg.contains('\n'));
1874 assert!(!msg.contains('\r'));
1875 assert!(msg.contains("Lambda execution failed"));
1876 assert!(msg.contains("host-gateway is empty"));
1877 }
1878
1879 #[test]
1880 fn build_error_response_with_control_chars_strips_them() {
1881 let resp = build_error_response(
1882 StatusCode::BAD_REQUEST,
1883 "Code\twith\ttabs",
1884 "msg\x00with\x01nulls",
1885 "req-ctrl",
1886 AwsProtocol::Json,
1887 );
1888 let code = resp
1889 .headers()
1890 .get("x-amz-error-code")
1891 .unwrap()
1892 .to_str()
1893 .unwrap();
1894 let msg = resp
1895 .headers()
1896 .get("x-amz-error-message")
1897 .unwrap()
1898 .to_str()
1899 .unwrap();
1900 assert!(!code.contains('\t'));
1901 assert!(!msg.contains('\x00'));
1902 assert!(!msg.contains('\x01'));
1903 }
1904
1905 #[test]
1906 fn sanitize_header_value_truncates_long_input() {
1907 let huge = "x".repeat(5_000);
1908 let out = sanitize_header_value(&huge);
1909 assert!(out.len() <= 1024);
1910 }
1911
1912 #[test]
1913 fn sanitize_header_value_collapses_consecutive_control_runs() {
1914 let out = sanitize_header_value("a\n\n\n\rb");
1915 assert_eq!(out, "a b");
1916 }
1917
1918 #[test]
1919 fn dispatch_config_carries_opt_in_flags() {
1920 let cfg = DispatchConfig {
1921 region: "eu-west-1".to_string(),
1922 account_id: "000000000000".to_string(),
1923 verify_sigv4: true,
1924 iam_mode: IamMode::Strict,
1925 credential_resolver: None,
1926 policy_evaluator: None,
1927 resource_policy_provider: None,
1928 scp_resolver: None,
1929 };
1930 assert!(cfg.verify_sigv4);
1931 assert!(cfg.iam_mode.is_strict());
1932 assert!(cfg.resource_policy_provider.is_none());
1933 assert!(cfg.scp_resolver.is_none());
1934 }
1935
1936 fn s3_sigv4_headers() -> http::HeaderMap {
1937 let mut headers = http::HeaderMap::new();
1938 headers.insert(
1939 "authorization",
1940 "AWS4-HMAC-SHA256 Credential=test/20240101/us-east-1/s3/aws4_request, \
1941 SignedHeaders=host, Signature=fake"
1942 .parse()
1943 .unwrap(),
1944 );
1945 headers
1946 }
1947
1948 #[test]
1949 fn streaming_route_path_style_s3_put_object() {
1950 let headers = s3_sigv4_headers();
1951 assert_eq!(
1952 streaming_route(
1953 &http::Method::PUT,
1954 "/my-bucket/key.txt",
1955 &headers,
1956 &HashMap::new(),
1957 ),
1958 Some(("s3", "")),
1959 );
1960 }
1961
1962 #[test]
1963 fn streaming_route_path_style_create_bucket_skipped() {
1964 let headers = s3_sigv4_headers();
1967 assert_eq!(
1968 streaming_route(&http::Method::PUT, "/my-bucket", &headers, &HashMap::new(),),
1969 None,
1970 );
1971 }
1972
1973 #[test]
1974 fn streaming_route_virtual_hosted_s3_put_object() {
1975 let mut headers = s3_sigv4_headers();
1976 headers.insert(
1977 "host",
1978 "vhost-bucket.s3.us-east-1.localhost.localstack.cloud:4566"
1979 .parse()
1980 .unwrap(),
1981 );
1982 assert_eq!(
1987 streaming_route(&http::Method::PUT, "/hello.txt", &headers, &HashMap::new(),),
1988 Some(("s3", "")),
1989 );
1990 }
1991
1992 #[test]
1993 fn streaming_route_virtual_hosted_s3_root_skipped() {
1994 let mut headers = s3_sigv4_headers();
1997 headers.insert(
1998 "host",
1999 "vhost-bucket.s3.us-east-1.localhost.localstack.cloud:4566"
2000 .parse()
2001 .unwrap(),
2002 );
2003 assert_eq!(
2004 streaming_route(&http::Method::PUT, "/", &headers, &HashMap::new()),
2005 None,
2006 );
2007 }
2008
2009 #[test]
2010 fn streaming_route_ecr_blob_upload() {
2011 let headers = http::HeaderMap::new();
2012 assert_eq!(
2013 streaming_route(
2014 &http::Method::PATCH,
2015 "/v2/my-repo/blobs/uploads/abcd1234",
2016 &headers,
2017 &HashMap::new(),
2018 ),
2019 Some(("ecr", "")),
2020 );
2021 assert_eq!(
2022 streaming_route(
2023 &http::Method::PUT,
2024 "/v2/my-repo/blobs/uploads/abcd1234",
2025 &headers,
2026 &HashMap::new(),
2027 ),
2028 Some(("ecr", "")),
2029 );
2030 }
2031
2032 #[test]
2033 fn streaming_route_presigned_v4_s3_put() {
2034 let headers = http::HeaderMap::new();
2035 let mut query_params = HashMap::new();
2036 query_params.insert(
2037 "X-Amz-Credential".to_string(),
2038 "test/20240101/us-east-1/s3/aws4_request".to_string(),
2039 );
2040 assert_eq!(
2041 streaming_route(
2042 &http::Method::PUT,
2043 "/my-bucket/key.txt",
2044 &headers,
2045 &query_params,
2046 ),
2047 Some(("s3", "")),
2048 );
2049 }
2050
2051 #[test]
2052 fn streaming_route_non_s3_auth_header_skipped() {
2053 let mut headers = http::HeaderMap::new();
2056 headers.insert(
2057 "authorization",
2058 "AWS4-HMAC-SHA256 Credential=test/20240101/us-east-1/lambda/aws4_request, \
2059 SignedHeaders=host, Signature=fake"
2060 .parse()
2061 .unwrap(),
2062 );
2063 assert_eq!(
2064 streaming_route(
2065 &http::Method::PUT,
2066 "/my-bucket/key.txt",
2067 &headers,
2068 &HashMap::new(),
2069 ),
2070 None,
2071 );
2072 }
2073
2074 #[test]
2075 fn streaming_route_get_skipped() {
2076 let headers = s3_sigv4_headers();
2077 assert_eq!(
2078 streaming_route(
2079 &http::Method::GET,
2080 "/my-bucket/key.txt",
2081 &headers,
2082 &HashMap::new(),
2083 ),
2084 None,
2085 );
2086 }
2087}