Validé sur PC Windows (DESKTOP-58D5CAC, 2560x1600) : - 8 clics résolus visuellement (1 anchor_template, 1 som_text_match, 6 som_vlm) - Score moyen 0.75, temps moyen 1.6s - Texte tapé correctement (bonjour, test word, date, email) - 0 retries, 2 actions non vérifiées (OK) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
269 lines
7.3 KiB
Markdown
269 lines
7.3 KiB
Markdown
# Fiche #23 - API Security & Governance - Design
|
|
|
|
## Vue d'ensemble de l'architecture
|
|
|
|
Le système de sécurité API est conçu comme une couche middleware modulaire qui s'intègre aux applications FastAPI et Flask existantes. Il implémente une approche de sécurité en profondeur avec plusieurs couches de protection.
|
|
|
|
## Architecture des composants
|
|
|
|
### 1. Core Security Layer (`core/security/`)
|
|
|
|
#### `api_tokens.py` - Gestion des tokens
|
|
```python
|
|
@dataclass
|
|
class RequestContext:
|
|
"""Contexte de requête avec informations d'authentification"""
|
|
token: Optional[str]
|
|
user_role: str
|
|
ip_address: str
|
|
is_authenticated: bool
|
|
auth_method: str # "bearer", "header", "cookie"
|
|
|
|
def classify_request(request) -> RequestContext:
|
|
"""Classification et extraction des tokens de requête"""
|
|
|
|
def auth_required() -> bool:
|
|
"""Vérification globale du besoin d'authentification"""
|
|
```
|
|
|
|
#### `ip_allowlist.py` - Liste blanche IP
|
|
```python
|
|
class IPAllowlist:
|
|
def __init__(self, allowed_ips: List[str], trust_proxy: bool = True)
|
|
def is_allowed(self, ip: str) -> bool
|
|
def get_real_ip(self, request) -> str # Support X-Forwarded-For
|
|
```
|
|
|
|
#### `rate_limiter.py` - Limitation de débit
|
|
```python
|
|
class TokenBucketRateLimiter:
|
|
def __init__(self, capacity: int, refill_rate: float)
|
|
def consume(self, tokens: int = 1) -> bool
|
|
def get_headers(self) -> Dict[str, str] # X-RateLimit-*
|
|
```
|
|
|
|
#### `audit_log.py` - Logging d'audit
|
|
```python
|
|
class AuditLogger:
|
|
def log_auth_attempt(self, context: RequestContext, success: bool)
|
|
def log_api_access(self, endpoint: str, context: RequestContext)
|
|
def log_security_event(self, event_type: str, details: Dict)
|
|
```
|
|
|
|
### 2. System Integration Layer (`core/system/`)
|
|
|
|
#### `safety_switch.py` - Commutateur de sécurité
|
|
```python
|
|
def demo_safe_enabled() -> bool:
|
|
"""Vérification du mode DEMO_SAFE"""
|
|
|
|
def kill_switch_enabled() -> bool:
|
|
"""Vérification du kill-switch (env + fichier)"""
|
|
|
|
def set_kill_switch(enabled: bool, reason: str = ""):
|
|
"""Activation/désactivation du kill-switch"""
|
|
```
|
|
|
|
#### `api_admin_security.py` - API d'administration sécurité
|
|
```python
|
|
@router.get("/status")
|
|
async def get_security_status():
|
|
"""Statut de sécurité (demo mode, kill-switch)"""
|
|
|
|
@router.post("/killswitch")
|
|
async def control_killswitch(request: KillSwitchRequest):
|
|
"""Contrôle du kill-switch via API"""
|
|
```
|
|
|
|
#### `api_admin_autoheal.py` - API d'administration AutoHeal
|
|
```python
|
|
# Routes d'administration pour la gestion des workflows
|
|
@router.get("/workflows")
|
|
@router.post("/quarantine/{workflow_id}")
|
|
@router.post("/rollback/{workflow_id}")
|
|
@router.post("/snapshot/{workflow_id}")
|
|
```
|
|
|
|
### 3. Framework Integration Layer
|
|
|
|
#### `fastapi_security.py` - Middleware FastAPI
|
|
```python
|
|
def install_security_middlewares(app: FastAPI):
|
|
"""Installation complète des middlewares de sécurité"""
|
|
# IP Allowlist Middleware
|
|
# Rate Limiting Middleware
|
|
# Audit Logging Middleware
|
|
# Kill-Switch Protection Middleware
|
|
|
|
@app.middleware("http")
|
|
async def security_middleware(request: Request, call_next):
|
|
"""Middleware principal de sécurité"""
|
|
```
|
|
|
|
#### `flask_security.py` - Middleware Flask
|
|
```python
|
|
def install_flask_security(app: Flask):
|
|
"""Installation des middlewares Flask"""
|
|
|
|
@app.before_request
|
|
def security_check():
|
|
"""Vérification de sécurité avant requête"""
|
|
```
|
|
|
|
## Flux d'authentification
|
|
|
|
### 1. Extraction des tokens
|
|
```
|
|
Request → classify_request() → RequestContext
|
|
├── Bearer Token (Authorization: Bearer xxx)
|
|
├── X-Admin-Token Header (rétrocompatibilité)
|
|
└── Cookie-based auth (session)
|
|
```
|
|
|
|
### 2. Validation multi-couches
|
|
```
|
|
RequestContext → Security Pipeline
|
|
├── IP Allowlist Check
|
|
├── Rate Limiting Check
|
|
├── Token Validation
|
|
├── Role-based Access Control
|
|
└── Kill-Switch/Demo-Safe Check
|
|
```
|
|
|
|
### 3. Audit et logging
|
|
```
|
|
Security Decision → AuditLogger
|
|
├── Authentication attempts
|
|
├── API access logs
|
|
├── Security violations
|
|
└── Admin actions
|
|
```
|
|
|
|
## Modèles de données
|
|
|
|
### Configuration de sécurité
|
|
```python
|
|
@dataclass
|
|
class SecurityConfig:
|
|
auth_disabled: bool = False
|
|
demo_safe_mode: bool = False
|
|
kill_switch_enabled: bool = False
|
|
allowed_ips: List[str] = field(default_factory=list)
|
|
rate_limit_capacity: int = 100
|
|
rate_limit_refill: float = 10.0
|
|
audit_log_path: str = "data/logs/audit.jsonl"
|
|
```
|
|
|
|
### Contexte de requête
|
|
```python
|
|
@dataclass
|
|
class RequestContext:
|
|
token: Optional[str]
|
|
user_role: str # "admin", "read-only", "anonymous"
|
|
ip_address: str
|
|
is_authenticated: bool
|
|
auth_method: str
|
|
timestamp: datetime
|
|
request_id: str
|
|
```
|
|
|
|
## Intégration avec les services existants
|
|
|
|
### Server API (`server/api_upload.py`)
|
|
```python
|
|
from core.security.fastapi_security import install_security_middlewares
|
|
from core.system.api_admin_autoheal import router as autoheal_admin_router
|
|
from core.system.api_admin_security import router as security_admin_router
|
|
|
|
# Installation des middlewares
|
|
install_security_middlewares(app)
|
|
|
|
# Montage des APIs d'administration
|
|
app.include_router(autoheal_admin_router, prefix="/admin/autoheal")
|
|
app.include_router(security_admin_router, prefix="/admin/security")
|
|
```
|
|
|
|
### Web Dashboard (`web_dashboard/app.py`)
|
|
```python
|
|
from core.security.flask_security import install_flask_security
|
|
|
|
# Installation de la sécurité Flask
|
|
install_flask_security(app)
|
|
```
|
|
|
|
## Configuration et déploiement
|
|
|
|
### Variables d'environnement
|
|
```bash
|
|
# Authentification
|
|
RPA_TOKEN_ADMIN=xxx # Token admin principal
|
|
AUTOHEAL_ADMIN_TOKEN=xxx # Token legacy (rétrocompatibilité)
|
|
RPA_AUTH_DISABLED=1 # Désactiver auth en dev
|
|
|
|
# Sécurité
|
|
DEMO_SAFE=1 # Mode démo sécurisé
|
|
RPA_KILL_SWITCH=1 # Kill-switch global
|
|
RPA_KILL_SWITCH_FILE=data/runtime/kill_switch.json
|
|
|
|
# IP Allowlist
|
|
RPA_ALLOWED_IPS=127.0.0.1,10.0.0.0/8,192.168.0.0/16
|
|
RPA_TRUST_PROXY=1 # Support X-Forwarded-For
|
|
|
|
# Rate Limiting
|
|
RPA_RATE_LIMIT_CAPACITY=100 # Capacité du bucket
|
|
RPA_RATE_LIMIT_REFILL=10.0 # Tokens par seconde
|
|
|
|
# Audit
|
|
RPA_AUDIT_LOG_PATH=data/logs/audit.jsonl
|
|
```
|
|
|
|
### Fichiers de configuration
|
|
```json
|
|
// data/runtime/kill_switch.json
|
|
{
|
|
"enabled": false,
|
|
"reason": "",
|
|
"timestamp": "2024-12-22T10:30:00Z",
|
|
"set_by": "admin"
|
|
}
|
|
```
|
|
|
|
## Patterns de sécurité
|
|
|
|
### 1. Defense in Depth
|
|
- Authentification multi-méthodes
|
|
- Validation IP + Rate limiting
|
|
- Audit complet des actions
|
|
- Kill-switch d'urgence
|
|
|
|
### 2. Fail-Safe Defaults
|
|
- Authentification requise par défaut
|
|
- Accès restreint en cas d'erreur
|
|
- Mode dégradé en développement
|
|
- Logging des échecs de sécurité
|
|
|
|
### 3. Principle of Least Privilege
|
|
- Rôles granulaires (admin/read-only)
|
|
- APIs d'administration séparées
|
|
- Tokens avec permissions limitées
|
|
- Validation stricte des inputs
|
|
|
|
## Tests et validation
|
|
|
|
### Tests unitaires
|
|
- Validation des tokens et rôles
|
|
- Logique IP allowlist et CIDR
|
|
- Algorithme token bucket
|
|
- Intégration safety switch
|
|
|
|
### Tests d'intégration
|
|
- Middlewares FastAPI/Flask
|
|
- APIs d'administration complètes
|
|
- Flux d'authentification end-to-end
|
|
- Scénarios de sécurité adverses
|
|
|
|
### Tests de sécurité
|
|
- Tentatives d'authentification malveillantes
|
|
- Contournement de rate limiting
|
|
- Injection dans les logs d'audit
|
|
- Validation des headers de sécurité |