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_privacy.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, 18 minutes ago History
test_privacy.py · 37.1 KB · 808 lines
1"""The tests that keep a generated privacy policy true.
2
3A privacy policy is the one document in a system that nothing checks. It
4is written once, by a template, and the software changes weekly; nothing
5connects the two, so nothing notices when they part company. Generating
6the page from the configuration removes most of that drift by
7construction -- but only most of it, because the generator itself is code
8somebody can forget to update.
9
10So the first test in this file is a SWEEP, and it is the one that matters:
11it walks every source file on the box looking for anything that sets a
12cookie, and fails unless every cookie name it finds is disclosed in the
13policy's table, naming the undisclosed cookie in the failure message. A
14new cookie added anywhere in this repo breaks the build until somebody
15writes down what it is for and whether it is strictly necessary. That is a
16property no amount of care in the policy module can give you, because the
17thing it guards against happens in a file the policy module has never
18heard of.
19
20The rest hold the fold honest in the directions it could go wrong: a
21retention it states that the box does not keep, a section for an app that
22is not installed, a sub-processor nobody configured, a policy nobody
23signed, and an export that returns somebody else's rows.
24"""
25
26import importlib.util
27import json
28import pathlib
29import re
30
31import pytest
32
33from conftest import stage_collection
34
35import object_analytics
36import object_execution
37import object_records
38import object_schemas
39import python_object_runtime
40
41REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
42PACKAGES = REPO_ROOT / "packages"
43PRIVACY_OBJECTS = PACKAGES / "app-privacy" / "objects"
44RUNTIME = python_object_runtime.PythonObjectRuntime()
45
46
47def _module(relative):
48 """Import a package object as a module, for the folds a test needs to
49 call directly rather than through a rendered page."""
50 path = PACKAGES / relative
51 spec = importlib.util.spec_from_file_location(path.stem, path)
52 module = importlib.util.module_from_spec(spec)
53 spec.loader.exec_module(module)
54 return module
55
56
57privacy = _module("app-privacy/objects/site/privacy.py")
58
59
60# ===========================================================================
61# 1. The sweep: every cookie this codebase sets is disclosed
62# ===========================================================================
63
64# A file is worth reading at all only if it mentions setting a cookie.
65_COOKIE_FILE = re.compile(r"set[_-]cookie|max-age", re.I)
66# ...and a candidate name counts only if a cookie ATTRIBUTE is nearby, so
67# an ordinary `days=7` in a query string is not mistaken for a cookie.
68_COOKIE_ATTRIBUTE = re.compile(r"Path=/|HttpOnly|SameSite|Max-Age|set[_-]cookie",
69 re.I)
70# The two shapes a cookie name is written in here: a constant interpolated
71# into the header (`f"{COOKIE}={token}; Path=/"`) or a literal
72# (`"consent=yes; Path=/"`).
73_NAME_FROM_CONSTANT = re.compile(r"\{\s*([A-Za-z_][A-Za-z0-9_.]*)\s*\}\s*=")
74_NAME_LITERAL = re.compile(r"""["']\s*([A-Za-z][A-Za-z0-9_-]*)=""")
75_LITERAL_MAX_AGE = re.compile(r"Max-Age=(\d+)")
76_WINDOW = 300
77
78# Cookie attributes are not cookie names; they look identical to the
79# literal pattern above and are the only false positives it produces.
80_ATTRIBUTE_WORDS = {"path", "httponly", "samesite", "max-age", "secure",
81 "expires", "domain", "priority", "partitioned", "version"}
82
83
84def _source_files():
85 """Every Python file this server actually runs. Tests excluded: a test
86 fixture is allowed to write `cart=xyz` without that being a cookie the
87 product sets."""
88 files = list(REPO_ROOT.glob("*.py")) + list(PACKAGES.rglob("*.py"))
89 return [path for path in files if "__pycache__" not in path.parts]
90
91
92def _constant_values():
93 """Every `NAME = "literal"` on the box, so a cookie whose name is a
94 constant resolves to the string a browser would actually see."""
95 values = {}
96 pattern = re.compile(
97 r"^\s*([A-Za-z_][A-Za-z0-9_]*)\s*(?::[^=\n]+)?=\s*[\"']([^\"'\n]+)[\"']",
98 re.M)
99 for path in _source_files():
100 for match in pattern.finditer(path.read_text(encoding="utf-8",
101 errors="replace")):
102 values.setdefault(match.group(1), match.group(2))
103 return values
104
105
106def _cookies_set_in_source():
107 """(cookie name, file, literal Max-Age or None) for everything on this
108 box that puts a cookie in a browser.
109
110 An unresolvable name is returned as-is rather than dropped: a cookie
111 written in a shape this sweep cannot read must fail the test too,
112 because the alternative is a sweep that goes quietly blind.
113 """
114 constants = _constant_values()
115 found = []
116 for path in _source_files():
117 text = path.read_text(encoding="utf-8", errors="replace")
118 if not _COOKIE_FILE.search(text):
119 continue
120 for pattern, from_constant in ((_NAME_FROM_CONSTANT, True),
121 (_NAME_LITERAL, False)):
122 for match in pattern.finditer(text):
123 window = text[max(0, match.start() - _WINDOW):
124 match.end() + _WINDOW]
125 if not _COOKIE_ATTRIBUTE.search(window):
126 continue
127 raw = match.group(1)
128 if not from_constant and raw.lower() in _ATTRIBUTE_WORDS:
129 continue
130 name = (constants.get(raw.split(".")[-1], raw) if from_constant
131 else raw)
132 ages = set(_LITERAL_MAX_AGE.findall(window))
133 age = int(ages.pop()) if len(ages) == 1 else None
134 found.append((name, path.relative_to(REPO_ROOT).as_posix(), age))
135 return found
136
137
138def test_every_cookie_this_codebase_sets_is_disclosed_in_the_policy():
139 """THE test that keeps the policy true.
140
141 Nothing else in this file can stop the drift this one stops, because
142 the drift happens in a file the policy module has never heard of: a
143 package adds a cookie, ships, and the policy goes on describing a
144 server that no longer exists. A policy that CAN be wrong about the
145 software is the normal case on the web; the only thing that makes one
146 that cannot is a check that reads the software rather than the policy.
147 """
148 disclosed = privacy.disclosed_cookie_names()
149 undisclosed = sorted({(name, where)
150 for name, where, _age in _cookies_set_in_source()
151 if name not in disclosed})
152 assert not undisclosed, (
153 "these cookies are set by this codebase and disclosed nowhere in the "
154 f"privacy policy's cookie table: {undisclosed}. Add each one to "
155 "COOKIE_DISCLOSURES in packages/app-privacy/objects/site/privacy.py "
156 "with what it is for, when it is set, and whether it is strictly "
157 "necessary for something the visitor asked for -- that last answer is "
158 "the one with a consent consequence. If the name shown is an "
159 "unresolved identifier rather than a cookie name, the sweep could not "
160 "read the shape it is written in; write the name as a module-level "
161 "constant so it can.")
162
163
164def test_the_sweep_can_actually_see_the_cookies_this_server_sets():
165 """A guard on the guard. A regex that matches nothing passes the test
166 above forever, and the failure would be silent and permanent -- the
167 single most dangerous shape a test can have."""
168 found = {name for name, _where, _age in _cookies_set_in_source()}
169 assert {"dbbasic_session", "cart", object_analytics.VISITOR_COOKIE_NAME} <= found, (
170 f"the sweep found {sorted(found)}; it should at minimum see the "
171 "identity session cookie, the shop's basket cookie and the visitor "
172 "cookie. If one has moved, fix the sweep -- do not narrow it.")
173
174
175def test_a_disclosed_lifetime_matches_the_one_the_code_actually_writes():
176 """Disclosing a cookie is not enough if the number beside it is
177 wrong. Where the source writes a literal Max-Age, the policy must
178 publish that same number of seconds."""
179 wrong = []
180 for name, where, age in _cookies_set_in_source():
181 if age is None or name not in privacy.disclosed_cookie_names():
182 continue
183 published = privacy.cookie_max_age_seconds(name)
184 if published != age:
185 wrong.append(f"{name} in {where}: code sets {age}s, "
186 f"policy publishes {published}s")
187 assert not wrong, (
188 f"the policy publishes a lifetime the code does not set: {wrong}")
189
190
191def test_the_policy_states_no_law_it_cannot_verify():
192 """The refusal, held as a property rather than a promise in a
193 docstring. Confident paragraphs about lawful bases and transfer
194 mechanisms would be legal claims about somebody else's business,
195 generated by a program that cannot know it -- and pasted into the one
196 document a regulator reads. Wrong legal text is worse than none."""
197 fold = privacy.policy(base="/nonexistent", env={})
198 rendered = json.dumps(fold) + privacy.GET({"_path": "/privacy"})["body"]
199 forbidden = ["standard contractual clause", "lawful basis", "lawful bases",
200 "legitimate interest", "article 6", "adequacy decision",
201 "gdpr compliant", "we are compliant"]
202 present = [phrase for phrase in forbidden if phrase in rendered.lower()]
203 assert not present, (
204 f"the generated policy asserts legal conclusions it cannot verify: "
205 f"{present}. Facts about the system go here; legal framing goes in "
206 "privacy.extra_markdown, where a human signs it.")
207
208
209# ===========================================================================
210# 2. The fold: the policy says what the box is configured to do
211# ===========================================================================
212
213SIGNED = (
214 ("privacy.controller_name", "Q9 Ltd"),
215 ("privacy.contact_email", "privacy@example.test"),
216 ("privacy.jurisdiction", "England and Wales"),
217)
218
219
220def box(tmp_path, monkeypatch, *, settings=SIGNED, apps=(), analytics=False,
221 visitor_cookie=False, retention=None, env=()):
222 """One configured server. `apps` names packages whose collection is
223 staged, which is what makes them installed as far as the policy is
224 concerned."""
225 data_dir = tmp_path / "data"
226 rows = "".join(f"s{index}\t{key}\t{value}\t\n"
227 for index, (key, value) in enumerate(settings))
228 stage_collection(data_dir, "app-settings", "app_settings", rows=rows)
229 for package_id, collection in apps:
230 stage_collection(data_dir, package_id, collection)
231 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
232 if analytics:
233 monkeypatch.setenv("DBBASIC_ANALYTICS", "on")
234 else:
235 monkeypatch.delenv("DBBASIC_ANALYTICS", raising=False)
236 if visitor_cookie:
237 monkeypatch.setenv("DBBASIC_ANALYTICS_VISITOR_COOKIE", "on")
238 else:
239 monkeypatch.delenv("DBBASIC_ANALYTICS_VISITOR_COOKIE", raising=False)
240 if retention is not None:
241 monkeypatch.setenv("DBBASIC_ANALYTICS_RETENTION_DAYS", str(retention))
242 else:
243 monkeypatch.delenv("DBBASIC_ANALYTICS_RETENTION_DAYS", raising=False)
244 for key, value in env:
245 monkeypatch.setenv(key, value)
246 return data_dir
247
248
249def render(path="/privacy"):
250 """Through the real execution path, exactly as a visitor reaches it."""
251 return object_execution.execute_object(
252 RUNTIME,
253 object_execution.ObjectExecutionRequest(
254 "site_privacy", method="GET", payload={"_path": path}),
255 roots=[PRIVACY_OBJECTS]).result
256
257
258def test_it_states_the_retention_the_box_is_actually_configured_with(
259 tmp_path, monkeypatch):
260 """The property the whole design is for. A policy that claims 30 days
261 while the box keeps 180 is the normal case on the web, and it is a
262 claim nobody can be held to because nobody wrote it deliberately."""
263 box(tmp_path, monkeypatch, analytics=True, retention=45)
264 assert "45 days" in render()["body"]
265
266
267def test_changing_the_setting_changes_the_page(tmp_path, monkeypatch):
268 """Not merely "a number appears" -- the number follows the box. This
269 is what makes the page a fold rather than a template with a variable
270 in it."""
271 box(tmp_path, monkeypatch, analytics=True, retention=7)
272 assert "7 days" in render()["body"]
273 monkeypatch.setenv("DBBASIC_ANALYTICS_RETENTION_DAYS", "180")
274 body = render()["body"]
275 assert "180 days" in body and "7 days" not in body
276
277
278def test_analytics_off_removes_the_section_entirely(tmp_path, monkeypatch):
279 """Not "0 page views kept" -- the honest statement is that nothing is
280 collected at all, and a section full of zeros would read as a
281 collection that happens to be empty."""
282 box(tmp_path, monkeypatch, analytics=False)
283 body = render()["body"]
284 assert "This server keeps no log of page views" in body
285 assert "User agent" not in body and "Referrer" not in body
286 fold = privacy.policy()
287 assert fold["analytics"]["fields"] == []
288 assert fold["analytics"]["retention_days"] == 0
289
290
291def test_analytics_on_names_the_fields_actually_recorded(tmp_path, monkeypatch):
292 """"Usage data" is the phrasing that lets a policy mean anything. The
293 fields are named one by one because they are knowable."""
294 box(tmp_path, monkeypatch, analytics=True)
295 body = render()["body"]
296 for field in ("IP address", "User agent", "Referrer", "Path and method"):
297 assert field in body, field
298
299
300def test_the_cookie_table_follows_the_configuration(tmp_path, monkeypatch):
301 """Off -- the default -- and the analytics cookie is not in the table,
302 because it cannot be set. On, and it appears with the real Max-Age
303 this server writes, not a number somebody typed."""
304 box(tmp_path, monkeypatch, analytics=True, visitor_cookie=False)
305 off = render("/cookies")["body"]
306 assert object_analytics.VISITOR_COOKIE_NAME not in off
307 assert "dbbasic_session" in off # the necessary one is still listed
308
309 box(tmp_path, monkeypatch, analytics=True, visitor_cookie=True)
310 on = render("/cookies")["body"]
311 assert object_analytics.VISITOR_COOKIE_NAME in on
312 assert f"Max-Age={object_analytics.DEFAULT_VISITOR_DAYS * 86400}" in on
313 # And the consent-relevant column is answered honestly: this is the
314 # one cookie here that is not strictly necessary.
315 rows = {row["name"]: row for row in privacy.cookie_table()}
316 assert rows[object_analytics.VISITOR_COOKIE_NAME]["strictly_necessary"] is False
317 assert rows["dbbasic_session"]["strictly_necessary"] is True
318
319
320def test_the_basket_cookie_appears_only_where_there_is_a_shop(
321 tmp_path, monkeypatch):
322 box(tmp_path, monkeypatch)
323 assert "cart" not in {row["name"] for row in privacy.cookie_table()}
324
325 box(tmp_path, monkeypatch, apps=[("app-shop", "carts")])
326 row = {entry["name"]: entry for entry in privacy.cookie_table()}["cart"]
327 assert row["strictly_necessary"] is True
328 assert row["max_age_seconds"] == privacy.CART_COOKIE_MAX_AGE
329
330
331def test_sections_appear_only_when_the_thing_exists(tmp_path, monkeypatch):
332 """A fulfilment paragraph on a box that ships nothing is invented
333 processing, and invented processing in a privacy policy is the
334 failure mode this page exists to remove."""
335 box(tmp_path, monkeypatch)
336 bare = render()["body"]
337 assert "Delivery" not in bare and "Payments" not in bare
338
339 box(tmp_path, monkeypatch, apps=[("app-shipping", "shipments"),
340 ("app-payments", "payments")])
341 full = render()["body"]
342 assert "Delivery" in full and "Payments" in full
343
344
345def test_the_subprocessor_list_contains_only_configured_third_parties(
346 tmp_path, monkeypatch):
347 """Derived from credentials that are actually present, so it is a list
348 nobody has to remember to update: a key removed from the environment
349 removes the row."""
350 box(tmp_path, monkeypatch, apps=[("app-payments", "payments")])
351 assert privacy.subprocessors() == []
352 assert "No third party is configured" in render()["body"]
353
354 monkeypatch.setenv("DBBASIC_STRIPE_SECRET_KEY", "sk_test_x")
355 monkeypatch.setenv("DBBASIC_STRIPE_WEBHOOK_SECRET", "whsec_x")
356 monkeypatch.setenv("DBBASIC_SMTP_MODE", "live")
357 monkeypatch.setenv("DBBASIC_SMTP_HOST", "smtp.example.test")
358 names = {row["name"] for row in privacy.subprocessors()}
359 assert names == {"Stripe", "smtp.example.test"}
360
361 # Half-wired Stripe is not a sub-processor: without the webhook secret
362 # the integration cannot run at all, so claiming a data flow that
363 # cannot happen would be as wrong as omitting one that can.
364 monkeypatch.delenv("DBBASIC_STRIPE_WEBHOOK_SECRET")
365 assert "Stripe" not in {row["name"] for row in privacy.subprocessors()}
366
367
368def test_a_carrier_is_a_subprocessor_only_when_one_is_connected(
369 tmp_path, monkeypatch):
370 """`manual` means the operator walks to the counter: no address
371 leaves this server, so no carrier belongs on the list."""
372 for provider in ("", "none", "manual"):
373 settings = SIGNED + (("carrier.provider", provider),) if provider else SIGNED
374 box(tmp_path, monkeypatch, settings=settings,
375 apps=[("app-shipping", "shipments")])
376 assert privacy.subprocessors() == [], provider
377
378 box(tmp_path, monkeypatch, settings=SIGNED + (("carrier.provider", "ups"),),
379 apps=[("app-shipping", "shipments")])
380 assert [row["name"] for row in privacy.subprocessors()] == ["ups"]
381
382
383def test_it_refuses_to_publish_a_policy_nobody_signed(tmp_path, monkeypatch):
384 """An unsigned policy is worse than none: it looks like compliance
385 while giving a reader nobody to write to. So the page states no
386 claims at all and says exactly which settings are missing."""
387 box(tmp_path, monkeypatch, settings=(), analytics=True, retention=45)
388 body = render()["body"]
389 assert "No privacy policy has been published" in body
390 for key, _value in SIGNED:
391 assert key in body
392 # And it makes no claims while unsigned -- not even true ones.
393 assert "45 days" not in body
394
395
396def test_the_refusal_names_only_the_settings_actually_missing(
397 tmp_path, monkeypatch):
398 box(tmp_path, monkeypatch, settings=SIGNED[:1])
399 fold = privacy.policy()
400 assert fold["controller"]["missing_settings"] == [
401 "privacy.contact_email", "privacy.jurisdiction"]
402 assert fold["controller"]["signed"] is False
403
404 box(tmp_path, monkeypatch, settings=SIGNED)
405 assert privacy.policy()["controller"]["signed"] is True
406
407
408def test_the_cookie_table_is_published_even_when_the_policy_is_not(
409 tmp_path, monkeypatch):
410 """The browser-facing facts are true regardless of who signed them,
411 and a visitor asking what is in their browser deserves an answer even
412 on a box whose operator has not filled the form in."""
413 box(tmp_path, monkeypatch, settings=())
414 body = render("/cookies")["body"]
415 assert "dbbasic_session" in body
416
417
418def test_a_signed_policy_names_the_controller_and_how_to_reach_them(
419 tmp_path, monkeypatch):
420 box(tmp_path, monkeypatch)
421 body = render()["body"]
422 assert "Q9 Ltd" in body
423 assert "England and Wales" in body
424 assert "privacy@example.test" in body
425
426
427def test_the_operators_own_legal_text_is_rendered_and_attributed(
428 tmp_path, monkeypatch):
429 """Under its own heading, so a reader can tell which half of the page
430 is machine-generated fact and which half is a human's statement."""
431 box(tmp_path, monkeypatch,
432 settings=SIGNED + (("privacy.extra_markdown",
433 "Disputes go to the courts of England and Wales."),))
434 body = render()["body"]
435 assert "Additional terms from Q9 Ltd" in body
436 assert "Disputes go to the courts of England and Wales." in body
437 assert "the operator&#x27;s own text" in body or "operator's own text" in body
438
439
440def test_the_three_surfaces_are_one_fold(tmp_path, monkeypatch):
441 """/privacy, /cookies and /privacy.json cannot disagree because there
442 is nothing for them to disagree about."""
443 box(tmp_path, monkeypatch, analytics=True, visitor_cookie=True, retention=90)
444 payload = json.loads(render("/privacy.json")["body"])
445 assert payload["analytics"]["retention_days"] == 90
446 assert {row["name"] for row in payload["cookies"]} == {
447 row["name"] for row in privacy.cookie_table()}
448 assert "90 days" in render()["body"]
449 for row in payload["cookies"]:
450 assert row["name"] in render("/cookies")["body"]
451
452
453def test_the_json_carries_no_timestamp_so_it_can_be_diffed(
454 tmp_path, monkeypatch):
455 """A generated-at stamp would make every fetch differ from the last
456 one and hide the changes that matter -- which is the entire reason
457 somebody would fetch it twice."""
458 box(tmp_path, monkeypatch, analytics=True)
459 assert render("/privacy.json")["body"] == render("/privacy.json")["body"]
460
461
462def test_the_json_is_served_even_unsigned_and_says_it_is_unsigned(
463 tmp_path, monkeypatch):
464 """404ing would leave a monitor guessing. The honest answer is the
465 fold, with `signed: false` in it."""
466 box(tmp_path, monkeypatch, settings=())
467 payload = json.loads(render("/privacy.json")["body"])
468 assert payload["controller"]["signed"] is False
469 assert payload["controller"]["missing_settings"]
470
471
472def test_the_default_box_tells_a_visitor_nothing_is_stored_about_them(
473 tmp_path, monkeypatch):
474 """The posture the whole design is aimed at, read from the visitor's
475 side: analytics off, no cookie but the necessary ones, no third
476 party. This is the page a default install publishes."""
477 box(tmp_path, monkeypatch)
478 body = render()["body"]
479 assert "This server keeps no log of page views" in body
480 assert "No third party is configured" in body
481 assert object_analytics.VISITOR_COOKIE_NAME not in body
482
483
484# ===========================================================================
485# 3. The export: this subject's rows, and nobody else's
486# ===========================================================================
487
488EXPORT_OBJECT = "action_export_subject_data"
489ADMIN = {"_identity": {"user_id": "dan", "roles": ["admin"]}}
490
491ANNA = "anna@example.test"
492BEN = "ben@example.test"
493
494
495def export(payload):
496 return object_execution.execute_object(
497 RUNTIME,
498 object_execution.ObjectExecutionRequest(
499 EXPORT_OBJECT, method="POST", payload=payload),
500 roots=[PRIVACY_OBJECTS]).result
501
502
503@pytest.fixture()
504def two_customers(tmp_path, monkeypatch):
505 """Anna and Ben, each with an order, an invoice, a payment against
506 that invoice and a shipment against that order. The whole point of
507 the fixture is that there are two of them."""
508 data_dir = tmp_path / "data"
509 for package_id, collection in (("app-orders", "orders"),
510 ("app-invoices", "invoices"),
511 ("app-payments", "payments"),
512 ("app-shipping", "shipments"),
513 ("app-shop", "carts"),
514 ("app-disputes", "disputes"),
515 ("app-contacts", "contacts"),
516 ("app-analytics", "conversions"),
517 ("app-analytics", "page_views")):
518 stage_collection(data_dir, package_id, collection)
519 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
520
521 for who, tag in ((ANNA, "a"), (BEN, "b")):
522 object_records.create_collection_record(
523 "orders", {"id": f"ord-{tag}", "number": f"SO-{tag}",
524 "customer_email": who,
525 "customer_name": who.split("@")[0], "status": "confirmed"},
526 base_dir=data_dir, actor="test")
527 object_records.create_collection_record(
528 "invoices", {"id": f"inv-{tag}", "number": f"INV-{tag}",
529 "customer_name": who.split("@")[0],
530 "customer_email": who, "status": "sent",
531 # what the payment below pays: every writer's payment
532 # is checked against its invoice (the ledger check)
533 "total_cents": "1000"},
534 base_dir=data_dir, actor="test")
535 object_records.create_collection_record(
536 "payments", {"id": f"pay-{tag}", "invoice_id": f"inv-{tag}",
537 "amount_cents": "1000", "received_on": "2026-07-01"},
538 base_dir=data_dir, actor="test")
539 object_records.create_collection_record(
540 "shipments", {"id": f"shp-{tag}", "order_id": f"ord-{tag}",
541 "status": "shipped"},
542 base_dir=data_dir, actor="test")
543 object_records.create_collection_record(
544 "carts", {"id": f"cart-{tag}", "session_token": f"tok-{tag}",
545 "customer_email": who, "status": "open"},
546 base_dir=data_dir, actor="test")
547 object_records.create_collection_record(
548 "disputes", {"id": f"dis-{tag}", "customer_email": who,
549 "kind": "delivery", "summary": "missing parcel",
550 "status": "open"},
551 base_dir=data_dir, actor="test")
552 object_records.create_collection_record(
553 "contacts", {"id": f"con-{tag}", "first_name": who.split("@")[0],
554 "email": who},
555 base_dir=data_dir, actor="test")
556 object_records.create_collection_record(
557 "conversions", {"id": f"cv-{tag}", "event_type": "order_confirmed",
558 "metadata": json.dumps({"source": f"orders/ord-{tag}"})},
559 base_dir=data_dir, actor="test")
560 return data_dir
561
562
563def test_the_export_returns_this_subjects_rows_and_nobody_elses(two_customers):
564 """The test that matters in this file's second half.
565
566 An export that leaks a second customer's order into the first
567 customer's subject request is not a partial success; it is a data
568 breach committed by the compliance feature.
569 """
570 result = export({**ADMIN, "email": ANNA})
571 assert result["ok"] is True
572
573 blob = json.dumps(result)
574 assert BEN not in blob
575 for row_id in ("ord-b", "inv-b", "pay-b", "shp-b", "cart-b", "dis-b",
576 "con-b", "cv-b"):
577 assert row_id not in blob, row_id
578
579 ids = {collection: {row["id"] for row in rows}
580 for collection, rows in result["collections"].items()}
581 assert ids["orders"] == {"ord-a"}
582 assert ids["invoices"] == {"inv-a"}
583 assert ids["carts"] == {"cart-a"}
584 assert ids["disputes"] == {"dis-a"}
585 assert ids["contacts"] == {"con-a"}
586
587
588def test_linked_rows_are_reached_only_through_the_subjects_own_records(
589 two_customers):
590 """Payments hang off an invoice and shipments off an order, so the
591 join runs in the safe direction only: the subject's ids select the
592 linked rows, and a payment whose invoice is not theirs is never
593 looked at again."""
594 result = export({**ADMIN, "email": ANNA})
595 assert {row["id"] for row in result["collections"]["payments"]} == {"pay-a"}
596 assert {row["id"] for row in result["collections"]["shipments"]} == {"shp-a"}
597
598
599def test_a_conversion_is_returned_only_when_it_genuinely_names_the_subject(
600 two_customers):
601 """By provenance -- the row names one of their own orders. Never by
602 visitor token: that token is anonymous by construction and joining it
603 to a person here would perform the exact de-anonymisation the
604 analytics rules forbid, inside the feature meant to protect them."""
605 result = export({**ADMIN, "email": ANNA})
606 assert {row["id"] for row in result["collections"]["conversions"]} == {"cv-a"}
607
608
609def test_the_export_says_what_it_cannot_search_rather_than_omitting_it(
610 two_customers):
611 """A silent omission reads as "we hold nothing about you", which is a
612 different and untrue answer."""
613 result = export({**ADMIN, "email": ANNA})
614 collections = {entry["collection"] for entry in result["not_searchable"]}
615 assert "page_views" in collections
616
617
618def _shipped_schemas():
619 """{collection: schema} for every shipped schema, as the installer
620 stores it (normalized), so a key the loader drops counts as absent."""
621 schemas = {}
622 for path in sorted(PACKAGES.glob("*/schemas/*.json")):
623 payload = json.loads(path.read_text())
624 name = payload.get("name") or path.stem
625 schemas[name] = object_schemas.normalize_schema(name, payload)
626 return schemas
627
628
629EXPORT_MODULE = "app-privacy/objects/action/export_subject_data.py"
630
631
632def test_every_shipped_email_field_is_exported_or_declared():
633 """The export's completeness, checked against the schemas instead of
634 against memory. Four customer_email collections (and three more keyed
635 by a recipient address) were once in neither list, and a clinic's
636 patients were never in it at all, so the export read as "that is
637 everything" when it was not. A package with an email-like field fails
638 here until its schema says what the field is ("subject": "email") or
639 why the collection cannot be searched ("subject_exempt")."""
640 module = _module(EXPORT_MODULE)
641 schemas = _shipped_schemas()
642 email_keyed, _linked, _exempt, undeclared = module.declarations(schemas)
643 assert "customer_email" in email_keyed["orders"] # the walk sees something
644 assert undeclared == [], "email-like and undeclared: " + ", ".join(
645 f"{entry['collection']}.{field}" for entry in undeclared for field in entry["fields"])
646
647
648def test_the_declarations_cover_at_least_what_the_old_hard_coded_list_did():
649 """The export used to fold twelve hard-coded (collection, field) pairs
650 and two links. Moving them into the schemas must lose none."""
651 module = _module(EXPORT_MODULE)
652 email_keyed, linked, exempt, _ = module.declarations(_shipped_schemas())
653 before = {
654 ("orders", "customer_email"), ("invoices", "customer_email"),
655 ("carts", "customer_email"), ("disputes", "customer_email"),
656 ("contacts", "email"), ("backorders", "customer_email"),
657 ("promotion_redemptions", "customer_email"),
658 ("return_authorizations", "customer_email"),
659 ("subscriptions", "customer_email"), ("sent_documents", "sent_to"),
660 ("email_outbox", "to"), ("profile_comments", "author_email"),
661 }
662 now = {(collection, field) for collection, fields in email_keyed.items() for field in fields}
663 assert before <= now, sorted(before - now)
664 assert {("payments", "invoice_id", "invoices"),
665 ("shipments", "order_id", "orders")} <= set(linked)
666 assert {"page_views", "conversions", "mail_accounts"} <= {e["collection"] for e in exempt}
667
668
669def test_a_pending_declaration_is_removed_once_its_schema_carries_it():
670 """PENDING_DECLARATIONS stands in for a key a shipped schema does not
671 carry yet (carts: app-shop was being changed at the same time). Once
672 the schema declares it, the entry is dead weight that would hide a
673 later removal from the schema, so this fails until it is deleted."""
674 module = _module(EXPORT_MODULE)
675 schemas = _shipped_schemas()
676 for collection, field_name, _kind in module.PENDING_DECLARATIONS:
677 field = next(f for f in schemas[collection]["fields"] if f["name"] == field_name)
678 assert "subject" not in field, (
679 f"{collection}.{field_name} now declares subject; remove it from "
680 "PENDING_DECLARATIONS")
681
682
683def test_every_subject_relation_points_at_a_collection_that_is_searched():
684 """A relation is only a way in from a record already proven to be the
685 subject's; one aimed at a collection nothing declares would never
686 select anything, and would read as coverage that is not there."""
687 module = _module(EXPORT_MODULE)
688 email_keyed, linked, _, _ = module.declarations(_shipped_schemas())
689 reachable = set(email_keyed) | {collection for collection, _, _ in linked}
690 assert [(c, f, t) for c, f, t in linked if t not in reachable] == []
691
692
693@pytest.mark.parametrize("field, message", [
694 ({"name": "email", "subject": "emial"}, "'subject' must be one of"),
695 ({"name": "patient_id", "subject": "relation"}, "needs a relation"),
696])
697def test_a_misspelt_subject_declaration_fails_at_load(field, message):
698 """Strict, because a typo here would quietly leave a person's records
699 out of their subject access request."""
700 with pytest.raises(ValueError, match=message):
701 object_schemas.normalize_schema("patients", {"fields": [{"name": "id"}, field]})
702 with pytest.raises(ValueError, match="subject_exempt"):
703 object_schemas.normalize_schema("patients", {"fields": [], "subject_exempt": " "})
704
705
706def test_an_absent_collection_is_not_an_empty_one(tmp_path, monkeypatch):
707 """"This server could not look" and "you have none" are different
708 answers to a subject request, and only one of them is about them. A
709 collection a declaration points at that this box does not have is
710 listed in `unavailable`, never shown as an empty list."""
711 data_dir = tmp_path / "data"
712 stage_collection(data_dir, "app-payments", "payments") # points at invoices
713 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
714 result = export({**ADMIN, "email": ANNA})
715 assert "invoices" in result["unavailable"]
716 assert "invoices" not in result["collections"]
717 assert result["counts"]["payments"] == 0
718
719
720# -- a package's own collections: a clinic ------------------------------------
721
722CLINIC = {
723 "patients": [{"name": "id"}, {"name": "name"},
724 {"name": "email", "subject": "email"}],
725 "appointments": [{"name": "id"}, {"name": "at"},
726 {"name": "patient_id", "subject": "relation",
727 "relation": {"collection": "patients"}}],
728 "treatment_notes": [{"name": "id"}, {"name": "note"},
729 {"name": "appointment_id", "subject": "relation",
730 "relation": {"collection": "appointments"}}],
731 # A newsletter list nobody declared anything about.
732 "newsletter": [{"name": "id"}, {"name": "subscriber_email"}],
733}
734
735
736@pytest.fixture()
737def clinic(tmp_path, monkeypatch):
738 data_dir = tmp_path / "data"
739 (data_dir / "schemas").mkdir(parents=True)
740 for name, fields in CLINIC.items():
741 (data_dir / "schemas" / f"{name}.json").write_text(
742 json.dumps({"name": name, "fields": fields}))
743 collection = data_dir / "collections" / name
744 collection.mkdir(parents=True)
745 (collection / "records.tsv").write_text(
746 "\t".join(field["name"] for field in fields) + "\n")
747 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
748 for who, tag in ((ANNA, "a"), (BEN, "b")):
749 for collection, row in (
750 ("patients", {"id": f"pat-{tag}", "name": tag, "email": who}),
751 ("appointments", {"id": f"apt-{tag}", "at": "2026-12-01", "patient_id": f"pat-{tag}"}),
752 ("treatment_notes", {"id": f"note-{tag}", "note": "seen",
753 "appointment_id": f"apt-{tag}"}),
754 ("newsletter", {"id": f"nl-{tag}", "subscriber_email": who})):
755 object_records.create_collection_record(collection, row, base_dir=data_dir, actor="test")
756 return data_dir
757
758
759def test_a_packages_own_collections_are_exported_through_its_declarations(clinic):
760 """The reported gap: a clinic's patients (keyed by email), and the
761 appointments and treatment notes keyed to a patient by id, were
762 silently missing from a subject access request because they were not
763 in a list inside app-privacy. Declared in their own schemas, they are
764 followed however deep the chain goes -- and still nothing of Ben's."""
765 result = export({**ADMIN, "email": ANNA})
766 ids = {name: {row["id"] for row in rows} for name, rows in result["collections"].items()}
767 assert ids["patients"] == {"pat-a"}
768 assert ids["appointments"] == {"apt-a"}
769 assert ids["treatment_notes"] == {"note-a"}
770 assert BEN not in json.dumps(result)
771 assert {"patients", "appointments", "treatment_notes"} <= set(result["searched"])
772
773
774def test_an_undeclared_email_field_is_named_not_silently_skipped(clinic):
775 """Fail visibly: a collection holding an email-like field that declares
776 nothing is listed in not_searchable with what to do about it, because
777 leaving it out reads as "we hold nothing else"."""
778 result = export({**ADMIN, "email": ANNA})
779 entry = next(e for e in result["not_searchable"] if e["collection"] == "newsletter")
780 assert entry["undeclared"] is True
781 assert entry["fields"] == ["subscriber_email"]
782 assert "newsletter" not in result["collections"]
783
784
785def test_the_export_refuses_anybody_who_is_not_an_operator(two_customers):
786 """No self-service door: it would be a lookup oracle for anyone who
787 knows a customer's email address."""
788 assert export({"email": ANNA})["status"] == 403
789 assert export({"_identity": {"user_id": "anna", "roles": []},
790 "email": ANNA})["status"] == 403
791 assert export({**ADMIN})["status"] == 400 # no email
792
793
794def test_the_export_does_not_pretend_to_offer_erasure(two_customers):
795 """Deliberately absent rather than quietly half-implemented: erasure
796 needs a redaction-with-tombstone design and a doctrine decision about
797 which fields are contact and which are evidence. Code written before
798 that decision would make the choice silently, in the one place it can
799 never be undone."""
800 result = export({**ADMIN, "email": ANNA})
801 assert "Not available through this action" in result["erasure"]
802
803
804def test_the_email_match_is_case_and_space_insensitive(two_customers):
805 """A subject request arrives typed by a human, not normalized by a
806 form."""
807 result = export({**ADMIN, "email": " ANNA@Example.Test "})
808 assert result["counts"]["orders"] == 1