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_scan_file_ownership.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_scan_file_ownership.py · 8.9 KB · 192 lines
1"""A scan reads only the document intake stored for it, under its owner.
2
3system_scan_processor runs as the system and reads a user's file bytes
4straight from storage, then writes the text it read onto the scan row, so
5it is the only gate between a scan and a file. The suspicion was a confused
6deputy: write a scan row naming somebody else's file and owner, let the
7hourly pass OCR it, read the text off your own row.
8
9Measured before the fix: over the record API that row could not be made
10(a create naming another owner is refused, and so is an update moving a
11row to another owner), and a caller's own row naming another user's file
12id failed to read, because bytes live under user_files/{owner}/. What did
13work: action_scan_ingest preferred the body's owner_id to the caller's
14identity, so any signed-in user (and with enforcement off, too) could file
15a scan, and store its bytes, under anybody's account.
16
17Now: the processor opens only scan-{id} under the scan's owner, the name
18ingest gives the bytes it stores, and fails any other scan without opening
19anything; file_id is read_only; ingest files the scan under the caller.
20"""
21
22from __future__ import annotations
23
24import base64
25import sys
26import types
27
28import pytest
29from test_findings_access_control import _json, _text, make_site # noqa: F401
30
31import object_records
32import object_user_files
33
34SECRET = b"ALICE PRIVATE MEDICAL BILL TOTAL 999.00"
35
36
37@pytest.fixture
38def tesseract(monkeypatch):
39 """pytesseract and PIL as the processor imports them: 'OCR' returns the
40 bytes as text, so whatever file was opened shows up on the scan."""
41 pil = types.ModuleType("PIL")
42 image = types.ModuleType("PIL.Image")
43 image.open = lambda handle: handle.read()
44 pil.Image = image
45 tess = types.ModuleType("pytesseract")
46 tess.image_to_string = lambda img: img.decode("utf-8", "replace")
47 monkeypatch.setitem(sys.modules, "PIL", pil)
48 monkeypatch.setitem(sys.modules, "PIL.Image", image)
49 monkeypatch.setitem(sys.modules, "pytesseract", tess)
50
51
52def _box(make_site, monkeypatch, mode):
53 site = make_site("app-intake", "app-finance", "app-files")
54 users = {name: site.user(name) for name in ("alice", "bob")}
55 site.create("files", {"id": "f-alice", "filename": "medical.png",
56 "content_type": "image/png", "size": str(len(SECRET)),
57 "is_public": "false", "owner_id": "alice"})
58 object_user_files.save_file("alice", "f-alice", SECRET, base_dir=site.data)
59 if mode == "off":
60 monkeypatch.delenv("DBBASIC_ENABLE_PERMISSION_ENFORCEMENT")
61 return site, users
62
63
64def _process(site):
65 response = site.execute("system_scan_processor", {"engine": "tesseract"}, site.admin)
66 assert response.status == 200, _text(response)
67 return _json(response)
68
69
70def _alice_files(site):
71 return sorted(p.name for p in (site.data / "user_files" / "alice").iterdir())
72
73
74# --- the record API ---------------------------------------------------------
75
76@pytest.mark.parametrize("mode", ["enforced", "off"])
77def test_a_scan_cannot_be_created_under_another_owner(make_site, monkeypatch, mode):
78 site, users = _box(make_site, monkeypatch, mode)
79 response = site.call("/collections/scans/records", "POST",
80 {"id": "s-forged", "owner_id": "alice", "file_id": "f-alice",
81 "status": "pending"}, users["bob"])
82 assert response.status in (401, 403), _text(response)
83 assert not [row for row in site.rows("scans") if row["id"] == "s-forged"]
84
85
86def test_a_scan_cannot_name_a_file_or_move_to_another_owner(make_site, monkeypatch):
87 site, users = _box(make_site, monkeypatch, "enforced")
88 bob = users["bob"]
89 named = site.call("/collections/scans/records", "POST",
90 {"id": "s-named", "file_id": "f-alice", "status": "pending"}, bob)
91 assert named.status in (400, 403), _text(named)
92
93 own = site.call("/collections/scans/records", "POST",
94 {"id": "s-own", "status": "pending"}, bob)
95 assert own.status == 201, _text(own)
96 assert site.row("scans", "s-own")["owner_id"] == "bob"
97 for change in ({"owner_id": "alice"}, {"file_id": "f-alice"},
98 {"owner_id": "alice", "file_id": "f-alice"}):
99 response = site.call("/collections/scans/records/s-own", "PUT", change, bob)
100 assert response.status in (400, 403), (change, _text(response))
101 row = site.row("scans", "s-own")
102 assert (row["owner_id"], row["file_id"]) == ("bob", "")
103
104
105# --- the processor ----------------------------------------------------------
106
107@pytest.mark.parametrize("owner", ["bob", "alice"])
108def test_the_processor_reads_no_file_but_the_scans_own(make_site, monkeypatch, tesseract, owner):
109 """A row written below the record API (an import, a restore, an
110 on_behalf grant) naming another file is failed without being opened:
111 another user's file under a forged owner, or a file id that is not
112 this scan's, under the scan's own owner."""
113 site, _users = _box(make_site, monkeypatch, "enforced")
114 object_records.create_collection_record(
115 "scans", {"id": "s-planted", "owner_id": owner, "file_id": "f-alice",
116 "status": "pending"}, base_dir=site.data, preserve_read_only=True)
117 if owner == "bob": # bytes of the same name in bob's folder: still not his scan's
118 object_user_files.save_file("bob", "f-alice", SECRET, base_dir=site.data)
119
120 result = _process(site)
121 row = site.row("scans", "s-planted")
122 assert row["status"] == "error"
123 assert row["ocr_text"] == "" and row["extracted"] == ""
124 for leaked in ("f-alice", "medical", "ALICE", "999"):
125 assert leaked not in row["error"] and leaked not in str(result)
126 assert "not read" in row["error"]
127 assert _process(site)["considered"] == 0 # failed, not retried forever
128
129
130@pytest.mark.parametrize("mode", ["enforced", "off"])
131def test_a_signed_in_user_cannot_run_the_processor(make_site, monkeypatch, tesseract, mode):
132 """A pass spends the owner's AI budget and touches every pending scan,
133 so the processor asks for itself who may start one: with enforcement
134 off it used to run for any signed-in user."""
135 site, users = _box(make_site, monkeypatch, mode)
136 object_records.create_collection_record(
137 "scans", {"id": "s-waiting", "owner_id": "alice", "file_id": "scan-s-waiting",
138 "status": "pending"}, base_dir=site.data, preserve_read_only=True)
139 object_user_files.save_file("alice", "scan-s-waiting", b"TOTAL 4.00", base_dir=site.data)
140 response = site.execute("system_scan_processor", {"engine": "tesseract"}, users["bob"])
141 assert response.status == 403, _text(response)
142 row = site.row("scans", "s-waiting")
143 assert (row["status"], row["attempts"], row["ocr_text"]) == ("pending", "0", "")
144 assert _process(site)["extracted"] == 1 # an admin still may
145
146
147# --- ingest -----------------------------------------------------------------
148
149@pytest.mark.parametrize("mode", ["enforced", "off"])
150def test_ingest_refuses_to_file_a_scan_under_another_user(make_site, monkeypatch, mode):
151 site, users = _box(make_site, monkeypatch, mode)
152 before = _alice_files(site)
153 response = site.execute(
154 "action_scan_ingest",
155 {"content_base64": base64.b64encode(b"planted").decode(), "owner_id": "alice"},
156 users["bob"])
157 assert response.status == 403, _text(response)
158 assert site.rows("scans") == []
159 assert _alice_files(site) == before
160
161
162def test_an_admin_may_still_ingest_for_somebody(make_site, monkeypatch):
163 site, _users = _box(make_site, monkeypatch, "enforced")
164 response = site.execute("action_scan_ingest", {"text": "TOTAL 1.00", "owner_id": "alice"},
165 site.admin)
166 assert response.status == 200, _text(response)
167 assert site.row("scans", _json(response)["scan_id"])["owner_id"] == "alice"
168
169
170# --- the honest path, end to end over HTTP ----------------------------------
171
172@pytest.mark.parametrize("send_own_id", [False, True])
173def test_an_owner_scans_their_own_receipt(make_site, monkeypatch, tesseract, send_own_id):
174 site, users = _box(make_site, monkeypatch, "enforced")
175 payload = {"content_base64": base64.b64encode(b"CAFE\nTOTAL 8.99\n").decode(),
176 "filename": "receipt.png"}
177 if send_own_id:
178 payload["owner_id"] = "bob"
179 response = site.execute("action_scan_ingest", payload, users["bob"])
180 assert response.status == 200, _text(response)
181 scan_id = _json(response)["scan_id"]
182 row = site.row("scans", scan_id)
183 assert (row["owner_id"], row["file_id"]) == ("bob", f"scan-{scan_id}")
184
185 _process(site)
186 read = site.call(f"/collections/scans/records/{scan_id}", headers=users["bob"])
187 assert read.status == 200, _text(read)
188 record = _json(read)["record"]
189 assert record["status"] == "extracted" and record["error"] == ""
190 assert "TOTAL 8.99" in record["ocr_text"] and record["ocr_engine"] == "tesseract"
191 assert site.call(f"/collections/scans/records/{scan_id}",
192 headers=users["alice"]).status == 404