-
Notifications
You must be signed in to change notification settings - Fork 802
Validate origin header #771
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| /* | ||
| * Copyright 2026-2026 the original author or authors. | ||
| */ | ||
|
|
||
| package io.modelcontextprotocol.server.transport; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
|
|
||
| import io.modelcontextprotocol.util.Assert; | ||
|
|
||
| /** | ||
| * Default implementation of {@link ServerTransportSecurityValidator} that validates the | ||
| * Origin header against a list of allowed origins. | ||
| * | ||
| * <p> | ||
| * Supports exact matches and wildcard port patterns (e.g., "http://example.com:*"). | ||
| * | ||
| * @author Daniel Garnier-Moiroux | ||
| * @see ServerTransportSecurityValidator | ||
| * @see ServerTransportSecurityException | ||
| */ | ||
| public class DefaultServerTransportSecurityValidator implements ServerTransportSecurityValidator { | ||
|
|
||
| private static final String ORIGIN_HEADER = "Origin"; | ||
|
|
||
| private static final ServerTransportSecurityException INVALID_ORIGIN = new ServerTransportSecurityException(403, | ||
| "Invalid Origin header"); | ||
|
|
||
| private final List<String> allowedOrigins; | ||
|
|
||
| /** | ||
| * Creates a new validator with the specified allowed origins. | ||
| * @param allowedOrigins List of allowed origin patterns. Supports exact matches | ||
| * (e.g., "http://example.com:8080") and wildcard ports (e.g., "http://example.com:*") | ||
| */ | ||
| public DefaultServerTransportSecurityValidator(List<String> allowedOrigins) { | ||
| Assert.notNull(allowedOrigins, "allowedOrigins must not be null"); | ||
| this.allowedOrigins = allowedOrigins; | ||
| } | ||
|
|
||
| @Override | ||
| public void validateHeaders(Map<String, List<String>> headers) throws ServerTransportSecurityException { | ||
| for (Map.Entry<String, List<String>> entry : headers.entrySet()) { | ||
| if (ORIGIN_HEADER.equalsIgnoreCase(entry.getKey())) { | ||
| List<String> values = entry.getValue(); | ||
| if (values != null && !values.isEmpty()) { | ||
| validateOrigin(values.get(0)); | ||
| } | ||
| break; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Validates a single origin value against the allowed origins. Subclasses can | ||
| * override this method to customize origin validation logic. | ||
| * @param origin The origin header value, or null if not present | ||
| * @throws ServerTransportSecurityException if the origin is not allowed | ||
| */ | ||
| protected void validateOrigin(String origin) throws ServerTransportSecurityException { | ||
| // Origin absent = no validation needed (same-origin request) | ||
| if (origin == null || origin.isBlank()) { | ||
| return; | ||
| } | ||
|
|
||
| for (String allowed : allowedOrigins) { | ||
| if (allowed.equals(origin)) { | ||
| return; | ||
| } | ||
| else if (allowed.endsWith(":*")) { | ||
| // Wildcard port pattern: "http://example.com:*" | ||
| String baseOrigin = allowed.substring(0, allowed.length() - 2); | ||
| if (origin.equals(baseOrigin) || origin.startsWith(baseOrigin + ":")) { | ||
| return; | ||
| } | ||
| } | ||
|
|
||
| } | ||
|
|
||
| throw INVALID_ORIGIN; | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Due to the exception being a static, the stack trace is inaccurate with regards to where it is raised. I understand the optimization, however it might make it harder to investigate where the issue happened. Perhaps we can create an instance each time it's raised? |
||
| } | ||
|
|
||
| /** | ||
| * Creates a new builder for constructing a DefaultServerTransportSecurityValidator. | ||
| * @return A new builder instance | ||
| */ | ||
| public static Builder builder() { | ||
| return new Builder(); | ||
| } | ||
|
|
||
| /** | ||
| * Builder for creating instances of {@link DefaultServerTransportSecurityValidator}. | ||
| */ | ||
| public static class Builder { | ||
|
|
||
| private final List<String> allowedOrigins = new ArrayList<>(); | ||
|
|
||
| /** | ||
| * Adds an allowed origin pattern. | ||
| * @param origin The origin to allow (e.g., "http://localhost:8080" or | ||
| * "http://example.com:*") | ||
| * @return this builder instance | ||
| */ | ||
| public Builder allowedOrigin(String origin) { | ||
| this.allowedOrigins.add(origin); | ||
| return this; | ||
| } | ||
|
|
||
| /** | ||
| * Adds multiple allowed origin patterns. | ||
| * @param origins The origins to allow | ||
| * @return this builder instance | ||
| */ | ||
| public Builder allowedOrigins(List<String> origins) { | ||
| Assert.notNull(origins, "origins must not be null"); | ||
| this.allowedOrigins.addAll(origins); | ||
| return this; | ||
| } | ||
|
|
||
| /** | ||
| * Builds the validator instance. | ||
| * @return A new DefaultServerTransportSecurityValidator | ||
| */ | ||
| public DefaultServerTransportSecurityValidator build() { | ||
| return new DefaultServerTransportSecurityValidator(allowedOrigins); | ||
| } | ||
|
|
||
| } | ||
|
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,5 @@ | ||
| /* | ||
| * Copyright 2024 - 2024 the original author or authors. | ||
| * Copyright 2024 - 2026 the original author or authors. | ||
| */ | ||
|
|
||
| package io.modelcontextprotocol.server.transport; | ||
|
|
@@ -8,6 +8,9 @@ | |
| import java.io.IOException; | ||
| import java.io.PrintWriter; | ||
| import java.time.Duration; | ||
| import java.util.Collections; | ||
| import java.util.Enumeration; | ||
| import java.util.HashMap; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.UUID; | ||
|
|
@@ -142,6 +145,11 @@ public class HttpServletSseServerTransportProvider extends HttpServlet implement | |
| */ | ||
| private KeepAliveScheduler keepAliveScheduler; | ||
|
|
||
| /** | ||
| * Security validator for validating HTTP requests. | ||
| */ | ||
| private final ServerTransportSecurityValidator securityValidator; | ||
|
|
||
| /** | ||
| * Creates a new HttpServletSseServerTransportProvider instance with a custom SSE | ||
| * endpoint. | ||
|
|
@@ -153,23 +161,25 @@ public class HttpServletSseServerTransportProvider extends HttpServlet implement | |
| * @param keepAliveInterval The interval for keep-alive pings, or null to disable | ||
| * keep-alive functionality | ||
| * @param contextExtractor The extractor for transport context from the request. | ||
| * @deprecated Use the builder {@link #builder()} instead for better configuration | ||
| * options. | ||
| * @param securityValidator The security validator for validating HTTP requests. | ||
| */ | ||
| private HttpServletSseServerTransportProvider(McpJsonMapper jsonMapper, String baseUrl, String messageEndpoint, | ||
| String sseEndpoint, Duration keepAliveInterval, | ||
| McpTransportContextExtractor<HttpServletRequest> contextExtractor) { | ||
| McpTransportContextExtractor<HttpServletRequest> contextExtractor, | ||
| ServerTransportSecurityValidator securityValidator) { | ||
|
|
||
| Assert.notNull(jsonMapper, "JsonMapper must not be null"); | ||
| Assert.notNull(messageEndpoint, "messageEndpoint must not be null"); | ||
| Assert.notNull(sseEndpoint, "sseEndpoint must not be null"); | ||
| Assert.notNull(contextExtractor, "Context extractor must not be null"); | ||
| Assert.notNull(securityValidator, "Security validator must not be null"); | ||
|
|
||
| this.jsonMapper = jsonMapper; | ||
| this.baseUrl = baseUrl; | ||
| this.messageEndpoint = messageEndpoint; | ||
| this.sseEndpoint = sseEndpoint; | ||
| this.contextExtractor = contextExtractor; | ||
| this.securityValidator = securityValidator; | ||
|
|
||
| if (keepAliveInterval != null) { | ||
|
|
||
|
|
@@ -246,6 +256,15 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) | |
| return; | ||
| } | ||
|
|
||
| try { | ||
| Map<String, List<String>> headers = extractHeaders(request); | ||
| this.securityValidator.validateHeaders(headers); | ||
| } | ||
| catch (ServerTransportSecurityException e) { | ||
| response.sendError(e.getStatusCode(), e.getMessage()); | ||
| return; | ||
| } | ||
|
|
||
| response.setContentType("text/event-stream"); | ||
| response.setCharacterEncoding(UTF_8); | ||
| response.setHeader("Cache-Control", "no-cache"); | ||
|
|
@@ -311,6 +330,15 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) | |
| return; | ||
| } | ||
|
|
||
| try { | ||
| Map<String, List<String>> headers = extractHeaders(request); | ||
| this.securityValidator.validateHeaders(headers); | ||
| } | ||
| catch (ServerTransportSecurityException e) { | ||
| response.sendError(e.getStatusCode(), e.getMessage()); | ||
| return; | ||
| } | ||
|
|
||
|
Comment on lines
+333
to
+341
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This bit is duplicated in doGet, we can create a helper method for it perhaps? |
||
| // Get the session ID from the request parameter | ||
| String sessionId = request.getParameter("sessionId"); | ||
| if (sessionId == null) { | ||
|
|
@@ -411,6 +439,21 @@ private void sendEvent(PrintWriter writer, String eventType, String data) throws | |
| } | ||
| } | ||
|
|
||
| /** | ||
| * Extracts all headers from the HTTP servlet request into a map. | ||
| * @param request The HTTP servlet request | ||
| * @return A map of header names to their values | ||
| */ | ||
| private Map<String, List<String>> extractHeaders(HttpServletRequest request) { | ||
| Map<String, List<String>> headers = new HashMap<>(); | ||
| Enumeration<String> names = request.getHeaderNames(); | ||
| while (names.hasMoreElements()) { | ||
| String name = names.nextElement(); | ||
| headers.put(name, Collections.list(request.getHeaders(name))); | ||
| } | ||
| return headers; | ||
| } | ||
|
|
||
| /** | ||
| * Cleans up resources when the servlet is being destroyed. | ||
| * <p> | ||
|
|
@@ -547,6 +590,8 @@ public static class Builder { | |
|
|
||
| private Duration keepAliveInterval; | ||
|
|
||
| private ServerTransportSecurityValidator securityValidator = ServerTransportSecurityValidator.NOOP; | ||
|
|
||
| /** | ||
| * Sets the JsonMapper implementation to use for serialization/deserialization. If | ||
| * not specified, a JacksonJsonMapper will be created from the configured | ||
|
|
@@ -621,6 +666,18 @@ public Builder keepAliveInterval(Duration keepAliveInterval) { | |
| return this; | ||
| } | ||
|
|
||
| /** | ||
| * Sets the security validator for validating HTTP requests. | ||
| * @param securityValidator The security validator to use. Must not be null. | ||
| * @return This builder instance | ||
| * @throws IllegalArgumentException if securityValidator is null | ||
| */ | ||
| public Builder securityValidator(ServerTransportSecurityValidator securityValidator) { | ||
| Assert.notNull(securityValidator, "Security validator must not be null"); | ||
| this.securityValidator = securityValidator; | ||
| return this; | ||
| } | ||
|
|
||
| /** | ||
| * Builds a new instance of HttpServletSseServerTransportProvider with the | ||
| * configured settings. | ||
|
|
@@ -633,7 +690,7 @@ public HttpServletSseServerTransportProvider build() { | |
| } | ||
| return new HttpServletSseServerTransportProvider( | ||
| jsonMapper == null ? McpJsonMapper.getDefault() : jsonMapper, baseUrl, messageEndpoint, sseEndpoint, | ||
| keepAliveInterval, contextExtractor); | ||
| keepAliveInterval, contextExtractor, securityValidator); | ||
| } | ||
|
|
||
| } | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There are two ways to create the validator - either via a constructor or via the builder. I'd vouch for a single version. The builder makes sense with no inheritance, but since users are encouraged to customize by inheriting from this class, perhaps we can skip the builder?