防护思路
点击放大

![CI/CD Pipeline]()
![Docker Pulls]()
![Python 3.11+]()
![FastAPI]()
![License: ELv2]()
A production-ready defensi microservice for detecting and mitigating prompt injection attacks, PII exposure, and other security threats in LLM-based systems. PromptSentinel provides real-time protection using multi-layered detection strategies with sub-100ms response times.
We provide a comprehensi with 40+ commands:
#### POST /api/v1/detect - Simple Detection
Response:
#### POST /api/v1/detect - Ad Detection with Role Support
#### POST /api/v1/analyze - Comprehensi
Provides detailed analysis including PII detection, format , and security recommendations.
#### POST /api/v1/detect/intelligent - Intelligent Routing Detection (NEW)
Automatically analyzes prompt complexity and routes to optimal detection strategy:
Features:
#### GET /api/v1/routing/complexity - Complexity Analysis
Analyze prompt complexity without detection:
#### GET /api/v1/routing/metrics - Routing Metrics
Get intelligent routing performance statistics.
#### GET /api/v1/metrics/complexity - Complexity Metrics
Comprehensi complexity metrics and distribution:
Configuration: Budget and rate limits are now configurable :
#### GET /api/v1/monitoring/usage - API Usage Metrics
Track API usage, costs, and performance:
Returns:
#### GET /api/v1/monitoring/budget - Budget Status
Monitor spending against configured limits:
Features:
#### GET /api/v1/monitoring/rate-limits - Rate Limit Status
Check current rate limiting status:
#### GET /api/v1/monitoring/usage/trend - Usage Trends
Historical usage data for analysis:
#### POST /api/v1/monitoring/budget/configure - Configure Budget
Dynamically update budget limits:
#### GET /api/v1/cache/stats - Cache Statistics
When running, visit:
PromptSentinel uses confidence scores to indicate the certainty of its detection . Understanding these scores is crucial for implementing appropriate response strategies.
Confidence scores range from 0.0 to 1.0:
The confidence score represents how certain PromptSentinel is about its , NOT the se of the threat. The same confidence value (e.g., 0.95) can appear with different :
#### Example 1: High Confidence ALLOW (Safe Content)
Request:
Response:
Interpretation: The system is 95% confident this content is SAFE.
#### Example 2: High Confidence BLOCK (Malicious Content)
Request:
Response:
Interpretation: The system is 92% confident this content is MALICIOUS.
#### Example 3: Low Confidence FLAG (Uncertain)
Request:
Response:
Interpretation: The system is only 45% confident about this . The content mentions "system prompts" which could be innocent or malicious depending on context. Manual review recommended.
| Confidence | | Meaning | Recommended Action |
|------------|---------|---------|-------------------|
| 0.95 | allow | 95% certain content is safe | Process normally |
| 0.95 | block | 95% certain content is malicious | Block immediately |
| 0.45 | allow | Uncertain, but leaning toward safe | Monitor/log for analysis |
| 0.45 | flag | Uncertain, possibly suspicious | Manual review recommended |
| 0.45 | block | Uncertain, but concerning patterns | Consider blocking or review |
Different detection methods contribute different confidence levels:
1. Heuristic Detection:
- Pattern matches: 0.7 - 0.95 confidence based on pattern strength
- No patterns matched: 0.95 confidence for benign content
2. LLM Classification:
- Typically provides 0.6 - 0.9 confidence based on model certainty
- Lower confidence for ambiguous or context-dependent content
3. Combined Detection:
- When both methods agree: Confidence boosted by up to 0.1
- When methods disagree: Lower confidence, typically 0.4 - 0.6
Detection mode affects confidence thresholds for :
PromptSentinel supports flexible authentication to fit different deployment scenarios:
| Mode | Use Case | Description |
|------|----------|-------------|
| none | Sidecar/Internal | No authentication required - for trusted en |
| optional | De/Mixed | API keys improve rate limits but aren't required |
| required | Public Access/Sensitive Info | API keys mandatory for all requests |
#### 1. Sidecar Container (No Auth)
#### 2. Internal Microservice (Optional Auth)
#### 3. Public Deployment (Required Auth)
#### Generate API Key (Admin)
#### Using API Keys
PromptSentinel includes configurable rate limiting to prevent abuse and manage resource usage. These limits are fully configurable based on your deployment needs:
Rate limits are enforced using a token bucket algorithm and can be adjusted based on your infrastructure capacity and security requirements.
| Mode | Description | False Positives | False Negatives | Use Case |
|------|-------------|-----------------|-----------------|----------|
| Strict | Maximum security | Higher | Lower | Financial, Healthcare |
| Moderate | Balanced approach | Medium | Medium | General applications |
| Permissive | Minimize false positives | Lower | Higher | Content creation tools |
PromptSentinel includes an ad ML-based pattern discovery system that automatically learns from detected threats:
1. Event Collection: Detection events are collected in a circular buffer
2. Feature Extraction: Multi-dimensional features extracted from prompts
3. Clustering: Similar attacks grouped using density-based clustering
4. Pattern Mining: Common patterns extracted using multiple techniques:
- Common substring analysis
- N-gram pattern matching
- Template-based extraction
- Differential analysis
5. E: Patterns tested and scored for precision/recall
6. Promotion: High-performing patterns automatically activated
7. Integration: Discovered patterns seamlessly integrated with heuristic detection
PromptSentinel includes an ad machine learning system that automatically discovers new attack patterns from blocked requests:
PromptSentinel provides WebSocket support for real-time streaming detection and continuous monitoring:
| Type | Direction | Description |
|------|-----------|-------------|
| detection | Client→Server | Single prompt detection |
| analysis | Client→Server | Comprehensi |
| batch_detection | Client→Server | Multiple prompts |
| ping | Client→Server | Heartbeat check |
| stats | Client→Server | Get connection stats |
| detection_response | Server→Client | Detection result |
| analysis_response | Server→Client | Analysis result |
| system_message | Server→Client | System notifications |
PromptSentinel includes optional Redis caching that provides:
PromptSentinel detects and redacts 15+ PII types:
| Mode | Example Input | Example Output | Use Case |
|------|---------------|----------------|----------|
| mask | SSN: 123-45-6789 | SSN: XXX-XX-6789 | Default - partial |
| remove | My SSN is 123-45-6789 | My SSN is [SSN_REMOVED] | Complete removal |
| hash | | a3f5b2c8... | Consistent anonymization |
| reject | (any PII detected) | (request blocked) | Zero tolerance |
PromptSentinel supports defining custom PII detection patterns specific to your organization through YAML configuration files. This allows you to detect domain-specific sensitive data like employee IDs, internal project codes, or proprietary identifiers.
Create a config/custom_pii_rules.yaml file:
📚 Full Documentation - Comprehensi with security considerations, best practices, and industry-specific examples.
📚 Full testing documentation: See docs/TESTING.md
Edit src/prompt_sentinel/detection/heuristics.py:
API_EN and DEBUG=false| Scenario | Latency (P50) | Latency (P95) | Throughput |
|----------|---------------|---------------|------------|
| Heuristic only | 8ms | 15ms | 5000 req/s |
| LLM only (no cache) | 700ms | 1500ms | 50 req/s |
| LLM with cache | 12ms | 25ms | 2000 req/s |
| Full detection + cache | 15ms | 35ms | 1500 req/s |
1. Enable Redis caching for 98% latency reduction
2. Use heuristic-only mode for high-, low-risk scenarios
3. Implement rate limiting to prevent abuse
4. Use connection pooling for database connections
5. Deploy multiple replicas for high a
This is a defensi tool. Please:
PromptSentinel provides comprehensi check endpoints for monitoring and orchestration:
#### Basic Health Check
Returns:
#### Detailed Component Health
Returns detailed status for:
#### Kubernetes Probes
The readiness probe checks:
Configure OTLP endpoint for traces and metrics:
We welcome contributions! Please see our Contributing Guide for details.
1. Fork the repository
2. Create your feature branch (git checkout -b feature/amazing-feature)
3. Write tests for your changes
4. Ensure all tests pass (make test)
5. Commit your changes (git commit -m 'Add amazing feature')
6. Push to the branch (git push origin feature/amazing-feature)
7. Open a Pull Request
This project is licensed under the Elastic License 2.0 (ELv2) - see the LICENSE file for details.
✅ You CAN:
❌ You CANNOT:
promptsentinelai/prompt-sentineldocs/ROADMAP.md)prompt_sentinel.monitoring in productiondocs/ROADMAP.md for the full, regularly updated roadmap including:Some modules are provided as scaffolding for future features and for tests. They are not wired into production flows by default:
prompt_sentinel.obser.* (logging, tracing, pipeline): in-memory/test stubs. Prefer prompt_sentinel.monitoring.metrics (Prometheus-backed) in production. See docs/ROADMAP.md.prompt_sentinel.api.performance_middleware: experimental; disabled by default.prompt_sentinel.i18n.* (localization, translator, detector helpers): experimental; minimal functionality intended for tests/examples.api/batch_endpoint.py: stubbed (NotImplementedError) until async orchestration is introduced.Refer to docs/ROADMAP.md for the status and planned milestones of these modules.
---
Built with ❤️ + ☕️ && 🥃 for securing all the things
*: 1.0.0 | Status: Production Ready*
开发语言:Python
Star 数:2
该项目属于防护思路方向的开源资源,代码结构清晰,适合安全研究人员学习参考。项目围绕A defensive security microservice for detecting and mitigating prompt injection attacks in LLM-based systems. PromptSentinel provides real-time protection using multi-layered detection strategies.展开,提供了可运行的实现,对理解相关安全机制、工具原理与攻防技术具有较高的研究价值。
从技术实现角度看,此类项目的核心在于对底层原理的深入理解与工程化落地。开发者在研究过程中可以结合官方文档与社区讨论,梳理项目的初始化流程、核心模块职责与数据流转,逐步掌握其中的技术细节与设计思路。
1. 下载源码压缩包,解压到本地环境。
2. 根据项目类型准备对应的运行环境与依赖。
3. 按照 README 中的步骤完成配置与部署。
4. 在隔离的测试环境中运行验证,避免影响生产系统。
本资源来源于开源社区,仅供安全研究、技术学习与合法授权范围内的攻防演练使用,请勿用于任何非法或侵害他人权益的用途。使用本项目产生的一切后果由使用者自行承担。
| 资源标题 | prompt-sentinel - A defensive security microservice for detecting an |
| 所属分类 | 防护思路 |
| 发布作者 | admin |
| 发布时间 | 2026-10-06 00:20:55 |
| 下载权限 | 免费下载 |
| 附件数量 | 2 个下载链接 |
| 浏览次数 | 455 |
| 讨论数量 | 0 |
| 主题状态 | 正常讨论中 |