A modern platform for visual, flexible, and extensible graph-based investigations. For cybersecurity analysts and investigators.
feat(types): types validation using pydantic directly
dextmorgnfa743f3055a1
diff --git a/flowsint-types/src/flowsint_types/asn.py b/flowsint-types/src/flowsint_types/asn.pyindex df8db510..5977fbd4 100644--- a/flowsint-types/src/flowsint_types/asn.py+++ b/flowsint-types/src/flowsint_types/asn.py@@ -1,6 +1,6 @@-from typing import List, Optional-from pydantic import BaseModel, Field-from .cidr import CIDR+from typing import List, Optional, Union+from pydantic import BaseModel, Field, field_validator, model_validator+import reclass ASN(BaseModel):@@ -9,6 +9,9 @@ class ASN(BaseModel):number: int = Field(..., description="Autonomous System Number (e.g., 15169)", title="ASN Number")+ asn_str: Optional[str] = Field(+ None, description="ASN in string format (e.g., 'AS15169')", title="ASN String"+ )name: Optional[str] = Field(None,description="Name of the organization owning the ASN",@@ -20,11 +23,50 @@ class ASN(BaseModel):description: Optional[str] = Field(None, description="Additional information about the ASN", title="Description")- cidrs: List[CIDR] = Field(+ cidrs: List['CIDR'] = Field(default_factory=list,description="List of announced CIDR blocks",title="CIDR Blocks",)+ @field_validator('number', mode='before')+ @classmethod+ def validate_asn_number(cls, v: Union[int, str]) -> int:+ """Validate and normalize ASN number.++ Accepts:+ - Integer: 15169+ - String with AS prefix: "AS15169"+ - String without prefix: "15169"++ Returns the integer ASN number.+ """+ if isinstance(v, str):+ # Remove 'AS' prefix if present (case insensitive)+ v = re.sub(r"(?i)^AS", "", v.strip())+ try:+ v = int(v)+ except ValueError:+ raise ValueError(f"Invalid ASN format: {v}")++ if not isinstance(v, int):+ raise ValueError(f"ASN must be an integer or string, got {type(v)}")++ # Validate ASN range (32-bit unsigned integer)+ if not (0 <= v <= 4294967295):+ raise ValueError(f"ASN number must be between 0 and 4294967295, got {v}")++ return v++ @model_validator(mode='after')+ def populate_asn_str(self) -> 'ASN':+ """Automatically populate asn_str from number if not provided."""+ # Always set asn_str based on number to ensure consistency+ self.asn_str = f"AS{self.number}"+ return self+++# Import CIDR here to avoid circular import+from .cidr import CIDRASN.model_rebuild()diff --git a/flowsint-types/src/flowsint_types/domain.py b/flowsint-types/src/flowsint_types/domain.pyindex 62231616..00db94f6 100644--- a/flowsint-types/src/flowsint_types/domain.py+++ b/flowsint-types/src/flowsint_types/domain.py@@ -1,5 +1,7 @@-from typing import Optional-from pydantic import BaseModel, Field+from typing import Optional, Union, Any+from pydantic import BaseModel, Field, field_validator, model_validator+from urllib.parse import urlparse+import reclass Domain(BaseModel):@@ -10,5 +12,35 @@ class Domain(BaseModel):True, description="Is root or not", title="Is Root Domain")+ @model_validator(mode='before')+ @classmethod+ def convert_string_to_dict(cls, data: Any) -> Any:+ """Allow creating Domain from a string directly."""+ if isinstance(data, str):+ return {'domain': data}+ return data++ @field_validator('domain')+ @classmethod+ def validate_domain(cls, v: str) -> str:+ """Validate that the domain is valid."""+ try:+ # Parse URL to extract hostname+ parsed = urlparse(v if "://" in v else "http://" + v)+ hostname = parsed.hostname or v++ # Check that domain has at least one dot+ if not hostname or "." not in hostname:+ raise ValueError(f"Invalid domain format: {v}")++ # Validate domain format with regex+ if not re.match(r"^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", hostname):+ raise ValueError(f"Invalid domain format: {v}")++ # Return the cleaned hostname (without protocol)+ return hostname+ except Exception as e:+ raise ValueError(f"Invalid domain: {v}") from e+Domain.model_rebuild()diff --git a/flowsint-types/src/flowsint_types/email.py b/flowsint-types/src/flowsint_types/email.pyindex 529d9897..f5405574 100644--- a/flowsint-types/src/flowsint_types/email.py+++ b/flowsint-types/src/flowsint_types/email.py@@ -1,7 +1,16 @@-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, EmailStr, model_validator+from typing import Anyclass Email(BaseModel):"""Represents an email address."""- email: str = Field(..., description="Email address", title="Email Address")+ email: EmailStr = Field(..., description="Email address", title="Email Address")++ @model_validator(mode='before')+ @classmethod+ def convert_string_to_dict(cls, data: Any) -> Any:+ """Allow creating Email from a string directly."""+ if isinstance(data, str):+ return {'email': data}+ return datadiff --git a/flowsint-types/src/flowsint_types/individual.py b/flowsint-types/src/flowsint_types/individual.pyindex 6d2362d0..dc670474 100644--- a/flowsint-types/src/flowsint_types/individual.py+++ b/flowsint-types/src/flowsint_types/individual.py@@ -1,6 +1,9 @@-from pydantic import BaseModel, Field-from typing import Optional, Literal, List+from pydantic import BaseModel, Field, field_validator+from typing import Optional, Literal, List, Unionfrom .address import Location+from .email import Email+from .phone import Phone+from .ip import Ipclass Individual(BaseModel):@@ -89,10 +92,10 @@ class Individual(BaseModel):)# Contact Information- phone_numbers: Optional[List[str]] = Field(+ phone_numbers: Optional[List[Phone]] = Field(None, description="Known phone numbers", title="Phone Numbers")- email_addresses: Optional[List[str]] = Field(+ email_addresses: Optional[List[Email]] = Field(None, description="Known email addresses", title="Email Addresses")social_media_profiles: Optional[List[str]] = Field(@@ -270,7 +273,7 @@ class Individual(BaseModel):)# Digital Footprint- ip_addresses: Optional[List[str]] = Field(+ ip_addresses: Optional[List[Ip]] = Field(None, description="Known IP addresses", title="IP Addresses")usernames: Optional[List[str]] = Field(@@ -306,3 +309,87 @@ class Individual(BaseModel):last_updated: Optional[str] = Field(None, description="Last update timestamp", title="Last Updated")++ @field_validator('email_addresses', mode='before')+ @classmethod+ def validate_email_addresses(cls, v: Optional[List[Union[str, Email]]]) -> Optional[List[Email]]:+ """Validate that all email addresses in the list are valid and convert to Email objects."""+ if v is None:+ return None++ validated_emails = []+ for email in v:+ if not email:+ continue++ try:+ # If already an Email object, keep it+ if isinstance(email, Email):+ validated_emails.append(email)+ # If string, convert to Email (will validate automatically)+ elif isinstance(email, str):+ validated_emails.append(Email(email=email))+ # If dict, convert to Email+ elif isinstance(email, dict):+ validated_emails.append(Email(**email))+ except Exception:+ # Skip invalid emails+ continue++ return validated_emails if validated_emails else None++ @field_validator('phone_numbers', mode='before')+ @classmethod+ def validate_phone_numbers(cls, v: Optional[List[Union[str, Phone]]]) -> Optional[List[Phone]]:+ """Validate phone numbers in the list and convert to Phone objects."""+ if v is None:+ return None++ validated_phones = []+ for phone in v:+ if not phone:+ continue++ try:+ # If already a Phone object, keep it+ if isinstance(phone, Phone):+ validated_phones.append(phone)+ # If string, convert to Phone (will validate and normalize automatically)+ elif isinstance(phone, str):+ validated_phones.append(Phone(number=phone))+ # If dict, convert to Phone+ elif isinstance(phone, dict):+ validated_phones.append(Phone(**phone))+ except Exception:+ # Skip invalid phone numbers+ continue++ return validated_phones if validated_phones else None++ @field_validator('ip_addresses', mode='before')+ @classmethod+ def validate_ip_addresses(cls, v: Optional[List[Union[str, Ip]]]) -> Optional[List[Ip]]:+ """Validate that all IP addresses in the list are valid and convert to Ip objects."""+ if v is None:+ return None++ validated_ips = []+ for ip in v:+ if not ip:+ continue++ try:+ # If already an Ip object, keep it+ if isinstance(ip, Ip):+ validated_ips.append(ip)+ # If string, convert to Ip (will validate automatically)+ elif isinstance(ip, str):+ validated_ips.append(Ip(address=ip))+ # If dict, convert to Ip+ elif isinstance(ip, dict):+ validated_ips.append(Ip(**ip))+ except Exception:+ # Skip invalid IPs+ continue++ return validated_ips if validated_ips else Nonediff --git a/flowsint-types/src/flowsint_types/ip.py b/flowsint-types/src/flowsint_types/ip.pyindex d40c6cd2..a329df47 100644--- a/flowsint-types/src/flowsint_types/ip.py+++ b/flowsint-types/src/flowsint_types/ip.py@@ -1,5 +1,6 @@-from pydantic import BaseModel, Field-from typing import Optional+from pydantic import BaseModel, Field, field_validator, model_validator+from typing import Optional, Any+import ipaddressclass Ip(BaseModel):@@ -21,3 +22,21 @@ class Ip(BaseModel):isp: Optional[str] = Field(None, description="Internet Service Provider", title="ISP")++ @model_validator(mode='before')+ @classmethod+ def convert_string_to_dict(cls, data: Any) -> Any:+ """Allow creating Ip from a string directly."""+ if isinstance(data, str):+ return {'address': data}+ return data++ @field_validator('address')+ @classmethod+ def validate_ip_address(cls, v: str) -> str:+ """Validate that the address is a valid IP address."""+ try:+ ipaddress.ip_address(v)+ return v+ except ValueError:+ raise ValueError(f"Invalid IP address: {v}")diff --git a/flowsint-types/src/flowsint_types/organization.py b/flowsint-types/src/flowsint_types/organization.pyindex df8cf3fa..3f84dc9c 100644--- a/flowsint-types/src/flowsint_types/organization.py+++ b/flowsint-types/src/flowsint_types/organization.py@@ -1,4 +1,4 @@-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, model_validatorfrom typing import Any, Optional, Listfrom .individual import Individualfrom .address import Location@@ -9,6 +9,14 @@ class Organization(BaseModel):# Basic informationname: Any = Field(..., description="Organization name", title="Organization Name")++ @model_validator(mode='before')+ @classmethod+ def convert_string_to_dict(cls, data: Any) -> Any:+ """Allow creating Organization from a string directly."""+ if isinstance(data, str):+ return {'name': data}+ return datasiren: Optional[Any] = Field(None, description="SIREN number", title="SIREN Number")nom_complet: Optional[Any] = Field(None, description="Complete name", title="Complete Name"@@ -72,7 +80,7 @@ class Organization(BaseModel):nature_juridique: Optional[Any] = Field(None, description="Legal nature", title="Legal Nature")- etat_adminiAnyatif: Optional[Any] = Field(+ etat_administratif: Optional[Any] = Field(None, description="AdminiAnyative status", title="AdminiAnyative Status")statut_diffusion: Optional[Any] = Field(@@ -82,7 +90,7 @@ class Organization(BaseModel):siege_activite_principale: Optional[Any] = Field(None, description="Siege main activity code", title="Headquarters Main Activity")- siege_activite_principale_regiAnye_metier: Optional[Any] = Field(+ siege_activite_principale_registre_metier: Optional[Any] = Field(None,description="Siege main activity in trade register",title="Headquarters Trade Register Activity",@@ -197,7 +205,7 @@ class Organization(BaseModel):title="Headquarters Foreign Country Label",)siege_libelle_voie: Optional[Any] = Field(- None, description="Siege Anyeet label", title="Headquarters Anyeet Label"+ None, description="Siege street label", title="Headquarters street Label")siege_liste_enseignes: Optional[List[Any]] = Field(None, description="Siege list of brands", title="Headquarters Brands List"@@ -229,7 +237,7 @@ class Organization(BaseModel):None, description="Siege commercial name", title="Headquarters Commercial Name")siege_numero_voie: Optional[Any] = Field(- None, description="Siege Anyeet number", title="Headquarters Anyeet Number"+ None, description="Siege street number", title="Headquarters street Number")siege_region: Optional[Any] = Field(None, description="Siege region code", title="Headquarters Region"@@ -248,7 +256,7 @@ class Organization(BaseModel):title="Headquarters Employee Size Range",)siege_type_voie: Optional[Any] = Field(- None, description="Siege Anyeet type", title="Headquarters Anyeet Type"+ None, description="Siege street type", title="Headquarters street Type")# Dirigeants (Leaders) - using Individual typedirigeants: Optional[List[Individual]] = Field(diff --git a/flowsint-types/src/flowsint_types/phone.py b/flowsint-types/src/flowsint_types/phone.pyindex 368e1c96..6e503be3 100644--- a/flowsint-types/src/flowsint_types/phone.py+++ b/flowsint-types/src/flowsint_types/phone.py@@ -1,5 +1,7 @@-from pydantic import BaseModel, Field-from typing import Optional+from pydantic import BaseModel, Field, field_validator, model_validator+from typing import Optional, Any+import phonenumbers+from phonenumbers import NumberParseExceptionclass Phone(BaseModel):@@ -12,3 +14,43 @@ class Phone(BaseModel):carrier: Optional[str] = Field(None, description="Mobile carrier or service provider", title="Carrier")++ @model_validator(mode='before')+ @classmethod+ def convert_string_to_dict(cls, data: Any) -> Any:+ """Allow creating Phone from a string directly."""+ if isinstance(data, str):+ return {'number': data}+ return data++ @field_validator('number')+ @classmethod+ def validate_phone_number(cls, v: str) -> str:+ """Validate phone number format using phonenumbers library.++ Tries to parse the number in multiple ways:+ 1. As international format (with + prefix)+ 2. With common region codes (US, GB, FR, etc.)+ """+ # If it looks like an international number (starts with +), try parsing without region+ if v.startswith('+'):+ try:+ parsed = phonenumbers.parse(v, None)+ if phonenumbers.is_valid_number(parsed):+ return v+ except NumberParseException:+ pass++ # Try parsing with common regions+ common_regions = ['US', 'GB', 'FR', 'DE', 'ES', 'IT', 'CA', 'AU', 'JP', 'CN']+ for region in common_regions:+ try:+ parsed = phonenumbers.parse(v, region)+ if phonenumbers.is_valid_number(parsed):+ # Return the number in international format+ return phonenumbers.format_number(parsed, phonenumbers.PhoneNumberFormat.E164)+ except NumberParseException:+ continue++ # If all attempts fail, raise an error+ raise ValueError(f"Invalid phone number: {v}. Must be in international format (+...) or a valid format for common regions.")diff --git a/flowsint-types/src/flowsint_types/port.py b/flowsint-types/src/flowsint_types/port.pyindex c2ac8bb1..384bede9 100644--- a/flowsint-types/src/flowsint_types/port.py+++ b/flowsint-types/src/flowsint_types/port.py@@ -1,4 +1,4 @@-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, field_validatorfrom typing import Optional@@ -18,3 +18,11 @@ class Port(BaseModel):banner: Optional[str] = Field(None, description="Service banner information", title="Banner")++ @field_validator('number')+ @classmethod+ def validate_port_number(cls, v: int) -> int:+ """Validate that port number is in valid range (0-65535)."""+ if not (0 <= v <= 65535):+ raise ValueError(f"Port number must be between 0 and 65535, got {v}")+ return vdiff --git a/flowsint-types/src/flowsint_types/username.py b/flowsint-types/src/flowsint_types/username.pyindex 1cab0345..732d3b0e 100644--- a/flowsint-types/src/flowsint_types/username.py+++ b/flowsint-types/src/flowsint_types/username.py@@ -1,5 +1,6 @@-from pydantic import BaseModel, Field-from typing import Optional+from pydantic import BaseModel, Field, field_validator, model_validator+from typing import Optional, Any+import reclass Username(BaseModel):@@ -10,3 +11,28 @@ class Username(BaseModel):last_seen: Optional[str] = Field(None, description="Last time this username was observed", title="Last seen at")++ @model_validator(mode='before')+ @classmethod+ def convert_string_to_dict(cls, data: Any) -> Any:+ """Allow creating Username from a string directly."""+ if isinstance(data, str):+ return {'value': data}+ return data++ @field_validator('value')+ @classmethod+ def validate_username(cls, v: str) -> str:+ """Validate username format.++ Username must be 3-30 characters long and contain only:+ - Letters (a-z, A-Z)+ - Numbers (0-9)+ - Underscores (_)+ - Hyphens (-)+ """+ if not re.match(r"^[a-zA-Z0-9_-]{3,30}$", v):+ raise ValueError(+ f"Invalid username: {v}. Must be 3-30 characters and contain only letters, numbers, underscores, and hyphens."+ )+ return vdiff --git a/flowsint-types/src/flowsint_types/whois.py b/flowsint-types/src/flowsint_types/whois.pyindex f19e6b56..67335369 100644--- a/flowsint-types/src/flowsint_types/whois.py+++ b/flowsint-types/src/flowsint_types/whois.py@@ -1,12 +1,16 @@-from typing import Optional-from pydantic import BaseModel, Field+from typing import Optional, Union+from pydantic import BaseModel, Field, field_validatorfrom .email import Email+from .domain import Domainclass Whois(BaseModel):"""Represents WHOIS domain registration information."""- domain: str = Field(..., description="Domain name", title="Domain")+ domain: Domain = Field(..., description="Domain information", title="Domain")+ registry_domain_id: Optional[str] = Field(+ None, description="Registry Domain ID (unique identifier)", title="Registry Domain ID"+ )registrar: Optional[str] = Field(None, description="Domain registrar name", title="Registrar")@@ -30,3 +34,15 @@ class Whois(BaseModel):expiration_date: Optional[str] = Field(None, description="Date when the domain expires", title="Expiration Date")++ @field_validator('domain', mode='before')+ @classmethod+ def convert_domain(cls, v: Union[str, dict, Domain]) -> Domain:+ """Convert string or dict to Domain object if needed."""+ if isinstance(v, Domain):+ return v+ elif isinstance(v, str):+ return Domain(domain=v)+ elif isinstance(v, dict):+ return Domain(**v)+ return v