guard-core is the framework-agnostic security engine that powers the Guard ecosystem. It provides IP control, rate limiting, penetration detection, security headers, and behavioral analysis through a protocol-based architecture. Framework-specific adapters (fastapi-guard, flaskapi-guard, djapi-guard) consume this library.
π Documentation - Full technical documentation for adapter developers.
π€ Monitoring Agent Integration - Monitor your Guard instance with a monitoring agent.
Guard Core is the engine. Framework adapters are thin wrappers that translate native request/response types into Guard Core's protocols:
guard-core (this library)
βββ fastapi-guard β ASGI adapter for FastAPI/Starlette
βββ flaskapi-guard β WSGI adapter for Flask
βββ djapi-guard β Django middleware adapter
Adapter developers implement three protocols β GuardRequest, GuardResponse, and GuardResponseFactory β to bridge their framework into the security pipeline. Everything else (17 security checks, detection engine, Redis state, event telemetry) works out of the box.
- IP Whitelisting and Blacklisting: Control access based on IP addresses and CIDR ranges.
- User Agent Filtering: Block requests from specific user agents.
- Rate Limiting: Sliding window algorithm with in-memory and Redis-backed storage.
- Automatic IP Banning: Threshold-based banning with configurable duration.
- Penetration Attempt Detection: SQL injection, XSS, command injection, path traversal detection with semantic analysis.
- HTTP Security Headers: CSP, HSTS, X-Frame-Options, and OWASP best practices.
- Cloud Provider IP Blocking: Block requests from AWS, GCP, Azure IP ranges.
- IP Geolocation: Country-based access control via GeoIP databases.
- Behavioral Analysis: Usage monitoring, return pattern detection, frequency analysis.
- Security Decorators: Route-level security with composable decorator mixins.
- Detection Engine: Multi-layered threat detection with regex, semantic analysis, and performance monitoring.
- Distributed State Management: Redis integration for shared state across instances.
- Protocol-Based Architecture: Framework-agnostic via
GuardRequest/GuardResponseprotocols.
pip install guard-coreIf you're building a framework adapter, add guard-core as a dependency:
[project]
dependencies = [
"guard-core",
]Then implement the three protocols:
from guard_core.protocols import GuardRequest, GuardResponse, GuardResponseFactory
class MyFrameworkRequest:
"""Wraps your framework's request into GuardRequest protocol."""
def __init__(self, native_request):
self._request = native_request
@property
def url_path(self) -> str:
return self._request.path
@property
def method(self) -> str:
return self._request.method
@property
def client_host(self) -> str | None:
return self._request.remote_addr
@property
def headers(self):
return dict(self._request.headers)
# ... implement remaining protocol propertiesSee the Building Adapters Guide for the complete walkthrough.
Guard Core executes 17 security checks in order for every request:
- Route configuration extraction
- Emergency mode
- HTTPS enforcement
- Request logging
- Size/content validation
- Required headers
- Authentication
- Referrer validation
- Custom validators
- Time windows
- Cloud IP refresh
- IP security (whitelist/blacklist)
- Cloud provider blocking
- User agent filtering
- Rate limiting
- Suspicious activity detection
- Custom request checks
Each check returns None (pass) or a GuardResponse (block). The pipeline short-circuits on the first blocking response.
All behavior is controlled through SecurityConfig:
from guard_core.models import SecurityConfig
config = SecurityConfig(
whitelist=["192.168.1.0/24"],
blacklist=["10.0.0.1"],
blocked_countries=["CN"],
blocked_user_agents=["curl", "wget"],
auto_ban_threshold=5,
auto_ban_duration=86400,
rate_limit=100,
rate_limit_window=60,
enforce_https=True,
block_cloud_providers={"AWS", "GCP", "Azure"},
enable_redis=True,
redis_url="redis://localhost:6379",
)See the SecurityConfig Reference for all fields.
Multi-layered threat detection:
- PatternCompiler: ReDoS-safe regex compilation with LRU caching and timeout protection.
- ContentPreprocessor: Unicode normalization, encoding detection, attack-region-aware truncation.
- SemanticAnalyzer: Attack probability scoring, entropy analysis, obfuscation detection.
- PerformanceMonitor: Anomaly detection, slow pattern tracking, statistical analysis.
See the Detection Engine Internals for details.
Distributed state management across multiple instances:
config = SecurityConfig(
enable_redis=True,
redis_url="redis://prod-redis:6379/1",
redis_prefix="myapp:security:",
)Provides atomic rate limiting, distributed IP ban tracking, cloud IP range caching, and pattern storage.
# Clone and install
git clone https://github.com/rennf93/guard-core.git
cd guard-core
make install-dev
# Run tests (100% coverage)
make local-test
# Run all quality checks
make check-all
# Serve documentation
make serve-docsContributions are welcome! Please open an issue or submit a pull request on GitHub.
This project is licensed under the MIT License. See the LICENSE file for details.
Renzo Franceschini - rennf93@users.noreply.github.com