Skip to main content

turul_a2a_aws_lambda/
adapter.rs

1//! Request/response conversion between Lambda and axum.
2
3use axum::body::Body;
4use http_body_util::BodyExt;
5
6/// Header prefix for authorizer context. Client-supplied headers with this
7/// prefix are stripped (anti-spoofing).
8pub const AUTHORIZER_HEADER_PREFIX: &str = "x-authorizer-";
9
10/// Convert a Lambda HTTP request to an axum request.
11///
12/// - Strips any client-supplied x-authorizer-* headers (anti-spoofing)
13/// - Injects authorizer context from Lambda requestContext as x-authorizer-* headers
14/// - Preserves all other headers, method, URI, body
15pub fn lambda_to_axum_request(
16    event: lambda_http::Request,
17) -> Result<http::Request<Body>, lambda_http::Error> {
18    let (mut parts, body) = event.into_parts();
19
20    // Anti-spoofing: strip ALL client-supplied x-authorizer-* headers
21    let keys_to_remove: Vec<http::header::HeaderName> = parts
22        .headers
23        .keys()
24        .filter(|k| k.as_str().starts_with(AUTHORIZER_HEADER_PREFIX))
25        .cloned()
26        .collect();
27    for key in keys_to_remove {
28        parts.headers.remove(&key);
29    }
30
31    // Extract authorizer context from Lambda extensions and inject as headers.
32    // The exact structure depends on the API Gateway type (v1, v2, ALB).
33    // We use a generic approach: look for the RequestContext extension and
34    // extract authorizer fields from it.
35    if let Some(ctx) = parts
36        .extensions
37        .get::<lambda_http::request::RequestContext>()
38    {
39        match ctx {
40            lambda_http::request::RequestContext::ApiGatewayV2(apigw) => {
41                if let Some(ref authorizer) = apigw.authorizer {
42                    // JWT authorizer: claims are in jwt.claims (HashMap<String, String>)
43                    if let Some(ref jwt) = authorizer.jwt {
44                        for (key, value) in &jwt.claims {
45                            inject_authorizer_header(&mut parts.headers, key, value);
46                        }
47                    }
48                    // Lambda authorizer: context fields
49                    // In lambda_http v1, these may be in authorizer.fields or similar
50                    // For now, JWT claims are the primary path
51                }
52            }
53            lambda_http::request::RequestContext::ApiGatewayV1(apigw) => {
54                // V1 authorizer context fields
55                for (key, value) in &apigw.authorizer.fields {
56                    if let serde_json::Value::String(s) = value {
57                        inject_authorizer_header(&mut parts.headers, key, s);
58                    }
59                }
60            }
61            _ => {} // ALB, etc. — no authorizer extraction
62        }
63    }
64
65    // Convert body
66    let body_bytes: bytes::Bytes = match body {
67        lambda_http::Body::Empty => bytes::Bytes::new(),
68        lambda_http::Body::Text(s) => bytes::Bytes::from(s),
69        lambda_http::Body::Binary(b) => bytes::Bytes::from(b),
70        _ => bytes::Bytes::new(),
71    };
72
73    let req = http::Request::from_parts(parts, Body::from(body_bytes));
74    Ok(req)
75}
76
77/// Rewrite `req.uri()` to drop a leading `prefix` from the path, if
78/// present. Preserves query string, scheme, authority. If `prefix` is
79/// `/` or the path does not start with `prefix`, the request is
80/// returned unchanged (callers downstream will 404 on a genuinely
81/// unknown path — that's the correct failure mode).
82///
83/// A path that equals `prefix` exactly becomes `/` so root-routed
84/// handlers reach the router.
85pub(crate) fn strip_request_path_prefix(
86    mut req: http::Request<Body>,
87    prefix: &str,
88) -> http::Request<Body> {
89    if prefix.is_empty() || prefix == "/" {
90        return req;
91    }
92    let uri = req.uri().clone();
93    let path = uri.path();
94    if !path.starts_with(prefix) {
95        return req;
96    }
97    let rest = &path[prefix.len()..];
98    let new_path = if rest.is_empty() || !rest.starts_with('/') {
99        // path == prefix → "/"; or prefix matches mid-segment
100        // (`/devs` vs `/dev`) → do not strip.
101        if rest.is_empty() {
102            "/"
103        } else {
104            return req;
105        }
106    } else {
107        rest
108    };
109
110    let path_and_query = match uri.query() {
111        Some(q) => format!("{new_path}?{q}"),
112        None => new_path.to_string(),
113    };
114
115    let mut parts = uri.into_parts();
116    parts.path_and_query = match http::uri::PathAndQuery::from_maybe_shared(path_and_query) {
117        Ok(pq) => Some(pq),
118        Err(_) => return req,
119    };
120    if let Ok(new_uri) = http::Uri::from_parts(parts) {
121        *req.uri_mut() = new_uri;
122    }
123    req
124}
125
126fn inject_authorizer_header(headers: &mut http::HeaderMap, key: &str, value: &str) {
127    let header_name = format!("{AUTHORIZER_HEADER_PREFIX}{}", key.to_lowercase());
128    if let Ok(name) = http::header::HeaderName::from_bytes(header_name.as_bytes())
129        && let Ok(val) = http::header::HeaderValue::from_str(value)
130    {
131        headers.insert(name, val);
132    }
133}
134
135/// Convert an axum response to a Lambda HTTP response.
136pub async fn axum_to_lambda_response(
137    resp: http::Response<Body>,
138) -> Result<lambda_http::Response<lambda_http::Body>, lambda_http::Error> {
139    let (parts, body) = resp.into_parts();
140    let body_bytes = body
141        .collect()
142        .await
143        .map_err(|e| lambda_http::Error::from(format!("Body collect error: {e}")))?
144        .to_bytes();
145
146    let lambda_body = if body_bytes.is_empty() {
147        lambda_http::Body::Empty
148    } else {
149        lambda_http::Body::Text(String::from_utf8_lossy(&body_bytes).into_owned())
150    };
151
152    let resp = http::Response::from_parts(parts, lambda_body);
153    Ok(resp)
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    #[test]
161    fn strips_client_supplied_authorizer_headers() {
162        let req: lambda_http::Request = http::Request::builder()
163            .method("POST")
164            .uri("/message:send")
165            .header("content-type", "application/json")
166            .header("a2a-version", "1.0")
167            .header("x-authorizer-userid", "forged-admin")
168            .header("x-authorizer-role", "superuser")
169            .header("x-real-header", "keep-this")
170            .body(lambda_http::Body::Text("{}".into()))
171            .unwrap();
172
173        let axum_req = lambda_to_axum_request(req).unwrap();
174
175        // Forged headers must be stripped
176        assert!(
177            axum_req.headers().get("x-authorizer-userid").is_none(),
178            "Forged x-authorizer-userid must be stripped"
179        );
180        assert!(
181            axum_req.headers().get("x-authorizer-role").is_none(),
182            "Forged x-authorizer-role must be stripped"
183        );
184
185        // Legitimate headers preserved
186        assert_eq!(
187            axum_req.headers().get("x-real-header").unwrap(),
188            "keep-this"
189        );
190        assert_eq!(
191            axum_req.headers().get("content-type").unwrap(),
192            "application/json"
193        );
194    }
195
196    /// Convert a raw API Gateway event the way the Lambda runtime does.
197    fn lambda_request_from_event(event: serde_json::Value) -> lambda_http::Request {
198        let req: lambda_http::request::LambdaRequest =
199            serde_json::from_value(event).expect("valid API Gateway event");
200        req.into()
201    }
202
203    /// The trust boundary: an authorizer value API Gateway put in
204    /// `requestContext` reaches the router as `x-authorizer-*`, while a
205    /// client-sent header of the same name — or any other
206    /// `x-authorizer-*` header — is dropped.
207    #[test]
208    fn apigw_v2_jwt_claims_survive_and_forged_headers_are_stripped() {
209        let event = serde_json::json!({
210            "version": "2.0",
211            "routeKey": "POST /message:send",
212            "rawPath": "/message:send",
213            "rawQueryString": "",
214            "headers": {
215                "content-type": "application/json",
216                "x-authorizer-sub": "forged-admin",
217                "x-authorizer-role": "superuser"
218            },
219            "requestContext": {
220                "accountId": "000000000000",
221                "apiId": "api",
222                "authorizer": {"jwt": {"claims": {"sub": "legit-user"}, "scopes": null}},
223                "domainName": "fake.execute-api",
224                "domainPrefix": "fake",
225                "http": {
226                    "method": "POST",
227                    "path": "/message:send",
228                    "protocol": "HTTP/1.1",
229                    "sourceIp": "127.0.0.1",
230                    "userAgent": "test"
231                },
232                "requestId": "rid",
233                "routeKey": "POST /message:send",
234                "stage": "$default",
235                "time": "01/Jan/2026:00:00:00 +0000",
236                "timeEpoch": 1_735_689_600_000i64
237            },
238            "body": "{}",
239            "isBase64Encoded": false
240        });
241
242        let axum_req = lambda_to_axum_request(lambda_request_from_event(event)).unwrap();
243        let values = |name: &str| -> Vec<String> {
244            axum_req
245                .headers()
246                .get_all(name)
247                .iter()
248                .map(|v| v.to_str().unwrap().to_string())
249                .collect()
250        };
251        assert_eq!(values("x-authorizer-sub"), vec!["legit-user".to_string()]);
252        assert!(values("x-authorizer-role").is_empty(), "forged header kept");
253        assert_eq!(values("content-type"), vec!["application/json".to_string()]);
254    }
255
256    #[test]
257    fn apigw_v1_authorizer_context_survives_and_forged_headers_are_stripped() {
258        let event = serde_json::json!({
259            "resource": "/{proxy+}",
260            "path": "/message:send",
261            "httpMethod": "POST",
262            "headers": {
263                "content-type": "application/json",
264                "x-authorizer-principalid": "forged-admin",
265                "x-authorizer-role": "superuser"
266            },
267            "multiValueHeaders": {},
268            "queryStringParameters": null,
269            "multiValueQueryStringParameters": null,
270            "pathParameters": {"proxy": "message:send"},
271            "stageVariables": null,
272            "requestContext": {
273                "accountId": "000000000000",
274                "apiId": "abc123",
275                "authorizer": {"principalId": "legit-principal"},
276                "domainName": "fake.execute-api",
277                "domainPrefix": "fake",
278                "extendedRequestId": "xrid",
279                "httpMethod": "POST",
280                "identity": {"sourceIp": "127.0.0.1", "userAgent": "test"},
281                "path": "/message:send",
282                "protocol": "HTTP/1.1",
283                "requestId": "rid",
284                "requestTime": "01/Jan/2026:00:00:00 +0000",
285                "requestTimeEpoch": 1_735_689_600_000i64,
286                "resourceId": "rsrc",
287                "resourcePath": "/{proxy+}",
288                "stage": "$default"
289            },
290            "body": "{}",
291            "isBase64Encoded": false
292        });
293
294        let axum_req = lambda_to_axum_request(lambda_request_from_event(event)).unwrap();
295        let values = |name: &str| -> Vec<String> {
296            axum_req
297                .headers()
298                .get_all(name)
299                .iter()
300                .map(|v| v.to_str().unwrap().to_string())
301                .collect()
302        };
303        assert_eq!(
304            values("x-authorizer-principalid"),
305            vec!["legit-principal".to_string()]
306        );
307        assert!(values("x-authorizer-role").is_empty(), "forged header kept");
308    }
309
310    #[test]
311    fn inject_authorizer_header_works() {
312        let mut headers = http::HeaderMap::new();
313        inject_authorizer_header(&mut headers, "userId", "user-123");
314        assert_eq!(headers.get("x-authorizer-userid").unwrap(), "user-123");
315    }
316
317    fn uri_only(path_and_query: &str) -> http::Request<Body> {
318        http::Request::builder()
319            .method("GET")
320            .uri(path_and_query)
321            .body(Body::empty())
322            .unwrap()
323    }
324
325    #[test]
326    fn strip_path_prefix_removes_api_gateway_stage_and_resource_prefix() {
327        let req = uri_only("/stage/agent/message:send");
328        let out = strip_request_path_prefix(req, "/stage/agent");
329        assert_eq!(out.uri().path(), "/message:send");
330    }
331
332    #[test]
333    fn strip_path_prefix_preserves_query_string() {
334        let req = uri_only("/stage/agent/tasks/abc?historyLength=5");
335        let out = strip_request_path_prefix(req, "/stage/agent");
336        assert_eq!(out.uri().path(), "/tasks/abc");
337        assert_eq!(out.uri().query(), Some("historyLength=5"));
338    }
339
340    #[test]
341    fn strip_path_prefix_handles_root_after_strip() {
342        // Path exactly equals prefix (e.g. agent-card at the prefix root).
343        let req = uri_only("/stage/agent");
344        let out = strip_request_path_prefix(req, "/stage/agent");
345        assert_eq!(out.uri().path(), "/");
346    }
347
348    #[test]
349    fn strip_path_prefix_passes_through_when_prefix_absent() {
350        let req = uri_only("/message:send");
351        let out = strip_request_path_prefix(req, "/stage/agent");
352        assert_eq!(
353            out.uri().path(),
354            "/message:send",
355            "non-matching prefix must not mutate path"
356        );
357    }
358
359    #[test]
360    fn strip_path_prefix_rejects_mid_segment_match() {
361        // "/dev" is a prefix of "/devs/foo" as a string, but not as a
362        // path segment — must not strip.
363        let req = uri_only("/devs/foo");
364        let out = strip_request_path_prefix(req, "/dev");
365        assert_eq!(out.uri().path(), "/devs/foo");
366    }
367
368    #[test]
369    fn strip_path_prefix_noop_on_empty_or_slash_config() {
370        let req = uri_only("/message:send");
371        let out = strip_request_path_prefix(req, "/");
372        assert_eq!(out.uri().path(), "/message:send");
373        let req = uri_only("/message:send");
374        let out = strip_request_path_prefix(req, "");
375        assert_eq!(out.uri().path(), "/message:send");
376    }
377
378    #[test]
379    fn strip_path_prefix_well_known_and_jsonrpc() {
380        let prefix = "/stage/agent";
381        for (input, expected) in [
382            (
383                "/stage/agent/.well-known/agent-card.json",
384                "/.well-known/agent-card.json",
385            ),
386            ("/stage/agent/jsonrpc", "/jsonrpc"),
387            ("/stage/agent/tasks/abc:cancel", "/tasks/abc:cancel"),
388            ("/stage/agent/extendedAgentCard", "/extendedAgentCard"),
389        ] {
390            let req = uri_only(input);
391            let out = strip_request_path_prefix(req, prefix);
392            assert_eq!(out.uri().path(), expected, "input: {input}");
393        }
394    }
395}