Skip to main content

fakecloud_core/
dispatch.rs

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
18/// The main dispatch handler. All HTTP requests come through here.
19pub 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    // Streaming opt-in: if the route is a known large-body S3 / ECR
32    // upload, we skip the buffered `to_bytes` step entirely and hand
33    // the raw body to the service handler. The handler spills it to
34    // disk on the fly. Header-only detection covers every streaming
35    // candidate (none of them rely on form-body sniffing).
36    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        // Header-only detection agrees with the URL match — covers S3
45        // PUT object (SigV4 service=s3 in Authorization).
46        (Some(sr), Some(detected)) if sr.0 == detected.service => Some(detected.clone()),
47        // ECR OCI v2 blob upload has no AWS auth header; the path
48        // alone (`/v2/.../blobs/uploads/...`) tells us the route is
49        // ECR. Synthesize a DetectedRequest so dispatch picks the
50        // streaming path. Same special-case the buffered branch
51        // applies on detect_service None (see below).
52        (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        // Buffered path: materialize the body into memory under the
64        // configured cap. `FAKECLOUD_MAX_REQUEST_BODY_BYTES` (default
65        // 1 GiB) caps non-streaming requests; streaming routes have no
66        // cap because nothing materializes the entire body in RAM.
67        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    // Detect service and action
83    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                // A request carrying X-Amz-Target is unambiguously an awsJson
90                // call whose operation we couldn't map to a known service. AWS
91                // answers these with UnknownOperationException; routing them to
92                // the apigateway catch-all below would 404 with a misleading
93                // "Stage not found" instead.
94                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                // OPTIONS requests (CORS preflight) don't carry Authorization headers.
108                // Route them to S3 since S3 is the only REST service that handles CORS.
109                // Note: API Gateway CORS preflight is not fully supported in this emulator
110                // because we can't distinguish between S3 and API Gateway OPTIONS requests
111                // without additional context (in real AWS, they have different domains).
112                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                    // OCI Distribution v2 protocol. Docker CLI / OCI clients
120                    // use Basic auth (not SigV4) and GET /v2/ with no body,
121                    // so this must be matched before the apigateway fallback.
122                    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                    // Unsigned request whose first path segment names an
129                    // existing S3 bucket: an anonymous path-style S3 access
130                    // (e.g. serving a public-read object to a browser). Without
131                    // this it would fall through to the apigateway catch-all
132                    // below and 404 with "Stage not found" (#1707). Authorization
133                    // for the anonymous caller still runs in the IAM block.
134                    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                    // Requests without AWS auth that don't match any service might be
142                    // API Gateway execute API calls (plain HTTP without signatures).
143                    // Route them to apigateway service which will validate if a matching
144                    // API/stage exists. Skip special FakeCloud endpoints (/_*).
145                    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    // Bedrock-agent and bedrock-runtime both send `bedrock` in the SigV4
164    // credential scope, but bedrock-agent has its own service handler.
165    // Disambiguate based on the request path.
166    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            // Further disambiguate runtime vs control plane for agents/flows paths
186            let segs: Vec<&str> = parts.uri.path().split('/').collect();
187            let is_runtime = matches!(
188                segs.as_slice(),
189                ["", "agents", _, "agentAliases", _, ..]  // InvokeAgent
190                    | ["", "flows", _, "aliases", _]   // InvokeFlow
191                    | ["", "knowledgebases", _, "retrieve"] // Retrieve
192                    | ["", "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    // Amazon DocumentDB shares RDS's Query wire protocol, `rds` SigV4
219    // signing scope, and `rds.<region>.amazonaws.com` endpoint, so a real
220    // `aws-sdk-docdb` request is indistinguishable from `aws-sdk-rds` by
221    // signing name or host alone. The DocumentDB SDK does stamp an
222    // `api/docdb` token into its `user-agent`; use it to route the request
223    // to the dedicated `docdb` handler. (The conformance probe signs the
224    // `docdb` scope directly, so it never reaches this branch.) Requests
225    // without the token stay on `rds`.
226    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    // Amazon Neptune shares RDS's Query wire protocol, `rds` SigV4 signing
236    // scope, and `rds.<region>.amazonaws.com` endpoint, so a real
237    // `aws-sdk-neptune` request is indistinguishable from `aws-sdk-rds` by
238    // signing name or host alone. The Neptune SDK does stamp an
239    // `api/neptune` token into its `user-agent`; use it to route the request
240    // to the dedicated `neptune` handler. (The conformance probe signs the
241    // `neptune` scope directly, so it never reaches this branch.) Requests
242    // without the token stay on `rds`.
243    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    // Look up service
253    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    // Extract region and access key from auth header (or presigned query).
267    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        // Presigned URL: credentials live in the query string.
275        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    // SigV2 presigned URLs (`AWSAccessKeyId` + `Signature` + `Expires` query
281    // parameters) carry the access key outside the SigV4 grammar, so the SigV4
282    // parsers above return None. Recover the key here so a SigV2-presigned
283    // request is attributed to its caller instead of being treated as
284    // anonymous (which would deny it under the object read auth gate).
285    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    // Host-header routing hint: LocalStack-shaped
291    // `<svc>.<region>.localhost.localstack.cloud[:port]`, real-AWS
292    // `<svc>.<region>.amazonaws.com`, and every S3 virtual-hosted variant
293    // of both. Secondary region source and carries the bucket for
294    // virtual-hosted S3 path rewrite.
295    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    // Resolve the caller's principal up front so both SigV4 verification
304    // (which needs the secret) and the service handler (which needs the
305    // identity for GetCallerIdentity and IAM enforcement) share a single
306    // lookup. The root-bypass AKID skips resolution entirely — `test`
307    // credentials have no backing identity and must always pass.
308    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    // Opt-in SigV4 cryptographic verification. Runs before the service
324    // handler so a failing signature never reaches business logic. The
325    // reserved `test*` root identity short-circuits verification to keep
326    // local-dev workflows frictionless.
327    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    // Build path segments. For S3 virtual-hosted-style requests the bucket
432    // lives in the Host header, not the path — prepend it so the S3 handler
433    // sees a uniform path-style request. SigV4 verification above already
434    // ran against the wire path, so this rewrite is signature-safe.
435    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    // For JSON protocol, validate that non-empty bodies are valid JSON
461    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    // Merge query params with form body params for the Query family (awsQuery
475    // and ec2Query share identical form-encoded request bodies).
476    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    // CloudWatch (`monitoring`) advertises awsJson1_0 alongside awsQuery. Its
488    // handlers all read the flat awsQuery param map, so when a client uses the
489    // JSON protocol we flatten the JSON body into that same map, leaving the
490    // handlers unchanged. The handler emits a JSON response for JSON callers.
491    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    // Opt-in IAM identity-policy enforcement. Runs before the service
531    // handler so a deny never reaches business logic. Root principals
532    // (both `test*` bypass AKIDs and the account's IAM root) are exempt,
533    // matching AWS behavior. Services that haven't opted in via
534    // `iam_enforceable()` are transparently skipped — the startup log
535    // lists which services are under enforcement so users always know.
536    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                        // F3 keys riding on the resolved credential. STS
551                        // populates these at mint time so subsequent
552                        // requests under the credential can be evaluated
553                        // against `aws:MultiFactorAuthPresent`,
554                        // `aws:MultiFactorAuthAge`, `aws:TokenIssueTime`,
555                        // and `aws:FederatedProvider`. IAM user access
556                        // keys carry none of these, matching AWS.
557                        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                            // `aws:MultiFactorAuthAge` is "seconds since
563                            // MFA was asserted" — computed at evaluation
564                            // time from the token issue moment so the
565                            // value increases monotonically as the session
566                            // ages. Only set when the session was actually
567                            // minted with MFA; otherwise the key is
568                            // absent, matching AWS.
569                            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                        // ABAC: populate tag-based condition keys.
583                        // aws:ResourceTag/*
584                        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                        // aws:RequestTag/* + aws:TagKeys
594                        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                        // aws:PrincipalTag/*
604                        condition_context.principal_tags = principal.tags.clone();
605
606                        // Phase 2: fetch the resource-based policy (if
607                        // any) attached to the target resource and
608                        // pass it to the evaluator alongside the
609                        // principal's identity policies. The resource's
610                        // owning account is parsed from the ARN (#381
611                        // multi-account alignment); S3 ARNs have an
612                        // empty account field, so we fall back to the
613                        // server's configured account ID in that case.
614                        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                        // Derive the resource-owning account. Prefer a provider
619                        // lookup (S3 ARNs carry no account, so the bucket's
620                        // owner is resolved from state — without this, account
621                        // A reaching account B's bucket would be mis-read as
622                        // same-account and skip B's bucket-policy requirement,
623                        // bug-audit 2026-05-28, 5.3), then fall back to the
624                        // account embedded in the ARN (SQS/SNS/Lambda/…), then
625                        // to the caller's account for wildcard / unscoped
626                        // actions (ListQueues, GetCallerIdentity).
627                        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                        // SCP ceiling: resolve the inherited SCP chain
636                        // for this principal (management accounts and
637                        // service-linked roles come back as `None`, in
638                        // which case the evaluator treats the layer as
639                        // absent). Audit breadcrumbs emitted by the
640                        // resolver itself, not here.
641                        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                                // Real AWS includes an "Encoded
669                                // authorization failure message" suffix
670                                // on AccessDeniedException — an opaque
671                                // base64+zlib JSON blob that the caller
672                                // can pass to STS
673                                // `DecodeAuthorizationMessage` to
674                                // recover the structured deny reason
675                                // (action, principal, matched
676                                // statements, condition context). We
677                                // produce the same blob inline so
678                                // existing tooling that decodes deny
679                                // reasons works against fakecloud.
680                                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                            // Soft mode: audit log already emitted; fall
717                            // through to the handler.
718                        }
719                    } else {
720                        // Service opted in via `iam_enforceable()` but its
721                        // `iam_action_for` returned no `IamAction` for this
722                        // specific operation (e.g. S3's `s3_detect_action`
723                        // has `_ => return None` arms for unrecognized
724                        // sub-resources). Under strict enforcement that must
725                        // fail closed: an operation we cannot map to an IAM
726                        // action cannot be authorized, so serving it would be
727                        // a fail-open bypass of `--iam strict`. Deny by
728                        // default. In soft mode we preserve the historical
729                        // warn-and-allow so an incomplete mapping surfaces
730                        // during rollout without blocking traffic.
731                        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                        // Soft mode: audit log emitted; fall through to the
752                        // handler.
753                    }
754                }
755            } else if aws_request.access_key_id.is_none() {
756                // Truly anonymous (unsigned) caller — no Authorization header at
757                // all. No identity policies exist, so authorization rests
758                // entirely on the resource policy (a bucket policy granting
759                // `Principal:"*"`) and public-read ACLs — mirroring AWS, which
760                // denies anonymous requests unless the resource is explicitly
761                // made public. Without this an anonymous request that reached an
762                // iam_enforceable service in enforcement mode would bypass
763                // authorization entirely.
764                //
765                // A request that carried an Authorization header but whose
766                // credential did not resolve (principal `None` with
767                // `access_key_id` `Some`) is intentionally left alone here: with
768                // SigV4 verification off, fakecloud does not reject unverified
769                // signed requests, and turning them into anonymous denials would
770                // change long-standing behavior.
771                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                    // An explicit Deny in the resource policy always wins, even
794                    // over a public-read ACL — matching AWS's Deny-overrides
795                    // precedence. Collapsing the decision to a bool and ORing the
796                    // ACL let a public ACL override an explicit anonymous Deny.
797                    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                        // Soft mode: audit log emitted; fall through to the handler.
828                    }
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/// Configuration passed to the dispatch handler.
896#[derive(Clone)]
897pub struct DispatchConfig {
898    pub region: String,
899    pub account_id: String,
900    /// Whether to cryptographically verify SigV4 signatures on incoming
901    /// requests. Wired through from `--verify-sigv4` /
902    /// `FAKECLOUD_VERIFY_SIGV4`. Off by default.
903    pub verify_sigv4: bool,
904    /// IAM policy evaluation mode. Wired through from `--iam` /
905    /// `FAKECLOUD_IAM`. Defaults to [`IamMode::Off`]. Actual evaluation is
906    /// added in a later batch; today this field is plumbed but never
907    /// consulted.
908    pub iam_mode: IamMode,
909    /// Resolves access key IDs to their secrets and owning principals.
910    /// Required when `verify_sigv4` or `iam_mode != Off`. When `None`, both
911    /// features gracefully degrade to off-by-default behavior.
912    pub credential_resolver: Option<Arc<dyn CredentialResolver>>,
913    /// Evaluates IAM identity policies for a resolved principal + action.
914    /// Required when `iam_mode != Off`. When `None`, enforcement silently
915    /// degrades to off even if `iam_mode` is set.
916    pub policy_evaluator: Option<Arc<dyn IamPolicyEvaluator>>,
917    /// Resolves resource-based policies (S3 bucket policies in the
918    /// initial rollout) to hand to the evaluator alongside the
919    /// principal's identity policies. `None` means the server was
920    /// started without any resource-policy-owning service registered;
921    /// dispatch then behaves as if no resource policy is attached to
922    /// any resource, identical to the Phase 1 behavior.
923    pub resource_policy_provider: Option<Arc<dyn ResourcePolicyProvider>>,
924    /// Resolves the ordered SCP chain that applies to a principal's
925    /// account (root-OU first, account-direct last). `None` means no
926    /// organizations resolver has been registered — SCPs never gate
927    /// any request in that case. Off-by-default matches the Batch 4
928    /// contract: zero behavior change until a user calls
929    /// `CreateOrganization` and the resolver is wired.
930    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    /// Minimal constructor for tests and call sites that don't care about the
971    /// opt-in security features.
972    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
986/// Extract the 12-digit account ID segment from an AWS ARN.
987///
988/// ARNs follow `arn:<partition>:<service>:<region>:<account>:<resource>`.
989/// Identifies routes that opt into streaming request bodies. Returns
990/// `Some((service, action_hint))` when the dispatch path should hand
991/// the raw body to the service handler unbuffered, otherwise `None`
992/// for the default buffered path. The handler reads the stream via
993/// [`crate::service::AwsRequest::take_body_stream`].
994///
995/// Streaming-eligible routes today:
996///
997/// * `s3` PUT object — `PUT /<bucket>/<key>` with a SigV4 (or
998///   presigned) auth header. Covers PutObject, UploadPart, and
999///   UploadPartCopy. The S3 service spills to disk via
1000///   [`fakecloud_persistence::BodySource::File`] when the stream is
1001///   present.
1002/// * `ecr` OCI Distribution v2 blob upload — `PATCH` and `PUT` on
1003///   `/v2/{name}/blobs/uploads/{uuid}`. The ECR service spools the
1004///   stream into a per-upload temp file before computing the digest.
1005fn 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    // ECR OCI v2 blob upload (PATCH chunk + final PUT).
1012    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    // S3 PutObject / UploadPart / UploadPartCopy. Detect either via
1020    // SigV4 service field in the Authorization header OR via a SigV4
1021    // presigned URL (X-Amz-Credential .../s3/...) OR a SigV2 presigned
1022    // URL (AWSAccessKeyId + Signature + Expires query parameters).
1023    if method == http::Method::PUT {
1024        let after = path.trim_start_matches('/');
1025        // Path-style PutObject is `PUT /<bucket>/<key>` (path contains a
1026        // slash); virtual-hosted-style is `PUT /<key>` with the bucket
1027        // in the Host header. For virtual-hosted, accept any non-empty
1028        // path so the key flows through the streaming dispatch — the
1029        // Host parser already routed this request to S3.
1030        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
1058/// Default request-body buffering cap. fakecloud reads the entire
1059/// request body into memory before handing it to a service handler,
1060/// so this ceiling caps RAM usage per in-flight request.
1061///
1062/// Default 1 GiB — comfortably above legitimate single S3 PutObject
1063/// payloads (AWS recommends multipart above ~100 MiB) and each
1064/// multipart part dispatches through here separately. Override with
1065/// `FAKECLOUD_MAX_REQUEST_BODY_BYTES` (decimal bytes) when running
1066/// stress tests that push past the default.
1067const DEFAULT_MAX_REQUEST_BODY_BYTES: usize = 1024 * 1024 * 1024;
1068
1069/// The server-wide buffered request body cap in bytes, from
1070/// `FAKECLOUD_MAX_REQUEST_BODY_BYTES` (default 1 GiB). Public so buffered
1071/// sub-proxies (e.g. the CloudFront viewer data plane) apply the SAME cap as
1072/// direct traffic rather than an inconsistent limit of their own.
1073pub 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
1084/// For the cross-account decision in IAM enforcement, the "resource
1085/// account" is the ARN's account segment. Some services (notably S3)
1086/// produce ARNs with an empty account field — for those we return
1087/// `None` and let the caller fall back to the server's configured
1088/// account ID. Malformed or non-ARN strings also return `None`.
1089fn 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    // Resource segment must exist (parts.next().is_some()) for the ARN
1099    // to be well-formed, but we don't consume its value here.
1100    parts.next()?;
1101    if account.is_empty() {
1102        None
1103    } else {
1104        Some(account.to_string())
1105    }
1106}
1107
1108/// Whether the request's `user-agent` (or `x-amz-user-agent`) carries the
1109/// `api/neptune` SDK-metadata token the `aws-sdk-neptune` client stamps in.
1110/// Used to disambiguate Neptune from RDS, which share the `rds` SigV4 scope
1111/// and endpoint. Matches the `api/neptune` token that AWS SDKs emit (a
1112/// leading `api/neptune` optionally followed by `#`/`/` and a version).
1113fn 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
1128/// Extract region from User-Agent header suffix `region/<region>`.
1129/// Whether the request's `user-agent` (or `x-amz-user-agent`) carries the
1130/// `api/docdb` SDK-metadata token the `aws-sdk-docdb` client stamps in. Used
1131/// to disambiguate DocumentDB from RDS, which share the `rds` SigV4 scope
1132/// and endpoint. Matches the `api/docdb` token that AWS SDKs emit (a leading
1133/// `api/docdb` optionally followed by `#`/`/` and a version).
1134fn 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        // awsQuery services (SQS, SNS, IAM, STS, RDS, ELBv2, CloudWatch,
1181        // AutoScaling, ...) share the `<ErrorResponse>` envelope.
1182        AwsProtocol::Query => {
1183            fakecloud_aws::error::xml_error_response(status, code, message, request_id)
1184        }
1185        // EC2 uses the distinct ec2Query error envelope
1186        // (`<Response><Errors><Error>...</Errors><RequestID>`). Only EC2 is
1187        // classified `Ec2Query`, so the other Query-protocol services above are
1188        // untouched.
1189        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    // S3 (and other REST-XML services) place the error code in
1210    // `x-amz-error-code` so HEAD responses — which HTTP forbids from
1211    // carrying a body — still surface the code. AWS SDKs read this header
1212    // when the body is empty. Emit it on every error response so HEAD,
1213    // OPTIONS, and any client that strips the body still see the code.
1214    // Backend errors regularly include newlines (multi-line stderr from
1215    // docker/podman/etc.); HTTP header values reject control characters,
1216    // so sanitize before insertion or the builder rejects the response
1217    // and the connection drops.
1218    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        // Builder only fails if a header is invalid; we sanitized the two
1233        // we control, so the remaining ones (content-type, request id) are
1234        // ASCII and safe. This fallback exists purely so we never panic.
1235        Response::new(Body::empty())
1236    })
1237}
1238
1239/// Strip characters that HTTP header values reject (control bytes, CR/LF/TAB)
1240/// and truncate to a length that AWS SDKs handle cleanly. Backend tools
1241/// (docker, podman, kubectl, …) emit multi-line stderr, and forwarding that
1242/// raw into `x-amz-error-message` previously panicked the dispatcher.
1243fn 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        // Header values forbid CR, LF, and other control bytes (RFC 9110).
1251        // Replace with a single space so multi-line messages stay readable.
1252        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
1263/// Build the [`ConditionContext`] passed to the IAM evaluator for one
1264/// request. Populates the 10 global condition keys from the resolved
1265/// principal + the HTTP request. Service-specific keys are deferred to
1266/// a follow-up batch and left empty.
1267/// For an unsigned request that no other detection rule claimed, return the
1268/// bucket name when the first path segment names an existing S3 bucket.
1269///
1270/// fakecloud serves every service from one endpoint, so an anonymous
1271/// path-style S3 request (`GET /bucket/key`, no SigV4) is indistinguishable
1272/// from an API Gateway execute-api call by headers alone. Bucket existence is
1273/// the disambiguator: if the segment is a real bucket, route to S3; otherwise
1274/// fall through to the apigateway catch-all. Uses the already-wired
1275/// `resource_policy_provider`, which resolves S3 bucket ownership from state
1276/// (`Some` => the bucket exists). Returns `None` when no provider is wired.
1277/// Recover the access key from a SigV2 presigned URL. AWS SigV2 presigning
1278/// puts the key in the `AWSAccessKeyId` query parameter alongside `Signature`
1279/// and `Expires`; all three must be present for the URL to be a SigV2 presign.
1280/// Returns None for SigV4 presigns (which use `X-Amz-Credential`) or unsigned
1281/// requests.
1282fn 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        // F3 keys: populated from the caller's session context when STS
1316        // mints credentials with MFA / SAML / OIDC / VPC-endpoint hints.
1317        // Default-None here so tests/dispatch sites that don't set them
1318        // safe-fail any policy referencing them — matching AWS for keys
1319        // that aren't asserted.
1320        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
1335/// `aws:username` is only set for IAM users, matching AWS. For assumed
1336/// roles, federated users, root, and unknown principals the key is
1337/// absent — operators that reference it without `IfExists` safe-fail.
1338fn 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    // Strip any IAM path prefix; bare username is the last segment.
1344    Some(after.rsplit('/').next().unwrap_or(after).to_string())
1345}
1346
1347/// AWS's `aws:PrincipalType` uses PascalCase identifiers, distinct from
1348/// the lowercase ones [`PrincipalType::as_str`] returns for ARNs.
1349fn 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
1359/// Best-effort detection of TLS-terminated requests. Direct HTTPS
1360/// connections are not yet supported by the fakecloud server (it speaks
1361/// plain HTTP), so the only signal is an `x-forwarded-proto: https`
1362/// header set by an upstream proxy. Anything else evaluates to `false`,
1363/// which matches the typical local-dev setup.
1364fn 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        // Without the env override, the cap defaults to 1 GiB. The
1389        // public function caches via OnceLock so only the first call
1390        // in the process matters; we assert the constant directly.
1391        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        // AWSAccessKeyId alone (e.g. a stray query param) is not a SigV2
1409        // presign and must not be treated as a credential.
1410        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        // S3 ARNs have both region and account empty.
1528        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    /// Regression for issue #1539: multi-line backend errors (e.g. podman
1721    /// stderr) used to panic the dispatcher when stuffed into the
1722    /// `x-amz-error-message` HTTP header. The response must build cleanly
1723    /// and the header value must not contain control characters.
1724    #[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        // `PUT /bucket` (no trailing key) is CreateBucket — must NOT
1834        // hit the streaming path.
1835        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        // Virtual-hosted PUT has no bucket in the URL path (`/<key>`),
1852        // so the slash check used for path-style would reject it. The
1853        // Host parser confirms this is virtual-hosted S3 and the key
1854        // flows through the streaming dispatch.
1855        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        // `PUT /` against a virtual-hosted Host = CreateBucket, which
1864        // is handled buffered. Empty path-after-slash must short-circuit.
1865        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        // Same path shape but the SigV4 service is lambda — must not
1923        // wire the streaming dispatch (Lambda has its own buffered path).
1924        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}