1use axum::body::Body;
2use axum::extract::{Extension, Query};
3use axum::http::{Request, StatusCode};
4use axum::response::Response;
5use std::collections::HashMap;
6use std::sync::Arc;
7
8use crate::protocol::{self, AwsProtocol};
9use crate::registry::ServiceRegistry;
10use crate::service::AwsRequest;
11
12pub async fn dispatch(
14 Extension(registry): Extension<Arc<ServiceRegistry>>,
15 Extension(config): Extension<Arc<DispatchConfig>>,
16 Query(query_params): Query<HashMap<String, String>>,
17 request: Request<Body>,
18) -> Response<Body> {
19 let request_id = uuid::Uuid::new_v4().to_string();
20
21 let (parts, body) = request.into_parts();
22 let body_bytes = match axum::body::to_bytes(body, 10 * 1024 * 1024).await {
23 Ok(b) => b,
24 Err(_) => {
25 return build_error_response(
26 StatusCode::PAYLOAD_TOO_LARGE,
27 "RequestEntityTooLarge",
28 "Request body too large",
29 &request_id,
30 AwsProtocol::Query,
31 );
32 }
33 };
34
35 let detected = match protocol::detect_service(&parts.headers, &query_params, &body_bytes) {
37 Some(d) => d,
38 None => {
39 if parts.method == http::Method::OPTIONS {
42 protocol::DetectedRequest {
43 service: "s3".to_string(),
44 action: String::new(),
45 protocol: AwsProtocol::Rest,
46 }
47 } else {
48 return build_error_response(
49 StatusCode::BAD_REQUEST,
50 "MissingAction",
51 "Could not determine target service or action from request",
52 &request_id,
53 AwsProtocol::Query,
54 );
55 }
56 }
57 };
58
59 let service = match registry.get(&detected.service) {
61 Some(s) => s,
62 None => {
63 return build_error_response(
64 detected.protocol.error_status(),
65 "UnknownService",
66 &format!("Service '{}' is not available", detected.service),
67 &request_id,
68 detected.protocol,
69 );
70 }
71 };
72
73 let sigv4_info = fakecloud_aws::sigv4::parse_sigv4(
75 parts
76 .headers
77 .get("authorization")
78 .and_then(|v| v.to_str().ok())
79 .unwrap_or(""),
80 );
81 let access_key_id = sigv4_info.as_ref().map(|info| info.access_key.clone());
82 let region = sigv4_info
83 .map(|info| info.region)
84 .or_else(|| extract_region_from_user_agent(&parts.headers))
85 .unwrap_or_else(|| config.region.clone());
86
87 let path = parts.uri.path().to_string();
89 let path_segments: Vec<String> = path
90 .split('/')
91 .filter(|s| !s.is_empty())
92 .map(|s| s.to_string())
93 .collect();
94
95 if detected.protocol == AwsProtocol::Json
97 && !body_bytes.is_empty()
98 && serde_json::from_slice::<serde_json::Value>(&body_bytes).is_err()
99 {
100 return build_error_response(
101 StatusCode::BAD_REQUEST,
102 "SerializationException",
103 "Start of structure or map found where not expected",
104 &request_id,
105 AwsProtocol::Json,
106 );
107 }
108
109 let mut all_params = query_params;
111 if detected.protocol == AwsProtocol::Query {
112 let body_params = protocol::parse_query_body(&body_bytes);
113 for (k, v) in body_params {
114 all_params.entry(k).or_insert(v);
115 }
116 }
117
118 let aws_request = AwsRequest {
119 service: detected.service.clone(),
120 action: detected.action.clone(),
121 region,
122 account_id: config.account_id.clone(),
123 request_id: request_id.clone(),
124 headers: parts.headers,
125 query_params: all_params,
126 body: body_bytes,
127 path_segments,
128 raw_path: path,
129 method: parts.method,
130 is_query_protocol: detected.protocol == AwsProtocol::Query,
131 access_key_id,
132 };
133
134 tracing::info!(
135 service = %aws_request.service,
136 action = %aws_request.action,
137 request_id = %aws_request.request_id,
138 "handling request"
139 );
140
141 match service.handle(aws_request).await {
142 Ok(resp) => {
143 let mut builder = Response::builder()
144 .status(resp.status)
145 .header("x-amzn-requestid", &request_id)
146 .header("x-amz-request-id", &request_id);
147
148 if !resp.content_type.is_empty() {
149 builder = builder.header("content-type", &resp.content_type);
150 }
151
152 for (k, v) in &resp.headers {
153 builder = builder.header(k, v);
154 }
155
156 builder.body(Body::from(resp.body)).unwrap()
157 }
158 Err(err) => {
159 tracing::warn!(
160 service = %detected.service,
161 action = %detected.action,
162 error = %err,
163 "request failed"
164 );
165 let error_headers = err.response_headers().to_vec();
166 let mut resp = build_error_response_with_fields(
167 err.status(),
168 err.code(),
169 &err.message(),
170 &request_id,
171 detected.protocol,
172 err.extra_fields(),
173 );
174 for (k, v) in &error_headers {
175 if let (Ok(name), Ok(val)) = (
176 k.parse::<http::header::HeaderName>(),
177 v.parse::<http::header::HeaderValue>(),
178 ) {
179 resp.headers_mut().insert(name, val);
180 }
181 }
182 resp
183 }
184 }
185}
186
187#[derive(Debug, Clone)]
189pub struct DispatchConfig {
190 pub region: String,
191 pub account_id: String,
192}
193
194fn extract_region_from_user_agent(headers: &http::HeaderMap) -> Option<String> {
196 let ua = headers.get("user-agent")?.to_str().ok()?;
197 for part in ua.split_whitespace() {
198 if let Some(region) = part.strip_prefix("region/") {
199 if !region.is_empty() {
200 return Some(region.to_string());
201 }
202 }
203 }
204 None
205}
206
207fn build_error_response(
208 status: StatusCode,
209 code: &str,
210 message: &str,
211 request_id: &str,
212 protocol: AwsProtocol,
213) -> Response<Body> {
214 build_error_response_with_fields(status, code, message, request_id, protocol, &[])
215}
216
217fn build_error_response_with_fields(
218 status: StatusCode,
219 code: &str,
220 message: &str,
221 request_id: &str,
222 protocol: AwsProtocol,
223 extra_fields: &[(String, String)],
224) -> Response<Body> {
225 let (status, content_type, body) = match protocol {
226 AwsProtocol::Query => {
227 fakecloud_aws::error::xml_error_response(status, code, message, request_id)
228 }
229 AwsProtocol::Rest => fakecloud_aws::error::s3_xml_error_response_with_fields(
230 status,
231 code,
232 message,
233 request_id,
234 extra_fields,
235 ),
236 AwsProtocol::Json => fakecloud_aws::error::json_error_response(status, code, message),
237 };
238
239 Response::builder()
240 .status(status)
241 .header("content-type", content_type)
242 .header("x-amzn-requestid", request_id)
243 .header("x-amz-request-id", request_id)
244 .body(Body::from(body))
245 .unwrap()
246}
247
248trait ProtocolExt {
249 fn error_status(&self) -> StatusCode;
250}
251
252impl ProtocolExt for AwsProtocol {
253 fn error_status(&self) -> StatusCode {
254 StatusCode::BAD_REQUEST
255 }
256}