Spaces:
Sleeping
Sleeping
svkrishna commited on
Commit ·
7b7b417
1
Parent(s): 78b489c
🤖 Implement Story 4: Reflexive Core
Browse files- Add ReflexiveEngine for self-monitoring and corrective actions
- Implement PolicyMonitor, LedgerMonitor, and AnomalyDetector
- Add HaltAction, EscalateAction, MonitorAction, and AllowAction
- Create ActionFactory and ActionExecutor for action management
- Add HTTP API endpoints for risk simulation and engine status
- Integrate ReflexiveEngine into FastMCP server
- Add comprehensive test suite with 70 passing tests
- Support halt(), escalate(), monitor(), and allow() decisions
- Record reflexive events with cryptographic proof hashes
- Enable automatic risk assessment and corrective actions
Closes: Story 4 - Reflexive Core implementation
Files changed (12)
- examples/reflexive_example.pyAdded+191
- src/fastmcp/reflexive/__init__.pyAdded+19
- src/fastmcp/reflexive/actions.pyAdded+340
- src/fastmcp/reflexive/engine.pyAdded+376
- src/fastmcp/reflexive/monitor.pyAdded+356
- src/fastmcp/server/reflexive_routes.pyAdded+385
- src/fastmcp/server/server.py+38
- tests/reflexive/__init__.pyAdded+1
- tests/reflexive/test_actions.pyAdded+461
- tests/reflexive/test_monitors.pyAdded+428
- tests/reflexive/test_reflexive_engine.pyAdded+320
- tests/reflexive/test_reflexive_http.pyAdded+325
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191"""Example usage of the Reflexive Core."""
import asynciofrom datetime import datetime
from fastmcp import FastMCPfrom fastmcp.reflexive import ReflexiveEngine, ActionContext, DecisionType, RiskLevelfrom fastmcp.reflexive.monitor import PolicyMonitor, LedgerMonitor, AnomalyDetectorfrom fastmcp.reflexive.actions import ActionFactory, ActionExecutor
async def main(): """Demonstrate reflexive core functionality.""" print("🚀 Reflexive Core Example") print("=" * 50) # Create a FastMCP server with reflexive core server = FastMCP("ReflexiveExampleServer") # Enable the reflexive core reflexive_engine = server.enable_reflexive_core() # Add monitors policy_monitor = PolicyMonitor() ledger_monitor = LedgerMonitor() anomaly_detector = AnomalyDetector() reflexive_engine.add_monitor(policy_monitor) reflexive_engine.add_monitor(ledger_monitor) reflexive_engine.add_monitor(anomaly_detector) print(f"✅ Reflexive core enabled with {len(reflexive_engine.monitors)} monitors") # Start the reflexive engine await reflexive_engine.start() print("✅ Reflexive engine started") # Create action executor action_executor = ActionExecutor() # Example 1: Normal action (should be allowed) print("\n📋 Example 1: Normal Action") print("-" * 30) normal_action = ActionContext( action_id="normal_action_001", actor_id="authorized_user", action_type="data_read", resource_id="public_data", metadata={"authorized": True} ) decision = await reflexive_engine._evaluate_action(normal_action) print(f"Decision: {decision.decision_type}") print(f"Risk Level: {decision.risk_level}") print(f"Reason: {decision.reason}") # Execute the action action = ActionFactory.create_action(decision) result = await action_executor.execute_action(action) print(f"Action Result: {action.get_action_type()} - {result.get('allowed', 'N/A')}") # Example 2: Policy violation (should be halted) print("\n🚨 Example 2: Policy Violation") print("-" * 30) violation_action = ActionContext( action_id="violation_action_002", actor_id="guest_user", action_type="admin_access", resource_id="admin_panel", metadata={"authorized": False} ) decision = await reflexive_engine._evaluate_action(violation_action) print(f"Decision: {decision.decision_type}") print(f"Risk Level: {decision.risk_level}") print(f"Reason: {decision.reason}") # Execute the action action = ActionFactory.create_action(decision) result = await action_executor.execute_action(action) print(f"Action Result: {action.get_action_type()}") print(f"Halted Operations: {result.get('halted_operations', [])}") # Example 3: Anomaly detection (should be escalated) print("\n⚠️ Example 3: Anomaly Detection") print("-" * 30) # Simulate multiple rapid actions to trigger anomaly for i in range(25): rapid_action = ActionContext( action_id=f"rapid_action_{i:03d}", actor_id="suspicious_user", action_type="api_call", resource_id="api_endpoint" ) anomaly_detector._update_patterns(rapid_action) # Now test the anomaly detection anomaly_action = ActionContext( action_id="anomaly_action_003", actor_id="suspicious_user", action_type="api_call", resource_id="api_endpoint" ) decision = await reflexive_engine._evaluate_action(anomaly_action) print(f"Decision: {decision.decision_type}") print(f"Risk Level: {decision.risk_level}") print(f"Reason: {decision.reason}") # Execute the action action = ActionFactory.create_action(decision) result = await action_executor.execute_action(action) print(f"Action Result: {action.get_action_type()}") print(f"Escalation Target: {result.get('escalation_target', 'N/A')}") # Example 4: Risk simulation print("\n🎯 Example 4: Risk Simulation") print("-" * 30) risk_scenario = { "action_context": { "action_id": "simulation_action", "actor_id": "test_actor", "action_type": "privilege_escalation", "resource_id": "root_access", "metadata": {"escalation_attempt": True} }, "monitors": [ lambda ctx: { "type": "violation", "severity": "critical", "violations": [{ "rule": "privilege_escalation", "message": "Unauthorized privilege escalation attempt", "severity": "critical" }] } ] } decision = await reflexive_engine.simulate_risk(risk_scenario) print(f"Simulation Decision: {decision.decision_type}") print(f"Simulation Risk Level: {decision.risk_level}") print(f"Simulation Reason: {decision.reason}") # Example 5: Monitor statistics print("\n📊 Example 5: Monitor Statistics") print("-" * 30) policy_stats = policy_monitor.get_violation_stats() ledger_stats = ledger_monitor.get_integrity_stats() anomaly_stats = anomaly_detector.get_anomaly_stats() print(f"Policy Monitor - Total Violations: {policy_stats['total_violations']}") print(f"Policy Monitor - Actor Violations: {policy_stats['actor_violations']}") print(f"Ledger Monitor - Total Checks: {ledger_stats['total_checks']}") print(f"Anomaly Detector - Tracked Actors: {anomaly_stats['tracked_actors']}") # Example 6: Engine status print("\n🔧 Example 6: Engine Status") print("-" * 30) status = reflexive_engine.get_engine_status() print(f"Engine Running: {status['is_running']}") print(f"Monitor Count: {status['monitor_count']}") print(f"Queue Size: {status['queue_size']}") print(f"Decision Handlers: {status['decision_handlers']}") # Example 7: Action execution statistics print("\n📈 Example 7: Action Execution Statistics") print("-" * 30) exec_stats = action_executor.get_execution_stats() print(f"Total Actions: {exec_stats['total_actions']}") print(f"Completed Actions: {exec_stats['completed_actions']}") print(f"Failed Actions: {exec_stats['failed_actions']}") print(f"Success Rate: {exec_stats['success_rate']:.2%}") # Stop the reflexive engine await reflexive_engine.stop() print("\n✅ Reflexive engine stopped") print("\n🎉 Reflexive Core Example Complete!") print("=" * 50)
if __name__ == "__main__": asyncio.run(main())12345678910111213141516171819"""FastMCP Reflexive Core - Self-monitoring and corrective action system."""
from .engine import ReflexiveEngine, ReflexiveDecision, DecisionType, RiskLevel, ActionContextfrom .monitor import PolicyMonitor, LedgerMonitor, AnomalyDetectorfrom .actions import HaltAction, EscalateAction, ReflexiveAction
__all__ = [ "ReflexiveEngine", "ReflexiveDecision", "DecisionType", "RiskLevel", "ActionContext", "PolicyMonitor", "LedgerMonitor", "AnomalyDetector", "HaltAction", "EscalateAction", "ReflexiveAction"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340"""Action components for the reflexive core."""
from abc import ABC, abstractmethodfrom datetime import datetimefrom typing import Any, Dict, List, Optionalfrom uuid import UUID, uuid4
from pydantic import BaseModel, Field
from .engine import ReflexiveDecision, ActionContextfrom fastmcp.utilities.logging import get_logger
logger = get_logger(__name__)
class ReflexiveAction(BaseModel, ABC): """Base class for reflexive actions.""" action_id: UUID = Field(default_factory=uuid4, description="Unique action identifier") decision: ReflexiveDecision = Field(..., description="The decision that triggered this action") timestamp: datetime = Field(default_factory=datetime.utcnow, description="When the action was created") status: str = Field(default="pending", description="Action status") result: Optional[Dict[str, Any]] = Field(default=None, description="Action result") @abstractmethod async def execute(self) -> Dict[str, Any]: """Execute the reflexive action.""" pass @abstractmethod def get_action_type(self) -> str: """Get the type of this action.""" pass
class HaltAction(ReflexiveAction): """Action to halt unsafe execution.""" halt_reason: str = Field(..., description="Reason for halting") halt_level: str = Field(default="immediate", description="Level of halt (immediate, graceful, etc.)") affected_operations: List[str] = Field(default_factory=list, description="Operations affected by the halt") async def execute(self) -> Dict[str, Any]: """Execute the halt action.""" try: self.status = "executing" # Log the halt logger.critical(f"HALTING OPERATIONS: {self.halt_reason}") logger.critical(f"Affected operations: {self.affected_operations}") logger.critical(f"Decision ID: {self.decision.decision_id}") # In a real implementation, this would: # 1. Stop the current operation # 2. Cancel pending operations # 3. Notify relevant systems # 4. Update system state # Simulate halt execution halt_result = { "halted_operations": self.affected_operations, "halt_timestamp": self.timestamp.isoformat(), "halt_reason": self.halt_reason, "halt_level": self.halt_level, "decision_id": str(self.decision.decision_id) } self.result = halt_result self.status = "completed" logger.info(f"Halt action completed: {self.action_id}") return halt_result except Exception as e: self.status = "failed" self.result = {"error": str(e)} logger.error(f"Halt action failed: {e}") raise def get_action_type(self) -> str: """Get the type of this action.""" return "halt"
class EscalateAction(ReflexiveAction): """Action to escalate an issue to higher authority.""" escalation_target: str = Field(..., description="Target role/entity for escalation") escalation_priority: str = Field(default="normal", description="Priority of the escalation") escalation_context: Dict[str, Any] = Field(default_factory=dict, description="Additional context for escalation") notification_channels: List[str] = Field(default_factory=list, description="Channels to use for notification") async def execute(self) -> Dict[str, Any]: """Execute the escalation action.""" try: self.status = "executing" # Log the escalation logger.warning(f"ESCALATING TO {self.escalation_target}: {self.decision.reason}") logger.warning(f"Priority: {self.escalation_priority}") logger.warning(f"Decision ID: {self.decision.decision_id}") # In a real implementation, this would: # 1. Create escalation ticket/alert # 2. Send notifications via configured channels # 3. Update escalation tracking # 4. Set up monitoring for response # Simulate escalation execution escalation_result = { "escalation_target": self.escalation_target, "escalation_priority": self.escalation_priority, "escalation_timestamp": self.timestamp.isoformat(), "escalation_context": self.escalation_context, "notification_channels": self.notification_channels, "decision_id": str(self.decision.decision_id), "action_context": self.decision.action_context.model_dump(mode='json') } self.result = escalation_result self.status = "completed" logger.info(f"Escalation action completed: {self.action_id}") return escalation_result except Exception as e: self.status = "failed" self.result = {"error": str(e)} logger.error(f"Escalation action failed: {e}") raise def get_action_type(self) -> str: """Get the type of this action.""" return "escalate"
class MonitorAction(ReflexiveAction): """Action to increase monitoring for an operation.""" monitoring_level: str = Field(default="enhanced", description="Level of monitoring to apply") monitoring_duration: int = Field(default=3600, description="Duration of enhanced monitoring in seconds") monitoring_scope: List[str] = Field(default_factory=list, description="Scope of monitoring") async def execute(self) -> Dict[str, Any]: """Execute the monitoring action.""" try: self.status = "executing" # Log the monitoring increase logger.info(f"ENHANCING MONITORING: {self.decision.reason}") logger.info(f"Monitoring level: {self.monitoring_level}") logger.info(f"Duration: {self.monitoring_duration} seconds") # In a real implementation, this would: # 1. Increase logging verbosity # 2. Add additional monitoring points # 3. Set up alerts for specific conditions # 4. Schedule monitoring reduction after duration # Simulate monitoring execution monitoring_result = { "monitoring_level": self.monitoring_level, "monitoring_duration": self.monitoring_duration, "monitoring_scope": self.monitoring_scope, "monitoring_timestamp": self.timestamp.isoformat(), "decision_id": str(self.decision.decision_id), "action_context": self.decision.action_context.model_dump(mode='json') } self.result = monitoring_result self.status = "completed" logger.info(f"Monitoring action completed: {self.action_id}") return monitoring_result except Exception as e: self.status = "failed" self.result = {"error": str(e)} logger.error(f"Monitoring action failed: {e}") raise def get_action_type(self) -> str: """Get the type of this action.""" return "monitor"
class AllowAction(ReflexiveAction): """Action to allow an operation to proceed.""" allow_conditions: List[str] = Field(default_factory=list, description="Conditions under which the action is allowed") allow_restrictions: List[str] = Field(default_factory=list, description="Restrictions that still apply") async def execute(self) -> Dict[str, Any]: """Execute the allow action.""" try: self.status = "executing" # Log the allowance logger.debug(f"ALLOWING OPERATION: {self.decision.action_context.action_id}") logger.debug(f"Reason: {self.decision.reason}") # In a real implementation, this would: # 1. Remove any temporary restrictions # 2. Log the decision for audit # 3. Continue normal operation flow # Simulate allow execution allow_result = { "allowed": True, "allow_timestamp": self.timestamp.isoformat(), "allow_conditions": self.allow_conditions, "allow_restrictions": self.allow_restrictions, "decision_id": str(self.decision.decision_id), "action_context": self.decision.action_context.model_dump(mode='json') } self.result = allow_result self.status = "completed" logger.debug(f"Allow action completed: {self.action_id}") return allow_result except Exception as e: self.status = "failed" self.result = {"error": str(e)} logger.error(f"Allow action failed: {e}") raise def get_action_type(self) -> str: """Get the type of this action.""" return "allow"
class ActionFactory: """Factory for creating reflexive actions.""" @staticmethod def create_action(decision: ReflexiveDecision, **kwargs) -> ReflexiveAction: """Create a reflexive action based on a decision.""" decision_type = decision.decision_type.value if hasattr(decision.decision_type, 'value') else str(decision.decision_type) if decision_type == "halt": return HaltAction( decision=decision, halt_reason=decision.reason, halt_level=kwargs.get("halt_level", "immediate"), affected_operations=kwargs.get("affected_operations", [decision.action_context.action_id]) ) elif decision_type == "escalate": return EscalateAction( decision=decision, escalation_target=decision.escalated_to or "default_admin", escalation_priority=kwargs.get("escalation_priority", "normal"), escalation_context=kwargs.get("escalation_context", {}), notification_channels=kwargs.get("notification_channels", ["email", "slack"]) ) elif decision_type == "monitor": return MonitorAction( decision=decision, monitoring_level=kwargs.get("monitoring_level", "enhanced"), monitoring_duration=kwargs.get("monitoring_duration", 3600), monitoring_scope=kwargs.get("monitoring_scope", [decision.action_context.actor_id]) ) elif decision_type == "allow": return AllowAction( decision=decision, allow_conditions=kwargs.get("allow_conditions", []), allow_restrictions=kwargs.get("allow_restrictions", []) ) else: raise ValueError(f"Unknown decision type: {decision.decision_type}")
class ActionExecutor: """Executor for reflexive actions.""" def __init__(self): """Initialize the action executor.""" self.execution_history = [] self.active_actions = {} async def execute_action(self, action: ReflexiveAction) -> Dict[str, Any]: """Execute a reflexive action.""" try: # Record the action self.active_actions[str(action.action_id)] = action self.execution_history.append({ "action_id": str(action.action_id), "action_type": action.get_action_type(), "decision_id": str(action.decision.decision_id), "start_time": action.timestamp.isoformat(), "status": action.status }) # Execute the action result = await action.execute() # Update history for record in self.execution_history: if record["action_id"] == str(action.action_id): record["end_time"] = datetime.utcnow().isoformat() record["status"] = action.status record["result"] = result break # Remove from active actions if str(action.action_id) in self.active_actions: del self.active_actions[str(action.action_id)] return result except Exception as e: # Update history with error for record in self.execution_history: if record["action_id"] == str(action.action_id): record["end_time"] = datetime.utcnow().isoformat() record["status"] = "failed" record["error"] = str(e) break # Remove from active actions if str(action.action_id) in self.active_actions: del self.active_actions[str(action.action_id)] raise def get_execution_stats(self) -> Dict[str, Any]: """Get execution statistics.""" total_actions = len(self.execution_history) completed_actions = len([a for a in self.execution_history if a.get("status") == "completed"]) failed_actions = len([a for a in self.execution_history if a.get("status") == "failed"]) active_actions = len(self.active_actions) return { "total_actions": total_actions, "completed_actions": completed_actions, "failed_actions": failed_actions, "active_actions": active_actions, "success_rate": completed_actions / total_actions if total_actions > 0 else 0 }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376"""Reflexive Core Engine - Main runtime for self-monitoring and corrective actions."""
import asyncioimport jsonimport hashlibfrom datetime import datetimefrom enum import Enumfrom typing import Any, Dict, List, Optional, Callable, Unionfrom uuid import UUID, uuid4
from pydantic import BaseModel, Field
from fastmcp.utilities.logging import get_logger
logger = get_logger(__name__)
class DecisionType(str, Enum): """Types of reflexive decisions.""" HALT = "halt" ESCALATE = "escalate" MONITOR = "monitor" ALLOW = "allow"
class RiskLevel(str, Enum): """Risk levels for reflexive decisions.""" LOW = "low" MEDIUM = "medium" HIGH = "high" CRITICAL = "critical"
class ActionContext(BaseModel): """Context for an action being evaluated by the reflexive core.""" action_id: str = Field(..., description="Unique identifier for the action") actor_id: str = Field(..., description="ID of the entity performing the action") action_type: str = Field(..., description="Type of action being performed") resource_id: Optional[str] = Field(default=None, description="ID of the resource being accessed") metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional action metadata") timestamp: datetime = Field(default_factory=datetime.utcnow, description="When the action occurred") session_id: Optional[str] = Field(default=None, description="Session identifier") request_id: Optional[str] = Field(default=None, description="Request identifier") def get_context_hash(self) -> str: """Get SHA-256 hash of action context for integrity verification.""" content = { "action_id": self.action_id, "actor_id": self.actor_id, "action_type": self.action_type, "resource_id": self.resource_id, "metadata": self.metadata, "session_id": self.session_id, "request_id": self.request_id } content_str = json.dumps(content, sort_keys=True, default=str) return hashlib.sha256(content_str.encode()).hexdigest()
class ReflexiveDecision(BaseModel): """A decision made by the reflexive core.""" decision_id: UUID = Field(default_factory=uuid4, description="Unique decision identifier") decision_type: DecisionType = Field(..., description="Type of decision made") risk_level: RiskLevel = Field(..., description="Risk level of the situation") action_context: ActionContext = Field(..., description="Context of the action being evaluated") reason: str = Field(..., description="Reason for the decision") evidence: Dict[str, Any] = Field(default_factory=dict, description="Evidence supporting the decision") timestamp: datetime = Field(default_factory=datetime.utcnow, description="When the decision was made") escalated_to: Optional[str] = Field(default=None, description="Role/entity escalated to") proof_hash: Optional[str] = Field(default=None, description="Hash of decision proof") model_config = {"use_enum_values": True} def get_decision_hash(self) -> str: """Get SHA-256 hash of decision for integrity verification.""" content = { "decision_id": str(self.decision_id), "decision_type": self.decision_type, "risk_level": self.risk_level, "action_context": self.action_context.model_dump(), "reason": self.reason, "evidence": self.evidence, "escalated_to": self.escalated_to } content_str = json.dumps(content, sort_keys=True, default=str) return hashlib.sha256(content_str.encode()).hexdigest()
class ReflexiveEngine: """Main reflexive core engine for self-monitoring and corrective actions.""" def __init__(self, policy_engine=None, ledger=None): """Initialize the reflexive engine. Args: policy_engine: Policy engine instance for policy monitoring ledger: Provenance ledger instance for audit logging """ self.policy_engine = policy_engine self.ledger = ledger self.monitors: List[Callable] = [] self.decision_handlers: Dict[DecisionType, Callable] = {} self.is_running = False self.event_queue = asyncio.Queue() # Register default decision handlers self._register_default_handlers() logger.info("Reflexive engine initialized") def _register_default_handlers(self): """Register default decision handlers.""" self.decision_handlers[DecisionType.HALT] = self._handle_halt self.decision_handlers[DecisionType.ESCALATE] = self._handle_escalate self.decision_handlers[DecisionType.MONITOR] = self._handle_monitor self.decision_handlers[DecisionType.ALLOW] = self._handle_allow async def start(self): """Start the reflexive engine.""" if self.is_running: logger.warning("Reflexive engine is already running") return self.is_running = True logger.info("Reflexive engine started") # Start the main event processing loop asyncio.create_task(self._process_events()) async def stop(self): """Stop the reflexive engine.""" self.is_running = False logger.info("Reflexive engine stopped") async def _process_events(self): """Main event processing loop.""" while self.is_running: try: # Wait for events with timeout event = await asyncio.wait_for(self.event_queue.get(), timeout=1.0) await self._handle_event(event) except asyncio.TimeoutError: # No events, continue continue except Exception as e: logger.error(f"Error processing reflexive event: {e}") async def _handle_event(self, event: Dict[str, Any]): """Handle a reflexive event.""" try: # Create action context from event action_context = ActionContext(**event.get("action_context", {})) # Evaluate the action decision = await self._evaluate_action(action_context) # Execute the decision await self._execute_decision(decision) # Log the decision to audit trail await self._log_decision(decision) except Exception as e: logger.error(f"Error handling reflexive event: {e}") async def _evaluate_action(self, action_context: ActionContext) -> ReflexiveDecision: """Evaluate an action and make a reflexive decision.""" # Run all monitors violations = [] anomalies = [] for monitor in self.monitors: try: # Check if monitor is async if asyncio.iscoroutinefunction(monitor): result = await monitor(action_context) else: result = monitor(action_context) if result: if result.get("type") == "violation": violations.append(result) elif result.get("type") == "anomaly": anomalies.append(result) except Exception as e: logger.error(f"Monitor error: {e}") # Make decision based on findings if violations or anomalies: # Determine risk level risk_level = self._assess_risk_level(violations, anomalies) # Make decision based on risk level if risk_level == RiskLevel.CRITICAL: decision_type = DecisionType.HALT reason = f"Critical risk detected: {len(violations)} violations, {len(anomalies)} anomalies" elif risk_level == RiskLevel.HIGH: decision_type = DecisionType.HALT reason = f"High risk detected: {len(violations)} violations, {len(anomalies)} anomalies" elif risk_level == RiskLevel.MEDIUM: decision_type = DecisionType.ESCALATE reason = f"Medium risk detected: {len(violations)} violations, {len(anomalies)} anomalies" else: decision_type = DecisionType.MONITOR reason = f"Low risk detected: {len(violations)} violations, {len(anomalies)} anomalies" else: decision_type = DecisionType.ALLOW reason = "No violations or anomalies detected" risk_level = RiskLevel.LOW # Create decision decision = ReflexiveDecision( decision_type=decision_type, risk_level=risk_level, action_context=action_context, reason=reason, evidence={ "violations": violations, "anomalies": anomalies } ) # Set proof hash decision.proof_hash = decision.get_decision_hash() return decision def _assess_risk_level(self, violations: List[Dict], anomalies: List[Dict]) -> RiskLevel: """Assess the overall risk level based on violations and anomalies.""" total_issues = len(violations) + len(anomalies) # Check for critical violations or anomalies critical_violations = [v for v in violations if v.get("severity") == "critical"] critical_anomalies = [a for a in anomalies if a.get("severity") == "critical"] if critical_violations or critical_anomalies: return RiskLevel.CRITICAL # Check for high severity issues high_violations = [v for v in violations if v.get("severity") == "high"] high_anomalies = [a for a in anomalies if a.get("severity") == "high"] if high_violations or high_anomalies or total_issues >= 5: return RiskLevel.HIGH # Check for medium severity issues medium_violations = [v for v in violations if v.get("severity") == "medium"] medium_anomalies = [a for a in anomalies if a.get("severity") == "medium"] if medium_violations or medium_anomalies or total_issues >= 2: return RiskLevel.MEDIUM return RiskLevel.LOW async def _execute_decision(self, decision: ReflexiveDecision): """Execute a reflexive decision.""" handler = self.decision_handlers.get(decision.decision_type) if handler: try: await handler(decision) except Exception as e: logger.error(f"Error executing decision {decision.decision_type}: {e}") else: logger.warning(f"No handler for decision type: {decision.decision_type}") async def _handle_halt(self, decision: ReflexiveDecision): """Handle a halt decision.""" logger.critical(f"HALTING ACTION: {decision.action_context.action_id} - {decision.reason}") # In a real implementation, this would stop the action execution # For now, we just log the halt decision async def _handle_escalate(self, decision: ReflexiveDecision): """Handle an escalate decision.""" # Determine escalation target escalation_target = self._determine_escalation_target(decision) decision.escalated_to = escalation_target logger.warning(f"ESCALATING TO {escalation_target}: {decision.action_context.action_id} - {decision.reason}") # In a real implementation, this would notify the escalation target async def _handle_monitor(self, decision: ReflexiveDecision): """Handle a monitor decision.""" logger.info(f"MONITORING ACTION: {decision.action_context.action_id} - {decision.reason}") # In a real implementation, this would increase monitoring for this action async def _handle_allow(self, decision: ReflexiveDecision): """Handle an allow decision.""" logger.debug(f"ALLOWING ACTION: {decision.action_context.action_id} - {decision.reason}") # Action is allowed to proceed def _determine_escalation_target(self, decision: ReflexiveDecision) -> str: """Determine the appropriate escalation target based on the decision.""" if decision.risk_level == RiskLevel.CRITICAL: return "security_admin" elif decision.risk_level == RiskLevel.HIGH: return "system_admin" else: return "monitoring_team" async def _log_decision(self, decision: ReflexiveDecision): """Log the reflexive decision to the audit trail.""" if self.ledger: try: from fastmcp.ledger import LedgerEvent, EventType event = LedgerEvent( event_type=EventType.REFLEXIVE_DECISION, actor_id="reflexive_core", resource_id=decision.action_context.action_id, action=f"reflexive_{decision.decision_type}", metadata={ "decision_id": str(decision.decision_id), "risk_level": decision.risk_level, "reason": decision.reason, "proof_hash": decision.proof_hash, "escalated_to": decision.escalated_to } ) self.ledger.append_event(event) logger.debug(f"Logged reflexive decision {decision.decision_id} to audit trail") except Exception as e: logger.error(f"Failed to log reflexive decision: {e}") else: # Log to standard logger if no ledger is available logger.info(f"Reflexive decision: {decision.decision_type} - {decision.reason} (Decision ID: {decision.decision_id})") def add_monitor(self, monitor: Callable): """Add a monitor function to the reflexive engine.""" self.monitors.append(monitor) logger.info(f"Added monitor: {monitor.__name__}") def remove_monitor(self, monitor: Callable): """Remove a monitor function from the reflexive engine.""" if monitor in self.monitors: self.monitors.remove(monitor) logger.info(f"Removed monitor: {monitor.__name__}") async def submit_action(self, action_context: ActionContext): """Submit an action for reflexive evaluation.""" event = { "action_context": action_context.model_dump(), "timestamp": datetime.utcnow().isoformat() } await self.event_queue.put(event) logger.debug(f"Submitted action {action_context.action_id} for reflexive evaluation") async def simulate_risk(self, risk_scenario: Dict[str, Any]) -> ReflexiveDecision: """Simulate a risk scenario and return the reflexive decision.""" # Create action context from scenario action_context = ActionContext(**risk_scenario.get("action_context", {})) # Override monitors temporarily for simulation original_monitors = self.monitors.copy() # Add simulation monitors simulation_monitors = risk_scenario.get("monitors", []) for monitor_func in simulation_monitors: self.monitors.append(monitor_func) try: # Evaluate the action decision = await self._evaluate_action(action_context) return decision finally: # Restore original monitors self.monitors = original_monitors def get_engine_status(self) -> Dict[str, Any]: """Get the current status of the reflexive engine.""" return { "is_running": self.is_running, "monitor_count": len(self.monitors), "queue_size": self.event_queue.qsize(), "decision_handlers": list(self.decision_handlers.keys()) }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356"""Monitoring components for the reflexive core."""
import asynciofrom datetime import datetime, timedeltafrom typing import Any, Dict, List, Optional, Callablefrom collections import defaultdict, deque
from fastmcp.utilities.logging import get_logger
logger = get_logger(__name__)
class PolicyMonitor: """Monitor for policy violations.""" def __init__(self, policy_engine=None): """Initialize the policy monitor. Args: policy_engine: Policy engine instance to monitor """ self.policy_engine = policy_engine self.violation_history = deque(maxlen=1000) # Keep last 1000 violations self.actor_violations = defaultdict(int) # Track violations per actor async def __call__(self, action_context) -> Optional[Dict[str, Any]]: """Monitor an action for policy violations.""" try: # Check for policy violations (works with or without policy engine) violations = await self._check_policy_violations(action_context) if violations: # Record violation violation_record = { "type": "violation", "severity": self._assess_violation_severity(violations), "violations": violations, "actor_id": action_context.actor_id, "action_id": action_context.action_id, "timestamp": datetime.utcnow().isoformat() } self.violation_history.append(violation_record) self.actor_violations[action_context.actor_id] += 1 return violation_record return None except Exception as e: logger.error(f"Policy monitor error: {e}") return None async def _check_policy_violations(self, action_context) -> List[Dict[str, Any]]: """Check for policy violations in an action.""" violations = [] try: # Simulate policy checking # In a real implementation, this would use the actual policy engine # Check for suspicious patterns if action_context.action_type == "admin_access" and action_context.actor_id.startswith("guest"): violations.append({ "rule": "admin_access_restriction", "message": "Guest user attempting admin access", "severity": "high" }) # Check for rate limiting recent_violations = [v for v in self.violation_history if v.get("actor_id") == action_context.actor_id and datetime.fromisoformat(v["timestamp"]) > datetime.utcnow() - timedelta(minutes=5)] if len(recent_violations) >= 3: violations.append({ "rule": "rate_limit_exceeded", "message": f"Actor {action_context.actor_id} has {len(recent_violations)} recent violations", "severity": "medium" }) # Check for resource access patterns if action_context.resource_id and "sensitive" in action_context.resource_id.lower(): if not action_context.metadata.get("authorized"): violations.append({ "rule": "unauthorized_sensitive_access", "message": "Unauthorized access to sensitive resource", "severity": "critical" }) except Exception as e: logger.error(f"Error checking policy violations: {e}") return violations def _assess_violation_severity(self, violations: List[Dict[str, Any]]) -> str: """Assess the overall severity of violations.""" if not violations: return "low" severities = [v.get("severity", "low") for v in violations] if "critical" in severities: return "critical" elif "high" in severities: return "high" elif "medium" in severities: return "medium" else: return "low" def get_violation_stats(self) -> Dict[str, Any]: """Get violation statistics.""" return { "total_violations": len(self.violation_history), "actor_violations": dict(self.actor_violations), "recent_violations": len([v for v in self.violation_history if datetime.fromisoformat(v["timestamp"]) > datetime.utcnow() - timedelta(hours=1)]) }
class LedgerMonitor: """Monitor for ledger inconsistencies and anomalies.""" def __init__(self, ledger=None): """Initialize the ledger monitor. Args: ledger: Provenance ledger instance to monitor """ self.ledger = ledger self.integrity_checks = deque(maxlen=100) # Keep last 100 integrity checks async def __call__(self, action_context) -> Optional[Dict[str, Any]]: """Monitor ledger for inconsistencies.""" try: if not self.ledger: return None # Check ledger integrity integrity_issues = await self._check_ledger_integrity() if integrity_issues: # Record integrity issue issue_record = { "type": "anomaly", "severity": self._assess_integrity_severity(integrity_issues), "issues": integrity_issues, "action_id": action_context.action_id, "timestamp": datetime.utcnow().isoformat() } self.integrity_checks.append(issue_record) return issue_record return None except Exception as e: logger.error(f"Ledger monitor error: {e}") return None async def _check_ledger_integrity(self) -> List[Dict[str, Any]]: """Check ledger for integrity issues.""" issues = [] try: # Check chain integrity is_valid = self.ledger.verify_chain_integrity() if not is_valid: issues.append({ "type": "chain_integrity", "message": "Ledger chain integrity verification failed", "severity": "critical" }) # Check for missing blocks stats = self.ledger.get_ledger_statistics() if stats.get("total_entries", 0) > 0 and stats.get("total_blocks", 0) == 0: issues.append({ "type": "missing_blocks", "message": "Entries exist but no blocks found", "severity": "high" }) # Check for unsealed blocks # This would require additional ledger methods to check for unsealed blocks except Exception as e: logger.error(f"Error checking ledger integrity: {e}") issues.append({ "type": "integrity_check_error", "message": f"Error during integrity check: {str(e)}", "severity": "medium" }) return issues def _assess_integrity_severity(self, issues: List[Dict[str, Any]]) -> str: """Assess the overall severity of integrity issues.""" if not issues: return "low" severities = [i.get("severity", "low") for i in issues] if "critical" in severities: return "critical" elif "high" in severities: return "high" elif "medium" in severities: return "medium" else: return "low" def get_integrity_stats(self) -> Dict[str, Any]: """Get integrity check statistics.""" return { "total_checks": len(self.integrity_checks), "recent_issues": len([i for i in self.integrity_checks if datetime.fromisoformat(i["timestamp"]) > datetime.utcnow() - timedelta(hours=1)]) }
class AnomalyDetector: """Detector for behavioral anomalies.""" def __init__(self): """Initialize the anomaly detector.""" self.actor_patterns = defaultdict(lambda: { "action_counts": defaultdict(int), "resource_access": defaultdict(int), "session_times": deque(maxlen=100), "last_seen": None }) self.global_patterns = { "action_frequency": defaultdict(int), "resource_access": defaultdict(int), "time_patterns": defaultdict(int) } async def __call__(self, action_context) -> Optional[Dict[str, Any]]: """Detect anomalies in an action.""" try: # Update patterns self._update_patterns(action_context) # Detect anomalies anomalies = await self._detect_anomalies(action_context) if anomalies: return { "type": "anomaly", "severity": self._assess_anomaly_severity(anomalies), "anomalies": anomalies, "actor_id": action_context.actor_id, "action_id": action_context.action_id, "timestamp": datetime.utcnow().isoformat() } return None except Exception as e: logger.error(f"Anomaly detector error: {e}") return None def _update_patterns(self, action_context): """Update behavioral patterns.""" actor_id = action_context.actor_id actor_data = self.actor_patterns[actor_id] # Update action counts actor_data["action_counts"][action_context.action_type] += 1 self.global_patterns["action_frequency"][action_context.action_type] += 1 # Update resource access if action_context.resource_id: actor_data["resource_access"][action_context.resource_id] += 1 self.global_patterns["resource_access"][action_context.resource_id] += 1 # Update session times actor_data["session_times"].append(action_context.timestamp) actor_data["last_seen"] = action_context.timestamp # Update time patterns hour = action_context.timestamp.hour self.global_patterns["time_patterns"][hour] += 1 async def _detect_anomalies(self, action_context) -> List[Dict[str, Any]]: """Detect anomalies in the action.""" anomalies = [] actor_id = action_context.actor_id actor_data = self.actor_patterns[actor_id] # Check for unusual action frequency if len(actor_data["session_times"]) >= 10: recent_actions = [t for t in actor_data["session_times"] if t > datetime.utcnow() - timedelta(minutes=5)] if len(recent_actions) > 20: # More than 20 actions in 5 minutes anomalies.append({ "type": "high_frequency", "message": f"Actor {actor_id} performing {len(recent_actions)} actions in 5 minutes", "severity": "medium" }) # Check for unusual time patterns current_hour = action_context.timestamp.hour if current_hour < 6 or current_hour > 22: # Unusual hours if actor_data["action_counts"].get(action_context.action_type, 0) < 5: # New action type anomalies.append({ "type": "unusual_timing", "message": f"Actor {actor_id} performing {action_context.action_type} at unusual hour {current_hour}", "severity": "low" }) # Check for new resource access if action_context.resource_id: if actor_data["resource_access"].get(action_context.resource_id, 0) == 1: # First time accessing this resource anomalies.append({ "type": "new_resource_access", "message": f"Actor {actor_id} accessing new resource {action_context.resource_id}", "severity": "low" }) # Check for privilege escalation patterns if action_context.action_type in ["admin_access", "root_access", "privilege_escalation"]: if actor_data["action_counts"].get(action_context.action_type, 0) == 1: # First time performing privileged action anomalies.append({ "type": "privilege_escalation", "message": f"Actor {actor_id} attempting privileged action for first time", "severity": "high" }) return anomalies def _assess_anomaly_severity(self, anomalies: List[Dict[str, Any]]) -> str: """Assess the overall severity of anomalies.""" if not anomalies: return "low" severities = [a.get("severity", "low") for a in anomalies] if "high" in severities: return "high" elif "medium" in severities: return "medium" else: return "low" def get_anomaly_stats(self) -> Dict[str, Any]: """Get anomaly detection statistics.""" return { "tracked_actors": len(self.actor_patterns), "global_action_types": len(self.global_patterns["action_frequency"]), "global_resources": len(self.global_patterns["resource_access"]) }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385"""Reflexive Core HTTP routes."""
from typing import Any, Dict, List, Optionalfrom uuid import UUID
from starlette.requests import Requestfrom starlette.responses import JSONResponsefrom starlette.routing import Route
from fastmcp.reflexive import ReflexiveEngine, ActionContext, DecisionType, RiskLevelfrom fastmcp.reflexive.actions import ActionFactory, ActionExecutorfrom fastmcp.utilities.logging import get_logger
logger = get_logger(__name__)
async def simulate_risk_endpoint(request: Request) -> JSONResponse: """HTTP endpoint for simulating risk scenarios. Expected JSON body: { "action_context": { "action_id": "test_action_123", "actor_id": "test_user", "action_type": "admin_access", "resource_id": "sensitive_data", "metadata": {...} }, "monitors": [ // List of monitor functions (for simulation) ], "scenario_type": "policy_violation" | "anomaly" | "integrity_issue" } """ try: # Parse request body body = await request.json() # Get reflexive engine from request state reflexive_engine: ReflexiveEngine = request.app.state.reflexive_engine # Validate required fields if "action_context" not in body: return JSONResponse( status_code=400, content={ "error": "Missing required field: action_context" } ) # Simulate the risk scenario decision = await reflexive_engine.simulate_risk(body) # Create and execute the corresponding action action = ActionFactory.create_action(decision) executor = ActionExecutor() action_result = await executor.execute_action(action) return JSONResponse( status_code=200, content={ "simulation_id": str(decision.decision_id), "decision": { "decision_id": str(decision.decision_id), "decision_type": decision.decision_type, "risk_level": decision.risk_level, "reason": decision.reason, "evidence": decision.evidence, "proof_hash": decision.proof_hash, "escalated_to": decision.escalated_to, "timestamp": decision.timestamp.isoformat() }, "action": { "action_id": str(action.action_id), "action_type": action.get_action_type(), "status": action.status, "result": action_result }, "action_context": decision.action_context.model_dump(mode='json') } ) except ValueError as e: logger.error(f"Invalid simulation data: {e}") return JSONResponse( status_code=400, content={ "error": "Invalid simulation data", "reason": str(e) } ) except Exception as e: logger.error(f"Failed to simulate risk: {e}") return JSONResponse( status_code=500, content={ "error": "Failed to simulate risk", "reason": str(e) } )
async def get_engine_status_endpoint(request: Request) -> JSONResponse: """HTTP endpoint for getting reflexive engine status.""" try: # Get reflexive engine from request state reflexive_engine: ReflexiveEngine = request.app.state.reflexive_engine # Get engine status status = reflexive_engine.get_engine_status() return JSONResponse( status_code=200, content=status ) except Exception as e: logger.error(f"Failed to get engine status: {e}") return JSONResponse( status_code=500, content={ "error": "Failed to get engine status", "reason": str(e) } )
async def submit_action_endpoint(request: Request) -> JSONResponse: """HTTP endpoint for submitting an action for reflexive evaluation. Expected JSON body: { "action_id": "action_123", "actor_id": "user_456", "action_type": "tool_call", "resource_id": "resource_789", "metadata": {...}, "session_id": "session_abc", "request_id": "request_def" } """ try: # Parse request body body = await request.json() # Get reflexive engine from request state reflexive_engine: ReflexiveEngine = request.app.state.reflexive_engine # Create action context action_context = ActionContext(**body) # Submit action for evaluation await reflexive_engine.submit_action(action_context) return JSONResponse( status_code=202, content={ "message": "Action submitted for reflexive evaluation", "action_id": action_context.action_id, "submitted_at": action_context.timestamp.isoformat() } ) except ValueError as e: logger.error(f"Invalid action data: {e}") return JSONResponse( status_code=400, content={ "error": "Invalid action data", "reason": str(e) } ) except Exception as e: logger.error(f"Failed to submit action: {e}") return JSONResponse( status_code=500, content={ "error": "Failed to submit action", "reason": str(e) } )
async def get_monitor_stats_endpoint(request: Request) -> JSONResponse: """HTTP endpoint for getting monitor statistics.""" try: # Get reflexive engine from request state reflexive_engine: ReflexiveEngine = request.app.state.reflexive_engine # Collect stats from all monitors stats = {} for monitor in reflexive_engine.monitors: if hasattr(monitor, 'get_violation_stats'): stats['policy_monitor'] = monitor.get_violation_stats() elif hasattr(monitor, 'get_integrity_stats'): stats['ledger_monitor'] = monitor.get_integrity_stats() elif hasattr(monitor, 'get_anomaly_stats'): stats['anomaly_detector'] = monitor.get_anomaly_stats() return JSONResponse( status_code=200, content=stats ) except Exception as e: logger.error(f"Failed to get monitor stats: {e}") return JSONResponse( status_code=500, content={ "error": "Failed to get monitor stats", "reason": str(e) } )
async def create_risk_scenario_endpoint(request: Request) -> JSONResponse: """HTTP endpoint for creating predefined risk scenarios. Expected JSON body: { "scenario_name": "admin_privilege_escalation", "scenario_type": "policy_violation", "parameters": { "actor_type": "guest_user", "target_resource": "admin_panel", "severity": "high" } } """ try: # Parse request body body = await request.json() scenario_name = body.get("scenario_name") scenario_type = body.get("scenario_type") parameters = body.get("parameters", {}) if not scenario_name or not scenario_type: return JSONResponse( status_code=400, content={ "error": "Missing required fields: scenario_name, scenario_type" } ) # Create scenario based on type scenario = _create_risk_scenario(scenario_name, scenario_type, parameters) return JSONResponse( status_code=200, content={ "scenario": scenario, "message": f"Risk scenario '{scenario_name}' created successfully" } ) except Exception as e: logger.error(f"Failed to create risk scenario: {e}") return JSONResponse( status_code=500, content={ "error": "Failed to create risk scenario", "reason": str(e) } )
def _create_risk_scenario(scenario_name: str, scenario_type: str, parameters: Dict[str, Any]) -> Dict[str, Any]: """Create a predefined risk scenario.""" scenarios = { "admin_privilege_escalation": { "action_context": { "action_id": f"admin_escalation_{scenario_name}", "actor_id": parameters.get("actor_type", "guest_user"), "action_type": "admin_access", "resource_id": parameters.get("target_resource", "admin_panel"), "metadata": { "privilege_level": "admin", "escalation_attempt": True } }, "expected_decision": "halt", "expected_risk_level": "high" }, "suspicious_activity": { "action_context": { "action_id": f"suspicious_{scenario_name}", "actor_id": "suspicious_user", "action_type": "data_access", "resource_id": "sensitive_data", "metadata": { "access_pattern": "unusual", "time_of_day": "off_hours" } }, "expected_decision": "escalate", "expected_risk_level": "medium" }, "integrity_violation": { "action_context": { "action_id": f"integrity_{scenario_name}", "actor_id": "system", "action_type": "ledger_modification", "resource_id": "provenance_ledger", "metadata": { "modification_type": "unauthorized", "integrity_check": "failed" } }, "expected_decision": "halt", "expected_risk_level": "critical" }, "rate_limit_exceeded": { "action_context": { "action_id": f"rate_limit_{scenario_name}", "actor_id": "high_frequency_user", "action_type": "api_call", "resource_id": "api_endpoint", "metadata": { "request_count": 1000, "time_window": "1_minute" } }, "expected_decision": "escalate", "expected_risk_level": "medium" } } return scenarios.get(scenario_name, { "action_context": { "action_id": f"custom_{scenario_name}", "actor_id": "test_user", "action_type": "custom_action", "resource_id": "test_resource", "metadata": parameters }, "expected_decision": "monitor", "expected_risk_level": "low" })
def create_reflexive_routes(reflexive_engine: ReflexiveEngine) -> List[Route]: """Create reflexive core routes. Args: reflexive_engine: The reflexive engine instance Returns: List of Starlette Route objects for reflexive core management """ def endpoint_with_engine(endpoint_func): async def wrapper(request: Request) -> JSONResponse: # Store reflexive engine in app state for access in endpoint request.app.state.reflexive_engine = reflexive_engine return await endpoint_func(request) return wrapper return [ Route( path="/core/simulate-risk", endpoint=endpoint_with_engine(simulate_risk_endpoint), methods=["POST"] ), Route( path="/core/status", endpoint=endpoint_with_engine(get_engine_status_endpoint), methods=["GET"] ), Route( path="/core/submit-action", endpoint=endpoint_with_engine(submit_action_endpoint), methods=["POST"] ), Route( path="/core/monitor-stats", endpoint=endpoint_with_engine(get_monitor_stats_endpoint), methods=["GET"] ), Route( path="/core/risk-scenario", endpoint=endpoint_with_engine(create_risk_scenario_endpoint), methods=["POST"] ) ]63 unmodified lines646566676869106 unmodified lines176177178179180181332 unmodified lines51451551651751851925 unmodified lines54554654754854955063 unmodified linesfrom fastmcp.tools.tool import FunctionTool, Tool, ToolResultfrom fastmcp.tools.tool_transform import ToolTransformConfigfrom fastmcp.policy import PolicyEnginefrom fastmcp.utilities.cli import log_server_bannerfrom fastmcp.utilities.components import FastMCPComponentfrom fastmcp.utilities.logging import get_logger106 unmodified linesself._additional_http_routes: list[BaseRoute] = []self._mounted_servers: list[MountedServer] = []self._policy_engine: Optional[PolicyEngine] = Noneself._tool_manager = ToolManager(duplicate_behavior=on_duplicate_tools,mask_error_details=mask_error_details,332 unmodified linespolicy_route = create_policy_evaluate_route(self._policy_engine)routes.append(policy_route)# Recursively get routes from mounted serversfor mounted_server in self._mounted_servers:mounted_routes = mounted_server.server._get_additional_http_routes()25 unmodified lines"""return self._policy_engineasync def _mcp_list_tools(self) -> list[MCPTool]:logger.debug("Handler called: list_tools")63 unmodified lines64656667686970106 unmodified lines177178179180181182183332 unmodified lines51651751851952052152252352452552652752852925 unmodified lines55555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758863 unmodified linesfrom fastmcp.tools.tool import FunctionTool, Tool, ToolResultfrom fastmcp.tools.tool_transform import ToolTransformConfigfrom fastmcp.policy import PolicyEnginefrom fastmcp.reflexive import ReflexiveEnginefrom fastmcp.utilities.cli import log_server_bannerfrom fastmcp.utilities.components import FastMCPComponentfrom fastmcp.utilities.logging import get_logger106 unmodified linesself._additional_http_routes: list[BaseRoute] = []self._mounted_servers: list[MountedServer] = []self._policy_engine: Optional[PolicyEngine] = Noneself._reflexive_engine: Optional[ReflexiveEngine] = Noneself._tool_manager = ToolManager(duplicate_behavior=on_duplicate_tools,mask_error_details=mask_error_details,332 unmodified linespolicy_route = create_policy_evaluate_route(self._policy_engine)routes.append(policy_route)# Add reflexive core endpoints if reflexive engine is configuredif self._reflexive_engine is not None:from fastmcp.server.reflexive_routes import create_reflexive_routesreflexive_routes = create_reflexive_routes(self._reflexive_engine)routes.extend(reflexive_routes)# Recursively get routes from mounted serversfor mounted_server in self._mounted_servers:mounted_routes = mounted_server.server._get_additional_http_routes()25 unmodified lines"""return self._policy_enginedef enable_reflexive_core(self, reflexive_engine: Optional[ReflexiveEngine] = None) -> ReflexiveEngine:"""Enable the reflexive core for this server.Args:reflexive_engine: Optional reflexive engine instance. If None, creates a new one.Returns:The reflexive engine instance"""if reflexive_engine is None:reflexive_engine = ReflexiveEngine(policy_engine=self._policy_engine,ledger=None)self._reflexive_engine = reflexive_enginelogger.info("Reflexive core enabled for server")return reflexive_enginedef get_reflexive_engine(self) -> Optional[ReflexiveEngine]:"""Get the reflexive engine instance.Returns:The reflexive engine instance, or None if not enabled"""return self._reflexive_engineasync def _mcp_list_tools(self) -> list[MCPTool]:logger.debug("Handler called: list_tools")
1"""Tests for the reflexive core module."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461"""Tests for the reflexive actions."""
import pytestfrom datetime import datetimefrom unittest.mock import Mock
from fastmcp.reflexive.actions import ( HaltAction, EscalateAction, MonitorAction, AllowAction, ActionFactory, ActionExecutor)from fastmcp.reflexive.engine import ReflexiveDecision, ActionContext, DecisionType, RiskLevel
class TestHaltAction: """Test the HaltAction class.""" @pytest.fixture def halt_decision(self): """Create a halt decision for testing.""" action_context = ActionContext( action_id="test_action", actor_id="test_user", action_type="admin_access" ) return ReflexiveDecision( decision_type=DecisionType.HALT, risk_level=RiskLevel.HIGH, action_context=action_context, reason="Unauthorized admin access attempt" ) @pytest.fixture def halt_action(self, halt_decision): """Create a halt action for testing.""" return HaltAction( decision=halt_decision, halt_reason="Security violation detected", halt_level="immediate", affected_operations=["admin_access", "user_management"] ) def test_halt_action_creation(self, halt_action, halt_decision): """Test halt action creation.""" assert halt_action.decision == halt_decision assert halt_action.halt_reason == "Security violation detected" assert halt_action.halt_level == "immediate" assert halt_action.affected_operations == ["admin_access", "user_management"] assert halt_action.status == "pending" assert halt_action.result is None async def test_halt_action_execution(self, halt_action): """Test halt action execution.""" result = await halt_action.execute() assert halt_action.status == "completed" assert halt_action.result is not None assert result["halted_operations"] == ["admin_access", "user_management"] assert result["halt_reason"] == "Security violation detected" assert result["halt_level"] == "immediate" assert "halt_timestamp" in result assert "decision_id" in result def test_halt_action_type(self, halt_action): """Test halt action type.""" assert halt_action.get_action_type() == "halt"
class TestEscalateAction: """Test the EscalateAction class.""" @pytest.fixture def escalate_decision(self): """Create an escalate decision for testing.""" action_context = ActionContext( action_id="test_action", actor_id="test_user", action_type="data_access" ) return ReflexiveDecision( decision_type=DecisionType.ESCALATE, risk_level=RiskLevel.MEDIUM, action_context=action_context, reason="Suspicious data access pattern" ) @pytest.fixture def escalate_action(self, escalate_decision): """Create an escalate action for testing.""" return EscalateAction( decision=escalate_decision, escalation_target="security_team", escalation_priority="high", escalation_context={"alert_level": "medium"}, notification_channels=["email", "slack"] ) def test_escalate_action_creation(self, escalate_action, escalate_decision): """Test escalate action creation.""" assert escalate_action.decision == escalate_decision assert escalate_action.escalation_target == "security_team" assert escalate_action.escalation_priority == "high" assert escalate_action.escalation_context == {"alert_level": "medium"} assert escalate_action.notification_channels == ["email", "slack"] assert escalate_action.status == "pending" assert escalate_action.result is None async def test_escalate_action_execution(self, escalate_action): """Test escalate action execution.""" result = await escalate_action.execute() assert escalate_action.status == "completed" assert escalate_action.result is not None assert result["escalation_target"] == "security_team" assert result["escalation_priority"] == "high" assert result["escalation_context"] == {"alert_level": "medium"} assert result["notification_channels"] == ["email", "slack"] assert "escalation_timestamp" in result assert "decision_id" in result assert "action_context" in result def test_escalate_action_type(self, escalate_action): """Test escalate action type.""" assert escalate_action.get_action_type() == "escalate"
class TestMonitorAction: """Test the MonitorAction class.""" @pytest.fixture def monitor_decision(self): """Create a monitor decision for testing.""" action_context = ActionContext( action_id="test_action", actor_id="test_user", action_type="api_call" ) return ReflexiveDecision( decision_type=DecisionType.MONITOR, risk_level=RiskLevel.LOW, action_context=action_context, reason="Unusual but not suspicious activity" ) @pytest.fixture def monitor_action(self, monitor_decision): """Create a monitor action for testing.""" return MonitorAction( decision=monitor_decision, monitoring_level="enhanced", monitoring_duration=1800, monitoring_scope=["test_user", "api_calls"] ) def test_monitor_action_creation(self, monitor_action, monitor_decision): """Test monitor action creation.""" assert monitor_action.decision == monitor_decision assert monitor_action.monitoring_level == "enhanced" assert monitor_action.monitoring_duration == 1800 assert monitor_action.monitoring_scope == ["test_user", "api_calls"] assert monitor_action.status == "pending" assert monitor_action.result is None async def test_monitor_action_execution(self, monitor_action): """Test monitor action execution.""" result = await monitor_action.execute() assert monitor_action.status == "completed" assert monitor_action.result is not None assert result["monitoring_level"] == "enhanced" assert result["monitoring_duration"] == 1800 assert result["monitoring_scope"] == ["test_user", "api_calls"] assert "monitoring_timestamp" in result assert "decision_id" in result assert "action_context" in result def test_monitor_action_type(self, monitor_action): """Test monitor action type.""" assert monitor_action.get_action_type() == "monitor"
class TestAllowAction: """Test the AllowAction class.""" @pytest.fixture def allow_decision(self): """Create an allow decision for testing.""" action_context = ActionContext( action_id="test_action", actor_id="test_user", action_type="normal_operation" ) return ReflexiveDecision( decision_type=DecisionType.ALLOW, risk_level=RiskLevel.LOW, action_context=action_context, reason="No violations or anomalies detected" ) @pytest.fixture def allow_action(self, allow_decision): """Create an allow action for testing.""" return AllowAction( decision=allow_decision, allow_conditions=["authenticated", "authorized"], allow_restrictions=["rate_limited"] ) def test_allow_action_creation(self, allow_action, allow_decision): """Test allow action creation.""" assert allow_action.decision == allow_decision assert allow_action.allow_conditions == ["authenticated", "authorized"] assert allow_action.allow_restrictions == ["rate_limited"] assert allow_action.status == "pending" assert allow_action.result is None async def test_allow_action_execution(self, allow_action): """Test allow action execution.""" result = await allow_action.execute() assert allow_action.status == "completed" assert allow_action.result is not None assert result["allowed"] is True assert result["allow_conditions"] == ["authenticated", "authorized"] assert result["allow_restrictions"] == ["rate_limited"] assert "allow_timestamp" in result assert "decision_id" in result assert "action_context" in result def test_allow_action_type(self, allow_action): """Test allow action type.""" assert allow_action.get_action_type() == "allow"
class TestActionFactory: """Test the ActionFactory class.""" @pytest.fixture def halt_decision(self): """Create a halt decision for testing.""" action_context = ActionContext( action_id="test_action", actor_id="test_user", action_type="admin_access" ) return ReflexiveDecision( decision_type=DecisionType.HALT, risk_level=RiskLevel.HIGH, action_context=action_context, reason="Security violation" ) @pytest.fixture def escalate_decision(self): """Create an escalate decision for testing.""" action_context = ActionContext( action_id="test_action", actor_id="test_user", action_type="data_access" ) return ReflexiveDecision( decision_type=DecisionType.ESCALATE, risk_level=RiskLevel.MEDIUM, action_context=action_context, reason="Suspicious activity" ) @pytest.fixture def monitor_decision(self): """Create a monitor decision for testing.""" action_context = ActionContext( action_id="test_action", actor_id="test_user", action_type="api_call" ) return ReflexiveDecision( decision_type=DecisionType.MONITOR, risk_level=RiskLevel.LOW, action_context=action_context, reason="Unusual activity" ) @pytest.fixture def allow_decision(self): """Create an allow decision for testing.""" action_context = ActionContext( action_id="test_action", actor_id="test_user", action_type="normal_operation" ) return ReflexiveDecision( decision_type=DecisionType.ALLOW, risk_level=RiskLevel.LOW, action_context=action_context, reason="No issues detected" ) def test_create_halt_action(self, halt_decision): """Test creating a halt action.""" action = ActionFactory.create_action(halt_decision) assert isinstance(action, HaltAction) assert action.decision == halt_decision assert action.halt_reason == halt_decision.reason assert action.halt_level == "immediate" assert halt_decision.action_context.action_id in action.affected_operations def test_create_escalate_action(self, escalate_decision): """Test creating an escalate action.""" action = ActionFactory.create_action(escalate_decision) assert isinstance(action, EscalateAction) assert action.decision == escalate_decision assert action.escalation_target == "default_admin" assert action.escalation_priority == "normal" def test_create_monitor_action(self, monitor_decision): """Test creating a monitor action.""" action = ActionFactory.create_action(monitor_decision) assert isinstance(action, MonitorAction) assert action.decision == monitor_decision assert action.monitoring_level == "enhanced" assert action.monitoring_duration == 3600 def test_create_allow_action(self, allow_decision): """Test creating an allow action.""" action = ActionFactory.create_action(allow_decision) assert isinstance(action, AllowAction) assert action.decision == allow_decision assert action.allow_conditions == [] assert action.allow_restrictions == [] def test_create_action_with_kwargs(self, halt_decision): """Test creating an action with additional kwargs.""" action = ActionFactory.create_action( halt_decision, halt_level="graceful", affected_operations=["operation1", "operation2"] ) assert isinstance(action, HaltAction) assert action.halt_level == "graceful" assert action.affected_operations == ["operation1", "operation2"] def test_create_action_unknown_type(self, halt_decision): """Test creating an action with unknown decision type.""" halt_decision.decision_type = "unknown_type" # type: ignore with pytest.raises(ValueError, match="Unknown decision type"): ActionFactory.create_action(halt_decision)
class TestActionExecutor: """Test the ActionExecutor class.""" @pytest.fixture def action_executor(self): """Create an action executor for testing.""" return ActionExecutor() @pytest.fixture def halt_action(self): """Create a halt action for testing.""" action_context = ActionContext( action_id="test_action", actor_id="test_user", action_type="admin_access" ) decision = ReflexiveDecision( decision_type=DecisionType.HALT, risk_level=RiskLevel.HIGH, action_context=action_context, reason="Security violation" ) return HaltAction( decision=decision, halt_reason="Unauthorized access", halt_level="immediate", affected_operations=[action_context.action_id] ) async def test_execute_action_success(self, action_executor, halt_action): """Test successful action execution.""" result = await action_executor.execute_action(halt_action) assert result["halted_operations"] == [halt_action.decision.action_context.action_id] assert result["halt_reason"] == "Unauthorized access" assert result["halt_level"] == "immediate" # Check execution history assert len(action_executor.execution_history) == 1 history_record = action_executor.execution_history[0] assert history_record["action_id"] == str(halt_action.action_id) assert history_record["action_type"] == "halt" assert history_record["status"] == "completed" assert "end_time" in history_record assert "result" in history_record async def test_execute_action_failure(self, action_executor): """Test action execution failure.""" # Create a mock action that raises an exception mock_action = Mock() mock_action.action_id = "test_action_id" mock_action.decision = Mock() mock_action.decision.decision_id = "test_decision_id" mock_action.execute.side_effect = Exception("Execution failed") mock_action.get_action_type.return_value = "test_type" mock_action.timestamp = datetime.utcnow() mock_action.status = "pending" with pytest.raises(Exception, match="Execution failed"): await action_executor.execute_action(mock_action) # Check execution history assert len(action_executor.execution_history) == 1 history_record = action_executor.execution_history[0] assert history_record["action_id"] == "test_action_id" assert history_record["status"] == "failed" assert "error" in history_record assert history_record["error"] == "Execution failed" def test_get_execution_stats(self, action_executor): """Test getting execution statistics.""" # Add some execution history action_executor.execution_history = [ {"action_id": "1", "status": "completed"}, {"action_id": "2", "status": "completed"}, {"action_id": "3", "status": "failed"}, ] stats = action_executor.get_execution_stats() assert stats["total_actions"] == 3 assert stats["completed_actions"] == 2 assert stats["failed_actions"] == 1 assert stats["active_actions"] == 0 assert stats["success_rate"] == 2/3 def test_active_actions_tracking(self, action_executor, halt_action): """Test active actions tracking.""" # Start execution (this would normally be async) action_executor.active_actions[str(halt_action.action_id)] = halt_action assert len(action_executor.active_actions) == 1 assert str(halt_action.action_id) in action_executor.active_actions # Simulate completion del action_executor.active_actions[str(halt_action.action_id)] assert len(action_executor.active_actions) == 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428"""Tests for the reflexive monitors."""
import pytestfrom datetime import datetime, timedeltafrom unittest.mock import Mock
from fastmcp.reflexive.monitor import PolicyMonitor, LedgerMonitor, AnomalyDetectorfrom fastmcp.reflexive.engine import ActionContext
class TestPolicyMonitor: """Test the PolicyMonitor class.""" @pytest.fixture def policy_monitor(self): """Create a policy monitor for testing.""" return PolicyMonitor() @pytest.fixture def action_context(self): """Create an action context for testing.""" return ActionContext( action_id="test_action", actor_id="test_user", action_type="tool_call", resource_id="test_resource" ) async def test_monitor_no_violations(self, policy_monitor, action_context): """Test monitoring with no violations.""" result = await policy_monitor(action_context) assert result is None async def test_monitor_admin_access_violation(self, policy_monitor, action_context): """Test monitoring admin access violation.""" # Create action context with admin access by guest user admin_context = ActionContext( action_id="admin_action", actor_id="guest_user", action_type="admin_access", resource_id="admin_panel" ) result = await policy_monitor(admin_context) assert result is not None assert result["type"] == "violation" assert result["severity"] == "high" assert len(result["violations"]) == 1 assert result["violations"][0]["rule"] == "admin_access_restriction" async def test_monitor_rate_limit_violation(self, policy_monitor, action_context): """Test monitoring rate limit violation.""" # Add multiple violations for the same actor for i in range(5): violation_context = ActionContext( action_id=f"action_{i}", actor_id="rate_limit_user", action_type="api_call" ) # Manually add violations to history policy_monitor.violation_history.append({ "type": "violation", "severity": "low", "actor_id": "rate_limit_user", "action_id": f"action_{i}", "timestamp": datetime.utcnow().isoformat() }) # Test rate limit violation result = await policy_monitor(action_context) # Should not trigger rate limit for different actor assert result is None # Test with same actor rate_limit_context = ActionContext( action_id="rate_limit_action", actor_id="rate_limit_user", action_type="api_call" ) result = await policy_monitor(rate_limit_context) assert result is not None assert result["type"] == "violation" assert result["severity"] == "medium" assert len(result["violations"]) == 1 assert result["violations"][0]["rule"] == "rate_limit_exceeded" async def test_monitor_sensitive_resource_violation(self, policy_monitor, action_context): """Test monitoring sensitive resource access violation.""" sensitive_context = ActionContext( action_id="sensitive_action", actor_id="unauthorized_user", action_type="data_access", resource_id="sensitive_data", metadata={"authorized": False} ) result = await policy_monitor(sensitive_context) assert result is not None assert result["type"] == "violation" assert result["severity"] == "critical" assert len(result["violations"]) == 1 assert result["violations"][0]["rule"] == "unauthorized_sensitive_access" def test_assess_violation_severity(self, policy_monitor): """Test violation severity assessment.""" # Test critical severity critical_violations = [{"severity": "critical"}] assert policy_monitor._assess_violation_severity(critical_violations) == "critical" # Test high severity high_violations = [{"severity": "high"}] assert policy_monitor._assess_violation_severity(high_violations) == "high" # Test medium severity medium_violations = [{"severity": "medium"}] assert policy_monitor._assess_violation_severity(medium_violations) == "medium" # Test low severity low_violations = [{"severity": "low"}] assert policy_monitor._assess_violation_severity(low_violations) == "low" # Test mixed severities mixed_violations = [{"severity": "low"}, {"severity": "high"}] assert policy_monitor._assess_violation_severity(mixed_violations) == "high" def test_get_violation_stats(self, policy_monitor): """Test getting violation statistics.""" # Add some violations policy_monitor.violation_history.append({ "type": "violation", "severity": "high", "actor_id": "user1", "action_id": "action1", "timestamp": datetime.utcnow().isoformat() }) policy_monitor.actor_violations["user1"] = 1 policy_monitor.actor_violations["user2"] = 2 stats = policy_monitor.get_violation_stats() assert stats["total_violations"] == 1 assert stats["actor_violations"]["user1"] == 1 assert stats["actor_violations"]["user2"] == 2 assert "recent_violations" in stats
class TestLedgerMonitor: """Test the LedgerMonitor class.""" @pytest.fixture def ledger_monitor(self): """Create a ledger monitor for testing.""" return LedgerMonitor() @pytest.fixture def mock_ledger(self): """Create a mock ledger for testing.""" mock_ledger = Mock() mock_ledger.verify_chain_integrity.return_value = True mock_ledger.get_ledger_statistics.return_value = { "total_entries": 10, "total_blocks": 2 } return mock_ledger @pytest.fixture def action_context(self): """Create an action context for testing.""" return ActionContext( action_id="test_action", actor_id="test_user", action_type="tool_call" ) async def test_monitor_no_issues(self, ledger_monitor, mock_ledger, action_context): """Test monitoring with no ledger issues.""" ledger_monitor.ledger = mock_ledger result = await ledger_monitor(action_context) assert result is None async def test_monitor_chain_integrity_issue(self, ledger_monitor, mock_ledger, action_context): """Test monitoring chain integrity issue.""" # Mock chain integrity failure mock_ledger.verify_chain_integrity.return_value = False ledger_monitor.ledger = mock_ledger result = await ledger_monitor(action_context) assert result is not None assert result["type"] == "anomaly" assert result["severity"] == "critical" assert len(result["issues"]) == 1 assert result["issues"][0]["type"] == "chain_integrity" async def test_monitor_missing_blocks_issue(self, ledger_monitor, mock_ledger, action_context): """Test monitoring missing blocks issue.""" # Mock missing blocks scenario mock_ledger.get_ledger_statistics.return_value = { "total_entries": 10, "total_blocks": 0 } ledger_monitor.ledger = mock_ledger result = await ledger_monitor(action_context) assert result is not None assert result["type"] == "anomaly" assert result["severity"] == "high" assert len(result["issues"]) == 1 assert result["issues"][0]["type"] == "missing_blocks" async def test_monitor_integrity_check_error(self, ledger_monitor, action_context): """Test monitoring with integrity check error.""" # Mock ledger that raises exception mock_ledger = Mock() mock_ledger.verify_chain_integrity.side_effect = Exception("Database error") ledger_monitor.ledger = mock_ledger result = await ledger_monitor(action_context) assert result is not None assert result["type"] == "anomaly" assert result["severity"] == "medium" assert len(result["issues"]) == 1 assert result["issues"][0]["type"] == "integrity_check_error" def test_assess_integrity_severity(self, ledger_monitor): """Test integrity severity assessment.""" # Test critical severity critical_issues = [{"severity": "critical"}] assert ledger_monitor._assess_integrity_severity(critical_issues) == "critical" # Test high severity high_issues = [{"severity": "high"}] assert ledger_monitor._assess_integrity_severity(high_issues) == "high" # Test medium severity medium_issues = [{"severity": "medium"}] assert ledger_monitor._assess_integrity_severity(medium_issues) == "medium" # Test low severity low_issues = [{"severity": "low"}] assert ledger_monitor._assess_integrity_severity(low_issues) == "low" def test_get_integrity_stats(self, ledger_monitor): """Test getting integrity statistics.""" # Add some integrity checks ledger_monitor.integrity_checks.append({ "type": "anomaly", "severity": "high", "timestamp": datetime.utcnow().isoformat() }) stats = ledger_monitor.get_integrity_stats() assert stats["total_checks"] == 1 assert "recent_issues" in stats
class TestAnomalyDetector: """Test the AnomalyDetector class.""" @pytest.fixture def anomaly_detector(self): """Create an anomaly detector for testing.""" return AnomalyDetector() @pytest.fixture def action_context(self): """Create an action context for testing.""" return ActionContext( action_id="test_action", actor_id="test_user", action_type="tool_call", resource_id="test_resource" ) async def test_detector_no_anomalies(self, anomaly_detector, action_context): """Test detection with no anomalies.""" # First access to a resource will be flagged as new resource access # So we need to access the resource twice to avoid the "new resource" anomaly await anomaly_detector(action_context) result = await anomaly_detector(action_context) assert result is None async def test_detector_high_frequency_anomaly(self, anomaly_detector, action_context): """Test detection of high frequency anomaly.""" # Add many recent actions for the same actor for i in range(25): recent_context = ActionContext( action_id=f"action_{i}", actor_id="high_frequency_user", action_type="api_call" ) anomaly_detector._update_patterns(recent_context) # Test high frequency detection high_freq_context = ActionContext( action_id="high_freq_action", actor_id="high_frequency_user", action_type="api_call" ) result = await anomaly_detector(high_freq_context) assert result is not None assert result["type"] == "anomaly" assert result["severity"] == "medium" assert len(result["anomalies"]) == 1 assert result["anomalies"][0]["type"] == "high_frequency" async def test_detector_unusual_timing_anomaly(self, anomaly_detector, action_context): """Test detection of unusual timing anomaly.""" # Create action at unusual hour with new action type unusual_context = ActionContext( action_id="unusual_action", actor_id="test_user", action_type="new_action_type" # New action type ) unusual_context.timestamp = datetime.utcnow().replace(hour=3) # 3 AM result = await anomaly_detector(unusual_context) assert result is not None assert result["type"] == "anomaly" assert result["severity"] == "low" assert len(result["anomalies"]) == 1 assert result["anomalies"][0]["type"] == "unusual_timing" async def test_detector_new_resource_access_anomaly(self, anomaly_detector, action_context): """Test detection of new resource access anomaly.""" # First access to a resource new_resource_context = ActionContext( action_id="new_resource_action", actor_id="test_user", action_type="data_access", resource_id="new_resource" ) result = await anomaly_detector(new_resource_context) assert result is not None assert result["type"] == "anomaly" assert result["severity"] == "low" assert len(result["anomalies"]) == 1 assert result["anomalies"][0]["type"] == "new_resource_access" async def test_detector_privilege_escalation_anomaly(self, anomaly_detector, action_context): """Test detection of privilege escalation anomaly.""" # First time performing privileged action privilege_context = ActionContext( action_id="privilege_action", actor_id="test_user", action_type="admin_access", resource_id="admin_panel" ) result = await anomaly_detector(privilege_context) assert result is not None assert result["type"] == "anomaly" assert result["severity"] == "high" # Should detect both new resource access and privilege escalation assert len(result["anomalies"]) >= 1 # Check that privilege escalation is detected privilege_anomalies = [a for a in result["anomalies"] if a["type"] == "privilege_escalation"] assert len(privilege_anomalies) == 1 assert privilege_anomalies[0]["type"] == "privilege_escalation" def test_update_patterns(self, anomaly_detector, action_context): """Test pattern updating.""" # Update patterns anomaly_detector._update_patterns(action_context) # Check that patterns were updated actor_data = anomaly_detector.actor_patterns[action_context.actor_id] assert actor_data["action_counts"][action_context.action_type] == 1 assert actor_data["resource_access"][action_context.resource_id] == 1 assert len(actor_data["session_times"]) == 1 assert actor_data["last_seen"] == action_context.timestamp # Check global patterns assert anomaly_detector.global_patterns["action_frequency"][action_context.action_type] == 1 assert anomaly_detector.global_patterns["resource_access"][action_context.resource_id] == 1 def test_assess_anomaly_severity(self, anomaly_detector): """Test anomaly severity assessment.""" # Test high severity high_anomalies = [{"severity": "high"}] assert anomaly_detector._assess_anomaly_severity(high_anomalies) == "high" # Test medium severity medium_anomalies = [{"severity": "medium"}] assert anomaly_detector._assess_anomaly_severity(medium_anomalies) == "medium" # Test low severity low_anomalies = [{"severity": "low"}] assert anomaly_detector._assess_anomaly_severity(low_anomalies) == "low" # Test mixed severities mixed_anomalies = [{"severity": "low"}, {"severity": "high"}] assert anomaly_detector._assess_anomaly_severity(mixed_anomalies) == "high" def test_get_anomaly_stats(self, anomaly_detector, action_context): """Test getting anomaly statistics.""" # Update patterns for some actors anomaly_detector._update_patterns(action_context) another_context = ActionContext( action_id="another_action", actor_id="another_user", action_type="another_type" ) anomaly_detector._update_patterns(another_context) stats = anomaly_detector.get_anomaly_stats() assert stats["tracked_actors"] == 2 assert stats["global_action_types"] == 2 assert stats["global_resources"] == 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320"""Tests for the reflexive engine."""
import pytestfrom datetime import datetimefrom unittest.mock import Mock, AsyncMock
from fastmcp.reflexive import ReflexiveEngine, ActionContext, DecisionType, RiskLevelfrom fastmcp.reflexive.engine import ReflexiveDecision
class TestReflexiveEngine: """Test the reflexive engine functionality.""" @pytest.fixture def reflexive_engine(self): """Create a reflexive engine for testing.""" return ReflexiveEngine() @pytest.fixture def action_context(self): """Create an action context for testing.""" return ActionContext( action_id="test_action_123", actor_id="test_user", action_type="tool_call", resource_id="test_resource", metadata={"test": "data"} ) def test_engine_initialization(self, reflexive_engine): """Test reflexive engine initialization.""" assert reflexive_engine.policy_engine is None assert reflexive_engine.ledger is None assert len(reflexive_engine.monitors) == 0 assert len(reflexive_engine.decision_handlers) == 4 assert not reflexive_engine.is_running def test_engine_status(self, reflexive_engine): """Test getting engine status.""" status = reflexive_engine.get_engine_status() assert "is_running" in status assert "monitor_count" in status assert "queue_size" in status assert "decision_handlers" in status assert status["is_running"] is False assert status["monitor_count"] == 0 assert len(status["decision_handlers"]) == 4 def test_add_remove_monitor(self, reflexive_engine): """Test adding and removing monitors.""" def test_monitor(context): return None # Add monitor reflexive_engine.add_monitor(test_monitor) assert len(reflexive_engine.monitors) == 1 assert test_monitor in reflexive_engine.monitors # Remove monitor reflexive_engine.remove_monitor(test_monitor) assert len(reflexive_engine.monitors) == 0 assert test_monitor not in reflexive_engine.monitors async def test_submit_action(self, reflexive_engine, action_context): """Test submitting an action for evaluation.""" await reflexive_engine.submit_action(action_context) # Check that action was added to queue assert reflexive_engine.event_queue.qsize() == 1 async def test_evaluate_action_no_violations(self, reflexive_engine, action_context): """Test evaluating an action with no violations.""" decision = await reflexive_engine._evaluate_action(action_context) assert decision.decision_type == DecisionType.ALLOW assert decision.risk_level == RiskLevel.LOW assert decision.reason == "No violations or anomalies detected" assert decision.action_context == action_context assert decision.proof_hash is not None async def test_evaluate_action_with_violations(self, reflexive_engine, action_context): """Test evaluating an action with violations.""" # Add a monitor that returns violations def violation_monitor(context): return { "type": "violation", "severity": "high", "violations": [{"rule": "test_rule", "message": "Test violation", "severity": "high"}] } reflexive_engine.add_monitor(violation_monitor) decision = await reflexive_engine._evaluate_action(action_context) assert decision.decision_type == DecisionType.HALT assert decision.risk_level == RiskLevel.HIGH assert "violations" in decision.evidence assert len(decision.evidence["violations"]) == 1 async def test_evaluate_action_with_anomalies(self, reflexive_engine, action_context): """Test evaluating an action with anomalies.""" # Add a monitor that returns anomalies def anomaly_monitor(context): return { "type": "anomaly", "severity": "medium", "anomalies": [{"type": "test_anomaly", "message": "Test anomaly", "severity": "medium"}] } reflexive_engine.add_monitor(anomaly_monitor) decision = await reflexive_engine._evaluate_action(action_context) assert decision.decision_type == DecisionType.ESCALATE assert decision.risk_level == RiskLevel.MEDIUM assert "anomalies" in decision.evidence assert len(decision.evidence["anomalies"]) == 1 async def test_evaluate_action_critical_violation(self, reflexive_engine, action_context): """Test evaluating an action with critical violations.""" # Add a monitor that returns critical violations def critical_monitor(context): return { "type": "violation", "severity": "critical", "violations": [{"rule": "critical_rule", "message": "Critical violation", "severity": "critical"}] } reflexive_engine.add_monitor(critical_monitor) decision = await reflexive_engine._evaluate_action(action_context) assert decision.decision_type == DecisionType.HALT assert decision.risk_level == RiskLevel.CRITICAL async def test_simulate_risk(self, reflexive_engine): """Test risk simulation.""" risk_scenario = { "action_context": { "action_id": "simulation_action", "actor_id": "test_actor", "action_type": "admin_access", "resource_id": "sensitive_data" }, "monitors": [ lambda ctx: { "type": "violation", "severity": "high", "violations": [{"rule": "admin_restriction", "message": "Unauthorized admin access", "severity": "high"}] } ] } decision = await reflexive_engine.simulate_risk(risk_scenario) assert decision.decision_type == DecisionType.HALT assert decision.risk_level == RiskLevel.HIGH assert decision.action_context.action_id == "simulation_action" def test_assess_risk_level(self, reflexive_engine): """Test risk level assessment.""" # Test critical risk critical_violations = [{"severity": "critical"}] assert reflexive_engine._assess_risk_level(critical_violations, []) == RiskLevel.CRITICAL # Test high risk high_violations = [{"severity": "high"}] assert reflexive_engine._assess_risk_level(high_violations, []) == RiskLevel.HIGH # Test medium risk medium_violations = [{"severity": "medium"}] assert reflexive_engine._assess_risk_level(medium_violations, []) == RiskLevel.MEDIUM # Test low risk low_violations = [{"severity": "low"}] assert reflexive_engine._assess_risk_level(low_violations, []) == RiskLevel.LOW # Test multiple issues multiple_issues = [{"severity": "low"}, {"severity": "low"}, {"severity": "low"}] assert reflexive_engine._assess_risk_level(multiple_issues, []) == RiskLevel.MEDIUM def test_determine_escalation_target(self, reflexive_engine): """Test escalation target determination.""" decision = ReflexiveDecision( decision_type=DecisionType.ESCALATE, risk_level=RiskLevel.CRITICAL, action_context=ActionContext(action_id="test", actor_id="test", action_type="test"), reason="Test" ) target = reflexive_engine._determine_escalation_target(decision) assert target == "security_admin" decision.risk_level = RiskLevel.HIGH target = reflexive_engine._determine_escalation_target(decision) assert target == "system_admin" decision.risk_level = RiskLevel.MEDIUM target = reflexive_engine._determine_escalation_target(decision) assert target == "monitoring_team"
class TestActionContext: """Test the ActionContext class.""" def test_action_context_creation(self): """Test creating an action context.""" context = ActionContext( action_id="test_action", actor_id="test_actor", action_type="test_type" ) assert context.action_id == "test_action" assert context.actor_id == "test_actor" assert context.action_type == "test_type" assert context.resource_id is None assert context.metadata == {} assert isinstance(context.timestamp, datetime) def test_action_context_hash(self): """Test action context hash generation.""" context1 = ActionContext( action_id="test_action", actor_id="test_actor", action_type="test_type", metadata={"key": "value"} ) context2 = ActionContext( action_id="test_action", actor_id="test_actor", action_type="test_type", metadata={"key": "value"} ) # Same content should produce same hash assert context1.get_context_hash() == context2.get_context_hash() # Different content should produce different hash context3 = ActionContext( action_id="different_action", actor_id="test_actor", action_type="test_type", metadata={"key": "value"} ) assert context1.get_context_hash() != context3.get_context_hash()
class TestReflexiveDecision: """Test the ReflexiveDecision class.""" def test_decision_creation(self): """Test creating a reflexive decision.""" action_context = ActionContext( action_id="test_action", actor_id="test_actor", action_type="test_type" ) decision = ReflexiveDecision( decision_type=DecisionType.HALT, risk_level=RiskLevel.HIGH, action_context=action_context, reason="Test reason" ) assert decision.decision_type == DecisionType.HALT assert decision.risk_level == RiskLevel.HIGH assert decision.action_context == action_context assert decision.reason == "Test reason" assert decision.evidence == {} assert decision.escalated_to is None assert decision.proof_hash is None assert isinstance(decision.timestamp, datetime) def test_decision_hash(self): """Test decision hash generation.""" from uuid import uuid4 action_context = ActionContext( action_id="test_action", actor_id="test_actor", action_type="test_type" ) # Use the same decision_id for both decisions decision_id = uuid4() decision1 = ReflexiveDecision( decision_id=decision_id, decision_type=DecisionType.HALT, risk_level=RiskLevel.HIGH, action_context=action_context, reason="Test reason" ) decision2 = ReflexiveDecision( decision_id=decision_id, decision_type=DecisionType.HALT, risk_level=RiskLevel.HIGH, action_context=action_context, reason="Test reason" ) # Same content should produce same hash assert decision1.get_decision_hash() == decision2.get_decision_hash() # Different content should produce different hash decision3 = ReflexiveDecision( decision_type=DecisionType.ESCALATE, risk_level=RiskLevel.HIGH, action_context=action_context, reason="Test reason" ) assert decision1.get_decision_hash() != decision3.get_decision_hash()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325"""Tests for the reflexive HTTP endpoints."""
import pytestimport httpxfrom unittest.mock import Mock, AsyncMock
from fastmcp.server.server import FastMCPfrom fastmcp.reflexive import ReflexiveEngine, ActionContext, DecisionType, RiskLevelfrom fastmcp.server.http import create_streamable_http_app
@pytest.fixture(name="server_with_reflexive")async def server_with_reflexive_fixture(): """Fixture for a FastMCP server with an enabled reflexive core.""" server = FastMCP("TestReflexiveServer") reflexive_engine = server.enable_reflexive_core() return server, reflexive_engine
@pytest.fixtureasync def client(server_with_reflexive): """Create an HTTP client for testing.""" server, reflexive_engine = server_with_reflexive app = create_streamable_http_app(server, streamable_http_path="/") async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: # Store server and reflexive engine in client for test access client.server = server client.reflexive_engine = reflexive_engine yield client
class TestReflexiveHTTPEndpoints: """Test the reflexive HTTP endpoints.""" async def test_simulate_risk_endpoint(self, client): """Test the simulate risk endpoint.""" risk_scenario = { "action_context": { "action_id": "test_action", "actor_id": "test_user", "action_type": "admin_access", "resource_id": "admin_panel" }, "scenario_type": "policy_violation" } response = await client.post("/core/simulate-risk", json=risk_scenario) assert response.status_code == 200 data = response.json() assert "simulation_id" in data assert "decision" in data assert "action" in data assert "action_context" in data # Check decision structure decision = data["decision"] assert "decision_id" in decision assert "decision_type" in decision assert "risk_level" in decision assert "reason" in decision assert "proof_hash" in decision # Check action structure action = data["action"] assert "action_id" in action assert "action_type" in action assert "status" in action assert "result" in action async def test_simulate_risk_invalid_data(self, client): """Test simulate risk endpoint with invalid data.""" invalid_scenario = { "invalid_field": "invalid_value" } response = await client.post("/core/simulate-risk", json=invalid_scenario) assert response.status_code == 400 data = response.json() assert "error" in data assert "Missing required field: action_context" in data["error"] async def test_get_engine_status_endpoint(self, client): """Test the get engine status endpoint.""" response = await client.get("/core/status") assert response.status_code == 200 data = response.json() assert "is_running" in data assert "monitor_count" in data assert "queue_size" in data assert "decision_handlers" in data async def test_submit_action_endpoint(self, client): """Test the submit action endpoint.""" action_data = { "action_id": "test_action", "actor_id": "test_user", "action_type": "tool_call", "resource_id": "test_resource", "metadata": {"test": "data"} } response = await client.post("/core/submit-action", json=action_data) assert response.status_code == 202 data = response.json() assert "message" in data assert "action_id" in data assert "submitted_at" in data assert data["action_id"] == "test_action" async def test_submit_action_invalid_data(self, client): """Test submit action endpoint with invalid data.""" invalid_action = { "invalid_field": "invalid_value" } response = await client.post("/core/submit-action", json=invalid_action) assert response.status_code == 400 data = response.json() assert "error" in data assert "Invalid action data" in data["error"] async def test_get_monitor_stats_endpoint(self, client): """Test the get monitor stats endpoint.""" response = await client.get("/core/monitor-stats") assert response.status_code == 200 data = response.json() # Should return empty dict if no monitors are configured assert isinstance(data, dict) async def test_create_risk_scenario_endpoint(self, client): """Test the create risk scenario endpoint.""" scenario_data = { "scenario_name": "admin_privilege_escalation", "scenario_type": "policy_violation", "parameters": { "actor_type": "guest_user", "target_resource": "admin_panel", "severity": "high" } } response = await client.post("/core/risk-scenario", json=scenario_data) assert response.status_code == 200 data = response.json() assert "scenario" in data assert "message" in data assert data["message"] == "Risk scenario 'admin_privilege_escalation' created successfully" # Check scenario structure scenario = data["scenario"] assert "action_context" in scenario assert "expected_decision" in scenario assert "expected_risk_level" in scenario # Check action context action_context = scenario["action_context"] assert action_context["action_type"] == "admin_access" assert action_context["resource_id"] == "admin_panel" async def test_create_risk_scenario_missing_fields(self, client): """Test create risk scenario endpoint with missing fields.""" invalid_scenario = { "scenario_name": "test_scenario" # Missing scenario_type } response = await client.post("/core/risk-scenario", json=invalid_scenario) assert response.status_code == 400 data = response.json() assert "error" in data assert "Missing required fields" in data["error"] async def test_create_risk_scenario_unknown_type(self, client): """Test create risk scenario endpoint with unknown scenario type.""" scenario_data = { "scenario_name": "unknown_scenario", "scenario_type": "unknown_type", "parameters": {} } response = await client.post("/core/risk-scenario", json=scenario_data) assert response.status_code == 200 data = response.json() assert "scenario" in data # Should create a custom scenario scenario = data["scenario"] assert scenario["action_context"]["action_id"] == "custom_unknown_scenario" assert scenario["expected_decision"] == "monitor" assert scenario["expected_risk_level"] == "low" async def test_simulate_risk_with_violations(self, client): """Test simulate risk with policy violations.""" # Add a monitor that returns violations def violation_monitor(context): return { "type": "violation", "severity": "high", "violations": [{"rule": "admin_restriction", "message": "Unauthorized admin access", "severity": "high"}] } client.reflexive_engine.add_monitor(violation_monitor) risk_scenario = { "action_context": { "action_id": "admin_action", "actor_id": "guest_user", "action_type": "admin_access", "resource_id": "admin_panel" } } response = await client.post("/core/simulate-risk", json=risk_scenario) assert response.status_code == 200 data = response.json() # Should result in a halt decision decision = data["decision"] assert decision["decision_type"] == "halt" assert decision["risk_level"] == "high" assert "violations" in decision["evidence"] async def test_simulate_risk_with_anomalies(self, client): """Test simulate risk with anomalies.""" # Add a monitor that returns anomalies def anomaly_monitor(context): return { "type": "anomaly", "severity": "medium", "anomalies": [{"type": "unusual_timing", "message": "Action at unusual hour", "severity": "medium"}] } client.reflexive_engine.add_monitor(anomaly_monitor) risk_scenario = { "action_context": { "action_id": "unusual_action", "actor_id": "test_user", "action_type": "data_access", "resource_id": "sensitive_data" } } response = await client.post("/core/simulate-risk", json=risk_scenario) assert response.status_code == 200 data = response.json() # Should result in an escalate decision decision = data["decision"] assert decision["decision_type"] == "escalate" assert decision["risk_level"] == "medium" assert "anomalies" in decision["evidence"] async def test_simulate_risk_no_issues(self, client): """Test simulate risk with no violations or anomalies.""" risk_scenario = { "action_context": { "action_id": "normal_action", "actor_id": "authorized_user", "action_type": "normal_operation", "resource_id": "public_resource" } } response = await client.post("/core/simulate-risk", json=risk_scenario) assert response.status_code == 200 data = response.json() # Should result in an allow decision decision = data["decision"] assert decision["decision_type"] == "allow" assert decision["risk_level"] == "low" assert decision["reason"] == "No violations or anomalies detected" async def test_multiple_risk_scenarios(self, client): """Test multiple predefined risk scenarios.""" scenarios = [ { "name": "admin_privilege_escalation", "expected_decision": "halt", "expected_risk": "high" }, { "name": "suspicious_activity", "expected_decision": "escalate", "expected_risk": "medium" }, { "name": "integrity_violation", "expected_decision": "halt", "expected_risk": "critical" }, { "name": "rate_limit_exceeded", "expected_decision": "escalate", "expected_risk": "medium" } ] for scenario in scenarios: scenario_data = { "scenario_name": scenario["name"], "scenario_type": "test", "parameters": {} } response = await client.post("/core/risk-scenario", json=scenario_data) assert response.status_code == 200 data = response.json() created_scenario = data["scenario"] assert created_scenario["expected_decision"] == scenario["expected_decision"] assert created_scenario["expected_risk_level"] == scenario["expected_risk"]examples/reflexive_example.pyAdded+191
src/fastmcp/reflexive/__init__.pyAdded+19
src/fastmcp/reflexive/actions.pyAdded+340
src/fastmcp/reflexive/engine.pyAdded+376
src/fastmcp/reflexive/monitor.pyAdded+356
src/fastmcp/server/reflexive_routes.pyAdded+385
src/fastmcp/server/server.py+38
tests/reflexive/__init__.pyAdded+1
tests/reflexive/test_actions.pyAdded+461
tests/reflexive/test_monitors.pyAdded+428
tests/reflexive/test_reflexive_engine.pyAdded+320
tests/reflexive/test_reflexive_http.pyAdded+325