1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
//! Device Registry methods for Client.
//!
//! Manages the device registry cache for tracking known devices per user.
//! Uses LID-first storage with bidirectional lookup support.
use anyhow::Result;
use log::{debug, info, warn};
use wacore_binary::Jid;
use super::Client;
/// Result of resolving a user identifier to lookup keys.
/// This makes the LID/PN relationship explicit instead of using magic indices.
#[derive(Debug, Clone)]
enum UserLookupKeys {
/// User is a LID with known phone number mapping.
/// Keys: [LID, PN]
LidWithPn { lid: String, pn: String },
/// User is a phone number with known LID mapping.
/// Keys: [LID, PN]
PnWithLid { lid: String, pn: String },
/// Unknown user - no LID-PN mapping exists.
/// Could be either a LID or PN, we don't know.
Unknown { user: String },
}
impl UserLookupKeys {
/// Returns all keys to try for lookups, in preference order.
fn all_keys(&self) -> Vec<&str> {
match self {
Self::LidWithPn { lid, pn } | Self::PnWithLid { lid, pn } => vec![lid, pn],
Self::Unknown { user } => vec![user],
}
}
/// Returns the canonical (preferred) key for storage.
fn canonical_key(&self) -> &str {
match self {
Self::LidWithPn { lid, .. } | Self::PnWithLid { lid, .. } => lid,
Self::Unknown { user } => user,
}
}
}
impl Client {
/// Resolve a user identifier to its canonical storage key (LID preferred).
///
/// This is a convenience wrapper around `resolve_lookup_keys().canonical_key()`.
#[cfg(test)]
pub(crate) async fn resolve_to_canonical_key(&self, user: &str) -> String {
self.resolve_lookup_keys(user)
.await
.canonical_key()
.to_string()
}
/// Resolve a user identifier to its lookup keys with type information.
///
/// Returns a `UserLookupKeys` enum that explicitly represents:
/// - `LidWithPn`: User is a LID with known phone number mapping
/// - `PnWithLid`: User is a phone number with known LID mapping
/// - `Unknown`: No LID-PN mapping exists (could be either type)
async fn resolve_lookup_keys(&self, user: &str) -> UserLookupKeys {
// Check if user is a LID (has a phone number mapping)
if let Some(pn) = self.lid_pn_cache.get_phone_number(user).await {
return UserLookupKeys::LidWithPn {
lid: user.to_string(),
pn,
};
}
// Check if user is a PN (has a LID mapping)
if let Some(lid) = self.lid_pn_cache.get_current_lid(user).await {
return UserLookupKeys::PnWithLid {
lid,
pn: user.to_string(),
};
}
// Unknown user - no mapping exists
UserLookupKeys::Unknown {
user: user.to_string(),
}
}
/// Get all possible lookup keys for a user (for bidirectional lookup).
/// Returns keys in order of preference: [canonical_key, fallback_key].
///
/// Note: Prefer `resolve_lookup_keys` when you need type information.
pub(crate) async fn get_lookup_keys(&self, user: &str) -> Vec<String> {
self.resolve_lookup_keys(user)
.await
.all_keys()
.into_iter()
.map(String::from)
.collect()
}
/// WA Web: `isFromKnownDevice(author)` — local check only, no network.
pub(crate) async fn is_from_known_device(&self, sender: &wacore_binary::Jid) -> bool {
let device_id = sender.device as u32;
self.has_device(&sender.user, device_id).await
}
/// Check if a device exists for a user.
/// Returns true for device_id 0 (primary device always exists).
pub(crate) async fn has_device(&self, user: &str, device_id: u32) -> bool {
if device_id == 0 {
return true;
}
let lookup_keys = self.get_lookup_keys(user).await;
for key in &lookup_keys {
if let Some(record) = self.device_registry_cache.get(key).await {
return record.devices.iter().any(|d| d.device_id == device_id);
}
}
let backend = self.persistence_manager.backend();
for key in &lookup_keys {
match backend.get_devices(key).await {
Ok(Some(record)) => {
let has_device = record.devices.iter().any(|d| d.device_id == device_id);
// Cache under the record's actual user key (the key it was stored under
// in the backend), not lookup_keys[0] which is our guessed canonical key.
// This ensures consistency between the in-memory cache and the backend.
self.device_registry_cache
.insert(record.user.clone(), record)
.await;
return has_device;
}
Ok(None) => continue,
Err(e) => {
warn!("Failed to check device registry for {}: {e}", key);
}
}
}
false
}
/// Update the device list for a user.
/// Stores under LID when mapping is known, otherwise under PN.
pub(crate) async fn update_device_list(
&self,
mut record: wacore::store::traits::DeviceListRecord,
) -> Result<()> {
use anyhow::Context;
let original_user = record.user.clone();
let lookup = self.resolve_lookup_keys(&original_user).await;
let canonical_key = lookup.canonical_key().to_string();
record.user.clone_from(&canonical_key); // More efficient: reuses allocation
// Clone record for cache before moving to backend
let record_for_cache = record.clone();
// Use canonical_key directly as cache key (no extra clone)
self.device_registry_cache
.insert(canonical_key.clone(), record_for_cache)
.await;
let backend = self.persistence_manager.backend();
backend
.update_device_list(record)
.await
.context("Failed to update device list in backend")?;
if canonical_key != original_user {
// Invalidate before + after delete so a concurrent reader that
// resurrects the cache from the about-to-be-deleted DB row still
// gets cleared. Run the second invalidate unconditionally: even
// if delete fails, the cache may have been repopulated with data
// that no longer reflects our intent.
self.device_registry_cache.invalidate(&original_user).await;
if let Err(e) = backend.delete_devices(&original_user).await {
warn!(
"Failed to delete stale device row under {} after canonical flip: {e}",
original_user
);
}
self.device_registry_cache.invalidate(&original_user).await;
debug!(
"Device registry: stored under LID {} (resolved from {})",
canonical_key, original_user
);
}
Ok(())
}
/// Batched variant of [`update_device_list`]. Cache is populated
/// synchronously per record (cheap moka inserts); the backend write
/// collapses into a single transaction. Used by usync after fetching
/// device lists for many users at once, where the per-row commit
/// dominated wall-clock time on large groups.
pub(crate) async fn update_device_lists(
&self,
records: Vec<wacore::store::traits::DeviceListRecord>,
) -> Result<()> {
use anyhow::Context;
if records.is_empty() {
return Ok(());
}
let mut prepared = Vec::with_capacity(records.len());
let mut to_delete: Vec<String> = Vec::new();
for mut record in records {
let original_user = record.user.clone();
let lookup = self.resolve_lookup_keys(&original_user).await;
let canonical_key = lookup.canonical_key().to_string();
record.user.clone_from(&canonical_key);
let record_for_cache = record.clone();
self.device_registry_cache
.insert(canonical_key.clone(), record_for_cache)
.await;
if canonical_key != original_user {
to_delete.push(original_user);
}
prepared.push(record);
}
let backend = self.persistence_manager.backend();
backend
.update_device_lists(prepared)
.await
.context("Failed to update device lists in backend")?;
// Canonical-flip cleanup is rare and per-row; keep the original
// pattern (invalidate cache + best-effort delete + re-invalidate)
// rather than batching deletes. On error we log and continue so a
// single bad row doesn't drop the rest of the batch.
for original_user in to_delete {
self.device_registry_cache.invalidate(&original_user).await;
if let Err(e) = backend.delete_devices(&original_user).await {
warn!(
"Failed to delete stale device row under {} after canonical flip: {e}",
original_user
);
}
self.device_registry_cache.invalidate(&original_user).await;
}
Ok(())
}
/// Invalidate cached device data for a specific user.
///
/// Removes all device registry cache entries (all LID/PN aliases) so the
/// next lookup falls through to the database or network.
pub(crate) async fn invalidate_device_cache(&self, user: &str) {
let lookup = self.resolve_lookup_keys(user).await;
for key in lookup.all_keys() {
self.device_registry_cache.invalidate(key).await;
// Also delete from DB so get_devices_from_registry doesn't
// fall back to stale persisted data — forces a network re-fetch
if let Err(e) = self.persistence_manager.backend().delete_devices(key).await {
warn!("Failed to delete device registry from DB for {key}: {e}");
}
}
debug!("Invalidated device cache for user: {} ({:?})", user, lookup);
}
/// Patch device registry after a device add notification.
///
/// Matches WA Web's `handleDeviceAddNotification()` in `AdvDeviceNotificationApi`:
/// 1. Decode `key-index-list` signed bytes → `ADVKeyIndexList`
/// 2. Filter existing devices by `valid_indexes` (prune stale devices)
/// 3. Add the new device
/// 4. Replace the full device record
///
/// If `signed_bytes` is absent, falls back to simple append (lenient).
///
/// New devices need no explicit cache invalidation: `resolve_skdm_targets`
/// queries the registry on each send and `device_has_key()` returns `None`
/// for unseen device IDs, dropping them into `needs_skdm` automatically.
pub(crate) async fn patch_device_add(
&self,
user: &str,
device: &wacore::stanza::devices::DeviceElement,
key_index_info: Option<&wacore::stanza::devices::KeyIndexInfo>,
) {
let device_id = device.device_id();
let Some(mut record) = self.load_device_record(user).await else {
return;
};
let signed_bytes = key_index_info.and_then(|ki| ki.signed_bytes.as_deref());
if let Some(bytes) = signed_bytes {
if let Some(decoded) = wacore::adv::decode_key_index_list(bytes) {
// Check raw_id mismatch (identity change)
// TODO: WA Web also triggers clearRecord on advAccountType change
// (HOSTED ↔ E2EE), gated behind bizCoexGatingUtils.bizHostedDevicesEnabled().
// Add when we implement hosted device coexistence support.
if let Some(stored_raw_id) = record.raw_id
&& stored_raw_id != decoded.raw_id
{
info!(
"raw_id mismatch for user {user}: stored={stored_raw_id}, received={}. Clearing record.",
decoded.raw_id
);
self.clear_device_record(user, device.jid.server.as_str(), &record)
.await;
record.devices.clear();
}
record.raw_id = Some(decoded.raw_id);
// Filter stale devices by valid_indexes
record.devices =
wacore::adv::filter_devices_by_key_index(&record.devices, &decoded);
// Only add the new device if its key_index is accepted by the ADV list
if !record.devices.iter().any(|d| d.device_id == device_id)
&& wacore::adv::is_key_index_valid(device.key_index, &decoded)
{
record.devices.push(wacore::store::traits::DeviceInfo {
device_id,
key_index: device.key_index,
});
}
} else {
warn!("patch_device_add: failed to decode key-index-list for user {user}");
self.append_device_if_new(&mut record, device_id, device.key_index);
}
} else {
// No signed bytes — fall back to simple append
self.append_device_if_new(&mut record, device_id, device.key_index);
}
// New devices are picked up automatically by `resolve_skdm_targets`:
// unknown device → `device_has_key()` returns `None` → falls into
// `needs_skdm`. No global cache invalidation needed.
if let Err(e) = self.update_device_list(record).await {
warn!("patch_device_add: failed to persist: {e}");
}
}
/// Append a device if it doesn't already exist in the record.
fn append_device_if_new(
&self,
record: &mut wacore::store::traits::DeviceListRecord,
device_id: u32,
key_index: Option<u32>,
) {
if !record.devices.iter().any(|d| d.device_id == device_id) {
record.devices.push(wacore::store::traits::DeviceInfo {
device_id,
key_index,
});
}
}
/// Delete Signal sessions for specific device IDs under both LID and PN
/// addresses, then flush. Shared by `clear_device_record` and
/// `patch_device_remove`.
async fn delete_sessions_for_devices(&self, user: &str, device_ids: &[u16]) {
let lookup = self.resolve_lookup_keys(user).await;
let servers = [wacore_binary::Server::Lid, wacore_binary::Server::Pn];
for server in servers {
for key in lookup.all_keys() {
for &device_id in device_ids {
let mut jid = Jid::new(key, server);
jid.device = device_id;
let addr = wacore::types::jid::JidExt::to_protocol_address(&jid);
self.signal_cache.delete_session(&addr).await;
}
}
}
self.flush_signal_cache_logged("delete_sessions_for_devices", None)
.await;
}
/// Clear device record on raw_id mismatch (identity change).
///
/// Matches WA Web's `clearDeviceRecord()` in `IdentityUpdateDeviceTableApi`:
/// - Deletes Signal sessions for non-primary devices (stale identity)
/// - Invalidates sender key device cache so SKDM will be redistributed
pub(crate) async fn clear_device_record(
&self,
user: &str,
_server: &str,
record: &wacore::store::traits::DeviceListRecord,
) {
let non_primary_ids: Vec<u16> = record
.devices
.iter()
.filter(|d| d.device_id != 0)
.map(|d| d.device_id as u16)
.collect();
info!(
"Clearing device record for user {user}: removing {} non-primary device(s) due to raw_id change",
non_primary_ids.len()
);
self.delete_sessions_for_devices(user, &non_primary_ids)
.await;
// WA Web's `WAWebUpdateLocalSignalSession` only calls `markForgetSenderKey`
// on retry receipts, per-group/per-device. A global SKDM wipe here would
// empty the tracker often enough to feed the no-distribution path.
}
/// Remove a device from the registry after a device remove notification.
///
/// Matches WA Web's `bulkApplyDeviceUpdate` cleanup for removed devices
/// (`UpdateDeviceTableApi`): deletes Signal sessions for the device,
/// then invalidates the sender key device cache so SKDM will be
/// redistributed on the next group send.
pub(crate) async fn patch_device_remove(&self, user: &str, device_id: u32) {
if let Some(mut record) = self.load_device_record(user).await {
let before = record.devices.len();
record.devices.retain(|d| d.device_id != device_id);
if record.devices.len() != before {
// JID-keyed structures (Signal sessions, sender_key_devices)
// store device as u16. A blind cast for ids > u16::MAX would
// truncate to a different value and cleanup the wrong device.
let Ok(device_id_u16) = u16::try_from(device_id) else {
warn!(
"patch_device_remove: device_id {device_id} > u16::MAX — skipping \
session/SKDM cleanup but still persisting registry removal"
);
if let Err(e) = self.update_device_list(record).await {
warn!("patch_device_remove: failed to persist: {e}");
}
return;
};
if device_id_u16 != 0 {
self.delete_sessions_for_devices(user, &[device_id_u16])
.await;
}
// WA Web's `updateGroupParticipantsInTransaction` deletes the
// device JID from each affected group's senderKey Map. Skip
// the registry update on failure: a half-applied state where
// `resolve_devices` says "gone" but the tracker still vouches
// `has_key=true` would silently skip SKDM redistribution.
if let Err(e) = self
.delete_sender_key_rows_for_device(user, device_id_u16)
.await
{
warn!(
"patch_device_remove: sender-key cleanup failed for {user}:{device_id}: {e} \
— aborting registry update"
);
return;
}
if let Err(e) = self.update_device_list(record).await {
warn!("patch_device_remove: failed to persist: {e}");
}
}
}
}
/// Delete `sender_key_devices` rows whose `device_jid` matches the given
/// (user, device_id) under either LID or PN addressing. Both alias keys
/// for the user are tried via `resolve_lookup_keys`. The in-memory cache
/// is also evicted for groups that indexed the removed JID — necessary
/// because a future re-add of the same device_id would otherwise hit
/// a stale `has_key=true` entry and skip SKDM.
///
/// Cache eviction runs only after the DB delete succeeds; on failure the
/// error is propagated so the caller can leave both DB and cache in their
/// pre-call state rather than half-applying the cleanup.
async fn delete_sender_key_rows_for_device(
&self,
user: &str,
device_id: u16,
) -> Result<(), wacore::store::error::StoreError> {
let lookup = self.resolve_lookup_keys(user).await;
let servers = [wacore_binary::Server::Lid, wacore_binary::Server::Pn];
let mut candidates: Vec<String> = Vec::with_capacity(4);
for server in servers {
for key in lookup.all_keys() {
let mut jid = Jid::new(key, server);
jid.device = device_id;
candidates.push(jid.to_string());
}
}
let refs: Vec<&str> = candidates.iter().map(|s| s.as_str()).collect();
self.persistence_manager
.delete_sender_key_device_rows(&refs)
.await?;
for key in lookup.all_keys() {
self.sender_key_device_cache
.invalidate_entries_for_device(key, device_id)
.await;
}
Ok(())
}
/// Update key_index for a device in the registry.
pub(crate) async fn patch_device_update(
&self,
user: &str,
device: &wacore::stanza::devices::DeviceElement,
) {
let device_id = device.device_id();
if let Some(mut record) = self.load_device_record(user).await
&& let Some(d) = record.devices.iter_mut().find(|d| d.device_id == device_id)
{
d.key_index = device.key_index;
if let Err(e) = self.update_device_list(record).await {
warn!("patch_device_update: failed to persist: {e}");
}
}
}
/// Load a `DeviceListRecord` from cache or DB for patching.
pub(crate) async fn load_device_record(
&self,
user: &str,
) -> Option<wacore::store::traits::DeviceListRecord> {
let lookup = self.resolve_lookup_keys(user).await;
for key in lookup.all_keys() {
if let Some(record) = self.device_registry_cache.get(key).await {
return Some(record);
}
}
let backend = self.persistence_manager.backend();
for key in lookup.all_keys() {
match backend.get_devices(key).await {
Ok(Some(record)) => {
self.device_registry_cache
.insert(record.user.clone(), record.clone())
.await;
return Some(record);
}
Ok(None) => continue,
Err(e) => {
warn!("load_device_record: DB lookup failed for {key}: {e}");
}
}
}
None
}
/// Look up device JIDs from the device registry (cache + DB) for a single user.
///
/// Returns `None` if no record exists. On DB hit, re-populates the
/// `device_registry_cache` for subsequent `has_device()` calls.
///
/// This follows the same 2-tier pattern as [`has_device`]: registry cache first,
/// then the backend database.
pub(crate) async fn get_devices_from_registry(&self, jid: &Jid) -> Option<Vec<Jid>> {
let lookup_keys = self.get_lookup_keys(&jid.user).await;
// L1: device_registry_cache (moka, fast)
for key in &lookup_keys {
if let Some(record) = self.device_registry_cache.get(key).await {
return Some(Self::reconstruct_device_jids(jid, &record));
}
}
// L2: backend DB
let backend = self.persistence_manager.backend();
for key in &lookup_keys {
match backend.get_devices(key).await {
Ok(Some(record)) => {
let devices = Self::reconstruct_device_jids(jid, &record);
self.device_registry_cache
.insert(record.user.clone(), record)
.await;
return Some(devices);
}
Ok(None) => continue,
Err(e) => {
warn!("get_devices_from_registry: DB lookup failed for {key}: {e}");
}
}
}
None
}
/// Reconstruct `Vec<Jid>` from a `DeviceListRecord`, using the query JID's
/// user part and server type. This ensures that a PN-typed query always
/// returns PN-typed device JIDs even if the record is stored under a LID key
/// (and vice versa), which matters after PN-to-LID migration.
fn reconstruct_device_jids(
query_jid: &Jid,
record: &wacore::store::traits::DeviceListRecord,
) -> Vec<Jid> {
let user = &query_jid.user;
record
.devices
.iter()
.map(|d| {
debug_assert!(
d.device_id <= u16::MAX as u32,
"device_id {} overflows u16",
d.device_id
);
let device = d.device_id as u16;
if query_jid.is_lid() {
Jid::lid_device(user.clone(), device)
} else {
Jid::pn_device(user.clone(), device)
}
})
.collect()
}
/// Background loop placeholder for device registry cleanup.
/// Note: Cleanup functionality was removed as part of trait simplification.
/// Device registry entries are managed through normal update/get operations.
pub(super) async fn device_registry_cleanup_loop(&self) {
// Simply wait for shutdown signal
self.shutdown_notifier.listen().await;
debug!(
target: "Client/DeviceRegistry",
"Shutdown signaled, exiting cleanup loop"
);
}
/// Migrate device registry entries from PN key to LID key.
pub(crate) async fn migrate_device_registry_on_lid_discovery(&self, pn: &str, lid: &str) {
let backend = self.persistence_manager.backend();
match backend.get_devices(pn).await {
Ok(Some(mut record)) => {
info!(
"Migrating device registry entry from PN {} to LID {} ({} devices)",
pn,
lid,
record.devices.len()
);
record.user = lid.to_string();
if let Err(e) = backend.update_device_list(record.clone()).await {
warn!("Failed to migrate device registry to LID: {}", e);
return;
}
self.device_registry_cache
.insert(lid.to_string(), record)
.await;
// Drop the PN-keyed row in both cache and DB. Invalidate
// twice (before + after delete) so a concurrent reader can't
// resurrect the cache from the DB row between the two calls.
// Always run the second invalidate; even if delete fails, the
// cache may carry resurrected data that shouldn't stick.
self.device_registry_cache.invalidate(pn).await;
if let Err(e) = backend.delete_devices(pn).await {
warn!("Failed to delete PN-keyed device row during LID migration: {e}");
}
self.device_registry_cache.invalidate(pn).await;
}
Ok(None) => {}
Err(e) => {
warn!("Failed to check for PN device registry entry: {}", e);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lid_pn_cache::LearningSource;
use crate::test_utils::create_test_client_with_failing_http;
use std::sync::Arc;
async fn create_test_client() -> Arc<Client> {
create_test_client_with_failing_http("device_registry").await
}
async fn setup_lid_pn(client: &Arc<Client>, lid: &str, pn: &str) {
use crate::lid_pn_cache::LidPnEntry;
let entry = LidPnEntry::new(lid.to_string(), pn.to_string(), LearningSource::Usync);
client.lid_pn_cache.add(&entry).await;
}
async fn setup_device_record(client: &Arc<Client>, user: &str, device_ids: &[u32]) {
let record = wacore::store::traits::DeviceListRecord {
user: user.into(),
devices: device_ids
.iter()
.map(|&id| wacore::store::traits::DeviceInfo {
device_id: id,
key_index: None,
})
.collect(),
timestamp: wacore::time::now_secs(),
phash: None,
raw_id: None,
};
client
.device_registry_cache
.insert(user.into(), record)
.await;
}
#[tokio::test]
async fn test_resolve_to_canonical_key_unknown_user() {
let client = create_test_client().await;
let result = client.resolve_to_canonical_key("15551234567").await;
assert_eq!(result, "15551234567");
}
#[tokio::test]
async fn test_resolve_to_canonical_key_with_lid_mapping() {
let client = create_test_client().await;
let lid = "100000000000001";
let pn = "15551234567";
setup_lid_pn(&client, lid, pn).await;
// PN should resolve to LID
let result = client.resolve_to_canonical_key(pn).await;
assert_eq!(result, lid);
// LID should stay as LID
let result = client.resolve_to_canonical_key(lid).await;
assert_eq!(result, lid);
}
#[tokio::test]
async fn test_get_lookup_keys_unknown_user() {
let client = create_test_client().await;
let keys = client.get_lookup_keys("15551234567").await;
assert_eq!(keys, vec!["15551234567"]);
}
#[tokio::test]
async fn test_get_lookup_keys_with_lid_mapping() {
let client = create_test_client().await;
let lid = "100000000000001";
let pn = "15551234567";
setup_lid_pn(&client, lid, pn).await;
// Looking up by PN should return [LID, PN]
let keys = client.get_lookup_keys(pn).await;
assert_eq!(keys, vec![lid.to_string(), pn.to_string()]);
// Looking up by LID should return [LID, PN]
let keys = client.get_lookup_keys(lid).await;
assert_eq!(keys, vec![lid.to_string(), pn.to_string()]);
}
#[tokio::test]
async fn test_15_digit_lid_handling() {
let client = create_test_client().await;
// Real example: 15-digit LID
let lid = "100000000000001";
let pn = "15551234567";
assert_eq!(lid.len(), 15, "LID should be 15 digits");
setup_lid_pn(&client, lid, pn).await;
// 15-digit LID should be properly recognized via cache lookup
let canonical = client.resolve_to_canonical_key(lid).await;
assert_eq!(canonical, lid);
let keys = client.get_lookup_keys(lid).await;
assert_eq!(keys.len(), 2);
assert_eq!(keys[0], lid);
assert_eq!(keys[1], pn);
}
#[tokio::test]
async fn test_has_device_primary_always_exists() {
let client = create_test_client().await;
assert!(client.has_device("anyuser", 0).await);
}
#[tokio::test]
async fn test_has_device_unknown_device() {
let client = create_test_client().await;
assert!(!client.has_device("15551234567", 5).await);
}
#[tokio::test]
async fn test_has_device_with_cached_record() {
let client = create_test_client().await;
let lid = "100000000000001";
let pn = "15551234567";
setup_lid_pn(&client, lid, pn).await;
setup_device_record(&client, lid, &[1]).await;
// Device should be findable via both PN and LID (bidirectional lookup)
assert!(client.has_device(pn, 1).await);
assert!(client.has_device(lid, 1).await);
// Non-existent device should return false
assert!(!client.has_device(lid, 99).await);
}
/// Test that invalidate_device_cache clears registry cache entries for
/// all LID/PN aliases when called with either identifier.
#[tokio::test]
async fn test_invalidate_device_cache_uses_correct_jid_types() {
let client = create_test_client().await;
let lid = "100000000000001";
let pn = "15551234567";
setup_lid_pn(&client, lid, pn).await;
setup_device_record(&client, lid, &[1]).await;
assert!(client.device_registry_cache.get(lid).await.is_some());
// Invalidate via PN — should clear LID entry too (bidirectional resolution)
client.invalidate_device_cache(pn).await;
assert!(
client.device_registry_cache.get(lid).await.is_none(),
"LID entry should be invalidated when called with PN"
);
// Re-insert and invalidate via LID
setup_device_record(&client, lid, &[2]).await;
client.invalidate_device_cache(lid).await;
assert!(
client.device_registry_cache.get(lid).await.is_none(),
"LID entry should be invalidated when called with LID"
);
}
/// Test that invalidate_device_cache handles unknown users (no LID-PN mapping).
#[tokio::test]
async fn test_invalidate_device_cache_unknown_user_invalidates_both_types() {
let client = create_test_client().await;
let unknown_user = "100000000000999";
setup_device_record(&client, unknown_user, &[1]).await;
assert!(
client
.device_registry_cache
.get(unknown_user)
.await
.is_some()
);
client.invalidate_device_cache(unknown_user).await;
assert!(
client
.device_registry_cache
.get(unknown_user)
.await
.is_none(),
"Unknown user entry should be invalidated"
);
}
// ── Granular patch tests ──────────────────────────────────────────────
fn make_device_element(
device_id: u16,
key_index: Option<u32>,
) -> wacore::stanza::devices::DeviceElement {
wacore::stanza::devices::DeviceElement {
jid: Jid {
user: "15551234567".into(),
server: wacore_binary::Server::Pn,
device: device_id,
..Default::default()
},
key_index,
lid: None,
}
}
#[tokio::test]
async fn test_patch_device_add_to_existing_cache() {
let client = create_test_client().await;
// Pre-populate registry cache with device 0
setup_device_record(&client, "15551234567", &[0]).await;
// Patch: add device 3
let elem = make_device_element(3, Some(5));
client.patch_device_add("15551234567", &elem, None).await;
let updated = client
.device_registry_cache
.get("15551234567")
.await
.unwrap();
assert_eq!(updated.devices.len(), 2);
assert!(updated.devices.iter().any(|d| d.device_id == 3));
let dev3 = updated.devices.iter().find(|d| d.device_id == 3).unwrap();
assert_eq!(dev3.key_index, Some(5));
}
#[tokio::test]
async fn test_patch_device_add_deduplicates() {
let client = create_test_client().await;
setup_device_record(&client, "15551234567", &[3]).await;
// Patch: add device 3 again — should not duplicate
let elem = make_device_element(3, None);
client.patch_device_add("15551234567", &elem, None).await;
let updated = client
.device_registry_cache
.get("15551234567")
.await
.unwrap();
assert_eq!(updated.devices.len(), 1);
}
#[tokio::test]
async fn test_patch_device_add_noop_on_miss() {
let client = create_test_client().await;
// No pre-populated cache — patch should be a no-op
let elem = make_device_element(3, None);
client.patch_device_add("15551234567", &elem, None).await;
assert!(
client
.device_registry_cache
.get("15551234567")
.await
.is_none()
);
}
#[tokio::test]
async fn test_patch_device_remove() {
let client = create_test_client().await;
setup_device_record(&client, "15551234567", &[0, 3]).await;
client.patch_device_remove("15551234567", 3).await;
let updated = client
.device_registry_cache
.get("15551234567")
.await
.unwrap();
assert_eq!(updated.devices.len(), 1);
assert_eq!(updated.devices[0].device_id, 0);
}
#[tokio::test]
async fn test_patch_device_update_key_index() {
let client = create_test_client().await;
// Pre-populate registry cache
let record = wacore::store::traits::DeviceListRecord {
user: "15551234567".to_string(),
devices: vec![
wacore::store::traits::DeviceInfo {
device_id: 0,
key_index: None,
},
wacore::store::traits::DeviceInfo {
device_id: 3,
key_index: Some(1),
},
],
timestamp: 1000,
phash: None,
raw_id: None,
};
client
.device_registry_cache
.insert("15551234567".to_string(), record)
.await;
// Patch: update device 3 key_index to 5
let elem = make_device_element(3, Some(5));
client.patch_device_update("15551234567", &elem).await;
let updated = client
.device_registry_cache
.get("15551234567")
.await
.unwrap();
let dev3 = updated.devices.iter().find(|d| d.device_id == 3).unwrap();
assert_eq!(dev3.key_index, Some(5));
}
#[tokio::test]
async fn test_patch_device_add_updates_registry() {
let client = create_test_client().await;
// Pre-populate registry cache
setup_device_record(&client, "15551234567", &[0]).await;
// Patch: add device 3
let elem = make_device_element(3, Some(2));
client.patch_device_add("15551234567", &elem, None).await;
let updated = client
.device_registry_cache
.get("15551234567")
.await
.unwrap();
assert_eq!(updated.devices.len(), 2);
let dev3 = updated.devices.iter().find(|d| d.device_id == 3).unwrap();
assert_eq!(dev3.key_index, Some(2));
}
#[tokio::test]
async fn test_lid_migration_preserves_registry_cache() {
use wacore::store::traits::{DeviceInfo, DeviceListRecord};
let client = create_test_client().await;
let pn = "15550000099";
let lid = "100000000000099";
// Store device list under PN in backend
let record = DeviceListRecord {
user: pn.to_string(),
devices: vec![
DeviceInfo {
device_id: 0,
key_index: None,
},
DeviceInfo {
device_id: 39,
key_index: Some(25),
},
],
timestamp: wacore::time::now_secs(),
phash: None,
raw_id: None,
};
client
.persistence_manager
.backend()
.update_device_list(record)
.await
.unwrap();
setup_lid_pn(&client, lid, pn).await;
// Migrate
client
.migrate_device_registry_on_lid_discovery(pn, lid)
.await;
// LID entry should exist in registry cache
let cached = client.device_registry_cache.get(lid).await;
assert!(
cached.is_some(),
"LID key should be in registry cache after migration"
);
assert_eq!(cached.unwrap().devices.len(), 2);
// PN entry should be gone
let pn_cached = client.device_registry_cache.get(pn).await;
assert!(
pn_cached.is_none(),
"PN key should be invalidated after migration"
);
// get_devices_from_registry should find devices via LID lookup
let lid_jid = Jid::lid(lid);
let devices = client.get_devices_from_registry(&lid_jid).await;
assert!(devices.is_some(), "should resolve devices via LID");
assert_eq!(devices.unwrap().len(), 2);
}
/// Regression: querying a LID-stored record by PN (and vice versa) must
/// return device JIDs whose user part matches the *query* alias, not the
/// storage key.
#[tokio::test]
async fn test_reconstruct_device_jids_uses_query_alias() {
let client = create_test_client().await;
let pn = "15550000088";
let lid = "100000000000088";
setup_device_record(&client, lid, &[5]).await;
setup_lid_pn(&client, lid, pn).await;
// Query by PN — should find the LID-stored record but return PN-typed JIDs
let pn_jid = Jid::pn(pn);
let devices = client
.get_devices_from_registry(&pn_jid)
.await
.expect("should resolve LID record via PN alias");
assert_eq!(devices.len(), 1);
assert!(devices[0].is_pn(), "device JID should be PN-typed");
assert_eq!(
devices[0].user, pn,
"device JID user should be the PN, not the LID"
);
assert_eq!(devices[0].device, 5);
// Query by LID — should return LID-typed JIDs
let lid_jid = Jid::lid(lid);
let devices = client
.get_devices_from_registry(&lid_jid)
.await
.expect("should resolve LID record via LID");
assert_eq!(devices.len(), 1);
assert!(devices[0].is_lid(), "device JID should be LID-typed");
assert_eq!(devices[0].user, lid, "device JID user should be the LID");
}
// ── DB-fallback tests for patch helpers ──────────────────────────────
#[tokio::test]
async fn test_patch_device_add_falls_back_to_db() {
use wacore::store::traits::{DeviceInfo, DeviceListRecord};
let client = create_test_client().await;
// Seed backend DB directly (bypassing moka cache)
let record = DeviceListRecord {
user: "15551234567".into(),
devices: vec![DeviceInfo {
device_id: 0,
key_index: None,
}],
timestamp: wacore::time::now_secs(),
phash: None,
raw_id: None,
};
client
.persistence_manager
.backend()
.update_device_list(record)
.await
.unwrap();
// Moka cache is empty — old code would no-op here
assert!(
client
.device_registry_cache
.get("15551234567")
.await
.is_none()
);
let elem = make_device_element(3, Some(7));
client.patch_device_add("15551234567", &elem, None).await;
// Verify patch was applied to DB (not silently dropped)
let updated = client
.persistence_manager
.backend()
.get_devices("15551234567")
.await
.unwrap()
.expect("record should still exist in DB");
assert_eq!(updated.devices.len(), 2);
assert!(updated.devices.iter().any(|d| d.device_id == 3));
// Cache should be warm now too
assert!(
client
.device_registry_cache
.get("15551234567")
.await
.is_some()
);
}
#[tokio::test]
async fn test_patch_device_remove_falls_back_to_db() {
use wacore::store::traits::{DeviceInfo, DeviceListRecord};
let client = create_test_client().await;
let record = DeviceListRecord {
user: "15551234567".into(),
devices: vec![
DeviceInfo {
device_id: 0,
key_index: None,
},
DeviceInfo {
device_id: 3,
key_index: Some(5),
},
],
timestamp: wacore::time::now_secs(),
phash: None,
raw_id: None,
};
client
.persistence_manager
.backend()
.update_device_list(record)
.await
.unwrap();
assert!(
client
.device_registry_cache
.get("15551234567")
.await
.is_none()
);
client.patch_device_remove("15551234567", 3).await;
let updated = client
.persistence_manager
.backend()
.get_devices("15551234567")
.await
.unwrap()
.expect("record should still exist");
assert_eq!(updated.devices.len(), 1);
assert_eq!(updated.devices[0].device_id, 0);
}
// ── Sender key device cache: post-fix behavior ──────────────────────
/// `device_has_key` returns `None` for unknown devices, so an added device
/// naturally falls into `needs_skdm` on the next send without any cache wipe.
#[tokio::test]
async fn test_patch_device_add_keeps_cache_warm_new_device_seen_as_unknown() {
use crate::sender_key_device_cache::SenderKeyDeviceMap;
let client = create_test_client().await;
setup_device_record(&client, "15551234567", &[0]).await;
let group = "120363000000000001@g.us";
let map =
SenderKeyDeviceMap::from_db_rows(&[("15551234567:0@s.whatsapp.net".into(), true)]);
client
.sender_key_device_cache
.get_or_init(group, async { std::sync::Arc::new(map) })
.await;
let elem = make_device_element(3, Some(5));
client.patch_device_add("15551234567", &elem, None).await;
let warm = client
.sender_key_device_cache
.get_or_init(group, async {
panic!("cache should still be warm — no global invalidation")
})
.await;
assert_eq!(warm.device_has_key("15551234567", 0), Some(true));
assert_eq!(warm.device_has_key("15551234567", 3), None);
}
#[tokio::test]
async fn test_patch_device_add_no_invalidation_when_device_exists() {
use crate::sender_key_device_cache::SenderKeyDeviceMap;
use wacore::store::traits::{DeviceInfo, DeviceListRecord};
let client = create_test_client().await;
// Pre-populate device registry with device 0 AND device 3
let record = DeviceListRecord {
user: "15551234567".into(),
devices: vec![
DeviceInfo {
device_id: 0,
key_index: None,
},
DeviceInfo {
device_id: 3,
key_index: Some(5),
},
],
timestamp: wacore::time::now_secs(),
phash: None,
raw_id: None,
};
client
.device_registry_cache
.insert("15551234567".into(), record)
.await;
// Warm the sender key device cache
let group = "120363000000000001@g.us";
let map = SenderKeyDeviceMap::from_db_rows(&[
("15551234567:0@s.whatsapp.net".into(), true),
("15551234567:3@s.whatsapp.net".into(), true),
]);
client
.sender_key_device_cache
.get_or_init(group, async { std::sync::Arc::new(map) })
.await;
// Re-add device 3 (already exists) — should NOT invalidate cache
let elem = make_device_element(3, Some(5));
client.patch_device_add("15551234567", &elem, None).await;
// Cache should still have the old entry
let cached = client
.sender_key_device_cache
.get_or_init(group, async {
panic!("init should not be called — cache should still be warm")
})
.await;
assert!(!cached.is_empty(), "cache should still be warm");
}
/// On remove, the sender_key_devices DB row for the device is dropped
/// (mirrors WA Web's `senderKey.delete(deviceJid)`). The next resolve sees
/// the device gone from the registry and skips it, so no SKDM redistribution
/// is needed for surviving devices.
#[tokio::test]
async fn test_patch_device_remove_clears_row_and_keeps_others_warm() {
let client = create_test_client().await;
setup_device_record(&client, "15551234567", &[0, 3]).await;
let group = "120363000000000001@g.us";
client
.persistence_manager
.set_sender_key_status(
group,
&[
("15551234567:0@s.whatsapp.net", true),
("15551234567:3@s.whatsapp.net", true),
],
)
.await
.unwrap();
client.patch_device_remove("15551234567", 3).await;
let rows = client
.persistence_manager
.get_sender_key_devices(group)
.await
.unwrap();
assert!(
rows.iter()
.any(|(j, _)| j == "15551234567:0@s.whatsapp.net")
);
assert!(
!rows
.iter()
.any(|(j, _)| j == "15551234567:3@s.whatsapp.net")
);
}
// ── LID↔PN zombie-path regression tests (PR #579) ───────────────────
/// U1 — `update_device_list` deletes the stale DB row when the canonical
/// key flips (e.g. the LID↔PN mapping is learned between two writes).
/// Without this, the old PN-keyed row lingers and re-surfaces as a zombie
/// through alias lookup, causing 406s on group sends.
#[tokio::test]
async fn test_update_device_list_canonical_flip_deletes_old_db_row() {
use wacore::store::traits::{DeviceInfo, DeviceListRecord};
let client = create_test_client().await;
let pn = "15550000011";
let lid = "100000000000011";
let backend = client.persistence_manager.backend();
// Legacy state: DB row stored under PN (mapping wasn't known yet).
backend
.update_device_list(DeviceListRecord {
user: pn.to_string(),
devices: vec![DeviceInfo {
device_id: 5,
key_index: None,
}],
timestamp: wacore::time::now_secs(),
phash: None,
raw_id: None,
})
.await
.unwrap();
setup_lid_pn(&client, lid, pn).await;
// New write: `update_device_list` with original_user = PN, canonical
// now resolves to LID because the mapping is known.
client
.update_device_list(DeviceListRecord {
user: pn.to_string(),
devices: vec![DeviceInfo {
device_id: 7,
key_index: None,
}],
timestamp: wacore::time::now_secs(),
phash: None,
raw_id: None,
})
.await
.unwrap();
assert!(
backend.get_devices(pn).await.unwrap().is_none(),
"old PN-keyed DB row must be deleted after canonical flip"
);
let lid_row = backend.get_devices(lid).await.unwrap();
assert!(lid_row.is_some(), "new LID-keyed DB row must exist");
assert_eq!(lid_row.unwrap().devices[0].device_id, 7);
}
/// U2 — `migrate_device_registry_on_lid_discovery` deletes the PN-keyed DB
/// row, not just the cache entry. Without this the PN row stayed around
/// as a zombie that surfaced via alias lookup on future sends.
#[tokio::test]
async fn test_migrate_device_registry_deletes_pn_db_row() {
use wacore::store::traits::{DeviceInfo, DeviceListRecord};
let client = create_test_client().await;
let pn = "15550000022";
let lid = "100000000000022";
let backend = client.persistence_manager.backend();
backend
.update_device_list(DeviceListRecord {
user: pn.to_string(),
devices: vec![DeviceInfo {
device_id: 0,
key_index: None,
}],
timestamp: wacore::time::now_secs(),
phash: None,
raw_id: None,
})
.await
.unwrap();
setup_lid_pn(&client, lid, pn).await;
client
.migrate_device_registry_on_lid_discovery(pn, lid)
.await;
assert!(
backend.get_devices(pn).await.unwrap().is_none(),
"PN-keyed DB row must be gone after migration"
);
assert!(
backend.get_devices(lid).await.unwrap().is_some(),
"LID-keyed DB row must exist after migration"
);
}
/// U3 — `invalidate_device_cache` with a known LID↔PN mapping clears both
/// aliases from the DB (not only the cache). This is the primary fix for
/// the 23-batches-in-3h45m zombie loop from the field report.
#[tokio::test]
async fn test_invalidate_device_cache_clears_both_aliases_from_db() {
use wacore::store::traits::{DeviceInfo, DeviceListRecord};
let client = create_test_client().await;
let pn = "15550000033";
let lid = "100000000000033";
let backend = client.persistence_manager.backend();
// Seed DB under BOTH aliases (simulating split-brain legacy state).
for user in [pn, lid] {
backend
.update_device_list(DeviceListRecord {
user: user.to_string(),
devices: vec![DeviceInfo {
device_id: 1,
key_index: None,
}],
timestamp: wacore::time::now_secs(),
phash: None,
raw_id: None,
})
.await
.unwrap();
}
setup_lid_pn(&client, lid, pn).await;
client.invalidate_device_cache(lid).await;
assert!(
backend.get_devices(pn).await.unwrap().is_none(),
"PN DB row must be deleted via alias resolution"
);
assert!(
backend.get_devices(lid).await.unwrap().is_none(),
"LID DB row must be deleted"
);
assert!(
client.device_registry_cache.get(pn).await.is_none(),
"PN cache entry must be gone"
);
assert!(
client.device_registry_cache.get(lid).await.is_none(),
"LID cache entry must be gone"
);
}
/// U4 — canonical-flip path with a warm cache: no zombie entry survives.
///
/// This does *not* deterministically exercise the TOCTOU window between
/// invalidate1 and delete — the first invalidate clears the pre-seeded
/// cache, so the test would pass even without the post-delete second
/// invalidate. Reaching that window requires interleaving a concurrent
/// reader between those two calls, which would need a backend-level
/// latch (i.e., wrapping `Backend` to run a hook before `delete_devices`).
/// The full trait has ~50 methods via blanket impl, so that machinery is
/// out of scope for this PR; the double-invalidate lives on as
/// defense-in-depth validated by code review rather than this test.
///
/// What this still guards: the first invalidate + DB delete end-to-end
/// (removing either one would fail this test).
#[tokio::test]
async fn test_update_device_list_canonical_flip_clears_warm_cache() {
use wacore::store::traits::{DeviceInfo, DeviceListRecord};
let client = create_test_client().await;
let pn = "15550000044";
let lid = "100000000000044";
let backend = client.persistence_manager.backend();
let legacy = DeviceListRecord {
user: pn.to_string(),
devices: vec![DeviceInfo {
device_id: 9,
key_index: None,
}],
timestamp: wacore::time::now_secs(),
phash: None,
raw_id: None,
};
backend.update_device_list(legacy.clone()).await.unwrap();
// Warm cache under PN to simulate a reader that populated it before
// the mapping was learned.
client.device_registry_cache.insert(pn.into(), legacy).await;
setup_lid_pn(&client, lid, pn).await;
client
.update_device_list(DeviceListRecord {
user: pn.to_string(),
devices: vec![DeviceInfo {
device_id: 10,
key_index: None,
}],
timestamp: wacore::time::now_secs(),
phash: None,
raw_id: None,
})
.await
.unwrap();
assert!(
client.device_registry_cache.get(pn).await.is_none(),
"cache[pn] must be cleared after canonical flip"
);
assert!(
backend.get_devices(pn).await.unwrap().is_none(),
"DB[pn] must be deleted after canonical flip"
);
}
// ── SKDM flow regression tests ─────────────────────────────────────
/// After remove, the in-memory cache must not return `has_key=true` for
/// the removed JID. A future re-add of the same device_id would otherwise
/// hit the stale entry and skip SKDM redistribution.
#[tokio::test]
async fn patch_device_remove_evicts_cached_has_key_for_removed_device() {
use crate::sender_key_device_cache::SenderKeyDeviceMap;
let client = create_test_client().await;
let user = "15551234567";
setup_device_record(&client, user, &[0, 5]).await;
let group = "120363000000000001@g.us";
let map = SenderKeyDeviceMap::from_db_rows(&[(format!("{user}:5@s.whatsapp.net"), true)]);
client
.sender_key_device_cache
.get_or_init(group, async { std::sync::Arc::new(map) })
.await;
client.patch_device_remove(user, 5).await;
let reloaded = client
.sender_key_device_cache
.get_or_init(group, async {
std::sync::Arc::new(SenderKeyDeviceMap::from_db_rows(
&client
.persistence_manager
.get_sender_key_devices(group)
.await
.unwrap(),
))
})
.await;
assert_eq!(reloaded.device_has_key(user, 5), None);
}
#[tokio::test]
async fn patch_device_remove_clears_sender_key_device_rows() {
let client = create_test_client().await;
let user = "15551234567";
setup_device_record(&client, user, &[0, 5]).await;
let group = "120363000000000001@g.us";
let device_jid = format!("{user}:5@s.whatsapp.net");
client
.persistence_manager
.set_sender_key_status(group, &[(device_jid.as_str(), true)])
.await
.unwrap();
client.patch_device_remove(user, 5).await;
let rows = client
.persistence_manager
.get_sender_key_devices(group)
.await
.unwrap();
assert!(rows.iter().all(|(jid, _)| jid != &device_jid));
}
#[tokio::test]
async fn patch_device_add_preserves_unrelated_group_caches() {
use crate::sender_key_device_cache::SenderKeyDeviceMap;
let client = create_test_client().await;
setup_device_record(&client, "15551234567", &[0]).await;
let group = "120363000000000002@g.us";
let map =
SenderKeyDeviceMap::from_db_rows(&[("99999999999:0@s.whatsapp.net".into(), true)]);
client
.sender_key_device_cache
.get_or_init(group, async { std::sync::Arc::new(map) })
.await;
let elem = make_device_element(3, Some(5));
client.patch_device_add("15551234567", &elem, None).await;
let warm = client
.sender_key_device_cache
.get_or_init(group, async {
panic!("cache should still be warm — no global invalidation")
})
.await;
assert_eq!(warm.device_has_key("99999999999", 0), Some(true));
}
#[tokio::test]
async fn patch_device_remove_preserves_unrelated_group_caches() {
use crate::sender_key_device_cache::SenderKeyDeviceMap;
let client = create_test_client().await;
setup_device_record(&client, "15551234567", &[0, 5]).await;
let group = "120363000000000002@g.us";
let map =
SenderKeyDeviceMap::from_db_rows(&[("99999999999:0@s.whatsapp.net".into(), true)]);
client
.sender_key_device_cache
.get_or_init(group, async { std::sync::Arc::new(map) })
.await;
client.patch_device_remove("15551234567", 5).await;
let warm = client
.sender_key_device_cache
.get_or_init(group, async {
panic!("cache should still be warm — no global invalidation")
})
.await;
assert_eq!(warm.device_has_key("99999999999", 0), Some(true));
}
/// Forward secrecy: removing a participant who had `has_key=true` must
/// drop the bot's own sender key and clear the group's tracker so the
/// next send forces full SKDM redistribution.
#[tokio::test]
async fn participant_remove_rotates_sender_key_when_any_had_key() {
use std::str::FromStr;
use wacore::libsignal::protocol::SenderKeyRecord;
use wacore::libsignal::store::sender_key_name::SenderKeyName;
use wacore::types::jid::JidExt;
let client = create_test_client().await;
let group = "120363000000000001@g.us";
let own_lid = Jid::from_str("193832511623409:13@lid").unwrap();
client
.persistence_manager
.process_command(crate::store::commands::DeviceCommand::SetLid(Some(
own_lid.clone(),
)))
.await;
let sk_name = SenderKeyName::from_parts(group, own_lid.to_protocol_address().as_str());
client
.signal_cache
.put_sender_key(&sk_name, SenderKeyRecord::new_empty())
.await;
client
.persistence_manager
.set_sender_key_status(
group,
&[
("271060335329480:0@lid", true),
("77610646245392:0@lid", true),
],
)
.await
.unwrap();
client
.rotate_sender_key_on_participant_remove(group, &["271060335329480"])
.await;
let device_arc = client.persistence_manager.get_device_arc().await;
let device = device_arc.read().await;
let key = client
.signal_cache
.get_sender_key(&sk_name, &*device.backend)
.await
.unwrap();
assert!(
key.is_none(),
"sender key must be deleted on remove rotation"
);
let rows = client
.persistence_manager
.get_sender_key_devices(group)
.await
.unwrap();
assert!(rows.is_empty(), "sender_key_devices must be cleared");
}
/// No rotation when removed participants never received an SKDM — there
/// is nothing for them to decrypt forward, so don't pay the redistribute cost.
#[tokio::test]
async fn participant_remove_skips_rotation_when_none_had_key() {
use std::str::FromStr;
use wacore::libsignal::protocol::SenderKeyRecord;
use wacore::libsignal::store::sender_key_name::SenderKeyName;
use wacore::types::jid::JidExt;
let client = create_test_client().await;
let group = "120363000000000001@g.us";
let own_lid = Jid::from_str("193832511623409:13@lid").unwrap();
client
.persistence_manager
.process_command(crate::store::commands::DeviceCommand::SetLid(Some(
own_lid.clone(),
)))
.await;
let sk_name = SenderKeyName::from_parts(group, own_lid.to_protocol_address().as_str());
client
.signal_cache
.put_sender_key(&sk_name, SenderKeyRecord::new_empty())
.await;
client
.persistence_manager
.set_sender_key_status(group, &[("271060335329480:0@lid", false)])
.await
.unwrap();
client
.rotate_sender_key_on_participant_remove(group, &["271060335329480"])
.await;
let device_arc = client.persistence_manager.get_device_arc().await;
let device = device_arc.read().await;
let key = client
.signal_cache
.get_sender_key(&sk_name, &*device.backend)
.await
.unwrap();
assert!(
key.is_some(),
"sender key must survive when removed had no key"
);
}
}