twister.py (7714B)
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 os 43 import shutil 44 import subprocess 45 import threading 46 import time 47 from pathlib import Path 48 from typing import Callable 49 50 51 def _binary() -> str: 52 """The twister *client* -- the thing that arms and disarms the proxy. 53 54 Three places, in order: SIM_TWISTER_CLI, the dedicated host's own build 55 under /opt/twister, and PATH. The last is what a CI container has, where 56 twister comes from the `taler-twister` Debian package as /usr/bin; before 57 this looked anywhere but /opt every fault-injection scenario there failed 58 with "no twister binary", which reads like a broken stack rather than a 59 harness that was looking in one hard-coded place. 60 """ 61 chosen = os.environ.get("SIM_TWISTER_CLI") 62 if chosen: 63 return chosen 64 builtin = "/opt/twister/bin/taler-twister" 65 if Path(builtin).is_file(): 66 return builtin 67 return shutil.which("taler-twister") or builtin 68 69 70 BINARY = _binary() 71 DEFAULT_CONFIG = "/opt/taler-sim/run/stack/sim-twister.conf" 72 ENV_FILE = Path("/opt/taler-sim/run/stack/env.json") 73 74 75 class TwisterUnavailable(RuntimeError): 76 pass 77 78 79 class Twister: 80 def __init__(self, config: str | None = None, timeout: int = 30): 81 self.config = config or self._config_from_env() or DEFAULT_CONFIG 82 self.timeout = timeout 83 84 @staticmethod 85 def _config_from_env() -> str | None: 86 try: 87 info = json.loads(ENV_FILE.read_text()).get("twister") 88 except (OSError, json.JSONDecodeError): 89 return None 90 return (info or {}).get("config") 91 92 def _run(self, *args: str) -> str: 93 if not Path(BINARY).is_file(): 94 raise TwisterUnavailable(f"no twister binary at {BINARY}") 95 proc = subprocess.run([BINARY, "-c", self.config, *args], 96 capture_output=True, text=True, timeout=self.timeout) 97 if proc.returncode != 0: 98 raise TwisterUnavailable( 99 f"taler-twister {' '.join(args)} failed: " 100 f"{(proc.stderr or proc.stdout).strip()[:300]}" 101 ) 102 return proc.stdout 103 104 # -- state ------------------------------------------------------------ 105 106 def alive(self) -> bool: 107 try: 108 self._run("--checkalive") 109 return True 110 except TwisterUnavailable: 111 return False 112 113 # -- faults ----------------------------------------------------------- 114 115 def malform(self) -> None: 116 """Truncate the next response at a random point.""" 117 self._run("--malform") 118 119 def malform_upload(self) -> None: 120 """Truncate the next request the wallet sends.""" 121 self._run("--malformupload") 122 123 def response_code(self, status: int) -> None: 124 """Answer the next request with this status code.""" 125 self._run(f"--responsecode={status}") 126 127 def delete(self, path: str) -> None: 128 """Remove a field from the next response body.""" 129 self._run(f"--deleteobject={path}") 130 131 def modify(self, path: str, value: str) -> None: 132 """Replace a field in the next response body (always as a string).""" 133 self._run(f"--modify-dl={path}", f"--value={value}") 134 135 def flip(self, path: str) -> None: 136 """Flip one character of a string field in the next response.""" 137 self._run(f"--flip-dl={path}") 138 139 def flip_upload(self, path: str) -> None: 140 self._run(f"--flip-ul={path}") 141 142 def header(self, name: str, value: str) -> None: 143 """Rewrite a header of the next response.""" 144 self._run(f"--modify-header-dl={name}", f"--value={value}") 145 146 147 # -- keeping a fault armed -------------------------------------------- 148 149 def armed(self, arm: "Callable[[Twister], None]", period: float = 0.4): 150 """Context manager that re-arms `arm` until the block exits. 151 152 A fault is one-shot, and the wallet talks to the exchange constantly 153 (/config, /keys, /reserves/...), so a single arming lands on an 154 arbitrary request. Re-arming in the background makes the fault apply 155 to the whole step; the number of times it actually fired is reported 156 as `fired` on the handle. 157 """ 158 twister = self 159 160 class _Armed: 161 fired = 0 162 errors: list[str] = [] 163 164 def __init__(self) -> None: 165 self._stop = threading.Event() 166 self._thread = threading.Thread(target=self._loop, daemon=True) 167 168 def _loop(self) -> None: 169 while not self._stop.is_set(): 170 try: 171 arm(twister) 172 self.fired += 1 173 except Exception as e: # noqa: BLE001 - reported, not raised 174 if len(self.errors) < 3: 175 self.errors.append(str(e)[:120]) 176 self._stop.wait(period) 177 178 def __enter__(self) -> "_Armed": 179 self._thread.start() 180 return self 181 182 def __exit__(self, *exc: object) -> None: 183 self._stop.set() 184 self._thread.join(timeout=5) 185 186 return _Armed() 187 188 189 # The faults a scenario can arm, with names that read in a report. 190 FAULTS = { 191 "truncated-response": lambda t: t.malform(), 192 "truncated-request": lambda t: t.malform_upload(), 193 "http-500": lambda t: t.response_code(500), 194 "http-404": lambda t: t.response_code(404), 195 "http-403": lambda t: t.response_code(403), 196 "http-502": lambda t: t.response_code(502), 197 "wrong-content-type": lambda t: t.header("Content-Type", "text/plain"), 198 } 199 200 201 if __name__ == "__main__": 202 import sys 203 t = Twister() 204 print(f"config: {t.config}") 205 print(f"alive: {t.alive()}") 206 if len(sys.argv) > 1: 207 FAULTS[sys.argv[1]](t) 208 print(f"armed {sys.argv[1]}")