|
| 1 | +"""Cross-reference and logical validation for scenarios. |
| 2 | +
|
| 3 | +This module provides validation beyond Pydantic's schema validation: |
| 4 | +- Cross-references between users, systems, personas, groups |
| 5 | +- Uniqueness constraints (usernames, hostnames, IPs) |
| 6 | +- Logical consistency checks |
| 7 | +""" |
| 8 | + |
| 9 | +from dataclasses import dataclass |
| 10 | +from typing import Optional |
| 11 | + |
| 12 | +from log_generator.models import Scenario |
| 13 | + |
| 14 | + |
| 15 | +@dataclass |
| 16 | +class ValidationIssue: |
| 17 | + """Represents a validation issue found in a scenario. |
| 18 | +
|
| 19 | + Attributes: |
| 20 | + severity: "error" (blocks generation) or "warning" (informational) |
| 21 | + field_path: Dot-separated path to the problematic field |
| 22 | + message: Human-readable description of the issue |
| 23 | + suggestion: Optional actionable suggestion to fix the issue |
| 24 | + """ |
| 25 | + |
| 26 | + severity: str # "error" | "warning" |
| 27 | + field_path: str |
| 28 | + message: str |
| 29 | + suggestion: Optional[str] = None |
| 30 | + |
| 31 | + |
| 32 | +class ScenarioValidator: |
| 33 | + """Validates cross-references and logical consistency in scenarios.""" |
| 34 | + |
| 35 | + def __init__(self, scenario: Scenario): |
| 36 | + """Initialize validator with a scenario. |
| 37 | +
|
| 38 | + Args: |
| 39 | + scenario: The scenario to validate |
| 40 | + """ |
| 41 | + self.scenario = scenario |
| 42 | + self.issues: list[ValidationIssue] = [] |
| 43 | + |
| 44 | + # Build lookup sets for fast reference checking |
| 45 | + self._build_lookups() |
| 46 | + |
| 47 | + def _build_lookups(self) -> None: |
| 48 | + """Build lookup dictionaries for users, systems, personas, groups.""" |
| 49 | + self.usernames = {user.username for user in self.scenario.environment.users} |
| 50 | + self.hostnames = { |
| 51 | + system.hostname for system in self.scenario.environment.systems |
| 52 | + } |
| 53 | + self.ips = {system.ip for system in self.scenario.environment.systems} |
| 54 | + self.persona_names = {persona.name for persona in self.scenario.personas} |
| 55 | + self.group_names = ( |
| 56 | + {group.name for group in self.scenario.environment.groups} |
| 57 | + if self.scenario.environment.groups |
| 58 | + else set() |
| 59 | + ) |
| 60 | + |
| 61 | + def validate(self) -> list[ValidationIssue]: |
| 62 | + """Run all validation checks and return issues found. |
| 63 | +
|
| 64 | + Returns: |
| 65 | + List of validation issues (errors and warnings) |
| 66 | + """ |
| 67 | + self._validate_user_persona_references() |
| 68 | + self._validate_system_user_references() |
| 69 | + self._validate_user_primary_system_references() |
| 70 | + self._validate_group_member_references() |
| 71 | + self._validate_storyline_references() |
| 72 | + self._validate_uniqueness() |
| 73 | + return self.issues |
| 74 | + |
| 75 | + def has_errors(self) -> bool: |
| 76 | + """Check if any error-level issues were found. |
| 77 | +
|
| 78 | + Returns: |
| 79 | + True if any errors found, False otherwise |
| 80 | + """ |
| 81 | + return any(issue.severity == "error" for issue in self.issues) |
| 82 | + |
| 83 | + def _validate_user_persona_references(self) -> None: |
| 84 | + """Check that user persona references exist in personas list.""" |
| 85 | + for idx, user in enumerate(self.scenario.environment.users): |
| 86 | + if user.persona and user.persona not in self.persona_names: |
| 87 | + available = ( |
| 88 | + ", ".join(sorted(self.persona_names)) |
| 89 | + if self.persona_names |
| 90 | + else "none defined" |
| 91 | + ) |
| 92 | + self.issues.append( |
| 93 | + ValidationIssue( |
| 94 | + severity="error", |
| 95 | + field_path=f"environment.users.{idx}.persona", |
| 96 | + message=f"User '{user.username}' references undefined persona '{user.persona}'", |
| 97 | + suggestion=f"Available personas: {available}", |
| 98 | + ) |
| 99 | + ) |
| 100 | + |
| 101 | + def _validate_system_user_references(self) -> None: |
| 102 | + """Check that system assigned_user references exist in users list.""" |
| 103 | + for idx, system in enumerate(self.scenario.environment.systems): |
| 104 | + if system.assigned_user and system.assigned_user not in self.usernames: |
| 105 | + self.issues.append( |
| 106 | + ValidationIssue( |
| 107 | + severity="error", |
| 108 | + field_path=f"environment.systems.{idx}.assigned_user", |
| 109 | + message=f"System '{system.hostname}' references undefined user '{system.assigned_user}'", |
| 110 | + suggestion=f"Available users: {', '.join(sorted(self.usernames))}", |
| 111 | + ) |
| 112 | + ) |
| 113 | + |
| 114 | + def _validate_user_primary_system_references(self) -> None: |
| 115 | + """Check that user primary_system references exist in systems list.""" |
| 116 | + for idx, user in enumerate(self.scenario.environment.users): |
| 117 | + if user.primary_system and user.primary_system not in self.hostnames: |
| 118 | + self.issues.append( |
| 119 | + ValidationIssue( |
| 120 | + severity="error", |
| 121 | + field_path=f"environment.users.{idx}.primary_system", |
| 122 | + message=f"User '{user.username}' references undefined system '{user.primary_system}'", |
| 123 | + suggestion=f"Available systems: {', '.join(sorted(self.hostnames))}", |
| 124 | + ) |
| 125 | + ) |
| 126 | + |
| 127 | + def _validate_group_member_references(self) -> None: |
| 128 | + """Check that group members exist in users list.""" |
| 129 | + if not self.scenario.environment.groups: |
| 130 | + return |
| 131 | + |
| 132 | + for idx, group in enumerate(self.scenario.environment.groups): |
| 133 | + for member_idx, member in enumerate(group.members): |
| 134 | + if member not in self.usernames: |
| 135 | + self.issues.append( |
| 136 | + ValidationIssue( |
| 137 | + severity="error", |
| 138 | + field_path=f"environment.groups.{idx}.members.{member_idx}", |
| 139 | + message=f"Group '{group.name}' references undefined member '{member}'", |
| 140 | + suggestion=f"Available users: {', '.join(sorted(self.usernames))}", |
| 141 | + ) |
| 142 | + ) |
| 143 | + |
| 144 | + def _validate_storyline_references(self) -> None: |
| 145 | + """Check that storyline actor/system references are valid.""" |
| 146 | + if not self.scenario.storyline: |
| 147 | + return |
| 148 | + |
| 149 | + for idx, event in enumerate(self.scenario.storyline): |
| 150 | + # Validate actor (must be user or "attacker") |
| 151 | + if event.actor not in self.usernames and event.actor != "attacker": |
| 152 | + self.issues.append( |
| 153 | + ValidationIssue( |
| 154 | + severity="error", |
| 155 | + field_path=f"storyline.{idx}.actor", |
| 156 | + message=f"Storyline event references undefined actor '{event.actor}'", |
| 157 | + suggestion=f"Available users: {', '.join(sorted(self.usernames))}, or use 'attacker'", |
| 158 | + ) |
| 159 | + ) |
| 160 | + |
| 161 | + # Validate system |
| 162 | + if event.system not in self.hostnames: |
| 163 | + self.issues.append( |
| 164 | + ValidationIssue( |
| 165 | + severity="error", |
| 166 | + field_path=f"storyline.{idx}.system", |
| 167 | + message=f"Storyline event references undefined system '{event.system}'", |
| 168 | + suggestion=f"Available systems: {', '.join(sorted(self.hostnames))}", |
| 169 | + ) |
| 170 | + ) |
| 171 | + |
| 172 | + def _validate_uniqueness(self) -> None: |
| 173 | + """Check for duplicate usernames, hostnames, and IPs.""" |
| 174 | + # Check duplicate usernames |
| 175 | + seen_usernames = set() |
| 176 | + for idx, user in enumerate(self.scenario.environment.users): |
| 177 | + if user.username in seen_usernames: |
| 178 | + self.issues.append( |
| 179 | + ValidationIssue( |
| 180 | + severity="error", |
| 181 | + field_path=f"environment.users.{idx}.username", |
| 182 | + message=f"Duplicate username '{user.username}' found", |
| 183 | + suggestion="Usernames must be unique across all users", |
| 184 | + ) |
| 185 | + ) |
| 186 | + seen_usernames.add(user.username) |
| 187 | + |
| 188 | + # Check duplicate hostnames |
| 189 | + seen_hostnames = set() |
| 190 | + for idx, system in enumerate(self.scenario.environment.systems): |
| 191 | + if system.hostname in seen_hostnames: |
| 192 | + self.issues.append( |
| 193 | + ValidationIssue( |
| 194 | + severity="error", |
| 195 | + field_path=f"environment.systems.{idx}.hostname", |
| 196 | + message=f"Duplicate hostname '{system.hostname}' found", |
| 197 | + suggestion="Hostnames must be unique across all systems", |
| 198 | + ) |
| 199 | + ) |
| 200 | + seen_hostnames.add(system.hostname) |
| 201 | + |
| 202 | + # Check duplicate IPs |
| 203 | + seen_ips = set() |
| 204 | + for idx, system in enumerate(self.scenario.environment.systems): |
| 205 | + if system.ip in seen_ips: |
| 206 | + self.issues.append( |
| 207 | + ValidationIssue( |
| 208 | + severity="error", |
| 209 | + field_path=f"environment.systems.{idx}.ip", |
| 210 | + message=f"Duplicate IP address '{system.ip}' found", |
| 211 | + suggestion="IP addresses must be unique across all systems", |
| 212 | + ) |
| 213 | + ) |
| 214 | + seen_ips.add(system.ip) |
0 commit comments