From 9a1622232b7de482f74394862a3b834f246d131d Mon Sep 17 00:00:00 2001 From: docker24001 Date: Wed, 4 Nov 2026 22:25:47 +0000 Subject: [PATCH] fix(#5): masquer les identifiants d'URL dans les journaux --- CHANGELOG.md | 11 ++ src/pystashtemplate/outputs/doris.py | 6 +- src/pystashtemplate/outputs/gelf.py | 4 +- src/pystashtemplate/tracing.py | 25 ++++- tests/test_fuites_identifiants.py | 152 +++++++++++++++++++++++++++ 5 files changed, 192 insertions(+), 6 deletions(-) create mode 100644 tests/test_fuites_identifiants.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 226a2ca..bc7879f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,17 @@ le projet suit SemVer. ## [Non publié] +### Sécurité + +- Identifiants écrits dans l'URL masqués dans les journaux (#5, audit du + 04/11) : avec `hosts => "http://user:secret@hote"`, le mot de passe + sortait en clair dans le DEBUG de sortie en exception des décorateurs + de traçage (les messages httpx citent l'URL) et dans le DEBUG de + signature de la sortie `doris`. Nouvelle fonction + `tracing.masquer_identifiants` (`http://***@hote`), appliquée par + `@traced`/`@atraced`, `doris` et `gelf` ; test de non-fuite sur toutes + les sorties HTTP du registre (`tests/test_fuites_identifiants.py`). + ### Documentation - README largement repris (#117, suite de #115) : architecture, démarrage diff --git a/src/pystashtemplate/outputs/doris.py b/src/pystashtemplate/outputs/doris.py index 6449a7b..34fb390 100644 --- a/src/pystashtemplate/outputs/doris.py +++ b/src/pystashtemplate/outputs/doris.py @@ -71,7 +71,7 @@ from pystashtemplate.outputs import Capacites, enregistrer from pystashtemplate.outputs.elasticsearch_bulk import ElasticsearchBulkOutput, SendOutcome from pystashtemplate.outputs.schema import OptionSpec -from pystashtemplate.tracing import atraced, traced +from pystashtemplate.tracing import atraced, masquer_identifiants, traced # Doris : lettres, chiffres, `-` et `_`, 128 caractères au plus ; le # préfixe en laisse 33 au suffixe (`_` + 32 chiffres hexadécimaux). @@ -110,7 +110,9 @@ def __init__(self, user: str | None, password: str | None) -> None: def _signer(self, request: httpx.Request) -> httpx.Request: """Ajoute l'en-tête `Authorization` quand des identifiants sont configurés.""" - logger.debug("AuthStreamLoad._signer | {} {}", request.method, request.url.copy_with(query=None)) + logger.debug( + "AuthStreamLoad._signer | {} {}", request.method, masquer_identifiants(request.url.copy_with(query=None)) + ) if self._en_tete is not None: request.headers["Authorization"] = self._en_tete logger.debug("AuthStreamLoad._signer | sortie (authentifiée={})", self._en_tete is not None) diff --git a/src/pystashtemplate/outputs/gelf.py b/src/pystashtemplate/outputs/gelf.py index 76c079e..e72d8b1 100644 --- a/src/pystashtemplate/outputs/gelf.py +++ b/src/pystashtemplate/outputs/gelf.py @@ -84,7 +84,7 @@ from pystashtemplate.outputs.elasticsearch_bulk import ElasticsearchBulkOutput, SendOutcome from pystashtemplate.outputs.schema import OptionSpec from pystashtemplate.templates import compile_template, render -from pystashtemplate.tracing import atraced, traced +from pystashtemplate.tracing import atraced, masquer_identifiants, traced __all__ = ["GelfOutput", "decouper_udp", "message_gelf"] @@ -384,7 +384,7 @@ def __init__( self._compression = bool(options.get("compression", False)) url = urlsplit(self._hosts if "://" in self._hosts else f"{self._mode}://{self._hosts}") if not url.hostname: - logger.warning(_("sortie gelf : hôte absent de hosts {}"), self._hosts) + logger.warning(_("sortie gelf : hôte absent de hosts {}"), masquer_identifiants(self._hosts)) raise ValueError(_("sortie gelf : hosts doit nommer un hôte (ex. http://graylog:12201)")) self._hote = url.hostname self._port = url.port or _PORT_DEFAUT diff --git a/src/pystashtemplate/tracing.py b/src/pystashtemplate/tracing.py index 98254dc..333bde3 100644 --- a/src/pystashtemplate/tracing.py +++ b/src/pystashtemplate/tracing.py @@ -29,6 +29,7 @@ from __future__ import annotations import functools +import re from typing import Any, Callable, Coroutine, TypeVar from loguru import logger @@ -37,6 +38,22 @@ A = TypeVar("A", bound=Callable[..., Coroutine[Any, Any, Any]]) +# Identifiants d'une URL (`schéma://utilisateur:secret@hôte`) : partie +# avant `@` de l'autorité, jusqu'au premier `/`, espace ou guillemet. +_IDENTIFIANTS_URL = re.compile(r"(?i)\b([a-z][a-z0-9+.\-]*://)[^\s/@'\"<>]+@") + + +def masquer_identifiants(texte: object) -> str: + """Texte de `texte` où les identifiants d'URL sont remplacés par `***`. + + `http://user:secret@hote:9200/x` devient `http://***@hote:9200/x` : + un message d'exception (httpx cite l'URL de la requête) ou une URL + journalisée ne laisse ainsi jamais passer un mot de passe écrit dans + `hosts` (#5). + """ + return _IDENTIFIANTS_URL.sub(r"\1***@", str(texte)) + + def traced(func: F) -> F: """Journalise l'entrée et la sortie (normale ou par exception) de `func`. @@ -69,7 +86,9 @@ def wrapper(*args, **kwargs): try: result = func(*args, **kwargs) except BaseException as exc: - logger.debug("{} | sortie (exception {}) : {}", func.__qualname__, type(exc).__name__, exc) + logger.debug( + "{} | sortie (exception {}) : {}", func.__qualname__, type(exc).__name__, masquer_identifiants(exc) + ) raise logger.debug("{} | sortie", func.__qualname__) return result @@ -105,7 +124,9 @@ async def wrapper(*args, **kwargs): try: result = await func(*args, **kwargs) except BaseException as exc: - logger.debug("{} | sortie (exception {}) : {}", func.__qualname__, type(exc).__name__, exc) + logger.debug( + "{} | sortie (exception {}) : {}", func.__qualname__, type(exc).__name__, masquer_identifiants(exc) + ) raise logger.debug("{} | sortie", func.__qualname__) return result diff --git a/tests/test_fuites_identifiants.py b/tests/test_fuites_identifiants.py new file mode 100644 index 0000000..8323367 --- /dev/null +++ b/tests/test_fuites_identifiants.py @@ -0,0 +1,152 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Aucun secret dans les journaux, même écrit dans l'URL (critère de #5). + +Audit du 04/11 : `hosts => "http://user:secret@hote"` faisait sortir le +mot de passe en clair dans le DEBUG de sortie en exception des +décorateurs de traçage (httpx cite l'URL dans ses messages) et dans le +DEBUG de signature de la sortie `doris`. Ces tests passent toutes les +sorties HTTP du registre, avec un secret dans l'URL et dans chaque +option d'authentification qu'elles acceptent, sur un faux serveur qui +répond 401, 400, 429 puis 500 ; aucun message, à aucun niveau, ne doit +contenir le secret. +""" + +from __future__ import annotations + +import asyncio +import re +from typing import Any + +import httpx +import pytest +from loguru import logger + +from pystashtemplate.outputs import REGISTRY +from pystashtemplate.outputs.elasticsearch_bulk import ElasticsearchBulkOutput +from pystashtemplate.tracing import atraced, masquer_identifiants, traced + +SECRET = "S3cr3tXYZ" +SORTIES_HTTP = sorted(nom for nom, cls in REGISTRY.items() if issubclass(cls, ElasticsearchBulkOutput)) + + +class TestMasquerIdentifiants: + @pytest.mark.parametrize( + ("texte", "attendu"), + [ + ("http://user:secret@hote:9200/x", "http://***@hote:9200/x"), + ("https://secret@hote", "https://***@hote"), + ("redis://:secret@redis:6379/0", "redis://***@redis:6379/0"), + ("amqp://u:p%40ss@mq/vhost", "amqp://***@mq/vhost"), + ("for url 'http://u:s@h/ready'", "for url 'http://***@h/ready'"), + ("a http://u:s@h1 b HTTP://v:t@h2", "a http://***@h1 b HTTP://***@h2"), + ("http://hote:9200/x", "http://hote:9200/x"), + ("courriel user@exemple.fr", "courriel user@exemple.fr"), + ("http://hote/chemin@version", "http://hote/chemin@version"), + ], + ) + def test_masquage(self, texte: str, attendu: str) -> None: + assert masquer_identifiants(texte) == attendu + + def test_accepte_tout_objet(self) -> None: + assert masquer_identifiants(httpx.URL("http://u:s@h/")) == "http://***@h/" + assert masquer_identifiants(["http://u:s@h"]) == "['http://***@h']" + + +def _journaux(action) -> list[str]: + messages: list[str] = [] + sink = logger.add(lambda m: messages.append(str(m)), level="TRACE") + try: + action() + finally: + logger.remove(sink) + return messages + + +class TestDecorateurs: + def test_traced_masque_le_message_d_exception(self) -> None: + @traced + def echoue() -> None: + raise ValueError(f"for url 'http://u:{SECRET}@h/'") + + def action() -> None: + with pytest.raises(ValueError): + echoue() + + messages = _journaux(action) + assert any("http://***@h/" in m for m in messages) + assert not any(SECRET in m for m in messages) + + def test_atraced_masque_le_message_d_exception(self) -> None: + @atraced + async def echoue() -> None: + raise ValueError(f"for url 'http://u:{SECRET}@h/'") + + def action() -> None: + with pytest.raises(ValueError): + asyncio.run(echoue()) + + messages = _journaux(action) + assert any("http://***@h/" in m for m in messages) + assert not any(SECRET in m for m in messages) + + +def _options(nom: str, cls: type) -> dict[str, Any]: + """Options avec le secret dans l'URL et dans les options d'authentification acceptées.""" + if nom == "http": + return {"url": f"http://u:{SECRET}@srv:1/x", "headers": {"Authorization": f"Bearer {SECRET}"}} + options: dict[str, Any] = {"hosts": f"http://u:{SECRET}@srv:1", "retry_max": 0, "retry_backoff": 0} + propres = set() + for classe in cls.__mro__: + propres |= set(getattr(classe, "OPTIONS_PROPRES", None) or {}) + if "api_key" in propres: + options["api_key"] = SECRET + elif "token" in propres: + options["token"] = SECRET + else: + options.update(user="u", password=SECRET) + return options + + +def _construire(nom: str, transport: httpx.MockTransport) -> ElasticsearchBulkOutput: + cls = REGISTRY[nom] + options = _options(nom, cls) + if nom == "parseable": + options["stream"] = "s" + for _ in range(5): + try: + return cls(options, transport=transport) + except ValueError as exc: + requise = re.search(r"option « (\w+) » est requise", str(exc)) + if requise is None: + raise + options[requise.group(1)] = "t" + raise AssertionError(nom) # pragma: no cover + + +@pytest.mark.parametrize("statut", [401, 400, 429, 500]) +@pytest.mark.parametrize("nom", SORTIES_HTTP) +def test_aucune_fuite_de_secret(nom: str, statut: int) -> None: + sortie = _construire(nom, httpx.MockTransport(lambda requete: httpx.Response(statut, text="erreur"))) + + async def scenario() -> None: + try: + try: + await sortie.envoyer({"message": "m"}) + await sortie.flush() + except Exception: # noqa: BLE001 - seul le contenu des journaux compte ici + pass + try: + await sortie.health() + except Exception: # noqa: BLE001 + pass + finally: + await sortie.close() + + messages = _journaux(lambda: asyncio.run(scenario())) + assert messages, "aucun journal : le test ne prouverait rien" + fuites = [m for m in messages if SECRET in m] + assert fuites == [] + + +def test_inventaire_des_sorties_http() -> None: + assert len(SORTIES_HTTP) >= 15