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:
2026-11-07 10:37:21 +02:00
co-authored by Claude Opus 5.5
parent fba5110cc0
commit 2a6f9697b8
7 changed files with 330 additions and 142 deletions
+1 -1
View File
@@ -218,7 +218,7 @@ class DeviceNoteUpdate(BaseModel):
class DeviceUserInfo(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 = "" user_id: str = ""
display_name: str = "" display_name: str = ""
email: str = "" email: str = ""
+4 -1
View File
@@ -462,13 +462,15 @@ async def add_user_to_device(
elif isinstance(entry, str): elif isinstance(entry, str):
existing_ids.add(entry.split("/")[-1]) 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) user_ref = fs.collection("users").document(body.user_id)
batch = fs.batch() batch = fs.batch()
if body.user_id not in existing_ids: if body.user_id not in existing_ids:
user_list.append(user_ref) user_list.append(user_ref)
batch.update(device_ref, {"user_list": user_list}) 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) 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() batch.commit()
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict()) 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() user_doc = user_ref.get()
if user_doc.exists: if user_doc.exists:
users_service.stage_device_serial_link(batch, user_ref, users_service.device_serial_of(data), linked=False) 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() batch.commit()
if user_doc.exists: if user_doc.exists:
users_service.invalidate_mqtt_acl_cache(user_doc.to_dict()) users_service.invalidate_mqtt_acl_cache(user_doc.to_dict())
+82 -77
View File
@@ -235,22 +235,35 @@ def update_device(device_doc_id: str, data: DeviceUpdate) -> DeviceInDB:
doc_ref.update(update_data) doc_ref.update(update_data)
else: else:
# A user_list change must also update each affected user's # 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 from users import service as users_service
old_ids = {_user_list_entry_id(e) for e in (existing.get("user_list") or [])} - {""} new_ids = []
new_ids = {_user_list_entry_id(e) for e in update_data["user_list"]} - {""} 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) serial = users_service.device_serial_of(existing)
mirror = device_users_by_user(doc_ref)
batch = db.batch() batch = db.batch()
batch.update(doc_ref, update_data) batch.update(doc_ref, update_data)
touched = [] 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_ref = db.collection("users").document(user_id)
user_doc = user_ref.get() user_doc = user_ref.get()
if not user_doc.exists: if not user_doc.exists:
continue # dangling reference — nothing to sync if not linked:
users_service.stage_device_serial_link(batch, user_ref, serial, linked=user_id in new_ids) 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()) touched.append(user_doc.to_dict())
batch.commit() batch.commit()
for user_data in touched: 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) 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.""" """user_list entries are DocumentReferences, "users/{id}" paths or raw doc IDs."""
if isinstance(entry, DocumentReference): if isinstance(entry, DocumentReference):
return entry.id return entry.id
@@ -269,11 +282,53 @@ def _user_list_entry_id(entry) -> str:
return "" return ""
def get_device_users(device_doc_id: str) -> list[dict]: # ─── device_users sub-collection mirror ──────────────────────────────────────
"""Get users assigned to a device from the device_users sub-collection. # 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 DEVICE_USERS_SUBCOLLECTION = "device_users"
sub-collection is empty. # 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() db = get_db()
doc_ref = db.collection(COLLECTION).document(device_doc_id) 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: if not doc.exists:
raise NotFoundError("Device") raise NotFoundError("Device")
# Try sub-collection first roles = {
sub_docs = list(doc_ref.collection("device_users").stream()) uid: (snaps[0].to_dict() or {}).get("role", "")
for uid, snaps in device_users_by_user(doc_ref).items()
}
users = [] users = []
seen = set()
if sub_docs: for entry in (doc.to_dict() or {}).get("user_list") or []:
for sub_doc in sub_docs: uid = user_list_entry_id(entry)
sub_data = sub_doc.to_dict() if not uid or uid in seen:
role = sub_data.get("role", "") continue
user_ref = sub_data.get("user_reference") seen.add(uid)
# Resolve user reference
user_id = ""
display_name = ""
email = ""
photo_url = ""
if isinstance(user_ref, DocumentReference):
try: try:
user_doc = user_ref.get() user_doc = db.collection("users").document(uid).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: except Exception as e:
print(f"[devices] Error resolving user reference: {e}") print(f"[devices] Error resolving user_list entry {uid}: {e}")
continue continue
elif isinstance(user_ref, str): if not user_doc.exists:
# 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 continue
user_data = user_doc.to_dict() or {}
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({ users.append({
"user_id": user_doc.id, "user_id": user_doc.id,
"display_name": user_data.get("display_name", ""), "display_name": user_data.get("display_name", ""),
"email": user_data.get("email", ""), "email": user_data.get("email", ""),
"role": "", "role": roles.get(uid, ""),
"photo_url": user_data.get("photo_url", ""), "photo_url": user_data.get("photo_url", ""),
}) })
except Exception as e:
print(f"[devices] Error resolving user_list entry: {e}")
return users return users
@@ -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())
+109 -20
View File
@@ -1,16 +1,21 @@
""" """
update_device must keep users.device_serials in sync when a PUT changes the Device user assignment: `user_list` is the source of truth. Every write must
device's user_list (the MQTT ACL reads device_serials). Firestore is faked. 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 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 import service as devices_service
from devices.models import DeviceUpdate from devices.models import DeviceUpdate
from mqtt import app_users from mqtt import app_users
from users import service as users_service
SERIAL = "BSVSPR-26C13X-STD01R-X7KQA" SERIAL = "BSVSPR-26C13X-STD01R-X7KQA"
MIRROR = "devices/dev1/device_users"
class _Snap: class _Snap:
@@ -24,9 +29,16 @@ class _Snap:
return dict(self._data) if self._data is not None else None return dict(self._data) if self._data is not None else None
class _Ref: class _Ref(DocumentReference):
def __init__(self, db, collection, doc_id): """A real DocumentReference subclass, so isinstance checks and .id/.path work."""
self._db, self._col, self.id = db, collection, doc_id
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): def get(self):
return _Snap(self, self._db.docs[self._col].get(self.id)) return _Snap(self, self._db.docs[self._col].get(self.id))
@@ -34,32 +46,48 @@ class _Ref:
def update(self, data): def update(self, data):
self._db.apply(self._col, self.id, 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: class _Batch:
def __init__(self, db): def __init__(self, db):
self._db, self.ops = db, [] self._db, self.ops = db, []
def update(self, ref, data): 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): def commit(self):
for ref, data in self.ops: for op, ref, data in self.ops:
ref.update(data) getattr(ref, op)(*([data] if data is not None else []))
self._db.commits += 1 self._db.commits += 1
class _Collection: class _Collection:
def __init__(self, db, name): def __init__(self, db, path):
self._db, self._name = db, name self._db, self._path = db, path
def document(self, doc_id): def document(self, doc_id=None):
return _Ref(self._db, self._name, doc_id) 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: class FakeDB:
def __init__(self): def __init__(self):
self.docs = {"devices": {}, "users": {}} self.docs = {"devices": {}, "users": {}, MIRROR: {}}
self.commits = 0 self.commits = 0
self.ids = itertools.count(1)
def collection(self, name): def collection(self, name):
return _Collection(self, name) return _Collection(self, name)
@@ -67,6 +95,10 @@ class FakeDB:
def batch(self): def batch(self):
return _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): def apply(self, col, doc_id, data):
doc = self.docs[col][doc_id] doc = self.docs[col][doc_id]
for key, val in data.items(): for key, val in data.items():
@@ -77,38 +109,53 @@ class FakeDB:
else: else:
doc[key] = val 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 @pytest.fixture
def db(monkeypatch): def db(monkeypatch):
fake = FakeDB() fake = FakeDB()
fake.docs["devices"]["dev1"] = { 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[MIRROR]["m1"] = {"role": "admin", "user_reference": fake.ref("users/alice")}
fake.docs["users"]["bob"] = {"uid": "bob", "device_serials": [SERIAL, "OTHER"]} fake.docs["users"]["alice"] = {"uid": "alice", "device_serials": [SERIAL], "display_name": "Alice"}
fake.docs["users"]["carol"] = {"uid": "carol"} 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(devices_service, "get_db", lambda: fake)
monkeypatch.setattr(users_service, "get_db", lambda: fake)
monkeypatch.setattr(app_users, "invalidate", lambda uid: None)
return fake return fake
# ── PUT /api/devices/{id} with user_list ─────────────────────────────────────
def test_put_user_list_syncs_added_and_removed_users(db, monkeypatch): def test_put_user_list_syncs_added_and_removed_users(db, monkeypatch):
invalidated = [] invalidated = []
monkeypatch.setattr(app_users, "invalidate", invalidated.append) monkeypatch.setattr(app_users, "invalidate", invalidated.append)
devices_service.update_device("dev1", DeviceUpdate(user_list=["users/alice", "users/carol"])) 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"]["alice"]["device_serials"] == [SERIAL] # unchanged
assert db.docs["users"]["bob"]["device_serials"] == ["OTHER"] # removed assert db.docs["users"]["bob"]["device_serials"] == ["OTHER"] # removed
assert db.docs["users"]["carol"]["device_serials"] == [SERIAL] # added 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 sorted(invalidated) == ["bob", "carol"]
assert db.commits == 1 # one atomic batch assert db.commits == 1 # one atomic batch
def test_put_user_list_ignores_dangling_user_refs(db): def test_put_user_list_ignores_dangling_user_refs(db):
devices_service.update_device("dev1", DeviceUpdate(user_list=["users/alice", "users/bob", "users/ghost"])) 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.docs["users"]
assert "ghost" not in db.mirror_user_ids()
def test_put_without_user_list_does_not_touch_users(db): 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.docs["devices"]["dev1"]["device_name"] == "Church"
assert db.commits == 0 assert db.commits == 0
assert db.docs["users"]["bob"]["device_serials"] == [SERIAL, "OTHER"] 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() == []
+17 -28
View File
@@ -236,29 +236,23 @@ def assign_device(user_doc_id: str, device_doc_id: str) -> UserInDB:
if not device_doc.exists: if not device_doc.exists:
raise NotFoundError("Device") 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() device_data = device_doc.to_dict()
user_list = device_data.get("user_list", []) user_list = device_data.get("user_list", []) or []
user_path = f"users/{user_doc_id}" 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) # Device user_list, the user's device_serials and the device_users mirror
already_assigned = False # are written in one atomic batch. device_serials and the mirror are
for entry in user_list: # re-synced even when already assigned, to heal drift.
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.
batch = db.batch() batch = db.batch()
if not already_assigned: if not already_assigned:
user_list.append(user_path) user_list.append(user_ref)
batch.update(device_ref, {"user_list": user_list}) batch.update(device_ref, {"user_list": user_list})
stage_device_serial_link(batch, user_ref, device_serial_of(device_data), linked=True) 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() batch.commit()
invalidate_mqtt_acl_cache(user_doc.to_dict()) 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: if not device_doc.exists:
raise NotFoundError("Device") raise NotFoundError("Device")
# Remove user from device's user_list from devices import service as devices_service
device_data = device_doc.to_dict()
user_list = device_data.get("user_list", [])
user_path = f"users/{user_doc_id}"
new_list = [] # Remove user from device's user_list (any entry format)
for entry in user_list: device_data = device_doc.to_dict()
if isinstance(entry, DocumentReference): user_list = device_data.get("user_list", []) or []
if entry.path != user_path: new_list = [e for e in user_list if devices_service.user_list_entry_id(e) != user_doc_id]
new_list.append(entry)
elif entry != user_path:
new_list.append(entry)
batch = db.batch() batch = db.batch()
batch.update(device_ref, {"user_list": new_list}) batch.update(device_ref, {"user_list": new_list})
stage_device_serial_link(batch, user_ref, device_serial_of(device_data), linked=False) 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() batch.commit()
invalidate_mqtt_acl_cache(user_doc.to_dict()) invalidate_mqtt_acl_cache(user_doc.to_dict())
+11 -5
View File
@@ -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 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 (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. 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, - **The `device_users` subcollection** on devices (`{role, user_reference}`, the older
read first by `devices.service.get_device_users`) is **intentionally ignored** by way of recording device users) is a **write-only mirror** since 2026-11. `user_list`
the backfill and the MQTT ACL. Left as is by decision. is the only source of truth: the Console reads assignments only from it
- The two Console assignment paths store `user_list` entries in different formats (`devices.service.get_device_users`, which takes just the `role` from the mirror).
(path strings vs DocumentReferences). This predates this work; all readers accept both. 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 - ACL denies are logged at INFO, which is not shown by default. Auth denies and
legacy-password logins are WARNING. legacy-password logins are WARNING.