JeeveshPandey29/Intelligent-API-Security-Gateway-with-AI-Based-Threat-Detection
GitHub: JeeveshPandey29/Intelligent-API-Security-Gateway-with-AI-Based-Threat-Detection
一个集成 AI 异常检测的智能 API 安全网关,解决流量滥用与恶意请求问题。
Stars: 0 | Forks: 0
# 🛡️ 智能 API 安全网关
## 架构概述
```
┌─────────────┐ ┌──────────────────────────────────────────────────┐
│ Client │───▶│ API GATEWAY (Node.js/Express) │
└─────────────┘ │ │
│ ┌─────────┐ ┌──────────┐ ┌───────────────────┐ │
│ │IP Filter│→│Fingerprint│→│ Abuse Detector │ │
│ └─────────┘ └──────────┘ └───────────────────┘ │
│ ┌──────────┐ ┌────┐ ┌────────┐ ┌───────────┐ │
│ │Rate Limit│→│Auth│→│ RBAC │→│ AI Client │ │
│ └──────────┘ └────┘ └────────┘ └─────┬─────┘ │
│ │ │
└────────────────────────────────────────┼──────────┘
│ │ │
┌──────────▼──┐ ┌──────▼──────┐ ┌─────▼──────┐
│User Service │ │Order Service │ │ AI Engine │
│ (Node.js) │ │ (Node.js) │ │ (Python) │
└─────────────┘ └─────────────┘ └────────────┘
Infrastructure: Redis │ MongoDB │ Prometheus │ Grafana
```
## 功能特性
### 安全流水线(请求流程)
1. **IP 过滤器** – 基于 Redis 后端的动态黑白名单
2. **请求指纹识别** – IP 与头部信息的 SHA-256 哈希;检测 IP 轮换异常
3. **滥用检测器** – 端点爬取与机器人重复行为检测并自动封禁
4. **速率限制器** – 基于 Redis 的分布式速率限制
5. **身份验证** – JWT 承载令牌 + 静态 API 密钥
6. **RBAC** – 基于角色的访问控制(管理员/用户角色)
7. **AI 威胁分析** – IsolationForest 机器学习模型与断路器及静态降级
### 高级能力
- **蜜罐端点** – 虚假路径(例如 `/wp-login.php`、`/.env`)自动封禁扫描器
- **断路器** – 当 AI 引擎宕机时防止级联故障
- **负载均衡器** – 轮询调度并跟踪上游服务健康状态
- **响应缓存** – 基于 Redis 的 GET 响应缓存与 TTL
- **实时告警** – SMTP 邮件 + Slack Webhook 通知,带频率限制
- **分段日志** – 三路 Winston 日志(正常、安全、审计)
- **Prometheus 指标** – HTTP 请求时长直方图、请求计数器、Node.js 指标
### AI 引擎
- **模型**:Scikit-Learn `IsolationForest`(200 估计器)
- **特征**:请求频率、负载大小、认证失败数、唯一端点、时间特征
- **训练**:启动时基于合成数据自动训练
- **评分**:返回归一化风险分数(0-1)并标记为恶意/正常
## 快速开始
### 前置条件
- Docker & Docker Compose
- (可选)本地开发需要 Node.js 18+ 和 Python 3.11+
### 启动所有服务
```
# 克隆并启动
docker-compose up -d --build
# 验证所有服务
docker-compose ps
```
### 服务端点
| 服务 | URL | 描述 |
|-------------|------------------------------|------------------------|
| API 网关 | `http://localhost:3000` | 主要入口点 |
| AI 引擎 | `http://localhost:8000` | 威胁分析 API |
| 用户服务 | `http://localhost:4001` | 上游微服务 |
| 订单服务 | `http://localhost:4002` | 仅管理员微服务 |
| Prometheus | `http://localhost:9090` | 指标仪表盘 |
| Grafana | `http://localhost:3001` | 可视化(admin/admin) |
## API 使用
### 1. 注册用户
```
curl -X POST http://localhost:3000/auth/register \
-H "Content-Type: application/json" \
-d '{"username":"testuser","email":"test@example.com","password":"securepass123"}'
```
### 2. 登录
```
curl -X POST http://localhost:3000/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"testuser","password":"securepass123"}'
```
### 3. 访问用户服务(已认证)
```
curl http://localhost:3000/api/users \
-H "Authorization: Bearer "
```
### 4. 访问订单服务(仅管理员)
```
# 这将向非管理员用户返回 403
curl http://localhost:3000/api/orders \
-H "Authorization: Bearer "
```
### 5. 健康检查
```
curl http://localhost:3000/health
```
### 6. Prometheus 指标
```
curl http://localhost:3000/metrics
```
## 测试安全功能
### 触发蜜罐
```
curl http://localhost:3000/wp-login.php
# → IP 自动封禁 10 分钟
```
### 测试速率限制
```
for i in $(seq 1 110); do curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3000/health; done
# → 100 次请求后返回 429
```
### 测试 RBAC
```
# 以普通用户登录,然后尝试访问订单
curl http://localhost:3000/api/orders -H "Authorization: Bearer "
# → 403 禁止
```
### 测试 AI 降级
```
# 停止 AI 引擎
docker stop ai-engine
# 发送流量 – 网关回退到静态规则
curl http://localhost:3000/api/users -H "Authorization: Bearer "
# 重启
docker start ai-engine
```
## 管理 API
所有管理端点需要管理员 JWT 令牌。
| 方法 | 端点 | 描述 |
|--------|--------------------------|------------------------|
| GET | `/admin/blacklist` | 列出被封禁的 IP |
| POST | `/admin/blacklist` | 添加 IP 到黑名单 |
| DELETE | `/admin/blacklist` | 从黑名单移除 IP |
| POST | `/admin/whitelist` | 添加 IP 到白名单 |
| POST | `/admin/cache/flush` | 刷新响应缓存 |
| GET | `/admin/ai/health` | 检查 AI 引擎状态 |
| GET | `/admin/ai/circuit` | 查看断路器状态 |
## 项目结构
```
project 3- api/
├── docker-compose.yml # Service orchestration
├── prometheus/
│ └── prometheus.yml # Scrape config
├── gateway/
│ ├── Dockerfile
│ ├── package.json
│ └── src/
│ ├── server.js # Main entry point
│ ├── config/index.js # Environment config
│ ├── models/User.js # Mongoose user model
│ ├── middleware/
│ │ ├── auth.js # JWT + API key auth
│ │ ├── rbacMiddleware.js
│ │ ├── rateLimiter.js # Redis-backed rate limiting
│ │ ├── security.js # Helmet, CORS, validation
│ │ ├── ipFilter.js # Whitelist/blacklist
│ │ ├── fingerprint.js # Request fingerprinting
│ │ └── abuseDetector.js
│ ├── routes/
│ │ ├── auth.js # Register/login
│ │ ├── admin.js # Admin management
│ │ ├── proxy.js # Reverse proxy + AI check
│ │ └── honeypot.js # Trap endpoints
│ ├── services/
│ │ ├── enhancedAIClient.js # AI with circuit breaker
│ │ ├── alertService.js # Email + Slack alerts
│ │ ├── circuitBreaker.js
│ │ ├── loadBalancer.js
│ │ └── cacheService.js
│ └── utils/
│ ├── logger.js # 3-stream Winston logging
│ └── redisClient.js
├── ai-engine/
│ ├── Dockerfile
│ ├── requirements.txt
│ └── app/
│ ├── main.py # FastAPI endpoints
│ ├── detector.py # IsolationForest model
│ └── features.py # Feature engineering
└── microservices/
├── user-service/
│ ├── Dockerfile
│ ├── package.json
│ └── index.js
└── order-service/
├── Dockerfile
├── package.json
└── index.js
```
## 可观测性
### 日志
网关生成三路独立日志流:
- `logs/normal.log` – 正常流量与应用日志
- `logs/security.log` – 被拦截请求、攻击、AI 标记
- `logs/audit.log` – 管理 API 操作
### 指标(Prometheus)
- `gateway_http_request_duration_seconds` – 请求延迟直方图
- `gateway_http_requests_total` – 总请求计数器
- 默认 Node.js 进程指标(CPU、内存、事件循环)
### Grafana
访问地址 `http://localhost:3001`(admin/admin)。添加 Prometheus 作为数据源,指向 `http://prometheus:9090`。
## 环境变量
参见 `gateway/.env.example` 获取完整列表。关键变量:
| 变量 | 默认值 | 描述 |
|----------------------------|----------------------------------------|--------------------|
| `JWT_SECRET` | `dev-secret-change-me` | JWT 签名密钥 |
| `MONGO_URI` | `mongodb://mongo:27017/api_gateway` | MongoDB 连接字符串 |
| `REDIS_HOST` | `redis` | Redis 主机名 |
| `AI_ENGINE_URL` | `http://ai-engine:8000` | AI 引擎基础 URL |
| `RATE_LIMIT_MAX_REQUESTS` | `100` | 每窗口请求数 |
| `ALERT_THROTTLE_MS` | `60000` | 告警节流间隔 |
## 许可证
MIT
标签:AI安全, API安全, API密钥检测, API网关, C2日志可视化, Chat Copilot, Express, GNU通用公共许可证, IP过滤, JSON输出, MacOS取证, MITM代理, Node.js, Python, RBAC, SEO: AI异常检测, SEO: API安全网关, SEO: 智能安全网关, 动态风险评分, 密钥泄露防护, 平台安全, 异常检测, 指纹识别, 搜索引擎查询, 无后门, 时间线生成, 机器学习安全, 流量控制, 滥用检测, 版权保护, 特征工程, 生产级, 自动阻断, 自定义脚本, 自定义请求头, 认证, 请求分析, 输入验证, 逆向工具, 鉴权