askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
object_exchange.py · 30.9 KB · 724 lines
| 1 | """object_exchange -- signed business documents between boxes: the primitives. |
| 2 | |
| 3 | One company's box sends a purchase order, an invoice or a remittance to |
| 4 | another company's box; the receiver checks who sent it and that nothing in |
| 5 | it changed, stores it verbatim and answers with a signed receipt |
| 6 | (docs/box-to-box-exchange.md). This module is the part of that which has |
| 7 | no opinion about collections: the canonical bytes a signature covers, the |
| 8 | envelope's shape, Ed25519 signing and verification, the box's private key |
| 9 | files, and the transport. object_exchange_box does the reading and writing |
| 10 | of records and calls this. |
| 11 | |
| 12 | ## Why the crypto is an extra, and how its absence looks |
| 13 | |
| 14 | The platform core is dependency-free (pyproject `dependencies = []`), and |
| 15 | Ed25519 is not in the standard library. So `cryptography` is the |
| 16 | `exchange` extra, imported here and nowhere else -- inside the functions |
| 17 | that need it, never at module load, so importing this module (and the |
| 18 | whole server) works on a box without it. A box without it does not stub |
| 19 | the exchange (AGENTS.md "a capability that is absent must refuse"): every |
| 20 | signing or verifying call raises ExchangeUnavailable, whose message names |
| 21 | exactly what to install, and the package objects answer 409 with that |
| 22 | message. tests/test_exchange_core.py pins both the refusal and the rule |
| 23 | that no other module imports `cryptography`. |
| 24 | |
| 25 | ## The canonical serialisation, exactly |
| 26 | |
| 27 | A signature covers bytes, and two boxes must produce the same bytes from |
| 28 | the same document. The canonical form of a JSON value here is: |
| 29 | |
| 30 | json.dumps(value, sort_keys=True, separators=(",", ":"), |
| 31 | ensure_ascii=False, allow_nan=False).encode("utf-8") |
| 32 | |
| 33 | that is: object keys sorted, no whitespace anywhere, strings as UTF-8 |
| 34 | (not \\u escapes, except the control characters JSON requires escaping), |
| 35 | and with two refusals that make it unambiguous: |
| 36 | |
| 37 | - **No floats, anywhere.** Money is an integer in minor units (AGENTS.md |
| 38 | #10) and a quantity is a decimal STRING ("1.5"), so a float in a |
| 39 | document is a mistake, and floats are where two JSON libraries disagree |
| 40 | about bytes (1e2 vs 100.0). Refused, not converted. |
| 41 | - **Object keys are ASCII.** Python sorts keys by code point and RFC 8785 |
| 42 | (JCS) by UTF-16 code unit; the two orders differ only for keys outside |
| 43 | the Basic Multilingual Plane. Every key this format defines is ASCII, so |
| 44 | refusing the rest makes this byte-for-byte JCS for every valid document, |
| 45 | and a second implementation in another language can use a JCS library. |
| 46 | |
| 47 | Values may be any Unicode; integers are written as plain decimal; true, |
| 48 | false and null as themselves. |
| 49 | |
| 50 | ## Three signed things, kept apart |
| 51 | |
| 52 | The same key signs three kinds of message, and each carries its own marker |
| 53 | key so a signature over one can never be presented as another: |
| 54 | |
| 55 | - the **envelope** (`dron_document`): the document itself, signed once |
| 56 | when it is made, kept forever by both sides. Detached: the signature |
| 57 | sits beside the envelope, not inside it, so what is signed is exactly |
| 58 | the envelope's canonical bytes. |
| 59 | - the **delivery** (`dron_delivery`): who is sending which envelope (by |
| 60 | hash) to whom, and when -- signed afresh on every attempt. The receiver |
| 61 | refuses a delivery stamped outside its clock window, which is what |
| 62 | stops a captured request from being replayed later, while the document |
| 63 | itself can be days old (a partner that was down for a day still gets |
| 64 | the order; the retry is a new delivery of the same envelope). |
| 65 | - the **receipt** (`dron_receipt`): the receiver saying it stored this |
| 66 | envelope (by hash) at this time. Signed by the receiver; the sender |
| 67 | verifies it against the receiver's pinned key and keeps it. |
| 68 | |
| 69 | A fourth, the **key vouch** (`dron_key_vouch`), is the old key saying the |
| 70 | new key is ours after a rotation; see vouch_message. |
| 71 | |
| 72 | ## Keys |
| 73 | |
| 74 | The box's Ed25519 private keys live under `<data dir>/exchange/private/`, |
| 75 | one file per key (`<hex>.key`, PKCS#8 PEM, unencrypted), the directory |
| 76 | 0700 and each file created 0600 with O_EXCL so it is never world-readable |
| 77 | even for an instant. That directory is outside every directory a runtime |
| 78 | backup copies (object_backup.RUNTIME_DATA_DIRS), so no backup holds a |
| 79 | private key; the public halves are records (exchange_keys) and are backed |
| 80 | up. A restored box therefore has its public keys and not its private ones, |
| 81 | and says so (the profile refuses until the key file is put back or the |
| 82 | key rotated) rather than signing with something it does not have. Nothing |
| 83 | here logs, returns or serialises a private key. |
| 84 | |
| 85 | A key id is `ed25519:` plus the first 16 hex characters of the SHA-256 of |
| 86 | the raw 32-byte public key: derived, so it cannot be claimed for a |
| 87 | different key. |
| 88 | """ |
| 89 | |
| 90 | from __future__ import annotations |
| 91 | |
| 92 | import base64 |
| 93 | import hashlib |
| 94 | import json |
| 95 | import os |
| 96 | import re |
| 97 | import urllib.error |
| 98 | import urllib.parse |
| 99 | import urllib.request |
| 100 | from datetime import datetime, timedelta, timezone |
| 101 | from decimal import Decimal, InvalidOperation |
| 102 | from pathlib import Path |
| 103 | from typing import Any, Callable, Mapping |
| 104 | |
| 105 | DRON_DOCUMENT_VERSION = "0.1" |
| 106 | PROFILE_VERSION = "0.1" |
| 107 | |
| 108 | DOCUMENT_TYPES = ( |
| 109 | "purchase_order", |
| 110 | "order_confirmation", |
| 111 | "invoice", |
| 112 | "credit_note", |
| 113 | "remittance", |
| 114 | "receipt", |
| 115 | ) |
| 116 | # Messages about the relationship itself, never business documents: they |
| 117 | # are not stored in the inbox and not mapped. connection_end says the sender |
| 118 | # ended the relationship (the receiver records the partner disconnected); |
| 119 | # document_refusal says a person at the sender refused a document the |
| 120 | # receiver delivered, naming it by id and envelope hash. |
| 121 | CONTROL_TYPES = ("connection_request", "connection_accept", "connection_end", |
| 122 | "document_refusal") |
| 123 | |
| 124 | # How a confirmation answers one line of the order (UBL LineStatusCode / |
| 125 | # OrderResponse LineResponse): as asked, changed (quantity, unit or price), |
| 126 | # not supplied (sent with quantity 0), or a line the buyer did not ask for. |
| 127 | LINE_STATUSES = ("accepted", "changed", "rejected", "added") |
| 128 | |
| 129 | ALG = "ed25519" |
| 130 | EXTRA_HINT = ( |
| 131 | "Box-to-box exchange needs the `cryptography` package for Ed25519: " |
| 132 | "install dbbasic-object-server[exchange] (pip install " |
| 133 | "'dbbasic-object-server[exchange]') and restart the server." |
| 134 | ) |
| 135 | |
| 136 | KEYS_DIR = "exchange" |
| 137 | PRIVATE_DIR = "private" |
| 138 | |
| 139 | # The largest document a box accepts. A purchase order of a few hundred |
| 140 | # lines is tens of kilobytes; anything near this is a mistake or abuse, |
| 141 | # and it is refused before it is parsed. |
| 142 | MAX_DOCUMENT_BYTES = 512 * 1024 |
| 143 | MAX_RESPONSE_BYTES = 1024 * 1024 |
| 144 | # How far a delivery's stamp may be from our clock, either way. |
| 145 | DEFAULT_CLOCK_WINDOW_SECONDS = 300 |
| 146 | CLOCK_WINDOW_ENV = "DBBASIC_EXCHANGE_CLOCK_WINDOW_SECONDS" |
| 147 | TRANSPORT_TIMEOUT_SECONDS = 20 |
| 148 | |
| 149 | _ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$") |
| 150 | _DOMAIN_RE = re.compile( |
| 151 | r"^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$") |
| 152 | _CURRENCY_RE = re.compile(r"^[A-Z]{3}$") |
| 153 | _DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") |
| 154 | _STAMP_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$") |
| 155 | _UNIT_RE = re.compile(r"^[A-Z0-9]{1,3}$") |
| 156 | |
| 157 | |
| 158 | # --- units of measure -------------------------------------------------------- |
| 159 | # |
| 160 | # Every priced line says what its quantity counts, as a UN/ECE |
| 161 | # Recommendation 20 code (UBL `@unitCode`, EN 16931 BT-130). Phase 0 sent |
| 162 | # every line as C62 ("one"), so ten kilograms and ten bags of coffee arrived |
| 163 | # as the same "10": the receiving box could not tell what it had been sold. |
| 164 | # The codes below are the ones a small trading business meets; a document |
| 165 | # may carry any code of the right shape (Rec 20 has some two thousand, and |
| 166 | # a partner's engine may use one we do not list), but a box only ever MAKES |
| 167 | # one from this table, so what it sends is a code it can name. |
| 168 | # |
| 169 | # Rec 20 revision 3 onwards includes the Rec 21 package codes with an "X" |
| 170 | # prefix (XBG bag, XBX box): a bag of beans is a package, not a measure. |
| 171 | UNIT_NAMES = { |
| 172 | "C62": "one", "H87": "piece", "EA": "each", "PR": "pair", "SET": "set", |
| 173 | "DZN": "dozen", |
| 174 | "KGM": "kilogram", "GRM": "gram", "TNE": "tonne", "LBR": "pound", "ONZ": "ounce", |
| 175 | "LTR": "litre", "MLT": "millilitre", "GLL": "US gallon", |
| 176 | "MTR": "metre", "CMT": "centimetre", "MMT": "millimetre", "MTK": "square metre", |
| 177 | "MTQ": "cubic metre", |
| 178 | "HUR": "hour", "MIN": "minute", "DAY": "day", "WEE": "week", "MON": "month", |
| 179 | "ANN": "year", |
| 180 | "XBG": "bag", "XBX": "box", "XCS": "case", "XBO": "bottle", "XCT": "carton", |
| 181 | "XPK": "package", "XPA": "packet", "XSA": "sack", "XCR": "crate", "XTN": "tin", |
| 182 | "XPX": "pallet", |
| 183 | } |
| 184 | # What people type in a product's free-text `unit` ("kg", "Bags", "each"). |
| 185 | _UNIT_WORDS = { |
| 186 | "one": "C62", "unit": "C62", "units": "C62", "count": "C62", |
| 187 | "piece": "H87", "pieces": "H87", "pc": "H87", "pcs": "H87", |
| 188 | "each": "EA", "ea": "EA", "item": "EA", "items": "EA", |
| 189 | "pair": "PR", "pairs": "PR", "set": "SET", "sets": "SET", "dozen": "DZN", "doz": "DZN", |
| 190 | "kg": "KGM", "kgs": "KGM", "kilo": "KGM", "kilos": "KGM", "kilogram": "KGM", |
| 191 | "kilograms": "KGM", "kilogramme": "KGM", "kilogrammes": "KGM", |
| 192 | "g": "GRM", "gr": "GRM", "gram": "GRM", "grams": "GRM", "gramme": "GRM", |
| 193 | "grammes": "GRM", |
| 194 | "t": "TNE", "tonne": "TNE", "tonnes": "TNE", |
| 195 | "lb": "LBR", "lbs": "LBR", "pound": "LBR", "pounds": "LBR", |
| 196 | "oz": "ONZ", "ounce": "ONZ", "ounces": "ONZ", |
| 197 | "l": "LTR", "lt": "LTR", "ltr": "LTR", "litre": "LTR", "litres": "LTR", "liter": "LTR", |
| 198 | "liters": "LTR", |
| 199 | "ml": "MLT", "millilitre": "MLT", "millilitres": "MLT", "milliliter": "MLT", |
| 200 | "milliliters": "MLT", |
| 201 | "gal": "GLL", "gallon": "GLL", "gallons": "GLL", |
| 202 | "m": "MTR", "metre": "MTR", "metres": "MTR", "meter": "MTR", "meters": "MTR", |
| 203 | "cm": "CMT", "mm": "MMT", "m2": "MTK", "sqm": "MTK", "m3": "MTQ", |
| 204 | "h": "HUR", "hr": "HUR", "hrs": "HUR", "hour": "HUR", "hours": "HUR", |
| 205 | "min": "MIN", "mins": "MIN", "minute": "MIN", "minutes": "MIN", |
| 206 | "day": "DAY", "days": "DAY", "week": "WEE", "weeks": "WEE", |
| 207 | "month": "MON", "months": "MON", "year": "ANN", "years": "ANN", |
| 208 | "bag": "XBG", "bags": "XBG", "box": "XBX", "boxes": "XBX", "case": "XCS", |
| 209 | "cases": "XCS", "bottle": "XBO", "bottles": "XBO", "carton": "XCT", "cartons": "XCT", |
| 210 | "package": "XPK", "packages": "XPK", "pack": "XPK", "packs": "XPK", |
| 211 | "packet": "XPA", "packets": "XPA", "sack": "XSA", "sacks": "XSA", |
| 212 | "crate": "XCR", "crates": "XCR", "tin": "XTN", "tins": "XTN", "can": "XTN", |
| 213 | "cans": "XTN", "pallet": "XPX", "pallets": "XPX", |
| 214 | } |
| 215 | DEFAULT_UNIT_CODE = "C62" |
| 216 | |
| 217 | |
| 218 | def valid_unit_code(value: Any) -> bool: |
| 219 | """The shape of a Rec 20 code: one to three upper-case letters or digits.""" |
| 220 | return isinstance(value, str) and bool(_UNIT_RE.match(value)) |
| 221 | |
| 222 | |
| 223 | def unit_code_for(text: Any) -> str | None: |
| 224 | """The Rec 20 code for what somebody typed as a unit ("kg", "Bags", |
| 225 | "KGM"), or None when it is not one this box can name. Never a guess: |
| 226 | an unknown unit is a question for a person, because sending "10" of the |
| 227 | wrong thing is the mistake units exist to prevent.""" |
| 228 | raw = str(text if text is not None else "").strip() |
| 229 | if not raw: |
| 230 | return None |
| 231 | if raw.upper() in UNIT_NAMES: |
| 232 | return raw.upper() |
| 233 | return _UNIT_WORDS.get(raw.lower().rstrip(".")) |
| 234 | |
| 235 | |
| 236 | class ExchangeUnavailable(RuntimeError): |
| 237 | """The `exchange` extra is not installed; the message says what to do.""" |
| 238 | |
| 239 | |
| 240 | class CanonicalError(ValueError): |
| 241 | """A value that has no canonical form here (a float, a non-ASCII key).""" |
| 242 | |
| 243 | |
| 244 | class EnvelopeError(ValueError): |
| 245 | """A document that is not well formed. `problems` lists every reason.""" |
| 246 | |
| 247 | def __init__(self, problems: list[str]): |
| 248 | super().__init__("; ".join(problems)) |
| 249 | self.problems = problems |
| 250 | |
| 251 | |
| 252 | class TransportError(RuntimeError): |
| 253 | """The partner could not be reached (no answer at all).""" |
| 254 | |
| 255 | |
| 256 | # --- the optional dependency ------------------------------------------------- |
| 257 | |
| 258 | def _ed25519(): |
| 259 | """The `cryptography` Ed25519 and serialization modules, or refuse.""" |
| 260 | try: |
| 261 | from cryptography.hazmat.primitives import serialization |
| 262 | from cryptography.hazmat.primitives.asymmetric import ed25519 |
| 263 | except ImportError as exc: |
| 264 | raise ExchangeUnavailable(EXTRA_HINT) from exc |
| 265 | return ed25519, serialization |
| 266 | |
| 267 | |
| 268 | def available() -> bool: |
| 269 | try: |
| 270 | _ed25519() |
| 271 | except ExchangeUnavailable: |
| 272 | return False |
| 273 | return True |
| 274 | |
| 275 | |
| 276 | # --- canonical bytes ----------------------------------------------------------- |
| 277 | |
| 278 | def _check_canonicalisable(value: Any, path: str = "$") -> None: |
| 279 | if isinstance(value, float): |
| 280 | raise CanonicalError(f"{path}: floats have no canonical form here " |
| 281 | f"(money is integer minor units, quantities are strings)") |
| 282 | if isinstance(value, Mapping): |
| 283 | for key, item in value.items(): |
| 284 | if not isinstance(key, str): |
| 285 | raise CanonicalError(f"{path}: object keys must be strings") |
| 286 | if not key.isascii(): |
| 287 | raise CanonicalError(f"{path}: object key {key!r} is not ASCII") |
| 288 | _check_canonicalisable(item, f"{path}.{key}") |
| 289 | elif isinstance(value, (list, tuple)): |
| 290 | for index, item in enumerate(value): |
| 291 | _check_canonicalisable(item, f"{path}[{index}]") |
| 292 | elif value is None or isinstance(value, (str, int, bool)): |
| 293 | return |
| 294 | else: |
| 295 | raise CanonicalError(f"{path}: {type(value).__name__} is not a JSON value") |
| 296 | |
| 297 | |
| 298 | def canonical(value: Any) -> bytes: |
| 299 | """The exact bytes a signature covers (see the module docstring).""" |
| 300 | _check_canonicalisable(value) |
| 301 | return json.dumps(value, sort_keys=True, separators=(",", ":"), |
| 302 | ensure_ascii=False, allow_nan=False).encode("utf-8") |
| 303 | |
| 304 | |
| 305 | def sha256_hex(data: bytes) -> str: |
| 306 | return hashlib.sha256(data).hexdigest() |
| 307 | |
| 308 | |
| 309 | def b64u(data: bytes) -> str: |
| 310 | return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") |
| 311 | |
| 312 | |
| 313 | def unb64u(text: str) -> bytes: |
| 314 | text = str(text or "") |
| 315 | return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)) |
| 316 | |
| 317 | |
| 318 | def key_id_for(public_raw: bytes) -> str: |
| 319 | return "ed25519:" + sha256_hex(public_raw)[:16] |
| 320 | |
| 321 | |
| 322 | # --- time -------------------------------------------------------------------- |
| 323 | |
| 324 | def utc_stamp(now: datetime | None = None) -> str: |
| 325 | """One spelling of an instant: `YYYY-MM-DDTHH:MM:SSZ` (AGENTS.md: two |
| 326 | spellings of the same instant do not compare equal).""" |
| 327 | now = now or datetime.now(timezone.utc) |
| 328 | return now.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") |
| 329 | |
| 330 | |
| 331 | def parse_stamp(text: Any) -> datetime | None: |
| 332 | text = str(text or "") |
| 333 | if not _STAMP_RE.match(text): |
| 334 | return None |
| 335 | try: |
| 336 | return datetime.strptime(text, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) |
| 337 | except ValueError: |
| 338 | return None |
| 339 | |
| 340 | |
| 341 | def clock_window_seconds() -> int: |
| 342 | try: |
| 343 | value = int(os.environ.get(CLOCK_WINDOW_ENV, "") or DEFAULT_CLOCK_WINDOW_SECONDS) |
| 344 | except ValueError: |
| 345 | return DEFAULT_CLOCK_WINDOW_SECONDS |
| 346 | return value if value > 0 else DEFAULT_CLOCK_WINDOW_SECONDS |
| 347 | |
| 348 | |
| 349 | def within_window(stamp: Any, now: datetime | None = None, |
| 350 | window_seconds: int | None = None) -> bool: |
| 351 | when = parse_stamp(stamp) |
| 352 | if when is None: |
| 353 | return False |
| 354 | now = now or datetime.now(timezone.utc) |
| 355 | window = timedelta(seconds=window_seconds or clock_window_seconds()) |
| 356 | return abs(now - when) <= window |
| 357 | |
| 358 | |
| 359 | # --- names ------------------------------------------------------------------- |
| 360 | |
| 361 | def valid_domain(value: Any) -> bool: |
| 362 | """A lower-case DNS name with at least one dot: the company's identity. |
| 363 | IP literals and bare hosts are refused; a box is its domain.""" |
| 364 | text = str(value or "") |
| 365 | return bool(_DOMAIN_RE.match(text)) and not text.replace(".", "").isdigit() |
| 366 | |
| 367 | |
| 368 | def valid_id(value: Any) -> bool: |
| 369 | return isinstance(value, str) and bool(_ID_RE.match(value)) |
| 370 | |
| 371 | |
| 372 | def endpoint_for(domain: str) -> str: |
| 373 | return f"https://{domain}/webhooks/exchange" |
| 374 | |
| 375 | |
| 376 | def profile_url(domain: str) -> str: |
| 377 | return f"https://{domain}/.well-known/dbbasic" |
| 378 | |
| 379 | |
| 380 | def endpoint_on_domain(endpoint: Any, domain: str) -> bool: |
| 381 | """A partner's endpoint must be https on its own domain: a profile that |
| 382 | pointed our deliveries somewhere else would make us post documents to |
| 383 | a host nobody pinned.""" |
| 384 | try: |
| 385 | parts = urllib.parse.urlsplit(str(endpoint or "")) |
| 386 | except ValueError: |
| 387 | return False |
| 388 | return parts.scheme == "https" and parts.hostname == domain and not parts.username |
| 389 | |
| 390 | |
| 391 | # --- the envelope ---------------------------------------------------------------- |
| 392 | |
| 393 | def _is_int(value: Any) -> bool: |
| 394 | return isinstance(value, int) and not isinstance(value, bool) |
| 395 | |
| 396 | |
| 397 | def _decimal_string(value: Any) -> bool: |
| 398 | if not isinstance(value, str) or not value.strip(): |
| 399 | return False |
| 400 | try: |
| 401 | number = Decimal(value) |
| 402 | except InvalidOperation: |
| 403 | return False |
| 404 | return number.is_finite() |
| 405 | |
| 406 | |
| 407 | def _check_money(body: Mapping[str, Any], key: str, problems: list[str], where: str, |
| 408 | required: bool = True) -> None: |
| 409 | if key not in body: |
| 410 | if required: |
| 411 | problems.append(f"{where}.{key} is required") |
| 412 | return |
| 413 | if not _is_int(body[key]): |
| 414 | problems.append(f"{where}.{key} must be an integer in minor units") |
| 415 | |
| 416 | |
| 417 | def _check_lines(lines: Any, problems: list[str], *, priced: bool, quantity_key: str) -> None: |
| 418 | if not isinstance(lines, list) or not lines: |
| 419 | problems.append("body.lines must be a non-empty list") |
| 420 | return |
| 421 | seen = set() |
| 422 | for index, line in enumerate(lines): |
| 423 | where = f"body.lines[{index}]" |
| 424 | if not isinstance(line, Mapping): |
| 425 | problems.append(f"{where} must be an object") |
| 426 | continue |
| 427 | line_id = line.get("line_id") |
| 428 | if not isinstance(line_id, str) or not line_id: |
| 429 | problems.append(f"{where}.line_id is required") |
| 430 | elif line_id in seen: |
| 431 | problems.append(f"{where}.line_id {line_id!r} repeats") |
| 432 | seen.add(line_id) |
| 433 | if not isinstance(line.get("description"), str) or not line["description"].strip(): |
| 434 | problems.append(f"{where}.description is required") |
| 435 | if not _decimal_string(line.get(quantity_key)): |
| 436 | problems.append(f"{where}.{quantity_key} must be a decimal string") |
| 437 | if "unit_code" in line and not _UNIT_RE.match(str(line["unit_code"])): |
| 438 | problems.append(f"{where}.unit_code must be a UN/ECE Rec 20 code") |
| 439 | if "ref_line_id" in line and not valid_id(line["ref_line_id"]): |
| 440 | problems.append(f"{where}.ref_line_id must name a line of the document answered") |
| 441 | if "line_status" in line and line["line_status"] not in LINE_STATUSES: |
| 442 | problems.append(f"{where}.line_status must be one of {', '.join(LINE_STATUSES)}") |
| 443 | if priced: |
| 444 | _check_money(line, "unit_price_minor", problems, where) |
| 445 | _check_money(line, "line_extension_minor", problems, where) |
| 446 | if "tax_rate_bps" in line and not _is_int(line["tax_rate_bps"]): |
| 447 | problems.append(f"{where}.tax_rate_bps must be an integer") |
| 448 | |
| 449 | |
| 450 | # The same shape, as a JSON Schema another engine can read: |
| 451 | # dron/dron-document.schema.json (tests/test_dron_schema.py holds the two together). |
| 452 | def validate_envelope(envelope: Any) -> None: |
| 453 | """Raise EnvelopeError listing everything wrong with a document, or |
| 454 | return None. Pure; it judges shape and types, not whether the sender |
| 455 | may send it or whether we know the documents it refers to.""" |
| 456 | problems: list[str] = [] |
| 457 | if not isinstance(envelope, Mapping): |
| 458 | raise EnvelopeError(["the envelope must be a JSON object"]) |
| 459 | if envelope.get("dron_document") != DRON_DOCUMENT_VERSION: |
| 460 | problems.append(f"dron_document must be {DRON_DOCUMENT_VERSION!r}") |
| 461 | if not valid_id(envelope.get("id")): |
| 462 | problems.append("id must be 1-128 characters of A-Z a-z 0-9 . _ : -") |
| 463 | doc_type = envelope.get("type") |
| 464 | if doc_type not in DOCUMENT_TYPES + CONTROL_TYPES: |
| 465 | problems.append(f"type must be one of {', '.join(DOCUMENT_TYPES)}") |
| 466 | for key in ("sender", "recipient"): |
| 467 | if not valid_domain(envelope.get(key)): |
| 468 | problems.append(f"{key} must be a domain name") |
| 469 | if parse_stamp(envelope.get("created_at")) is None: |
| 470 | problems.append("created_at must be a UTC time written YYYY-MM-DDTHH:MM:SSZ") |
| 471 | refs = envelope.get("refs", []) |
| 472 | if not isinstance(refs, list): |
| 473 | problems.append("refs must be a list") |
| 474 | else: |
| 475 | for index, ref in enumerate(refs): |
| 476 | if not (isinstance(ref, Mapping) and valid_id(ref.get("id")) |
| 477 | and ref.get("type") in DOCUMENT_TYPES): |
| 478 | problems.append(f"refs[{index}] must be {{id, type}} naming an earlier document") |
| 479 | body = envelope.get("body") |
| 480 | if not isinstance(body, Mapping): |
| 481 | problems.append("body must be an object") |
| 482 | raise EnvelopeError(problems) |
| 483 | allowed = {"dron_document", "id", "type", "sender", "recipient", "created_at", "refs", "body"} |
| 484 | extra = sorted(set(envelope) - allowed) |
| 485 | if extra: |
| 486 | problems.append(f"unknown envelope keys: {', '.join(extra)}") |
| 487 | |
| 488 | if doc_type in ("purchase_order", "order_confirmation", "invoice", "credit_note"): |
| 489 | if not isinstance(body.get("number"), str) or not body["number"].strip(): |
| 490 | problems.append("body.number is required") |
| 491 | if not _DATE_RE.match(str(body.get("issue_date") or "")): |
| 492 | problems.append("body.issue_date must be YYYY-MM-DD") |
| 493 | if not _CURRENCY_RE.match(str(body.get("currency") or "")): |
| 494 | problems.append("body.currency must be an ISO 4217 code") |
| 495 | _check_lines(body.get("lines"), problems, priced=True, quantity_key="quantity") |
| 496 | totals = body.get("totals") |
| 497 | if not isinstance(totals, Mapping): |
| 498 | problems.append("body.totals is required") |
| 499 | else: |
| 500 | for key in ("line_extension_minor", "tax_minor", "payable_minor"): |
| 501 | _check_money(totals, key, problems, "body.totals") |
| 502 | if doc_type == "order_confirmation" and body.get("response") not in ( |
| 503 | "accepted", "rejected", "amended"): |
| 504 | problems.append("body.response must be accepted, rejected or amended") |
| 505 | if "due_date" in body and not _DATE_RE.match(str(body["due_date"])): |
| 506 | problems.append("body.due_date must be YYYY-MM-DD") |
| 507 | elif doc_type == "remittance": |
| 508 | if not _CURRENCY_RE.match(str(body.get("currency") or "")): |
| 509 | problems.append("body.currency must be an ISO 4217 code") |
| 510 | _check_money(body, "paid_minor", problems, "body") |
| 511 | if not _DATE_RE.match(str(body.get("paid_on") or "")): |
| 512 | problems.append("body.paid_on must be YYYY-MM-DD") |
| 513 | settles = body.get("settles") |
| 514 | if not isinstance(settles, list) or not settles: |
| 515 | problems.append("body.settles must list the invoices paid") |
| 516 | else: |
| 517 | total = 0 |
| 518 | for index, item in enumerate(settles): |
| 519 | where = f"body.settles[{index}]" |
| 520 | if not isinstance(item, Mapping) or not valid_id(item.get("document_id")): |
| 521 | problems.append(f"{where}.document_id is required") |
| 522 | continue |
| 523 | _check_money(item, "amount_minor", problems, where) |
| 524 | if _is_int(item.get("amount_minor")): |
| 525 | total += item["amount_minor"] |
| 526 | if _is_int(body.get("paid_minor")) and total != body["paid_minor"]: |
| 527 | problems.append("body.paid_minor must equal the sum of body.settles amounts") |
| 528 | elif doc_type == "connection_end": |
| 529 | if "reason" in body and not isinstance(body["reason"], str): |
| 530 | problems.append("body.reason must be text") |
| 531 | elif doc_type == "document_refusal": |
| 532 | if not valid_id(body.get("document_id")): |
| 533 | problems.append("body.document_id must name the refused document") |
| 534 | if not re.fullmatch(r"[0-9a-f]{64}", str(body.get("envelope_sha256") or "")): |
| 535 | problems.append("body.envelope_sha256 must be the refused envelope's SHA-256") |
| 536 | if not isinstance(body.get("reason"), str) or not body["reason"].strip(): |
| 537 | problems.append("body.reason is required") |
| 538 | elif doc_type == "receipt": |
| 539 | if not _DATE_RE.match(str(body.get("received_on") or "")): |
| 540 | problems.append("body.received_on must be YYYY-MM-DD") |
| 541 | _check_lines(body.get("lines"), problems, priced=False, quantity_key="quantity_received") |
| 542 | if problems: |
| 543 | raise EnvelopeError(problems) |
| 544 | |
| 545 | |
| 546 | def new_envelope(*, doc_id: str, doc_type: str, sender: str, recipient: str, |
| 547 | body: Mapping[str, Any], refs: list[Mapping[str, str]] | None = None, |
| 548 | created_at: str | None = None) -> dict[str, Any]: |
| 549 | envelope = { |
| 550 | "dron_document": DRON_DOCUMENT_VERSION, |
| 551 | "id": doc_id, |
| 552 | "type": doc_type, |
| 553 | "sender": sender, |
| 554 | "recipient": recipient, |
| 555 | "created_at": created_at or utc_stamp(), |
| 556 | "refs": [dict(ref) for ref in (refs or [])], |
| 557 | "body": dict(body), |
| 558 | } |
| 559 | validate_envelope(envelope) |
| 560 | return envelope |
| 561 | |
| 562 | |
| 563 | def delivery_message(delivery: Mapping[str, Any]) -> bytes: |
| 564 | return canonical({"dron_delivery": DRON_DOCUMENT_VERSION, **delivery}) |
| 565 | |
| 566 | |
| 567 | def receipt_message(receipt: Mapping[str, Any]) -> bytes: |
| 568 | return canonical(receipt) |
| 569 | |
| 570 | |
| 571 | def vouch_message(key_id: str, public_key: str) -> bytes: |
| 572 | return canonical({"dron_key_vouch": DRON_DOCUMENT_VERSION, |
| 573 | "key_id": key_id, "public_key": public_key}) |
| 574 | |
| 575 | |
| 576 | def profile_message(profile: Mapping[str, Any]) -> bytes: |
| 577 | return canonical({k: v for k, v in profile.items() if k != "signature"}) |
| 578 | |
| 579 | |
| 580 | # --- keys -------------------------------------------------------------------------- |
| 581 | |
| 582 | def private_dir(base_dir: Path | str) -> Path: |
| 583 | return Path(base_dir) / KEYS_DIR / PRIVATE_DIR |
| 584 | |
| 585 | |
| 586 | def _private_path(base_dir: Path | str, key_id: str) -> Path: |
| 587 | if not key_id.startswith("ed25519:") or not re.fullmatch(r"[0-9a-f]{16}", key_id[8:]): |
| 588 | raise ValueError("not a key id") |
| 589 | return private_dir(base_dir) / f"{key_id[8:]}.key" |
| 590 | |
| 591 | |
| 592 | def generate_key(base_dir: Path | str) -> tuple[str, str]: |
| 593 | """Make a new Ed25519 key pair, write the private half 0600 under the |
| 594 | data dir, and return (key_id, public key base64url). Never returns the |
| 595 | private half.""" |
| 596 | ed25519, serialization = _ed25519() |
| 597 | private = ed25519.Ed25519PrivateKey.generate() |
| 598 | public_raw = private.public_key().public_bytes( |
| 599 | serialization.Encoding.Raw, serialization.PublicFormat.Raw) |
| 600 | key_id = key_id_for(public_raw) |
| 601 | folder = private_dir(base_dir) |
| 602 | folder.mkdir(parents=True, exist_ok=True) |
| 603 | os.chmod(folder.parent, 0o700) |
| 604 | os.chmod(folder, 0o700) |
| 605 | pem = private.private_bytes(serialization.Encoding.PEM, |
| 606 | serialization.PrivateFormat.PKCS8, |
| 607 | serialization.NoEncryption()) |
| 608 | fd = os.open(_private_path(base_dir, key_id), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) |
| 609 | try: |
| 610 | os.write(fd, pem) |
| 611 | os.fsync(fd) |
| 612 | finally: |
| 613 | os.close(fd) |
| 614 | return key_id, b64u(public_raw) |
| 615 | |
| 616 | |
| 617 | def has_private_key(base_dir: Path | str, key_id: str) -> bool: |
| 618 | try: |
| 619 | return _private_path(base_dir, key_id).is_file() |
| 620 | except ValueError: |
| 621 | return False |
| 622 | |
| 623 | |
| 624 | def destroy_private_key(base_dir: Path | str, key_id: str) -> None: |
| 625 | """A retired key signs nothing more, so its private half is removed: |
| 626 | what is not kept cannot leak. Its public half stays listed, so what it |
| 627 | signed still verifies.""" |
| 628 | try: |
| 629 | _private_path(base_dir, key_id).unlink() |
| 630 | except (FileNotFoundError, ValueError): |
| 631 | pass |
| 632 | |
| 633 | |
| 634 | def sign(base_dir: Path | str, key_id: str, message: bytes) -> dict[str, str]: |
| 635 | """A detached signature: {alg, key_id, value}.""" |
| 636 | ed25519, serialization = _ed25519() |
| 637 | path = _private_path(base_dir, key_id) |
| 638 | try: |
| 639 | pem = path.read_bytes() |
| 640 | except FileNotFoundError as exc: |
| 641 | raise KeyError(f"the private key for {key_id} is not on this box") from exc |
| 642 | private = serialization.load_pem_private_key(pem, password=None) |
| 643 | if not isinstance(private, ed25519.Ed25519PrivateKey): |
| 644 | raise KeyError(f"{key_id} is not an Ed25519 key") |
| 645 | return {"alg": ALG, "key_id": key_id, "value": b64u(private.sign(message))} |
| 646 | |
| 647 | |
| 648 | def verify(public_key: str, message: bytes, signature: Any) -> bool: |
| 649 | """True only for a well-formed Ed25519 signature by this public key over |
| 650 | exactly these bytes. Anything malformed is False, never an exception |
| 651 | (except ExchangeUnavailable: no crypto is not "a bad signature").""" |
| 652 | ed25519, _ = _ed25519() |
| 653 | if not isinstance(signature, Mapping) or signature.get("alg") != ALG: |
| 654 | return False |
| 655 | try: |
| 656 | raw = unb64u(public_key) |
| 657 | sig = unb64u(signature.get("value")) |
| 658 | if len(raw) != 32 or len(sig) != 64: |
| 659 | return False |
| 660 | if key_id_for(raw) != signature.get("key_id"): |
| 661 | return False |
| 662 | ed25519.Ed25519PublicKey.from_public_bytes(raw).verify(sig, message) |
| 663 | except Exception as exc: # InvalidSignature, binascii errors, ValueError |
| 664 | if isinstance(exc, ExchangeUnavailable): |
| 665 | raise |
| 666 | return False |
| 667 | return True |
| 668 | |
| 669 | |
| 670 | # --- transport --------------------------------------------------------------------- |
| 671 | |
| 672 | Transport = Callable[[str, str, bytes, Mapping[str, str]], "tuple[int, bytes]"] |
| 673 | _transport: Transport | None = None |
| 674 | |
| 675 | |
| 676 | class _NoRedirect(urllib.request.HTTPRedirectHandler): |
| 677 | """A redirect is refused, not followed: a partner's endpoint is pinned to |
| 678 | its own domain, and following a 30x would post the document wherever the |
| 679 | redirect said.""" |
| 680 | |
| 681 | def redirect_request(self, *args, **kwargs): # noqa: D401 |
| 682 | return None |
| 683 | |
| 684 | |
| 685 | def urllib_transport(method: str, url: str, body: bytes, |
| 686 | headers: Mapping[str, str]) -> tuple[int, bytes]: |
| 687 | """The production transport: HTTPS with certificate verification |
| 688 | (urllib's default context), no redirects, a timeout, a size cap.""" |
| 689 | if urllib.parse.urlsplit(url).scheme != "https": |
| 690 | raise TransportError("exchange transport is https only") |
| 691 | request = urllib.request.Request(url, data=body if method != "GET" else None, |
| 692 | method=method, headers=dict(headers)) |
| 693 | opener = urllib.request.build_opener(_NoRedirect) |
| 694 | try: |
| 695 | with opener.open(request, timeout=TRANSPORT_TIMEOUT_SECONDS) as response: |
| 696 | return response.status, response.read(MAX_RESPONSE_BYTES + 1)[:MAX_RESPONSE_BYTES] |
| 697 | except urllib.error.HTTPError as exc: |
| 698 | return exc.code, exc.read(MAX_RESPONSE_BYTES) |
| 699 | except (urllib.error.URLError, OSError, ValueError) as exc: |
| 700 | raise TransportError(str(exc)[:200]) from exc |
| 701 | |
| 702 | |
| 703 | def set_transport(transport: Transport | None) -> None: |
| 704 | """Replace how requests reach partners (tests deliver in-process |
| 705 | between two boxes). None restores urllib.""" |
| 706 | global _transport |
| 707 | _transport = transport |
| 708 | |
| 709 | |
| 710 | def transport() -> Transport: |
| 711 | return _transport or urllib_transport |
| 712 | |
| 713 | |
| 714 | def request_json(method: str, url: str, payload: Any = None) -> tuple[int, Any]: |
| 715 | """One request through the configured transport; (status, parsed JSON or |
| 716 | None). TransportError when there was no answer.""" |
| 717 | body = b"" if payload is None else json.dumps(payload, ensure_ascii=False).encode("utf-8") |
| 718 | headers = {"content-type": "application/json", "accept": "application/json", |
| 719 | "user-agent": "dbbasic-exchange/" + DRON_DOCUMENT_VERSION} |
| 720 | status, raw = transport()(method, url, body, headers) |
| 721 | try: |
| 722 | return status, json.loads(raw.decode("utf-8")) if raw else None |
| 723 | except (UnicodeDecodeError, ValueError): |
| 724 | return status, None |