Framework-agnostic security engine for the Guard ecosystem.
Project description
guard-core is the framework-agnostic security engine that powers the Guard ecosystem. It provides IP control, rate limiting, signature-based attack-pattern detection, security headers, and threshold-based behavior tracking through a protocol-based architecture. Framework-specific adapters (fastapi-guard, flaskapi-guard, djapi-guard) consume this library.
Website · Docs · Playground · Dashboard · Discord
Documentation
📚 Documentation - Full technical documentation for adapter developers.
🤖 Monitoring Agent Integration - Monitor your Guard instance with a monitoring agent.
Ecosystem
Guard Core is the Python engine. Framework adapters are thin wrappers that translate native request/response types into Guard Core's protocols. The telemetry agent ships security events and metrics to the monitoring backend. Parallel implementations exist for TypeScript (on npm) and Rust (on crates.io).
Python
| Package | Role | PyPI |
|---|---|---|
| guard-core | Framework-agnostic security engine (this package) | |
| guard-agent | Telemetry agent | |
| fastapi-guard | FastAPI / Starlette adapter | |
| flaskapi-guard | Flask adapter | |
| djapi-guard | Django adapter | |
| tornadoapi-guard | Tornado adapter |
TypeScript / JavaScript
Published under the @guardcore npm scope. Source in the guard-core-ts monorepo. Production-ready.
| Package | Role | npm |
|---|---|---|
| @guardcore/core | Core engine | |
| @guardcore/express | Express adapter | |
| @guardcore/nestjs | NestJS adapter | |
| @guardcore/fastify | Fastify adapter | |
| @guardcore/hono | Hono adapter |
Rust
Published on crates.io. 🚧 Placeholder crates — implementation in progress.
| Package | Role | crates.io |
|---|---|---|
| guard-core | Core engine | |
| actix-guard-rs | Actix adapter | |
| axum-guard-rs | Axum adapter | |
| rocket-guard-rs | Rocket adapter | |
| tower-guard-rs | Tower 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.
Features
- 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.
- Threshold-Based Behavior Tracking: Per-IP request counting, response-pattern matching, suspicious-frequency triggers (deterministic threshold matching, not learning-based).
- 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.
How Detection Works
- Request inputs (query, headers, body) are decoded through up to 7 layers covering URL, HTML entities, base64, hex, Unicode escapes, and SQL comments.
- Decoded content is matched against ~64 regex patterns across 16 attack categories, with patterns context-filtered to relevant input zones.
- Matched payloads receive a multi-metric semantic score combining keyword overlap, Shannon entropy, encoding-layer count, and obfuscation indicators.
- ReDoS protection enforces a 0.1s pattern-validation timeout and a 2-5s match timeout per pattern.
The engine is signature-based with multi-metric semantic scoring on top. It is not machine-learning-based and does not learn from traffic.
Installation
pip install guard-core
For Adapter Developers
If 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 properties
See the Building Adapters Guide for the complete walkthrough.
Security Pipeline
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.
SecurityConfig
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.
Detection Engine
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: Slow-pattern detection via execution-time statistics (mean/stddev thresholds), not anomaly learning.
See the Detection Engine Internals for details.
Redis Integration
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.
Development
# 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-docs
Contributing
Contributions are welcome! Please open an issue or submit a pull request on GitHub.
License
This project is licensed under the MIT License. See the LICENSE file for details.
Author
Renzo Franceschini - rennf93@users.noreply.github.com
Acknowledgements
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file guard_core-2.2.2.tar.gz.
File metadata
- Download URL: guard_core-2.2.2.tar.gz
- Upload date:
- Size: 188.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.20
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b7cfd8a0aefc62603e0f6695948f9a6ec6cd6fd510e7a158c9ab58f04fdcd2b1
|
|
| MD5 |
08848104d734fd1963a66b203faafcfa
|
|
| BLAKE2b-256 |
2d21ad46de8791359b5c1192179fb05fd18cc41c124b63c5bc42a0024612c674
|
File details
Details for the file guard_core-2.2.2-py3-none-any.whl.
File metadata
- Download URL: guard_core-2.2.2-py3-none-any.whl
- Upload date:
- Size: 218.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.20
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
07c89422be31c700af403216a2d0d400002fcf6cb4d9f5175a12442f35f16ed2
|
|
| MD5 |
8fd1c3922fed6619b6d1b8e326160916
|
|
| BLAKE2b-256 |
39e03070f24d90715642544ba30ed2f83a3170d88410e92ac5326cc4c2127d25
|