309 行
17 KiB
Python
309 行
17 KiB
Python
|
|
# -*- coding: utf-8 -*-
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
from copy import deepcopy
|
||
|
|
import threading
|
||
|
|
import unittest
|
||
|
|
|
||
|
|
from unified_person_contract import build_identity_key, build_person_projection, empty_unified_person_store, resolve_identity, validate_projection
|
||
|
|
from unified_person_registry import UnifiedPersonRegistry
|
||
|
|
|
||
|
|
|
||
|
|
RESULT_FIELDS = {
|
||
|
|
"ok", "code", "operation_id", "changed", "person_id", "affected_person_ids", "projection_revision", "audit_event_id",
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
def identity(subject_id: str, *, bot: str = "bot-1", adapter: str = "telegram-main", namespace: str = "telegram.user") -> dict[str, str]:
|
||
|
|
return {
|
||
|
|
"companion_instance_id": "companion-a",
|
||
|
|
"bot_account_id": bot,
|
||
|
|
"adapter_instance_id": adapter,
|
||
|
|
"subject_namespace": namespace,
|
||
|
|
"platform_subject_id": subject_id,
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
class UnifiedPersonRegistryTests(unittest.TestCase):
|
||
|
|
def setUp(self) -> None:
|
||
|
|
self.store = {"unified_person": empty_unified_person_store()}
|
||
|
|
self.registry = UnifiedPersonRegistry(self.store)
|
||
|
|
|
||
|
|
def _observe(self, subject_id: str, operation_id: str) -> dict:
|
||
|
|
return self.registry.upsert_observed_identity(identity(subject_id), operation_id=operation_id, display_name=f"user-{subject_id}")
|
||
|
|
|
||
|
|
def test_concurrent_same_identity_upsert_creates_one_profile_and_link(self):
|
||
|
|
barrier = threading.Barrier(8)
|
||
|
|
results: list[dict] = []
|
||
|
|
result_lock = threading.Lock()
|
||
|
|
|
||
|
|
def worker(index: int) -> None:
|
||
|
|
barrier.wait()
|
||
|
|
result = self._observe("42", f"observe-{index}")
|
||
|
|
with result_lock:
|
||
|
|
results.append(result)
|
||
|
|
|
||
|
|
threads = [threading.Thread(target=worker, args=(index,)) for index in range(8)]
|
||
|
|
for thread in threads:
|
||
|
|
thread.start()
|
||
|
|
for thread in threads:
|
||
|
|
thread.join()
|
||
|
|
self.assertEqual(len(results), 8)
|
||
|
|
self.assertEqual(sum(result["code"] == "person_created" for result in results), 1)
|
||
|
|
self.assertEqual(len(self.store["unified_person"]["profiles"]), 1)
|
||
|
|
self.assertEqual(len(self.store["unified_person"]["identity_links"]), 1)
|
||
|
|
for result in results:
|
||
|
|
self.assertTrue(RESULT_FIELDS.issubset(result))
|
||
|
|
self.assertTrue(result["operation_id"].startswith("observe-"))
|
||
|
|
other_bot = self.registry.upsert_observed_identity(identity("42", bot="bot-2"), operation_id="observe-other-bot")
|
||
|
|
other_namespace = self.registry.upsert_observed_identity(identity("42", namespace="telegram.channel_author"), operation_id="observe-other-namespace")
|
||
|
|
self.assertNotEqual(other_bot["person_id"], other_namespace["person_id"])
|
||
|
|
self.assertEqual(len(self.store["unified_person"]["profiles"]), 3)
|
||
|
|
|
||
|
|
def test_explicit_link_unlink_is_idempotent_and_never_uses_weak_aliases(self):
|
||
|
|
first = self._observe("42", "observe-42")
|
||
|
|
person_id = first["person_id"]
|
||
|
|
before = deepcopy(self.store)
|
||
|
|
denied = self.registry.link_identity(
|
||
|
|
identity("alice-name"), person_id, operation_id="link-denied", actor_id="operator", reason="nickname match", authorized=False,
|
||
|
|
)
|
||
|
|
self.assertEqual(denied["code"], "unauthorized")
|
||
|
|
self.assertEqual(denied["operation_id"], "link-denied")
|
||
|
|
self.assertEqual(self.store, before)
|
||
|
|
|
||
|
|
linked = self.registry.link_identity(
|
||
|
|
identity("web-verified-7", adapter="webchat-main", namespace="webchat.web_account_id"),
|
||
|
|
person_id,
|
||
|
|
operation_id="link-explicit",
|
||
|
|
actor_id="owner-person",
|
||
|
|
reason="owner verified account binding",
|
||
|
|
authorized=True,
|
||
|
|
)
|
||
|
|
self.assertTrue(linked["changed"])
|
||
|
|
self.assertEqual(linked["person_id"], person_id)
|
||
|
|
repeated = self.registry.link_identity(
|
||
|
|
identity("web-verified-7", adapter="webchat-main", namespace="webchat.web_account_id"),
|
||
|
|
person_id,
|
||
|
|
operation_id="link-explicit",
|
||
|
|
actor_id="owner-person",
|
||
|
|
reason="owner verified account binding",
|
||
|
|
authorized=True,
|
||
|
|
)
|
||
|
|
self.assertTrue(repeated["idempotent"])
|
||
|
|
resolved = resolve_identity(self.store, identity("web-verified-7", adapter="webchat-main", namespace="webchat.web_account_id"))
|
||
|
|
self.assertEqual(resolved["person_id"], person_id)
|
||
|
|
self.assertEqual(resolved["projection"]["resolved_identity_key"], build_identity_key(identity("web-verified-7", adapter="webchat-main", namespace="webchat.web_account_id")))
|
||
|
|
|
||
|
|
unlinked = self.registry.unlink_identity(
|
||
|
|
identity("web-verified-7", adapter="webchat-main", namespace="webchat.web_account_id"),
|
||
|
|
operation_id="unlink-explicit", actor_id="owner-person", reason="binding revoked", authorized=True,
|
||
|
|
)
|
||
|
|
self.assertTrue(unlinked["changed"])
|
||
|
|
link = self.store["unified_person"]["identity_links"][unlinked["identity_key"]]
|
||
|
|
self.assertEqual(link["status"], "unlinked")
|
||
|
|
self.assertEqual(link["origin_identity_key"], unlinked["identity_key"])
|
||
|
|
|
||
|
|
def test_merge_split_restore_exact_links_and_require_owner_authorization(self):
|
||
|
|
source_id = self._observe("42", "observe-source")["person_id"]
|
||
|
|
target_id = self._observe("99", "observe-target")["person_id"]
|
||
|
|
self.store["unified_person"]["profiles"][source_id]["owner_mode"] = "owner"
|
||
|
|
self.store["unified_person"]["profiles"][source_id]["projection_revision"] = 10
|
||
|
|
self.store["unified_person"]["profiles"][target_id]["projection_revision"] = 2
|
||
|
|
before = deepcopy(self.store)
|
||
|
|
denied = self.registry.merge_people(
|
||
|
|
source_id, target_id, operation_id="merge-denied", actor_id="operator", reason="owner request", authorized=True,
|
||
|
|
)
|
||
|
|
self.assertEqual(denied["code"], "owner_authorization_required")
|
||
|
|
self.assertEqual(self.store, before)
|
||
|
|
merged = self.registry.merge_people(
|
||
|
|
source_id, target_id, operation_id="merge-1", actor_id="owner-person", reason="explicit account merge", authorized=True, owner_authorized=True,
|
||
|
|
)
|
||
|
|
self.assertTrue(merged["changed"])
|
||
|
|
self.assertEqual(self.store["unified_person"]["profiles"][source_id]["profile_status"], "suspended")
|
||
|
|
source_key = build_identity_key(identity("42"))
|
||
|
|
self.assertEqual(self.store["unified_person"]["identity_links"][source_key]["person_id"], target_id)
|
||
|
|
consumed_merge_projection = resolve_identity(self.store, identity("42"))["projection"]
|
||
|
|
merge_revision = consumed_merge_projection["projection_revision"]
|
||
|
|
self.assertEqual(merge_revision, 11)
|
||
|
|
split_denied = self.registry.split_merged_people(
|
||
|
|
"merge-1", operation_id="split-denied", actor_id="operator", reason="try", authorized=True,
|
||
|
|
)
|
||
|
|
self.assertEqual(split_denied["code"], "owner_authorization_required")
|
||
|
|
split = self.registry.split_merged_people(
|
||
|
|
"merge-1", operation_id="split-1", actor_id="owner-person", reason="explicit undo", authorized=True, owner_authorized=True,
|
||
|
|
)
|
||
|
|
self.assertTrue(split["changed"])
|
||
|
|
self.assertEqual(self.store["unified_person"]["identity_links"][source_key]["person_id"], source_id)
|
||
|
|
self.assertEqual(self.store["unified_person"]["profiles"][source_id]["profile_status"], "active")
|
||
|
|
self.assertEqual(self.store["unified_person"]["merge_operations"]["merge-1"]["state"], "reversed")
|
||
|
|
split_projection = resolve_identity(self.store, identity("42"))["projection"]
|
||
|
|
self.assertGreater(split_projection["projection_revision"], merge_revision)
|
||
|
|
|
||
|
|
def test_split_preserves_unrelated_target_follow_up_state(self):
|
||
|
|
source_id = self._observe("42", "observe-source-follow-up")["person_id"]
|
||
|
|
target_id = self._observe("99", "observe-target-follow-up")["person_id"]
|
||
|
|
source = self.store["unified_person"]["profiles"][source_id]
|
||
|
|
source["aliases"] = ["source-only-alias"]
|
||
|
|
overlay_key = "group-follow-up"
|
||
|
|
self.store["unified_person"]["group_overlays"][overlay_key] = {
|
||
|
|
"person_id": source_id,
|
||
|
|
"origin_person_id": "preexisting-origin",
|
||
|
|
"merge_operation_id": "preexisting-merge",
|
||
|
|
"group_id": "group-1",
|
||
|
|
"policy": {"quiet_hours": False},
|
||
|
|
}
|
||
|
|
merged = self.registry.merge_people(
|
||
|
|
source_id, target_id, operation_id="merge-follow-up", actor_id="operator",
|
||
|
|
reason="explicit account merge", authorized=True,
|
||
|
|
)
|
||
|
|
self.assertTrue(merged["ok"])
|
||
|
|
merged_overlay = self.store["unified_person"]["group_overlays"][overlay_key]
|
||
|
|
self.assertEqual(merged_overlay["person_id"], target_id)
|
||
|
|
self.assertEqual(merged_overlay["origin_person_id"], source_id)
|
||
|
|
self.assertEqual(merged_overlay["merge_operation_id"], "merge-follow-up")
|
||
|
|
merged_overlay["policy"]["quiet_hours"] = True
|
||
|
|
merged_overlay["post_merge_note"] = "must survive split"
|
||
|
|
target = self.store["unified_person"]["profiles"][target_id]
|
||
|
|
target.update({
|
||
|
|
"display_name": "target after merge",
|
||
|
|
"relation_policy_id": "default_friend",
|
||
|
|
"aliases": list(target.get("aliases") or []) + ["target-follow-up-alias"],
|
||
|
|
"unrelated_follow_up": {"note": "must survive split"},
|
||
|
|
"projection_revision": merged["projection_revision"] + 7,
|
||
|
|
"last_operation_id": "target-unrelated-follow-up",
|
||
|
|
})
|
||
|
|
current_target_revision = target["projection_revision"]
|
||
|
|
|
||
|
|
split = self.registry.split_merged_people(
|
||
|
|
"merge-follow-up", operation_id="split-follow-up", actor_id="operator",
|
||
|
|
reason="explicit undo", authorized=True,
|
||
|
|
)
|
||
|
|
|
||
|
|
self.assertTrue(split["ok"])
|
||
|
|
restored_source = self.store["unified_person"]["profiles"][source_id]
|
||
|
|
preserved_target = self.store["unified_person"]["profiles"][target_id]
|
||
|
|
self.assertEqual(restored_source["aliases"], ["source-only-alias"])
|
||
|
|
self.assertEqual(preserved_target["display_name"], "target after merge")
|
||
|
|
self.assertIn("target-follow-up-alias", preserved_target["aliases"])
|
||
|
|
self.assertNotIn("source-only-alias", preserved_target["aliases"])
|
||
|
|
self.assertEqual(preserved_target["unrelated_follow_up"], {"note": "must survive split"})
|
||
|
|
restored_overlay = self.store["unified_person"]["group_overlays"][overlay_key]
|
||
|
|
self.assertEqual(restored_overlay["person_id"], source_id)
|
||
|
|
self.assertEqual(restored_overlay["origin_person_id"], "preexisting-origin")
|
||
|
|
self.assertEqual(restored_overlay["merge_operation_id"], "preexisting-merge")
|
||
|
|
self.assertTrue(restored_overlay["policy"]["quiet_hours"])
|
||
|
|
self.assertEqual(restored_overlay["post_merge_note"], "must survive split")
|
||
|
|
self.assertGreater(restored_source["projection_revision"], merged["projection_revision"])
|
||
|
|
self.assertGreater(preserved_target["projection_revision"], merged["projection_revision"])
|
||
|
|
self.assertGreater(restored_source["projection_revision"], current_target_revision)
|
||
|
|
self.assertEqual(restored_source["projection_revision"], preserved_target["projection_revision"])
|
||
|
|
after_split = deepcopy(self.store)
|
||
|
|
repeated = self.registry.split_merged_people(
|
||
|
|
"merge-follow-up", operation_id="split-follow-up", actor_id="operator",
|
||
|
|
reason="explicit undo", authorized=True,
|
||
|
|
)
|
||
|
|
self.assertTrue(repeated["idempotent"])
|
||
|
|
self.assertEqual(self.store, after_split)
|
||
|
|
|
||
|
|
def test_split_conflicts_without_writes_when_a_moved_link_changes(self):
|
||
|
|
for mutation in ("rebind", "delete"):
|
||
|
|
with self.subTest(mutation=mutation):
|
||
|
|
self.store = {"unified_person": empty_unified_person_store()}
|
||
|
|
self.registry = UnifiedPersonRegistry(self.store)
|
||
|
|
source_id = self._observe("42", f"observe-source-{mutation}")["person_id"]
|
||
|
|
target_id = self._observe("99", f"observe-target-{mutation}")["person_id"]
|
||
|
|
merged = self.registry.merge_people(
|
||
|
|
source_id, target_id, operation_id=f"merge-{mutation}", actor_id="operator",
|
||
|
|
reason="explicit account merge", authorized=True,
|
||
|
|
)
|
||
|
|
self.assertTrue(merged["ok"])
|
||
|
|
source_key = build_identity_key(identity("42"))
|
||
|
|
if mutation == "rebind":
|
||
|
|
self.store["unified_person"]["identity_links"][source_key]["last_operation_id"] = "later-explicit-rebind"
|
||
|
|
else:
|
||
|
|
del self.store["unified_person"]["identity_links"][source_key]
|
||
|
|
before = deepcopy(self.store)
|
||
|
|
|
||
|
|
split = self.registry.split_merged_people(
|
||
|
|
f"merge-{mutation}", operation_id=f"split-{mutation}", actor_id="operator",
|
||
|
|
reason="must not overwrite changed link", authorized=True,
|
||
|
|
)
|
||
|
|
|
||
|
|
self.assertEqual(split["code"], "split_conflict")
|
||
|
|
self.assertEqual(self.store, before)
|
||
|
|
|
||
|
|
def test_split_conflicts_without_writes_when_overlay_provenance_changes(self):
|
||
|
|
source_id = self._observe("42", "observe-source-overlay-conflict")["person_id"]
|
||
|
|
target_id = self._observe("99", "observe-target-overlay-conflict")["person_id"]
|
||
|
|
self.store["unified_person"]["group_overlays"]["group-overlay-conflict"] = {
|
||
|
|
"person_id": source_id,
|
||
|
|
"group_id": "group-1",
|
||
|
|
"policy": {"quiet_hours": False},
|
||
|
|
}
|
||
|
|
merged = self.registry.merge_people(
|
||
|
|
source_id, target_id, operation_id="merge-overlay-conflict", actor_id="operator",
|
||
|
|
reason="explicit account merge", authorized=True,
|
||
|
|
)
|
||
|
|
self.assertTrue(merged["ok"])
|
||
|
|
self.store["unified_person"]["group_overlays"]["group-overlay-conflict"]["origin_person_id"] = "later-origin"
|
||
|
|
before = deepcopy(self.store)
|
||
|
|
|
||
|
|
split = self.registry.split_merged_people(
|
||
|
|
"merge-overlay-conflict", operation_id="split-overlay-conflict", actor_id="operator",
|
||
|
|
reason="must not overwrite changed overlay provenance", authorized=True,
|
||
|
|
)
|
||
|
|
|
||
|
|
self.assertEqual(split["code"], "split_conflict")
|
||
|
|
self.assertEqual(self.store, before)
|
||
|
|
|
||
|
|
def test_operation_id_conflict_and_bad_requests_do_not_partially_write(self):
|
||
|
|
first = self._observe("42", "same-operation")
|
||
|
|
before = deepcopy(self.store)
|
||
|
|
conflict = self.registry.upsert_observed_identity(identity("99"), operation_id="same-operation", display_name="user-99")
|
||
|
|
self.assertEqual(conflict["code"], "operation_id_conflict")
|
||
|
|
self.assertEqual(self.store, before)
|
||
|
|
malformed = self.registry.upsert_observed_identity({"platform_subject_id": "42"}, operation_id="malformed")
|
||
|
|
self.assertEqual(malformed["code"], "invalid_identity")
|
||
|
|
self.assertEqual(self.store, before)
|
||
|
|
self.assertTrue(RESULT_FIELDS.issubset(first))
|
||
|
|
|
||
|
|
def test_owner_link_unlink_and_primary_failover_preserve_a_valid_projection(self):
|
||
|
|
owner_id = self._observe("42", "observe-owner")["person_id"]
|
||
|
|
self.store["unified_person"]["profiles"][owner_id]["owner_mode"] = "owner"
|
||
|
|
before = deepcopy(self.store)
|
||
|
|
denied_link = self.registry.link_identity(
|
||
|
|
identity("43"), owner_id, operation_id="owner-link-denied", actor_id="operator", reason="test", authorized=True,
|
||
|
|
)
|
||
|
|
self.assertEqual(denied_link["code"], "owner_authorization_required")
|
||
|
|
self.assertEqual(self.store, before)
|
||
|
|
linked = self.registry.link_identity(
|
||
|
|
identity("43"), owner_id, operation_id="owner-link", actor_id="owner", reason="verified", authorized=True, owner_authorized=True,
|
||
|
|
)
|
||
|
|
self.assertTrue(linked["changed"])
|
||
|
|
denied_unlink = self.registry.unlink_identity(
|
||
|
|
identity("42"), operation_id="owner-unlink-denied", actor_id="operator", reason="test", authorized=True,
|
||
|
|
)
|
||
|
|
self.assertEqual(denied_unlink["code"], "owner_authorization_required")
|
||
|
|
primary_key = build_identity_key(identity("42"))
|
||
|
|
unlinked = self.registry.unlink_identity(
|
||
|
|
identity("42"), operation_id="owner-unlink", actor_id="owner", reason="verified revoke", authorized=True, owner_authorized=True,
|
||
|
|
)
|
||
|
|
self.assertTrue(unlinked["changed"])
|
||
|
|
profile = self.store["unified_person"]["profiles"][owner_id]
|
||
|
|
self.assertNotEqual(profile["resolved_identity_key"], primary_key)
|
||
|
|
projection = build_person_projection(self.store, owner_id)
|
||
|
|
self.assertIsNotNone(projection)
|
||
|
|
self.assertEqual(validate_projection(projection), [])
|
||
|
|
|
||
|
|
lone = self._observe("99", "observe-lone")["person_id"]
|
||
|
|
before_last_unlink = deepcopy(self.store)
|
||
|
|
last = self.registry.unlink_identity(
|
||
|
|
identity("99"), operation_id="unlink-last", actor_id="owner", reason="not allowed", authorized=True,
|
||
|
|
)
|
||
|
|
self.assertEqual(last["code"], "last_identity_required")
|
||
|
|
self.assertEqual(self.store, before_last_unlink)
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
unittest.main()
|