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