Validate origin header by Kehrlann · Pull Request #771 · modelcontextprotocol/java-sdk · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions conformance-tests/VALIDATION_RESULTS.md
3 changes: 0 additions & 3 deletions conformance-tests/conformance-baseline.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@ server:
# Resource subscription not implemented in SDK
- resources-subscribe
- resources-unsubscribe

# DNS rebinding protection missing Host/Origin validation
- dns-rebinding-protection

client:
# SSE retry field handling not implemented
Expand Down
4 changes: 2 additions & 2 deletions conformance-tests/server-servlet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ The server has been validated against the official [MCP conformance test suite](
✅ **SSE Transport** (2/2)
- Multiple streams support

⚠️ **Security** (1/2)
- ⚠️ DNS rebinding protection (SDK limitation)
**Security** (2/2)
- DNS rebinding protection

## Features

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,36 @@

import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.server.McpServerFeatures;
import io.modelcontextprotocol.server.transport.DefaultServerTransportSecurityValidator;
import io.modelcontextprotocol.server.transport.HttpServletStreamableServerTransportProvider;
import io.modelcontextprotocol.spec.McpSchema.*;
import io.modelcontextprotocol.spec.McpSchema.AudioContent;
import io.modelcontextprotocol.spec.McpSchema.BlobResourceContents;
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
import io.modelcontextprotocol.spec.McpSchema.CompleteResult;
import io.modelcontextprotocol.spec.McpSchema.CreateMessageRequest;
import io.modelcontextprotocol.spec.McpSchema.CreateMessageResult;
import io.modelcontextprotocol.spec.McpSchema.ElicitRequest;
import io.modelcontextprotocol.spec.McpSchema.ElicitResult;
import io.modelcontextprotocol.spec.McpSchema.EmbeddedResource;
import io.modelcontextprotocol.spec.McpSchema.GetPromptResult;
import io.modelcontextprotocol.spec.McpSchema.ImageContent;
import io.modelcontextprotocol.spec.McpSchema.JsonSchema;
import io.modelcontextprotocol.spec.McpSchema.LoggingLevel;
import io.modelcontextprotocol.spec.McpSchema.LoggingMessageNotification;
import io.modelcontextprotocol.spec.McpSchema.ProgressNotification;
import io.modelcontextprotocol.spec.McpSchema.Prompt;
import io.modelcontextprotocol.spec.McpSchema.PromptArgument;
import io.modelcontextprotocol.spec.McpSchema.PromptMessage;
import io.modelcontextprotocol.spec.McpSchema.PromptReference;
import io.modelcontextprotocol.spec.McpSchema.ReadResourceResult;
import io.modelcontextprotocol.spec.McpSchema.Resource;
import io.modelcontextprotocol.spec.McpSchema.ResourceTemplate;
import io.modelcontextprotocol.spec.McpSchema.Role;
import io.modelcontextprotocol.spec.McpSchema.SamplingMessage;
import io.modelcontextprotocol.spec.McpSchema.ServerCapabilities;
import io.modelcontextprotocol.spec.McpSchema.TextContent;
import io.modelcontextprotocol.spec.McpSchema.TextResourceContents;
import io.modelcontextprotocol.spec.McpSchema.Tool;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
Expand Down Expand Up @@ -39,6 +67,8 @@ public static void main(String[] args) throws Exception {
.builder()
.mcpEndpoint(MCP_ENDPOINT)
.keepAliveInterval(Duration.ofSeconds(30))
.securityValidator(
DefaultServerTransportSecurityValidator.builder().allowedOrigin("http://localhost:*").build())
.build();

// Build server with all conformance test features
Expand Down
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) {
Comment thread
Kehrlann marked this conversation as resolved.
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;
Comment thread
Kehrlann marked this conversation as resolved.
}

/**
* 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);
}

}

}
Loading