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

yuqi1129 pushed a commit to branch branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git


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

commit a59a8980e66d06ea0cf398b764cf771cdf4bae95
Author: github-actions[bot] 
<41898282+github-actions[bot]@users.noreply.github.com>
AuthorDate: Wed Nov 11 22:45:34 2026 +0800

    [Cherry-pick to branch-1.3] [#14871] improvement(mcp-server): Document 
private CA trust for HTTPS Gravitino and test both TLS hops (#14872) (#14889)
    
    **Cherry-pick Information:**
    - Original commit: 8dc5c43bf0e792aededf800f93e64658e3ee7f93 (#14872,
    fixes #14871)
    - Target branch: `branch-1.3`
    - Conflicts resolved in e833a0a7ad.
    
    Preserves the TLS/private CA documentation alongside the existing
    statistics documentation. Keeps the 1.3 runtime dependency versions in
    `uv.lock`, adding only the certificate-generation test dependency.
    Adapts the outbound TLS tests to the catalog API available in 1.3.
    
    Validation on Python 3.10:
    - `uv lock --check` and `uv sync --locked` passed.
    - All 181 MCP unit tests passed with locked dependencies and again with
    CI-pinned `cryptography==50.0.2`.
    - Black, isort, pylint, and `git diff --check` passed for the changes.
    
    ---------
    
    Co-authored-by: Qi Yu <[email protected]>
    Co-authored-by: yuqi <[email protected]>
---
 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 | 280 +++++++++++++++++++++++++++
 mcp-server/uv.lock                           |   2 +
 5 files changed, 306 insertions(+), 2 deletions(-)

diff --git a/docs/gravitino-mcp-server.md b/docs/gravitino-mcp-server.md
index 0422a113ba..a2571da1d9 100644
--- a/docs/gravitino-mcp-server.md
+++ b/docs/gravitino-mcp-server.md
@@ -207,6 +207,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.
+
 ## Statistics tool parameters
 
 The statistic tools (`list_statistics_for_metadata`, 
`list_statistics_for_partition`) require `metalake_name` to identify the 
metalake.
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 43b3969ec2..b1ad274bea 100644
--- a/mcp-server/pyproject.toml
+++ b/mcp-server/pyproject.toml
@@ -44,6 +44,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..5e1bc961bc
--- /dev/null
+++ b/mcp-server/tests/unit/test_tls_end_to_end.py
@@ -0,0 +1,280 @@
+# 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]
+_CATALOGS = {"code": 0, "catalogs": [{"name": "catalog_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(_CATALOGS).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_catalogs(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_catalog_operation().get_list_of_catalogs()
+        finally:
+            await operation.close()
+
+    async def test_gravitino_signed_by_trusted_private_ca(self):
+        result = await self._list_catalogs(
+            {"SSL_CERT_FILE": str(self.tls.bundle), "SSL_CERT_DIR": ""}
+        )
+        self.assertIn("catalog_over_tls", result)
+
+    async def test_gravitino_signed_by_untrusted_private_ca(self):
+        with self.assertRaisesRegex(
+            httpx.ConnectError, "CERTIFICATE_VERIFY_FAILED"
+        ):
+            await self._list_catalogs({"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 69ec4fd1af..dc47d56335 100644
--- a/mcp-server/uv.lock
+++ b/mcp-server/uv.lock
@@ -470,6 +470,7 @@ dependencies = [
 
 [package.dev-dependencies]
 dev = [
+    { name = "cryptography" },
     { name = "parameterized" },
     { name = "pylint" },
     { name = "pytest" },
@@ -485,6 +486,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" },

Reply via email to