merchant.py (19030B)
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 """The merchant backend, as the harness sees it. 15 16 Two jobs. The first is *provisioning*: minting the access tokens the terminal 17 is configured with, which is the only way to give it a credential that expires 18 on a schedule the harness chooses -- the login form always asks for 19 `TokenDuration.Forever`, so an expiring session cannot be set up through the 20 UI at all. The second is acting as the merchant's own back office, so a 21 scenario can arrange the state the terminal is supposed to react to: an order 22 that is already claimed, an order past its refund deadline, a product that is 23 out of stock. 24 25 Only the standard merchant HTTP API is used, over `urllib`, so this runs 26 wherever Python does and needs nothing installed. 27 """ 28 29 from __future__ import annotations 30 31 import base64 32 import json 33 import os 34 import ssl 35 import time 36 import urllib.error 37 import urllib.parse 38 import urllib.request 39 from dataclasses import dataclass, field 40 from typing import Any, Optional 41 42 DEMO_BASE = os.environ.get("POS_MERCHANT", "https://backend.demo.taler.net") 43 DEMO_INSTANCE = os.environ.get("POS_INSTANCE", "sandbox") 44 # The password the terminal's own "Fill demo credentials" button types. 45 DEMO_SECRET = os.environ.get("POS_SECRET", "sandbox") 46 47 TIMEOUT = 30 48 49 50 class MerchantError(RuntimeError): 51 """A backend request that came back with a status the caller did not expect.""" 52 53 def __init__(self, status: int, body: str, url: str): 54 self.status = status 55 self.body = body 56 self.url = url 57 try: 58 detail = json.loads(body) 59 hint = detail.get("hint") or detail.get("detail") or body 60 self.code = detail.get("code") 61 except (json.JSONDecodeError, AttributeError): 62 hint = body 63 self.code = None 64 super().__init__(f"HTTP {status} from {url}: {str(hint)[:300]}") 65 66 67 @dataclass 68 class Token: 69 """An access token, with the expiry the harness asked for. 70 71 `expires_at` is wall-clock seconds, as the backend reports it; it is the 72 only honest way to decide whether a session *should* still be alive, since 73 the terminal shows nothing about its own credential. 74 """ 75 76 value: str 77 scope: str 78 expires_at: Optional[int] 79 refreshable: bool = False 80 81 @property 82 def expired(self) -> bool: 83 return self.expires_at is not None and time.time() >= self.expires_at 84 85 @property 86 def seconds_left(self) -> Optional[float]: 87 if self.expires_at is None: 88 return None 89 return self.expires_at - time.time() 90 91 def __str__(self) -> str: 92 if self.expires_at is None: 93 return f"token(forever, {self.value[:18]}...)" 94 return f"token({self.seconds_left:.0f}s left, {self.value[:18]}...)" 95 96 97 class Merchant: 98 """One instance of one merchant backend. 99 100 `base` is the backend root (no instance path); `instance` names the 101 instance. The terminal is configured with `<base>/instances/<instance>`, 102 which is what `pos_url` returns. 103 """ 104 105 def __init__(self, base: str = DEMO_BASE, instance: str = DEMO_INSTANCE, 106 secret: str = DEMO_SECRET, ca_file: Optional[str] = None): 107 self.base = base.rstrip("/") 108 self.instance = instance 109 self.secret = secret 110 # The mock backend answers TLS with the simulator's own CA, which the 111 # host's trust store does not know; the emulator learns it from the 112 # sim build's network security config, and the driver from here. 113 self.ctx: Optional[ssl.SSLContext] = None 114 if ca_file: 115 self.ctx = ssl.create_default_context(cafile=ca_file) 116 117 # -- plumbing --------------------------------------------------------- 118 119 @property 120 def instance_url(self) -> str: 121 return f"{self.base}/instances/{self.instance}" 122 123 def pos_url(self) -> str: 124 """What the terminal stores as its merchant URL.""" 125 return self.instance_url 126 127 def _request(self, method: str, path: str, *, token: Optional[str] = None, 128 body: Any = None, headers: Optional[dict[str, str]] = None, 129 expect: tuple[int, ...] = (200, 204), 130 absolute: bool = False) -> tuple[int, Any]: 131 url = path if absolute else f"{self.instance_url}/{path.lstrip('/')}" 132 data = None 133 hdrs = dict(headers or {}) 134 if body is not None: 135 data = json.dumps(body).encode() 136 hdrs["Content-Type"] = "application/json" 137 if token: 138 # The backend accepts the token with or without its prefix, but 139 # only the prefixed form works everywhere, and the terminal adds 140 # the prefix itself when a bare token gets a 401 -- so normalise. 141 value = token if token.startswith("secret-token:") else f"secret-token:{token}" 142 hdrs["Authorization"] = f"Bearer {value}" 143 req = urllib.request.Request(url, data=data, headers=hdrs, method=method) 144 try: 145 with urllib.request.urlopen(req, timeout=TIMEOUT, context=self.ctx) as resp: 146 raw = resp.read() 147 status = resp.status 148 except urllib.error.HTTPError as e: 149 raw = e.read() 150 status = e.code 151 payload: Any = None 152 if raw: 153 try: 154 payload = json.loads(raw) 155 except json.JSONDecodeError: 156 payload = raw.decode(errors="replace") 157 if status not in expect: 158 raise MerchantError(status, raw.decode(errors="replace") if raw else "", url) 159 return status, payload 160 161 # -- the backend itself ----------------------------------------------- 162 163 def config(self) -> dict: 164 _, payload = self._request("GET", f"{self.base}/config", absolute=True) 165 return payload 166 167 def currency(self) -> str: 168 return self.config()["currency"] 169 170 def backend_version(self) -> str: 171 return self.config()["version"] 172 173 # -- credentials ------------------------------------------------------ 174 175 def mint_token(self, seconds: Optional[int] = None, scope: str = "write", 176 secret: Optional[str] = None, 177 refreshable: bool = False) -> Token: 178 """Mint an access token, optionally one that expires. 179 180 `seconds=None` asks for a token that never expires, which is what the 181 login form would produce. Anything else is a credential the terminal 182 cannot obtain for itself, and is the whole point of this method: the 183 only way to watch the app handle a session ending is to hand it a 184 session that ends. 185 """ 186 duration = {"d_us": "forever"} if seconds is None else { 187 "d_us": int(seconds * 1_000_000)} 188 body: dict[str, Any] = {"scope": scope, "duration": duration} 189 if refreshable: 190 body["refreshable"] = True 191 status, payload = self._request( 192 "POST", "private/token", token=secret or self.secret, body=body, 193 expect=(200, 202)) 194 if status == 202: 195 raise MerchantError( 196 202, json.dumps(payload), 197 f"{self.instance_url}/private/token") 198 expires = None 199 exp = payload.get("expiration") or {} 200 if isinstance(exp, dict) and isinstance(exp.get("t_s"), int): 201 expires = exp["t_s"] 202 return Token( 203 value=payload["token"], 204 scope=payload.get("scope", scope), 205 expires_at=expires, 206 refreshable=bool(payload.get("refreshable")), 207 ) 208 209 def revoke_token(self, token: str) -> None: 210 """Drop a token server side, so the next request with it gets a 401. 211 212 This is how a session is ended at a moment of the harness's choosing, 213 without waiting out an expiry. 214 """ 215 self._request("DELETE", "private/token", token=token, expect=(204, 200, 404)) 216 217 def pos_config(self, token: str) -> dict: 218 """What the terminal reads at startup: categories and products.""" 219 _, payload = self._request("GET", "private/pos", token=token) 220 return payload 221 222 # -- instances -------------------------------------------------------- 223 224 def provision_instance(self, instance_id: str, name: str, password: str, 225 email: Optional[str] = None, 226 token_validity_ms: int = 86_400_000) -> dict: 227 """Self-provision a fresh instance. 228 229 Returns the body on success. A backend with a mandatory TAN channel 230 answers 202 with a challenge instead, which is not something the 231 harness can solve on its own -- see README, "a fresh instance" -- so 232 that case is raised with the challenge attached rather than swallowed. 233 """ 234 body = { 235 "id": instance_id, 236 "name": name, 237 "auth": {"method": "token", "password": f"secret-token:{password}"}, 238 "address": {}, 239 "jurisdiction": {}, 240 "use_stefan": True, 241 } 242 if email: 243 body["email"] = email 244 status, payload = self._request( 245 "POST", f"{self.base}/instances?token_validity_ms={token_validity_ms}", 246 body=body, absolute=True, expect=(200, 204, 202, 409)) 247 if status == 202: 248 raise MerchantError(202, json.dumps(payload), f"{self.base}/instances") 249 if status == 409: 250 raise MerchantError(409, json.dumps(payload), f"{self.base}/instances") 251 return payload or {} 252 253 def accounts(self, token: str) -> list[dict]: 254 """The instance's bank accounts. 255 256 An instance with none cannot be paid out and the backend refuses to 257 create orders for it, which is one of the two ways a terminal can be 258 pointed at a badly configured merchant. 259 """ 260 _, payload = self._request("GET", "private/accounts", token=token) 261 return (payload or {}).get("accounts", []) 262 263 # -- inventory -------------------------------------------------------- 264 265 def products(self, token: str) -> list[dict]: 266 _, payload = self._request("GET", "private/products", token=token) 267 return (payload or {}).get("products", []) 268 269 def product(self, token: str, product_id: str) -> dict: 270 _, payload = self._request("GET", f"private/products/{product_id}", token=token) 271 return payload 272 273 def add_product(self, token: str, product_id: str, description: str, 274 price: str, *, total_stock: int = -1, 275 unit: str = "item", categories: Optional[list[int]] = None, 276 extra: Optional[dict] = None) -> None: 277 body: dict[str, Any] = { 278 "product_id": product_id, 279 "description": description, 280 "unit": unit, 281 "price": price, 282 "total_stock": total_stock, 283 "address": {}, 284 "next_restock": {"t_s": "never"}, 285 } 286 if categories is not None: 287 body["categories"] = categories 288 if extra: 289 body.update(extra) 290 self._request("POST", "private/products", token=token, body=body, 291 expect=(204, 200, 409)) 292 293 def delete_product(self, token: str, product_id: str) -> None: 294 self._request("DELETE", f"private/products/{product_id}", token=token, 295 expect=(204, 200, 404, 409)) 296 297 def categories(self, token: str) -> list[dict]: 298 _, payload = self._request("GET", "private/categories", token=token) 299 return (payload or {}).get("categories", []) 300 301 def add_category(self, token: str, name: str, 302 name_i18n: Optional[dict] = None) -> int: 303 body: dict[str, Any] = {"name": name} 304 if name_i18n: 305 body["name_i18n"] = name_i18n 306 _, payload = self._request("POST", "private/categories", token=token, 307 body=body, expect=(200, 204, 409)) 308 return (payload or {}).get("category_id", -1) 309 310 # -- orders ----------------------------------------------------------- 311 312 def create_order(self, token: str, amount: str, summary: str, *, 313 pay_deadline_s: Optional[int] = None, 314 refund_deadline_s: Optional[int] = None, 315 fulfillment_url: Optional[str] = None, 316 extra_order: Optional[dict] = None) -> dict: 317 """Post an order the way the terminal would, with a controllable deadline. 318 319 A pay deadline a few seconds out is how the "no payment within the 320 payment period" path is reached without waiting an hour, and a refund 321 deadline in the past is how the refund screen's deadline error is. 322 """ 323 order: dict[str, Any] = {"amount": amount, "summary": summary} 324 if pay_deadline_s is not None: 325 order["pay_deadline"] = {"t_s": int(time.time()) + pay_deadline_s} 326 if refund_deadline_s is not None: 327 order["refund_deadline"] = {"t_s": int(time.time()) + refund_deadline_s} 328 if fulfillment_url: 329 order["fulfillment_url"] = fulfillment_url 330 if extra_order: 331 order.update(extra_order) 332 _, payload = self._request("POST", "private/orders", token=token, 333 body={"order": order}) 334 return payload 335 336 def order_status(self, token: str, order_id: str) -> dict: 337 _, payload = self._request("GET", f"private/orders/{order_id}", token=token) 338 return payload 339 340 def pay_uri(self, token: str, order_id: str) -> Optional[str]: 341 return self.order_status(token, order_id).get("taler_pay_uri") 342 343 def delete_order(self, token: str, order_id: str, force: bool = False) -> int: 344 suffix = "?force=yes" if force else "" 345 status, _ = self._request("DELETE", f"private/orders/{order_id}{suffix}", 346 token=token, expect=(204, 200, 404, 409)) 347 return status 348 349 def history(self, token: str, limit: int = -20, 350 offset: Optional[int] = None) -> list[dict]: 351 query = f"?limit={limit}" 352 if offset is not None: 353 query += f"&offset={offset}" 354 _, payload = self._request("GET", f"private/orders{query}", token=token) 355 return (payload or {}).get("orders", []) 356 357 def refund(self, token: str, order_id: str, amount: str, 358 reason: str = "pos-simulator") -> dict: 359 _, payload = self._request("POST", f"private/orders/{order_id}/refund", 360 token=token, 361 body={"refund": amount, "reason": reason}) 362 return payload 363 364 def claim_order(self, order_id: str, claim_token: Optional[str] = None, 365 nonce: Optional[str] = None) -> dict: 366 """Claim an order without paying it, the way a wallet does first. 367 368 This is the only way to reach the terminal's force-delete dialog: a 369 claimed order cannot be deleted normally, and the dialog exists for 370 exactly that. The claim is a public endpoint -- no merchant 371 credential -- because it is the customer's side of the contract. 372 """ 373 nonce = nonce or base64.b32encode(os.urandom(16)).decode().rstrip("=") 374 body: dict[str, Any] = {"nonce": nonce} 375 if claim_token: 376 body["token"] = claim_token 377 _, payload = self._request("POST", f"orders/{order_id}/claim", body=body) 378 return payload 379 380 381 @dataclass 382 class Instance: 383 """A provisioned instance plus the credentials the harness holds for it.""" 384 385 merchant: Merchant 386 token: Token 387 currency: str 388 label: str = "" 389 products: list[dict] = field(default_factory=list) 390 391 def setup_uri(self, host: Optional[str] = None, style: str = "path") -> str: 392 """The `taler-pos://` URI that configures a terminal for this instance. 393 394 Two shapes reach the same place, and MainActivity parses them with 395 different code: 396 397 * `path`: taler-pos://<host>/instances/<id>#<token> 398 * `params`: taler-pos://<host>#username=<id>&password=<token> 399 400 The scheme is fixed and so is https -- the terminal rebuilds the base 401 URL itself and hard-codes the scheme -- so the host must be reachable 402 over TLS from inside the emulator. 403 """ 404 parsed = urllib.parse.urlsplit(self.merchant.base) 405 host = host or parsed.netloc 406 token = self.token.value 407 if style == "path": 408 return (f"taler-pos://{host}/instances/{self.merchant.instance}" 409 f"#{urllib.parse.quote(token, safe='')}") 410 if style == "params": 411 return (f"taler-pos://{host}#username={urllib.parse.quote(self.merchant.instance)}" 412 f"&password={urllib.parse.quote(token, safe='')}") 413 raise ValueError(f"unknown setup-uri style {style!r}") 414 415 416 def demo(instance: str = DEMO_INSTANCE, secret: str = DEMO_SECRET, 417 seconds: Optional[int] = None) -> Instance: 418 """The public demo backend, with a freshly minted token. 419 420 The `sandbox` instance is shared and already carries a large inventory and 421 a long order history, which is what makes it worth testing against: the 422 terminal's pagination, its stock badges and its history list never see that 423 much data on a stack the harness builds itself. Nothing here modifies 424 anybody else's data beyond adding orders and refunds of its own. 425 """ 426 m = Merchant(instance=instance, secret=secret) 427 token = m.mint_token(seconds=seconds) 428 cfg = m.config() 429 return Instance(merchant=m, token=token, currency=cfg["currency"], 430 label=f"demo/{instance}") 431 432 433 if __name__ == "__main__": 434 import sys 435 want = sys.argv[1] if len(sys.argv) > 1 else "info" 436 inst = demo() 437 if want == "info": 438 print(f"{inst.label}: {inst.currency}, {inst.token}") 439 print(f" backend {inst.merchant.backend_version()}") 440 print(f" pos url {inst.merchant.pos_url()}") 441 pos = inst.merchant.pos_config(inst.token.value) 442 print(f" products {len(pos.get('products', []))}" 443 f" categories {len(pos.get('categories', []))}") 444 print(f" accounts {len(inst.merchant.accounts(inst.token.value))}") 445 print(f" history {len(inst.merchant.history(inst.token.value, limit=-5))} of the last 5") 446 elif want == "uri": 447 print(inst.setup_uri())