Skip to content
Open
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
10 changes: 10 additions & 0 deletions src/oracle-db-mcp-java-toolkit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -669,6 +669,10 @@ In order to configure an OAuth2 server, enable `-Dauth.enabled=true` alongside t
* `-Dauth.authorizationServer`: The OAuth2 server URL which MUST provide the `/.well-known/oauth-authorization-server`. If it only provides `/.well-known/openid-configuration`, enable `-Dauth.openIdDiscoveryRedirectEnabled=true`.
* `-Dmcp.oauth.scopes`: Optional space- or comma-separated OAuth scopes advertised to MCP clients for end-user login (default: `openid`).
* `-Dmcp.oauth.resourceUrl`: Optional externally visible MCP resource URL advertised in OAuth protected-resource metadata. Set this when the server is behind a proxy or public route whose URL differs from the incoming servlet request URL.
* `-Dmcp.oauth.resourceMetadataUrl`: Optional public protected-resource metadata URL advertised in both the HTTP 401 `WWW-Authenticate` header and JSON body. Absent or blank values retain the request-derived origin plus `/.well-known/oauth-protected-resource`.
A nonblank value must be an absolute ASCII HTTPS URI without user-info or a fragment, with a valid port; percent-encode non-ASCII path/query characters. Invalid values are rejected when the HTTP authorization filter initializes. The configured value is preserved exactly and no network reachability check is performed.
Configure `mcp.oauth.resourceUrl=https://mcp.example.com/owned/mcp` for the resource identifier and, independently, `mcp.oauth.resourceMetadataUrl=https://mcp.example.com/owned/.well-known/oauth-protected-resource` for the public metadata location. Ensure the proxy actually serves that location; this setting does not create a route. The value is public discovery information and must not contain credentials.
When `mcp.oauth.resourceUrl` is set, redirect mode advertises the configured authorization server directly; `auth.authorizationServer` must match that server's metadata issuer.
* `-Dauth.openIdDiscoveryRedirectEnabled`: (default: `false`) Creates an `/.well-known/oauth-authorization-server` endpoint that redirects to the authorization server's `/.well-known/openid-configuration` endpoint.
It works by creating an `/.well-known/oauth-authorization-server` endpoint on the MCP Server that redirects to the OAuth server's `/.well-known/openid-configuration` endpoint.
* `-Dauth.userTokenValidation.mode`: Token validation mode. Use `introspection` (default) to validate bearer tokens by calling the OAuth2 introspection endpoint, or `jwt` to validate JWT access tokens locally with JWKS.
Expand Down Expand Up @@ -1091,6 +1095,12 @@ Ultimately, the token must be included in the http request header (e.g. `Authori
<td>Externally visible MCP endpoint URL advertised in OAuth protected-resource metadata. Useful behind proxies or public routes.</td>
<td><code>-Dmcp.oauth.resourceUrl=https://example.com/api/mcp</code></td>
</tr>
<tr>
<td><code>mcp.oauth.resourceMetadataUrl</code></td>
<td>No</td>
<td>Public protected-resource metadata URL for the 401 challenge header and JSON body. An absolute ASCII HTTPS URI without user-info or fragment, with a valid port. Absent/blank retains the request-derived root well-known URL. Invalid explicit values fail HTTP filter initialization; the proxy must serve the configured route.</td>
<td><code>-Dmcp.oauth.resourceMetadataUrl=https://example.com/api/.well-known/oauth-protected-resource</code></td>
</tr>
<tr>
<td><code>auth.userTokenValidation.mode</code></td>
<td>No</td>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ private LoadedConstants() {} // Prevent instantiation
/** MCP OAuth discovery config */
public static final String MCP_OAUTH_SCOPES = System.getProperty("mcp.oauth.scopes", "openid");
public static final String MCP_OAUTH_RESOURCE_URL = System.getProperty("mcp.oauth.resourceUrl");
public static final String MCP_OAUTH_RESOURCE_METADATA_URL =
System.getProperty("mcp.oauth.resourceMetadataUrl");

/** Deep Data Security config */
public static final boolean DEEPSEC_ENABLED = Boolean.parseBoolean(System.getProperty("deepsec.enabled", "false"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ public class AuthorizationFilter implements Filter {
private static final OAuth2TokenValidator VALIDATOR = new OAuth2TokenValidator();
private static final RequestTargetValidator REQUEST_TARGET_VALIDATOR =
new RequestTargetValidator(LoadedConstants.HTTP_ALLOWED_ORIGINAL_HOSTS);
private static final String CONFIGURED_RESOURCE_METADATA_URL =
WebUtils.validateMcpResourceMetadataUrl(LoadedConstants.MCP_OAUTH_RESOURCE_METADATA_URL);

/**
* Intercepts incoming requests to authenticate them based on the presence and validity of an OAuth2 access token.
Expand Down Expand Up @@ -128,8 +130,9 @@ private EndUserSecurityContext createEndUserSecurityContext(String endUserToken)
* @throws IOException if an I/O error occurs while writing the response
*/
private void handleError(HttpServletResponse httpResponse, HttpServletRequest httpRequest) throws IOException {
final String serverURL = WebUtils.buildURLFromRequest(httpRequest);
final String resourceMetadataURL = serverURL + "/.well-known/oauth-protected-resource";
final String resourceMetadataURL = CONFIGURED_RESOURCE_METADATA_URL != null
? CONFIGURED_RESOURCE_METADATA_URL
: WebUtils.buildURLFromRequest(httpRequest) + "/.well-known/oauth-protected-resource";
final String scopes = LoadedConstants.MCP_OAUTH_SCOPES == null || LoadedConstants.MCP_OAUTH_SCOPES.isBlank()
? "openid"
: LoadedConstants.MCP_OAUTH_SCOPES;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import com.oracle.database.mcptoolkit.LoadedConstants;
import jakarta.servlet.http.HttpServletRequest;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Objects;

/**
Expand Down Expand Up @@ -58,6 +60,57 @@ static String buildURLFromRequest(final HttpServletRequest request) {
return url.toString();
}

/**
* Resolves the protected resource identifier without changing a configured value.
* A configured identifier may include a public path prefix or query component.
*
* @param request the servlet request used only when the configured value is absent or blank
* @param configuredResourceUrl the optional externally visible MCP resource identifier
* @return the configured identifier, or the existing request-derived default
*/
static String resolveMcpResourceUrl(
final HttpServletRequest request, final String configuredResourceUrl) {
if (configuredResourceUrl != null && !configuredResourceUrl.isBlank()) {
return configuredResourceUrl;
}
return buildURLFromRequest(request) + "/mcp";
}

/**
* Validates an optional public metadata URL before it is advertised in a challenge.
* No network lookup or URL normalization is performed.
*
* @param configuredUrl an ASCII HTTPS URI, or an absent/blank value
* @return the unchanged configured URL, or null to retain the request-derived default
* @throws IllegalArgumentException if a nonblank value is not a valid public metadata URL
*/
static String validateMcpResourceMetadataUrl(final String configuredUrl) {
if (configuredUrl == null || configuredUrl.isBlank()) {
return null;
}
if (configuredUrl.chars().anyMatch(c -> c <= 0x20 || c >= 0x7f)) {
throw invalidMcpResourceMetadataUrl();
}
try {
final URI uri = new URI(configuredUrl);
final int port = uri.getPort();
if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null
|| uri.getRawUserInfo() != null || uri.getRawFragment() != null
|| (port != -1 && (port < 1 || port > 65535))) {
throw invalidMcpResourceMetadataUrl();
}
} catch (URISyntaxException e) {
throw invalidMcpResourceMetadataUrl();
}
return configuredUrl;
}

private static IllegalArgumentException invalidMcpResourceMetadataUrl() {
return new IllegalArgumentException(
"mcp.oauth.resourceMetadataUrl must be an absolute ASCII HTTPS URL "
+ "without user-info or a fragment, and with a valid port");
}

/**
* Retrieves the value of the system property {@code allowedHosts}.
* If the property is not set, it defaults to {@code "*"}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,17 @@

package com.oracle.database.mcptoolkit.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oracle.database.mcptoolkit.LoadedConstants;
import com.oracle.database.mcptoolkit.oauth.OAuth2Configuration;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
* The WellKnownServlet class handles HTTP GET requests to the well-known endpoint,
Expand Down Expand Up @@ -48,15 +52,16 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) t
response.addHeader("Access-Control-Allow-Origin", WebUtils.getAllowedHosts());
response.setStatus(HttpServletResponse.SC_OK);

final String serverURL = WebUtils.buildURLFromRequest(request);
final String mcpEndpoint = serverURL + "/mcp";
String authServer = WebUtils.isRedirectOpenIDToOAuthEnabled() ? serverURL : OAUTH2_CONFIG.getAuthServer();
final String configuredResourceUrl = LoadedConstants.MCP_OAUTH_RESOURCE_URL;
final String mcpEndpoint = WebUtils.resolveMcpResourceUrl(request, configuredResourceUrl);
final String authServer = WebUtils.isRedirectOpenIDToOAuthEnabled()
&& (configuredResourceUrl == null || configuredResourceUrl.isBlank())
? WebUtils.buildURLFromRequest(request)
: OAUTH2_CONFIG.getAuthServer();

final String json = """
{
"resource":"%s",
"authorization_servers":["%s"]
}""".formatted(mcpEndpoint, authServer);
final String json = new ObjectMapper().writeValueAsString(Map.of(
"resource", mcpEndpoint,
"authorization_servers", List.of(authServer)));
response.getWriter()
.write(json);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.oracle.database.mcptoolkit.web;

import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

class WebUtilsResourceMetadataUrlTest {
@Test
void absentAndBlankValuesRetainTheDefault() {
assertNull(WebUtils.validateMcpResourceMetadataUrl(null));
assertNull(WebUtils.validateMcpResourceMetadataUrl(""));
assertNull(WebUtils.validateMcpResourceMetadataUrl(" \t\r\n"));
}

@ParameterizedTest
@ValueSource(strings = {
"https://127.0.0.1:45450/owned/.well-known/oauth-protected-resource",
"HTTPS://metadata.example.test:8443/discovery?tenant=demo",
"https://[::1]:443/discovery",
"https://metadata.example.test:65535/a/../metadata",
"https://metadata.example.test/m%C3%A9tadata?value=%22safe%22"
})
void preservesValidConfiguredUrlsExactly(String configured) {
assertEquals(configured, WebUtils.validateMcpResourceMetadataUrl(configured));
}

@ParameterizedTest
@MethodSource("invalidUrls")
void rejectsInvalidConfigurationWithoutEchoingItsValue(String configured) {
IllegalArgumentException error = assertThrows(
IllegalArgumentException.class, () -> WebUtils.validateMcpResourceMetadataUrl(configured));
assertTrue(error.getMessage().contains("mcp.oauth.resourceMetadataUrl"));
assertFalse(error.getMessage().contains(configured));
}

static Stream<String> invalidUrls() {
return Stream.of(
"http://127.0.0.1/discovery",
"/discovery",
"https:///discovery",
"https://127.0.0.1/discovery#section",
"https://fixture:fixture@127.0.0.1/discovery",
" https://127.0.0.1/discovery",
"https://127.0.0.1/discovery ",
"https://127.0.0.1:0/discovery",
"https://127.0.0.1:65536/discovery",
"https://127.0.0.1/discovery\n",
"https://127.0.0.1/dis\rcovery",
"https://127.0.0.1/discovery\u007f",
"https://127.0.0.1/m\u00e9tadata",
"https://127.0.0.1/discovery?value=\"raw\"",
"https://127.0.0.1/dis\\covery",
"https://127.0.0.1/discovery?value=\u0080");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package com.oracle.database.mcptoolkit.web;

import jakarta.servlet.http.HttpServletRequest;
import java.lang.reflect.Proxy;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

class WebUtilsResourceUrlTest {
private HttpServletRequest request() {
return (HttpServletRequest) Proxy.newProxyInstance(
getClass().getClassLoader(), new Class<?>[]{HttpServletRequest.class},
(proxy, method, args) -> switch (method.getName()) {
case "getHeader" -> null;
case "getScheme" -> "http";
case "getServerName" -> "127.0.0.1";
case "getServerPort" -> 18080;
default -> throw new UnsupportedOperationException(method.getName());
});
}

@Test
void honorsConfiguredResourceInsteadOfServletOrigin() {
String configured = "https://127.0.0.1:45450/mcp";
assertEquals(configured, WebUtils.resolveMcpResourceUrl(request(), configured));
}

@Test
void preservesPublicPathPrefixExactly() {
String configured = "https://127.0.0.1:45450/owned/mcp";
assertEquals(configured, WebUtils.resolveMcpResourceUrl(request(), configured));
}

@Test
void preservesQueryAndTrailingSlashExactly() {
String configured = "https://127.0.0.1:45450/owned/mcp/?version=1";
assertEquals(configured, WebUtils.resolveMcpResourceUrl(request(), configured));
}

@Test
void doesNotReadRequestWhenConfigured() {
String configured = "https://127.0.0.1:45450/mcp";
assertEquals(configured, WebUtils.resolveMcpResourceUrl(null, configured));
}

@Test
void retainsRequestDefaultWhenAbsent() {
assertEquals("http://127.0.0.1:18080/mcp", WebUtils.resolveMcpResourceUrl(request(), null));
}

@Test
void retainsRequestDefaultWhenBlank() {
assertEquals("http://127.0.0.1:18080/mcp", WebUtils.resolveMcpResourceUrl(request(), " "));
}

@Test
void absentConfigurationStillRequiresRequest() {
assertThrows(NullPointerException.class, () -> WebUtils.resolveMcpResourceUrl(null, null));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package com.oracle.database.mcptoolkit.web;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Proxy;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

class WellKnownServletConfiguredResourceTest {
private static final String RESOURCE = "https://mcp.example.test/public/mcp";
private static final String AUTHORIZATION_SERVER = "https://auth.example.test";

@Test
void advertisesConfiguredResourceAndAuthorizationServer() throws Exception {
// Configuration is static, so use a fresh JVM independent of other tests.
Process process = new ProcessBuilder(
Path.of(System.getProperty("java.home"), "bin", "java").toString(),
"-Dauth.enabled=true",
"-Dauth.userTokenValidation.mode=jwt",
"-Dauth.userTokenValidation.jwt.issuer=" + AUTHORIZATION_SERVER,
"-Dauth.userTokenValidation.jwt.jwksUri=" + AUTHORIZATION_SERVER + "/jwks",
"-Dauth.userTokenValidation.jwt.audience=configured-resource-test",
"-Dauth.authorizationServer=" + AUTHORIZATION_SERVER,
"-Dauth.openIdDiscoveryRedirectEnabled=false",
"-Dmcp.oauth.resourceUrl=" + RESOURCE,
"-cp", System.getProperty("surefire.test.class.path",
System.getProperty("java.class.path")),
WellKnownServletConfiguredResourceTest.class.getName())
.redirectError(ProcessBuilder.Redirect.INHERIT)
.start();
try {
assertTrue(process.waitFor(20, TimeUnit.SECONDS), "Servlet probe did not exit");
assertEquals(0, process.exitValue(), "Servlet probe failed");
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
JsonNode metadata = new ObjectMapper().readTree(output);
assertEquals(RESOURCE, metadata.path("resource").asText());
assertEquals(AUTHORIZATION_SERVER, metadata.path("authorization_servers").get(0).asText());
} finally {
if (process.isAlive()) {
process.destroyForcibly();
assertTrue(process.waitFor(5, TimeUnit.SECONDS), "Servlet probe did not stop");
}
}
}

public static void main(String[] args) throws Exception {
HttpServletRequest request = (HttpServletRequest) Proxy.newProxyInstance(
WellKnownServletConfiguredResourceTest.class.getClassLoader(),
new Class<?>[]{HttpServletRequest.class},
(proxy, method, arguments) -> switch (method.getName()) {
case "getHeader" -> null;
case "getScheme" -> "http";
case "getServerName" -> "127.0.0.1";
case "getServerPort" -> 18080;
default -> throw new UnsupportedOperationException(method.getName());
});
StringWriter body = new StringWriter();
int[] status = {0};
HttpServletResponse response = (HttpServletResponse) Proxy.newProxyInstance(
WellKnownServletConfiguredResourceTest.class.getClassLoader(),
new Class<?>[]{HttpServletResponse.class},
(proxy, method, arguments) -> switch (method.getName()) {
case "setContentType", "addHeader" -> null;
case "setStatus" -> { status[0] = (int) arguments[0]; yield null; }
case "getWriter" -> new PrintWriter(body);
default -> throw new UnsupportedOperationException(method.getName());
});
new WellKnownServlet().doGet(request, response);
if (status[0] != HttpServletResponse.SC_OK) {
throw new IllegalStateException("Expected metadata status 200, got " + status[0]);
}
System.out.print(body);
}
}
Loading
Loading