turul-mcp-aws-lambda 0.3.45

AWS Lambda integration for turul-mcp-framework servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
//! HTTP type conversion utilities for Lambda MCP requests
//!
//! This module provides comprehensive conversion between lambda_http and hyper types,
//! enabling seamless integration between Lambda's HTTP model and the SessionMcpHandler.

use std::collections::HashMap;
use std::str::FromStr;

use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::Response as HyperResponse;
use lambda_http::{Body as LambdaBody, Request as LambdaRequest, Response as LambdaResponse};
use tracing::{debug, trace};

use crate::error::{LambdaError, Result};

/// Type alias for the unified MCP response body used by SessionMcpHandler
type UnifiedMcpBody = http_body_util::combinators::UnsyncBoxBody<Bytes, hyper::Error>;

/// Error mapping function for Full<Bytes>
fn infallible_to_hyper_error(never: std::convert::Infallible) -> hyper::Error {
    match never {}
}

/// Type alias for Full<Bytes> with mapped error type compatible with SessionMcpHandler
type MappedFullBody =
    http_body_util::combinators::MapErr<Full<Bytes>, fn(std::convert::Infallible) -> hyper::Error>;

/// Convert lambda_http::Request to hyper::Request<MappedFullBody>
///
/// This enables delegation to SessionMcpHandler by converting Lambda's request format
/// to the hyper format expected by the framework. All headers are preserved, and Lambda
/// authorizer context (if present) is extracted and injected as `x-authorizer-*` headers.
///
/// # Authorizer Context
///
/// If the request includes API Gateway authorizer context, fields are extracted and
/// added as headers with the `x-authorizer-` prefix. This makes authorizer data
/// available to middleware via `RequestContext.metadata`.
///
/// Field names are sanitized (lowercase, alphanumeric + dash/underscore only).
/// Invalid header names/values are skipped gracefully.
pub fn lambda_to_hyper_request(
    lambda_req: LambdaRequest,
) -> Result<hyper::Request<MappedFullBody>> {
    // Extract authorizer context BEFORE consuming request
    let authorizer_fields = extract_authorizer_context(&lambda_req);

    // Convert to parts (consumes request)
    let (mut parts, lambda_body) = lambda_req.into_parts();

    // Inject authorizer fields as x-authorizer-* headers (defensive - skip failures)
    for (field_name, field_value) in authorizer_fields {
        let header_name = format!("x-authorizer-{}", field_name);

        // Try to create HeaderName and HeaderValue
        // Skip entry if either fails (defensive - don't break request)
        let Ok(name) = http::HeaderName::from_str(&header_name) else {
            debug!(
                "Skipping authorizer field '{}' - invalid header name",
                field_name
            );
            continue;
        };

        let Ok(value) = http::HeaderValue::from_str(&field_value) else {
            debug!(
                "Skipping authorizer field '{}' - invalid header value",
                field_name
            );
            continue;
        };

        parts.headers.insert(name, value);
        trace!(
            "Injected authorizer header: {} = {}",
            header_name, field_value
        );
    }

    // Convert LambdaBody to Bytes
    let body_bytes = match lambda_body {
        LambdaBody::Empty => Bytes::new(),
        LambdaBody::Text(s) => Bytes::from(s),
        LambdaBody::Binary(b) => Bytes::from(b),
        _ => Bytes::new(),
    };

    // Create Full<Bytes> body and map error type to hyper::Error
    let full_body = Full::new(body_bytes)
        .map_err(infallible_to_hyper_error as fn(std::convert::Infallible) -> hyper::Error);

    // Create hyper Request with enhanced headers
    let hyper_req = hyper::Request::from_parts(parts, full_body);

    debug!(
        "Converted Lambda request: {} {} -> hyper::Request<Full<Bytes>>",
        hyper_req.method(),
        hyper_req.uri()
    );

    Ok(hyper_req)
}

/// Convert hyper::Response<UnifiedMcpBody> to lambda_http::Response<LambdaBody>
///
/// This collects the streaming body into a LambdaBody for non-streaming responses.
/// Used by the handle() method which returns snapshot responses.
pub async fn hyper_to_lambda_response(
    hyper_resp: HyperResponse<UnifiedMcpBody>,
) -> Result<LambdaResponse<LambdaBody>> {
    let (parts, body) = hyper_resp.into_parts();

    // Collect the body into bytes
    let body_bytes = match body.collect().await {
        Ok(collected) => collected.to_bytes(),
        Err(err) => {
            return Err(LambdaError::Body(format!(
                "Failed to collect response body: {}",
                err
            )));
        }
    };

    // Convert to LambdaBody
    let lambda_body = if body_bytes.is_empty() {
        LambdaBody::Empty
    } else {
        // Try to convert to text if it's valid UTF-8, otherwise use binary
        match String::from_utf8(body_bytes.to_vec()) {
            Ok(text) => LambdaBody::Text(text),
            Err(_) => LambdaBody::Binary(body_bytes.to_vec()),
        }
    };

    // Create Lambda response with preserved headers
    let lambda_resp = LambdaResponse::from_parts(parts, lambda_body);

    debug!(
        "Converted hyper response -> Lambda response (status: {})",
        lambda_resp.status()
    );

    Ok(lambda_resp)
}

/// Convert hyper::Response<UnifiedMcpBody> to lambda_http streaming response
///
/// This preserves the streaming body for real-time SSE responses.
/// Used by the handle_streaming() method for true streaming.
pub fn hyper_to_lambda_streaming(
    hyper_resp: HyperResponse<UnifiedMcpBody>,
) -> lambda_http::Response<UnifiedMcpBody> {
    let (parts, body) = hyper_resp.into_parts();

    // Direct passthrough - no body collection, preserves streaming
    let lambda_resp = lambda_http::Response::from_parts(parts, body);

    debug!(
        "Converted hyper response -> Lambda streaming response (status: {})",
        lambda_resp.status()
    );

    lambda_resp
}

/// Convert camelCase or PascalCase to snake_case
///
/// # Examples
///
/// ```no_run
/// # use turul_mcp_aws_lambda::adapter::camel_to_snake;
/// assert_eq!(camel_to_snake("userId"), "user_id");
/// assert_eq!(camel_to_snake("deviceId"), "device_id");
/// assert_eq!(camel_to_snake("APIKey"), "api_key");
/// assert_eq!(camel_to_snake("HTTPSEnabled"), "https_enabled");
/// assert_eq!(camel_to_snake("user_id"), "user_id");
/// ```
pub fn camel_to_snake(s: &str) -> String {
    let mut result = String::new();
    let chars: Vec<char> = s.chars().collect();

    for i in 0..chars.len() {
        let ch = chars[i];

        if ch.is_uppercase() {
            let is_first = i == 0;
            let prev_is_lower = i > 0 && chars[i - 1].is_lowercase();
            let next_is_lower = i + 1 < chars.len() && chars[i + 1].is_lowercase();

            // Add underscore before uppercase if:
            // - Not at start AND
            // - (Previous was lowercase OR next is lowercase)
            if !is_first && (prev_is_lower || next_is_lower) {
                result.push('_');
            }

            result.push(ch.to_ascii_lowercase());
        } else {
            result.push(ch);
        }
    }

    result
}

/// Sanitize authorizer field name for use in HTTP headers
///
/// Converts field names to valid HTTP header format:
/// 1. Convert camelCase to snake_case (userId → user_id)
/// 2. ASCII lowercase
/// 3. Replace non-alphanumeric (except _ and -) with dash
///
/// # Examples
///
/// ```no_run
/// # use turul_mcp_aws_lambda::adapter::sanitize_authorizer_field_name;
/// assert_eq!(sanitize_authorizer_field_name("userId"), "user_id");
/// assert_eq!(sanitize_authorizer_field_name("deviceId"), "device_id");
/// assert_eq!(sanitize_authorizer_field_name("device_id"), "device_id");
/// assert_eq!(sanitize_authorizer_field_name("user@email"), "user-email");
/// ```
pub fn sanitize_authorizer_field_name(field: &str) -> String {
    // Step 1: Convert camelCase to snake_case
    let snake_case = camel_to_snake(field);

    // Step 2: Sanitize for HTTP header compatibility
    snake_case
        .to_ascii_lowercase()
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
                c
            } else {
                '-'
            }
        })
        .collect()
}

/// Extract authorizer context from Lambda request extensions
///
/// Supports both API Gateway V1 (REST API) and V2 (HTTP API) formats.
/// Returns HashMap with snake_case keys ready for header injection.
///
/// # Behavior
///
/// - Returns empty HashMap if no authorizer context present
/// - Converts camelCase to snake_case (userId → user_id)
/// - Skips fields that fail sanitization
/// - Converts non-string values to JSON strings
/// - Handles `ApiGateway.authorizer.fields["lambda"]` (V1 nested) or direct fields (V1 flat)
/// - Handles `ApiGatewayV2.authorizer.fields` (V2, deserialized from "lambda" key by serde)
///
/// # Examples
///
/// ```no_run
/// # use lambda_http::Request;
/// # use turul_mcp_aws_lambda::adapter::extract_authorizer_context;
/// # let request: Request = unimplemented!();
/// let fields = extract_authorizer_context(&request);
/// assert_eq!(fields.get("account_id"), Some(&"acc_123".to_string()));
/// ```
pub fn extract_authorizer_context(req: &LambdaRequest) -> HashMap<String, String> {
    use lambda_http::request::RequestContext;

    let mut fields = HashMap::new();

    // Get RequestContext from extensions
    let Some(request_context) = req.extensions().get::<RequestContext>() else {
        return fields; // No context, return empty
    };

    // Diagnostic: log raw authorizer context shape (debug level only)
    match request_context {
        RequestContext::ApiGatewayV1(ctx) => {
            debug!(
                authorizer_field_count = ctx.authorizer.fields.len(),
                authorizer_keys = ?ctx.authorizer.fields.keys().collect::<Vec<_>>(),
                "V1 REST API authorizer context"
            );
        }
        RequestContext::ApiGatewayV2(ctx) => {
            if let Some(ref authorizer) = ctx.authorizer {
                debug!(
                    authorizer_field_count = authorizer.fields.len(),
                    authorizer_keys = ?authorizer.fields.keys().collect::<Vec<_>>(),
                    "V2 HTTP API authorizer context"
                );
            } else {
                debug!("V2 HTTP API: no authorizer present");
            }
        }
        _ => {
            debug!("Non-API Gateway request context (ALB or other)");
        }
    }

    // Extract authorizer fields based on API Gateway version
    // V1: flat HashMap (may contain "lambda" key or direct fields)
    // V2: fields in ctx.authorizer.fields (deserialized from "lambda" key by serde)
    let mut authorizer_fields_map = HashMap::new();

    match request_context {
        RequestContext::ApiGatewayV2(ctx) => {
            // API Gateway V2 (HTTP API) format - already HashMap
            if let Some(ref authorizer) = ctx.authorizer {
                for (key, value) in &authorizer.fields {
                    authorizer_fields_map.insert(key.clone(), value.clone());
                }
            }
        }
        RequestContext::ApiGatewayV1(ctx) => {
            // API Gateway V1 (REST API) — authorizer fields are deserialized as a
            // flat HashMap by aws_lambda_events. Two shapes occur:
            //   1. Nested: { "lambda": { "userId": "...", ... } }
            //   2. Flat: { "userId": "...", "accountId": "..." }
            // Try nested "lambda" first, then fall back to flat top-level fields.
            if let Some(serde_json::Value::Object(auth_map)) = ctx.authorizer.fields.get("lambda") {
                for (key, value) in auth_map {
                    authorizer_fields_map.insert(key.clone(), value.clone());
                }
            } else {
                // Flat shape — iterate all fields, skip known API Gateway internals:
                //   principalId        — required authorizer output, not user context
                //   integrationLatency — injected by API Gateway
                //   usageIdentifierKey — API key for usage plans (apiKeySource=AUTHORIZER)
                for (key, value) in &ctx.authorizer.fields {
                    if key == "principalId"
                        || key == "integrationLatency"
                        || key == "usageIdentifierKey"
                    {
                        continue;
                    }
                    authorizer_fields_map.insert(key.clone(), value.clone());
                }
            }
        }
        _ => {} // Other contexts (ALB, etc.) - no authorizer
    }

    // Convert extracted fields to sanitized headers
    for (key, value) in authorizer_fields_map {
        // Sanitize field name for header compatibility
        let sanitized_key = sanitize_authorizer_field_name(&key);

        // Convert value to string
        let value_str = match value {
            serde_json::Value::String(s) => s,
            other => other.to_string(), // JSON serialize non-strings
        };

        fields.insert(sanitized_key, value_str);
    }

    if !fields.is_empty() {
        debug!(
            "Extracted {} authorizer fields from Lambda context",
            fields.len()
        );
    }

    fields
}

/// Extract MCP-specific headers from Lambda request context
///
/// Lambda requests may have additional context that needs to be preserved
/// for proper MCP protocol handling.
pub fn extract_mcp_headers(req: &LambdaRequest) -> HashMap<String, String> {
    let mut mcp_headers = HashMap::new();

    // Extract session ID from headers
    if let Some(session_id) = req.headers().get("mcp-session-id")
        && let Ok(session_id_str) = session_id.to_str()
    {
        mcp_headers.insert("mcp-session-id".to_string(), session_id_str.to_string());
    }

    // Extract protocol version
    if let Some(protocol_version) = req.headers().get("mcp-protocol-version")
        && let Ok(version_str) = protocol_version.to_str()
    {
        mcp_headers.insert("mcp-protocol-version".to_string(), version_str.to_string());
    }

    // Extract Last-Event-ID for SSE resumability
    if let Some(last_event_id) = req.headers().get("last-event-id")
        && let Ok(event_id_str) = last_event_id.to_str()
    {
        mcp_headers.insert("last-event-id".to_string(), event_id_str.to_string());
    }

    trace!("Extracted MCP headers: {:?}", mcp_headers);
    mcp_headers
}

/// Add MCP-specific headers to Lambda response
///
/// Ensures proper MCP protocol headers are included in the response.
pub fn inject_mcp_headers(resp: &mut LambdaResponse<LambdaBody>, headers: HashMap<String, String>) {
    for (name, value) in headers {
        if let (Ok(header_name), Ok(header_value)) = (
            http::HeaderName::from_bytes(name.as_bytes()),
            http::HeaderValue::from_str(&value),
        ) {
            resp.headers_mut().insert(header_name, header_value);
            debug!("Injected MCP header: {} = {}", name, value);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use http::{HeaderValue, Method, Request, StatusCode};
    use http_body_util::Full;

    #[test]
    fn test_lambda_to_hyper_request_conversion() {
        // Create a test Lambda request with headers and body
        let mut lambda_req = Request::builder()
            .method(Method::POST)
            .uri("/mcp")
            .body(LambdaBody::Text(
                r#"{"jsonrpc":"2.0","method":"initialize","id":1}"#.to_string(),
            ))
            .unwrap();

        // Add MCP headers
        let headers = lambda_req.headers_mut();
        headers.insert("content-type", HeaderValue::from_static("application/json"));
        headers.insert(
            "mcp-session-id",
            HeaderValue::from_static("test-session-123"),
        );
        headers.insert(
            "mcp-protocol-version",
            HeaderValue::from_static("2025-11-25"),
        );

        // Test the conversion
        let hyper_req = lambda_to_hyper_request(lambda_req).unwrap();

        // Verify method and URI are preserved
        assert_eq!(hyper_req.method(), &Method::POST);
        assert_eq!(hyper_req.uri().path(), "/mcp");

        // Verify headers are preserved
        assert_eq!(
            hyper_req.headers().get("content-type").unwrap(),
            "application/json"
        );
        assert_eq!(
            hyper_req.headers().get("mcp-session-id").unwrap(),
            "test-session-123"
        );
        assert_eq!(
            hyper_req.headers().get("mcp-protocol-version").unwrap(),
            "2025-11-25"
        );
    }

    #[test]
    fn test_lambda_to_hyper_empty_body() {
        let lambda_req = Request::builder()
            .method(Method::GET)
            .uri("/sse")
            .body(LambdaBody::Empty)
            .unwrap();

        let hyper_req = lambda_to_hyper_request(lambda_req).unwrap();
        assert_eq!(hyper_req.method(), &Method::GET);
        assert_eq!(hyper_req.uri().path(), "/sse");
    }

    #[test]
    fn test_lambda_to_hyper_binary_body() {
        let test_data = vec![0x48, 0x65, 0x6c, 0x6c, 0x6f]; // "Hello" in bytes
        let lambda_req = Request::builder()
            .method(Method::POST)
            .uri("/binary")
            .body(LambdaBody::Binary(test_data.clone()))
            .unwrap();

        let hyper_req = lambda_to_hyper_request(lambda_req).unwrap();
        assert_eq!(hyper_req.method(), &Method::POST);
        assert_eq!(hyper_req.uri().path(), "/binary");
    }

    #[tokio::test]
    async fn test_hyper_to_lambda_response_conversion() {
        // Create a test hyper response
        let json_body = r#"{"jsonrpc":"2.0","id":1,"result":{"capabilities":{}}}"#;
        let full_body = Full::new(Bytes::from(json_body));
        let boxed_body = full_body.map_err(|never| match never {}).boxed_unsync();

        let hyper_resp = hyper::Response::builder()
            .status(StatusCode::OK)
            .header("content-type", "application/json")
            .header("mcp-session-id", "resp-session-456")
            .body(boxed_body)
            .unwrap();

        // Test the conversion
        let lambda_resp = hyper_to_lambda_response(hyper_resp).await.unwrap();

        // Verify status and headers are preserved
        assert_eq!(lambda_resp.status(), StatusCode::OK);
        assert_eq!(
            lambda_resp.headers().get("content-type").unwrap(),
            "application/json"
        );
        assert_eq!(
            lambda_resp.headers().get("mcp-session-id").unwrap(),
            "resp-session-456"
        );

        // Verify body is converted to text
        match lambda_resp.body() {
            LambdaBody::Text(text) => assert_eq!(text, json_body),
            _ => panic!("Expected text body"),
        }
    }

    #[tokio::test]
    async fn test_hyper_to_lambda_empty_response() {
        let empty_body = Full::new(Bytes::new());
        let boxed_body = empty_body.map_err(|never| match never {}).boxed_unsync();

        let hyper_resp = hyper::Response::builder()
            .status(StatusCode::NO_CONTENT)
            .body(boxed_body)
            .unwrap();

        let lambda_resp = hyper_to_lambda_response(hyper_resp).await.unwrap();

        assert_eq!(lambda_resp.status(), StatusCode::NO_CONTENT);
        match lambda_resp.body() {
            LambdaBody::Empty => {} // Expected
            _ => panic!("Expected empty body"),
        }
    }

    #[test]
    fn test_hyper_to_lambda_streaming() {
        // Create a streaming response
        let stream_body = Full::new(Bytes::from("data: test\n\n"));
        let boxed_body = stream_body.map_err(|never| match never {}).boxed_unsync();

        let hyper_resp = hyper::Response::builder()
            .status(StatusCode::OK)
            .header("content-type", "text/event-stream")
            .header("cache-control", "no-cache")
            .body(boxed_body)
            .unwrap();

        // Test streaming conversion (should preserve body as-is)
        let lambda_resp = hyper_to_lambda_streaming(hyper_resp);

        assert_eq!(lambda_resp.status(), StatusCode::OK);
        assert_eq!(
            lambda_resp.headers().get("content-type").unwrap(),
            "text/event-stream"
        );
        assert_eq!(
            lambda_resp.headers().get("cache-control").unwrap(),
            "no-cache"
        );
        // Body should be preserved as UnifiedMcpBody for streaming
    }

    #[tokio::test]
    async fn test_mcp_headers_extraction() {
        use http::{HeaderValue, Request};

        // Create a test request with MCP headers
        let mut request = Request::builder()
            .method("POST")
            .uri("/mcp")
            .body(LambdaBody::Empty)
            .unwrap();

        let headers = request.headers_mut();
        headers.insert("mcp-session-id", HeaderValue::from_static("sess-123"));
        headers.insert(
            "mcp-protocol-version",
            HeaderValue::from_static("2025-11-25"),
        );
        headers.insert("last-event-id", HeaderValue::from_static("event-456"));

        let mcp_headers = extract_mcp_headers(&request);

        assert_eq!(
            mcp_headers.get("mcp-session-id"),
            Some(&"sess-123".to_string())
        );
        assert_eq!(
            mcp_headers.get("mcp-protocol-version"),
            Some(&"2025-11-25".to_string())
        );
        assert_eq!(
            mcp_headers.get("last-event-id"),
            Some(&"event-456".to_string())
        );
    }

    #[tokio::test]
    async fn test_mcp_headers_injection() {
        use lambda_http::Body;

        let mut lambda_resp = LambdaResponse::builder()
            .status(200)
            .body(Body::Empty)
            .unwrap();

        let mut headers = HashMap::new();
        headers.insert("mcp-session-id".to_string(), "sess-789".to_string());
        headers.insert("mcp-protocol-version".to_string(), "2025-11-25".to_string());

        inject_mcp_headers(&mut lambda_resp, headers);

        assert_eq!(
            lambda_resp.headers().get("mcp-session-id").unwrap(),
            "sess-789"
        );
        assert_eq!(
            lambda_resp.headers().get("mcp-protocol-version").unwrap(),
            "2025-11-25"
        );
    }

    // Authorizer context tests
    mod authorizer_tests {
        use super::*;

        #[test]
        fn test_sanitize_field_name_camelcase() {
            // camelCase → snake_case conversion
            assert_eq!(sanitize_authorizer_field_name("accountId"), "account_id");
            assert_eq!(sanitize_authorizer_field_name("entityType"), "entity_type");
            assert_eq!(sanitize_authorizer_field_name("deviceId"), "device_id");
            assert_eq!(sanitize_authorizer_field_name("userId"), "user_id");
            assert_eq!(sanitize_authorizer_field_name("tenantId"), "tenant_id");
            assert_eq!(
                sanitize_authorizer_field_name("customClaim"),
                "custom_claim"
            );
        }

        #[test]
        fn test_sanitize_field_name_snake_case() {
            // Already snake_case - should remain unchanged
            assert_eq!(sanitize_authorizer_field_name("device_id"), "device_id");
            assert_eq!(sanitize_authorizer_field_name("user_name"), "user_name");
            assert_eq!(sanitize_authorizer_field_name("tenant_id"), "tenant_id");
        }

        #[test]
        fn test_sanitize_field_name_acronyms() {
            // Acronyms: treated as a single unit, underscore before transition to lowercase
            assert_eq!(sanitize_authorizer_field_name("APIKey"), "api_key");
            assert_eq!(
                sanitize_authorizer_field_name("HTTPSEnabled"),
                "https_enabled"
            );
            assert_eq!(sanitize_authorizer_field_name("XMLParser"), "xml_parser");
        }

        #[test]
        fn test_sanitize_field_name_with_numbers() {
            // Numbers should be preserved
            assert_eq!(sanitize_authorizer_field_name("userId123"), "user_id123");
            assert_eq!(sanitize_authorizer_field_name("device2Id"), "device2_id");
        }

        #[test]
        fn test_sanitize_field_name_special_chars() {
            assert_eq!(sanitize_authorizer_field_name("user@email"), "user-email");
            assert_eq!(sanitize_authorizer_field_name("test.field"), "test-field");
            assert_eq!(sanitize_authorizer_field_name("a/b/c"), "a-b-c");
        }

        #[test]
        fn test_sanitize_field_name_unicode() {
            // Unicode characters get replaced with dashes (one dash per character)
            assert_eq!(sanitize_authorizer_field_name("用户"), "--");
        }

        #[test]
        fn test_extract_authorizer_no_context() {
            // Request with no extensions
            let lambda_req = Request::builder()
                .method(Method::POST)
                .uri("/mcp")
                .body(LambdaBody::Empty)
                .unwrap();

            let fields = extract_authorizer_context(&lambda_req);
            assert!(fields.is_empty());
        }

        #[test]
        fn test_lambda_to_hyper_without_authorizer() {
            // Request without authorizer should work normally
            let lambda_req = Request::builder()
                .method(Method::POST)
                .uri("/mcp")
                .header("content-type", "application/json")
                .body(LambdaBody::Empty)
                .unwrap();

            let hyper_req = lambda_to_hyper_request(lambda_req).unwrap();

            // Should succeed, no authorizer headers
            assert!(hyper_req.headers().get("x-authorizer-account_id").is_none());
            assert_eq!(
                hyper_req.headers().get("content-type").unwrap(),
                "application/json"
            );
        }

        /// Helper: build a LambdaRequest with a RequestContext inserted into extensions
        fn request_with_context(ctx: lambda_http::request::RequestContext) -> LambdaRequest {
            let mut req = Request::builder()
                .method(Method::POST)
                .uri("/mcp")
                .body(LambdaBody::Empty)
                .unwrap();
            req.extensions_mut().insert(ctx);
            req
        }

        #[test]
        fn test_extract_authorizer_v1_top_level_fields() {
            // V1 REST API where authorizer returns flat fields (no "lambda" wrapper).
            // This is the shape seen with proxy integration authorizers that return
            // context directly, e.g. { "userId": "user-123", "tenantId": "tenant-456" }
            use aws_lambda_events::apigw::{
                ApiGatewayProxyRequestContext, ApiGatewayRequestAuthorizer,
            };

            let mut authorizer = ApiGatewayRequestAuthorizer::default();
            authorizer
                .fields
                .insert("userId".to_string(), serde_json::json!("user-123"));
            authorizer
                .fields
                .insert("tenantId".to_string(), serde_json::json!("tenant-456"));
            authorizer
                .fields
                .insert("role".to_string(), serde_json::json!("admin"));

            let mut v1_ctx = ApiGatewayProxyRequestContext::default();
            v1_ctx.authorizer = authorizer;

            let req =
                request_with_context(lambda_http::request::RequestContext::ApiGatewayV1(v1_ctx));
            let fields = extract_authorizer_context(&req);

            assert_eq!(fields.get("user_id"), Some(&"user-123".to_string()));
            assert_eq!(fields.get("tenant_id"), Some(&"tenant-456".to_string()));
            assert_eq!(fields.get("role"), Some(&"admin".to_string()));
        }

        #[test]
        fn test_extract_authorizer_v1_nested_lambda() {
            // V1 REST API where authorizer context is nested under "lambda" key.
            // Shape: { "lambda": { "userId": "user-123", ... } }
            use aws_lambda_events::apigw::{
                ApiGatewayProxyRequestContext, ApiGatewayRequestAuthorizer,
            };

            let mut authorizer = ApiGatewayRequestAuthorizer::default();
            authorizer.fields.insert(
                "lambda".to_string(),
                serde_json::json!({
                    "userId": "user-123",
                    "tenantId": "tenant-456"
                }),
            );

            let mut v1_ctx = ApiGatewayProxyRequestContext::default();
            v1_ctx.authorizer = authorizer;

            let req =
                request_with_context(lambda_http::request::RequestContext::ApiGatewayV1(v1_ctx));
            let fields = extract_authorizer_context(&req);

            assert_eq!(fields.get("user_id"), Some(&"user-123".to_string()));
            assert_eq!(fields.get("tenant_id"), Some(&"tenant-456".to_string()));
        }

        #[test]
        fn test_extract_authorizer_v1_skips_internal_fields() {
            // Verify API Gateway internal fields are excluded from extraction
            use aws_lambda_events::apigw::{
                ApiGatewayProxyRequestContext, ApiGatewayRequestAuthorizer,
            };

            let mut authorizer = ApiGatewayRequestAuthorizer::default();
            authorizer
                .fields
                .insert("userId".to_string(), serde_json::json!("user-123"));
            authorizer.fields.insert(
                "principalId".to_string(),
                serde_json::json!("principal-abc"),
            );
            authorizer
                .fields
                .insert("integrationLatency".to_string(), serde_json::json!(42));
            authorizer.fields.insert(
                "usageIdentifierKey".to_string(),
                serde_json::json!("api-key-xyz"),
            );

            let mut v1_ctx = ApiGatewayProxyRequestContext::default();
            v1_ctx.authorizer = authorizer;

            let req =
                request_with_context(lambda_http::request::RequestContext::ApiGatewayV1(v1_ctx));
            let fields = extract_authorizer_context(&req);

            assert_eq!(fields.get("user_id"), Some(&"user-123".to_string()));
            assert!(
                !fields.contains_key("principal_id"),
                "principalId should be skipped"
            );
            assert!(
                !fields.contains_key("integration_latency"),
                "integrationLatency should be skipped"
            );
            assert!(
                !fields.contains_key("usage_identifier_key"),
                "usageIdentifierKey should be skipped"
            );
        }

        #[test]
        fn test_extract_authorizer_v1_non_string_values() {
            // Verify numeric and boolean values are JSON-serialized to strings
            use aws_lambda_events::apigw::{
                ApiGatewayProxyRequestContext, ApiGatewayRequestAuthorizer,
            };

            let mut authorizer = ApiGatewayRequestAuthorizer::default();
            authorizer
                .fields
                .insert("maxAge".to_string(), serde_json::json!(3600));
            authorizer
                .fields
                .insert("isAdmin".to_string(), serde_json::json!(true));

            let mut v1_ctx = ApiGatewayProxyRequestContext::default();
            v1_ctx.authorizer = authorizer;

            let req =
                request_with_context(lambda_http::request::RequestContext::ApiGatewayV1(v1_ctx));
            let fields = extract_authorizer_context(&req);

            assert_eq!(fields.get("max_age"), Some(&"3600".to_string()));
            assert_eq!(fields.get("is_admin"), Some(&"true".to_string()));
        }

        #[test]
        fn test_extract_authorizer_v1_empty() {
            // Verify empty authorizer returns empty HashMap
            use aws_lambda_events::apigw::ApiGatewayProxyRequestContext;

            let v1_ctx = ApiGatewayProxyRequestContext::default();

            let req =
                request_with_context(lambda_http::request::RequestContext::ApiGatewayV1(v1_ctx));
            let fields = extract_authorizer_context(&req);

            assert!(fields.is_empty());
        }

        #[test]
        fn test_extract_authorizer_v2_lambda_fields() {
            // V2 HTTP API — authorizer.fields are already deserialized from "lambda" key
            use aws_lambda_events::apigw::{
                ApiGatewayRequestAuthorizer, ApiGatewayV2httpRequestContext,
            };

            let mut authorizer = ApiGatewayRequestAuthorizer::default();
            authorizer
                .fields
                .insert("userId".to_string(), serde_json::json!("user-v2"));
            authorizer
                .fields
                .insert("scope".to_string(), serde_json::json!("read write"));

            let mut v2_ctx = ApiGatewayV2httpRequestContext::default();
            v2_ctx.authorizer = Some(authorizer);

            let req =
                request_with_context(lambda_http::request::RequestContext::ApiGatewayV2(v2_ctx));
            let fields = extract_authorizer_context(&req);

            assert_eq!(fields.get("user_id"), Some(&"user-v2".to_string()));
            assert_eq!(fields.get("scope"), Some(&"read write".to_string()));
        }
    }
}