diff --git a/backend/devices/models.py b/backend/devices/models.py index 6341da6..14c09a9 100644 --- a/backend/devices/models.py +++ b/backend/devices/models.py @@ -218,7 +218,7 @@ class DeviceNoteUpdate(BaseModel): class DeviceUserInfo(BaseModel): - """User info resolved from device_users sub-collection or user_list.""" + """User info resolved from the device's user_list (role from the device_users mirror).""" user_id: str = "" display_name: str = "" email: str = "" diff --git a/backend/devices/router.py b/backend/devices/router.py index 293613c..1d7444e 100644 --- a/backend/devices/router.py +++ b/backend/devices/router.py @@ -462,13 +462,15 @@ async def add_user_to_device( elif isinstance(entry, str): existing_ids.add(entry.split("/")[-1]) - # user_list and the user's device_serials (MQTT ACL lookup) commit together. + # user_list, the user's device_serials (MQTT ACL lookup) and the + # device_users mirror commit together. user_ref = fs.collection("users").document(body.user_id) batch = fs.batch() if body.user_id not in existing_ids: user_list.append(user_ref) batch.update(device_ref, {"user_list": user_list}) users_service.stage_device_serial_link(batch, user_ref, users_service.device_serial_of(data), linked=True) + service.stage_device_users_mirror(batch, device_ref, user_ref, linked=True) batch.commit() users_service.invalidate_mqtt_acl_cache(user_doc.to_dict()) @@ -512,6 +514,7 @@ async def remove_user_from_device( user_doc = user_ref.get() if user_doc.exists: users_service.stage_device_serial_link(batch, user_ref, users_service.device_serial_of(data), linked=False) + service.stage_device_users_mirror(batch, device_ref, user_ref, linked=False) batch.commit() if user_doc.exists: users_service.invalidate_mqtt_acl_cache(user_doc.to_dict()) diff --git a/backend/devices/service.py b/backend/devices/service.py index 29e7c10..aa5d026 100644 --- a/backend/devices/service.py +++ b/backend/devices/service.py @@ -235,22 +235,35 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB: doc_ref.update(update_data) else: # A user_list change must also update each affected user's - # device_serials (MQTT ACL), in the same atomic batch. + # device_serials (MQTT ACL) and the device_users mirror, in the + # same atomic batch. from users import service as users_service - old_ids = {_user_list_entry_id(e) for e in (existing.get("user_list") or [])} - {""} - new_ids = {_user_list_entry_id(e) for e in update_data["user_list"]} - {""} + new_ids = [] + for e in update_data["user_list"]: + uid = user_list_entry_id(e) + if uid and uid not in new_ids: + new_ids.append(uid) + # Stored as DocumentReferences, the format the FlutterFlow app writes. + update_data["user_list"] = [db.collection("users").document(uid) for uid in new_ids] + + old_ids = {user_list_entry_id(e) for e in (existing.get("user_list") or [])} - {""} serial = users_service.device_serial_of(existing) + mirror = device_users_by_user(doc_ref) batch = db.batch() batch.update(doc_ref, update_data) touched = [] - for user_id in (old_ids ^ new_ids): + for user_id in (old_ids ^ set(new_ids)): + linked = user_id in new_ids user_ref = db.collection("users").document(user_id) user_doc = user_ref.get() if not user_doc.exists: - continue # dangling reference — nothing to sync - users_service.stage_device_serial_link(batch, user_ref, serial, linked=user_id in new_ids) + if not linked: + stage_device_users_mirror(batch, doc_ref, user_ref, linked=False, existing=mirror) + continue # dangling reference — no user doc to sync + users_service.stage_device_serial_link(batch, user_ref, serial, linked=linked) + stage_device_users_mirror(batch, doc_ref, user_ref, linked=linked, existing=mirror) touched.append(user_doc.to_dict()) batch.commit() for user_data in touched: @@ -260,7 +273,7 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB: return _doc_to_device(updated_doc) -def _user_list_entry_id(entry) -> str: +def user_list_entry_id(entry) -> str: """user_list entries are DocumentReferences, "users/{id}" paths or raw doc IDs.""" if isinstance(entry, DocumentReference): return entry.id @@ -269,11 +282,53 @@ def _user_list_entry_id(entry) -> str: return "" -def get_device_users(device_doc_id: str) -> list[dict]: - """Get users assigned to a device from the device_users sub-collection. +# ─── device_users sub-collection mirror ────────────────────────────────────── +# The device's `user_list` field is the single source of truth for who is +# assigned to a device. The older `device_users` sub-collection +# ({role, user_reference}) is kept as a write-only mirror in case the phone +# app still reads it, and is slated for removal. Never read assignments from it. - Falls back to the user_list field on the device document if the - sub-collection is empty. +DEVICE_USERS_SUBCOLLECTION = "device_users" +# Every existing device_users doc (2026-11) has role "admin". +DEFAULT_DEVICE_USER_ROLE = "admin" + + +def device_users_by_user(device_ref) -> dict[str, list]: + """user doc id -> the device_users snapshots that point at that user.""" + out: dict[str, list] = {} + for snap in device_ref.collection(DEVICE_USERS_SUBCOLLECTION).stream(): + uid = user_list_entry_id((snap.to_dict() or {}).get("user_reference")) + if uid: + out.setdefault(uid, []).append(snap) + return out + + +def stage_device_users_mirror(batch, device_ref, user_ref, linked: bool, existing: dict | None = None) -> None: + """Add (linked=True) or remove the user's device_users mirror doc inside the + caller's batch, so it commits together with the `user_list` change. + + `existing` is a pre-fetched device_users_by_user() map, for callers that + touch several users of one device. + """ + if existing is None: + existing = device_users_by_user(device_ref) + current = existing.get(user_ref.id, []) + if linked: + if not current: + batch.set(device_ref.collection(DEVICE_USERS_SUBCOLLECTION).document(), { + "role": DEFAULT_DEVICE_USER_ROLE, + "user_reference": user_ref, + }) + else: + for snap in current: + batch.delete(snap.reference) + + +def get_device_users(device_doc_id: str) -> list[dict]: + """Users assigned to a device, read from the device's `user_list` field. + + `role` is taken from the device_users mirror when one exists for the user + (that's the only place a role is stored); otherwise it is "". """ db = get_db() doc_ref = db.collection(COLLECTION).document(device_doc_id) @@ -281,83 +336,33 @@ def get_device_users(device_doc_id: str) -> list[dict]: if not doc.exists: raise NotFoundError("Device") - # Try sub-collection first - sub_docs = list(doc_ref.collection("device_users").stream()) + roles = { + uid: (snaps[0].to_dict() or {}).get("role", "") + for uid, snaps in device_users_by_user(doc_ref).items() + } + users = [] - - if sub_docs: - for sub_doc in sub_docs: - sub_data = sub_doc.to_dict() - role = sub_data.get("role", "") - user_ref = sub_data.get("user_reference") - - # Resolve user reference - user_id = "" - display_name = "" - email = "" - photo_url = "" - - if isinstance(user_ref, DocumentReference): - try: - user_doc = user_ref.get() - if user_doc.exists: - user_data = user_doc.to_dict() - user_id = user_doc.id - display_name = user_data.get("display_name", "") - email = user_data.get("email", "") - photo_url = user_data.get("photo_url", "") - except Exception as e: - print(f"[devices] Error resolving user reference: {e}") - continue - elif isinstance(user_ref, str): - # String path like "users/abc123" - try: - ref_doc = db.document(user_ref).get() - if ref_doc.exists: - user_data = ref_doc.to_dict() - user_id = ref_doc.id - display_name = user_data.get("display_name", "") - email = user_data.get("email", "") - photo_url = user_data.get("photo_url", "") - except Exception as e: - print(f"[devices] Error resolving user path: {e}") - continue - - users.append({ - "user_id": user_id, - "display_name": display_name, - "email": email, - "role": role, - "photo_url": photo_url, - }) - else: - # Fallback to user_list field - device_data = doc.to_dict() - user_list = device_data.get("user_list", []) - for entry in user_list: - try: - if isinstance(entry, DocumentReference): - user_doc = entry.get() - elif isinstance(entry, str) and entry.strip(): - # Could be a path like "users/abc" or a raw doc ID - if "/" in entry: - user_doc = db.document(entry).get() - else: - user_doc = db.collection("users").document(entry).get() - else: - continue - - if user_doc.exists: - user_data = user_doc.to_dict() - users.append({ - "user_id": user_doc.id, - "display_name": user_data.get("display_name", ""), - "email": user_data.get("email", ""), - "role": "", - "photo_url": user_data.get("photo_url", ""), - }) - except Exception as e: - print(f"[devices] Error resolving user_list entry: {e}") + seen = set() + for entry in (doc.to_dict() or {}).get("user_list") or []: + uid = user_list_entry_id(entry) + if not uid or uid in seen: + continue + seen.add(uid) + try: + user_doc = db.collection("users").document(uid).get() + except Exception as e: + print(f"[devices] Error resolving user_list entry {uid}: {e}") + continue + if not user_doc.exists: + continue + user_data = user_doc.to_dict() or {} + users.append({ + "user_id": user_doc.id, + "display_name": user_data.get("display_name", ""), + "email": user_data.get("email", ""), + "role": roles.get(uid, ""), + "photo_url": user_data.get("photo_url", ""), + }) return users diff --git a/backend/scripts/sync_device_users_mirror.py b/backend/scripts/sync_device_users_mirror.py new file mode 100644 index 0000000..c323c4a --- /dev/null +++ b/backend/scripts/sync_device_users_mirror.py @@ -0,0 +1,96 @@ +""" +Make every device's `device_users` sub-collection mirror its `user_list`. + +`user_list` is the source of truth for device assignments. The Console keeps +`device_users` ({role, user_reference}) only as a write-only mirror in case the +phone app still reads it. Before 2026-11 the Console read `device_users` first +and never wrote it, so the two drifted. This script lists the drift and, with +--apply, fixes the mirror: + + - users in user_list with no device_users doc -> doc added (role "admin") + - device_users docs for users NOT in user_list -> doc deleted + +It never changes `user_list` or `device_serials`. Check the dry-run output +first: if a user only appears in device_users and should keep the device, +assign them in the Console (Manage tab) before running --apply, or they will be +dropped from the mirror. Running it twice is a no-op the second time. + +Run from backend/ (locally or inside the backend container): + + python scripts/sync_device_users_mirror.py # dry run + python scripts/sync_device_users_mirror.py --apply # write changes +""" + +import argparse +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +from shared.firebase import init_firebase, get_db # noqa: E402 +from devices.service import ( # noqa: E402 + DEFAULT_DEVICE_USER_ROLE, DEVICE_USERS_SUBCOLLECTION, device_users_by_user, user_list_entry_id, +) + +BATCH_SIZE = 400 # Firestore batch limit is 500 writes + + +def _label(db, uid: str) -> str: + snap = db.collection("users").document(uid).get() + if not snap.exists: + return f"{uid} (no user doc)" + data = snap.to_dict() or {} + return f"{uid} ({data.get('display_name') or data.get('email') or '?'})" + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--apply", action="store_true", help="write changes (default: dry run)") + args = parser.parse_args() + + init_firebase() + db = get_db() + if db is None: + print("[ERROR] Firebase not initialized — check FIREBASE_SERVICE_ACCOUNT_PATH") + return 1 + + print(f"=== sync device_users mirror — {'APPLY' if args.apply else 'DRY RUN'} ===") + writes = [] # (op, ref, data) + for dev in db.collection("devices").stream(): + data = dev.to_dict() or {} + wanted = {user_list_entry_id(e) for e in data.get("user_list") or []} - {""} + mirror = device_users_by_user(dev.reference) + to_add = sorted(u for u in wanted - mirror.keys() + if db.collection("users").document(u).get().exists) + to_del = sorted(mirror.keys() - wanted) + if not to_add and not to_del: + continue + serial = data.get("serial_number") or data.get("device_id") or "?" + print(f"\n{dev.id} {serial} {data.get('device_name') or ''}") + for u in to_add: + print(f" + add mirror {_label(db, u)}") + writes.append(("set", dev.reference.collection(DEVICE_USERS_SUBCOLLECTION).document(), { + "role": DEFAULT_DEVICE_USER_ROLE, + "user_reference": db.collection("users").document(u), + })) + for u in to_del: + print(f" - remove mirror {_label(db, u)} <- only in device_users, not in user_list") + writes.extend(("delete", snap.reference, None) for snap in mirror[u]) + + print(f"\n{len(writes)} write(s) needed.") + if not args.apply or not writes: + if writes: + print("Dry run — nothing written. Re-run with --apply to write.") + return 0 + + for i in range(0, len(writes), BATCH_SIZE): + batch = db.batch() + for op, ref, payload in writes[i:i + BATCH_SIZE]: + batch.set(ref, payload) if op == "set" else batch.delete(ref) + batch.commit() + print("Done.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/backend/tests/test_device_serials_sync.py b/backend/tests/test_device_serials_sync.py index 93f0582..369bbe2 100644 --- a/backend/tests/test_device_serials_sync.py +++ b/backend/tests/test_device_serials_sync.py @@ -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() == [] diff --git a/backend/users/service.py b/backend/users/service.py index e76df8d..3d62e34 100644 --- a/backend/users/service.py +++ b/backend/users/service.py @@ -236,29 +236,23 @@ def assign_device(user_doc_id: str, device_doc_id: str) -> UserInDB: if not device_doc.exists: raise NotFoundError("Device") - # Add user path to device's user_list if not already there + from devices import service as devices_service + + # Add a user reference to device's user_list if not already there. + # Stored as a DocumentReference, the format the FlutterFlow app writes. device_data = device_doc.to_dict() - user_list = device_data.get("user_list", []) - user_path = f"users/{user_doc_id}" + user_list = device_data.get("user_list", []) or [] + already_assigned = any(devices_service.user_list_entry_id(e) == user_doc_id for e in user_list) - # Check if already assigned (handle both string paths and DocumentReferences) - already_assigned = False - for entry in user_list: - if isinstance(entry, DocumentReference): - if entry.path == user_path: - already_assigned = True - break - elif entry == user_path: - already_assigned = True - break - - # Device user_list and the user's device_serials are written in one atomic batch. - # device_serials is re-synced even when already assigned, to heal drift. + # Device user_list, the user's device_serials and the device_users mirror + # are written in one atomic batch. device_serials and the mirror are + # re-synced even when already assigned, to heal drift. batch = db.batch() if not already_assigned: - user_list.append(user_path) + user_list.append(user_ref) batch.update(device_ref, {"user_list": user_list}) stage_device_serial_link(batch, user_ref, device_serial_of(device_data), linked=True) + devices_service.stage_device_users_mirror(batch, device_ref, user_ref, linked=True) batch.commit() invalidate_mqtt_acl_cache(user_doc.to_dict()) @@ -281,22 +275,17 @@ def unassign_device(user_doc_id: str, device_doc_id: str) -> UserInDB: if not device_doc.exists: raise NotFoundError("Device") - # Remove user from device's user_list - device_data = device_doc.to_dict() - user_list = device_data.get("user_list", []) - user_path = f"users/{user_doc_id}" + from devices import service as devices_service - new_list = [] - for entry in user_list: - if isinstance(entry, DocumentReference): - if entry.path != user_path: - new_list.append(entry) - elif entry != user_path: - new_list.append(entry) + # Remove user from device's user_list (any entry format) + device_data = device_doc.to_dict() + user_list = device_data.get("user_list", []) or [] + new_list = [e for e in user_list if devices_service.user_list_entry_id(e) != user_doc_id] batch = db.batch() batch.update(device_ref, {"user_list": new_list}) stage_device_serial_link(batch, user_ref, device_serial_of(device_data), linked=False) + devices_service.stage_device_users_mirror(batch, device_ref, user_ref, linked=False) batch.commit() invalidate_mqtt_acl_cache(user_doc.to_dict()) diff --git a/docs/mqtt-app-user-auth.md b/docs/mqtt-app-user-auth.md index 296cee5..6d60559 100644 --- a/docs/mqtt-app-user-auth.md +++ b/docs/mqtt-app-user-auth.md @@ -201,11 +201,17 @@ When those lines stop appearing, set `MQTT_ALLOW_LEGACY_PASSWORD=false`. Firestore (e.g. a claim flow), it must also update `device_serials` the same way (ArrayUnion / ArrayRemove of the serial on the user doc). Otherwise that user cannot reach the device over MQTT. The app owner will handle this in the app. -- **The `device_users` subcollection** on devices (older way of recording device users, - read first by `devices.service.get_device_users`) is **intentionally ignored** by - the backfill and the MQTT ACL. Left as is by decision. -- The two Console assignment paths store `user_list` entries in different formats - (path strings vs DocumentReferences). This predates this work; all readers accept both. +- **The `device_users` subcollection** on devices (`{role, user_reference}`, the older + way of recording device users) is a **write-only mirror** since 2026-11. `user_list` + is the only source of truth: the Console reads assignments only from it + (`devices.service.get_device_users`, which takes just the `role` from the mirror). + Every Console path that edits `user_list` also adds/removes the mirror doc in the + same batch (`devices.service.stage_device_users_mirror`). The MQTT ACL and the + backfill ignore it. It is kept only in case the phone app still reads it, and is + meant to be removed. `scripts/sync_device_users_mirror.py` (dry run by default) + fixes drift from before 2026-11. +- All Console paths now write `user_list` entries as DocumentReferences (what the app + writes). Older data may still hold `"users/{id}"` path strings; all readers accept both. - ACL denies are logged at INFO, which is not shown by default. Auth denies and legacy-password logins are WARNING.