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.
test_exchange_core.py · 10.3 KB · 233 lines
| 1 | """The exchange primitives: canonical bytes, Ed25519 keys, envelopes, refusal. |
| 2 | |
| 3 | Everything a second implementation would have to agree with byte for byte |
| 4 | (the canonical form), everything that keeps the private key private (file |
| 5 | modes, backups), and the rule that the optional `cryptography` dependency |
| 6 | is imported in one module only and refuses clearly when it is missing. |
| 7 | """ |
| 8 | |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | import builtins |
| 12 | import os |
| 13 | import re |
| 14 | import stat |
| 15 | import sys |
| 16 | import tarfile |
| 17 | from datetime import datetime, timedelta, timezone |
| 18 | from pathlib import Path |
| 19 | |
| 20 | import pytest |
| 21 | |
| 22 | import object_backup |
| 23 | import object_exchange as ex |
| 24 | |
| 25 | REPO = Path(__file__).resolve().parent.parent |
| 26 | |
| 27 | # Tests that generate or use a key need the `exchange` extra; without it they |
| 28 | # skip (a `.[test]` install), while the refusal and import-rule tests below |
| 29 | # run either way. |
| 30 | needs_extra = pytest.mark.skipif(not ex.available(), |
| 31 | reason="needs the exchange extra: pip install -e '.[exchange]'") |
| 32 | |
| 33 | |
| 34 | # --- canonical bytes ------------------------------------------------------------ |
| 35 | |
| 36 | def test_canonical_form_is_sorted_keys_no_whitespace_utf8(): |
| 37 | """The signature covers these bytes; a second engine must produce the |
| 38 | same ones, so the rule is pinned to a literal.""" |
| 39 | value = {"b": 1, "a": {"z": "café", "y": [True, None, -3]}} |
| 40 | assert ex.canonical(value) == '{"a":{"y":[true,null,-3],"z":"café"},"b":1}'.encode("utf-8") |
| 41 | |
| 42 | |
| 43 | def test_canonical_form_refuses_floats_and_non_ascii_keys(): |
| 44 | """A float is where two JSON libraries disagree about bytes, and money is |
| 45 | never one; a non-ASCII key is where code-point and JCS ordering differ.""" |
| 46 | with pytest.raises(ex.CanonicalError): |
| 47 | ex.canonical({"amount": 18.5}) |
| 48 | with pytest.raises(ex.CanonicalError): |
| 49 | ex.canonical({"lines": [{"q": 1.0}]}) |
| 50 | with pytest.raises(ex.CanonicalError): |
| 51 | ex.canonical({"clé": 1}) |
| 52 | |
| 53 | |
| 54 | # --- keys ---------------------------------------------------------------------- |
| 55 | |
| 56 | @needs_extra |
| 57 | def test_private_key_file_is_0600_in_a_0700_directory_and_id_is_derived(tmp_path): |
| 58 | key_id, public = ex.generate_key(tmp_path) |
| 59 | path = tmp_path / "exchange" / "private" / f"{key_id[8:]}.key" |
| 60 | assert stat.S_IMODE(path.stat().st_mode) == 0o600 |
| 61 | assert stat.S_IMODE(path.parent.stat().st_mode) == 0o700 |
| 62 | assert stat.S_IMODE(path.parent.parent.stat().st_mode) == 0o700 |
| 63 | assert key_id == ex.key_id_for(ex.unb64u(public)) |
| 64 | # The returned public half is not the private key, and nothing else is returned. |
| 65 | assert public.encode() not in path.read_bytes() |
| 66 | |
| 67 | |
| 68 | @needs_extra |
| 69 | def test_signature_verifies_and_any_change_breaks_it(tmp_path): |
| 70 | key_id, public = ex.generate_key(tmp_path) |
| 71 | message = ex.canonical({"x": 1}) |
| 72 | sig = ex.sign(tmp_path, key_id, message) |
| 73 | assert ex.verify(public, message, sig) |
| 74 | assert not ex.verify(public, ex.canonical({"x": 2}), sig) |
| 75 | other_id, other_public = ex.generate_key(tmp_path) |
| 76 | assert not ex.verify(other_public, message, sig), "a signature names its key" |
| 77 | flipped = ("B" if sig["value"][0] == "A" else "A") + sig["value"][1:] |
| 78 | assert not ex.verify(public, message, {**sig, "value": flipped}) |
| 79 | assert not ex.verify(public, message, {**sig, "alg": "rsa"}) |
| 80 | assert not ex.verify(public, message, "garbage") |
| 81 | |
| 82 | |
| 83 | @needs_extra |
| 84 | def test_a_destroyed_private_key_signs_nothing(tmp_path): |
| 85 | key_id, _ = ex.generate_key(tmp_path) |
| 86 | ex.destroy_private_key(tmp_path, key_id) |
| 87 | assert not ex.has_private_key(tmp_path, key_id) |
| 88 | with pytest.raises(KeyError): |
| 89 | ex.sign(tmp_path, key_id, b"x") |
| 90 | |
| 91 | |
| 92 | @needs_extra |
| 93 | def test_no_backup_carries_a_private_key(tmp_path): |
| 94 | """The private key is the most sensitive thing on the box; a runtime |
| 95 | backup is copied off-box. The exchange directory is outside every |
| 96 | directory a backup takes, and this proves it on a real archive.""" |
| 97 | data = tmp_path / "data" |
| 98 | objects = tmp_path / "objects" |
| 99 | (data / "collections").mkdir(parents=True) |
| 100 | (data / "collections" / "x.tsv").write_text("id\n1\n") |
| 101 | objects.mkdir() |
| 102 | key_id, _ = ex.generate_key(data) |
| 103 | pem = (data / "exchange" / "private" / f"{key_id[8:]}.key").read_bytes() |
| 104 | out = tmp_path / "backup.tar.gz" |
| 105 | object_backup.create_runtime_backup(out, objects_dir=objects, data_dir=data) |
| 106 | with tarfile.open(out) as archive: |
| 107 | names = archive.getnames() |
| 108 | blobs = b"".join(archive.extractfile(m).read() for m in archive.getmembers() if m.isfile()) |
| 109 | assert not any("exchange" in name for name in names), names |
| 110 | assert pem not in blobs and b"PRIVATE KEY" not in blobs |
| 111 | |
| 112 | |
| 113 | # --- the optional dependency ------------------------------------------------------- |
| 114 | |
| 115 | def test_missing_cryptography_refuses_naming_the_extra(monkeypatch, tmp_path): |
| 116 | """No stub: a box without the extra cannot sign or verify, and the |
| 117 | refusal says exactly what to install.""" |
| 118 | real_import = builtins.__import__ |
| 119 | |
| 120 | def no_crypto(name, *args, **kwargs): |
| 121 | if name == "cryptography" or name.startswith("cryptography."): |
| 122 | raise ImportError("No module named 'cryptography'") |
| 123 | return real_import(name, *args, **kwargs) |
| 124 | |
| 125 | for name in [n for n in sys.modules if n == "cryptography" or n.startswith("cryptography.")]: |
| 126 | monkeypatch.delitem(sys.modules, name) |
| 127 | monkeypatch.setattr(builtins, "__import__", no_crypto) |
| 128 | assert ex.available() is False |
| 129 | with pytest.raises(ex.ExchangeUnavailable, match=r"dbbasic-object-server\[exchange\]"): |
| 130 | ex.generate_key(tmp_path) |
| 131 | with pytest.raises(ex.ExchangeUnavailable): |
| 132 | ex.verify("AAAA", b"x", {"alg": "ed25519", "key_id": "k", "value": "v"}) |
| 133 | # The pure parts still work: the module itself imports nothing optional. |
| 134 | assert ex.canonical({"a": 1}) == b'{"a":1}' |
| 135 | |
| 136 | |
| 137 | def test_only_the_exchange_module_imports_cryptography(): |
| 138 | """The core stays dependency-free: one module may import the extra, and |
| 139 | only inside functions.""" |
| 140 | pattern = re.compile(r"^\s*(from\s+cryptography|import\s+cryptography)", re.M) |
| 141 | offenders = [] |
| 142 | for path in list(REPO.glob("*.py")) + list((REPO / "packages").rglob("*.py")) \ |
| 143 | + list((REPO / "scripts").rglob("*.py")): |
| 144 | if path.name == "object_exchange.py": |
| 145 | continue |
| 146 | if pattern.search(path.read_text(encoding="utf-8", errors="replace")): |
| 147 | offenders.append(str(path.relative_to(REPO))) |
| 148 | assert offenders == [] |
| 149 | source = (REPO / "object_exchange.py").read_text() |
| 150 | top_level = [line for line in source.splitlines() |
| 151 | if re.match(r"^(from|import)\s+cryptography", line)] |
| 152 | assert top_level == [], "imported at module level" |
| 153 | |
| 154 | |
| 155 | def test_pyproject_keeps_core_dependencies_empty_and_offers_the_extra(): |
| 156 | text = (REPO / "pyproject.toml").read_text() |
| 157 | assert re.search(r"^dependencies = \[\]$", text, re.M) |
| 158 | assert re.search(r'^exchange = \[\s*"cryptography>=42",?\s*\]', text, re.M) |
| 159 | |
| 160 | |
| 161 | # --- envelopes ----------------------------------------------------------------------- |
| 162 | |
| 163 | def _po(**overrides): |
| 164 | body = { |
| 165 | "number": "PO-1042", "issue_date": "2026-12-01", "currency": "EUR", |
| 166 | "lines": [{"line_id": "1", "description": "Widget", "quantity": "12", |
| 167 | "unit_code": "H87", "unit_price_minor": 1850, |
| 168 | "line_extension_minor": 22200}], |
| 169 | "totals": {"line_extension_minor": 22200, "tax_minor": 0, "payable_minor": 22200}, |
| 170 | } |
| 171 | body.update(overrides) |
| 172 | return body |
| 173 | |
| 174 | |
| 175 | def test_a_well_formed_purchase_order_passes_and_money_must_be_integers(): |
| 176 | env = ex.new_envelope(doc_id="doc-1", doc_type="purchase_order", sender="shop.example", |
| 177 | recipient="supplier.example", body=_po()) |
| 178 | assert env["dron_document"] == "0.1" and env["refs"] == [] |
| 179 | bad = dict(env, body=_po(totals={"line_extension_minor": "22200", "tax_minor": 0, |
| 180 | "payable_minor": 22200})) |
| 181 | with pytest.raises(ex.EnvelopeError, match="integer in minor units"): |
| 182 | ex.validate_envelope(bad) |
| 183 | with pytest.raises(ex.EnvelopeError, match="ISO 4217"): |
| 184 | ex.validate_envelope(dict(env, body=_po(currency="euro"))) |
| 185 | with pytest.raises(ex.EnvelopeError, match="decimal string"): |
| 186 | ex.validate_envelope(dict(env, body=_po(lines=[{**_po()["lines"][0], "quantity": 12}]))) |
| 187 | |
| 188 | |
| 189 | def test_every_problem_is_listed_at_once(): |
| 190 | with pytest.raises(ex.EnvelopeError) as info: |
| 191 | ex.validate_envelope({"dron_document": "0.1", "id": "", "type": "nonsense", |
| 192 | "sender": "x", "recipient": "y.example", "created_at": "today", |
| 193 | "body": {}, "extra": 1}) |
| 194 | assert len(info.value.problems) >= 5 |
| 195 | |
| 196 | |
| 197 | def test_a_remittance_must_add_up(): |
| 198 | body = {"currency": "EUR", "paid_minor": 100, "paid_on": "2026-12-05", |
| 199 | "settles": [{"document_id": "inv-1", "amount_minor": 60}]} |
| 200 | with pytest.raises(ex.EnvelopeError, match="sum"): |
| 201 | ex.new_envelope(doc_id="r1", doc_type="remittance", sender="a.example", |
| 202 | recipient="b.example", body=body) |
| 203 | |
| 204 | |
| 205 | def test_clock_window_and_one_spelling_of_time(): |
| 206 | now = datetime(2026, 12, 1, 12, 0, tzinfo=timezone.utc) |
| 207 | assert ex.utc_stamp(now) == "2026-12-01T12:00:00Z" |
| 208 | assert ex.within_window("2026-12-01T12:04:00Z", now) |
| 209 | assert not ex.within_window(ex.utc_stamp(now - timedelta(minutes=6)), now) |
| 210 | assert not ex.within_window("2026-12-01T12:00:00+00:00", now), "one spelling only" |
| 211 | |
| 212 | |
| 213 | def test_domains_and_endpoints(): |
| 214 | assert ex.valid_domain("supplier.example") |
| 215 | for bad in ("Supplier.example", "localhost", "10.0.0.1", "a..b", "-a.example"): |
| 216 | assert not ex.valid_domain(bad), bad |
| 217 | assert ex.endpoint_on_domain("https://s.example/webhooks/exchange", "s.example") |
| 218 | assert not ex.endpoint_on_domain("http://s.example/webhooks/exchange", "s.example") |
| 219 | assert not ex.endpoint_on_domain("https://evil.example/x", "s.example") |
| 220 | assert not ex.endpoint_on_domain("https://s.example@evil.example/x", "s.example") |
| 221 | |
| 222 | |
| 223 | def test_production_transport_is_https_only_and_never_reached_here(monkeypatch): |
| 224 | with pytest.raises(ex.TransportError, match="https only"): |
| 225 | ex.urllib_transport("POST", "http://s.example/webhooks/exchange", b"{}", {}) |
| 226 | assert ex.transport() is ex.urllib_transport |
| 227 | seen = [] |
| 228 | ex.set_transport(lambda *a: seen.append(a) or (200, b'{"ok": true}')) |
| 229 | try: |
| 230 | assert ex.request_json("GET", "https://s.example/x") == (200, {"ok": True}) |
| 231 | finally: |
| 232 | ex.set_transport(None) |
| 233 | assert seen and ex.transport() is ex.urllib_transport |