Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /dislovelhl_enhanced-agent-bus /bus /validation.py
| """ | |
| Message validation helpers for EnhancedAgentBus. | |
| Constitutional Hash: 608508a9bd224290 | |
| """ | |
| from __future__ import annotations | |
| from datetime import UTC, datetime | |
| from typing import TYPE_CHECKING, Any | |
| if TYPE_CHECKING: | |
| from enhanced_agent_bus._compat.types import JSONDict | |
| else: | |
| try: | |
| from enhanced_agent_bus._compat.types import JSONDict as _JSONDict | |
| except ImportError: | |
| _JSONDict = dict[str, Any] | |
| JSONDict = _JSONDict | |
| from enhanced_agent_bus.observability.structured_logging import get_logger | |
| if TYPE_CHECKING: | |
| from ..components import GovernanceValidator | |
| from enhanced_agent_bus.models import AgentMessage | |
| from enhanced_agent_bus.validators import ValidationResult | |
| from ..security.tenant_validator import TenantValidator | |
| from ..security_helpers import normalize_tenant_id, validate_tenant_consistency | |
| logger = get_logger(__name__) | |
| # Mock detection helper - avoids importing unittest.mock in production | |
| def _is_mock_instance(obj: object) -> bool: | |
| """Check if an object is a mock instance without importing unittest.mock.""" | |
| return hasattr(obj, "_mock_name") or type(obj).__name__ in ( | |
| "MagicMock", | |
| "Mock", | |
| "AsyncMock", | |
| ) | |
| class MessageValidator: | |
| """ | |
| Validates messages for constitutional compliance and tenant isolation. | |
| Constitutional Hash: 608508a9bd224290 | |
| """ | |
| def __init__( | |
| self, | |
| governance: GovernanceValidator, | |
| agents: JSONDict, | |
| metrics: JSONDict, | |
| ) -> None: | |
| """ | |
| Initialize the message validator. | |
| Args: | |
| governance: GovernanceValidator component for constitutional checks. | |
| agents: Dict of registered agents for tenant validation. | |
| metrics: Metrics dict reference for recording failures/successes. | |
| """ | |
| self._governance = governance | |
| self._agents = agents | |
| self._metrics = metrics | |
| def record_metrics_failure(self) -> None: | |
| """ | |
| Record failure metrics atomically for message processing. | |
| Increments both 'messages_failed' and 'failed' counters in the internal | |
| metrics dictionary. This method is called when message validation, | |
| tenant verification, or constitutional hash checks fail. | |
| Thread Safety: | |
| This method modifies shared state. In high-concurrency scenarios, | |
| consider using atomic operations or locks if precise counts are | |
| required for billing/audit purposes. | |
| Constitutional Hash: 608508a9bd224290 | |
| """ | |
| self._metrics["messages_failed"] += 1 | |
| self._metrics["failed"] += 1 | |
| def record_metrics_success(self) -> None: | |
| """ | |
| Record success metrics atomically for message processing. | |
| Increments both 'sent' and 'messages_sent' counters in the internal | |
| metrics dictionary. This method is called after successful message | |
| validation and delivery. | |
| Thread Safety: | |
| This method modifies shared state. In high-concurrency scenarios, | |
| consider using atomic operations or locks if precise counts are | |
| required for billing/audit purposes. | |
| Constitutional Hash: 608508a9bd224290 | |
| """ | |
| self._metrics["sent"] += 1 | |
| self._metrics["messages_sent"] += 1 | |
| def validate_constitutional_hash_for_message( | |
| self, msg: AgentMessage, result: ValidationResult | |
| ) -> bool: | |
| """ | |
| Validate message constitutional hash via governance component. | |
| Ensures the message's constitutional hash matches the expected system | |
| hash (608508a9bd224290). This is a critical security check that prevents | |
| unauthorized governance policy modifications or bypass attempts. | |
| Args: | |
| msg: The AgentMessage to validate. Must contain a constitutional_hash | |
| field that will be compared against the system hash. | |
| result: ValidationResult object where errors will be recorded if | |
| validation fails. | |
| Returns: | |
| bool: True if the constitutional hash is valid, False otherwise. | |
| On failure, the result object will contain specific error details. | |
| Side Effects: | |
| - Records failure metrics if validation fails | |
| - Increments sent counter for tracking total attempts | |
| Constitutional Hash: 608508a9bd224290 | |
| """ | |
| valid = bool(self._governance.validate_constitutional_hash(msg, result)) | |
| if not valid: | |
| self.record_metrics_failure() | |
| self._metrics["sent"] += 1 | |
| return bool(valid) | |
| def validate_message_shape(self, msg: AgentMessage, result: ValidationResult) -> bool: | |
| """Reject structurally invalid or expired messages before processing.""" | |
| if not getattr(msg, "from_agent", ""): | |
| result.add_error("Message from_agent is required") | |
| if not getattr(msg, "to_agent", ""): | |
| result.add_error("Message to_agent is required") | |
| content = getattr(msg, "content", None) | |
| if not isinstance(content, dict) or not content: | |
| result.add_error("Message content must be a non-empty dictionary") | |
| expires_at = getattr(msg, "expires_at", None) | |
| if expires_at is not None and expires_at <= datetime.now(UTC): | |
| result.add_error("Message has expired") | |
| if result.errors: | |
| self.record_metrics_failure() | |
| return False | |
| return True | |
| def validate_and_normalize_tenant(self, msg: AgentMessage, result: ValidationResult) -> bool: | |
| """ | |
| Normalize and validate tenant ID for multi-tenant message isolation. | |
| Performs three-stage tenant validation: | |
| 1. Normalizes the tenant ID format (handles None, empty, whitespace) | |
| 2. Validates tenant ID against security patterns (TenantValidator) | |
| 3. Checks cross-tenant consistency between sender and receiver agents | |
| Args: | |
| msg: The AgentMessage to validate. The tenant_id field will be | |
| modified in-place to the normalized value. | |
| result: ValidationResult object where errors will be recorded if | |
| validation fails. | |
| Returns: | |
| bool: True if tenant validation passes, False otherwise. | |
| On failure, result.errors will contain specific violation details. | |
| Side Effects: | |
| - Modifies msg.tenant_id in-place with normalized value | |
| - Sets tenant_id to "default" if None after normalization | |
| - Records failure metrics on validation errors | |
| Raises: | |
| No exceptions are raised; errors are recorded in the result object. | |
| Security: | |
| Prevents cross-tenant data leakage by ensuring agents can only | |
| communicate within their tenant boundary. | |
| Constitutional Hash: 608508a9bd224290 | |
| """ | |
| msg.tenant_id = normalize_tenant_id(msg.tenant_id) or "default" | |
| if msg.tenant_id and not TenantValidator.validate(msg.tenant_id): | |
| result.add_error(f"Invalid tenant_id format: {msg.tenant_id}") | |
| self.record_metrics_failure() | |
| self._metrics["sent"] += 1 | |
| return False | |
| # Use registry manager's agents for consistency check | |
| errors = validate_tenant_consistency( | |
| self._agents, msg.from_agent, msg.to_agent, msg.tenant_id | |
| ) | |
| if errors: | |
| for error in errors: | |
| result.add_error(error) | |
| self.record_metrics_failure() | |
| return False | |
| return True | |
Xet Storage Details
- Size:
- 7.61 kB
- Xet hash:
- 3c9936ec3345ca1ee7f9cca4bc07391aa966e3dc624a58e5ab4c99582b1dbd4a
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.