ledger.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. """Case ledger: opt-out state machine + append-only audit log.
  2. A "case" is one (subject x broker) record. State changes are validated against
  3. TRANSITIONS and mirrored into audit.jsonl so every action is auditable.
  4. """
  5. from __future__ import annotations
  6. import datetime as _dt
  7. from pathlib import Path
  8. import paths
  9. import storage
  10. STATES = [
  11. "new", "searching", "not_found", "found", "indirect_exposure", "action_selected", "submitted",
  12. "verification_pending", "awaiting_processing", "confirmed_removed", "reappeared",
  13. "human_task_queued", "blocked",
  14. ]
  15. TRANSITIONS: dict[str, set[str]] = {
  16. "new": {"searching", "found", "not_found", "indirect_exposure", "blocked"},
  17. "searching": {"not_found", "found", "indirect_exposure", "blocked"},
  18. "not_found": {"searching", "found", "indirect_exposure", "blocked"},
  19. # found -> not_found: a parent re-verification (or re-scan) found the "found" was a false
  20. # positive (namesake, or an address-only property-record match) -- retract it with evidence.
  21. "found": {"action_selected", "submitted", "human_task_queued", "indirect_exposure", "blocked",
  22. "not_found"},
  23. # indirect_exposure: subject's PII (email/phone/name) sits on a THIRD PARTY's record. The
  24. # self-service opt-out form does not apply; the lever is a targeted CCPA/GDPR delete-my-PII
  25. # request (-> submitted) or a human task. Re-scan can clear it (-> not_found) or upgrade it to a
  26. # direct listing (-> found).
  27. "indirect_exposure": {"submitted", "human_task_queued", "not_found", "found", "blocked"},
  28. "action_selected": {"submitted", "human_task_queued", "blocked"},
  29. "submitted": {"verification_pending", "awaiting_processing", "human_task_queued", "blocked"},
  30. # verification_pending -> awaiting_processing: the verify link was opened/acknowledged and the
  31. # broker is now processing the removal (their stated window). confirmed_removed still requires a
  32. # verifying re-scan, never the submission flow's own say-so.
  33. "verification_pending": {"awaiting_processing", "confirmed_removed", "human_task_queued", "blocked"},
  34. "awaiting_processing": {"confirmed_removed", "human_task_queued", "blocked"},
  35. "confirmed_removed": {"reappeared", "confirmed_removed"},
  36. "reappeared": {"found", "indirect_exposure"},
  37. "human_task_queued": {
  38. "found", "indirect_exposure", "action_selected", "submitted", "verification_pending",
  39. "awaiting_processing", "confirmed_removed", "blocked",
  40. },
  41. # blocked: automated tools (web_extract/proxyless browser) couldn't read the site. A later pass
  42. # -- a stealth/cloud browser OR guiding the operator's own (residential) browser -- can resolve it
  43. # to any real scan verdict, so blocked reaches not_found / indirect_exposure too, not just found.
  44. # blocked -> human_task_queued: some blocked sites need an operator step to proceed at all
  45. # (face-recognition sites needing a selfie/gov-ID, etc.), so route them to the digest.
  46. "blocked": {"searching", "found", "not_found", "indirect_exposure", "action_selected",
  47. "human_task_queued"},
  48. }
  49. # A defunct broker (structured `defunct` field in its record: domain seized / NXDOMAIN) cannot
  50. # hold a listing, so its open case may close as not_found from an in-flight state. Gated on the
  51. # broker record via `can_transition(..., broker_defunct=True)`: a LIVE broker's in-flight request
  52. # waits out its processing window and is confirmed by a verifying re-scan instead.
  53. DEFUNCT_CLOSEOUT_FROM = frozenset({"action_selected", "submitted", "verification_pending",
  54. "awaiting_processing", "human_task_queued"})
  55. def now() -> str:
  56. return _dt.datetime.now(_dt.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
  57. def load(subject_id: str) -> dict:
  58. return storage.read_json(paths.ledger_path(subject_id), {}) or {}
  59. def save(subject_id: str, ledger: dict) -> Path:
  60. return storage.write_json(paths.ledger_path(subject_id), ledger)
  61. def new_case(subject_id: str, broker_id: str) -> dict:
  62. return {
  63. "case_id": f"case_{subject_id}_{broker_id}",
  64. "subject_id": subject_id,
  65. "broker_id": broker_id,
  66. "state": "new",
  67. "found": None,
  68. "evidence": {},
  69. "disclosure_log": [],
  70. "history": [],
  71. }
  72. def get_case(subject_id: str, broker_id: str) -> dict:
  73. return load(subject_id).get(broker_id) or new_case(subject_id, broker_id)
  74. def can_transition(old: str, new: str, *, broker_defunct: bool = False) -> bool:
  75. if new == old or new in TRANSITIONS.get(old, set()):
  76. return True
  77. return broker_defunct and new == "not_found" and old in DEFUNCT_CLOSEOUT_FROM
  78. def transition(subject_id: str, broker_id: str, new_state: str, *, broker_defunct: bool = False,
  79. **fields) -> dict:
  80. if new_state not in STATES:
  81. raise ValueError(f"unknown state {new_state!r}")
  82. # Lock the whole load-modify-save so a concurrent cron re-scan / other tenant
  83. # can't read a stale ledger and clobber this transition.
  84. with storage.locked(paths.ledger_path(subject_id)):
  85. ledger = load(subject_id)
  86. case = ledger.get(broker_id) or new_case(subject_id, broker_id)
  87. old = case.get("state", "new")
  88. if not can_transition(old, new_state, broker_defunct=broker_defunct):
  89. raise ValueError(f"illegal transition {old!r} -> {new_state!r} for broker {broker_id!r}")
  90. case["state"] = new_state
  91. if new_state == "not_found":
  92. # not_found schedules no follow-up; a recheck date left by the prior state would
  93. # keep `next` waking for a closed case.
  94. case.pop("next_recheck_at", None)
  95. for key, value in fields.items():
  96. case[key] = value
  97. stamp = now()
  98. case.setdefault("history", []).append({"at": stamp, "from": old, "to": new_state})
  99. ledger[broker_id] = case
  100. save(subject_id, ledger)
  101. storage.append_jsonl(
  102. paths.audit_path(subject_id),
  103. {"at": stamp, "broker_id": broker_id, "event": "transition", "from": old, "to": new_state},
  104. )
  105. return case
  106. DEFAULT_PROCESSING_DAYS = 14 # when a broker record doesn't state est_processing_days
  107. VERIFICATION_POLL_DAYS = 1 # how soon to re-poll for an unarrived verification email
  108. def _plus_days(days: int, start: str | None = None) -> str:
  109. base = _dt.datetime.strptime(start, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=_dt.UTC) \
  110. if start else _dt.datetime.now(_dt.UTC)
  111. return (base + _dt.timedelta(days=days)).strftime("%Y-%m-%dT%H:%M:%SZ")
  112. def followup_fields(new_state: str, broker: dict | None = None,
  113. dossier: dict | None = None) -> dict:
  114. """Auto-scheduling stamps for a transition, so nobody has to remember follow-ups.
  115. submitted / awaiting_processing -> recheck after the broker's stated processing window;
  116. verification_pending -> re-poll the inbox quickly;
  117. confirmed_removed -> periodic reappearance re-scan per subject preference.
  118. """
  119. if new_state in ("submitted", "awaiting_processing"):
  120. days = ((broker or {}).get("optout") or {}).get("est_processing_days") or DEFAULT_PROCESSING_DAYS
  121. return {"next_recheck_at": _plus_days(int(days))}
  122. if new_state == "verification_pending":
  123. return {"next_recheck_at": _plus_days(VERIFICATION_POLL_DAYS)}
  124. if new_state == "confirmed_removed":
  125. interval = ((dossier or {}).get("preferences") or {}).get("rescan_interval_days") or 120
  126. return {"removal_confirmed_at": now(), "next_recheck_at": _plus_days(int(interval))}
  127. return {}
  128. def due(subject_id: str, at: str | None = None, ledger: dict | None = None) -> list[dict]:
  129. """Cases whose next_recheck_at has arrived - the autonomous follow-up queue."""
  130. stamp = at or now()
  131. out = []
  132. for case in (ledger if ledger is not None else load(subject_id)).values():
  133. when = case.get("next_recheck_at")
  134. if when and when <= stamp:
  135. out.append(case)
  136. out.sort(key=lambda c: c.get("next_recheck_at") or "")
  137. return out
  138. def log_disclosure(subject_id: str, broker_id: str, fields: list[str], channel: str) -> dict:
  139. """Record exactly which PII field *names* were disclosed to a broker."""
  140. with storage.locked(paths.ledger_path(subject_id)):
  141. ledger = load(subject_id)
  142. case = ledger.get(broker_id) or new_case(subject_id, broker_id)
  143. stamp = now()
  144. record = {"at": stamp, "fields": sorted(fields), "channel": channel}
  145. case.setdefault("disclosure_log", []).append(record)
  146. ledger[broker_id] = case
  147. save(subject_id, ledger)
  148. storage.append_jsonl(
  149. paths.audit_path(subject_id),
  150. {"at": stamp, "broker_id": broker_id, "event": "disclosure",
  151. "fields": record["fields"], "channel": channel},
  152. )
  153. return record