This is an automated email from the ASF dual-hosted git repository.

jerryshao pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/main by this push:
     new 8dc5c43bf0 [#14871] improvement(mcp-server): Document private CA trust 
for HTTPS Gravitino and test both TLS hops (#14872)
8dc5c43bf0 is described below

commit 8dc5c43bf0e792aededf800f93e64658e3ee7f93
Author: Qi Yu <[email protected]>
AuthorDate: Wed Nov 11 16:06:03 2026 +0800

    [#14871] improvement(mcp-server): Document private CA trust for HTTPS 
Gravitino and test both TLS hops (#14872)
    
    ### What changes were proposed in this pull request?
    
    - `docs/gravitino-mcp-server.md`:
    - A new "Connecting to Gravitino over HTTPS" section explains how to
    trust a private CA for `--gravitino-uri`. Build a PEM bundle that holds
    the public roots plus the CA, and point `SSL_CERT_FILE` at it. The
    section warns that `SSL_CERT_FILE` replaces the default roots instead of
    adding to them, that the bundle also applies to the OAuth token
    endpoint, and what the error looks like when the certificate is not
    trusted.
    - The serving section now says that the certificate and key are read at
    startup.
    - `tests/unit/test_tls_end_to_end.py` generates throwaway certificates
    from one private CA and makes real connections:
    - **Outbound**: a Gravitino stub served over HTTPS. With the CA bundle
    in `SSL_CERT_FILE`, `list_metalakes` succeeds. Without it, the call
    fails with `CERTIFICATE_VERIFY_FAILED`.
    - **Inbound**: `python -m mcp_server` is started with
    `--tls-cert`/`--tls-key`. The endpoint completes a TLS handshake with
    the CA, and rejects both the default roots and plain HTTP.
    - `cryptography` is added to the dev dependencies (`pyproject.toml`, the
    pinned `devToolRequirements` in `build.gradle.kts`, and `uv.lock`). It
    was already installed as a transitive runtime dependency, but the tests
    now import it directly. The other `uv.lock` changes are uv re-resolving
    its environment markers after this direct dev dependency was added.
    
    ### Why are the changes needed?
    
    Operators running Gravitino with a private CA had no documented way to
    make the MCP server trust it, and the obvious setting, pointing
    `SSL_CERT_FILE` at the CA alone, silently breaks a public identity
    provider. No existing test made a real TLS connection, so a break on
    either hop would go unnoticed.
    
    Fix: #14871
    
    ### Does this PR introduce _any_ user-facing change?
    
    Documentation only. There is no change to runtime code or options.
    
    ### How was this patch tested?
    
    - `./gradlew :mcp-server:formatCheckPython :mcp-server:pylint
    :mcp-server:testPython`: formatting is clean, pylint rates the code
    10.00/10, and all 327 unit tests pass, including the 3 new ones.
    - Mutation check: without the `uvicorn_config` TLS wiring in
    `server.py`, the endpoint test fails.
---
 docs/gravitino-mcp-server.md                 |  18 ++
 mcp-server/build.gradle.kts                  |   6 +-
 mcp-server/pyproject.toml                    |   2 +
 mcp-server/tests/unit/test_tls_end_to_end.py | 284 +++++++++++++++++++++++++++
 mcp-server/uv.lock                           |  20 +-
 5 files changed, 319 insertions(+), 11 deletions(-)

diff --git a/docs/gravitino-mcp-server.md b/docs/gravitino-mcp-server.md
index d748cf378a..407e1b7249 100644
--- a/docs/gravitino-mcp-server.md
+++ b/docs/gravitino-mcp-server.md
@@ -340,6 +340,24 @@ uv run mcp_server --metalake test --gravitino-uri 
http://127.0.0.1:8090 \
   --tls-cert /path/to/cert.pem --tls-key /path/to/key.pem
 ```
 
+The server reads the certificate and key at startup, so restart it after 
rotating them.
+
+### Connecting to Gravitino over HTTPS
+
+When `--gravitino-uri` uses `https://`, the server verifies Gravitino's 
certificate against the public root certificates it ships with. If a private CA 
signed that certificate, set `SSL_CERT_FILE` to a PEM bundle that contains both 
the public roots and the CA:
+
+```shell
+cat "$(uv run python -c 'import certifi; print(certifi.where())')" 
/path/to/ca.crt > /path/to/ca-bundle.crt
+SSL_CERT_FILE=/path/to/ca-bundle.crt uv run mcp_server --metalake test \
+  --gravitino-uri https://gravitino.example.com:8433 \
+  --transport streamable-http --mcp-url https://localhost:8000/mcp \
+  --tls-cert /path/to/cert.pem --tls-key /path/to/key.pem
+```
+
+- `SSL_CERT_FILE` replaces the default roots instead of adding to them. A file 
with only the private CA breaks connections to servers with public 
certificates, such as an identity provider's token endpoint.
+- The bundle applies to every outbound HTTPS connection, including the 
`--oauth-token-endpoint` request.
+- If the certificate is not trusted, tool calls fail with 
`CERTIFICATE_VERIFY_FAILED`. Restart the server after replacing the bundle.
+
 ## Selecting a metalake
 
 A metalake is Gravitino's top-level tenant boundary, and every tool operates 
inside one. `--metalake` sets the **default**: the metalake used by any tool 
call that does not name one itself. It is optional on every transport.
diff --git a/mcp-server/build.gradle.kts b/mcp-server/build.gradle.kts
index 892da89774..0e3caf47c1 100644
--- a/mcp-server/build.gradle.kts
+++ b/mcp-server/build.gradle.kts
@@ -55,12 +55,14 @@ val blackRequirement = "black==26.5.1"
 val isortRequirement = "isort==9.0.0"
 
 // Dev tooling used by the pylint and testPython tasks: pylint (and its 
transitive
-// astroid) for linting, pytest and parameterized for the unit tests. These 
live in
+// astroid) for linting, pytest and parameterized for the unit tests, and
+// cryptography to generate certificates for the TLS end-to-end tests. These 
live in
 // pyproject's [dependency-groups] dev, not the runtime dependencies, so
 // `uv pip install -e .` (installDependenciesWithUv) does not pull them in and 
they
 // never reach the shipped image. Pinned so a new release cannot change the 
lint/test
 // outcome in CI.
 val devToolRequirements = listOf(
+  "cryptography==50.0.2",
   "pylint==3.3.8",
   "pytest==8.4.1",
   "parameterized==0.9.0"
@@ -192,7 +194,7 @@ tasks {
 
   register<Exec>("installDevTools") {
     group = "python"
-    description = "Install dev-group tooling (pylint, pytest, parameterized) 
into the venv"
+    description = "Install dev-group tooling (pylint, pytest, parameterized, 
cryptography) into the venv"
     dependsOn("installDependenciesWithUv")
     workingDir(pythonProjectDir)
 
diff --git a/mcp-server/pyproject.toml b/mcp-server/pyproject.toml
index 1d6acfa504..42abf3e399 100644
--- a/mcp-server/pyproject.toml
+++ b/mcp-server/pyproject.toml
@@ -46,6 +46,8 @@ dependencies = [
 # distributed runtime environment. Developers still get them via `uv sync` 
locally.
 [dependency-groups]
 dev = [
+    # Generates throwaway certificates for the TLS end-to-end tests.
+    "cryptography>=46",
     "parameterized>=0.9.0",
     "pytest>=8.4.1",
     "pylint>=2.20.0",
diff --git a/mcp-server/tests/unit/test_tls_end_to_end.py 
b/mcp-server/tests/unit/test_tls_end_to_end.py
new file mode 100644
index 0000000000..ea00c3ab64
--- /dev/null
+++ b/mcp-server/tests/unit/test_tls_end_to_end.py
@@ -0,0 +1,284 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""End-to-end TLS with a private CA, over real connections.
+
+Covers both hops: the MCP endpoint served over HTTPS with --tls-cert/--tls-key,
+and outbound calls to a Gravitino server whose certificate is signed by a
+private CA that is trusted through SSL_CERT_FILE.
+"""
+
+import datetime
+import http.server
+import ipaddress
+import json
+import os
+import shutil
+import socket
+import ssl
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+import certifi
+import httpx
+from cryptography import x509
+from cryptography.hazmat.primitives import hashes, serialization
+from cryptography.hazmat.primitives.asymmetric import ec
+from cryptography.x509.oid import NameOID
+
+from mcp_server.client.plain.plain_rest_client_operation import (
+    PlainRESTClientOperation,
+)
+
+_PROJECT_DIR = Path(__file__).resolve().parents[2]
+_METALAKES = {"code": 0, "metalakes": [{"name": "lake_over_tls"}]}
+
+
+def _free_port() -> int:
+    with socket.socket() as sock:
+        sock.bind(("127.0.0.1", 0))
+        return sock.getsockname()[1]
+
+
+def _write_private_ca(directory: Path) -> tuple[Path, Path, Path]:
+    """Write a private CA and a localhost certificate it signs.
+
+    Returns the CA certificate, the server certificate and the server key.
+    """
+    now = datetime.datetime.now(datetime.timezone.utc)
+    ca_key = ec.generate_private_key(ec.SECP256R1())
+    ca_name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "test-ca")])
+    ca_cert = (
+        x509.CertificateBuilder()
+        .subject_name(ca_name)
+        .issuer_name(ca_name)
+        .public_key(ca_key.public_key())
+        .serial_number(x509.random_serial_number())
+        .not_valid_before(now - datetime.timedelta(minutes=5))
+        .not_valid_after(now + datetime.timedelta(days=1))
+        .add_extension(x509.BasicConstraints(ca=True, path_length=None), True)
+        .add_extension(
+            x509.KeyUsage(
+                digital_signature=True,
+                content_commitment=False,
+                key_encipherment=False,
+                data_encipherment=False,
+                key_agreement=False,
+                key_cert_sign=True,
+                crl_sign=True,
+                encipher_only=False,
+                decipher_only=False,
+            ),
+            True,
+        )
+        .sign(ca_key, hashes.SHA256())
+    )
+    server_key = ec.generate_private_key(ec.SECP256R1())
+    server_cert = (
+        x509.CertificateBuilder()
+        .subject_name(
+            x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "localhost")])
+        )
+        .issuer_name(ca_name)
+        .public_key(server_key.public_key())
+        .serial_number(x509.random_serial_number())
+        .not_valid_before(now - datetime.timedelta(minutes=5))
+        .not_valid_after(now + datetime.timedelta(days=1))
+        .add_extension(
+            x509.SubjectAlternativeName(
+                [
+                    x509.DNSName("localhost"),
+                    x509.IPAddress(ipaddress.ip_address("127.0.0.1")),
+                ]
+            ),
+            False,
+        )
+        .sign(ca_key, hashes.SHA256())
+    )
+    ca_path = directory / "ca.crt"
+    cert_path = directory / "server.crt"
+    key_path = directory / "server.key"
+    ca_path.write_bytes(ca_cert.public_bytes(serialization.Encoding.PEM))
+    cert_path.write_bytes(server_cert.public_bytes(serialization.Encoding.PEM))
+    key_path.write_bytes(
+        server_key.private_bytes(
+            serialization.Encoding.PEM,
+            serialization.PrivateFormat.PKCS8,
+            serialization.NoEncryption(),
+        )
+    )
+    return ca_path, cert_path, key_path
+
+
+class _GravitinoHandler(http.server.BaseHTTPRequestHandler):
+    def do_GET(self):  # pylint: disable=invalid-name
+        body = json.dumps(_METALAKES).encode()
+        self.send_response(200)
+        self.send_header("Content-Type", "application/json")
+        self.send_header("Content-Length", str(len(body)))
+        self.end_headers()
+        self.wfile.write(body)
+
+    def log_message(self, *args):  # Keep the test output quiet.
+        pass
+
+
+class _PrivateCaFixture:
+    """Certificates from one private CA, and a fake Gravitino served over 
TLS."""
+
+    def __init__(self):
+        self.directory = Path(tempfile.mkdtemp())
+        self.ca, self.cert, self.key = _write_private_ca(self.directory)
+        # SSL_CERT_FILE replaces the default roots, so the bundle carries both.
+        self.bundle = self.directory / "bundle.crt"
+        self.bundle.write_bytes(
+            Path(certifi.where()).read_bytes() + self.ca.read_bytes()
+        )
+        self.gravitino = http.server.ThreadingHTTPServer(
+            ("127.0.0.1", 0), _GravitinoHandler
+        )
+        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+        context.load_cert_chain(self.cert, self.key)
+        self.gravitino.socket = context.wrap_socket(
+            self.gravitino.socket, server_side=True
+        )
+        self.gravitino_uri = f"https://localhost:{self.gravitino.server_port}";
+        threading.Thread(
+            target=self.gravitino.serve_forever, daemon=True
+        ).start()
+
+    def close(self):
+        self.gravitino.shutdown()
+        self.gravitino.server_close()
+        shutil.rmtree(self.directory, ignore_errors=True)
+
+
+class TestGravitinoOverTls(unittest.IsolatedAsyncioTestCase):
+    """Outbound calls to a Gravitino server whose certificate a private CA 
signs."""
+
+    @classmethod
+    def setUpClass(cls):
+        cls.tls = _PrivateCaFixture()
+
+    @classmethod
+    def tearDownClass(cls):
+        cls.tls.close()
+
+    async def _list_metalakes(self, trust: dict) -> str:
+        # httpx reads SSL_CERT_FILE when the client is created.
+        with patch.dict(os.environ, trust):
+            operation = PlainRESTClientOperation("lake", 
self.tls.gravitino_uri)
+        try:
+            return (
+                await operation.as_metalake_operation().get_list_of_metalakes()
+            )
+        finally:
+            await operation.close()
+
+    async def test_gravitino_signed_by_trusted_private_ca(self):
+        result = await self._list_metalakes(
+            {"SSL_CERT_FILE": str(self.tls.bundle), "SSL_CERT_DIR": ""}
+        )
+        self.assertIn("lake_over_tls", result)
+
+    async def test_gravitino_signed_by_untrusted_private_ca(self):
+        with self.assertRaisesRegex(
+            httpx.ConnectError, "CERTIFICATE_VERIFY_FAILED"
+        ):
+            await self._list_metalakes(
+                {"SSL_CERT_FILE": "", "SSL_CERT_DIR": ""}
+            )
+
+
+class TestMcpEndpointOverTls(unittest.TestCase):
+    """The MCP endpoint served with --tls-cert/--tls-key, from a real 
process."""
+
+    @classmethod
+    def setUpClass(cls):
+        cls.tls = _PrivateCaFixture()
+
+    @classmethod
+    def tearDownClass(cls):
+        cls.tls.close()
+
+    def test_mcp_endpoint_served_over_tls(self):
+        port = _free_port()
+        url = f"https://127.0.0.1:{port}/mcp";
+        process = subprocess.Popen(  # pylint: disable=consider-using-with
+            [
+                sys.executable,
+                "-m",
+                "mcp_server",
+                "--metalake",
+                "lake",
+                "--gravitino-uri",
+                self.tls.gravitino_uri,
+                "--transport",
+                "streamable-http",
+                "--mcp-url",
+                url,
+                "--tls-cert",
+                str(self.tls.cert),
+                "--tls-key",
+                str(self.tls.key),
+            ],
+            cwd=_PROJECT_DIR,
+            stdout=subprocess.DEVNULL,
+            stderr=subprocess.DEVNULL,
+        )
+        try:
+            trusted = ssl.create_default_context(cafile=str(self.tls.ca))
+            response = self._wait_for_tls(url, trusted, process)
+            # The endpoint answers over TLS; a plain GET is not a valid MCP 
request.
+            self.assertLess(response.status_code, 500)
+            with self.assertRaisesRegex(
+                httpx.ConnectError, "CERTIFICATE_VERIFY_FAILED"
+            ):
+                httpx.get(
+                    url,
+                    verify=ssl.create_default_context(cafile=certifi.where()),
+                )
+            with self.assertRaises(httpx.HTTPError):
+                httpx.get(url.replace("https://";, "http://";, 1))
+        finally:
+            process.terminate()
+            process.wait(timeout=30)
+
+    @staticmethod
+    def _wait_for_tls(url, context, process, timeout=60.0):
+        deadline = time.monotonic() + timeout
+        while True:
+            try:
+                return httpx.get(url, verify=context)
+            except httpx.ConnectError:
+                if process.poll() is not None:
+                    raise AssertionError(
+                        f"MCP server exited with {process.returncode}"
+                    ) from None
+                if time.monotonic() > deadline:
+                    raise
+                time.sleep(0.2)
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/mcp-server/uv.lock b/mcp-server/uv.lock
index c3920da987..8f315d3714 100644
--- a/mcp-server/uv.lock
+++ b/mcp-server/uv.lock
@@ -18,7 +18,7 @@ resolution-markers = [
     "python_full_version < '3.11'",
 ]
 dependencies = [
-    { name = "caio" },
+    { name = "caio", marker = "python_full_version < '3.11'" },
 ]
 sdist = { url = 
"https://files.pythonhosted.org/packages/67/e2/d7cb819de8df6b5c1968a2756c3cb4122d4fa2b8fc768b53b7c9e5edb646/aiofile-3.9.0.tar.gz";,
 hash = 
"sha256:e5ad718bb148b265b6df1b3752c4d1d83024b93da9bd599df74b9d9ffcf7919b", size 
= 17943, upload-time = "2024-10-08T10:39:35.846Z" }
 wheels = [
@@ -37,7 +37,7 @@ resolution-markers = [
     "python_full_version == '3.11.*'",
 ]
 dependencies = [
-    { name = "caio" },
+    { name = "caio", marker = "python_full_version >= '3.11'" },
 ]
 sdist = { url = 
"https://files.pythonhosted.org/packages/48/41/2fea7e193e061ce54eacc3b7bc0e6a99e4fcff43c78cf0a76dd781ed8334/aiofile-3.11.1.tar.gz";,
 hash = 
"sha256:1f91912c6643d2a4e49ca4ae3514f0bf3867ce948a36d99a6411b8f4755f4cf9", size 
= 19342, upload-time = "2026-05-16T08:18:33.538Z" }
 wheels = [
@@ -520,6 +520,7 @@ dependencies = [
 
 [package.dev-dependencies]
 dev = [
+    { name = "cryptography" },
     { name = "parameterized" },
     { name = "pylint" },
     { name = "pytest" },
@@ -536,6 +537,7 @@ requires-dist = [
 
 [package.metadata.requires-dev]
 dev = [
+    { name = "cryptography", specifier = ">=46" },
     { name = "parameterized", specifier = ">=0.9.0" },
     { name = "pylint", specifier = ">=2.20.0" },
     { name = "pytest", specifier = ">=8.4.1" },
@@ -622,7 +624,7 @@ name = "importlib-metadata"
 version = "9.0.0"
 source = { registry = "https://pypi.org/simple"; }
 dependencies = [
-    { name = "zipp" },
+    { name = "zipp", marker = "python_full_version < '3.12'" },
 ]
 sdist = { url = 
"https://files.pythonhosted.org/packages/a9/01/15bb152d77b21318514a96f43af312635eb2500c96b55398d020c93d86ea/importlib_metadata-9.0.0.tar.gz";,
 hash = 
"sha256:a4f57ab599e6a2e3016d7595cfd72eb4661a5106e787a95bcc90c7105b831efc", size 
= 56405, upload-time = "2026-03-20T06:42:56.999Z" }
 wheels = [
@@ -1477,8 +1479,8 @@ name = "secretstorage"
 version = "3.5.0"
 source = { registry = "https://pypi.org/simple"; }
 dependencies = [
-    { name = "cryptography" },
-    { name = "jeepney" },
+    { name = "cryptography", marker = "python_full_version < '3.12' or 
sys_platform != 'win32'" },
+    { name = "jeepney", marker = "python_full_version < '3.12' or sys_platform 
!= 'win32'" },
 ]
 sdist = { url = 
"https://files.pythonhosted.org/packages/1c/03/e834bcd866f2f8a49a85eaff47340affa3bfa391ee9912a952a1faa68c7b/secretstorage-3.5.0.tar.gz";,
 hash = 
"sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be", size 
= 19884, upload-time = "2025-11-23T19:02:53.191Z" }
 wheels = [
@@ -1575,8 +1577,8 @@ resolution-markers = [
     "python_full_version < '3.11'",
 ]
 dependencies = [
-    { name = "anyio" },
-    { name = "typing-extensions" },
+    { name = "anyio", marker = "python_full_version < '3.11'" },
+    { name = "typing-extensions", marker = "python_full_version < '3.11'" },
 ]
 sdist = { url = 
"https://files.pythonhosted.org/packages/7b/2b/3850dc6bf7ef71b088962eba31dafc6cffd2f96e577ebb0bb316df96da3e/starlette-1.7.0.tar.gz";,
 hash = 
"sha256:c79f74ea63cff761804fbbfb182f1e0b440c2d07b164d24700c5a1bab5d6ff5d", size 
= 2736246, upload-time = "2026-09-23T07:30:26.35Z" }
 wheels = [
@@ -1595,8 +1597,8 @@ resolution-markers = [
     "python_full_version == '3.11.*'",
 ]
 dependencies = [
-    { name = "anyio" },
-    { name = "typing-extensions", marker = "python_full_version < '3.13'" },
+    { name = "anyio", marker = "python_full_version >= '3.11'" },
+    { name = "typing-extensions", marker = "python_full_version >= '3.11' and 
python_full_version < '3.13'" },
 ]
 sdist = { url = 
"https://files.pythonhosted.org/packages/48/bb/3d8757f21e9a53d9035c9eb039a777047139a16bfdbedfc7a58241c3d914/starlette-1.10.0.tar.gz";,
 hash = 
"sha256:b8399098d4c1e3522734f7235dc79b1fc967f96cf139c81e0fa30479e0685f9b", size 
= 2734356, upload-time = "2026-10-24T15:04:12.342Z" }
 wheels = [

Reply via email to