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 Query protocol
475    let mut all_params = query_params;
476    if detected.protocol == AwsProtocol::Query {
477        let body_params = protocol::parse_query_body(&body_bytes);
478        for (k, v) in body_params {
479            all_params.entry(k).or_insert(v);
480        }
481    }
482
483    // CloudWatch (`monitoring`) advertises awsJson1_0 alongside awsQuery. Its
484    // handlers all read the flat awsQuery param map, so when a client uses the
485    // JSON protocol we flatten the JSON body into that same map, leaving the
486    // handlers unchanged. The handler emits a JSON response for JSON callers.
487    if detected.protocol == AwsProtocol::Json && detected.service == "monitoring" {
488        let body_params = protocol::flatten_json_to_query(&body_bytes);
489        for (k, v) in body_params {
490            all_params.entry(k).or_insert(v);
491        }
492    }
493
494    let aws_request = AwsRequest {
495        service: detected.service.clone(),
496        action: detected.action.clone(),
497        region,
498        account_id: caller_principal
499            .as_ref()
500            .map(|p| p.account_id.clone())
501            .unwrap_or_else(|| config.account_id.clone()),
502        request_id: request_id.clone(),
503        headers: parts.headers,
504        query_params: all_params,
505        body: body_bytes,
506        body_stream: parking_lot::Mutex::new(body_stream),
507        path_segments,
508        raw_path: path,
509        raw_query,
510        method: parts.method,
511        is_query_protocol: detected.protocol == AwsProtocol::Query,
512        access_key_id,
513        principal: caller_principal,
514    };
515
516    tracing::info!(
517        service = %aws_request.service,
518        action = %aws_request.action,
519        request_id = %aws_request.request_id,
520        "handling request"
521    );
522
523    // Opt-in IAM identity-policy enforcement. Runs before the service
524    // handler so a deny never reaches business logic. Root principals
525    // (both `test*` bypass AKIDs and the account's IAM root) are exempt,
526    // matching AWS behavior. Services that haven't opted in via
527    // `iam_enforceable()` are transparently skipped — the startup log
528    // lists which services are under enforcement so users always know.
529    if config.iam_mode.is_enabled()
530        && service.iam_enforceable()
531        && !is_root_bypass(aws_request.access_key_id.as_deref().unwrap_or(""))
532    {
533        if let Some(evaluator) = config.policy_evaluator.as_ref() {
534            if let Some(principal) = aws_request.principal.as_ref() {
535                if !principal.is_root() {
536                    if let Some(iam_action) = service.iam_action_for(&aws_request) {
537                        let mut condition_context = build_condition_context(
538                            principal,
539                            remote_addr,
540                            &aws_request.region,
541                            is_secure_transport(&aws_request.headers),
542                        );
543                        // F3 keys riding on the resolved credential. STS
544                        // populates these at mint time so subsequent
545                        // requests under the credential can be evaluated
546                        // against `aws:MultiFactorAuthPresent`,
547                        // `aws:MultiFactorAuthAge`, `aws:TokenIssueTime`,
548                        // and `aws:FederatedProvider`. IAM user access
549                        // keys carry none of these, matching AWS.
550                        if let Some(rc) = resolved.as_ref() {
551                            condition_context.aws_mfa_present = Some(rc.mfa_present);
552                            condition_context.aws_token_issue_time = rc.token_issued_at;
553                            condition_context.aws_federated_provider =
554                                rc.federated_provider.clone();
555                            // `aws:MultiFactorAuthAge` is "seconds since
556                            // MFA was asserted" — computed at evaluation
557                            // time from the token issue moment so the
558                            // value increases monotonically as the session
559                            // ages. Only set when the session was actually
560                            // minted with MFA; otherwise the key is
561                            // absent, matching AWS.
562                            if rc.mfa_present {
563                                if let Some(issued) = rc.token_issued_at {
564                                    let age = chrono::Utc::now()
565                                        .signed_duration_since(issued)
566                                        .num_seconds()
567                                        .max(0);
568                                    condition_context.aws_mfa_age_seconds = Some(age);
569                                }
570                            }
571                        }
572                        condition_context.service_keys =
573                            service.iam_condition_keys_for(&aws_request, &iam_action);
574
575                        // ABAC: populate tag-based condition keys.
576                        // aws:ResourceTag/*
577                        match service.resource_tags_for(&iam_action.resource) {
578                            Some(tags) => condition_context.resource_tags = Some(tags),
579                            None => tracing::debug!(
580                                target: "fakecloud::iam::audit",
581                                service = %detected.service,
582                                resource = %iam_action.resource,
583                                "service does not expose resource tags for ABAC; skipping aws:ResourceTag/* evaluation"
584                            ),
585                        }
586                        // aws:RequestTag/* + aws:TagKeys
587                        match service.request_tags_from(&aws_request, iam_action.action) {
588                            Some(tags) => condition_context.request_tags = Some(tags),
589                            None => tracing::debug!(
590                                target: "fakecloud::iam::audit",
591                                service = %detected.service,
592                                action = %iam_action.action_string(),
593                                "service does not expose request tags for ABAC; skipping aws:RequestTag/* / aws:TagKeys evaluation"
594                            ),
595                        }
596                        // aws:PrincipalTag/*
597                        condition_context.principal_tags = principal.tags.clone();
598
599                        // Phase 2: fetch the resource-based policy (if
600                        // any) attached to the target resource and
601                        // pass it to the evaluator alongside the
602                        // principal's identity policies. The resource's
603                        // owning account is parsed from the ARN (#381
604                        // multi-account alignment); S3 ARNs have an
605                        // empty account field, so we fall back to the
606                        // server's configured account ID in that case.
607                        let resource_policy_json =
608                            config.resource_policy_provider.as_ref().and_then(|p| {
609                                p.resource_policy(&detected.service, &iam_action.resource)
610                            });
611                        // Derive the resource-owning account. Prefer a provider
612                        // lookup (S3 ARNs carry no account, so the bucket's
613                        // owner is resolved from state — without this, account
614                        // A reaching account B's bucket would be mis-read as
615                        // same-account and skip B's bucket-policy requirement,
616                        // bug-audit 2026-05-28, 5.3), then fall back to the
617                        // account embedded in the ARN (SQS/SNS/Lambda/…), then
618                        // to the caller's account for wildcard / unscoped
619                        // actions (ListQueues, GetCallerIdentity).
620                        let resource_account_id = config
621                            .resource_policy_provider
622                            .as_ref()
623                            .and_then(|p| {
624                                p.resource_owner_account(&detected.service, &iam_action.resource)
625                            })
626                            .or_else(|| parse_account_from_arn(&iam_action.resource))
627                            .unwrap_or_else(|| principal.account_id.clone());
628                        // SCP ceiling: resolve the inherited SCP chain
629                        // for this principal (management accounts and
630                        // service-linked roles come back as `None`, in
631                        // which case the evaluator treats the layer as
632                        // absent). Audit breadcrumbs emitted by the
633                        // resolver itself, not here.
634                        let scps = config
635                            .scp_resolver
636                            .as_ref()
637                            .and_then(|r| r.scps_for(principal));
638                        let decision = evaluator.evaluate_with_resource_policy(
639                            principal,
640                            &iam_action,
641                            &condition_context,
642                            resource_policy_json.as_deref(),
643                            &resource_account_id,
644                            &caller_session_policies,
645                            scps.as_deref(),
646                        );
647                        if !decision.is_allow() {
648                            tracing::warn!(
649                                target: "fakecloud::iam::audit",
650                                service = %detected.service,
651                                action = %iam_action.action_string(),
652                                resource = %iam_action.resource,
653                                principal = %principal.arn,
654                                resource_policy_present = resource_policy_json.is_some(),
655                                decision = ?decision,
656                                mode = %config.iam_mode,
657                                request_id = %request_id,
658                                "IAM policy evaluation denied request"
659                            );
660                            if config.iam_mode.is_strict() {
661                                // Real AWS includes an "Encoded
662                                // authorization failure message" suffix
663                                // on AccessDeniedException — an opaque
664                                // base64+zlib JSON blob that the caller
665                                // can pass to STS
666                                // `DecodeAuthorizationMessage` to
667                                // recover the structured deny reason
668                                // (action, principal, matched
669                                // statements, condition context). We
670                                // produce the same blob inline so
671                                // existing tooling that decodes deny
672                                // reasons works against fakecloud.
673                                let context_summary = serde_json::json!({
674                                    "aws:PrincipalArn": principal.arn,
675                                    "aws:PrincipalAccount": principal.account_id,
676                                    "aws:RequestedRegion": condition_context
677                                        .aws_requested_region
678                                        .clone()
679                                        .unwrap_or_default(),
680                                    "aws:SecureTransport": condition_context
681                                        .aws_secure_transport
682                                        .unwrap_or(false),
683                                    "aws:Action": iam_action.action_string(),
684                                    "aws:Resource": iam_action.resource,
685                                    "decision": format!("{:?}", decision),
686                                });
687                                let action_string = iam_action.action_string();
688                                let encoded = crate::auth_message::encode_deny(
689                                    matches!(decision, crate::auth::IamDecision::ExplicitDeny),
690                                    Some(&action_string),
691                                    Some(&principal.arn),
692                                    Vec::new(),
693                                    Some(context_summary),
694                                );
695                                return build_error_response(
696                                    StatusCode::FORBIDDEN,
697                                    "AccessDeniedException",
698                                    &format!(
699                                        "User: {} is not authorized to perform: {} on resource: {} Encoded authorization failure message: {}",
700                                        principal.arn,
701                                        iam_action.action_string(),
702                                        iam_action.resource,
703                                        encoded,
704                                    ),
705                                    &request_id,
706                                    detected.protocol,
707                                );
708                            }
709                            // Soft mode: audit log already emitted; fall
710                            // through to the handler.
711                        }
712                    } else {
713                        // Service opted in via `iam_enforceable()` but its
714                        // `iam_action_for` returned no `IamAction` for this
715                        // specific operation (e.g. S3's `s3_detect_action`
716                        // has `_ => return None` arms for unrecognized
717                        // sub-resources). Under strict enforcement that must
718                        // fail closed: an operation we cannot map to an IAM
719                        // action cannot be authorized, so serving it would be
720                        // a fail-open bypass of `--iam strict`. Deny by
721                        // default. In soft mode we preserve the historical
722                        // warn-and-allow so an incomplete mapping surfaces
723                        // during rollout without blocking traffic.
724                        tracing::warn!(
725                            target: "fakecloud::iam::audit",
726                            service = %detected.service,
727                            action = %aws_request.action,
728                            mode = %config.iam_mode,
729                            request_id = %request_id,
730                            "service is iam_enforceable but has no IamAction mapping for this action; denying under strict, allowing under soft"
731                        );
732                        if config.iam_mode.is_strict() {
733                            return build_error_response(
734                                StatusCode::FORBIDDEN,
735                                "AccessDeniedException",
736                                &format!(
737                                    "User: {} is not authorized to perform: {}: no IAM action mapping exists for this operation, so it cannot be authorized under strict IAM enforcement",
738                                    principal.arn, aws_request.action,
739                                ),
740                                &request_id,
741                                detected.protocol,
742                            );
743                        }
744                        // Soft mode: audit log emitted; fall through to the
745                        // handler.
746                    }
747                }
748            } else if aws_request.access_key_id.is_none() {
749                // Truly anonymous (unsigned) caller — no Authorization header at
750                // all. No identity policies exist, so authorization rests
751                // entirely on the resource policy (a bucket policy granting
752                // `Principal:"*"`) and public-read ACLs — mirroring AWS, which
753                // denies anonymous requests unless the resource is explicitly
754                // made public. Without this an anonymous request that reached an
755                // iam_enforceable service in enforcement mode would bypass
756                // authorization entirely.
757                //
758                // A request that carried an Authorization header but whose
759                // credential did not resolve (principal `None` with
760                // `access_key_id` `Some`) is intentionally left alone here: with
761                // SigV4 verification off, fakecloud does not reject unverified
762                // signed requests, and turning them into anonymous denials would
763                // change long-standing behavior.
764                if let Some(iam_action) = service.iam_action_for(&aws_request) {
765                    let now = chrono::Utc::now();
766                    let mut condition_context = ConditionContext {
767                        aws_source_ip: remote_addr.map(|sa| sa.ip()),
768                        aws_current_time: Some(now),
769                        aws_epoch_time: Some(now.timestamp()),
770                        aws_secure_transport: Some(is_secure_transport(&aws_request.headers)),
771                        aws_requested_region: Some(aws_request.region.clone()),
772                        ..Default::default()
773                    };
774                    condition_context.service_keys =
775                        service.iam_condition_keys_for(&aws_request, &iam_action);
776                    let resource_policy_json = config
777                        .resource_policy_provider
778                        .as_ref()
779                        .and_then(|p| p.resource_policy(&detected.service, &iam_action.resource));
780                    let policy_decision = evaluator.evaluate_anonymous(
781                        &iam_action,
782                        &condition_context,
783                        resource_policy_json.as_deref(),
784                    );
785                    let policy_allows = policy_decision.is_allow();
786                    // An explicit Deny in the resource policy always wins, even
787                    // over a public-read ACL — matching AWS's Deny-overrides
788                    // precedence. Collapsing the decision to a bool and ORing the
789                    // ACL let a public ACL override an explicit anonymous Deny.
790                    let policy_explicit_deny =
791                        matches!(policy_decision, crate::auth::IamDecision::ExplicitDeny);
792                    let acl_allows = !policy_explicit_deny
793                        && config.resource_policy_provider.as_ref().is_some_and(|p| {
794                            p.public_acl_allows(
795                                &detected.service,
796                                &iam_action.resource,
797                                iam_action.action,
798                            )
799                        });
800                    if !policy_allows && !acl_allows {
801                        tracing::warn!(
802                            target: "fakecloud::iam::audit",
803                            service = %detected.service,
804                            action = %iam_action.action_string(),
805                            resource = %iam_action.resource,
806                            resource_policy_present = resource_policy_json.is_some(),
807                            mode = %config.iam_mode,
808                            request_id = %request_id,
809                            "anonymous request denied: no public bucket policy or ACL grants the action"
810                        );
811                        if config.iam_mode.is_strict() {
812                            return build_error_response(
813                                StatusCode::FORBIDDEN,
814                                "AccessDenied",
815                                "Access Denied",
816                                &request_id,
817                                detected.protocol,
818                            );
819                        }
820                        // Soft mode: audit log emitted; fall through to the handler.
821                    }
822                }
823            }
824        }
825    }
826
827    match service.handle(aws_request).await {
828        Ok(resp) => {
829            let mut builder = Response::builder()
830                .status(resp.status)
831                .header("x-amzn-requestid", &request_id)
832                .header("x-amz-request-id", &request_id);
833
834            if !resp.content_type.is_empty() {
835                builder = builder.header("content-type", &resp.content_type);
836            }
837
838            let has_content_length = resp
839                .headers
840                .iter()
841                .any(|(k, _)| k.as_str().eq_ignore_ascii_case("content-length"));
842
843            for (k, v) in &resp.headers {
844                builder = builder.header(k, v);
845            }
846
847            match resp.body {
848                ResponseBody::Bytes(b) => builder.body(Body::from(b)).unwrap(),
849                ResponseBody::File { file, size } => {
850                    let stream = tokio_util::io::ReaderStream::new(file);
851                    let body = Body::from_stream(stream);
852                    if !has_content_length {
853                        builder = builder.header("content-length", size.to_string());
854                    }
855                    builder.body(body).unwrap()
856                }
857            }
858        }
859        Err(err) => {
860            tracing::warn!(
861                service = %detected.service,
862                action = %detected.action,
863                error = %err,
864                "request failed"
865            );
866            let error_headers = err.response_headers().to_vec();
867            let mut resp = build_error_response_with_fields(
868                err.status(),
869                err.code(),
870                &err.message(),
871                &request_id,
872                detected.protocol,
873                err.extra_fields(),
874            );
875            for (k, v) in &error_headers {
876                if let (Ok(name), Ok(val)) = (
877                    k.parse::<http::header::HeaderName>(),
878                    v.parse::<http::header::HeaderValue>(),
879                ) {
880                    resp.headers_mut().insert(name, val);
881                }
882            }
883            resp
884        }
885    }
886}
887
888/// Configuration passed to the dispatch handler.
889#[derive(Clone)]
890pub struct DispatchConfig {
891    pub region: String,
892    pub account_id: String,
893    /// Whether to cryptographically verify SigV4 signatures on incoming
894    /// requests. Wired through from `--verify-sigv4` /
895    /// `FAKECLOUD_VERIFY_SIGV4`. Off by default.
896    pub verify_sigv4: bool,
897    /// IAM policy evaluation mode. Wired through from `--iam` /
898    /// `FAKECLOUD_IAM`. Defaults to [`IamMode::Off`]. Actual evaluation is
899    /// added in a later batch; today this field is plumbed but never
900    /// consulted.
901    pub iam_mode: IamMode,
902    /// Resolves access key IDs to their secrets and owning principals.
903    /// Required when `verify_sigv4` or `iam_mode != Off`. When `None`, both
904    /// features gracefully degrade to off-by-default behavior.
905    pub credential_resolver: Option<Arc<dyn CredentialResolver>>,
906    /// Evaluates IAM identity policies for a resolved principal + action.
907    /// Required when `iam_mode != Off`. When `None`, enforcement silently
908    /// degrades to off even if `iam_mode` is set.
909    pub policy_evaluator: Option<Arc<dyn IamPolicyEvaluator>>,
910    /// Resolves resource-based policies (S3 bucket policies in the
911    /// initial rollout) to hand to the evaluator alongside the
912    /// principal's identity policies. `None` means the server was
913    /// started without any resource-policy-owning service registered;
914    /// dispatch then behaves as if no resource policy is attached to
915    /// any resource, identical to the Phase 1 behavior.
916    pub resource_policy_provider: Option<Arc<dyn ResourcePolicyProvider>>,
917    /// Resolves the ordered SCP chain that applies to a principal's
918    /// account (root-OU first, account-direct last). `None` means no
919    /// organizations resolver has been registered — SCPs never gate
920    /// any request in that case. Off-by-default matches the Batch 4
921    /// contract: zero behavior change until a user calls
922    /// `CreateOrganization` and the resolver is wired.
923    pub scp_resolver: Option<Arc<dyn crate::auth::ScpResolver>>,
924}
925
926impl std::fmt::Debug for DispatchConfig {
927    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
928        f.debug_struct("DispatchConfig")
929            .field("region", &self.region)
930            .field("account_id", &self.account_id)
931            .field("verify_sigv4", &self.verify_sigv4)
932            .field("iam_mode", &self.iam_mode)
933            .field(
934                "credential_resolver",
935                &self
936                    .credential_resolver
937                    .as_ref()
938                    .map(|_| "<CredentialResolver>"),
939            )
940            .field(
941                "policy_evaluator",
942                &self
943                    .policy_evaluator
944                    .as_ref()
945                    .map(|_| "<IamPolicyEvaluator>"),
946            )
947            .field(
948                "resource_policy_provider",
949                &self
950                    .resource_policy_provider
951                    .as_ref()
952                    .map(|_| "<ResourcePolicyProvider>"),
953            )
954            .field(
955                "scp_resolver",
956                &self.scp_resolver.as_ref().map(|_| "<ScpResolver>"),
957            )
958            .finish()
959    }
960}
961
962impl DispatchConfig {
963    /// Minimal constructor for tests and call sites that don't care about the
964    /// opt-in security features.
965    pub fn new(region: impl Into<String>, account_id: impl Into<String>) -> Self {
966        Self {
967            region: region.into(),
968            account_id: account_id.into(),
969            verify_sigv4: false,
970            iam_mode: IamMode::Off,
971            credential_resolver: None,
972            policy_evaluator: None,
973            resource_policy_provider: None,
974            scp_resolver: None,
975        }
976    }
977}
978
979/// Extract the 12-digit account ID segment from an AWS ARN.
980///
981/// ARNs follow `arn:<partition>:<service>:<region>:<account>:<resource>`.
982/// Identifies routes that opt into streaming request bodies. Returns
983/// `Some((service, action_hint))` when the dispatch path should hand
984/// the raw body to the service handler unbuffered, otherwise `None`
985/// for the default buffered path. The handler reads the stream via
986/// [`crate::service::AwsRequest::take_body_stream`].
987///
988/// Streaming-eligible routes today:
989///
990/// * `s3` PUT object — `PUT /<bucket>/<key>` with a SigV4 (or
991///   presigned) auth header. Covers PutObject, UploadPart, and
992///   UploadPartCopy. The S3 service spills to disk via
993///   [`fakecloud_persistence::BodySource::File`] when the stream is
994///   present.
995/// * `ecr` OCI Distribution v2 blob upload — `PATCH` and `PUT` on
996///   `/v2/{name}/blobs/uploads/{uuid}`. The ECR service spools the
997///   stream into a per-upload temp file before computing the digest.
998fn streaming_route(
999    method: &http::Method,
1000    path: &str,
1001    headers: &http::HeaderMap,
1002    query_params: &HashMap<String, String>,
1003) -> Option<(&'static str, &'static str)> {
1004    // ECR OCI v2 blob upload (PATCH chunk + final PUT).
1005    if (method == http::Method::PATCH || method == http::Method::PUT)
1006        && path.starts_with("/v2/")
1007        && path.contains("/blobs/uploads/")
1008    {
1009        return Some(("ecr", ""));
1010    }
1011
1012    // S3 PutObject / UploadPart / UploadPartCopy. Detect either via
1013    // SigV4 service field in the Authorization header OR via a SigV4
1014    // presigned URL (X-Amz-Credential .../s3/...) OR a SigV2 presigned
1015    // URL (AWSAccessKeyId + Signature + Expires query parameters).
1016    if method == http::Method::PUT {
1017        let after = path.trim_start_matches('/');
1018        // Path-style PutObject is `PUT /<bucket>/<key>` (path contains a
1019        // slash); virtual-hosted-style is `PUT /<key>` with the bucket
1020        // in the Host header. For virtual-hosted, accept any non-empty
1021        // path so the key flows through the streaming dispatch — the
1022        // Host parser already routed this request to S3.
1023        let virtual_hosted_s3 = protocol::parse_routing_host_from_headers(headers)
1024            .filter(|h| h.service == "s3" && h.bucket.is_some())
1025            .is_some();
1026        if after.is_empty() || (!virtual_hosted_s3 && !after.contains('/')) {
1027            return None;
1028        }
1029        let header_s3 = headers
1030            .get("authorization")
1031            .and_then(|v| v.to_str().ok())
1032            .and_then(fakecloud_aws::sigv4::parse_sigv4)
1033            .map(|info| info.service == "s3")
1034            .unwrap_or(false);
1035        let presigned_v4_s3 = query_params
1036            .get("X-Amz-Credential")
1037            .and_then(|c| c.split('/').nth(3).map(|s| s.to_string()))
1038            .map(|service| service == "s3")
1039            .unwrap_or(false);
1040        let presigned_v2 = query_params.contains_key("AWSAccessKeyId")
1041            && query_params.contains_key("Signature")
1042            && query_params.contains_key("Expires");
1043        if header_s3 || presigned_v4_s3 || presigned_v2 {
1044            return Some(("s3", ""));
1045        }
1046    }
1047
1048    None
1049}
1050
1051/// Default request-body buffering cap. fakecloud reads the entire
1052/// request body into memory before handing it to a service handler,
1053/// so this ceiling caps RAM usage per in-flight request.
1054///
1055/// Default 1 GiB — comfortably above legitimate single S3 PutObject
1056/// payloads (AWS recommends multipart above ~100 MiB) and each
1057/// multipart part dispatches through here separately. Override with
1058/// `FAKECLOUD_MAX_REQUEST_BODY_BYTES` (decimal bytes) when running
1059/// stress tests that push past the default.
1060const DEFAULT_MAX_REQUEST_BODY_BYTES: usize = 1024 * 1024 * 1024;
1061
1062/// The server-wide buffered request body cap in bytes, from
1063/// `FAKECLOUD_MAX_REQUEST_BODY_BYTES` (default 1 GiB). Public so buffered
1064/// sub-proxies (e.g. the CloudFront viewer data plane) apply the SAME cap as
1065/// direct traffic rather than an inconsistent limit of their own.
1066pub fn max_request_body_bytes() -> usize {
1067    static CACHED: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1068    *CACHED.get_or_init(|| {
1069        std::env::var("FAKECLOUD_MAX_REQUEST_BODY_BYTES")
1070            .ok()
1071            .and_then(|s| s.parse::<usize>().ok())
1072            .filter(|&n| n > 0)
1073            .unwrap_or(DEFAULT_MAX_REQUEST_BODY_BYTES)
1074    })
1075}
1076
1077/// For the cross-account decision in IAM enforcement, the "resource
1078/// account" is the ARN's account segment. Some services (notably S3)
1079/// produce ARNs with an empty account field — for those we return
1080/// `None` and let the caller fall back to the server's configured
1081/// account ID. Malformed or non-ARN strings also return `None`.
1082fn parse_account_from_arn(arn: &str) -> Option<String> {
1083    let mut parts = arn.splitn(6, ':');
1084    if parts.next()? != "arn" {
1085        return None;
1086    }
1087    let _partition = parts.next()?;
1088    let _service = parts.next()?;
1089    let _region = parts.next()?;
1090    let account = parts.next()?;
1091    // Resource segment must exist (parts.next().is_some()) for the ARN
1092    // to be well-formed, but we don't consume its value here.
1093    parts.next()?;
1094    if account.is_empty() {
1095        None
1096    } else {
1097        Some(account.to_string())
1098    }
1099}
1100
1101/// Whether the request's `user-agent` (or `x-amz-user-agent`) carries the
1102/// `api/neptune` SDK-metadata token the `aws-sdk-neptune` client stamps in.
1103/// Used to disambiguate Neptune from RDS, which share the `rds` SigV4 scope
1104/// and endpoint. Matches the `api/neptune` token that AWS SDKs emit (a
1105/// leading `api/neptune` optionally followed by `#`/`/` and a version).
1106fn user_agent_indicates_neptune(headers: &http::HeaderMap) -> bool {
1107    for name in ["user-agent", "x-amz-user-agent"] {
1108        if let Some(ua) = headers.get(name).and_then(|v| v.to_str().ok()) {
1109            for part in ua.split_whitespace() {
1110                if let Some(rest) = part.strip_prefix("api/neptune") {
1111                    if rest.is_empty() || rest.starts_with('#') || rest.starts_with('/') {
1112                        return true;
1113                    }
1114                }
1115            }
1116        }
1117    }
1118    false
1119}
1120
1121/// Extract region from User-Agent header suffix `region/<region>`.
1122/// Whether the request's `user-agent` (or `x-amz-user-agent`) carries the
1123/// `api/docdb` SDK-metadata token the `aws-sdk-docdb` client stamps in. Used
1124/// to disambiguate DocumentDB from RDS, which share the `rds` SigV4 scope
1125/// and endpoint. Matches the `api/docdb` token that AWS SDKs emit (a leading
1126/// `api/docdb` optionally followed by `#`/`/` and a version).
1127fn user_agent_indicates_docdb(headers: &http::HeaderMap) -> bool {
1128    for name in ["user-agent", "x-amz-user-agent"] {
1129        if let Some(ua) = headers.get(name).and_then(|v| v.to_str().ok()) {
1130            for part in ua.split_whitespace() {
1131                if let Some(rest) = part.strip_prefix("api/docdb") {
1132                    if rest.is_empty() || rest.starts_with('#') || rest.starts_with('/') {
1133                        return true;
1134                    }
1135                }
1136            }
1137        }
1138    }
1139    false
1140}
1141
1142fn extract_region_from_user_agent(headers: &http::HeaderMap) -> Option<String> {
1143    let ua = headers.get("user-agent")?.to_str().ok()?;
1144    for part in ua.split_whitespace() {
1145        if let Some(region) = part.strip_prefix("region/") {
1146            if !region.is_empty() {
1147                return Some(region.to_string());
1148            }
1149        }
1150    }
1151    None
1152}
1153
1154fn build_error_response(
1155    status: StatusCode,
1156    code: &str,
1157    message: &str,
1158    request_id: &str,
1159    protocol: AwsProtocol,
1160) -> Response<Body> {
1161    build_error_response_with_fields(status, code, message, request_id, protocol, &[])
1162}
1163
1164fn build_error_response_with_fields(
1165    status: StatusCode,
1166    code: &str,
1167    message: &str,
1168    request_id: &str,
1169    protocol: AwsProtocol,
1170    extra_fields: &[(String, String)],
1171) -> Response<Body> {
1172    let (status, content_type, body) = match protocol {
1173        AwsProtocol::Query => {
1174            fakecloud_aws::error::xml_error_response(status, code, message, request_id)
1175        }
1176        AwsProtocol::Rest => fakecloud_aws::error::s3_xml_error_response_with_fields(
1177            status,
1178            code,
1179            message,
1180            request_id,
1181            extra_fields,
1182        ),
1183        AwsProtocol::Json | AwsProtocol::RestJson => {
1184            fakecloud_aws::error::json_error_response_with_fields(
1185                status,
1186                code,
1187                message,
1188                extra_fields,
1189            )
1190        }
1191    };
1192
1193    // S3 (and other REST-XML services) place the error code in
1194    // `x-amz-error-code` so HEAD responses — which HTTP forbids from
1195    // carrying a body — still surface the code. AWS SDKs read this header
1196    // when the body is empty. Emit it on every error response so HEAD,
1197    // OPTIONS, and any client that strips the body still see the code.
1198    // Backend errors regularly include newlines (multi-line stderr from
1199    // docker/podman/etc.); HTTP header values reject control characters,
1200    // so sanitize before insertion or the builder rejects the response
1201    // and the connection drops.
1202    let safe_code = sanitize_header_value(code);
1203    let safe_message = sanitize_header_value(message);
1204    let mut builder = Response::builder()
1205        .status(status)
1206        .header("content-type", content_type)
1207        .header("x-amzn-requestid", request_id)
1208        .header("x-amz-request-id", request_id);
1209    if let Ok(v) = http::HeaderValue::from_str(&safe_code) {
1210        builder = builder.header("x-amz-error-code", v);
1211    }
1212    if let Ok(v) = http::HeaderValue::from_str(&safe_message) {
1213        builder = builder.header("x-amz-error-message", v);
1214    }
1215    builder.body(Body::from(body)).unwrap_or_else(|_| {
1216        // Builder only fails if a header is invalid; we sanitized the two
1217        // we control, so the remaining ones (content-type, request id) are
1218        // ASCII and safe. This fallback exists purely so we never panic.
1219        Response::new(Body::empty())
1220    })
1221}
1222
1223/// Strip characters that HTTP header values reject (control bytes, CR/LF/TAB)
1224/// and truncate to a length that AWS SDKs handle cleanly. Backend tools
1225/// (docker, podman, kubectl, …) emit multi-line stderr, and forwarding that
1226/// raw into `x-amz-error-message` previously panicked the dispatcher.
1227fn sanitize_header_value(s: &str) -> String {
1228    const MAX_LEN: usize = 1024;
1229    let mut out = String::with_capacity(s.len().min(MAX_LEN));
1230    for ch in s.chars() {
1231        if out.len() >= MAX_LEN {
1232            break;
1233        }
1234        // Header values forbid CR, LF, and other control bytes (RFC 9110).
1235        // Replace with a single space so multi-line messages stay readable.
1236        if ch.is_control() {
1237            if !out.ends_with(' ') {
1238                out.push(' ');
1239            }
1240        } else {
1241            out.push(ch);
1242        }
1243    }
1244    out.trim().to_string()
1245}
1246
1247/// Build the [`ConditionContext`] passed to the IAM evaluator for one
1248/// request. Populates the 10 global condition keys from the resolved
1249/// principal + the HTTP request. Service-specific keys are deferred to
1250/// a follow-up batch and left empty.
1251/// For an unsigned request that no other detection rule claimed, return the
1252/// bucket name when the first path segment names an existing S3 bucket.
1253///
1254/// fakecloud serves every service from one endpoint, so an anonymous
1255/// path-style S3 request (`GET /bucket/key`, no SigV4) is indistinguishable
1256/// from an API Gateway execute-api call by headers alone. Bucket existence is
1257/// the disambiguator: if the segment is a real bucket, route to S3; otherwise
1258/// fall through to the apigateway catch-all. Uses the already-wired
1259/// `resource_policy_provider`, which resolves S3 bucket ownership from state
1260/// (`Some` => the bucket exists). Returns `None` when no provider is wired.
1261/// Recover the access key from a SigV2 presigned URL. AWS SigV2 presigning
1262/// puts the key in the `AWSAccessKeyId` query parameter alongside `Signature`
1263/// and `Expires`; all three must be present for the URL to be a SigV2 presign.
1264/// Returns None for SigV4 presigns (which use `X-Amz-Credential`) or unsigned
1265/// requests.
1266fn sigv2_presigned_access_key(query_params: &HashMap<String, String>) -> Option<String> {
1267    if query_params.contains_key("Signature") && query_params.contains_key("Expires") {
1268        query_params.get("AWSAccessKeyId").cloned()
1269    } else {
1270        None
1271    }
1272}
1273
1274fn anonymous_s3_bucket(uri: &http::Uri, config: &DispatchConfig) -> Option<String> {
1275    let provider = config.resource_policy_provider.as_ref()?;
1276    let segment = uri.path().split('/').find(|s| !s.is_empty())?.to_string();
1277    let arn = format!("arn:aws:s3:::{segment}");
1278    provider.resource_owner_account("s3", &arn).map(|_| segment)
1279}
1280
1281fn build_condition_context(
1282    principal: &Principal,
1283    remote_addr: Option<SocketAddr>,
1284    region: &str,
1285    secure_transport: bool,
1286) -> ConditionContext {
1287    let now = chrono::Utc::now();
1288    ConditionContext {
1289        aws_username: aws_username_from_principal(principal),
1290        aws_userid: Some(principal.user_id.clone()),
1291        aws_principal_arn: Some(principal.arn.clone()),
1292        aws_principal_account: Some(principal.account_id.clone()),
1293        aws_principal_type: Some(principal_type_label(principal.principal_type).to_string()),
1294        aws_source_ip: remote_addr.map(|sa| sa.ip()),
1295        aws_current_time: Some(now),
1296        aws_epoch_time: Some(now.timestamp()),
1297        aws_secure_transport: Some(secure_transport),
1298        aws_requested_region: Some(region.to_string()),
1299        // F3 keys: populated from the caller's session context when STS
1300        // mints credentials with MFA / SAML / OIDC / VPC-endpoint hints.
1301        // Default-None here so tests/dispatch sites that don't set them
1302        // safe-fail any policy referencing them — matching AWS for keys
1303        // that aren't asserted.
1304        aws_mfa_present: None,
1305        aws_mfa_age_seconds: None,
1306        aws_called_via: Vec::new(),
1307        aws_source_vpce: None,
1308        aws_source_vpc: None,
1309        aws_vpc_source_ip: None,
1310        aws_federated_provider: None,
1311        aws_token_issue_time: None,
1312        service_keys: Default::default(),
1313        resource_tags: None,
1314        request_tags: None,
1315        principal_tags: None,
1316    }
1317}
1318
1319/// `aws:username` is only set for IAM users, matching AWS. For assumed
1320/// roles, federated users, root, and unknown principals the key is
1321/// absent — operators that reference it without `IfExists` safe-fail.
1322fn aws_username_from_principal(principal: &Principal) -> Option<String> {
1323    if principal.principal_type != PrincipalType::User {
1324        return None;
1325    }
1326    let after = principal.arn.rsplit_once(":user/").map(|(_, s)| s)?;
1327    // Strip any IAM path prefix; bare username is the last segment.
1328    Some(after.rsplit('/').next().unwrap_or(after).to_string())
1329}
1330
1331/// AWS's `aws:PrincipalType` uses PascalCase identifiers, distinct from
1332/// the lowercase ones [`PrincipalType::as_str`] returns for ARNs.
1333fn principal_type_label(t: PrincipalType) -> &'static str {
1334    match t {
1335        PrincipalType::User => "User",
1336        PrincipalType::AssumedRole => "AssumedRole",
1337        PrincipalType::FederatedUser => "FederatedUser",
1338        PrincipalType::Root => "Account",
1339        PrincipalType::Unknown => "Unknown",
1340    }
1341}
1342
1343/// Best-effort detection of TLS-terminated requests. Direct HTTPS
1344/// connections are not yet supported by the fakecloud server (it speaks
1345/// plain HTTP), so the only signal is an `x-forwarded-proto: https`
1346/// header set by an upstream proxy. Anything else evaluates to `false`,
1347/// which matches the typical local-dev setup.
1348fn is_secure_transport(headers: &http::HeaderMap) -> bool {
1349    headers
1350        .get("x-forwarded-proto")
1351        .and_then(|v| v.to_str().ok())
1352        .map(|s| s.eq_ignore_ascii_case("https"))
1353        .unwrap_or(false)
1354}
1355
1356trait ProtocolExt {
1357    fn error_status(&self) -> StatusCode;
1358}
1359
1360impl ProtocolExt for AwsProtocol {
1361    fn error_status(&self) -> StatusCode {
1362        StatusCode::BAD_REQUEST
1363    }
1364}
1365
1366#[cfg(test)]
1367mod tests {
1368    use super::*;
1369
1370    #[test]
1371    fn default_max_request_body_bytes_is_one_gib() {
1372        // Without the env override, the cap defaults to 1 GiB. The
1373        // public function caches via OnceLock so only the first call
1374        // in the process matters; we assert the constant directly.
1375        assert_eq!(DEFAULT_MAX_REQUEST_BODY_BYTES, 1024 * 1024 * 1024);
1376    }
1377
1378    #[test]
1379    fn sigv2_presigned_access_key_extracted_with_signature_and_expires() {
1380        let mut q = HashMap::new();
1381        q.insert("AWSAccessKeyId".to_string(), "AKIAEXAMPLE".to_string());
1382        q.insert("Signature".to_string(), "abc%2Bdef".to_string());
1383        q.insert("Expires".to_string(), "1700000000".to_string());
1384        assert_eq!(
1385            sigv2_presigned_access_key(&q).as_deref(),
1386            Some("AKIAEXAMPLE")
1387        );
1388    }
1389
1390    #[test]
1391    fn sigv2_presigned_access_key_none_without_signature_or_expires() {
1392        // AWSAccessKeyId alone (e.g. a stray query param) is not a SigV2
1393        // presign and must not be treated as a credential.
1394        let mut q = HashMap::new();
1395        q.insert("AWSAccessKeyId".to_string(), "AKIAEXAMPLE".to_string());
1396        assert_eq!(sigv2_presigned_access_key(&q), None);
1397
1398        q.insert("Expires".to_string(), "1700000000".to_string());
1399        assert_eq!(
1400            sigv2_presigned_access_key(&q),
1401            None,
1402            "missing Signature must not qualify"
1403        );
1404    }
1405
1406    #[test]
1407    fn sigv2_presigned_access_key_none_for_unsigned_request() {
1408        assert_eq!(sigv2_presigned_access_key(&HashMap::new()), None);
1409    }
1410
1411    #[test]
1412    fn dispatch_config_new_defaults_to_off() {
1413        let cfg = DispatchConfig::new("us-east-1", "123456789012");
1414        assert_eq!(cfg.region, "us-east-1");
1415        assert_eq!(cfg.account_id, "123456789012");
1416        assert!(!cfg.verify_sigv4);
1417        assert_eq!(cfg.iam_mode, IamMode::Off);
1418    }
1419
1420    #[test]
1421    fn aws_username_strips_iam_path_for_users() {
1422        let p = Principal {
1423            arn: "arn:aws:iam::123456789012:user/engineering/alice".into(),
1424            user_id: "AIDAALICE".into(),
1425            account_id: "123456789012".into(),
1426            principal_type: PrincipalType::User,
1427            source_identity: None,
1428            tags: None,
1429        };
1430        assert_eq!(aws_username_from_principal(&p), Some("alice".into()));
1431    }
1432
1433    #[test]
1434    fn aws_username_unset_for_assumed_role() {
1435        let p = Principal {
1436            arn: "arn:aws:sts::123456789012:assumed-role/ops/session".into(),
1437            user_id: "AROAOPS:session".into(),
1438            account_id: "123456789012".into(),
1439            principal_type: PrincipalType::AssumedRole,
1440            source_identity: None,
1441            tags: None,
1442        };
1443        assert_eq!(aws_username_from_principal(&p), None);
1444    }
1445
1446    #[test]
1447    fn principal_type_label_matches_aws_casing() {
1448        assert_eq!(principal_type_label(PrincipalType::User), "User");
1449        assert_eq!(
1450            principal_type_label(PrincipalType::AssumedRole),
1451            "AssumedRole"
1452        );
1453        assert_eq!(principal_type_label(PrincipalType::Root), "Account");
1454    }
1455
1456    #[test]
1457    fn build_condition_context_populates_global_keys() {
1458        let p = Principal {
1459            arn: "arn:aws:iam::123456789012:user/alice".into(),
1460            user_id: "AIDAALICE".into(),
1461            account_id: "123456789012".into(),
1462            principal_type: PrincipalType::User,
1463            source_identity: None,
1464            tags: None,
1465        };
1466        let addr: SocketAddr = "10.0.0.1:54321".parse().unwrap();
1467        let ctx = build_condition_context(&p, Some(addr), "us-east-1", false);
1468        assert_eq!(ctx.aws_username.as_deref(), Some("alice"));
1469        assert_eq!(ctx.aws_userid.as_deref(), Some("AIDAALICE"));
1470        assert_eq!(
1471            ctx.aws_principal_arn.as_deref(),
1472            Some("arn:aws:iam::123456789012:user/alice")
1473        );
1474        assert_eq!(ctx.aws_principal_account.as_deref(), Some("123456789012"));
1475        assert_eq!(ctx.aws_principal_type.as_deref(), Some("User"));
1476        assert_eq!(
1477            ctx.aws_source_ip.map(|i| i.to_string()).as_deref(),
1478            Some("10.0.0.1")
1479        );
1480        assert_eq!(ctx.aws_requested_region.as_deref(), Some("us-east-1"));
1481        assert_eq!(ctx.aws_secure_transport, Some(false));
1482        assert!(ctx.aws_current_time.is_some());
1483        assert!(ctx.aws_epoch_time.is_some());
1484    }
1485
1486    #[test]
1487    fn is_secure_transport_reads_x_forwarded_proto() {
1488        let mut headers = http::HeaderMap::new();
1489        headers.insert("x-forwarded-proto", "https".parse().unwrap());
1490        assert!(is_secure_transport(&headers));
1491        headers.insert("x-forwarded-proto", "http".parse().unwrap());
1492        assert!(!is_secure_transport(&headers));
1493        let empty = http::HeaderMap::new();
1494        assert!(!is_secure_transport(&empty));
1495    }
1496
1497    #[test]
1498    fn parse_account_from_arn_extracts_standard_shapes() {
1499        assert_eq!(
1500            parse_account_from_arn("arn:aws:sqs:us-east-1:123456789012:queue"),
1501            Some("123456789012".to_string())
1502        );
1503        assert_eq!(
1504            parse_account_from_arn("arn:aws:iam::123456789012:user/alice"),
1505            Some("123456789012".to_string())
1506        );
1507    }
1508
1509    #[test]
1510    fn parse_account_from_arn_returns_none_for_s3_empty_account() {
1511        // S3 ARNs have both region and account empty.
1512        assert_eq!(parse_account_from_arn("arn:aws:s3:::my-bucket"), None);
1513        assert_eq!(
1514            parse_account_from_arn("arn:aws:s3:::my-bucket/path/to/key"),
1515            None
1516        );
1517    }
1518
1519    #[test]
1520    fn parse_account_from_arn_returns_none_for_malformed() {
1521        assert_eq!(parse_account_from_arn(""), None);
1522        assert_eq!(parse_account_from_arn("not-an-arn"), None);
1523        assert_eq!(parse_account_from_arn("arn:aws:sqs:us-east-1"), None);
1524        assert_eq!(parse_account_from_arn("arn:aws:sqs"), None);
1525    }
1526
1527    #[test]
1528    fn extract_region_from_user_agent_finds_region_segment() {
1529        let mut headers = http::HeaderMap::new();
1530        headers.insert(
1531            "user-agent",
1532            "aws-sdk-rust/1.0 os/linux region/eu-central-1"
1533                .parse()
1534                .unwrap(),
1535        );
1536        assert_eq!(
1537            extract_region_from_user_agent(&headers),
1538            Some("eu-central-1".to_string())
1539        );
1540    }
1541
1542    #[test]
1543    fn extract_region_from_user_agent_none_without_header() {
1544        let headers = http::HeaderMap::new();
1545        assert_eq!(extract_region_from_user_agent(&headers), None);
1546    }
1547
1548    #[test]
1549    fn extract_region_from_user_agent_ignores_empty_region() {
1550        let mut headers = http::HeaderMap::new();
1551        headers.insert("user-agent", "aws-sdk-java region/".parse().unwrap());
1552        assert_eq!(extract_region_from_user_agent(&headers), None);
1553    }
1554
1555    #[test]
1556    fn extract_region_from_user_agent_none_when_no_region_marker() {
1557        let mut headers = http::HeaderMap::new();
1558        headers.insert("user-agent", "curl/7.79.1".parse().unwrap());
1559        assert_eq!(extract_region_from_user_agent(&headers), None);
1560    }
1561
1562    #[test]
1563    fn aws_username_none_for_root() {
1564        let p = Principal {
1565            arn: "arn:aws:iam::123456789012:root".into(),
1566            user_id: "123456789012".into(),
1567            account_id: "123456789012".into(),
1568            principal_type: PrincipalType::Root,
1569            source_identity: None,
1570            tags: None,
1571        };
1572        assert_eq!(aws_username_from_principal(&p), None);
1573    }
1574
1575    #[test]
1576    fn aws_username_bare_no_path() {
1577        let p = Principal {
1578            arn: "arn:aws:iam::123456789012:user/bob".into(),
1579            user_id: "AIDABOB".into(),
1580            account_id: "123456789012".into(),
1581            principal_type: PrincipalType::User,
1582            source_identity: None,
1583            tags: None,
1584        };
1585        assert_eq!(aws_username_from_principal(&p), Some("bob".into()));
1586    }
1587
1588    #[test]
1589    fn principal_type_label_covers_federated_and_unknown() {
1590        assert_eq!(
1591            principal_type_label(PrincipalType::FederatedUser),
1592            "FederatedUser"
1593        );
1594        assert_eq!(principal_type_label(PrincipalType::Unknown), "Unknown");
1595    }
1596
1597    #[test]
1598    fn build_condition_context_marks_secure_when_flag_set() {
1599        let p = Principal {
1600            arn: "arn:aws:iam::123456789012:user/alice".into(),
1601            user_id: "AIDAALICE".into(),
1602            account_id: "123456789012".into(),
1603            principal_type: PrincipalType::User,
1604            source_identity: None,
1605            tags: None,
1606        };
1607        let ctx = build_condition_context(&p, None, "us-west-2", true);
1608        assert_eq!(ctx.aws_secure_transport, Some(true));
1609        assert!(ctx.aws_source_ip.is_none());
1610        assert_eq!(ctx.aws_requested_region.as_deref(), Some("us-west-2"));
1611    }
1612
1613    #[test]
1614    fn is_secure_transport_case_insensitive() {
1615        let mut headers = http::HeaderMap::new();
1616        headers.insert("x-forwarded-proto", "HTTPS".parse().unwrap());
1617        assert!(is_secure_transport(&headers));
1618    }
1619
1620    #[test]
1621    fn is_secure_transport_non_ascii_bytes_false() {
1622        let mut headers = http::HeaderMap::new();
1623        headers.insert(
1624            "x-forwarded-proto",
1625            http::HeaderValue::from_bytes(&[0xFF, 0xFE]).unwrap(),
1626        );
1627        assert!(!is_secure_transport(&headers));
1628    }
1629
1630    #[test]
1631    fn protocol_ext_error_status_is_bad_request() {
1632        assert_eq!(AwsProtocol::Query.error_status(), StatusCode::BAD_REQUEST);
1633        assert_eq!(AwsProtocol::Json.error_status(), StatusCode::BAD_REQUEST);
1634        assert_eq!(AwsProtocol::Rest.error_status(), StatusCode::BAD_REQUEST);
1635        assert_eq!(
1636            AwsProtocol::RestJson.error_status(),
1637            StatusCode::BAD_REQUEST
1638        );
1639    }
1640
1641    #[test]
1642    fn build_error_response_json_has_json_content_type() {
1643        let resp = build_error_response(
1644            StatusCode::BAD_REQUEST,
1645            "TestCode",
1646            "test msg",
1647            "req-1",
1648            AwsProtocol::Json,
1649        );
1650        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1651        let ct = resp
1652            .headers()
1653            .get("content-type")
1654            .unwrap()
1655            .to_str()
1656            .unwrap();
1657        assert!(ct.contains("json"));
1658        let rid = resp
1659            .headers()
1660            .get("x-amzn-requestid")
1661            .unwrap()
1662            .to_str()
1663            .unwrap();
1664        assert_eq!(rid, "req-1");
1665    }
1666
1667    #[test]
1668    fn build_error_response_rest_returns_xml_content_type() {
1669        let resp = build_error_response(
1670            StatusCode::NOT_FOUND,
1671            "NoSuchBucket",
1672            "bucket missing",
1673            "req-2",
1674            AwsProtocol::Rest,
1675        );
1676        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1677        let ct = resp
1678            .headers()
1679            .get("content-type")
1680            .unwrap()
1681            .to_str()
1682            .unwrap();
1683        assert!(ct.contains("xml"));
1684    }
1685
1686    #[test]
1687    fn build_error_response_query_returns_xml() {
1688        let resp = build_error_response(
1689            StatusCode::BAD_REQUEST,
1690            "InvalidParameter",
1691            "bad param",
1692            "req-3",
1693            AwsProtocol::Query,
1694        );
1695        let ct = resp
1696            .headers()
1697            .get("content-type")
1698            .unwrap()
1699            .to_str()
1700            .unwrap();
1701        assert!(ct.contains("xml"));
1702    }
1703
1704    /// Regression for issue #1539: multi-line backend errors (e.g. podman
1705    /// stderr) used to panic the dispatcher when stuffed into the
1706    /// `x-amz-error-message` HTTP header. The response must build cleanly
1707    /// and the header value must not contain control characters.
1708    #[test]
1709    fn build_error_response_with_multiline_message_does_not_panic() {
1710        let resp = build_error_response(
1711            StatusCode::INTERNAL_SERVER_ERROR,
1712            "ServiceException",
1713            "Lambda execution failed: container failed to start: docker start failed: \
1714             Error: unable to start container \"abc\": \
1715             failed to create new hosts file:\nhost-gateway is empty\n",
1716            "req-multi",
1717            AwsProtocol::Json,
1718        );
1719        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1720        let msg = resp
1721            .headers()
1722            .get("x-amz-error-message")
1723            .expect("x-amz-error-message must be set even when input contains newlines")
1724            .to_str()
1725            .unwrap();
1726        assert!(!msg.contains('\n'));
1727        assert!(!msg.contains('\r'));
1728        assert!(msg.contains("Lambda execution failed"));
1729        assert!(msg.contains("host-gateway is empty"));
1730    }
1731
1732    #[test]
1733    fn build_error_response_with_control_chars_strips_them() {
1734        let resp = build_error_response(
1735            StatusCode::BAD_REQUEST,
1736            "Code\twith\ttabs",
1737            "msg\x00with\x01nulls",
1738            "req-ctrl",
1739            AwsProtocol::Json,
1740        );
1741        let code = resp
1742            .headers()
1743            .get("x-amz-error-code")
1744            .unwrap()
1745            .to_str()
1746            .unwrap();
1747        let msg = resp
1748            .headers()
1749            .get("x-amz-error-message")
1750            .unwrap()
1751            .to_str()
1752            .unwrap();
1753        assert!(!code.contains('\t'));
1754        assert!(!msg.contains('\x00'));
1755        assert!(!msg.contains('\x01'));
1756    }
1757
1758    #[test]
1759    fn sanitize_header_value_truncates_long_input() {
1760        let huge = "x".repeat(5_000);
1761        let out = sanitize_header_value(&huge);
1762        assert!(out.len() <= 1024);
1763    }
1764
1765    #[test]
1766    fn sanitize_header_value_collapses_consecutive_control_runs() {
1767        let out = sanitize_header_value("a\n\n\n\rb");
1768        assert_eq!(out, "a b");
1769    }
1770
1771    #[test]
1772    fn dispatch_config_carries_opt_in_flags() {
1773        let cfg = DispatchConfig {
1774            region: "eu-west-1".to_string(),
1775            account_id: "000000000000".to_string(),
1776            verify_sigv4: true,
1777            iam_mode: IamMode::Strict,
1778            credential_resolver: None,
1779            policy_evaluator: None,
1780            resource_policy_provider: None,
1781            scp_resolver: None,
1782        };
1783        assert!(cfg.verify_sigv4);
1784        assert!(cfg.iam_mode.is_strict());
1785        assert!(cfg.resource_policy_provider.is_none());
1786        assert!(cfg.scp_resolver.is_none());
1787    }
1788
1789    fn s3_sigv4_headers() -> http::HeaderMap {
1790        let mut headers = http::HeaderMap::new();
1791        headers.insert(
1792            "authorization",
1793            "AWS4-HMAC-SHA256 Credential=test/20240101/us-east-1/s3/aws4_request, \
1794             SignedHeaders=host, Signature=fake"
1795                .parse()
1796                .unwrap(),
1797        );
1798        headers
1799    }
1800
1801    #[test]
1802    fn streaming_route_path_style_s3_put_object() {
1803        let headers = s3_sigv4_headers();
1804        assert_eq!(
1805            streaming_route(
1806                &http::Method::PUT,
1807                "/my-bucket/key.txt",
1808                &headers,
1809                &HashMap::new(),
1810            ),
1811            Some(("s3", "")),
1812        );
1813    }
1814
1815    #[test]
1816    fn streaming_route_path_style_create_bucket_skipped() {
1817        // `PUT /bucket` (no trailing key) is CreateBucket — must NOT
1818        // hit the streaming path.
1819        let headers = s3_sigv4_headers();
1820        assert_eq!(
1821            streaming_route(&http::Method::PUT, "/my-bucket", &headers, &HashMap::new(),),
1822            None,
1823        );
1824    }
1825
1826    #[test]
1827    fn streaming_route_virtual_hosted_s3_put_object() {
1828        let mut headers = s3_sigv4_headers();
1829        headers.insert(
1830            "host",
1831            "vhost-bucket.s3.us-east-1.localhost.localstack.cloud:4566"
1832                .parse()
1833                .unwrap(),
1834        );
1835        // Virtual-hosted PUT has no bucket in the URL path (`/<key>`),
1836        // so the slash check used for path-style would reject it. The
1837        // Host parser confirms this is virtual-hosted S3 and the key
1838        // flows through the streaming dispatch.
1839        assert_eq!(
1840            streaming_route(&http::Method::PUT, "/hello.txt", &headers, &HashMap::new(),),
1841            Some(("s3", "")),
1842        );
1843    }
1844
1845    #[test]
1846    fn streaming_route_virtual_hosted_s3_root_skipped() {
1847        // `PUT /` against a virtual-hosted Host = CreateBucket, which
1848        // is handled buffered. Empty path-after-slash must short-circuit.
1849        let mut headers = s3_sigv4_headers();
1850        headers.insert(
1851            "host",
1852            "vhost-bucket.s3.us-east-1.localhost.localstack.cloud:4566"
1853                .parse()
1854                .unwrap(),
1855        );
1856        assert_eq!(
1857            streaming_route(&http::Method::PUT, "/", &headers, &HashMap::new()),
1858            None,
1859        );
1860    }
1861
1862    #[test]
1863    fn streaming_route_ecr_blob_upload() {
1864        let headers = http::HeaderMap::new();
1865        assert_eq!(
1866            streaming_route(
1867                &http::Method::PATCH,
1868                "/v2/my-repo/blobs/uploads/abcd1234",
1869                &headers,
1870                &HashMap::new(),
1871            ),
1872            Some(("ecr", "")),
1873        );
1874        assert_eq!(
1875            streaming_route(
1876                &http::Method::PUT,
1877                "/v2/my-repo/blobs/uploads/abcd1234",
1878                &headers,
1879                &HashMap::new(),
1880            ),
1881            Some(("ecr", "")),
1882        );
1883    }
1884
1885    #[test]
1886    fn streaming_route_presigned_v4_s3_put() {
1887        let headers = http::HeaderMap::new();
1888        let mut query_params = HashMap::new();
1889        query_params.insert(
1890            "X-Amz-Credential".to_string(),
1891            "test/20240101/us-east-1/s3/aws4_request".to_string(),
1892        );
1893        assert_eq!(
1894            streaming_route(
1895                &http::Method::PUT,
1896                "/my-bucket/key.txt",
1897                &headers,
1898                &query_params,
1899            ),
1900            Some(("s3", "")),
1901        );
1902    }
1903
1904    #[test]
1905    fn streaming_route_non_s3_auth_header_skipped() {
1906        // Same path shape but the SigV4 service is lambda — must not
1907        // wire the streaming dispatch (Lambda has its own buffered path).
1908        let mut headers = http::HeaderMap::new();
1909        headers.insert(
1910            "authorization",
1911            "AWS4-HMAC-SHA256 Credential=test/20240101/us-east-1/lambda/aws4_request, \
1912             SignedHeaders=host, Signature=fake"
1913                .parse()
1914                .unwrap(),
1915        );
1916        assert_eq!(
1917            streaming_route(
1918                &http::Method::PUT,
1919                "/my-bucket/key.txt",
1920                &headers,
1921                &HashMap::new(),
1922            ),
1923            None,
1924        );
1925    }
1926
1927    #[test]
1928    fn streaming_route_get_skipped() {
1929        let headers = s3_sigv4_headers();
1930        assert_eq!(
1931            streaming_route(
1932                &http::Method::GET,
1933                "/my-bucket/key.txt",
1934                &headers,
1935                &HashMap::new(),
1936            ),
1937            None,
1938        );
1939    }
1940}