Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

25.5 KB
Raw Blame
# 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.

import asyncio
import base64
import hashlib
import json
import logging
import unittest
from unittest.mock import MagicMock, patch

import httpx
from fastmcp import Client

from mcp_server.client.factory import RESTClientFactory
from mcp_server.client.plain.exception import GravitinoException
from mcp_server.client.plain.plain_rest_client_operation import (
    PlainRESTClientOperation,
)
from mcp_server.core import audit
from mcp_server.core.setting import Setting
from mcp_server.server import GravitinoMCPServer
from tests.unit.tools import MockOperation

# Tests intentionally exercise module-private helpers (e.g. audit._extract_principal)
# and client internals; protected access is expected here.
# pylint: disable=protected-access


class TestAuditEmit(unittest.TestCase):
    """Unit tests for the audit.emit() function."""

    def setUp(self):
        # tests/unit/tools/__init__.py calls logging.disable(logging.INFO).
        # Re-enable here so audit records flow through; restore on teardown.
        logging.disable(logging.NOTSET)
        self.log_records = []
        self.handler = _CapturingHandler(self.log_records)
        audit_logger = logging.getLogger("gravitino.mcp.audit")
        audit_logger.addHandler(self.handler)
        audit_logger.setLevel(logging.INFO)
        audit_logger.propagate = False

    def tearDown(self):
        logging.disable(logging.INFO)
        audit_logger = logging.getLogger("gravitino.mcp.audit")
        audit_logger.removeHandler(self.handler)
        audit_logger.propagate = True

    def test_allow_record_structure(self):
        """emit() writes a JSON record with all required fields on allow."""
        audit.emit(
            principal="bearer:abc12345", tool="list_catalogs", outcome="allow"
        )

        self.assertEqual(len(self.log_records), 1)
        record = json.loads(self.log_records[0])
        self.assertEqual(record["principal"], "bearer:abc12345")
        self.assertEqual(record["tool"], "list_catalogs")
        self.assertEqual(record["outcome"], "allow")
        self.assertIn("timestamp", record)
        self.assertNotIn("error_type", record)

    def test_deny_record_includes_error_type(self):
        """emit() includes error_type in the record when outcome is deny."""
        audit.emit(
            principal="bearer:xyz99999",
            tool="create_tag",
            outcome="deny",
            error_type="GravitinoException",
        )

        record = json.loads(self.log_records[0])
        self.assertEqual(record["outcome"], "deny")
        self.assertEqual(record["error_type"], "GravitinoException")

    def test_anonymous_principal(self):
        """emit() works with anonymous principal."""
        audit.emit(
            principal="anonymous", tool="get_list_of_catalogs", outcome="allow"
        )
        record = json.loads(self.log_records[0])
        self.assertEqual(record["principal"], "anonymous")


class TestExtractPrincipal(unittest.TestCase):
    """Unit tests for audit._extract_principal()."""

    def test_bearer_token_is_fingerprinted(self):
        self.assertEqual(
            audit._extract_principal("Bearer abcdefghijklmnop"),
            "bearer:f39dac6cbaba535e",
        )

    def test_empty_header_returns_anonymous(self):
        self.assertEqual(audit._extract_principal(""), "anonymous")

    def test_none_like_empty_returns_anonymous(self):
        self.assertEqual(audit._extract_principal(None), "anonymous")

    def test_short_token_is_fingerprinted(self):
        self.assertEqual(
            audit._extract_principal("Bearer abc"),
            "bearer:ba7816bf8f01cfea",
        )

    def test_jwts_sharing_a_header_get_distinct_principals(self):
        tokens = [_jwt_for(subject) for subject in ("alice", "bob", "carol")]
        self.assertEqual(len({token.split(".")[0] for token in tokens}), 1)
        principals = {
            audit._extract_principal(f"Bearer {token}") for token in tokens
        }
        self.assertEqual(len(principals), 3)

    def test_same_claims_under_another_signature_get_another_principal(self):
        self.assertNotEqual(
            audit._extract_principal(f"Bearer {_jwt_for('alice')}"),
            audit._extract_principal(f"Bearer {_jwt_for('alice', b'forged')}"),
        )

    def test_jwt_principal_is_the_fingerprint_of_the_whole_token(self):
        token = _jwt_for("alice")
        self.assertEqual(
            hashlib.sha256(token.encode()).hexdigest()[:16], "3056aa588a7ade5e"
        )
        self.assertEqual(
            audit._extract_principal(f"Bearer {token}"),
            "bearer:3056aa588a7ade5e",
        )

    def test_credential_that_is_not_valid_utf8_still_yields_a_principal(self):
        self.assertEqual(
            audit._extract_principal("Bearer \udcff\udcfe"),
            "bearer:8db8cb0aa243f9fc",
        )

    def test_basic_auth_decodes_user(self):
        """Simple auth header 'Basic base64(alice:dummy)' -> principal 'alice'."""
        # base64("alice:dummy") == "YWxpY2U6ZHVtbXk="
        self.assertEqual(
            audit._extract_principal("Basic YWxpY2U6ZHVtbXk="), "alice"
        )

    def test_basic_auth_invalid_base64_returns_anonymous(self):
        self.assertEqual(
            audit._extract_principal("Basic not-valid-base64!!"), "anonymous"
        )

    def test_other_scheme_falls_back_to_scheme_prefix(self):
        """A non-Basic scheme stays attributable via '<scheme>:<sha256[:16]>'."""
        self.assertEqual(
            audit._extract_principal("Negotiate abc123"),
            "negotiate:6ca13d52ca70c883",
        )

    def test_custom_scheme_with_multi_word_credential(self):
        """A credential containing spaces is not treated as unparsable."""
        self.assertEqual(
            audit._extract_principal("Custom-Scheme key=abcdefghij, sig=xy"),
            "custom-scheme:356588a47129863a",
        )

    def test_extra_space_between_scheme_and_credential(self):
        """Repeated separators do not break Basic decoding."""
        self.assertEqual(
            audit._extract_principal("Basic   YWxpY2U6ZHVtbXk="), "alice"
        )

    def test_scheme_without_credential_returns_anonymous(self):
        """A scheme with no credential has no identity to report."""
        self.assertEqual(audit._extract_principal("Bearer"), "anonymous")
        self.assertEqual(audit._extract_principal("Bearer   "), "anonymous")


class TestAuditMiddlewareIntegration(unittest.TestCase):
    """Integration tests: AuditMiddleware emits records via the full MCP tool path."""

    def setUp(self):
        logging.disable(logging.NOTSET)
        self.log_records = []
        self.handler = _CapturingHandler(self.log_records)
        audit_logger = logging.getLogger("gravitino.mcp.audit")
        audit_logger.addHandler(self.handler)
        audit_logger.setLevel(logging.INFO)
        audit_logger.propagate = False

        RESTClientFactory.set_rest_client(MockOperation)
        server = GravitinoMCPServer(Setting("mock_metalake"))
        self.mcp = server.mcp

    def tearDown(self):
        logging.disable(logging.INFO)
        audit_logger = logging.getLogger("gravitino.mcp.audit")
        audit_logger.removeHandler(self.handler)
        audit_logger.propagate = True
        # Restore original REST client so other tests are not affected.
        RESTClientFactory.set_rest_client(PlainRESTClientOperation)

    def test_successful_tool_call_emits_allow_record(self):
        """A successful tool call produces an audit record with outcome=allow."""

        async def _run():
            async with Client(self.mcp) as client:
                await client.call_tool("get_list_of_catalogs")

        asyncio.run(_run())

        self.assertEqual(len(self.log_records), 1)
        record = json.loads(self.log_records[0])
        self.assertEqual(record["tool"], "get_list_of_catalogs")
        self.assertEqual(record["outcome"], "allow")
        self.assertEqual(record["principal"], "anonymous")

    def test_record_carries_the_resolved_metalake(self):
        """Defaulted calls must record the metalake too, not just named ones -
        otherwise the log cannot say which tenant was touched without also
        knowing the server's startup configuration."""

        async def _run():
            async with Client(self.mcp) as client:
                await client.call_tool("get_list_of_catalogs")
                await client.call_tool(
                    "get_list_of_catalogs", {"metalake": "named_ml"}
                )

        asyncio.run(_run())

        metalakes = [json.loads(r)["metalake"] for r in self.log_records]
        self.assertEqual(metalakes, ["mock_metalake", "named_ml"])

    def test_non_metalake_scoped_tool_records_no_metalake(self):
        """list_metalakes spans every metalake the caller can see, so tagging
        it with the server default would claim a tenant it never touched."""

        async def _run():
            async with Client(self.mcp) as client:
                await client.call_tool("list_metalakes")

        asyncio.run(_run())

        record = json.loads(self.log_records[0])
        self.assertEqual(record["tool"], "list_metalakes")
        self.assertNotIn("metalake", record)

    def test_principal_falls_back_to_startup_token(self):
        """With no request header, the audit principal uses the startup --token."""
        RESTClientFactory.set_rest_client(MockOperation)
        server = GravitinoMCPServer(
            Setting("mock_metalake", token="abcdef123456")
        )

        async def _run():
            async with Client(server.mcp) as client:
                await client.call_tool("get_list_of_catalogs")

        asyncio.run(_run())

        record = json.loads(self.log_records[0])
        self.assertEqual(record["principal"], "bearer:da4ec3358a10c9b0")

    def test_two_jwt_callers_get_separate_records_without_credentials(self):
        tokens = [_jwt_for("alice"), _jwt_for("bob")]

        async def _run():
            async with Client(self.mcp) as client:
                await client.call_tool("get_list_of_catalogs")

        for token in tokens:
            with patch(
                "mcp_server.server._get_request_authorization",
                return_value=f"Bearer {token}",
            ):
                asyncio.run(_run())

        records = [json.loads(line) for line in self.log_records]
        self.assertNotEqual(records[0]["principal"], records[1]["principal"])
        forbidden = {"alice", "bob", *".".join(tokens).split(".")}
        for line in self.log_records:
            for material in forbidden:
                self.assertNotIn(material, line)

    def test_principal_falls_back_to_oauth_client_id(self):
        """With no request header, OAuth client-credentials is attributable."""
        RESTClientFactory.set_rest_client(MockOperation)
        server = GravitinoMCPServer(
            Setting(
                "mock_metalake",
                oauth_token_endpoint="https://idp/token",
                oauth_client_id="mcp-service",
                oauth_client_secret="s",
            )
        )

        async def _run():
            async with Client(server.mcp) as client:
                await client.call_tool("get_list_of_catalogs")

        asyncio.run(_run())

        record = json.loads(self.log_records[0])
        self.assertEqual(record["principal"], "oauth:0d315e3c73d7840c")

    def test_failed_tool_call_emits_deny_record(self):
        """An authorization denial produces outcome=deny with the original error_type."""

        class FailingOperation(MockOperation):
            def as_catalog_operation(self):
                return _FailingCatalogOperation(
                    GravitinoException(
                        "Error code: 1008, Error type: ForbiddenException, "
                        "Error message: Not allowed",
                        status_code=403,
                        error_code=1008,
                        error_type="ForbiddenException",
                    )
                )

        RESTClientFactory.set_rest_client(FailingOperation)
        server = GravitinoMCPServer(Setting("mock_metalake"))

        async def _run():
            async with Client(server.mcp) as client:
                await client.call_tool(
                    "get_list_of_catalogs", raise_on_error=False
                )

        asyncio.run(_run())

        self.assertEqual(len(self.log_records), 1)
        record = json.loads(self.log_records[0])
        self.assertEqual(record["tool"], "get_list_of_catalogs")
        self.assertEqual(record["outcome"], "deny")
        self.assertEqual(record["error_type"], "ForbiddenException")
        self.assertEqual(record["error_category"], "permission_denied")
        self.assertNotEqual(record["error_type"], "McpError")

    def test_non_authz_failures_emit_error_outcome_and_original_classification(
        self,
    ):
        """Non-authz failures emit outcome=error with their original error type and category."""
        request = httpx.Request("GET", "http://gravitino/api/metalakes")
        cases = [
            (
                GravitinoException(
                    "Bad request",
                    status_code=400,
                    error_code=1001,
                    error_type="IllegalArgumentException",
                ),
                "error",
                "IllegalArgumentException",
                "invalid_params",
            ),
            (
                GravitinoException(
                    "Not found",
                    status_code=404,
                    error_code=1003,
                    error_type="NoSuchTableException",
                ),
                "error",
                "NoSuchTableException",
                "not_found",
            ),
            (
                GravitinoException(
                    "In use",
                    status_code=409,
                    error_code=1010,
                    error_type="CatalogInUseException",
                ),
                "error",
                "CatalogInUseException",
                "conflict",
            ),
            (
                httpx.ConnectError("Connection refused", request=request),
                "error",
                "ConnectError",
                "unavailable",
            ),
            (
                GravitinoException(
                    "Unauthenticated",
                    status_code=401,
                    error_code=1011,
                    error_type="UnauthorizedException",
                ),
                "deny",
                "UnauthorizedException",
                "unauthorized",
            ),
        ]

        for (
            exc_to_raise,
            expected_outcome,
            expected_type,
            expected_category,
        ) in cases:
            with self.subTest(expected_type=expected_type):
                self.log_records.clear()

                class FailingOperation(MockOperation):
                    def as_catalog_operation(self, err=exc_to_raise):
                        return _FailingCatalogOperation(err)

                RESTClientFactory.set_rest_client(FailingOperation)
                server = GravitinoMCPServer(Setting("mock_metalake"))

                async def _run(mcp=server.mcp):
                    async with Client(mcp) as client:
                        await client.call_tool(
                            "get_list_of_catalogs", raise_on_error=False
                        )

                asyncio.run(_run())

                self.assertEqual(len(self.log_records), 1)
                record = json.loads(self.log_records[0])
                self.assertEqual(record["outcome"], expected_outcome)
                self.assertEqual(record["error_type"], expected_type)
                self.assertEqual(record["error_category"], expected_category)

    def test_fallback_disabled_emits_deny_record(self):
        """--no-service-identity-fallback rejection is audited as outcome=deny."""
        server = GravitinoMCPServer(
            Setting(
                "mock_metalake",
                transport="http",
                token="service-token",
                no_service_identity_fallback=True,
            )
        )
        mock_request = MagicMock()
        mock_request.headers.get.return_value = ""

        async def _run():
            with patch(
                "fastmcp.server.dependencies.get_http_request",
                return_value=mock_request,
            ):
                async with Client(server.mcp) as client:
                    await client.call_tool(
                        "get_list_of_catalogs", raise_on_error=False
                    )

        asyncio.run(_run())

        self.assertEqual(len(self.log_records), 1)
        record = json.loads(self.log_records[0])
        self.assertEqual(record["outcome"], "deny")
        self.assertEqual(
            record["error_type"], "ServiceIdentityFallbackDisabled"
        )
        self.assertEqual(record["error_category"], "unauthorized")

    def test_write_and_delete_tools_record_target_object_on_allow_and_deny(
        self,
    ):
        """Write/delete audit records include target_type and target_name."""

        async def _run_allow():
            async with Client(self.mcp) as client:
                await client.call_tool(
                    "drop_schema",
                    {
                        "catalog_name": "mcpcat",
                        "schema_name": "alice_s",
                        "metalake": "authz",
                    },
                )
                await client.call_tool(
                    "drop_catalog",
                    {"catalog_name": "mcpcat"},
                )

        asyncio.run(_run_allow())

        schema_record = json.loads(self.log_records[0])
        self.assertEqual(schema_record["outcome"], "allow")
        self.assertEqual(schema_record["metalake"], "authz")
        self.assertEqual(schema_record["target_type"], "schema")
        self.assertEqual(schema_record["target_name"], "authz.mcpcat.alice_s")

        catalog_record = json.loads(self.log_records[1])
        self.assertEqual(catalog_record["outcome"], "allow")
        self.assertEqual(catalog_record["target_type"], "catalog")
        self.assertEqual(catalog_record["target_name"], "mock_metalake.mcpcat")

        # Denied drop_table must still carry its target object.
        self.log_records.clear()

        class _DeniedTableOp:
            async def drop_table(self, *_args, **_kwargs):
                raise GravitinoException(
                    "Forbidden",
                    status_code=403,
                    error_code=1008,
                    error_type="ForbiddenException",
                )

        class DeniedOperation(MockOperation):
            def as_table_operation(self):
                return _DeniedTableOp()

        RESTClientFactory.set_rest_client(DeniedOperation)
        denied_server = GravitinoMCPServer(Setting("authz"))

        async def _run_deny():
            async with Client(denied_server.mcp) as client:
                await client.call_tool(
                    "drop_table",
                    {
                        "catalog_name": "mcpcat",
                        "schema_name": "alice_s",
                        "table_name": "orders",
                    },
                    raise_on_error=False,
                )

        asyncio.run(_run_deny())

        denied_record = json.loads(self.log_records[0])
        self.assertEqual(denied_record["outcome"], "deny")
        self.assertEqual(denied_record["error_type"], "ForbiddenException")
        self.assertEqual(denied_record["target_type"], "table")
        self.assertEqual(
            denied_record["target_name"], "authz.mcpcat.alice_s.orders"
        )

    def test_readonly_tool_omits_target_fields(self):
        """Read-only calls do not emit target_type or target_name."""

        async def _run():
            async with Client(self.mcp) as client:
                await client.call_tool("get_list_of_catalogs")

        asyncio.run(_run())

        record = json.loads(self.log_records[0])
        self.assertNotIn("target_type", record)
        self.assertNotIn("target_name", record)


class TestExtractWriteTarget(unittest.TestCase):
    """Unit tests for audit.extract_write_target() and write-tool coverage."""

    def test_extracts_hierarchical_and_special_targets(self):
        self.assertEqual(
            audit.extract_write_target(
                "link_model_version",
                {"catalog_name": "c", "schema_name": "s", "model_name": "m"},
                "ml",
            ),
            ("model", "ml.c.s.m"),
        )
        self.assertEqual(
            audit.extract_write_target(
                "create_table",
                {"catalog_name": "c", "schema_name": "s", "name": "t"},
                "ml",
            ),
            ("table", "ml.c.s.t"),
        )
        self.assertEqual(
            audit.extract_write_target(
                "alter_model_version",
                {
                    "catalog_name": "c",
                    "schema_name": "s",
                    "model_name": "m",
                    "version": 0,
                },
                "ml",
            ),
            ("model_version", "ml.c.s.m.0"),
        )
        self.assertEqual(
            audit.extract_write_target(
                "associate_tag_with_metadata",
                {
                    "metadata_type": "TABLE",
                    "metadata_full_name": "c.s.t",
                    "tags_to_associate": ["pii"],
                },
                "ml",
            ),
            ("table", "ml.c.s.t"),
        )
        self.assertEqual(
            audit.extract_write_target(
                "associate_tag_with_metadata",
                {
                    "metadata_type": "metalake",
                    "metadata_full_name": "ml",
                    "tags_to_associate": ["pii"],
                },
                "ml",
            ),
            ("metalake", "ml"),
        )
        self.assertEqual(
            audit.extract_write_target(
                "cancel_job", {"job_id": "job-42"}, "ml"
            ),
            ("job", "job-42"),
        )
        self.assertEqual(
            audit.extract_write_target(
                "drop_schema", {"catalog_name": "c", "schema_name": "s"}, ""
            ),
            ("", ""),
        )

    def test_missing_or_invalid_arguments_return_empty_target(self):
        self.assertEqual(
            audit.extract_write_target(
                "drop_table", {"catalog_name": "c"}, "ml"
            ),
            ("", ""),
        )
        self.assertEqual(
            audit.extract_write_target(
                "alter_model_version",
                {
                    "catalog_name": "c",
                    "schema_name": "s",
                    "model_name": "m",
                    "version": 1.5,
                },
                "ml",
            ),
            ("", ""),
        )
        self.assertEqual(
            audit.extract_write_target("drop_catalog", None, "ml"), ("", "")
        )
        self.assertEqual(
            audit.extract_write_target("get_list_of_catalogs", {}, "ml"),
            ("", ""),
        )

    def test_every_mutating_registered_tool_has_a_write_target_spec(self):
        """Keep WRITE_TARGET_SPECS synchronized with the registered MCP tools."""
        RESTClientFactory.set_rest_client(MockOperation)
        try:
            server = GravitinoMCPServer(Setting("ml"))
            tools = asyncio.run(server.mcp.list_tools())
        finally:
            RESTClientFactory.set_rest_client(PlainRESTClientOperation)

        registered_names = {tool.name for tool in tools}
        # Every configured spec must name an actual registered tool.
        self.assertLessEqual(
            set(audit.WRITE_TARGET_SPECS.keys()), registered_names
        )

        readonly_prefixes = ("get_", "list_", "load_", "metadata_type_")
        mutating_tools = {
            name
            for name in registered_names
            if not name.startswith(readonly_prefixes)
        }
        self.assertEqual(mutating_tools, set(audit.WRITE_TARGET_SPECS.keys()))


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


class _CapturingHandler(logging.Handler):
    """Logging handler that stores formatted messages in a list."""

    def __init__(self, records: list):
        super().__init__()
        self._records = records

    def emit(self, record: logging.LogRecord) -> None:
        self._records.append(self.format(record))


class _FailingCatalogOperation:
    def __init__(self, exc: Exception):
        self._exc = exc

    async def get_list_of_catalogs(self) -> str:
        raise self._exc


def _jwt_for(subject: str, signature: bytes = b"signature") -> str:
    parts = (
        json.dumps({"alg": "RS256", "typ": "JWT"}).encode(),
        json.dumps({"sub": subject}).encode(),
        signature,
    )
    return ".".join(
        base64.urlsafe_b64encode(part).decode().rstrip("=") for part in parts
    )