Service d'accès : les projets du client au clic sur « Generate reply »

- acces/ : conteneur (bibliothèque standard) qui répond à l'outil get_customer_access de LibreDesk.
  L'e-mail du contact (X-Libredesk-Contact-Email, ajouté par LibreDesk, jamais par le LLM) est
  traduit en compte auth0|… par l'export d'Auth0 (utilisateurs.json), puis en projets par les
  UserGroup de la base du dashboard (database.db, lecture seule) : project, serial, role.
  Jeton Bearer obligatoire ; fichier ou base illisible → 502, jamais une liste vide.
- exporter_utilisateurs.py : l'export Auth0, lancé avec le .env du dashboard.
- Données et secrets hors de git (acces/.env, database.db, utilisateurs.json), .env interdit à Claude.
- Production : en service provisoire sur le PC de Maxime (point 14), vérifié sur un vrai
  « Generate reply » (1 projet renvoyé). Architecture draw.io : la partie accès.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maximeandClaude Opus 5.5 committed 2026-11-18 13:50:31 +01:00
1 parent 2f7ec25731
commit 369f2e0a44
12 files changed
+452 -16

No files matched your search

+2 -1
View File
@@ -5,7 +5,8 @@
"deny": [ "deny": [
"Read(./.env)", "Read(./.env)",
"Read(./.env.*)", "Read(./.env.*)",
"Read(./instance-de-test/.env)" "Read(./instance-de-test/.env)",
"Read(./acces/.env)"
] ]
}, },
"hooks": {} "hooks": {}
+3
View File
@@ -1,5 +1,8 @@
.env .env
instance-de-test/.env instance-de-test/.env
acces/.env
acces/database.db
acces/utilisateurs.json
instance-de-test/config.toml instance-de-test/config.toml
instance-de-test/uploads/ instance-de-test/uploads/
__pycache__/ __pycache__/
+1
View File
@@ -5,6 +5,7 @@ Les demandes des clients AIMsight arrivent par mail dans LibreDesk (`helpdesk.se
Ce dépôt porte tout ce qu'il faut pour cela : Ce dépôt porte tout ce qu'il faut pour cela :
- `snippets/` : les textes des snippets, relus (`textes/`, un fichier par snippet), les consignes de rédaction (`consignes_redaction.md`, à coller dans Admin → IA → Providers → Custom instructions) et l'import vers LibreDesk ; - `snippets/` : les textes des snippets, relus (`textes/`, un fichier par snippet), les consignes de rédaction (`consignes_redaction.md`, à coller dans Admin → IA → Providers → Custom instructions) et l'import vers LibreDesk ;
- `ollama/` : l'image Ollama avec le modèle d'embeddings `bge-m3:567m` embarqué, qui sert la recherche dans la base depuis le serveur de LibreDesk ; - `ollama/` : l'image Ollama avec le modèle d'embeddings `bge-m3:567m` embarqué, qui sert la recherche dans la base depuis le serveur de LibreDesk ;
- `acces/` : le service d'accès, appelé par l'outil `get_customer_access` de LibreDesk au clic sur « Generate reply » : les stations que le client de la conversation peut voir sur le dashboard (export d'Auth0 `acces/utilisateurs.json` + ses UserGroup, en lecture seule) ; lancement dans `acces/compose.yml` ;
- `instance-de-test/` : un LibreDesk v2.9.0 local avec Mailpit (un piège SMTP : rien ne sort), pour tout essayer avant la production ; - `instance-de-test/` : un LibreDesk v2.9.0 local avec Mailpit (un piège SMTP : rien ne sort), pour tout essayer avant la production ;
- `.vscode/tasks.json` : les opérations courantes en un clic (Terminal → Run Task). - `.vscode/tasks.json` : les opérations courantes en un clic (Terminal → Run Task).
+7
View File
@@ -0,0 +1,7 @@
# Le service d'accès (acces/service.py) : bibliothèque standard seulement, rien à installer.
# Version figée (2026-11-18) ; la changer = reconstruire et relancer tests/test_acces.py.
FROM python:3.12.8-slim-bookworm
COPY service.py /app/service.py
USER nobody
EXPOSE 8080
CMD ["python", "-u", "/app/service.py"]
+13
View File
@@ -0,0 +1,13 @@
# Surcharge : rattache le service d'accès au réseau Docker de LibreDesk, où il est joignable sous le nom « acces »
# (http://acces:8080/customer/access). Localement RESEAU_LIBREDESK=ldtest_libredesk ; sur le serveur, le réseau de LibreDesk.
# RESEAU_LIBREDESK=<réseau> docker compose -f acces/compose.yml -f acces/compose.reseau.yml up -d
services:
acces:
networks:
libredesk:
aliases: [acces]
networks:
libredesk:
name: ${RESEAU_LIBREDESK:?donner le réseau Docker de LibreDesk dans RESEAU_LIBREDESK}
external: true
+23
View File
@@ -0,0 +1,23 @@
# Le service d'accès. Son port n'est publié que sur 127.0.0.1, sauf si ACCES_BIND donne une autre adresse (une adresse
# INTERNE, jamais publique) ; ACCES_PORT change le port publié (8080 par défaut).
# - acces/.env (hors de git, jamais lu par Claude) : ACCES_JETON, le même que l'en-tête « Authorization: Bearer … » de
# l'outil get_customer_access de LibreDesk ; ACCES_BIND, ACCES_PORT, BASE_DASHBOARD s'il le faut ;
# - BASE_DASHBOARD : le chemin, sur l'hôte, du database.db du dashboard (acces/database.db par défaut) ;
# acces/utilisateurs.json : l'export d'Auth0 (acces/exporter_utilisateurs.py). Les deux montés en lecture seule.
# docker compose -f acces/compose.yml up -d --build
# Sur le réseau Docker de LibreDesk (URL de l'outil : http://acces:8080/customer/access) : ajouter compose.reseau.yml.
services:
acces:
build: .
image: exchange.sensima.ch/maxime.pasquier/libredesk-acces:1
container_name: libredesk-acces
restart: unless-stopped
env_file: .env
environment:
ACCES_BASE: /data/database.db
ACCES_UTILISATEURS: /data/utilisateurs.json
volumes:
- "${BASE_DASHBOARD:-./database.db}:/data/database.db:ro"
- "./utilisateurs.json:/data/utilisateurs.json:ro"
ports:
- "${ACCES_BIND:-127.0.0.1}:${ACCES_PORT:-8080}:8080"
+42
View File
@@ -0,0 +1,42 @@
"""Les contacts de LibreDesk (lecture seule) : leurs e-mails, pour les comparer aux utilisateurs du dashboard (Auth0).
Lancé par Maxime (Claude ne lit pas le .env) :
set -a && . ./.env && set +a && python3 acces/contacts.py
Clé admin (LIBREDESK_ADMIN_KEY / _SECRET) : lister tous les contacts demande `contacts:read_all`, que la clé agent n'a
pas. Seulement GET /api/v1/contacts. La liste complète va dans cases/ (hors de git) ; à l'écran, des totaux seulement.
"""
import collections
import json
import os
import urllib.request
from datetime import date
from pathlib import Path
URL = os.environ.get("LIBREDESK_URL", "https://helpdesk.sensima.ch").rstrip("/")
SORTIE = Path(__file__).resolve().parents[1] / "cases" / f"contacts-libredesk-{date.today()}.json"
def page(n: int) -> dict:
cle = f"token {os.environ['LIBREDESK_ADMIN_KEY']}:{os.environ['LIBREDESK_ADMIN_SECRET']}"
requete = urllib.request.Request(f"{URL}/api/v1/contacts?page={n}&page_size=100", headers={"Authorization": cle})
with urllib.request.urlopen(requete, timeout=30) as r:
return json.load(r)["data"]
if __name__ == "__main__":
contacts, n = [], 1
while True:
d = page(n)
contacts += d["results"]
if n >= d["total_pages"]:
break
n += 1
SORTIE.parent.mkdir(exist_ok=True)
SORTIE.write_text(json.dumps(contacts, ensure_ascii=False, indent=1), encoding="utf-8")
emails = [(c.get("email") or "").strip() for c in contacts]
domaines = collections.Counter(e.rsplit("@", 1)[-1].lower() for e in emails if "@" in e)
print(f"{URL} : {len(contacts)} contacts, {sum(map(bool, emails))} avec e-mail, "
f"{sum(e != e.lower() for e in emails)} avec des majuscules, "
f"{sum(bool(c.get('external_user_id')) for c in contacts)} avec external_user_id, "
f"{len(domaines)} domaines")
print(f"liste complète : {SORTIE}")
+64
View File
@@ -0,0 +1,64 @@
"""Exporte une fois les utilisateurs du dashboard depuis Auth0 (e-mail → auth0|…) dans acces/utilisateurs.json (hors de git).
Lecture seule (GET /users), avec l'application Auth0 du dashboard, comme sa page Settings (`get_all_users`).
Lancé par Maxime avec les variables du dashboard (Claude ne lit pas ce .env) :
set -a && . ~/monitoring-dashboard/.env && set +a && python3 acces/exporter_utilisateurs.py
Variables : AUTH0_API_AUDIENCE (https://<tenant>/api/v2), AUTH0_API_CLIENTID, AUTH0_API_CLIENT_SECRET.
À relancer quand des utilisateurs sont ajoutés au dashboard ; le service relit le fichier à chaque appel.
"""
import json
import os
import sys
import urllib.parse
import urllib.request
from pathlib import Path
SORTIE = Path(__file__).resolve().parent / "utilisateurs.json"
PAR_PAGE = 100
def index_par_email(utilisateurs: list[dict]) -> dict[str, list[str]]:
"""{e-mail en minuscules: [user_id…]} ; une adresse peut avoir plusieurs comptes, un compte sans e-mail est ignoré."""
index: dict[str, list[str]] = {}
for u in utilisateurs:
email = (u.get("email") or "").strip().lower()
if email:
index.setdefault(email, []).append(u["user_id"])
return {e: sorted(ids) for e, ids in sorted(index.items())}
def jeton(api: str) -> str:
u = urllib.parse.urlsplit(api)
corps = json.dumps({"client_id": os.environ["AUTH0_API_CLIENTID"],
"client_secret": os.environ["AUTH0_API_CLIENT_SECRET"],
"audience": api + "/", "grant_type": "client_credentials"}).encode()
requete = urllib.request.Request(f"{u.scheme}://{u.netloc}/oauth/token", corps, {"Content-Type": "application/json"})
with urllib.request.urlopen(requete, timeout=30) as r:
return json.load(r)["access_token"]
def tous_les_utilisateurs(api: str) -> list[dict]:
entete = {"Authorization": f"Bearer {jeton(api)}"}
utilisateurs, page = [], 0
while True:
q = urllib.parse.urlencode({"page": page, "per_page": PAR_PAGE, "include_totals": "true",
"fields": "user_id,email", "include_fields": "true"})
with urllib.request.urlopen(urllib.request.Request(f"{api}/users?{q}", headers=entete), timeout=30) as r:
d = json.load(r)
utilisateurs += d["users"]
if not d["users"] or len(utilisateurs) >= d["total"]:
return utilisateurs
page += 1
# ponytail: Auth0 ne pagine que les 1000 premiers comptes ; au-delà, passer par un job d'export
if page * PAR_PAGE >= 1000:
sys.exit(f"plus de 1000 comptes ({d['total']}) : la pagination d'Auth0 ne suffit plus")
if __name__ == "__main__":
api = os.environ["AUTH0_API_AUDIENCE"].rstrip("/")
utilisateurs = tous_les_utilisateurs(api)
index = index_par_email(utilisateurs)
SORTIE.write_text(json.dumps(index, ensure_ascii=False, indent=1), encoding="utf-8")
print(f"{len(utilisateurs)} comptes Auth0, {len(index)} adresses, "
f"{sum(len(v) > 1 for v in index.values())} adresses avec plusieurs comptes, "
f"{sum(not u.get('email') for u in utilisateurs)} comptes sans e-mail → {SORTIE}")
+94
View File
@@ -0,0 +1,94 @@
"""Le service d'accès : les stations qu'un contact LibreDesk a le droit de voir (docs/architecture.drawio).
GET /customer/access, appelé par l'outil `get_customer_access` de LibreDesk au clic sur « Generate reply » :
- `Authorization: Bearer <ACCES_JETON>` (l'en-tête secret déclaré dans l'outil), sinon 401 ;
- `X-Libredesk-Contact-Email`, ajouté par LibreDesk lui-même, jamais par le LLM ;
- e-mail → comptes du dashboard (utilisateurs.json, exporté d'Auth0 par exporter_utilisateurs.py) → leurs UserGroup
→ les projets (Device) : {"projects": [{"project": nom, "serial": station, "role": "dev_admin" | "user"}]}.
Les deux rôles voient le projet sur le dashboard ; c'est la règle du dashboard
(`Device.user_access`, `can_access_system`). La table UserAccess, ancienne, n'est plus lue par le dashboard : ignorée.
ponytail: les admins globaux du dashboard (`is_admin()`, un rôle Auth0, absent de la base) voient tout là-bas mais
reçoivent ici une liste vide ; laissé de côté (équipe interne, pas des clients) : exporter les rôles si ça change.
Contact sans e-mail, inconnu ou sans droit : liste vide. Fichier ou base illisible : 502, jamais une liste vide
(« aucun droit » serait faux).
Variables : ACCES_JETON (32 caractères au moins), ACCES_BASE (database.db du dashboard, ouverte en lecture seule),
ACCES_UTILISATEURS (utilisateurs.json, relu à chaque appel : un nouvel export sert sans redémarrer).
Écoute toujours sur 8080 dans le conteneur ; le port publié se choisit dans le compose (ACCES_PORT).
"""
import hmac
import json
import os
import sqlite3
import sys
import urllib.parse
from contextlib import closing
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
ROUTE = "/customer/access"
VARIABLES = ("ACCES_JETON", "ACCES_BASE", "ACCES_UTILISATEURS")
def comptes(utilisateurs: str, email: str) -> list[str]:
"""Les comptes du dashboard (auth0|…) de cette adresse."""
return json.loads(Path(utilisateurs).read_text(encoding="utf-8")).get(email, [])
def projets(base: str, user_ids: list[str]) -> list[dict]:
"""Les projets (Device) dont l'un de ces comptes est membre d'un groupe : nom, station (serial) et rôle (`dev_admin`
l'emporte sur `user` si le compte est dans les deux groupes du projet)."""
if not user_ids:
return []
with closing(sqlite3.connect(Path(base).resolve().as_uri() + "?mode=ro", uri=True)) as c:
lignes = c.execute(
"SELECT d.name, d.serial_number, MIN(CASE g.role WHEN 'dev_admin' THEN 0 ELSE 1 END) "
"FROM UserGroupEntry e JOIN UserGroup g ON g.id = e.group_id JOIN Device d ON d.id = g.device_id "
f"WHERE d.serial_number IS NOT NULL AND e.user_id IN ({','.join('?' * len(user_ids))}) "
"GROUP BY d.id ORDER BY 2, 1", user_ids).fetchall()
return [{"project": nom, "serial": serial, "role": "dev_admin" if r == 0 else "user"} for nom, serial, r in lignes]
def creer_serveur(adresse: tuple[str, int], jeton: str, base: str, utilisateurs: str) -> ThreadingHTTPServer:
attendu = f"Bearer {jeton}".encode()
class Gestion(BaseHTTPRequestHandler):
def _repondre(self, code: int, corps: dict):
texte = json.dumps(corps, ensure_ascii=False).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(texte)))
self.end_headers()
self.wfile.write(texte)
def do_GET(self):
if urllib.parse.urlsplit(self.path).path != ROUTE:
return self._repondre(404, {"error": "not found"})
if not hmac.compare_digest(self.headers.get("Authorization", "").encode(), attendu):
return self._repondre(401, {"error": "unauthorized"})
email = self.headers.get("X-Libredesk-Contact-Email", "").strip().lower()
try:
liste = projets(base, comptes(utilisateurs, email)) if email else []
except Exception as e: # fichier ou base : on refuse plutôt que de répondre « aucun droit »
self.log_error("recherche des droits impossible : %r", e)
return self._repondre(502, {"error": "access lookup unavailable"})
# sans l'adresse : seulement si le contact a un e-mail et combien de projets il voit
self.log_message("e-mail %s, %d projet(s)", "présent" if email else "absent", len(liste))
self._repondre(200, {"projects": liste})
return ThreadingHTTPServer(adresse, Gestion)
if __name__ == "__main__":
manquantes = [n for n in VARIABLES if not os.environ.get(n)]
if manquantes:
sys.exit("variables manquantes : " + ", ".join(manquantes))
if len(os.environ["ACCES_JETON"]) < 32:
sys.exit("ACCES_JETON trop court (32 caractères au moins)")
base, utilisateurs = os.environ["ACCES_BASE"], os.environ["ACCES_UTILISATEURS"]
projets(base, comptes(utilisateurs, "")) # base et fichier lisibles, sinon on s'arrête au démarrage
projets(base, ["-"])
serveur = creer_serveur(("0.0.0.0", 8080), os.environ["ACCES_JETON"], base,
utilisateurs)
print(f"service d'accès sur le port {serveur.server_address[1]}", flush=True)
serveur.serve_forever()
+69 -15
View File
@@ -1,6 +1,6 @@
<mxfile host="Electron"> <mxfile host="Electron">
<diagram name="1. Architecture" id="arch"> <diagram name="1. Architecture" id="arch">
<mxGraphModel dx="2914" dy="841" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1500" pageHeight="900" math="0" shadow="0"> <mxGraphModel dx="2678" dy="701" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1500" pageHeight="900" math="0" shadow="0">
<root> <root>
<mxCell id="0" /> <mxCell id="0" />
<mxCell id="1" parent="0" /> <mxCell id="1" parent="0" />
@@ -18,13 +18,13 @@
</mxGeometry> </mxGeometry>
</mxCell> </mxCell>
<mxCell id="arch-2" parent="1" style="shape=umlActor;verticalLabelPosition=bottom;verticalAlign=top;html=1;outlineConnect=0;" value="Customer" vertex="1"> <mxCell id="arch-2" parent="1" style="shape=umlActor;verticalLabelPosition=bottom;verticalAlign=top;html=1;outlineConnect=0;" value="Customer" vertex="1">
<mxGeometry height="70" width="40" x="-170" y="205" as="geometry" /> <mxGeometry height="70" width="40" x="-220" y="205" as="geometry" />
</mxCell> </mxCell>
<mxCell id="9YVmYg31Dtc29ZtFE1oE-3" edge="1" parent="1" source="arch-3" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;defaultLabelBackgroundColor=page;fillColor=#60a917;strokeColor=#2D7600;" target="arch-2"> <mxCell id="9YVmYg31Dtc29ZtFE1oE-3" edge="1" parent="1" source="arch-3" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;defaultLabelBackgroundColor=page;fillColor=#60a917;strokeColor=#2D7600;" target="arch-2">
<mxGeometry relative="1" as="geometry"> <mxGeometry relative="1" as="geometry">
<Array as="points"> <Array as="points">
<mxPoint x="-270" y="470" /> <mxPoint x="-320" y="470" />
<mxPoint x="-270" y="240" /> <mxPoint x="-320" y="240" />
</Array> </Array>
</mxGeometry> </mxGeometry>
</mxCell> </mxCell>
@@ -34,7 +34,7 @@
</mxGeometry> </mxGeometry>
</mxCell> </mxCell>
<mxCell id="arch-3" parent="1" style="shape=umlActor;verticalLabelPosition=bottom;verticalAlign=top;html=1;outlineConnect=0;" value="Support agent&lt;div&gt;(human)&lt;/div&gt;" vertex="1"> <mxCell id="arch-3" parent="1" style="shape=umlActor;verticalLabelPosition=bottom;verticalAlign=top;html=1;outlineConnect=0;" value="Support agent&lt;div&gt;(human)&lt;/div&gt;" vertex="1">
<mxGeometry height="70" width="40" x="-170" y="435" as="geometry" /> <mxGeometry height="70" width="40" x="-220" y="435" as="geometry" />
</mxCell> </mxCell>
<mxCell id="arch-4" parent="1" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" value="&lt;b&gt;Anthropic&lt;/b&gt;&lt;div&gt;https://api.anthropic.com/v1&lt;/div&gt;" vertex="1"> <mxCell id="arch-4" parent="1" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" value="&lt;b&gt;Anthropic&lt;/b&gt;&lt;div&gt;https://api.anthropic.com/v1&lt;/div&gt;" vertex="1">
<mxGeometry height="60" width="180" x="225" y="10" as="geometry" /> <mxGeometry height="60" width="180" x="225" y="10" as="geometry" />
@@ -45,13 +45,13 @@
<mxCell id="9YVmYg31Dtc29ZtFE1oE-2" edge="1" parent="1" source="arch-6" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;defaultLabelBackgroundColor=page;" target="arch-3"> <mxCell id="9YVmYg31Dtc29ZtFE1oE-2" edge="1" parent="1" source="arch-6" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;defaultLabelBackgroundColor=page;" target="arch-3">
<mxGeometry relative="1" as="geometry"> <mxGeometry relative="1" as="geometry">
<Array as="points"> <Array as="points">
<mxPoint y="470" /> <mxPoint x="-110" y="470" />
<mxPoint y="470" /> <mxPoint x="-110" y="470" />
</Array> </Array>
</mxGeometry> </mxGeometry>
</mxCell> </mxCell>
<mxCell id="arch-6" parent="1" style="rounded=1;arcSize=3;whiteSpace=wrap;html=1;verticalAlign=top;align=left;spacingLeft=8;fontStyle=1;fillColor=#fafafa;strokeColor=#6c8ebf;" value="LibreDesk" vertex="1"> <mxCell id="arch-6" parent="1" style="rounded=1;arcSize=3;whiteSpace=wrap;html=1;verticalAlign=top;align=left;spacingLeft=8;fontStyle=1;fillColor=#fafafa;strokeColor=#6c8ebf;" value="LibreDesk" vertex="1">
<mxGeometry height="465" width="890" x="50" y="160" as="geometry" /> <mxGeometry height="465" width="970" x="-30" y="160" as="geometry" />
</mxCell> </mxCell>
<mxCell id="HigBPHvGvvlsroYYhkdi-20" edge="1" parent="1" source="arch-7" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;defaultLabelBackgroundColor=page;endArrow=none;endFill=0;" target="arch-4"> <mxCell id="HigBPHvGvvlsroYYhkdi-20" edge="1" parent="1" source="arch-7" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;defaultLabelBackgroundColor=page;endArrow=none;endFill=0;" target="arch-4">
<mxGeometry relative="1" as="geometry" /> <mxGeometry relative="1" as="geometry" />
@@ -83,7 +83,7 @@
<mxGeometry height="70" width="170" x="700" y="180" as="geometry" /> <mxGeometry height="70" width="170" x="700" y="180" as="geometry" />
</mxCell> </mxCell>
<mxCell id="arch-11" parent="1" style="rounded=1;arcSize=3;whiteSpace=wrap;html=1;verticalAlign=top;align=left;spacingLeft=8;fontStyle=1;fillColor=#fafafa;strokeColor=#6c8ebf;" value="Tools &lt;span style=&quot;font-weight:normal&quot;&gt;(function calling: name + JSON schema, exposed to the LLM)&lt;/span&gt;" vertex="1"> <mxCell id="arch-11" parent="1" style="rounded=1;arcSize=3;whiteSpace=wrap;html=1;verticalAlign=top;align=left;spacingLeft=8;fontStyle=1;fillColor=#fafafa;strokeColor=#6c8ebf;" value="Tools &lt;span style=&quot;font-weight:normal&quot;&gt;(function calling: name + JSON schema, exposed to the LLM)&lt;/span&gt;" vertex="1">
<mxGeometry height="190" width="735" x="135" y="410" as="geometry" /> <mxGeometry height="210" width="735" x="135" y="390" as="geometry" />
</mxCell> </mxCell>
<mxCell id="HigBPHvGvvlsroYYhkdi-16" edge="1" parent="1" source="arch-12" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;defaultLabelBackgroundColor=page;endArrow=none;endFill=0;" target="arch-8"> <mxCell id="HigBPHvGvvlsroYYhkdi-16" edge="1" parent="1" source="arch-12" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;defaultLabelBackgroundColor=page;endArrow=none;endFill=0;" target="arch-8">
<mxGeometry relative="1" as="geometry" /> <mxGeometry relative="1" as="geometry" />
@@ -123,16 +123,70 @@
<mxCell id="fix-6" parent="1" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#ffe6cc;strokeColor=#d79b00;dashed=1;strokeWidth=2;" value="&lt;b&gt;REST API&lt;/b&gt;&lt;br&gt;GET /stations/{serial}/diagnostic?from=…&amp;amp;to=…&lt;br&gt;→ events: family, start, end, evidence" vertex="1"> <mxCell id="fix-6" parent="1" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#ffe6cc;strokeColor=#d79b00;dashed=1;strokeWidth=2;" value="&lt;b&gt;REST API&lt;/b&gt;&lt;br&gt;GET /stations/{serial}/diagnostic?from=…&amp;amp;to=…&lt;br&gt;→ events: family, start, end, evidence" vertex="1">
<mxGeometry height="80" width="360" x="135" y="780" as="geometry" /> <mxGeometry height="80" width="360" x="135" y="780" as="geometry" />
</mxCell> </mxCell>
<mxCell id="acc-check" parent="1" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;dashed=1;strokeWidth=2;" value="&lt;b&gt;Access check&lt;/b&gt; (before any data is read)&lt;br&gt;same identity headers → access service:&lt;br&gt;serial among the customer&#39;s stations? no → 403" vertex="1">
<mxGeometry height="70" width="360" x="135" y="880" as="geometry" />
</mxCell>
<mxCell id="acc-allowed" edge="1" parent="1" source="acc-check" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;labelBackgroundColor=#ffffff;endArrow=classic;strokeColor=#d79b00;strokeWidth=2;dashed=1;fontColor=#b36b00;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" target="fix-7" value="allowed">
<mxGeometry relative="1" as="geometry" />
</mxCell>
<mxCell id="acc-tool" parent="1" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;dashed=1;strokeWidth=2;" value="&lt;b&gt;get_customer_access()&lt;/b&gt;&lt;br&gt;no parameter: called first, on Generate reply" vertex="1">
<mxGeometry height="62" width="320" x="155" y="432" as="geometry" />
</mxCell>
<mxCell id="acc-e-conv" edge="1" parent="1" source="HigBPHvGvvlsroYYhkdi-3" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;labelBackgroundColor=#ffffff;endArrow=classic;strokeColor=#b85450;dashed=1;fontColor=#b85450;" target="acc-tool" value="contact identity&lt;br&gt;(X-Libredesk-Contact-*&lt;br&gt;headers, added by&lt;br&gt;LibreDesk, not the LLM)">
<mxGeometry relative="1" x="-0.1837" as="geometry">
<mxPoint as="offset" />
<Array as="points">
<mxPoint x="40" y="260" />
<mxPoint x="40" y="448" />
</Array>
</mxGeometry>
</mxCell>
<mxCell id="acc-svc" parent="1" style="rounded=1;arcSize=3;whiteSpace=wrap;html=1;verticalAlign=top;align=left;spacingLeft=8;fontStyle=1;fillColor=#fdf3f2;strokeColor=#b85450;dashed=1;strokeWidth=2;" value="Access service (independent container)" vertex="1">
<mxGeometry height="330" width="465" x="-390" y="740" as="geometry" />
</mxCell>
<mxCell id="acc-api" parent="1" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;dashed=1;strokeWidth=2;" value="&lt;b&gt;REST API&lt;/b&gt;&lt;br&gt;GET /customer/access (identity from the headers)&lt;br&gt;→ projects the customer may see: project, serial, role" vertex="1">
<mxGeometry height="80" width="425" x="-370" y="780" as="geometry" />
</mxCell>
<mxCell id="acc-lookup" parent="1" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;dashed=1;strokeWidth=2;" value="&lt;b&gt;Rights lookup&lt;/b&gt;&lt;br&gt;contact e-mail → dashboard account (auth0|…)&lt;br&gt;→ its UserGroups (user / dev_admin) → Device.serial_number&lt;br&gt;unknown contact → empty list" vertex="1">
<mxGeometry height="150" width="425" x="-370" y="890" as="geometry" />
</mxCell>
<mxCell id="acc-e-api" edge="1" parent="1" source="acc-api" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;labelBackgroundColor=#ffffff;endArrow=classic;strokeColor=#b85450;dashed=1;fontColor=#b85450;strokeWidth=2;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" target="acc-lookup" value="">
<mxGeometry relative="1" as="geometry" />
</mxCell>
<mxCell id="acc-auth0" parent="1" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;" value="&lt;b&gt;utilisateurs.json&lt;/b&gt;&lt;br&gt;e-mail → auth0|…&lt;br&gt;exported once from Auth0" vertex="1">
<mxGeometry height="70" width="200" x="-390" y="1190" as="geometry" />
</mxCell>
<mxCell id="acc-db" parent="1" style="shape=cylinder3;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;size=10;fillColor=#f8cecc;strokeColor=#b85450;" value="&lt;b&gt;Access rights&lt;/b&gt; (dashboard DB)&lt;br&gt;&lt;b&gt;UserGroupEntry&lt;/b&gt;: user → UserGroup&lt;br&gt;&lt;b&gt;UserGroup&lt;/b&gt;: device × role (user · dev_admin)&lt;br&gt;&lt;b&gt;Device&lt;/b&gt;.serial_number (1..n per serial)" vertex="1">
<mxGeometry height="120" width="245" x="-170" y="1165" as="geometry" />
</mxCell>
<mxCell id="acc-e-auth0" edge="1" parent="1" source="acc-lookup" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;labelBackgroundColor=#ffffff;endArrow=classic;strokeColor=#b85450;dashed=1;fontColor=#b85450;exitX=0.2;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" target="acc-auth0" value="e-mail → auth0|…">
<mxGeometry relative="1" as="geometry" />
</mxCell>
<mxCell id="acc-e-db" edge="1" parent="1" source="acc-lookup" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;labelBackgroundColor=#ffffff;endArrow=classic;strokeColor=#b85450;dashed=1;fontColor=#b85450;exitX=0.75;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" target="acc-db" value="read-only">
<mxGeometry relative="1" as="geometry" />
</mxCell>
<mxCell id="acc-e-tool" edge="1" parent="1" source="acc-tool" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;labelBackgroundColor=#ffffff;endArrow=classic;strokeColor=#b85450;dashed=1;fontColor=#b85450;strokeWidth=2;exitX=0;exitY=0.75;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" target="acc-api" value="HTTP GET&lt;br&gt;+ identity headers">
<mxGeometry relative="1" as="geometry">
<Array as="points">
<mxPoint x="100" y="478" />
<mxPoint x="100" y="660" />
<mxPoint x="-157" y="660" />
</Array>
</mxGeometry>
</mxCell>
<mxCell id="acc-e-check" edge="1" parent="1" source="acc-check" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;labelBackgroundColor=#ffffff;endArrow=classic;strokeColor=#b85450;dashed=1;fontColor=#b85450;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=1;entryY=0.5;entryDx=0;entryDy=0;" target="acc-api" value="re-check:&lt;br&gt;the LLM cannot&lt;br&gt;widen access">
<mxGeometry relative="1" as="geometry" />
</mxCell>
<mxCell id="fix-7" parent="1" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#ffe6cc;strokeColor=#d79b00;dashed=1;strokeWidth=2;" value="&lt;b&gt;Detectors&lt;/b&gt;&lt;br&gt;visibility · obstruction · target issue&lt;br&gt;thermal · no data · displacement&lt;br&gt;→ classified events" vertex="1"> <mxCell id="fix-7" parent="1" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#ffe6cc;strokeColor=#d79b00;dashed=1;strokeWidth=2;" value="&lt;b&gt;Detectors&lt;/b&gt;&lt;br&gt;visibility · obstruction · target issue&lt;br&gt;thermal · no data · displacement&lt;br&gt;→ classified events" vertex="1">
<mxGeometry height="150" width="360" x="135" y="890" as="geometry" /> <mxGeometry height="80" width="360" x="135" y="975" as="geometry" />
</mxCell> </mxCell>
<mxCell id="fix-8" parent="1" style="shape=cylinder3;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;size=10;fillColor=#d5e8d4;strokeColor=#82b366;" value="&lt;b&gt;Station data&lt;/b&gt; (AIMsight platform)" vertex="1"> <mxCell id="fix-8" parent="1" style="shape=cylinder3;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;size=10;fillColor=#d5e8d4;strokeColor=#82b366;" value="&lt;b&gt;Station data&lt;/b&gt; (AIMsight platform)" vertex="1">
<mxGeometry height="70" width="360" x="135" y="1190" as="geometry" /> <mxGeometry height="70" width="360" x="135" y="1190" as="geometry" />
</mxCell> </mxCell>
<mxCell id="fix-10" edge="1" parent="1" source="arch-13" style="rounded=0;html=1;labelBackgroundColor=#ffffff;endArrow=classic;strokeColor=#d79b00;strokeWidth=2;dashed=1;fontColor=#b36b00;edgeStyle=orthogonalEdgeStyle;" target="fix-6" value="7. HTTP GET (serial, from, to)"> <mxCell id="fix-10" edge="1" parent="1" source="arch-13" style="rounded=0;html=1;labelBackgroundColor=#ffffff;endArrow=classic;strokeColor=#d79b00;strokeWidth=2;dashed=1;fontColor=#b36b00;edgeStyle=orthogonalEdgeStyle;" target="fix-6" value="7. HTTP GET (serial, from, to)&lt;br&gt;+ identity headers">
<mxGeometry relative="1" x="0.1306" as="geometry" /> <mxGeometry relative="1" x="0.1306" as="geometry" />
</mxCell> </mxCell>
<mxCell id="fix-11" edge="1" parent="1" source="fix-6" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;labelBackgroundColor=#ffffff;endArrow=classic;strokeColor=#d79b00;strokeWidth=2;dashed=1;fontColor=#b36b00;exitX=0.500;exitY=1.000;exitDx=0;exitDy=0;entryX=0.500;entryY=0.000;entryDx=0;entryDy=0;" target="fix-7" value=""> <mxCell id="fix-11" edge="1" parent="1" source="fix-6" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;labelBackgroundColor=#ffffff;endArrow=classic;strokeColor=#d79b00;strokeWidth=2;dashed=1;fontColor=#b36b00;exitX=0.500;exitY=1.000;exitDx=0;exitDy=0;entryX=0.500;entryY=0.000;entryDx=0;entryDy=0;" target="acc-check" value="">
<mxGeometry relative="1" as="geometry" /> <mxGeometry relative="1" as="geometry" />
</mxCell> </mxCell>
<mxCell id="fix-12" edge="1" parent="1" source="fix-7" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;labelBackgroundColor=#ffffff;endArrow=classic;strokeColor=#d79b00;strokeWidth=2;dashed=1;fontColor=#b36b00;exitX=0.500;exitY=1.000;exitDx=0;exitDy=0;entryX=0.500;entryY=0.000;entryDx=0;entryDy=0;" target="fix-8" value="reads the range (read-only)"> <mxCell id="fix-12" edge="1" parent="1" source="fix-7" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;labelBackgroundColor=#ffffff;endArrow=classic;strokeColor=#d79b00;strokeWidth=2;dashed=1;fontColor=#b36b00;exitX=0.500;exitY=1.000;exitDx=0;exitDy=0;entryX=0.500;entryY=0.000;entryDx=0;entryDy=0;" target="fix-8" value="reads the range (read-only)">
@@ -140,7 +194,7 @@
</mxCell> </mxCell>
<mxCell id="gen-boundary" edge="1" parent="1" style="endArrow=none;html=1;rounded=0;dashed=1;dashPattern=8 4;strokeColor=#999999;strokeWidth=1;" value=""> <mxCell id="gen-boundary" edge="1" parent="1" style="endArrow=none;html=1;rounded=0;dashed=1;dashPattern=8 4;strokeColor=#999999;strokeWidth=1;" value="">
<mxGeometry relative="1" as="geometry"> <mxGeometry relative="1" as="geometry">
<mxPoint x="60" y="680" as="sourcePoint" /> <mxPoint x="-400" y="680" as="sourcePoint" />
<mxPoint x="1380" y="680" as="targetPoint" /> <mxPoint x="1380" y="680" as="targetPoint" />
</mxGeometry> </mxGeometry>
</mxCell> </mxCell>
@@ -177,8 +231,8 @@
<mxCell id="gen-host-edge" edge="1" parent="1" source="gen-host" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;labelBackgroundColor=#ffffff;endArrow=classic;strokeColor=#999999;dashed=1;fontColor=#666666;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=1;entryY=0.5;entryDx=0;entryDy=0;" target="gen-6" value="HTTP"> <mxCell id="gen-host-edge" edge="1" parent="1" source="gen-host" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;labelBackgroundColor=#ffffff;endArrow=classic;strokeColor=#999999;dashed=1;fontColor=#666666;exitX=0;exitY=0.5;exitDx=0;exitDy=0;entryX=1;entryY=0.5;entryDx=0;entryDy=0;" target="gen-6" value="HTTP">
<mxGeometry relative="1" as="geometry" /> <mxGeometry relative="1" as="geometry" />
</mxCell> </mxCell>
<mxCell id="gen-legend" parent="1" style="shape=note;whiteSpace=wrap;html=1;size=14;align=left;verticalAlign=top;spacingLeft=10;spacingTop=6;spacingRight=8;fillColor=#fff2cc;strokeColor=#d6b656;" value="&lt;b style=&quot;font-size:13px&quot;&gt;Reusable mechanism&lt;/b&gt;&lt;br&gt;&lt;br&gt;&lt;b&gt;1. Host app&lt;/b&gt; (here LibreDesk) triggers an action and sends context + tool list to the LLM.&lt;br&gt;&lt;b&gt;2. Tool&lt;/b&gt; = name + JSON schema + thin HTTP adapter. No business logic in the host.&lt;br&gt;&lt;b&gt;3. Independent service&lt;/b&gt; = container exposing a REST API; owns its domain logic and its data access, returns structured JSON.&lt;br&gt;&lt;b&gt;4.&lt;/b&gt; The LLM turns the tool result into the output (here a draft reviewed by a human).&lt;br&gt;&lt;br&gt;New capability = one service + one tool declaration.&lt;br&gt;Same pattern for another host app (sales agent: CRM, quotes, stock…).&lt;br&gt;&lt;br&gt;&lt;b&gt;Legend&lt;/b&gt;&lt;br&gt;&lt;span style=&quot;color:#6c8ebf&quot;&gt;■&lt;/span&gt; existing LibreDesk&lt;br&gt;&lt;span style=&quot;color:#d79b00&quot;&gt;■&lt;/span&gt; dashed orange: this use case (planned)&lt;br&gt;&lt;span style=&quot;color:#9673a6&quot;&gt;■&lt;/span&gt; dashed purple: any other service, plugged the same way&lt;br&gt;&lt;span style=&quot;color:#999999&quot;&gt;■&lt;/span&gt; dashed grey: other consumers of the services" vertex="1"> <mxCell id="gen-legend" parent="1" style="shape=note;whiteSpace=wrap;html=1;size=14;align=left;verticalAlign=top;spacingLeft=10;spacingTop=6;spacingRight=8;fillColor=#fff2cc;strokeColor=#d6b656;" value="&lt;b style=&quot;font-size:13px&quot;&gt;Reusable mechanism&lt;/b&gt;&lt;br&gt;&lt;br&gt;&lt;b&gt;1. Host app&lt;/b&gt; (here LibreDesk) triggers an action and sends context + tool list to the LLM.&lt;br&gt;&lt;b&gt;2. Tool&lt;/b&gt; = name + JSON schema + thin HTTP adapter. No business logic in the host.&lt;br&gt;&lt;b&gt;3. Independent service&lt;/b&gt; = container exposing a REST API; owns its domain logic and its data access, returns structured JSON.&lt;br&gt;&lt;b&gt;4.&lt;/b&gt; The LLM turns the tool result into the output (here a draft reviewed by a human).&lt;br&gt;&lt;b&gt;5. Access&lt;/b&gt;: on Generate reply the LLM first calls get_customer_access; LibreDesk adds the contact identity (headers), the access service returns the stations the customer may read (Auth0 export + UserGroup, the dashboard's rule). Each data service checks again with the same headers.&lt;br&gt;&lt;br&gt;New capability = one service + one tool declaration.&lt;br&gt;Same pattern for another host app (sales agent: CRM, quotes, stock…).&lt;br&gt;&lt;br&gt;&lt;b&gt;Legend&lt;/b&gt;&lt;br&gt;&lt;span style=&quot;color:#6c8ebf&quot;&gt;■&lt;/span&gt; existing LibreDesk&lt;br&gt;&lt;span style=&quot;color:#d79b00&quot;&gt;■&lt;/span&gt; dashed orange: this use case (planned)&lt;br&gt;&lt;span style=&quot;color:#b85450&quot;&gt;■&lt;/span&gt; red: access rights (planned)&lt;br&gt;&lt;span style=&quot;color:#9673a6&quot;&gt;■&lt;/span&gt; dashed purple: any other service, plugged the same way&lt;br&gt;&lt;span style=&quot;color:#999999&quot;&gt;■&lt;/span&gt; dashed grey: other consumers of the services" vertex="1">
<mxGeometry height="380" width="380" x="1000" y="160" as="geometry" /> <mxGeometry height="450" width="380" x="1000" y="160" as="geometry" />
</mxCell> </mxCell>
</root> </root>
</mxGraphModel> </mxGraphModel>
+15
View File
@@ -85,6 +85,21 @@ But : remplacer LM Studio par Ollama (`bge-m3:567m`) sur le serveur de LibreDesk
### Retour en arrière ### Retour en arrière
Admin → IA → Providers, Embeddings : remettre `http://10.0.2.140:1234/v1`, `text-embedding-bge-m3`, clé `lm-studio` (LM Studio lancé sur le PC de Maxime), tester, enregistrer : LibreDesk recalcule de nouveau. Puis, sur le serveur si besoin : `cd ~/ollama && docker compose down`. Admin → IA → Providers, Embeddings : remettre `http://10.0.2.140:1234/v1`, `text-embedding-bge-m3`, clé `lm-studio` (LM Studio lancé sur le PC de Maxime), tester, enregistrer : LibreDesk recalcule de nouveau. Puis, sur le serveur si besoin : `cd ~/ollama && docker compose down`.
## Le service d'accès (les projets du client)
Au clic sur « Generate reply », le LLM peut appeler l'outil `get_customer_access` : LibreDesk ajoute l'e-mail du contact (`X-Libredesk-Contact-Email`), le service `acces/` renvoie les projets que ce client voit sur le dashboard (`{"projects": [{"project", "serial", "role"}]}`). Code et données : `acces/` (README du dépôt).
- [x] **14 provisoire. Sur le PC de Maxime** (2026-11-18), comme Ollama au point 1 bis.
- Données, hors de git : `acces/database.db` (copie de la base du dashboard du 2026-11-12) et `acces/utilisateurs.json` (export d'Auth0, e-mail → `auth0|…`, `acces/exporter_utilisateurs.py`, lancé par Maxime avec le `.env` du dashboard).
- `acces/.env` (jamais lu par Claude) : `ACCES_JETON`, `ACCES_BIND=10.0.2.140`, `ACCES_PORT=18080`. Construction (sur le poste) : `docker compose -f acces/compose.yml build` ; lancement : `docker compose -f acces/compose.yml up -d --no-build`.
- Pare-feu de WSL ouvert par Maxime : règle `Acces-LibreDesk`, TCP 18080, depuis le seul serveur LibreDesk `10.0.1.184` (retrait : `Remove-NetFirewallHyperVRule -Name "Acces-LibreDesk"`).
- Outil dans Admin → IA → Tools : `get_customer_access`, `GET http://10.0.2.140:18080/customer/access`, en-tête `Authorization: Bearer <ACCES_JETON>`, paramètres `{"type":"object","properties":{}}`, activé pour Generate reply, sans approbation.
- Vérifié : un « Generate reply » en production → `docker logs libredesk-acces` montre `10.0.1.184 … e-mail présent, 1 projet(s)` puis `200`. Le journal ne contient jamais l'adresse.
- Mêmes limites qu'Ollama : PC allumé, adresse Wi-Fi qui peut changer ; HTTP en clair sur le réseau interne. Données figées : rafraîchir la base et l'export à la main. Les admins globaux du dashboard (rôle Auth0) reçoivent une liste vide.
- Si l'outil est en erreur : `docker ps --filter name=libredesk-acces`, puis `docker compose -f acces/compose.yml up -d --no-build` ; en dernier recours, désactiver l'outil (le brouillon se fait alors sans les projets).
- [ ] **15. Les consignes** : dire au LLM quoi faire des projets (`snippets/consignes_redaction.md`).
- [ ] **16. Sur le serveur**, à côté d'Ollama (après le point 7) : `acces/compose.reseau.yml`, URL `http://acces:8080/customer/access`, et une base du dashboard tenue à jour.
## Au quotidien ## Au quotidien
- **Si Ollama est arrêté**, « Generate reply » rend quand même un brouillon, mais **sans la base de connaissances**, et rien ne le signale à l'agent (journaux de LibreDesk : `AI provider unavailable`, `search_articles` en erreur). Si les brouillons deviennent vagues : `docker ps --filter name=ollama-bge-m3` et `python3 ~/ollama/verifier_ollama.py …` sur le serveur. Pour le relancer (un arrêt manuel n'est pas relancé seul), toujours `cd ~/ollama && docker compose up -d --no-build` plutôt que `docker start` : si LibreDesk a recréé son réseau entre-temps, seul Compose y rattache Ollama. - **Si Ollama est arrêté**, « Generate reply » rend quand même un brouillon, mais **sans la base de connaissances**, et rien ne le signale à l'agent (journaux de LibreDesk : `AI provider unavailable`, `search_articles` en erreur). Si les brouillons deviennent vagues : `docker ps --filter name=ollama-bge-m3` et `python3 ~/ollama/verifier_ollama.py …` sur le serveur. Pour le relancer (un arrêt manuel n'est pas relancé seul), toujours `cd ~/ollama && docker compose up -d --no-build` plutôt que `docker start` : si LibreDesk a recréé son réseau entre-temps, seul Compose y rattache Ollama.
+119
View File
@@ -0,0 +1,119 @@
"""Le service d'accès (acces/service.py) et l'index de l'export Auth0, contre une base SQLite et un utilisateurs.json."""
import json
import sqlite3
import sys
import tempfile
import threading
import unittest
import urllib.error
import urllib.request
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "acces"))
from exporter_utilisateurs import index_par_email # noqa: E402
from service import ROUTE, creer_serveur # noqa: E402
JETON = "j" * 40
UTILISATEURS = {"alice@client.ch": ["auth0|a1", "auth0|a2"], "bob@client.ch": ["auth0|b"]}
def creer_base(chemin: Path):
with sqlite3.connect(chemin) as c:
c.executescript("""
CREATE TABLE Device (id INTEGER PRIMARY KEY, serial_number VARCHAR, name VARCHAR UNIQUE);
CREATE TABLE UserGroup (id INTEGER PRIMARY KEY, device_id INTEGER, role VARCHAR);
CREATE TABLE UserGroupEntry (id INTEGER PRIMARY KEY, group_id INTEGER, user_id VARCHAR);
CREATE TABLE UserAccess (id INTEGER PRIMARY KEY, device_id INTEGER, user_id VARCHAR, access_type TEXT);
INSERT INTO Device VALUES (1, 'PONT', 'Voie Lac'), (2, 'PONT', 'Voie Jura'), (3, 'NORDEND', 'Nordend'),
(4, 'ALASKA', 'Alaska');
INSERT INTO UserGroup VALUES (10, 1, 'user'), (11, 2, 'dev_admin'), (12, 4, 'user'), (13, 99, 'user');
INSERT INTO UserGroupEntry (group_id, user_id) VALUES
(10, 'auth0|a1'), (11, 'auth0|a2'), (10, 'auth0|a2'), (13, 'auth0|a1'), (12, 'auth0|b');
-- l'ancienne table, ignorée comme par le dashboard
INSERT INTO UserAccess (device_id, user_id, access_type) VALUES (3, 'auth0|a1', 'read');
""")
c.close() # « with » valide la transaction mais ne ferme pas
class TestServiceAcces(unittest.TestCase):
def setUp(self):
dossier = tempfile.TemporaryDirectory()
self.addCleanup(dossier.cleanup)
self.base = Path(dossier.name) / "database.db"
self.utilisateurs = Path(dossier.name) / "utilisateurs.json"
creer_base(self.base)
self.utilisateurs.write_text(json.dumps(UTILISATEURS))
self.serveur = creer_serveur(("127.0.0.1", 0), JETON, str(self.base), str(self.utilisateurs))
self.serveur.RequestHandlerClass.log_message = lambda *a: None
threading.Thread(target=self.serveur.serve_forever, daemon=True).start()
self.addCleanup(self.serveur.server_close)
self.addCleanup(self.serveur.shutdown)
def demander(self, entetes: dict, route=ROUTE) -> tuple[int, dict]:
url = f"http://127.0.0.1:{self.serveur.server_address[1]}{route}"
try:
with urllib.request.urlopen(urllib.request.Request(url, headers=entetes), timeout=5) as r:
return r.status, json.load(r)
except urllib.error.HTTPError as e:
with e:
return e.code, json.load(e)
def client(self, email=None) -> tuple[int, dict]:
entetes = {"Authorization": f"Bearer {JETON}"}
if email is not None:
entetes["X-Libredesk-Contact-Email"] = email
return self.demander(entetes)
def test_sans_jeton_ou_mauvais_jeton_401(self):
for entetes in ({}, {"Authorization": "Bearer faux"}, {"Authorization": JETON}):
self.assertEqual(self.demander({**entetes, "X-Libredesk-Contact-Email": "alice@client.ch"})[0], 401)
def test_projets_avec_role_sans_useraccess_ni_device_supprime(self):
# a1 et a2 sont tous deux dans le groupe « user » de Voie Lac : une seule ligne ; a2 administre Voie Jura
self.assertEqual(self.client(" Alice@Client.CH "), (200, {"projects": [
{"project": "Voie Jura", "serial": "PONT", "role": "dev_admin"},
{"project": "Voie Lac", "serial": "PONT", "role": "user"}]}))
def test_dev_admin_l_emporte_sur_user_dans_le_meme_projet(self):
self.utilisateurs.write_text(json.dumps({"dan@client.ch": ["auth0|a2"]}))
with sqlite3.connect(self.base) as c:
c.execute("INSERT INTO UserGroup VALUES (14, 1, 'dev_admin')")
c.execute("INSERT INTO UserGroupEntry (group_id, user_id) VALUES (14, 'auth0|a2')")
c.close()
self.assertIn({"project": "Voie Lac", "serial": "PONT", "role": "dev_admin"}, self.client("dan@client.ch")[1]["projects"])
def test_inconnu_ou_sans_e_mail_liste_vide(self):
self.assertEqual(self.client("inconnu@ailleurs.ch"), (200, {"projects": []}))
self.assertEqual(self.client(), (200, {"projects": []}))
def test_nouvel_export_lu_sans_redemarrer(self):
self.utilisateurs.write_text(json.dumps({"carol@client.ch": ["auth0|b"]}))
self.assertEqual(self.client("carol@client.ch")[1],
{"projects": [{"project": "Alaska", "serial": "ALASKA", "role": "user"}]})
def test_fichier_ou_base_illisible_502_jamais_liste_vide(self):
self.utilisateurs.write_text("pas du json")
self.assertEqual(self.client("alice@client.ch"), (502, {"error": "access lookup unavailable"}))
self.utilisateurs.write_text(json.dumps(UTILISATEURS))
self.base.unlink()
self.assertEqual(self.client("alice@client.ch")[0], 502)
def test_autre_route_404(self):
self.assertEqual(self.demander({"Authorization": f"Bearer {JETON}"}, "/")[0], 404)
def test_base_jamais_modifiee(self):
avant = self.base.read_bytes()
self.client("alice@client.ch")
self.assertEqual(self.base.read_bytes(), avant)
class TestIndexParEmail(unittest.TestCase):
def test_minuscules_plusieurs_comptes_sans_e_mail_ignore(self):
self.assertEqual(index_par_email([
{"user_id": "auth0|2", "email": "Alice@Client.ch "}, {"user_id": "auth0|1", "email": "alice@client.ch"},
{"user_id": "auth0|3"}, {"user_id": "auth0|4", "email": None}]),
{"alice@client.ch": ["auth0|1", "auth0|2"]})
if __name__ == "__main__":
unittest.main()