|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT License. |
| 3 | +""" |
| 4 | +Agent Behavior Monitor |
| 5 | +====================== |
| 6 | +
|
| 7 | +Runtime anomaly detection and quarantine for rogue agent behavior. |
| 8 | +Tracks per-agent metrics and triggers alerts or quarantine when |
| 9 | +thresholds are breached. |
| 10 | +
|
| 11 | +Monitored signals: |
| 12 | + - Tool call frequency (burst detection) |
| 13 | + - Consecutive failure rate |
| 14 | + - Capability escalation attempts |
| 15 | + - Trust score manipulation attempts |
| 16 | +
|
| 17 | +Usage:: |
| 18 | +
|
| 19 | + monitor = AgentBehaviorMonitor() |
| 20 | + monitor.record_tool_call("did:mesh:abc", "sql_query", success=True) |
| 21 | + # ... later ... |
| 22 | + if monitor.is_quarantined("did:mesh:abc"): |
| 23 | + raise PermissionError("Agent is quarantined") |
| 24 | +""" |
| 25 | + |
| 26 | +from __future__ import annotations |
| 27 | + |
| 28 | +import logging |
| 29 | +import threading |
| 30 | +from collections import defaultdict |
| 31 | +from dataclasses import dataclass, field |
| 32 | +from datetime import datetime, timedelta |
| 33 | +from typing import Optional |
| 34 | + |
| 35 | +logger = logging.getLogger(__name__) |
| 36 | + |
| 37 | + |
| 38 | +@dataclass |
| 39 | +class AgentMetrics: |
| 40 | + """Rolling metrics for a single agent.""" |
| 41 | + |
| 42 | + agent_did: str |
| 43 | + total_calls: int = 0 |
| 44 | + failed_calls: int = 0 |
| 45 | + consecutive_failures: int = 0 |
| 46 | + capability_denials: int = 0 |
| 47 | + last_activity: Optional[datetime] = None |
| 48 | + quarantined: bool = False |
| 49 | + quarantine_reason: Optional[str] = None |
| 50 | + quarantined_at: Optional[datetime] = None |
| 51 | + # Rolling window for burst detection |
| 52 | + call_timestamps: list[datetime] = field(default_factory=list) |
| 53 | + |
| 54 | + |
| 55 | +class AgentBehaviorMonitor: |
| 56 | + """Monitors agent behavior and quarantines anomalous agents. |
| 57 | +
|
| 58 | + Args: |
| 59 | + burst_window_seconds: Time window for burst detection. |
| 60 | + burst_threshold: Max calls in the burst window before alert. |
| 61 | + consecutive_failure_threshold: Failures in a row before quarantine. |
| 62 | + capability_denial_threshold: Denied capability checks before quarantine. |
| 63 | + quarantine_duration: How long an auto-quarantine lasts. |
| 64 | + max_tracked_agents: Evict oldest agents beyond this limit. |
| 65 | + """ |
| 66 | + |
| 67 | + def __init__( |
| 68 | + self, |
| 69 | + burst_window_seconds: int = 60, |
| 70 | + burst_threshold: int = 100, |
| 71 | + consecutive_failure_threshold: int = 20, |
| 72 | + capability_denial_threshold: int = 10, |
| 73 | + quarantine_duration: timedelta = timedelta(minutes=15), |
| 74 | + max_tracked_agents: int = 50_000, |
| 75 | + ) -> None: |
| 76 | + self._agents: dict[str, AgentMetrics] = {} |
| 77 | + self._lock = threading.Lock() |
| 78 | + self._burst_window = timedelta(seconds=burst_window_seconds) |
| 79 | + self._burst_threshold = burst_threshold |
| 80 | + self._consecutive_failure_threshold = consecutive_failure_threshold |
| 81 | + self._capability_denial_threshold = capability_denial_threshold |
| 82 | + self._quarantine_duration = quarantine_duration |
| 83 | + self._max_tracked = max_tracked_agents |
| 84 | + |
| 85 | + def _get_metrics(self, agent_did: str) -> AgentMetrics: |
| 86 | + with self._lock: |
| 87 | + if agent_did not in self._agents: |
| 88 | + if len(self._agents) >= self._max_tracked: |
| 89 | + oldest = min( |
| 90 | + self._agents, |
| 91 | + key=lambda d: self._agents[d].last_activity or datetime.min, |
| 92 | + ) |
| 93 | + del self._agents[oldest] |
| 94 | + self._agents[agent_did] = AgentMetrics(agent_did=agent_did) |
| 95 | + return self._agents[agent_did] |
| 96 | + |
| 97 | + def record_tool_call( |
| 98 | + self, |
| 99 | + agent_did: str, |
| 100 | + tool_name: str, |
| 101 | + *, |
| 102 | + success: bool, |
| 103 | + ) -> None: |
| 104 | + """Record a tool invocation and check for anomalies.""" |
| 105 | + m = self._get_metrics(agent_did) |
| 106 | + now = datetime.utcnow() |
| 107 | + m.total_calls += 1 |
| 108 | + m.last_activity = now |
| 109 | + |
| 110 | + if success: |
| 111 | + m.consecutive_failures = 0 |
| 112 | + else: |
| 113 | + m.failed_calls += 1 |
| 114 | + m.consecutive_failures += 1 |
| 115 | + if m.consecutive_failures >= self._consecutive_failure_threshold: |
| 116 | + self._quarantine( |
| 117 | + agent_did, |
| 118 | + f"Consecutive failure threshold breached " |
| 119 | + f"({m.consecutive_failures} failures)", |
| 120 | + ) |
| 121 | + |
| 122 | + # Burst detection |
| 123 | + cutoff = now - self._burst_window |
| 124 | + m.call_timestamps = [t for t in m.call_timestamps if t > cutoff] |
| 125 | + m.call_timestamps.append(now) |
| 126 | + if len(m.call_timestamps) > self._burst_threshold: |
| 127 | + self._quarantine( |
| 128 | + agent_did, |
| 129 | + f"Burst threshold breached ({len(m.call_timestamps)} calls " |
| 130 | + f"in {self._burst_window.total_seconds()}s)", |
| 131 | + ) |
| 132 | + |
| 133 | + def record_capability_denial(self, agent_did: str, capability: str) -> None: |
| 134 | + """Record a denied capability check (possible privilege escalation).""" |
| 135 | + m = self._get_metrics(agent_did) |
| 136 | + m.capability_denials += 1 |
| 137 | + if m.capability_denials >= self._capability_denial_threshold: |
| 138 | + self._quarantine( |
| 139 | + agent_did, |
| 140 | + f"Capability denial threshold breached " |
| 141 | + f"({m.capability_denials} denials, last: {capability})", |
| 142 | + ) |
| 143 | + |
| 144 | + def _quarantine(self, agent_did: str, reason: str) -> None: |
| 145 | + m = self._get_metrics(agent_did) |
| 146 | + if m.quarantined: |
| 147 | + return # already quarantined |
| 148 | + m.quarantined = True |
| 149 | + m.quarantine_reason = reason |
| 150 | + m.quarantined_at = datetime.utcnow() |
| 151 | + logger.warning("QUARANTINE agent %s: %s", agent_did, reason) |
| 152 | + |
| 153 | + def is_quarantined(self, agent_did: str) -> bool: |
| 154 | + """Check if an agent is currently quarantined.""" |
| 155 | + m = self._agents.get(agent_did) |
| 156 | + if not m or not m.quarantined: |
| 157 | + return False |
| 158 | + # Auto-release after quarantine duration |
| 159 | + if m.quarantined_at and datetime.utcnow() - m.quarantined_at > self._quarantine_duration: |
| 160 | + self.release_quarantine(agent_did) |
| 161 | + return False |
| 162 | + return True |
| 163 | + |
| 164 | + def release_quarantine(self, agent_did: str) -> None: |
| 165 | + """Manually release an agent from quarantine.""" |
| 166 | + m = self._agents.get(agent_did) |
| 167 | + if m: |
| 168 | + m.quarantined = False |
| 169 | + m.quarantine_reason = None |
| 170 | + m.quarantined_at = None |
| 171 | + m.consecutive_failures = 0 |
| 172 | + m.capability_denials = 0 |
| 173 | + logger.info("Released agent %s from quarantine", agent_did) |
| 174 | + |
| 175 | + def get_metrics(self, agent_did: str) -> Optional[AgentMetrics]: |
| 176 | + """Get current metrics for an agent (read-only snapshot).""" |
| 177 | + return self._agents.get(agent_did) |
| 178 | + |
| 179 | + def get_quarantined_agents(self) -> list[AgentMetrics]: |
| 180 | + """List all currently quarantined agents.""" |
| 181 | + return [m for m in self._agents.values() if m.quarantined] |
0 commit comments