|
| 1 | +//! 2026-07-28 stateless-lane session construction over the buffered Lambda transport. |
| 2 | +//! |
| 3 | +//! The stateless core removes the client-visible `Mcp-Session-Id`, but every |
| 4 | +//! dispatched request still carries an internally-minted per-request session. |
| 5 | +//! Middleware state written via `SessionInjection::set_state` must therefore be |
| 6 | +//! readable from the tool's `SessionContext` — over the Lambda transport exactly |
| 7 | +//! as over the local `turul-http-mcp-server` transport. |
| 8 | +//! |
| 9 | +//! Exercises the production path: `LambdaMcpServerBuilder` → `server.handler()` |
| 10 | +//! → `LambdaMcpHandler::handle()` (buffered, non-streaming Lambda runtime). |
| 11 | +#![cfg(feature = "protocol-2026-07-28")] |
| 12 | + |
| 13 | +use std::sync::Arc; |
| 14 | + |
| 15 | +use async_trait::async_trait; |
| 16 | +use serde_json::json; |
| 17 | + |
| 18 | +use turul_http_mcp_server::middleware::{ |
| 19 | + DispatcherResult, McpMiddleware, MiddlewareError, RequestContext, SessionInjection, |
| 20 | +}; |
| 21 | +use turul_mcp_aws_lambda::{LambdaMcpHandler, LambdaMcpServerBuilder}; |
| 22 | +use turul_mcp_derive::McpTool; |
| 23 | +use turul_mcp_protocol::McpError; |
| 24 | +use turul_mcp_server::{McpResult, SessionContext}; |
| 25 | +use turul_mcp_session_storage::SessionView; |
| 26 | + |
| 27 | +/// Simulates an authenticating middleware (e.g. API Gateway authorizer bridge) |
| 28 | +/// that stamps the caller's identity into per-request session state. |
| 29 | +struct AccountInjectingMiddleware; |
| 30 | + |
| 31 | +#[async_trait] |
| 32 | +impl McpMiddleware for AccountInjectingMiddleware { |
| 33 | + async fn before_dispatch( |
| 34 | + &self, |
| 35 | + _ctx: &mut RequestContext<'_>, |
| 36 | + _session: Option<&dyn SessionView>, |
| 37 | + injection: &mut SessionInjection, |
| 38 | + ) -> Result<(), MiddlewareError> { |
| 39 | + injection.set_state("account_id", json!("acct-42")); |
| 40 | + Ok(()) |
| 41 | + } |
| 42 | + |
| 43 | + async fn after_dispatch( |
| 44 | + &self, |
| 45 | + _ctx: &RequestContext<'_>, |
| 46 | + _result: &mut DispatcherResult, |
| 47 | + ) -> Result<(), MiddlewareError> { |
| 48 | + Ok(()) |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +/// Tool that requires a session and echoes the middleware-injected account id. |
| 53 | +#[derive(McpTool, Clone, Default)] |
| 54 | +#[tool( |
| 55 | + name = "whoami", |
| 56 | + description = "Return the middleware-injected account id", |
| 57 | + output = String |
| 58 | +)] |
| 59 | +struct WhoamiTool {} |
| 60 | + |
| 61 | +impl WhoamiTool { |
| 62 | + async fn execute(&self, session: Option<SessionContext>) -> McpResult<String> { |
| 63 | + let session = session.ok_or_else(|| McpError::InvalidRequest { |
| 64 | + message: "session required".to_string(), |
| 65 | + })?; |
| 66 | + session |
| 67 | + .get_typed_state::<String>("account_id") |
| 68 | + .await |
| 69 | + .ok_or_else(|| McpError::InvalidRequest { |
| 70 | + message: "account_id missing from session".to_string(), |
| 71 | + }) |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +fn request_meta() -> serde_json::Value { |
| 76 | + json!({ |
| 77 | + "io.modelcontextprotocol/protocolVersion": "2026-07-28", |
| 78 | + "io.modelcontextprotocol/clientInfo": { "name": "test-client", "version": "1.0.0" }, |
| 79 | + "io.modelcontextprotocol/clientCapabilities": {} |
| 80 | + }) |
| 81 | +} |
| 82 | + |
| 83 | +async fn build_handler() -> LambdaMcpHandler { |
| 84 | + let server = LambdaMcpServerBuilder::new() |
| 85 | + .name("stateless-session-test") |
| 86 | + .version("1.0.0") |
| 87 | + .tool(WhoamiTool::default()) |
| 88 | + .middleware(Arc::new(AccountInjectingMiddleware)) |
| 89 | + .build() |
| 90 | + .await |
| 91 | + .expect("build lambda server"); |
| 92 | + server.handler().await.expect("create lambda handler") |
| 93 | +} |
| 94 | + |
| 95 | +fn whoami_request() -> lambda_http::Request { |
| 96 | + let body = json!({ |
| 97 | + "jsonrpc": "2.0", |
| 98 | + "id": 1, |
| 99 | + "method": "tools/call", |
| 100 | + "params": { |
| 101 | + "name": "whoami", |
| 102 | + "arguments": {}, |
| 103 | + "_meta": request_meta() |
| 104 | + } |
| 105 | + }); |
| 106 | + http::Request::builder() |
| 107 | + .method("POST") |
| 108 | + .uri("/mcp") |
| 109 | + .header("Content-Type", "application/json") |
| 110 | + .header("Accept", "application/json") |
| 111 | + .header("MCP-Protocol-Version", "2026-07-28") |
| 112 | + .header("Mcp-Method", "tools/call") |
| 113 | + .header("Mcp-Name", "whoami") |
| 114 | + .body(lambda_http::Body::from( |
| 115 | + serde_json::to_string(&body).unwrap(), |
| 116 | + )) |
| 117 | + .unwrap() |
| 118 | +} |
| 119 | + |
| 120 | +fn response_json(response: &lambda_http::Response<lambda_http::Body>) -> serde_json::Value { |
| 121 | + let bytes = match response.body() { |
| 122 | + lambda_http::Body::Text(s) => s.as_bytes().to_vec(), |
| 123 | + lambda_http::Body::Binary(b) => b.clone(), |
| 124 | + _ => Vec::new(), |
| 125 | + }; |
| 126 | + serde_json::from_slice(&bytes).expect("response body must be JSON") |
| 127 | +} |
| 128 | + |
| 129 | +/// A middleware-authenticated tools/call over the buffered Lambda transport |
| 130 | +/// receives a per-request session carrying the injected state. |
| 131 | +#[tokio::test] |
| 132 | +async fn tool_receives_session_with_middleware_state_over_lambda_handle() { |
| 133 | + let handler = build_handler().await; |
| 134 | + let response = handler.handle(whoami_request()).await.expect("handle"); |
| 135 | + |
| 136 | + assert_eq!(response.status(), 200, "tools/call must succeed"); |
| 137 | + assert_eq!( |
| 138 | + response |
| 139 | + .headers() |
| 140 | + .get("content-type") |
| 141 | + .and_then(|v| v.to_str().ok()), |
| 142 | + Some("application/json"), |
| 143 | + "JSON framing expected for Accept: application/json" |
| 144 | + ); |
| 145 | + |
| 146 | + let body = response_json(&response); |
| 147 | + assert!( |
| 148 | + body.get("error").is_none(), |
| 149 | + "expected success result, got error: {body}" |
| 150 | + ); |
| 151 | + let text = body["result"]["content"][0]["text"] |
| 152 | + .as_str() |
| 153 | + .unwrap_or_else(|| panic!("missing result.content[0].text in: {body}")); |
| 154 | + assert!( |
| 155 | + text.contains("acct-42"), |
| 156 | + "tool must read middleware-injected account_id, got: {text}" |
| 157 | + ); |
| 158 | +} |
| 159 | + |
| 160 | +/// Middleware that rejects every request, simulating failed authentication. |
| 161 | +struct BlockingMiddleware; |
| 162 | + |
| 163 | +#[async_trait] |
| 164 | +impl McpMiddleware for BlockingMiddleware { |
| 165 | + async fn before_dispatch( |
| 166 | + &self, |
| 167 | + _ctx: &mut RequestContext<'_>, |
| 168 | + _session: Option<&dyn SessionView>, |
| 169 | + _injection: &mut SessionInjection, |
| 170 | + ) -> Result<(), MiddlewareError> { |
| 171 | + Err(MiddlewareError::Unauthenticated( |
| 172 | + "Lambda auth required".to_string(), |
| 173 | + )) |
| 174 | + } |
| 175 | + |
| 176 | + async fn after_dispatch( |
| 177 | + &self, |
| 178 | + _ctx: &RequestContext<'_>, |
| 179 | + _result: &mut DispatcherResult, |
| 180 | + ) -> Result<(), MiddlewareError> { |
| 181 | + Ok(()) |
| 182 | + } |
| 183 | +} |
| 184 | + |
| 185 | +/// A middleware rejection short-circuits dispatch and surfaces as a JSON-RPC |
| 186 | +/// error (-32001 Unauthenticated) over the buffered Lambda transport. |
| 187 | +#[tokio::test] |
| 188 | +async fn middleware_error_short_circuits_over_lambda_handle() { |
| 189 | + let server = LambdaMcpServerBuilder::new() |
| 190 | + .name("stateless-session-test") |
| 191 | + .version("1.0.0") |
| 192 | + .tool(WhoamiTool::default()) |
| 193 | + .middleware(Arc::new(BlockingMiddleware)) |
| 194 | + .build() |
| 195 | + .await |
| 196 | + .expect("build lambda server"); |
| 197 | + let handler = server.handler().await.expect("create lambda handler"); |
| 198 | + |
| 199 | + let response = handler.handle(whoami_request()).await.expect("handle"); |
| 200 | + assert_eq!(response.status(), 200, "JSON-RPC errors ride HTTP 200"); |
| 201 | + |
| 202 | + let body = response_json(&response); |
| 203 | + assert_eq!( |
| 204 | + body["error"]["code"].as_i64(), |
| 205 | + Some(-32001), |
| 206 | + "expected Unauthenticated, got: {body}" |
| 207 | + ); |
| 208 | + assert!( |
| 209 | + body["error"]["message"] |
| 210 | + .as_str() |
| 211 | + .unwrap_or_default() |
| 212 | + .contains("Lambda auth required"), |
| 213 | + "middleware message must surface, got: {body}" |
| 214 | + ); |
| 215 | +} |
| 216 | + |
| 217 | +/// The buffered Lambda lane enforces 2026-07-28 Server Validation: a request |
| 218 | +/// missing the MCP-Protocol-Version header is rejected with HTTP 400 and |
| 219 | +/// JSON-RPC -32020 (HeaderMismatch), not silently dispatched. |
| 220 | +#[tokio::test] |
| 221 | +async fn missing_protocol_version_header_rejected_over_lambda_handle() { |
| 222 | + let handler = build_handler().await; |
| 223 | + |
| 224 | + let body = json!({ |
| 225 | + "jsonrpc": "2.0", |
| 226 | + "id": 1, |
| 227 | + "method": "tools/call", |
| 228 | + "params": { |
| 229 | + "name": "whoami", |
| 230 | + "arguments": {}, |
| 231 | + "_meta": request_meta() |
| 232 | + } |
| 233 | + }); |
| 234 | + let request = http::Request::builder() |
| 235 | + .method("POST") |
| 236 | + .uri("/mcp") |
| 237 | + .header("Content-Type", "application/json") |
| 238 | + .header("Accept", "application/json") |
| 239 | + .header("Mcp-Method", "tools/call") |
| 240 | + .header("Mcp-Name", "whoami") |
| 241 | + .body(lambda_http::Body::from( |
| 242 | + serde_json::to_string(&body).unwrap(), |
| 243 | + )) |
| 244 | + .unwrap(); |
| 245 | + |
| 246 | + let response = handler.handle(request).await.expect("handle"); |
| 247 | + assert_eq!(response.status(), 400, "header validation must reject"); |
| 248 | + |
| 249 | + let body = response_json(&response); |
| 250 | + assert_eq!( |
| 251 | + body["error"]["code"].as_i64(), |
| 252 | + Some(turul_mcp_protocol::headers::ERROR_CODE_HEADER_MISMATCH), |
| 253 | + "expected -32020 HeaderMismatch, got: {body}" |
| 254 | + ); |
| 255 | +} |
0 commit comments