Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 1.1k
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
Merged
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
32 changes: 31 additions & 1 deletion
32 ...-servlet/src/main/java/io/modelcontextprotocol/conformance/server/ConformanceServlet.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
132 changes: 132 additions & 0 deletions
132 ...ava/io/modelcontextprotocol/server/transport/DefaultServerTransportSecurityValidator.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
Kehrlann marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| } | ||
| /** | ||
| * 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); | ||
| } | ||
| } | ||
| } | ||
67 changes: 62 additions & 5 deletions
67 .../java/io/modelcontextprotocol/server/transport/HttpServletSseServerTransportProvider.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
chemicL marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| // 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); | ||
| } | ||
| } | ||
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.