Skip to content

Models

guard_core.models

DynamicRules

Bases: BaseModel

blocked_cloud_providers = Field(default_factory=set, description='Cloud providers to block') class-attribute instance-attribute

blocked_countries = Field(default_factory=list, description='Countries to block') class-attribute instance-attribute

blocked_user_agents = Field(default_factory=list, description='User agents to block') class-attribute instance-attribute

emergency_mode = Field(default=False, description='Emergency lockdown mode') class-attribute instance-attribute

emergency_whitelist = Field(default_factory=list, description='Emergency whitelist IPs') class-attribute instance-attribute

enable_ip_banning = Field(default=None, description='Override IP banning setting') class-attribute instance-attribute

enable_penetration_detection = Field(default=None, description='Override penetration detection setting') class-attribute instance-attribute

enable_rate_limiting = Field(default=None, description='Override rate limiting setting') class-attribute instance-attribute

endpoint_rate_limits = Field(default_factory=dict, description='Per-endpoint rate limits {endpoint: (requests, window)}') class-attribute instance-attribute

expires_at = Field(default=None, description='Rule expiration time') class-attribute instance-attribute

global_rate_limit = Field(default=None, description='Global rate limit') class-attribute instance-attribute

global_rate_window = Field(default=None, description='Global rate window') class-attribute instance-attribute

ip_ban_duration = Field(default=3600, description='Ban duration in seconds') class-attribute instance-attribute

ip_blacklist = Field(default_factory=list, description='IPs to ban') class-attribute instance-attribute

ip_whitelist = Field(default_factory=list, description='IPs to allow') class-attribute instance-attribute

model_config = ConfigDict(arbitrary_types_allowed=True) class-attribute instance-attribute

rule_id = Field(description='Unique rule ID') class-attribute instance-attribute

suspicious_patterns = Field(default_factory=list, description='Additional suspicious patterns') class-attribute instance-attribute

timestamp = Field(description='Rule creation/update timestamp') class-attribute instance-attribute

ttl = Field(default=300, description='Cache TTL in seconds') class-attribute instance-attribute

version = Field(description='Rule version number') class-attribute instance-attribute

whitelist_countries = Field(default_factory=list, description='Countries to allow') class-attribute instance-attribute

SecurityConfig

Bases: BaseModel

agent_api_key = Field(default=None, description='API key for Guard Agent SaaS platform') class-attribute instance-attribute

agent_buffer_size = Field(default=100, description='Number of events to buffer before auto-flush') class-attribute instance-attribute

agent_enable_events = Field(default=True, description='Enable sending security events to SaaS platform') class-attribute instance-attribute

agent_enable_metrics = Field(default=True, description='Enable sending performance metrics to SaaS platform') class-attribute instance-attribute

agent_endpoint = Field(default='https://api.fastapi-guard.com', description='Guard Agent SaaS platform endpoint') class-attribute instance-attribute

agent_flush_interval = Field(default=30, description='Interval in seconds between automatic buffer flushes') class-attribute instance-attribute

agent_project_id = Field(default=None, description='Project ID for organizing telemetry data') class-attribute instance-attribute

agent_retry_attempts = Field(default=3, description='Number of retry attempts for failed requests') class-attribute instance-attribute

agent_timeout = Field(default=30, description='Timeout in seconds for agent HTTP requests') class-attribute instance-attribute

auto_ban_duration = Field(default=3600, description='Duration of auto-ban in seconds (default: 1 hour)') class-attribute instance-attribute

auto_ban_threshold = Field(default=10, description='Number of suspicious requests before auto-ban') class-attribute instance-attribute

blacklist = Field(default_factory=list, description='Blocked IP addresses or CIDR ranges') class-attribute instance-attribute

block_cloud_providers = Field(default=None, description='Set of cloud provider names to block') class-attribute instance-attribute

blocked_countries = Field(default_factory=list, description='A list of country codes that are always blocked') class-attribute instance-attribute

blocked_user_agents = Field(default_factory=list, description='Blocked user agents') class-attribute instance-attribute

cloud_ip_refresh_interval = Field(default=3600, description='Interval in seconds between cloud IP range refreshes', ge=60, le=86400) class-attribute instance-attribute

cors_allow_credentials = Field(default=False, description='Whether to allow credentials in CORS requests') class-attribute instance-attribute

cors_allow_headers = Field(default_factory=(lambda: ['*']), description='Headers allowed in CORS requests') class-attribute instance-attribute

cors_allow_methods = Field(default_factory=(lambda: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']), description='Methods allowed in CORS requests') class-attribute instance-attribute

cors_allow_origins = Field(default_factory=(lambda: ['*']), description='Origins allowed in CORS requests') class-attribute instance-attribute

cors_expose_headers = Field(default_factory=list, description='Headers exposed in CORS responses') class-attribute instance-attribute

cors_max_age = Field(default=600, description='Maximum age of CORS preflight results') class-attribute instance-attribute

custom_error_responses = Field(default_factory=dict, description='Custom error for specific HTTP status codes') class-attribute instance-attribute

custom_log_file = Field(default=None, description='The path to a custom log file for logging security events') class-attribute instance-attribute

custom_request_check = Field(default=None, description='Perform additional checks on the request') class-attribute instance-attribute

custom_response_modifier = Field(default=None, description="A custom function to modify the response before it's sent") class-attribute instance-attribute

detection_anomaly_threshold = Field(default=3.0, description='Standard deviations from mean to consider anomaly', ge=1.0, le=10.0) class-attribute instance-attribute

detection_compiler_timeout = Field(default=2.0, description='Timeout for pattern compilation and matching (seconds)', ge=0.1, le=10.0) class-attribute instance-attribute

detection_max_content_length = Field(default=10000, description='Maximum content length for pattern detection', ge=1000, le=100000) class-attribute instance-attribute

detection_max_tracked_patterns = Field(default=1000, description='Maximum number of patterns to track for performance', ge=100, le=5000) class-attribute instance-attribute

detection_monitor_history_size = Field(default=1000, description='Number of recent metrics to keep in history', ge=100, le=10000) class-attribute instance-attribute

detection_preserve_attack_patterns = Field(default=True, description='Preserve attack patterns during content truncation') class-attribute instance-attribute

detection_semantic_threshold = Field(default=0.7, description='Threshold for semantic attack detection (0.0-1.0)', ge=0.0, le=1.0) class-attribute instance-attribute

detection_slow_pattern_threshold = Field(default=0.1, description='Execution time to consider pattern slow (seconds)', ge=0.01, le=1.0) class-attribute instance-attribute

dynamic_rule_interval = Field(default=300, description='Interval in seconds between dynamic rule updates') class-attribute instance-attribute

emergency_mode = Field(default=False, description='Emergency lockdown mode (set by dynamic rules)') class-attribute instance-attribute

emergency_whitelist = Field(default_factory=list, description='Emergency whitelist IPs (set by dynamic rules)') class-attribute instance-attribute

enable_agent = Field(default=False, description='Enable Guard Agent telemetry and monitoring') class-attribute instance-attribute

enable_cors = Field(default=False, description='Enable/disable CORS') class-attribute instance-attribute

enable_dynamic_rules = Field(default=False, description='Enable dynamic rule updates from SaaS platform') class-attribute instance-attribute

enable_ip_banning = Field(default=True, description='Enable/disable IP banning functionality') class-attribute instance-attribute

enable_penetration_detection = Field(default=True, description='Enable/disable penetration attempt detection') class-attribute instance-attribute

enable_rate_limiting = Field(default=True, description='Enable/disable rate limiting functionality') class-attribute instance-attribute

enable_redis = Field(default=True, description='Enable/disable Redis for distributed state management') class-attribute instance-attribute

endpoint_rate_limits = Field(default_factory=dict, description='Per-endpoint rate limits set by dynamic rules') class-attribute instance-attribute

enforce_https = Field(default=False, description='Whether to enforce HTTPS connections') class-attribute instance-attribute

exclude_paths = Field(default_factory=(lambda: ['/docs', '/redoc', '/openapi.json', '/openapi.yaml', '/favicon.ico', '/static']), description='Paths to exclude from security checks') class-attribute instance-attribute

geo_ip_handler = Field(default=None, description='Geographical IP handler to use for IP geolocation') class-attribute instance-attribute

ipinfo_db_path = Field(default=(Path('data/ipinfo/country_asn.mmdb')), description='Path to the IPInfo database file. Deprecated. Create a custom `geo_ip_handler` instead.') class-attribute instance-attribute

ipinfo_token = Field(default=None, description='IPInfo API token for IP geolocation. Deprecated. Create a custom `geo_ip_handler` instead.') class-attribute instance-attribute

log_format = Field(default='text', description="Log output format: 'text' or 'json' for structured JSON") class-attribute instance-attribute

log_request_level = Field(default=None, description='Log level for requests') class-attribute instance-attribute

log_suspicious_level = Field(default='WARNING', description='Log level for suspicious requests') class-attribute instance-attribute

model_config = ConfigDict(arbitrary_types_allowed=True) class-attribute instance-attribute

passive_mode = Field(default=False, description="Enable Log-Only mode. Won't block requests, only log.") class-attribute instance-attribute

rate_limit = Field(default=10, description='Maximum requests per rate_limit_window') class-attribute instance-attribute

rate_limit_window = Field(default=60, description='Rate limiting time window (seconds)') class-attribute instance-attribute

redis_prefix = Field(default='guard_core:', description='Prefix for Redis keys to avoid collisions with other apps') class-attribute instance-attribute

redis_url = Field(default='redis://localhost:6379', description='Redis URL for distributed state management') class-attribute instance-attribute

security_headers = Field(default_factory=(lambda: {'enabled': True, 'hsts': {'max_age': 31536000, 'include_subdomains': True, 'preload': False}, 'csp': None, 'frame_options': 'SAMEORIGIN', 'content_type_options': 'nosniff', 'xss_protection': '1; mode=block', 'referrer_policy': 'strict-origin-when-cross-origin', 'permissions_policy': 'geolocation=(), microphone=(), camera=()', 'custom': None}), description='Security headers configuration') class-attribute instance-attribute

trust_x_forwarded_proto = Field(default=False, description='Trust X-Forwarded-Proto header for HTTPS detection') class-attribute instance-attribute

trusted_proxies = Field(default_factory=list, description='List of trusted proxy IPs or CIDR ranges for X-Forwarded-For') class-attribute instance-attribute

trusted_proxy_depth = Field(default=1, description='How many proxies to expect in the X-Forwarded-For chain') class-attribute instance-attribute

whitelist = Field(default=None, description='Allowed IP addresses or CIDR ranges') class-attribute instance-attribute

whitelist_countries = Field(default_factory=list, description='A list of country codes that are always allowed') class-attribute instance-attribute

to_agent_config()

Source code in guard_core/models.py
def to_agent_config(self) -> "AgentConfig | None":
    if not self.enable_agent or not self.agent_api_key:
        return None

    try:
        from guard_agent import AgentConfig

        return AgentConfig(
            api_key=self.agent_api_key,
            endpoint=self.agent_endpoint,
            project_id=self.agent_project_id,
            buffer_size=self.agent_buffer_size,
            flush_interval=self.agent_flush_interval,
            enable_events=self.agent_enable_events,
            enable_metrics=self.agent_enable_metrics,
            timeout=self.agent_timeout,
            retry_attempts=self.agent_retry_attempts,
        )
    except ImportError:
        return None

validate_agent_config()

Source code in guard_core/models.py
@model_validator(mode="after")  # type: ignore
def validate_agent_config(self) -> Self:
    if self.enable_agent and not self.agent_api_key:
        raise ValueError("agent_api_key is required when enable_agent is True")

    if self.enable_dynamic_rules and not self.enable_agent:
        raise ValueError(
            "enable_agent must be True when enable_dynamic_rules is True"
        )

    return self

validate_cloud_providers(v)

Source code in guard_core/models.py
@field_validator("block_cloud_providers", mode="before")  # type: ignore
def validate_cloud_providers(cls, v: Any) -> set[str]:
    valid_providers = {"AWS", "GCP", "Azure"}
    if v is None:
        return set()
    return {p for p in v if p in valid_providers}

validate_geo_ip_handler_exists()

Source code in guard_core/models.py
@model_validator(mode="after")  # type: ignore
def validate_geo_ip_handler_exists(self) -> Self:
    if self.geo_ip_handler is None and (
        self.blocked_countries or self.whitelist_countries
    ):
        if self.ipinfo_token:
            from guard_core.handlers.ipinfo_handler import IPInfoManager

            self.geo_ip_handler = IPInfoManager(
                token=self.ipinfo_token,
                db_path=self.ipinfo_db_path,
            )
        else:
            raise ValueError(
                "geo_ip_handler is required "
                "if blocked_countries or whitelist_countries is set"
            )
    return self

validate_ip_lists(v)

Source code in guard_core/models.py
@field_validator("whitelist", "blacklist")  # type: ignore
def validate_ip_lists(cls, v: list[str] | None) -> list[str] | None:
    if v is None:
        return None

    validated = []
    for entry in v:
        try:
            if "/" in entry:
                network = ip_network(entry, strict=False)
                validated.append(str(network))
            else:
                addr = ip_address(entry)
                validated.append(str(addr))
        except ValueError:
            raise ValueError(f"Invalid IP or CIDR range: {entry}") from None
    return validated

validate_proxy_depth(v)

Source code in guard_core/models.py
@field_validator("trusted_proxy_depth")  # type: ignore
def validate_proxy_depth(cls, v: int) -> int:
    if v < 1:
        raise ValueError("trusted_proxy_depth must be at least 1")
    return v

validate_trusted_proxies(v)

Source code in guard_core/models.py
@field_validator("trusted_proxies")  # type: ignore
def validate_trusted_proxies(cls, v: list[str]) -> list[str]:
    if not v:
        return []

    validated = []
    for entry in v:
        try:
            if "/" in entry:
                network = ip_network(entry, strict=False)
                validated.append(str(network))
            else:
                addr = ip_address(entry)
                validated.append(str(addr))
        except ValueError:
            raise ValueError(f"Invalid proxy IP or CIDR range: {entry}") from None
    return validated