fix(devices): read device users from user_list, mirror writes to device_users
The Manage tab and Onboarding page list users via GET /devices/{id}/users,
which read the device_users sub-collection first and only fell back to
user_list when it was empty. Every write (add/remove on those pages, the
Users page, PUT with user_list) went to user_list only, so on any device
that had a device_users doc the list showed stale data: users added in the
Console never appeared and removed users never went away. A production
survey found 6 device_users docs (all role "admin") on 6 devices; 2 of them
disagree with user_list.
user_list is now the single source of truth:
- get_device_users reads only user_list; role comes from the mirror if any.
- Every user_list write also adds/removes the device_users mirror doc
({role: "admin", user_reference}) in the same atomic batch, in case the
phone app still reads the sub-collection. It is meant to go away later.
- users.service.assign_device and PUT /devices/{id} now store
DocumentReferences (the app's format) instead of "users/{id}" strings.
scripts/sync_device_users_mirror.py (dry run by default) reports and fixes
pre-existing drift between the two. Not run yet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,16 +1,21 @@
|
||||
"""
|
||||
update_device must keep users.device_serials in sync when a PUT changes the
|
||||
device's user_list (the MQTT ACL reads device_serials). Firestore is faked.
|
||||
Device user assignment: `user_list` is the source of truth. Every write must
|
||||
keep users.device_serials (MQTT ACL) and the device_users sub-collection
|
||||
mirror in sync, and reads must come from user_list only. Firestore is faked.
|
||||
"""
|
||||
|
||||
import itertools
|
||||
|
||||
import pytest
|
||||
from google.cloud.firestore_v1 import ArrayRemove, ArrayUnion
|
||||
from google.cloud.firestore_v1 import ArrayRemove, ArrayUnion, DocumentReference
|
||||
|
||||
from devices import service as devices_service
|
||||
from devices.models import DeviceUpdate
|
||||
from mqtt import app_users
|
||||
from users import service as users_service
|
||||
|
||||
SERIAL = "BSVSPR-26C13X-STD01R-X7KQA"
|
||||
MIRROR = "devices/dev1/device_users"
|
||||
|
||||
|
||||
class _Snap:
|
||||
@@ -24,9 +29,16 @@ class _Snap:
|
||||
return dict(self._data) if self._data is not None else None
|
||||
|
||||
|
||||
class _Ref:
|
||||
def __init__(self, db, collection, doc_id):
|
||||
self._db, self._col, self.id = db, collection, doc_id
|
||||
class _Ref(DocumentReference):
|
||||
"""A real DocumentReference subclass, so isinstance checks and .id/.path work."""
|
||||
|
||||
def __init__(self, db, col_path, doc_id):
|
||||
self._db, self._col = db, col_path
|
||||
self._client = db
|
||||
self._path = tuple(col_path.split("/")) + (doc_id,)
|
||||
|
||||
def collection(self, name):
|
||||
return _Collection(self._db, f"{self._col}/{self.id}/{name}")
|
||||
|
||||
def get(self):
|
||||
return _Snap(self, self._db.docs[self._col].get(self.id))
|
||||
@@ -34,32 +46,48 @@ class _Ref:
|
||||
def update(self, data):
|
||||
self._db.apply(self._col, self.id, data)
|
||||
|
||||
def set(self, data):
|
||||
self._db.docs[self._col][self.id] = dict(data)
|
||||
|
||||
def delete(self):
|
||||
self._db.docs[self._col].pop(self.id, None)
|
||||
|
||||
|
||||
class _Batch:
|
||||
def __init__(self, db):
|
||||
self._db, self.ops = db, []
|
||||
|
||||
def update(self, ref, data):
|
||||
self.ops.append((ref, data))
|
||||
self.ops.append(("update", ref, data))
|
||||
|
||||
def set(self, ref, data):
|
||||
self.ops.append(("set", ref, data))
|
||||
|
||||
def delete(self, ref):
|
||||
self.ops.append(("delete", ref, None))
|
||||
|
||||
def commit(self):
|
||||
for ref, data in self.ops:
|
||||
ref.update(data)
|
||||
for op, ref, data in self.ops:
|
||||
getattr(ref, op)(*([data] if data is not None else []))
|
||||
self._db.commits += 1
|
||||
|
||||
|
||||
class _Collection:
|
||||
def __init__(self, db, name):
|
||||
self._db, self._name = db, name
|
||||
def __init__(self, db, path):
|
||||
self._db, self._path = db, path
|
||||
|
||||
def document(self, doc_id):
|
||||
return _Ref(self._db, self._name, doc_id)
|
||||
def document(self, doc_id=None):
|
||||
return _Ref(self._db, self._path, doc_id or f"auto{next(self._db.ids)}")
|
||||
|
||||
def stream(self):
|
||||
return [_Snap(_Ref(self._db, self._path, k), v) for k, v in list(self._db.docs[self._path].items())]
|
||||
|
||||
|
||||
class FakeDB:
|
||||
def __init__(self):
|
||||
self.docs = {"devices": {}, "users": {}}
|
||||
self.docs = {"devices": {}, "users": {}, MIRROR: {}}
|
||||
self.commits = 0
|
||||
self.ids = itertools.count(1)
|
||||
|
||||
def collection(self, name):
|
||||
return _Collection(self, name)
|
||||
@@ -67,6 +95,10 @@ class FakeDB:
|
||||
def batch(self):
|
||||
return _Batch(self)
|
||||
|
||||
def ref(self, path):
|
||||
col, doc_id = path.rsplit("/", 1)
|
||||
return _Ref(self, col, doc_id)
|
||||
|
||||
def apply(self, col, doc_id, data):
|
||||
doc = self.docs[col][doc_id]
|
||||
for key, val in data.items():
|
||||
@@ -77,38 +109,53 @@ class FakeDB:
|
||||
else:
|
||||
doc[key] = val
|
||||
|
||||
def mirror_user_ids(self):
|
||||
return sorted(d["user_reference"].id for d in self.docs[MIRROR].values())
|
||||
|
||||
def user_list_ids(self, device="dev1"):
|
||||
return [devices_service.user_list_entry_id(e) for e in self.docs["devices"][device]["user_list"]]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db(monkeypatch):
|
||||
fake = FakeDB()
|
||||
fake.docs["devices"]["dev1"] = {
|
||||
"serial_number": SERIAL, "mfg_status": "claimed", "user_list": ["users/alice", "users/bob"],
|
||||
"serial_number": SERIAL, "mfg_status": "claimed",
|
||||
"user_list": [fake.ref("users/alice"), "users/bob"], # both formats seen in the wild
|
||||
}
|
||||
fake.docs["users"]["alice"] = {"uid": "alice", "device_serials": [SERIAL]}
|
||||
fake.docs["users"]["bob"] = {"uid": "bob", "device_serials": [SERIAL, "OTHER"]}
|
||||
fake.docs["users"]["carol"] = {"uid": "carol"}
|
||||
fake.docs[MIRROR]["m1"] = {"role": "admin", "user_reference": fake.ref("users/alice")}
|
||||
fake.docs["users"]["alice"] = {"uid": "alice", "device_serials": [SERIAL], "display_name": "Alice"}
|
||||
fake.docs["users"]["bob"] = {"uid": "bob", "device_serials": [SERIAL, "OTHER"], "display_name": "Bob"}
|
||||
fake.docs["users"]["carol"] = {"uid": "carol", "display_name": "Carol"}
|
||||
monkeypatch.setattr(devices_service, "get_db", lambda: fake)
|
||||
monkeypatch.setattr(users_service, "get_db", lambda: fake)
|
||||
monkeypatch.setattr(app_users, "invalidate", lambda uid: None)
|
||||
return fake
|
||||
|
||||
|
||||
# ── PUT /api/devices/{id} with user_list ─────────────────────────────────────
|
||||
|
||||
def test_put_user_list_syncs_added_and_removed_users(db, monkeypatch):
|
||||
invalidated = []
|
||||
monkeypatch.setattr(app_users, "invalidate", invalidated.append)
|
||||
|
||||
devices_service.update_device("dev1", DeviceUpdate(user_list=["users/alice", "users/carol"]))
|
||||
|
||||
assert db.docs["devices"]["dev1"]["user_list"] == ["users/alice", "users/carol"]
|
||||
assert db.user_list_ids() == ["alice", "carol"]
|
||||
assert all(isinstance(e, DocumentReference) for e in db.docs["devices"]["dev1"]["user_list"])
|
||||
assert db.docs["users"]["alice"]["device_serials"] == [SERIAL] # unchanged
|
||||
assert db.docs["users"]["bob"]["device_serials"] == ["OTHER"] # removed
|
||||
assert db.docs["users"]["carol"]["device_serials"] == [SERIAL] # added
|
||||
assert db.mirror_user_ids() == ["alice", "carol"] # alice's mirror kept, carol's added
|
||||
assert sorted(invalidated) == ["bob", "carol"]
|
||||
assert db.commits == 1 # one atomic batch
|
||||
|
||||
|
||||
def test_put_user_list_ignores_dangling_user_refs(db):
|
||||
devices_service.update_device("dev1", DeviceUpdate(user_list=["users/alice", "users/bob", "users/ghost"]))
|
||||
assert db.docs["devices"]["dev1"]["user_list"] == ["users/alice", "users/bob", "users/ghost"]
|
||||
assert db.user_list_ids() == ["alice", "bob", "ghost"]
|
||||
assert "ghost" not in db.docs["users"]
|
||||
assert "ghost" not in db.mirror_user_ids()
|
||||
|
||||
|
||||
def test_put_without_user_list_does_not_touch_users(db):
|
||||
@@ -116,3 +163,45 @@ def test_put_without_user_list_does_not_touch_users(db):
|
||||
assert db.docs["devices"]["dev1"]["device_name"] == "Church"
|
||||
assert db.commits == 0
|
||||
assert db.docs["users"]["bob"]["device_serials"] == [SERIAL, "OTHER"]
|
||||
|
||||
|
||||
# ── Reads come from user_list, not the sub-collection ────────────────────────
|
||||
|
||||
def test_get_device_users_reads_user_list_with_mirror_role(db):
|
||||
# A stale mirror doc for someone NOT in user_list must not show up.
|
||||
db.docs[MIRROR]["stale"] = {"role": "admin", "user_reference": db.ref("users/carol")}
|
||||
|
||||
users = devices_service.get_device_users("dev1")
|
||||
|
||||
assert [(u["user_id"], u["display_name"], u["role"]) for u in users] == [
|
||||
("alice", "Alice", "admin"),
|
||||
("bob", "Bob", ""),
|
||||
]
|
||||
|
||||
|
||||
def test_get_device_users_skips_duplicates_and_missing_users(db):
|
||||
db.docs["devices"]["dev1"]["user_list"] += ["alice", db.ref("users/ghost")]
|
||||
assert [u["user_id"] for u in devices_service.get_device_users("dev1")] == ["alice", "bob"]
|
||||
|
||||
|
||||
# ── Users page: assign / unassign ────────────────────────────────────────────
|
||||
|
||||
def test_assign_device_writes_reference_and_mirror(db):
|
||||
users_service.assign_device("carol", "dev1")
|
||||
assert db.user_list_ids() == ["alice", "bob", "carol"]
|
||||
assert isinstance(db.docs["devices"]["dev1"]["user_list"][-1], DocumentReference)
|
||||
assert db.docs["users"]["carol"]["device_serials"] == [SERIAL]
|
||||
assert db.mirror_user_ids() == ["alice", "carol"]
|
||||
|
||||
|
||||
def test_assign_device_twice_does_not_duplicate(db):
|
||||
users_service.assign_device("alice", "dev1")
|
||||
assert db.user_list_ids() == ["alice", "bob"]
|
||||
assert db.mirror_user_ids() == ["alice"]
|
||||
|
||||
|
||||
def test_unassign_device_removes_any_format_and_mirror(db):
|
||||
users_service.unassign_device("alice", "dev1")
|
||||
assert db.user_list_ids() == ["bob"]
|
||||
assert db.docs["users"]["alice"]["device_serials"] == []
|
||||
assert db.mirror_user_ids() == []
|
||||
|
||||
Reference in New Issue
Block a user