|
22 | 22 | GlobalContext, |
23 | 23 | Plugin, |
24 | 24 | PluginConfig, |
| 25 | + PluginContext, |
25 | 26 | PluginManager, |
26 | 27 | PluginMode, |
27 | 28 | PluginResult, |
28 | 29 | PromptHookType, |
29 | 30 | PromptPrehookPayload, |
| 31 | + PromptPrehookResult, |
30 | 32 | ) |
31 | 33 | from mcpgateway.plugins.framework.base import HookRef |
32 | 34 | from mcpgateway.plugins.framework.manager import PluginExecutor |
@@ -381,9 +383,206 @@ def record_span(name: str, attributes: Optional[Dict[str, Any]] = None): |
381 | 383 | plugin_span = recorded[1] |
382 | 384 | assert hook_chain_span.name == "plugin.hook.invoke" |
383 | 385 | assert hook_chain_span.attributes["plugin.chain.stopped"] is True |
384 | | - assert hook_chain_span.attributes["plugin.chain.stopped_by"] == "BlockingPlugin" |
385 | | - assert plugin_span.name == "plugin.execute" |
386 | | - assert plugin_span.attributes["plugin.name"] == "BlockingPlugin" |
| 386 | + |
| 387 | + |
| 388 | +@pytest.mark.asyncio |
| 389 | +async def test_plugin_manager_captures_violation_details_in_otel_spans(): |
| 390 | + """Plugin manager should capture detailed violation information in OTEL spans with proper sanitization.""" |
| 391 | + manager = PluginManager("./tests/unit/mcpgateway/plugins/fixtures/configs/valid_no_plugin.yaml", observability=None) |
| 392 | + await manager.initialize() |
| 393 | + |
| 394 | + # Create a plugin that returns a violation with full details |
| 395 | + config = PluginConfig( |
| 396 | + name="ViolationPlugin", |
| 397 | + description="Plugin that returns violations", |
| 398 | + author="Test", |
| 399 | + version="1.0", |
| 400 | + tags=["test"], |
| 401 | + kind="ViolationPlugin", |
| 402 | + hooks=["prompt_pre_fetch"], |
| 403 | + config={}, |
| 404 | + mode=PluginMode.ENFORCE, |
| 405 | + ) |
| 406 | + |
| 407 | + class ViolationPlugin(Plugin): |
| 408 | + async def prompt_pre_fetch(self, payload: PromptPrehookPayload, context: PluginContext) -> PromptPrehookResult: |
| 409 | + from mcpgateway.plugins.framework import PluginViolation |
| 410 | + |
| 411 | + violation = PluginViolation( |
| 412 | + reason="Content policy violation", |
| 413 | + description="Request contains prohibited content", |
| 414 | + code="PROHIBITED_CONTENT", |
| 415 | + details={ |
| 416 | + "matched_pattern": "sensitive_keyword", |
| 417 | + "field": "user_input", |
| 418 | + "password": "secret123", # Should be sanitized |
| 419 | + "api_key": "sk-test-key", # Should be sanitized |
| 420 | + }, |
| 421 | + http_status_code=403, |
| 422 | + mcp_error_code=-32001, |
| 423 | + ) |
| 424 | + return PromptPrehookResult(continue_processing=False, violation=violation) |
| 425 | + |
| 426 | + plugin = ViolationPlugin(config) |
| 427 | + |
| 428 | + class RecordingSpan: |
| 429 | + def __init__(self, name: str, attributes: Optional[Dict[str, Any]] = None): |
| 430 | + self.name = name |
| 431 | + self.attributes = dict(attributes or {}) |
| 432 | + self.status = None |
| 433 | + self.status_description = None |
| 434 | + |
| 435 | + def set_attribute(self, key: str, value: Any) -> None: |
| 436 | + self.attributes[key] = value |
| 437 | + |
| 438 | + def set_status(self, status: Any) -> None: |
| 439 | + self.status = status |
| 440 | + if hasattr(status, "description"): |
| 441 | + self.status_description = status.description |
| 442 | + |
| 443 | + recorded: List[RecordingSpan] = [] |
| 444 | + |
| 445 | + @contextmanager |
| 446 | + def record_span(name: str, attributes: Optional[Dict[str, Any]] = None): |
| 447 | + span = RecordingSpan(name, attributes) |
| 448 | + recorded.append(span) |
| 449 | + yield span |
| 450 | + |
| 451 | + with patch.object(manager._registry, "get_hook_refs_for_hook") as mock_get: |
| 452 | + hook_ref = HookRef(PromptHookType.PROMPT_PRE_FETCH, PluginRef(plugin)) |
| 453 | + mock_get.return_value = [hook_ref] |
| 454 | + |
| 455 | + payload = PromptPrehookPayload(prompt_id="test", args={"user": "test input"}) |
| 456 | + global_context = GlobalContext(request_id="req-violation-test") |
| 457 | + |
| 458 | + with patch("mcpgateway.plugins.framework.manager.create_span", side_effect=record_span): |
| 459 | + result, _ = await manager.invoke_hook( |
| 460 | + PromptHookType.PROMPT_PRE_FETCH, |
| 461 | + payload, |
| 462 | + global_context=global_context, |
| 463 | + ) |
| 464 | + |
| 465 | + # Verify violation was returned |
| 466 | + assert result.continue_processing is False |
| 467 | + assert result.violation is not None |
| 468 | + |
| 469 | + # Find the plugin execution span |
| 470 | + plugin_span = next((s for s in recorded if s.name == "plugin.execute"), None) |
| 471 | + assert plugin_span is not None |
| 472 | + |
| 473 | + # Verify core violation attributes are captured |
| 474 | + assert plugin_span.attributes["plugin.had_violation"] is True |
| 475 | + assert plugin_span.attributes["plugin.violation.reason"] == "Content policy violation" |
| 476 | + assert plugin_span.attributes["plugin.violation.code"] == "PROHIBITED_CONTENT" |
| 477 | + assert plugin_span.attributes["plugin.violation.description"] == "Request contains prohibited content" |
| 478 | + assert plugin_span.attributes["plugin.violation.http_status_code"] == 403 |
| 479 | + assert plugin_span.attributes["plugin.violation.mcp_error_code"] == -32001 |
| 480 | + |
| 481 | + # Verify violation details are captured |
| 482 | + assert "plugin.violation.details.matched_pattern" in plugin_span.attributes |
| 483 | + assert plugin_span.attributes["plugin.violation.details.matched_pattern"] == "sensitive_keyword" |
| 484 | + assert "plugin.violation.details.field" in plugin_span.attributes |
| 485 | + assert plugin_span.attributes["plugin.violation.details.field"] == "user_input" |
| 486 | + |
| 487 | + # Verify sensitive fields are sanitized (password and api_key should be redacted) |
| 488 | + assert "plugin.violation.details.password" in plugin_span.attributes |
| 489 | + assert plugin_span.attributes["plugin.violation.details.password"] == "***" |
| 490 | + assert "plugin.violation.details.api_key" in plugin_span.attributes |
| 491 | + assert plugin_span.attributes["plugin.violation.details.api_key"] == "***" |
| 492 | + |
| 493 | + # Verify span is marked as error |
| 494 | + assert plugin_span.status is not None |
| 495 | + assert plugin_span.status_description == "Request contains prohibited content" |
| 496 | + |
| 497 | + await manager.shutdown() |
| 498 | + |
| 499 | + |
| 500 | +@pytest.mark.asyncio |
| 501 | +async def test_plugin_manager_handles_violation_without_optional_fields(): |
| 502 | + """Plugin manager should handle violations that don't have optional fields (http_status_code, mcp_error_code, details).""" |
| 503 | + manager = PluginManager("./tests/unit/mcpgateway/plugins/fixtures/configs/valid_no_plugin.yaml", observability=None) |
| 504 | + await manager.initialize() |
| 505 | + |
| 506 | + config = PluginConfig( |
| 507 | + name="MinimalViolationPlugin", |
| 508 | + description="Plugin with minimal violation", |
| 509 | + author="Test", |
| 510 | + version="1.0", |
| 511 | + tags=["test"], |
| 512 | + kind="MinimalViolationPlugin", |
| 513 | + hooks=["prompt_pre_fetch"], |
| 514 | + config={}, |
| 515 | + mode=PluginMode.ENFORCE, |
| 516 | + ) |
| 517 | + |
| 518 | + class MinimalViolationPlugin(Plugin): |
| 519 | + async def prompt_pre_fetch(self, payload: PromptPrehookPayload, context: PluginContext) -> PromptPrehookResult: |
| 520 | + from mcpgateway.plugins.framework import PluginViolation |
| 521 | + |
| 522 | + # Violation with only required fields |
| 523 | + violation = PluginViolation( |
| 524 | + reason="Rate limit exceeded", |
| 525 | + description="Too many requests", |
| 526 | + code="RATE_LIMIT", |
| 527 | + ) |
| 528 | + return PromptPrehookResult(continue_processing=False, violation=violation) |
| 529 | + |
| 530 | + plugin = MinimalViolationPlugin(config) |
| 531 | + |
| 532 | + class RecordingSpan: |
| 533 | + def __init__(self, name: str, attributes: Optional[Dict[str, Any]] = None): |
| 534 | + self.name = name |
| 535 | + self.attributes = dict(attributes or {}) |
| 536 | + |
| 537 | + def set_attribute(self, key: str, value: Any) -> None: |
| 538 | + self.attributes[key] = value |
| 539 | + |
| 540 | + def set_status(self, status: Any) -> None: |
| 541 | + pass |
| 542 | + |
| 543 | + recorded: List[RecordingSpan] = [] |
| 544 | + |
| 545 | + @contextmanager |
| 546 | + def record_span(name: str, attributes: Optional[Dict[str, Any]] = None): |
| 547 | + span = RecordingSpan(name, attributes) |
| 548 | + recorded.append(span) |
| 549 | + yield span |
| 550 | + |
| 551 | + with patch.object(manager._registry, "get_hook_refs_for_hook") as mock_get: |
| 552 | + hook_ref = HookRef(PromptHookType.PROMPT_PRE_FETCH, PluginRef(plugin)) |
| 553 | + mock_get.return_value = [hook_ref] |
| 554 | + |
| 555 | + payload = PromptPrehookPayload(prompt_id="test", args={}) |
| 556 | + global_context = GlobalContext(request_id="req-minimal-violation") |
| 557 | + |
| 558 | + with patch("mcpgateway.plugins.framework.manager.create_span", side_effect=record_span): |
| 559 | + result, _ = await manager.invoke_hook( |
| 560 | + PromptHookType.PROMPT_PRE_FETCH, |
| 561 | + payload, |
| 562 | + global_context=global_context, |
| 563 | + ) |
| 564 | + |
| 565 | + # Verify violation was returned |
| 566 | + assert result.continue_processing is False |
| 567 | + assert result.violation is not None |
| 568 | + |
| 569 | + # Find the plugin execution span |
| 570 | + plugin_span = next((s for s in recorded if s.name == "plugin.execute"), None) |
| 571 | + assert plugin_span is not None |
| 572 | + |
| 573 | + # Verify core violation attributes are captured |
| 574 | + assert plugin_span.attributes["plugin.had_violation"] is True |
| 575 | + assert plugin_span.attributes["plugin.violation.reason"] == "Rate limit exceeded" |
| 576 | + assert plugin_span.attributes["plugin.violation.code"] == "RATE_LIMIT" |
| 577 | + assert plugin_span.attributes["plugin.violation.description"] == "Too many requests" |
| 578 | + |
| 579 | + # Verify optional fields are not present when not set |
| 580 | + assert "plugin.violation.http_status_code" not in plugin_span.attributes |
| 581 | + assert "plugin.violation.mcp_error_code" not in plugin_span.attributes |
| 582 | + # Details dict is empty, so no detail attributes should be present |
| 583 | + assert not any(k.startswith("plugin.violation.details.") for k in plugin_span.attributes.keys()) |
| 584 | + |
| 585 | + await manager.shutdown() |
387 | 586 |
|
388 | 587 | await manager.shutdown() |
389 | 588 |
|
|
0 commit comments