From e4123fba1c5b7bdde38a91221b7d5d5d6c668840 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Vihoal=C3=A9=20ANIGLO?= <46029829+JIV-DLS@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:08:31 +0100 Subject: [PATCH] =?UTF-8?q?fix(s=C3=A9curit=C3=A9)=20:=20identifiants=20va?= =?UTF-8?q?lid=C3=A9s=20avant=20tout=20appel=20(0.7.1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Un identifiant mis dans un chemin d'URL doit correspondre à ^[A-Za-z0-9_-]{1,128}$ ; sinon invalid_request (statut 0, non rejouable), sans appel et sans citer la valeur. Avant, get_payment("../balance") partait en /v1/payments/..%2Fbalance avec la clé du marchand. Routes toutes faites : identifiant de paiement hors motif → 404 payment_not_found, orderId hors motif → 404 order_not_found, sans appel. --- AGENTS.md | 2 +- CHANGELOG.md | 4 +++ README.md | 2 +- src/technas_pay/_version.py | 2 +- src/technas_pay/app_routes.py | 8 +++++ src/technas_pay/client.py | 32 +++++++++++------- tests/test_app_contract.py | 30 +++++++++++++++++ tests/test_client.py | 61 +++++++++++++++++++++++++++++------ 8 files changed, 116 insertions(+), 25 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0bf60f3..c8283ea 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,7 @@ Même API, mêmes règles que le SDK TypeScript `@technas/pay-next` : seuls les ## Installer ```bash -pip install "technas-pay @ git+https://github.com/Technas-Organization/technas-pay-python@v0.7.0" +pip install "technas-pay @ git+https://github.com/Technas-Organization/technas-pay-python@v0.7.1" ``` diff --git a/CHANGELOG.md b/CHANGELOG.md index 34133aa..647e41a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 0.7.1 — 2026-11-16 + +Sécurité : identifiants validés avant tout appel. Un identifiant mis dans un chemin d'URL (`get_payment`, `cancel_payment`, `refund`, `record_external_refund`, `get_refund`, `simulate_test_payment`, clients sync et async) doit correspondre à `^[A-Za-z0-9_-]{1,128}$` ; sinon erreur `invalid_request` (statut 0, non rejouable), sans aucun appel et sans citer la valeur reçue. Avant, `get_payment("../balance")` partait encodé (`..%2Fbalance`) avec votre clé : un intermédiaire qui décode puis normalise le chemin pouvait viser une autre route. Routes toutes faites : un identifiant de paiement hors de ce motif rend 404 `payment_not_found`, un `orderId` hors de ce motif 404 `order_not_found`, sans appel. + ## 0.7.0 — 2026-11-16 Annuler un paiement : `cancel_payment(id)` (`POST /v1/payments/{id}/cancel`, client sync et async) annule DÉFINITIVEMENT un paiement que personne n'a commencé à payer ; rend le paiement (`status` `expired`, `checkout_url` `None`). Idempotent. `Payment` : `canceled_at`, `cancel_reason` ; `Payment` et `EventPayment` : `reason` (avis `payment.expired` : `canceled` ou `timeout`, `None` dans un avis plus ancien). Nouvelle erreur `payment_already_completed` (409, non rejouable). Routes toutes faites : `POST /payments/{id}/cancel` (même contrôle de propriété que `GET /payments/{id}`), et sur `reference_conflict` l'ancien essai est relu par sa référence puis annulé avant l'essai suivant ; payé ou demande en cours chez l'opérateur : aucun second paiement, l'erreur est rendue à l'app. Si l'annulation répond 404 (serveur qui ne l'a pas encore), le démarrage passe à l'essai suivant comme avant. Contrat v1 : 31 cas (`query_includes` vérifié). diff --git a/README.md b/README.md index 7e8701a..983421e 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ C'est la même API que le SDK TypeScript [`@technas/pay-next`](https://github.co ## 1. Installer ```bash -pip install "technas-pay @ git+https://github.com/Technas-Organization/technas-pay-python@v0.7.0" +pip install "technas-pay @ git+https://github.com/Technas-Organization/technas-pay-python@v0.7.1" ``` Seule dépendance : `httpx`. Python 3.9 ou plus récent. diff --git a/src/technas_pay/_version.py b/src/technas_pay/_version.py index 49e0fc1..a5f830a 100644 --- a/src/technas_pay/_version.py +++ b/src/technas_pay/_version.py @@ -1 +1 @@ -__version__ = "0.7.0" +__version__ = "0.7.1" diff --git a/src/technas_pay/app_routes.py b/src/technas_pay/app_routes.py index 2facddc..eeddd05 100644 --- a/src/technas_pay/app_routes.py +++ b/src/technas_pay/app_routes.py @@ -109,6 +109,8 @@ def _as_order(raw: Any) -> AppOrder: _PAYMENT_PATH = re.compile(r"^/payments/([^/]+)$") _CANCEL_PATH = re.compile(r"^/payments/([^/]+)/cancel$") +# Un identifiant de commande ou de paiement : hors de ce motif, « introuvable » sans aucun appel. +_ID = re.compile(r"[A-Za-z0-9_-]{1,128}") class AppRoutes: @@ -231,6 +233,8 @@ async def handle(self, req: AppRequest) -> AppResponse: order_id = req.query.get("orderId") if not order_id: return _err(400, "invalid_request", "orderId manquant") + if not _ID.fullmatch(order_id): + return _err(404, "order_not_found", "Commande introuvable") raw = await _maybe(self._resolve(order_id, user)) if raw is None: return _err(404, "order_not_found", "Commande introuvable") @@ -251,6 +255,8 @@ async def handle(self, req: AppRequest) -> AppResponse: if not isinstance(order_id, (str, int)) or isinstance(order_id, bool) or str(order_id) == "": return _err(400, "invalid_request", "orderId manquant") order_id = str(order_id) + if not _ID.fullmatch(order_id): + return _err(404, "order_not_found", "Commande introuvable") pay_method = body.get("method") or "mobile_money" if pay_method not in ("mobile_money", "card"): return _err(400, "invalid_request", 'method vaut "mobile_money" ou "card"') @@ -268,6 +274,8 @@ async def handle(self, req: AppRequest) -> AppResponse: # GET /payments/{id} et POST /payments/{id}/cancel : seulement si la commande de ce # paiement est à cet utilisateur. payment_id = unquote((cancel or _PAYMENT_PATH.match(path)).group(1)) # type: ignore[union-attr] + if not _ID.fullmatch(payment_id): + return _err(404, "payment_not_found", "Paiement introuvable") try: payment = await _maybe(self._pay.get_payment(payment_id)) except TechnasPayError as e: diff --git a/src/technas_pay/client.py b/src/technas_pay/client.py index 131b83c..5d50b39 100644 --- a/src/technas_pay/client.py +++ b/src/technas_pay/client.py @@ -17,7 +17,7 @@ import uuid from dataclasses import dataclass from typing import Any, Callable, Dict, Generic, List, Optional, Sequence, TypeVar, Union -from urllib.parse import quote, urlencode +from urllib.parse import urlencode import httpx @@ -77,11 +77,19 @@ def _parse_secret(secret: Optional[str]) -> _Secret: return _Secret(mode=match.group(1), api_key=match.group(2), webhook_secret=match.group(3)) -def _payment_segment(payment_id: Any) -> str: - """L'identifiant d'un paiement, encodé pour le chemin ; vide ou absent : refusé avant tout appel.""" - if not isinstance(payment_id, str) or payment_id == "": - raise TechnasPayError("invalid_request", "Identifiant de paiement invalide") - return quote(payment_id, safe="") +_SEGMENT_RE = re.compile(r"[A-Za-z0-9_-]{1,128}") + + +def _segment(identifier: Any) -> str: + """Un identifiant mis dans un chemin d'URL, refusé avant tout appel s'il sort de ``[A-Za-z0-9_-]{1,128}``. + + Jamais « . », « .. », « / » ni rien d'encodé : un proxy qui décode ``%2F`` puis normalise le + chemin enverrait ``../balance`` vers une autre route, avec votre clé. Le message ne cite pas la + valeur reçue. + """ + if not isinstance(identifier, str) or not _SEGMENT_RE.fullmatch(identifier): + raise TechnasPayError("invalid_request", "Identifiant invalide") + return identifier def _positive_amount(value: Any) -> None: @@ -221,11 +229,11 @@ def _ask_for_payment( @staticmethod def _get_payment(payment_id: str) -> _Call[Payment]: - return _Call("GET", f"/v1/payments/{_payment_segment(payment_id)}", None, Payment.from_api) + return _Call("GET", f"/v1/payments/{_segment(payment_id)}", None, Payment.from_api) @staticmethod def _cancel_payment(payment_id: str) -> _Call[Payment]: - return _Call("POST", f"/v1/payments/{_payment_segment(payment_id)}/cancel", {}, Payment.from_api) + return _Call("POST", f"/v1/payments/{_segment(payment_id)}/cancel", {}, Payment.from_api) @staticmethod def _get_payment_by_reference(reference: str) -> _Call[Payment]: @@ -263,7 +271,7 @@ def _refund(payment_id: str, amount: Optional[Union[int, float]], fees: str, ref body["amount"] = amount if reference: body["reference"] = reference - return _Call("POST", f"/v1/payments/{quote(payment_id, safe='')}/refunds", body, Refund.from_api) + return _Call("POST", f"/v1/payments/{_segment(payment_id)}/refunds", body, Refund.from_api) @staticmethod def _record_external_refund( @@ -279,11 +287,11 @@ def _record_external_refund( body["recorded_by"] = recorded_by if reference: body["reference"] = reference - return _Call("POST", f"/v1/payments/{quote(payment_id, safe='')}/external-refunds", body, Refund.from_api) + return _Call("POST", f"/v1/payments/{_segment(payment_id)}/external-refunds", body, Refund.from_api) @staticmethod def _get_refund(refund_id: str) -> _Call[Refund]: - return _Call("GET", f"/v1/refunds/{quote(refund_id, safe='')}", None, Refund.from_api) + return _Call("GET", f"/v1/refunds/{_segment(refund_id)}", None, Refund.from_api) @staticmethod def _top_up_balance(amount: int, currency: str, return_url: Optional[str]) -> _Call[TopUp]: @@ -374,7 +382,7 @@ def _simulate_path(self, payment_id: str, outcome: str) -> str: raise TechnasPayError("test_only", "simulate_test_payment exige un secret tps_test_") if outcome not in ("completed", "failed", "expired"): raise TechnasPayError("invalid_outcome", "outcome : completed, failed ou expired") - return f"{self._base_url}/test-checkout/{quote(payment_id, safe='')}/{outcome}" + return f"{self._base_url}/test-checkout/{_segment(payment_id)}/{outcome}" def app_routes(self, **options: Any) -> Any: """Routes toutes faites pour votre app Flutter (``technas_pay_flutter``) : voir ``AppRoutes``. diff --git a/tests/test_app_contract.py b/tests/test_app_contract.py index 385ebc2..0d1b9d0 100644 --- a/tests/test_app_contract.py +++ b/tests/test_app_contract.py @@ -195,3 +195,33 @@ def test_django_view(): urlpatterns = [] assert sys # garde l'import (django lit ROOT_URLCONF sur ce module) + + +@pytest.mark.parametrize("path, query, body, code", [ + ("/payments/..%2Fbalance", None, None, "payment_not_found"), + ("/payments/..%2Fbalance/cancel", None, None, "payment_not_found"), + ("/payments/pay%201", None, None, "payment_not_found"), + ("/payments/a%252Fb", None, None, "payment_not_found"), + ("/payments/" + "x" * 129, None, None, "payment_not_found"), + ("/methods", {"orderId": "../42"}, None, "order_not_found"), + ("/methods", {"orderId": "42 1"}, None, "order_not_found"), + ("/payments", None, {"orderId": "../balance"}, "order_not_found"), + ("/payments", None, {"orderId": "a/b"}, "order_not_found"), +]) +async def test_identifiant_mal_forme_introuvable_sans_appel(path, query, body, code): + resolved = [] + gw = Gateway([]) + + def resolve(order_id, user): + resolved.append(order_id) + return {"amount": 5000} + + method = "GET" if path.startswith("/methods") or (path.startswith("/payments/") and not path.endswith("/cancel")) else "POST" + request = AppRequest(method=method, path=path, query=query or {}, + raw_body=json.dumps(body).encode() if body is not None else b"") + for pay in (AsyncTechnasPay(SECRET, base_url=BASE, http_client=httpx.AsyncClient(transport=httpx.MockTransport(gw.handler))), + TechnasPay(SECRET, base_url=BASE, http_client=httpx.Client(transport=httpx.MockTransport(gw.handler)))): + routes = pay.app_routes(authorize=lambda req: "u1", resolve_order=resolve, return_url="https://app.test/retour") + response = await routes.handle(request) + assert response.status == 404 and response.body["code"] == code + assert gw.calls == [] and resolved == [] diff --git a/tests/test_client.py b/tests/test_client.py index e61331b..970e144 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -170,10 +170,57 @@ def test_le_reste_de_la_surface(pay, gw): assert rules.allowed is None and rules.excluded == ["NG"] -def test_identifiants_echappes_dans_le_chemin(pay, gw): - with pytest.raises(TechnasPayError): - pay.get_payment("../balance") - assert gw.requests[-1].url.raw_path == b"/v1/payments/..%2Fbalance" +IDENTIFIANTS_INVALIDES = ["../balance", "..", ".", "a/b", "a%2Fb", "", "pay 1", "pay_1\n", "é", "x" * 129, None, 42] + +# Toutes les méthodes qui mettent un identifiant dans un chemin d'URL. +APPELS_AVEC_IDENTIFIANT = { + "get_payment": lambda c, i: c.get_payment(i), + "cancel_payment": lambda c, i: c.cancel_payment(i), + "refund": lambda c, i: c.refund(i, amount=100), + "record_external_refund": lambda c, i: c.record_external_refund(i, amount=100, method="Espèces"), + "get_refund": lambda c, i: c.get_refund(i), + "simulate_test_payment": lambda c, i: c.simulate_test_payment(i, "completed"), +} + + +@pytest.mark.parametrize("appel", APPELS_AVEC_IDENTIFIANT, ids=list(APPELS_AVEC_IDENTIFIANT)) +@pytest.mark.parametrize("identifiant", IDENTIFIANTS_INVALIDES, ids=repr) +def test_identifiant_mal_forme_refuse_avant_tout_appel(pay, gw, appel, identifiant): + with pytest.raises(TechnasPayError) as e: + APPELS_AVEC_IDENTIFIANT[appel](pay, identifiant) + assert e.value.code == "invalid_request" and e.value.status == 0 and not e.value.retryable + if isinstance(identifiant, str) and identifiant: + assert identifiant not in e.value.message + assert gw.requests == [] + + +@pytest.mark.parametrize("appel", APPELS_AVEC_IDENTIFIANT, ids=list(APPELS_AVEC_IDENTIFIANT)) +async def test_identifiant_mal_forme_refuse_par_le_client_async(appel): + calls = [] + transport = httpx.MockTransport(lambda r: calls.append(r) or httpx.Response(500)) + async with AsyncTechnasPay(SECRET, base_url=BASE, http_client=httpx.AsyncClient(transport=transport)) as client: + for identifiant in IDENTIFIANTS_INVALIDES: + with pytest.raises(TechnasPayError) as e: + await APPELS_AVEC_IDENTIFIANT[appel](client, identifiant) + assert e.value.code == "invalid_request" and e.value.status == 0 + assert calls == [] + + +@pytest.mark.parametrize("identifiant", ["pay_1", "3f2b8c1e-9a4d-4e2b-8f61-0c7d5e9a1b23", "x" * 128]) +def test_identifiant_valide_part_tel_quel(identifiant): + seen = [] + + def handler(request): + seen.append(request.url.raw_path) + return httpx.Response(404, json={"code": "payment_not_found", "message": "introuvable"}) + + with TechnasPay(SECRET, base_url=BASE, http_client=httpx.Client(transport=httpx.MockTransport(handler))) as client: + for appel in (client.get_payment, client.cancel_payment, client.get_refund): + with pytest.raises(TechnasPayError) as e: + appel(identifiant) + assert e.value.code == "payment_not_found" + assert seen == [f"/v1/payments/{identifiant}".encode(), f"/v1/payments/{identifiant}/cancel".encode(), + f"/v1/refunds/{identifiant}".encode()] def test_erreurs_reseau_et_serveur_rejouables(gw): @@ -398,12 +445,6 @@ def test_annuler_l_ancien_essai_quand_le_client_change_d_offre(): assert len(calls) == 4 -def test_annuler_echappe_l_identifiant(pay, gw): - with pytest.raises(TechnasPayError): - pay.cancel_payment("../balance") - assert gw.requests[-1].url.raw_path == b"/v1/payments/..%2Fbalance/cancel" - - async def test_annuler_avec_le_client_async(): calls, handler = _sequence((200, ANNULE)) async with AsyncTechnasPay(SECRET, base_url=BASE, http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler))) as pay: