Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/tests/test_rev_oracle.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 19 minutes ago History
test_rev_oracle.py · 8.1 KB · 193 lines
1"""A record's `_rev` says "this row changed" and nothing about what it holds.
2
3Through the HTTP app with enforcement on. Before the fix the `_rev` a GET, a
4list's `revs` and an update's answer carried was an unkeyed sha256 of the
5whole stored row, hidden fields included, so a caller who could see every
6other field of a row hashed each candidate value of a hidden one (a salary
7band A/B/C) and compared: the rev answered which one it was. The rev is now
8an HMAC under a key only the box holds (object_records.client_record_rev).
9"""
10
11import asyncio
12import json
13import os
14import stat
15
16import pytest
17
18import object_backup
19import object_records
20from scripts.try_package import Sandbox, _asgi
21from tests.test_field_visibility_leaks import OWN_ROWS, RECORDS, SUPPORT, _package
22
23BANDS = ("A", "B", "C")
24
25
26@pytest.fixture()
27def box(tmp_path):
28 with Sandbox(["tickets"], packages_dir=_package(tmp_path, [OWN_ROWS, SUPPORT])) as box:
29 box.add_user("ann")
30 box.add_user("sam", roles=["support"])
31 yield box
32
33
34def _ticket(box, band, title="same title"):
35 status, body = box.call("ann", "POST", RECORDS, {"title": title, "salary_band": band})
36 assert status == 201, body
37 return body["record"]["id"]
38
39
40def _stored(box, record_id):
41 return object_records.get_collection_record("tickets", record_id, base_dir=box.data_dir)
42
43
44def _guesses(box, record_id):
45 """What the attacker computes: every field of the row as stored (they
46 see all but the band), with each candidate band in turn, hashed the way
47 the rev used to be."""
48 row = _stored(box, record_id)
49 return {band: object_records.compute_record_rev({**row, "salary_band": band}) for band in BANDS}
50
51
52def _put(box, user, path, body, if_match=None):
53 headers = box.headers(user) + ([("if-match", if_match)] if if_match is not None else [])
54 status, raw = asyncio.run(_asgi(path, "PUT", "", json.dumps(body).encode(), headers))
55 return status, json.loads(raw)
56
57
58def _restart():
59 """A new process: nothing cached in memory, only what is on disk."""
60 object_records._REV_KEYS.clear()
61
62
63# 1. the offline guess -----------------------------------------------------
64
65def test_the_rev_a_get_gives_cannot_be_matched_by_guessing_a_hidden_field(box):
66 record_id = _ticket(box, "B")
67 status, body = box.call("sam", "GET", f"{RECORDS}/{record_id}")
68 assert status == 200 and "salary_band" not in body["record"]
69 assert body["_rev"] not in _guesses(box, record_id).values()
70
71
72def test_the_revs_a_list_gives_cannot_be_matched_by_guessing_a_hidden_field(box):
73 record_id = _ticket(box, "C")
74 status, body = box.call("sam", "GET", RECORDS)
75 assert status == 200
76 assert body["revs"][record_id] not in _guesses(box, record_id).values()
77
78
79def test_the_rev_an_update_answers_with_cannot_be_matched_either(box):
80 record_id = _ticket(box, "A")
81 status, body = box.call("ann", "PUT", f"{RECORDS}/{record_id}", {"title": "renamed"})
82 assert status == 200, body
83 assert body["_rev"] not in _guesses(box, record_id).values()
84
85
86def test_an_unkeyed_fingerprint_is_not_accepted_as_if_match(box):
87 """Or a guess could be tested by whether the write 409s. It is also what
88 a client holding a rev from before the upgrade sees: one 409, then the
89 re-read gives a rev that works."""
90 record_id = _ticket(box, "A")
91 path = f"{RECORDS}/{record_id}"
92 unkeyed = object_records.compute_record_rev(_stored(box, record_id))
93 status, body = _put(box, "ann", path, {"title": "x"}, if_match=unkeyed)
94 assert (status, body["code"]) == (409, "conflict")
95 assert _stored(box, record_id)["title"] == "same title"
96
97
98# 2. rows and time ---------------------------------------------------------
99
100def test_rows_with_identical_visible_content_do_not_say_whether_hidden_fields_match(box):
101 same_a, also_a, b = _ticket(box, "A"), _ticket(box, "A"), _ticket(box, "B")
102 status, body = box.call("sam", "GET", RECORDS)
103 assert status == 200
104 visible = {r["id"]: {k: v for k, v in r.items() if k != "id"} for r in body["records"]}
105 assert visible[same_a] == visible[also_a] == visible[b]
106 revs = body["revs"]
107 # Every rev is its own: equal hidden content and unequal hidden content
108 # look the same (different) from outside.
109 assert len({revs[same_a], revs[also_a], revs[b]}) == 3
110
111
112def test_a_hidden_field_change_is_a_change_to_the_row(box):
113 """Deliberate: a rev ignoring hidden fields would let a partial update
114 proceed over a change its writer never saw. What it reveals is "this row
115 changed", which the 409 itself would say anyway."""
116 record_id = _ticket(box, "A")
117 path = f"{RECORDS}/{record_id}"
118 held = box.call("ann", "GET", path)[1]["_rev"]
119 assert box.call("admin", "PUT", path, {"salary_band": "B"})[0] == 200
120 assert box.call("ann", "GET", path)[1]["_rev"] != held
121 status, body = _put(box, "ann", path, {"title": "x"}, if_match=held)
122 assert (status, body["code"]) == (409, "conflict")
123
124
125# 3. If-Match keeps working -------------------------------------------------
126
127def test_if_match_round_trips_from_a_get_a_list_and_an_update_answer(box):
128 record_id = _ticket(box, "A")
129 path = f"{RECORDS}/{record_id}"
130 rev = box.call("ann", "GET", path)[1]["_rev"]
131 assert box.call("ann", "GET", RECORDS)[1]["revs"][record_id] == rev
132
133 status, body = _put(box, "ann", path, {"title": "one"}, if_match=rev)
134 assert status == 200, body
135 status, body = _put(box, "ann", path, {"title": "two"}, if_match=body["_rev"])
136 assert status == 200, body
137 # The body channel the MCP bridge uses, too.
138 status, body = box.call("ann", "PUT", path, {"title": "three", "expected_rev": body["_rev"]})
139 assert status == 200, body
140 status, body = _put(box, "ann", path, {"title": "four"}, if_match=rev)
141 assert (status, body["code"]) == (409, "conflict")
142 assert _stored(box, record_id)["title"] == "three"
143
144
145def test_a_held_rev_survives_a_restart(box):
146 record_id = _ticket(box, "A")
147 path = f"{RECORDS}/{record_id}"
148 rev = box.call("ann", "GET", path)[1]["_rev"]
149 _restart()
150 assert box.call("ann", "GET", path)[1]["_rev"] == rev
151 _restart()
152 status, body = _put(box, "ann", path, {"title": "after restart"}, if_match=rev)
153 assert status == 200, body
154
155
156# 4. the key ---------------------------------------------------------------
157
158def test_the_key_is_private_shared_by_workers_and_outside_every_backup(box):
159 record_id = _ticket(box, "A")
160 assert box.call("ann", "GET", f"{RECORDS}/{record_id}")[0] == 200 # first rev makes the key
161 path = box.data_dir / object_records.REV_KEY_DIR / object_records.REV_KEY_FILE
162 assert stat.S_IMODE(path.stat().st_mode) == 0o600
163 assert stat.S_IMODE(path.parent.stat().st_mode) == 0o700
164 key = object_records._record_rev_key(box.data_dir)
165 _restart() # a second worker process reads the file, never makes its own
166 assert object_records._record_rev_key(box.data_dir) == key
167 assert [p.name for p in path.parent.iterdir()] == [object_records.REV_KEY_FILE]
168 assert object_records.REV_KEY_DIR not in object_backup.RUNTIME_DATA_DIRS
169 assert not any(f.startswith(object_records.REV_KEY_DIR + "/") for f in object_backup.RUNTIME_DATA_FILES)
170
171
172def test_a_worker_that_loses_the_race_to_make_the_key_uses_the_winners(tmp_path, monkeypatch):
173 """Two workers both find no key and both make one: the second link
174 fails, and that worker reads the file the first one put in place."""
175 winner = "ab" * 32
176 real_link = os.link
177
178 def link_after_another_worker(src, dst):
179 with open(dst, "x") as other: # the other worker got there first
180 other.write(winner)
181 return real_link(src, dst)
182
183 monkeypatch.setattr(os, "link", link_after_another_worker)
184 assert object_records._record_rev_key(tmp_path) == bytes.fromhex(winner)
185 assert sorted(os.listdir(tmp_path / object_records.REV_KEY_DIR)) == [object_records.REV_KEY_FILE]
186
187
188def test_a_damaged_key_refuses_rather_than_guessing(tmp_path):
189 folder = tmp_path / object_records.REV_KEY_DIR
190 folder.mkdir()
191 (folder / object_records.REV_KEY_FILE).write_text("not a key")
192 with pytest.raises(RuntimeError, match="damaged"):
193 object_records.client_record_rev("tickets", {"id": "t1"}, base_dir=tmp_path)