mockd.py (37357B)
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 """A merchant backend that answers however the scenario needs it to. 15 16 The public demo backend is the right thing to test against for anything that 17 has to be real -- a payment that settles, an inventory with history behind it. 18 It is the wrong thing for testing how the terminal copes with a merchant who 19 is *not* set up: nobody's shared demo instance should be broken on purpose, 20 self-provisioning a fresh one needs an emailed TAN, and "what does the 21 terminal do when `/private/pos` answers with a product in the wrong currency" 22 is not a question a correct backend can be asked. 23 24 So: a few hundred lines of HTTP that speaks just enough of the merchant API 25 for the terminal to configure itself and create an order, with a profile 26 switch for each way a merchant can be wrong. 27 28 It answers TLS, because it has to. The terminal builds its merchant URL by 29 hard-coding `https://` -- in the login form and in the `taler-pos://` parser 30 both -- so a plain-http mock is unreachable without patching the app, which 31 would mean testing something other than the app. The certificate is signed by 32 the simulator's own CA, which the "sim" build type trusts and nothing else 33 does (see pos-simulator/tls/). 34 35 python3 mockd.py --profile fresh --port 19443 36 python3 mockd.py --list 37 38 Profiles: 39 40 healthy a small, correct instance: two categories, three products 41 fresh provisioned and never stocked: no categories, no products 42 no-bank-account stocked, but order creation fails the way it does when the 43 instance has no bank account configured 44 wrong-currency products priced in a currency the instance does not use 45 bad-category a product referencing a category id that does not exist 46 version-old a backend too old for the terminal to talk to 47 version-new a backend too new for it 48 malformed `/private/pos` that is not the JSON the terminal expects 49 empty-reply `/private/pos` that answers 200 with nothing at all 50 slow every reply delayed past the terminal's patience 51 hang accepts the connection and never answers 52 expire-after-3 the token stops working on the fourth request 53 huge-inventory four hundred products, to see what the grid does 54 unicode product names in scripts the terminal has to lay out 55 """ 56 57 from __future__ import annotations 58 59 import argparse 60 import json 61 import ssl 62 import sys 63 import threading 64 import time 65 import uuid 66 from dataclasses import dataclass, field 67 from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer 68 from pathlib import Path 69 from typing import Any, Callable, Optional 70 71 HERE = Path(__file__).resolve().parent 72 TLS_DIR = HERE.parent / "tls" 73 74 # What the terminal checks itself against: BACKEND_API_VERSION is "20:0:8", so 75 # it accepts a backend whose current:revision:age covers 20. 76 # Taler protocol versions are current:revision:age, and two peers agree when 77 # their supported ranges overlap: the terminal is 20:0:8, so it speaks 78 # anything from 12 to 20. 79 VERSION_OK = "42:0:30" # 12 .. 42 -- overlaps 80 VERSION_TOO_OLD = "11:0:0" # 11 .. 11 -- one short of the terminal's floor 81 VERSION_TOO_NEW = "60:0:2" # 58 .. 60 -- above its ceiling 82 83 CURRENCY = "KUDOS" 84 CURRENCY_SPEC = { 85 "name": "Kudos", 86 "currency": CURRENCY, 87 "num_fractional_input_digits": 2, 88 "num_fractional_normal_digits": 2, 89 "num_fractional_trailing_zero_digits": 2, 90 "alt_unit_names": {"0": "ク"}, 91 } 92 93 94 def _product(pid: str, description: str, price: str, categories: list[int], 95 **extra: Any) -> dict: 96 out = { 97 "product_id": pid, 98 "product_name": description, 99 "description": description, 100 "price": price, 101 "categories": categories, 102 "total_stock": -1, 103 "unit": "item", 104 } 105 out.update(extra) 106 return out 107 108 109 HEALTHY_CATEGORIES = [{"id": 1, "name": "Drinks"}, {"id": 2, "name": "Snacks"}] 110 HEALTHY_PRODUCTS = [ 111 _product("coffee", "Coffee", f"{CURRENCY}:2.50", [1]), 112 _product("tea", "Tea", f"{CURRENCY}:2.00", [1]), 113 _product("pretzel", "Pretzel", f"{CURRENCY}:1.25", [2], total_stock=4, 114 total_sold=1, total_lost=0), 115 ] 116 117 118 @dataclass 119 class Profile: 120 """One way a merchant backend can behave.""" 121 122 name: str 123 description: str 124 categories: list[dict] = field(default_factory=lambda: list(HEALTHY_CATEGORIES)) 125 products: list[dict] = field(default_factory=lambda: list(HEALTHY_PRODUCTS)) 126 version: str = VERSION_OK 127 currency: str = CURRENCY 128 # Raw body to send for /private/pos instead of the generated one. 129 pos_body: Optional[str] = None 130 delay: float = 0.0 131 # Requests with a valid token before it starts answering 401; None = never. 132 token_uses: Optional[int] = None 133 # How `/collect` and `/refund-external` fail, as (status, code, hint), or 134 # None for "they work". These are the two calls a mixed-payment sale 135 # ends on, and both of them happen *after* the cashier has taken real 136 # money, which is what makes their failure modes worth having. 137 collect_status: Optional[tuple] = None 138 external_refund_status: Optional[tuple] = None 139 # Error to answer order creation with: (status, code, hint). 140 order_error: Optional[tuple[int, int, str]] = None 141 # Body to answer order creation with instead of the generic error shape. 142 # The merchant backend's inventory refusal is not a `{code, hint}` error: 143 # it is a 410 carrying which product ran out and by how much, which 144 # `Response.parseInventoryAvailabilityError` turns into a sentence of its 145 # own. Nothing else in the protocol looks like that, so it needs a body 146 # rather than a code and a hint. 147 order_error_body: Optional[tuple[int, dict]] = None 148 # Hand out `taler+http://` pay URIs, as a backend behind a plain-HTTP 149 # reverse proxy does. The terminal is supposed to offer to upgrade it. 150 insecure_pay_uri: bool = False 151 # Challenges `POST /private/token` answers 202 with until they are solved, 152 # as a backend with `mandatory_tan_channels` does. The real demo backend 153 # mails the code, which is why nothing driving only the UI has ever reached 154 # this path: here the code is a constant the harness knows. 155 token_challenges: Optional[list[dict]] = None 156 combi_and: bool = False 157 tan: str = "12345678" 158 # Wrong codes answered 409 ("wrong, try again") before the backend starts 159 # answering 429 ("too many, here is a new one"). Those are the two arms of 160 # `MfaUtils.handleChallengeConfirmError` that are not simply "give up". 161 tan_attempts_before_rate_limit: int = 2 162 # Refuse a bare token and accept only "secret-token:<it>". The terminal 163 # tries the bare one first and retries with the prefix on a 401 -- see 164 # `ConfigManager.fetchPosConfig` -- and nothing else makes it do that. 165 token_needs_prefix: bool = False 166 167 168 def _unicode_products() -> list[dict]: 169 names = [ 170 ("espresso-ar", "قهوة إسبريسو"), 171 ("tea-ja", "緑茶とても長い名前のついた商品"), 172 ("cake-he", "עוגת גבינה"), 173 ("kvass-ru", "Квас домашний"), 174 ("combining", "Café crème"), 175 ("rtl-mixed", "Pita RTL 3x"), 176 ("emoji", "Birthday \U0001F382 slice"), 177 ("zalgo", "C͑oͫf̰f̘e͉e"), 178 ] 179 return [_product(pid, name, f"{CURRENCY}:1.{i:02d}", [1]) 180 for i, (pid, name) in enumerate(names)] 181 182 183 # A 2x2 PNG, so the terminal has a real bitmap to decode rather than a string 184 # it will reject. `ConfigProduct.image` is a data URL and the order grid runs 185 # it through `base64Bitmap` in two places and lays the row out differently when 186 # any product in it has one. 187 _PIXEL_PNG = ( 188 "data:image/png;base64," 189 "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAFElEQVR4nGP8z4AATAxQxhAX" 190 "AAAA//8DcgEqBrfkPQAAAABJRU5ErkJggg==" 191 ) 192 193 194 def _rich_products() -> list[dict]: 195 """One product per thing the terminal does with product metadata. 196 197 Everything here is optional in the protocol and absent from the healthy 198 profile, so each field is a branch the terminal takes only when a merchant 199 has filled it in: a picture, a name that differs from the description, a 200 translation, a tax, a stock count written as a decimal string rather than 201 an integer, and a product that has sold out. 202 """ 203 return [ 204 # Picture, and a name that is not the description: `displayName` takes 205 # the name and `displayDescription` the description, which is the only 206 # case where the card shows two lines of text. 207 _product("espresso", "Single shot, 25 s extraction", f"{CURRENCY}:2.50", 208 [1], product_name="Espresso", image=_PIXEL_PNG, 209 description_i18n={"de": "Einfacher Espresso", "fr": "Expresso"}, 210 name_i18n={"de": "Espresso", "fr": "Expresso"}, 211 total_stock=20, total_sold=3, total_lost=1), 212 # Stock as decimal strings: `stockLimit` has a BigDecimal arm for each 213 # of total, sold and lost, and integers never reach any of them. 214 _product("flour", "Flour, by the kilo", f"{CURRENCY}:1.80", [2], 215 product_name="Flour", image=_PIXEL_PNG, 216 total_stock=None, unit_total_stock="12.750", 217 unit_total_sold="4.250", unit_total_lost="0.500"), 218 # Sold out: the card says so rather than offering the product. 219 _product("pastry", "Yesterday's pastry", f"{CURRENCY}:1.00", [2], 220 product_name="Pastry", total_stock=6, total_sold=6, 221 total_lost=0), 222 # Unlimited stock written the other way round, as a string. 223 _product("water", "Tap water", f"{CURRENCY}:0.50", [1], 224 total_stock=None, unit_total_stock="-1"), 225 # Taxes and a net price, which only `toContractProduct` looks at, plus 226 # a delivery location. 227 _product("hamper", "Gift hamper", f"{CURRENCY}:30.00", [2], 228 product_name="Hamper", prices_are_net=True, 229 delivery_location="counter", 230 taxes=[{"name": "VAT", "tax": f"{CURRENCY}:5.00"}]), 231 # No picture at all, so a row mixes products with and without one. 232 _product("newspaper", "Daily paper", f"{CURRENCY}:3.20", [2]), 233 ] 234 235 236 PROFILES: dict[str, Profile] = { 237 "healthy": Profile("healthy", "a small, correct instance"), 238 "fresh": Profile( 239 "fresh", "provisioned and never stocked", 240 categories=[], products=[]), 241 "no-bank-account": Profile( 242 "no-bank-account", "order creation fails for want of a bank account", 243 order_error=(409, 2010, 244 "No wire account is configured for this instance")), 245 "wrong-currency": Profile( 246 "wrong-currency", "products priced in another currency", 247 products=[_product("coffee", "Coffee", "EUR:2.50", [1]), 248 _product("tea", "Tea", "CHF:2.00", [1])]), 249 "bad-category": Profile( 250 "bad-category", "a product in a category that does not exist", 251 products=[_product("ghost", "Ghost product", f"{CURRENCY}:1.00", [99])]), 252 "collect-fails": Profile( 253 "collect-fails", 254 "settling a fully-cash sale is refused by the backend", 255 collect_status=(502, 2017, "The backend could not settle the order")), 256 "external-refund-fails": Profile( 257 "external-refund-fails", 258 "recording cash handed back is refused by the backend", 259 external_refund_status=(409, 2537, 260 "The order was already refunded externally")), 261 "version-old": Profile("version-old", "a backend too old to talk to", 262 version=VERSION_TOO_OLD), 263 "version-new": Profile("version-new", "a backend too new to talk to", 264 version=VERSION_TOO_NEW), 265 "malformed": Profile( 266 "malformed", "/private/pos that is not what the terminal expects", 267 pos_body=json.dumps({"categories": "not a list", "products": 42})), 268 "empty-reply": Profile( 269 "empty-reply", "/private/pos that answers 200 with nothing", 270 pos_body=""), 271 "slow": Profile("slow", "every reply delayed past the terminal's patience", 272 delay=65.0), 273 "hang": Profile("hang", "accepts the connection and never answers", 274 delay=86_400.0), 275 "expire-after-3": Profile( 276 "expire-after-3", "the token stops working on the fourth request", 277 token_uses=3), 278 "huge-inventory": Profile( 279 "huge-inventory", "four hundred products", 280 products=[_product(f"p{i:03d}", f"Product {i:03d}", 281 f"{CURRENCY}:{1 + i % 50}.{i % 100:02d}", [1 + i % 2]) 282 for i in range(400)]), 283 "unicode": Profile("unicode", "product names in several scripts", 284 products=_unicode_products()), 285 "inventory-gone": Profile( 286 "inventory-gone", "the product sold out between the tap and the order", 287 order_error_body=(410, {"product_id": "pretzel", 288 "requested_quantity": 2, 289 "available_quantity": 0})), 290 "insecure-pay-uri": Profile( 291 "insecure-pay-uri", "pay URIs that are not https", 292 insecure_pay_uri=True), 293 "mfa-two-channels": Profile( 294 "mfa-two-channels", "logging in needs a code, by email or by SMS", 295 token_challenges=[ 296 {"challenge_id": "mock-chal-email", 297 "tan_channel": "email", "tan_info": "o...r@example.com"}, 298 {"challenge_id": "mock-chal-sms", 299 "tan_channel": "sms", "tan_info": "+49 *** *** 42"}, 300 ]), 301 "rich-catalogue": Profile( 302 "rich-catalogue", "products carrying every optional field there is", 303 products=_rich_products()), 304 "token-needs-prefix": Profile( 305 "token-needs-prefix", "a backend that only accepts secret-token:<tok>", 306 token_needs_prefix=True), 307 "mfa-both-required": Profile( 308 "mfa-both-required", "logging in needs a code from each of two channels", 309 combi_and=True, 310 token_challenges=[ 311 {"challenge_id": "mock-chal-email", 312 "tan_channel": "email", "tan_info": "o...r@example.com"}, 313 {"challenge_id": "mock-chal-sms", 314 "tan_channel": "sms", "tan_info": "+49 *** *** 42"}, 315 ]), 316 } 317 318 319 @dataclass 320 class Order: 321 order_id: str 322 amount: str 323 summary: str 324 claim_token: str 325 created: float 326 pay_deadline: float 327 claimed: bool = False 328 paid: bool = False 329 refunded: bool = False 330 # Refunds settled outside Taler -- cash handed back, a card refunded in 331 # the provider's own app. The backend keeps these apart from Taler 332 # refunds and so does this: a cash refund must never show up in 333 # `refund_amount`, and a scenario that cannot tell them apart would not 334 # notice if it did. 335 refunds_external: list = field(default_factory=list) 336 collected: bool = False 337 338 339 class MockState: 340 """Everything the server remembers, so a scenario can inspect it.""" 341 342 def __init__(self, profile: Profile, host: str, instance: str): 343 self.profile = profile 344 self.host = host 345 self.instance = instance 346 self.orders: dict[str, Order] = {} 347 self.requests: list[tuple[float, str, str]] = [] 348 self.authorised_requests = 0 349 # The two-factor dance, so a scenario can check that the terminal 350 # asked for a code before it typed one and did not skip a channel. 351 self.challenges_sent: list[str] = [] 352 self.challenges_solved: list[str] = [] 353 self.bad_tans: list[str] = [] 354 # Requests refused for carrying the token without its prefix, so a 355 # scenario can tell a retry from a first attempt that happened to work. 356 self.bare_token_requests = 0 357 self.lock = threading.Lock() 358 359 def note(self, method: str, path: str) -> None: 360 with self.lock: 361 self.requests.append((time.time(), method, path)) 362 363 def paths(self) -> list[str]: 364 with self.lock: 365 return [p for _, _, p in self.requests] 366 367 def encoded_slash_requests(self) -> list[str]: 368 """Requests that arrived with a percent-encoded path separator.""" 369 with self.lock: 370 return [p for _, method, p in self.requests if method == "ENCODED-SLASH"] 371 372 def token_still_good(self) -> bool: 373 limit = self.profile.token_uses 374 with self.lock: 375 self.authorised_requests += 1 376 return limit is None or self.authorised_requests <= limit 377 378 379 class Handler(BaseHTTPRequestHandler): 380 state: MockState # set on the server class 381 382 protocol_version = "HTTP/1.1" 383 server_version = "pos-simulator-mockd/1" 384 385 def log_message(self, fmt: str, *args: Any) -> None: 386 sys.stderr.write(f"mockd {self.address_string()} {fmt % args}\n") 387 388 def handle_one_request(self) -> None: 389 """Serve one request, without a traceback when the client walks away. 390 391 The terminal closes idle connections and is itself killed mid-request 392 by several scenarios, so a broken pipe or a reset TLS session is 393 normal here. http.server's default is to print a full traceback for 394 each one, which buries the request log the oracles read. 395 """ 396 try: 397 super().handle_one_request() 398 except (BrokenPipeError, ConnectionResetError, ssl.SSLError) as e: 399 self.close_connection = True 400 sys.stderr.write(f"mockd {self.address_string()} client went away: " 401 f"{type(e).__name__}\n") 402 403 # -- plumbing --------------------------------------------------------- 404 405 def _send(self, status: int, payload: Any, raw: Optional[str] = None) -> None: 406 if self.state.profile.delay: 407 time.sleep(self.state.profile.delay) 408 body = (raw if raw is not None else json.dumps(payload)).encode() 409 self.send_response(status) 410 self.send_header("Content-Type", "application/json") 411 self.send_header("Content-Length", str(len(body))) 412 self.end_headers() 413 if body: 414 self.wfile.write(body) 415 416 def _error(self, status: int, code: int, hint: str) -> None: 417 self._send(status, {"code": code, "hint": hint, "detail": ""}) 418 419 def _normalised_path(self) -> str: 420 """The request path with encoded slashes turned back into separators. 421 422 The terminal asks for `/instances/<id>/private%2Fpos`: it builds that 423 URL with `Uri.Builder.appendPath("private/pos")`, which percent-encodes 424 the separator because a path *segment* may legitimately contain one. 425 The GNU Taler backend decodes the path before routing and so answers 426 it anyway, which is why this has never been noticed -- but a reverse 427 proxy in front of the backend need not, and Apache with its default 428 `AllowEncodedSlashes Off` refuses such a request outright. 429 430 So the mock accepts it, like the real backend, and records that it had 431 to: `MockState.encoded_slash_requests` is what the finding is written 432 from. 433 """ 434 path = self.path.split("?")[0] 435 if "%2F" in path or "%2f" in path: 436 self.state.note("ENCODED-SLASH", path) 437 return path.replace("%2F", "/").replace("%2f", "/") 438 439 def _body(self) -> dict: 440 length = int(self.headers.get("Content-Length") or 0) 441 if not length: 442 return {} 443 try: 444 return json.loads(self.rfile.read(length)) 445 except json.JSONDecodeError: 446 return {} 447 448 def _authorised(self) -> bool: 449 header = self.headers.get("Authorization", "") 450 if not header.startswith("Bearer "): 451 return False 452 if (self.state.profile.token_needs_prefix 453 and not header.startswith("Bearer secret-token:")): 454 self.state.bare_token_requests += 1 455 return False 456 return self.state.token_still_good() 457 458 # -- routes ----------------------------------------------------------- 459 460 def do_GET(self) -> None: # noqa: N802 (http.server's naming) 461 self.state.note("GET", self.path) 462 path = self._normalised_path() 463 prefix = f"/instances/{self.state.instance}" 464 465 if path in ("/config", f"{prefix}/config"): 466 return self._send(200, { 467 "currency": self.state.profile.currency, 468 "currencies": {self.state.profile.currency: CURRENCY_SPEC}, 469 "version": self.state.profile.version, 470 "name": "taler-merchant", 471 "implementation": "urn:net:taler:specs:taler-merchant:pos-simulator-mock", 472 "have_self_provisioning": True, 473 "exchanges": [], 474 }) 475 476 if path == f"{prefix}/private/pos": 477 if not self._authorised(): 478 return self._error(401, 40, "Invalid access token") 479 profile = self.state.profile 480 if profile.pos_body is not None: 481 return self._send(200, None, raw=profile.pos_body) 482 return self._send(200, { 483 "categories": profile.categories, 484 "products": profile.products, 485 }) 486 487 if path.startswith(f"{prefix}/private/products/"): 488 if not self._authorised(): 489 return self._error(401, 40, "Invalid access token") 490 pid = path.rsplit("/", 1)[-1] 491 product = next((p for p in self.state.profile.products 492 if p["product_id"] == pid), None) 493 if product is None: 494 return self._error(404, 2549, "Product unknown") 495 return self._send(200, { 496 "description": product["description"], 497 "price": product["price"], 498 "total_stock": product.get("total_stock", -1), 499 "total_sold": product.get("total_sold", 0), 500 "total_lost": product.get("total_lost", 0), 501 }) 502 503 if path == f"{prefix}/private/orders": 504 if not self._authorised(): 505 return self._error(401, 40, "Invalid access token") 506 orders = sorted(self.state.orders.values(), 507 key=lambda o: o.created, reverse=True) 508 return self._send(200, {"orders": [ 509 { 510 "order_id": o.order_id, 511 "row_id": i + 1, 512 "timestamp": {"t_s": int(o.created)}, 513 "amount": o.amount, 514 "summary": o.summary, 515 "paid": o.paid, 516 "refunded": o.refunded, 517 "refund_pending": False, 518 } 519 for i, o in enumerate(orders) 520 ]}) 521 522 if path.startswith(f"{prefix}/private/orders/"): 523 if not self._authorised(): 524 return self._error(401, 40, "Invalid access token") 525 order = self.state.orders.get(path.rsplit("/", 1)[-1]) 526 if order is None: 527 return self._error(404, 2005, "The proposal is not known") 528 if order.paid: 529 return self._send(200, { 530 "order_status": "paid", "refunded": order.refunded, 531 "refund_pending": False, "wired": False, 532 "deposit_total": order.amount, 533 "exchange_code": 0, "exchange_http_status": 0, 534 "refunds_external": order.refunds_external, 535 "refund_amount": f"{self.state.profile.currency}:0", 536 "contract_terms": {"summary": order.summary, 537 "amount": order.amount}, 538 "last_payment": {"t_s": int(time.time())}, 539 }) 540 if order.claimed: 541 return self._send(200, {"order_status": "claimed", 542 "contract_terms": { 543 "summary": order.summary, 544 "amount": order.amount}}) 545 scheme = ("taler+http" if self.state.profile.insecure_pay_uri 546 else "taler") 547 return self._send(200, { 548 "order_status": "unpaid", 549 "taler_pay_uri": (f"{scheme}://pay/{self.state.host}/instances/" 550 f"{self.state.instance}/{order.order_id}/" 551 f"?c={order.claim_token}"), 552 "creation_time": {"t_s": int(order.created)}, 553 "summary": order.summary, 554 "order_status_url": "https://example.invalid/", 555 }) 556 557 if path == f"{prefix}/private/accounts": 558 if not self._authorised(): 559 return self._error(401, 40, "Invalid access token") 560 if self.state.profile.name == "no-bank-account": 561 return self._send(200, {"accounts": []}) 562 return self._send(200, {"accounts": [{ 563 "payto_uri": "payto://x-taler-bank/bank.example.invalid/mock", 564 "h_wire": "0" * 64, "active": True}]}) 565 566 self.state.note("GET-404", path) 567 return self._error(404, 21, "No endpoint for this URL in the mock") 568 569 def do_POST(self) -> None: # noqa: N802 570 self.state.note("POST", self.path) 571 path = self._normalised_path() 572 prefix = f"/instances/{self.state.instance}" 573 body = self._body() 574 575 # The two-factor dance, which only `mfa-*` profiles ask for. Order is 576 # POST /private/token -> 202 with the challenges, then one 577 # POST .../challenge/<id> to have the code sent and one 578 # POST .../challenge/<id>/confirm to answer it, then /private/token 579 # again carrying `Taler-Challenge-Ids` for what was solved. 580 challenges = self.state.profile.token_challenges 581 if challenges and path.startswith(f"{prefix}/challenge/"): 582 rest = path[len(f"{prefix}/challenge/"):] 583 challenge_id = rest.removesuffix("/confirm") 584 if challenge_id not in {c["challenge_id"] for c in challenges}: 585 return self._error(404, 2900, f"No such challenge {challenge_id}") 586 if not rest.endswith("/confirm"): 587 self.state.challenges_sent.append(challenge_id) 588 return self._send(204, None, raw="") 589 # The terminal sends the code hyphenated -- `MfaUtils.formatMfaCode` 590 # turns 12345678 into "1234-5678" -- so the comparison is on the 591 # digits and the profile's `tan` can be written either way. 592 given = str(body.get("tan", "")) 593 digits = "".join(ch for ch in given if ch.isdigit()) 594 if digits != "".join(ch for ch in self.state.profile.tan 595 if ch.isdigit()): 596 self.state.bad_tans.append(given) 597 # 409 is the only status the terminal reads as "wrong code, ask 598 # for another"; 429 is "too many attempts, a new code is on its 599 # way"; anything else makes it give up. See 600 # `MfaUtils.handleChallengeConfirmError`. 601 if len(self.state.bad_tans) > self.state.profile.tan_attempts_before_rate_limit: 602 return self._error(429, 2903, "Too many attempts") 603 return self._error(409, 2901, "Invalid TAN") 604 self.state.challenges_solved.append(challenge_id) 605 return self._send(204, None, raw="") 606 607 if path == f"{prefix}/private/token": 608 if challenges: 609 solved = [i for i in (self.headers.get("Taler-Challenge-Ids") or "") 610 .split(",") if i] 611 needed = ({c["challenge_id"] for c in challenges} 612 if self.state.profile.combi_and else None) 613 enough = (set(solved) >= needed) if needed else bool(solved) 614 if not enough: 615 return self._send(202, { 616 "challenges": challenges, 617 "combi_and": self.state.profile.combi_and, 618 }) 619 # The login form asks for this one. A mock token is accepted from 620 # anybody: what is under test is the terminal, not an access 621 # control decision. 622 duration = (body.get("duration") or {}).get("d_us") 623 expiration: dict[str, Any] = {"t_s": "never"} 624 if isinstance(duration, int): 625 expiration = {"t_s": int(time.time() + duration / 1_000_000)} 626 # A backend that insists on the prefix hands the token out 627 # *without* it, which is the whole point: the terminal stores what 628 # it was given, sends it bare, is refused, and retries prefixed. 629 # Handing out a prefixed token means it never has to. 630 token = f"mock-{uuid.uuid4().hex[:24]}" 631 if not self.state.profile.token_needs_prefix: 632 token = f"secret-token:{token}" 633 return self._send(200, { 634 "token": token, "access_token": token, 635 "scope": body.get("scope", "write"), "refreshable": False, 636 "expiration": expiration, 637 }) 638 639 if path == f"{prefix}/private/orders": 640 if not self._authorised(): 641 return self._error(401, 40, "Invalid access token") 642 error = self.state.profile.order_error 643 if error: 644 return self._error(*error) 645 raw = self.state.profile.order_error_body 646 if raw: 647 return self._send(raw[0], raw[1]) 648 order_spec = (body.get("order") or {}) 649 order_id = f"mock-{uuid.uuid4().hex[:12]}" 650 order = Order( 651 order_id=order_id, 652 amount=order_spec.get("amount", f"{self.state.profile.currency}:0"), 653 summary=order_spec.get("summary", ""), 654 claim_token=uuid.uuid4().hex[:26].upper(), 655 created=time.time(), 656 pay_deadline=time.time() + 3600, 657 ) 658 self.state.orders[order_id] = order 659 return self._send(200, {"order_id": order_id, 660 "token": order.claim_token}) 661 662 if path.endswith("/refund") and path.startswith(f"{prefix}/private/orders/"): 663 if not self._authorised(): 664 return self._error(401, 40, "Invalid access token") 665 order_id = path.split("/")[-2] 666 order = self.state.orders.get(order_id) 667 if order is None: 668 return self._error(404, 2005, "The proposal is not known") 669 order.refunded = True 670 return self._send(200, { 671 "taler_refund_uri": (f"taler://refund/{self.state.host}/instances/" 672 f"{self.state.instance}/{order_id}"), 673 "h_contract": "0" * 64, 674 }) 675 676 # Settling an order that was paid entirely outside Taler. Without 677 # this the checkout can be driven right up to "Complete payment" on a 678 # mock and no further, which is where the interesting half starts. 679 if (path.endswith("/collect") 680 and path.startswith(f"{prefix}/private/orders/")): 681 if not self._authorised(): 682 return self._error(401, 40, "Invalid access token") 683 order_id = path.split("/")[-2] 684 order = self.state.orders.get(order_id) 685 if order is None: 686 return self._error(404, 2005, "The proposal is not known") 687 if self.state.profile.collect_status: 688 code, num, hint = self.state.profile.collect_status 689 return self._error(code, num, hint) 690 order.paid = True 691 order.collected = True 692 return self._send(200, {}) 693 694 # Recording money handed back outside Taler. 695 if (path.endswith("/refund-external") 696 and path.startswith(f"{prefix}/private/orders/")): 697 if not self._authorised(): 698 return self._error(401, 40, "Invalid access token") 699 order_id = path.split("/")[-2] 700 order = self.state.orders.get(order_id) 701 if order is None: 702 return self._error(404, 2005, "The proposal is not known") 703 if self.state.profile.external_refund_status: 704 code, num, hint = self.state.profile.external_refund_status 705 return self._error(code, num, hint) 706 body = self._body() or {} 707 order.refunds_external.append({ 708 "id": body.get("id", "mock-refund"), 709 "method": body.get("method", "cash"), 710 "payment_id": body.get("payment_id"), 711 "amount": body.get("amount", f"{self.state.profile.currency}:0"), 712 "reason": body.get("reason", ""), 713 "timestamp": {"t_s": int(time.time())}, 714 }) 715 return self._send(200, {}) 716 717 self.state.note("POST-404", path) 718 return self._error(404, 21, "No endpoint for this URL in the mock") 719 720 def do_DELETE(self) -> None: # noqa: N802 721 self.state.note("DELETE", self.path) 722 path = self._normalised_path() 723 prefix = f"/instances/{self.state.instance}" 724 if path.startswith(f"{prefix}/private/orders/"): 725 if not self._authorised(): 726 return self._error(401, 40, "Invalid access token") 727 order_id = path.rsplit("/", 1)[-1] 728 order = self.state.orders.get(order_id) 729 if order is None: 730 return self._error(404, 2005, "The proposal is not known") 731 if order.claimed and "force=yes" not in self.path: 732 return self._error(409, 2026, 733 "The order has been claimed and cannot be " 734 "deleted without force") 735 del self.state.orders[order_id] 736 return self._send(204, None, raw="") 737 return self._error(404, 21, "No endpoint for this URL in the mock") 738 739 740 def build_server(profile_name: str, port: int, instance: str = "mockshop", 741 host: Optional[str] = None 742 ) -> tuple[ThreadingHTTPServer, MockState]: 743 """A configured, not-yet-serving mock backend and the state it will fill. 744 745 Separated from `serve` so that a caller inside the driver can run it in a 746 thread and shut it down again -- a suite process runs several mock 747 scenarios one after another, and a server left listening takes the port 748 with it. 749 """ 750 profile = PROFILES[profile_name] 751 host = host or f"localhost:{port}" 752 state = MockState(profile, host=host, instance=instance) 753 handler = type("BoundHandler", (Handler,), {"state": state}) 754 server = ThreadingHTTPServer(("127.0.0.1", port), handler) 755 context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) 756 context.load_cert_chain(certfile=str(TLS_DIR / "srv.crt"), 757 keyfile=str(TLS_DIR / "srv.key")) 758 server.socket = context.wrap_socket(server.socket, server_side=True) 759 return server, state 760 761 762 def serve(profile_name: str, port: int, instance: str = "mockshop", 763 host: Optional[str] = None, 764 ready: Optional[Callable[[MockState], None]] = None) -> None: 765 server, state = build_server(profile_name, port, instance, host) 766 print(f"mockd: profile {profile_name!r} ({PROFILES[profile_name].description}) " 767 f"on https://{state.host}/instances/{instance}", flush=True) 768 if ready: 769 ready(state) 770 try: 771 server.serve_forever() 772 except KeyboardInterrupt: 773 pass 774 finally: 775 server.server_close() 776 777 778 def main() -> int: 779 ap = argparse.ArgumentParser(description=__doc__, 780 formatter_class=argparse.RawDescriptionHelpFormatter) 781 ap.add_argument("--profile", default="healthy") 782 ap.add_argument("--port", type=int, default=19443) 783 ap.add_argument("--instance", default="mockshop") 784 ap.add_argument("--host", default=None, 785 help="the authority the terminal will use, if not localhost:<port>") 786 ap.add_argument("--list", action="store_true") 787 args = ap.parse_args() 788 if args.list: 789 width = max(len(n) for n in PROFILES) 790 for name, profile in PROFILES.items(): 791 print(f" {name:<{width}} {profile.description}") 792 return 0 793 if args.profile not in PROFILES: 794 print(f"unknown profile {args.profile!r}; --list shows them all") 795 return 2 796 serve(args.profile, args.port, args.instance, args.host) 797 return 0 798 799 800 if __name__ == "__main__": 801 sys.exit(main())