manatrix/pentest/human_in_loop.py

pentest / human_in_loop.py

pentest/human_in_loop.py · 56.8 KB

"""
Human-in-the-Loop Collaboration Interface

Provides a structured interface for human experts to review, approve, override,
and guide AI decisions during penetration testing operations. Supports multiple
collaboration modes (advisory, approval, full-control) and provides clear
interfaces for human feedback.

Key components:
- ReviewRequest: A pending decision awaiting human review
- HumanFeedback: Human's response to a review request
- ApprovalRule: Rules for when human review is required
- HumanInTheLoop: Central manager for human-AI collaboration
- HumanDashboard: Simple CLI interface for human operators
"""

import logging
import queue
import threading
import time
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing import Any, Callable, Dict, List, Optional, Tuple

logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
# Enums
# ---------------------------------------------------------------------------

class CollaborationMode(Enum):
    """Collaboration modes for human-AI interaction.

    - ADVISORY: AI operates autonomously, human provides guidance when asked
    - APPROVAL: AI requires human approval for certain actions
    - FULL_CONTROL: AI suggests, human decides on all actions
    """
    ADVISORY = "advisory"
    APPROVAL = "approval"
    FULL_CONTROL = "full-control"


class DecisionType(Enum):
    """Types of decisions that may require human review."""
    EXPLOIT = "exploit"
    LATERAL_MOVE = "lateral_move"
    CREDENTIAL_DUMP = "credential_dump"
    PRIVILEGE_ESCALATION = "privilege_escalation"
    PERSISTENCE = "persistence"
    DATA_EXFILTRATION = "data_exfiltration"
    SOCIAL_ENGINEERING = "social_engineering"
    DENIAL_OF_SERVICE = "denial_of_service"
    TOOL_EXECUTION = "tool_execution"
    TARGET_SELECTION = "target_selection"
    CUSTOM = "custom"


class UrgencyLevel(Enum):
    """Urgency levels for review requests."""
    CRITICAL = "critical"
    HIGH = "high"
    MEDIUM = "medium"
    LOW = "low"


class ReviewStatus(Enum):
    """Status of a review request."""
    PENDING = "pending"
    APPROVED = "approved"
    REJECTED = "rejected"
    MODIFIED = "modified"
    ESCALATED = "escalated"
    TIMEOUT = "timeout"


class FeedbackType(Enum):
    """Types of human feedback."""
    APPROVE = "approve"
    REJECT = "reject"
    MODIFY = "modify"
    ASK_MORE = "ask_more"
    DELEGATE = "delegate"
    ESCALATE = "escalate"


class ApprovalLevel(Enum):
    """Levels of approval scrutiny."""
    BRIEF = "brief"           # Quick review, minimal context
    NORMAL = "normal"         # Standard review with context
    ELEVATED = "elevated"     # Detailed review with risk assessment
    EXTREME = "extreme"       # Full review with multiple approvers


# ---------------------------------------------------------------------------
# Dataclasses
# ---------------------------------------------------------------------------

@dataclass
class ReviewRequest:
    """A pending decision awaiting human review.

    Represents a single decision point where human input is needed.
    Contains all context necessary for an informed decision.

    Attributes:
        request_id: Unique identifier for this request.
        timestamp: Unix timestamp when the request was created.
        decision_type: Category of the decision (exploit/lateral_move/etc.).
        context: Relevant state and reasoning at decision time.
        reasoning: AI's explanation for the recommended action.
        confidence: AI's confidence score for the recommendation [0,1].
        recommended_action: The action the AI recommends taking.
        alternatives: Other options considered by the AI.
        urgency: Urgency level (critical/high/medium/low).
        status: Current status of the review request.
        metadata: Additional structured data.
    """
    request_id: str
    timestamp: float
    decision_type: str
    context: Dict[str, Any] = field(default_factory=dict)
    reasoning: str = ""
    confidence: float = 0.0
    recommended_action: Dict[str, Any] = field(default_factory=dict)
    alternatives: List[Dict[str, Any]] = field(default_factory=list)
    urgency: str = "medium"
    status: str = "pending"
    metadata: Dict[str, Any] = field(default_factory=dict)

    def __post_init__(self):
        """Validate and normalize fields after initialization."""
        if not self.request_id:
            self.request_id = str(uuid.uuid4())
        if not self.timestamp:
            self.timestamp = time.time()
        # Normalize urgency to lowercase
        if isinstance(self.urgency, str):
            self.urgency = self.urgency.lower()
        if isinstance(self.status, str):
            self.status = self.status.lower()

    def to_dict(self) -> dict:
        """Serialize to a plain dictionary."""
        return {
            "request_id": self.request_id,
            "timestamp": self.timestamp,
            "timestamp_iso": datetime.fromtimestamp(
                self.timestamp, tz=timezone.utc
            ).isoformat(),
            "decision_type": self.decision_type,
            "context": self.context,
            "reasoning": self.reasoning,
            "confidence": self.confidence,
            "recommended_action": self.recommended_action,
            "alternatives": self.alternatives,
            "urgency": self.urgency,
            "status": self.status,
            "metadata": self.metadata,
        }

    @classmethod
    def from_dict(cls, data: dict) -> "ReviewRequest":
        """Reconstruct a ReviewRequest from a dictionary."""
        return cls(
            request_id=data.get("request_id", str(uuid.uuid4())),
            timestamp=float(data.get("timestamp", time.time())),
            decision_type=data.get("decision_type", "custom"),
            context=data.get("context", {}),
            reasoning=data.get("reasoning", ""),
            confidence=float(data.get("confidence", 0.0)),
            recommended_action=data.get("recommended_action", {}),
            alternatives=data.get("alternatives", []),
            urgency=data.get("urgency", "medium"),
            status=data.get("status", "pending"),
            metadata=data.get("metadata", {}),
        )

    def is_pending(self) -> bool:
        """Check if this request is still pending review."""
        return self.status == "pending"

    def get_age_seconds(self) -> float:
        """Get the age of this request in seconds."""
        return time.time() - self.timestamp


@dataclass
class HumanFeedback:
    """Human's response to a review request.

    Captures the human operator's decision, rationale, and any
    modifications to the proposed action.

    Attributes:
        request_id: ID of the ReviewRequest this feedback addresses.
        feedback_type: Type of feedback (approve/reject/modify/ask_more).
        decision: The action to take (approved/rejected/modified).
        rationale: Human's reasoning for the decision.
        modifications: If modified, the changes made to the action.
        timestamp: When the feedback was submitted.
        operator_id: ID of the human operator who provided feedback.
    """
    request_id: str
    feedback_type: str
    decision: Dict[str, Any] = field(default_factory=dict)
    rationale: str = ""
    modifications: Optional[Dict[str, Any]] = None
    timestamp: float = field(default_factory=time.time)
    operator_id: str = ""

    def __post_init__(self):
        """Normalize fields after initialization."""
        if isinstance(self.feedback_type, str):
            self.feedback_type = self.feedback_type.lower()

    def to_dict(self) -> dict:
        """Serialize to a plain dictionary."""
        return {
            "request_id": self.request_id,
            "feedback_type": self.feedback_type,
            "decision": self.decision,
            "rationale": self.rationale,
            "modifications": self.modifications,
            "timestamp": self.timestamp,
            "timestamp_iso": datetime.fromtimestamp(
                self.timestamp, tz=timezone.utc
            ).isoformat(),
            "operator_id": self.operator_id,
        }

    @classmethod
    def from_dict(cls, data: dict) -> "HumanFeedback":
        """Reconstruct HumanFeedback from a dictionary."""
        return cls(
            request_id=data["request_id"],
            feedback_type=data.get("feedback_type", "approve"),
            decision=data.get("decision", {}),
            rationale=data.get("rationale", ""),
            modifications=data.get("modifications"),
            timestamp=float(data.get("timestamp", time.time())),
            operator_id=data.get("operator_id", ""),
        )

    def is_approval(self) -> bool:
        """Check if this is an approval."""
        return self.feedback_type == "approve"

    def is_rejection(self) -> bool:
        """Check if this is a rejection."""
        return self.feedback_type == "reject"

    def is_modification(self) -> bool:
        """Check if this includes modifications."""
        return self.feedback_type == "modify" and self.modifications is not None


@dataclass
class ApprovalRule:
    """Rules for when human review is required.

    Defines conditions under which human approval must be obtained
    before an action can proceed.

    Attributes:
        rule_id: Unique identifier for this rule.
        trigger_condition: Condition expression (e.g., "action_type=='exploit' AND severity>7").
        approval_level: Level of scrutiny required (brief/normal/elevated/extreme).
        auto_approve_threshold: Confidence above which no review is needed.
        timeout_seconds: If no response, use default action after this time.
        default_action: Default action on timeout (proceed/abort/ask_again).
        enabled: Whether this rule is active.
        description: Human-readable description of the rule.
    """
    rule_id: str
    trigger_condition: str
    approval_level: str = "normal"
    auto_approve_threshold: float = 0.95
    timeout_seconds: int = 300  # 5 minutes
    default_action: str = "abort"
    enabled: bool = True
    description: str = ""

    def __post_init__(self):
        """Generate rule_id if not provided."""
        if not self.rule_id:
            self.rule_id = str(uuid.uuid4())[:8]
        # Normalize values
        if isinstance(self.approval_level, str):
            self.approval_level = self.approval_level.lower()
        if isinstance(self.default_action, str):
            self.default_action = self.default_action.lower()

    def to_dict(self) -> dict:
        """Serialize to a plain dictionary."""
        return {
            "rule_id": self.rule_id,
            "trigger_condition": self.trigger_condition,
            "approval_level": self.approval_level,
            "auto_approve_threshold": self.auto_approve_threshold,
            "timeout_seconds": self.timeout_seconds,
            "default_action": self.default_action,
            "enabled": self.enabled,
            "description": self.description,
        }

    @classmethod
    def from_dict(cls, data: dict) -> "ApprovalRule":
        """Reconstruct ApprovalRule from a dictionary."""
        return cls(
            rule_id=data.get("rule_id", ""),
            trigger_condition=data.get("trigger_condition", ""),
            approval_level=data.get("approval_level", "normal"),
            auto_approve_threshold=float(data.get("auto_approve_threshold", 0.95)),
            timeout_seconds=int(data.get("timeout_seconds", 300)),
            default_action=data.get("default_action", "abort"),
            enabled=bool(data.get("enabled", True)),
            description=data.get("description", ""),
        )

    def evaluate_condition(self, decision: dict) -> bool:
        """Evaluate whether this rule's trigger condition is met.

        Simple expression evaluator for common conditions.
        Supports: AND, OR, ==, !=, >, <, >=, <=, in, not in

        Args:
            decision: The decision dict to evaluate against.

        Returns:
            True if the trigger condition is met.
        """
        if not self.trigger_condition or not self.enabled:
            return False

        try:
            # Simple condition parser
            condition = self.trigger_condition.strip()

            # Handle AND/OR combinations
            if " AND " in condition.upper():
                parts = self._split_by_operator(condition, "AND")
                return all(self._evaluate_simple(p.strip(), decision) for p in parts)

            if " OR " in condition.upper():
                parts = self._split_by_operator(condition, "OR")
                return any(self._evaluate_simple(p.strip(), decision) for p in parts)

            return self._evaluate_simple(condition, decision)

        except Exception as e:
            logger.warning(
                "Failed to evaluate condition '%s': %s",
                self.trigger_condition,
                e,
            )
            return False

    def _split_by_operator(self, condition: str, operator: str) -> List[str]:
        """Split condition by logical operator (preserving quoted strings)."""
        result = []
        current = ""
        in_quotes = False
        upper_cond = condition.upper()
        op_upper = f" {operator} "

        i = 0
        while i < len(condition):
            if condition[i] in ('"', "'"):
                in_quotes = not in_quotes
                current += condition[i]
            elif not in_quotes and upper_cond[i:].startswith(op_upper):
                result.append(current.strip())
                current = ""
                i += len(op_upper)
                continue
            else:
                current += condition[i]
            i += 1

        if current.strip():
            result.append(current.strip())

        return result

    def _evaluate_simple(self, condition: str, decision: dict) -> bool:
        """Evaluate a simple comparison condition."""
        # Parse comparison operators
        operators = ["==", "!=", ">=", "<=", ">", "<", " in ", " not in "]

        for op in operators:
            if op in condition:
                parts = condition.split(op, 1)
                if len(parts) != 2:
                    continue

                left = parts[0].strip()
                right = parts[1].strip()

                # Get left value from decision
                left_val = self._get_value(left, decision)
                right_val = self._parse_value(right)

                # Perform comparison
                op_clean = op.strip()
                if op_clean == "==":
                    return left_val == right_val
                elif op_clean == "!=":
                    return left_val != right_val
                elif op_clean == ">":
                    return left_val > right_val
                elif op_clean == "<":
                    return left_val < right_val
                elif op_clean == ">=":
                    return left_val >= right_val
                elif op_clean == "<=":
                    return left_val <= right_val
                elif op_clean == "in":
                    return left_val in right_val
                elif op_clean == "not in":
                    return left_val not in right_val

        return False

    def _get_value(self, key: str, decision: dict) -> Any:
        """Get a value from the decision dict by key name."""
        # Handle nested keys with dot notation
        if "." in key:
            parts = key.split(".")
            val = decision
            for part in parts:
                if isinstance(val, dict):
                    val = val.get(part)
                else:
                    return None
            return val
        return decision.get(key)

    def _parse_value(self, value_str: str) -> Any:
        """Parse a value string into the appropriate Python type."""
        value_str = value_str.strip()

        # String (quoted)
        if (value_str.startswith('"') and value_str.endswith('"')) or \
           (value_str.startswith("'") and value_str.endswith("'")):
            return value_str[1:-1]

        # List
        if value_str.startswith("[") and value_str.endswith("]"):
            inner = value_str[1:-1].strip()
            if not inner:
                return []
            items = [self._parse_value(i.strip()) for i in inner.split(",")]
            return items

        # Boolean
        if value_str.lower() == "true":
            return True
        if value_str.lower() == "false":
            return False

        # None/null
        if value_str.lower() in ("none", "null"):
            return None

        # Number
        try:
            if "." in value_str:
                return float(value_str)
            return int(value_str)
        except ValueError:
            pass

        # Return as string
        return value_str


@dataclass
class HumanOperator:
    """Represents a registered human operator.

    Attributes:
        operator_id: Unique identifier for this operator.
        name: Human-readable name.
        capabilities: List of capabilities/permissions this operator has.
        roles: List of roles (e.g., 'reviewer', 'approver', 'admin').
        contact_info: Contact information (email, phone, etc.).
        available: Whether the operator is currently available.
        last_active: Timestamp of last activity.
    """
    operator_id: str
    name: str = ""
    capabilities: List[str] = field(default_factory=list)
    roles: List[str] = field(default_factory=list)
    contact_info: Dict[str, str] = field(default_factory=dict)
    available: bool = True
    last_active: float = field(default_factory=time.time)

    def to_dict(self) -> dict:
        """Serialize to a plain dictionary."""
        return {
            "operator_id": self.operator_id,
            "name": self.name,
            "capabilities": self.capabilities,
            "roles": self.roles,
            "contact_info": self.contact_info,
            "available": self.available,
            "last_active": self.last_active,
        }


# ---------------------------------------------------------------------------
# HumanInTheLoop
# ---------------------------------------------------------------------------

class HumanInTheLoop:
    """Central manager for human-in-the-loop collaboration.

    Provides structured interfaces for human experts to review, approve,
    override, and guide AI decisions during penetration testing operations.
    Supports multiple collaboration modes and configurable approval rules.

    Usage::

        hitl = HumanInTheLoop(mode="approval")

        # Check if approval is needed
        needs_review, reason = hitl.check_approval_required(decision, 0.7)
        if needs_review:
            request_id = hitl.request_review(decision)
            # Wait for human feedback...

        # Submit feedback
        feedback = HumanFeedback(
            request_id=request_id,
            feedback_type="approve",
            rationale="Target is within scope",
        )
        hitl.submit_feedback(request_id, feedback)
    """

    def __init__(
        self,
        mode: str = "advisory",
        default_timeout: int = 300,
        max_pending: int = 100,
    ) -> None:
        """Initialize the Human-in-the-Loop system.

        Args:
            mode: Collaboration mode ("advisory", "approval", "full-control").
            default_timeout: Default timeout in seconds for review requests.
            max_pending: Maximum number of pending requests before alerts.
        """
        self._mode = CollaborationMode(mode.lower())
        self._default_timeout = default_timeout
        self._max_pending = max_pending

        # Storage
        self._pending_requests: Dict[str, ReviewRequest] = {}
        self._completed_requests: Dict[str, ReviewRequest] = {}
        self._feedback_history: Dict[str, HumanFeedback] = {}
        self._approval_rules: List[ApprovalRule] = []
        self._operators: Dict[str, HumanOperator] = {}

        # Callbacks
        self._on_request_created: Optional[Callable[[ReviewRequest], None]] = None
        self._on_feedback_received: Optional[Callable[[ReviewRequest, HumanFeedback], None]] = None

        # Threading
        self._lock = threading.RLock()
        self._feedback_queue: queue.Queue[HumanFeedback] = queue.Queue()

        logger.info(
            "HumanInTheLoop initialized: mode=%s, timeout=%ds",
            self._mode.value,
            self._default_timeout,
        )

    # ------------------------------------------------------------------
    # Properties
    # ------------------------------------------------------------------

    @property
    def mode(self) -> CollaborationMode:
        """Get the current collaboration mode."""
        return self._mode

    @mode.setter
    def mode(self, value: str) -> None:
        """Set the collaboration mode."""
        self._mode = CollaborationMode(value.lower())
        logger.info("Collaboration mode changed to: %s", self._mode.value)

    @property
    def pending_count(self) -> int:
        """Get the number of pending review requests."""
        return len(self._pending_requests)

    # ------------------------------------------------------------------
    # Request Management
    # ------------------------------------------------------------------

    def request_review(
        self,
        decision: dict,
        reasoning: str = "",
        confidence: float = 0.0,
        urgency: str = "medium",
    ) -> str:
        """Submit a decision for human review.

        Creates a ReviewRequest and adds it to the pending queue.
        In 'advisory' mode, this is informational; in 'approval' and
        'full-control' modes, this blocks until feedback is received.

        Args:
            decision: The decision dict requiring review. Should contain
                      'action_type', 'target', and relevant context.
            reasoning: AI's explanation for the recommended action.
            confidence: AI's confidence score [0,1].
            urgency: Urgency level (critical/high/medium/low).

        Returns:
            The request_id for tracking this review request.
        """
        with self._lock:
            request = ReviewRequest(
                request_id=str(uuid.uuid4()),
                timestamp=time.time(),
                decision_type=decision.get("action_type", "custom"),
                context=decision.get("context", {}),
                reasoning=reasoning,
                confidence=confidence,
                recommended_action=decision.get("recommended_action", decision),
                alternatives=decision.get("alternatives", []),
                urgency=urgency,
                status="pending",
                metadata=decision.get("metadata", {}),
            )

            self._pending_requests[request.request_id] = request

            logger.info(
                "Review request created: %s (type=%s, urgency=%s, confidence=%.2f)",
                request.request_id[:8],
                request.decision_type,
                request.urgency,
                request.confidence,
            )

            # Trigger callback if set
            if self._on_request_created:
                try:
                    self._on_request_created(request)
                except Exception as e:
                    logger.error("Callback error: %s", e)

            # Check if pending queue is getting full
            if len(self._pending_requests) > self._max_pending:
                logger.warning(
                    "Pending requests exceed max (%d > %d)",
                    len(self._pending_requests),
                    self._max_pending,
                )

            return request.request_id

    def submit_feedback(
        self,
        request_id: str,
        feedback: HumanFeedback,
    ) -> bool:
        """Submit human feedback for a review request.

        Updates the request status and stores the feedback for
        downstream processing.

        Args:
            request_id: ID of the request being reviewed.
            feedback: The human feedback object.

        Returns:
            True if feedback was successfully recorded.
        """
        with self._lock:
            request = self._pending_requests.get(request_id)
            if request is None:
                logger.error(
                    "Cannot submit feedback: request %s not found",
                    request_id[:8],
                )
                return False

            # Update request status based on feedback type
            if feedback.feedback_type == "approve":
                request.status = "approved"
            elif feedback.feedback_type == "reject":
                request.status = "rejected"
            elif feedback.feedback_type == "modify":
                request.status = "modified"
            elif feedback.feedback_type == "escalate":
                request.status = "escalated"

            # Move to completed
            self._completed_requests[request_id] = request
            del self._pending_requests[request_id]

            # Store feedback
            self._feedback_history[request_id] = feedback

            # Put in queue for waiting threads
            self._feedback_queue.put(feedback)

            logger.info(
                "Feedback received for %s: %s (%s)",
                request_id[:8],
                feedback.feedback_type,
                feedback.rationale[:50] if feedback.rationale else "no rationale",
            )

            # Trigger callback if set
            if self._on_feedback_received:
                try:
                    self._on_feedback_received(request, feedback)
                except Exception as e:
                    logger.error("Callback error: %s", e)

            return True

    def check_approval_required(
        self,
        decision: dict,
        confidence: float,
    ) -> Tuple[bool, str]:
        """Check if a decision requires human approval.

        Evaluates approval rules and collaboration mode to determine
        if human review is needed before proceeding.

        Args:
            decision: The decision dict to evaluate.
            confidence: AI's confidence score for the decision.

        Returns:
            Tuple of (requires_review, reason).
        """
        # Full-control mode always requires review
        if self._mode == CollaborationMode.FULL_CONTROL:
            return True, "Full-control mode requires all actions to be reviewed"

        # Advisory mode typically doesn't require approval
        if self._mode == CollaborationMode.ADVISORY:
            # Only require review for explicitly flagged actions
            if decision.get("requires_human_review", False):
                return True, "Decision explicitly flagged for human review"
            return False, "Advisory mode - proceeding autonomously"

        # Approval mode - check rules
        if self._mode == CollaborationMode.APPROVAL:
            # Check if confidence exceeds auto-approve threshold
            if confidence >= 0.95:
                return False, f"Confidence {confidence:.2f} exceeds auto-approve threshold"

            # Evaluate approval rules
            for rule in self._approval_rules:
                if not rule.enabled:
                    continue

                # Check if confidence exceeds rule's auto-approve threshold
                if confidence >= rule.auto_approve_threshold:
                    continue

                # Evaluate trigger condition
                if rule.evaluate_condition(decision):
                    return True, f"Rule '{rule.rule_id}' triggered: {rule.trigger_condition}"

            # Default in approval mode: require review for risky actions
            risky_actions = {
                "exploit", "credential_dump", "privilege_escalation",
                "persistence", "data_exfiltration", "denial_of_service",
            }
            action_type = decision.get("action_type", "").lower()
            if action_type in risky_actions:
                return True, f"Risky action '{action_type}' requires approval"

        return False, "No approval required"

    def get_pending_requests(self) -> List[ReviewRequest]:
        """Get all pending review requests.

        Returns:
            List of ReviewRequest objects awaiting feedback,
            ordered by urgency then timestamp.
        """
        with self._lock:
            requests = list(self._pending_requests.values())

        # Sort by urgency (critical first) then by timestamp
        urgency_order = {"critical": 0, "high": 1, "medium": 2, "low": 3}
        requests.sort(
            key=lambda r: (urgency_order.get(r.urgency, 2), r.timestamp)
        )
        return requests

    def get_request_status(self, request_id: str) -> str:
        """Get the current status of a review request.

        Args:
            request_id: The request ID to check.

        Returns:
            Status string or "not_found" if request doesn't exist.
        """
        with self._lock:
            if request_id in self._pending_requests:
                return self._pending_requests[request_id].status
            if request_id in self._completed_requests:
                return self._completed_requests[request_id].status
        return "not_found"

    def get_request(self, request_id: str) -> Optional[ReviewRequest]:
        """Get a specific review request by ID.

        Args:
            request_id: The request ID to retrieve.

        Returns:
            ReviewRequest or None if not found.
        """
        with self._lock:
            if request_id in self._pending_requests:
                return self._pending_requests[request_id]
            if request_id in self._completed_requests:
                return self._completed_requests[request_id]
        return None

    def get_feedback(self, request_id: str) -> Optional[HumanFeedback]:
        """Get the feedback for a completed request.

        Args:
            request_id: The request ID to get feedback for.

        Returns:
            HumanFeedback or None if not found.
        """
        with self._lock:
            return self._feedback_history.get(request_id)

    def wait_for_feedback(
        self,
        request_id: str,
        timeout: Optional[float] = None,
    ) -> Optional[HumanFeedback]:
        """Wait for human feedback on a specific request.

        Blocks until feedback is received or timeout expires.

        Args:
            request_id: The request ID to wait for.
            timeout: Maximum time to wait in seconds. None for no timeout.

        Returns:
            HumanFeedback when received, or None on timeout.
        """
        deadline = None if timeout is None else time.time() + timeout

        while True:
            # Check if we already have feedback
            with self._lock:
                if request_id in self._feedback_history:
                    return self._feedback_history[request_id]

            # Check timeout
            if deadline is not None and time.time() >= deadline:
                logger.warning(
                    "Timeout waiting for feedback on %s",
                    request_id[:8],
                )
                return None

            # Wait briefly before checking again
            time.sleep(0.1)

    # ------------------------------------------------------------------
    # Approval Rules
    # ------------------------------------------------------------------

    def set_approval_rules(self, rules: List[ApprovalRule]) -> None:
        """Set the approval rules for the system.

        Replaces any existing rules with the provided list.

        Args:
            rules: List of ApprovalRule objects.
        """
        with self._lock:
            self._approval_rules = list(rules)

        logger.info("Set %d approval rules", len(rules))

    def add_approval_rule(self, rule: ApprovalRule) -> None:
        """Add a single approval rule.

        Args:
            rule: The ApprovalRule to add.
        """
        with self._lock:
            self._approval_rules.append(rule)

        logger.info("Added approval rule: %s", rule.rule_id)

    def remove_approval_rule(self, rule_id: str) -> bool:
        """Remove an approval rule by ID.

        Args:
            rule_id: ID of the rule to remove.

        Returns:
            True if rule was found and removed.
        """
        with self._lock:
            for i, rule in enumerate(self._approval_rules):
                if rule.rule_id == rule_id:
                    del self._approval_rules[i]
                    logger.info("Removed approval rule: %s", rule_id)
                    return True
        return False

    def get_approval_rules(self) -> List[ApprovalRule]:
        """Get all approval rules.

        Returns:
            List of ApprovalRule objects.
        """
        with self._lock:
            return list(self._approval_rules)

    # ------------------------------------------------------------------
    # Escalation and Guidance
    # ------------------------------------------------------------------

    def escalate_to_human(
        self,
        decision: dict,
        reason: str,
        urgency: str = "high",
    ) -> str:
        """Escalate a decision directly to human review.

        Used for urgent situations or when the AI determines it
        cannot make a safe decision autonomously.

        Args:
            decision: The decision requiring escalation.
            reason: Why this decision was escalated.
            urgency: Urgency level for the escalation.

        Returns:
            The request_id for tracking.
        """
        logger.warning(
            "Escalating to human: %s (urgency=%s)",
            reason,
            urgency,
        )

        request_id = self.request_review(
            decision=decision,
            reasoning=f"ESCALATED: {reason}",
            confidence=0.0,  # Low confidence indicates uncertainty
            urgency=urgency,
        )

        # Update status to escalated
        with self._lock:
            if request_id in self._pending_requests:
                self._pending_requests[request_id].status = "escalated"

        return request_id

    def get_human_guidance(
        self,
        query: str,
        context: dict,
    ) -> dict:
        """Request guidance from a human operator.

        Creates a guidance request that can be answered asynchronously.
        In advisory mode, this is informational; in other modes it may block.

        Args:
            query: The question or guidance request.
            context: Relevant context for the query.

        Returns:
            Dict containing the guidance response.
        """
        guidance_request = {
            "action_type": "guidance_request",
            "query": query,
            "context": context,
            "requires_human_review": True,
        }

        request_id = self.request_review(
            decision=guidance_request,
            reasoning=f"Guidance requested: {query}",
            confidence=0.0,
            urgency="medium",
        )

        return {
            "request_id": request_id,
            "status": "pending",
            "message": "Guidance request submitted for human review",
        }

    # ------------------------------------------------------------------
    # Operator Management
    # ------------------------------------------------------------------

    def register_human_operator(
        self,
        operator_id: str,
        capabilities: List[str],
        name: str = "",
        roles: Optional[List[str]] = None,
        contact_info: Optional[Dict[str, str]] = None,
    ) -> bool:
        """Register a human operator who can provide feedback.

        Args:
            operator_id: Unique identifier for the operator.
            capabilities: List of capabilities this operator has.
            name: Human-readable name.
            roles: List of roles (reviewer, approver, admin).
            contact_info: Contact information dict.

        Returns:
            True if registration was successful.
        """
        with self._lock:
            if operator_id in self._operators:
                logger.warning("Operator %s already registered, updating", operator_id)

            self._operators[operator_id] = HumanOperator(
                operator_id=operator_id,
                name=name or operator_id,
                capabilities=capabilities,
                roles=roles or ["reviewer"],
                contact_info=contact_info or {},
                available=True,
                last_active=time.time(),
            )

        logger.info(
            "Registered operator: %s (capabilities=%s)",
            operator_id,
            capabilities,
        )
        return True

    def unregister_human_operator(self, operator_id: str) -> bool:
        """Unregister a human operator.

        Args:
            operator_id: ID of the operator to unregister.

        Returns:
            True if operator was found and removed.
        """
        with self._lock:
            if operator_id in self._operators:
                del self._operators[operator_id]
                logger.info("Unregistered operator: %s", operator_id)
                return True
        return False

    def get_operators(self) -> List[HumanOperator]:
        """Get all registered human operators.

        Returns:
            List of HumanOperator objects.
        """
        with self._lock:
            return list(self._operators.values())

    def get_available_operators(self) -> List[HumanOperator]:
        """Get operators currently marked as available.

        Returns:
            List of available HumanOperator objects.
        """
        with self._lock:
            return [op for op in self._operators.values() if op.available]

    def set_operator_availability(self, operator_id: str, available: bool) -> bool:
        """Set an operator's availability status.

        Args:
            operator_id: ID of the operator.
            available: Whether the operator is available.

        Returns:
            True if operator was found and updated.
        """
        with self._lock:
            if operator_id in self._operators:
                self._operators[operator_id].available = available
                self._operators[operator_id].last_active = time.time()
                logger.info(
                    "Operator %s availability: %s",
                    operator_id,
                    "available" if available else "unavailable",
                )
                return True
        return False

    # ------------------------------------------------------------------
    # Callbacks
    # ------------------------------------------------------------------

    def set_on_request_created(
        self,
        callback: Optional[Callable[[ReviewRequest], None]],
    ) -> None:
        """Set callback for when a review request is created.

        Args:
            callback: Function to call when request is created.
        """
        self._on_request_created = callback

    def set_on_feedback_received(
        self,
        callback: Optional[Callable[[ReviewRequest, HumanFeedback], None]],
    ) -> None:
        """Set callback for when feedback is received.

        Args:
            callback: Function to call when feedback is received.
        """
        self._on_feedback_received = callback

    # ------------------------------------------------------------------
    # Statistics and Export
    # ------------------------------------------------------------------

    def get_statistics(self) -> dict:
        """Get statistics about the HITL system.

        Returns:
            Dict with counts, averages, and other metrics.
        """
        with self._lock:
            total_pending = len(self._pending_requests)
            total_completed = len(self._completed_requests)
            total_feedback = len(self._feedback_history)

            # Count by status
            status_counts: Dict[str, int] = {}
            for req in self._completed_requests.values():
                status_counts[req.status] = status_counts.get(req.status, 0) + 1

            # Count by decision type
            type_counts: Dict[str, int] = {}
            for req in list(self._pending_requests.values()) + list(self._completed_requests.values()):
                type_counts[req.decision_type] = type_counts.get(req.decision_type, 0) + 1

            # Average confidence
            confidences = [
                req.confidence for req in self._completed_requests.values()
            ]
            avg_confidence = sum(confidences) / len(confidences) if confidences else 0.0

            return {
                "mode": self._mode.value,
                "pending_requests": total_pending,
                "completed_requests": total_completed,
                "total_feedback": total_feedback,
                "operators_registered": len(self._operators),
                "operators_available": len([op for op in self._operators.values() if op.available]),
                "approval_rules": len(self._approval_rules),
                "status_breakdown": status_counts,
                "type_breakdown": type_counts,
                "avg_confidence": round(avg_confidence, 4),
            }

    def export_state(self) -> dict:
        """Export the current state for serialization.

        Returns:
            Dict containing all state that can be serialized.
        """
        with self._lock:
            return {
                "mode": self._mode.value,
                "pending_requests": [
                    req.to_dict() for req in self._pending_requests.values()
                ],
                "completed_requests": [
                    req.to_dict() for req in self._completed_requests.values()
                ],
                "feedback_history": [
                    fb.to_dict() for fb in self._feedback_history.values()
                ],
                "approval_rules": [
                    rule.to_dict() for rule in self._approval_rules
                ],
                "operators": [
                    op.to_dict() for op in self._operators.values()
                ],
                "statistics": self.get_statistics(),
            }


# ---------------------------------------------------------------------------
# HumanDashboard
# ---------------------------------------------------------------------------

class HumanDashboard:
    """Simple CLI interface for human operators.

    Provides a text-based interface for reviewing pending requests,
    displaying details, and submitting feedback.

    Usage::

        hitl = HumanInTheLoop(mode="approval")
        dashboard = HumanDashboard(hitl)
        dashboard.show_dashboard()
    """

    # ANSI color codes for terminal output
    _COLORS = {
        "reset": "\033[0m",
        "red": "\033[91m",
        "green": "\033[92m",
        "yellow": "\033[93m",
        "blue": "\033[94m",
        "magenta": "\033[95m",
        "cyan": "\033[96m",
        "white": "\033[97m",
        "bold": "\033[1m",
    }

    def __init__(
        self,
        hitl: HumanInTheLoop,
        operator_id: str = "default_operator",
        use_colors: bool = True,
    ) -> None:
        """Initialize the dashboard.

        Args:
            hitl: The HumanInTheLoop instance to interface with.
            operator_id: ID of the operator using this dashboard.
            use_colors: Whether to use ANSI colors in output.
        """
        self._hitl = hitl
        self._operator_id = operator_id
        self._use_colors = use_colors

    def _color(self, text: str, color: str) -> str:
        """Apply ANSI color to text if enabled."""
        if not self._use_colors:
            return text
        return f"{self._COLORS.get(color, '')}{text}{self._COLORS['reset']}"

    def show_dashboard(self) -> None:
        """Display the full dashboard status."""
        stats = self._hitl.get_statistics()

        print("\n" + "=" * 60)
        print(self._color("  HUMAN-IN-THE-LOOP DASHBOARD", "bold") + "\n")
        print("=" * 60)

        # Mode and status
        print(f"\n  Mode: {self._color(stats['mode'].upper(), 'cyan')}")
        print(f"  Pending Requests: {self._color(str(stats['pending_requests']), 'yellow')}")
        print(f"  Completed Today: {stats['completed_requests']}")
        print(f"  Operators Available: {stats['operators_available']}/{stats['operators_registered']}")

        # Pending requests summary
        pending = self._hitl.get_pending_requests()
        if pending:
            print(f"\n  {self._color('Pending Requests:', 'bold')}")
            self.display_pending_requests()
        else:
            print(f"\n  {self._color('No pending requests', 'green')}")

        print("\n" + "=" * 60 + "\n")

    def display_pending_requests(self) -> None:
        """Display a summary of all pending requests."""
        pending = self._hitl.get_pending_requests()

        if not pending:
            print("  No pending requests.")
            return

        print(f"\n  {'ID':<10} {'Type':<20} {'Urgency':<10} {'Age':<10} {'Confidence'}")
        print("  " + "-" * 60)

        for req in pending:
            # Color-code urgency
            urgency_color = {
                "critical": "red",
                "high": "yellow",
                "medium": "white",
                "low": "blue",
            }.get(req.urgency, "white")

            age = self._format_age(req.get_age_seconds())

            print(
                f"  {req.request_id[:8]:<10} "
                f"{req.decision_type:<20} "
                f"{self._color(req.urgency.upper(), urgency_color):<19} "
                f"{age:<10} "
                f"{req.confidence:.2f}"
            )

    def display_request_details(self, request_id: str) -> None:
        """Display detailed information about a specific request.

        Args:
            request_id: ID of the request to display.
        """
        request = self._hitl.get_request(request_id)

        if request is None:
            print(f"  {self._color('Request not found:', 'red')} {request_id}")
            return

        print("\n" + "=" * 60)
        print(f"  {self._color('REQUEST DETAILS', 'bold')}")
        print("=" * 60)

        print(f"\n  Request ID: {request.request_id}")
        print(f"  Status: {self._color(request.status.upper(), 'cyan')}")
        print(f"  Decision Type: {request.decision_type}")
        print(f"  Urgency: {request.urgency.upper()}")
        print(f"  Confidence: {request.confidence:.2f}")
        print(f"  Created: {datetime.fromtimestamp(request.timestamp).strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"  Age: {self._format_age(request.get_age_seconds())}")

        print(f"\n  {self._color('AI Reasoning:', 'bold')}")
        print(f"  {request.reasoning}")

        print(f"\n  {self._color('Recommended Action:', 'bold')}")
        for key, value in request.recommended_action.items():
            print(f"    {key}: {value}")

        if request.context:
            print(f"\n  {self._color('Context:', 'bold')}")
            for key, value in request.context.items():
                value_str = str(value)
                if len(value_str) > 100:
                    value_str = value_str[:100] + "..."
                print(f"    {key}: {value_str}")

        if request.alternatives:
            print(f"\n  {self._color('Alternatives Considered:', 'bold')}")
            for i, alt in enumerate(request.alternatives, 1):
                print(f"    {i}. {alt.get('type', 'unknown')}: {alt.get('description', '')}")

        print("\n" + "=" * 60)

    def prompt_feedback(self, request_id: str) -> HumanFeedback:
        """Prompt the operator for feedback on a request.

        Interactive CLI prompt for submitting feedback.

        Args:
            request_id: ID of the request to provide feedback for.

        Returns:
            HumanFeedback object with the operator's response.
        """
        request = self._hitl.get_request(request_id)

        if request is None:
            raise ValueError(f"Request not found: {request_id}")

        self.display_request_details(request_id)

        print(f"\n  {self._color('Provide Feedback', 'bold')}")
        print("  " + "-" * 40)
        print("  1. Approve")
        print("  2. Reject")
        print("  3. Modify")
        print("  4. Ask for more information")
        print("  5. Escalate")

        try:
            choice = input("\n  Select action [1-5]: ").strip()
        except EOFError:
            choice = "2"  # Default to reject on EOF

        feedback_map = {
            "1": "approve",
            "2": "reject",
            "3": "modify",
            "4": "ask_more",
            "5": "escalate",
        }

        feedback_type = feedback_map.get(choice, "reject")

        try:
            rationale = input("  Enter rationale: ").strip()
        except EOFError:
            rationale = "No rationale provided"

        modifications = None
        if feedback_type == "modify":
            print("  Enter modifications (key=value, one per line, empty line to finish):")
            modifications = {}
            while True:
                try:
                    line = input("  ").strip()
                except EOFError:
                    break
                if not line:
                    break
                if "=" in line:
                    key, value = line.split("=", 1)
                    modifications[key.strip()] = value.strip()

        feedback = HumanFeedback(
            request_id=request_id,
            feedback_type=feedback_type,
            decision=request.recommended_action,
            rationale=rationale,
            modifications=modifications,
            operator_id=self._operator_id,
        )

        return feedback

    def interactive_loop(self) -> None:
        """Run an interactive CLI loop for processing requests."""
        print(self._color("\n  Human-in-the-Loop Interactive Dashboard", "bold"))
        print("  Type 'help' for commands, 'exit' to quit\n")

        while True:
            try:
                cmd = input("hitl> ").strip().lower()
            except (EOFError, KeyboardInterrupt):
                print("\n  Exiting...")
                break

            if not cmd:
                continue

            if cmd in ("exit", "quit", "q"):
                print("  Goodbye!")
                break

            elif cmd in ("help", "h", "?"):
                self._print_help()

            elif cmd in ("status", "stats"):
                self.show_dashboard()

            elif cmd in ("pending", "list"):
                self.display_pending_requests()

            elif cmd.startswith("show "):
                request_id = cmd[5:].strip()
                self.display_request_details(request_id)

            elif cmd.startswith("review "):
                request_id = cmd[7:].strip()
                try:
                    feedback = self.prompt_feedback(request_id)
                    self._hitl.submit_feedback(request_id, feedback)
                    print(f"  {self._color('Feedback submitted!', 'green')}")
                except Exception as e:
                    print(f"  {self._color('Error:', 'red')} {e}")

            elif cmd in ("clear", "cls"):
                print("\033[2J\033[H", end="")

            else:
                print(f"  Unknown command: {cmd}. Type 'help' for commands.")

    def _print_help(self) -> None:
        """Print help text for interactive commands."""
        print("""
  Available Commands:

  status, stats     - Show dashboard status
  pending, list     - List pending requests
  show <id>         - Show details for a request
  review <id>       - Review and provide feedback for a request
  clear, cls        - Clear the screen
  help, h, ?        - Show this help
  exit, quit, q     - Exit the dashboard
        """)

    def _format_age(self, seconds: float) -> str:
        """Format a duration in seconds to a human-readable string."""
        if seconds < 60:
            return f"{int(seconds)}s"
        elif seconds < 3600:
            minutes = int(seconds / 60)
            secs = int(seconds % 60)
            return f"{minutes}m {secs}s"
        elif seconds < 86400:
            hours = int(seconds / 3600)
            minutes = int((seconds % 3600) / 60)
            return f"{hours}h {minutes}m"
        else:
            days = int(seconds / 86400)
            hours = int((seconds % 86400) / 3600)
            return f"{days}d {hours}h"


# ---------------------------------------------------------------------------
# Factory Functions
# ---------------------------------------------------------------------------

def create_hitl_system(
    mode: str = "advisory",
    rules: Optional[List[ApprovalRule]] = None,
) -> HumanInTheLoop:
    """Create a configured Human-in-the-Loop system.

    Factory function that creates a HumanInTheLoop instance with
    sensible defaults and optional custom rules.

    Args:
        mode: Collaboration mode ("advisory", "approval", "full-control").
        rules: Optional list of approval rules to configure.

    Returns:
        Configured HumanInTheLoop instance.
    """
    hitl = HumanInTheLoop(mode=mode)

    # Add default rules if none provided
    if rules is None and mode == "approval":
        default_rules = [
            ApprovalRule(
                rule_id="exploit_rule",
                trigger_condition="action_type=='exploit'",
                approval_level="elevated",
                auto_approve_threshold=0.95,
                timeout_seconds=600,
                description="All exploit attempts require human approval",
            ),
            ApprovalRule(
                rule_id="high_severity_rule",
                trigger_condition="severity>7",
                approval_level="extreme",
                auto_approve_threshold=0.99,
                timeout_seconds=900,
                description="High severity actions require elevated approval",
            ),
            ApprovalRule(
                rule_id="credential_rule",
                trigger_condition="action_type=='credential_dump'",
                approval_level="elevated",
                auto_approve_threshold=0.90,
                timeout_seconds=300,
                description="Credential dumping requires approval",
            ),
            ApprovalRule(
                rule_id="lateral_rule",
                trigger_condition="action_type=='lateral_move'",
                approval_level="normal",
                auto_approve_threshold=0.85,
                timeout_seconds=300,
                description="Lateral movement requires approval",
            ),
        ]
        hitl.set_approval_rules(default_rules)
    elif rules:
        hitl.set_approval_rules(rules)

    logger.info("Created HITL system with mode=%s", mode)
    return hitl


def create_default_approval_rules() -> List[ApprovalRule]:
    """Create a list of default approval rules.

    Returns:
        List of commonly used ApprovalRule objects.
    """
    return [
        ApprovalRule(
            rule_id="exploit_default",
            trigger_condition="action_type=='exploit'",
            approval_level="elevated",
            auto_approve_threshold=0.95,
            timeout_seconds=600,
            default_action="abort",
            description="Exploit attempts require elevated approval",
        ),
        ApprovalRule(
            rule_id="credential_default",
            trigger_condition="action_type=='credential_dump'",
            approval_level="elevated",
            auto_approve_threshold=0.90,
            timeout_seconds=300,
            default_action="abort",
            description="Credential operations require approval",
        ),
        ApprovalRule(
            rule_id="lateral_default",
            trigger_condition="action_type=='lateral_move'",
            approval_level="normal",
            auto_approve_threshold=0.85,
            timeout_seconds=300,
            default_action="ask_again",
            description="Lateral movement requires normal approval",
        ),
        ApprovalRule(
            rule_id="privesc_default",
            trigger_condition="action_type=='privilege_escalation'",
            approval_level="elevated",
            auto_approve_threshold=0.90,
            timeout_seconds=600,
            default_action="abort",
            description="Privilege escalation requires elevated approval",
        ),
        ApprovalRule(
            rule_id="persistence_default",
            trigger_condition="action_type=='persistence'",
            approval_level="extreme",
            auto_approve_threshold=0.99,
            timeout_seconds=900,
            default_action="abort",
            description="Persistence mechanisms require extreme scrutiny",
        ),
        ApprovalRule(
            rule_id="exfil_default",
            trigger_condition="action_type=='data_exfiltration'",
            approval_level="extreme",
            auto_approve_threshold=0.99,
            timeout_seconds=900,
            default_action="abort",
            description="Data exfiltration requires extreme approval",
        ),
        ApprovalRule(
            rule_id="dos_default",
            trigger_condition="action_type=='denial_of_service'",
            approval_level="extreme",
            auto_approve_threshold=1.0,  # Never auto-approve
            timeout_seconds=1800,
            default_action="abort",
            description="DoS actions require explicit human approval",
        ),
    ]

← 返回文件树 · 在 GitHub 上查看