docs: réécriture complète de la documentation des services en français
- bot-detector.md : architecture 11 modules, 77/65 features, ensemble triple voix (EIF+AE+XGBoost), browser 5 axes, HDBSCAN, toutes les variables d'environnement vérifiées depuis le code source - dashboard.md : corrigé stack (Jinja2+htmx, pas React+Vite), 14 pages + 35 API routes + health, dual-database, IPv4/IPv6 - python-ja4common.md : ajouté CLICKHOUSE_DB_PROCESSING/LOGS, schéma dual-database, note dashboard n'utilise pas ja4_common Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@ -1,64 +1,106 @@
|
||||
# python-ja4common
|
||||
|
||||
`ja4_common` is the shared Python library for the ja4-platform, providing a unified ClickHouse client singleton and configuration settings. It is used by [bot-detector](../services/bot-detector.md) and [dashboard](../services/dashboard.md).
|
||||
Bibliothèque Python partagée pour la plateforme ja4, fournissant un client
|
||||
ClickHouse singleton et une configuration centralisée via pydantic-settings.
|
||||
|
||||
**Package name**: `ja4-common`
|
||||
**Utilisée par** : [bot-detector](../services/bot-detector.md) (via `ja4_common.clickhouse`)
|
||||
|
||||
**Python version**: ≥ 3.11
|
||||
> **Note :** le [dashboard](../services/dashboard.md) n'utilise **pas** `ja4_common`. Il possède
|
||||
> son propre client `clickhouse-connect` léger dans `backend/database.py`.
|
||||
|
||||
**Dependencies**:
|
||||
- `clickhouse-connect >= 0.8.0`
|
||||
- `pydantic-settings >= 2.1.0`
|
||||
---
|
||||
|
||||
## Informations du package
|
||||
|
||||
| Clé | Valeur |
|
||||
|-----|--------|
|
||||
| **Nom du package** | `ja4-common` |
|
||||
| **Version** | `0.1.0` |
|
||||
| **Python** | ≥ 3.11 |
|
||||
| **Dépendances** | `clickhouse-connect >= 0.8.0`, `pydantic-settings >= 2.1.0` |
|
||||
| **Build system** | `setuptools >= 68` + `wheel` |
|
||||
|
||||
---
|
||||
|
||||
## ClickHouseSettings
|
||||
|
||||
Pydantic-settings model that reads configuration from environment variables and `.env` files.
|
||||
Modèle pydantic-settings qui lit la configuration depuis les variables d'environnement
|
||||
et les fichiers `.env`.
|
||||
|
||||
### Fields
|
||||
### Champs
|
||||
|
||||
| Field | Type | Default | Env Variable | Description |
|
||||
|-------|------|---------|-------------|-------------|
|
||||
| `CLICKHOUSE_HOST` | str | `"clickhouse"` | `CLICKHOUSE_HOST` | ClickHouse server hostname |
|
||||
| `CLICKHOUSE_PORT` | int | `8123` | `CLICKHOUSE_PORT` | ClickHouse HTTP API port |
|
||||
| `CLICKHOUSE_DB` | str | `"ja4_processing"` | `CLICKHOUSE_DB` | Database name |
|
||||
| `CLICKHOUSE_USER` | str | `"admin"` | `CLICKHOUSE_USER` | Username for authentication |
|
||||
| `CLICKHOUSE_PASSWORD` | str | `""` | `CLICKHOUSE_PASSWORD` | Password for authentication |
|
||||
| Champ | Type | Défaut | Variable d'env | Description |
|
||||
|-------|------|--------|----------------|-------------|
|
||||
| `CLICKHOUSE_HOST` | str | `"clickhouse"` | `CLICKHOUSE_HOST` | Nom d'hôte du serveur ClickHouse |
|
||||
| `CLICKHOUSE_PORT` | int | `8123` | `CLICKHOUSE_PORT` | Port de l'API HTTP ClickHouse |
|
||||
| `CLICKHOUSE_DB` | str | `"ja4_processing"` | `CLICKHOUSE_DB` | Base de données par défaut (rétro-compatibilité) |
|
||||
| `CLICKHOUSE_DB_PROCESSING` | str | `"ja4_processing"` | `CLICKHOUSE_DB_PROCESSING` | Base de données ML, agrégations, dictionnaires |
|
||||
| `CLICKHOUSE_DB_LOGS` | str | `"ja4_logs"` | `CLICKHOUSE_DB_LOGS` | Base de données des logs HTTP bruts |
|
||||
| `CLICKHOUSE_USER` | str | `"admin"` | `CLICKHOUSE_USER` | Utilisateur pour l'authentification |
|
||||
| `CLICKHOUSE_PASSWORD` | str | `""` | `CLICKHOUSE_PASSWORD` | Mot de passe pour l'authentification |
|
||||
|
||||
### Configuration Sources
|
||||
### Schéma dual-database
|
||||
|
||||
Settings are loaded in order of precedence:
|
||||
1. **Environment variables** (highest priority)
|
||||
2. **`.env` file** in the current working directory
|
||||
3. **Default values** (lowest priority)
|
||||
La plateforme utilise deux bases de données ClickHouse :
|
||||
|
||||
Environment variable names are **case-sensitive** (e.g., `CLICKHOUSE_HOST`, not `clickhouse_host`).
|
||||
- **`CLICKHOUSE_DB_PROCESSING`** (`ja4_processing`) : tables ML (`ml_detected_anomalies`,
|
||||
`ml_all_scores`), agrégations (`agg_*`), dictionnaires (`dict_*`), feedback SOC, audit
|
||||
- **`CLICKHOUSE_DB_LOGS`** (`ja4_logs`) : `http_logs_raw`, `http_logs`, vues matérialisées
|
||||
|
||||
### Usage
|
||||
Des **références croisées** existent entre les deux bases — les vues matérialisées de l'une
|
||||
lisent dans l'autre. Utiliser toujours des noms de tables pleinement qualifiés :
|
||||
|
||||
```python
|
||||
from ja4_common.settings import settings
|
||||
|
||||
print(settings.CLICKHOUSE_HOST) # "clickhouse" or from env
|
||||
print(settings.CLICKHOUSE_PORT) # 8123 or from env
|
||||
query = f"SELECT ... FROM {settings.CLICKHOUSE_DB_PROCESSING}.ml_detected_anomalies ..."
|
||||
query = f"SELECT ... FROM {settings.CLICKHOUSE_DB_LOGS}.http_logs ..."
|
||||
```
|
||||
|
||||
Ne jamais coder en dur les noms de bases dans les requêtes.
|
||||
|
||||
### Sources de configuration
|
||||
|
||||
Les paramètres sont chargés par ordre de priorité :
|
||||
1. **Variables d'environnement** (priorité la plus haute)
|
||||
2. **Fichier `.env`** dans le répertoire courant
|
||||
3. **Valeurs par défaut** (priorité la plus basse)
|
||||
|
||||
Les noms de variables d'environnement sont **sensibles à la casse** (ex. `CLICKHOUSE_HOST`, pas `clickhouse_host`).
|
||||
|
||||
### Utilisation
|
||||
|
||||
```python
|
||||
from ja4_common.settings import settings
|
||||
|
||||
print(settings.CLICKHOUSE_HOST) # "clickhouse" ou depuis l'env
|
||||
print(settings.CLICKHOUSE_PORT) # 8123 ou depuis l'env
|
||||
print(settings.CLICKHOUSE_DB_PROCESSING) # "ja4_processing" ou depuis l'env
|
||||
print(settings.CLICKHOUSE_DB_LOGS) # "ja4_logs" ou depuis l'env
|
||||
```
|
||||
|
||||
Le singleton `settings` est créé au niveau du module à l'import.
|
||||
|
||||
---
|
||||
|
||||
## ClickHouseClient
|
||||
|
||||
Wraps `clickhouse_connect` with auto-reconnection and a clean API.
|
||||
Encapsule `clickhouse_connect` avec reconnexion automatique et une API épurée.
|
||||
|
||||
### Methods
|
||||
### Méthodes
|
||||
|
||||
| Method | Signature | Description |
|
||||
|--------|-----------|-------------|
|
||||
| `connect` | `connect() -> Client` | Returns the underlying `clickhouse_connect` client, creating or reconnecting as needed |
|
||||
| `query` | `query(query: str, params: dict = None)` | Execute a SELECT query, returns result set |
|
||||
| `command` | `command(query: str, params: dict = None)` | Execute a DDL/DML command (CREATE, INSERT, etc.) |
|
||||
| `insert` | `insert(table: str, data, column_names=None)` | Bulk insert data into a table |
|
||||
| `close` | `close()` | Close the connection and release resources |
|
||||
| Méthode | Signature | Description |
|
||||
|---------|-----------|-------------|
|
||||
| `connect` | `connect() → Client` | Retourne le client `clickhouse_connect` sous-jacent, crée ou reconnecte si nécessaire |
|
||||
| `_ping` | `_ping() → bool` | Vérifie la connexion via `client.ping()`, retourne `False` en cas d'exception |
|
||||
| `query` | `query(query: str, params: dict = None)` | Exécute une requête SELECT, retourne le résultat |
|
||||
| `command` | `command(query: str, params: dict = None)` | Exécute une commande DDL/DML (CREATE, INSERT, etc.) |
|
||||
| `insert` | `insert(table: str, data, column_names=None)` | Insertion en masse dans une table |
|
||||
| `close` | `close()` | Ferme la connexion et libère les ressources |
|
||||
|
||||
### Auto-Reconnection
|
||||
### Reconnexion automatique
|
||||
|
||||
The `connect()` method automatically reconnects if the current connection is lost:
|
||||
La méthode `connect()` reconnecte automatiquement si la connexion est perdue :
|
||||
|
||||
```python
|
||||
def connect(self):
|
||||
@ -74,41 +116,50 @@ def connect(self):
|
||||
return self._client
|
||||
```
|
||||
|
||||
### Usage Example
|
||||
### Exemple d'utilisation
|
||||
|
||||
```python
|
||||
from ja4_common.clickhouse import get_client
|
||||
|
||||
client = get_client()
|
||||
|
||||
# SELECT query
|
||||
result = client.query("SELECT count() FROM http_logs WHERE src_ip = {ip:String}", {"ip": "203.0.113.42"})
|
||||
# Requête SELECT avec noms de tables pleinement qualifiés
|
||||
result = client.query(
|
||||
f"SELECT count() FROM {settings.CLICKHOUSE_DB_LOGS}.http_logs "
|
||||
"WHERE src_ip = {ip:String}",
|
||||
{"ip": "203.0.113.42"},
|
||||
)
|
||||
print(result.result_rows)
|
||||
|
||||
# INSERT
|
||||
client.insert("audit_logs", [[datetime.now(), "analyst1", "investigate", "ip", "203.0.113.42"]],
|
||||
column_names=["timestamp", "user_name", "action", "entity_type", "entity_id"])
|
||||
client.insert(
|
||||
"audit_logs",
|
||||
[[datetime.now(), "analyst1", "investigate", "ip", "203.0.113.42"]],
|
||||
column_names=["timestamp", "user_name", "action", "entity_type", "entity_id"],
|
||||
)
|
||||
|
||||
# Command
|
||||
# Commande DDL
|
||||
client.command("OPTIMIZE TABLE http_logs FINAL")
|
||||
```
|
||||
|
||||
## get_client() Singleton
|
||||
---
|
||||
|
||||
The `get_client()` function provides a module-level singleton `ClickHouseClient`:
|
||||
## Singleton `get_client()`
|
||||
|
||||
La fonction `get_client()` fournit un singleton de `ClickHouseClient` au niveau du module :
|
||||
|
||||
```python
|
||||
from ja4_common.clickhouse import get_client
|
||||
|
||||
# First call creates the client
|
||||
# Le premier appel crée le client
|
||||
client1 = get_client()
|
||||
|
||||
# Subsequent calls return the same instance
|
||||
# Les appels suivants retournent la même instance
|
||||
client2 = get_client()
|
||||
assert client1 is client2
|
||||
```
|
||||
|
||||
### Implementation
|
||||
### Implémentation
|
||||
|
||||
```python
|
||||
_client: Optional[ClickHouseClient] = None
|
||||
@ -120,16 +171,40 @@ def get_client() -> ClickHouseClient:
|
||||
return _client
|
||||
```
|
||||
|
||||
## Using from a New Service
|
||||
Architecture à **deux niveaux de singleton** :
|
||||
- `get_client()` → singleton pour `ClickHouseClient`
|
||||
- `settings` dans `settings.py` → singleton pour `ClickHouseSettings`
|
||||
|
||||
### 1. Add Dependency
|
||||
---
|
||||
|
||||
In your service's `requirements.txt`:
|
||||
## Exports du package
|
||||
|
||||
Le `__init__.py` n'exporte qu'une chaîne de version :
|
||||
|
||||
```python
|
||||
"""JA4 Common — shared utilities for the JA4 security suite."""
|
||||
__version__ = "0.1.0"
|
||||
```
|
||||
|
||||
Les consommateurs doivent importer directement depuis les sous-modules :
|
||||
|
||||
```python
|
||||
from ja4_common.clickhouse import get_client
|
||||
from ja4_common.settings import settings
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Intégration dans un nouveau service
|
||||
|
||||
### 1. Ajouter la dépendance
|
||||
|
||||
Dans le `requirements.txt` du service :
|
||||
```
|
||||
ja4-common @ file:///app/shared/python/ja4_common
|
||||
```
|
||||
|
||||
Or in `pyproject.toml`:
|
||||
Ou dans `pyproject.toml` :
|
||||
```toml
|
||||
[project]
|
||||
dependencies = [
|
||||
@ -137,54 +212,62 @@ dependencies = [
|
||||
]
|
||||
```
|
||||
|
||||
### 2. Docker Setup
|
||||
### 2. Configuration Docker
|
||||
|
||||
```dockerfile
|
||||
# Copy shared library
|
||||
# Copier la bibliothèque partagée
|
||||
COPY shared/python/ja4_common /app/shared/python/ja4_common
|
||||
RUN pip install /app/shared/python/ja4_common
|
||||
|
||||
# Copy service code
|
||||
COPY services/my-service /app/services/my-service
|
||||
# Copier le code du service
|
||||
COPY services/mon-service /app/services/mon-service
|
||||
```
|
||||
|
||||
### 3. Use in Code
|
||||
### 3. Utiliser dans le code
|
||||
|
||||
```python
|
||||
from ja4_common.clickhouse import get_client
|
||||
from ja4_common.settings import settings
|
||||
|
||||
# Access settings
|
||||
print(f"Connecting to {settings.CLICKHOUSE_HOST}:{settings.CLICKHOUSE_PORT}")
|
||||
# Accéder à la configuration
|
||||
print(f"Connexion à {settings.CLICKHOUSE_HOST}:{settings.CLICKHOUSE_PORT}")
|
||||
print(f"Base logs : {settings.CLICKHOUSE_DB_LOGS}")
|
||||
print(f"Base processing : {settings.CLICKHOUSE_DB_PROCESSING}")
|
||||
|
||||
# Use client
|
||||
# Utiliser le client avec noms pleinement qualifiés
|
||||
db = get_client()
|
||||
result = db.query("SELECT count() FROM ml_detected_anomalies")
|
||||
result = db.query(
|
||||
f"SELECT count() FROM {settings.CLICKHOUSE_DB_PROCESSING}.ml_detected_anomalies"
|
||||
)
|
||||
```
|
||||
|
||||
### 4. Environment Configuration
|
||||
### 4. Configuration d'environnement
|
||||
|
||||
Create a `.env` file or set environment variables:
|
||||
Créer un fichier `.env` ou définir les variables d'environnement :
|
||||
```bash
|
||||
CLICKHOUSE_HOST=clickhouse.example.com
|
||||
CLICKHOUSE_PORT=8123
|
||||
CLICKHOUSE_DB=ja4_processing
|
||||
CLICKHOUSE_DB_PROCESSING=ja4_processing
|
||||
CLICKHOUSE_DB_LOGS=ja4_logs
|
||||
CLICKHOUSE_USER=data_writer
|
||||
CLICKHOUSE_PASSWORD=secret
|
||||
```
|
||||
|
||||
## Testing: Mocking the Client
|
||||
---
|
||||
|
||||
### Using unittest.mock
|
||||
## Tests : simuler le client
|
||||
|
||||
### Avec unittest.mock
|
||||
|
||||
```python
|
||||
from unittest.mock import MagicMock, patch
|
||||
from ja4_common.clickhouse import ClickHouseClient
|
||||
|
||||
def test_my_service():
|
||||
def test_mon_service():
|
||||
mock_client = MagicMock(spec=ClickHouseClient)
|
||||
mock_client.query.return_value = MagicMock(result_rows=[(42,)])
|
||||
|
||||
|
||||
with patch("ja4_common.clickhouse._client", mock_client):
|
||||
from ja4_common.clickhouse import get_client
|
||||
client = get_client()
|
||||
@ -192,25 +275,32 @@ def test_my_service():
|
||||
assert result.result_rows == [(42,)]
|
||||
```
|
||||
|
||||
### Overriding Settings in Tests
|
||||
### Surcharger les paramètres en test
|
||||
|
||||
```python
|
||||
from ja4_common.settings import ClickHouseSettings
|
||||
|
||||
# Create custom settings for tests
|
||||
# Créer des paramètres personnalisés pour les tests
|
||||
test_settings = ClickHouseSettings(
|
||||
CLICKHOUSE_HOST="localhost",
|
||||
CLICKHOUSE_PORT=8123,
|
||||
CLICKHOUSE_DB="test_db",
|
||||
CLICKHOUSE_DB_PROCESSING="test_processing",
|
||||
CLICKHOUSE_DB_LOGS="test_logs",
|
||||
CLICKHOUSE_USER="test_user",
|
||||
CLICKHOUSE_PASSWORD="test_pass",
|
||||
)
|
||||
```
|
||||
|
||||
## Source Files
|
||||
---
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `ja4_common/settings.py` | `ClickHouseSettings` pydantic-settings model |
|
||||
| `ja4_common/clickhouse.py` | `ClickHouseClient` class and `get_client()` singleton |
|
||||
| `pyproject.toml` | Package metadata and dependencies |
|
||||
## Fichiers sources
|
||||
|
||||
| Fichier | Description |
|
||||
|---------|-------------|
|
||||
| `ja4_common/__init__.py` | Docstring du package et `__version__` |
|
||||
| `ja4_common/settings.py` | Modèle pydantic-settings `ClickHouseSettings` et singleton `settings` |
|
||||
| `ja4_common/clickhouse.py` | Classe `ClickHouseClient` et singleton `get_client()` |
|
||||
| `pyproject.toml` | Métadonnées du package et dépendances |
|
||||
| `tests/test_settings.py` | Tests unitaires pour `ClickHouseSettings` |
|
||||
| `tests/test_clickhouse.py` | Tests unitaires pour `ClickHouseClient` |
|
||||
|
||||
Reference in New Issue
Block a user