secops-brain-rag 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- secops_brain_rag-0.1.0.dist-info/METADATA +131 -0
- secops_brain_rag-0.1.0.dist-info/RECORD +15 -0
- secops_brain_rag-0.1.0.dist-info/WHEEL +5 -0
- secops_brain_rag-0.1.0.dist-info/entry_points.txt +2 -0
- secops_brain_rag-0.1.0.dist-info/licenses/LICENSE +21 -0
- secops_brain_rag-0.1.0.dist-info/top_level.txt +1 -0
- secops_rag/__init__.py +8 -0
- secops_rag/cli.py +320 -0
- secops_rag/evals.py +149 -0
- secops_rag/generator.py +106 -0
- secops_rag/ingestion.py +180 -0
- secops_rag/otel.py +128 -0
- secops_rag/retrieval.py +234 -0
- secops_rag/security.py +87 -0
- secops_rag/telemetry.py +182 -0
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: secops-brain-rag
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: RAG sécurisé (RBAC + redaction secrets) sur corpus markdown.
|
|
5
|
+
Author: shenn667
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/shenn667/secops-brain-rag
|
|
8
|
+
Project-URL: Repository, https://github.com/shenn667/secops-brain-rag
|
|
9
|
+
Requires-Python: >=3.12
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: pydantic>=2
|
|
13
|
+
Requires-Dist: typer>=0.9
|
|
14
|
+
Requires-Dist: rich>=13
|
|
15
|
+
Requires-Dist: numpy>=1.26
|
|
16
|
+
Requires-Dist: scikit-learn>=1.3
|
|
17
|
+
Requires-Dist: httpx>=0.27
|
|
18
|
+
Requires-Dist: openai>=1.0
|
|
19
|
+
Requires-Dist: pyyaml>=6
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# SecOps Brain RAG
|
|
23
|
+
|
|
24
|
+
RAG sécurisé sur corpus markdown (second brain) : **filtrage RBAC avant recherche**,
|
|
25
|
+
**redaction des secrets** avant envoi au LLM, **citations obligatoires** `[Source: path]`,
|
|
26
|
+
et **évaluation** (recall@k, MRR, violations RBAC).
|
|
27
|
+
|
|
28
|
+
Aucun appel réseau au import ni dans les tests. Le mode `--offline` répond sans réseau.
|
|
29
|
+
|
|
30
|
+
## Arborescence
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
secops-brain-rag/
|
|
34
|
+
├── pyproject.toml
|
|
35
|
+
├── README.md / .env.example
|
|
36
|
+
├── src/secops_rag/
|
|
37
|
+
│ ├── ingestion.py # parse markdown, sensibilité, chunks, index
|
|
38
|
+
│ ├── security.py # RBAC, redaction secrets, audit
|
|
39
|
+
│ ├── retrieval.py # BM25 + TF-IDF/SVD, fusion RRF
|
|
40
|
+
│ ├── generator.py # prompt cité, clients LLM
|
|
41
|
+
│ ├── evals.py # recall@k, MRR, run_eval
|
|
42
|
+
│ └── cli.py # index, query, eval, audit-rbac
|
|
43
|
+
└── tests/ # conftest + 6 modules + eval_dataset.json
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Installation
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
cd secops-brain-rag
|
|
50
|
+
pip install -e . # dépendances : pydantic, typer, rich, numpy,
|
|
51
|
+
# scikit-learn, httpx, openai, pyyaml, pytest
|
|
52
|
+
cp .env.example .env # optionnel : FREELMAPI_API_KEY, RAG_MODEL
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Usage
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
# 1. Indexer le corpus
|
|
59
|
+
secops-rag index ./docs -o index.json
|
|
60
|
+
|
|
61
|
+
# 2. Interroger (rôle viewer par défaut, offline sans réseau)
|
|
62
|
+
# Timeout global fail-closed: --timeout 30 (défaut). Timeout => DENY verdict explicite.
|
|
63
|
+
secops-rag query "Quel est le protocole de travail ?" --role viewer --offline --index index.json
|
|
64
|
+
|
|
65
|
+
# 3. Évaluer
|
|
66
|
+
secops-rag eval tests/eval_dataset.json --index index.json --role viewer
|
|
67
|
+
|
|
68
|
+
# 4. Auditer le RBAC (chunks par sensibilité + matrice rôles + verdict PASS/FAIL)
|
|
69
|
+
secops-rag audit-rbac index.json
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Injection de secret (portable)
|
|
73
|
+
|
|
74
|
+
Ne jamais utiliser `export` ni passer une clé en `env VAR=...` (fuite via `ps`,
|
|
75
|
+
historique shell, CI logs). Recommandation générique :
|
|
76
|
+
|
|
77
|
+
- utiliser un gestionnaire de secrets (Vault, 1Password CLI, variables
|
|
78
|
+
chiffrées du CI, systemd LoadCredential, Docker secrets, etc.) qui expose
|
|
79
|
+
la clé uniquement au processus enfant ;
|
|
80
|
+
- ou un fichier secret en mode `0600` (ou `0400`), jamais commité, chargé
|
|
81
|
+
à l'exécution sans l'écrire dans l'historique shell.
|
|
82
|
+
|
|
83
|
+
Le secret ne doit jamais apparaître en clair dans l'historique shell, ni être
|
|
84
|
+
committé dans le dépôt. Exemple de principe (avec votre outil d'injection) :
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
# fichier secret 0600 contenant : FREELMAPI_API_KEY=...
|
|
88
|
+
# votre outil d'injection expose FREELMAPI_API_KEY uniquement à secops-rag, puis :
|
|
89
|
+
secops-rag query "..." --role viewer --index index.json
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Sécurité (RBAC)
|
|
93
|
+
|
|
94
|
+
| Rôle | Voit public | Voit internal | Voit restricted |
|
|
95
|
+
|--------|:-----------:|:-------------:|:---------------:|
|
|
96
|
+
| viewer | yes | no | no |
|
|
97
|
+
| member | yes | yes | no |
|
|
98
|
+
| admin | yes | yes | yes |
|
|
99
|
+
|
|
100
|
+
Sensibilité déduite dans l'ordre : frontmatter (`sensitivity`/`classification`) →
|
|
101
|
+
tags (`restricted`, `confidentiel`, `secret`) → chemin (`credentials`, `secret`, `prive`) →
|
|
102
|
+
défaut `public`.
|
|
103
|
+
|
|
104
|
+
Secrets masqués (`security.redact_secrets`) : clés OpenAI `sk-…`, `ghp_…`, `xoxb-…`,
|
|
105
|
+
`AKIA…`, `api_key=…`, `password=…`, `mot de passe=…`, `Bearer …`, clés privées PEM.
|
|
106
|
+
Remplacement par `[REDACTED:TYPE]`.
|
|
107
|
+
|
|
108
|
+
## Retrieval
|
|
109
|
+
|
|
110
|
+
- **BM25** maison (k1=1.5, b=0.6), tokenisation fr/en (accents inclus).
|
|
111
|
+
- **TF-IDF** sklearn (`max_features=2048`) + **TruncatedSVD** si dim > 64, similarité cosinus.
|
|
112
|
+
- **Fusion RRF** : `score = somme 1/(k + rang)`, k=60 par défaut.
|
|
113
|
+
|
|
114
|
+
## Évaluation
|
|
115
|
+
|
|
116
|
+
`run_eval` filtre les chunks par rôle **avant** la recherche, puis calcule par cas :
|
|
117
|
+
recall@k, MRR, fuites RBAC, `must_not_contain`. Le résumé impose
|
|
118
|
+
`rbac_violations == 0` et reporte `citation_groundedness`.
|
|
119
|
+
|
|
120
|
+
## Télémétrie
|
|
121
|
+
|
|
122
|
+
- Traces JSONL locales (`SECOPS_RAG_TRACES`, défaut `~/.local/state/secops_rag/traces.jsonl`) : append-only, sanitization secrets, allowlist de clés.
|
|
123
|
+
- Export OTLP **fail-open** (jamais bloquant) : `SECOPS_RAG_OTLP_ENDPOINT` ou `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` (défaut `http://127.0.0.1:4318/v1/traces`). Si opentelemetry/collecteur absent ou en erreur, la query continue et le verdict reste explicite.
|
|
124
|
+
- Aucune raw query exportée en OTLP (seulement longueur/métadonnées).
|
|
125
|
+
|
|
126
|
+
## Tests
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
cd secops-brain-rag
|
|
130
|
+
PYTHONPATH=src python -m pytest tests -q
|
|
131
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
secops_brain_rag-0.1.0.dist-info/licenses/LICENSE,sha256=XKTrANYTBSuL8H4K0bs2OE5lXwz-0lwXAHmw3HIPVSw,1065
|
|
2
|
+
secops_rag/__init__.py,sha256=RyRFWwFhZqj4tuBEBQnt4WpfES7yHUoJQag5xI6K7IM,279
|
|
3
|
+
secops_rag/cli.py,sha256=tuV2VSSRuHUYhHb_LzxfnuWErnI5Ksxt8LNXLBYrmVA,13733
|
|
4
|
+
secops_rag/evals.py,sha256=prleIC3d4oscZA3P5snDnYF1_H2jsNXwhXyLUrn9_zU,5071
|
|
5
|
+
secops_rag/generator.py,sha256=yRPjirJEU5hTcFBplxzHkpDJMrffaDPvq1U0uDBlRWA,3913
|
|
6
|
+
secops_rag/ingestion.py,sha256=wDQv0cXuzbYLjPlZUPWAKiMoBDIkaj5hoekSSxCTmyY,5802
|
|
7
|
+
secops_rag/otel.py,sha256=Qo3mOizY0POuTDAy5nP16lbhrv_-02xNFfH4g7YFS1Q,3837
|
|
8
|
+
secops_rag/retrieval.py,sha256=v60uOWj22HcMXGylxzN2ThSaD3M-sFsHapGophEI2Rc,9202
|
|
9
|
+
secops_rag/security.py,sha256=rpczAObPlxPaUMX3T5l7L2XQmL-jN09eNKT4iBp4Na4,2895
|
|
10
|
+
secops_rag/telemetry.py,sha256=5DIDecIIvcxKyUKXYpDOQFS7SOB2mgIt5nmC7aeTjTs,5931
|
|
11
|
+
secops_brain_rag-0.1.0.dist-info/METADATA,sha256=ntZpk4g2tLMDVSiQmJNaBdf68HxLdPg55uiOeKF8gTI,5035
|
|
12
|
+
secops_brain_rag-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
13
|
+
secops_brain_rag-0.1.0.dist-info/entry_points.txt,sha256=S2cInNK-DzJ4Ac231mIYQMC6x_oyiV9D1qc37-qfOfc,50
|
|
14
|
+
secops_brain_rag-0.1.0.dist-info/top_level.txt,sha256=9g9hHAwkyspjXY7a6n9KGt0_--cR1VOiwRAh6bKsduM,11
|
|
15
|
+
secops_brain_rag-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 shenn667
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
secops_rag
|
secops_rag/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""SecOps Brain RAG — RAG sécurisé sur corpus markdown."""
|
|
2
|
+
|
|
3
|
+
from secops_rag.generator import CitedAnswer
|
|
4
|
+
from secops_rag.ingestion import Chunk, Sensitivity
|
|
5
|
+
from secops_rag.security import Role
|
|
6
|
+
|
|
7
|
+
__all__ = ["Chunk", "CitedAnswer", "Role", "Sensitivity"]
|
|
8
|
+
__version__ = "0.1.0"
|
secops_rag/cli.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
"""CLI secops-rag : index, query, eval, audit-rbac, stats."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import concurrent.futures
|
|
6
|
+
import time
|
|
7
|
+
import uuid
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Annotated
|
|
10
|
+
|
|
11
|
+
import typer
|
|
12
|
+
from rich.console import Console
|
|
13
|
+
from rich.table import Table
|
|
14
|
+
|
|
15
|
+
from secops_rag.evals import load_dataset, run_compare, run_eval
|
|
16
|
+
from secops_rag.generator import OfflineClient, OpenAICompatibleClient, generate_answer
|
|
17
|
+
from secops_rag.ingestion import Sensitivity, index_corpus, load_index, save_index
|
|
18
|
+
from secops_rag.retrieval import HybridRetriever
|
|
19
|
+
from secops_rag.security import POLICIES, Role, audit_access, filter_chunks, guard_prompt, redact_secrets
|
|
20
|
+
from secops_rag.telemetry import append_trace, get_traces_path, stats
|
|
21
|
+
|
|
22
|
+
app = typer.Typer(help="RAG sécurisé (RBAC + redaction) sur corpus markdown.")
|
|
23
|
+
console = Console()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@app.command()
|
|
27
|
+
def index(
|
|
28
|
+
corpus: Annotated[Path, typer.Argument(help="Racine du corpus markdown.")],
|
|
29
|
+
output: Annotated[Path, typer.Option("--output", "-o")] = Path("index.json"),
|
|
30
|
+
) -> None:
|
|
31
|
+
"""Indexe le corpus et sauvegarde l'index JSON."""
|
|
32
|
+
chunks = index_corpus(corpus)
|
|
33
|
+
save_index(chunks, output)
|
|
34
|
+
table = Table(title="Index construit")
|
|
35
|
+
table.add_column("Métrique")
|
|
36
|
+
table.add_column("Valeur")
|
|
37
|
+
table.add_row("Documents chunkés", str(len({c.path for c in chunks})))
|
|
38
|
+
table.add_row("Chunks", str(len(chunks)))
|
|
39
|
+
for sens in Sensitivity:
|
|
40
|
+
n = sum(1 for c in chunks if c.sensitivity == sens)
|
|
41
|
+
table.add_row(f"Chunks {sens.value}", str(n))
|
|
42
|
+
console.print(table)
|
|
43
|
+
console.print(f"[green]Index sauvegardé : {output}[/green]")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@app.command()
|
|
47
|
+
def query(
|
|
48
|
+
question: Annotated[str, typer.Argument(help="Question posée au RAG.")],
|
|
49
|
+
role: Annotated[Role, typer.Option("--role", "-r")] = Role.viewer,
|
|
50
|
+
top_k: Annotated[int, typer.Option("--top-k", "-k")] = 5,
|
|
51
|
+
offline: Annotated[bool, typer.Option("--offline")] = False,
|
|
52
|
+
index_path: Annotated[Path, typer.Option("--index", "-i")] = Path("index.json"),
|
|
53
|
+
mode: Annotated[str, typer.Option("--mode", help="Mode retrieval : bm25|vector|hybrid.")] = "hybrid",
|
|
54
|
+
timeout_s: Annotated[float, typer.Option("--timeout", help="Timeout global (s). 0 = désactivé.")] = 30.0,
|
|
55
|
+
) -> None:
|
|
56
|
+
"""Interroge l'index avec filtrage RBAC + redaction (tracé, jamais bloquant)."""
|
|
57
|
+
t_total = time.perf_counter()
|
|
58
|
+
trace_id = uuid.uuid4().hex[:16]
|
|
59
|
+
status = "ok"
|
|
60
|
+
model_name = "offline" if offline else "freellmapi/auto"
|
|
61
|
+
|
|
62
|
+
def _deny(verdict: str, detail: str, *, nb_total: int = 0, nb_autorise: int = 0, nb_bloque: int = 0) -> None:
|
|
63
|
+
nonlocal status
|
|
64
|
+
status = verdict
|
|
65
|
+
latency_total_ms = round((time.perf_counter() - t_total) * 1000.0, 2)
|
|
66
|
+
console.print(f"[red]DENY[/red] verdict={verdict}")
|
|
67
|
+
console.print(f"[red]{detail}[/red]")
|
|
68
|
+
try:
|
|
69
|
+
append_trace({
|
|
70
|
+
"trace_id": trace_id,
|
|
71
|
+
"role": role.value if isinstance(role, Role) else str(role),
|
|
72
|
+
"mode": mode,
|
|
73
|
+
"top_k": top_k,
|
|
74
|
+
"query": question,
|
|
75
|
+
"latency_total_ms": latency_total_ms,
|
|
76
|
+
"nb_total": nb_total,
|
|
77
|
+
"nb_autorise": nb_autorise,
|
|
78
|
+
"nb_bloque": nb_bloque,
|
|
79
|
+
"nb_secrets_dlp": 0,
|
|
80
|
+
"model": model_name,
|
|
81
|
+
"status": verdict,
|
|
82
|
+
})
|
|
83
|
+
except Exception:
|
|
84
|
+
pass
|
|
85
|
+
raise typer.Exit(code=1)
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
if timeout_s < 0:
|
|
89
|
+
raise typer.BadParameter("timeout doit être >= 0")
|
|
90
|
+
if mode not in ("bm25", "vector", "hybrid"):
|
|
91
|
+
raise typer.BadParameter("mode doit être bm25|vector|hybrid")
|
|
92
|
+
|
|
93
|
+
def _run_query():
|
|
94
|
+
chunks = load_index(index_path)
|
|
95
|
+
allowed = filter_chunks(chunks, role)
|
|
96
|
+
audit = audit_access(chunks, allowed)
|
|
97
|
+
t_ret = time.perf_counter()
|
|
98
|
+
retriever = HybridRetriever(allowed)
|
|
99
|
+
results = retriever.search(question, top_k=top_k, mode=mode)
|
|
100
|
+
latency_retrieval_ms = (time.perf_counter() - t_ret) * 1000.0
|
|
101
|
+
top_chunks = guard_prompt([c for c, _ in results])
|
|
102
|
+
nb_secrets_dlp = 0
|
|
103
|
+
for c, _ in results:
|
|
104
|
+
_, findings = redact_secrets(c.content)
|
|
105
|
+
nb_secrets_dlp += len(findings)
|
|
106
|
+
client = OfflineClient() if offline else OpenAICompatibleClient()
|
|
107
|
+
resolved_model = "offline" if offline else getattr(client, "model", "freellmapi/auto")
|
|
108
|
+
t_gen = time.perf_counter()
|
|
109
|
+
answer = generate_answer(question, top_chunks, client)
|
|
110
|
+
latency_generation_ms = (time.perf_counter() - t_gen) * 1000.0
|
|
111
|
+
return {
|
|
112
|
+
"audit": audit,
|
|
113
|
+
"results": results,
|
|
114
|
+
"answer": answer,
|
|
115
|
+
"latency_retrieval_ms": latency_retrieval_ms,
|
|
116
|
+
"latency_generation_ms": latency_generation_ms,
|
|
117
|
+
"nb_secrets_dlp": nb_secrets_dlp,
|
|
118
|
+
"model": resolved_model,
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if timeout_s and timeout_s > 0:
|
|
122
|
+
ex = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
|
123
|
+
fut = ex.submit(_run_query)
|
|
124
|
+
try:
|
|
125
|
+
payload = fut.result(timeout=timeout_s)
|
|
126
|
+
except concurrent.futures.TimeoutError:
|
|
127
|
+
ex.shutdown(wait=False, cancel_futures=True)
|
|
128
|
+
_deny(
|
|
129
|
+
"DENY_TIMEOUT",
|
|
130
|
+
f"Query timeout après {timeout_s:.1f}s (fail-closed). Aucun résultat retourné.",
|
|
131
|
+
)
|
|
132
|
+
finally:
|
|
133
|
+
ex.shutdown(wait=False, cancel_futures=True)
|
|
134
|
+
else:
|
|
135
|
+
payload = _run_query()
|
|
136
|
+
|
|
137
|
+
audit = payload["audit"]
|
|
138
|
+
results = payload["results"]
|
|
139
|
+
answer = payload["answer"]
|
|
140
|
+
model_name = str(payload["model"])
|
|
141
|
+
latency_retrieval_ms = float(payload["latency_retrieval_ms"])
|
|
142
|
+
latency_generation_ms = float(payload["latency_generation_ms"])
|
|
143
|
+
nb_secrets_dlp = int(payload["nb_secrets_dlp"])
|
|
144
|
+
|
|
145
|
+
console.print(f"[dim]RBAC {role.value} : {audit['nb_autorise']}/{audit['nb_total']} chunks autorisés[/dim]")
|
|
146
|
+
table = Table(title=f"Top-{top_k} passages (rôle={role.value} mode={mode})")
|
|
147
|
+
table.add_column("Score")
|
|
148
|
+
table.add_column("Path")
|
|
149
|
+
table.add_column("Section")
|
|
150
|
+
for c, s in results:
|
|
151
|
+
table.add_row(f"{s:.4f}", c.path, c.section or "—")
|
|
152
|
+
console.print(table)
|
|
153
|
+
console.print("\n[bold]Réponse :[/bold]")
|
|
154
|
+
console.print(answer.answer)
|
|
155
|
+
console.print(f"\n[dim]Citations : {', '.join(answer.citations) or '—'} "
|
|
156
|
+
f"| grounded={answer.grounded} redacted={answer.redacted}[/dim]")
|
|
157
|
+
|
|
158
|
+
latency_total_ms = (time.perf_counter() - t_total) * 1000.0
|
|
159
|
+
tokens_est = len((question + " " + answer.answer).split())
|
|
160
|
+
try:
|
|
161
|
+
append_trace({
|
|
162
|
+
"trace_id": trace_id,
|
|
163
|
+
"role": role.value,
|
|
164
|
+
"mode": mode,
|
|
165
|
+
"top_k": top_k,
|
|
166
|
+
"query": question, # sanitizé dans append_trace
|
|
167
|
+
"latency_retrieval_ms": round(latency_retrieval_ms, 2),
|
|
168
|
+
"latency_generation_ms": round(latency_generation_ms, 2),
|
|
169
|
+
"latency_total_ms": round(latency_total_ms, 2),
|
|
170
|
+
"nb_total": audit["nb_total"],
|
|
171
|
+
"nb_autorise": audit["nb_autorise"],
|
|
172
|
+
"nb_bloque": audit["nb_bloque"],
|
|
173
|
+
"nb_results": len(results),
|
|
174
|
+
"nb_secrets_dlp": nb_secrets_dlp,
|
|
175
|
+
"model": model_name,
|
|
176
|
+
"tokens_est": tokens_est,
|
|
177
|
+
"status": status,
|
|
178
|
+
})
|
|
179
|
+
except Exception:
|
|
180
|
+
pass
|
|
181
|
+
except typer.Exit:
|
|
182
|
+
raise
|
|
183
|
+
except Exception as exc:
|
|
184
|
+
status = f"error:{type(exc).__name__}"
|
|
185
|
+
latency_total_ms = round((time.perf_counter() - t_total) * 1000.0, 2)
|
|
186
|
+
console.print(f"[red]DENY[/red] verdict={status}")
|
|
187
|
+
console.print(f"[red]Query refusée (fail-closed): {type(exc).__name__}[/red]")
|
|
188
|
+
try:
|
|
189
|
+
append_trace({
|
|
190
|
+
"trace_id": trace_id,
|
|
191
|
+
"role": role.value if isinstance(role, Role) else str(role),
|
|
192
|
+
"mode": mode,
|
|
193
|
+
"top_k": top_k,
|
|
194
|
+
"query": question,
|
|
195
|
+
"latency_total_ms": latency_total_ms,
|
|
196
|
+
"nb_bloque": 0,
|
|
197
|
+
"nb_secrets_dlp": 0,
|
|
198
|
+
"model": model_name,
|
|
199
|
+
"status": status,
|
|
200
|
+
})
|
|
201
|
+
except Exception:
|
|
202
|
+
pass
|
|
203
|
+
raise typer.Exit(code=1) from exc
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
@app.command()
|
|
207
|
+
def eval(
|
|
208
|
+
dataset: Annotated[Path, typer.Argument(help="Chemin du dataset JSON.")],
|
|
209
|
+
index_path: Annotated[Path, typer.Option("--index", "-i")] = Path("index.json"),
|
|
210
|
+
role: Annotated[Role, typer.Option("--role", "-r")] = Role.viewer,
|
|
211
|
+
top_k: Annotated[int, typer.Option("--top-k", "-k")] = 5,
|
|
212
|
+
compare: Annotated[bool, typer.Option("--compare", help="Compare bm25/vector/hybrid.")] = False,
|
|
213
|
+
) -> None:
|
|
214
|
+
"""Évalue le retriever sur le dataset (RBAC appliqué avant recherche)."""
|
|
215
|
+
chunks = load_index(index_path)
|
|
216
|
+
retriever = HybridRetriever(chunks)
|
|
217
|
+
if compare:
|
|
218
|
+
results = run_compare(retriever, load_dataset(dataset), role=role, top_k=top_k)
|
|
219
|
+
table = Table(title=f"Comparatif modes (rôle={role.value})")
|
|
220
|
+
table.add_column("Mode")
|
|
221
|
+
table.add_column("Recall")
|
|
222
|
+
table.add_column("MRR")
|
|
223
|
+
table.add_column("Lat. moy (ms)")
|
|
224
|
+
table.add_column("Violations RBAC")
|
|
225
|
+
for m in ("bm25", "vector", "hybrid"):
|
|
226
|
+
s = results.get(m, {})
|
|
227
|
+
table.add_row(
|
|
228
|
+
m,
|
|
229
|
+
f"{float(s.get(f'mean_recall@{top_k}', 0.0)):.4f}",
|
|
230
|
+
f"{float(s.get('mean_mrr', 0.0)):.4f}",
|
|
231
|
+
f"{float(s.get('avg_latency_ms', 0.0)):.2f}",
|
|
232
|
+
str(s.get("rbac_violations", "?")),
|
|
233
|
+
)
|
|
234
|
+
console.print(table)
|
|
235
|
+
total_viol = sum(int(s.get("rbac_violations", 0)) for s in results.values())
|
|
236
|
+
if total_viol > 0:
|
|
237
|
+
console.print("[red]VIOLATIONS RBAC détectées ![/red]")
|
|
238
|
+
raise typer.Exit(code=1)
|
|
239
|
+
return
|
|
240
|
+
report = run_eval(retriever, load_dataset(dataset), role=role, top_k=top_k)
|
|
241
|
+
summary = report["summary"]
|
|
242
|
+
assert isinstance(summary, dict)
|
|
243
|
+
table = Table(title=f"Évaluation (rôle={role.value})")
|
|
244
|
+
table.add_column("Métrique")
|
|
245
|
+
table.add_column("Valeur")
|
|
246
|
+
for k, v in summary.items():
|
|
247
|
+
table.add_row(str(k), f"{v:.4f}" if isinstance(v, float) else str(v))
|
|
248
|
+
console.print(table)
|
|
249
|
+
if int(summary.get("rbac_violations", 0)) > 0:
|
|
250
|
+
console.print("[red]VIOLATIONS RBAC détectées ![/red]")
|
|
251
|
+
raise typer.Exit(code=1)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
@app.command(name="audit-rbac")
|
|
255
|
+
def audit_rbac(
|
|
256
|
+
index_path: Annotated[Path, typer.Argument(help="Chemin de l'index JSON.")],
|
|
257
|
+
) -> None:
|
|
258
|
+
"""Liste les chunks par sensibilité + matrice des rôles."""
|
|
259
|
+
chunks = load_index(index_path)
|
|
260
|
+
table = Table(title="Chunks par sensibilité")
|
|
261
|
+
table.add_column("Sensibilité")
|
|
262
|
+
table.add_column("Chunks")
|
|
263
|
+
table.add_column("Docs")
|
|
264
|
+
for sens in Sensitivity:
|
|
265
|
+
paths = sorted({c.path for c in chunks if c.sensitivity == sens})
|
|
266
|
+
n_chunks = sum(1 for c in chunks if c.sensitivity == sens)
|
|
267
|
+
table.add_row(sens.value, str(n_chunks), f"{len(paths)} docs — {', '.join(paths[:5]) or '—'}")
|
|
268
|
+
console.print(table)
|
|
269
|
+
|
|
270
|
+
matrix = Table(title="Matrice RBAC (rôle -> sensibilités autorisées)")
|
|
271
|
+
matrix.add_column("Rôle")
|
|
272
|
+
matrix.add_column("Autorisé")
|
|
273
|
+
matrix.add_column("Nb chunks visibles")
|
|
274
|
+
matrix.add_column("Nb chunks bloqués")
|
|
275
|
+
for r, sens_list in POLICIES.items():
|
|
276
|
+
allowed = filter_chunks(chunks, r)
|
|
277
|
+
n = len(allowed)
|
|
278
|
+
blocked = len(chunks) - n
|
|
279
|
+
matrix.add_row(r.value, ", ".join(s.value for s in sens_list), str(n), str(blocked))
|
|
280
|
+
console.print(matrix)
|
|
281
|
+
|
|
282
|
+
console.print("\n[bold]Verdict RBAC[/bold]")
|
|
283
|
+
violations = 0
|
|
284
|
+
for r, sens_list in POLICIES.items():
|
|
285
|
+
allowed = filter_chunks(chunks, r)
|
|
286
|
+
for c in allowed:
|
|
287
|
+
if c.sensitivity not in sens_list:
|
|
288
|
+
violations += 1
|
|
289
|
+
console.print(f"[red]FAIL[/red] role={r.value} leak={c.path} sensitivity={c.sensitivity.value}")
|
|
290
|
+
if violations:
|
|
291
|
+
console.print(f"[red]FAIL[/red] rbac_violations={violations}")
|
|
292
|
+
raise typer.Exit(code=1)
|
|
293
|
+
console.print("[green]PASS[/green] rbac_violations=0")
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
@app.command(name="stats")
|
|
297
|
+
def stats_cmd() -> None:
|
|
298
|
+
"""Affiche les statistiques de télémétrie (traces JSONL)."""
|
|
299
|
+
path = get_traces_path()
|
|
300
|
+
s = stats(path)
|
|
301
|
+
table = Table(title=f"Télémétrie RAG ({s.get('count', 0)} traces — {path})")
|
|
302
|
+
table.add_column("Métrique")
|
|
303
|
+
table.add_column("Valeur")
|
|
304
|
+
table.add_row("Traces", str(s.get("count", 0)))
|
|
305
|
+
table.add_row("p50 latence (ms)", f"{float(s.get('p50_latency_ms', 0.0)):.2f}")
|
|
306
|
+
table.add_row("p95 latence (ms)", f"{float(s.get('p95_latency_ms', 0.0)):.2f}")
|
|
307
|
+
table.add_row("Latence moyenne (ms)", f"{float(s.get('mean_latency_ms', 0.0)):.2f}")
|
|
308
|
+
table.add_row("Taux blocage RBAC", f"{float(s.get('taux_blocage', 0.0)):.2%}")
|
|
309
|
+
table.add_row("DENY/erreurs", f"{int(s.get('nb_denied', 0))} ({float(s.get('taux_denied', 0.0)):.2%})")
|
|
310
|
+
modes = s.get("repartition_modes", {})
|
|
311
|
+
assert isinstance(modes, dict)
|
|
312
|
+
table.add_row("Modes", ", ".join(f"{k}={v}" for k, v in modes.items()) or "—")
|
|
313
|
+
statuses = s.get("repartition_status", {})
|
|
314
|
+
assert isinstance(statuses, dict)
|
|
315
|
+
table.add_row("Status", ", ".join(f"{k}={v}" for k, v in statuses.items()) or "—")
|
|
316
|
+
console.print(table)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
if __name__ == "__main__":
|
|
320
|
+
app()
|
secops_rag/evals.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Évaluations : dataset, recall@k, MRR, RBAC, groundedness."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel, Field
|
|
10
|
+
|
|
11
|
+
from secops_rag.ingestion import Chunk, index_corpus, load_index
|
|
12
|
+
from secops_rag.retrieval import HybridRetriever
|
|
13
|
+
from secops_rag.security import Role, filter_chunks
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class EvalCase(BaseModel):
|
|
17
|
+
query: str
|
|
18
|
+
expected_paths: list[str] = Field(default_factory=list)
|
|
19
|
+
allowed_role: Role = Role.viewer
|
|
20
|
+
must_not_contain: list[str] = Field(default_factory=list)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def load_dataset(path: Path | str) -> list[EvalCase]:
|
|
24
|
+
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
25
|
+
return [EvalCase(**item) for item in data]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _norm(p: str) -> str:
|
|
29
|
+
"""Normalise un path pour comparaison : basename en minuscules."""
|
|
30
|
+
return Path(p).name.lower()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def recall_at_k(retrieved_paths: list[str], expected: list[str], k: int) -> float:
|
|
34
|
+
"""Part des attendus retrouvés dans le top-k (match exact normalisé)."""
|
|
35
|
+
if not expected:
|
|
36
|
+
return 1.0
|
|
37
|
+
top = {_norm(r) for r in retrieved_paths[:k]}
|
|
38
|
+
hit = sum(1 for e in expected if _norm(e) in top)
|
|
39
|
+
return hit / len(expected)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def mrr(retrieved_ranked: list[str], expected: list[str]) -> float:
|
|
43
|
+
"""1/rang du premier attendu retrouvé (0 si absent, match exact normalisé)."""
|
|
44
|
+
want = {_norm(e) for e in expected}
|
|
45
|
+
for rank, r in enumerate(retrieved_ranked, start=1):
|
|
46
|
+
if _norm(r) in want:
|
|
47
|
+
return 1.0 / rank
|
|
48
|
+
return 0.0
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def run_eval(
|
|
52
|
+
retriever: HybridRetriever,
|
|
53
|
+
dataset: list[EvalCase],
|
|
54
|
+
role: Role | str = Role.viewer,
|
|
55
|
+
top_k: int = 5,
|
|
56
|
+
mode: str = "hybrid",
|
|
57
|
+
) -> dict[str, object]:
|
|
58
|
+
"""Évalue le retriever. Le filtrage RBAC est appliqué AVANT la recherche."""
|
|
59
|
+
r = role if isinstance(role, Role) else Role(str(role))
|
|
60
|
+
if mode not in ("bm25", "vector", "hybrid"):
|
|
61
|
+
raise ValueError(f"mode doit être bm25|vector|hybrid (reçu {mode!r})")
|
|
62
|
+
allowed = filter_chunks(retriever.chunks, r)
|
|
63
|
+
scoped = HybridRetriever(allowed) if len(allowed) != len(retriever.chunks) else retriever
|
|
64
|
+
|
|
65
|
+
cases: list[dict[str, object]] = []
|
|
66
|
+
recalls: list[float] = []
|
|
67
|
+
mrrs: list[float] = []
|
|
68
|
+
latences: list[float] = []
|
|
69
|
+
violations = 0
|
|
70
|
+
grounded = 0
|
|
71
|
+
for case in dataset:
|
|
72
|
+
t0 = time.perf_counter()
|
|
73
|
+
results = scoped.search(case.query, top_k=top_k, mode=mode)
|
|
74
|
+
latences.append((time.perf_counter() - t0) * 1000.0)
|
|
75
|
+
paths = [c.path for c, _ in results]
|
|
76
|
+
rec = recall_at_k(paths, case.expected_paths, top_k)
|
|
77
|
+
m = mrr(paths, case.expected_paths)
|
|
78
|
+
# RBAC : aucun chunk restreint ne doit fuiter pour un rôle non admin
|
|
79
|
+
leaked = [c for c, _ in results if not _role_may_see(r, c)]
|
|
80
|
+
violations += len(leaked)
|
|
81
|
+
# must_not_contain : aucun secret attendu dans les contenus retournés
|
|
82
|
+
for c, _ in results:
|
|
83
|
+
for forbidden in case.must_not_contain:
|
|
84
|
+
if forbidden in c.content:
|
|
85
|
+
violations += 1
|
|
86
|
+
norm_paths = {_norm(p) for p in paths}
|
|
87
|
+
if any(_norm(e) in norm_paths for e in case.expected_paths) or not case.expected_paths:
|
|
88
|
+
grounded += 1
|
|
89
|
+
recalls.append(rec)
|
|
90
|
+
mrrs.append(m)
|
|
91
|
+
cases.append(
|
|
92
|
+
{
|
|
93
|
+
"query": case.query,
|
|
94
|
+
"retrieved": paths,
|
|
95
|
+
f"recall@{top_k}": rec,
|
|
96
|
+
"mrr": m,
|
|
97
|
+
"rbac_leaks": len(leaked),
|
|
98
|
+
}
|
|
99
|
+
)
|
|
100
|
+
n = len(dataset) or 1
|
|
101
|
+
return {
|
|
102
|
+
"cases": cases,
|
|
103
|
+
"summary": {
|
|
104
|
+
f"mean_recall@{top_k}": sum(recalls) / n,
|
|
105
|
+
"mean_mrr": sum(mrrs) / n,
|
|
106
|
+
"rbac_violations": violations,
|
|
107
|
+
"citation_groundedness": grounded / n,
|
|
108
|
+
"avg_latency_ms": sum(latences) / n if latences else 0.0,
|
|
109
|
+
"mode": mode,
|
|
110
|
+
},
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def run_compare(
|
|
115
|
+
retriever: HybridRetriever,
|
|
116
|
+
dataset: list[EvalCase],
|
|
117
|
+
role: Role | str = Role.viewer,
|
|
118
|
+
top_k: int = 5,
|
|
119
|
+
modes: tuple[str, ...] = ("bm25", "vector", "hybrid"),
|
|
120
|
+
) -> dict[str, dict[str, object]]:
|
|
121
|
+
"""Compare les 3 modes : recall, MRR, latences, 0 violation RBAC attendue."""
|
|
122
|
+
out: dict[str, dict[str, object]] = {}
|
|
123
|
+
for m in modes:
|
|
124
|
+
report = run_eval(retriever, dataset, role=role, top_k=top_k, mode=m)
|
|
125
|
+
summary = dict(report["summary"]) # type: ignore[arg-type]
|
|
126
|
+
out[m] = summary
|
|
127
|
+
return out
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _role_may_see(role: Role, chunk: Chunk) -> bool:
|
|
131
|
+
from secops_rag.security import can_access
|
|
132
|
+
|
|
133
|
+
return can_access(role, chunk.sensitivity)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def evaluate_corpus(
|
|
137
|
+
corpus_root: Path | str,
|
|
138
|
+
dataset_path: Path | str,
|
|
139
|
+
role: Role | str = Role.viewer,
|
|
140
|
+
top_k: int = 5,
|
|
141
|
+
) -> dict[str, object]:
|
|
142
|
+
chunks = index_corpus(corpus_root)
|
|
143
|
+
retriever = HybridRetriever(chunks)
|
|
144
|
+
dataset = load_dataset(dataset_path)
|
|
145
|
+
return run_eval(retriever, dataset, role=role, top_k=top_k)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def load_retriever_from_index(index_path: Path | str) -> HybridRetriever:
|
|
149
|
+
return HybridRetriever(load_index(index_path))
|