taler-android

Android apps for GNU Taler (wallet, PoS, cashier)
Log | Files | Refs | README | LICENSE

twister.py (6927B)


      1 # This file is part of GNU Taler
      2 # (C) 2026 Taler Systems S.A.
      3 #
      4 # GNU Taler is free software; you can redistribute it and/or modify it under the
      5 # terms of the GNU General Public License as published by the Free Software
      6 # Foundation; either version 3, or (at your option) any later version.
      7 #
      8 # GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
      9 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     10 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
     11 #
     12 # You should have received a copy of the GNU General Public License along with
     13 # GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     14 """Fault injection between the wallet and the exchange.
     15 
     16 `taler-twister` is an HTTP proxy that forwards to the real exchange and can
     17 damage what passes through: truncate a response, force a status code, delete
     18 or rewrite a field of the JSON. The stack has to be started from
     19 `sim-twister.conf` for any of this to have something to talk to, and the
     20 wallet's exchange base URL is then the twister port.
     21 
     22 Each command affects the *next* response (or upload) the proxy handles and is
     23 then forgotten, so arming once and then starting a wallet operation usually
     24 damages some unrelated poll instead of the request under test. `armed` keeps a
     25 fault re-armed for as long as the step runs, which is what a scenario wants.
     26 
     27     t = Twister()
     28     t.response_code(500)      # the next exchange reply becomes a 500
     29     t.malform()               # ... or is truncated at a random point
     30     t.delete("denominations") # ... or loses a field
     31 
     32     with t.armed(lambda x: x.response_code(500)):
     33         ...                   # every exchange reply in here is a 500
     34 
     35 Dot paths address nested fields, and a numeric token is an array index, so
     36 `denominations.0.denoms.0.master_sig` names one denomination signature.
     37 """
     38 
     39 from __future__ import annotations
     40 
     41 import json
     42 import subprocess
     43 import threading
     44 import time
     45 from pathlib import Path
     46 from typing import Callable
     47 
     48 BINARY = "/opt/twister/bin/taler-twister"
     49 DEFAULT_CONFIG = "/opt/taler-sim/run/stack/sim-twister.conf"
     50 ENV_FILE = Path("/opt/taler-sim/run/stack/env.json")
     51 
     52 
     53 class TwisterUnavailable(RuntimeError):
     54     pass
     55 
     56 
     57 class Twister:
     58     def __init__(self, config: str | None = None, timeout: int = 30):
     59         self.config = config or self._config_from_env() or DEFAULT_CONFIG
     60         self.timeout = timeout
     61 
     62     @staticmethod
     63     def _config_from_env() -> str | None:
     64         try:
     65             info = json.loads(ENV_FILE.read_text()).get("twister")
     66         except (OSError, json.JSONDecodeError):
     67             return None
     68         return (info or {}).get("config")
     69 
     70     def _run(self, *args: str) -> str:
     71         if not Path(BINARY).is_file():
     72             raise TwisterUnavailable(f"no twister binary at {BINARY}")
     73         proc = subprocess.run([BINARY, "-c", self.config, *args],
     74                               capture_output=True, text=True, timeout=self.timeout)
     75         if proc.returncode != 0:
     76             raise TwisterUnavailable(
     77                 f"taler-twister {' '.join(args)} failed: "
     78                 f"{(proc.stderr or proc.stdout).strip()[:300]}"
     79             )
     80         return proc.stdout
     81 
     82     # -- state ------------------------------------------------------------
     83 
     84     def alive(self) -> bool:
     85         try:
     86             self._run("--checkalive")
     87             return True
     88         except TwisterUnavailable:
     89             return False
     90 
     91     # -- faults -----------------------------------------------------------
     92 
     93     def malform(self) -> None:
     94         """Truncate the next response at a random point."""
     95         self._run("--malform")
     96 
     97     def malform_upload(self) -> None:
     98         """Truncate the next request the wallet sends."""
     99         self._run("--malformupload")
    100 
    101     def response_code(self, status: int) -> None:
    102         """Answer the next request with this status code."""
    103         self._run(f"--responsecode={status}")
    104 
    105     def delete(self, path: str) -> None:
    106         """Remove a field from the next response body."""
    107         self._run(f"--deleteobject={path}")
    108 
    109     def modify(self, path: str, value: str) -> None:
    110         """Replace a field in the next response body (always as a string)."""
    111         self._run(f"--modify-dl={path}", f"--value={value}")
    112 
    113     def flip(self, path: str) -> None:
    114         """Flip one character of a string field in the next response."""
    115         self._run(f"--flip-dl={path}")
    116 
    117     def flip_upload(self, path: str) -> None:
    118         self._run(f"--flip-ul={path}")
    119 
    120     def header(self, name: str, value: str) -> None:
    121         """Rewrite a header of the next response."""
    122         self._run(f"--modify-header-dl={name}", f"--value={value}")
    123 
    124 
    125     # -- keeping a fault armed --------------------------------------------
    126 
    127     def armed(self, arm: "Callable[[Twister], None]", period: float = 0.4):
    128         """Context manager that re-arms `arm` until the block exits.
    129 
    130         A fault is one-shot, and the wallet talks to the exchange constantly
    131         (/config, /keys, /reserves/...), so a single arming lands on an
    132         arbitrary request.  Re-arming in the background makes the fault apply
    133         to the whole step; the number of times it actually fired is reported
    134         as `fired` on the handle.
    135         """
    136         twister = self
    137 
    138         class _Armed:
    139             fired = 0
    140             errors: list[str] = []
    141 
    142             def __init__(self) -> None:
    143                 self._stop = threading.Event()
    144                 self._thread = threading.Thread(target=self._loop, daemon=True)
    145 
    146             def _loop(self) -> None:
    147                 while not self._stop.is_set():
    148                     try:
    149                         arm(twister)
    150                         self.fired += 1
    151                     except Exception as e:  # noqa: BLE001 - reported, not raised
    152                         if len(self.errors) < 3:
    153                             self.errors.append(str(e)[:120])
    154                     self._stop.wait(period)
    155 
    156             def __enter__(self) -> "_Armed":
    157                 self._thread.start()
    158                 return self
    159 
    160             def __exit__(self, *exc: object) -> None:
    161                 self._stop.set()
    162                 self._thread.join(timeout=5)
    163 
    164         return _Armed()
    165 
    166 
    167 # The faults a scenario can arm, with names that read in a report.
    168 FAULTS = {
    169     "truncated-response": lambda t: t.malform(),
    170     "truncated-request": lambda t: t.malform_upload(),
    171     "http-500": lambda t: t.response_code(500),
    172     "http-404": lambda t: t.response_code(404),
    173     "http-403": lambda t: t.response_code(403),
    174     "http-502": lambda t: t.response_code(502),
    175     "wrong-content-type": lambda t: t.header("Content-Type", "text/plain"),
    176 }
    177 
    178 
    179 if __name__ == "__main__":
    180     import sys
    181     t = Twister()
    182     print(f"config: {t.config}")
    183     print(f"alive: {t.alive()}")
    184     if len(sys.argv) > 1:
    185         FAULTS[sys.argv[1]](t)
    186         print(f"armed {sys.argv[1]}")