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.
export_subject_data.py · 16.1 KB · 379 lines
| 1 | """action_export_subject_data -- everything this server holds against one |
| 2 | email address, folded into one JSON document. |
| 3 | |
| 4 | POST {email} -> {ok, email, collections: {...}, counts: {...}, searched: [...], |
| 5 | unavailable: [...], not_searchable: [...]} |
| 6 | |
| 7 | The access/portability half of a subject request, and the half this system |
| 8 | can do honestly. Almost everything a customer gives this server is keyed |
| 9 | by an email address -- orders, invoices, disputes, a clinic's patients -- |
| 10 | and the rest hangs off those by id: payments belong to an invoice, |
| 11 | shipments to an order, appointments to a patient. So the export is a fold, |
| 12 | not a search, and it can be complete in a way a keyword search over a |
| 13 | database never is. |
| 14 | |
| 15 | ## What it folds: the schemas say, not this file |
| 16 | |
| 17 | Each installed collection's schema declares its part (docs/package- |
| 18 | authoring.md, "Personal data: the subject export"): |
| 19 | |
| 20 | - a field with `"subject": "email"` holds the data subject's email address: |
| 21 | a row whose value is the subject's address is theirs; |
| 22 | - a field with `"subject": "relation"` is a relation to a record already |
| 23 | proven to be the subject's: a row pointing at one of those is theirs too |
| 24 | (followed to a fixpoint, so treatment notes -> appointments -> patients |
| 25 | works however deep); |
| 26 | - a root `"subject_exempt": "<why>"` says the collection cannot be searched |
| 27 | for a person, and why; the reason is returned in `not_searchable`. |
| 28 | |
| 29 | It used to be a hard-coded list of twelve (collection, field) pairs here. |
| 30 | A package nobody had added to it -- a clinic's `patients`, keyed by email, |
| 31 | and its appointments and treatment notes, keyed to a patient by id -- was |
| 32 | silently missing from the answer, and a missing collection reads as "we |
| 33 | hold nothing else" (bug-reports/2026-11-30-03-21-08). Now the package that owns the |
| 34 | data says what in it is personal, and an installed collection with an |
| 35 | email-like field that declares nothing is named in `not_searchable` as |
| 36 | undeclared rather than skipped in silence. tests/test_privacy.py fails when |
| 37 | a shipped schema has an email-like field and no declaration. |
| 38 | |
| 39 | ## The property it is judged on: nothing keyed to anybody else |
| 40 | |
| 41 | An export that leaks a second customer's order into the first customer's |
| 42 | subject request is not a partial success, it is a data breach performed by |
| 43 | the compliance feature. So relations run only in the safe direction: the |
| 44 | subject's own rows' ids select the rows that point at them, and a row whose |
| 45 | parent is not the subject's is never looked at again. A relation is |
| 46 | followed only where its schema declares `"subject": "relation"`: a pointer |
| 47 | to a shared record (a product, a price list) is never a way in. |
| 48 | tests/test_privacy.py stages two customers and asserts one export contains |
| 49 | nothing of the other's -- that is the test that matters here. |
| 50 | |
| 51 | ## Admin-executed, always |
| 52 | |
| 53 | There is no self-service door. A page that returned somebody's entire |
| 54 | order history to whoever typed their email address would be a lookup |
| 55 | oracle for anyone who knows a customer's address, and the identity check a |
| 56 | real subject request needs -- "prove you are this person" -- is a human |
| 57 | judgement rather than an HTTP parameter. So this refuses anyone who is not |
| 58 | an operator, and the operator runs it after satisfying themselves who they |
| 59 | are talking to. |
| 60 | |
| 61 | ## What it deliberately does NOT return, and says so |
| 62 | |
| 63 | `page_views` and untethered `conversions` rows are keyed by IP address and |
| 64 | by an opaque visitor token with no link to a person. They cannot be |
| 65 | searched for a subject in either direction, and guessing -- "these hits |
| 66 | came from an address that once loaded her invoice" -- would invent a link |
| 67 | this system spent real effort not creating. Their schemas say so |
| 68 | (`subject_exempt`) and the reason is returned rather than the collection |
| 69 | silently omitted, because a silent omission reads as "we hold nothing". |
| 70 | |
| 71 | Conversions ARE returned where they are genuinely identifiable: a row |
| 72 | whose `user_id` is this subject's account, or whose provenance names one |
| 73 | of their own orders or invoices. |
| 74 | |
| 75 | ## There is no erasure here, and that is a decision rather than a gap |
| 76 | |
| 77 | Do not add one to this object. Erasure and Doctrine #8 (evidence is never |
| 78 | edited) genuinely conflict: orders, invoices and payments are business |
| 79 | records with statutory retention, and deleting a row an invoice |
| 80 | references does not anonymise a customer, it breaks the ledger. The |
| 81 | resolution the plan argues for is redaction-with-a-tombstone -- the LEDGER |
| 82 | keeps the fact, the CONTACT record loses the identifier, and the tombstone |
| 83 | records that a redaction happened so a later reader knows the gap is |
| 84 | deliberate rather than corruption. That needs a doctrine decision about |
| 85 | which fields are contact and which are evidence, per collection, and how |
| 86 | long each is retained, before any code is written. It is an open decision |
| 87 | for the owner. A `delete_subject_data` written before that decision would |
| 88 | make the choice silently, one collection at a time, in the one place it |
| 89 | can never be undone. The `subject` declarations say what is personal; they |
| 90 | deliberately say nothing about what may be erased. |
| 91 | """ |
| 92 | |
| 93 | import json |
| 94 | import os |
| 95 | |
| 96 | import object_identity |
| 97 | import object_records |
| 98 | import object_schemas |
| 99 | |
| 100 | ACTOR = "action_export_subject_data" |
| 101 | DATA_DIR_ENV = "DBBASIC_DATA_DIR" |
| 102 | |
| 103 | SUBJECT_EMAIL = "email" |
| 104 | SUBJECT_RELATION = "relation" |
| 105 | |
| 106 | # A field that looks like it holds an email address: named *email*, typed |
| 107 | # email, or one of the recipient names the mail-sending collections use. |
| 108 | # Used only to NAME a collection that declares nothing; it never decides |
| 109 | # what is searched. |
| 110 | EMAIL_LIKE_NAMES = ("sent_to", "to") |
| 111 | |
| 112 | # Declarations a shipped schema is owed but does not carry yet, because its |
| 113 | # package is being changed elsewhere at the same time. Applied only while |
| 114 | # the installed schema says nothing about that field, and |
| 115 | # tests/test_privacy.py fails as soon as the shipped schema declares it, so |
| 116 | # an entry cannot outlive its reason. (collection, field, kind) |
| 117 | PENDING_DECLARATIONS = () |
| 118 | |
| 119 | CONVERSIONS = "conversions" |
| 120 | |
| 121 | |
| 122 | def _base_dir(): |
| 123 | return os.environ.get(DATA_DIR_ENV, "data") |
| 124 | |
| 125 | |
| 126 | def _rows(collection, base): |
| 127 | """A collection's rows, or None when they cannot be read. |
| 128 | |
| 129 | None and [] are different answers and the export reports them |
| 130 | differently: "this server could not look" is not "this person has |
| 131 | none".""" |
| 132 | try: |
| 133 | # access: admin-only object (execute grant role:admin) |
| 134 | return object_records.read_collection_records(collection, base_dir=base) |
| 135 | except Exception: |
| 136 | return None |
| 137 | |
| 138 | |
| 139 | def _matches(row, field, email): |
| 140 | return str(row.get(field) or "").strip().lower() == email |
| 141 | |
| 142 | |
| 143 | def email_like(field): |
| 144 | name = str(field.get("name") or "") |
| 145 | return ("email" in name or str(field.get("type") or "") == "email" |
| 146 | or name in EMAIL_LIKE_NAMES) |
| 147 | |
| 148 | |
| 149 | def relation_target(field): |
| 150 | relation = field.get("relation") |
| 151 | if isinstance(relation, str): |
| 152 | return relation.strip() |
| 153 | if isinstance(relation, dict): |
| 154 | return str(relation.get("collection") or "").strip() |
| 155 | return "" |
| 156 | |
| 157 | |
| 158 | def declarations(schemas): |
| 159 | """What the export folds, read from `schemas` ({name: schema}). |
| 160 | |
| 161 | Returns (email_keyed, linked, exempt, undeclared): |
| 162 | `email_keyed` {collection: [field, ...]}; `linked` [(collection, field, |
| 163 | target collection)]; `exempt` [{collection, reason}] from |
| 164 | `subject_exempt`; `undeclared` [{collection, fields, undeclared, reason}] |
| 165 | for a collection with an email-like field that declares nothing. Pure, |
| 166 | so a test can hand it the shipped schemas.""" |
| 167 | pending = {} |
| 168 | for collection, field_name, kind in PENDING_DECLARATIONS: |
| 169 | pending.setdefault(collection, {})[field_name] = kind |
| 170 | email_keyed, linked, exempt, undeclared = {}, [], [], [] |
| 171 | for name in sorted(schemas): |
| 172 | schema = schemas[name] or {} |
| 173 | silent = [] |
| 174 | for field in schema.get("fields") or []: |
| 175 | if not isinstance(field, dict): |
| 176 | continue |
| 177 | field_name = str(field.get("name") or "") |
| 178 | kind = field.get("subject") or pending.get(name, {}).get(field_name) |
| 179 | if kind == SUBJECT_EMAIL: |
| 180 | email_keyed.setdefault(name, []).append(field_name) |
| 181 | elif kind == SUBJECT_RELATION and relation_target(field): |
| 182 | linked.append((name, field_name, relation_target(field))) |
| 183 | elif email_like(field): |
| 184 | silent.append(field_name) |
| 185 | reason = schema.get("subject_exempt") |
| 186 | if isinstance(reason, str) and reason.strip(): |
| 187 | exempt.append({"collection": name, "reason": reason.strip()}) |
| 188 | elif silent: |
| 189 | undeclared.append({ |
| 190 | "collection": name, |
| 191 | "fields": silent, |
| 192 | "undeclared": True, |
| 193 | "reason": ( |
| 194 | "Holds an email-like field (" + ", ".join(silent) + ") but its " |
| 195 | "schema declares no \"subject\" key, so whether its rows are a " |
| 196 | "person's is not stated and it was NOT searched. Check it by " |
| 197 | "hand, and have its package mark the field \"subject\": " |
| 198 | "\"email\" (or the schema \"subject_exempt\" with the reason)."), |
| 199 | }) |
| 200 | return email_keyed, linked, exempt, undeclared |
| 201 | |
| 202 | |
| 203 | def _installed_schemas(base): |
| 204 | """({name: schema} for every collection installed here, [names whose |
| 205 | schema could not be read]), or (None, None) when the installed |
| 206 | collections cannot even be listed.""" |
| 207 | try: |
| 208 | names = [summary["name"] for summary in object_schemas.list_schemas(base_dir=base)] |
| 209 | except Exception: |
| 210 | return None, None |
| 211 | schemas, unreadable = {}, [] |
| 212 | for name in names: |
| 213 | try: |
| 214 | schemas[name] = object_schemas.get_schema(name, base_dir=base) |
| 215 | except Exception: |
| 216 | unreadable.append(name) |
| 217 | return schemas, unreadable |
| 218 | |
| 219 | |
| 220 | def _subject_user_id(base, email): |
| 221 | """The account id for this email, if this server has one. |
| 222 | |
| 223 | Read from identity rather than guessed, and used only to select |
| 224 | conversion rows that already name it. |
| 225 | """ |
| 226 | try: |
| 227 | users = object_identity.list_users(base_dir=base) |
| 228 | except Exception: |
| 229 | return "" |
| 230 | for user in users: |
| 231 | if str(user.get("email") or "").strip().lower() == email: |
| 232 | return str(user.get("user_id") or "") |
| 233 | return "" |
| 234 | |
| 235 | |
| 236 | def _identifiable_conversions(base, email, order_ids, invoice_ids): |
| 237 | """Conversion rows that genuinely name this subject. |
| 238 | |
| 239 | Two ways a row can: it carries their account id, or its provenance |
| 240 | blob names a record already proven to be theirs |
| 241 | (`{"source": "orders/ord-1"}`). Nothing is matched by visitor token -- |
| 242 | that token is anonymous by construction and joining it to a person |
| 243 | here would perform exactly the de-anonymisation the analytics rules |
| 244 | forbid, inside the feature meant to protect them. |
| 245 | """ |
| 246 | rows = _rows(CONVERSIONS, base) |
| 247 | if rows is None: |
| 248 | return None |
| 249 | |
| 250 | user_id = _subject_user_id(base, email) |
| 251 | sources = {f"orders/{oid}" for oid in order_ids} |
| 252 | sources |= {f"invoices/{iid}" for iid in invoice_ids} |
| 253 | |
| 254 | matched = [] |
| 255 | for row in rows: |
| 256 | row_user = str(row.get("user_id") or "").strip() |
| 257 | if user_id and row_user == user_id: |
| 258 | matched.append(row) |
| 259 | continue |
| 260 | try: |
| 261 | metadata = json.loads(str(row.get("metadata") or "") or "{}") |
| 262 | except (TypeError, ValueError): |
| 263 | continue |
| 264 | source = str((metadata or {}).get("source") or "").strip() |
| 265 | if source and source in sources: |
| 266 | matched.append(row) |
| 267 | return matched |
| 268 | |
| 269 | |
| 270 | def POST(request): |
| 271 | identity = (request or {}).get("_identity") or {} |
| 272 | if "admin" not in (identity.get("roles") or []): |
| 273 | # No self-service door on purpose -- see the module docstring. |
| 274 | return {"status": 403, |
| 275 | "error": "Only an operator may export a subject's data. " |
| 276 | "Identifying the person asking is a human judgement, " |
| 277 | "not an HTTP parameter."} |
| 278 | |
| 279 | email = str((request or {}).get("email") or "").strip().lower() |
| 280 | if not email: |
| 281 | return {"status": 400, "error": "email is required"} |
| 282 | |
| 283 | base = _base_dir() |
| 284 | schemas, unreadable = _installed_schemas(base) |
| 285 | if schemas is None: |
| 286 | # Not knowing what is installed is not "nothing is installed". |
| 287 | return {"status": 503, |
| 288 | "error": "The installed collections could not be listed, so what " |
| 289 | "this server holds about anyone cannot be stated. Nothing " |
| 290 | "was exported."} |
| 291 | email_keyed, linked, exempt, undeclared = declarations(schemas) |
| 292 | |
| 293 | unavailable = set(unreadable) |
| 294 | rows_by = {} |
| 295 | |
| 296 | def rows_of(collection): |
| 297 | if collection not in rows_by: |
| 298 | rows_by[collection] = _rows(collection, base) if collection in schemas else None |
| 299 | if rows_by[collection] is None: |
| 300 | unavailable.add(collection) |
| 301 | return rows_by[collection] |
| 302 | |
| 303 | # Ids proven to belong to this subject, per collection. A row reached by |
| 304 | # a relation is selected from these and never from the email again, so |
| 305 | # it can only be reached through a record already established as theirs. |
| 306 | owned = {} |
| 307 | for collection, fields in email_keyed.items(): |
| 308 | rows = rows_of(collection) |
| 309 | if rows is not None: |
| 310 | owned[collection] = {str(row.get("id") or "") for row in rows |
| 311 | if any(_matches(row, field, email) for field in fields)} |
| 312 | for collection, _field, target in linked: |
| 313 | if rows_of(collection) is not None: |
| 314 | owned.setdefault(collection, set()) |
| 315 | if target not in schemas: |
| 316 | unavailable.add(target) |
| 317 | |
| 318 | # Follow relations to a fixpoint: appointments from patients, then the |
| 319 | # treatment notes of those appointments. A pass only ever adds ids and |
| 320 | # there are finitely many rows, so it ends. |
| 321 | grew = True |
| 322 | while grew: |
| 323 | grew = False |
| 324 | for collection, field, target in linked: |
| 325 | rows = rows_by.get(collection) |
| 326 | parents = owned.get(target, set()) - {""} |
| 327 | if rows is None or not parents: |
| 328 | continue |
| 329 | mine = owned[collection] |
| 330 | for row in rows: |
| 331 | row_id = str(row.get("id") or "") |
| 332 | if (row_id and row_id not in mine |
| 333 | and str(row.get(field) or "").strip() in parents): |
| 334 | mine.add(row_id) |
| 335 | grew = True |
| 336 | |
| 337 | collections = {} |
| 338 | counts = {} |
| 339 | for collection in sorted(owned): |
| 340 | ids = owned[collection] - {""} |
| 341 | matched = [row for row in rows_by[collection] if str(row.get("id") or "") in ids] |
| 342 | collections[collection] = matched |
| 343 | counts[collection] = len(matched) |
| 344 | |
| 345 | if CONVERSIONS in schemas: |
| 346 | conversions = _identifiable_conversions( |
| 347 | base, email, owned.get("orders", set()), owned.get("invoices", set())) |
| 348 | if conversions is None: |
| 349 | unavailable.add(CONVERSIONS) |
| 350 | else: |
| 351 | collections[CONVERSIONS] = conversions |
| 352 | counts[CONVERSIONS] = len(conversions) |
| 353 | |
| 354 | return { |
| 355 | "status": 200, |
| 356 | "ok": True, |
| 357 | "email": email, |
| 358 | "collections": collections, |
| 359 | "counts": counts, |
| 360 | "total": sum(counts.values()), |
| 361 | # Every installed collection a declaration made this export look in. |
| 362 | "searched": sorted(collections), |
| 363 | # Collections it could NOT look in: one a declaration here points at |
| 364 | # that this box does not have, or one whose schema or rows could not |
| 365 | # be read. Kept apart from the ones it read and found nothing in: |
| 366 | # "we could not look" and "you have none" are different answers to |
| 367 | # a subject request and only one of them is about them. |
| 368 | "unavailable": sorted(unavailable), |
| 369 | # Installed collections this export cannot search for a person, each |
| 370 | # with the reason: declared by its schema (`subject_exempt`), or |
| 371 | # holding an email-like field and declaring nothing (`undeclared`). |
| 372 | "not_searchable": exempt + undeclared, |
| 373 | # Erasure is deliberately not offered here. See the docstring. |
| 374 | "erasure": "Not available through this action. Business records have " |
| 375 | "a statutory retention period and the redaction design " |
| 376 | "that would honour an erasure request without breaking the " |
| 377 | "ledger has not been decided yet; write to the contact " |
| 378 | "address on /privacy.", |
| 379 | } |